1/* X Communication module for terminals which understand the X protocol.
2   Copyright (C) 1989, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
3                 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
4
5This file is part of GNU Emacs.
6
7GNU Emacs is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
9the Free Software Foundation; either version 2, or (at your option)
10any later version.
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with GNU Emacs; see the file COPYING.  If not, write to
19the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20Boston, MA 02110-1301, USA.  */
21
22/* New display code by Gerd Moellmann <gerd@gnu.org>.  */
23/* Xt features made by Fred Pierresteguy.  */
24
25#include <config.h>
26
27/* On 4.3 these lose if they come after xterm.h.  */
28/* Putting these at the beginning seems to be standard for other .c files.  */
29#include <signal.h>
30
31#include <stdio.h>
32
33#ifdef HAVE_X_WINDOWS
34
35#include "lisp.h"
36#include "blockinput.h"
37
38/* Need syssignal.h for various externs and definitions that may be required
39   by some configurations for calls to signal later in this source file.  */
40#include "syssignal.h"
41
42/* This may include sys/types.h, and that somehow loses
43   if this is not done before the other system files.  */
44#include "xterm.h"
45#include <X11/cursorfont.h>
46
47/* Load sys/types.h if not already loaded.
48   In some systems loading it twice is suicidal.  */
49#ifndef makedev
50#include <sys/types.h>
51#endif /* makedev */
52
53#ifdef BSD_SYSTEM
54#include <sys/ioctl.h>
55#endif /* ! defined (BSD_SYSTEM) */
56
57#include "systty.h"
58#include "systime.h"
59
60#ifndef INCLUDED_FCNTL
61#include <fcntl.h>
62#endif
63#include <ctype.h>
64#include <errno.h>
65#include <setjmp.h>
66#include <sys/stat.h>
67/* Caused redefinition of DBL_DIG on Netbsd; seems not to be needed.  */
68/* #include <sys/param.h>  */
69
70#include "charset.h"
71#include "coding.h"
72#include "ccl.h"
73#include "frame.h"
74#include "dispextern.h"
75#include "fontset.h"
76#include "termhooks.h"
77#include "termopts.h"
78#include "termchar.h"
79#include "gnu.h"
80#include "disptab.h"
81#include "buffer.h"
82#include "window.h"
83#include "keyboard.h"
84#include "intervals.h"
85#include "process.h"
86#include "atimer.h"
87#include "keymap.h"
88
89#ifdef USE_X_TOOLKIT
90#include <X11/Shell.h>
91#endif
92
93#ifdef HAVE_SYS_TIME_H
94#include <sys/time.h>
95#endif
96#ifdef HAVE_UNISTD_H
97#include <unistd.h>
98#endif
99
100#ifdef USE_GTK
101#include "gtkutil.h"
102#endif
103
104#ifdef USE_LUCID
105extern int xlwmenu_window_p P_ ((Widget w, Window window));
106extern void xlwmenu_redisplay P_ ((Widget));
107#endif
108
109#if defined (USE_X_TOOLKIT) || defined (USE_GTK)
110
111extern void free_frame_menubar P_ ((struct frame *));
112extern struct frame *x_menubar_window_to_frame P_ ((struct x_display_info *,
113						    int));
114#endif
115
116#ifdef USE_X_TOOLKIT
117#if (XtSpecificationRelease >= 5) && !defined(NO_EDITRES)
118#define HACK_EDITRES
119extern void _XEditResCheckMessages ();
120#endif /* not NO_EDITRES */
121
122/* Include toolkit specific headers for the scroll bar widget.  */
123
124#ifdef USE_TOOLKIT_SCROLL_BARS
125#if defined USE_MOTIF
126#include <Xm/Xm.h>		/* for LESSTIF_VERSION */
127#include <Xm/ScrollBar.h>
128#else /* !USE_MOTIF i.e. use Xaw */
129
130#ifdef HAVE_XAW3D
131#include <X11/Xaw3d/Simple.h>
132#include <X11/Xaw3d/Scrollbar.h>
133#include <X11/Xaw3d/ThreeD.h>
134#else /* !HAVE_XAW3D */
135#include <X11/Xaw/Simple.h>
136#include <X11/Xaw/Scrollbar.h>
137#endif /* !HAVE_XAW3D */
138#ifndef XtNpickTop
139#define XtNpickTop "pickTop"
140#endif /* !XtNpickTop */
141#endif /* !USE_MOTIF */
142#endif /* USE_TOOLKIT_SCROLL_BARS */
143
144#endif /* USE_X_TOOLKIT */
145
146#if ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
147#define x_any_window_to_frame x_window_to_frame
148#define x_top_window_to_frame x_window_to_frame
149#endif
150
151#ifdef USE_X_TOOLKIT
152#include "widget.h"
153#ifndef XtNinitialState
154#define XtNinitialState "initialState"
155#endif
156#endif
157
158#define abs(x)	((x) < 0 ? -(x) : (x))
159
160/* Default to using XIM if available.  */
161#ifdef USE_XIM
162int use_xim = 1;
163#else
164int use_xim = 0;  /* configure --without-xim */
165#endif
166
167
168
169/* Non-nil means Emacs uses toolkit scroll bars.  */
170
171Lisp_Object Vx_toolkit_scroll_bars;
172
173/* Non-zero means that a HELP_EVENT has been generated since Emacs
174   start.  */
175
176static int any_help_event_p;
177
178/* Last window where we saw the mouse.  Used by mouse-autoselect-window.  */
179static Lisp_Object last_window;
180
181/* Non-zero means make use of UNDERLINE_POSITION font properties.  */
182
183int x_use_underline_position_properties;
184
185/* Non-zero means to draw the underline at the same place as the descent line.  */
186
187int x_underline_at_descent_line;
188
189/* This is a chain of structures for all the X displays currently in
190   use.  */
191
192struct x_display_info *x_display_list;
193
194/* This is a list of cons cells, each of the form (NAME
195   . FONT-LIST-CACHE), one for each element of x_display_list and in
196   the same order.  NAME is the name of the frame.  FONT-LIST-CACHE
197   records previous values returned by x-list-fonts.  */
198
199Lisp_Object x_display_name_list;
200
201/* Frame being updated by update_frame.  This is declared in term.c.
202   This is set by update_begin and looked at by all the XT functions.
203   It is zero while not inside an update.  In that case, the XT
204   functions assume that `selected_frame' is the frame to apply to.  */
205
206extern struct frame *updating_frame;
207
208/* This is a frame waiting to be auto-raised, within XTread_socket.  */
209
210struct frame *pending_autoraise_frame;
211
212#ifdef USE_X_TOOLKIT
213/* The application context for Xt use.  */
214XtAppContext Xt_app_con;
215static String Xt_default_resources[] = {0};
216#endif /* USE_X_TOOLKIT */
217
218/* Non-zero means user is interacting with a toolkit scroll bar.  */
219
220static int toolkit_scroll_bar_interaction;
221
222/* Non-zero means to not move point as a result of clicking on a
223   frame to focus it (when focus-follows-mouse is nil).  */
224
225int x_mouse_click_focus_ignore_position;
226
227/* Non-zero timeout value means ignore next mouse click if it arrives
228   before that timeout elapses (i.e. as part of the same sequence of
229   events resulting from clicking on a frame to select it).  */
230
231static unsigned long ignore_next_mouse_click_timeout;
232
233/* Mouse movement.
234
235   Formerly, we used PointerMotionHintMask (in standard_event_mask)
236   so that we would have to call XQueryPointer after each MotionNotify
237   event to ask for another such event.  However, this made mouse tracking
238   slow, and there was a bug that made it eventually stop.
239
240   Simply asking for MotionNotify all the time seems to work better.
241
242   In order to avoid asking for motion events and then throwing most
243   of them away or busy-polling the server for mouse positions, we ask
244   the server for pointer motion hints.  This means that we get only
245   one event per group of mouse movements.  "Groups" are delimited by
246   other kinds of events (focus changes and button clicks, for
247   example), or by XQueryPointer calls; when one of these happens, we
248   get another MotionNotify event the next time the mouse moves.  This
249   is at least as efficient as getting motion events when mouse
250   tracking is on, and I suspect only negligibly worse when tracking
251   is off.  */
252
253/* Where the mouse was last time we reported a mouse event.  */
254
255static XRectangle last_mouse_glyph;
256static FRAME_PTR last_mouse_glyph_frame;
257static Lisp_Object last_mouse_press_frame;
258
259/* The scroll bar in which the last X motion event occurred.
260
261   If the last X motion event occurred in a scroll bar, we set this so
262   XTmouse_position can know whether to report a scroll bar motion or
263   an ordinary motion.
264
265   If the last X motion event didn't occur in a scroll bar, we set
266   this to Qnil, to tell XTmouse_position to return an ordinary motion
267   event.  */
268
269static Lisp_Object last_mouse_scroll_bar;
270
271/* This is a hack.  We would really prefer that XTmouse_position would
272   return the time associated with the position it returns, but there
273   doesn't seem to be any way to wrest the time-stamp from the server
274   along with the position query.  So, we just keep track of the time
275   of the last movement we received, and return that in hopes that
276   it's somewhat accurate.  */
277
278static Time last_mouse_movement_time;
279
280/* Time for last user interaction as returned in X events.  */
281
282static Time last_user_time;
283
284/* Incremented by XTread_socket whenever it really tries to read
285   events.  */
286
287#ifdef __STDC__
288static int volatile input_signal_count;
289#else
290static int input_signal_count;
291#endif
292
293/* Used locally within XTread_socket.  */
294
295static int x_noop_count;
296
297/* Initial values of argv and argc.  */
298
299extern char **initial_argv;
300extern int initial_argc;
301
302extern Lisp_Object Vcommand_line_args, Vsystem_name;
303
304/* Tells if a window manager is present or not.  */
305
306extern Lisp_Object Vx_no_window_manager;
307
308extern Lisp_Object Qeql;
309
310extern int errno;
311
312/* A mask of extra modifier bits to put into every keyboard char.  */
313
314extern EMACS_INT extra_keyboard_modifiers;
315
316/* The keysyms to use for the various modifiers.  */
317
318Lisp_Object Vx_alt_keysym, Vx_hyper_keysym, Vx_meta_keysym, Vx_super_keysym;
319Lisp_Object Vx_keysym_table;
320static Lisp_Object Qalt, Qhyper, Qmeta, Qsuper, Qmodifier_value;
321
322static Lisp_Object Qvendor_specific_keysyms;
323static Lisp_Object Qlatin_1;
324
325extern XrmDatabase x_load_resources P_ ((Display *, char *, char *, char *));
326extern int x_bitmap_mask P_ ((FRAME_PTR, int));
327
328static int x_alloc_nearest_color_1 P_ ((Display *, Colormap, XColor *));
329static void x_set_window_size_1 P_ ((struct frame *, int, int, int));
330static const XColor *x_color_cells P_ ((Display *, int *));
331static void x_update_window_end P_ ((struct window *, int, int));
332
333static int x_io_error_quitter P_ ((Display *));
334static void x_font_min_bounds P_ ((XFontStruct *, int *, int *));
335static int x_compute_min_glyph_bounds P_ ((struct frame *));
336static void x_update_end P_ ((struct frame *));
337static void XTframe_up_to_date P_ ((struct frame *));
338static void XTset_terminal_modes P_ ((void));
339static void XTreset_terminal_modes P_ ((void));
340static void x_clear_frame P_ ((void));
341static void frame_highlight P_ ((struct frame *));
342static void frame_unhighlight P_ ((struct frame *));
343static void x_new_focus_frame P_ ((struct x_display_info *, struct frame *));
344static void  x_focus_changed P_ ((int, int, struct x_display_info *,
345				  struct frame *, struct input_event *));
346static void x_detect_focus_change P_ ((struct x_display_info *,
347                                       XEvent *, struct input_event *));
348static void XTframe_rehighlight P_ ((struct frame *));
349static void x_frame_rehighlight P_ ((struct x_display_info *));
350static void x_draw_hollow_cursor P_ ((struct window *, struct glyph_row *));
351static void x_draw_bar_cursor P_ ((struct window *, struct glyph_row *, int,
352				   enum text_cursor_kinds));
353
354static void x_clip_to_row P_ ((struct window *, struct glyph_row *, int, GC));
355static void x_flush P_ ((struct frame *f));
356static void x_update_begin P_ ((struct frame *));
357static void x_update_window_begin P_ ((struct window *));
358static void x_after_update_window_line P_ ((struct glyph_row *));
359static struct scroll_bar *x_window_to_scroll_bar P_ ((Display *, Window));
360static void x_scroll_bar_report_motion P_ ((struct frame **, Lisp_Object *,
361					    enum scroll_bar_part *,
362					    Lisp_Object *, Lisp_Object *,
363					    unsigned long *));
364static void x_check_fullscreen P_ ((struct frame *));
365static void x_check_expected_move P_ ((struct frame *, int, int));
366static void x_sync_with_move P_ ((struct frame *, int, int, int));
367static int handle_one_xevent P_ ((struct x_display_info *, XEvent *,
368				  int *, struct input_event *));
369/* Don't declare this NO_RETURN because we want no
370   interference with debugging failing X calls.  */
371static SIGTYPE x_connection_closed P_ ((Display *, char *));
372
373
374/* Flush display of frame F, or of all frames if F is null.  */
375
376static void
377x_flush (f)
378     struct frame *f;
379{
380  BLOCK_INPUT;
381  if (f == NULL)
382    {
383      Lisp_Object rest, frame;
384      FOR_EACH_FRAME (rest, frame)
385	x_flush (XFRAME (frame));
386    }
387  else if (FRAME_X_P (f))
388    XFlush (FRAME_X_DISPLAY (f));
389  UNBLOCK_INPUT;
390}
391
392
393/* Remove calls to XFlush by defining XFlush to an empty replacement.
394   Calls to XFlush should be unnecessary because the X output buffer
395   is flushed automatically as needed by calls to XPending,
396   XNextEvent, or XWindowEvent according to the XFlush man page.
397   XTread_socket calls XPending.  Removing XFlush improves
398   performance.  */
399
400#define XFlush(DISPLAY)	(void) 0
401
402
403/***********************************************************************
404			      Debugging
405 ***********************************************************************/
406
407#if 0
408
409/* This is a function useful for recording debugging information about
410   the sequence of occurrences in this file.  */
411
412struct record
413{
414  char *locus;
415  int type;
416};
417
418struct record event_record[100];
419
420int event_record_index;
421
422record_event (locus, type)
423     char *locus;
424     int type;
425{
426  if (event_record_index == sizeof (event_record) / sizeof (struct record))
427    event_record_index = 0;
428
429  event_record[event_record_index].locus = locus;
430  event_record[event_record_index].type = type;
431  event_record_index++;
432}
433
434#endif /* 0 */
435
436
437
438/* Return the struct x_display_info corresponding to DPY.  */
439
440struct x_display_info *
441x_display_info_for_display (dpy)
442     Display *dpy;
443{
444  struct x_display_info *dpyinfo;
445
446  for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
447    if (dpyinfo->display == dpy)
448      return dpyinfo;
449
450  return 0;
451}
452
453
454
455/***********************************************************************
456		    Starting and ending an update
457 ***********************************************************************/
458
459/* Start an update of frame F.  This function is installed as a hook
460   for update_begin, i.e. it is called when update_begin is called.
461   This function is called prior to calls to x_update_window_begin for
462   each window being updated.  Currently, there is nothing to do here
463   because all interesting stuff is done on a window basis.  */
464
465static void
466x_update_begin (f)
467     struct frame *f;
468{
469  /* Nothing to do.  */
470}
471
472
473/* Start update of window W.  Set the global variable updated_window
474   to the window being updated and set output_cursor to the cursor
475   position of W.  */
476
477static void
478x_update_window_begin (w)
479     struct window *w;
480{
481  struct frame *f = XFRAME (WINDOW_FRAME (w));
482  struct x_display_info *display_info = FRAME_X_DISPLAY_INFO (f);
483
484  updated_window = w;
485  set_output_cursor (&w->cursor);
486
487  BLOCK_INPUT;
488
489  if (f == display_info->mouse_face_mouse_frame)
490    {
491      /* Don't do highlighting for mouse motion during the update.  */
492      display_info->mouse_face_defer = 1;
493
494      /* If F needs to be redrawn, simply forget about any prior mouse
495	 highlighting.  */
496      if (FRAME_GARBAGED_P (f))
497	display_info->mouse_face_window = Qnil;
498
499#if 0 /* Rows in a current matrix containing glyphs in mouse-face have
500	 their mouse_face_p flag set, which means that they are always
501	 unequal to rows in a desired matrix which never have that
502	 flag set.  So, rows containing mouse-face glyphs are never
503	 scrolled, and we don't have to switch the mouse highlight off
504	 here to prevent it from being scrolled.  */
505
506      /* Can we tell that this update does not affect the window
507	 where the mouse highlight is?  If so, no need to turn off.
508	 Likewise, don't do anything if the frame is garbaged;
509	 in that case, the frame's current matrix that we would use
510	 is all wrong, and we will redisplay that line anyway.  */
511      if (!NILP (display_info->mouse_face_window)
512	  && w == XWINDOW (display_info->mouse_face_window))
513	{
514	  int i;
515
516	  for (i = 0; i < w->desired_matrix->nrows; ++i)
517	    if (MATRIX_ROW_ENABLED_P (w->desired_matrix, i))
518	      break;
519
520	  if (i < w->desired_matrix->nrows)
521	    clear_mouse_face (display_info);
522	}
523#endif /* 0 */
524    }
525
526  UNBLOCK_INPUT;
527}
528
529
530/* Draw a vertical window border from (x,y0) to (x,y1)  */
531
532static void
533x_draw_vertical_window_border (w, x, y0, y1)
534     struct window *w;
535     int x, y0, y1;
536{
537  struct frame *f = XFRAME (WINDOW_FRAME (w));
538  struct face *face;
539
540  face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
541  if (face)
542    XSetForeground (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
543		    face->foreground);
544
545  XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
546	     f->output_data.x->normal_gc, x, y0, x, y1);
547}
548
549/* End update of window W (which is equal to updated_window).
550
551   Draw vertical borders between horizontally adjacent windows, and
552   display W's cursor if CURSOR_ON_P is non-zero.
553
554   MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
555   glyphs in mouse-face were overwritten.  In that case we have to
556   make sure that the mouse-highlight is properly redrawn.
557
558   W may be a menu bar pseudo-window in case we don't have X toolkit
559   support.  Such windows don't have a cursor, so don't display it
560   here.  */
561
562static void
563x_update_window_end (w, cursor_on_p, mouse_face_overwritten_p)
564     struct window *w;
565     int cursor_on_p, mouse_face_overwritten_p;
566{
567  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (XFRAME (w->frame));
568
569  if (!w->pseudo_window_p)
570    {
571      BLOCK_INPUT;
572
573      if (cursor_on_p)
574	display_and_set_cursor (w, 1, output_cursor.hpos,
575				output_cursor.vpos,
576				output_cursor.x, output_cursor.y);
577
578      if (draw_window_fringes (w, 1))
579	x_draw_vertical_border (w);
580
581      UNBLOCK_INPUT;
582    }
583
584  /* If a row with mouse-face was overwritten, arrange for
585     XTframe_up_to_date to redisplay the mouse highlight.  */
586  if (mouse_face_overwritten_p)
587    {
588      dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
589      dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
590      dpyinfo->mouse_face_window = Qnil;
591    }
592
593  updated_window = NULL;
594}
595
596
597/* End update of frame F.  This function is installed as a hook in
598   update_end.  */
599
600static void
601x_update_end (f)
602     struct frame *f;
603{
604  /* Mouse highlight may be displayed again.  */
605  FRAME_X_DISPLAY_INFO (f)->mouse_face_defer = 0;
606
607#ifndef XFlush
608  BLOCK_INPUT;
609  XFlush (FRAME_X_DISPLAY (f));
610  UNBLOCK_INPUT;
611#endif
612}
613
614
615/* This function is called from various places in xdisp.c whenever a
616   complete update has been performed.  The global variable
617   updated_window is not available here.  */
618
619static void
620XTframe_up_to_date (f)
621     struct frame *f;
622{
623  if (FRAME_X_P (f))
624    {
625      struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
626
627      if (dpyinfo->mouse_face_deferred_gc
628	  || f == dpyinfo->mouse_face_mouse_frame)
629	{
630	  BLOCK_INPUT;
631	  if (dpyinfo->mouse_face_mouse_frame)
632	    note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
633				  dpyinfo->mouse_face_mouse_x,
634				  dpyinfo->mouse_face_mouse_y);
635	  dpyinfo->mouse_face_deferred_gc = 0;
636	  UNBLOCK_INPUT;
637	}
638    }
639}
640
641
642/* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
643   arrow bitmaps, or clear the fringes if no bitmaps are required
644   before DESIRED_ROW is made current.  The window being updated is
645   found in updated_window.  This function It is called from
646   update_window_line only if it is known that there are differences
647   between bitmaps to be drawn between current row and DESIRED_ROW.  */
648
649static void
650x_after_update_window_line (desired_row)
651     struct glyph_row *desired_row;
652{
653  struct window *w = updated_window;
654  struct frame *f;
655  int width, height;
656
657  xassert (w);
658
659  if (!desired_row->mode_line_p && !w->pseudo_window_p)
660    desired_row->redraw_fringe_bitmaps_p = 1;
661
662  /* When a window has disappeared, make sure that no rest of
663     full-width rows stays visible in the internal border.  Could
664     check here if updated_window is the leftmost/rightmost window,
665     but I guess it's not worth doing since vertically split windows
666     are almost never used, internal border is rarely set, and the
667     overhead is very small.  */
668  if (windows_or_buffers_changed
669      && desired_row->full_width_p
670      && (f = XFRAME (w->frame),
671	  width = FRAME_INTERNAL_BORDER_WIDTH (f),
672	  width != 0)
673      && (height = desired_row->visible_height,
674	  height > 0))
675    {
676      int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
677
678      /* Internal border is drawn below the tool bar.  */
679      if (WINDOWP (f->tool_bar_window)
680	  && w == XWINDOW (f->tool_bar_window))
681	y -= width;
682
683      BLOCK_INPUT;
684      x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
685		    0, y, width, height, False);
686      x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
687		    FRAME_PIXEL_WIDTH (f) - width,
688		    y, width, height, False);
689      UNBLOCK_INPUT;
690    }
691}
692
693static void
694x_draw_fringe_bitmap (w, row, p)
695     struct window *w;
696     struct glyph_row *row;
697     struct draw_fringe_bitmap_params *p;
698{
699  struct frame *f = XFRAME (WINDOW_FRAME (w));
700  Display *display = FRAME_X_DISPLAY (f);
701  Window window = FRAME_X_WINDOW (f);
702  GC gc = f->output_data.x->normal_gc;
703  struct face *face = p->face;
704  int rowY;
705
706  /* Must clip because of partially visible lines.  */
707  rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
708  if (p->y < rowY)
709    {
710      /* Adjust position of "bottom aligned" bitmap on partially
711	 visible last row.  */
712      int oldY = row->y;
713      int oldVH = row->visible_height;
714      row->visible_height = p->h;
715      row->y -= rowY - p->y;
716      x_clip_to_row (w, row, -1, gc);
717      row->y = oldY;
718      row->visible_height = oldVH;
719    }
720  else
721    x_clip_to_row (w, row, -1, gc);
722
723  if (p->bx >= 0 && !p->overlay_p)
724    {
725      /* In case the same realized face is used for fringes and
726	 for something displayed in the text (e.g. face `region' on
727	 mono-displays, the fill style may have been changed to
728	 FillSolid in x_draw_glyph_string_background.  */
729      if (face->stipple)
730	XSetFillStyle (display, face->gc, FillOpaqueStippled);
731      else
732	XSetForeground (display, face->gc, face->background);
733
734      XFillRectangle (display, window, face->gc,
735		      p->bx, p->by, p->nx, p->ny);
736
737      if (!face->stipple)
738	XSetForeground (display, face->gc, face->foreground);
739    }
740
741  if (p->which)
742    {
743      unsigned char *bits;
744      Pixmap pixmap, clipmask = (Pixmap) 0;
745      int depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
746      XGCValues gcv;
747
748      if (p->wd > 8)
749	bits = (unsigned char *)(p->bits + p->dh);
750      else
751	bits = (unsigned char *)p->bits + p->dh;
752
753      /* Draw the bitmap.  I believe these small pixmaps can be cached
754	 by the server.  */
755      pixmap = XCreatePixmapFromBitmapData (display, window, bits, p->wd, p->h,
756					    (p->cursor_p
757					     ? (p->overlay_p ? face->background
758						: f->output_data.x->cursor_pixel)
759					     : face->foreground),
760					    face->background, depth);
761
762      if (p->overlay_p)
763	{
764	  clipmask = XCreatePixmapFromBitmapData (display,
765						  FRAME_X_DISPLAY_INFO (f)->root_window,
766						  bits, p->wd, p->h,
767						  1, 0, 1);
768	  gcv.clip_mask = clipmask;
769	  gcv.clip_x_origin = p->x;
770	  gcv.clip_y_origin = p->y;
771	  XChangeGC (display, gc, GCClipMask | GCClipXOrigin | GCClipYOrigin, &gcv);
772	}
773
774      XCopyArea (display, pixmap, window, gc, 0, 0,
775		 p->wd, p->h, p->x, p->y);
776      XFreePixmap (display, pixmap);
777
778      if (p->overlay_p)
779	{
780	  gcv.clip_mask = (Pixmap) 0;
781	  XChangeGC (display, gc, GCClipMask, &gcv);
782	  XFreePixmap (display, clipmask);
783	}
784    }
785
786  XSetClipMask (display, gc, None);
787}
788
789
790
791/* This is called when starting Emacs and when restarting after
792   suspend.  When starting Emacs, no X window is mapped.  And nothing
793   must be done to Emacs's own window if it is suspended (though that
794   rarely happens).  */
795
796static void
797XTset_terminal_modes ()
798{
799}
800
801/* This is called when exiting or suspending Emacs.  Exiting will make
802   the X-windows go away, and suspending requires no action.  */
803
804static void
805XTreset_terminal_modes ()
806{
807}
808
809
810
811/***********************************************************************
812			   Display Iterator
813 ***********************************************************************/
814
815/* Function prototypes of this page.  */
816
817static int x_encode_char P_ ((int, XChar2b *, struct font_info *, int *));
818
819
820/* Get metrics of character CHAR2B in FONT.  Value is null if CHAR2B
821   is not contained in the font.  */
822
823static XCharStruct *
824x_per_char_metric (font, char2b, font_type)
825     XFontStruct *font;
826     XChar2b *char2b;
827     int font_type;  /* unused on X */
828{
829  /* The result metric information.  */
830  XCharStruct *pcm = NULL;
831
832  xassert (font && char2b);
833
834  if (font->per_char != NULL)
835    {
836      if (font->min_byte1 == 0 && font->max_byte1 == 0)
837	{
838	  /* min_char_or_byte2 specifies the linear character index
839	     corresponding to the first element of the per_char array,
840	     max_char_or_byte2 is the index of the last character.  A
841	     character with non-zero CHAR2B->byte1 is not in the font.
842	     A character with byte2 less than min_char_or_byte2 or
843	     greater max_char_or_byte2 is not in the font.  */
844	  if (char2b->byte1 == 0
845	      && char2b->byte2 >= font->min_char_or_byte2
846	      && char2b->byte2 <= font->max_char_or_byte2)
847	    pcm = font->per_char + char2b->byte2 - font->min_char_or_byte2;
848	}
849      else
850	{
851	  /* If either min_byte1 or max_byte1 are nonzero, both
852	     min_char_or_byte2 and max_char_or_byte2 are less than
853	     256, and the 2-byte character index values corresponding
854	     to the per_char array element N (counting from 0) are:
855
856	     byte1 = N/D + min_byte1
857	     byte2 = N\D + min_char_or_byte2
858
859	     where:
860
861	     D = max_char_or_byte2 - min_char_or_byte2 + 1
862	     / = integer division
863	     \ = integer modulus  */
864	  if (char2b->byte1 >= font->min_byte1
865	      && char2b->byte1 <= font->max_byte1
866	      && char2b->byte2 >= font->min_char_or_byte2
867	      && char2b->byte2 <= font->max_char_or_byte2)
868	    {
869	      pcm = (font->per_char
870		     + ((font->max_char_or_byte2 - font->min_char_or_byte2 + 1)
871			* (char2b->byte1 - font->min_byte1))
872		     + (char2b->byte2 - font->min_char_or_byte2));
873	    }
874	}
875    }
876  else
877    {
878      /* If the per_char pointer is null, all glyphs between the first
879	 and last character indexes inclusive have the same
880	 information, as given by both min_bounds and max_bounds.  */
881      if (char2b->byte2 >= font->min_char_or_byte2
882	  && char2b->byte2 <= font->max_char_or_byte2)
883	pcm = &font->max_bounds;
884    }
885
886  return ((pcm == NULL
887	   || (pcm->width == 0 && (pcm->rbearing - pcm->lbearing) == 0))
888	  ? NULL : pcm);
889}
890
891
892/* Encode CHAR2B using encoding information from FONT_INFO.  CHAR2B is
893   the two-byte form of C.  Encoding is returned in *CHAR2B.  */
894
895static int
896x_encode_char (c, char2b, font_info, two_byte_p)
897     int c;
898     XChar2b *char2b;
899     struct font_info *font_info;
900     int *two_byte_p;
901{
902  int charset = CHAR_CHARSET (c);
903  XFontStruct *font = font_info->font;
904
905  /* FONT_INFO may define a scheme by which to encode byte1 and byte2.
906     This may be either a program in a special encoder language or a
907     fixed encoding.  */
908  if (font_info->font_encoder)
909    {
910      /* It's a program.  */
911      struct ccl_program *ccl = font_info->font_encoder;
912
913      check_ccl_update (ccl);
914      if (CHARSET_DIMENSION (charset) == 1)
915	{
916	  ccl->reg[0] = charset;
917	  ccl->reg[1] = char2b->byte2;
918	  ccl->reg[2] = -1;
919	}
920      else
921	{
922	  ccl->reg[0] = charset;
923	  ccl->reg[1] = char2b->byte1;
924	  ccl->reg[2] = char2b->byte2;
925	}
926
927      ccl_driver (ccl, NULL, NULL, 0, 0, NULL);
928
929      /* We assume that MSBs are appropriately set/reset by CCL
930	 program.  */
931      if (font->max_byte1 == 0)	/* 1-byte font */
932	char2b->byte1 = 0, char2b->byte2 = ccl->reg[1];
933      else
934	char2b->byte1 = ccl->reg[1], char2b->byte2 = ccl->reg[2];
935    }
936  else if (font_info->encoding[charset])
937    {
938      /* Fixed encoding scheme.  See fontset.h for the meaning of the
939	 encoding numbers.  */
940      int enc = font_info->encoding[charset];
941
942      if ((enc == 1 || enc == 2)
943	  && CHARSET_DIMENSION (charset) == 2)
944	char2b->byte1 |= 0x80;
945
946      if (enc == 1 || enc == 3)
947	char2b->byte2 |= 0x80;
948    }
949
950  if (two_byte_p)
951    *two_byte_p = ((XFontStruct *) (font_info->font))->max_byte1 > 0;
952
953  return FONT_TYPE_UNKNOWN;
954}
955
956
957
958/***********************************************************************
959			    Glyph display
960 ***********************************************************************/
961
962
963
964static void x_set_glyph_string_clipping P_ ((struct glyph_string *));
965static void x_set_glyph_string_gc P_ ((struct glyph_string *));
966static void x_draw_glyph_string_background P_ ((struct glyph_string *,
967						int));
968static void x_draw_glyph_string_foreground P_ ((struct glyph_string *));
969static void x_draw_composite_glyph_string_foreground P_ ((struct glyph_string *));
970static void x_draw_glyph_string_box P_ ((struct glyph_string *));
971static void x_draw_glyph_string  P_ ((struct glyph_string *));
972static void x_compute_glyph_string_overhangs P_ ((struct glyph_string *));
973static void x_set_cursor_gc P_ ((struct glyph_string *));
974static void x_set_mode_line_face_gc P_ ((struct glyph_string *));
975static void x_set_mouse_face_gc P_ ((struct glyph_string *));
976static int x_alloc_lighter_color P_ ((struct frame *, Display *, Colormap,
977				      unsigned long *, double, int));
978static void x_setup_relief_color P_ ((struct frame *, struct relief *,
979				      double, int, unsigned long));
980static void x_setup_relief_colors P_ ((struct glyph_string *));
981static void x_draw_image_glyph_string P_ ((struct glyph_string *));
982static void x_draw_image_relief P_ ((struct glyph_string *));
983static void x_draw_image_foreground P_ ((struct glyph_string *));
984static void x_draw_image_foreground_1 P_ ((struct glyph_string *, Pixmap));
985static void x_clear_glyph_string_rect P_ ((struct glyph_string *, int,
986					   int, int, int));
987static void x_draw_relief_rect P_ ((struct frame *, int, int, int, int,
988				    int, int, int, int, int, int,
989				    XRectangle *));
990static void x_draw_box_rect P_ ((struct glyph_string *, int, int, int, int,
991				 int, int, int, XRectangle *));
992
993#if GLYPH_DEBUG
994static void x_check_font P_ ((struct frame *, XFontStruct *));
995#endif
996
997
998/* Set S->gc to a suitable GC for drawing glyph string S in cursor
999   face.  */
1000
1001static void
1002x_set_cursor_gc (s)
1003     struct glyph_string *s;
1004{
1005  if (s->font == FRAME_FONT (s->f)
1006      && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
1007      && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
1008      && !s->cmp)
1009    s->gc = s->f->output_data.x->cursor_gc;
1010  else
1011    {
1012      /* Cursor on non-default face: must merge.  */
1013      XGCValues xgcv;
1014      unsigned long mask;
1015
1016      xgcv.background = s->f->output_data.x->cursor_pixel;
1017      xgcv.foreground = s->face->background;
1018
1019      /* If the glyph would be invisible, try a different foreground.  */
1020      if (xgcv.foreground == xgcv.background)
1021	xgcv.foreground = s->face->foreground;
1022      if (xgcv.foreground == xgcv.background)
1023	xgcv.foreground = s->f->output_data.x->cursor_foreground_pixel;
1024      if (xgcv.foreground == xgcv.background)
1025	xgcv.foreground = s->face->foreground;
1026
1027      /* Make sure the cursor is distinct from text in this face.  */
1028      if (xgcv.background == s->face->background
1029	  && xgcv.foreground == s->face->foreground)
1030	{
1031	  xgcv.background = s->face->foreground;
1032	  xgcv.foreground = s->face->background;
1033	}
1034
1035      IF_DEBUG (x_check_font (s->f, s->font));
1036      xgcv.font = s->font->fid;
1037      xgcv.graphics_exposures = False;
1038      mask = GCForeground | GCBackground | GCFont | GCGraphicsExposures;
1039
1040      if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1041	XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1042		   mask, &xgcv);
1043      else
1044	FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
1045	  = XCreateGC (s->display, s->window, mask, &xgcv);
1046
1047      s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1048    }
1049}
1050
1051
1052/* Set up S->gc of glyph string S for drawing text in mouse face.  */
1053
1054static void
1055x_set_mouse_face_gc (s)
1056     struct glyph_string *s;
1057{
1058  int face_id;
1059  struct face *face;
1060
1061  /* What face has to be used last for the mouse face?  */
1062  face_id = FRAME_X_DISPLAY_INFO (s->f)->mouse_face_face_id;
1063  face = FACE_FROM_ID (s->f, face_id);
1064  if (face == NULL)
1065    face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
1066
1067  if (s->first_glyph->type == CHAR_GLYPH)
1068    face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch);
1069  else
1070    face_id = FACE_FOR_CHAR (s->f, face, 0);
1071  s->face = FACE_FROM_ID (s->f, face_id);
1072  PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1073
1074  /* If font in this face is same as S->font, use it.  */
1075  if (s->font == s->face->font)
1076    s->gc = s->face->gc;
1077  else
1078    {
1079      /* Otherwise construct scratch_cursor_gc with values from FACE
1080	 but font FONT.  */
1081      XGCValues xgcv;
1082      unsigned long mask;
1083
1084      xgcv.background = s->face->background;
1085      xgcv.foreground = s->face->foreground;
1086      IF_DEBUG (x_check_font (s->f, s->font));
1087      xgcv.font = s->font->fid;
1088      xgcv.graphics_exposures = False;
1089      mask = GCForeground | GCBackground | GCFont | GCGraphicsExposures;
1090
1091      if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1092	XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1093		   mask, &xgcv);
1094      else
1095	FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
1096	  = XCreateGC (s->display, s->window, mask, &xgcv);
1097
1098      s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1099    }
1100
1101  xassert (s->gc != 0);
1102}
1103
1104
1105/* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1106   Faces to use in the mode line have already been computed when the
1107   matrix was built, so there isn't much to do, here.  */
1108
1109static INLINE void
1110x_set_mode_line_face_gc (s)
1111     struct glyph_string *s;
1112{
1113  s->gc = s->face->gc;
1114}
1115
1116
1117/* Set S->gc of glyph string S for drawing that glyph string.  Set
1118   S->stippled_p to a non-zero value if the face of S has a stipple
1119   pattern.  */
1120
1121static INLINE void
1122x_set_glyph_string_gc (s)
1123     struct glyph_string *s;
1124{
1125  PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1126
1127  if (s->hl == DRAW_NORMAL_TEXT)
1128    {
1129      s->gc = s->face->gc;
1130      s->stippled_p = s->face->stipple != 0;
1131    }
1132  else if (s->hl == DRAW_INVERSE_VIDEO)
1133    {
1134      x_set_mode_line_face_gc (s);
1135      s->stippled_p = s->face->stipple != 0;
1136    }
1137  else if (s->hl == DRAW_CURSOR)
1138    {
1139      x_set_cursor_gc (s);
1140      s->stippled_p = 0;
1141    }
1142  else if (s->hl == DRAW_MOUSE_FACE)
1143    {
1144      x_set_mouse_face_gc (s);
1145      s->stippled_p = s->face->stipple != 0;
1146    }
1147  else if (s->hl == DRAW_IMAGE_RAISED
1148	   || s->hl == DRAW_IMAGE_SUNKEN)
1149    {
1150      s->gc = s->face->gc;
1151      s->stippled_p = s->face->stipple != 0;
1152    }
1153  else
1154    {
1155      s->gc = s->face->gc;
1156      s->stippled_p = s->face->stipple != 0;
1157    }
1158
1159  /* GC must have been set.  */
1160  xassert (s->gc != 0);
1161}
1162
1163
1164/* Set clipping for output of glyph string S.  S may be part of a mode
1165   line or menu if we don't have X toolkit support.  */
1166
1167static INLINE void
1168x_set_glyph_string_clipping (s)
1169     struct glyph_string *s;
1170{
1171  XRectangle r;
1172  get_glyph_string_clip_rect (s, &r);
1173  XSetClipRectangles (s->display, s->gc, 0, 0, &r, 1, Unsorted);
1174}
1175
1176
1177/* RIF:
1178   Compute left and right overhang of glyph string S.  If S is a glyph
1179   string for a composition, assume overhangs don't exist.  */
1180
1181static void
1182x_compute_glyph_string_overhangs (s)
1183     struct glyph_string *s;
1184{
1185  if (s->cmp == NULL
1186      && s->first_glyph->type == CHAR_GLYPH)
1187    {
1188      XCharStruct cs;
1189      int direction, font_ascent, font_descent;
1190      XTextExtents16 (s->font, s->char2b, s->nchars, &direction,
1191		      &font_ascent, &font_descent, &cs);
1192      s->right_overhang = cs.rbearing > cs.width ? cs.rbearing - cs.width : 0;
1193      s->left_overhang = cs.lbearing < 0 ? -cs.lbearing : 0;
1194    }
1195}
1196
1197
1198/* Fill rectangle X, Y, W, H with background color of glyph string S.  */
1199
1200static INLINE void
1201x_clear_glyph_string_rect (s, x, y, w, h)
1202     struct glyph_string *s;
1203     int x, y, w, h;
1204{
1205  XGCValues xgcv;
1206  XGetGCValues (s->display, s->gc, GCForeground | GCBackground, &xgcv);
1207  XSetForeground (s->display, s->gc, xgcv.background);
1208  XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
1209  XSetForeground (s->display, s->gc, xgcv.foreground);
1210}
1211
1212
1213/* Draw the background of glyph_string S.  If S->background_filled_p
1214   is non-zero don't draw it.  FORCE_P non-zero means draw the
1215   background even if it wouldn't be drawn normally.  This is used
1216   when a string preceding S draws into the background of S, or S
1217   contains the first component of a composition.  */
1218
1219static void
1220x_draw_glyph_string_background (s, force_p)
1221     struct glyph_string *s;
1222     int force_p;
1223{
1224  /* Nothing to do if background has already been drawn or if it
1225     shouldn't be drawn in the first place.  */
1226  if (!s->background_filled_p)
1227    {
1228      int box_line_width = max (s->face->box_line_width, 0);
1229
1230      if (s->stippled_p)
1231	{
1232	  /* Fill background with a stipple pattern.  */
1233	  XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1234	  XFillRectangle (s->display, s->window, s->gc, s->x,
1235			  s->y + box_line_width,
1236			  s->background_width,
1237			  s->height - 2 * box_line_width);
1238	  XSetFillStyle (s->display, s->gc, FillSolid);
1239	  s->background_filled_p = 1;
1240	}
1241      else if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
1242	       || s->font_not_found_p
1243	       || s->extends_to_end_of_line_p
1244	       || force_p)
1245	{
1246	  x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
1247				     s->background_width,
1248				     s->height - 2 * box_line_width);
1249	  s->background_filled_p = 1;
1250	}
1251    }
1252}
1253
1254
1255/* Draw the foreground of glyph string S.  */
1256
1257static void
1258x_draw_glyph_string_foreground (s)
1259     struct glyph_string *s;
1260{
1261  int i, x;
1262
1263  /* If first glyph of S has a left box line, start drawing the text
1264     of S to the right of that box line.  */
1265  if (s->face->box != FACE_NO_BOX
1266      && s->first_glyph->left_box_line_p)
1267    x = s->x + abs (s->face->box_line_width);
1268  else
1269    x = s->x;
1270
1271  /* Draw characters of S as rectangles if S's font could not be
1272     loaded.  */
1273  if (s->font_not_found_p)
1274    {
1275      for (i = 0; i < s->nchars; ++i)
1276	{
1277	  struct glyph *g = s->first_glyph + i;
1278	  XDrawRectangle (s->display, s->window,
1279			  s->gc, x, s->y, g->pixel_width - 1,
1280			  s->height - 1);
1281	  x += g->pixel_width;
1282	}
1283    }
1284  else
1285    {
1286      char *char1b = (char *) s->char2b;
1287      int boff = s->font_info->baseline_offset;
1288
1289      if (s->font_info->vertical_centering)
1290	boff = VCENTER_BASELINE_OFFSET (s->font, s->f) - boff;
1291
1292      /* If we can use 8-bit functions, condense S->char2b.  */
1293      if (!s->two_byte_p)
1294	for (i = 0; i < s->nchars; ++i)
1295	  char1b[i] = s->char2b[i].byte2;
1296
1297      /* Draw text with XDrawString if background has already been
1298	 filled.  Otherwise, use XDrawImageString.  (Note that
1299	 XDrawImageString is usually faster than XDrawString.)  Always
1300	 use XDrawImageString when drawing the cursor so that there is
1301	 no chance that characters under a box cursor are invisible.  */
1302      if (s->for_overlaps
1303	  || (s->background_filled_p && s->hl != DRAW_CURSOR))
1304	{
1305	  /* Draw characters with 16-bit or 8-bit functions.  */
1306	  if (s->two_byte_p)
1307	    XDrawString16 (s->display, s->window, s->gc, x,
1308			   s->ybase - boff, s->char2b, s->nchars);
1309	  else
1310	    XDrawString (s->display, s->window, s->gc, x,
1311			 s->ybase - boff, char1b, s->nchars);
1312	}
1313      else
1314	{
1315	  if (s->two_byte_p)
1316	    XDrawImageString16 (s->display, s->window, s->gc, x,
1317				s->ybase - boff, s->char2b, s->nchars);
1318	  else
1319	    XDrawImageString (s->display, s->window, s->gc, x,
1320			      s->ybase - boff, char1b, s->nchars);
1321	}
1322
1323      if (s->face->overstrike)
1324	{
1325	  /* For overstriking (to simulate bold-face), draw the
1326	     characters again shifted to the right by one pixel.  */
1327	  if (s->two_byte_p)
1328	    XDrawString16 (s->display, s->window, s->gc, x + 1,
1329			   s->ybase - boff, s->char2b, s->nchars);
1330	  else
1331	    XDrawString (s->display, s->window, s->gc, x + 1,
1332			 s->ybase - boff, char1b, s->nchars);
1333	}
1334    }
1335}
1336
1337/* Draw the foreground of composite glyph string S.  */
1338
1339static void
1340x_draw_composite_glyph_string_foreground (s)
1341     struct glyph_string *s;
1342{
1343  int i, x;
1344
1345  /* If first glyph of S has a left box line, start drawing the text
1346     of S to the right of that box line.  */
1347  if (s->face->box != FACE_NO_BOX
1348      && s->first_glyph->left_box_line_p)
1349    x = s->x + abs (s->face->box_line_width);
1350  else
1351    x = s->x;
1352
1353  /* S is a glyph string for a composition.  S->gidx is the index of
1354     the first character drawn for glyphs of this composition.
1355     S->gidx == 0 means we are drawing the very first character of
1356     this composition.  */
1357
1358  /* Draw a rectangle for the composition if the font for the very
1359     first character of the composition could not be loaded.  */
1360  if (s->font_not_found_p)
1361    {
1362      if (s->gidx == 0)
1363	XDrawRectangle (s->display, s->window, s->gc, x, s->y,
1364			s->width - 1, s->height - 1);
1365    }
1366  else
1367    {
1368      for (i = 0; i < s->nchars; i++, ++s->gidx)
1369	{
1370	  XDrawString16 (s->display, s->window, s->gc,
1371			 x + s->cmp->offsets[s->gidx * 2],
1372			 s->ybase - s->cmp->offsets[s->gidx * 2 + 1],
1373			 s->char2b + i, 1);
1374	  if (s->face->overstrike)
1375	    XDrawString16 (s->display, s->window, s->gc,
1376			   x + s->cmp->offsets[s->gidx * 2] + 1,
1377			   s->ybase - s->cmp->offsets[s->gidx * 2 + 1],
1378			   s->char2b + i, 1);
1379	}
1380    }
1381}
1382
1383
1384#ifdef USE_X_TOOLKIT
1385
1386static struct frame *x_frame_of_widget P_ ((Widget));
1387static Boolean cvt_string_to_pixel P_ ((Display *, XrmValue *, Cardinal *,
1388					XrmValue *, XrmValue *, XtPointer *));
1389static void cvt_pixel_dtor P_ ((XtAppContext, XrmValue *, XtPointer,
1390				XrmValue *, Cardinal *));
1391
1392
1393/* Return the frame on which widget WIDGET is used.. Abort if frame
1394   cannot be determined.  */
1395
1396static struct frame *
1397x_frame_of_widget (widget)
1398     Widget widget;
1399{
1400  struct x_display_info *dpyinfo;
1401  Lisp_Object tail;
1402  struct frame *f;
1403
1404  dpyinfo = x_display_info_for_display (XtDisplay (widget));
1405
1406  /* Find the top-level shell of the widget.  Note that this function
1407     can be called when the widget is not yet realized, so XtWindow
1408     (widget) == 0.  That's the reason we can't simply use
1409     x_any_window_to_frame.  */
1410  while (!XtIsTopLevelShell (widget))
1411    widget = XtParent (widget);
1412
1413  /* Look for a frame with that top-level widget.  Allocate the color
1414     on that frame to get the right gamma correction value.  */
1415  for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
1416    if (GC_FRAMEP (XCAR (tail))
1417	&& (f = XFRAME (XCAR (tail)),
1418	    (f->output_data.nothing != 1
1419	     && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
1420	&& f->output_data.x->widget == widget)
1421      return f;
1422
1423  abort ();
1424}
1425
1426
1427/* Allocate the color COLOR->pixel on the screen and display of
1428   widget WIDGET in colormap CMAP.  If an exact match cannot be
1429   allocated, try the nearest color available.  Value is non-zero
1430   if successful.  This is called from lwlib.  */
1431
1432int
1433x_alloc_nearest_color_for_widget (widget, cmap, color)
1434     Widget widget;
1435     Colormap cmap;
1436     XColor *color;
1437{
1438  struct frame *f = x_frame_of_widget (widget);
1439  return x_alloc_nearest_color (f, cmap, color);
1440}
1441
1442
1443/* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1444   or DELTA.  Try a color with RGB values multiplied by FACTOR first.
1445   If this produces the same color as PIXEL, try a color where all RGB
1446   values have DELTA added.  Return the allocated color in *PIXEL.
1447   DISPLAY is the X display, CMAP is the colormap to operate on.
1448   Value is non-zero if successful.  */
1449
1450int
1451x_alloc_lighter_color_for_widget (widget, display, cmap, pixel, factor, delta)
1452     Widget widget;
1453     Display *display;
1454     Colormap cmap;
1455     unsigned long *pixel;
1456     double factor;
1457     int delta;
1458{
1459  struct frame *f = x_frame_of_widget (widget);
1460  return x_alloc_lighter_color (f, display, cmap, pixel, factor, delta);
1461}
1462
1463
1464/* Structure specifying which arguments should be passed by Xt to
1465   cvt_string_to_pixel.  We want the widget's screen and colormap.  */
1466
1467static XtConvertArgRec cvt_string_to_pixel_args[] =
1468  {
1469    {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.screen),
1470     sizeof (Screen *)},
1471    {XtWidgetBaseOffset, (XtPointer) XtOffset (Widget, core.colormap),
1472     sizeof (Colormap)}
1473  };
1474
1475
1476/* The address of this variable is returned by
1477   cvt_string_to_pixel.  */
1478
1479static Pixel cvt_string_to_pixel_value;
1480
1481
1482/* Convert a color name to a pixel color.
1483
1484   DPY is the display we are working on.
1485
1486   ARGS is an array of *NARGS XrmValue structures holding additional
1487   information about the widget for which the conversion takes place.
1488   The contents of this array are determined by the specification
1489   in cvt_string_to_pixel_args.
1490
1491   FROM is a pointer to an XrmValue which points to the color name to
1492   convert.  TO is an XrmValue in which to return the pixel color.
1493
1494   CLOSURE_RET is a pointer to user-data, in which we record if
1495   we allocated the color or not.
1496
1497   Value is True if successful, False otherwise.  */
1498
1499static Boolean
1500cvt_string_to_pixel (dpy, args, nargs, from, to, closure_ret)
1501     Display *dpy;
1502     XrmValue *args;
1503     Cardinal *nargs;
1504     XrmValue *from, *to;
1505     XtPointer *closure_ret;
1506{
1507  Screen *screen;
1508  Colormap cmap;
1509  Pixel pixel;
1510  String color_name;
1511  XColor color;
1512
1513  if (*nargs != 2)
1514    {
1515      XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1516		       "wrongParameters", "cvt_string_to_pixel",
1517		       "XtToolkitError",
1518		       "Screen and colormap args required", NULL, NULL);
1519      return False;
1520    }
1521
1522  screen = *(Screen **) args[0].addr;
1523  cmap = *(Colormap *) args[1].addr;
1524  color_name = (String) from->addr;
1525
1526  if (strcmp (color_name, XtDefaultBackground) == 0)
1527    {
1528      *closure_ret = (XtPointer) False;
1529      pixel = WhitePixelOfScreen (screen);
1530    }
1531  else if (strcmp (color_name, XtDefaultForeground) == 0)
1532    {
1533      *closure_ret = (XtPointer) False;
1534      pixel = BlackPixelOfScreen (screen);
1535    }
1536  else if (XParseColor (dpy, cmap, color_name, &color)
1537	   && x_alloc_nearest_color_1 (dpy, cmap, &color))
1538    {
1539      pixel = color.pixel;
1540      *closure_ret = (XtPointer) True;
1541    }
1542  else
1543    {
1544      String params[1];
1545      Cardinal nparams = 1;
1546
1547      params[0] = color_name;
1548      XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
1549		       "badValue", "cvt_string_to_pixel",
1550		       "XtToolkitError", "Invalid color `%s'",
1551		       params, &nparams);
1552      return False;
1553    }
1554
1555  if (to->addr != NULL)
1556    {
1557      if (to->size < sizeof (Pixel))
1558	{
1559	  to->size = sizeof (Pixel);
1560	  return False;
1561	}
1562
1563      *(Pixel *) to->addr = pixel;
1564    }
1565  else
1566    {
1567      cvt_string_to_pixel_value = pixel;
1568      to->addr = (XtPointer) &cvt_string_to_pixel_value;
1569    }
1570
1571  to->size = sizeof (Pixel);
1572  return True;
1573}
1574
1575
1576/* Free a pixel color which was previously allocated via
1577   cvt_string_to_pixel.  This is registered as the destructor
1578   for this type of resource via XtSetTypeConverter.
1579
1580   APP is the application context in which we work.
1581
1582   TO is a pointer to an XrmValue holding the color to free.
1583   CLOSURE is the value we stored in CLOSURE_RET for this color
1584   in cvt_string_to_pixel.
1585
1586   ARGS and NARGS are like for cvt_string_to_pixel.  */
1587
1588static void
1589cvt_pixel_dtor (app, to, closure, args, nargs)
1590    XtAppContext app;
1591    XrmValuePtr to;
1592    XtPointer closure;
1593    XrmValuePtr args;
1594    Cardinal *nargs;
1595{
1596  if (*nargs != 2)
1597    {
1598      XtAppWarningMsg (app, "wrongParameters", "cvt_pixel_dtor",
1599		       "XtToolkitError",
1600		       "Screen and colormap arguments required",
1601		       NULL, NULL);
1602    }
1603  else if (closure != NULL)
1604    {
1605      /* We did allocate the pixel, so free it.  */
1606      Screen *screen = *(Screen **) args[0].addr;
1607      Colormap cmap = *(Colormap *) args[1].addr;
1608      x_free_dpy_colors (DisplayOfScreen (screen), screen, cmap,
1609			 (Pixel *) to->addr, 1);
1610    }
1611}
1612
1613
1614#endif /* USE_X_TOOLKIT */
1615
1616
1617/* Value is an array of XColor structures for the contents of the
1618   color map of display DPY.  Set *NCELLS to the size of the array.
1619   Note that this probably shouldn't be called for large color maps,
1620   say a 24-bit TrueColor map.  */
1621
1622static const XColor *
1623x_color_cells (dpy, ncells)
1624     Display *dpy;
1625     int *ncells;
1626{
1627  struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1628
1629  if (dpyinfo->color_cells == NULL)
1630    {
1631      Screen *screen = dpyinfo->screen;
1632      int i;
1633
1634      dpyinfo->ncolor_cells
1635	= XDisplayCells (dpy, XScreenNumberOfScreen (screen));
1636      dpyinfo->color_cells
1637	= (XColor *) xmalloc (dpyinfo->ncolor_cells
1638			      * sizeof *dpyinfo->color_cells);
1639
1640      for (i = 0; i < dpyinfo->ncolor_cells; ++i)
1641	dpyinfo->color_cells[i].pixel = i;
1642
1643      XQueryColors (dpy, dpyinfo->cmap,
1644		    dpyinfo->color_cells, dpyinfo->ncolor_cells);
1645    }
1646
1647  *ncells = dpyinfo->ncolor_cells;
1648  return dpyinfo->color_cells;
1649}
1650
1651
1652/* On frame F, translate pixel colors to RGB values for the NCOLORS
1653   colors in COLORS.  Use cached information, if available.  */
1654
1655void
1656x_query_colors (f, colors, ncolors)
1657     struct frame *f;
1658     XColor *colors;
1659     int ncolors;
1660{
1661  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1662
1663  if (dpyinfo->color_cells)
1664    {
1665      int i;
1666      for (i = 0; i < ncolors; ++i)
1667	{
1668	  unsigned long pixel = colors[i].pixel;
1669	  xassert (pixel < dpyinfo->ncolor_cells);
1670	  xassert (dpyinfo->color_cells[pixel].pixel == pixel);
1671	  colors[i] = dpyinfo->color_cells[pixel];
1672	}
1673    }
1674  else
1675    XQueryColors (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), colors, ncolors);
1676}
1677
1678
1679/* On frame F, translate pixel color to RGB values for the color in
1680   COLOR.  Use cached information, if available.  */
1681
1682void
1683x_query_color (f, color)
1684     struct frame *f;
1685     XColor *color;
1686{
1687  x_query_colors (f, color, 1);
1688}
1689
1690
1691/* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP.  If an
1692   exact match can't be allocated, try the nearest color available.
1693   Value is non-zero if successful.  Set *COLOR to the color
1694   allocated.  */
1695
1696static int
1697x_alloc_nearest_color_1 (dpy, cmap, color)
1698     Display *dpy;
1699     Colormap cmap;
1700     XColor *color;
1701{
1702  int rc;
1703
1704  rc = XAllocColor (dpy, cmap, color);
1705  if (rc == 0)
1706    {
1707      /* If we got to this point, the colormap is full, so we're going
1708	 to try to get the next closest color.  The algorithm used is
1709	 a least-squares matching, which is what X uses for closest
1710	 color matching with StaticColor visuals.  */
1711      int nearest, i;
1712      unsigned long nearest_delta = ~0;
1713      int ncells;
1714      const XColor *cells = x_color_cells (dpy, &ncells);
1715
1716      for (nearest = i = 0; i < ncells; ++i)
1717	{
1718	  long dred   = (color->red   >> 8) - (cells[i].red   >> 8);
1719	  long dgreen = (color->green >> 8) - (cells[i].green >> 8);
1720	  long dblue  = (color->blue  >> 8) - (cells[i].blue  >> 8);
1721	  unsigned long delta = dred * dred + dgreen * dgreen + dblue * dblue;
1722
1723	  if (delta < nearest_delta)
1724	    {
1725	      nearest = i;
1726	      nearest_delta = delta;
1727	    }
1728	}
1729
1730      color->red   = cells[nearest].red;
1731      color->green = cells[nearest].green;
1732      color->blue  = cells[nearest].blue;
1733      rc = XAllocColor (dpy, cmap, color);
1734    }
1735  else
1736    {
1737      /* If allocation succeeded, and the allocated pixel color is not
1738         equal to a cached pixel color recorded earlier, there was a
1739         change in the colormap, so clear the color cache.  */
1740      struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
1741      XColor *cached_color;
1742
1743      if (dpyinfo->color_cells
1744	  && (cached_color = &dpyinfo->color_cells[color->pixel],
1745	      (cached_color->red != color->red
1746	       || cached_color->blue != color->blue
1747	       || cached_color->green != color->green)))
1748	{
1749	  xfree (dpyinfo->color_cells);
1750	  dpyinfo->color_cells = NULL;
1751	  dpyinfo->ncolor_cells = 0;
1752	}
1753    }
1754
1755#ifdef DEBUG_X_COLORS
1756  if (rc)
1757    register_color (color->pixel);
1758#endif /* DEBUG_X_COLORS */
1759
1760  return rc;
1761}
1762
1763
1764/* Allocate the color COLOR->pixel on frame F, colormap CMAP.  If an
1765   exact match can't be allocated, try the nearest color available.
1766   Value is non-zero if successful.  Set *COLOR to the color
1767   allocated.  */
1768
1769int
1770x_alloc_nearest_color (f, cmap, color)
1771     struct frame *f;
1772     Colormap cmap;
1773     XColor *color;
1774{
1775  gamma_correct (f, color);
1776  return x_alloc_nearest_color_1 (FRAME_X_DISPLAY (f), cmap, color);
1777}
1778
1779
1780/* Allocate color PIXEL on frame F.  PIXEL must already be allocated.
1781   It's necessary to do this instead of just using PIXEL directly to
1782   get color reference counts right.  */
1783
1784unsigned long
1785x_copy_color (f, pixel)
1786     struct frame *f;
1787     unsigned long pixel;
1788{
1789  XColor color;
1790
1791  color.pixel = pixel;
1792  BLOCK_INPUT;
1793  x_query_color (f, &color);
1794  XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
1795  UNBLOCK_INPUT;
1796#ifdef DEBUG_X_COLORS
1797  register_color (pixel);
1798#endif
1799  return color.pixel;
1800}
1801
1802
1803/* Allocate color PIXEL on display DPY.  PIXEL must already be allocated.
1804   It's necessary to do this instead of just using PIXEL directly to
1805   get color reference counts right.  */
1806
1807unsigned long
1808x_copy_dpy_color (dpy, cmap, pixel)
1809     Display *dpy;
1810     Colormap cmap;
1811     unsigned long pixel;
1812{
1813  XColor color;
1814
1815  color.pixel = pixel;
1816  BLOCK_INPUT;
1817  XQueryColor (dpy, cmap, &color);
1818  XAllocColor (dpy, cmap, &color);
1819  UNBLOCK_INPUT;
1820#ifdef DEBUG_X_COLORS
1821  register_color (pixel);
1822#endif
1823  return color.pixel;
1824}
1825
1826
1827/* Brightness beyond which a color won't have its highlight brightness
1828   boosted.
1829
1830   Nominally, highlight colors for `3d' faces are calculated by
1831   brightening an object's color by a constant scale factor, but this
1832   doesn't yield good results for dark colors, so for colors who's
1833   brightness is less than this value (on a scale of 0-65535) have an
1834   use an additional additive factor.
1835
1836   The value here is set so that the default menu-bar/mode-line color
1837   (grey75) will not have its highlights changed at all.  */
1838#define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 48000
1839
1840
1841/* Allocate a color which is lighter or darker than *PIXEL by FACTOR
1842   or DELTA.  Try a color with RGB values multiplied by FACTOR first.
1843   If this produces the same color as PIXEL, try a color where all RGB
1844   values have DELTA added.  Return the allocated color in *PIXEL.
1845   DISPLAY is the X display, CMAP is the colormap to operate on.
1846   Value is non-zero if successful.  */
1847
1848static int
1849x_alloc_lighter_color (f, display, cmap, pixel, factor, delta)
1850     struct frame *f;
1851     Display *display;
1852     Colormap cmap;
1853     unsigned long *pixel;
1854     double factor;
1855     int delta;
1856{
1857  XColor color, new;
1858  long bright;
1859  int success_p;
1860
1861  /* Get RGB color values.  */
1862  color.pixel = *pixel;
1863  x_query_color (f, &color);
1864
1865  /* Change RGB values by specified FACTOR.  Avoid overflow!  */
1866  xassert (factor >= 0);
1867  new.red = min (0xffff, factor * color.red);
1868  new.green = min (0xffff, factor * color.green);
1869  new.blue = min (0xffff, factor * color.blue);
1870
1871  /* Calculate brightness of COLOR.  */
1872  bright = (2 * color.red + 3 * color.green + color.blue) / 6;
1873
1874  /* We only boost colors that are darker than
1875     HIGHLIGHT_COLOR_DARK_BOOST_LIMIT.  */
1876  if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
1877    /* Make an additive adjustment to NEW, because it's dark enough so
1878       that scaling by FACTOR alone isn't enough.  */
1879    {
1880      /* How far below the limit this color is (0 - 1, 1 being darker).  */
1881      double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
1882      /* The additive adjustment.  */
1883      int min_delta = delta * dimness * factor / 2;
1884
1885      if (factor < 1)
1886	{
1887	  new.red =   max (0, new.red -   min_delta);
1888	  new.green = max (0, new.green - min_delta);
1889	  new.blue =  max (0, new.blue -  min_delta);
1890	}
1891      else
1892	{
1893	  new.red =   min (0xffff, min_delta + new.red);
1894	  new.green = min (0xffff, min_delta + new.green);
1895	  new.blue =  min (0xffff, min_delta + new.blue);
1896	}
1897    }
1898
1899  /* Try to allocate the color.  */
1900  success_p = x_alloc_nearest_color (f, cmap, &new);
1901  if (success_p)
1902    {
1903      if (new.pixel == *pixel)
1904	{
1905	  /* If we end up with the same color as before, try adding
1906	     delta to the RGB values.  */
1907	  x_free_colors (f, &new.pixel, 1);
1908
1909	  new.red = min (0xffff, delta + color.red);
1910	  new.green = min (0xffff, delta + color.green);
1911	  new.blue = min (0xffff, delta + color.blue);
1912	  success_p = x_alloc_nearest_color (f, cmap, &new);
1913	}
1914      else
1915	success_p = 1;
1916      *pixel = new.pixel;
1917    }
1918
1919  return success_p;
1920}
1921
1922
1923/* Set up the foreground color for drawing relief lines of glyph
1924   string S.  RELIEF is a pointer to a struct relief containing the GC
1925   with which lines will be drawn.  Use a color that is FACTOR or
1926   DELTA lighter or darker than the relief's background which is found
1927   in S->f->output_data.x->relief_background.  If such a color cannot
1928   be allocated, use DEFAULT_PIXEL, instead.  */
1929
1930static void
1931x_setup_relief_color (f, relief, factor, delta, default_pixel)
1932     struct frame *f;
1933     struct relief *relief;
1934     double factor;
1935     int delta;
1936     unsigned long default_pixel;
1937{
1938  XGCValues xgcv;
1939  struct x_output *di = f->output_data.x;
1940  unsigned long mask = GCForeground | GCLineWidth | GCGraphicsExposures;
1941  unsigned long pixel;
1942  unsigned long background = di->relief_background;
1943  Colormap cmap = FRAME_X_COLORMAP (f);
1944  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1945  Display *dpy = FRAME_X_DISPLAY (f);
1946
1947  xgcv.graphics_exposures = False;
1948  xgcv.line_width = 1;
1949
1950  /* Free previously allocated color.  The color cell will be reused
1951     when it has been freed as many times as it was allocated, so this
1952     doesn't affect faces using the same colors.  */
1953  if (relief->gc
1954      && relief->allocated_p)
1955    {
1956      x_free_colors (f, &relief->pixel, 1);
1957      relief->allocated_p = 0;
1958    }
1959
1960  /* Allocate new color.  */
1961  xgcv.foreground = default_pixel;
1962  pixel = background;
1963  if (dpyinfo->n_planes != 1
1964      && x_alloc_lighter_color (f, dpy, cmap, &pixel, factor, delta))
1965    {
1966      relief->allocated_p = 1;
1967      xgcv.foreground = relief->pixel = pixel;
1968    }
1969
1970  if (relief->gc == 0)
1971    {
1972      xgcv.stipple = dpyinfo->gray;
1973      mask |= GCStipple;
1974      relief->gc = XCreateGC (dpy, FRAME_X_WINDOW (f), mask, &xgcv);
1975    }
1976  else
1977    XChangeGC (dpy, relief->gc, mask, &xgcv);
1978}
1979
1980
1981/* Set up colors for the relief lines around glyph string S.  */
1982
1983static void
1984x_setup_relief_colors (s)
1985     struct glyph_string *s;
1986{
1987  struct x_output *di = s->f->output_data.x;
1988  unsigned long color;
1989
1990  if (s->face->use_box_color_for_shadows_p)
1991    color = s->face->box_color;
1992  else if (s->first_glyph->type == IMAGE_GLYPH
1993	   && s->img->pixmap
1994	   && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
1995    color = IMAGE_BACKGROUND (s->img, s->f, 0);
1996  else
1997    {
1998      XGCValues xgcv;
1999
2000      /* Get the background color of the face.  */
2001      XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2002      color = xgcv.background;
2003    }
2004
2005  if (di->white_relief.gc == 0
2006      || color != di->relief_background)
2007    {
2008      di->relief_background = color;
2009      x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2010			    WHITE_PIX_DEFAULT (s->f));
2011      x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2012			    BLACK_PIX_DEFAULT (s->f));
2013    }
2014}
2015
2016
2017/* Draw a relief on frame F inside the rectangle given by LEFT_X,
2018   TOP_Y, RIGHT_X, and BOTTOM_Y.  WIDTH is the thickness of the relief
2019   to draw, it must be >= 0.  RAISED_P non-zero means draw a raised
2020   relief.  LEFT_P non-zero means draw a relief on the left side of
2021   the rectangle.  RIGHT_P non-zero means draw a relief on the right
2022   side of the rectangle.  CLIP_RECT is the clipping rectangle to use
2023   when drawing.  */
2024
2025static void
2026x_draw_relief_rect (f, left_x, top_y, right_x, bottom_y, width,
2027		    raised_p, top_p, bot_p, left_p, right_p, clip_rect)
2028     struct frame *f;
2029     int left_x, top_y, right_x, bottom_y, width;
2030     int top_p, bot_p, left_p, right_p, raised_p;
2031     XRectangle *clip_rect;
2032{
2033  Display *dpy = FRAME_X_DISPLAY (f);
2034  Window window = FRAME_X_WINDOW (f);
2035  int i;
2036  GC gc;
2037
2038  if (raised_p)
2039    gc = f->output_data.x->white_relief.gc;
2040  else
2041    gc = f->output_data.x->black_relief.gc;
2042  XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2043
2044  /* Top.  */
2045  if (top_p)
2046    for (i = 0; i < width; ++i)
2047      XDrawLine (dpy, window, gc,
2048		 left_x + i * left_p, top_y + i,
2049		 right_x + 1 - i * right_p, top_y + i);
2050
2051  /* Left.  */
2052  if (left_p)
2053    for (i = 0; i < width; ++i)
2054      XDrawLine (dpy, window, gc,
2055		 left_x + i, top_y + i, left_x + i, bottom_y - i + 1);
2056
2057  XSetClipMask (dpy, gc, None);
2058  if (raised_p)
2059    gc = f->output_data.x->black_relief.gc;
2060  else
2061    gc = f->output_data.x->white_relief.gc;
2062  XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
2063
2064  /* Bottom.  */
2065  if (bot_p)
2066    for (i = 0; i < width; ++i)
2067      XDrawLine (dpy, window, gc,
2068		 left_x + i * left_p, bottom_y - i,
2069		 right_x + 1 - i * right_p, bottom_y - i);
2070
2071  /* Right.  */
2072  if (right_p)
2073    for (i = 0; i < width; ++i)
2074      XDrawLine (dpy, window, gc,
2075		 right_x - i, top_y + i + 1, right_x - i, bottom_y - i);
2076
2077  XSetClipMask (dpy, gc, None);
2078}
2079
2080
2081/* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2082   RIGHT_X, and BOTTOM_Y.  WIDTH is the thickness of the lines to
2083   draw, it must be >= 0.  LEFT_P non-zero means draw a line on the
2084   left side of the rectangle.  RIGHT_P non-zero means draw a line
2085   on the right side of the rectangle.  CLIP_RECT is the clipping
2086   rectangle to use when drawing.  */
2087
2088static void
2089x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2090		 left_p, right_p, clip_rect)
2091     struct glyph_string *s;
2092     int left_x, top_y, right_x, bottom_y, width, left_p, right_p;
2093     XRectangle *clip_rect;
2094{
2095  XGCValues xgcv;
2096
2097  XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2098  XSetForeground (s->display, s->gc, s->face->box_color);
2099  XSetClipRectangles (s->display, s->gc, 0, 0, clip_rect, 1, Unsorted);
2100
2101  /* Top.  */
2102  XFillRectangle (s->display, s->window, s->gc,
2103		  left_x, top_y, right_x - left_x + 1, width);
2104
2105  /* Left.  */
2106  if (left_p)
2107    XFillRectangle (s->display, s->window, s->gc,
2108		    left_x, top_y, width, bottom_y - top_y + 1);
2109
2110  /* Bottom.  */
2111  XFillRectangle (s->display, s->window, s->gc,
2112		  left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2113
2114  /* Right.  */
2115  if (right_p)
2116    XFillRectangle (s->display, s->window, s->gc,
2117		    right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2118
2119  XSetForeground (s->display, s->gc, xgcv.foreground);
2120  XSetClipMask (s->display, s->gc, None);
2121}
2122
2123
2124/* Draw a box around glyph string S.  */
2125
2126static void
2127x_draw_glyph_string_box (s)
2128     struct glyph_string *s;
2129{
2130  int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2131  int left_p, right_p;
2132  struct glyph *last_glyph;
2133  XRectangle clip_rect;
2134
2135  last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2136	    ? WINDOW_RIGHT_EDGE_X (s->w)
2137	    : window_box_right (s->w, s->area));
2138
2139  /* The glyph that may have a right box line.  */
2140  last_glyph = (s->cmp || s->img
2141		? s->first_glyph
2142		: s->first_glyph + s->nchars - 1);
2143
2144  width = abs (s->face->box_line_width);
2145  raised_p = s->face->box == FACE_RAISED_BOX;
2146  left_x = s->x;
2147  right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2148	     ? last_x - 1
2149	     : min (last_x, s->x + s->background_width) - 1);
2150  top_y = s->y;
2151  bottom_y = top_y + s->height - 1;
2152
2153  left_p = (s->first_glyph->left_box_line_p
2154	    || (s->hl == DRAW_MOUSE_FACE
2155		&& (s->prev == NULL
2156		    || s->prev->hl != s->hl)));
2157  right_p = (last_glyph->right_box_line_p
2158	     || (s->hl == DRAW_MOUSE_FACE
2159		 && (s->next == NULL
2160		     || s->next->hl != s->hl)));
2161
2162  get_glyph_string_clip_rect (s, &clip_rect);
2163
2164  if (s->face->box == FACE_SIMPLE_BOX)
2165    x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2166		     left_p, right_p, &clip_rect);
2167  else
2168    {
2169      x_setup_relief_colors (s);
2170      x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2171			  width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2172    }
2173}
2174
2175
2176/* Draw foreground of image glyph string S.  */
2177
2178static void
2179x_draw_image_foreground (s)
2180     struct glyph_string *s;
2181{
2182  int x = s->x;
2183  int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2184
2185  /* If first glyph of S has a left box line, start drawing it to the
2186     right of that line.  */
2187  if (s->face->box != FACE_NO_BOX
2188      && s->first_glyph->left_box_line_p
2189      && s->slice.x == 0)
2190    x += abs (s->face->box_line_width);
2191
2192  /* If there is a margin around the image, adjust x- and y-position
2193     by that margin.  */
2194  if (s->slice.x == 0)
2195    x += s->img->hmargin;
2196  if (s->slice.y == 0)
2197    y += s->img->vmargin;
2198
2199  if (s->img->pixmap)
2200    {
2201      if (s->img->mask)
2202	{
2203	  /* We can't set both a clip mask and use XSetClipRectangles
2204	     because the latter also sets a clip mask.  We also can't
2205	     trust on the shape extension to be available
2206	     (XShapeCombineRegion).  So, compute the rectangle to draw
2207	     manually.  */
2208	  unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2209				| GCFunction);
2210	  XGCValues xgcv;
2211	  XRectangle clip_rect, image_rect, r;
2212
2213	  xgcv.clip_mask = s->img->mask;
2214	  xgcv.clip_x_origin = x;
2215	  xgcv.clip_y_origin = y;
2216	  xgcv.function = GXcopy;
2217	  XChangeGC (s->display, s->gc, mask, &xgcv);
2218
2219	  get_glyph_string_clip_rect (s, &clip_rect);
2220	  image_rect.x = x;
2221	  image_rect.y = y;
2222	  image_rect.width = s->slice.width;
2223	  image_rect.height = s->slice.height;
2224	  if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2225	    XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2226		       s->slice.x + r.x - x, s->slice.y + r.y - y,
2227		       r.width, r.height, r.x, r.y);
2228	}
2229      else
2230	{
2231	  XRectangle clip_rect, image_rect, r;
2232
2233	  get_glyph_string_clip_rect (s, &clip_rect);
2234	  image_rect.x = x;
2235	  image_rect.y = y;
2236	  image_rect.width = s->slice.width;
2237	  image_rect.height = s->slice.height;
2238	  if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
2239	    XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
2240		       s->slice.x + r.x - x, s->slice.y + r.y - y,
2241		       r.width, r.height, r.x, r.y);
2242
2243	  /* When the image has a mask, we can expect that at
2244	     least part of a mouse highlight or a block cursor will
2245	     be visible.  If the image doesn't have a mask, make
2246	     a block cursor visible by drawing a rectangle around
2247	     the image.  I believe it's looking better if we do
2248	     nothing here for mouse-face.  */
2249	  if (s->hl == DRAW_CURSOR)
2250	    {
2251	      int r = s->img->relief;
2252	      if (r < 0) r = -r;
2253	      XDrawRectangle (s->display, s->window, s->gc,
2254			      x - r, y - r,
2255			      s->slice.width + r*2 - 1,
2256			      s->slice.height + r*2 - 1);
2257	    }
2258	}
2259    }
2260  else
2261    /* Draw a rectangle if image could not be loaded.  */
2262    XDrawRectangle (s->display, s->window, s->gc, x, y,
2263		    s->slice.width - 1, s->slice.height - 1);
2264}
2265
2266
2267/* Draw a relief around the image glyph string S.  */
2268
2269static void
2270x_draw_image_relief (s)
2271     struct glyph_string *s;
2272{
2273  int x0, y0, x1, y1, thick, raised_p;
2274  XRectangle r;
2275  int x = s->x;
2276  int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2277
2278  /* If first glyph of S has a left box line, start drawing it to the
2279     right of that line.  */
2280  if (s->face->box != FACE_NO_BOX
2281      && s->first_glyph->left_box_line_p
2282      && s->slice.x == 0)
2283    x += abs (s->face->box_line_width);
2284
2285  /* If there is a margin around the image, adjust x- and y-position
2286     by that margin.  */
2287  if (s->slice.x == 0)
2288    x += s->img->hmargin;
2289  if (s->slice.y == 0)
2290    y += s->img->vmargin;
2291
2292  if (s->hl == DRAW_IMAGE_SUNKEN
2293      || s->hl == DRAW_IMAGE_RAISED)
2294    {
2295      thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2296      raised_p = s->hl == DRAW_IMAGE_RAISED;
2297    }
2298  else
2299    {
2300      thick = abs (s->img->relief);
2301      raised_p = s->img->relief > 0;
2302    }
2303
2304  x0 = x - thick;
2305  y0 = y - thick;
2306  x1 = x + s->slice.width + thick - 1;
2307  y1 = y + s->slice.height + thick - 1;
2308
2309  x_setup_relief_colors (s);
2310  get_glyph_string_clip_rect (s, &r);
2311  x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
2312		      s->slice.y == 0,
2313		      s->slice.y + s->slice.height == s->img->height,
2314		      s->slice.x == 0,
2315		      s->slice.x + s->slice.width == s->img->width,
2316		      &r);
2317}
2318
2319
2320/* Draw the foreground of image glyph string S to PIXMAP.  */
2321
2322static void
2323x_draw_image_foreground_1 (s, pixmap)
2324     struct glyph_string *s;
2325     Pixmap pixmap;
2326{
2327  int x = 0;
2328  int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2329
2330  /* If first glyph of S has a left box line, start drawing it to the
2331     right of that line.  */
2332  if (s->face->box != FACE_NO_BOX
2333      && s->first_glyph->left_box_line_p
2334      && s->slice.x == 0)
2335    x += abs (s->face->box_line_width);
2336
2337  /* If there is a margin around the image, adjust x- and y-position
2338     by that margin.  */
2339  if (s->slice.x == 0)
2340    x += s->img->hmargin;
2341  if (s->slice.y == 0)
2342    y += s->img->vmargin;
2343
2344  if (s->img->pixmap)
2345    {
2346      if (s->img->mask)
2347	{
2348	  /* We can't set both a clip mask and use XSetClipRectangles
2349	     because the latter also sets a clip mask.  We also can't
2350	     trust on the shape extension to be available
2351	     (XShapeCombineRegion).  So, compute the rectangle to draw
2352	     manually.  */
2353	  unsigned long mask = (GCClipMask | GCClipXOrigin | GCClipYOrigin
2354				| GCFunction);
2355	  XGCValues xgcv;
2356
2357	  xgcv.clip_mask = s->img->mask;
2358	  xgcv.clip_x_origin = x - s->slice.x;
2359	  xgcv.clip_y_origin = y - s->slice.y;
2360	  xgcv.function = GXcopy;
2361	  XChangeGC (s->display, s->gc, mask, &xgcv);
2362
2363	  XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2364		     s->slice.x, s->slice.y,
2365		     s->slice.width, s->slice.height, x, y);
2366	  XSetClipMask (s->display, s->gc, None);
2367	}
2368      else
2369	{
2370	  XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
2371		     s->slice.x, s->slice.y,
2372		     s->slice.width, s->slice.height, x, y);
2373
2374	  /* When the image has a mask, we can expect that at
2375	     least part of a mouse highlight or a block cursor will
2376	     be visible.  If the image doesn't have a mask, make
2377	     a block cursor visible by drawing a rectangle around
2378	     the image.  I believe it's looking better if we do
2379	     nothing here for mouse-face.  */
2380	  if (s->hl == DRAW_CURSOR)
2381	    {
2382	      int r = s->img->relief;
2383	      if (r < 0) r = -r;
2384	      XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
2385			      s->slice.width + r*2 - 1,
2386			      s->slice.height + r*2 - 1);
2387	    }
2388	}
2389    }
2390  else
2391    /* Draw a rectangle if image could not be loaded.  */
2392    XDrawRectangle (s->display, pixmap, s->gc, x, y,
2393		    s->slice.width - 1, s->slice.height - 1);
2394}
2395
2396
2397/* Draw part of the background of glyph string S.  X, Y, W, and H
2398   give the rectangle to draw.  */
2399
2400static void
2401x_draw_glyph_string_bg_rect (s, x, y, w, h)
2402     struct glyph_string *s;
2403     int x, y, w, h;
2404{
2405  if (s->stippled_p)
2406    {
2407      /* Fill background with a stipple pattern.  */
2408      XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2409      XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2410      XSetFillStyle (s->display, s->gc, FillSolid);
2411    }
2412  else
2413    x_clear_glyph_string_rect (s, x, y, w, h);
2414}
2415
2416
2417/* Draw image glyph string S.
2418
2419            s->y
2420   s->x      +-------------------------
2421	     |   s->face->box
2422	     |
2423	     |     +-------------------------
2424	     |     |  s->img->margin
2425	     |     |
2426	     |     |       +-------------------
2427	     |     |       |  the image
2428
2429 */
2430
2431static void
2432x_draw_image_glyph_string (s)
2433     struct glyph_string *s;
2434{
2435  int box_line_hwidth = abs (s->face->box_line_width);
2436  int box_line_vwidth = max (s->face->box_line_width, 0);
2437  int height;
2438  Pixmap pixmap = None;
2439
2440  height = s->height;
2441  if (s->slice.y == 0)
2442    height -= box_line_vwidth;
2443  if (s->slice.y + s->slice.height >= s->img->height)
2444    height -= box_line_vwidth;
2445
2446  /* Fill background with face under the image.  Do it only if row is
2447     taller than image or if image has a clip mask to reduce
2448     flickering.  */
2449  s->stippled_p = s->face->stipple != 0;
2450  if (height > s->slice.height
2451      || s->img->hmargin
2452      || s->img->vmargin
2453      || s->img->mask
2454      || s->img->pixmap == 0
2455      || s->width != s->background_width)
2456    {
2457      if (s->img->mask)
2458	{
2459	  /* Create a pixmap as large as the glyph string.  Fill it
2460	     with the background color.  Copy the image to it, using
2461	     its mask.  Copy the temporary pixmap to the display.  */
2462	  Screen *screen = FRAME_X_SCREEN (s->f);
2463	  int depth = DefaultDepthOfScreen (screen);
2464
2465	  /* Create a pixmap as large as the glyph string.  */
2466 	  pixmap = XCreatePixmap (s->display, s->window,
2467				  s->background_width,
2468				  s->height, depth);
2469
2470	  /* Don't clip in the following because we're working on the
2471	     pixmap.  */
2472	  XSetClipMask (s->display, s->gc, None);
2473
2474	  /* Fill the pixmap with the background color/stipple.  */
2475	  if (s->stippled_p)
2476	    {
2477	      /* Fill background with a stipple pattern.  */
2478	      XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2479	      XFillRectangle (s->display, pixmap, s->gc,
2480			      0, 0, s->background_width, s->height);
2481	      XSetFillStyle (s->display, s->gc, FillSolid);
2482	    }
2483	  else
2484	    {
2485	      XGCValues xgcv;
2486	      XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2487			    &xgcv);
2488	      XSetForeground (s->display, s->gc, xgcv.background);
2489	      XFillRectangle (s->display, pixmap, s->gc,
2490			      0, 0, s->background_width, s->height);
2491	      XSetForeground (s->display, s->gc, xgcv.foreground);
2492	    }
2493	}
2494      else
2495	{
2496	  int x = s->x;
2497	  int y = s->y;
2498
2499	  if (s->first_glyph->left_box_line_p
2500	      && s->slice.x == 0)
2501	    x += box_line_hwidth;
2502
2503	  if (s->slice.y == 0)
2504	    y += box_line_vwidth;
2505
2506	  x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
2507	}
2508
2509      s->background_filled_p = 1;
2510    }
2511
2512  /* Draw the foreground.  */
2513  if (pixmap != None)
2514    {
2515      x_draw_image_foreground_1 (s, pixmap);
2516      x_set_glyph_string_clipping (s);
2517      XCopyArea (s->display, pixmap, s->window, s->gc,
2518		 0, 0, s->background_width, s->height, s->x, s->y);
2519      XFreePixmap (s->display, pixmap);
2520    }
2521  else
2522    x_draw_image_foreground (s);
2523
2524  /* If we must draw a relief around the image, do it.  */
2525  if (s->img->relief
2526      || s->hl == DRAW_IMAGE_RAISED
2527      || s->hl == DRAW_IMAGE_SUNKEN)
2528    x_draw_image_relief (s);
2529}
2530
2531
2532/* Draw stretch glyph string S.  */
2533
2534static void
2535x_draw_stretch_glyph_string (s)
2536     struct glyph_string *s;
2537{
2538  xassert (s->first_glyph->type == STRETCH_GLYPH);
2539  s->stippled_p = s->face->stipple != 0;
2540
2541  if (s->hl == DRAW_CURSOR
2542      && !x_stretch_cursor_p)
2543    {
2544      /* If `x-stretch-block-cursor' is nil, don't draw a block cursor
2545	 as wide as the stretch glyph.  */
2546      int width, background_width = s->background_width;
2547      int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
2548
2549      if (x < left_x)
2550	{
2551	  background_width -= left_x - x;
2552	  x = left_x;
2553	}
2554      width = min (FRAME_COLUMN_WIDTH (s->f), background_width);
2555
2556      /* Draw cursor.  */
2557      x_draw_glyph_string_bg_rect (s, x, s->y, width, s->height);
2558
2559      /* Clear rest using the GC of the original non-cursor face.  */
2560      if (width < background_width)
2561	{
2562	  int y = s->y;
2563	  int w = background_width - width, h = s->height;
2564	  XRectangle r;
2565	  GC gc;
2566
2567	  x += width;
2568	  if (s->row->mouse_face_p
2569	      && cursor_in_mouse_face_p (s->w))
2570	    {
2571	      x_set_mouse_face_gc (s);
2572	      gc = s->gc;
2573	    }
2574	  else
2575	    gc = s->face->gc;
2576
2577	  get_glyph_string_clip_rect (s, &r);
2578	  XSetClipRectangles (s->display, gc, 0, 0, &r, 1, Unsorted);
2579
2580	  if (s->face->stipple)
2581	    {
2582	      /* Fill background with a stipple pattern.  */
2583	      XSetFillStyle (s->display, gc, FillOpaqueStippled);
2584	      XFillRectangle (s->display, s->window, gc, x, y, w, h);
2585	      XSetFillStyle (s->display, gc, FillSolid);
2586	    }
2587	  else
2588	    {
2589	      XGCValues xgcv;
2590	      XGetGCValues (s->display, gc, GCForeground | GCBackground, &xgcv);
2591	      XSetForeground (s->display, gc, xgcv.background);
2592	      XFillRectangle (s->display, s->window, gc, x, y, w, h);
2593	      XSetForeground (s->display, gc, xgcv.foreground);
2594	    }
2595	}
2596    }
2597  else if (!s->background_filled_p)
2598    {
2599      int background_width = s->background_width;
2600      int x = s->x, left_x = window_box_left_offset (s->w, TEXT_AREA);
2601
2602      /* Don't draw into left margin, fringe or scrollbar area
2603         except for header line and mode line.  */
2604      if (x < left_x && !s->row->mode_line_p)
2605	{
2606	  background_width -= left_x - x;
2607	  x = left_x;
2608	}
2609      if (background_width > 0)
2610	x_draw_glyph_string_bg_rect (s, x, s->y, background_width, s->height);
2611    }
2612
2613  s->background_filled_p = 1;
2614}
2615
2616
2617/* Draw glyph string S.  */
2618
2619static void
2620x_draw_glyph_string (s)
2621     struct glyph_string *s;
2622{
2623  int relief_drawn_p = 0;
2624
2625  /* If S draws into the background of its successor, draw the
2626     background of the successor first so that S can draw into it.
2627     This makes S->next use XDrawString instead of XDrawImageString.  */
2628  if (s->next && s->right_overhang && !s->for_overlaps)
2629    {
2630      xassert (s->next->img == NULL);
2631      x_set_glyph_string_gc (s->next);
2632      x_set_glyph_string_clipping (s->next);
2633      x_draw_glyph_string_background (s->next, 1);
2634    }
2635
2636  /* Set up S->gc, set clipping and draw S.  */
2637  x_set_glyph_string_gc (s);
2638
2639  /* Draw relief (if any) in advance for char/composition so that the
2640     glyph string can be drawn over it.  */
2641  if (!s->for_overlaps
2642      && s->face->box != FACE_NO_BOX
2643      && (s->first_glyph->type == CHAR_GLYPH
2644	  || s->first_glyph->type == COMPOSITE_GLYPH))
2645
2646    {
2647      x_set_glyph_string_clipping (s);
2648      x_draw_glyph_string_background (s, 1);
2649      x_draw_glyph_string_box (s);
2650      x_set_glyph_string_clipping (s);
2651      relief_drawn_p = 1;
2652    }
2653  else
2654    x_set_glyph_string_clipping (s);
2655
2656  switch (s->first_glyph->type)
2657    {
2658    case IMAGE_GLYPH:
2659      x_draw_image_glyph_string (s);
2660      break;
2661
2662    case STRETCH_GLYPH:
2663      x_draw_stretch_glyph_string (s);
2664      break;
2665
2666    case CHAR_GLYPH:
2667      if (s->for_overlaps)
2668	s->background_filled_p = 1;
2669      else
2670	x_draw_glyph_string_background (s, 0);
2671      x_draw_glyph_string_foreground (s);
2672      break;
2673
2674    case COMPOSITE_GLYPH:
2675      if (s->for_overlaps || s->gidx > 0)
2676	s->background_filled_p = 1;
2677      else
2678	x_draw_glyph_string_background (s, 1);
2679      x_draw_composite_glyph_string_foreground (s);
2680      break;
2681
2682    default:
2683      abort ();
2684    }
2685
2686  if (!s->for_overlaps)
2687    {
2688      /* Draw underline.  */
2689      if (s->face->underline_p)
2690	{
2691	  unsigned long tem, h;
2692	  int y;
2693
2694	  /* Get the underline thickness.  Default is 1 pixel.  */
2695	  if (!XGetFontProperty (s->font, XA_UNDERLINE_THICKNESS, &h))
2696	    h = 1;
2697
2698	  y = s->y + s->height - h;
2699	  if (!x_underline_at_descent_line)
2700            {
2701	      /* Get the underline position.  This is the recommended
2702                 vertical offset in pixels from the baseline to the top of
2703                 the underline.  This is a signed value according to the
2704                 specs, and its default is
2705
2706	         ROUND ((maximum descent) / 2), with
2707	         ROUND(x) = floor (x + 0.5)  */
2708
2709              if (x_use_underline_position_properties
2710                  && XGetFontProperty (s->font, XA_UNDERLINE_POSITION, &tem))
2711                y = s->ybase + (long) tem;
2712              else if (s->face->font)
2713                y = s->ybase + (s->face->font->max_bounds.descent + 1) / 2;
2714            }
2715
2716	  if (s->face->underline_defaulted_p)
2717	    XFillRectangle (s->display, s->window, s->gc,
2718			    s->x, y, s->background_width, h);
2719	  else
2720	    {
2721	      XGCValues xgcv;
2722	      XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2723	      XSetForeground (s->display, s->gc, s->face->underline_color);
2724	      XFillRectangle (s->display, s->window, s->gc,
2725			      s->x, y, s->background_width, h);
2726	      XSetForeground (s->display, s->gc, xgcv.foreground);
2727	    }
2728	}
2729
2730      /* Draw overline.  */
2731      if (s->face->overline_p)
2732	{
2733	  unsigned long dy = 0, h = 1;
2734
2735	  if (s->face->overline_color_defaulted_p)
2736	    XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2737			    s->background_width, h);
2738	  else
2739	    {
2740	      XGCValues xgcv;
2741	      XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2742	      XSetForeground (s->display, s->gc, s->face->overline_color);
2743	      XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2744			      s->background_width, h);
2745	      XSetForeground (s->display, s->gc, xgcv.foreground);
2746	    }
2747	}
2748
2749      /* Draw strike-through.  */
2750      if (s->face->strike_through_p)
2751	{
2752	  unsigned long h = 1;
2753	  unsigned long dy = (s->height - h) / 2;
2754
2755	  if (s->face->strike_through_color_defaulted_p)
2756	    XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2757			    s->width, h);
2758	  else
2759	    {
2760	      XGCValues xgcv;
2761	      XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2762	      XSetForeground (s->display, s->gc, s->face->strike_through_color);
2763	      XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
2764			      s->width, h);
2765	      XSetForeground (s->display, s->gc, xgcv.foreground);
2766	    }
2767	}
2768
2769      /* Draw relief if not yet drawn.  */
2770      if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
2771	x_draw_glyph_string_box (s);
2772    }
2773
2774  /* Reset clipping.  */
2775  XSetClipMask (s->display, s->gc, None);
2776}
2777
2778/* Shift display to make room for inserted glyphs.   */
2779
2780void
2781x_shift_glyphs_for_insert (f, x, y, width, height, shift_by)
2782     struct frame *f;
2783     int x, y, width, height, shift_by;
2784{
2785  XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
2786	     f->output_data.x->normal_gc,
2787	     x, y, width, height,
2788	     x + shift_by, y);
2789}
2790
2791/* Delete N glyphs at the nominal cursor position.  Not implemented
2792   for X frames.  */
2793
2794static void
2795x_delete_glyphs (n)
2796     register int n;
2797{
2798  abort ();
2799}
2800
2801
2802/* Like XClearArea, but check that WIDTH and HEIGHT are reasonable.
2803   If they are <= 0, this is probably an error.  */
2804
2805void
2806x_clear_area (dpy, window, x, y, width, height, exposures)
2807     Display *dpy;
2808     Window window;
2809     int x, y;
2810     int width, height;
2811     int exposures;
2812{
2813  xassert (width > 0 && height > 0);
2814  XClearArea (dpy, window, x, y, width, height, exposures);
2815}
2816
2817
2818/* Clear entire frame.  If updating_frame is non-null, clear that
2819   frame.  Otherwise clear the selected frame.  */
2820
2821static void
2822x_clear_frame ()
2823{
2824  struct frame *f;
2825
2826  if (updating_frame)
2827    f = updating_frame;
2828  else
2829    f = SELECTED_FRAME ();
2830
2831  /* Clearing the frame will erase any cursor, so mark them all as no
2832     longer visible.  */
2833  mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2834  output_cursor.hpos = output_cursor.vpos = 0;
2835  output_cursor.x = -1;
2836
2837  /* We don't set the output cursor here because there will always
2838     follow an explicit cursor_to.  */
2839  BLOCK_INPUT;
2840  XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
2841
2842  /* We have to clear the scroll bars, too.  If we have changed
2843     colors or something like that, then they should be notified.  */
2844  x_scroll_bar_clear (f);
2845
2846  XFlush (FRAME_X_DISPLAY (f));
2847
2848  UNBLOCK_INPUT;
2849}
2850
2851
2852
2853/* Invert the middle quarter of the frame for .15 sec.  */
2854
2855/* We use the select system call to do the waiting, so we have to make
2856   sure it's available.  If it isn't, we just won't do visual bells.  */
2857
2858#if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
2859
2860
2861/* Subtract the `struct timeval' values X and Y, storing the result in
2862   *RESULT.  Return 1 if the difference is negative, otherwise 0.  */
2863
2864static int
2865timeval_subtract (result, x, y)
2866     struct timeval *result, x, y;
2867{
2868  /* Perform the carry for the later subtraction by updating y.  This
2869     is safer because on some systems the tv_sec member is unsigned.  */
2870  if (x.tv_usec < y.tv_usec)
2871    {
2872      int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
2873      y.tv_usec -= 1000000 * nsec;
2874      y.tv_sec += nsec;
2875    }
2876
2877  if (x.tv_usec - y.tv_usec > 1000000)
2878    {
2879      int nsec = (y.tv_usec - x.tv_usec) / 1000000;
2880      y.tv_usec += 1000000 * nsec;
2881      y.tv_sec -= nsec;
2882    }
2883
2884  /* Compute the time remaining to wait.  tv_usec is certainly
2885     positive.  */
2886  result->tv_sec = x.tv_sec - y.tv_sec;
2887  result->tv_usec = x.tv_usec - y.tv_usec;
2888
2889  /* Return indication of whether the result should be considered
2890     negative.  */
2891  return x.tv_sec < y.tv_sec;
2892}
2893
2894void
2895XTflash (f)
2896     struct frame *f;
2897{
2898  BLOCK_INPUT;
2899
2900  {
2901    GC gc;
2902
2903    /* Create a GC that will use the GXxor function to flip foreground
2904       pixels into background pixels.  */
2905    {
2906      XGCValues values;
2907
2908      values.function = GXxor;
2909      values.foreground = (f->output_data.x->foreground_pixel
2910			   ^ f->output_data.x->background_pixel);
2911
2912      gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
2913		      GCFunction | GCForeground, &values);
2914    }
2915
2916    {
2917      /* Get the height not including a menu bar widget.  */
2918      int height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, FRAME_LINES (f));
2919      /* Height of each line to flash.  */
2920      int flash_height = FRAME_LINE_HEIGHT (f);
2921      /* These will be the left and right margins of the rectangles.  */
2922      int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
2923      int flash_right = FRAME_PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
2924
2925      int width;
2926
2927      /* Don't flash the area between a scroll bar and the frame
2928	 edge it is next to.  */
2929      switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
2930	{
2931	case vertical_scroll_bar_left:
2932	  flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
2933	  break;
2934
2935	case vertical_scroll_bar_right:
2936	  flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
2937	  break;
2938
2939	default:
2940	  break;
2941	}
2942
2943      width = flash_right - flash_left;
2944
2945      /* If window is tall, flash top and bottom line.  */
2946      if (height > 3 * FRAME_LINE_HEIGHT (f))
2947	{
2948	  XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
2949			  flash_left,
2950			  (FRAME_INTERNAL_BORDER_WIDTH (f)
2951			   + FRAME_TOOL_BAR_LINES (f) * FRAME_LINE_HEIGHT (f)),
2952			  width, flash_height);
2953	  XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
2954			  flash_left,
2955			  (height - flash_height
2956			   - FRAME_INTERNAL_BORDER_WIDTH (f)),
2957			  width, flash_height);
2958	}
2959      else
2960	/* If it is short, flash it all.  */
2961	XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
2962			flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
2963			width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
2964
2965      x_flush (f);
2966
2967      {
2968	struct timeval wakeup;
2969
2970	EMACS_GET_TIME (wakeup);
2971
2972	/* Compute time to wait until, propagating carry from usecs.  */
2973	wakeup.tv_usec += 150000;
2974	wakeup.tv_sec += (wakeup.tv_usec / 1000000);
2975	wakeup.tv_usec %= 1000000;
2976
2977	/* Keep waiting until past the time wakeup or any input gets
2978	   available.  */
2979	while (! detect_input_pending ())
2980	  {
2981	    struct timeval current;
2982	    struct timeval timeout;
2983
2984	    EMACS_GET_TIME (current);
2985
2986	    /* Break if result would be negative.  */
2987	    if (timeval_subtract (&current, wakeup, current))
2988	      break;
2989
2990	    /* How long `select' should wait.  */
2991	    timeout.tv_sec = 0;
2992	    timeout.tv_usec = 10000;
2993
2994	    /* Try to wait that long--but we might wake up sooner.  */
2995	    select (0, NULL, NULL, NULL, &timeout);
2996	  }
2997      }
2998
2999      /* If window is tall, flash top and bottom line.  */
3000      if (height > 3 * FRAME_LINE_HEIGHT (f))
3001	{
3002	  XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3003			  flash_left,
3004			  (FRAME_INTERNAL_BORDER_WIDTH (f)
3005			   + FRAME_TOOL_BAR_LINES (f) * FRAME_LINE_HEIGHT (f)),
3006			  width, flash_height);
3007	  XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3008			  flash_left,
3009			  (height - flash_height
3010			   - FRAME_INTERNAL_BORDER_WIDTH (f)),
3011			  width, flash_height);
3012	}
3013      else
3014	/* If it is short, flash it all.  */
3015	XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
3016			flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
3017			width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
3018
3019      XFreeGC (FRAME_X_DISPLAY (f), gc);
3020      x_flush (f);
3021    }
3022  }
3023
3024  UNBLOCK_INPUT;
3025}
3026
3027#endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3028
3029
3030/* Make audible bell.  */
3031
3032void
3033XTring_bell ()
3034{
3035  struct frame *f = SELECTED_FRAME ();
3036
3037  if (FRAME_X_DISPLAY (f))
3038    {
3039#if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3040      if (visible_bell)
3041	XTflash (f);
3042      else
3043#endif
3044	{
3045	  BLOCK_INPUT;
3046	  XBell (FRAME_X_DISPLAY (f), 0);
3047	  XFlush (FRAME_X_DISPLAY (f));
3048	  UNBLOCK_INPUT;
3049	}
3050    }
3051}
3052
3053
3054/* Specify how many text lines, from the top of the window,
3055   should be affected by insert-lines and delete-lines operations.
3056   This, and those operations, are used only within an update
3057   that is bounded by calls to x_update_begin and x_update_end.  */
3058
3059static void
3060XTset_terminal_window (n)
3061     register int n;
3062{
3063  /* This function intentionally left blank.  */
3064}
3065
3066
3067
3068/***********************************************************************
3069			      Line Dance
3070 ***********************************************************************/
3071
3072/* Perform an insert-lines or delete-lines operation, inserting N
3073   lines or deleting -N lines at vertical position VPOS.  */
3074
3075static void
3076x_ins_del_lines (vpos, n)
3077     int vpos, n;
3078{
3079  abort ();
3080}
3081
3082
3083/* Scroll part of the display as described by RUN.  */
3084
3085static void
3086x_scroll_run (w, run)
3087     struct window *w;
3088     struct run *run;
3089{
3090  struct frame *f = XFRAME (w->frame);
3091  int x, y, width, height, from_y, to_y, bottom_y;
3092
3093  /* Get frame-relative bounding box of the text display area of W,
3094     without mode lines.  Include in this box the left and right
3095     fringe of W.  */
3096  window_box (w, -1, &x, &y, &width, &height);
3097
3098  from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3099  to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3100  bottom_y = y + height;
3101
3102  if (to_y < from_y)
3103    {
3104      /* Scrolling up.  Make sure we don't copy part of the mode
3105	 line at the bottom.  */
3106      if (from_y + run->height > bottom_y)
3107	height = bottom_y - from_y;
3108      else
3109	height = run->height;
3110    }
3111  else
3112    {
3113      /* Scolling down.  Make sure we don't copy over the mode line.
3114	 at the bottom.  */
3115      if (to_y + run->height > bottom_y)
3116	height = bottom_y - to_y;
3117      else
3118	height = run->height;
3119    }
3120
3121  BLOCK_INPUT;
3122
3123  /* Cursor off.  Will be switched on again in x_update_window_end.  */
3124  updated_window = w;
3125  x_clear_cursor (w);
3126
3127  XCopyArea (FRAME_X_DISPLAY (f),
3128	     FRAME_X_WINDOW (f), FRAME_X_WINDOW (f),
3129	     f->output_data.x->normal_gc,
3130	     x, from_y,
3131	     width, height,
3132	     x, to_y);
3133
3134  UNBLOCK_INPUT;
3135}
3136
3137
3138
3139/***********************************************************************
3140			   Exposure Events
3141 ***********************************************************************/
3142
3143
3144static void
3145frame_highlight (f)
3146     struct frame *f;
3147{
3148  /* We used to only do this if Vx_no_window_manager was non-nil, but
3149     the ICCCM (section 4.1.6) says that the window's border pixmap
3150     and border pixel are window attributes which are "private to the
3151     client", so we can always change it to whatever we want.  */
3152  BLOCK_INPUT;
3153  XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3154		    f->output_data.x->border_pixel);
3155  UNBLOCK_INPUT;
3156  x_update_cursor (f, 1);
3157}
3158
3159static void
3160frame_unhighlight (f)
3161     struct frame *f;
3162{
3163  /* We used to only do this if Vx_no_window_manager was non-nil, but
3164     the ICCCM (section 4.1.6) says that the window's border pixmap
3165     and border pixel are window attributes which are "private to the
3166     client", so we can always change it to whatever we want.  */
3167  BLOCK_INPUT;
3168  XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
3169			  f->output_data.x->border_tile);
3170  UNBLOCK_INPUT;
3171  x_update_cursor (f, 1);
3172}
3173
3174/* The focus has changed.  Update the frames as necessary to reflect
3175   the new situation.  Note that we can't change the selected frame
3176   here, because the Lisp code we are interrupting might become confused.
3177   Each event gets marked with the frame in which it occurred, so the
3178   Lisp code can tell when the switch took place by examining the events.  */
3179
3180static void
3181x_new_focus_frame (dpyinfo, frame)
3182     struct x_display_info *dpyinfo;
3183     struct frame *frame;
3184{
3185  struct frame *old_focus = dpyinfo->x_focus_frame;
3186
3187  if (frame != dpyinfo->x_focus_frame)
3188    {
3189      /* Set this before calling other routines, so that they see
3190	 the correct value of x_focus_frame.  */
3191      dpyinfo->x_focus_frame = frame;
3192
3193      if (old_focus && old_focus->auto_lower)
3194	x_lower_frame (old_focus);
3195
3196#if 0
3197      selected_frame = frame;
3198      XSETFRAME (XWINDOW (selected_frame->selected_window)->frame,
3199		 selected_frame);
3200      Fselect_window (selected_frame->selected_window, Qnil);
3201      choose_minibuf_frame ();
3202#endif /* ! 0 */
3203
3204      if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3205	pending_autoraise_frame = dpyinfo->x_focus_frame;
3206      else
3207	pending_autoraise_frame = 0;
3208    }
3209
3210  x_frame_rehighlight (dpyinfo);
3211}
3212
3213/* Handle FocusIn and FocusOut state changes for FRAME.
3214   If FRAME has focus and there exists more than one frame, puts
3215   a FOCUS_IN_EVENT into *BUFP.  */
3216
3217static void
3218x_focus_changed (type, state, dpyinfo, frame, bufp)
3219     int type;
3220     int state;
3221     struct x_display_info *dpyinfo;
3222     struct frame *frame;
3223     struct input_event *bufp;
3224{
3225  if (type == FocusIn)
3226    {
3227      if (dpyinfo->x_focus_event_frame != frame)
3228        {
3229          x_new_focus_frame (dpyinfo, frame);
3230          dpyinfo->x_focus_event_frame = frame;
3231
3232          /* Don't stop displaying the initial startup message
3233             for a switch-frame event we don't need.  */
3234          if (GC_NILP (Vterminal_frame)
3235              && GC_CONSP (Vframe_list)
3236              && !GC_NILP (XCDR (Vframe_list)))
3237            {
3238              bufp->kind = FOCUS_IN_EVENT;
3239              XSETFRAME (bufp->frame_or_window, frame);
3240            }
3241        }
3242
3243      frame->output_data.x->focus_state |= state;
3244
3245#ifdef HAVE_X_I18N
3246      if (FRAME_XIC (frame))
3247        XSetICFocus (FRAME_XIC (frame));
3248#endif
3249    }
3250  else if (type == FocusOut)
3251    {
3252      frame->output_data.x->focus_state &= ~state;
3253
3254      if (dpyinfo->x_focus_event_frame == frame)
3255        {
3256          dpyinfo->x_focus_event_frame = 0;
3257          x_new_focus_frame (dpyinfo, 0);
3258        }
3259
3260#ifdef HAVE_X_I18N
3261      if (FRAME_XIC (frame))
3262        XUnsetICFocus (FRAME_XIC (frame));
3263#endif
3264    }
3265}
3266
3267/* The focus may have changed.  Figure out if it is a real focus change,
3268   by checking both FocusIn/Out and Enter/LeaveNotify events.
3269
3270   Returns FOCUS_IN_EVENT event in *BUFP. */
3271
3272static void
3273x_detect_focus_change (dpyinfo, event, bufp)
3274     struct x_display_info *dpyinfo;
3275     XEvent *event;
3276     struct input_event *bufp;
3277{
3278  struct frame *frame;
3279
3280  frame = x_any_window_to_frame (dpyinfo, event->xany.window);
3281  if (! frame)
3282    return;
3283
3284  switch (event->type)
3285    {
3286    case EnterNotify:
3287    case LeaveNotify:
3288      {
3289        struct frame *focus_frame = dpyinfo->x_focus_event_frame;
3290        int focus_state
3291          = focus_frame ? focus_frame->output_data.x->focus_state : 0;
3292
3293        if (event->xcrossing.detail != NotifyInferior
3294            && event->xcrossing.focus
3295            && ! (focus_state & FOCUS_EXPLICIT))
3296          x_focus_changed ((event->type == EnterNotify ? FocusIn : FocusOut),
3297			   FOCUS_IMPLICIT,
3298			   dpyinfo, frame, bufp);
3299      }
3300      break;
3301
3302    case FocusIn:
3303    case FocusOut:
3304      x_focus_changed (event->type,
3305		       (event->xfocus.detail == NotifyPointer ?
3306			FOCUS_IMPLICIT : FOCUS_EXPLICIT),
3307		       dpyinfo, frame, bufp);
3308      break;
3309    }
3310}
3311
3312
3313/* Handle an event saying the mouse has moved out of an Emacs frame.  */
3314
3315void
3316x_mouse_leave (dpyinfo)
3317     struct x_display_info *dpyinfo;
3318{
3319  x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3320}
3321
3322/* The focus has changed, or we have redirected a frame's focus to
3323   another frame (this happens when a frame uses a surrogate
3324   mini-buffer frame).  Shift the highlight as appropriate.
3325
3326   The FRAME argument doesn't necessarily have anything to do with which
3327   frame is being highlighted or un-highlighted; we only use it to find
3328   the appropriate X display info.  */
3329
3330static void
3331XTframe_rehighlight (frame)
3332     struct frame *frame;
3333{
3334  x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
3335}
3336
3337static void
3338x_frame_rehighlight (dpyinfo)
3339     struct x_display_info *dpyinfo;
3340{
3341  struct frame *old_highlight = dpyinfo->x_highlight_frame;
3342
3343  if (dpyinfo->x_focus_frame)
3344    {
3345      dpyinfo->x_highlight_frame
3346	= ((GC_FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3347	   ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3348	   : dpyinfo->x_focus_frame);
3349      if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3350	{
3351	  FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
3352	  dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3353	}
3354    }
3355  else
3356    dpyinfo->x_highlight_frame = 0;
3357
3358  if (dpyinfo->x_highlight_frame != old_highlight)
3359    {
3360      if (old_highlight)
3361	frame_unhighlight (old_highlight);
3362      if (dpyinfo->x_highlight_frame)
3363	frame_highlight (dpyinfo->x_highlight_frame);
3364    }
3365}
3366
3367
3368
3369/* Keyboard processing - modifier keys, vendor-specific keysyms, etc.  */
3370
3371/* Initialize mode_switch_bit and modifier_meaning.  */
3372static void
3373x_find_modifier_meanings (dpyinfo)
3374     struct x_display_info *dpyinfo;
3375{
3376  int min_code, max_code;
3377  KeySym *syms;
3378  int syms_per_code;
3379  XModifierKeymap *mods;
3380
3381  dpyinfo->meta_mod_mask = 0;
3382  dpyinfo->shift_lock_mask = 0;
3383  dpyinfo->alt_mod_mask = 0;
3384  dpyinfo->super_mod_mask = 0;
3385  dpyinfo->hyper_mod_mask = 0;
3386
3387#ifdef HAVE_X11R4
3388  XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3389#else
3390  min_code = dpyinfo->display->min_keycode;
3391  max_code = dpyinfo->display->max_keycode;
3392#endif
3393
3394  syms = XGetKeyboardMapping (dpyinfo->display,
3395			      min_code, max_code - min_code + 1,
3396			      &syms_per_code);
3397  mods = XGetModifierMapping (dpyinfo->display);
3398
3399  /* Scan the modifier table to see which modifier bits the Meta and
3400     Alt keysyms are on.  */
3401  {
3402    int row, col;	/* The row and column in the modifier table.  */
3403    int found_alt_or_meta;
3404
3405    for (row = 3; row < 8; row++)
3406    {
3407      found_alt_or_meta = 0;
3408      for (col = 0; col < mods->max_keypermod; col++)
3409	{
3410	  KeyCode code = mods->modifiermap[(row * mods->max_keypermod) + col];
3411
3412	  /* Zeroes are used for filler.  Skip them.  */
3413	  if (code == 0)
3414	    continue;
3415
3416	  /* Are any of this keycode's keysyms a meta key?  */
3417	  {
3418	    int code_col;
3419
3420	    for (code_col = 0; code_col < syms_per_code; code_col++)
3421	      {
3422		int sym = syms[((code - min_code) * syms_per_code) + code_col];
3423
3424		switch (sym)
3425		  {
3426		  case XK_Meta_L:
3427		  case XK_Meta_R:
3428		    found_alt_or_meta = 1;
3429		    dpyinfo->meta_mod_mask |= (1 << row);
3430		    break;
3431
3432		  case XK_Alt_L:
3433		  case XK_Alt_R:
3434		    found_alt_or_meta = 1;
3435		    dpyinfo->alt_mod_mask |= (1 << row);
3436		    break;
3437
3438		  case XK_Hyper_L:
3439		  case XK_Hyper_R:
3440		    if (!found_alt_or_meta)
3441		      dpyinfo->hyper_mod_mask |= (1 << row);
3442		    code_col = syms_per_code;
3443		    col = mods->max_keypermod;
3444		    break;
3445
3446		  case XK_Super_L:
3447		  case XK_Super_R:
3448		    if (!found_alt_or_meta)
3449		      dpyinfo->super_mod_mask |= (1 << row);
3450		    code_col = syms_per_code;
3451		    col = mods->max_keypermod;
3452		    break;
3453
3454		  case XK_Shift_Lock:
3455		    /* Ignore this if it's not on the lock modifier.  */
3456		    if (!found_alt_or_meta && ((1 << row) == LockMask))
3457		      dpyinfo->shift_lock_mask = LockMask;
3458		    code_col = syms_per_code;
3459		    col = mods->max_keypermod;
3460		    break;
3461		  }
3462	      }
3463	  }
3464	}
3465    }
3466  }
3467
3468  /* If we couldn't find any meta keys, accept any alt keys as meta keys.  */
3469  if (! dpyinfo->meta_mod_mask)
3470    {
3471      dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3472      dpyinfo->alt_mod_mask = 0;
3473    }
3474
3475  /* If some keys are both alt and meta,
3476     make them just meta, not alt.  */
3477  if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3478    {
3479      dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3480    }
3481
3482  XFree ((char *) syms);
3483  XFreeModifiermap (mods);
3484}
3485
3486/* Convert between the modifier bits X uses and the modifier bits
3487   Emacs uses.  */
3488
3489unsigned int
3490x_x_to_emacs_modifiers (dpyinfo, state)
3491     struct x_display_info *dpyinfo;
3492     unsigned int state;
3493{
3494  EMACS_UINT mod_meta = meta_modifier;
3495  EMACS_UINT mod_alt  = alt_modifier;
3496  EMACS_UINT mod_hyper = hyper_modifier;
3497  EMACS_UINT mod_super = super_modifier;
3498  Lisp_Object tem;
3499
3500  tem = Fget (Vx_alt_keysym, Qmodifier_value);
3501  if (! EQ (tem, Qnil)) mod_alt = XUINT (tem);
3502  tem = Fget (Vx_meta_keysym, Qmodifier_value);
3503  if (! EQ (tem, Qnil)) mod_meta = XUINT (tem);
3504  tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3505  if (! EQ (tem, Qnil)) mod_hyper = XUINT (tem);
3506  tem = Fget (Vx_super_keysym, Qmodifier_value);
3507  if (! EQ (tem, Qnil)) mod_super = XUINT (tem);
3508
3509
3510  return (  ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
3511            | ((state & ControlMask)			? ctrl_modifier	: 0)
3512            | ((state & dpyinfo->meta_mod_mask)		? mod_meta	: 0)
3513            | ((state & dpyinfo->alt_mod_mask)		? mod_alt	: 0)
3514            | ((state & dpyinfo->super_mod_mask)	? mod_super	: 0)
3515            | ((state & dpyinfo->hyper_mod_mask)	? mod_hyper	: 0));
3516}
3517
3518static unsigned int
3519x_emacs_to_x_modifiers (dpyinfo, state)
3520     struct x_display_info *dpyinfo;
3521     unsigned int state;
3522{
3523  EMACS_UINT mod_meta = meta_modifier;
3524  EMACS_UINT mod_alt  = alt_modifier;
3525  EMACS_UINT mod_hyper = hyper_modifier;
3526  EMACS_UINT mod_super = super_modifier;
3527
3528  Lisp_Object tem;
3529
3530  tem = Fget (Vx_alt_keysym, Qmodifier_value);
3531  if (! EQ (tem, Qnil)) mod_alt = XUINT (tem);
3532  tem = Fget (Vx_meta_keysym, Qmodifier_value);
3533  if (! EQ (tem, Qnil)) mod_meta = XUINT (tem);
3534  tem = Fget (Vx_hyper_keysym, Qmodifier_value);
3535  if (! EQ (tem, Qnil)) mod_hyper = XUINT (tem);
3536  tem = Fget (Vx_super_keysym, Qmodifier_value);
3537  if (! EQ (tem, Qnil)) mod_super = XUINT (tem);
3538
3539
3540  return (  ((state & mod_alt)		? dpyinfo->alt_mod_mask   : 0)
3541            | ((state & mod_super)	? dpyinfo->super_mod_mask : 0)
3542            | ((state & mod_hyper)	? dpyinfo->hyper_mod_mask : 0)
3543            | ((state & shift_modifier)	? ShiftMask        : 0)
3544            | ((state & ctrl_modifier)	? ControlMask      : 0)
3545            | ((state & mod_meta)	? dpyinfo->meta_mod_mask  : 0));
3546}
3547
3548/* Convert a keysym to its name.  */
3549
3550char *
3551x_get_keysym_name (keysym)
3552     KeySym keysym;
3553{
3554  char *value;
3555
3556  BLOCK_INPUT;
3557  value = XKeysymToString (keysym);
3558  UNBLOCK_INPUT;
3559
3560  return value;
3561}
3562
3563
3564
3565/* Mouse clicks and mouse movement.  Rah.  */
3566
3567/* Prepare a mouse-event in *RESULT for placement in the input queue.
3568
3569   If the event is a button press, then note that we have grabbed
3570   the mouse.  */
3571
3572static Lisp_Object
3573construct_mouse_click (result, event, f)
3574     struct input_event *result;
3575     XButtonEvent *event;
3576     struct frame *f;
3577{
3578  /* Make the event type NO_EVENT; we'll change that when we decide
3579     otherwise.  */
3580  result->kind = MOUSE_CLICK_EVENT;
3581  result->code = event->button - Button1;
3582  result->timestamp = event->time;
3583  result->modifiers = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
3584					       event->state)
3585		       | (event->type == ButtonRelease
3586			  ? up_modifier
3587			  : down_modifier));
3588
3589  XSETINT (result->x, event->x);
3590  XSETINT (result->y, event->y);
3591  XSETFRAME (result->frame_or_window, f);
3592  result->arg = Qnil;
3593  return Qnil;
3594}
3595
3596
3597/* Function to report a mouse movement to the mainstream Emacs code.
3598   The input handler calls this.
3599
3600   We have received a mouse movement event, which is given in *event.
3601   If the mouse is over a different glyph than it was last time, tell
3602   the mainstream emacs code by setting mouse_moved.  If not, ask for
3603   another motion event, so we can check again the next time it moves.  */
3604
3605static XMotionEvent last_mouse_motion_event;
3606static Lisp_Object last_mouse_motion_frame;
3607
3608static int
3609note_mouse_movement (frame, event)
3610     FRAME_PTR frame;
3611     XMotionEvent *event;
3612{
3613  last_mouse_movement_time = event->time;
3614  last_mouse_motion_event = *event;
3615  XSETFRAME (last_mouse_motion_frame, frame);
3616
3617  if (!FRAME_X_OUTPUT (frame))
3618    return 0;
3619
3620  if (event->window != FRAME_X_WINDOW (frame))
3621    {
3622      frame->mouse_moved = 1;
3623      last_mouse_scroll_bar = Qnil;
3624      note_mouse_highlight (frame, -1, -1);
3625      last_mouse_glyph_frame = 0;
3626      return 1;
3627    }
3628
3629
3630  /* Has the mouse moved off the glyph it was on at the last sighting?  */
3631  if (frame != last_mouse_glyph_frame
3632      || event->x < last_mouse_glyph.x
3633      || event->x >= last_mouse_glyph.x + last_mouse_glyph.width
3634      || event->y < last_mouse_glyph.y
3635      || event->y >= last_mouse_glyph.y + last_mouse_glyph.height)
3636    {
3637      frame->mouse_moved = 1;
3638      last_mouse_scroll_bar = Qnil;
3639      note_mouse_highlight (frame, event->x, event->y);
3640      /* Remember which glyph we're now on.  */
3641      remember_mouse_glyph (frame, event->x, event->y, &last_mouse_glyph);
3642      last_mouse_glyph_frame = frame;
3643      return 1;
3644    }
3645
3646  return 0;
3647}
3648
3649
3650/************************************************************************
3651			      Mouse Face
3652 ************************************************************************/
3653
3654static void
3655redo_mouse_highlight ()
3656{
3657  if (!NILP (last_mouse_motion_frame)
3658      && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
3659    note_mouse_highlight (XFRAME (last_mouse_motion_frame),
3660			  last_mouse_motion_event.x,
3661			  last_mouse_motion_event.y);
3662}
3663
3664
3665
3666/* Return the current position of the mouse.
3667   *FP should be a frame which indicates which display to ask about.
3668
3669   If the mouse movement started in a scroll bar, set *FP, *BAR_WINDOW,
3670   and *PART to the frame, window, and scroll bar part that the mouse
3671   is over.  Set *X and *Y to the portion and whole of the mouse's
3672   position on the scroll bar.
3673
3674   If the mouse movement started elsewhere, set *FP to the frame the
3675   mouse is on, *BAR_WINDOW to nil, and *X and *Y to the character cell
3676   the mouse is over.
3677
3678   Set *TIME to the server time-stamp for the time at which the mouse
3679   was at this position.
3680
3681   Don't store anything if we don't have a valid set of values to report.
3682
3683   This clears the mouse_moved flag, so we can wait for the next mouse
3684   movement.  */
3685
3686static void
3687XTmouse_position (fp, insist, bar_window, part, x, y, time)
3688     FRAME_PTR *fp;
3689     int insist;
3690     Lisp_Object *bar_window;
3691     enum scroll_bar_part *part;
3692     Lisp_Object *x, *y;
3693     unsigned long *time;
3694{
3695  FRAME_PTR f1;
3696
3697  BLOCK_INPUT;
3698
3699  if (! NILP (last_mouse_scroll_bar) && insist == 0)
3700    x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
3701  else
3702    {
3703      Window root;
3704      int root_x, root_y;
3705
3706      Window dummy_window;
3707      int dummy;
3708
3709      Lisp_Object frame, tail;
3710
3711      /* Clear the mouse-moved flag for every frame on this display.  */
3712      FOR_EACH_FRAME (tail, frame)
3713	if (FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
3714	  XFRAME (frame)->mouse_moved = 0;
3715
3716      last_mouse_scroll_bar = Qnil;
3717
3718      /* Figure out which root window we're on.  */
3719      XQueryPointer (FRAME_X_DISPLAY (*fp),
3720		     DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
3721
3722		     /* The root window which contains the pointer.  */
3723		     &root,
3724
3725		     /* Trash which we can't trust if the pointer is on
3726			a different screen.  */
3727		     &dummy_window,
3728
3729		     /* The position on that root window.  */
3730		     &root_x, &root_y,
3731
3732		     /* More trash we can't trust.  */
3733		     &dummy, &dummy,
3734
3735		     /* Modifier keys and pointer buttons, about which
3736			we don't care.  */
3737		     (unsigned int *) &dummy);
3738
3739      /* Now we have a position on the root; find the innermost window
3740	 containing the pointer.  */
3741      {
3742	Window win, child;
3743	int win_x, win_y;
3744	int parent_x = 0, parent_y = 0;
3745
3746	win = root;
3747
3748	/* XTranslateCoordinates can get errors if the window
3749	   structure is changing at the same time this function
3750	   is running.  So at least we must not crash from them.  */
3751
3752	x_catch_errors (FRAME_X_DISPLAY (*fp));
3753
3754	if (FRAME_X_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
3755	    && FRAME_LIVE_P (last_mouse_frame))
3756	  {
3757	    /* If mouse was grabbed on a frame, give coords for that frame
3758	       even if the mouse is now outside it.  */
3759	    XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3760
3761				   /* From-window, to-window.  */
3762				   root, FRAME_X_WINDOW (last_mouse_frame),
3763
3764				   /* From-position, to-position.  */
3765				   root_x, root_y, &win_x, &win_y,
3766
3767				   /* Child of win.  */
3768				   &child);
3769	    f1 = last_mouse_frame;
3770	  }
3771	else
3772	  {
3773	    while (1)
3774	      {
3775		XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
3776
3777				       /* From-window, to-window.  */
3778				       root, win,
3779
3780				       /* From-position, to-position.  */
3781				       root_x, root_y, &win_x, &win_y,
3782
3783				       /* Child of win.  */
3784				       &child);
3785
3786		if (child == None || child == win)
3787		  break;
3788
3789		win = child;
3790		parent_x = win_x;
3791		parent_y = win_y;
3792	      }
3793
3794	    /* Now we know that:
3795	       win is the innermost window containing the pointer
3796	       (XTC says it has no child containing the pointer),
3797	       win_x and win_y are the pointer's position in it
3798	       (XTC did this the last time through), and
3799	       parent_x and parent_y are the pointer's position in win's parent.
3800	       (They are what win_x and win_y were when win was child.
3801	       If win is the root window, it has no parent, and
3802	       parent_{x,y} are invalid, but that's okay, because we'll
3803	       never use them in that case.)  */
3804
3805	    /* Is win one of our frames?  */
3806	    f1 = x_any_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win);
3807
3808#ifdef USE_X_TOOLKIT
3809	    /* If we end up with the menu bar window, say it's not
3810	       on the frame.  */
3811	    if (f1 != NULL
3812		&& f1->output_data.x->menubar_widget
3813		&& win == XtWindow (f1->output_data.x->menubar_widget))
3814	      f1 = NULL;
3815#endif /* USE_X_TOOLKIT */
3816	  }
3817
3818	if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
3819	  f1 = 0;
3820
3821	x_uncatch_errors ();
3822
3823	/* If not, is it one of our scroll bars?  */
3824	if (! f1)
3825	  {
3826	    struct scroll_bar *bar;
3827
3828            bar = x_window_to_scroll_bar (FRAME_X_DISPLAY (*fp), win);
3829
3830	    if (bar)
3831	      {
3832		f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
3833		win_x = parent_x;
3834		win_y = parent_y;
3835	      }
3836	  }
3837
3838	if (f1 == 0 && insist > 0)
3839	  f1 = SELECTED_FRAME ();
3840
3841	if (f1)
3842	  {
3843	    /* Ok, we found a frame.  Store all the values.
3844	       last_mouse_glyph is a rectangle used to reduce the
3845	       generation of mouse events.  To not miss any motion
3846	       events, we must divide the frame into rectangles of the
3847	       size of the smallest character that could be displayed
3848	       on it, i.e. into the same rectangles that matrices on
3849	       the frame are divided into.  */
3850
3851	    remember_mouse_glyph (f1, win_x, win_y, &last_mouse_glyph);
3852	    last_mouse_glyph_frame = f1;
3853
3854	    *bar_window = Qnil;
3855	    *part = 0;
3856	    *fp = f1;
3857	    XSETINT (*x, win_x);
3858	    XSETINT (*y, win_y);
3859	    *time = last_mouse_movement_time;
3860	  }
3861      }
3862    }
3863
3864  UNBLOCK_INPUT;
3865}
3866
3867
3868
3869/***********************************************************************
3870			       Scroll bars
3871 ***********************************************************************/
3872
3873/* Scroll bar support.  */
3874
3875/* Given an X window ID and a DISPLAY, find the struct scroll_bar which
3876   manages it.
3877   This can be called in GC, so we have to make sure to strip off mark
3878   bits.  */
3879
3880static struct scroll_bar *
3881x_window_to_scroll_bar (display, window_id)
3882     Display *display;
3883     Window window_id;
3884{
3885  Lisp_Object tail;
3886
3887#if defined (USE_GTK) && defined (USE_TOOLKIT_SCROLL_BARS)
3888  window_id = (Window) xg_get_scroll_id_for_window (display, window_id);
3889#endif /* USE_GTK  && USE_TOOLKIT_SCROLL_BARS */
3890
3891  for (tail = Vframe_list;
3892       XGCTYPE (tail) == Lisp_Cons;
3893       tail = XCDR (tail))
3894    {
3895      Lisp_Object frame, bar, condemned;
3896
3897      frame = XCAR (tail);
3898      /* All elements of Vframe_list should be frames.  */
3899      if (! GC_FRAMEP (frame))
3900	abort ();
3901
3902      /* Scan this frame's scroll bar list for a scroll bar with the
3903         right window ID.  */
3904      condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
3905      for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
3906	   /* This trick allows us to search both the ordinary and
3907              condemned scroll bar lists with one loop.  */
3908	   ! GC_NILP (bar) || (bar = condemned,
3909			       condemned = Qnil,
3910			       ! GC_NILP (bar));
3911	   bar = XSCROLL_BAR (bar)->next)
3912	if (SCROLL_BAR_X_WINDOW (XSCROLL_BAR (bar)) == window_id &&
3913            FRAME_X_DISPLAY (XFRAME (frame)) == display)
3914	  return XSCROLL_BAR (bar);
3915    }
3916
3917  return 0;
3918}
3919
3920
3921#if defined USE_LUCID
3922
3923/* Return the Lucid menu bar WINDOW is part of.  Return null
3924   if WINDOW is not part of a menu bar.  */
3925
3926static Widget
3927x_window_to_menu_bar (window)
3928     Window window;
3929{
3930  Lisp_Object tail;
3931
3932  for (tail = Vframe_list;
3933       XGCTYPE (tail) == Lisp_Cons;
3934       tail = XCDR (tail))
3935    {
3936      Lisp_Object frame = XCAR (tail);
3937      Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
3938
3939      if (menu_bar && xlwmenu_window_p (menu_bar, window))
3940	return menu_bar;
3941    }
3942
3943  return NULL;
3944}
3945
3946#endif /* USE_LUCID */
3947
3948
3949/************************************************************************
3950			 Toolkit scroll bars
3951 ************************************************************************/
3952
3953#ifdef USE_TOOLKIT_SCROLL_BARS
3954
3955static void x_scroll_bar_to_input_event P_ ((XEvent *, struct input_event *));
3956static void x_send_scroll_bar_event P_ ((Lisp_Object, int, int, int));
3957static void x_create_toolkit_scroll_bar P_ ((struct frame *,
3958					     struct scroll_bar *));
3959static void x_set_toolkit_scroll_bar_thumb P_ ((struct scroll_bar *,
3960						int, int, int));
3961
3962
3963/* Lisp window being scrolled.  Set when starting to interact with
3964   a toolkit scroll bar, reset to nil when ending the interaction.  */
3965
3966static Lisp_Object window_being_scrolled;
3967
3968/* Last scroll bar part sent in xm_scroll_callback.  */
3969
3970static int last_scroll_bar_part;
3971
3972/* Whether this is an Xaw with arrow-scrollbars.  This should imply
3973   that movements of 1/20 of the screen size are mapped to up/down.  */
3974
3975#ifndef USE_GTK
3976/* Id of action hook installed for scroll bars.  */
3977
3978static XtActionHookId action_hook_id;
3979
3980static Boolean xaw3d_arrow_scroll;
3981
3982/* Whether the drag scrolling maintains the mouse at the top of the
3983   thumb.  If not, resizing the thumb needs to be done more carefully
3984   to avoid jerkyness.  */
3985
3986static Boolean xaw3d_pick_top;
3987
3988/* Action hook installed via XtAppAddActionHook when toolkit scroll
3989   bars are used..  The hook is responsible for detecting when
3990   the user ends an interaction with the scroll bar, and generates
3991   a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so.  */
3992
3993static void
3994xt_action_hook (widget, client_data, action_name, event, params,
3995		num_params)
3996     Widget widget;
3997     XtPointer client_data;
3998     String action_name;
3999     XEvent *event;
4000     String *params;
4001     Cardinal *num_params;
4002{
4003  int scroll_bar_p;
4004  char *end_action;
4005
4006#ifdef USE_MOTIF
4007  scroll_bar_p = XmIsScrollBar (widget);
4008  end_action = "Release";
4009#else /* !USE_MOTIF i.e. use Xaw */
4010  scroll_bar_p = XtIsSubclass (widget, scrollbarWidgetClass);
4011  end_action = "EndScroll";
4012#endif /* USE_MOTIF */
4013
4014  if (scroll_bar_p
4015      && strcmp (action_name, end_action) == 0
4016      && WINDOWP (window_being_scrolled))
4017    {
4018      struct window *w;
4019
4020      x_send_scroll_bar_event (window_being_scrolled,
4021			       scroll_bar_end_scroll, 0, 0);
4022      w = XWINDOW (window_being_scrolled);
4023
4024      if (!NILP (XSCROLL_BAR (w->vertical_scroll_bar)->dragging))
4025	{
4026	  XSCROLL_BAR (w->vertical_scroll_bar)->dragging = Qnil;
4027	  /* The thumb size is incorrect while dragging: fix it.  */
4028	  set_vertical_scroll_bar (w);
4029	}
4030      window_being_scrolled = Qnil;
4031      last_scroll_bar_part = -1;
4032
4033      /* Xt timeouts no longer needed.  */
4034      toolkit_scroll_bar_interaction = 0;
4035    }
4036}
4037#endif /* not USE_GTK */
4038
4039/* A vector of windows used for communication between
4040   x_send_scroll_bar_event and x_scroll_bar_to_input_event.  */
4041
4042static struct window **scroll_bar_windows;
4043static int scroll_bar_windows_size;
4044
4045
4046/* Send a client message with message type Xatom_Scrollbar for a
4047   scroll action to the frame of WINDOW.  PART is a value identifying
4048   the part of the scroll bar that was clicked on.  PORTION is the
4049   amount to scroll of a whole of WHOLE.  */
4050
4051static void
4052x_send_scroll_bar_event (window, part, portion, whole)
4053     Lisp_Object window;
4054     int part, portion, whole;
4055{
4056  XEvent event;
4057  XClientMessageEvent *ev = (XClientMessageEvent *) &event;
4058  struct window *w = XWINDOW (window);
4059  struct frame *f = XFRAME (w->frame);
4060  int i;
4061
4062  BLOCK_INPUT;
4063
4064  /* Construct a ClientMessage event to send to the frame.  */
4065  ev->type = ClientMessage;
4066  ev->message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_Scrollbar;
4067  ev->display = FRAME_X_DISPLAY (f);
4068  ev->window = FRAME_X_WINDOW (f);
4069  ev->format = 32;
4070
4071  /* We can only transfer 32 bits in the XClientMessageEvent, which is
4072     not enough to store a pointer or Lisp_Object on a 64 bit system.
4073     So, store the window in scroll_bar_windows and pass the index
4074     into that array in the event.  */
4075  for (i = 0; i < scroll_bar_windows_size; ++i)
4076    if (scroll_bar_windows[i] == NULL)
4077      break;
4078
4079  if (i == scroll_bar_windows_size)
4080    {
4081      int new_size = max (10, 2 * scroll_bar_windows_size);
4082      size_t nbytes = new_size * sizeof *scroll_bar_windows;
4083      size_t old_nbytes = scroll_bar_windows_size * sizeof *scroll_bar_windows;
4084
4085      scroll_bar_windows = (struct window **) xrealloc (scroll_bar_windows,
4086							nbytes);
4087      bzero (&scroll_bar_windows[i], nbytes - old_nbytes);
4088      scroll_bar_windows_size = new_size;
4089    }
4090
4091  scroll_bar_windows[i] = w;
4092  ev->data.l[0] = (long) i;
4093  ev->data.l[1] = (long) part;
4094  ev->data.l[2] = (long) 0;
4095  ev->data.l[3] = (long) portion;
4096  ev->data.l[4] = (long) whole;
4097
4098  /* Make Xt timeouts work while the scroll bar is active.  */
4099  toolkit_scroll_bar_interaction = 1;
4100#ifdef USE_X_TOOLKIT
4101  x_activate_timeout_atimer ();
4102#endif
4103
4104  /* Setting the event mask to zero means that the message will
4105     be sent to the client that created the window, and if that
4106     window no longer exists, no event will be sent.  */
4107  XSendEvent (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), False, 0, &event);
4108  UNBLOCK_INPUT;
4109}
4110
4111
4112/* Transform a scroll bar ClientMessage EVENT to an Emacs input event
4113   in *IEVENT.  */
4114
4115static void
4116x_scroll_bar_to_input_event (event, ievent)
4117     XEvent *event;
4118     struct input_event *ievent;
4119{
4120  XClientMessageEvent *ev = (XClientMessageEvent *) event;
4121  Lisp_Object window;
4122  struct frame *f;
4123  struct window *w;
4124
4125  w = scroll_bar_windows[ev->data.l[0]];
4126  scroll_bar_windows[ev->data.l[0]] = NULL;
4127
4128  XSETWINDOW (window, w);
4129  f = XFRAME (w->frame);
4130
4131  ievent->kind = SCROLL_BAR_CLICK_EVENT;
4132  ievent->frame_or_window = window;
4133  ievent->arg = Qnil;
4134#ifdef USE_GTK
4135  ievent->timestamp = CurrentTime;
4136#else
4137  ievent->timestamp = XtLastTimestampProcessed (FRAME_X_DISPLAY (f));
4138#endif
4139  ievent->part = ev->data.l[1];
4140  ievent->code = ev->data.l[2];
4141  ievent->x = make_number ((int) ev->data.l[3]);
4142  ievent->y = make_number ((int) ev->data.l[4]);
4143  ievent->modifiers = 0;
4144}
4145
4146
4147#ifdef USE_MOTIF
4148
4149/* Minimum and maximum values used for Motif scroll bars.  */
4150
4151#define XM_SB_MAX 10000000
4152
4153
4154/* Scroll bar callback for Motif scroll bars.  WIDGET is the scroll
4155   bar widget.  CLIENT_DATA is a pointer to the scroll_bar structure.
4156   CALL_DATA is a pointer to a XmScrollBarCallbackStruct.  */
4157
4158static void
4159xm_scroll_callback (widget, client_data, call_data)
4160     Widget widget;
4161     XtPointer client_data, call_data;
4162{
4163  struct scroll_bar *bar = (struct scroll_bar *) client_data;
4164  XmScrollBarCallbackStruct *cs = (XmScrollBarCallbackStruct *) call_data;
4165  int part = -1, whole = 0, portion = 0;
4166
4167  switch (cs->reason)
4168    {
4169    case XmCR_DECREMENT:
4170      bar->dragging = Qnil;
4171      part = scroll_bar_up_arrow;
4172      break;
4173
4174    case XmCR_INCREMENT:
4175      bar->dragging = Qnil;
4176      part = scroll_bar_down_arrow;
4177      break;
4178
4179    case XmCR_PAGE_DECREMENT:
4180      bar->dragging = Qnil;
4181      part = scroll_bar_above_handle;
4182      break;
4183
4184    case XmCR_PAGE_INCREMENT:
4185      bar->dragging = Qnil;
4186      part = scroll_bar_below_handle;
4187      break;
4188
4189    case XmCR_TO_TOP:
4190      bar->dragging = Qnil;
4191      part = scroll_bar_to_top;
4192      break;
4193
4194    case XmCR_TO_BOTTOM:
4195      bar->dragging = Qnil;
4196      part = scroll_bar_to_bottom;
4197      break;
4198
4199    case XmCR_DRAG:
4200      {
4201	int slider_size;
4202
4203	/* Get the slider size.  */
4204	BLOCK_INPUT;
4205	XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
4206	UNBLOCK_INPUT;
4207
4208	whole = XM_SB_MAX - slider_size;
4209	portion = min (cs->value, whole);
4210	part = scroll_bar_handle;
4211	bar->dragging = make_number (cs->value);
4212      }
4213      break;
4214
4215    case XmCR_VALUE_CHANGED:
4216      break;
4217    };
4218
4219  if (part >= 0)
4220    {
4221      window_being_scrolled = bar->window;
4222      last_scroll_bar_part = part;
4223      x_send_scroll_bar_event (bar->window, part, portion, whole);
4224    }
4225}
4226
4227
4228#else /* !USE_MOTIF, i.e. Xaw or GTK */
4229#ifdef USE_GTK
4230/* Scroll bar callback for GTK scroll bars.  WIDGET is the scroll
4231   bar widget.  DATA is a pointer to the scroll_bar structure. */
4232
4233static void
4234xg_scroll_callback (widget, data)
4235     GtkRange *widget;
4236     gpointer data;
4237{
4238  struct scroll_bar *bar = (struct scroll_bar *) data;
4239  gdouble previous;
4240  gdouble position;
4241  gdouble *p;
4242  int diff;
4243
4244  int part = -1, whole = 0, portion = 0;
4245  GtkAdjustment *adj = GTK_ADJUSTMENT (gtk_range_get_adjustment (widget));
4246
4247  position = gtk_adjustment_get_value (adj);
4248
4249  p = g_object_get_data (G_OBJECT (widget), XG_LAST_SB_DATA);
4250  if (! p)
4251    {
4252      p = (gdouble*) xmalloc (sizeof (gdouble));
4253      *p = XG_SB_MIN;
4254      g_object_set_data (G_OBJECT (widget), XG_LAST_SB_DATA, p);
4255    }
4256
4257  previous = *p;
4258  *p = position;
4259
4260  if (xg_ignore_gtk_scrollbar) return;
4261
4262  diff = (int) (position - previous);
4263
4264  if (diff == (int) adj->step_increment)
4265    {
4266      part = scroll_bar_down_arrow;
4267      bar->dragging = Qnil;
4268    }
4269  else if (-diff == (int) adj->step_increment)
4270    {
4271      part = scroll_bar_up_arrow;
4272      bar->dragging = Qnil;
4273    }
4274  else if (diff == (int) adj->page_increment)
4275    {
4276      part = scroll_bar_below_handle;
4277      bar->dragging = Qnil;
4278    }
4279  else if (-diff == (int) adj->page_increment)
4280    {
4281      part = scroll_bar_above_handle;
4282      bar->dragging = Qnil;
4283    }
4284  else
4285    {
4286      part = scroll_bar_handle;
4287      whole = adj->upper - adj->page_size;
4288      portion = min ((int)position, whole);
4289      bar->dragging = make_number ((int)portion);
4290    }
4291
4292  if (part >= 0)
4293    {
4294      window_being_scrolled = bar->window;
4295      last_scroll_bar_part = part;
4296      x_send_scroll_bar_event (bar->window, part, portion, whole);
4297    }
4298}
4299
4300#else /* not USE_GTK */
4301
4302/* Xaw scroll bar callback.  Invoked when the thumb is dragged.
4303   WIDGET is the scroll bar widget.  CLIENT_DATA is a pointer to the
4304   scroll bar struct.  CALL_DATA is a pointer to a float saying where
4305   the thumb is.  */
4306
4307static void
4308xaw_jump_callback (widget, client_data, call_data)
4309     Widget widget;
4310     XtPointer client_data, call_data;
4311{
4312  struct scroll_bar *bar = (struct scroll_bar *) client_data;
4313  float top = *(float *) call_data;
4314  float shown;
4315  int whole, portion, height;
4316  int part;
4317
4318  /* Get the size of the thumb, a value between 0 and 1.  */
4319  BLOCK_INPUT;
4320  XtVaGetValues (widget, XtNshown, &shown, XtNheight, &height, NULL);
4321  UNBLOCK_INPUT;
4322
4323  whole = 10000000;
4324  portion = shown < 1 ? top * whole : 0;
4325
4326  if (shown < 1 && (abs (top + shown - 1) < 1.0/height))
4327    /* Some derivatives of Xaw refuse to shrink the thumb when you reach
4328       the bottom, so we force the scrolling whenever we see that we're
4329       too close to the bottom (in x_set_toolkit_scroll_bar_thumb
4330       we try to ensure that we always stay two pixels away from the
4331       bottom).  */
4332    part = scroll_bar_down_arrow;
4333  else
4334    part = scroll_bar_handle;
4335
4336  window_being_scrolled = bar->window;
4337  bar->dragging = make_number (portion);
4338  last_scroll_bar_part = part;
4339  x_send_scroll_bar_event (bar->window, part, portion, whole);
4340}
4341
4342
4343/* Xaw scroll bar callback.  Invoked for incremental scrolling.,
4344   i.e. line or page up or down.  WIDGET is the Xaw scroll bar
4345   widget.  CLIENT_DATA is a pointer to the scroll_bar structure for
4346   the scroll bar.  CALL_DATA is an integer specifying the action that
4347   has taken place.  Its magnitude is in the range 0..height of the
4348   scroll bar.  Negative values mean scroll towards buffer start.
4349   Values < height of scroll bar mean line-wise movement.  */
4350
4351static void
4352xaw_scroll_callback (widget, client_data, call_data)
4353     Widget widget;
4354     XtPointer client_data, call_data;
4355{
4356  struct scroll_bar *bar = (struct scroll_bar *) client_data;
4357  /* The position really is stored cast to a pointer.  */
4358  int position = (long) call_data;
4359  Dimension height;
4360  int part;
4361
4362  /* Get the height of the scroll bar.  */
4363  BLOCK_INPUT;
4364  XtVaGetValues (widget, XtNheight, &height, NULL);
4365  UNBLOCK_INPUT;
4366
4367  if (abs (position) >= height)
4368    part = (position < 0) ? scroll_bar_above_handle : scroll_bar_below_handle;
4369
4370  /* If Xaw3d was compiled with ARROW_SCROLLBAR,
4371     it maps line-movement to call_data = max(5, height/20).  */
4372  else if (xaw3d_arrow_scroll && abs (position) <= max (5, height / 20))
4373    part = (position < 0) ? scroll_bar_up_arrow : scroll_bar_down_arrow;
4374  else
4375    part = scroll_bar_move_ratio;
4376
4377  window_being_scrolled = bar->window;
4378  bar->dragging = Qnil;
4379  last_scroll_bar_part = part;
4380  x_send_scroll_bar_event (bar->window, part, position, height);
4381}
4382
4383#endif /* not USE_GTK */
4384#endif /* not USE_MOTIF */
4385
4386#define SCROLL_BAR_NAME "verticalScrollBar"
4387
4388/* Create the widget for scroll bar BAR on frame F.  Record the widget
4389   and X window of the scroll bar in BAR.  */
4390
4391#ifdef USE_GTK
4392static void
4393x_create_toolkit_scroll_bar (f, bar)
4394     struct frame *f;
4395     struct scroll_bar *bar;
4396{
4397  char *scroll_bar_name = SCROLL_BAR_NAME;
4398
4399  BLOCK_INPUT;
4400  xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
4401                        scroll_bar_name);
4402  UNBLOCK_INPUT;
4403}
4404
4405#else /* not USE_GTK */
4406
4407static void
4408x_create_toolkit_scroll_bar (f, bar)
4409     struct frame *f;
4410     struct scroll_bar *bar;
4411{
4412  Window xwindow;
4413  Widget widget;
4414  Arg av[20];
4415  int ac = 0;
4416  char *scroll_bar_name = SCROLL_BAR_NAME;
4417  unsigned long pixel;
4418
4419  BLOCK_INPUT;
4420
4421#ifdef USE_MOTIF
4422  /* Set resources.  Create the widget.  */
4423  XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4424  XtSetArg (av[ac], XmNminimum, 0); ++ac;
4425  XtSetArg (av[ac], XmNmaximum, XM_SB_MAX); ++ac;
4426  XtSetArg (av[ac], XmNorientation, XmVERTICAL); ++ac;
4427  XtSetArg (av[ac], XmNprocessingDirection, XmMAX_ON_BOTTOM), ++ac;
4428  XtSetArg (av[ac], XmNincrement, 1); ++ac;
4429  XtSetArg (av[ac], XmNpageIncrement, 1); ++ac;
4430
4431  pixel = f->output_data.x->scroll_bar_foreground_pixel;
4432  if (pixel != -1)
4433    {
4434      XtSetArg (av[ac], XmNforeground, pixel);
4435      ++ac;
4436    }
4437
4438  pixel = f->output_data.x->scroll_bar_background_pixel;
4439  if (pixel != -1)
4440    {
4441      XtSetArg (av[ac], XmNbackground, pixel);
4442      ++ac;
4443    }
4444
4445  widget = XmCreateScrollBar (f->output_data.x->edit_widget,
4446			      scroll_bar_name, av, ac);
4447
4448  /* Add one callback for everything that can happen.  */
4449  XtAddCallback (widget, XmNdecrementCallback, xm_scroll_callback,
4450		 (XtPointer) bar);
4451  XtAddCallback (widget, XmNdragCallback, xm_scroll_callback,
4452		 (XtPointer) bar);
4453  XtAddCallback (widget, XmNincrementCallback, xm_scroll_callback,
4454		 (XtPointer) bar);
4455  XtAddCallback (widget, XmNpageDecrementCallback, xm_scroll_callback,
4456		 (XtPointer) bar);
4457  XtAddCallback (widget, XmNpageIncrementCallback, xm_scroll_callback,
4458		 (XtPointer) bar);
4459  XtAddCallback (widget, XmNtoBottomCallback, xm_scroll_callback,
4460		 (XtPointer) bar);
4461  XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
4462		 (XtPointer) bar);
4463
4464  /* Realize the widget.  Only after that is the X window created.  */
4465  XtRealizeWidget (widget);
4466
4467  /* Set the cursor to an arrow.  I didn't find a resource to do that.
4468     And I'm wondering why it hasn't an arrow cursor by default.  */
4469  XDefineCursor (XtDisplay (widget), XtWindow (widget),
4470		 f->output_data.x->nontext_cursor);
4471
4472#else /* !USE_MOTIF i.e. use Xaw */
4473
4474  /* Set resources.  Create the widget.  The background of the
4475     Xaw3d scroll bar widget is a little bit light for my taste.
4476     We don't alter it here to let users change it according
4477     to their taste with `emacs*verticalScrollBar.background: xxx'.  */
4478  XtSetArg (av[ac], XtNmappedWhenManaged, False); ++ac;
4479  XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
4480  /* For smoother scrolling with Xaw3d   -sm */
4481  /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
4482
4483  pixel = f->output_data.x->scroll_bar_foreground_pixel;
4484  if (pixel != -1)
4485    {
4486      XtSetArg (av[ac], XtNforeground, pixel);
4487      ++ac;
4488    }
4489
4490  pixel = f->output_data.x->scroll_bar_background_pixel;
4491  if (pixel != -1)
4492    {
4493      XtSetArg (av[ac], XtNbackground, pixel);
4494      ++ac;
4495    }
4496
4497  /* Top/bottom shadow colors.  */
4498
4499  /* Allocate them, if necessary.  */
4500  if (f->output_data.x->scroll_bar_top_shadow_pixel == -1)
4501    {
4502      pixel = f->output_data.x->scroll_bar_background_pixel;
4503      if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
4504				  &pixel, 1.2, 0x8000))
4505	pixel = -1;
4506      f->output_data.x->scroll_bar_top_shadow_pixel = pixel;
4507    }
4508  if (f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4509    {
4510      pixel = f->output_data.x->scroll_bar_background_pixel;
4511      if (!x_alloc_lighter_color (f, FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f),
4512				  &pixel, 0.6, 0x4000))
4513	pixel = -1;
4514      f->output_data.x->scroll_bar_bottom_shadow_pixel = pixel;
4515    }
4516
4517#ifdef XtNbeNiceToColormap
4518  /* Tell the toolkit about them.  */
4519  if (f->output_data.x->scroll_bar_top_shadow_pixel == -1
4520      || f->output_data.x->scroll_bar_bottom_shadow_pixel == -1)
4521    /* We tried to allocate a color for the top/bottom shadow, and
4522       failed, so tell Xaw3d to use dithering instead.   */
4523    {
4524      XtSetArg (av[ac], XtNbeNiceToColormap, True);
4525      ++ac;
4526    }
4527  else
4528    /* Tell what colors Xaw3d should use for the top/bottom shadow, to
4529       be more consistent with other emacs 3d colors, and since Xaw3d is
4530       not good at dealing with allocation failure.  */
4531    {
4532      /* This tells Xaw3d to use real colors instead of dithering for
4533	 the shadows.  */
4534      XtSetArg (av[ac], XtNbeNiceToColormap, False);
4535      ++ac;
4536
4537      /* Specify the colors.  */
4538      pixel = f->output_data.x->scroll_bar_top_shadow_pixel;
4539      if (pixel != -1)
4540	{
4541	  XtSetArg (av[ac], XtNtopShadowPixel, pixel);
4542	  ++ac;
4543	}
4544      pixel = f->output_data.x->scroll_bar_bottom_shadow_pixel;
4545      if (pixel != -1)
4546	{
4547	  XtSetArg (av[ac], XtNbottomShadowPixel, pixel);
4548	  ++ac;
4549	}
4550    }
4551#endif
4552
4553  widget = XtCreateWidget (scroll_bar_name, scrollbarWidgetClass,
4554			   f->output_data.x->edit_widget, av, ac);
4555
4556  {
4557    char *initial = "";
4558    char *val = initial;
4559    XtVaGetValues (widget, XtNscrollVCursor, (XtPointer) &val,
4560#ifdef XtNarrowScrollbars
4561		   XtNarrowScrollbars, (XtPointer) &xaw3d_arrow_scroll,
4562#endif
4563		   XtNpickTop, (XtPointer) &xaw3d_pick_top, NULL);
4564    if (xaw3d_arrow_scroll || val == initial)
4565      {	/* ARROW_SCROLL */
4566	xaw3d_arrow_scroll = True;
4567	/* Isn't that just a personal preference ?   --Stef */
4568	XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
4569      }
4570  }
4571
4572  /* Define callbacks.  */
4573  XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
4574  XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
4575		 (XtPointer) bar);
4576
4577  /* Realize the widget.  Only after that is the X window created.  */
4578  XtRealizeWidget (widget);
4579
4580#endif /* !USE_MOTIF */
4581
4582  /* Install an action hook that lets us detect when the user
4583     finishes interacting with a scroll bar.  */
4584  if (action_hook_id == 0)
4585    action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
4586
4587  /* Remember X window and widget in the scroll bar vector.  */
4588  SET_SCROLL_BAR_X_WIDGET (bar, widget);
4589  xwindow = XtWindow (widget);
4590  SET_SCROLL_BAR_X_WINDOW (bar, xwindow);
4591
4592  UNBLOCK_INPUT;
4593}
4594#endif /* not USE_GTK */
4595
4596
4597/* Set the thumb size and position of scroll bar BAR.  We are currently
4598   displaying PORTION out of a whole WHOLE, and our position POSITION.  */
4599
4600#ifdef USE_GTK
4601static void
4602x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
4603     struct scroll_bar *bar;
4604     int portion, position, whole;
4605{
4606  xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4607}
4608
4609#else /* not USE_GTK */
4610static void
4611x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
4612     struct scroll_bar *bar;
4613     int portion, position, whole;
4614{
4615  struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4616  Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4617  float top, shown;
4618
4619  BLOCK_INPUT;
4620
4621#ifdef USE_MOTIF
4622
4623  /* We use an estimate of 30 chars per line rather than the real
4624     `portion' value.  This has the disadvantage that the thumb size
4625     is not very representative, but it makes our life a lot easier.
4626     Otherwise, we have to constantly adjust the thumb size, which
4627     we can't always do quickly enough: while dragging, the size of
4628     the thumb might prevent the user from dragging the thumb all the
4629     way to the end.  but Motif and some versions of Xaw3d don't allow
4630     updating the thumb size while dragging.  Also, even if we can update
4631     its size, the update will often happen too late.
4632     If you don't believe it, check out revision 1.650 of xterm.c to see
4633     what hoops we were going through and the still poor behavior we got.  */
4634  portion = WINDOW_TOTAL_LINES (XWINDOW (bar->window)) * 30;
4635  /* When the thumb is at the bottom, position == whole.
4636     So we need to increase `whole' to make space for the thumb.  */
4637  whole += portion;
4638
4639  if (whole <= 0)
4640    top = 0, shown = 1;
4641  else
4642    {
4643      top = (float) position / whole;
4644      shown = (float) portion / whole;
4645    }
4646
4647  if (NILP (bar->dragging))
4648    {
4649      int size, value;
4650
4651      /* Slider size.  Must be in the range [1 .. MAX - MIN] where MAX
4652         is the scroll bar's maximum and MIN is the scroll bar's minimum
4653	 value.  */
4654      size = shown * XM_SB_MAX;
4655      size = min (size, XM_SB_MAX);
4656      size = max (size, 1);
4657
4658      /* Position.  Must be in the range [MIN .. MAX - SLIDER_SIZE].  */
4659      value = top * XM_SB_MAX;
4660      value = min (value, XM_SB_MAX - size);
4661
4662      XmScrollBarSetValues (widget, value, size, 0, 0, False);
4663    }
4664#else /* !USE_MOTIF i.e. use Xaw */
4665
4666  if (whole == 0)
4667    top = 0, shown = 1;
4668  else
4669    {
4670      top = (float) position / whole;
4671      shown = (float) portion / whole;
4672    }
4673
4674  {
4675    float old_top, old_shown;
4676    Dimension height;
4677    XtVaGetValues (widget,
4678		   XtNtopOfThumb, &old_top,
4679		   XtNshown, &old_shown,
4680		   XtNheight, &height,
4681		   NULL);
4682
4683    /* Massage the top+shown values.  */
4684    if (NILP (bar->dragging) || last_scroll_bar_part == scroll_bar_down_arrow)
4685      top = max (0, min (1, top));
4686    else
4687      top = old_top;
4688    /* Keep two pixels available for moving the thumb down.  */
4689    shown = max (0, min (1 - top - (2.0 / height), shown));
4690
4691    /* If the call to XawScrollbarSetThumb below doesn't seem to work,
4692       check that your system's configuration file contains a define
4693       for `NARROWPROTO'.  See s/freebsd.h for an example.  */
4694    if (top != old_top || shown != old_shown)
4695      {
4696	if (NILP (bar->dragging))
4697	  XawScrollbarSetThumb (widget, top, shown);
4698	else
4699	  {
4700	    /* Try to make the scrolling a tad smoother.  */
4701	    if (!xaw3d_pick_top)
4702	      shown = min (shown, old_shown);
4703
4704	    XawScrollbarSetThumb (widget, top, shown);
4705	  }
4706      }
4707  }
4708#endif /* !USE_MOTIF */
4709
4710  UNBLOCK_INPUT;
4711}
4712#endif /* not USE_GTK */
4713
4714#endif /* USE_TOOLKIT_SCROLL_BARS */
4715
4716
4717
4718/************************************************************************
4719			 Scroll bars, general
4720 ************************************************************************/
4721
4722/* Create a scroll bar and return the scroll bar vector for it.  W is
4723   the Emacs window on which to create the scroll bar. TOP, LEFT,
4724   WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4725   scroll bar. */
4726
4727static struct scroll_bar *
4728x_scroll_bar_create (w, top, left, width, height)
4729     struct window *w;
4730     int top, left, width, height;
4731{
4732  struct frame *f = XFRAME (w->frame);
4733  struct scroll_bar *bar
4734    = XSCROLL_BAR (Fmake_vector (make_number (SCROLL_BAR_VEC_SIZE), Qnil));
4735
4736  BLOCK_INPUT;
4737
4738#ifdef USE_TOOLKIT_SCROLL_BARS
4739  x_create_toolkit_scroll_bar (f, bar);
4740#else /* not USE_TOOLKIT_SCROLL_BARS */
4741  {
4742    XSetWindowAttributes a;
4743    unsigned long mask;
4744    Window window;
4745
4746    a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
4747    if (a.background_pixel == -1)
4748      a.background_pixel = f->output_data.x->background_pixel;
4749
4750    a.event_mask = (ButtonPressMask | ButtonReleaseMask
4751		    | ButtonMotionMask | PointerMotionHintMask
4752		    | ExposureMask);
4753    a.cursor = FRAME_X_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
4754
4755    mask = (CWBackPixel | CWEventMask | CWCursor);
4756
4757    /* Clear the area of W that will serve as a scroll bar.  This is
4758       for the case that a window has been split horizontally.  In
4759       this case, no clear_frame is generated to reduce flickering.  */
4760    if (width > 0 && height > 0)
4761      x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4762		    left, top, width,
4763		    window_box_height (w), False);
4764
4765    window = XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
4766			    /* Position and size of scroll bar.  */
4767			    left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4768			    top,
4769			    width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4770			    height,
4771			    /* Border width, depth, class, and visual.  */
4772			     0,
4773			    CopyFromParent,
4774			    CopyFromParent,
4775			    CopyFromParent,
4776			     /* Attributes.  */
4777			    mask, &a);
4778    SET_SCROLL_BAR_X_WINDOW (bar, window);
4779  }
4780#endif /* not USE_TOOLKIT_SCROLL_BARS */
4781
4782  XSETWINDOW (bar->window, w);
4783  XSETINT (bar->top, top);
4784  XSETINT (bar->left, left);
4785  XSETINT (bar->width, width);
4786  XSETINT (bar->height, height);
4787  XSETINT (bar->start, 0);
4788  XSETINT (bar->end, 0);
4789  bar->dragging = Qnil;
4790
4791  /* Add bar to its frame's list of scroll bars.  */
4792  bar->next = FRAME_SCROLL_BARS (f);
4793  bar->prev = Qnil;
4794  XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4795  if (!NILP (bar->next))
4796    XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4797
4798  /* Map the window/widget.  */
4799#ifdef USE_TOOLKIT_SCROLL_BARS
4800  {
4801#ifdef USE_GTK
4802    xg_update_scrollbar_pos (f,
4803                             SCROLL_BAR_X_WINDOW (bar),
4804                             top,
4805                             left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4806                             width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4807                             max (height, 1));
4808    xg_show_scroll_bar (SCROLL_BAR_X_WINDOW (bar));
4809#else /* not USE_GTK */
4810    Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
4811    XtConfigureWidget (scroll_bar,
4812		       left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
4813		       top,
4814		       width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4815		       max (height, 1), 0);
4816    XtMapWidget (scroll_bar);
4817#endif /* not USE_GTK */
4818    }
4819#else /* not USE_TOOLKIT_SCROLL_BARS */
4820  XMapRaised (FRAME_X_DISPLAY (f), SCROLL_BAR_X_WINDOW (bar));
4821#endif /* not USE_TOOLKIT_SCROLL_BARS */
4822
4823  UNBLOCK_INPUT;
4824  return bar;
4825}
4826
4827
4828/* Draw BAR's handle in the proper position.
4829
4830   If the handle is already drawn from START to END, don't bother
4831   redrawing it, unless REBUILD is non-zero; in that case, always
4832   redraw it.  (REBUILD is handy for drawing the handle after expose
4833   events.)
4834
4835   Normally, we want to constrain the start and end of the handle to
4836   fit inside its rectangle, but if the user is dragging the scroll
4837   bar handle, we want to let them drag it down all the way, so that
4838   the bar's top is as far down as it goes; otherwise, there's no way
4839   to move to the very end of the buffer.  */
4840
4841#ifndef USE_TOOLKIT_SCROLL_BARS
4842
4843static void
4844x_scroll_bar_set_handle (bar, start, end, rebuild)
4845     struct scroll_bar *bar;
4846     int start, end;
4847     int rebuild;
4848{
4849  int dragging = ! NILP (bar->dragging);
4850  Window w = SCROLL_BAR_X_WINDOW (bar);
4851  FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4852  GC gc = f->output_data.x->normal_gc;
4853
4854  /* If the display is already accurate, do nothing.  */
4855  if (! rebuild
4856      && start == XINT (bar->start)
4857      && end == XINT (bar->end))
4858    return;
4859
4860  BLOCK_INPUT;
4861
4862  {
4863    int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, XINT (bar->width));
4864    int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, XINT (bar->height));
4865    int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
4866
4867    /* Make sure the values are reasonable, and try to preserve
4868       the distance between start and end.  */
4869    {
4870      int length = end - start;
4871
4872      if (start < 0)
4873	start = 0;
4874      else if (start > top_range)
4875	start = top_range;
4876      end = start + length;
4877
4878      if (end < start)
4879	end = start;
4880      else if (end > top_range && ! dragging)
4881	end = top_range;
4882    }
4883
4884    /* Store the adjusted setting in the scroll bar.  */
4885    XSETINT (bar->start, start);
4886    XSETINT (bar->end, end);
4887
4888    /* Clip the end position, just for display.  */
4889    if (end > top_range)
4890      end = top_range;
4891
4892    /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
4893       below top positions, to make sure the handle is always at least
4894       that many pixels tall.  */
4895    end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
4896
4897    /* Draw the empty space above the handle.  Note that we can't clear
4898       zero-height areas; that means "clear to end of window."  */
4899    if (0 < start)
4900      x_clear_area (FRAME_X_DISPLAY (f), w,
4901		    /* x, y, width, height, and exposures.  */
4902		    VERTICAL_SCROLL_BAR_LEFT_BORDER,
4903		    VERTICAL_SCROLL_BAR_TOP_BORDER,
4904		    inside_width, start,
4905		    False);
4906
4907    /* Change to proper foreground color if one is specified.  */
4908    if (f->output_data.x->scroll_bar_foreground_pixel != -1)
4909      XSetForeground (FRAME_X_DISPLAY (f), gc,
4910		      f->output_data.x->scroll_bar_foreground_pixel);
4911
4912    /* Draw the handle itself.  */
4913    XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
4914		    /* x, y, width, height */
4915		    VERTICAL_SCROLL_BAR_LEFT_BORDER,
4916		    VERTICAL_SCROLL_BAR_TOP_BORDER + start,
4917		    inside_width, end - start);
4918
4919    /* Restore the foreground color of the GC if we changed it above.  */
4920    if (f->output_data.x->scroll_bar_foreground_pixel != -1)
4921      XSetForeground (FRAME_X_DISPLAY (f), gc,
4922		      f->output_data.x->foreground_pixel);
4923
4924    /* Draw the empty space below the handle.  Note that we can't
4925       clear zero-height areas; that means "clear to end of window." */
4926    if (end < inside_height)
4927      x_clear_area (FRAME_X_DISPLAY (f), w,
4928		    /* x, y, width, height, and exposures.  */
4929		    VERTICAL_SCROLL_BAR_LEFT_BORDER,
4930		    VERTICAL_SCROLL_BAR_TOP_BORDER + end,
4931		    inside_width, inside_height - end,
4932		    False);
4933
4934  }
4935
4936  UNBLOCK_INPUT;
4937}
4938
4939#endif /* !USE_TOOLKIT_SCROLL_BARS */
4940
4941/* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
4942   nil.  */
4943
4944static void
4945x_scroll_bar_remove (bar)
4946     struct scroll_bar *bar;
4947{
4948  struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4949  BLOCK_INPUT;
4950
4951#ifdef USE_TOOLKIT_SCROLL_BARS
4952#ifdef USE_GTK
4953  xg_remove_scroll_bar (f, SCROLL_BAR_X_WINDOW (bar));
4954#else /* not USE_GTK */
4955  XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
4956#endif /* not USE_GTK */
4957#else
4958  XDestroyWindow (FRAME_X_DISPLAY (f), SCROLL_BAR_X_WINDOW (bar));
4959#endif
4960
4961  /* Disassociate this scroll bar from its window.  */
4962  XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
4963
4964  UNBLOCK_INPUT;
4965}
4966
4967
4968/* Set the handle of the vertical scroll bar for WINDOW to indicate
4969   that we are displaying PORTION characters out of a total of WHOLE
4970   characters, starting at POSITION.  If WINDOW has no scroll bar,
4971   create one.  */
4972
4973static void
4974XTset_vertical_scroll_bar (w, portion, whole, position)
4975     struct window *w;
4976     int portion, whole, position;
4977{
4978  struct frame *f = XFRAME (w->frame);
4979  struct scroll_bar *bar;
4980  int top, height, left, sb_left, width, sb_width;
4981  int window_y, window_height;
4982
4983  /* Get window dimensions.  */
4984  window_box (w, -1, 0, &window_y, 0, &window_height);
4985  top = window_y;
4986  width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
4987  height = window_height;
4988
4989  /* Compute the left edge of the scroll bar area.  */
4990  left = WINDOW_SCROLL_BAR_AREA_X (w);
4991
4992  /* Compute the width of the scroll bar which might be less than
4993     the width of the area reserved for the scroll bar.  */
4994  if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
4995    sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
4996  else
4997    sb_width = width;
4998
4999  /* Compute the left edge of the scroll bar.  */
5000#ifdef USE_TOOLKIT_SCROLL_BARS
5001  if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5002    sb_left = (left +
5003	       (WINDOW_RIGHTMOST_P (w)
5004		? width - sb_width - (width - sb_width) / 2
5005		: 0));
5006  else
5007    sb_left = (left +
5008	       (WINDOW_LEFTMOST_P (w)
5009		? (width - sb_width) / 2
5010		: width - sb_width));
5011#else
5012  if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
5013    sb_left = left + width - sb_width;
5014  else
5015    sb_left = left;
5016#endif
5017
5018  /* Does the scroll bar exist yet?  */
5019  if (NILP (w->vertical_scroll_bar))
5020    {
5021      if (width > 0 && height > 0)
5022	{
5023	  BLOCK_INPUT;
5024	  x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5025			left, top, width, height, False);
5026	  UNBLOCK_INPUT;
5027	}
5028
5029      bar = x_scroll_bar_create (w, top, sb_left, sb_width, height);
5030    }
5031  else
5032    {
5033      /* It may just need to be moved and resized.  */
5034      unsigned int mask = 0;
5035
5036      bar = XSCROLL_BAR (w->vertical_scroll_bar);
5037
5038      BLOCK_INPUT;
5039
5040      if (sb_left != XINT (bar->left))
5041	mask |= CWX;
5042      if (top != XINT (bar->top))
5043	mask |= CWY;
5044      if (sb_width != XINT (bar->width))
5045	mask |= CWWidth;
5046      if (height != XINT (bar->height))
5047	mask |= CWHeight;
5048
5049#ifdef USE_TOOLKIT_SCROLL_BARS
5050
5051      /* Move/size the scroll bar widget.  */
5052      if (mask)
5053	{
5054	  /* Since toolkit scroll bars are smaller than the space reserved
5055	     for them on the frame, we have to clear "under" them.  */
5056	  if (width > 0 && height > 0)
5057	    x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5058                          left, top, width, height, False);
5059#ifdef USE_GTK
5060          xg_update_scrollbar_pos (f,
5061                                   SCROLL_BAR_X_WINDOW (bar),
5062                                   top,
5063                                   sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5064                                   sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM *2,
5065                                   max (height, 1));
5066#else /* not USE_GTK */
5067          XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
5068                             sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5069                             top,
5070                             sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
5071                             max (height, 1), 0);
5072#endif /* not USE_GTK */
5073	}
5074#else /* not USE_TOOLKIT_SCROLL_BARS */
5075
5076      /* Clear areas not covered by the scroll bar because of
5077	 VERTICAL_SCROLL_BAR_WIDTH_TRIM.  */
5078      if (VERTICAL_SCROLL_BAR_WIDTH_TRIM)
5079	{
5080	  x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5081			left, top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5082			height, False);
5083	  x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5084			left + width - VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5085			top, VERTICAL_SCROLL_BAR_WIDTH_TRIM,
5086			height, False);
5087	}
5088
5089      /* Clear areas not covered by the scroll bar because it's not as
5090	 wide as the area reserved for it.  This makes sure a
5091	 previous mode line display is cleared after C-x 2 C-x 1, for
5092	 example.  */
5093      {
5094	int area_width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
5095	int rest = area_width - sb_width;
5096	if (rest > 0 && height > 0)
5097	  {
5098	    if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
5099	      x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5100			    left + area_width -  rest, top,
5101			    rest, height, False);
5102	    else
5103	      x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5104			    left, top, rest, height, False);
5105	  }
5106      }
5107
5108      /* Move/size the scroll bar window.  */
5109      if (mask)
5110	{
5111	  XWindowChanges wc;
5112
5113	  wc.x = sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5114	  wc.y = top;
5115	  wc.width = sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2;
5116	  wc.height = height;
5117	  XConfigureWindow (FRAME_X_DISPLAY (f), SCROLL_BAR_X_WINDOW (bar),
5118			    mask, &wc);
5119	}
5120
5121#endif /* not USE_TOOLKIT_SCROLL_BARS */
5122
5123      /* Remember new settings.  */
5124      XSETINT (bar->left, sb_left);
5125      XSETINT (bar->top, top);
5126      XSETINT (bar->width, sb_width);
5127      XSETINT (bar->height, height);
5128
5129      UNBLOCK_INPUT;
5130    }
5131
5132#ifdef USE_TOOLKIT_SCROLL_BARS
5133  x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
5134#else /* not USE_TOOLKIT_SCROLL_BARS */
5135  /* Set the scroll bar's current state, unless we're currently being
5136     dragged.  */
5137  if (NILP (bar->dragging))
5138    {
5139      int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
5140
5141      if (whole == 0)
5142	x_scroll_bar_set_handle (bar, 0, top_range, 0);
5143      else
5144	{
5145	  int start = ((double) position * top_range) / whole;
5146	  int end = ((double) (position + portion) * top_range) / whole;
5147	  x_scroll_bar_set_handle (bar, start, end, 0);
5148	}
5149    }
5150#endif /* not USE_TOOLKIT_SCROLL_BARS */
5151
5152  XSETVECTOR (w->vertical_scroll_bar, bar);
5153}
5154
5155
5156/* The following three hooks are used when we're doing a thorough
5157   redisplay of the frame.  We don't explicitly know which scroll bars
5158   are going to be deleted, because keeping track of when windows go
5159   away is a real pain - "Can you say set-window-configuration, boys
5160   and girls?"  Instead, we just assert at the beginning of redisplay
5161   that *all* scroll bars are to be removed, and then save a scroll bar
5162   from the fiery pit when we actually redisplay its window.  */
5163
5164/* Arrange for all scroll bars on FRAME to be removed at the next call
5165   to `*judge_scroll_bars_hook'.  A scroll bar may be spared if
5166   `*redeem_scroll_bar_hook' is applied to its window before the judgment.  */
5167
5168static void
5169XTcondemn_scroll_bars (frame)
5170     FRAME_PTR frame;
5171{
5172  /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS.  */
5173  while (! NILP (FRAME_SCROLL_BARS (frame)))
5174    {
5175      Lisp_Object bar;
5176      bar = FRAME_SCROLL_BARS (frame);
5177      FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
5178      XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
5179      XSCROLL_BAR (bar)->prev = Qnil;
5180      if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
5181	XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
5182      FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
5183    }
5184}
5185
5186
5187/* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
5188   Note that WINDOW isn't necessarily condemned at all.  */
5189
5190static void
5191XTredeem_scroll_bar (window)
5192     struct window *window;
5193{
5194  struct scroll_bar *bar;
5195  struct frame *f;
5196
5197  /* We can't redeem this window's scroll bar if it doesn't have one.  */
5198  if (NILP (window->vertical_scroll_bar))
5199    abort ();
5200
5201  bar = XSCROLL_BAR (window->vertical_scroll_bar);
5202
5203  /* Unlink it from the condemned list.  */
5204  f = XFRAME (WINDOW_FRAME (window));
5205  if (NILP (bar->prev))
5206    {
5207      /* If the prev pointer is nil, it must be the first in one of
5208	 the lists.  */
5209      if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
5210	/* It's not condemned.  Everything's fine.  */
5211	return;
5212      else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
5213		   window->vertical_scroll_bar))
5214	FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
5215      else
5216	/* If its prev pointer is nil, it must be at the front of
5217	   one or the other!  */
5218	abort ();
5219    }
5220  else
5221    XSCROLL_BAR (bar->prev)->next = bar->next;
5222
5223  if (! NILP (bar->next))
5224    XSCROLL_BAR (bar->next)->prev = bar->prev;
5225
5226  bar->next = FRAME_SCROLL_BARS (f);
5227  bar->prev = Qnil;
5228  XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
5229  if (! NILP (bar->next))
5230    XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
5231}
5232
5233/* Remove all scroll bars on FRAME that haven't been saved since the
5234   last call to `*condemn_scroll_bars_hook'.  */
5235
5236static void
5237XTjudge_scroll_bars (f)
5238     FRAME_PTR f;
5239{
5240  Lisp_Object bar, next;
5241
5242  bar = FRAME_CONDEMNED_SCROLL_BARS (f);
5243
5244  /* Clear out the condemned list now so we won't try to process any
5245     more events on the hapless scroll bars.  */
5246  FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
5247
5248  for (; ! NILP (bar); bar = next)
5249    {
5250      struct scroll_bar *b = XSCROLL_BAR (bar);
5251
5252      x_scroll_bar_remove (b);
5253
5254      next = b->next;
5255      b->next = b->prev = Qnil;
5256    }
5257
5258  /* Now there should be no references to the condemned scroll bars,
5259     and they should get garbage-collected.  */
5260}
5261
5262
5263#ifndef USE_TOOLKIT_SCROLL_BARS
5264/* Handle an Expose or GraphicsExpose event on a scroll bar.  This
5265   is a no-op when using toolkit scroll bars.
5266
5267   This may be called from a signal handler, so we have to ignore GC
5268   mark bits.  */
5269
5270static void
5271x_scroll_bar_expose (bar, event)
5272     struct scroll_bar *bar;
5273     XEvent *event;
5274{
5275  Window w = SCROLL_BAR_X_WINDOW (bar);
5276  FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5277  GC gc = f->output_data.x->normal_gc;
5278  int width_trim = VERTICAL_SCROLL_BAR_WIDTH_TRIM;
5279
5280  BLOCK_INPUT;
5281
5282  x_scroll_bar_set_handle (bar, XINT (bar->start), XINT (bar->end), 1);
5283
5284  /* Switch to scroll bar foreground color.  */
5285  if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5286    XSetForeground (FRAME_X_DISPLAY (f), gc,
5287 		    f->output_data.x->scroll_bar_foreground_pixel);
5288
5289  /* Draw a one-pixel border just inside the edges of the scroll bar.  */
5290  XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
5291
5292		  /* x, y, width, height */
5293		  0, 0,
5294		  XINT (bar->width) - 1 - width_trim - width_trim,
5295		  XINT (bar->height) - 1);
5296
5297   /* Restore the foreground color of the GC if we changed it above.  */
5298   if (f->output_data.x->scroll_bar_foreground_pixel != -1)
5299     XSetForeground (FRAME_X_DISPLAY (f), gc,
5300 		    f->output_data.x->foreground_pixel);
5301
5302   UNBLOCK_INPUT;
5303
5304}
5305#endif /* not USE_TOOLKIT_SCROLL_BARS */
5306
5307/* Handle a mouse click on the scroll bar BAR.  If *EMACS_EVENT's kind
5308   is set to something other than NO_EVENT, it is enqueued.
5309
5310   This may be called from a signal handler, so we have to ignore GC
5311   mark bits.  */
5312
5313
5314static void
5315x_scroll_bar_handle_click (bar, event, emacs_event)
5316     struct scroll_bar *bar;
5317     XEvent *event;
5318     struct input_event *emacs_event;
5319{
5320  if (! GC_WINDOWP (bar->window))
5321    abort ();
5322
5323  emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5324  emacs_event->code = event->xbutton.button - Button1;
5325  emacs_event->modifiers
5326    = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO
5327			       (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
5328			       event->xbutton.state)
5329       | (event->type == ButtonRelease
5330	  ? up_modifier
5331	  : down_modifier));
5332  emacs_event->frame_or_window = bar->window;
5333  emacs_event->arg = Qnil;
5334  emacs_event->timestamp = event->xbutton.time;
5335  {
5336#if 0
5337    FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5338    int internal_height
5339      = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, XINT (bar->height));
5340#endif
5341    int top_range
5342      = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
5343    int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
5344
5345    if (y < 0) y = 0;
5346    if (y > top_range) y = top_range;
5347
5348    if (y < XINT (bar->start))
5349      emacs_event->part = scroll_bar_above_handle;
5350    else if (y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5351      emacs_event->part = scroll_bar_handle;
5352    else
5353      emacs_event->part = scroll_bar_below_handle;
5354
5355    /* Just because the user has clicked on the handle doesn't mean
5356       they want to drag it.  Lisp code needs to be able to decide
5357       whether or not we're dragging.  */
5358#if 0
5359    /* If the user has just clicked on the handle, record where they're
5360       holding it.  */
5361    if (event->type == ButtonPress
5362	&& emacs_event->part == scroll_bar_handle)
5363      XSETINT (bar->dragging, y - XINT (bar->start));
5364#endif
5365
5366#ifndef USE_TOOLKIT_SCROLL_BARS
5367    /* If the user has released the handle, set it to its final position.  */
5368    if (event->type == ButtonRelease
5369	&& ! NILP (bar->dragging))
5370      {
5371	int new_start = y - XINT (bar->dragging);
5372	int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
5373
5374	x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5375	bar->dragging = Qnil;
5376      }
5377#endif
5378
5379    /* Same deal here as the other #if 0.  */
5380#if 0
5381    /* Clicks on the handle are always reported as occurring at the top of
5382       the handle.  */
5383    if (emacs_event->part == scroll_bar_handle)
5384      emacs_event->x = bar->start;
5385    else
5386      XSETINT (emacs_event->x, y);
5387#else
5388    XSETINT (emacs_event->x, y);
5389#endif
5390
5391    XSETINT (emacs_event->y, top_range);
5392  }
5393}
5394
5395#ifndef USE_TOOLKIT_SCROLL_BARS
5396
5397/* Handle some mouse motion while someone is dragging the scroll bar.
5398
5399   This may be called from a signal handler, so we have to ignore GC
5400   mark bits.  */
5401
5402static void
5403x_scroll_bar_note_movement (bar, event)
5404     struct scroll_bar *bar;
5405     XEvent *event;
5406{
5407  FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
5408
5409  last_mouse_movement_time = event->xmotion.time;
5410
5411  f->mouse_moved = 1;
5412  XSETVECTOR (last_mouse_scroll_bar, bar);
5413
5414  /* If we're dragging the bar, display it.  */
5415  if (! GC_NILP (bar->dragging))
5416    {
5417      /* Where should the handle be now?  */
5418      int new_start = event->xmotion.y - XINT (bar->dragging);
5419
5420      if (new_start != XINT (bar->start))
5421	{
5422	  int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
5423
5424	  x_scroll_bar_set_handle (bar, new_start, new_end, 0);
5425	}
5426    }
5427}
5428
5429#endif /* !USE_TOOLKIT_SCROLL_BARS */
5430
5431/* Return information to the user about the current position of the mouse
5432   on the scroll bar.  */
5433
5434static void
5435x_scroll_bar_report_motion (fp, bar_window, part, x, y, time)
5436     FRAME_PTR *fp;
5437     Lisp_Object *bar_window;
5438     enum scroll_bar_part *part;
5439     Lisp_Object *x, *y;
5440     unsigned long *time;
5441{
5442  struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
5443  Window w = SCROLL_BAR_X_WINDOW (bar);
5444  FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
5445  int win_x, win_y;
5446  Window dummy_window;
5447  int dummy_coord;
5448  unsigned int dummy_mask;
5449
5450  BLOCK_INPUT;
5451
5452  /* Get the mouse's position relative to the scroll bar window, and
5453     report that.  */
5454  if (! XQueryPointer (FRAME_X_DISPLAY (f), w,
5455
5456		       /* Root, child, root x and root y.  */
5457		       &dummy_window, &dummy_window,
5458		       &dummy_coord, &dummy_coord,
5459
5460		       /* Position relative to scroll bar.  */
5461		       &win_x, &win_y,
5462
5463		       /* Mouse buttons and modifier keys.  */
5464		       &dummy_mask))
5465    ;
5466  else
5467    {
5468#if 0
5469      int inside_height
5470	= VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, XINT (bar->height));
5471#endif
5472      int top_range
5473	= VERTICAL_SCROLL_BAR_TOP_RANGE     (f, XINT (bar->height));
5474
5475      win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
5476
5477      if (! NILP (bar->dragging))
5478	win_y -= XINT (bar->dragging);
5479
5480      if (win_y < 0)
5481	win_y = 0;
5482      if (win_y > top_range)
5483	win_y = top_range;
5484
5485      *fp = f;
5486      *bar_window = bar->window;
5487
5488      if (! NILP (bar->dragging))
5489	*part = scroll_bar_handle;
5490      else if (win_y < XINT (bar->start))
5491	*part = scroll_bar_above_handle;
5492      else if (win_y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
5493	*part = scroll_bar_handle;
5494      else
5495	*part = scroll_bar_below_handle;
5496
5497      XSETINT (*x, win_y);
5498      XSETINT (*y, top_range);
5499
5500      f->mouse_moved = 0;
5501      last_mouse_scroll_bar = Qnil;
5502    }
5503
5504  *time = last_mouse_movement_time;
5505
5506  UNBLOCK_INPUT;
5507}
5508
5509
5510/* The screen has been cleared so we may have changed foreground or
5511   background colors, and the scroll bars may need to be redrawn.
5512   Clear out the scroll bars, and ask for expose events, so we can
5513   redraw them.  */
5514
5515void
5516x_scroll_bar_clear (f)
5517     FRAME_PTR f;
5518{
5519#ifndef USE_TOOLKIT_SCROLL_BARS
5520  Lisp_Object bar;
5521
5522  /* We can have scroll bars even if this is 0,
5523     if we just turned off scroll bar mode.
5524     But in that case we should not clear them.  */
5525  if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
5526    for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
5527	 bar = XSCROLL_BAR (bar)->next)
5528      XClearArea (FRAME_X_DISPLAY (f),
5529		  SCROLL_BAR_X_WINDOW (XSCROLL_BAR (bar)),
5530		  0, 0, 0, 0, True);
5531#endif /* not USE_TOOLKIT_SCROLL_BARS */
5532}
5533
5534
5535/* The main X event-reading loop - XTread_socket.  */
5536
5537#if 0
5538/* Time stamp of enter window event.  This is only used by XTread_socket,
5539   but we have to put it out here, since static variables within functions
5540   sometimes don't work.  */
5541
5542static Time enter_timestamp;
5543#endif
5544
5545/* This holds the state XLookupString needs to implement dead keys
5546   and other tricks known as "compose processing".  _X Window System_
5547   says that a portable program can't use this, but Stephen Gildea assures
5548   me that letting the compiler initialize it to zeros will work okay.
5549
5550   This must be defined outside of XTread_socket, for the same reasons
5551   given for enter_timestamp, above.  */
5552
5553static XComposeStatus compose_status;
5554
5555/* Record the last 100 characters stored
5556   to help debug the loss-of-chars-during-GC problem.  */
5557
5558static int temp_index;
5559static short temp_buffer[100];
5560
5561#define STORE_KEYSYM_FOR_DEBUG(keysym)				\
5562  if (temp_index == sizeof temp_buffer / sizeof (short))	\
5563    temp_index = 0;						\
5564  temp_buffer[temp_index++] = (keysym)
5565
5566/* Set this to nonzero to fake an "X I/O error"
5567   on a particular display.  */
5568
5569struct x_display_info *XTread_socket_fake_io_error;
5570
5571/* When we find no input here, we occasionally do a no-op command
5572   to verify that the X server is still running and we can still talk with it.
5573   We try all the open displays, one by one.
5574   This variable is used for cycling thru the displays.  */
5575
5576static struct x_display_info *next_noop_dpyinfo;
5577
5578#define SET_SAVED_MENU_EVENT(size)					\
5579     do									\
5580       {								\
5581	 if (f->output_data.x->saved_menu_event == 0)			\
5582           f->output_data.x->saved_menu_event				\
5583	     = (XEvent *) xmalloc (sizeof (XEvent));			\
5584         bcopy (&event, f->output_data.x->saved_menu_event, size);	\
5585	 inev.ie.kind = MENU_BAR_ACTIVATE_EVENT;			\
5586	 XSETFRAME (inev.ie.frame_or_window, f);			\
5587       }								\
5588     while (0)
5589
5590#define SET_SAVED_BUTTON_EVENT SET_SAVED_MENU_EVENT (sizeof (XButtonEvent))
5591#define SET_SAVED_KEY_EVENT    SET_SAVED_MENU_EVENT (sizeof (XKeyEvent))
5592
5593
5594enum
5595{
5596  X_EVENT_NORMAL,
5597  X_EVENT_GOTO_OUT,
5598  X_EVENT_DROP
5599};
5600
5601/* Filter events for the current X input method.
5602   DPYINFO is the display this event is for.
5603   EVENT is the X event to filter.
5604
5605   Returns non-zero if the event was filtered, caller shall not process
5606   this event further.
5607   Returns zero if event is wasn't filtered.  */
5608
5609#ifdef HAVE_X_I18N
5610static int
5611x_filter_event (dpyinfo, event)
5612     struct x_display_info *dpyinfo;
5613     XEvent *event;
5614{
5615  /* XFilterEvent returns non-zero if the input method has
5616   consumed the event.  We pass the frame's X window to
5617   XFilterEvent because that's the one for which the IC
5618   was created.  */
5619
5620  struct frame *f1 = x_any_window_to_frame (dpyinfo,
5621                                            event->xclient.window);
5622
5623  return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
5624}
5625#endif
5626
5627#ifdef USE_GTK
5628static int current_count;
5629static int current_finish;
5630static struct input_event *current_hold_quit;
5631
5632/* This is the filter function invoked by the GTK event loop.
5633   It is invoked before the XEvent is translated to a GdkEvent,
5634   so we have a chance to act on the event before GTK. */
5635static GdkFilterReturn
5636event_handler_gdk (gxev, ev, data)
5637     GdkXEvent *gxev;
5638     GdkEvent *ev;
5639     gpointer data;
5640{
5641  XEvent *xev = (XEvent *) gxev;
5642
5643  if (current_count >= 0)
5644    {
5645      struct x_display_info *dpyinfo;
5646
5647      dpyinfo = x_display_info_for_display (xev->xany.display);
5648
5649#ifdef HAVE_X_I18N
5650      /* Filter events for the current X input method.
5651         GTK calls XFilterEvent but not for key press and release,
5652         so we do it here.  */
5653      if (xev->type == KeyPress || xev->type == KeyRelease)
5654        if (dpyinfo && x_filter_event (dpyinfo, xev))
5655          return GDK_FILTER_REMOVE;
5656#endif
5657
5658      if (! dpyinfo)
5659        current_finish = X_EVENT_NORMAL;
5660      else
5661	{
5662	  current_count +=
5663	    handle_one_xevent (dpyinfo, xev, &current_finish,
5664			       current_hold_quit);
5665	}
5666    }
5667  else
5668    current_finish = x_dispatch_event (xev, xev->xany.display);
5669
5670  if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
5671    return GDK_FILTER_REMOVE;
5672
5673  return GDK_FILTER_CONTINUE;
5674}
5675#endif /* USE_GTK */
5676
5677
5678/* Handles the XEvent EVENT on display DPYINFO.
5679
5680   *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
5681   *FINISH is zero if caller should continue reading events.
5682   *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
5683
5684   We return the number of characters stored into the buffer. */
5685
5686static int
5687handle_one_xevent (dpyinfo, eventp, finish, hold_quit)
5688     struct x_display_info *dpyinfo;
5689     XEvent *eventp;
5690     int *finish;
5691     struct input_event *hold_quit;
5692{
5693  union {
5694    struct input_event ie;
5695    struct selection_input_event sie;
5696  } inev;
5697  int count = 0;
5698  int do_help = 0;
5699  int nbytes = 0;
5700  struct frame *f;
5701  struct coding_system coding;
5702  XEvent event = *eventp;
5703
5704  *finish = X_EVENT_NORMAL;
5705
5706  EVENT_INIT (inev.ie);
5707  inev.ie.kind = NO_EVENT;
5708  inev.ie.arg = Qnil;
5709
5710  switch (event.type)
5711    {
5712    case ClientMessage:
5713      {
5714        if (event.xclient.message_type
5715            == dpyinfo->Xatom_wm_protocols
5716            && event.xclient.format == 32)
5717          {
5718            if (event.xclient.data.l[0]
5719                == dpyinfo->Xatom_wm_take_focus)
5720              {
5721                /* Use x_any_window_to_frame because this
5722                   could be the shell widget window
5723                   if the frame has no title bar.  */
5724                f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5725#ifdef HAVE_X_I18N
5726                /* Not quite sure this is needed -pd */
5727                if (f && FRAME_XIC (f))
5728                  XSetICFocus (FRAME_XIC (f));
5729#endif
5730#if 0 /* Emacs sets WM hints whose `input' field is `true'.  This
5731	 instructs the WM to set the input focus automatically for
5732	 Emacs with a call to XSetInputFocus.  Setting WM_TAKE_FOCUS
5733	 tells the WM to send us a ClientMessage WM_TAKE_FOCUS after
5734	 it has set the focus.  So, XSetInputFocus below is not
5735	 needed.
5736
5737	 The call to XSetInputFocus below has also caused trouble.  In
5738	 cases where the XSetInputFocus done by the WM and the one
5739	 below are temporally close (on a fast machine), the call
5740	 below can generate additional FocusIn events which confuse
5741	 Emacs.  */
5742
5743                /* Since we set WM_TAKE_FOCUS, we must call
5744                   XSetInputFocus explicitly.  But not if f is null,
5745                   since that might be an event for a deleted frame.  */
5746                if (f)
5747                  {
5748                    Display *d = event.xclient.display;
5749                    /* Catch and ignore errors, in case window has been
5750                       iconified by a window manager such as GWM.  */
5751                    x_catch_errors (d);
5752                    XSetInputFocus (d, event.xclient.window,
5753                                    /* The ICCCM says this is
5754                                       the only valid choice.  */
5755                                    RevertToParent,
5756                                    event.xclient.data.l[1]);
5757                    /* This is needed to detect the error
5758                       if there is an error.  */
5759                    XSync (d, False);
5760                    x_uncatch_errors ();
5761                  }
5762                /* Not certain about handling scroll bars here */
5763#endif /* 0 */
5764		goto done;
5765              }
5766
5767            if (event.xclient.data.l[0]
5768                     == dpyinfo->Xatom_wm_save_yourself)
5769              {
5770                /* Save state modify the WM_COMMAND property to
5771                   something which can reinstate us.  This notifies
5772                   the session manager, who's looking for such a
5773                   PropertyNotify.  Can restart processing when
5774                   a keyboard or mouse event arrives.  */
5775                /* If we have a session manager, don't set this.
5776                   KDE will then start two Emacsen, one for the
5777                   session manager and one for this. */
5778#ifdef HAVE_X_SM
5779                if (! x_session_have_connection ())
5780#endif
5781                  {
5782                    f = x_top_window_to_frame (dpyinfo,
5783                                               event.xclient.window);
5784                    /* This is just so we only give real data once
5785                       for a single Emacs process.  */
5786                    if (f == SELECTED_FRAME ())
5787                      XSetCommand (FRAME_X_DISPLAY (f),
5788                                   event.xclient.window,
5789                                   initial_argv, initial_argc);
5790                    else if (f)
5791                      XSetCommand (FRAME_X_DISPLAY (f),
5792                                   event.xclient.window,
5793                                   0, 0);
5794                  }
5795		goto done;
5796              }
5797
5798            if (event.xclient.data.l[0]
5799		== dpyinfo->Xatom_wm_delete_window)
5800              {
5801                f = x_any_window_to_frame (dpyinfo,
5802                                           event.xclient.window);
5803                if (!f)
5804		  goto OTHER; /* May be a dialog that is to be removed  */
5805
5806		inev.ie.kind = DELETE_WINDOW_EVENT;
5807		XSETFRAME (inev.ie.frame_or_window, f);
5808		goto done;
5809              }
5810
5811	    goto done;
5812          }
5813
5814        if (event.xclient.message_type
5815                 == dpyinfo->Xatom_wm_configure_denied)
5816          {
5817	    goto done;
5818          }
5819
5820        if (event.xclient.message_type
5821	    == dpyinfo->Xatom_wm_window_moved)
5822          {
5823            int new_x, new_y;
5824	    f = x_window_to_frame (dpyinfo, event.xclient.window);
5825
5826            new_x = event.xclient.data.s[0];
5827            new_y = event.xclient.data.s[1];
5828
5829            if (f)
5830              {
5831                f->left_pos = new_x;
5832                f->top_pos = new_y;
5833              }
5834	    goto done;
5835          }
5836
5837#ifdef HACK_EDITRES
5838        if (event.xclient.message_type
5839	    == dpyinfo->Xatom_editres)
5840          {
5841	    f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5842	    if (f)
5843              _XEditResCheckMessages (f->output_data.x->widget, NULL,
5844                                      &event, NULL);
5845	    goto done;
5846          }
5847#endif /* HACK_EDITRES */
5848
5849        if ((event.xclient.message_type
5850	     == dpyinfo->Xatom_DONE)
5851	    || (event.xclient.message_type
5852		== dpyinfo->Xatom_PAGE))
5853          {
5854            /* Ghostview job completed.  Kill it.  We could
5855               reply with "Next" if we received "Page", but we
5856               currently never do because we are interested in
5857               images, only, which should have 1 page.  */
5858            Pixmap pixmap = (Pixmap) event.xclient.data.l[1];
5859	    f = x_window_to_frame (dpyinfo, event.xclient.window);
5860	    if (!f)
5861	      goto OTHER;
5862            x_kill_gs_process (pixmap, f);
5863            expose_frame (f, 0, 0, 0, 0);
5864	    goto done;
5865          }
5866
5867#ifdef USE_TOOLKIT_SCROLL_BARS
5868        /* Scroll bar callbacks send a ClientMessage from which
5869           we construct an input_event.  */
5870        if (event.xclient.message_type
5871	    == dpyinfo->Xatom_Scrollbar)
5872          {
5873            x_scroll_bar_to_input_event (&event, &inev.ie);
5874	    *finish = X_EVENT_GOTO_OUT;
5875            goto done;
5876          }
5877#endif /* USE_TOOLKIT_SCROLL_BARS */
5878
5879	f = x_any_window_to_frame (dpyinfo, event.xclient.window);
5880	if (!f)
5881	  goto OTHER;
5882	if (x_handle_dnd_message (f, &event.xclient, dpyinfo, &inev.ie))
5883	  *finish = X_EVENT_DROP;
5884      }
5885      break;
5886
5887    case SelectionNotify:
5888      last_user_time = event.xselection.time;
5889#ifdef USE_X_TOOLKIT
5890      if (! x_window_to_frame (dpyinfo, event.xselection.requestor))
5891        goto OTHER;
5892#endif /* not USE_X_TOOLKIT */
5893      x_handle_selection_notify (&event.xselection);
5894      break;
5895
5896    case SelectionClear:	/* Someone has grabbed ownership.  */
5897      last_user_time = event.xselectionclear.time;
5898#ifdef USE_X_TOOLKIT
5899      if (! x_window_to_frame (dpyinfo, event.xselectionclear.window))
5900        goto OTHER;
5901#endif /* USE_X_TOOLKIT */
5902      {
5903        XSelectionClearEvent *eventp = (XSelectionClearEvent *) &event;
5904
5905        inev.ie.kind = SELECTION_CLEAR_EVENT;
5906        SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
5907        SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
5908        SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
5909        inev.ie.frame_or_window = Qnil;
5910      }
5911      break;
5912
5913    case SelectionRequest:	/* Someone wants our selection.  */
5914      last_user_time = event.xselectionrequest.time;
5915#ifdef USE_X_TOOLKIT
5916      if (!x_window_to_frame (dpyinfo, event.xselectionrequest.owner))
5917        goto OTHER;
5918#endif /* USE_X_TOOLKIT */
5919      {
5920          XSelectionRequestEvent *eventp
5921            = (XSelectionRequestEvent *) &event;
5922
5923          inev.ie.kind = SELECTION_REQUEST_EVENT;
5924          SELECTION_EVENT_DISPLAY (&inev.sie) = eventp->display;
5925          SELECTION_EVENT_REQUESTOR (&inev.sie) = eventp->requestor;
5926          SELECTION_EVENT_SELECTION (&inev.sie) = eventp->selection;
5927          SELECTION_EVENT_TARGET (&inev.sie) = eventp->target;
5928          SELECTION_EVENT_PROPERTY (&inev.sie) = eventp->property;
5929          SELECTION_EVENT_TIME (&inev.sie) = eventp->time;
5930          inev.ie.frame_or_window = Qnil;
5931      }
5932      break;
5933
5934    case PropertyNotify:
5935      last_user_time = event.xproperty.time;
5936#if 0 /* This is plain wrong.  In the case that we are waiting for a
5937	 PropertyNotify used as an ACK in incremental selection
5938	 transfer, the property will be on the receiver's window.  */
5939#if defined USE_X_TOOLKIT
5940      if (!x_any_window_to_frame (dpyinfo, event.xproperty.window))
5941        goto OTHER;
5942#endif
5943#endif
5944      x_handle_property_notify (&event.xproperty);
5945      goto OTHER;
5946
5947    case ReparentNotify:
5948      f = x_top_window_to_frame (dpyinfo, event.xreparent.window);
5949      if (f)
5950        {
5951          int x, y;
5952          f->output_data.x->parent_desc = event.xreparent.parent;
5953          x_real_positions (f, &x, &y);
5954          f->left_pos = x;
5955          f->top_pos = y;
5956
5957          /* Perhaps reparented due to a WM restart.  Reset this.  */
5958          FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_UNKNOWN;
5959          FRAME_X_DISPLAY_INFO (f)->net_supported_window = 0;
5960        }
5961      goto OTHER;
5962
5963    case Expose:
5964      f = x_window_to_frame (dpyinfo, event.xexpose.window);
5965      if (f)
5966        {
5967          x_check_fullscreen (f);
5968
5969#ifdef USE_GTK
5970          /* This seems to be needed for GTK 2.6.  */
5971          x_clear_area (event.xexpose.display,
5972                        event.xexpose.window,
5973                        event.xexpose.x, event.xexpose.y,
5974                        event.xexpose.width, event.xexpose.height,
5975                        FALSE);
5976#endif
5977          if (f->async_visible == 0)
5978            {
5979              f->async_visible = 1;
5980              f->async_iconified = 0;
5981              f->output_data.x->has_been_visible = 1;
5982              SET_FRAME_GARBAGED (f);
5983            }
5984          else
5985            expose_frame (f,
5986			  event.xexpose.x, event.xexpose.y,
5987                          event.xexpose.width, event.xexpose.height);
5988        }
5989      else
5990        {
5991#ifndef USE_TOOLKIT_SCROLL_BARS
5992          struct scroll_bar *bar;
5993#endif
5994#if defined USE_LUCID
5995          /* Submenus of the Lucid menu bar aren't widgets
5996             themselves, so there's no way to dispatch events
5997             to them.  Recognize this case separately.  */
5998          {
5999            Widget widget
6000              = x_window_to_menu_bar (event.xexpose.window);
6001            if (widget)
6002              xlwmenu_redisplay (widget);
6003          }
6004#endif /* USE_LUCID */
6005
6006#ifdef USE_TOOLKIT_SCROLL_BARS
6007          /* Dispatch event to the widget.  */
6008          goto OTHER;
6009#else /* not USE_TOOLKIT_SCROLL_BARS */
6010          bar = x_window_to_scroll_bar (event.xexpose.display,
6011                                        event.xexpose.window);
6012
6013          if (bar)
6014            x_scroll_bar_expose (bar, &event);
6015#ifdef USE_X_TOOLKIT
6016          else
6017            goto OTHER;
6018#endif /* USE_X_TOOLKIT */
6019#endif /* not USE_TOOLKIT_SCROLL_BARS */
6020        }
6021      break;
6022
6023    case GraphicsExpose:	/* This occurs when an XCopyArea's
6024                                   source area was obscured or not
6025                                   available.  */
6026      f = x_window_to_frame (dpyinfo, event.xgraphicsexpose.drawable);
6027      if (f)
6028        {
6029          expose_frame (f,
6030                        event.xgraphicsexpose.x, event.xgraphicsexpose.y,
6031                        event.xgraphicsexpose.width,
6032                        event.xgraphicsexpose.height);
6033        }
6034#ifdef USE_X_TOOLKIT
6035      else
6036        goto OTHER;
6037#endif /* USE_X_TOOLKIT */
6038      break;
6039
6040    case NoExpose:		/* This occurs when an XCopyArea's
6041                                   source area was completely
6042                                   available.  */
6043      break;
6044
6045    case UnmapNotify:
6046      /* Redo the mouse-highlight after the tooltip has gone.  */
6047      if (event.xmap.window == tip_window)
6048        {
6049          tip_window = 0;
6050          redo_mouse_highlight ();
6051        }
6052
6053      f = x_top_window_to_frame (dpyinfo, event.xunmap.window);
6054      if (f)		/* F may no longer exist if
6055                           the frame was deleted.  */
6056        {
6057          /* While a frame is unmapped, display generation is
6058             disabled; you don't want to spend time updating a
6059             display that won't ever be seen.  */
6060          f->async_visible = 0;
6061          /* We can't distinguish, from the event, whether the window
6062             has become iconified or invisible.  So assume, if it
6063             was previously visible, than now it is iconified.
6064             But x_make_frame_invisible clears both
6065             the visible flag and the iconified flag;
6066             and that way, we know the window is not iconified now.  */
6067          if (FRAME_VISIBLE_P (f) || FRAME_ICONIFIED_P (f))
6068            {
6069              f->async_iconified = 1;
6070
6071              inev.ie.kind = ICONIFY_EVENT;
6072              XSETFRAME (inev.ie.frame_or_window, f);
6073            }
6074        }
6075      goto OTHER;
6076
6077    case MapNotify:
6078      if (event.xmap.window == tip_window)
6079        /* The tooltip has been drawn already.  Avoid
6080           the SET_FRAME_GARBAGED below.  */
6081        goto OTHER;
6082
6083      /* We use x_top_window_to_frame because map events can
6084         come for sub-windows and they don't mean that the
6085         frame is visible.  */
6086      f = x_top_window_to_frame (dpyinfo, event.xmap.window);
6087      if (f)
6088        {
6089          /* wait_reading_process_output will notice this and update
6090             the frame's display structures.
6091             If we where iconified, we should not set garbaged,
6092             because that stops redrawing on Expose events.  This looks
6093             bad if we are called from a recursive event loop
6094             (x_dispatch_event), for example when a dialog is up.  */
6095          if (! f->async_iconified)
6096            SET_FRAME_GARBAGED (f);
6097
6098          f->async_visible = 1;
6099          f->async_iconified = 0;
6100          f->output_data.x->has_been_visible = 1;
6101
6102          if (f->iconified)
6103            {
6104              inev.ie.kind = DEICONIFY_EVENT;
6105              XSETFRAME (inev.ie.frame_or_window, f);
6106            }
6107          else if (! NILP (Vframe_list)
6108                   && ! NILP (XCDR (Vframe_list)))
6109            /* Force a redisplay sooner or later
6110               to update the frame titles
6111               in case this is the second frame.  */
6112            record_asynch_buffer_change ();
6113        }
6114      goto OTHER;
6115
6116    case KeyPress:
6117
6118      last_user_time = event.xkey.time;
6119      ignore_next_mouse_click_timeout = 0;
6120
6121#if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6122      /* Dispatch KeyPress events when in menu.  */
6123      if (popup_activated ())
6124        goto OTHER;
6125#endif
6126
6127      f = x_any_window_to_frame (dpyinfo, event.xkey.window);
6128
6129      /* If mouse-highlight is an integer, input clears out
6130	 mouse highlighting.  */
6131      if (!dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight)
6132	  && (f == 0
6133	      || !EQ (f->tool_bar_window, dpyinfo->mouse_face_window)))
6134        {
6135          clear_mouse_face (dpyinfo);
6136          dpyinfo->mouse_face_hidden = 1;
6137        }
6138
6139#if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
6140      if (f == 0)
6141        {
6142          /* Scroll bars consume key events, but we want
6143             the keys to go to the scroll bar's frame.  */
6144          Widget widget = XtWindowToWidget (dpyinfo->display,
6145                                            event.xkey.window);
6146          if (widget && XmIsScrollBar (widget))
6147            {
6148              widget = XtParent (widget);
6149              f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
6150            }
6151        }
6152#endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
6153
6154      if (f != 0)
6155        {
6156          KeySym keysym, orig_keysym;
6157          /* al%imercury@uunet.uu.net says that making this 81
6158             instead of 80 fixed a bug whereby meta chars made
6159             his Emacs hang.
6160
6161             It seems that some version of XmbLookupString has
6162             a bug of not returning XBufferOverflow in
6163             status_return even if the input is too long to
6164             fit in 81 bytes.  So, we must prepare sufficient
6165             bytes for copy_buffer.  513 bytes (256 chars for
6166             two-byte character set) seems to be a fairly good
6167             approximation.  -- 2000.8.10 handa@etl.go.jp  */
6168          unsigned char copy_buffer[513];
6169          unsigned char *copy_bufptr = copy_buffer;
6170          int copy_bufsiz = sizeof (copy_buffer);
6171          int modifiers;
6172          Lisp_Object coding_system = Qlatin_1;
6173	  Lisp_Object c;
6174
6175#ifdef USE_GTK
6176          /* Don't pass keys to GTK.  A Tab will shift focus to the
6177             tool bar in GTK 2.4.  Keys will still go to menus and
6178             dialogs because in that case popup_activated is TRUE
6179             (see above).  */
6180          *finish = X_EVENT_DROP;
6181#endif
6182
6183          event.xkey.state
6184            |= x_emacs_to_x_modifiers (FRAME_X_DISPLAY_INFO (f),
6185                                       extra_keyboard_modifiers);
6186          modifiers = event.xkey.state;
6187
6188          /* This will have to go some day...  */
6189
6190          /* make_lispy_event turns chars into control chars.
6191             Don't do it here because XLookupString is too eager.  */
6192          event.xkey.state &= ~ControlMask;
6193          event.xkey.state &= ~(dpyinfo->meta_mod_mask
6194                                | dpyinfo->super_mod_mask
6195                                | dpyinfo->hyper_mod_mask
6196                                | dpyinfo->alt_mod_mask);
6197
6198          /* In case Meta is ComposeCharacter,
6199             clear its status.  According to Markus Ehrnsperger
6200             Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
6201             this enables ComposeCharacter to work whether or
6202             not it is combined with Meta.  */
6203          if (modifiers & dpyinfo->meta_mod_mask)
6204            bzero (&compose_status, sizeof (compose_status));
6205
6206#ifdef HAVE_X_I18N
6207          if (FRAME_XIC (f))
6208            {
6209              Status status_return;
6210
6211              coding_system = Vlocale_coding_system;
6212              nbytes = XmbLookupString (FRAME_XIC (f),
6213                                        &event.xkey, copy_bufptr,
6214                                        copy_bufsiz, &keysym,
6215                                        &status_return);
6216              if (status_return == XBufferOverflow)
6217                {
6218                  copy_bufsiz = nbytes + 1;
6219                  copy_bufptr = (unsigned char *) alloca (copy_bufsiz);
6220                  nbytes = XmbLookupString (FRAME_XIC (f),
6221                                            &event.xkey, copy_bufptr,
6222                                            copy_bufsiz, &keysym,
6223                                            &status_return);
6224                }
6225              /* Xutf8LookupString is a new but already deprecated interface.  -stef  */
6226#if 0 && defined X_HAVE_UTF8_STRING
6227              else if (status_return == XLookupKeySym)
6228                {  /* Try again but with utf-8.  */
6229                  coding_system = Qutf_8;
6230                  nbytes = Xutf8LookupString (FRAME_XIC (f),
6231                                              &event.xkey, copy_bufptr,
6232                                              copy_bufsiz, &keysym,
6233                                              &status_return);
6234                  if (status_return == XBufferOverflow)
6235                    {
6236                      copy_bufsiz = nbytes + 1;
6237                      copy_bufptr = (unsigned char *) alloca (copy_bufsiz);
6238                      nbytes = Xutf8LookupString (FRAME_XIC (f),
6239                                                  &event.xkey,
6240                                                  copy_bufptr,
6241                                                  copy_bufsiz, &keysym,
6242                                                  &status_return);
6243                    }
6244                }
6245#endif
6246
6247              if (status_return == XLookupNone)
6248                break;
6249              else if (status_return == XLookupChars)
6250                {
6251                  keysym = NoSymbol;
6252                  modifiers = 0;
6253                }
6254              else if (status_return != XLookupKeySym
6255                       && status_return != XLookupBoth)
6256                abort ();
6257            }
6258          else
6259            nbytes = XLookupString (&event.xkey, copy_bufptr,
6260                                    copy_bufsiz, &keysym,
6261                                    &compose_status);
6262#else
6263          nbytes = XLookupString (&event.xkey, copy_bufptr,
6264                                  copy_bufsiz, &keysym,
6265                                  &compose_status);
6266#endif
6267
6268          /* If not using XIM/XIC, and a compose sequence is in progress,
6269             we break here.  Otherwise, chars_matched is always 0.  */
6270          if (compose_status.chars_matched > 0 && nbytes == 0)
6271            break;
6272
6273          bzero (&compose_status, sizeof (compose_status));
6274          orig_keysym = keysym;
6275
6276	  /* Common for all keysym input events.  */
6277	  XSETFRAME (inev.ie.frame_or_window, f);
6278	  inev.ie.modifiers
6279	    = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f), modifiers);
6280	  inev.ie.timestamp = event.xkey.time;
6281
6282	  /* First deal with keysyms which have defined
6283	     translations to characters.  */
6284	  if (keysym >= 32 && keysym < 128)
6285	    /* Avoid explicitly decoding each ASCII character.  */
6286	    {
6287	      inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6288	      inev.ie.code = keysym;
6289	      goto done_keysym;
6290	    }
6291
6292	  /* Keysyms directly mapped to supported Unicode characters.  */
6293	  if ((keysym >= 0x01000000 && keysym <= 0x010033ff)
6294	      || (keysym >= 0x0100e000 && keysym <= 0x0100ffff))
6295	    {
6296	      int code = keysym & 0xFFFF, charset_id, c1, c2;
6297
6298	      if (code < 0x80)
6299		{
6300		  inev.ie.kind = ASCII_KEYSTROKE_EVENT;
6301		  inev.ie.code = code;
6302		}
6303	      else if (code < 0x100)
6304		{
6305		  if (code < 0xA0)
6306		    charset_id = CHARSET_8_BIT_CONTROL;
6307		  else
6308		    charset_id = charset_latin_iso8859_1;
6309		  inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
6310		  inev.ie.code = MAKE_CHAR (charset_id, code, 0);
6311		}
6312	      else
6313		{
6314		  if (code < 0x2500)
6315		    charset_id = charset_mule_unicode_0100_24ff,
6316		      code -= 0x100;
6317		  else if (code < 0xE000)
6318		    charset_id = charset_mule_unicode_2500_33ff,
6319		      code -= 0x2500;
6320		  else
6321		    charset_id = charset_mule_unicode_e000_ffff,
6322		      code -= 0xE000;
6323		  c1 = (code / 96) + 32, c2 = (code % 96) + 32;
6324		  inev.ie.kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
6325		  inev.ie.code = MAKE_CHAR (charset_id, c1, c2);
6326		}
6327	      goto done_keysym;
6328	    }
6329
6330	  /* Now non-ASCII.  */
6331	  if (HASH_TABLE_P (Vx_keysym_table)
6332	      && (NATNUMP (c = Fgethash (make_number (keysym),
6333					 Vx_keysym_table,
6334					 Qnil))))
6335	    {
6336	      inev.ie.kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
6337			      ? ASCII_KEYSTROKE_EVENT
6338			      : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6339	      inev.ie.code = XFASTINT (c);
6340	      goto done_keysym;
6341	    }
6342
6343	  /* Random non-modifier sorts of keysyms.  */
6344	  if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
6345                        || keysym == XK_Delete
6346#ifdef XK_ISO_Left_Tab
6347                        || (keysym >= XK_ISO_Left_Tab
6348                            && keysym <= XK_ISO_Enter)
6349#endif
6350                        || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
6351                        || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
6352#ifdef HPUX
6353                        /* This recognizes the "extended function
6354                           keys".  It seems there's no cleaner way.
6355                           Test IsModifierKey to avoid handling
6356                           mode_switch incorrectly.  */
6357                        || ((unsigned) (keysym) >= XK_Select
6358                            && (unsigned)(keysym) < XK_KP_Space)
6359#endif
6360#ifdef XK_dead_circumflex
6361                        || orig_keysym == XK_dead_circumflex
6362#endif
6363#ifdef XK_dead_grave
6364                        || orig_keysym == XK_dead_grave
6365#endif
6366#ifdef XK_dead_tilde
6367                        || orig_keysym == XK_dead_tilde
6368#endif
6369#ifdef XK_dead_diaeresis
6370                        || orig_keysym == XK_dead_diaeresis
6371#endif
6372#ifdef XK_dead_macron
6373                        || orig_keysym == XK_dead_macron
6374#endif
6375#ifdef XK_dead_degree
6376                        || orig_keysym == XK_dead_degree
6377#endif
6378#ifdef XK_dead_acute
6379                        || orig_keysym == XK_dead_acute
6380#endif
6381#ifdef XK_dead_cedilla
6382                        || orig_keysym == XK_dead_cedilla
6383#endif
6384#ifdef XK_dead_breve
6385                        || orig_keysym == XK_dead_breve
6386#endif
6387#ifdef XK_dead_ogonek
6388                        || orig_keysym == XK_dead_ogonek
6389#endif
6390#ifdef XK_dead_caron
6391                        || orig_keysym == XK_dead_caron
6392#endif
6393#ifdef XK_dead_doubleacute
6394                        || orig_keysym == XK_dead_doubleacute
6395#endif
6396#ifdef XK_dead_abovedot
6397                        || orig_keysym == XK_dead_abovedot
6398#endif
6399                        || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
6400                        || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
6401                        /* Any "vendor-specific" key is ok.  */
6402                        || (orig_keysym & (1 << 28))
6403                        || (keysym != NoSymbol && nbytes == 0))
6404                       && ! (IsModifierKey (orig_keysym)
6405#ifndef HAVE_X11R5
6406#ifdef XK_Mode_switch
6407                             || ((unsigned)(orig_keysym) == XK_Mode_switch)
6408#endif
6409#ifdef XK_Num_Lock
6410                             || ((unsigned)(orig_keysym) == XK_Num_Lock)
6411#endif
6412#endif /* not HAVE_X11R5 */
6413                             /* The symbols from XK_ISO_Lock
6414                                to XK_ISO_Last_Group_Lock
6415                                don't have real modifiers but
6416                                should be treated similarly to
6417                                Mode_switch by Emacs. */
6418#if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
6419                             || ((unsigned)(orig_keysym)
6420                                 >=  XK_ISO_Lock
6421                                 && (unsigned)(orig_keysym)
6422                                 <= XK_ISO_Last_Group_Lock)
6423#endif
6424                             ))
6425	    {
6426	      STORE_KEYSYM_FOR_DEBUG (keysym);
6427	      /* make_lispy_event will convert this to a symbolic
6428		 key.  */
6429	      inev.ie.kind = NON_ASCII_KEYSTROKE_EVENT;
6430	      inev.ie.code = keysym;
6431	      goto done_keysym;
6432	    }
6433
6434	  {	/* Raw bytes, not keysym.  */
6435	    register int i;
6436	    register int c;
6437	    int nchars, len;
6438
6439	    /* The input should be decoded with `coding_system'
6440	       which depends on which X*LookupString function
6441	       we used just above and the locale.  */
6442	    setup_coding_system (coding_system, &coding);
6443	    coding.src_multibyte = 0;
6444	    coding.dst_multibyte = 1;
6445	    /* The input is converted to events, thus we can't
6446	       handle composition.  Anyway, there's no XIM that
6447	       gives us composition information.  */
6448	    coding.composing = COMPOSITION_DISABLED;
6449
6450	    for (i = 0; i < nbytes; i++)
6451	      {
6452		STORE_KEYSYM_FOR_DEBUG (copy_bufptr[i]);
6453	      }
6454
6455	    {
6456	      /* Decode the input data.  */
6457	      int require;
6458	      unsigned char *p;
6459
6460	      require = decoding_buffer_size (&coding, nbytes);
6461	      p = (unsigned char *) alloca (require);
6462	      coding.mode |= CODING_MODE_LAST_BLOCK;
6463	      /* We explicitly disable composition handling because
6464		 key data should not contain any composition sequence.  */
6465	      coding.composing = COMPOSITION_DISABLED;
6466	      decode_coding (&coding, copy_bufptr, p, nbytes, require);
6467	      nbytes = coding.produced;
6468	      nchars = coding.produced_char;
6469	      copy_bufptr = p;
6470	    }
6471
6472	    /* Convert the input data to a sequence of
6473	       character events.  */
6474	    for (i = 0; i < nbytes; i += len)
6475	      {
6476		if (nchars == nbytes)
6477		  c = copy_bufptr[i], len = 1;
6478		else
6479		  c = STRING_CHAR_AND_LENGTH (copy_bufptr + i,
6480					      nbytes - i, len);
6481		inev.ie.kind = (SINGLE_BYTE_CHAR_P (c)
6482			      ? ASCII_KEYSTROKE_EVENT
6483			      : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
6484		inev.ie.code = c;
6485		kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6486	      }
6487
6488	    /* Previous code updated count by nchars rather than nbytes,
6489	       but that seems bogus to me.  ++kfs  */
6490	    count += nbytes;
6491
6492	    inev.ie.kind = NO_EVENT;  /* Already stored above.  */
6493
6494	    if (keysym == NoSymbol)
6495	      break;
6496	  }
6497        }
6498    done_keysym:
6499#ifdef HAVE_X_I18N
6500      /* Don't dispatch this event since XtDispatchEvent calls
6501         XFilterEvent, and two calls in a row may freeze the
6502         client.  */
6503      break;
6504#else
6505      goto OTHER;
6506#endif
6507
6508    case KeyRelease:
6509      last_user_time = event.xkey.time;
6510#ifdef HAVE_X_I18N
6511      /* Don't dispatch this event since XtDispatchEvent calls
6512         XFilterEvent, and two calls in a row may freeze the
6513         client.  */
6514      break;
6515#else
6516      goto OTHER;
6517#endif
6518
6519    case EnterNotify:
6520      last_user_time = event.xcrossing.time;
6521      x_detect_focus_change (dpyinfo, &event, &inev.ie);
6522
6523      f = x_any_window_to_frame (dpyinfo, event.xcrossing.window);
6524
6525      if (f && x_mouse_click_focus_ignore_position)
6526	ignore_next_mouse_click_timeout = event.xmotion.time + 200;
6527
6528#if 0
6529      if (event.xcrossing.focus)
6530	{
6531	  /* Avoid nasty pop/raise loops.  */
6532	  if (f && (!(f->auto_raise)
6533		    || !(f->auto_lower)
6534		    || (event.xcrossing.time - enter_timestamp) > 500))
6535	    {
6536	      x_new_focus_frame (dpyinfo, f);
6537	      enter_timestamp = event.xcrossing.time;
6538	    }
6539	}
6540      else if (f == dpyinfo->x_focus_frame)
6541	x_new_focus_frame (dpyinfo, 0);
6542#endif
6543
6544      /* EnterNotify counts as mouse movement,
6545	 so update things that depend on mouse position.  */
6546      if (f && !f->output_data.x->hourglass_p)
6547	note_mouse_movement (f, &event.xmotion);
6548#ifdef USE_GTK
6549      /* We may get an EnterNotify on the buttons in the toolbar.  In that
6550         case we moved out of any highlighted area and need to note this.  */
6551      if (!f && last_mouse_glyph_frame)
6552        note_mouse_movement (last_mouse_glyph_frame, &event);
6553#endif
6554      goto OTHER;
6555
6556    case FocusIn:
6557      x_detect_focus_change (dpyinfo, &event, &inev.ie);
6558      goto OTHER;
6559
6560    case LeaveNotify:
6561      last_user_time = event.xcrossing.time;
6562      x_detect_focus_change (dpyinfo, &event, &inev.ie);
6563
6564      f = x_top_window_to_frame (dpyinfo, event.xcrossing.window);
6565      if (f)
6566        {
6567          if (f == dpyinfo->mouse_face_mouse_frame)
6568            {
6569              /* If we move outside the frame, then we're
6570                 certainly no longer on any text in the frame.  */
6571              clear_mouse_face (dpyinfo);
6572              dpyinfo->mouse_face_mouse_frame = 0;
6573            }
6574
6575          /* Generate a nil HELP_EVENT to cancel a help-echo.
6576             Do it only if there's something to cancel.
6577             Otherwise, the startup message is cleared when
6578             the mouse leaves the frame.  */
6579          if (any_help_event_p)
6580	    do_help = -1;
6581        }
6582#ifdef USE_GTK
6583      /* See comment in EnterNotify above */
6584      else if (last_mouse_glyph_frame)
6585        note_mouse_movement (last_mouse_glyph_frame, &event);
6586#endif
6587      goto OTHER;
6588
6589    case FocusOut:
6590      x_detect_focus_change (dpyinfo, &event, &inev.ie);
6591      goto OTHER;
6592
6593    case MotionNotify:
6594      {
6595        last_user_time = event.xmotion.time;
6596        previous_help_echo_string = help_echo_string;
6597        help_echo_string = Qnil;
6598
6599        if (dpyinfo->grabbed && last_mouse_frame
6600            && FRAME_LIVE_P (last_mouse_frame))
6601          f = last_mouse_frame;
6602        else
6603          f = x_window_to_frame (dpyinfo, event.xmotion.window);
6604
6605        if (dpyinfo->mouse_face_hidden)
6606          {
6607            dpyinfo->mouse_face_hidden = 0;
6608            clear_mouse_face (dpyinfo);
6609          }
6610
6611        if (f)
6612          {
6613
6614            /* Generate SELECT_WINDOW_EVENTs when needed.  */
6615            if (!NILP (Vmouse_autoselect_window))
6616              {
6617                Lisp_Object window;
6618
6619                window = window_from_coordinates (f,
6620                                                  event.xmotion.x, event.xmotion.y,
6621                                                  0, 0, 0, 0);
6622
6623                /* Window will be selected only when it is not selected now and
6624                   last mouse movement event was not in it.  Minibuffer window
6625                   will be selected iff it is active.  */
6626                if (WINDOWP (window)
6627                    && !EQ (window, last_window)
6628                    && !EQ (window, selected_window))
6629                  {
6630                    inev.ie.kind = SELECT_WINDOW_EVENT;
6631                    inev.ie.frame_or_window = window;
6632                  }
6633
6634                last_window=window;
6635              }
6636            if (!note_mouse_movement (f, &event.xmotion))
6637	      help_echo_string = previous_help_echo_string;
6638          }
6639        else
6640          {
6641#ifndef USE_TOOLKIT_SCROLL_BARS
6642            struct scroll_bar *bar
6643              = x_window_to_scroll_bar (event.xmotion.display,
6644                                        event.xmotion.window);
6645
6646            if (bar)
6647              x_scroll_bar_note_movement (bar, &event);
6648#endif /* USE_TOOLKIT_SCROLL_BARS */
6649
6650            /* If we move outside the frame, then we're
6651               certainly no longer on any text in the frame.  */
6652            clear_mouse_face (dpyinfo);
6653          }
6654
6655        /* If the contents of the global variable help_echo_string
6656           has changed, generate a HELP_EVENT.  */
6657        if (!NILP (help_echo_string)
6658            || !NILP (previous_help_echo_string))
6659	  do_help = 1;
6660        goto OTHER;
6661      }
6662
6663    case ConfigureNotify:
6664      f = x_top_window_to_frame (dpyinfo, event.xconfigure.window);
6665      if (f)
6666        {
6667#ifndef USE_X_TOOLKIT
6668#ifdef USE_GTK
6669          xg_resize_widgets (f, event.xconfigure.width,
6670                             event.xconfigure.height);
6671#else /* not USE_GTK */
6672          /* If there is a pending resize for fullscreen, don't
6673             do this one, the right one will come later.
6674             The toolkit version doesn't seem to need this, but we
6675             need to reset it below.  */
6676          int dont_resize
6677	    = ((f->want_fullscreen & FULLSCREEN_WAIT)
6678	       && f->new_text_cols != 0);
6679          int rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, event.xconfigure.height);
6680          int columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, event.xconfigure.width);
6681
6682          if (dont_resize)
6683            goto OTHER;
6684
6685          /* In the toolkit version, change_frame_size
6686             is called by the code that handles resizing
6687             of the EmacsFrame widget.  */
6688
6689          /* Even if the number of character rows and columns has
6690             not changed, the font size may have changed, so we need
6691             to check the pixel dimensions as well.  */
6692          if (columns != FRAME_COLS (f)
6693              || rows != FRAME_LINES (f)
6694              || event.xconfigure.width != FRAME_PIXEL_WIDTH (f)
6695              || event.xconfigure.height != FRAME_PIXEL_HEIGHT (f))
6696            {
6697              change_frame_size (f, rows, columns, 0, 1, 0);
6698              SET_FRAME_GARBAGED (f);
6699              cancel_mouse_face (f);
6700            }
6701#endif /* not USE_GTK */
6702#endif
6703
6704          FRAME_PIXEL_WIDTH (f) = event.xconfigure.width;
6705          FRAME_PIXEL_HEIGHT (f) = event.xconfigure.height;
6706
6707#ifdef USE_GTK
6708          /* GTK creates windows but doesn't map them.
6709             Only get real positions and check fullscreen when mapped. */
6710          if (FRAME_GTK_OUTER_WIDGET (f)
6711              && GTK_WIDGET_MAPPED (FRAME_GTK_OUTER_WIDGET (f)))
6712#endif
6713            {
6714	      x_real_positions (f, &f->left_pos, &f->top_pos);
6715
6716	      if (f->want_fullscreen & FULLSCREEN_WAIT)
6717		f->want_fullscreen &= ~(FULLSCREEN_WAIT|FULLSCREEN_BOTH);
6718            }
6719
6720#ifdef HAVE_X_I18N
6721          if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
6722            xic_set_statusarea (f);
6723#endif
6724
6725          if (f->output_data.x->parent_desc != FRAME_X_DISPLAY_INFO (f)->root_window)
6726            {
6727              /* Since the WM decorations come below top_pos now,
6728                 we must put them below top_pos in the future.  */
6729              f->win_gravity = NorthWestGravity;
6730              x_wm_set_size_hint (f, (long) 0, 0);
6731            }
6732        }
6733      goto OTHER;
6734
6735    case ButtonRelease:
6736    case ButtonPress:
6737      {
6738        /* If we decide we want to generate an event to be seen
6739           by the rest of Emacs, we put it here.  */
6740        int tool_bar_p = 0;
6741
6742        bzero (&compose_status, sizeof (compose_status));
6743	last_mouse_glyph_frame = 0;
6744        last_user_time = event.xbutton.time;
6745
6746        if (dpyinfo->grabbed
6747            && last_mouse_frame
6748            && FRAME_LIVE_P (last_mouse_frame))
6749          f = last_mouse_frame;
6750        else
6751          f = x_window_to_frame (dpyinfo, event.xbutton.window);
6752
6753        if (f)
6754          {
6755            /* Is this in the tool-bar?  */
6756            if (WINDOWP (f->tool_bar_window)
6757                && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)))
6758              {
6759                Lisp_Object window;
6760                int x = event.xbutton.x;
6761                int y = event.xbutton.y;
6762
6763                window = window_from_coordinates (f, x, y, 0, 0, 0, 1);
6764                tool_bar_p = EQ (window, f->tool_bar_window);
6765
6766                if (tool_bar_p && event.xbutton.button < 4)
6767                  {
6768                    if (event.xbutton.type == ButtonPress)
6769                      handle_tool_bar_click (f, x, y, 1, 0);
6770                    else
6771                      handle_tool_bar_click (f, x, y, 0,
6772                                             x_x_to_emacs_modifiers (dpyinfo,
6773								     event.xbutton.state));
6774                  }
6775              }
6776
6777            if (!tool_bar_p)
6778              if (!dpyinfo->x_focus_frame
6779                  || f == dpyinfo->x_focus_frame)
6780                {
6781#if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6782                  if (! popup_activated ())
6783#endif
6784		    {
6785		      if (ignore_next_mouse_click_timeout)
6786			{
6787			  if (event.type == ButtonPress
6788			      && (int)(event.xbutton.time - ignore_next_mouse_click_timeout) > 0)
6789			    {
6790			      ignore_next_mouse_click_timeout = 0;
6791			      construct_mouse_click (&inev.ie, &event.xbutton, f);
6792			    }
6793			  if (event.type == ButtonRelease)
6794			    ignore_next_mouse_click_timeout = 0;
6795			}
6796		      else
6797			construct_mouse_click (&inev.ie, &event.xbutton, f);
6798		    }
6799                }
6800          }
6801        else
6802          {
6803            struct scroll_bar *bar
6804              = x_window_to_scroll_bar (event.xbutton.display,
6805                                        event.xbutton.window);
6806
6807#ifdef USE_TOOLKIT_SCROLL_BARS
6808            /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
6809               scroll bars.  */
6810            if (bar && event.xbutton.state & ControlMask)
6811              {
6812                x_scroll_bar_handle_click (bar, &event, &inev.ie);
6813                *finish = X_EVENT_DROP;
6814              }
6815#else /* not USE_TOOLKIT_SCROLL_BARS */
6816            if (bar)
6817              x_scroll_bar_handle_click (bar, &event, &inev.ie);
6818#endif /* not USE_TOOLKIT_SCROLL_BARS */
6819          }
6820
6821        if (event.type == ButtonPress)
6822          {
6823            dpyinfo->grabbed |= (1 << event.xbutton.button);
6824            last_mouse_frame = f;
6825
6826            if (!tool_bar_p)
6827              last_tool_bar_item = -1;
6828          }
6829        else
6830          dpyinfo->grabbed &= ~(1 << event.xbutton.button);
6831
6832	/* Ignore any mouse motion that happened before this event;
6833	   any subsequent mouse-movement Emacs events should reflect
6834	   only motion after the ButtonPress/Release.  */
6835	if (f != 0)
6836	  f->mouse_moved = 0;
6837
6838#if defined (USE_X_TOOLKIT) || defined (USE_GTK)
6839        f = x_menubar_window_to_frame (dpyinfo, event.xbutton.window);
6840        /* For a down-event in the menu bar,
6841           don't pass it to Xt right now.
6842           Instead, save it away
6843           and we will pass it to Xt from kbd_buffer_get_event.
6844           That way, we can run some Lisp code first.  */
6845        if (
6846#ifdef USE_GTK
6847            ! popup_activated ()
6848            &&
6849#endif
6850            f && event.type == ButtonPress
6851            /* Verify the event is really within the menu bar
6852               and not just sent to it due to grabbing.  */
6853            && event.xbutton.x >= 0
6854            && event.xbutton.x < FRAME_PIXEL_WIDTH (f)
6855            && event.xbutton.y >= 0
6856            && event.xbutton.y < f->output_data.x->menubar_height
6857            && event.xbutton.same_screen)
6858          {
6859            SET_SAVED_BUTTON_EVENT;
6860            XSETFRAME (last_mouse_press_frame, f);
6861#ifdef USE_GTK
6862            *finish = X_EVENT_DROP;
6863#endif
6864          }
6865        else if (event.type == ButtonPress)
6866          {
6867            last_mouse_press_frame = Qnil;
6868            goto OTHER;
6869          }
6870
6871#ifdef USE_MOTIF /* This should do not harm for Lucid,
6872		    but I am trying to be cautious.  */
6873        else if (event.type == ButtonRelease)
6874          {
6875            if (!NILP (last_mouse_press_frame))
6876              {
6877                f = XFRAME (last_mouse_press_frame);
6878                if (f->output_data.x)
6879                  SET_SAVED_BUTTON_EVENT;
6880              }
6881            else
6882              goto OTHER;
6883          }
6884#endif /* USE_MOTIF */
6885        else
6886          goto OTHER;
6887#endif /* USE_X_TOOLKIT || USE_GTK */
6888      }
6889      break;
6890
6891    case CirculateNotify:
6892      goto OTHER;
6893
6894    case CirculateRequest:
6895      goto OTHER;
6896
6897    case VisibilityNotify:
6898      goto OTHER;
6899
6900    case MappingNotify:
6901      /* Someone has changed the keyboard mapping - update the
6902         local cache.  */
6903      switch (event.xmapping.request)
6904        {
6905        case MappingModifier:
6906          x_find_modifier_meanings (dpyinfo);
6907          /* This is meant to fall through.  */
6908        case MappingKeyboard:
6909          XRefreshKeyboardMapping (&event.xmapping);
6910        }
6911      goto OTHER;
6912
6913    default:
6914    OTHER:
6915#ifdef USE_X_TOOLKIT
6916    BLOCK_INPUT;
6917    if (*finish != X_EVENT_DROP)
6918      XtDispatchEvent (&event);
6919    UNBLOCK_INPUT;
6920#endif /* USE_X_TOOLKIT */
6921    break;
6922    }
6923
6924 done:
6925  if (inev.ie.kind != NO_EVENT)
6926    {
6927      kbd_buffer_store_event_hold (&inev.ie, hold_quit);
6928      count++;
6929    }
6930
6931  if (do_help
6932      && !(hold_quit && hold_quit->kind != NO_EVENT))
6933    {
6934      Lisp_Object frame;
6935
6936      if (f)
6937	XSETFRAME (frame, f);
6938      else
6939	frame = Qnil;
6940
6941      if (do_help > 0)
6942	{
6943	  any_help_event_p = 1;
6944	  gen_help_event (help_echo_string, frame, help_echo_window,
6945			  help_echo_object, help_echo_pos);
6946	}
6947      else
6948	{
6949	  help_echo_string = Qnil;
6950	  gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6951	}
6952      count++;
6953    }
6954
6955  *eventp = event;
6956  return count;
6957}
6958
6959
6960/* Handles the XEvent EVENT on display DISPLAY.
6961   This is used for event loops outside the normal event handling,
6962   i.e. looping while a popup menu or a dialog is posted.
6963
6964   Returns the value handle_one_xevent sets in the finish argument.  */
6965int
6966x_dispatch_event (event, display)
6967     XEvent *event;
6968     Display *display;
6969{
6970  struct x_display_info *dpyinfo;
6971  int finish = X_EVENT_NORMAL;
6972
6973  dpyinfo = x_display_info_for_display (display);
6974
6975  if (dpyinfo)
6976    handle_one_xevent (dpyinfo, event, &finish, 0);
6977
6978  return finish;
6979}
6980
6981
6982/* Read events coming from the X server.
6983   This routine is called by the SIGIO handler.
6984   We return as soon as there are no more events to be read.
6985
6986   We return the number of characters stored into the buffer,
6987   thus pretending to be `read'.
6988
6989   EXPECTED is nonzero if the caller knows input is available.  */
6990
6991static int
6992XTread_socket (sd, expected, hold_quit)
6993     register int sd;
6994     int expected;
6995     struct input_event *hold_quit;
6996{
6997  int count = 0;
6998  XEvent event;
6999  int event_found = 0;
7000  struct x_display_info *dpyinfo;
7001
7002  if (interrupt_input_blocked)
7003    {
7004      interrupt_input_pending = 1;
7005      return -1;
7006    }
7007
7008  interrupt_input_pending = 0;
7009  BLOCK_INPUT;
7010
7011  /* So people can tell when we have read the available input.  */
7012  input_signal_count++;
7013
7014  ++handling_signal;
7015
7016  /* Find the display we are supposed to read input for.
7017     It's the one communicating on descriptor SD.  */
7018  for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
7019    {
7020#if 0 /* This ought to be unnecessary; let's verify it.  */
7021#ifdef FIOSNBIO
7022      /* If available, Xlib uses FIOSNBIO to make the socket
7023	 non-blocking, and then looks for EWOULDBLOCK.  If O_NDELAY is set,
7024	 FIOSNBIO is ignored, and instead of signaling EWOULDBLOCK,
7025	 a read returns 0, which Xlib interprets as equivalent to EPIPE.  */
7026      fcntl (dpyinfo->connection, F_SETFL, 0);
7027#endif /* ! defined (FIOSNBIO) */
7028#endif
7029
7030#if 0 /* This code can't be made to work, with multiple displays,
7031	 and appears not to be used on any system any more.
7032	 Also keyboard.c doesn't turn O_NDELAY on and off
7033	 for X connections.  */
7034#ifndef SIGIO
7035#ifndef HAVE_SELECT
7036      if (! (fcntl (dpyinfo->connection, F_GETFL, 0) & O_NDELAY))
7037	{
7038	  extern int read_alarm_should_throw;
7039	  read_alarm_should_throw = 1;
7040	  XPeekEvent (dpyinfo->display, &event);
7041	  read_alarm_should_throw = 0;
7042	}
7043#endif /* HAVE_SELECT */
7044#endif /* SIGIO */
7045#endif
7046
7047      /* For debugging, this gives a way to fake an I/O error.  */
7048      if (dpyinfo == XTread_socket_fake_io_error)
7049	{
7050	  XTread_socket_fake_io_error = 0;
7051	  x_io_error_quitter (dpyinfo->display);
7052	}
7053
7054#ifdef HAVE_X_SM
7055      {
7056	struct input_event inev;
7057	BLOCK_INPUT;
7058	/* We don't need to EVENT_INIT (inev) here, as
7059	   x_session_check_input copies an entire input_event.  */
7060	if (x_session_check_input (&inev))
7061	  {
7062	    kbd_buffer_store_event_hold (&inev, hold_quit);
7063	    count++;
7064	  }
7065	UNBLOCK_INPUT;
7066      }
7067#endif
7068
7069#ifndef USE_GTK
7070      while (XPending (dpyinfo->display))
7071	{
7072          int finish;
7073
7074	  XNextEvent (dpyinfo->display, &event);
7075
7076#ifdef HAVE_X_I18N
7077          /* Filter events for the current X input method.  */
7078          if (x_filter_event (dpyinfo, &event))
7079            break;
7080#endif
7081	  event_found = 1;
7082
7083          count += handle_one_xevent (dpyinfo, &event, &finish, hold_quit);
7084
7085          if (finish == X_EVENT_GOTO_OUT)
7086            goto out;
7087        }
7088#endif /* not USE_GTK */
7089    }
7090
7091#ifdef USE_GTK
7092
7093  /* For GTK we must use the GTK event loop.  But XEvents gets passed
7094     to our filter function above, and then to the big event switch.
7095     We use a bunch of globals to communicate with our filter function,
7096     that is kind of ugly, but it works.
7097
7098     There is no way to do one display at the time, GTK just does events
7099     from all displays.  */
7100
7101  while (gtk_events_pending ())
7102    {
7103      current_count = count;
7104      current_hold_quit = hold_quit;
7105
7106      gtk_main_iteration ();
7107
7108      count = current_count;
7109      current_count = -1;
7110      current_hold_quit = 0;
7111
7112      if (current_finish == X_EVENT_GOTO_OUT)
7113        break;
7114    }
7115#endif /* USE_GTK */
7116
7117 out:;
7118
7119  /* On some systems, an X bug causes Emacs to get no more events
7120     when the window is destroyed.  Detect that.  (1994.)  */
7121  if (! event_found)
7122    {
7123      /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
7124	 One XNOOP in 100 loops will make Emacs terminate.
7125	 B. Bretthauer, 1994 */
7126      x_noop_count++;
7127      if (x_noop_count >= 100)
7128	{
7129	  x_noop_count=0;
7130
7131	  if (next_noop_dpyinfo == 0)
7132	    next_noop_dpyinfo = x_display_list;
7133
7134	  XNoOp (next_noop_dpyinfo->display);
7135
7136	  /* Each time we get here, cycle through the displays now open.  */
7137	  next_noop_dpyinfo = next_noop_dpyinfo->next;
7138	}
7139    }
7140
7141  /* If the focus was just given to an auto-raising frame,
7142     raise it now.  */
7143  /* ??? This ought to be able to handle more than one such frame.  */
7144  if (pending_autoraise_frame)
7145    {
7146      x_raise_frame (pending_autoraise_frame);
7147      pending_autoraise_frame = 0;
7148    }
7149
7150  --handling_signal;
7151  UNBLOCK_INPUT;
7152
7153  return count;
7154}
7155
7156
7157
7158
7159/***********************************************************************
7160			     Text Cursor
7161 ***********************************************************************/
7162
7163/* Set clipping for output in glyph row ROW.  W is the window in which
7164   we operate.  GC is the graphics context to set clipping in.
7165
7166   ROW may be a text row or, e.g., a mode line.  Text rows must be
7167   clipped to the interior of the window dedicated to text display,
7168   mode lines must be clipped to the whole window.  */
7169
7170static void
7171x_clip_to_row (w, row, area, gc)
7172     struct window *w;
7173     struct glyph_row *row;
7174     int area;
7175     GC gc;
7176{
7177  struct frame *f = XFRAME (WINDOW_FRAME (w));
7178  XRectangle clip_rect;
7179  int window_x, window_y, window_width;
7180
7181  window_box (w, area, &window_x, &window_y, &window_width, 0);
7182
7183  clip_rect.x = window_x;
7184  clip_rect.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
7185  clip_rect.y = max (clip_rect.y, window_y);
7186  clip_rect.width = window_width;
7187  clip_rect.height = row->visible_height;
7188
7189  XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, &clip_rect, 1, Unsorted);
7190}
7191
7192
7193/* Draw a hollow box cursor on window W in glyph row ROW.  */
7194
7195static void
7196x_draw_hollow_cursor (w, row)
7197     struct window *w;
7198     struct glyph_row *row;
7199{
7200  struct frame *f = XFRAME (WINDOW_FRAME (w));
7201  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7202  Display *dpy = FRAME_X_DISPLAY (f);
7203  int x, y, wd, h;
7204  XGCValues xgcv;
7205  struct glyph *cursor_glyph;
7206  GC gc;
7207
7208  /* Get the glyph the cursor is on.  If we can't tell because
7209     the current matrix is invalid or such, give up.  */
7210  cursor_glyph = get_phys_cursor_glyph (w);
7211  if (cursor_glyph == NULL)
7212    return;
7213
7214  /* Compute frame-relative coordinates for phys cursor.  */
7215  get_phys_cursor_geometry (w, row, cursor_glyph, &x, &y, &h);
7216  wd = w->phys_cursor_width;
7217
7218  /* The foreground of cursor_gc is typically the same as the normal
7219     background color, which can cause the cursor box to be invisible.  */
7220  xgcv.foreground = f->output_data.x->cursor_pixel;
7221  if (dpyinfo->scratch_cursor_gc)
7222    XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
7223  else
7224    dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_X_WINDOW (f),
7225					    GCForeground, &xgcv);
7226  gc = dpyinfo->scratch_cursor_gc;
7227
7228  /* Set clipping, draw the rectangle, and reset clipping again.  */
7229  x_clip_to_row (w, row, TEXT_AREA, gc);
7230  XDrawRectangle (dpy, FRAME_X_WINDOW (f), gc, x, y, wd, h - 1);
7231  XSetClipMask (dpy, gc, None);
7232}
7233
7234
7235/* Draw a bar cursor on window W in glyph row ROW.
7236
7237   Implementation note: One would like to draw a bar cursor with an
7238   angle equal to the one given by the font property XA_ITALIC_ANGLE.
7239   Unfortunately, I didn't find a font yet that has this property set.
7240   --gerd.  */
7241
7242static void
7243x_draw_bar_cursor (w, row, width, kind)
7244     struct window *w;
7245     struct glyph_row *row;
7246     int width;
7247     enum text_cursor_kinds kind;
7248{
7249  struct frame *f = XFRAME (w->frame);
7250  struct glyph *cursor_glyph;
7251
7252  /* If cursor is out of bounds, don't draw garbage.  This can happen
7253     in mini-buffer windows when switching between echo area glyphs
7254     and mini-buffer.  */
7255  cursor_glyph = get_phys_cursor_glyph (w);
7256  if (cursor_glyph == NULL)
7257    return;
7258
7259  /* If on an image, draw like a normal cursor.  That's usually better
7260     visible than drawing a bar, esp. if the image is large so that
7261     the bar might not be in the window.  */
7262  if (cursor_glyph->type == IMAGE_GLYPH)
7263    {
7264      struct glyph_row *row;
7265      row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
7266      draw_phys_cursor_glyph (w, row, DRAW_CURSOR);
7267    }
7268  else
7269    {
7270      Display *dpy = FRAME_X_DISPLAY (f);
7271      Window window = FRAME_X_WINDOW (f);
7272      GC gc = FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc;
7273      unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
7274      struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
7275      XGCValues xgcv;
7276
7277      /* If the glyph's background equals the color we normally draw
7278	 the bar cursor in, the bar cursor in its normal color is
7279	 invisible.  Use the glyph's foreground color instead in this
7280	 case, on the assumption that the glyph's colors are chosen so
7281	 that the glyph is legible.  */
7282      if (face->background == f->output_data.x->cursor_pixel)
7283	xgcv.background = xgcv.foreground = face->foreground;
7284      else
7285	xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
7286      xgcv.graphics_exposures = 0;
7287
7288      if (gc)
7289	XChangeGC (dpy, gc, mask, &xgcv);
7290      else
7291	{
7292	  gc = XCreateGC (dpy, window, mask, &xgcv);
7293	  FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
7294	}
7295
7296      if (width < 0)
7297	width = FRAME_CURSOR_WIDTH (f);
7298      width = min (cursor_glyph->pixel_width, width);
7299
7300      w->phys_cursor_width = width;
7301      x_clip_to_row (w, row, TEXT_AREA, gc);
7302
7303      if (kind == BAR_CURSOR)
7304	  XFillRectangle (dpy, window, gc,
7305			  WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
7306			  WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
7307			  width, row->height);
7308      else
7309	  XFillRectangle (dpy, window, gc,
7310			  WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
7311			  WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
7312						   row->height - width),
7313			  cursor_glyph->pixel_width,
7314			  width);
7315
7316      XSetClipMask (dpy, gc, None);
7317    }
7318}
7319
7320
7321/* RIF: Define cursor CURSOR on frame F.  */
7322
7323static void
7324x_define_frame_cursor (f, cursor)
7325     struct frame *f;
7326     Cursor cursor;
7327{
7328  XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
7329}
7330
7331
7332/* RIF: Clear area on frame F.  */
7333
7334static void
7335x_clear_frame_area (f, x, y, width, height)
7336     struct frame *f;
7337     int x, y, width, height;
7338{
7339  x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
7340		x, y, width, height, False);
7341}
7342
7343
7344/* RIF: Draw cursor on window W.  */
7345
7346static void
7347x_draw_window_cursor (w, glyph_row, x, y, cursor_type, cursor_width, on_p, active_p)
7348     struct window *w;
7349     struct glyph_row *glyph_row;
7350     int x, y;
7351     int cursor_type, cursor_width;
7352     int on_p, active_p;
7353{
7354  struct frame *f = XFRAME (WINDOW_FRAME (w));
7355
7356  if (on_p)
7357    {
7358      w->phys_cursor_type = cursor_type;
7359      w->phys_cursor_on_p = 1;
7360
7361      if (glyph_row->exact_window_width_line_p
7362	  && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
7363	{
7364	  glyph_row->cursor_in_fringe_p = 1;
7365	  draw_fringe_bitmap (w, glyph_row, 0);
7366	}
7367      else
7368      switch (cursor_type)
7369	{
7370	case HOLLOW_BOX_CURSOR:
7371	  x_draw_hollow_cursor (w, glyph_row);
7372	  break;
7373
7374	case FILLED_BOX_CURSOR:
7375	  draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
7376	  break;
7377
7378	case BAR_CURSOR:
7379	  x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
7380	  break;
7381
7382	case HBAR_CURSOR:
7383	  x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
7384	  break;
7385
7386	case NO_CURSOR:
7387	  w->phys_cursor_width = 0;
7388	  break;
7389
7390	default:
7391	  abort ();
7392	}
7393
7394#ifdef HAVE_X_I18N
7395      if (w == XWINDOW (f->selected_window))
7396	if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
7397	  xic_set_preeditarea (w, x, y);
7398#endif
7399    }
7400
7401#ifndef XFlush
7402  if (updating_frame != f)
7403    XFlush (FRAME_X_DISPLAY (f));
7404#endif
7405}
7406
7407
7408/* Icons.  */
7409
7410/* Make the x-window of frame F use the gnu icon bitmap.  */
7411
7412int
7413x_bitmap_icon (f, file)
7414     struct frame *f;
7415     Lisp_Object file;
7416{
7417  int bitmap_id;
7418
7419  if (FRAME_X_WINDOW (f) == 0)
7420    return 1;
7421
7422  /* Free up our existing icon bitmap and mask if any.  */
7423  if (f->output_data.x->icon_bitmap > 0)
7424    x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7425  f->output_data.x->icon_bitmap = 0;
7426
7427  if (STRINGP (file))
7428    {
7429#ifdef USE_GTK
7430      /* Use gtk_window_set_icon_from_file () if available,
7431	 It's not restricted to bitmaps */
7432      if (xg_set_icon (f, file))
7433	return 0;
7434#endif /* USE_GTK */
7435      bitmap_id = x_create_bitmap_from_file (f, file);
7436      x_create_bitmap_mask (f, bitmap_id);
7437    }
7438  else
7439    {
7440      /* Create the GNU bitmap and mask if necessary.  */
7441      if (FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id < 0)
7442	{
7443	  int rc = -1;
7444
7445#if defined (HAVE_XPM) && defined (HAVE_X_WINDOWS)
7446#ifdef USE_GTK
7447	  if (xg_set_icon_from_xpm_data (f, gnu_xpm_bits))
7448	    return 0;
7449#else
7450	  rc = x_create_bitmap_from_xpm_data (f, gnu_xpm_bits);
7451	  if (rc != -1)
7452	    FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7453#endif /* USE_GTK */
7454#endif /* defined (HAVE_XPM) && defined (HAVE_X_WINDOWS) */
7455
7456	  /* If all else fails, use the (black and white) xbm image. */
7457	  if (rc == -1)
7458	    {
7459	      rc = x_create_bitmap_from_data (f, gnu_xbm_bits,
7460					      gnu_xbm_width, gnu_xbm_height);
7461	      if (rc == -1)
7462		return 1;
7463
7464	      FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id = rc;
7465	      x_create_bitmap_mask (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
7466	    }
7467	}
7468
7469      /* The first time we create the GNU bitmap and mask,
7470	 this increments the ref-count one extra time.
7471	 As a result, the GNU bitmap and mask are never freed.
7472	 That way, we don't have to worry about allocating it again.  */
7473      x_reference_bitmap (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
7474
7475      bitmap_id = FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id;
7476    }
7477
7478  x_wm_set_icon_pixmap (f, bitmap_id);
7479  f->output_data.x->icon_bitmap = bitmap_id;
7480
7481  return 0;
7482}
7483
7484
7485/* Make the x-window of frame F use a rectangle with text.
7486   Use ICON_NAME as the text.  */
7487
7488int
7489x_text_icon (f, icon_name)
7490     struct frame *f;
7491     char *icon_name;
7492{
7493  if (FRAME_X_WINDOW (f) == 0)
7494    return 1;
7495
7496#ifdef HAVE_X11R4
7497  {
7498    XTextProperty text;
7499    text.value = (unsigned char *) icon_name;
7500    text.encoding = XA_STRING;
7501    text.format = 8;
7502    text.nitems = strlen (icon_name);
7503    XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
7504  }
7505#else /* not HAVE_X11R4 */
7506  XSetIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), icon_name);
7507#endif /* not HAVE_X11R4 */
7508
7509  if (f->output_data.x->icon_bitmap > 0)
7510    x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
7511  f->output_data.x->icon_bitmap = 0;
7512  x_wm_set_icon_pixmap (f, 0);
7513
7514  return 0;
7515}
7516
7517#define X_ERROR_MESSAGE_SIZE 200
7518
7519/* If non-nil, this should be a string.
7520   It means catch X errors  and store the error message in this string.
7521
7522   The reason we use a stack is that x_catch_error/x_uncatch_error can
7523   be called from a signal handler.
7524*/
7525
7526struct x_error_message_stack {
7527  char string[X_ERROR_MESSAGE_SIZE];
7528  Display *dpy;
7529  struct x_error_message_stack *prev;
7530};
7531static struct x_error_message_stack *x_error_message;
7532
7533/* An X error handler which stores the error message in
7534   *x_error_message.  This is called from x_error_handler if
7535   x_catch_errors is in effect.  */
7536
7537static void
7538x_error_catcher (display, error)
7539     Display *display;
7540     XErrorEvent *error;
7541{
7542  XGetErrorText (display, error->error_code,
7543		 x_error_message->string,
7544		 X_ERROR_MESSAGE_SIZE);
7545}
7546
7547/* Begin trapping X errors for display DPY.  Actually we trap X errors
7548   for all displays, but DPY should be the display you are actually
7549   operating on.
7550
7551   After calling this function, X protocol errors no longer cause
7552   Emacs to exit; instead, they are recorded in the string
7553   stored in *x_error_message.
7554
7555   Calling x_check_errors signals an Emacs error if an X error has
7556   occurred since the last call to x_catch_errors or x_check_errors.
7557
7558   Calling x_uncatch_errors resumes the normal error handling.  */
7559
7560void x_check_errors ();
7561
7562void
7563x_catch_errors (dpy)
7564     Display *dpy;
7565{
7566  struct x_error_message_stack *data = xmalloc (sizeof (*data));
7567
7568  /* Make sure any errors from previous requests have been dealt with.  */
7569  XSync (dpy, False);
7570
7571  data->dpy = dpy;
7572  data->string[0] = 0;
7573  data->prev = x_error_message;
7574  x_error_message = data;
7575}
7576
7577/* Undo the last x_catch_errors call.
7578   DPY should be the display that was passed to x_catch_errors.  */
7579
7580void
7581x_uncatch_errors ()
7582{
7583  struct x_error_message_stack *tmp;
7584
7585  BLOCK_INPUT;
7586
7587  /* The display may have been closed before this function is called.
7588     Check if it is still open before calling XSync.  */
7589  if (x_display_info_for_display (x_error_message->dpy) != 0)
7590    XSync (x_error_message->dpy, False);
7591
7592  tmp = x_error_message;
7593  x_error_message = x_error_message->prev;
7594  xfree (tmp);
7595  UNBLOCK_INPUT;
7596}
7597
7598/* If any X protocol errors have arrived since the last call to
7599   x_catch_errors or x_check_errors, signal an Emacs error using
7600   sprintf (a buffer, FORMAT, the x error message text) as the text.  */
7601
7602void
7603x_check_errors (dpy, format)
7604     Display *dpy;
7605     char *format;
7606{
7607  /* Make sure to catch any errors incurred so far.  */
7608  XSync (dpy, False);
7609
7610  if (x_error_message->string[0])
7611    {
7612      char string[X_ERROR_MESSAGE_SIZE];
7613      bcopy (x_error_message->string, string, X_ERROR_MESSAGE_SIZE);
7614      x_uncatch_errors ();
7615      error (format, string);
7616    }
7617}
7618
7619/* Nonzero if we had any X protocol errors
7620   since we did x_catch_errors on DPY.  */
7621
7622int
7623x_had_errors_p (dpy)
7624     Display *dpy;
7625{
7626  /* Make sure to catch any errors incurred so far.  */
7627  XSync (dpy, False);
7628
7629  return x_error_message->string[0] != 0;
7630}
7631
7632/* Forget about any errors we have had, since we did x_catch_errors on DPY.  */
7633
7634void
7635x_clear_errors (dpy)
7636     Display *dpy;
7637{
7638  x_error_message->string[0] = 0;
7639}
7640
7641/* Close off all unclosed x_catch_errors calls.  */
7642
7643void
7644x_fully_uncatch_errors ()
7645{
7646  while (x_error_message)
7647    x_uncatch_errors ();
7648}
7649
7650/* Nonzero if x_catch_errors has been done and not yet canceled.  */
7651
7652int
7653x_catching_errors ()
7654{
7655  return x_error_message != 0;
7656}
7657
7658#if 0
7659static unsigned int x_wire_count;
7660x_trace_wire ()
7661{
7662  fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
7663}
7664#endif /* ! 0 */
7665
7666
7667/* Handle SIGPIPE, which can happen when the connection to a server
7668   simply goes away.  SIGPIPE is handled by x_connection_signal.
7669   Don't need to do anything, because the write which caused the
7670   SIGPIPE will fail, causing Xlib to invoke the X IO error handler,
7671   which will do the appropriate cleanup for us.  */
7672
7673static SIGTYPE
7674x_connection_signal (signalnum)	/* If we don't have an argument, */
7675     int signalnum;		/* some compilers complain in signal calls.  */
7676{
7677#ifdef USG
7678  /* USG systems forget handlers when they are used;
7679     must reestablish each time */
7680  signal (signalnum, x_connection_signal);
7681#endif /* USG */
7682}
7683
7684
7685/************************************************************************
7686			  Handling X errors
7687 ************************************************************************/
7688
7689/* Error message passed to x_connection_closed.  */
7690
7691static char *error_msg;
7692
7693/* Function installed as fatal_error_signal_hook in
7694   x_connection_closed.  Print the X error message, and exit normally,
7695   instead of dumping core when XtCloseDisplay fails.  */
7696
7697static void
7698x_fatal_error_signal ()
7699{
7700  fprintf (stderr, "%s\n", error_msg);
7701  exit (70);
7702}
7703
7704/* Handle the loss of connection to display DPY.  ERROR_MESSAGE is
7705   the text of an error message that lead to the connection loss.  */
7706
7707static SIGTYPE
7708x_connection_closed (dpy, error_message)
7709     Display *dpy;
7710     char *error_message;
7711{
7712  struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
7713  Lisp_Object frame, tail;
7714
7715  error_msg = (char *) alloca (strlen (error_message) + 1);
7716  strcpy (error_msg, error_message);
7717  handling_signal = 0;
7718
7719  /* Prevent being called recursively because of an error condition
7720     below.  Otherwise, we might end up with printing ``can't find per
7721     display information'' in the recursive call instead of printing
7722     the original message here.  */
7723  x_catch_errors (dpy);
7724
7725  /* We have to close the display to inform Xt that it doesn't
7726     exist anymore.  If we don't, Xt will continue to wait for
7727     events from the display.  As a consequence, a sequence of
7728
7729     M-x make-frame-on-display RET :1 RET
7730     ...kill the new frame, so that we get an IO error...
7731     M-x make-frame-on-display RET :1 RET
7732
7733     will indefinitely wait in Xt for events for display `:1', opened
7734     in the first class to make-frame-on-display.
7735
7736     Closing the display is reported to lead to a bus error on
7737     OpenWindows in certain situations.  I suspect that is a bug
7738     in OpenWindows.  I don't know how to cicumvent it here.  */
7739
7740#ifdef USE_X_TOOLKIT
7741  /* If DPYINFO is null, this means we didn't open the display
7742     in the first place, so don't try to close it.  */
7743  if (dpyinfo)
7744    {
7745      extern void (*fatal_error_signal_hook) P_ ((void));
7746      fatal_error_signal_hook = x_fatal_error_signal;
7747      XtCloseDisplay (dpy);
7748      fatal_error_signal_hook = NULL;
7749    }
7750#endif
7751
7752#ifdef USE_GTK
7753  if (dpyinfo)
7754    xg_display_close (dpyinfo->display);
7755#endif
7756
7757  /* Indicate that this display is dead.  */
7758  if (dpyinfo)
7759    dpyinfo->display = 0;
7760
7761  /* First delete frames whose mini-buffers are on frames
7762     that are on the dead display.  */
7763  FOR_EACH_FRAME (tail, frame)
7764    {
7765      Lisp_Object minibuf_frame;
7766      minibuf_frame
7767	= WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
7768      if (FRAME_X_P (XFRAME (frame))
7769	  && FRAME_X_P (XFRAME (minibuf_frame))
7770	  && ! EQ (frame, minibuf_frame)
7771	  && FRAME_X_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
7772	Fdelete_frame (frame, Qt);
7773    }
7774
7775  /* Now delete all remaining frames on the dead display.
7776     We are now sure none of these is used as the mini-buffer
7777     for another frame that we need to delete.  */
7778  FOR_EACH_FRAME (tail, frame)
7779    if (FRAME_X_P (XFRAME (frame))
7780	&& FRAME_X_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
7781      {
7782	/* Set this to t so that Fdelete_frame won't get confused
7783	   trying to find a replacement.  */
7784	FRAME_KBOARD (XFRAME (frame))->Vdefault_minibuffer_frame = Qt;
7785	Fdelete_frame (frame, Qt);
7786      }
7787
7788  if (dpyinfo)
7789    x_delete_display (dpyinfo);
7790
7791  x_uncatch_errors ();
7792
7793  if (x_display_list == 0)
7794    {
7795      fprintf (stderr, "%s\n", error_msg);
7796      shut_down_emacs (0, 0, Qnil);
7797      exit (70);
7798    }
7799
7800  /* Ordinary stack unwind doesn't deal with these.  */
7801#ifdef SIGIO
7802  sigunblock (sigmask (SIGIO));
7803#endif
7804  sigunblock (sigmask (SIGALRM));
7805  TOTALLY_UNBLOCK_INPUT;
7806
7807  clear_waiting_for_input ();
7808  error ("%s", error_msg);
7809}
7810
7811/* We specifically use it before defining it, so that gcc doesn't inline it,
7812   otherwise gdb doesn't know how to properly put a breakpoint on it.  */
7813static void x_error_quitter P_ ((Display *, XErrorEvent *));
7814
7815/* This is the first-level handler for X protocol errors.
7816   It calls x_error_quitter or x_error_catcher.  */
7817
7818static int
7819x_error_handler (display, error)
7820     Display *display;
7821     XErrorEvent *error;
7822{
7823  if (x_error_message)
7824    x_error_catcher (display, error);
7825  else
7826    x_error_quitter (display, error);
7827  return 0;
7828}
7829
7830/* This is the usual handler for X protocol errors.
7831   It kills all frames on the display that we got the error for.
7832   If that was the only one, it prints an error message and kills Emacs.  */
7833
7834/* .gdbinit puts a breakpoint here, so make sure it is not inlined.  */
7835
7836#if __GNUC__ >= 3  /* On GCC 3.0 we might get a warning.  */
7837#define NO_INLINE __attribute__((noinline))
7838#else
7839#define NO_INLINE
7840#endif
7841
7842/* Some versions of GNU/Linux define noinline in their headers.  */
7843
7844#ifdef noinline
7845#undef noinline
7846#endif
7847
7848/* On older GCC versions, just putting x_error_quitter
7849   after x_error_handler prevents inlining into the former.  */
7850
7851static void NO_INLINE
7852x_error_quitter (display, error)
7853     Display *display;
7854     XErrorEvent *error;
7855{
7856  char buf[256], buf1[356];
7857
7858  /* Ignore BadName errors.  They can happen because of fonts
7859     or colors that are not defined.  */
7860
7861  if (error->error_code == BadName)
7862    return;
7863
7864  /* Note that there is no real way portable across R3/R4 to get the
7865     original error handler.  */
7866
7867  XGetErrorText (display, error->error_code, buf, sizeof (buf));
7868  sprintf (buf1, "X protocol error: %s on protocol request %d",
7869	   buf, error->request_code);
7870  x_connection_closed (display, buf1);
7871}
7872
7873
7874/* This is the handler for X IO errors, always.
7875   It kills all frames on the display that we lost touch with.
7876   If that was the only one, it prints an error message and kills Emacs.  */
7877
7878static int
7879x_io_error_quitter (display)
7880     Display *display;
7881{
7882  char buf[256];
7883
7884  sprintf (buf, "Connection lost to X server `%s'", DisplayString (display));
7885  x_connection_closed (display, buf);
7886  return 0;
7887}
7888
7889/* Changing the font of the frame.  */
7890
7891/* Give frame F the font named FONTNAME as its default font, and
7892   return the full name of that font.  FONTNAME may be a wildcard
7893   pattern; in that case, we choose some font that fits the pattern.
7894   The return value shows which font we chose.  */
7895
7896Lisp_Object
7897x_new_font (f, fontname)
7898     struct frame *f;
7899     register char *fontname;
7900{
7901  struct font_info *fontp
7902    = FS_LOAD_FONT (f, 0, fontname, -1);
7903
7904  if (!fontp)
7905    return Qnil;
7906
7907  FRAME_FONT (f) = (XFontStruct *) (fontp->font);
7908  FRAME_BASELINE_OFFSET (f) = fontp->baseline_offset;
7909  FRAME_FONTSET (f) = -1;
7910
7911  FRAME_COLUMN_WIDTH (f) = fontp->average_width;
7912  FRAME_SPACE_WIDTH (f) = fontp->space_width;
7913  FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (FRAME_FONT (f));
7914
7915  compute_fringe_widths (f, 1);
7916
7917  /* Compute the scroll bar width in character columns.  */
7918  if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7919    {
7920      int wid = FRAME_COLUMN_WIDTH (f);
7921      FRAME_CONFIG_SCROLL_BAR_COLS (f)
7922	= (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
7923    }
7924  else
7925    {
7926      int wid = FRAME_COLUMN_WIDTH (f);
7927      FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7928    }
7929
7930  /* Now make the frame display the given font.  */
7931  if (FRAME_X_WINDOW (f) != 0)
7932    {
7933      XSetFont (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
7934		FRAME_FONT (f)->fid);
7935      XSetFont (FRAME_X_DISPLAY (f), f->output_data.x->reverse_gc,
7936		FRAME_FONT (f)->fid);
7937      XSetFont (FRAME_X_DISPLAY (f), f->output_data.x->cursor_gc,
7938		FRAME_FONT (f)->fid);
7939
7940      /* Don't change the size of a tip frame; there's no point in
7941	 doing it because it's done in Fx_show_tip, and it leads to
7942	 problems because the tip frame has no widget.  */
7943      if (NILP (tip_frame) || XFRAME (tip_frame) != f)
7944	x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
7945    }
7946
7947  return build_string (fontp->full_name);
7948}
7949
7950/* Give frame F the fontset named FONTSETNAME as its default font, and
7951   return the full name of that fontset.  FONTSETNAME may be a wildcard
7952   pattern; in that case, we choose some fontset that fits the pattern.
7953   The return value shows which fontset we chose.  */
7954
7955Lisp_Object
7956x_new_fontset (f, fontsetname)
7957     struct frame *f;
7958     char *fontsetname;
7959{
7960  int fontset = fs_query_fontset (build_string (fontsetname), 0);
7961  Lisp_Object result;
7962
7963  if (fontset < 0)
7964    return Qnil;
7965
7966  if (FRAME_FONTSET (f) == fontset)
7967    /* This fontset is already set in frame F.  There's nothing more
7968       to do.  */
7969    return fontset_name (fontset);
7970
7971  result = x_new_font (f, (SDATA (fontset_ascii (fontset))));
7972
7973  if (!STRINGP (result))
7974    /* Can't load ASCII font.  */
7975    return Qnil;
7976
7977  /* Since x_new_font doesn't update any fontset information, do it now.  */
7978  FRAME_FONTSET (f) = fontset;
7979
7980#ifdef HAVE_X_I18N
7981  if (FRAME_XIC (f)
7982      && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
7983    xic_set_xfontset (f, SDATA (fontset_ascii (fontset)));
7984#endif
7985
7986  return build_string (fontsetname);
7987}
7988
7989
7990/***********************************************************************
7991			   X Input Methods
7992 ***********************************************************************/
7993
7994#ifdef HAVE_X_I18N
7995
7996#ifdef HAVE_X11R6
7997
7998/* XIM destroy callback function, which is called whenever the
7999   connection to input method XIM dies.  CLIENT_DATA contains a
8000   pointer to the x_display_info structure corresponding to XIM.  */
8001
8002static void
8003xim_destroy_callback (xim, client_data, call_data)
8004     XIM xim;
8005     XPointer client_data;
8006     XPointer call_data;
8007{
8008  struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
8009  Lisp_Object frame, tail;
8010
8011  BLOCK_INPUT;
8012
8013  /* No need to call XDestroyIC.. */
8014  FOR_EACH_FRAME (tail, frame)
8015    {
8016      struct frame *f = XFRAME (frame);
8017      if (FRAME_X_DISPLAY_INFO (f) == dpyinfo)
8018	{
8019	  FRAME_XIC (f) = NULL;
8020          xic_free_xfontset (f);
8021	}
8022    }
8023
8024  /* No need to call XCloseIM.  */
8025  dpyinfo->xim = NULL;
8026  XFree (dpyinfo->xim_styles);
8027  UNBLOCK_INPUT;
8028}
8029
8030#endif /* HAVE_X11R6 */
8031
8032#ifdef HAVE_X11R6
8033/* This isn't prototyped in OSF 5.0 or 5.1a.  */
8034extern char *XSetIMValues P_ ((XIM, ...));
8035#endif
8036
8037/* Open the connection to the XIM server on display DPYINFO.
8038   RESOURCE_NAME is the resource name Emacs uses.  */
8039
8040static void
8041xim_open_dpy (dpyinfo, resource_name)
8042     struct x_display_info *dpyinfo;
8043     char *resource_name;
8044{
8045  XIM xim;
8046
8047#ifdef HAVE_XIM
8048  if (use_xim)
8049    {
8050      xim = XOpenIM (dpyinfo->display, dpyinfo->xrdb, resource_name,
8051		     EMACS_CLASS);
8052      dpyinfo->xim = xim;
8053
8054      if (xim)
8055	{
8056#ifdef HAVE_X11R6
8057	  XIMCallback destroy;
8058#endif
8059
8060	  /* Get supported styles and XIM values.  */
8061	  XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
8062
8063#ifdef HAVE_X11R6
8064	  destroy.callback = xim_destroy_callback;
8065	  destroy.client_data = (XPointer)dpyinfo;
8066	  XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
8067#endif
8068	}
8069    }
8070
8071  else
8072#endif /* HAVE_XIM */
8073    dpyinfo->xim = NULL;
8074}
8075
8076
8077#ifdef HAVE_X11R6_XIM
8078
8079struct xim_inst_t
8080{
8081  struct x_display_info *dpyinfo;
8082  char *resource_name;
8083};
8084
8085/* XIM instantiate callback function, which is called whenever an XIM
8086   server is available.  DISPLAY is the display of the XIM.
8087   CLIENT_DATA contains a pointer to an xim_inst_t structure created
8088   when the callback was registered.  */
8089
8090static void
8091xim_instantiate_callback (display, client_data, call_data)
8092     Display *display;
8093     XPointer client_data;
8094     XPointer call_data;
8095{
8096  struct xim_inst_t *xim_inst = (struct xim_inst_t *) client_data;
8097  struct x_display_info *dpyinfo = xim_inst->dpyinfo;
8098
8099  /* We don't support multiple XIM connections. */
8100  if (dpyinfo->xim)
8101    return;
8102
8103  xim_open_dpy (dpyinfo, xim_inst->resource_name);
8104
8105  /* Create XIC for the existing frames on the same display, as long
8106     as they have no XIC.  */
8107  if (dpyinfo->xim && dpyinfo->reference_count > 0)
8108    {
8109      Lisp_Object tail, frame;
8110
8111      BLOCK_INPUT;
8112      FOR_EACH_FRAME (tail, frame)
8113	{
8114	  struct frame *f = XFRAME (frame);
8115
8116	  if (FRAME_X_DISPLAY_INFO (f) == xim_inst->dpyinfo)
8117	    if (FRAME_XIC (f) == NULL)
8118	      {
8119		create_frame_xic (f);
8120		if (FRAME_XIC_STYLE (f) & XIMStatusArea)
8121		  xic_set_statusarea (f);
8122		if (FRAME_XIC_STYLE (f) & XIMPreeditPosition)
8123		  {
8124		    struct window *w = XWINDOW (f->selected_window);
8125		    xic_set_preeditarea (w, w->cursor.x, w->cursor.y);
8126		  }
8127	      }
8128	}
8129
8130      UNBLOCK_INPUT;
8131    }
8132}
8133
8134#endif /* HAVE_X11R6_XIM */
8135
8136
8137/* Open a connection to the XIM server on display DPYINFO.
8138   RESOURCE_NAME is the resource name for Emacs.  On X11R5, open the
8139   connection only at the first time.  On X11R6, open the connection
8140   in the XIM instantiate callback function.  */
8141
8142static void
8143xim_initialize (dpyinfo, resource_name)
8144     struct x_display_info *dpyinfo;
8145     char *resource_name;
8146{
8147#ifdef HAVE_XIM
8148  if (use_xim)
8149    {
8150#ifdef HAVE_X11R6_XIM
8151      struct xim_inst_t *xim_inst;
8152      int len;
8153
8154      dpyinfo->xim = NULL;
8155      xim_inst = (struct xim_inst_t *) xmalloc (sizeof (struct xim_inst_t));
8156      xim_inst->dpyinfo = dpyinfo;
8157      len = strlen (resource_name);
8158      xim_inst->resource_name = (char *) xmalloc (len + 1);
8159      bcopy (resource_name, xim_inst->resource_name, len + 1);
8160      XRegisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8161				      resource_name, EMACS_CLASS,
8162				      xim_instantiate_callback,
8163				      /* This is XPointer in XFree86
8164					 but (XPointer *) on Tru64, at
8165					 least, hence the configure test.  */
8166				      (XRegisterIMInstantiateCallback_arg6) xim_inst);
8167#else /* not HAVE_X11R6_XIM */
8168      dpyinfo->xim = NULL;
8169      xim_open_dpy (dpyinfo, resource_name);
8170#endif /* not HAVE_X11R6_XIM */
8171
8172    }
8173  else
8174#endif /* HAVE_XIM */
8175    dpyinfo->xim = NULL;
8176}
8177
8178
8179/* Close the connection to the XIM server on display DPYINFO. */
8180
8181static void
8182xim_close_dpy (dpyinfo)
8183     struct x_display_info *dpyinfo;
8184{
8185#ifdef HAVE_XIM
8186  if (use_xim)
8187    {
8188#ifdef HAVE_X11R6_XIM
8189      if (dpyinfo->display)
8190	XUnregisterIMInstantiateCallback (dpyinfo->display, dpyinfo->xrdb,
8191					  NULL, EMACS_CLASS,
8192					  xim_instantiate_callback, NULL);
8193#endif /* not HAVE_X11R6_XIM */
8194      if (dpyinfo->display)
8195	XCloseIM (dpyinfo->xim);
8196      dpyinfo->xim = NULL;
8197      XFree (dpyinfo->xim_styles);
8198    }
8199#endif /* HAVE_XIM */
8200}
8201
8202#endif /* not HAVE_X11R6_XIM */
8203
8204
8205
8206/* Calculate the absolute position in frame F
8207   from its current recorded position values and gravity.  */
8208
8209void
8210x_calc_absolute_position (f)
8211     struct frame *f;
8212{
8213  int flags = f->size_hint_flags;
8214
8215  /* We have nothing to do if the current position
8216     is already for the top-left corner.  */
8217  if (! ((flags & XNegative) || (flags & YNegative)))
8218    return;
8219
8220  /* Treat negative positions as relative to the leftmost bottommost
8221     position that fits on the screen.  */
8222  if (flags & XNegative)
8223    f->left_pos = (FRAME_X_DISPLAY_INFO (f)->width
8224                   - FRAME_PIXEL_WIDTH (f) + f->left_pos);
8225
8226  {
8227    int height = FRAME_PIXEL_HEIGHT (f);
8228
8229#if defined USE_X_TOOLKIT && defined USE_MOTIF
8230    /* Something is fishy here.  When using Motif, starting Emacs with
8231       `-g -0-0', the frame appears too low by a few pixels.
8232
8233       This seems to be so because initially, while Emacs is starting,
8234       the column widget's height and the frame's pixel height are
8235       different.  The column widget's height is the right one.  In
8236       later invocations, when Emacs is up, the frame's pixel height
8237       is right, though.
8238
8239       It's not obvious where the initial small difference comes from.
8240       2000-12-01, gerd.  */
8241
8242    XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
8243#endif
8244
8245  if (flags & YNegative)
8246    f->top_pos = (FRAME_X_DISPLAY_INFO (f)->height - height + f->top_pos);
8247  }
8248
8249  /* The left_pos and top_pos
8250     are now relative to the top and left screen edges,
8251     so the flags should correspond.  */
8252  f->size_hint_flags &= ~ (XNegative | YNegative);
8253}
8254
8255/* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
8256   to really change the position, and 0 when calling from
8257   x_make_frame_visible (in that case, XOFF and YOFF are the current
8258   position values).  It is -1 when calling from x_set_frame_parameters,
8259   which means, do adjust for borders but don't change the gravity.  */
8260
8261void
8262x_set_offset (f, xoff, yoff, change_gravity)
8263     struct frame *f;
8264     register int xoff, yoff;
8265     int change_gravity;
8266{
8267  int modified_top, modified_left;
8268
8269  if (change_gravity != 0)
8270    {
8271      FRAME_X_OUTPUT (f)->left_before_move = f->left_pos;
8272      FRAME_X_OUTPUT (f)->top_before_move = f->top_pos;
8273
8274      f->top_pos = yoff;
8275      f->left_pos = xoff;
8276      f->size_hint_flags &= ~ (XNegative | YNegative);
8277      if (xoff < 0)
8278	f->size_hint_flags |= XNegative;
8279      if (yoff < 0)
8280	f->size_hint_flags |= YNegative;
8281      f->win_gravity = NorthWestGravity;
8282    }
8283  x_calc_absolute_position (f);
8284
8285  BLOCK_INPUT;
8286  x_wm_set_size_hint (f, (long) 0, 0);
8287
8288  modified_left = f->left_pos;
8289  modified_top = f->top_pos;
8290
8291  if (change_gravity != 0 && FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A)
8292    {
8293      /* Some WMs (twm, wmaker at least) has an offset that is smaller
8294         than the WM decorations.  So we use the calculated offset instead
8295         of the WM decoration sizes here (x/y_pixels_outer_diff).  */
8296      modified_left += FRAME_X_OUTPUT (f)->move_offset_left;
8297      modified_top += FRAME_X_OUTPUT (f)->move_offset_top;
8298    }
8299
8300  XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8301               modified_left, modified_top);
8302
8303  x_sync_with_move (f, f->left_pos, f->top_pos,
8304                    FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8305                    ? 1 : 0);
8306
8307  /* change_gravity is non-zero when this function is called from Lisp to
8308     programmatically move a frame.  In that case, we call
8309     x_check_expected_move to discover if we have a "Type A" or "Type B"
8310     window manager, and, for a "Type A" window manager, adjust the position
8311     of the frame.
8312
8313     We call x_check_expected_move if a programmatic move occurred, and
8314     either the window manager type (A/B) is unknown or it is Type A but we
8315     need to compute the top/left offset adjustment for this frame.  */
8316
8317  if (change_gravity != 0 &&
8318      (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_UNKNOWN
8319       || (FRAME_X_DISPLAY_INFO (f)->wm_type == X_WMTYPE_A
8320           && (FRAME_X_OUTPUT (f)->move_offset_left == 0
8321               && FRAME_X_OUTPUT (f)->move_offset_top == 0))))
8322    x_check_expected_move (f, modified_left, modified_top);
8323
8324  UNBLOCK_INPUT;
8325}
8326
8327/* Return non-zero if _NET_SUPPORTING_WM_CHECK window exists and _NET_SUPPORTED
8328   on the root window for frame F contains ATOMNAME.
8329   This is how a WM check shall be done according to the Window Manager
8330   Specification/Extended Window Manager Hints at
8331   http://freedesktop.org/wiki/Standards_2fwm_2dspec.  */
8332
8333static int
8334wm_supports (f, atomname)
8335     struct frame *f;
8336     const char *atomname;
8337{
8338  Atom actual_type;
8339  unsigned long actual_size, bytes_remaining;
8340  int i, rc, actual_format;
8341  Atom prop_atom;
8342  Window wmcheck_window;
8343  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
8344  Window target_window = dpyinfo->root_window;
8345  long max_len = 65536;
8346  Display *dpy = FRAME_X_DISPLAY (f);
8347  unsigned char *tmp_data = NULL;
8348  Atom target_type = XA_WINDOW;
8349  Atom want_atom;
8350
8351  BLOCK_INPUT;
8352
8353  prop_atom = XInternAtom (dpy, "_NET_SUPPORTING_WM_CHECK", False);
8354
8355  x_catch_errors (dpy);
8356  rc = XGetWindowProperty (dpy, target_window,
8357                           prop_atom, 0, max_len, False, target_type,
8358                           &actual_type, &actual_format, &actual_size,
8359                           &bytes_remaining, &tmp_data);
8360
8361  if (rc != Success || actual_type != XA_WINDOW || x_had_errors_p (dpy))
8362    {
8363      if (tmp_data) XFree (tmp_data);
8364      x_uncatch_errors ();
8365      UNBLOCK_INPUT;
8366      return 0;
8367    }
8368
8369  wmcheck_window = *(Window *) tmp_data;
8370  XFree (tmp_data);
8371
8372  /* Check if window exists. */
8373  XSelectInput (dpy, wmcheck_window, StructureNotifyMask);
8374  x_sync (f);
8375  if (x_had_errors_p (dpy))
8376    {
8377      x_uncatch_errors ();
8378      UNBLOCK_INPUT;
8379      return 0;
8380    }
8381
8382  if (dpyinfo->net_supported_window != wmcheck_window)
8383    {
8384      /* Window changed, reload atoms */
8385      if (dpyinfo->net_supported_atoms != NULL)
8386        XFree (dpyinfo->net_supported_atoms);
8387      dpyinfo->net_supported_atoms = NULL;
8388      dpyinfo->nr_net_supported_atoms = 0;
8389      dpyinfo->net_supported_window = 0;
8390
8391      target_type = XA_ATOM;
8392      prop_atom = XInternAtom (dpy, "_NET_SUPPORTED", False);
8393      tmp_data = NULL;
8394      rc = XGetWindowProperty (dpy, target_window,
8395                               prop_atom, 0, max_len, False, target_type,
8396                               &actual_type, &actual_format, &actual_size,
8397                               &bytes_remaining, &tmp_data);
8398
8399      if (rc != Success || actual_type != XA_ATOM || x_had_errors_p (dpy))
8400        {
8401          if (tmp_data) XFree (tmp_data);
8402          x_uncatch_errors ();
8403          UNBLOCK_INPUT;
8404          return 0;
8405        }
8406
8407      dpyinfo->net_supported_atoms = (Atom *)tmp_data;
8408      dpyinfo->nr_net_supported_atoms = actual_size;
8409      dpyinfo->net_supported_window = wmcheck_window;
8410    }
8411
8412  rc = 0;
8413  want_atom = XInternAtom (dpy, atomname, False);
8414
8415  for (i = 0; rc == 0 && i < dpyinfo->nr_net_supported_atoms; ++i)
8416    rc = dpyinfo->net_supported_atoms[i] == want_atom;
8417
8418  x_uncatch_errors ();
8419  UNBLOCK_INPUT;
8420
8421  return rc;
8422}
8423
8424/* Do fullscreen as specified in extended window manager hints */
8425
8426static int
8427do_ewmh_fullscreen (f)
8428     struct frame *f;
8429{
8430  int have_net_atom = wm_supports (f, "_NET_WM_STATE");
8431
8432  /* Some window managers don't say they support _NET_WM_STATE, but they do say
8433     they support _NET_WM_STATE_FULLSCREEN.  Try that also.  */
8434  if (!have_net_atom)
8435      have_net_atom = wm_supports (f, "_NET_WM_STATE_FULLSCREEN");
8436
8437  if (have_net_atom)
8438    {
8439      Lisp_Object frame;
8440      const char *atom = "_NET_WM_STATE";
8441      const char *fs = "_NET_WM_STATE_FULLSCREEN";
8442      const char *fw = "_NET_WM_STATE_MAXIMIZED_HORZ";
8443      const char *fh = "_NET_WM_STATE_MAXIMIZED_VERT";
8444      const char *what = NULL;
8445
8446      XSETFRAME (frame, f);
8447
8448      /* If there are _NET_ atoms we assume we have extended window manager
8449         hints.  */
8450      switch (f->want_fullscreen)
8451        {
8452        case FULLSCREEN_BOTH:
8453          what = fs;
8454          break;
8455        case FULLSCREEN_WIDTH:
8456          what = fw;
8457          break;
8458        case FULLSCREEN_HEIGHT:
8459          what = fh;
8460          break;
8461        }
8462
8463      if (what != NULL && !wm_supports (f, what)) return 0;
8464
8465
8466      Fx_send_client_event (frame, make_number (0), frame,
8467                            make_unibyte_string (atom, strlen (atom)),
8468                            make_number (32),
8469                            Fcons (make_number (0), /* Remove */
8470                                   Fcons
8471                                   (make_unibyte_string (fs,
8472                                                         strlen (fs)),
8473                                    Qnil)));
8474      Fx_send_client_event (frame, make_number (0), frame,
8475                            make_unibyte_string (atom, strlen (atom)),
8476                            make_number (32),
8477                            Fcons (make_number (0), /* Remove */
8478                                   Fcons
8479                                   (make_unibyte_string (fh,
8480                                                         strlen (fh)),
8481                                    Qnil)));
8482      Fx_send_client_event (frame, make_number (0), frame,
8483                            make_unibyte_string (atom, strlen (atom)),
8484                            make_number (32),
8485                            Fcons (make_number (0), /* Remove */
8486                                   Fcons
8487                                   (make_unibyte_string (fw,
8488                                                         strlen (fw)),
8489                                    Qnil)));
8490      f->want_fullscreen = FULLSCREEN_NONE;
8491      if (what != NULL)
8492        Fx_send_client_event (frame, make_number (0), frame,
8493                              make_unibyte_string (atom, strlen (atom)),
8494                              make_number (32),
8495                              Fcons (make_number (1), /* Add */
8496                                     Fcons
8497                                     (make_unibyte_string (what,
8498                                                           strlen (what)),
8499                                      Qnil)));
8500    }
8501
8502  return have_net_atom;
8503}
8504
8505static void
8506XTfullscreen_hook (f)
8507     FRAME_PTR f;
8508{
8509  if (f->async_visible)
8510    {
8511      BLOCK_INPUT;
8512      do_ewmh_fullscreen (f);
8513      x_sync (f);
8514      UNBLOCK_INPUT;
8515    }
8516}
8517
8518
8519/* Check if we need to resize the frame due to a fullscreen request.
8520   If so needed, resize the frame. */
8521static void
8522x_check_fullscreen (f)
8523     struct frame *f;
8524{
8525  if (f->want_fullscreen & FULLSCREEN_BOTH)
8526    {
8527      int width, height, ign;
8528
8529      if (do_ewmh_fullscreen (f))
8530        return;
8531
8532      x_real_positions (f, &f->left_pos, &f->top_pos);
8533
8534      x_fullscreen_adjust (f, &width, &height, &ign, &ign);
8535
8536      /* We do not need to move the window, it shall be taken care of
8537         when setting WM manager hints.
8538         If the frame is visible already, the position is checked by
8539         x_check_expected_move. */
8540      if (FRAME_COLS (f) != width || FRAME_LINES (f) != height)
8541        {
8542          change_frame_size (f, height, width, 0, 1, 0);
8543          SET_FRAME_GARBAGED (f);
8544          cancel_mouse_face (f);
8545
8546          /* Wait for the change of frame size to occur */
8547          f->want_fullscreen |= FULLSCREEN_WAIT;
8548        }
8549    }
8550}
8551
8552/* This function is called by x_set_offset to determine whether the window
8553   manager interfered with the positioning of the frame.  Type A window
8554   managers position the surrounding window manager decorations a small
8555   amount above and left of the user-supplied position.  Type B window
8556   managers position the surrounding window manager decorations at the
8557   user-specified position.  If we detect a Type A window manager, we
8558   compensate by moving the window right and down by the proper amount.  */
8559
8560static void
8561x_check_expected_move (f, expected_left, expected_top)
8562     struct frame *f;
8563     int expected_left;
8564     int expected_top;
8565{
8566  int current_left = 0, current_top = 0;
8567
8568  /* x_real_positions returns the left and top offsets of the outermost
8569     window manager window around the frame.  */
8570
8571  x_real_positions (f, &current_left, &current_top);
8572
8573  if (current_left != expected_left || current_top != expected_top)
8574      {
8575      /* It's a "Type A" window manager. */
8576
8577      int adjusted_left;
8578      int adjusted_top;
8579
8580        FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_A;
8581      FRAME_X_OUTPUT (f)->move_offset_left = expected_left - current_left;
8582      FRAME_X_OUTPUT (f)->move_offset_top = expected_top - current_top;
8583
8584      /* Now fix the mispositioned frame's location. */
8585
8586      adjusted_left = expected_left + FRAME_X_OUTPUT (f)->move_offset_left;
8587      adjusted_top = expected_top + FRAME_X_OUTPUT (f)->move_offset_top;
8588
8589      XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8590                   adjusted_left, adjusted_top);
8591
8592      x_sync_with_move (f, expected_left, expected_top, 0);
8593      }
8594  else
8595    /* It's a "Type B" window manager.  We don't have to adjust the
8596       frame's position. */
8597
8598      FRAME_X_DISPLAY_INFO (f)->wm_type = X_WMTYPE_B;
8599}
8600
8601
8602/* Wait for XGetGeometry to return up-to-date position information for a
8603   recently-moved frame.  Call this immediately after calling XMoveWindow.
8604   If FUZZY is non-zero, then LEFT and TOP are just estimates of where the
8605   frame has been moved to, so we use a fuzzy position comparison instead
8606   of an exact comparison.  */
8607
8608static void
8609x_sync_with_move (f, left, top, fuzzy)
8610    struct frame *f;
8611    int left, top, fuzzy;
8612{
8613  int count = 0;
8614
8615  while (count++ < 50)
8616    {
8617      int current_left = 0, current_top = 0;
8618
8619      /* In theory, this call to XSync only needs to happen once, but in
8620         practice, it doesn't seem to work, hence the need for the surrounding
8621         loop.  */
8622
8623      XSync (FRAME_X_DISPLAY (f), False);
8624      x_real_positions (f, &current_left, &current_top);
8625
8626      if (fuzzy)
8627        {
8628          /* The left fuzz-factor is 10 pixels.  The top fuzz-factor is 40
8629             pixels.  */
8630
8631          if (abs (current_left - left) <= 10 && abs (current_top - top) <= 40)
8632            return;
8633  }
8634      else if (current_left == left && current_top == top)
8635        return;
8636    }
8637
8638  /* As a last resort, just wait 0.5 seconds and hope that XGetGeometry
8639     will then return up-to-date position info. */
8640
8641  wait_reading_process_output (0, 500000, 0, 0, Qnil, NULL, 0);
8642}
8643
8644
8645/* Change the size of frame F's X window to COLS/ROWS in the case F
8646   doesn't have a widget.  If CHANGE_GRAVITY is 1, we change to
8647   top-left-corner window gravity for this size change and subsequent
8648   size changes.  Otherwise we leave the window gravity unchanged.  */
8649
8650static void
8651x_set_window_size_1 (f, change_gravity, cols, rows)
8652     struct frame *f;
8653     int change_gravity;
8654     int cols, rows;
8655{
8656  int pixelwidth, pixelheight;
8657
8658  check_frame_size (f, &rows, &cols);
8659  f->scroll_bar_actual_width
8660    = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
8661       ? 0
8662       : FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0
8663       ? FRAME_CONFIG_SCROLL_BAR_WIDTH (f)
8664       : (FRAME_CONFIG_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)));
8665
8666  compute_fringe_widths (f, 0);
8667
8668  pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
8669  pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
8670
8671  f->win_gravity = NorthWestGravity;
8672  x_wm_set_size_hint (f, (long) 0, 0);
8673
8674  XSync (FRAME_X_DISPLAY (f), False);
8675  XResizeWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8676		 pixelwidth, pixelheight);
8677
8678  /* Now, strictly speaking, we can't be sure that this is accurate,
8679     but the window manager will get around to dealing with the size
8680     change request eventually, and we'll hear how it went when the
8681     ConfigureNotify event gets here.
8682
8683     We could just not bother storing any of this information here,
8684     and let the ConfigureNotify event set everything up, but that
8685     might be kind of confusing to the Lisp code, since size changes
8686     wouldn't be reported in the frame parameters until some random
8687     point in the future when the ConfigureNotify event arrives.
8688
8689     We pass 1 for DELAY since we can't run Lisp code inside of
8690     a BLOCK_INPUT.  */
8691  change_frame_size (f, rows, cols, 0, 1, 0);
8692  FRAME_PIXEL_WIDTH (f) = pixelwidth;
8693  FRAME_PIXEL_HEIGHT (f) = pixelheight;
8694
8695  /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
8696     receive in the ConfigureNotify event; if we get what we asked
8697     for, then the event won't cause the screen to become garbaged, so
8698     we have to make sure to do it here.  */
8699  SET_FRAME_GARBAGED (f);
8700
8701  XFlush (FRAME_X_DISPLAY (f));
8702}
8703
8704
8705/* Call this to change the size of frame F's x-window.
8706   If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
8707   for this size change and subsequent size changes.
8708   Otherwise we leave the window gravity unchanged.  */
8709
8710void
8711x_set_window_size (f, change_gravity, cols, rows)
8712     struct frame *f;
8713     int change_gravity;
8714     int cols, rows;
8715{
8716  BLOCK_INPUT;
8717
8718#ifdef USE_GTK
8719  if (FRAME_GTK_WIDGET (f))
8720    xg_frame_set_char_size (f, cols, rows);
8721  else
8722    x_set_window_size_1 (f, change_gravity, cols, rows);
8723#elif USE_X_TOOLKIT
8724
8725  if (f->output_data.x->widget != NULL)
8726    {
8727      /* The x and y position of the widget is clobbered by the
8728	 call to XtSetValues within EmacsFrameSetCharSize.
8729	 This is a real kludge, but I don't understand Xt so I can't
8730	 figure out a correct fix.  Can anyone else tell me? -- rms.  */
8731      int xpos = f->output_data.x->widget->core.x;
8732      int ypos = f->output_data.x->widget->core.y;
8733      EmacsFrameSetCharSize (f->output_data.x->edit_widget, cols, rows);
8734      f->output_data.x->widget->core.x = xpos;
8735      f->output_data.x->widget->core.y = ypos;
8736    }
8737  else
8738    x_set_window_size_1 (f, change_gravity, cols, rows);
8739
8740#else /* not USE_X_TOOLKIT */
8741
8742  x_set_window_size_1 (f, change_gravity, cols, rows);
8743
8744#endif /* not USE_X_TOOLKIT */
8745
8746  /* If cursor was outside the new size, mark it as off.  */
8747  mark_window_cursors_off (XWINDOW (f->root_window));
8748
8749  /* Clear out any recollection of where the mouse highlighting was,
8750     since it might be in a place that's outside the new frame size.
8751     Actually checking whether it is outside is a pain in the neck,
8752     so don't try--just let the highlighting be done afresh with new size.  */
8753  cancel_mouse_face (f);
8754
8755  UNBLOCK_INPUT;
8756}
8757
8758/* Mouse warping.  */
8759
8760void
8761x_set_mouse_position (f, x, y)
8762     struct frame *f;
8763     int x, y;
8764{
8765  int pix_x, pix_y;
8766
8767  pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
8768  pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
8769
8770  if (pix_x < 0) pix_x = 0;
8771  if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
8772
8773  if (pix_y < 0) pix_y = 0;
8774  if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
8775
8776  BLOCK_INPUT;
8777
8778  XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8779		0, 0, 0, 0, pix_x, pix_y);
8780  UNBLOCK_INPUT;
8781}
8782
8783/* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F.  */
8784
8785void
8786x_set_mouse_pixel_position (f, pix_x, pix_y)
8787     struct frame *f;
8788     int pix_x, pix_y;
8789{
8790  BLOCK_INPUT;
8791
8792  XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
8793		0, 0, 0, 0, pix_x, pix_y);
8794  UNBLOCK_INPUT;
8795}
8796
8797/* focus shifting, raising and lowering.  */
8798
8799void
8800x_focus_on_frame (f)
8801     struct frame *f;
8802{
8803#if 0  /* This proves to be unpleasant.  */
8804  x_raise_frame (f);
8805#endif
8806#if 0
8807  /* I don't think that the ICCCM allows programs to do things like this
8808     without the interaction of the window manager.  Whatever you end up
8809     doing with this code, do it to x_unfocus_frame too.  */
8810  XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
8811		  RevertToPointerRoot, CurrentTime);
8812#endif /* ! 0 */
8813}
8814
8815void
8816x_unfocus_frame (f)
8817     struct frame *f;
8818{
8819#if 0
8820  /* Look at the remarks in x_focus_on_frame.  */
8821  if (FRAME_X_DISPLAY_INFO (f)->x_focus_frame == f)
8822    XSetInputFocus (FRAME_X_DISPLAY (f), PointerRoot,
8823		    RevertToPointerRoot, CurrentTime);
8824#endif /* ! 0 */
8825}
8826
8827/* Raise frame F.  */
8828
8829void
8830x_raise_frame (f)
8831     struct frame *f;
8832{
8833  BLOCK_INPUT;
8834  if (f->async_visible)
8835    XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8836
8837  XFlush (FRAME_X_DISPLAY (f));
8838  UNBLOCK_INPUT;
8839}
8840
8841/* Lower frame F.  */
8842
8843void
8844x_lower_frame (f)
8845     struct frame *f;
8846{
8847  if (f->async_visible)
8848    {
8849      BLOCK_INPUT;
8850      XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
8851      XFlush (FRAME_X_DISPLAY (f));
8852      UNBLOCK_INPUT;
8853    }
8854}
8855
8856static void
8857XTframe_raise_lower (f, raise_flag)
8858     FRAME_PTR f;
8859     int raise_flag;
8860{
8861  if (raise_flag)
8862    {
8863      /* The following code is needed for `raise-frame' to work on
8864	 some versions of metacity; see Window Manager
8865	 Specification/Extended Window Manager Hints at
8866	 http://freedesktop.org/wiki/Standards_2fwm_2dspec  */
8867
8868#if 0
8869      /* However, on other versions (metacity 2.17.2-1.fc7), it
8870	 reportedly causes hangs when resizing frames.  */
8871
8872      const char *atom = "_NET_ACTIVE_WINDOW";
8873      if (f->async_visible && wm_supports (f, atom))
8874        {
8875          Lisp_Object frame;
8876          XSETFRAME (frame, f);
8877          Fx_send_client_event (frame, make_number (0), frame,
8878                                make_unibyte_string (atom, strlen (atom)),
8879                                make_number (32),
8880                                Fcons (make_number (1),
8881                                       Fcons (make_number (last_user_time),
8882                                              Qnil)));
8883        }
8884      else
8885#endif
8886        x_raise_frame (f);
8887    }
8888  else
8889    x_lower_frame (f);
8890}
8891
8892/* Change of visibility.  */
8893
8894/* This tries to wait until the frame is really visible.
8895   However, if the window manager asks the user where to position
8896   the frame, this will return before the user finishes doing that.
8897   The frame will not actually be visible at that time,
8898   but it will become visible later when the window manager
8899   finishes with it.  */
8900
8901void
8902x_make_frame_visible (f)
8903     struct frame *f;
8904{
8905  Lisp_Object type;
8906  int original_top, original_left;
8907  int retry_count = 2;
8908
8909 retry:
8910
8911  BLOCK_INPUT;
8912
8913  type = x_icon_type (f);
8914  if (!NILP (type))
8915    x_bitmap_icon (f, type);
8916
8917  if (! FRAME_VISIBLE_P (f))
8918    {
8919      /* We test FRAME_GARBAGED_P here to make sure we don't
8920	 call x_set_offset a second time
8921	 if we get to x_make_frame_visible a second time
8922	 before the window gets really visible.  */
8923      if (! FRAME_ICONIFIED_P (f)
8924	  && ! f->output_data.x->asked_for_visible)
8925	x_set_offset (f, f->left_pos, f->top_pos, 0);
8926
8927      f->output_data.x->asked_for_visible = 1;
8928
8929      if (! EQ (Vx_no_window_manager, Qt))
8930	x_wm_set_window_state (f, NormalState);
8931#ifdef USE_X_TOOLKIT
8932      /* This was XtPopup, but that did nothing for an iconified frame.  */
8933      XtMapWidget (f->output_data.x->widget);
8934#else /* not USE_X_TOOLKIT */
8935#ifdef USE_GTK
8936      gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
8937      gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
8938#else
8939      XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
8940#endif /* not USE_GTK */
8941#endif /* not USE_X_TOOLKIT */
8942#if 0 /* This seems to bring back scroll bars in the wrong places
8943	 if the window configuration has changed.  They seem
8944	 to come back ok without this.  */
8945      if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
8946	XMapSubwindows (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
8947#endif
8948    }
8949
8950  XFlush (FRAME_X_DISPLAY (f));
8951
8952  /* Synchronize to ensure Emacs knows the frame is visible
8953     before we do anything else.  We do this loop with input not blocked
8954     so that incoming events are handled.  */
8955  {
8956    Lisp_Object frame;
8957    int count;
8958    /* This must be before UNBLOCK_INPUT
8959       since events that arrive in response to the actions above
8960       will set it when they are handled.  */
8961    int previously_visible = f->output_data.x->has_been_visible;
8962
8963    original_left = f->left_pos;
8964    original_top = f->top_pos;
8965
8966    /* This must come after we set COUNT.  */
8967    UNBLOCK_INPUT;
8968
8969    /* We unblock here so that arriving X events are processed.  */
8970
8971    /* Now move the window back to where it was "supposed to be".
8972       But don't do it if the gravity is negative.
8973       When the gravity is negative, this uses a position
8974       that is 3 pixels too low.  Perhaps that's really the border width.
8975
8976       Don't do this if the window has never been visible before,
8977       because the window manager may choose the position
8978       and we don't want to override it.  */
8979
8980    if (! FRAME_VISIBLE_P (f) && ! FRAME_ICONIFIED_P (f)
8981	&& f->win_gravity == NorthWestGravity
8982	&& previously_visible)
8983      {
8984	Drawable rootw;
8985	int x, y;
8986	unsigned int width, height, border, depth;
8987
8988	BLOCK_INPUT;
8989
8990	/* On some window managers (such as FVWM) moving an existing
8991	   window, even to the same place, causes the window manager
8992	   to introduce an offset.  This can cause the window to move
8993	   to an unexpected location.  Check the geometry (a little
8994	   slow here) and then verify that the window is in the right
8995	   place.  If the window is not in the right place, move it
8996	   there, and take the potential window manager hit.  */
8997	XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
8998		      &rootw, &x, &y, &width, &height, &border, &depth);
8999
9000	if (original_left != x || original_top != y)
9001	  XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
9002		       original_left, original_top);
9003
9004	UNBLOCK_INPUT;
9005      }
9006
9007    XSETFRAME (frame, f);
9008
9009    /* Wait until the frame is visible.  Process X events until a
9010       MapNotify event has been seen, or until we think we won't get a
9011       MapNotify at all..  */
9012    for (count = input_signal_count + 10;
9013	 input_signal_count < count && !FRAME_VISIBLE_P (f);)
9014      {
9015	/* Force processing of queued events.  */
9016	x_sync (f);
9017
9018	/* Machines that do polling rather than SIGIO have been
9019	   observed to go into a busy-wait here.  So we'll fake an
9020	   alarm signal to let the handler know that there's something
9021	   to be read.  We used to raise a real alarm, but it seems
9022	   that the handler isn't always enabled here.  This is
9023	   probably a bug.  */
9024	if (input_polling_used ())
9025	  {
9026	    /* It could be confusing if a real alarm arrives while
9027	       processing the fake one.  Turn it off and let the
9028	       handler reset it.  */
9029	    extern void poll_for_input_1 P_ ((void));
9030	    int old_poll_suppress_count = poll_suppress_count;
9031	    poll_suppress_count = 1;
9032	    poll_for_input_1 ();
9033	    poll_suppress_count = old_poll_suppress_count;
9034	  }
9035
9036	/* See if a MapNotify event has been processed.  */
9037	FRAME_SAMPLE_VISIBILITY (f);
9038      }
9039
9040    /* 2000-09-28: In
9041
9042       (let ((f (selected-frame)))
9043          (iconify-frame f)
9044	  (raise-frame f))
9045
9046       the frame is not raised with various window managers on
9047       FreeBSD, GNU/Linux and Solaris.  It turns out that, for some
9048       unknown reason, the call to XtMapWidget is completely ignored.
9049       Mapping the widget a second time works.  */
9050
9051    if (!FRAME_VISIBLE_P (f) && --retry_count > 0)
9052      goto retry;
9053  }
9054}
9055
9056/* Change from mapped state to withdrawn state.  */
9057
9058/* Make the frame visible (mapped and not iconified).  */
9059
9060void
9061x_make_frame_invisible (f)
9062     struct frame *f;
9063{
9064  Window window;
9065
9066  /* Use the frame's outermost window, not the one we normally draw on.  */
9067  window = FRAME_OUTER_WINDOW (f);
9068
9069  /* Don't keep the highlight on an invisible frame.  */
9070  if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9071    FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9072
9073#if 0/* This might add unreliability; I don't trust it -- rms.  */
9074  if (! f->async_visible && ! f->async_iconified)
9075    return;
9076#endif
9077
9078  BLOCK_INPUT;
9079
9080  /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
9081     that the current position of the window is user-specified, rather than
9082     program-specified, so that when the window is mapped again, it will be
9083     placed at the same location, without forcing the user to position it
9084     by hand again (they have already done that once for this window.)  */
9085  x_wm_set_size_hint (f, (long) 0, 1);
9086
9087#ifdef USE_GTK
9088  if (FRAME_GTK_OUTER_WIDGET (f))
9089    gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
9090  else
9091#endif
9092  {
9093#ifdef HAVE_X11R4
9094
9095  if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
9096			 DefaultScreen (FRAME_X_DISPLAY (f))))
9097    {
9098      UNBLOCK_INPUT_RESIGNAL;
9099      error ("Can't notify window manager of window withdrawal");
9100    }
9101#else /* ! defined (HAVE_X11R4) */
9102
9103  /*  Tell the window manager what we're going to do.  */
9104  if (! EQ (Vx_no_window_manager, Qt))
9105    {
9106      XEvent unmap;
9107
9108      unmap.xunmap.type = UnmapNotify;
9109      unmap.xunmap.window = window;
9110      unmap.xunmap.event = DefaultRootWindow (FRAME_X_DISPLAY (f));
9111      unmap.xunmap.from_configure = False;
9112      if (! XSendEvent (FRAME_X_DISPLAY (f),
9113			DefaultRootWindow (FRAME_X_DISPLAY (f)),
9114			False,
9115			SubstructureRedirectMaskSubstructureNotifyMask,
9116			&unmap))
9117	{
9118	  UNBLOCK_INPUT_RESIGNAL;
9119	  error ("Can't notify window manager of withdrawal");
9120	}
9121    }
9122
9123  /* Unmap the window ourselves.  Cheeky!  */
9124  XUnmapWindow (FRAME_X_DISPLAY (f), window);
9125#endif /* ! defined (HAVE_X11R4) */
9126  }
9127
9128  /* We can't distinguish this from iconification
9129     just by the event that we get from the server.
9130     So we can't win using the usual strategy of letting
9131     FRAME_SAMPLE_VISIBILITY set this.  So do it by hand,
9132     and synchronize with the server to make sure we agree.  */
9133  f->visible = 0;
9134  FRAME_ICONIFIED_P (f) = 0;
9135  f->async_visible = 0;
9136  f->async_iconified = 0;
9137
9138  x_sync (f);
9139
9140  UNBLOCK_INPUT;
9141}
9142
9143/* Change window state from mapped to iconified.  */
9144
9145void
9146x_iconify_frame (f)
9147     struct frame *f;
9148{
9149  int result;
9150  Lisp_Object type;
9151
9152  /* Don't keep the highlight on an invisible frame.  */
9153  if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
9154    FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
9155
9156  if (f->async_iconified)
9157    return;
9158
9159  BLOCK_INPUT;
9160
9161  FRAME_SAMPLE_VISIBILITY (f);
9162
9163  type = x_icon_type (f);
9164  if (!NILP (type))
9165    x_bitmap_icon (f, type);
9166
9167#ifdef USE_GTK
9168  if (FRAME_GTK_OUTER_WIDGET (f))
9169    {
9170      if (! FRAME_VISIBLE_P (f))
9171        gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
9172
9173      gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
9174      f->iconified = 1;
9175      f->visible = 1;
9176      f->async_iconified = 1;
9177      f->async_visible = 0;
9178      UNBLOCK_INPUT;
9179      return;
9180    }
9181#endif
9182
9183#ifdef USE_X_TOOLKIT
9184
9185  if (! FRAME_VISIBLE_P (f))
9186    {
9187      if (! EQ (Vx_no_window_manager, Qt))
9188	x_wm_set_window_state (f, IconicState);
9189      /* This was XtPopup, but that did nothing for an iconified frame.  */
9190      XtMapWidget (f->output_data.x->widget);
9191      /* The server won't give us any event to indicate
9192	 that an invisible frame was changed to an icon,
9193	 so we have to record it here.  */
9194      f->iconified = 1;
9195      f->visible = 1;
9196      f->async_iconified = 1;
9197      f->async_visible = 0;
9198      UNBLOCK_INPUT;
9199      return;
9200    }
9201
9202  result = XIconifyWindow (FRAME_X_DISPLAY (f),
9203			   XtWindow (f->output_data.x->widget),
9204			   DefaultScreen (FRAME_X_DISPLAY (f)));
9205  UNBLOCK_INPUT;
9206
9207  if (!result)
9208    error ("Can't notify window manager of iconification");
9209
9210  f->async_iconified = 1;
9211  f->async_visible = 0;
9212
9213
9214  BLOCK_INPUT;
9215  XFlush (FRAME_X_DISPLAY (f));
9216  UNBLOCK_INPUT;
9217#else /* not USE_X_TOOLKIT */
9218
9219  /* Make sure the X server knows where the window should be positioned,
9220     in case the user deiconifies with the window manager.  */
9221  if (! FRAME_VISIBLE_P (f) && !FRAME_ICONIFIED_P (f))
9222    x_set_offset (f, f->left_pos, f->top_pos, 0);
9223
9224  /* Since we don't know which revision of X we're running, we'll use both
9225     the X11R3 and X11R4 techniques.  I don't know if this is a good idea.  */
9226
9227  /* X11R4: send a ClientMessage to the window manager using the
9228     WM_CHANGE_STATE type.  */
9229  {
9230    XEvent message;
9231
9232    message.xclient.window = FRAME_X_WINDOW (f);
9233    message.xclient.type = ClientMessage;
9234    message.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_change_state;
9235    message.xclient.format = 32;
9236    message.xclient.data.l[0] = IconicState;
9237
9238    if (! XSendEvent (FRAME_X_DISPLAY (f),
9239		      DefaultRootWindow (FRAME_X_DISPLAY (f)),
9240		      False,
9241		      SubstructureRedirectMask | SubstructureNotifyMask,
9242		      &message))
9243      {
9244	UNBLOCK_INPUT_RESIGNAL;
9245	error ("Can't notify window manager of iconification");
9246      }
9247  }
9248
9249  /* X11R3: set the initial_state field of the window manager hints to
9250     IconicState.  */
9251  x_wm_set_window_state (f, IconicState);
9252
9253  if (!FRAME_VISIBLE_P (f))
9254    {
9255      /* If the frame was withdrawn, before, we must map it.  */
9256      XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9257    }
9258
9259  f->async_iconified = 1;
9260  f->async_visible = 0;
9261
9262  XFlush (FRAME_X_DISPLAY (f));
9263  UNBLOCK_INPUT;
9264#endif /* not USE_X_TOOLKIT */
9265}
9266
9267
9268/* Free X resources of frame F.  */
9269
9270void
9271x_free_frame_resources (f)
9272     struct frame *f;
9273{
9274  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9275  Lisp_Object bar;
9276  struct scroll_bar *b;
9277
9278  BLOCK_INPUT;
9279
9280  /* If a display connection is dead, don't try sending more
9281     commands to the X server.  */
9282  if (dpyinfo->display)
9283    {
9284      if (f->output_data.x->icon_desc)
9285	XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
9286
9287#ifdef USE_X_TOOLKIT
9288      /* Explicitly destroy the scroll bars of the frame.  Without
9289	 this, we get "BadDrawable" errors from the toolkit later on,
9290	 presumably from expose events generated for the disappearing
9291	 toolkit scroll bars.  */
9292      for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
9293	{
9294	  b = XSCROLL_BAR (bar);
9295	  x_scroll_bar_remove (b);
9296	}
9297#endif
9298
9299#ifdef HAVE_X_I18N
9300      if (FRAME_XIC (f))
9301	free_frame_xic (f);
9302#endif
9303
9304#ifdef USE_X_TOOLKIT
9305      if (f->output_data.x->widget)
9306	{
9307	  XtDestroyWidget (f->output_data.x->widget);
9308	  f->output_data.x->widget = NULL;
9309	}
9310      /* Tooltips don't have widgets, only a simple X window, even if
9311	 we are using a toolkit.  */
9312      else if (FRAME_X_WINDOW (f))
9313	XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9314
9315      free_frame_menubar (f);
9316#else  /* !USE_X_TOOLKIT */
9317
9318#ifdef USE_GTK
9319      /* In the GTK version, tooltips are normal X
9320         frames.  We must check and free both types. */
9321      if (FRAME_GTK_OUTER_WIDGET (f))
9322        {
9323          gtk_widget_destroy (FRAME_GTK_OUTER_WIDGET (f));
9324          FRAME_X_WINDOW (f) = 0; /* Set to avoid XDestroyWindow below */
9325          FRAME_GTK_OUTER_WIDGET (f) = 0;
9326        }
9327#endif /* USE_GTK */
9328
9329      if (FRAME_X_WINDOW (f))
9330	XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
9331#endif /* !USE_X_TOOLKIT */
9332
9333      unload_color (f, f->output_data.x->foreground_pixel);
9334      unload_color (f, f->output_data.x->background_pixel);
9335      unload_color (f, f->output_data.x->cursor_pixel);
9336      unload_color (f, f->output_data.x->cursor_foreground_pixel);
9337      unload_color (f, f->output_data.x->border_pixel);
9338      unload_color (f, f->output_data.x->mouse_pixel);
9339
9340      if (f->output_data.x->scroll_bar_background_pixel != -1)
9341	unload_color (f, f->output_data.x->scroll_bar_background_pixel);
9342      if (f->output_data.x->scroll_bar_foreground_pixel != -1)
9343	unload_color (f, f->output_data.x->scroll_bar_foreground_pixel);
9344#ifdef USE_TOOLKIT_SCROLL_BARS
9345      /* Scrollbar shadow colors.  */
9346      if (f->output_data.x->scroll_bar_top_shadow_pixel != -1)
9347	unload_color (f, f->output_data.x->scroll_bar_top_shadow_pixel);
9348      if (f->output_data.x->scroll_bar_bottom_shadow_pixel != -1)
9349	unload_color (f, f->output_data.x->scroll_bar_bottom_shadow_pixel);
9350#endif /* USE_TOOLKIT_SCROLL_BARS */
9351      if (f->output_data.x->white_relief.allocated_p)
9352	unload_color (f, f->output_data.x->white_relief.pixel);
9353      if (f->output_data.x->black_relief.allocated_p)
9354	unload_color (f, f->output_data.x->black_relief.pixel);
9355
9356      if (FRAME_FACE_CACHE (f))
9357	free_frame_faces (f);
9358
9359      x_free_gcs (f);
9360      XFlush (FRAME_X_DISPLAY (f));
9361    }
9362
9363  if (f->output_data.x->saved_menu_event)
9364    xfree (f->output_data.x->saved_menu_event);
9365
9366  xfree (f->output_data.x);
9367  f->output_data.x = NULL;
9368
9369  if (f == dpyinfo->x_focus_frame)
9370    dpyinfo->x_focus_frame = 0;
9371  if (f == dpyinfo->x_focus_event_frame)
9372    dpyinfo->x_focus_event_frame = 0;
9373  if (f == dpyinfo->x_highlight_frame)
9374    dpyinfo->x_highlight_frame = 0;
9375
9376  if (f == dpyinfo->mouse_face_mouse_frame)
9377    {
9378      dpyinfo->mouse_face_beg_row
9379	= dpyinfo->mouse_face_beg_col = -1;
9380      dpyinfo->mouse_face_end_row
9381	= dpyinfo->mouse_face_end_col = -1;
9382      dpyinfo->mouse_face_window = Qnil;
9383      dpyinfo->mouse_face_deferred_gc = 0;
9384      dpyinfo->mouse_face_mouse_frame = 0;
9385    }
9386
9387  UNBLOCK_INPUT;
9388}
9389
9390
9391/* Destroy the X window of frame F.  */
9392
9393void
9394x_destroy_window (f)
9395     struct frame *f;
9396{
9397  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9398
9399  /* If a display connection is dead, don't try sending more
9400     commands to the X server.  */
9401  if (dpyinfo->display != 0)
9402    x_free_frame_resources (f);
9403
9404  dpyinfo->reference_count--;
9405}
9406
9407
9408/* Setting window manager hints.  */
9409
9410/* Set the normal size hints for the window manager, for frame F.
9411   FLAGS is the flags word to use--or 0 meaning preserve the flags
9412   that the window now has.
9413   If USER_POSITION is nonzero, we set the USPosition
9414   flag (this is useful when FLAGS is 0).
9415   The GTK version is in gtkutils.c  */
9416
9417#ifndef USE_GTK
9418void
9419x_wm_set_size_hint (f, flags, user_position)
9420     struct frame *f;
9421     long flags;
9422     int user_position;
9423{
9424  XSizeHints size_hints;
9425
9426#ifdef USE_X_TOOLKIT
9427  Arg al[2];
9428  int ac = 0;
9429  Dimension widget_width, widget_height;
9430#endif
9431
9432  Window window = FRAME_OUTER_WINDOW (f);
9433
9434  /* Setting PMaxSize caused various problems.  */
9435  size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
9436
9437  size_hints.x = f->left_pos;
9438  size_hints.y = f->top_pos;
9439
9440#ifdef USE_X_TOOLKIT
9441  XtSetArg (al[ac], XtNwidth, &widget_width); ac++;
9442  XtSetArg (al[ac], XtNheight, &widget_height); ac++;
9443  XtGetValues (f->output_data.x->widget, al, ac);
9444  size_hints.height = widget_height;
9445  size_hints.width = widget_width;
9446#else /* not USE_X_TOOLKIT */
9447  size_hints.height = FRAME_PIXEL_HEIGHT (f);
9448  size_hints.width = FRAME_PIXEL_WIDTH (f);
9449#endif /* not USE_X_TOOLKIT */
9450
9451  size_hints.width_inc = FRAME_COLUMN_WIDTH (f);
9452  size_hints.height_inc = FRAME_LINE_HEIGHT (f);
9453  size_hints.max_width
9454    = FRAME_X_DISPLAY_INFO (f)->width - FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9455  size_hints.max_height
9456    = FRAME_X_DISPLAY_INFO (f)->height - FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9457
9458  /* Calculate the base and minimum sizes.
9459
9460     (When we use the X toolkit, we don't do it here.
9461     Instead we copy the values that the widgets are using, below.)  */
9462#ifndef USE_X_TOOLKIT
9463  {
9464    int base_width, base_height;
9465    int min_rows = 0, min_cols = 0;
9466
9467    base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
9468    base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
9469
9470    check_frame_size (f, &min_rows, &min_cols);
9471
9472    /* The window manager uses the base width hints to calculate the
9473       current number of rows and columns in the frame while
9474       resizing; min_width and min_height aren't useful for this
9475       purpose, since they might not give the dimensions for a
9476       zero-row, zero-column frame.
9477
9478       We use the base_width and base_height members if we have
9479       them; otherwise, we set the min_width and min_height members
9480       to the size for a zero x zero frame.  */
9481
9482#ifdef HAVE_X11R4
9483    size_hints.flags |= PBaseSize;
9484    size_hints.base_width = base_width;
9485    size_hints.base_height = base_height;
9486    size_hints.min_width  = base_width + min_cols * size_hints.width_inc;
9487    size_hints.min_height = base_height + min_rows * size_hints.height_inc;
9488#else
9489    size_hints.min_width = base_width;
9490    size_hints.min_height = base_height;
9491#endif
9492  }
9493
9494  /* If we don't need the old flags, we don't need the old hint at all.  */
9495  if (flags)
9496    {
9497      size_hints.flags |= flags;
9498      goto no_read;
9499    }
9500#endif /* not USE_X_TOOLKIT */
9501
9502  {
9503    XSizeHints hints;		/* Sometimes I hate X Windows... */
9504    long supplied_return;
9505    int value;
9506
9507#ifdef HAVE_X11R4
9508    value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
9509			       &supplied_return);
9510#else
9511    value = XGetNormalHints (FRAME_X_DISPLAY (f), window, &hints);
9512#endif
9513
9514#ifdef USE_X_TOOLKIT
9515    size_hints.base_height = hints.base_height;
9516    size_hints.base_width = hints.base_width;
9517    size_hints.min_height = hints.min_height;
9518    size_hints.min_width = hints.min_width;
9519#endif
9520
9521    if (flags)
9522      size_hints.flags |= flags;
9523    else
9524      {
9525	if (value == 0)
9526	  hints.flags = 0;
9527	if (hints.flags & PSize)
9528	  size_hints.flags |= PSize;
9529	if (hints.flags & PPosition)
9530	  size_hints.flags |= PPosition;
9531	if (hints.flags & USPosition)
9532	  size_hints.flags |= USPosition;
9533	if (hints.flags & USSize)
9534	  size_hints.flags |= USSize;
9535      }
9536  }
9537
9538#ifndef USE_X_TOOLKIT
9539 no_read:
9540#endif
9541
9542#ifdef PWinGravity
9543  size_hints.win_gravity = f->win_gravity;
9544  size_hints.flags |= PWinGravity;
9545
9546  if (user_position)
9547    {
9548      size_hints.flags &= ~ PPosition;
9549      size_hints.flags |= USPosition;
9550    }
9551#endif /* PWinGravity */
9552
9553#ifdef HAVE_X11R4
9554  XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
9555#else
9556  XSetNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
9557#endif
9558}
9559#endif /* not USE_GTK */
9560
9561/* Used for IconicState or NormalState */
9562
9563void
9564x_wm_set_window_state (f, state)
9565     struct frame *f;
9566     int state;
9567{
9568#ifdef USE_X_TOOLKIT
9569  Arg al[1];
9570
9571  XtSetArg (al[0], XtNinitialState, state);
9572  XtSetValues (f->output_data.x->widget, al, 1);
9573#else /* not USE_X_TOOLKIT */
9574  Window window = FRAME_X_WINDOW (f);
9575
9576  f->output_data.x->wm_hints.flags |= StateHint;
9577  f->output_data.x->wm_hints.initial_state = state;
9578
9579  XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9580#endif /* not USE_X_TOOLKIT */
9581}
9582
9583void
9584x_wm_set_icon_pixmap (f, pixmap_id)
9585     struct frame *f;
9586     int pixmap_id;
9587{
9588  Pixmap icon_pixmap, icon_mask;
9589
9590#ifndef USE_X_TOOLKIT
9591  Window window = FRAME_OUTER_WINDOW (f);
9592#endif
9593
9594  if (pixmap_id > 0)
9595    {
9596      icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
9597      f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
9598      icon_mask = x_bitmap_mask (f, pixmap_id);
9599      f->output_data.x->wm_hints.icon_mask = icon_mask;
9600    }
9601  else
9602    {
9603      /* It seems there is no way to turn off use of an icon pixmap.
9604	 The following line does it, only if no icon has yet been created,
9605	 for some window managers.  But with mwm it crashes.
9606	 Some people say it should clear the IconPixmapHint bit in this case,
9607	 but that doesn't work, and the X consortium said it isn't the
9608	 right thing at all.  Since there is no way to win,
9609	 best to explicitly give up.  */
9610#if 0
9611      f->output_data.x->wm_hints.icon_pixmap = None;
9612      f->output_data.x->wm_hints.icon_mask = None;
9613#else
9614      return;
9615#endif
9616    }
9617
9618
9619#ifdef USE_GTK
9620  {
9621    xg_set_frame_icon (f, icon_pixmap, icon_mask);
9622    return;
9623  }
9624
9625#elif defined (USE_X_TOOLKIT) /* same as in x_wm_set_window_state.  */
9626
9627  {
9628    Arg al[1];
9629    XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
9630    XtSetValues (f->output_data.x->widget, al, 1);
9631    XtSetArg (al[0], XtNiconMask, icon_mask);
9632    XtSetValues (f->output_data.x->widget, al, 1);
9633  }
9634
9635#else /* not USE_X_TOOLKIT && not USE_GTK */
9636
9637  f->output_data.x->wm_hints.flags |= (IconPixmapHint | IconMaskHint);
9638  XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9639
9640#endif /* not USE_X_TOOLKIT && not USE_GTK */
9641}
9642
9643void
9644x_wm_set_icon_position (f, icon_x, icon_y)
9645     struct frame *f;
9646     int icon_x, icon_y;
9647{
9648  Window window = FRAME_OUTER_WINDOW (f);
9649
9650  f->output_data.x->wm_hints.flags |= IconPositionHint;
9651  f->output_data.x->wm_hints.icon_x = icon_x;
9652  f->output_data.x->wm_hints.icon_y = icon_y;
9653
9654  XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
9655}
9656
9657
9658/***********************************************************************
9659				Fonts
9660 ***********************************************************************/
9661
9662/* Return a pointer to struct font_info of font FONT_IDX of frame F.  */
9663
9664struct font_info *
9665x_get_font_info (f, font_idx)
9666     FRAME_PTR f;
9667     int font_idx;
9668{
9669  return (FRAME_X_FONT_TABLE (f) + font_idx);
9670}
9671
9672
9673/* Return a list of names of available fonts matching PATTERN on frame F.
9674
9675   If SIZE is > 0, it is the size (maximum bounds width) of fonts
9676   to be listed.
9677
9678   SIZE < 0 means include scalable fonts.
9679
9680   Frame F null means we have not yet created any frame on X, and
9681   consult the first display in x_display_list.  MAXNAMES sets a limit
9682   on how many fonts to match.  */
9683
9684Lisp_Object
9685x_list_fonts (f, pattern, size, maxnames)
9686     struct frame *f;
9687     Lisp_Object pattern;
9688     int size;
9689     int maxnames;
9690{
9691  Lisp_Object list = Qnil, patterns, newlist = Qnil, key = Qnil;
9692  Lisp_Object tem, second_best;
9693  struct x_display_info *dpyinfo
9694    = f ? FRAME_X_DISPLAY_INFO (f) : x_display_list;
9695  Display *dpy = dpyinfo->display;
9696  int try_XLoadQueryFont = 0;
9697  int allow_auto_scaled_font = 0;
9698
9699  if (size < 0)
9700    {
9701      allow_auto_scaled_font = 1;
9702      size = 0;
9703    }
9704
9705  patterns = Fassoc (pattern, Valternate_fontname_alist);
9706  if (NILP (patterns))
9707    patterns = Fcons (pattern, Qnil);
9708
9709  if (maxnames == 1 && !size)
9710    /* We can return any single font matching PATTERN.  */
9711    try_XLoadQueryFont = 1;
9712
9713  for (; CONSP (patterns); patterns = XCDR (patterns))
9714    {
9715      int num_fonts;
9716      char **names = NULL;
9717
9718      pattern = XCAR (patterns);
9719      /* See if we cached the result for this particular query.
9720         The cache is an alist of the form:
9721	 ((((PATTERN . MAXNAMES) . SCALABLE) (FONTNAME . WIDTH) ...) ...)  */
9722      tem = XCDR (dpyinfo->name_list_element);
9723      key = Fcons (Fcons (pattern, make_number (maxnames)),
9724		   allow_auto_scaled_font ? Qt : Qnil);
9725      list = Fassoc (key, tem);
9726      if (!NILP (list))
9727	{
9728	  list = Fcdr_safe (list);
9729	  /* We have a cashed list.  Don't have to get the list again.  */
9730	  goto label_cached;
9731	}
9732
9733      /* At first, put PATTERN in the cache.  */
9734
9735      BLOCK_INPUT;
9736      x_catch_errors (dpy);
9737
9738      if (try_XLoadQueryFont)
9739	{
9740	  XFontStruct *font;
9741	  unsigned long value;
9742
9743	  font = XLoadQueryFont (dpy, SDATA (pattern));
9744	  if (x_had_errors_p (dpy))
9745	    {
9746	      /* This error is perhaps due to insufficient memory on X
9747                 server.  Let's just ignore it.  */
9748	      font = NULL;
9749	      x_clear_errors (dpy);
9750	    }
9751
9752	  if (font
9753	      && XGetFontProperty (font, XA_FONT, &value))
9754	    {
9755	      char *name = (char *) XGetAtomName (dpy, (Atom) value);
9756	      int len = strlen (name);
9757	      char *tmp;
9758
9759	      /* If DXPC (a Differential X Protocol Compressor)
9760                 Ver.3.7 is running, XGetAtomName will return null
9761                 string.  We must avoid such a name.  */
9762	      if (len == 0)
9763		try_XLoadQueryFont = 0;
9764	      else
9765		{
9766		  num_fonts = 1;
9767		  names = (char **) alloca (sizeof (char *));
9768		  /* Some systems only allow alloca assigned to a
9769                     simple var.  */
9770		  tmp = (char *) alloca (len + 1);  names[0] = tmp;
9771		  bcopy (name, names[0], len + 1);
9772		  XFree (name);
9773		}
9774	    }
9775	  else
9776	    try_XLoadQueryFont = 0;
9777
9778	  if (font)
9779	    XFreeFont (dpy, font);
9780	}
9781
9782      if (!try_XLoadQueryFont)
9783	{
9784	  /* We try at least 10 fonts because XListFonts will return
9785	     auto-scaled fonts at the head.  */
9786          if (maxnames < 0)
9787            {
9788              int limit;
9789
9790              for (limit = 500;;)
9791                {
9792                  names = XListFonts (dpy, SDATA (pattern), limit, &num_fonts);
9793                  if (num_fonts == limit)
9794                    {
9795                      BLOCK_INPUT;
9796                      XFreeFontNames (names);
9797                      UNBLOCK_INPUT;
9798                      limit *= 2;
9799                    }
9800                  else
9801                    break;
9802                }
9803            }
9804          else
9805            names = XListFonts (dpy, SDATA (pattern), max (maxnames, 10),
9806                                &num_fonts);
9807
9808	  if (x_had_errors_p (dpy))
9809	    {
9810	      /* This error is perhaps due to insufficient memory on X
9811                 server.  Let's just ignore it.  */
9812	      names = NULL;
9813	      x_clear_errors (dpy);
9814	    }
9815	}
9816
9817      x_uncatch_errors ();
9818      UNBLOCK_INPUT;
9819
9820      if (names)
9821	{
9822	  int i;
9823
9824	  /* Make a list of all the fonts we got back.
9825	     Store that in the font cache for the display.  */
9826	  for (i = 0; i < num_fonts; i++)
9827	    {
9828	      int width = 0;
9829	      char *p = names[i];
9830	      int average_width = -1, resx = 0, dashes = 0;
9831
9832	      /* Count the number of dashes in NAMES[I].  If there are
9833		 14 dashes, the field value following 9th dash
9834		 (RESOLUTION_X) is nonzero, and the field value
9835		 following 12th dash (AVERAGE_WIDTH) is 0, this is a
9836		 auto-scaled font which is usually too ugly to be used
9837		 for editing.  Let's ignore it.  */
9838	      while (*p)
9839		if (*p++ == '-')
9840		  {
9841		    dashes++;
9842		    if (dashes == 7) /* PIXEL_SIZE field */
9843		      width = atoi (p);
9844		    else if (dashes == 9)
9845		      resx = atoi (p);
9846		    else if (dashes == 12) /* AVERAGE_WIDTH field */
9847		      average_width = atoi (p);
9848		  }
9849
9850	      if (allow_auto_scaled_font
9851		  || dashes < 14 || average_width != 0 || resx == 0)
9852		{
9853		  tem = build_string (names[i]);
9854		  if (NILP (Fassoc (tem, list)))
9855		    {
9856		      if (STRINGP (Vx_pixel_size_width_font_regexp)
9857			  && ((fast_c_string_match_ignore_case
9858			       (Vx_pixel_size_width_font_regexp, names[i]))
9859			      >= 0))
9860			/* We can set the value of PIXEL_SIZE to the
9861			  width of this font.  */
9862			list = Fcons (Fcons (tem, make_number (width)), list);
9863		      else
9864			/* For the moment, width is not known.  */
9865			list = Fcons (Fcons (tem, Qnil), list);
9866		    }
9867		}
9868	    }
9869
9870	  if (!try_XLoadQueryFont)
9871	    {
9872	      BLOCK_INPUT;
9873	      XFreeFontNames (names);
9874	      UNBLOCK_INPUT;
9875	    }
9876	}
9877
9878      /* Now store the result in the cache.  */
9879      XSETCDR (dpyinfo->name_list_element,
9880	       Fcons (Fcons (key, list), XCDR (dpyinfo->name_list_element)));
9881
9882    label_cached:
9883      if (NILP (list)) continue; /* Try the remaining alternatives.  */
9884
9885      newlist = second_best = Qnil;
9886      /* Make a list of the fonts that have the right width.  */
9887      for (; CONSP (list); list = XCDR (list))
9888	{
9889	  int found_size;
9890
9891	  tem = XCAR (list);
9892
9893	  if (!CONSP (tem) || NILP (XCAR (tem)))
9894	    continue;
9895	  if (!size)
9896	    {
9897	      newlist = Fcons (XCAR (tem), newlist);
9898	      continue;
9899	    }
9900
9901	  if (!INTEGERP (XCDR (tem)))
9902	    {
9903	      /* Since we have not yet known the size of this font, we
9904		 must try slow function call XLoadQueryFont.  */
9905	      XFontStruct *thisinfo;
9906
9907	      BLOCK_INPUT;
9908	      x_catch_errors (dpy);
9909	      thisinfo = XLoadQueryFont (dpy,
9910					 SDATA (XCAR (tem)));
9911	      if (x_had_errors_p (dpy))
9912		{
9913		  /* This error is perhaps due to insufficient memory on X
9914		     server.  Let's just ignore it.  */
9915		  thisinfo = NULL;
9916		  x_clear_errors (dpy);
9917		}
9918	      x_uncatch_errors ();
9919	      UNBLOCK_INPUT;
9920
9921	      if (thisinfo)
9922		{
9923		  XSETCDR (tem,
9924			   (thisinfo->min_bounds.width == 0
9925			    ? make_number (0)
9926			    : make_number (thisinfo->max_bounds.width)));
9927		  BLOCK_INPUT;
9928		  XFreeFont (dpy, thisinfo);
9929		  UNBLOCK_INPUT;
9930		}
9931	      else
9932		/* For unknown reason, the previous call of XListFont had
9933		  returned a font which can't be opened.  Record the size
9934		  as 0 not to try to open it again.  */
9935		XSETCDR (tem, make_number (0));
9936	    }
9937
9938	  found_size = XINT (XCDR (tem));
9939	  if (found_size == size)
9940	    newlist = Fcons (XCAR (tem), newlist);
9941	  else if (found_size > 0)
9942	    {
9943	      if (NILP (second_best))
9944		second_best = tem;
9945	      else if (found_size < size)
9946		{
9947		  if (XINT (XCDR (second_best)) > size
9948		      || XINT (XCDR (second_best)) < found_size)
9949		    second_best = tem;
9950		}
9951	      else
9952		{
9953		  if (XINT (XCDR (second_best)) > size
9954		      && XINT (XCDR (second_best)) > found_size)
9955		    second_best = tem;
9956		}
9957	    }
9958	}
9959      if (!NILP (newlist))
9960	break;
9961      else if (!NILP (second_best))
9962	{
9963	  newlist = Fcons (XCAR (second_best), Qnil);
9964	  break;
9965	}
9966    }
9967
9968  return newlist;
9969}
9970
9971
9972#if GLYPH_DEBUG
9973
9974/* Check that FONT is valid on frame F.  It is if it can be found in F's
9975   font table.  */
9976
9977static void
9978x_check_font (f, font)
9979     struct frame *f;
9980     XFontStruct *font;
9981{
9982  int i;
9983  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9984
9985  xassert (font != NULL);
9986
9987  for (i = 0; i < dpyinfo->n_fonts; i++)
9988    if (dpyinfo->font_table[i].name
9989	&& font == dpyinfo->font_table[i].font)
9990      break;
9991
9992  xassert (i < dpyinfo->n_fonts);
9993}
9994
9995#endif /* GLYPH_DEBUG != 0 */
9996
9997/* Set *W to the minimum width, *H to the minimum font height of FONT.
9998   Note: There are (broken) X fonts out there with invalid XFontStruct
9999   min_bounds contents.  For example, handa@etl.go.jp reports that
10000   "-adobe-courier-medium-r-normal--*-180-*-*-m-*-iso8859-1" fonts
10001   have font->min_bounds.width == 0.  */
10002
10003static INLINE void
10004x_font_min_bounds (font, w, h)
10005     XFontStruct *font;
10006     int *w, *h;
10007{
10008  *h = FONT_HEIGHT (font);
10009  *w = font->min_bounds.width;
10010
10011  /* Try to handle the case where FONT->min_bounds has invalid
10012     contents.  Since the only font known to have invalid min_bounds
10013     is fixed-width, use max_bounds if min_bounds seems to be invalid.  */
10014  if (*w <= 0)
10015    *w = font->max_bounds.width;
10016}
10017
10018
10019/* Compute the smallest character width and smallest font height over
10020   all fonts available on frame F.  Set the members smallest_char_width
10021   and smallest_font_height in F's x_display_info structure to
10022   the values computed.  Value is non-zero if smallest_font_height or
10023   smallest_char_width become smaller than they were before.  */
10024
10025static int
10026x_compute_min_glyph_bounds (f)
10027     struct frame *f;
10028{
10029  int i;
10030  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
10031  XFontStruct *font;
10032  int old_width = dpyinfo->smallest_char_width;
10033  int old_height = dpyinfo->smallest_font_height;
10034
10035  dpyinfo->smallest_font_height = 100000;
10036  dpyinfo->smallest_char_width = 100000;
10037
10038  for (i = 0; i < dpyinfo->n_fonts; ++i)
10039    if (dpyinfo->font_table[i].name)
10040      {
10041	struct font_info *fontp = dpyinfo->font_table + i;
10042	int w, h;
10043
10044	font = (XFontStruct *) fontp->font;
10045	xassert (font != (XFontStruct *) ~0);
10046	x_font_min_bounds (font, &w, &h);
10047
10048	dpyinfo->smallest_font_height = min (dpyinfo->smallest_font_height, h);
10049	dpyinfo->smallest_char_width = min (dpyinfo->smallest_char_width, w);
10050      }
10051
10052  xassert (dpyinfo->smallest_char_width > 0
10053	   && dpyinfo->smallest_font_height > 0);
10054
10055  return (dpyinfo->n_fonts == 1
10056	  || dpyinfo->smallest_char_width < old_width
10057	  || dpyinfo->smallest_font_height < old_height);
10058}
10059
10060
10061/* Load font named FONTNAME of the size SIZE for frame F, and return a
10062   pointer to the structure font_info while allocating it dynamically.
10063   If SIZE is 0, load any size of font.
10064   If loading is failed, return NULL.  */
10065
10066struct font_info *
10067x_load_font (f, fontname, size)
10068     struct frame *f;
10069     register char *fontname;
10070     int size;
10071{
10072  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
10073  Lisp_Object font_names;
10074
10075  /* Get a list of all the fonts that match this name.  Once we
10076     have a list of matching fonts, we compare them against the fonts
10077     we already have by comparing names.  */
10078  font_names = x_list_fonts (f, build_string (fontname), size, 1);
10079
10080  if (!NILP (font_names))
10081    {
10082      Lisp_Object tail;
10083      int i;
10084
10085      for (i = 0; i < dpyinfo->n_fonts; i++)
10086	for (tail = font_names; CONSP (tail); tail = XCDR (tail))
10087	  if (dpyinfo->font_table[i].name
10088	      && (!strcmp (dpyinfo->font_table[i].name,
10089			   SDATA (XCAR (tail)))
10090		  || !strcmp (dpyinfo->font_table[i].full_name,
10091			      SDATA (XCAR (tail)))))
10092	    return (dpyinfo->font_table + i);
10093    }
10094
10095  /* Load the font and add it to the table.  */
10096  {
10097    char *full_name;
10098    XFontStruct *font;
10099    struct font_info *fontp;
10100    unsigned long value;
10101    int i;
10102
10103    /* If we have found fonts by x_list_font, load one of them.  If
10104       not, we still try to load a font by the name given as FONTNAME
10105       because XListFonts (called in x_list_font) of some X server has
10106       a bug of not finding a font even if the font surely exists and
10107       is loadable by XLoadQueryFont.  */
10108    if (size > 0 && !NILP (font_names))
10109      fontname = (char *) SDATA (XCAR (font_names));
10110
10111    BLOCK_INPUT;
10112    x_catch_errors (FRAME_X_DISPLAY (f));
10113    font = (XFontStruct *) XLoadQueryFont (FRAME_X_DISPLAY (f), fontname);
10114    if (x_had_errors_p (FRAME_X_DISPLAY (f)))
10115      {
10116	/* This error is perhaps due to insufficient memory on X
10117	   server.  Let's just ignore it.  */
10118	font = NULL;
10119	x_clear_errors (FRAME_X_DISPLAY (f));
10120      }
10121    x_uncatch_errors ();
10122    UNBLOCK_INPUT;
10123    if (!font)
10124      return NULL;
10125
10126    /* Find a free slot in the font table.  */
10127    for (i = 0; i < dpyinfo->n_fonts; ++i)
10128      if (dpyinfo->font_table[i].name == NULL)
10129	break;
10130
10131    /* If no free slot found, maybe enlarge the font table.  */
10132    if (i == dpyinfo->n_fonts
10133	&& dpyinfo->n_fonts == dpyinfo->font_table_size)
10134      {
10135	int sz;
10136	dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
10137	sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
10138	dpyinfo->font_table
10139	  = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
10140      }
10141
10142    fontp = dpyinfo->font_table + i;
10143    if (i == dpyinfo->n_fonts)
10144      ++dpyinfo->n_fonts;
10145
10146    /* Now fill in the slots of *FONTP.  */
10147    BLOCK_INPUT;
10148    bzero (fontp, sizeof (*fontp));
10149    fontp->font = font;
10150    fontp->font_idx = i;
10151    fontp->name = (char *) xmalloc (strlen (fontname) + 1);
10152    bcopy (fontname, fontp->name, strlen (fontname) + 1);
10153
10154    if (font->min_bounds.width == font->max_bounds.width)
10155      {
10156	/* Fixed width font.  */
10157	fontp->average_width = fontp->space_width = font->min_bounds.width;
10158      }
10159    else
10160      {
10161	XChar2b char2b;
10162	XCharStruct *pcm;
10163
10164	char2b.byte1 = 0x00, char2b.byte2 = 0x20;
10165	pcm = x_per_char_metric (font, &char2b, 0);
10166	if (pcm)
10167	  fontp->space_width = pcm->width;
10168	else
10169	  fontp->space_width = FONT_WIDTH (font);
10170
10171	fontp->average_width
10172	  = (XGetFontProperty (font, dpyinfo->Xatom_AVERAGE_WIDTH, &value)
10173	     ? (long) value / 10 : 0);
10174	if (fontp->average_width < 0)
10175	  fontp->average_width = - fontp->average_width;
10176	if (fontp->average_width == 0)
10177	  {
10178	    if (pcm)
10179	      {
10180		int width = pcm->width;
10181		for (char2b.byte2 = 33; char2b.byte2 <= 126; char2b.byte2++)
10182		  if ((pcm = x_per_char_metric (font, &char2b, 0)) != NULL)
10183		    width += pcm->width;
10184		fontp->average_width = width / 95;
10185	      }
10186	    else
10187	      fontp->average_width = FONT_WIDTH (font);
10188	  }
10189      }
10190
10191    /* Try to get the full name of FONT.  Put it in FULL_NAME.  */
10192    full_name = 0;
10193    if (XGetFontProperty (font, XA_FONT, &value))
10194      {
10195	char *name = (char *) XGetAtomName (FRAME_X_DISPLAY (f), (Atom) value);
10196	char *p = name;
10197	int dashes = 0;
10198
10199	/* Count the number of dashes in the "full name".
10200	   If it is too few, this isn't really the font's full name,
10201	   so don't use it.
10202	   In X11R4, the fonts did not come with their canonical names
10203	   stored in them.  */
10204	while (*p)
10205	  {
10206	    if (*p == '-')
10207	      dashes++;
10208	    p++;
10209	  }
10210
10211	if (dashes >= 13)
10212	  {
10213	    full_name = (char *) xmalloc (p - name + 1);
10214	    bcopy (name, full_name, p - name + 1);
10215	  }
10216
10217	XFree (name);
10218      }
10219
10220    if (full_name != 0)
10221      fontp->full_name = full_name;
10222    else
10223      fontp->full_name = fontp->name;
10224
10225    fontp->size = font->max_bounds.width;
10226    fontp->height = FONT_HEIGHT (font);
10227
10228    if (NILP (font_names))
10229      {
10230	/* We come here because of a bug of XListFonts mentioned at
10231	   the head of this block.  Let's store this information in
10232	   the cache for x_list_fonts.  */
10233	Lisp_Object lispy_name = build_string (fontname);
10234	Lisp_Object lispy_full_name = build_string (fontp->full_name);
10235	Lisp_Object key = Fcons (Fcons (lispy_name, make_number (256)),
10236				 Qnil);
10237
10238	XSETCDR (dpyinfo->name_list_element,
10239		 Fcons (Fcons (key,
10240			       Fcons (Fcons (lispy_full_name,
10241					     make_number (fontp->size)),
10242				      Qnil)),
10243			XCDR (dpyinfo->name_list_element)));
10244	if (full_name)
10245	  {
10246	    key = Fcons (Fcons (lispy_full_name, make_number (256)),
10247			 Qnil);
10248	    XSETCDR (dpyinfo->name_list_element,
10249		     Fcons (Fcons (key,
10250				   Fcons (Fcons (lispy_full_name,
10251						 make_number (fontp->size)),
10252					  Qnil)),
10253			    XCDR (dpyinfo->name_list_element)));
10254	  }
10255      }
10256
10257    /* The slot `encoding' specifies how to map a character
10258       code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
10259       the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
10260       (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
10261       2:0xA020..0xFF7F).  For the moment, we don't know which charset
10262       uses this font.  So, we set information in fontp->encoding[1]
10263       which is never used by any charset.  If mapping can't be
10264       decided, set FONT_ENCODING_NOT_DECIDED.  */
10265    fontp->encoding[1]
10266      = (font->max_byte1 == 0
10267	 /* 1-byte font */
10268	 ? (font->min_char_or_byte2 < 0x80
10269	    ? (font->max_char_or_byte2 < 0x80
10270	       ? 0		/* 0x20..0x7F */
10271	       : FONT_ENCODING_NOT_DECIDED) /* 0x20..0xFF */
10272	    : 1)		/* 0xA0..0xFF */
10273	 /* 2-byte font */
10274	 : (font->min_byte1 < 0x80
10275	    ? (font->max_byte1 < 0x80
10276	       ? (font->min_char_or_byte2 < 0x80
10277		  ? (font->max_char_or_byte2 < 0x80
10278		     ? 0		/* 0x2020..0x7F7F */
10279		     : FONT_ENCODING_NOT_DECIDED) /* 0x2020..0x7FFF */
10280		  : 3)		/* 0x20A0..0x7FFF */
10281	       : FONT_ENCODING_NOT_DECIDED) /* 0x20??..0xA0?? */
10282	    : (font->min_char_or_byte2 < 0x80
10283	       ? (font->max_char_or_byte2 < 0x80
10284		  ? 2		/* 0xA020..0xFF7F */
10285		  : FONT_ENCODING_NOT_DECIDED) /* 0xA020..0xFFFF */
10286	       : 1)));		/* 0xA0A0..0xFFFF */
10287
10288    fontp->baseline_offset
10289      = (XGetFontProperty (font, dpyinfo->Xatom_MULE_BASELINE_OFFSET, &value)
10290	 ? (long) value : 0);
10291    fontp->relative_compose
10292      = (XGetFontProperty (font, dpyinfo->Xatom_MULE_RELATIVE_COMPOSE, &value)
10293	 ? (long) value : 0);
10294    fontp->default_ascent
10295      = (XGetFontProperty (font, dpyinfo->Xatom_MULE_DEFAULT_ASCENT, &value)
10296	 ? (long) value : 0);
10297
10298    /* Set global flag fonts_changed_p to non-zero if the font loaded
10299       has a character with a smaller width than any other character
10300       before, or if the font loaded has a smaller height than any
10301       other font loaded before.  If this happens, it will make a
10302       glyph matrix reallocation necessary.  */
10303    fonts_changed_p |= x_compute_min_glyph_bounds (f);
10304    UNBLOCK_INPUT;
10305    return fontp;
10306  }
10307}
10308
10309
10310/* Return a pointer to struct font_info of a font named FONTNAME for
10311   frame F.  If no such font is loaded, return NULL.  */
10312
10313struct font_info *
10314x_query_font (f, fontname)
10315     struct frame *f;
10316     register char *fontname;
10317{
10318  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
10319  int i;
10320
10321  for (i = 0; i < dpyinfo->n_fonts; i++)
10322    if (dpyinfo->font_table[i].name
10323	&& (!xstricmp (dpyinfo->font_table[i].name, fontname)
10324	    || !xstricmp (dpyinfo->font_table[i].full_name, fontname)))
10325      return (dpyinfo->font_table + i);
10326  return NULL;
10327}
10328
10329
10330/* Find a CCL program for a font specified by FONTP, and set the member
10331 `encoder' of the structure.  */
10332
10333void
10334x_find_ccl_program (fontp)
10335     struct font_info *fontp;
10336{
10337  Lisp_Object list, elt;
10338
10339  elt = Qnil;
10340  for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
10341    {
10342      elt = XCAR (list);
10343      if (CONSP (elt)
10344	  && STRINGP (XCAR (elt))
10345	  && ((fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
10346	       >= 0)
10347	      || (fast_c_string_match_ignore_case (XCAR (elt), fontp->full_name)
10348		  >= 0)))
10349	break;
10350    }
10351
10352  if (! NILP (list))
10353    {
10354      struct ccl_program *ccl
10355	= (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
10356
10357      if (setup_ccl_program (ccl, XCDR (elt)) < 0)
10358	xfree (ccl);
10359      else
10360	fontp->font_encoder = ccl;
10361    }
10362}
10363
10364
10365
10366/***********************************************************************
10367			    Initialization
10368 ***********************************************************************/
10369
10370#ifdef USE_X_TOOLKIT
10371static XrmOptionDescRec emacs_options[] = {
10372  {"-geometry",	".geometry", XrmoptionSepArg, NULL},
10373  {"-iconic",	".iconic", XrmoptionNoArg, (XtPointer) "yes"},
10374
10375  {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
10376     XrmoptionSepArg, NULL},
10377  {"-ib",	"*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
10378
10379  {"-T",	"*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
10380  {"-wn",	"*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
10381  {"-title",	"*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
10382  {"-iconname",	"*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
10383  {"-in",	"*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
10384  {"-mc",	"*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
10385  {"-cr",	"*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
10386};
10387
10388/* Whether atimer for Xt timeouts is activated or not.  */
10389
10390static int x_timeout_atimer_activated_flag;
10391
10392#endif /* USE_X_TOOLKIT */
10393
10394static int x_initialized;
10395
10396#ifdef HAVE_X_SM
10397static int x_session_initialized;
10398#endif
10399
10400#ifdef MULTI_KBOARD
10401/* Test whether two display-name strings agree up to the dot that separates
10402   the screen number from the server number.  */
10403static int
10404same_x_server (name1, name2)
10405     const char *name1, *name2;
10406{
10407  int seen_colon = 0;
10408  const unsigned char *system_name = SDATA (Vsystem_name);
10409  int system_name_length = strlen (system_name);
10410  int length_until_period = 0;
10411
10412  while (system_name[length_until_period] != 0
10413	 && system_name[length_until_period] != '.')
10414    length_until_period++;
10415
10416  /* Treat `unix' like an empty host name.  */
10417  if (! strncmp (name1, "unix:", 5))
10418    name1 += 4;
10419  if (! strncmp (name2, "unix:", 5))
10420    name2 += 4;
10421  /* Treat this host's name like an empty host name.  */
10422  if (! strncmp (name1, system_name, system_name_length)
10423      && name1[system_name_length] == ':')
10424    name1 += system_name_length;
10425  if (! strncmp (name2, system_name, system_name_length)
10426      && name2[system_name_length] == ':')
10427    name2 += system_name_length;
10428  /* Treat this host's domainless name like an empty host name.  */
10429  if (! strncmp (name1, system_name, length_until_period)
10430      && name1[length_until_period] == ':')
10431    name1 += length_until_period;
10432  if (! strncmp (name2, system_name, length_until_period)
10433      && name2[length_until_period] == ':')
10434    name2 += length_until_period;
10435
10436  for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
10437    {
10438      if (*name1 == ':')
10439	seen_colon++;
10440      if (seen_colon && *name1 == '.')
10441	return 1;
10442    }
10443  return (seen_colon
10444	  && (*name1 == '.' || *name1 == '\0')
10445	  && (*name2 == '.' || *name2 == '\0'));
10446}
10447#endif
10448
10449/* Count number of set bits in mask and number of bits to shift to
10450   get to the first bit.  With MASK 0x7e0, *BITS is set to 6, and *OFFSET
10451   to 5.  */
10452static void
10453get_bits_and_offset (mask, bits, offset)
10454     unsigned long mask;
10455     int *bits;
10456     int *offset;
10457{
10458  int nr = 0;
10459  int off = 0;
10460
10461  while (!(mask & 1))
10462    {
10463      off++;
10464      mask >>= 1;
10465    }
10466
10467  while (mask & 1)
10468    {
10469      nr++;
10470      mask >>= 1;
10471    }
10472
10473  *offset = off;
10474  *bits = nr;
10475}
10476
10477int
10478x_display_ok (display)
10479    const char * display;
10480{
10481    int dpy_ok = 1;
10482    Display *dpy;
10483
10484    dpy = XOpenDisplay (display);
10485    if (dpy)
10486      XCloseDisplay (dpy);
10487    else
10488      dpy_ok = 0;
10489    return dpy_ok;
10490}
10491
10492struct x_display_info *
10493x_term_init (display_name, xrm_option, resource_name)
10494     Lisp_Object display_name;
10495     char *xrm_option;
10496     char *resource_name;
10497{
10498  int connection;
10499  Display *dpy;
10500  struct x_display_info *dpyinfo;
10501  XrmDatabase xrdb;
10502
10503  BLOCK_INPUT;
10504
10505  if (!x_initialized)
10506    {
10507      x_initialize ();
10508      ++x_initialized;
10509    }
10510
10511#ifdef USE_GTK
10512  {
10513#define NUM_ARGV 10
10514    int argc;
10515    char *argv[NUM_ARGV];
10516    char **argv2 = argv;
10517    GdkAtom atom;
10518
10519    if (x_initialized++ > 1)
10520      {
10521        /* Opening another display.  If xg_display_open returns less
10522           than zero, we are probably on GTK 2.0, which can only handle
10523           one display.  GTK 2.2 or later can handle more than one.  */
10524        if (xg_display_open (SDATA (display_name), &dpy) < 0)
10525          error ("Sorry, this version of GTK can only handle one display");
10526     }
10527    else
10528      {
10529        for (argc = 0; argc < NUM_ARGV; ++argc)
10530          argv[argc] = 0;
10531
10532        argc = 0;
10533        argv[argc++] = initial_argv[0];
10534
10535        if (! NILP (display_name))
10536          {
10537            argv[argc++] = "--display";
10538            argv[argc++] = SDATA (display_name);
10539          }
10540
10541        argv[argc++] = "--name";
10542        argv[argc++] = resource_name;
10543
10544#ifdef HAVE_X11R5
10545        XSetLocaleModifiers ("");
10546#endif
10547
10548        gtk_init (&argc, &argv2);
10549
10550        /* gtk_init does set_locale.  We must fix locale after calling it.  */
10551        fixup_locale ();
10552        xg_initialize ();
10553
10554        dpy = GDK_DISPLAY ();
10555
10556        /* NULL window -> events for all windows go to our function */
10557        gdk_window_add_filter (NULL, event_handler_gdk, NULL);
10558
10559        /* Load our own gtkrc if it exists.  */
10560        {
10561          char *file = "~/.emacs.d/gtkrc";
10562          Lisp_Object s, abs_file;
10563
10564          s = make_string (file, strlen (file));
10565          abs_file = Fexpand_file_name (s, Qnil);
10566
10567          if (! NILP (abs_file) && !NILP (Ffile_readable_p (abs_file)))
10568            gtk_rc_parse (SDATA (abs_file));
10569        }
10570
10571        XSetErrorHandler (x_error_handler);
10572        XSetIOErrorHandler (x_io_error_quitter);
10573      }
10574  }
10575#else /* not USE_GTK */
10576#ifdef USE_X_TOOLKIT
10577  /* weiner@footloose.sps.mot.com reports that this causes
10578     errors with X11R5:
10579	   X protocol error: BadAtom (invalid Atom parameter)
10580	   on protocol request 18skiloaf.
10581     So let's not use it until R6.  */
10582#ifdef HAVE_X11XTR6
10583  XtSetLanguageProc (NULL, NULL, NULL);
10584#endif
10585
10586  {
10587    int argc = 0;
10588    char *argv[3];
10589
10590    argv[0] = "";
10591    argc = 1;
10592    if (xrm_option)
10593      {
10594	argv[argc++] = "-xrm";
10595	argv[argc++] = xrm_option;
10596      }
10597    turn_on_atimers (0);
10598    dpy = XtOpenDisplay (Xt_app_con, SDATA (display_name),
10599			 resource_name, EMACS_CLASS,
10600			 emacs_options, XtNumber (emacs_options),
10601			 &argc, argv);
10602    turn_on_atimers (1);
10603
10604#ifdef HAVE_X11XTR6
10605    /* I think this is to compensate for XtSetLanguageProc.  */
10606    fixup_locale ();
10607#endif
10608  }
10609
10610#else /* not USE_X_TOOLKIT */
10611#ifdef HAVE_X11R5
10612  XSetLocaleModifiers ("");
10613#endif
10614  dpy = XOpenDisplay (SDATA (display_name));
10615#endif /* not USE_X_TOOLKIT */
10616#endif /* not USE_GTK*/
10617
10618  /* Detect failure.  */
10619  if (dpy == 0)
10620    {
10621      UNBLOCK_INPUT;
10622      return 0;
10623    }
10624
10625  /* We have definitely succeeded.  Record the new connection.  */
10626
10627  dpyinfo = (struct x_display_info *) xmalloc (sizeof (struct x_display_info));
10628  bzero (dpyinfo, sizeof *dpyinfo);
10629
10630#ifdef MULTI_KBOARD
10631  {
10632    struct x_display_info *share;
10633    Lisp_Object tail;
10634
10635    for (share = x_display_list, tail = x_display_name_list; share;
10636	 share = share->next, tail = XCDR (tail))
10637      if (same_x_server (SDATA (XCAR (XCAR (tail))),
10638			 SDATA (display_name)))
10639	break;
10640    if (share)
10641      dpyinfo->kboard = share->kboard;
10642    else
10643      {
10644	dpyinfo->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
10645	init_kboard (dpyinfo->kboard);
10646	if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
10647	  {
10648	    char *vendor = ServerVendor (dpy);
10649	    UNBLOCK_INPUT;
10650	    dpyinfo->kboard->Vsystem_key_alist
10651	      = call1 (Qvendor_specific_keysyms,
10652		       build_string (vendor ? vendor : ""));
10653	    BLOCK_INPUT;
10654	  }
10655
10656	dpyinfo->kboard->next_kboard = all_kboards;
10657	all_kboards = dpyinfo->kboard;
10658	/* Don't let the initial kboard remain current longer than necessary.
10659	   That would cause problems if a file loaded on startup tries to
10660	   prompt in the mini-buffer.  */
10661	if (current_kboard == initial_kboard)
10662	  current_kboard = dpyinfo->kboard;
10663      }
10664    dpyinfo->kboard->reference_count++;
10665  }
10666#endif
10667
10668  /* Put this display on the chain.  */
10669  dpyinfo->next = x_display_list;
10670  x_display_list = dpyinfo;
10671
10672  /* Put it on x_display_name_list as well, to keep them parallel.  */
10673  x_display_name_list = Fcons (Fcons (display_name, Qnil),
10674			       x_display_name_list);
10675  dpyinfo->name_list_element = XCAR (x_display_name_list);
10676
10677  dpyinfo->display = dpy;
10678
10679#if 0
10680  XSetAfterFunction (x_current_display, x_trace_wire);
10681#endif /* ! 0 */
10682
10683  dpyinfo->x_id_name
10684    = (char *) xmalloc (SBYTES (Vinvocation_name)
10685			+ SBYTES (Vsystem_name)
10686			+ 2);
10687  sprintf (dpyinfo->x_id_name, "%s@%s",
10688	   SDATA (Vinvocation_name), SDATA (Vsystem_name));
10689
10690  /* Figure out which modifier bits mean what.  */
10691  x_find_modifier_meanings (dpyinfo);
10692
10693  /* Get the scroll bar cursor.  */
10694#ifdef USE_GTK
10695  /* We must create a GTK cursor, it is required for GTK widgets.  */
10696  dpyinfo->xg_cursor = xg_create_default_cursor (dpyinfo->display);
10697#endif /* USE_GTK */
10698
10699  dpyinfo->vertical_scroll_bar_cursor
10700    = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
10701
10702  xrdb = x_load_resources (dpyinfo->display, xrm_option,
10703			   resource_name, EMACS_CLASS);
10704#ifdef HAVE_XRMSETDATABASE
10705  XrmSetDatabase (dpyinfo->display, xrdb);
10706#else
10707  dpyinfo->display->db = xrdb;
10708#endif
10709  /* Put the rdb where we can find it in a way that works on
10710     all versions.  */
10711  dpyinfo->xrdb = xrdb;
10712
10713  dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
10714				     DefaultScreen (dpyinfo->display));
10715  select_visual (dpyinfo);
10716  dpyinfo->cmap = DefaultColormapOfScreen (dpyinfo->screen);
10717  dpyinfo->height = HeightOfScreen (dpyinfo->screen);
10718  dpyinfo->width = WidthOfScreen (dpyinfo->screen);
10719  dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
10720  dpyinfo->client_leader_window = 0;
10721  dpyinfo->grabbed = 0;
10722  dpyinfo->reference_count = 0;
10723  dpyinfo->icon_bitmap_id = -1;
10724  dpyinfo->font_table = NULL;
10725  dpyinfo->n_fonts = 0;
10726  dpyinfo->font_table_size = 0;
10727  dpyinfo->bitmaps = 0;
10728  dpyinfo->bitmaps_size = 0;
10729  dpyinfo->bitmaps_last = 0;
10730  dpyinfo->scratch_cursor_gc = 0;
10731  dpyinfo->mouse_face_mouse_frame = 0;
10732  dpyinfo->mouse_face_deferred_gc = 0;
10733  dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
10734  dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
10735  dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
10736  dpyinfo->mouse_face_window = Qnil;
10737  dpyinfo->mouse_face_overlay = Qnil;
10738  dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
10739  dpyinfo->mouse_face_defer = 0;
10740  dpyinfo->mouse_face_hidden = 0;
10741  dpyinfo->x_focus_frame = 0;
10742  dpyinfo->x_focus_event_frame = 0;
10743  dpyinfo->x_highlight_frame = 0;
10744  dpyinfo->image_cache = make_image_cache ();
10745  dpyinfo->wm_type = X_WMTYPE_UNKNOWN;
10746
10747  /* See if we can construct pixel values from RGB values.  */
10748  dpyinfo->red_bits = dpyinfo->blue_bits = dpyinfo->green_bits = 0;
10749  dpyinfo->red_offset = dpyinfo->blue_offset = dpyinfo->green_offset = 0;
10750
10751  if (dpyinfo->visual->class == TrueColor)
10752    {
10753      get_bits_and_offset (dpyinfo->visual->red_mask,
10754                           &dpyinfo->red_bits, &dpyinfo->red_offset);
10755      get_bits_and_offset (dpyinfo->visual->blue_mask,
10756                           &dpyinfo->blue_bits, &dpyinfo->blue_offset);
10757      get_bits_and_offset (dpyinfo->visual->green_mask,
10758                           &dpyinfo->green_bits, &dpyinfo->green_offset);
10759    }
10760
10761  /* See if a private colormap is requested.  */
10762  if (dpyinfo->visual == DefaultVisualOfScreen (dpyinfo->screen))
10763    {
10764      if (dpyinfo->visual->class == PseudoColor)
10765	{
10766	  Lisp_Object value;
10767	  value = display_x_get_resource (dpyinfo,
10768					  build_string ("privateColormap"),
10769					  build_string ("PrivateColormap"),
10770					  Qnil, Qnil);
10771	  if (STRINGP (value)
10772	      && (!strcmp (SDATA (value), "true")
10773		  || !strcmp (SDATA (value), "on")))
10774	    dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
10775	}
10776    }
10777  else
10778    dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
10779				     dpyinfo->visual, AllocNone);
10780
10781  {
10782    int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
10783    double pixels = DisplayHeight (dpyinfo->display, screen_number);
10784    double mm = DisplayHeightMM (dpyinfo->display, screen_number);
10785    /* Mac OS X 10.3's Xserver sometimes reports 0.0mm.  */
10786    dpyinfo->resy = (mm < 1) ? 100 : pixels * 25.4 / mm;
10787    pixels = DisplayWidth (dpyinfo->display, screen_number);
10788    /* Mac OS X 10.3's Xserver sometimes reports 0.0mm.  */
10789    mm = DisplayWidthMM (dpyinfo->display, screen_number);
10790    dpyinfo->resx = (mm < 1) ? 100 : pixels * 25.4 / mm;
10791  }
10792
10793  dpyinfo->Xatom_wm_protocols
10794    = XInternAtom (dpyinfo->display, "WM_PROTOCOLS", False);
10795  dpyinfo->Xatom_wm_take_focus
10796    = XInternAtom (dpyinfo->display, "WM_TAKE_FOCUS", False);
10797  dpyinfo->Xatom_wm_save_yourself
10798    = XInternAtom (dpyinfo->display, "WM_SAVE_YOURSELF", False);
10799  dpyinfo->Xatom_wm_delete_window
10800    = XInternAtom (dpyinfo->display, "WM_DELETE_WINDOW", False);
10801  dpyinfo->Xatom_wm_change_state
10802    = XInternAtom (dpyinfo->display, "WM_CHANGE_STATE", False);
10803  dpyinfo->Xatom_wm_configure_denied
10804    = XInternAtom (dpyinfo->display, "WM_CONFIGURE_DENIED", False);
10805  dpyinfo->Xatom_wm_window_moved
10806    = XInternAtom (dpyinfo->display, "WM_MOVED", False);
10807  dpyinfo->Xatom_wm_client_leader
10808    = XInternAtom (dpyinfo->display, "WM_CLIENT_LEADER", False);
10809  dpyinfo->Xatom_editres
10810    = XInternAtom (dpyinfo->display, "Editres", False);
10811  dpyinfo->Xatom_CLIPBOARD
10812    = XInternAtom (dpyinfo->display, "CLIPBOARD", False);
10813  dpyinfo->Xatom_TIMESTAMP
10814    = XInternAtom (dpyinfo->display, "TIMESTAMP", False);
10815  dpyinfo->Xatom_TEXT
10816    = XInternAtom (dpyinfo->display, "TEXT", False);
10817  dpyinfo->Xatom_COMPOUND_TEXT
10818    = XInternAtom (dpyinfo->display, "COMPOUND_TEXT", False);
10819  dpyinfo->Xatom_UTF8_STRING
10820    = XInternAtom (dpyinfo->display, "UTF8_STRING", False);
10821  dpyinfo->Xatom_DELETE
10822    = XInternAtom (dpyinfo->display, "DELETE", False);
10823  dpyinfo->Xatom_MULTIPLE
10824    = XInternAtom (dpyinfo->display, "MULTIPLE", False);
10825  dpyinfo->Xatom_INCR
10826    = XInternAtom (dpyinfo->display, "INCR", False);
10827  dpyinfo->Xatom_EMACS_TMP
10828    = XInternAtom (dpyinfo->display, "_EMACS_TMP_", False);
10829  dpyinfo->Xatom_TARGETS
10830    = XInternAtom (dpyinfo->display, "TARGETS", False);
10831  dpyinfo->Xatom_NULL
10832    = XInternAtom (dpyinfo->display, "NULL", False);
10833  dpyinfo->Xatom_ATOM_PAIR
10834    = XInternAtom (dpyinfo->display, "ATOM_PAIR", False);
10835  /* For properties of font.  */
10836  dpyinfo->Xatom_PIXEL_SIZE
10837    = XInternAtom (dpyinfo->display, "PIXEL_SIZE", False);
10838  dpyinfo->Xatom_AVERAGE_WIDTH
10839    = XInternAtom (dpyinfo->display, "AVERAGE_WIDTH", False);
10840  dpyinfo->Xatom_MULE_BASELINE_OFFSET
10841    = XInternAtom (dpyinfo->display, "_MULE_BASELINE_OFFSET", False);
10842  dpyinfo->Xatom_MULE_RELATIVE_COMPOSE
10843    = XInternAtom (dpyinfo->display, "_MULE_RELATIVE_COMPOSE", False);
10844  dpyinfo->Xatom_MULE_DEFAULT_ASCENT
10845    = XInternAtom (dpyinfo->display, "_MULE_DEFAULT_ASCENT", False);
10846
10847  /* Ghostscript support.  */
10848  dpyinfo->Xatom_PAGE = XInternAtom (dpyinfo->display, "PAGE", False);
10849  dpyinfo->Xatom_DONE = XInternAtom (dpyinfo->display, "DONE", False);
10850
10851  dpyinfo->Xatom_Scrollbar = XInternAtom (dpyinfo->display, "SCROLLBAR",
10852					  False);
10853
10854  dpyinfo->cut_buffers_initialized = 0;
10855
10856  dpyinfo->x_dnd_atoms_size = 8;
10857  dpyinfo->x_dnd_atoms_length = 0;
10858  dpyinfo->x_dnd_atoms = xmalloc (sizeof (*dpyinfo->x_dnd_atoms)
10859                                  * dpyinfo->x_dnd_atoms_size);
10860
10861  dpyinfo->net_supported_atoms = NULL;
10862  dpyinfo->nr_net_supported_atoms = 0;
10863  dpyinfo->net_supported_window = 0;
10864
10865  connection = ConnectionNumber (dpyinfo->display);
10866  dpyinfo->connection = connection;
10867
10868  {
10869    char null_bits[1];
10870
10871    null_bits[0] = 0x00;
10872
10873    dpyinfo->null_pixel
10874      = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
10875				     null_bits, 1, 1, (long) 0, (long) 0,
10876				     1);
10877  }
10878
10879  {
10880    extern int gray_bitmap_width, gray_bitmap_height;
10881    extern char *gray_bitmap_bits;
10882    dpyinfo->gray
10883      = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
10884				     gray_bitmap_bits,
10885				     gray_bitmap_width, gray_bitmap_height,
10886				     (unsigned long) 1, (unsigned long) 0, 1);
10887  }
10888
10889#ifdef HAVE_X_I18N
10890  xim_initialize (dpyinfo, resource_name);
10891#endif
10892
10893#ifdef subprocesses
10894  /* This is only needed for distinguishing keyboard and process input.  */
10895  if (connection != 0)
10896    add_keyboard_wait_descriptor (connection);
10897#endif
10898
10899#ifndef F_SETOWN_BUG
10900#ifdef F_SETOWN
10901#ifdef F_SETOWN_SOCK_NEG
10902  /* stdin is a socket here */
10903  fcntl (connection, F_SETOWN, -getpid ());
10904#else /* ! defined (F_SETOWN_SOCK_NEG) */
10905  fcntl (connection, F_SETOWN, getpid ());
10906#endif /* ! defined (F_SETOWN_SOCK_NEG) */
10907#endif /* ! defined (F_SETOWN) */
10908#endif /* F_SETOWN_BUG */
10909
10910#ifdef SIGIO
10911  if (interrupt_input)
10912    init_sigio (connection);
10913#endif /* ! defined (SIGIO) */
10914
10915#ifdef USE_LUCID
10916#ifdef HAVE_X11R5 /* It seems X11R4 lacks XtCvtStringToFont, and XPointer.  */
10917  /* Make sure that we have a valid font for dialog boxes
10918     so that Xt does not crash.  */
10919  {
10920    Display *dpy = dpyinfo->display;
10921    XrmValue d, fr, to;
10922    Font font;
10923
10924    d.addr = (XPointer)&dpy;
10925    d.size = sizeof (Display *);
10926    fr.addr = XtDefaultFont;
10927    fr.size = sizeof (XtDefaultFont);
10928    to.size = sizeof (Font *);
10929    to.addr = (XPointer)&font;
10930    x_catch_errors (dpy);
10931    if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
10932      abort ();
10933    if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
10934      XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
10935    x_uncatch_errors ();
10936  }
10937#endif
10938#endif
10939
10940  /* See if we should run in synchronous mode.  This is useful
10941     for debugging X code.  */
10942  {
10943    Lisp_Object value;
10944    value = display_x_get_resource (dpyinfo,
10945				    build_string ("synchronous"),
10946				    build_string ("Synchronous"),
10947				    Qnil, Qnil);
10948    if (STRINGP (value)
10949	&& (!strcmp (SDATA (value), "true")
10950	    || !strcmp (SDATA (value), "on")))
10951      XSynchronize (dpyinfo->display, True);
10952  }
10953
10954  {
10955    Lisp_Object value;
10956    value = display_x_get_resource (dpyinfo,
10957				    build_string ("useXIM"),
10958				    build_string ("UseXIM"),
10959				    Qnil, Qnil);
10960#ifdef USE_XIM
10961    if (STRINGP (value)
10962	&& (!strcmp (XSTRING (value)->data, "false")
10963	    || !strcmp (XSTRING (value)->data, "off")))
10964      use_xim = 0;
10965#else
10966    if (STRINGP (value)
10967	&& (!strcmp (XSTRING (value)->data, "true")
10968	    || !strcmp (XSTRING (value)->data, "on")))
10969      use_xim = 1;
10970#endif
10971  }
10972
10973#ifdef HAVE_X_SM
10974  /* Only do this for the first display.  */
10975  if (!x_session_initialized++)
10976    x_session_initialize (dpyinfo);
10977#endif
10978
10979  UNBLOCK_INPUT;
10980
10981  return dpyinfo;
10982}
10983
10984/* Get rid of display DPYINFO, assuming all frames are already gone,
10985   and without sending any more commands to the X server.  */
10986
10987void
10988x_delete_display (dpyinfo)
10989     struct x_display_info *dpyinfo;
10990{
10991  int i;
10992
10993  delete_keyboard_wait_descriptor (dpyinfo->connection);
10994
10995  /* Discard this display from x_display_name_list and x_display_list.
10996     We can't use Fdelq because that can quit.  */
10997  if (! NILP (x_display_name_list)
10998      && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10999    x_display_name_list = XCDR (x_display_name_list);
11000  else
11001    {
11002      Lisp_Object tail;
11003
11004      tail = x_display_name_list;
11005      while (CONSP (tail) && CONSP (XCDR (tail)))
11006	{
11007	  if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
11008	    {
11009	      XSETCDR (tail, XCDR (XCDR (tail)));
11010	      break;
11011	    }
11012	  tail = XCDR (tail);
11013	}
11014    }
11015
11016  if (next_noop_dpyinfo == dpyinfo)
11017    next_noop_dpyinfo = dpyinfo->next;
11018
11019  if (x_display_list == dpyinfo)
11020    x_display_list = dpyinfo->next;
11021  else
11022    {
11023      struct x_display_info *tail;
11024
11025      for (tail = x_display_list; tail; tail = tail->next)
11026	if (tail->next == dpyinfo)
11027	  tail->next = tail->next->next;
11028    }
11029
11030#ifndef USE_X_TOOLKIT   /* I'm told Xt does this itself.  */
11031#ifndef AIX		/* On AIX, XCloseDisplay calls this.  */
11032  XrmDestroyDatabase (dpyinfo->xrdb);
11033#endif
11034#endif
11035#ifdef MULTI_KBOARD
11036  if (--dpyinfo->kboard->reference_count == 0)
11037    delete_kboard (dpyinfo->kboard);
11038#endif
11039#ifdef HAVE_X_I18N
11040  if (dpyinfo->xim)
11041    xim_close_dpy (dpyinfo);
11042#endif
11043
11044  /* Free the font names in the font table.  */
11045  for (i = 0; i < dpyinfo->n_fonts; i++)
11046    if (dpyinfo->font_table[i].name)
11047      {
11048	if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
11049	  xfree (dpyinfo->font_table[i].full_name);
11050	xfree (dpyinfo->font_table[i].name);
11051      }
11052
11053  if (dpyinfo->font_table)
11054    {
11055      if (dpyinfo->font_table->font_encoder)
11056	xfree (dpyinfo->font_table->font_encoder);
11057      xfree (dpyinfo->font_table);
11058    }
11059  if (dpyinfo->x_id_name)
11060    xfree (dpyinfo->x_id_name);
11061  if (dpyinfo->color_cells)
11062    xfree (dpyinfo->color_cells);
11063  xfree (dpyinfo);
11064}
11065
11066#ifdef USE_X_TOOLKIT
11067
11068/* Atimer callback function for TIMER.  Called every 0.1s to process
11069   Xt timeouts, if needed.  We must avoid calling XtAppPending as
11070   much as possible because that function does an implicit XFlush
11071   that slows us down.  */
11072
11073static void
11074x_process_timeouts (timer)
11075     struct atimer *timer;
11076{
11077  BLOCK_INPUT;
11078  x_timeout_atimer_activated_flag = 0;
11079  if (toolkit_scroll_bar_interaction || popup_activated ())
11080    {
11081      while (XtAppPending (Xt_app_con) & XtIMTimer)
11082	XtAppProcessEvent (Xt_app_con, XtIMTimer);
11083      /* Reactivate the atimer for next time.  */
11084      x_activate_timeout_atimer ();
11085    }
11086  UNBLOCK_INPUT;
11087}
11088
11089/* Install an asynchronous timer that processes Xt timeout events
11090   every 0.1s as long as either `toolkit_scroll_bar_interaction' or
11091   `popup_activated_flag' (in xmenu.c) is set.  Make sure to call this
11092   function whenever these variables are set.  This is necessary
11093   because some widget sets use timeouts internally, for example the
11094   LessTif menu bar, or the Xaw3d scroll bar.  When Xt timeouts aren't
11095   processed, these widgets don't behave normally.  */
11096
11097void
11098x_activate_timeout_atimer ()
11099{
11100  BLOCK_INPUT;
11101  if (!x_timeout_atimer_activated_flag)
11102    {
11103      EMACS_TIME interval;
11104
11105      EMACS_SET_SECS_USECS (interval, 0, 100000);
11106      start_atimer (ATIMER_RELATIVE, interval, x_process_timeouts, 0);
11107      x_timeout_atimer_activated_flag = 1;
11108    }
11109  UNBLOCK_INPUT;
11110}
11111
11112#endif /* USE_X_TOOLKIT */
11113
11114
11115/* Set up use of X before we make the first connection.  */
11116
11117extern frame_parm_handler x_frame_parm_handlers[];
11118
11119static struct redisplay_interface x_redisplay_interface =
11120{
11121  x_frame_parm_handlers,
11122  x_produce_glyphs,
11123  x_write_glyphs,
11124  x_insert_glyphs,
11125  x_clear_end_of_line,
11126  x_scroll_run,
11127  x_after_update_window_line,
11128  x_update_window_begin,
11129  x_update_window_end,
11130  x_cursor_to,
11131  x_flush,
11132#ifdef XFlush
11133  x_flush,
11134#else
11135  0,  /* flush_display_optional */
11136#endif
11137  x_clear_window_mouse_face,
11138  x_get_glyph_overhangs,
11139  x_fix_overlapping_area,
11140  x_draw_fringe_bitmap,
11141  0, /* define_fringe_bitmap */
11142  0, /* destroy_fringe_bitmap */
11143  x_per_char_metric,
11144  x_encode_char,
11145  x_compute_glyph_string_overhangs,
11146  x_draw_glyph_string,
11147  x_define_frame_cursor,
11148  x_clear_frame_area,
11149  x_draw_window_cursor,
11150  x_draw_vertical_window_border,
11151  x_shift_glyphs_for_insert
11152};
11153
11154void
11155x_initialize ()
11156{
11157  rif = &x_redisplay_interface;
11158
11159  clear_frame_hook = x_clear_frame;
11160  ins_del_lines_hook = x_ins_del_lines;
11161  delete_glyphs_hook = x_delete_glyphs;
11162  ring_bell_hook = XTring_bell;
11163  reset_terminal_modes_hook = XTreset_terminal_modes;
11164  set_terminal_modes_hook = XTset_terminal_modes;
11165  update_begin_hook = x_update_begin;
11166  update_end_hook = x_update_end;
11167  set_terminal_window_hook = XTset_terminal_window;
11168  read_socket_hook = XTread_socket;
11169  frame_up_to_date_hook = XTframe_up_to_date;
11170  mouse_position_hook = XTmouse_position;
11171  frame_rehighlight_hook = XTframe_rehighlight;
11172  frame_raise_lower_hook = XTframe_raise_lower;
11173  set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
11174  condemn_scroll_bars_hook = XTcondemn_scroll_bars;
11175  redeem_scroll_bar_hook = XTredeem_scroll_bar;
11176  judge_scroll_bars_hook = XTjudge_scroll_bars;
11177  fullscreen_hook = XTfullscreen_hook;
11178
11179  scroll_region_ok = 1;		/* we'll scroll partial frames */
11180  char_ins_del_ok = 1;
11181  line_ins_del_ok = 1;		/* we'll just blt 'em */
11182  fast_clear_end_of_line = 1;	/* X does this well */
11183  memory_below_frame = 0;	/* we don't remember what scrolls
11184				   off the bottom */
11185  baud_rate = 19200;
11186
11187  x_noop_count = 0;
11188  last_tool_bar_item = -1;
11189  any_help_event_p = 0;
11190  ignore_next_mouse_click_timeout = 0;
11191#ifdef HAVE_X_SM
11192  x_session_initialized = 0;
11193#endif
11194
11195#ifdef USE_GTK
11196  current_count = -1;
11197#endif
11198
11199  /* Try to use interrupt input; if we can't, then start polling.  */
11200  Fset_input_mode (Qt, Qnil, Qt, Qnil);
11201
11202#ifdef USE_X_TOOLKIT
11203  XtToolkitInitialize ();
11204
11205  Xt_app_con = XtCreateApplicationContext ();
11206
11207  /* Register a converter from strings to pixels, which uses
11208     Emacs' color allocation infrastructure.  */
11209  XtAppSetTypeConverter (Xt_app_con,
11210			 XtRString, XtRPixel, cvt_string_to_pixel,
11211			 cvt_string_to_pixel_args,
11212			 XtNumber (cvt_string_to_pixel_args),
11213			 XtCacheByDisplay, cvt_pixel_dtor);
11214
11215  XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
11216#endif
11217
11218#ifdef USE_TOOLKIT_SCROLL_BARS
11219#ifndef USE_GTK
11220  xaw3d_arrow_scroll = False;
11221  xaw3d_pick_top = True;
11222#endif
11223#endif
11224
11225  /* Note that there is no real way portable across R3/R4 to get the
11226     original error handler.  */
11227  XSetErrorHandler (x_error_handler);
11228  XSetIOErrorHandler (x_io_error_quitter);
11229
11230  /* Disable Window Change signals;  they are handled by X events.  */
11231#ifdef SIGWINCH
11232  signal (SIGWINCH, SIG_DFL);
11233#endif /* SIGWINCH */
11234
11235  signal (SIGPIPE, x_connection_signal);
11236}
11237
11238
11239void
11240syms_of_xterm ()
11241{
11242  x_error_message = NULL;
11243
11244  staticpro (&x_display_name_list);
11245  x_display_name_list = Qnil;
11246
11247  staticpro (&last_mouse_scroll_bar);
11248  last_mouse_scroll_bar = Qnil;
11249
11250  staticpro (&Qvendor_specific_keysyms);
11251  Qvendor_specific_keysyms = intern ("vendor-specific-keysyms");
11252
11253  staticpro (&Qutf_8);
11254  Qutf_8 = intern ("utf-8");
11255  staticpro (&Qlatin_1);
11256  Qlatin_1 = intern ("latin-1");
11257
11258  staticpro (&last_mouse_press_frame);
11259  last_mouse_press_frame = Qnil;
11260
11261  DEFVAR_BOOL ("x-use-underline-position-properties",
11262	       &x_use_underline_position_properties,
11263     doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
11264A value of nil means ignore them.  If you encounter fonts with bogus
11265UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
11266to 4.1, set this to nil.  */);
11267  x_use_underline_position_properties = 1;
11268
11269  DEFVAR_BOOL ("x-underline-at-descent-line",
11270	       &x_underline_at_descent_line,
11271     doc: /* *Non-nil means to draw the underline at the same place as the descent line.
11272A value of nil means to draw the underline according to the value of the
11273variable `x-use-underline-position-properties', which is usually at the
11274baseline level.  The default value is nil.  */);
11275  x_underline_at_descent_line = 0;
11276
11277  DEFVAR_BOOL ("x-mouse-click-focus-ignore-position",
11278	       &x_mouse_click_focus_ignore_position,
11279    doc: /* Non-nil means that a mouse click to focus a frame does not move point.
11280This variable is only used when the window manager requires that you
11281click on a frame to select it (give it focus).  In that case, a value
11282of nil, means that the selected window and cursor position changes to
11283reflect the mouse click position, while a non-nil value means that the
11284selected window or cursor position is preserved.  */);
11285  x_mouse_click_focus_ignore_position = 0;
11286
11287  DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
11288    doc: /* What X toolkit scroll bars Emacs uses.
11289A value of nil means Emacs doesn't use X toolkit scroll bars.
11290Otherwise, value is a symbol describing the X toolkit.  */);
11291#ifdef USE_TOOLKIT_SCROLL_BARS
11292#ifdef USE_MOTIF
11293  Vx_toolkit_scroll_bars = intern ("motif");
11294#elif defined HAVE_XAW3D
11295  Vx_toolkit_scroll_bars = intern ("xaw3d");
11296#elif USE_GTK
11297  Vx_toolkit_scroll_bars = intern ("gtk");
11298#else
11299  Vx_toolkit_scroll_bars = intern ("xaw");
11300#endif
11301#else
11302  Vx_toolkit_scroll_bars = Qnil;
11303#endif
11304
11305  staticpro (&last_mouse_motion_frame);
11306  last_mouse_motion_frame = Qnil;
11307
11308  Qmodifier_value = intern ("modifier-value");
11309  Qalt = intern ("alt");
11310  Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
11311  Qhyper = intern ("hyper");
11312  Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
11313  Qmeta = intern ("meta");
11314  Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
11315  Qsuper = intern ("super");
11316  Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
11317
11318  DEFVAR_LISP ("x-alt-keysym", &Vx_alt_keysym,
11319    doc: /* Which keys Emacs uses for the alt modifier.
11320This should be one of the symbols `alt', `hyper', `meta', `super'.
11321For example, `alt' means use the Alt_L and Alt_R keysyms.  The default
11322is nil, which is the same as `alt'.  */);
11323  Vx_alt_keysym = Qnil;
11324
11325  DEFVAR_LISP ("x-hyper-keysym", &Vx_hyper_keysym,
11326    doc: /* Which keys Emacs uses for the hyper modifier.
11327This should be one of the symbols `alt', `hyper', `meta', `super'.
11328For example, `hyper' means use the Hyper_L and Hyper_R keysyms.  The
11329default is nil, which is the same as `hyper'.  */);
11330  Vx_hyper_keysym = Qnil;
11331
11332  DEFVAR_LISP ("x-meta-keysym", &Vx_meta_keysym,
11333    doc: /* Which keys Emacs uses for the meta modifier.
11334This should be one of the symbols `alt', `hyper', `meta', `super'.
11335For example, `meta' means use the Meta_L and Meta_R keysyms.  The
11336default is nil, which is the same as `meta'.  */);
11337  Vx_meta_keysym = Qnil;
11338
11339  DEFVAR_LISP ("x-super-keysym", &Vx_super_keysym,
11340    doc: /* Which keys Emacs uses for the super modifier.
11341This should be one of the symbols `alt', `hyper', `meta', `super'.
11342For example, `super' means use the Super_L and Super_R keysyms.  The
11343default is nil, which is the same as `super'.  */);
11344  Vx_super_keysym = Qnil;
11345
11346  DEFVAR_LISP ("x-keysym-table", &Vx_keysym_table,
11347    doc: /* Hash table of character codes indexed by X keysym codes.  */);
11348  Vx_keysym_table = make_hash_table (Qeql, make_number (900),
11349				     make_float (DEFAULT_REHASH_SIZE),
11350				     make_float (DEFAULT_REHASH_THRESHOLD),
11351				     Qnil, Qnil, Qnil);
11352}
11353
11354#endif /* HAVE_X_WINDOWS */
11355
11356/* arch-tag: 6d4e4cb7-abc1-4302-9585-d84dcfb09d0f
11357   (do not change this comment) */
11358