home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 5 Edit / 05-Edit.zip / e20313sr.zip / emacs / 20.3.1 / src / xterm.c < prev    next >
C/C++ Source or Header  |  1999-07-31  |  222KB  |  7,381 lines

  1. /* X Communication module for terminals which understand the X protocol.
  2.    Copyright (C) 1989, 93, 94, 95, 96, 1997 Free Software Foundation, Inc.
  3.  
  4. This file is part of GNU Emacs.
  5.  
  6. GNU Emacs is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10.  
  11. GNU Emacs is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU Emacs; see the file COPYING.  If not, write to
  18. the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  19. Boston, MA 02111-1307, USA.  */
  20.  
  21. /* Xt features made by Fred Pierresteguy.  */
  22.  
  23. /* On 4.3 these lose if they come after xterm.h.  */
  24. /* On HP-UX 8.0 signal.h loses if it comes after config.h.  */
  25. /* Putting these at the beginning seems to be standard for other .c files.  */
  26. #include <signal.h>
  27.  
  28. #include <config.h>
  29.  
  30. #include <stdio.h>
  31.  
  32. #ifdef HAVE_X_WINDOWS
  33.  
  34. #include "lisp.h"
  35. #include "blockinput.h"
  36.  
  37. /* Need syssignal.h for various externs and definitions that may be required
  38.    by some configurations for calls to signal later in this source file.  */
  39. #include "syssignal.h"
  40.  
  41. /* This may include sys/types.h, and that somehow loses
  42.    if this is not done before the other system files.  */
  43. #include "xterm.h"
  44. #include <X11/cursorfont.h>
  45.  
  46. #ifndef USG
  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. #endif /* USG */
  53.  
  54. #ifdef BSD_SYSTEM
  55. #include <sys/ioctl.h>
  56. #endif /* ! defined (BSD_SYSTEM) */
  57.  
  58. #include "systty.h"
  59. #include "systime.h"
  60.  
  61. #ifndef INCLUDED_FCNTL
  62. #include <fcntl.h>
  63. #endif
  64. #include <ctype.h>
  65. #include <errno.h>
  66. #include <setjmp.h>
  67. #include <sys/stat.h>
  68. /* Caused redefinition of DBL_DIG on Netbsd; seems not to be needed.  */
  69. /* #include <sys/param.h>  */
  70.  
  71. #include "charset.h"
  72. #include "ccl.h"
  73. #include "fontset.h"
  74. #include "frame.h"
  75. #include "dispextern.h"
  76. #include "termhooks.h"
  77. #include "termopts.h"
  78. #include "termchar.h"
  79. #if 0
  80. #include "sink.h"
  81. #include "sinkmask.h"
  82. #endif /* ! 0 */
  83. #include "gnu.h"
  84. #include "disptab.h"
  85. #include "buffer.h"
  86. #include "window.h"
  87. #include "keyboard.h"
  88. #include "intervals.h"
  89. #include "process.h"
  90.  
  91. #ifdef USE_X_TOOLKIT
  92. #include <X11/Shell.h>
  93. #endif
  94.  
  95. #ifdef USE_X_TOOLKIT
  96. extern void free_frame_menubar ();
  97. extern FRAME_PTR x_menubar_window_to_frame ();
  98. #if (XtSpecificationRelease >= 5) && !defined(NO_EDITRES)
  99. #define HACK_EDITRES
  100. extern void _XEditResCheckMessages ();
  101. #endif /* not NO_EDITRES */
  102. #endif /* USE_X_TOOLKIT */
  103.  
  104. #ifndef USE_X_TOOLKIT
  105. #define x_any_window_to_frame x_window_to_frame
  106. #define x_top_window_to_frame x_window_to_frame
  107. #endif
  108.  
  109. #ifdef USE_X_TOOLKIT
  110. #include "widget.h"
  111. #ifndef XtNinitialState
  112. #define XtNinitialState "initialState"
  113. #endif
  114. #endif
  115.  
  116. #ifdef HAVE_SETLOCALE
  117. /* So we can do setlocale.  */
  118. #include <locale.h>
  119. #endif
  120.  
  121. #ifdef SOLARIS2
  122. /* memmove will be defined as a macro in Xfuncs.h unless
  123.    <string.h> is included beforehand.  The declaration for memmove in
  124.    <string.h> will cause a syntax error when Xfuncs.h later includes it.  */
  125. #include <string.h>
  126. #endif
  127.  
  128. #ifndef min
  129. #define min(a,b) ((a)<(b) ? (a) : (b))
  130. #endif
  131. #ifndef max
  132. #define max(a,b) ((a)>(b) ? (a) : (b))
  133. #endif
  134.  
  135. /* This is a chain of structures for all the X displays currently in use.  */
  136. struct x_display_info *x_display_list;
  137.  
  138. /* This is a list of cons cells, each of the form (NAME . FONT-LIST-CACHE),
  139.    one for each element of x_display_list and in the same order.
  140.    NAME is the name of the frame.
  141.    FONT-LIST-CACHE records previous values returned by x-list-fonts.  */
  142. Lisp_Object x_display_name_list;
  143.  
  144. /* Frame being updated by update_frame.  This is declared in term.c.
  145.    This is set by update_begin and looked at by all the
  146.    XT functions.  It is zero while not inside an update.
  147.    In that case, the XT functions assume that `selected_frame'
  148.    is the frame to apply to.  */
  149. extern struct frame *updating_frame;
  150.  
  151. extern int waiting_for_input;
  152.  
  153. /* This is a frame waiting to be autoraised, within XTread_socket.  */
  154. struct frame *pending_autoraise_frame;
  155.  
  156. #ifdef USE_X_TOOLKIT
  157. /* The application context for Xt use.  */
  158. XtAppContext Xt_app_con;
  159.  
  160. static String Xt_default_resources[] =
  161. {
  162.   0
  163. };
  164. #endif
  165.  
  166. /* During an update, maximum vpos for ins/del line operations to affect.  */
  167.  
  168. static int flexlines;
  169.  
  170. /* During an update, nonzero if chars output now should be highlighted.  */
  171.  
  172. static int highlight;
  173.  
  174. /* Nominal cursor position -- where to draw output.
  175.    During an update, these are different from the cursor-box position.  */
  176.  
  177. static int curs_x;
  178. static int curs_y;
  179.  
  180. /* Mouse movement.
  181.  
  182.    Formerly, we used PointerMotionHintMask (in STANDARD_EVENT_MASK)
  183.    so that we would have to call XQueryPointer after each MotionNotify
  184.    event to ask for another such event.  However, this made mouse tracking
  185.    slow, and there was a bug that made it eventually stop.
  186.  
  187.    Simply asking for MotionNotify all the time seems to work better.
  188.  
  189.    In order to avoid asking for motion events and then throwing most
  190.    of them away or busy-polling the server for mouse positions, we ask
  191.    the server for pointer motion hints.  This means that we get only
  192.    one event per group of mouse movements.  "Groups" are delimited by
  193.    other kinds of events (focus changes and button clicks, for
  194.    example), or by XQueryPointer calls; when one of these happens, we
  195.    get another MotionNotify event the next time the mouse moves.  This
  196.    is at least as efficient as getting motion events when mouse
  197.    tracking is on, and I suspect only negligibly worse when tracking
  198.    is off.  */
  199.  
  200. /* Where the mouse was last time we reported a mouse event.  */
  201. static FRAME_PTR last_mouse_frame;
  202. static XRectangle last_mouse_glyph;
  203.  
  204. static Lisp_Object last_mouse_press_frame;
  205.  
  206. /* The scroll bar in which the last X motion event occurred.
  207.  
  208.    If the last X motion event occurred in a scroll bar, we set this
  209.    so XTmouse_position can know whether to report a scroll bar motion or
  210.    an ordinary motion.
  211.  
  212.    If the last X motion event didn't occur in a scroll bar, we set this
  213.    to Qnil, to tell XTmouse_position to return an ordinary motion event.  */
  214. static Lisp_Object last_mouse_scroll_bar;
  215.  
  216. /* This is a hack.  We would really prefer that XTmouse_position would
  217.    return the time associated with the position it returns, but there
  218.    doesn't seem to be any way to wrest the timestamp from the server
  219.    along with the position query.  So, we just keep track of the time
  220.    of the last movement we received, and return that in hopes that
  221.    it's somewhat accurate.  */
  222. static Time last_mouse_movement_time;
  223.  
  224. /* Incremented by XTread_socket whenever it really tries to read events.  */
  225. #ifdef __STDC__
  226. static int volatile input_signal_count;
  227. #else
  228. static int input_signal_count;
  229. #endif
  230.  
  231. /* Used locally within XTread_socket.  */
  232. static int x_noop_count;
  233.  
  234. /* Initial values of argv and argc.  */
  235. extern char **initial_argv;
  236. extern int initial_argc;
  237.  
  238. extern Lisp_Object Vcommand_line_args, Vsystem_name;
  239.  
  240. /* Tells if a window manager is present or not. */
  241.  
  242. extern Lisp_Object Vx_no_window_manager;
  243.  
  244. extern Lisp_Object Qface, Qmouse_face;
  245.  
  246. extern int errno;
  247.  
  248. /* A mask of extra modifier bits to put into every keyboard char.  */
  249. extern int extra_keyboard_modifiers;
  250.  
  251. static Lisp_Object Qvendor_specific_keysyms;
  252.  
  253. extern XrmDatabase x_load_resources ();
  254.  
  255. extern Lisp_Object x_icon_type ();
  256.  
  257. void x_delete_display ();
  258.  
  259. static void redraw_previous_char ();
  260. static void redraw_following_char ();
  261. static unsigned int x_x_to_emacs_modifiers ();
  262.  
  263. static int fast_find_position ();
  264. static void note_mouse_highlight ();
  265. static void clear_mouse_face ();
  266. static void show_mouse_face ();
  267. static void do_line_dance ();
  268.  
  269. static void XTcursor_to ();
  270. static void XTclear_end_of_line ();
  271. static int x_io_error_quitter ();
  272. int x_catch_errors ();
  273. void x_uncatch_errors ();
  274.  
  275. #if 0
  276. /* This is a function useful for recording debugging information
  277.    about the sequence of occurrences in this file.  */
  278.  
  279. struct record 
  280. {
  281.   char *locus;
  282.   int type;
  283. };
  284.  
  285. struct record event_record[100];
  286.  
  287. int event_record_index;
  288.  
  289. record_event (locus, type)
  290.      char *locus;
  291.      int type;
  292. {
  293.   if (event_record_index == sizeof (event_record) / sizeof (struct record))
  294.     event_record_index = 0;
  295.  
  296.   event_record[event_record_index].locus = locus;
  297.   event_record[event_record_index].type = type;
  298.   event_record_index++;
  299. }
  300.  
  301. #endif /* 0 */
  302.  
  303. /* Return the struct x_display_info corresponding to DPY.  */
  304.  
  305. struct x_display_info *
  306. x_display_info_for_display (dpy)
  307.      Display *dpy;
  308. {
  309.   struct x_display_info *dpyinfo;
  310.  
  311.   for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
  312.     if (dpyinfo->display == dpy)
  313.       return dpyinfo;
  314.  
  315.   return 0;
  316. }
  317.  
  318. /* Starting and ending updates.
  319.  
  320.    These hooks are called by update_frame at the beginning and end
  321.    of a frame update.  We record in `updating_frame' the identity
  322.    of the frame being updated, so that the XT... functions do not
  323.    need to take a frame as argument.  Most of the XT... functions
  324.    should never be called except during an update, the only exceptions
  325.    being XTcursor_to, XTwrite_glyphs and XTreassert_line_highlight.  */
  326.  
  327. static void
  328. XTupdate_begin (f)
  329.      struct frame *f;
  330. {
  331.   int mask;
  332.  
  333.   if (f == 0)
  334.     abort ();
  335.  
  336.   flexlines = f->height;
  337.   highlight = 0;
  338.  
  339.   BLOCK_INPUT;
  340.  
  341.   curs_x = FRAME_CURSOR_X (f);
  342.   curs_y = FRAME_CURSOR_Y (f);
  343.  
  344.   if (f == FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_frame)
  345.     {
  346.       /* Don't do highlighting for mouse motion during the update.  */
  347.       FRAME_X_DISPLAY_INFO (f)->mouse_face_defer = 1;
  348.  
  349.       /* If the frame needs to be redrawn,
  350.      simply forget about any prior mouse highlighting.  */
  351.       if (FRAME_GARBAGED_P (f))
  352.     FRAME_X_DISPLAY_INFO (f)->mouse_face_window = Qnil;
  353.  
  354.       if (!NILP (FRAME_X_DISPLAY_INFO (f)->mouse_face_window))
  355.     {
  356.       int firstline, lastline, i;
  357.       struct window *w = XWINDOW (FRAME_X_DISPLAY_INFO (f)->mouse_face_window);
  358.  
  359.       /* Find the first, and the last+1, lines affected by redisplay.  */
  360.       for (firstline = 0; firstline < f->height; firstline++)
  361.         if (FRAME_DESIRED_GLYPHS (f)->enable[firstline])
  362.           break;
  363.  
  364.       lastline = f->height;
  365.       for (i = f->height - 1; i >= 0; i--)
  366.         {
  367.           if (FRAME_DESIRED_GLYPHS (f)->enable[i])
  368.         break;
  369.           else
  370.         lastline = i;
  371.         }
  372.  
  373.       /* Can we tell that this update does not affect the window
  374.          where the mouse highlight is?  If so, no need to turn off.
  375.          Likewise, don't do anything if the frame is garbaged;
  376.          in that case, the FRAME_CURRENT_GLYPHS that we would use
  377.          are all wrong, and we will redisplay that line anyway.  */
  378.       if (! (firstline > (XFASTINT (w->top) + window_internal_height (w))
  379.          || lastline < XFASTINT (w->top)))
  380.         clear_mouse_face (FRAME_X_DISPLAY_INFO (f));
  381.     }
  382.     }
  383.  
  384.   UNBLOCK_INPUT;
  385. }
  386.  
  387. static void
  388. XTupdate_end (f)
  389.      struct frame *f;
  390. {
  391.   int mask;
  392.  
  393.   BLOCK_INPUT;
  394.  
  395.   do_line_dance ();
  396.   x_display_cursor (f, 1, curs_x, curs_y);
  397.  
  398.   FRAME_X_DISPLAY_INFO (f)->mouse_face_defer = 0;
  399. #if 0
  400.   /* This fails in the case of having updated only the echo area
  401.      if we have switched buffers.  In that case, FRAME_CURRENT_GLYPHS
  402.      has no relation to the current contents, and its charstarts
  403.      have no relation to the contents of the window-buffer.
  404.   I don't know a clean way to check
  405.      for that case.  window_end_valid isn't set up yet.  */
  406.   if (f == FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_frame)
  407.     note_mouse_highlight (f, FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_x,
  408.               FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_y);
  409. #endif
  410.  
  411.   XFlush (FRAME_X_DISPLAY (f));
  412.   UNBLOCK_INPUT;
  413. }
  414.  
  415. /* This is called after a redisplay on frame F.  */
  416.  
  417. static void
  418. XTframe_up_to_date (f)
  419.      FRAME_PTR f;
  420. {
  421.   BLOCK_INPUT;
  422.   if (FRAME_X_DISPLAY_INFO (f)->mouse_face_deferred_gc
  423.       || f == FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_frame)
  424.     {
  425.       if (FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_frame)
  426.     note_mouse_highlight (FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_frame,
  427.                   FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_x,
  428.                   FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_y);
  429.       FRAME_X_DISPLAY_INFO (f)->mouse_face_deferred_gc = 0;
  430.     }
  431.   UNBLOCK_INPUT;
  432. }
  433.  
  434. /* External interface to control of standout mode.
  435.    Call this when about to modify line at position VPOS
  436.    and not change whether it is highlighted.  */
  437.  
  438. void
  439. XTreassert_line_highlight (new, vpos)
  440.      int new, vpos;
  441. {
  442.   highlight = new;
  443. }
  444.  
  445. /* Call this when about to modify line at position VPOS
  446.    and change whether it is highlighted.  */
  447.  
  448. static void
  449. XTchange_line_highlight (new_highlight, vpos, first_unused_hpos)
  450.      int new_highlight, vpos, first_unused_hpos;
  451. {
  452.   highlight = new_highlight;
  453.   XTcursor_to (vpos, 0);
  454.   XTclear_end_of_line (FRAME_WINDOW_WIDTH (updating_frame));
  455. }
  456.  
  457. /* This is used when starting Emacs and when restarting after suspend.
  458.    When starting Emacs, no X window is mapped.  And nothing must be done
  459.    to Emacs's own window if it is suspended (though that rarely happens).  */
  460.  
  461. static void
  462. XTset_terminal_modes ()
  463. {
  464. }
  465.  
  466. /* This is called when exiting or suspending Emacs.
  467.    Exiting will make the X-windows go away, and suspending
  468.    requires no action.  */
  469.  
  470. static void
  471. XTreset_terminal_modes ()
  472. {
  473. /*  XTclear_frame ();  */
  474. }
  475.  
  476. /* Set the nominal cursor position of the frame.
  477.    This is where display update commands will take effect.
  478.    This does not affect the place where the cursor-box is displayed.  */
  479.  
  480. static void
  481. XTcursor_to (row, col)
  482.      register int row, col;
  483. {
  484.   int mask;
  485.   int orow = row;
  486.   struct frame *f;
  487.   
  488.   f = updating_frame;
  489.   if (f == 0)
  490.     f = selected_frame;
  491.  
  492.   curs_x = col;
  493.   if (curs_x >= FRAME_CURSOR_X_LIMIT (f))
  494.     curs_x = FRAME_CURSOR_X_LIMIT (f) - 1;
  495.  
  496.   curs_y = row;
  497.  
  498.   if (updating_frame == 0)
  499.     {
  500.       BLOCK_INPUT;
  501.       x_display_cursor (selected_frame, 1, curs_x, curs_y);
  502.       XFlush (FRAME_X_DISPLAY (selected_frame));
  503.       UNBLOCK_INPUT;
  504.     }
  505. }
  506.  
  507.  
  508. /* Return a pointer to per char metric information in FONT of a
  509.    character pointed by B (*XChar2b).  */
  510.  
  511. #define PER_CHAR_METRIC(font, b)                       \
  512.   ((font)->per_char                               \
  513.    ? ((font)->per_char + (b)->byte2 - (font)->min_char_or_byte2           \
  514.       + (((font)->min_byte1 || (font)->max_byte1)               \
  515.      ? (((b)->byte1 - (font)->min_byte1)                   \
  516.         * ((font)->max_char_or_byte2 - (font)->min_char_or_byte2 + 1)) \
  517.      : 0))                                   \
  518.    : &((font)->max_bounds))
  519.  
  520. /* Display a sequence of N glyphs found at GP.
  521.    WINDOW is the x-window to output to.  LEFT and TOP are starting coords.
  522.    HL is 1 if this text is highlighted, 2 if the cursor is on it,
  523.    3 if should appear in its mouse-face.
  524.    JUST_FOREGROUND if 1 means draw only the foreground;
  525.    don't alter the background.
  526.  
  527.    CMPCHARP if non NULL is a pointer to the struct cmpchar_info, which
  528.    means drawing glyphs on the same column.  This is set to non NULL
  529.    only when recursively called within dumpglyphs to draw a composite
  530.    character specified by CMPCHAR.
  531.  
  532.    FONT is the default font to use (for glyphs whose font-code is 0).
  533.  
  534.    Since the display generation code is responsible for calling
  535.    compute_char_face and compute_glyph_face on everything it puts in
  536.    the display structure, we can assume that the face code on each
  537.    glyph is a valid index into FRAME_COMPUTED_FACES (f), and the one
  538.    to which we can actually apply intern_face.
  539.    Call this function with input blocked.
  540.  
  541.    Return overall pixel width of the drawn glyphs.  */
  542.  
  543. #if 1
  544. /* This is the multi-face code.  */
  545.  
  546. static int
  547. dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
  548.      struct frame *f;
  549.      int left, top;
  550.      register GLYPH *gp; /* Points to first GLYPH. */
  551.      register int n;  /* Number of glyphs to display. */
  552.      int hl;
  553.      int just_foreground;
  554.      struct cmpchar_info *cmpcharp;
  555. {
  556.   /* Holds characters to be displayed. */
  557.   XChar2b *x_2byte_buffer
  558.     = (XChar2b *) alloca (FRAME_WINDOW_WIDTH (f) * sizeof (*x_2byte_buffer));
  559.   register XChar2b *cp;        /* Steps through x_2byte_buffer[]. */
  560.   char *x_1byte_buffer
  561.     = (char *) alloca (FRAME_WINDOW_WIDTH (f) * sizeof (*x_1byte_buffer));
  562.   register int tlen = GLYPH_TABLE_LENGTH;
  563.   register Lisp_Object *tbase = GLYPH_TABLE_BASE;
  564.   Window window = FRAME_X_WINDOW (f);
  565.   int orig_left = left;
  566.   int gidx = 0;
  567.   int i;
  568.  
  569.   while (n > 0)
  570.     {
  571.       /* Get the face-code of the next GLYPH.  */
  572.       int cf, len;
  573.       GLYPH g = *gp;
  574.       int ch, charset;
  575.       Lisp_Object first_ch;
  576.       /* HIGHEST and LOWEST are used while drawing a composite
  577.          character.  The meanings are described later.  */
  578.       int highest, lowest;
  579.  
  580.       GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
  581.       cf = (cmpcharp ? cmpcharp->face_work : FAST_GLYPH_FACE (g));
  582.       ch = FAST_GLYPH_CHAR (g);
  583.       if (unibyte_display_via_language_environment
  584.       && SINGLE_BYTE_CHAR_P (ch)
  585.       && ch >= 160)
  586.     ch = unibyte_char_to_multibyte (ch);
  587.       if (gidx == 0) XSETFASTINT (first_ch, ch);
  588.       charset = CHAR_CHARSET (ch);
  589.       if (charset == CHARSET_COMPOSITION)
  590.     {
  591.       /* We must draw components of the composite character on the
  592.              same column.  */
  593.       cmpcharp = cmpchar_table[COMPOSITE_CHAR_ID (ch)];
  594.  
  595.       /* Set the face in the slot for work.  */
  596.       cmpcharp->face_work = cf;
  597.  
  598.       /* We don't need the return value ... */
  599.       dumpglyphs (f, left, top, cmpcharp->glyph, cmpcharp->glyph_len,
  600.               hl, just_foreground, cmpcharp);
  601.       /* ... because the width of just drawn text can be
  602.              calculated as follows.  */
  603.       left += FONT_WIDTH (f->output_data.x->font) * cmpcharp->width;
  604.  
  605.       ++gp, --n;
  606.       while (gp && (*gp & GLYPH_MASK_PADDING)) ++gp, --n;
  607.       cmpcharp = NULL;
  608.       continue;
  609.     }
  610.  
  611.       /* Find the run of consecutive glyphs which can be drawn with
  612.      the same GC (i.e. the same charset and the same face-code).
  613.      Extract their character codes into X_2BYTE_BUFFER.
  614.      If CMPCHARP is not NULL, face-code is not checked because we
  615.      use only the face specified in `cmpcharp->face_work'.  */
  616.       cp = x_2byte_buffer;
  617.       while (n > 0)
  618.     {
  619.       int this_charset, c1, c2;
  620.  
  621.       g = *gp;
  622.       GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
  623.       ch = FAST_GLYPH_CHAR (g);
  624.       if (unibyte_display_via_language_environment
  625.           && SINGLE_BYTE_CHAR_P (ch)
  626.           && ch >= 160)
  627.         ch = unibyte_char_to_multibyte (ch);
  628.       SPLIT_CHAR (ch, this_charset, c1, c2);
  629.       if (this_charset != charset
  630.           || (cmpcharp == NULL && FAST_GLYPH_FACE (g) != cf))
  631.         break;
  632.  
  633.       if (c2 > 0)
  634.         cp->byte1 = c1, cp->byte2 = c2;
  635.       else
  636.         cp->byte1 = 0, cp->byte2 = c1;
  637.       ++cp;
  638.       ++gp, --n;
  639.       while (gp && (*gp & GLYPH_MASK_PADDING))
  640.         ++gp, --n;
  641.     }
  642.  
  643.       /* LEN gets the length of the run.  */
  644.       len = cp - x_2byte_buffer;
  645.       /* Now output this run of chars, with the font and pixel values
  646.      determined by the face code CF.  */
  647.       {
  648.     struct face *face = FRAME_DEFAULT_FACE (f);
  649.     XFontStruct *font = NULL;
  650.     GC gc;
  651.     int stippled = 0;
  652.     int line_height = f->output_data.x->line_height;
  653.     /* Pixel width of each glyph in this run.  */
  654.     int glyph_width
  655.       = (FONT_WIDTH (f->output_data.x->font)
  656.          * (cmpcharp ? cmpcharp->width : CHARSET_WIDTH (charset)));
  657.     /* Overall pixel width of this run.  */
  658.     int run_width
  659.       = (FONT_WIDTH (f->output_data.x->font)
  660.          * (cmpcharp ? cmpcharp->width : len * CHARSET_WIDTH (charset)));
  661.     /* A flag to tell if we have already filled background.  We
  662.        fill background in advance in the following cases:
  663.        1) A face has stipple.
  664.        2) A height of font is shorter than LINE_HEIGHT.
  665.        3) Drawing a composite character.
  666.        4) Font has non-zero _MULE_BASELINE_OFFSET property.
  667.        After filling background, we draw glyphs by XDrawString16.  */
  668.     int background_filled;
  669.     /* Baseline position of a character, offset from TOP.  */
  670.     int baseline;
  671.     /* The property value of `_MULE_RELATIVE_COMPOSE' and
  672.            `_MULE_DEFAULT_ASCENT'.  */
  673.     int relative_compose = 0, default_ascent = 0;
  674.     /* 1 if we find no font or a font of inappropriate size.  */
  675.     int require_clipping;
  676.  
  677.     /* HL = 3 means use a mouse face previously chosen.  */
  678.     if (hl == 3)
  679.       cf = FRAME_X_DISPLAY_INFO (f)->mouse_face_face_id;
  680.  
  681.     /* First look at the face of the text itself.  */
  682.     if (cf != 0)
  683.       {
  684.         /* It's possible for the display table to specify
  685.            a face code that is out of range.  Use 0 in that case.  */
  686.         if (cf < 0 || cf >= FRAME_N_COMPUTED_FACES (f)
  687.         || FRAME_COMPUTED_FACES (f) [cf] == 0)
  688.           cf = 0;
  689.  
  690.         if (cf == 1)
  691.           face = FRAME_MODE_LINE_FACE (f);
  692.         else
  693.           face = intern_face (f, FRAME_COMPUTED_FACES (f) [cf]);
  694.         if (FACE_STIPPLE (face))
  695.           stippled = 1;
  696.       }
  697.  
  698.     /* Then comes the distinction between modeline and normal text.  */
  699.     else if (hl == 0)
  700.       ;
  701.     else if (hl == 1)
  702.       {
  703.         face = FRAME_MODE_LINE_FACE (f);
  704.         if (FACE_STIPPLE (face))
  705.           stippled = 1;
  706.       }
  707.  
  708. #define FACE_DEFAULT (~0)
  709.  
  710.     /* Setting appropriate font and gc for this charset.  */
  711.     if (charset != CHARSET_ASCII)
  712.       {
  713.         int font_id;
  714.         int fontset = FACE_FONTSET (face);
  715.         struct font_info *fontp;
  716.  
  717.         if ((fontset < 0 && (fontset = FRAME_FONTSET (f)) < 0)
  718.         || !(fontp = FS_LOAD_FONT (f, FRAME_X_FONT_TABLE (f),
  719.                        charset, NULL, fontset)))
  720.           goto font_not_found;
  721.  
  722.         font = (XFontStruct *) (fontp->font);
  723.         gc = FACE_NON_ASCII_GC (face);
  724.         XSetFont (FRAME_X_DISPLAY (f), gc, font->fid);
  725.         baseline
  726.           = (font->max_byte1 != 0
  727.          ? (line_height + font->ascent - font->descent) / 2
  728.          : f->output_data.x->font_baseline - fontp->baseline_offset);
  729.         if (FONT_HEIGHT (font) <= line_height
  730.         && (font->ascent > baseline
  731.             || font->descent > line_height - baseline))
  732.           /* Adjust baseline for this font to show the whole
  733.                  glyphs in a line.  */
  734.           baseline = line_height - font->descent;
  735.           
  736.         if (cmpcharp && cmpcharp->cmp_rule == NULL)
  737.           {
  738.         relative_compose = fontp->relative_compose;
  739.         default_ascent = fontp->default_ascent;
  740.           }
  741.  
  742.         /* We have to change code points in the following cases.  */
  743.         if (fontp->font_encoder)
  744.           {
  745.         /* This font requires CCL program to calculate code
  746.                    point of characters.  */
  747.         struct ccl_program *ccl = fontp->font_encoder;
  748.  
  749.         if (CHARSET_DIMENSION (charset) == 1)
  750.           for (cp = x_2byte_buffer; cp < x_2byte_buffer + len; cp++)
  751.             {
  752.               ccl->reg[0] = charset;
  753.               ccl->reg[1] = cp->byte2;
  754.               ccl_driver (ccl, NULL, NULL, 0, 0, NULL);
  755.               /* We assume that MSBs are appropriately
  756.                          set/reset by CCL program.  */
  757.               if (font->max_byte1 == 0)    /* 1-byte font */
  758.             cp->byte1 = 0, cp->byte2 = ccl->reg[1];
  759.               else
  760.             cp->byte1 = ccl->reg[1], cp->byte2 = ccl->reg[2];
  761.             }
  762.         else
  763.           for (cp = x_2byte_buffer; cp < x_2byte_buffer + len; cp++)
  764.             {
  765.               ccl->reg[0] = charset;
  766.               ccl->reg[1] = cp->byte1, ccl->reg[2] = cp->byte2;
  767.               ccl_driver (ccl, NULL, NULL, 0, 0, NULL);
  768.               /* We assume that MSBs are appropriately
  769.                          set/reset by CCL program.  */
  770.               if (font->max_byte1 == 0)    /* 1-byte font */
  771.             cp->byte1 = 0, cp->byte2 = ccl->reg[1];
  772.               else
  773.             cp->byte1 = ccl->reg[1], cp->byte2 = ccl->reg[2];
  774.             }
  775.           }
  776.         else if (fontp->encoding[charset])
  777.           {
  778.         int enc = fontp->encoding[charset];
  779.  
  780.         if ((enc == 1 || enc == 2) && CHARSET_DIMENSION (charset) == 2)
  781.           for (cp = x_2byte_buffer; cp < x_2byte_buffer + len; cp++)
  782.             cp->byte1 |= 0x80;
  783.         if (enc == 1 || enc == 3)
  784.           for (cp = x_2byte_buffer; cp < x_2byte_buffer + len; cp++)
  785.             cp->byte2 |= 0x80;
  786.           }
  787.       }
  788.     else
  789.       {
  790.       font_not_found:
  791.         if (charset == CHARSET_ASCII || charset == charset_latin_iso8859_1)
  792.           {
  793.         font = FACE_FONT (face);
  794.         if (!font || font == (XFontStruct *) FACE_DEFAULT)
  795.           font = f->output_data.x->font;
  796.         baseline = FONT_BASE (f->output_data.x->font);
  797.         if (charset == charset_latin_iso8859_1)
  798.           {
  799.             if (font->max_char_or_byte2 < 0x80)
  800.               /* This font can't display Latin1 characters.  */
  801.               font = NULL;
  802.             else
  803.               {
  804.             for (cp = x_2byte_buffer; cp < x_2byte_buffer + len; cp++)
  805.               cp->byte2 |= 0x80;
  806.               }
  807.           }
  808.           }
  809.         gc = FACE_GC (face);
  810.       }
  811.  
  812.     /* Now override that if the cursor's on this character.  */
  813.     if (hl == 2)
  814.       {
  815.         /* The cursor overrides stippling.  */
  816.         stippled = 0;
  817.  
  818.         if (font == f->output_data.x->font
  819.         && face->background == f->output_data.x->background_pixel
  820.         && face->foreground == f->output_data.x->foreground_pixel
  821.         && !cmpcharp)
  822.           {
  823.         gc = f->output_data.x->cursor_gc;
  824.           }
  825.         /* Cursor on non-default face: must merge.  */
  826.         else
  827.           {
  828.         XGCValues xgcv;
  829.         unsigned long mask;
  830.  
  831.         xgcv.background = f->output_data.x->cursor_pixel;
  832.         xgcv.foreground = face->background;
  833.         /* If the glyph would be invisible,
  834.            try a different foreground.  */
  835.         if (xgcv.foreground == xgcv.background)
  836.           xgcv.foreground = face->foreground;
  837.         if (xgcv.foreground == xgcv.background)
  838.           xgcv.foreground = f->output_data.x->cursor_foreground_pixel;
  839.         if (xgcv.foreground == xgcv.background)
  840.           xgcv.foreground = face->foreground;
  841.         /* Make sure the cursor is distinct from text in this face.  */
  842.         if (xgcv.background == face->background
  843.             && xgcv.foreground == face->foreground)
  844.           {
  845.             xgcv.background = face->foreground;
  846.             xgcv.foreground = face->background;
  847.           }
  848.         xgcv.graphics_exposures = 0;
  849.         mask = GCForeground | GCBackground | GCGraphicsExposures;
  850.         if (font)
  851.           {
  852.             xgcv.font = font->fid;
  853.             mask |= GCFont;
  854.           }
  855.  
  856.         if (FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc)
  857.           XChangeGC (FRAME_X_DISPLAY (f),
  858.                  FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc,
  859.                  mask, &xgcv);
  860.         else
  861.           FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc
  862.             = XCreateGC (FRAME_X_DISPLAY (f), window, mask, &xgcv);
  863.         gc = FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc;
  864. #if 0
  865. /* If this code is restored, it must also reset to the default stipple
  866.    if necessary. */
  867.         if (face->stipple && face->stipple != FACE_DEFAULT)
  868.           XSetStipple (FRAME_X_DISPLAY (f), gc, face->stipple);
  869. #endif
  870.           }
  871.       }
  872.  
  873.     if (font)
  874.       require_clipping = (!NILP (Vclip_large_size_font)
  875.                   && (font->ascent > baseline
  876.                   || font->descent > line_height - baseline
  877.                   || (!cmpcharp
  878.                       && FONT_WIDTH (font) > glyph_width)));
  879.  
  880.     if (font && (just_foreground || (cmpcharp && gidx > 0)))
  881.       background_filled = 1;
  882.     else if (stippled)
  883.       {
  884.         /* Turn stipple on.  */
  885.         XSetFillStyle (FRAME_X_DISPLAY (f), gc, FillOpaqueStippled);
  886.  
  887.         /* Draw stipple or background color on background.  */
  888.         XFillRectangle (FRAME_X_DISPLAY (f), window, gc,
  889.                 left, top, run_width, line_height);
  890.  
  891.         /* Turn stipple off.  */
  892.         XSetFillStyle (FRAME_X_DISPLAY (f), gc, FillSolid);
  893.  
  894.         background_filled = 1;
  895.       }
  896.     else if (!font
  897.          || FONT_HEIGHT (font) < line_height
  898.          || FONT_WIDTH (font) < glyph_width
  899.          || cmpcharp)
  900.       {
  901.         /* Fill a area for the current run in background pixle of GC.  */
  902.         XGCValues xgcv;
  903.         unsigned long mask = GCForeground | GCBackground | GCFillStyle;
  904.  
  905.         /* The current code at first set foreground to background,
  906.           fill the area, then recover the original foreground.
  907.           Aren't there any smarter ways?  */
  908.  
  909.         XGetGCValues (FRAME_X_DISPLAY (f), gc, mask, &xgcv);
  910.         XSetForeground (FRAME_X_DISPLAY (f), gc, xgcv.background);
  911.         XSetFillStyle (FRAME_X_DISPLAY (f), gc, FillSolid);
  912.         XFillRectangle (FRAME_X_DISPLAY (f), window, gc,
  913.                 left, top, run_width, line_height);
  914.         XSetForeground (FRAME_X_DISPLAY (f), gc, xgcv.foreground);
  915.  
  916.         background_filled = 1;
  917.         if (cmpcharp)
  918.           /* To assure not to fill background while drawing
  919.          remaining components.  */
  920.           just_foreground = 1;
  921.       }
  922.     else
  923.       background_filled = 0;
  924.  
  925.     if (font)
  926.       {
  927.         if (require_clipping)
  928.           {
  929.         Region region;    /* Region used for setting clip mask to GC.  */
  930.         XPoint x[4];    /* Data used for creating REGION.  */
  931.  
  932.         x[0].x = x[3].x = left, x[1].x = x[2].x = left + glyph_width;
  933.         x[0].y = x[1].y = top,  x[2].y = x[3].y = top + line_height;
  934.         region = XPolygonRegion (x, 4, EvenOddRule);
  935.         XSetRegion (FRAME_X_DISPLAY (f), gc, region);
  936.         XDestroyRegion (region);
  937.           }
  938.  
  939.         if (!cmpcharp)
  940.           {
  941.         if (require_clipping || FONT_WIDTH (font) != glyph_width)
  942.           for (i = 0; i < len; i++)
  943.             {
  944.               if (require_clipping && i > 0) 
  945.             XSetClipOrigin (FRAME_X_DISPLAY (f), gc,
  946.                     glyph_width * i, 0);
  947.               if (background_filled)
  948.             XDrawString16 (FRAME_X_DISPLAY (f), window, gc,
  949.                        left + glyph_width * i,
  950.                        top + baseline, x_2byte_buffer + i, 1);
  951.               else
  952.             XDrawImageString16 (FRAME_X_DISPLAY (f), window, gc,
  953.                         left + glyph_width * i,
  954.                         top + baseline, x_2byte_buffer + i, 1);
  955.             }
  956.         else
  957.           {
  958.             /* See if this whole buffer can be output as 8-bit chars.
  959.                If so, copy x_2byte_buffer to x_1byte_buffer
  960.                and do it as 8-bit chars.  */
  961.             for (i = 0; i < len; i++)
  962.               {
  963.             if (x_2byte_buffer[i].byte1 != 0)
  964.               break;
  965.             x_1byte_buffer[i] = x_2byte_buffer[i].byte2;
  966.               }
  967.  
  968.             if (i == len)
  969.               {
  970.             if (background_filled)
  971.               XDrawString (FRAME_X_DISPLAY (f), window, gc,
  972.                        left, top + baseline, x_1byte_buffer, len);
  973.             else
  974.               XDrawImageString (FRAME_X_DISPLAY (f), window, gc,
  975.                         left, top + baseline, x_1byte_buffer, len);
  976.               }
  977.             else
  978.               {
  979.             /* We can't output them as 8-bit chars,
  980.                so do it as 16-bit chars.  */
  981.  
  982.             if (background_filled)
  983.               XDrawString16 (FRAME_X_DISPLAY (f), window, gc,
  984.                      left, top + baseline, x_2byte_buffer, len);
  985.             else
  986.               XDrawImageString16 (FRAME_X_DISPLAY (f), window, gc,
  987.                           left, top + baseline, x_2byte_buffer, len);
  988.               }
  989.           }
  990.           }
  991.         else
  992.           {
  993.         /* Handle composite characters.  */
  994.         XCharStruct *pcm; /* Pointer to per char metric info.  */
  995.  
  996.         if ((cmpcharp->cmp_rule || relative_compose)
  997.             && gidx == 0)
  998.           {
  999.             /* This is the first character.  Initialize variables.
  1000.                HIGHEST is the highest position of glyphs ever
  1001.                written, LOWEST the lowest position.  */
  1002.             int x_offset = 0;
  1003.  
  1004.             if (default_ascent
  1005.             && CHAR_TABLE_P (Vuse_default_ascent)
  1006.             && !NILP (Faref (Vuse_default_ascent, first_ch)))
  1007.               {
  1008.             highest = default_ascent;
  1009.             lowest = 0;
  1010.               }
  1011.             else
  1012.               {
  1013.             pcm = PER_CHAR_METRIC (font, x_2byte_buffer);
  1014.             highest = pcm->ascent + 1;
  1015.             lowest = - pcm->descent;
  1016.               }
  1017.  
  1018.             if (cmpcharp->cmp_rule)
  1019.               x_offset = (cmpcharp->col_offset[0]
  1020.                   * FONT_WIDTH (f->output_data.x->font));
  1021.             /* Draw the first character at the normal position.  */
  1022.             XDrawString16 (FRAME_X_DISPLAY (f), window, gc,
  1023.                    left + x_offset, top + baseline, x_2byte_buffer, 1);
  1024.             i = 1;
  1025.             gidx++;
  1026.           }
  1027.         else
  1028.           i = 0;
  1029.  
  1030.         for (; i < len; i++, gidx++)
  1031.           {
  1032.             int x_offset = 0, y_offset = 0;
  1033.  
  1034.             if (relative_compose)
  1035.               {
  1036.             pcm = PER_CHAR_METRIC (font, x_2byte_buffer + i);
  1037.             if (NILP (Vignore_relative_composition)
  1038.                 || NILP (Faref (Vignore_relative_composition,
  1039.                         make_number (cmpcharp->glyph[gidx]))))
  1040.               {
  1041.                 if (- pcm->descent >= relative_compose)
  1042.                   {
  1043.                 /* Draw above the current glyphs.  */
  1044.                 y_offset = highest + pcm->descent;
  1045.                 highest += pcm->ascent + pcm->descent;
  1046.                   }
  1047.                 else if (pcm->ascent <= 0)
  1048.                   {
  1049.                 /* Draw beneath the current glyphs.  */
  1050.                 y_offset = lowest - pcm->ascent;
  1051.                 lowest -= pcm->ascent + pcm->descent;
  1052.                   }
  1053.               }
  1054.             else
  1055.               {
  1056.                 /* Draw the glyph at normal position.  If
  1057.                                it sticks out of HIGHEST or LOWEST,
  1058.                                update them appropriately.  */
  1059.                 if (pcm->ascent > highest)
  1060.                   highest = pcm->ascent;
  1061.                 else if (- pcm->descent < lowest)
  1062.                   lowest = - pcm->descent;
  1063.               }
  1064.               }
  1065.             else if (cmpcharp->cmp_rule)
  1066.               {
  1067.             int gref = (cmpcharp->cmp_rule[gidx] - 0xA0) / 9;
  1068.             int nref = (cmpcharp->cmp_rule[gidx] - 0xA0) % 9;
  1069.             int bottom, top;
  1070.  
  1071.             /* Re-encode GREF and NREF so that they specify
  1072.                only Y-axis information:
  1073.                0:top, 1:base, 2:bottom, 3:center  */
  1074.             gref = gref / 3 + (gref == 4) * 2;
  1075.             nref = nref / 3 + (nref == 4) * 2;
  1076.  
  1077.             pcm = PER_CHAR_METRIC (font, x_2byte_buffer + i);
  1078.             bottom = ((gref == 0 ? highest : gref == 1 ? 0
  1079.                    : gref == 2 ? lowest
  1080.                    : (highest + lowest) / 2)
  1081.                   - (nref == 0 ? pcm->ascent + pcm->descent
  1082.                      : nref == 1 ? pcm->descent : nref == 2 ? 0
  1083.                      : (pcm->ascent + pcm->descent) / 2));
  1084.             top = bottom + (pcm->ascent + pcm->descent);
  1085.             if (top > highest)
  1086.               highest = top;
  1087.             if (bottom < lowest)
  1088.               lowest = bottom;
  1089.             y_offset = bottom + pcm->descent;
  1090.             x_offset = (cmpcharp->col_offset[gidx]
  1091.                     * FONT_WIDTH (f->output_data.x->font));
  1092.               }
  1093.             XDrawString16 (FRAME_X_DISPLAY (f), window, gc,
  1094.                    left + x_offset, top + baseline - y_offset,
  1095.                    x_2byte_buffer + i, 1);
  1096.           }
  1097.           }
  1098.         if (require_clipping)
  1099.           XSetClipMask (FRAME_X_DISPLAY (f), gc, None);
  1100.  
  1101. #if 0 /* Doesn't work, because it uses FRAME_CURRENT_GLYPHS,
  1102.      which often is not up to date yet.  */
  1103.         if (!just_foreground)
  1104.           {
  1105.         if (left == orig_left)
  1106.           redraw_previous_char (f, PIXEL_TO_CHAR_COL (f, left),
  1107.                     PIXEL_TO_CHAR_ROW (f, top), hl == 1);
  1108.         if (n == 0)
  1109.           redraw_following_char (f, PIXEL_TO_CHAR_COL (f, left + len * FONT_WIDTH (font)),
  1110.                      PIXEL_TO_CHAR_ROW (f, top), hl == 1);
  1111.           }
  1112. #endif
  1113.       }
  1114.     if (!font)
  1115.       {
  1116.         /* Show rectangles to indicate that we found no font.  */
  1117.         int limit = cmpcharp ? 1 : len;
  1118.  
  1119.         for (i = 0; i < limit; i++)
  1120.           XDrawRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
  1121.                   left + glyph_width * i, top,
  1122.                   glyph_width - 1, line_height - 1);
  1123.       }
  1124.     else if (require_clipping && !NILP (Vhighlight_wrong_size_font))
  1125.       {
  1126.         /* Show ??? to indicate that we found a font of
  1127.                inappropriate size.  */
  1128.         int limit = cmpcharp ? 1 : len;
  1129.  
  1130.         for (i = 0; i < limit; i++)
  1131.           {
  1132.         XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
  1133.                left + glyph_width * i, top + line_height - 1,
  1134.                left + glyph_width * i + 1, top + line_height - 1);
  1135.         XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
  1136.                left + glyph_width * i, top + line_height - 3,
  1137.                left + glyph_width * i, top + line_height - 1);
  1138.           }
  1139.       }
  1140.  
  1141.     /* We should probably check for XA_UNDERLINE_POSITION and
  1142.        XA_UNDERLINE_THICKNESS properties on the font, but let's
  1143.        just get the thing working, and come back to that.  */
  1144.     {
  1145.       /* Setting underline position based on the metric of the
  1146.          current font results in shaky underline if it strides
  1147.          over different fonts.  So, we set the position based only
  1148.          on the default font of this frame.  */
  1149.       int underline_position = f->output_data.x->font_baseline + 1;
  1150.  
  1151.       if (underline_position >= line_height)
  1152.         underline_position = line_height - 1;
  1153.  
  1154.       if (face->underline)
  1155.         XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  1156.                 FACE_GC (face),
  1157.                 left, top + underline_position, run_width, 1);
  1158.     }
  1159.  
  1160.     if (!cmpcharp)
  1161.       left += run_width;
  1162.       }
  1163.     }
  1164.  
  1165.   return (left - orig_left);
  1166. }
  1167. #endif /* 1 */
  1168.  
  1169. #if 0
  1170. /* This is the old single-face code.  */
  1171.  
  1172. static void
  1173. dumpglyphs (f, left, top, gp, n, hl, font)
  1174.      struct frame *f;
  1175.      int left, top;
  1176.      register GLYPH *gp; /* Points to first GLYPH. */
  1177.      register int n;  /* Number of glyphs to display. */
  1178.      int hl;
  1179.      XFontStruct *font;
  1180. {
  1181.   register int len;
  1182.   Window window = FRAME_X_WINDOW (f);
  1183.   GC drawing_gc =   (hl == 2 ? f->output_data.x->cursor_gc
  1184.                      : (hl ? f->output_data.x->reverse_gc
  1185.                    : f->output_data.x->normal_gc));
  1186.  
  1187.   if (sizeof (GLYPH) == sizeof (XChar2b))
  1188.     XDrawImageString16 (FRAME_X_DISPLAY (f), window, drawing_gc,
  1189.             left, top + FONT_BASE (font), (XChar2b *) gp, n);
  1190.   else if (sizeof (GLYPH) == sizeof (unsigned char))
  1191.     XDrawImageString (FRAME_X_DISPLAY (f), window, drawing_gc,
  1192.               left, top + FONT_BASE (font), (char *) gp, n);
  1193.   else
  1194.     /* What size of glyph ARE you using?  And does X have a function to
  1195.        draw them?  */
  1196.     abort ();
  1197. }
  1198. #endif
  1199.  
  1200. /* Output some text at the nominal frame cursor position.
  1201.    Advance the cursor over the text.
  1202.    Output LEN glyphs at START.
  1203.  
  1204.    `highlight', set up by XTreassert_line_highlight or XTchange_line_highlight,
  1205.    controls the pixel values used for foreground and background.  */
  1206.  
  1207. static void
  1208. XTwrite_glyphs (start, len)
  1209.      register GLYPH *start;
  1210.      int len;
  1211. {
  1212.   register int temp_length;
  1213.   int mask;
  1214.   struct frame *f;
  1215.  
  1216.   BLOCK_INPUT;
  1217.  
  1218.   do_line_dance ();
  1219.   f = updating_frame;
  1220.   if (f == 0)
  1221.     {
  1222.       f = selected_frame;
  1223.       /* If not within an update,
  1224.      output at the frame's visible cursor.  */
  1225.       curs_x = FRAME_CURSOR_X (f);
  1226.       curs_y = FRAME_CURSOR_Y (f);
  1227.     }
  1228.  
  1229.   dumpglyphs (f,
  1230.           CHAR_TO_PIXEL_COL (f, curs_x),
  1231.           CHAR_TO_PIXEL_ROW (f, curs_y),
  1232.           start, len, highlight, 0, NULL);
  1233.  
  1234.   /* If we drew on top of the cursor, note that it is turned off.  */
  1235.   if (curs_y == f->phys_cursor_y
  1236.       && curs_x <= f->phys_cursor_x
  1237.       && curs_x + len > f->phys_cursor_x)
  1238.     f->phys_cursor_on = 0;
  1239.  
  1240.   curs_x += len;
  1241.   if (curs_x >= FRAME_CURSOR_X_LIMIT (f))
  1242.     curs_x = FRAME_CURSOR_X_LIMIT (f) - 1;
  1243.  
  1244.   if (updating_frame == 0)
  1245.     x_display_cursor (f, 1, curs_x, FRAME_CURSOR_Y (f));
  1246.       
  1247.  
  1248.   UNBLOCK_INPUT;
  1249. }
  1250.  
  1251. /* Clear to the end of the line.
  1252.    Erase the current text line from the nominal cursor position (inclusive)
  1253.    to column FIRST_UNUSED (exclusive).  The idea is that everything
  1254.    from FIRST_UNUSED onward is already erased.  */
  1255.  
  1256. static void
  1257. XTclear_end_of_line (first_unused)
  1258.      register int first_unused;
  1259. {
  1260.   struct frame *f = updating_frame;
  1261.   int mask;
  1262.  
  1263.   if (f == 0)
  1264.     abort ();
  1265.  
  1266.   if (curs_y < 0 || curs_y >= f->height)
  1267.     return;
  1268.   if (first_unused <= 0)
  1269.     return;
  1270.  
  1271.   if (first_unused >= FRAME_WINDOW_WIDTH (f))
  1272.     first_unused = FRAME_WINDOW_WIDTH (f);
  1273.  
  1274.   first_unused += FRAME_LEFT_SCROLL_BAR_WIDTH (f);
  1275.  
  1276.   BLOCK_INPUT;
  1277.  
  1278.   do_line_dance ();
  1279.  
  1280.   /* Notice if the cursor will be cleared by this operation.  */
  1281.   if (curs_y == f->phys_cursor_y
  1282.       && curs_x <= f->phys_cursor_x
  1283.       && f->phys_cursor_x < first_unused)
  1284.     f->phys_cursor_on = 0;
  1285.  
  1286.   XClearArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  1287.           CHAR_TO_PIXEL_COL (f, curs_x),
  1288.           CHAR_TO_PIXEL_ROW (f, curs_y),
  1289.           FONT_WIDTH (f->output_data.x->font) * (first_unused - curs_x),
  1290.           f->output_data.x->line_height, False);
  1291. #if 0
  1292.   redraw_previous_char (f, curs_x, curs_y, highlight);
  1293. #endif
  1294.  
  1295.   UNBLOCK_INPUT;
  1296. }
  1297.  
  1298. static void
  1299. XTclear_frame ()
  1300. {
  1301.   int mask;
  1302.   struct frame *f = updating_frame;
  1303.  
  1304.   if (f == 0)
  1305.     f = selected_frame;
  1306.  
  1307.   f->phys_cursor_on = 0;    /* Cursor not visible.  */
  1308.   curs_x = 0;            /* Nominal cursor position is top left.  */
  1309.   curs_y = 0;
  1310.  
  1311.   BLOCK_INPUT;
  1312.  
  1313.   XClearWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
  1314.  
  1315.   /* We have to clear the scroll bars, too.  If we have changed
  1316.      colors or something like that, then they should be notified.  */
  1317.   x_scroll_bar_clear (f);
  1318.  
  1319.   XFlush (FRAME_X_DISPLAY (f));
  1320.   UNBLOCK_INPUT;
  1321. }
  1322.  
  1323. #if 0
  1324. /* This currently does not work because FRAME_CURRENT_GLYPHS doesn't
  1325.    always contain the right glyphs to use.
  1326.  
  1327.    It also needs to be changed to look at the details of the font and
  1328.    see whether there is really overlap, and do nothing when there is
  1329.    not.  This can use font_char_overlap_left and font_char_overlap_right,
  1330.    but just how to use them is not clear.  */
  1331.  
  1332. /* Erase the character (if any) at the position just before X, Y in frame F,
  1333.    then redraw it and the character before it.
  1334.    This is necessary when we erase starting at X,
  1335.    in case the character after X overlaps into the one before X.
  1336.    Call this function with input blocked.  */
  1337.  
  1338. static void
  1339. redraw_previous_char (f, x, y, highlight_flag)
  1340.      FRAME_PTR f;
  1341.      int x, y;
  1342.      int highlight_flag;
  1343. {
  1344.   /* Erase the character before the new ones, in case
  1345.      what was here before overlaps it.
  1346.      Reoutput that character, and the previous character
  1347.      (in case the previous character overlaps it).  */
  1348.   if (x > 0)
  1349.     {
  1350.       int start_x = x - 2;
  1351.       if (start_x < 0)
  1352.     start_x = 0;
  1353.       XClearArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  1354.           CHAR_TO_PIXEL_COL (f, x - 1),
  1355.           CHAR_TO_PIXEL_ROW (f, y),
  1356.           FONT_WIDTH (f->output_data.x->font),
  1357.           f->output_data.x->line_height, False);
  1358.  
  1359.       dumpglyphs (f, CHAR_TO_PIXEL_COL (f, start_x),
  1360.           CHAR_TO_PIXEL_ROW (f, y),
  1361.           &FRAME_CURRENT_GLYPHS (f)->glyphs[y][start_x],
  1362.           x - start_x, highlight_flag, 1, NULL);
  1363.     }
  1364. }
  1365.  
  1366. /* Erase the character (if any) at the position X, Y in frame F,
  1367.    then redraw it and the character after it.
  1368.    This is necessary when we erase endng at X,
  1369.    in case the character after X overlaps into the one before X.
  1370.    Call this function with input blocked.  */
  1371.  
  1372. static void
  1373. redraw_following_char (f, x, y, highlight_flag)
  1374.      FRAME_PTR f;
  1375.      int x, y;
  1376.      int highlight_flag;
  1377. {
  1378.   int limit = FRAME_CURRENT_GLYPHS (f)->used[y];
  1379.   /* Erase the character after the new ones, in case
  1380.      what was here before overlaps it.
  1381.      Reoutput that character, and the following character
  1382.      (in case the following character overlaps it).  */
  1383.   if (x < limit
  1384.       && FRAME_CURRENT_GLYPHS (f)->glyphs[y][x] != SPACEGLYPH)
  1385.     {
  1386.       int end_x = x + 2;
  1387.       if (end_x > limit)
  1388.     end_x = limit;
  1389.       XClearArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  1390.           CHAR_TO_PIXEL_COL (f, x),
  1391.           CHAR_TO_PIXEL_ROW (f, y),
  1392.           FONT_WIDTH (f->output_data.x->font),
  1393.           f->output_data.x->line_height, False);
  1394.  
  1395.       dumpglyphs (f, CHAR_TO_PIXEL_COL (f, x),
  1396.           CHAR_TO_PIXEL_ROW (f, y),
  1397.           &FRAME_CURRENT_GLYPHS (f)->glyphs[y][x],
  1398.           end_x - x, highlight_flag, 1, NULL);
  1399.     }
  1400. }
  1401. #endif /* 0 */
  1402.  
  1403. #if 0 /* Not in use yet */
  1404.  
  1405. /* Return 1 if character C in font F extends past its left edge.  */
  1406.  
  1407. static int
  1408. font_char_overlap_left (font, c)
  1409.      XFontStruct *font;
  1410.      int c;
  1411. {
  1412.   XCharStruct *s;
  1413.  
  1414.   /* Find the bounding-box info for C.  */
  1415.   if (font->per_char == 0)
  1416.     s = &font->max_bounds;
  1417.   else
  1418.     {
  1419.       int rowlen = font->max_char_or_byte2 - font->min_char_or_byte2 + 1;
  1420.       int row, within;
  1421.  
  1422.       /* Decode char into row number (byte 1) and code within row (byte 2).  */
  1423.       row = c >> 8;
  1424.       within = c & 0177;
  1425.       if (!(within >= font->min_char_or_byte2
  1426.         && within <= font->max_char_or_byte2
  1427.         && row >= font->min_byte1
  1428.         && row <= font->max_byte1))
  1429.     {
  1430.       /* If char is out of range, try the font's default char instead.  */
  1431.       c = font->default_char;
  1432.       row = c >> (BITS_PER_INT - 8);
  1433.       within = c & 0177;
  1434.     }
  1435.       if (!(within >= font->min_char_or_byte2
  1436.         && within <= font->max_char_or_byte2
  1437.         && row >= font->min_byte1
  1438.         && row <= font->max_byte1))
  1439.     /* Still out of range means this char does not overlap.  */
  1440.     return 0;
  1441.       else
  1442.     /* We found the info for this char.  */
  1443.     s = (font->per_char + (within - font->min_char_or_byte2)
  1444.          + row * rowlen);
  1445.     }
  1446.  
  1447.   return (s && s->lbearing < 0);
  1448. }
  1449.  
  1450. /* Return 1 if character C in font F extends past its right edge.  */
  1451.  
  1452. static int
  1453. font_char_overlap_right (font, c)
  1454.      XFontStruct *font;
  1455.      int c;
  1456. {
  1457.   XCharStruct *s;
  1458.  
  1459.   /* Find the bounding-box info for C.  */
  1460.   if (font->per_char == 0)
  1461.     s = &font->max_bounds;
  1462.   else
  1463.     {
  1464.       int rowlen = font->max_char_or_byte2 - font->min_char_or_byte2 + 1;
  1465.       int row, within;
  1466.  
  1467.       /* Decode char into row number (byte 1) and code within row (byte 2).  */
  1468.       row = c >> 8;
  1469.       within = c & 0177;
  1470.       if (!(within >= font->min_char_or_byte2
  1471.         && within <= font->max_char_or_byte2
  1472.         && row >= font->min_byte1
  1473.         && row <= font->max_byte1))
  1474.     {
  1475.       /* If char is out of range, try the font's default char instead.  */
  1476.       c = font->default_char;
  1477.       row = c >> (BITS_PER_INT - 8);
  1478.       within = c & 0177;
  1479.     }
  1480.       if (!(within >= font->min_char_or_byte2
  1481.         && within <= font->max_char_or_byte2
  1482.         && row >= font->min_byte1
  1483.         && row <= font->max_byte1))
  1484.     /* Still out of range means this char does not overlap.  */
  1485.     return 0;
  1486.       else
  1487.     /* We found the info for this char.  */
  1488.     s = (font->per_char + (within - font->min_char_or_byte2)
  1489.          + row * rowlen);
  1490.     }
  1491.  
  1492.   return (s && s->rbearing >= s->width);
  1493. }
  1494. #endif /* 0 */
  1495.  
  1496. /* Invert the middle quarter of the frame for .15 sec.  */
  1497.  
  1498. /* We use the select system call to do the waiting, so we have to make sure
  1499.    it's available.  If it isn't, we just won't do visual bells.  */
  1500. #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
  1501.  
  1502. /* Subtract the `struct timeval' values X and Y,
  1503.    storing the result in RESULT.
  1504.    Return 1 if the difference is negative, otherwise 0.  */
  1505.  
  1506. static int
  1507. timeval_subtract (result, x, y)
  1508.      struct timeval *result, x, y;
  1509. {
  1510.   /* Perform the carry for the later subtraction by updating y.
  1511.      This is safer because on some systems
  1512.      the tv_sec member is unsigned.  */
  1513.   if (x.tv_usec < y.tv_usec)
  1514.     {
  1515.       int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
  1516.       y.tv_usec -= 1000000 * nsec;
  1517.       y.tv_sec += nsec;
  1518.     }
  1519.   if (x.tv_usec - y.tv_usec > 1000000)
  1520.     {
  1521.       int nsec = (y.tv_usec - x.tv_usec) / 1000000;
  1522.       y.tv_usec += 1000000 * nsec;
  1523.       y.tv_sec -= nsec;
  1524.     }
  1525.  
  1526.   /* Compute the time remaining to wait.  tv_usec is certainly positive.  */
  1527.   result->tv_sec = x.tv_sec - y.tv_sec;
  1528.   result->tv_usec = x.tv_usec - y.tv_usec;
  1529.  
  1530.   /* Return indication of whether the result should be considered negative.  */
  1531.   return x.tv_sec < y.tv_sec;
  1532. }
  1533.  
  1534. void
  1535. XTflash (f)
  1536.      struct frame *f;
  1537. {
  1538.   BLOCK_INPUT;
  1539.  
  1540.   {
  1541.     GC gc;
  1542.  
  1543.     /* Create a GC that will use the GXxor function to flip foreground pixels
  1544.        into background pixels.  */
  1545.     {
  1546.       XGCValues values;
  1547.  
  1548.       values.function = GXxor;
  1549.       values.foreground = (f->output_data.x->foreground_pixel
  1550.                ^ f->output_data.x->background_pixel);
  1551.  
  1552.       gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  1553.               GCFunction | GCForeground, &values);
  1554.     }
  1555.  
  1556.     {
  1557.       /* Get the height not including a menu bar widget.  */
  1558.       int height = CHAR_TO_PIXEL_HEIGHT (f, FRAME_HEIGHT (f));
  1559.       /* Height of each line to flash.  */
  1560.       int flash_height = FRAME_LINE_HEIGHT (f);
  1561.       /* These will be the left and right margins of the rectangles.  */
  1562.       int flash_left = FRAME_INTERNAL_BORDER_WIDTH (f);
  1563.       int flash_right = PIXEL_WIDTH (f) - FRAME_INTERNAL_BORDER_WIDTH (f);
  1564.  
  1565.       int width;
  1566.  
  1567.       /* Don't flash the area between a scroll bar and the frame
  1568.      edge it is next to.  */
  1569.       switch (FRAME_VERTICAL_SCROLL_BAR_TYPE (f))
  1570.     {
  1571.     case vertical_scroll_bar_left:
  1572.       flash_left += VERTICAL_SCROLL_BAR_WIDTH_TRIM;
  1573.       break;
  1574.  
  1575.     case vertical_scroll_bar_right:
  1576.       flash_right -= VERTICAL_SCROLL_BAR_WIDTH_TRIM;
  1577.       break;
  1578.     }
  1579.  
  1580.       width = flash_right - flash_left;
  1581.  
  1582.       /* If window is tall, flash top and bottom line.  */
  1583.       if (height > 3 * FRAME_LINE_HEIGHT (f))
  1584.     {
  1585.       XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
  1586.               flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
  1587.               width, flash_height);
  1588.       XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
  1589.               flash_left,
  1590.               (height - flash_height
  1591.                - FRAME_INTERNAL_BORDER_WIDTH (f)),
  1592.               width, flash_height);
  1593.     }
  1594.       else
  1595.     /* If it is short, flash it all.  */ 
  1596.     XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
  1597.             flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
  1598.             width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
  1599.  
  1600.       XFlush (FRAME_X_DISPLAY (f));
  1601.  
  1602.       {
  1603.     struct timeval wakeup, now;
  1604.  
  1605.     EMACS_GET_TIME (wakeup);
  1606.  
  1607.     /* Compute time to wait until, propagating carry from usecs.  */
  1608.     wakeup.tv_usec += 150000;
  1609.     wakeup.tv_sec += (wakeup.tv_usec / 1000000);
  1610.     wakeup.tv_usec %= 1000000;
  1611.  
  1612.     /* Keep waiting until past the time wakeup.  */
  1613.     while (1)
  1614.       {
  1615.         struct timeval timeout;
  1616.  
  1617.         EMACS_GET_TIME (timeout);
  1618.  
  1619.         /* In effect, timeout = wakeup - timeout.
  1620.            Break if result would be negative.  */
  1621.         if (timeval_subtract (&timeout, wakeup, timeout))
  1622.           break;
  1623.  
  1624.         /* Try to wait that long--but we might wake up sooner.  */
  1625.         select (0, NULL, NULL, NULL, &timeout);
  1626.       }
  1627.       }
  1628.  
  1629.       /* If window is tall, flash top and bottom line.  */
  1630.       if (height > 3 * FRAME_LINE_HEIGHT (f))
  1631.     {
  1632.       XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
  1633.               flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
  1634.               width, flash_height);
  1635.       XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
  1636.               flash_left,
  1637.               (height - flash_height
  1638.                - FRAME_INTERNAL_BORDER_WIDTH (f)),
  1639.               width, flash_height);
  1640.     }
  1641.       else
  1642.     /* If it is short, flash it all.  */ 
  1643.     XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
  1644.             flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
  1645.             width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
  1646.  
  1647.       XFreeGC (FRAME_X_DISPLAY (f), gc);
  1648.       XFlush (FRAME_X_DISPLAY (f));
  1649.     }
  1650.   }
  1651.  
  1652.   UNBLOCK_INPUT;
  1653. }
  1654.  
  1655. #endif
  1656.  
  1657.  
  1658. /* Make audible bell.  */
  1659.  
  1660. #define XRINGBELL XBell (FRAME_X_DISPLAY (selected_frame), 0)
  1661.  
  1662. void
  1663. XTring_bell ()
  1664. {
  1665.   if (FRAME_X_DISPLAY (selected_frame) == 0)
  1666.     return;
  1667.  
  1668. #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
  1669.   if (visible_bell)
  1670.     XTflash (selected_frame);
  1671.   else
  1672. #endif
  1673.     {
  1674.       BLOCK_INPUT;
  1675.       XRINGBELL;
  1676.       XFlush (FRAME_X_DISPLAY (selected_frame));
  1677.       UNBLOCK_INPUT;
  1678.     }
  1679. }
  1680.  
  1681. /* Insert and delete character.
  1682.    These are not supposed to be used because we are supposed to turn
  1683.    off the feature of using them.  */
  1684.  
  1685. static void
  1686. XTinsert_glyphs (start, len)
  1687.      register char *start;
  1688.      register int len;
  1689. {
  1690.   abort ();
  1691. }
  1692.  
  1693. static void
  1694. XTdelete_glyphs (n)
  1695.      register int n;
  1696. {
  1697.   abort ();
  1698. }
  1699.  
  1700. /* Specify how many text lines, from the top of the window,
  1701.    should be affected by insert-lines and delete-lines operations.
  1702.    This, and those operations, are used only within an update
  1703.    that is bounded by calls to XTupdate_begin and XTupdate_end.  */
  1704.  
  1705. static void
  1706. XTset_terminal_window (n)
  1707.      register int n;
  1708. {
  1709.   if (updating_frame == 0)
  1710.     abort ();
  1711.  
  1712.   if ((n <= 0) || (n > updating_frame->height))
  1713.     flexlines = updating_frame->height;
  1714.   else
  1715.     flexlines = n;
  1716. }
  1717.  
  1718. /* These variables need not be per frame
  1719.    because redisplay is done on a frame-by-frame basis
  1720.    and the line dance for one frame is finished before
  1721.    anything is done for anoter frame.  */
  1722.  
  1723. /* Array of line numbers from cached insert/delete operations.
  1724.    line_dance[i] is the old position of the line that we want
  1725.    to move to line i, or -1 if we want a blank line there.  */
  1726. static int *line_dance;
  1727.  
  1728. /* Allocated length of that array.  */
  1729. static int line_dance_len;
  1730.  
  1731. /* Flag indicating whether we've done any work.  */
  1732. static int line_dance_in_progress;
  1733.  
  1734. /* Perform an insert-lines or delete-lines operation,
  1735.    inserting N lines or deleting -N lines at vertical position VPOS.  */
  1736. void
  1737. XTins_del_lines (vpos, n)
  1738.      int vpos, n;
  1739. {
  1740.   register int fence, i;
  1741.  
  1742.   if (vpos >= flexlines)
  1743.     return;
  1744.  
  1745.   if (!line_dance_in_progress)
  1746.     {
  1747.       int ht = updating_frame->height;
  1748.       if (ht > line_dance_len)
  1749.     {
  1750.       line_dance = (int *)xrealloc (line_dance, ht * sizeof (int));
  1751.       line_dance_len = ht;
  1752.     }
  1753.       for (i = 0; i < ht; ++i) line_dance[i] = i;
  1754.       line_dance_in_progress = 1;
  1755.     }
  1756.   if (n >= 0)
  1757.     {
  1758.       if (n > flexlines - vpos)
  1759.     n = flexlines - vpos;
  1760.       fence = vpos + n;
  1761.       for (i = flexlines; --i >= fence;)
  1762.     line_dance[i] = line_dance[i-n];
  1763.       for (i = fence; --i >= vpos;)
  1764.     line_dance[i] = -1;
  1765.     }
  1766.   else
  1767.     {
  1768.       n = -n;
  1769.       if (n > flexlines - vpos)
  1770.     n = flexlines - vpos;
  1771.       fence = flexlines - n;
  1772.       for (i = vpos; i < fence; ++i)
  1773.     line_dance[i] = line_dance[i + n];
  1774.       for (i = fence; i < flexlines; ++i)
  1775.     line_dance[i] = -1;
  1776.     }
  1777. }
  1778.  
  1779. /* Here's where we actually move the pixels around.
  1780.    Must be called with input blocked.  */
  1781. static void
  1782. do_line_dance ()
  1783. {
  1784.   register int i, j, distance;
  1785.   register struct frame *f;
  1786.   int ht;
  1787.   int intborder;
  1788.  
  1789.   /* Must check this flag first.  If it's not set, then not only is the
  1790.      array uninitialized, but we might not even have a frame.  */
  1791.   if (!line_dance_in_progress)
  1792.     return;
  1793.  
  1794.   f = updating_frame;
  1795.   if (f == 0)
  1796.     abort ();
  1797.  
  1798.   ht = f->height;
  1799.   intborder = CHAR_TO_PIXEL_COL (f, FRAME_LEFT_SCROLL_BAR_WIDTH (f));
  1800.  
  1801.   x_update_cursor (updating_frame, 0);
  1802.  
  1803.   for (i = 0; i < ht; ++i)
  1804.     if (line_dance[i] != -1 && (distance = line_dance[i]-i) > 0)
  1805.       {
  1806.     for (j = i; (j < ht && line_dance[j] != -1
  1807.              && line_dance[j]-j == distance); ++j);
  1808.     /* Copy [i,j) upward from [i+distance,j+distance) */
  1809.     XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  1810.            FRAME_X_WINDOW (f), f->output_data.x->normal_gc,
  1811.            intborder, CHAR_TO_PIXEL_ROW (f, i+distance),
  1812.            FRAME_WINDOW_WIDTH (f) * FONT_WIDTH (f->output_data.x->font),
  1813.            (j-i) * f->output_data.x->line_height,
  1814.            intborder, CHAR_TO_PIXEL_ROW (f, i));
  1815.     i = j-1;
  1816.       }
  1817.  
  1818.   for (i = ht; --i >=0; )
  1819.     if (line_dance[i] != -1 && (distance = line_dance[i]-i) < 0)
  1820.       {
  1821.     for (j = i; (--j >= 0 && line_dance[j] != -1
  1822.              && line_dance[j]-j == distance););
  1823.     /* Copy (j,i] downward from (j+distance, i+distance] */
  1824.     XCopyArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  1825.            FRAME_X_WINDOW (f), f->output_data.x->normal_gc,
  1826.            intborder, CHAR_TO_PIXEL_ROW (f, j+1+distance),
  1827.            FRAME_WINDOW_WIDTH (f) * FONT_WIDTH (f->output_data.x->font),
  1828.            (i-j) * f->output_data.x->line_height,
  1829.            intborder, CHAR_TO_PIXEL_ROW (f, j+1));
  1830.     i = j+1;
  1831.       }
  1832.  
  1833.   for (i = 0; i < ht; ++i)
  1834.     if (line_dance[i] == -1)
  1835.       {
  1836.     for (j = i; j < ht && line_dance[j] == -1; ++j);
  1837.     /* Clear [i,j) */
  1838.     XClearArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  1839.             intborder, CHAR_TO_PIXEL_ROW (f, i),
  1840.             FRAME_WINDOW_WIDTH (f) * FONT_WIDTH (f->output_data.x->font),
  1841.             (j-i) * f->output_data.x->line_height, False);
  1842.     i = j-1;
  1843.       }
  1844.   line_dance_in_progress = 0;
  1845. }
  1846.  
  1847. /* Support routines for exposure events.  */
  1848. static void clear_cursor ();
  1849.  
  1850. /* Output into a rectangle of an X-window (for frame F)
  1851.    the characters in f->phys_lines that overlap that rectangle.
  1852.    TOP and LEFT are the position of the upper left corner of the rectangle.
  1853.    ROWS and COLS are the size of the rectangle.
  1854.    Call this function with input blocked.  */
  1855.  
  1856. static void
  1857. dumprectangle (f, left, top, cols, rows)
  1858.      struct frame *f;
  1859.      register int left, top, cols, rows;
  1860. {
  1861.   register struct frame_glyphs *active_frame = FRAME_CURRENT_GLYPHS (f);
  1862.   int cursor_cleared = 0;
  1863.   int bottom, right;
  1864.   register int y;
  1865.  
  1866.   if (FRAME_GARBAGED_P (f))
  1867.     return;
  1868.  
  1869.   /* Express rectangle as four edges, instead of position-and-size.  */
  1870.   bottom = top + rows;
  1871.   right = left + cols;
  1872.  
  1873.   /* Convert rectangle edges in pixels to edges in chars.
  1874.      Round down for left and top, up for right and bottom.  */
  1875.   top  = PIXEL_TO_CHAR_ROW (f, top);
  1876.   left = PIXEL_TO_CHAR_COL (f, left);
  1877.   bottom += (f->output_data.x->line_height - 1);
  1878.   right += (FONT_WIDTH (f->output_data.x->font) - 1);
  1879.   bottom = PIXEL_TO_CHAR_ROW (f, bottom);
  1880.   right = PIXEL_TO_CHAR_COL (f, right);
  1881.  
  1882.   /* Clip the rectangle to what can be visible.  */
  1883.   if (left < 0)
  1884.     left = 0;
  1885.   if (top < 0)
  1886.     top = 0;
  1887.   if (right > FRAME_WINDOW_WIDTH (f))
  1888.     right = FRAME_WINDOW_WIDTH (f);
  1889.   if (bottom > f->height)
  1890.     bottom = f->height;
  1891.  
  1892.   /* Get size in chars of the rectangle.  */
  1893.   cols = right - left;
  1894.   rows = bottom - top;
  1895.  
  1896.   /* If rectangle has zero area, return.  */
  1897.   if (rows <= 0) return;
  1898.   if (cols <= 0) return;
  1899.  
  1900.   /* Turn off the cursor if it is in the rectangle.
  1901.      We will turn it back on afterward.  */
  1902.   if ((f->phys_cursor_x >= left) && (f->phys_cursor_x < right)
  1903.       && (f->phys_cursor_y >= top) && (f->phys_cursor_y < bottom))
  1904.     {
  1905.       clear_cursor (f);
  1906.       cursor_cleared = 1;
  1907.     }
  1908.  
  1909.   /* Display the text in the rectangle, one text line at a time.  */
  1910.  
  1911.   for (y = top; y < bottom; y++)
  1912.     {
  1913.       GLYPH *line = &active_frame->glyphs[y][left];
  1914.  
  1915.       if (! active_frame->enable[y] || left > active_frame->used[y])
  1916.     continue;
  1917.  
  1918.       while (*line & GLYPH_MASK_PADDING)
  1919.     {
  1920.       /* We must display the whole glyph of a wide-column
  1921.              character.  */
  1922.       left--;
  1923.       line--;
  1924.       cols++;
  1925.     }
  1926.       dumpglyphs (f,
  1927.           CHAR_TO_PIXEL_COL (f, left),
  1928.           CHAR_TO_PIXEL_ROW (f, y),
  1929.           line, min (cols, active_frame->used[y] - left),
  1930.           active_frame->highlight[y], 0, NULL);
  1931.     }
  1932.  
  1933.   /* Turn the cursor on if we turned it off.  */
  1934.  
  1935.   if (cursor_cleared)
  1936.     x_update_cursor (f, 1);
  1937. }
  1938.  
  1939. static void
  1940. frame_highlight (f)
  1941.      struct frame *f;
  1942. {
  1943.   /* We used to only do this if Vx_no_window_manager was non-nil, but
  1944.      the ICCCM (section 4.1.6) says that the window's border pixmap
  1945.      and border pixel are window attributes which are "private to the
  1946.      client", so we can always change it to whatever we want.  */
  1947.   BLOCK_INPUT;
  1948.   XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  1949.             f->output_data.x->border_pixel);
  1950.   UNBLOCK_INPUT;
  1951.   x_update_cursor (f, 1);
  1952. }
  1953.  
  1954. static void
  1955. frame_unhighlight (f)
  1956.      struct frame *f;
  1957. {
  1958.   /* We used to only do this if Vx_no_window_manager was non-nil, but
  1959.      the ICCCM (section 4.1.6) says that the window's border pixmap
  1960.      and border pixel are window attributes which are "private to the
  1961.      client", so we can always change it to whatever we want.  */
  1962.   BLOCK_INPUT;
  1963.   XSetWindowBorderPixmap (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  1964.               f->output_data.x->border_tile);
  1965.   UNBLOCK_INPUT;
  1966.   x_update_cursor (f, 1);
  1967. }
  1968.  
  1969. static void XTframe_rehighlight ();
  1970. static void x_frame_rehighlight ();
  1971.  
  1972. /* The focus has changed.  Update the frames as necessary to reflect
  1973.    the new situation.  Note that we can't change the selected frame
  1974.    here, because the Lisp code we are interrupting might become confused.
  1975.    Each event gets marked with the frame in which it occurred, so the
  1976.    Lisp code can tell when the switch took place by examining the events.  */
  1977.  
  1978. static void
  1979. x_new_focus_frame (dpyinfo, frame)
  1980.      struct x_display_info *dpyinfo;
  1981.      struct frame *frame;
  1982. {
  1983.   struct frame *old_focus = dpyinfo->x_focus_frame;
  1984.   int events_enqueued = 0;
  1985.  
  1986.   if (frame != dpyinfo->x_focus_frame)
  1987.     {
  1988.       /* Set this before calling other routines, so that they see
  1989.      the correct value of x_focus_frame.  */
  1990.       dpyinfo->x_focus_frame = frame;
  1991.  
  1992.       if (old_focus && old_focus->auto_lower)
  1993.     x_lower_frame (old_focus);
  1994.  
  1995. #if 0
  1996.       selected_frame = frame;
  1997.       XSETFRAME (XWINDOW (selected_frame->selected_window)->frame,
  1998.          selected_frame);
  1999.       Fselect_window (selected_frame->selected_window);
  2000.       choose_minibuf_frame ();
  2001. #endif /* ! 0 */
  2002.  
  2003.       if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
  2004.     pending_autoraise_frame = dpyinfo->x_focus_frame;
  2005.       else
  2006.     pending_autoraise_frame = 0;
  2007.     }
  2008.  
  2009.   x_frame_rehighlight (dpyinfo);
  2010. }
  2011.  
  2012. /* Handle an event saying the mouse has moved out of an Emacs frame.  */
  2013.  
  2014. void
  2015. x_mouse_leave (dpyinfo)
  2016.      struct x_display_info *dpyinfo;
  2017. {
  2018.   x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
  2019. }
  2020.  
  2021. /* The focus has changed, or we have redirected a frame's focus to
  2022.    another frame (this happens when a frame uses a surrogate
  2023.    minibuffer frame).  Shift the highlight as appropriate.
  2024.  
  2025.    The FRAME argument doesn't necessarily have anything to do with which
  2026.    frame is being highlighted or unhighlighted; we only use it to find
  2027.    the appropriate X display info.  */
  2028. static void
  2029. XTframe_rehighlight (frame)
  2030.      struct frame *frame;
  2031. {
  2032.   x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
  2033. }
  2034.  
  2035. static void
  2036. x_frame_rehighlight (dpyinfo)
  2037.      struct x_display_info *dpyinfo;
  2038. {
  2039.   struct frame *old_highlight = dpyinfo->x_highlight_frame;
  2040.  
  2041.   if (dpyinfo->x_focus_frame)
  2042.     {
  2043.       dpyinfo->x_highlight_frame
  2044.     = ((GC_FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
  2045.        ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
  2046.        : dpyinfo->x_focus_frame);
  2047.       if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
  2048.     {
  2049.       FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
  2050.       dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
  2051.     }
  2052.     }
  2053.   else
  2054.     dpyinfo->x_highlight_frame = 0;
  2055.  
  2056.   if (dpyinfo->x_highlight_frame != old_highlight)
  2057.     {
  2058.       if (old_highlight)
  2059.     frame_unhighlight (old_highlight);
  2060.       if (dpyinfo->x_highlight_frame)
  2061.     frame_highlight (dpyinfo->x_highlight_frame);
  2062.     }
  2063. }
  2064.  
  2065. /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
  2066.  
  2067. /* Initialize mode_switch_bit and modifier_meaning.  */
  2068. static void
  2069. x_find_modifier_meanings (dpyinfo)
  2070.      struct x_display_info *dpyinfo;
  2071. {
  2072.   int min_code, max_code;
  2073.   KeySym *syms;
  2074.   int syms_per_code;
  2075.   XModifierKeymap *mods;
  2076.  
  2077.   dpyinfo->meta_mod_mask = 0;
  2078.   dpyinfo->shift_lock_mask = 0;
  2079.   dpyinfo->alt_mod_mask = 0;
  2080.   dpyinfo->super_mod_mask = 0;
  2081.   dpyinfo->hyper_mod_mask = 0;
  2082.  
  2083. #ifdef HAVE_X11R4
  2084.   XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
  2085. #else
  2086.   min_code = dpyinfo->display->min_keycode;
  2087.   max_code = dpyinfo->display->max_keycode;
  2088. #endif
  2089.  
  2090.   syms = XGetKeyboardMapping (dpyinfo->display,
  2091.                   min_code, max_code - min_code + 1,
  2092.                   &syms_per_code);
  2093.   mods = XGetModifierMapping (dpyinfo->display);
  2094.  
  2095.   /* Scan the modifier table to see which modifier bits the Meta and
  2096.      Alt keysyms are on.  */
  2097.   {
  2098.     int row, col;    /* The row and column in the modifier table. */
  2099.  
  2100.     for (row = 3; row < 8; row++)
  2101.       for (col = 0; col < mods->max_keypermod; col++)
  2102.     {
  2103.       KeyCode code
  2104.         = mods->modifiermap[(row * mods->max_keypermod) + col];
  2105.  
  2106.       /* Zeroes are used for filler.  Skip them.  */
  2107.       if (code == 0)
  2108.         continue;
  2109.  
  2110.       /* Are any of this keycode's keysyms a meta key?  */
  2111.       {
  2112.         int code_col;
  2113.  
  2114.         for (code_col = 0; code_col < syms_per_code; code_col++)
  2115.           {
  2116.         int sym = syms[((code - min_code) * syms_per_code) + code_col];
  2117.  
  2118.         switch (sym)
  2119.           {
  2120.           case XK_Meta_L:
  2121.           case XK_Meta_R:
  2122.             dpyinfo->meta_mod_mask |= (1 << row);
  2123.             break;
  2124.  
  2125.           case XK_Alt_L:
  2126.           case XK_Alt_R:
  2127.             dpyinfo->alt_mod_mask |= (1 << row);
  2128.             break;
  2129.  
  2130.           case XK_Hyper_L:
  2131.           case XK_Hyper_R:
  2132.             dpyinfo->hyper_mod_mask |= (1 << row);
  2133.             break;
  2134.  
  2135.           case XK_Super_L:
  2136.           case XK_Super_R:
  2137.             dpyinfo->super_mod_mask |= (1 << row);
  2138.             break;
  2139.  
  2140.           case XK_Shift_Lock:
  2141.             /* Ignore this if it's not on the lock modifier.  */
  2142.             if ((1 << row) == LockMask)
  2143.               dpyinfo->shift_lock_mask = LockMask;
  2144.             break;
  2145.           }
  2146.           }
  2147.       }
  2148.     }
  2149.   }
  2150.  
  2151.   /* If we couldn't find any meta keys, accept any alt keys as meta keys.  */
  2152.   if (! dpyinfo->meta_mod_mask)
  2153.     {
  2154.       dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
  2155.       dpyinfo->alt_mod_mask = 0;
  2156.     }
  2157.  
  2158.   /* If some keys are both alt and meta,
  2159.      make them just meta, not alt.  */
  2160.   if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
  2161.     {
  2162.       dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
  2163.     }
  2164.  
  2165.   XFree ((char *) syms);
  2166.   XFreeModifiermap (mods);
  2167. }
  2168.  
  2169. /* Convert between the modifier bits X uses and the modifier bits
  2170.    Emacs uses.  */
  2171. static unsigned int
  2172. x_x_to_emacs_modifiers (dpyinfo, state)
  2173.      struct x_display_info *dpyinfo;
  2174.      unsigned int state;
  2175. {
  2176.   return (  ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
  2177.       | ((state & ControlMask)           ? ctrl_modifier  : 0)
  2178.       | ((state & dpyinfo->meta_mod_mask)  ? meta_modifier  : 0)
  2179.       | ((state & dpyinfo->alt_mod_mask)   ? alt_modifier  : 0)
  2180.       | ((state & dpyinfo->super_mod_mask) ? super_modifier  : 0)
  2181.       | ((state & dpyinfo->hyper_mod_mask) ? hyper_modifier  : 0));
  2182. }
  2183.  
  2184. static unsigned int
  2185. x_emacs_to_x_modifiers (dpyinfo, state)
  2186.      struct x_display_info *dpyinfo;
  2187.      unsigned int state;
  2188. {
  2189.   return (  ((state & alt_modifier)    ? dpyinfo->alt_mod_mask   : 0)
  2190.       | ((state & super_modifier)    ? dpyinfo->super_mod_mask : 0)
  2191.       | ((state & hyper_modifier)    ? dpyinfo->hyper_mod_mask : 0)
  2192.       | ((state & shift_modifier)    ? ShiftMask        : 0)
  2193.       | ((state & ctrl_modifier)    ? ControlMask      : 0)
  2194.       | ((state & meta_modifier)    ? dpyinfo->meta_mod_mask  : 0));
  2195. }
  2196.  
  2197. /* Convert a keysym to its name.  */
  2198.  
  2199. char *
  2200. x_get_keysym_name (keysym)
  2201.      KeySym keysym;
  2202. {
  2203.   char *value;
  2204.  
  2205.   BLOCK_INPUT;
  2206.   value = XKeysymToString (keysym);
  2207.   UNBLOCK_INPUT;
  2208.  
  2209.   return value;
  2210. }
  2211.  
  2212. /* Mouse clicks and mouse movement.  Rah.  */
  2213.  
  2214. /* Given a pixel position (PIX_X, PIX_Y) on the frame F, return
  2215.    glyph co-ordinates in (*X, *Y).  Set *BOUNDS to the rectangle
  2216.    that the glyph at X, Y occupies, if BOUNDS != 0.
  2217.    If NOCLIP is nonzero, do not force the value into range.  */
  2218.  
  2219. void
  2220. pixel_to_glyph_coords (f, pix_x, pix_y, x, y, bounds, noclip)
  2221.      FRAME_PTR f;
  2222.      register int pix_x, pix_y;
  2223.      register int *x, *y;
  2224.      XRectangle *bounds;
  2225.      int noclip;
  2226. {
  2227.   /* Arrange for the division in PIXEL_TO_CHAR_COL etc. to round down
  2228.      even for negative values.  */
  2229.   if (pix_x < 0)
  2230.     pix_x -= FONT_WIDTH ((f)->output_data.x->font) - 1;
  2231.   if (pix_y < 0)
  2232.     pix_y -= (f)->output_data.x->line_height - 1;
  2233.  
  2234.   pix_x = PIXEL_TO_CHAR_COL (f, pix_x);
  2235.   pix_y = PIXEL_TO_CHAR_ROW (f, pix_y);
  2236.  
  2237.   if (bounds)
  2238.     {
  2239.       bounds->width  = FONT_WIDTH  (f->output_data.x->font);
  2240.       bounds->height = f->output_data.x->line_height;
  2241.       bounds->x = CHAR_TO_PIXEL_COL (f, pix_x);
  2242.       bounds->y = CHAR_TO_PIXEL_ROW (f, pix_y);
  2243.     }
  2244.  
  2245.   if (!noclip)
  2246.     {
  2247.       if (pix_x < 0)
  2248.     pix_x = 0;
  2249.       else if (pix_x > FRAME_WINDOW_WIDTH (f))
  2250.     pix_x = FRAME_WINDOW_WIDTH (f);
  2251.  
  2252.       if (pix_y < 0)
  2253.     pix_y = 0;
  2254.       else if (pix_y > f->height)
  2255.     pix_y = f->height;
  2256.     }
  2257.  
  2258.   *x = pix_x;
  2259.   *y = pix_y;
  2260. }
  2261.  
  2262. void
  2263. glyph_to_pixel_coords (f, x, y, pix_x, pix_y)
  2264.      FRAME_PTR f;
  2265.      register int x, y;
  2266.      register int *pix_x, *pix_y;
  2267. {
  2268.   *pix_x = CHAR_TO_PIXEL_COL (f, x);
  2269.   *pix_y = CHAR_TO_PIXEL_ROW (f, y);
  2270. }
  2271.  
  2272. /* Prepare a mouse-event in *RESULT for placement in the input queue.
  2273.  
  2274.    If the event is a button press, then note that we have grabbed
  2275.    the mouse.  */
  2276.  
  2277. static Lisp_Object
  2278. construct_mouse_click (result, event, f)
  2279.      struct input_event *result;
  2280.      XButtonEvent *event;
  2281.      struct frame *f;
  2282. {
  2283.   /* Make the event type no_event; we'll change that when we decide
  2284.      otherwise.  */
  2285.   result->kind = mouse_click;
  2286.   result->code = event->button - Button1;
  2287.   result->timestamp = event->time;
  2288.   result->modifiers = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
  2289.                            event->state)
  2290.                | (event->type == ButtonRelease
  2291.               ? up_modifier
  2292.               : down_modifier));
  2293.  
  2294.   {
  2295.     int row, column;
  2296.  
  2297. #if 0
  2298.     pixel_to_glyph_coords (f, event->x, event->y, &column, &row, NULL, 0);
  2299.     XSETFASTINT (result->x, column);
  2300.     XSETFASTINT (result->y, row);
  2301. #endif
  2302.     XSETINT (result->x, event->x);
  2303.     XSETINT (result->y, event->y);
  2304.     XSETFRAME (result->frame_or_window, f);
  2305.   }
  2306. }
  2307.  
  2308. /* Prepare a menu-event in *RESULT for placement in the input queue.  */
  2309.  
  2310. static Lisp_Object
  2311. construct_menu_click (result, event, f)
  2312.      struct input_event *result;
  2313.      XButtonEvent *event;
  2314.      struct frame *f;
  2315. {
  2316.   /* Make the event type no_event; we'll change that when we decide
  2317.      otherwise.  */
  2318.   result->kind = mouse_click;
  2319.   result->code = event->button - Button1;
  2320.   result->timestamp = event->time;
  2321.   result->modifiers = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
  2322.                            event->state)
  2323.                | (event->type == ButtonRelease
  2324.               ? up_modifier
  2325.               : down_modifier));
  2326.  
  2327.   XSETINT (result->x, event->x);
  2328.   XSETINT (result->y, -1);
  2329.   XSETFRAME (result->frame_or_window, f);
  2330. }
  2331.  
  2332. /* Function to report a mouse movement to the mainstream Emacs code.
  2333.    The input handler calls this.
  2334.  
  2335.    We have received a mouse movement event, which is given in *event.
  2336.    If the mouse is over a different glyph than it was last time, tell
  2337.    the mainstream emacs code by setting mouse_moved.  If not, ask for
  2338.    another motion event, so we can check again the next time it moves.  */
  2339.  
  2340. static void
  2341. note_mouse_movement (frame, event)
  2342.      FRAME_PTR frame;
  2343.      XMotionEvent *event;
  2344. {
  2345.   last_mouse_movement_time = event->time;
  2346.  
  2347.   if (event->window != FRAME_X_WINDOW (frame))
  2348.     {
  2349.       frame->mouse_moved = 1;
  2350.       last_mouse_scroll_bar = Qnil;
  2351.  
  2352.       note_mouse_highlight (frame, -1, -1);
  2353.     }
  2354.  
  2355.   /* Has the mouse moved off the glyph it was on at the last sighting?  */
  2356.   else if (event->x < last_mouse_glyph.x
  2357.        || event->x >= last_mouse_glyph.x + last_mouse_glyph.width
  2358.        || event->y < last_mouse_glyph.y
  2359.        || event->y >= last_mouse_glyph.y + last_mouse_glyph.height)
  2360.     {
  2361.       frame->mouse_moved = 1;
  2362.       last_mouse_scroll_bar = Qnil;
  2363.  
  2364.       note_mouse_highlight (frame, event->x, event->y);
  2365.     }
  2366. }
  2367.  
  2368. /* This is used for debugging, to turn off note_mouse_highlight.  */
  2369. static int disable_mouse_highlight;
  2370.  
  2371. /* Take proper action when the mouse has moved to position X, Y on frame F
  2372.    as regards highlighting characters that have mouse-face properties.
  2373.    Also dehighlighting chars where the mouse was before.
  2374.    X and Y can be negative or out of range.  */
  2375.  
  2376. static void
  2377. note_mouse_highlight (f, x, y)
  2378.      FRAME_PTR f;
  2379.      int x, y;
  2380. {
  2381.   int row, column, portion;
  2382.   XRectangle new_glyph;
  2383.   Lisp_Object window;
  2384.   struct window *w;
  2385.  
  2386.   if (disable_mouse_highlight)
  2387.     return;
  2388.  
  2389.   FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_x = x;
  2390.   FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_y = y;
  2391.   FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_frame = f;
  2392.  
  2393.   if (FRAME_X_DISPLAY_INFO (f)->mouse_face_defer)
  2394.     return;
  2395.  
  2396.   if (gc_in_progress)
  2397.     {
  2398.       FRAME_X_DISPLAY_INFO (f)->mouse_face_deferred_gc = 1;
  2399.       return;
  2400.     }
  2401.  
  2402.   /* Find out which glyph the mouse is on.  */
  2403.   pixel_to_glyph_coords (f, x, y, &column, &row,
  2404.              &new_glyph, FRAME_X_DISPLAY_INFO (f)->grabbed);
  2405.  
  2406.   /* Which window is that in?  */
  2407.   window = window_from_coordinates (f, column, row, &portion);
  2408.   w = XWINDOW (window);
  2409.  
  2410.   /* If we were displaying active text in another window, clear that.  */
  2411.   if (! EQ (window, FRAME_X_DISPLAY_INFO (f)->mouse_face_window))
  2412.     clear_mouse_face (FRAME_X_DISPLAY_INFO (f));
  2413.  
  2414.   /* Are we in a window whose display is up to date?
  2415.      And verify the buffer's text has not changed.  */
  2416.   if (WINDOWP (window) && portion == 0 && row >= 0 && column >= 0
  2417.       && row < FRAME_HEIGHT (f) && column < FRAME_WIDTH (f)
  2418.       && EQ (w->window_end_valid, w->buffer)
  2419.       && XFASTINT (w->last_modified) == BUF_MODIFF (XBUFFER (w->buffer))
  2420.       && (XFASTINT (w->last_overlay_modified)
  2421.       == BUF_OVERLAY_MODIFF (XBUFFER (w->buffer))))
  2422.     {
  2423.       int *ptr = FRAME_CURRENT_GLYPHS (f)->charstarts[row];
  2424.       int i, pos;
  2425.  
  2426.       /* Find which buffer position the mouse corresponds to.  */
  2427.       for (i = column; i >= 0; i--)
  2428.     if (ptr[i] > 0)
  2429.       break;
  2430.       pos = ptr[i];
  2431.       /* Is it outside the displayed active region (if any)?  */
  2432.       if (pos <= 0)
  2433.     clear_mouse_face (FRAME_X_DISPLAY_INFO (f));
  2434.       else if (! (EQ (window, FRAME_X_DISPLAY_INFO (f)->mouse_face_window)
  2435.           && row >= FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_row
  2436.           && row <= FRAME_X_DISPLAY_INFO (f)->mouse_face_end_row
  2437.           && (row > FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_row
  2438.               || column >= FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_col)
  2439.           && (row < FRAME_X_DISPLAY_INFO (f)->mouse_face_end_row
  2440.               || column < FRAME_X_DISPLAY_INFO (f)->mouse_face_end_col
  2441.               || FRAME_X_DISPLAY_INFO (f)->mouse_face_past_end)))
  2442.     {
  2443.       Lisp_Object mouse_face, overlay, position;
  2444.       Lisp_Object *overlay_vec;
  2445.       int len, noverlays, ignor1;
  2446.       struct buffer *obuf;
  2447.       int obegv, ozv;
  2448.  
  2449.       /* If we get an out-of-range value, return now; avoid an error.  */
  2450.       if (pos > BUF_Z (XBUFFER (w->buffer)))
  2451.         return;
  2452.  
  2453.       /* Make the window's buffer temporarily current for
  2454.          overlays_at and compute_char_face.  */
  2455.       obuf = current_buffer;
  2456.       current_buffer = XBUFFER (w->buffer);
  2457.       obegv = BEGV;
  2458.       ozv = ZV;
  2459.       BEGV = BEG;
  2460.       ZV = Z;
  2461.  
  2462.       /* Yes.  Clear the display of the old active region, if any.  */
  2463.       clear_mouse_face (FRAME_X_DISPLAY_INFO (f));
  2464.  
  2465.       /* Is this char mouse-active?  */
  2466.       XSETINT (position, pos);
  2467.  
  2468.       len = 10;
  2469.       overlay_vec = (Lisp_Object *) xmalloc (len * sizeof (Lisp_Object));
  2470.  
  2471.       /* Put all the overlays we want in a vector in overlay_vec.
  2472.          Store the length in len.  */
  2473.       noverlays = overlays_at (pos, 1, &overlay_vec, &len,
  2474.                    NULL, NULL);
  2475.       noverlays = sort_overlays (overlay_vec, noverlays, w);
  2476.  
  2477.       /* Find the highest priority overlay that has a mouse-face prop.  */
  2478.       overlay = Qnil;
  2479.       for (i = 0; i < noverlays; i++)
  2480.         {
  2481.           mouse_face = Foverlay_get (overlay_vec[i], Qmouse_face);
  2482.           if (!NILP (mouse_face))
  2483.         {
  2484.           overlay = overlay_vec[i];
  2485.           break;
  2486.         }
  2487.         }
  2488.       free (overlay_vec);
  2489.       /* If no overlay applies, get a text property.  */
  2490.       if (NILP (overlay))
  2491.         mouse_face = Fget_text_property (position, Qmouse_face, w->buffer);
  2492.  
  2493.       /* Handle the overlay case.  */
  2494.       if (! NILP (overlay))
  2495.         {
  2496.           /* Find the range of text around this char that
  2497.          should be active.  */
  2498.           Lisp_Object before, after;
  2499.           int ignore;
  2500.  
  2501.           before = Foverlay_start (overlay);
  2502.           after = Foverlay_end (overlay);
  2503.           /* Record this as the current active region.  */
  2504.           fast_find_position (window, XFASTINT (before),
  2505.                   &FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_col,
  2506.                   &FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_row);
  2507.           FRAME_X_DISPLAY_INFO (f)->mouse_face_past_end
  2508.         = !fast_find_position (window, XFASTINT (after),
  2509.                        &FRAME_X_DISPLAY_INFO (f)->mouse_face_end_col,
  2510.                        &FRAME_X_DISPLAY_INFO (f)->mouse_face_end_row);
  2511.           FRAME_X_DISPLAY_INFO (f)->mouse_face_window = window;
  2512.           FRAME_X_DISPLAY_INFO (f)->mouse_face_face_id
  2513.         = compute_char_face (f, w, pos, 0, 0,
  2514.                      &ignore, pos + 1, 1);
  2515.  
  2516.           /* Display it as active.  */
  2517.           show_mouse_face (FRAME_X_DISPLAY_INFO (f), 1);
  2518.         }
  2519.       /* Handle the text property case.  */
  2520.       else if (! NILP (mouse_face))
  2521.         {
  2522.           /* Find the range of text around this char that
  2523.          should be active.  */
  2524.           Lisp_Object before, after, beginning, end;
  2525.           int ignore;
  2526.  
  2527.           beginning = Fmarker_position (w->start);
  2528.           XSETINT (end, (BUF_Z (XBUFFER (w->buffer))
  2529.                  - XFASTINT (w->window_end_pos)));
  2530.           before
  2531.         = Fprevious_single_property_change (make_number (pos + 1),
  2532.                             Qmouse_face,
  2533.                             w->buffer, beginning);
  2534.           after
  2535.         = Fnext_single_property_change (position, Qmouse_face,
  2536.                         w->buffer, end);
  2537.           /* Record this as the current active region.  */
  2538.           fast_find_position (window, XFASTINT (before),
  2539.                   &FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_col,
  2540.                   &FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_row);
  2541.           FRAME_X_DISPLAY_INFO (f)->mouse_face_past_end
  2542.         = !fast_find_position (window, XFASTINT (after),
  2543.                        &FRAME_X_DISPLAY_INFO (f)->mouse_face_end_col,
  2544.                        &FRAME_X_DISPLAY_INFO (f)->mouse_face_end_row);
  2545.           FRAME_X_DISPLAY_INFO (f)->mouse_face_window = window;
  2546.           FRAME_X_DISPLAY_INFO (f)->mouse_face_face_id
  2547.         = compute_char_face (f, w, pos, 0, 0,
  2548.                      &ignore, pos + 1, 1);
  2549.  
  2550.           /* Display it as active.  */
  2551.           show_mouse_face (FRAME_X_DISPLAY_INFO (f), 1);
  2552.         }
  2553.       BEGV = obegv;
  2554.       ZV = ozv;
  2555.       current_buffer = obuf;
  2556.     }
  2557.     }
  2558. }
  2559.  
  2560. /* Find the row and column of position POS in window WINDOW.
  2561.    Store them in *COLUMNP and *ROWP.
  2562.    This assumes display in WINDOW is up to date.
  2563.    If POS is above start of WINDOW, return coords
  2564.    of start of first screen line.
  2565.    If POS is after end of WINDOW, return coords of end of last screen line.
  2566.  
  2567.    Value is 1 if POS is in range, 0 if it was off screen.  */
  2568.  
  2569. static int
  2570. fast_find_position (window, pos, columnp, rowp)
  2571.      Lisp_Object window;
  2572.      int pos;
  2573.      int *columnp, *rowp;
  2574. {
  2575.   struct window *w = XWINDOW (window);
  2576.   FRAME_PTR f = XFRAME (WINDOW_FRAME (w));
  2577.   int i;
  2578.   int row = 0;
  2579.   int left = WINDOW_LEFT_MARGIN (w);
  2580.   int top = XFASTINT (w->top);
  2581.   int height = XFASTINT (w->height) - ! MINI_WINDOW_P (w);
  2582.   int width = window_internal_width (w);
  2583.   int *charstarts;
  2584.   int lastcol;
  2585.   int maybe_next_line = 0;
  2586.  
  2587.   /* Find the right row.  */
  2588.   for (i = 0;
  2589.        i < height;
  2590.        i++)
  2591.     {
  2592.       int linestart = FRAME_CURRENT_GLYPHS (f)->charstarts[top + i][left];
  2593.       if (linestart > pos)
  2594.     break;
  2595.       /* If the position sought is the end of the buffer,
  2596.      don't include the blank lines at the bottom of the window.  */
  2597.       if (linestart == pos && pos == BUF_ZV (XBUFFER (w->buffer)))
  2598.     {
  2599.       maybe_next_line = 1;
  2600.       break;
  2601.     }
  2602.       if (linestart > 0)
  2603.     row = i;
  2604.     }
  2605.  
  2606.   /* Find the right column with in it.  */
  2607.   charstarts = FRAME_CURRENT_GLYPHS (f)->charstarts[top + row];
  2608.   lastcol = left;
  2609.   for (i = 0; i < width; i++)
  2610.     {
  2611.       if (charstarts[left + i] == pos)
  2612.     {
  2613.       *rowp = row + top;
  2614.       *columnp = i + left;
  2615.       return 1;
  2616.     }
  2617.       else if (charstarts[left + i] > pos)
  2618.     break;
  2619.       else if (charstarts[left + i] > 0)
  2620.     lastcol = left + i + 1;
  2621.     }
  2622.  
  2623.   /* If we're looking for the end of the buffer,
  2624.      and we didn't find it in the line we scanned,
  2625.      use the start of the following line.  */
  2626.   if (maybe_next_line)
  2627.     {
  2628.       row++;
  2629.       lastcol = left;
  2630.     }
  2631.  
  2632.   *rowp = row + top;
  2633.   *columnp = lastcol;
  2634.   return 0;
  2635. }
  2636.  
  2637. /* Display the active region described by mouse_face_*
  2638.    in its mouse-face if HL > 0, in its normal face if HL = 0.  */
  2639.  
  2640. static void
  2641. show_mouse_face (dpyinfo, hl)
  2642.      struct x_display_info *dpyinfo;
  2643.      int hl;
  2644. {
  2645.   struct window *w = XWINDOW (dpyinfo->mouse_face_window);
  2646.   int width = window_internal_width (w);
  2647.   FRAME_PTR f = XFRAME (WINDOW_FRAME (w));
  2648.   int i;
  2649.   int cursor_off = 0;
  2650.   int old_curs_x = curs_x;
  2651.   int old_curs_y = curs_y;
  2652.  
  2653.   /* Set these variables temporarily
  2654.      so that if we have to turn the cursor off and on again
  2655.      we will put it back at the same place.  */
  2656.   curs_x = f->phys_cursor_x;
  2657.   curs_y = f->phys_cursor_y;  
  2658.   for (i = FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_row;
  2659.        i <= FRAME_X_DISPLAY_INFO (f)->mouse_face_end_row; i++)
  2660.     {
  2661.       int column = (i == FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_row
  2662.             ? FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_col
  2663.             : WINDOW_LEFT_MARGIN (w));
  2664.       int endcolumn = (i == FRAME_X_DISPLAY_INFO (f)->mouse_face_end_row
  2665.                ? FRAME_X_DISPLAY_INFO (f)->mouse_face_end_col
  2666.                : WINDOW_LEFT_MARGIN (w) + width);
  2667.       endcolumn = min (endcolumn, FRAME_CURRENT_GLYPHS (f)->used[i]);
  2668.  
  2669.       /* If the cursor's in the text we are about to rewrite,
  2670.      turn the cursor off.  */
  2671.       if (i == curs_y
  2672.       && curs_x >= column - 1
  2673.       && curs_x <= endcolumn)
  2674.     {
  2675.       x_update_cursor (f, 0);
  2676.       cursor_off = 1;
  2677.     }
  2678.  
  2679.       dumpglyphs (f,
  2680.           CHAR_TO_PIXEL_COL (f, column),
  2681.           CHAR_TO_PIXEL_ROW (f, i),
  2682.           FRAME_CURRENT_GLYPHS (f)->glyphs[i] + column,
  2683.           endcolumn - column,
  2684.           /* Highlight with mouse face if hl > 0.  */
  2685.           hl > 0 ? 3 : 0, 0, NULL);
  2686.     }
  2687.  
  2688.   /* If we turned the cursor off, turn it back on.  */
  2689.   if (cursor_off)
  2690.     x_display_cursor (f, 1, curs_x, curs_y);
  2691.  
  2692.   curs_x = old_curs_x;
  2693.   curs_y = old_curs_y;
  2694.  
  2695.   /* Change the mouse cursor according to the value of HL.  */
  2696.   if (hl > 0)
  2697.     XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  2698.            f->output_data.x->cross_cursor);
  2699.   else
  2700.     XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  2701.            f->output_data.x->text_cursor);
  2702. }
  2703.  
  2704. /* Clear out the mouse-highlighted active region.
  2705.    Redraw it unhighlighted first.  */
  2706.  
  2707. static void
  2708. clear_mouse_face (dpyinfo)
  2709.      struct x_display_info *dpyinfo;
  2710. {
  2711.   if (! NILP (dpyinfo->mouse_face_window))
  2712.     show_mouse_face (dpyinfo, 0);
  2713.  
  2714.   dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
  2715.   dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
  2716.   dpyinfo->mouse_face_window = Qnil;
  2717. }
  2718.  
  2719. /* Just discard the mouse face information for frame F, if any.
  2720.    This is used when the size of F is changed.  */
  2721.  
  2722. void
  2723. cancel_mouse_face (f)
  2724.      FRAME_PTR f;
  2725. {
  2726.   Lisp_Object window;
  2727.   struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
  2728.  
  2729.   window = dpyinfo->mouse_face_window;
  2730.   if (! NILP (window) && XFRAME (XWINDOW (window)->frame) == f)
  2731.     {
  2732.       dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
  2733.       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
  2734.       dpyinfo->mouse_face_window = Qnil;
  2735.     }
  2736. }
  2737.  
  2738. static struct scroll_bar *x_window_to_scroll_bar ();
  2739. static void x_scroll_bar_report_motion ();
  2740.  
  2741. /* Return the current position of the mouse.
  2742.    *fp should be a frame which indicates which display to ask about.
  2743.  
  2744.    If the mouse movement started in a scroll bar, set *fp, *bar_window,
  2745.    and *part to the frame, window, and scroll bar part that the mouse
  2746.    is over.  Set *x and *y to the portion and whole of the mouse's
  2747.    position on the scroll bar.
  2748.  
  2749.    If the mouse movement started elsewhere, set *fp to the frame the
  2750.    mouse is on, *bar_window to nil, and *x and *y to the character cell
  2751.    the mouse is over.
  2752.  
  2753.    Set *time to the server timestamp for the time at which the mouse
  2754.    was at this position.
  2755.  
  2756.    Don't store anything if we don't have a valid set of values to report.
  2757.  
  2758.    This clears the mouse_moved flag, so we can wait for the next mouse
  2759.    movement.  */
  2760.  
  2761. static void
  2762. XTmouse_position (fp, insist, bar_window, part, x, y, time)
  2763.      FRAME_PTR *fp;
  2764.      int insist;
  2765.      Lisp_Object *bar_window;
  2766.      enum scroll_bar_part *part;
  2767.      Lisp_Object *x, *y;
  2768.      unsigned long *time;
  2769. {
  2770.   FRAME_PTR f1;
  2771.  
  2772.   BLOCK_INPUT;
  2773.  
  2774.   if (! NILP (last_mouse_scroll_bar) && insist == 0)
  2775.     x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
  2776.   else
  2777.     {
  2778.       Window root;
  2779.       int root_x, root_y;
  2780.  
  2781.       Window dummy_window;
  2782.       int dummy;
  2783.  
  2784.       Lisp_Object frame, tail;
  2785.  
  2786.       /* Clear the mouse-moved flag for every frame on this display.  */
  2787.       FOR_EACH_FRAME (tail, frame)
  2788.     if (FRAME_X_DISPLAY (XFRAME (frame)) == FRAME_X_DISPLAY (*fp))
  2789.       XFRAME (frame)->mouse_moved = 0;
  2790.  
  2791.       last_mouse_scroll_bar = Qnil;
  2792.  
  2793.       /* Figure out which root window we're on.  */
  2794.       XQueryPointer (FRAME_X_DISPLAY (*fp),
  2795.              DefaultRootWindow (FRAME_X_DISPLAY (*fp)),
  2796.  
  2797.              /* The root window which contains the pointer.  */
  2798.              &root,
  2799.  
  2800.              /* Trash which we can't trust if the pointer is on
  2801.             a different screen.  */
  2802.              &dummy_window,
  2803.  
  2804.              /* The position on that root window.  */
  2805.              &root_x, &root_y,
  2806.  
  2807.              /* More trash we can't trust.  */
  2808.              &dummy, &dummy,
  2809.  
  2810.              /* Modifier keys and pointer buttons, about which
  2811.             we don't care.  */
  2812.              (unsigned int *) &dummy);
  2813.  
  2814.       /* Now we have a position on the root; find the innermost window
  2815.      containing the pointer.  */
  2816.       {
  2817.     Window win, child;
  2818.     int win_x, win_y;
  2819.     int parent_x, parent_y;
  2820.     int count;
  2821.  
  2822.     win = root;
  2823.  
  2824.     /* XTranslateCoordinates can get errors if the window
  2825.        structure is changing at the same time this function
  2826.        is running.  So at least we must not crash from them.  */
  2827.  
  2828.     count = x_catch_errors (FRAME_X_DISPLAY (*fp));
  2829.  
  2830.     if (FRAME_X_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
  2831.         && FRAME_LIVE_P (last_mouse_frame))
  2832.       {
  2833.         /* If mouse was grabbed on a frame, give coords for that frame
  2834.            even if the mouse is now outside it.  */
  2835.         XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
  2836.  
  2837.                    /* From-window, to-window.  */
  2838.                    root, FRAME_X_WINDOW (last_mouse_frame),
  2839.  
  2840.                    /* From-position, to-position.  */
  2841.                    root_x, root_y, &win_x, &win_y,
  2842.  
  2843.                    /* Child of win.  */
  2844.                    &child);
  2845.         f1 = last_mouse_frame;
  2846.       }
  2847.     else
  2848.       {
  2849.         while (1)
  2850.           {
  2851.         XTranslateCoordinates (FRAME_X_DISPLAY (*fp),
  2852.  
  2853.                        /* From-window, to-window.  */
  2854.                        root, win,
  2855.  
  2856.                        /* From-position, to-position.  */
  2857.                        root_x, root_y, &win_x, &win_y,
  2858.  
  2859.                        /* Child of win.  */
  2860.                        &child);
  2861.  
  2862.         if (child == None || child == win)
  2863.           break;
  2864.  
  2865.         win = child;
  2866.         parent_x = win_x;
  2867.         parent_y = win_y;
  2868.           }
  2869.  
  2870.         /* Now we know that:
  2871.            win is the innermost window containing the pointer
  2872.            (XTC says it has no child containing the pointer),
  2873.            win_x and win_y are the pointer's position in it
  2874.            (XTC did this the last time through), and
  2875.            parent_x and parent_y are the pointer's position in win's parent.
  2876.            (They are what win_x and win_y were when win was child.
  2877.            If win is the root window, it has no parent, and
  2878.            parent_{x,y} are invalid, but that's okay, because we'll
  2879.            never use them in that case.)  */
  2880.  
  2881.         /* Is win one of our frames?  */
  2882.         f1 = x_any_window_to_frame (FRAME_X_DISPLAY_INFO (*fp), win);
  2883.       }
  2884.  
  2885.     if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
  2886.       f1 = 0;
  2887.  
  2888.     x_uncatch_errors (FRAME_X_DISPLAY (*fp), count);
  2889.  
  2890.     /* If not, is it one of our scroll bars?  */
  2891.     if (! f1)
  2892.       {
  2893.         struct scroll_bar *bar = x_window_to_scroll_bar (win);
  2894.  
  2895.         if (bar)
  2896.           {
  2897.         f1 = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
  2898.         win_x = parent_x;
  2899.         win_y = parent_y;
  2900.           }
  2901.       }
  2902.  
  2903.     if (f1 == 0 && insist > 0)
  2904.       f1 = selected_frame;
  2905.  
  2906.     if (f1)
  2907.       {
  2908.         int ignore1, ignore2;
  2909.  
  2910.         /* Ok, we found a frame.  Store all the values.  */
  2911.  
  2912.         pixel_to_glyph_coords (f1, win_x, win_y, &ignore1, &ignore2,
  2913.                    &last_mouse_glyph,
  2914.                    FRAME_X_DISPLAY_INFO (f1)->grabbed
  2915.                    || insist);
  2916.  
  2917.         *bar_window = Qnil;
  2918.         *part = 0;
  2919.         *fp = f1;
  2920.         XSETINT (*x, win_x);
  2921.         XSETINT (*y, win_y);
  2922.         *time = last_mouse_movement_time;
  2923.       }
  2924.       }
  2925.     }
  2926.  
  2927.   UNBLOCK_INPUT;
  2928. }
  2929.  
  2930. /* Scroll bar support.  */
  2931.  
  2932. /* Given an X window ID, find the struct scroll_bar which manages it.
  2933.    This can be called in GC, so we have to make sure to strip off mark
  2934.    bits.  */
  2935. static struct scroll_bar *
  2936. x_window_to_scroll_bar (window_id)
  2937.      Window window_id;
  2938. {
  2939.   Lisp_Object tail, frame;
  2940.  
  2941.   for (tail = Vframe_list;
  2942.        XGCTYPE (tail) == Lisp_Cons;
  2943.        tail = XCONS (tail)->cdr)
  2944.     {
  2945.       Lisp_Object frame, bar, condemned;
  2946.  
  2947.       frame = XCONS (tail)->car;
  2948.       /* All elements of Vframe_list should be frames.  */
  2949.       if (! GC_FRAMEP (frame))
  2950.     abort ();
  2951.  
  2952.       /* Scan this frame's scroll bar list for a scroll bar with the
  2953.          right window ID.  */
  2954.       condemned = FRAME_CONDEMNED_SCROLL_BARS (XFRAME (frame));
  2955.       for (bar = FRAME_SCROLL_BARS (XFRAME (frame));
  2956.        /* This trick allows us to search both the ordinary and
  2957.               condemned scroll bar lists with one loop.  */
  2958.        ! GC_NILP (bar) || (bar = condemned,
  2959.                    condemned = Qnil,
  2960.                    ! GC_NILP (bar));
  2961.        bar = XSCROLL_BAR (bar)->next)
  2962.     if (SCROLL_BAR_X_WINDOW (XSCROLL_BAR (bar)) == window_id)
  2963.       return XSCROLL_BAR (bar);
  2964.     }
  2965.  
  2966.   return 0;
  2967. }
  2968.  
  2969. /* Open a new X window to serve as a scroll bar, and return the
  2970.    scroll bar vector for it.  */
  2971. static struct scroll_bar *
  2972. x_scroll_bar_create (window, top, left, width, height)
  2973.      struct window *window;
  2974.      int top, left, width, height;
  2975. {
  2976.   FRAME_PTR f = XFRAME (WINDOW_FRAME (window));
  2977.   struct scroll_bar *bar
  2978.     = XSCROLL_BAR (Fmake_vector (make_number (SCROLL_BAR_VEC_SIZE), Qnil));
  2979.  
  2980.   BLOCK_INPUT;
  2981.  
  2982.   {
  2983.     XSetWindowAttributes a;
  2984.     unsigned long mask;
  2985.     a.background_pixel = f->output_data.x->background_pixel;
  2986.     a.event_mask = (ButtonPressMask | ButtonReleaseMask
  2987.             | ButtonMotionMask | PointerMotionHintMask
  2988.             | ExposureMask);
  2989.     a.cursor = FRAME_X_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
  2990.  
  2991.     mask = (CWBackPixel | CWEventMask | CWCursor);
  2992.  
  2993. #if 0
  2994.  
  2995.     ac = 0;
  2996.     XtSetArg (al[ac], XtNx, left); ac++;
  2997.     XtSetArg (al[ac], XtNy, top); ac++;
  2998.     XtSetArg (al[ac], XtNwidth, width); ac++;
  2999.     XtSetArg (al[ac], XtNheight, height); ac++;
  3000.     XtSetArg (al[ac], XtNborderWidth, 0); ac++;
  3001.     sb_widget = XtCreateManagedWidget ("box",
  3002.                        boxWidgetClass,
  3003.                        f->output_data.x->edit_widget, al, ac);
  3004.     SET_SCROLL_BAR_X_WINDOW
  3005.       (bar, sb_widget->core.window);
  3006. #endif
  3007.     SET_SCROLL_BAR_X_WINDOW
  3008.       (bar,
  3009.        XCreateWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  3010.  
  3011.               /* Position and size of scroll bar.  */
  3012.               left + VERTICAL_SCROLL_BAR_WIDTH_TRIM, top,
  3013.               width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2, height,
  3014.  
  3015.               /* Border width, depth, class, and visual.  */
  3016.               0, CopyFromParent, CopyFromParent, CopyFromParent,
  3017.  
  3018.               /* Attributes.  */
  3019.               mask, &a));
  3020.   }
  3021.  
  3022.   XSETWINDOW (bar->window, window);
  3023.   XSETINT (bar->top, top);
  3024.   XSETINT (bar->left, left);
  3025.   XSETINT (bar->width, width);
  3026.   XSETINT (bar->height, height);
  3027.   XSETINT (bar->start, 0);
  3028.   XSETINT (bar->end, 0);
  3029.   bar->dragging = Qnil;
  3030.  
  3031.   /* Add bar to its frame's list of scroll bars.  */
  3032.   bar->next = FRAME_SCROLL_BARS (f);
  3033.   bar->prev = Qnil;
  3034.   XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
  3035.   if (! NILP (bar->next))
  3036.     XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
  3037.  
  3038.   XMapRaised (FRAME_X_DISPLAY (f), SCROLL_BAR_X_WINDOW (bar));
  3039.  
  3040.   UNBLOCK_INPUT;
  3041.  
  3042.   return bar;
  3043. }
  3044.  
  3045. /* Draw BAR's handle in the proper position.
  3046.    If the handle is already drawn from START to END, don't bother
  3047.    redrawing it, unless REBUILD is non-zero; in that case, always
  3048.    redraw it.  (REBUILD is handy for drawing the handle after expose
  3049.    events.)
  3050.  
  3051.    Normally, we want to constrain the start and end of the handle to
  3052.    fit inside its rectangle, but if the user is dragging the scroll bar
  3053.    handle, we want to let them drag it down all the way, so that the
  3054.    bar's top is as far down as it goes; otherwise, there's no way to
  3055.    move to the very end of the buffer.  */
  3056. static void
  3057. x_scroll_bar_set_handle (bar, start, end, rebuild)
  3058.      struct scroll_bar *bar;
  3059.      int start, end;
  3060.      int rebuild;
  3061. {
  3062.   int dragging = ! NILP (bar->dragging);
  3063.   Window w = SCROLL_BAR_X_WINDOW (bar);
  3064.   FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
  3065.   GC gc = f->output_data.x->normal_gc;
  3066.  
  3067.   /* If the display is already accurate, do nothing.  */
  3068.   if (! rebuild
  3069.       && start == XINT (bar->start)
  3070.       && end == XINT (bar->end))
  3071.     return;
  3072.  
  3073.   BLOCK_INPUT;
  3074.  
  3075.   {
  3076.     int inside_width = VERTICAL_SCROLL_BAR_INSIDE_WIDTH (f, XINT (bar->width));
  3077.     int inside_height = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, XINT (bar->height));
  3078.     int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
  3079.  
  3080.     /* Make sure the values are reasonable, and try to preserve
  3081.        the distance between start and end.  */
  3082.     {
  3083.       int length = end - start;
  3084.  
  3085.       if (start < 0)
  3086.     start = 0;
  3087.       else if (start > top_range)
  3088.     start = top_range;
  3089.       end = start + length;
  3090.  
  3091.       if (end < start)
  3092.     end = start;
  3093.       else if (end > top_range && ! dragging)
  3094.     end = top_range;
  3095.     }
  3096.  
  3097.     /* Store the adjusted setting in the scroll bar.  */
  3098.     XSETINT (bar->start, start);
  3099.     XSETINT (bar->end, end);
  3100.  
  3101.     /* Clip the end position, just for display.  */
  3102.     if (end > top_range)
  3103.       end = top_range;
  3104.  
  3105.     /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels
  3106.        below top positions, to make sure the handle is always at least
  3107.        that many pixels tall.  */
  3108.     end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
  3109.  
  3110.     /* Draw the empty space above the handle.  Note that we can't clear
  3111.        zero-height areas; that means "clear to end of window."  */
  3112.     if (0 < start)
  3113.       XClearArea (FRAME_X_DISPLAY (f), w,
  3114.  
  3115.           /* x, y, width, height, and exposures.  */
  3116.           VERTICAL_SCROLL_BAR_LEFT_BORDER,
  3117.           VERTICAL_SCROLL_BAR_TOP_BORDER,
  3118.           inside_width, start,
  3119.           False);
  3120.  
  3121.     /* Draw the handle itself.  */
  3122.     XFillRectangle (FRAME_X_DISPLAY (f), w, gc,
  3123.  
  3124.             /* x, y, width, height */
  3125.             VERTICAL_SCROLL_BAR_LEFT_BORDER,
  3126.             VERTICAL_SCROLL_BAR_TOP_BORDER + start,
  3127.             inside_width, end - start);
  3128.  
  3129.  
  3130.     /* Draw the empty space below the handle.  Note that we can't
  3131.        clear zero-height areas; that means "clear to end of window." */
  3132.     if (end < inside_height)
  3133.       XClearArea (FRAME_X_DISPLAY (f), w,
  3134.  
  3135.           /* x, y, width, height, and exposures.  */
  3136.           VERTICAL_SCROLL_BAR_LEFT_BORDER,
  3137.           VERTICAL_SCROLL_BAR_TOP_BORDER + end,
  3138.           inside_width, inside_height - end,
  3139.           False);
  3140.  
  3141.   }
  3142.  
  3143.   UNBLOCK_INPUT;
  3144. }
  3145.  
  3146. /* Move a scroll bar around on the screen, to accommodate changing
  3147.    window configurations.  */
  3148. static void
  3149. x_scroll_bar_move (bar, top, left, width, height)
  3150.      struct scroll_bar *bar;
  3151.      int top, left, width, height;
  3152. {
  3153.   Window w = SCROLL_BAR_X_WINDOW (bar);
  3154.   FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
  3155.  
  3156.   BLOCK_INPUT;
  3157.  
  3158.   {
  3159.     XWindowChanges wc;
  3160.     unsigned int mask = 0;
  3161.  
  3162.     wc.x = left + VERTICAL_SCROLL_BAR_WIDTH_TRIM;
  3163.     wc.y = top;
  3164.  
  3165.     wc.width = width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2;
  3166.     wc.height = height;
  3167.  
  3168.     if (left != XINT (bar->left))    mask |= CWX;
  3169.     if (top != XINT (bar->top))        mask |= CWY;
  3170.     if (width != XINT (bar->width))    mask |= CWWidth;
  3171.     if (height != XINT (bar->height))    mask |= CWHeight;
  3172.  
  3173.     if (mask)
  3174.       XConfigureWindow (FRAME_X_DISPLAY (f), SCROLL_BAR_X_WINDOW (bar),
  3175.             mask, &wc);
  3176.   }
  3177.  
  3178.   XSETINT (bar->left, left);
  3179.   XSETINT (bar->top, top);
  3180.   XSETINT (bar->width, width);
  3181.   XSETINT (bar->height, height);
  3182.  
  3183.   UNBLOCK_INPUT;
  3184. }
  3185.  
  3186. /* Destroy the X window for BAR, and set its Emacs window's scroll bar
  3187.    to nil.  */
  3188. static void
  3189. x_scroll_bar_remove (bar)
  3190.      struct scroll_bar *bar;
  3191. {
  3192.   FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
  3193.  
  3194.   BLOCK_INPUT;
  3195.  
  3196.   /* Destroy the window.  */
  3197.   XDestroyWindow (FRAME_X_DISPLAY (f), SCROLL_BAR_X_WINDOW (bar));
  3198.  
  3199.   /* Disassociate this scroll bar from its window.  */
  3200.   XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
  3201.  
  3202.   UNBLOCK_INPUT;
  3203. }
  3204.  
  3205. /* Set the handle of the vertical scroll bar for WINDOW to indicate
  3206.    that we are displaying PORTION characters out of a total of WHOLE
  3207.    characters, starting at POSITION.  If WINDOW has no scroll bar,
  3208.    create one.  */
  3209. static void
  3210. XTset_vertical_scroll_bar (window, portion, whole, position)
  3211.      struct window *window;
  3212.      int portion, whole, position;
  3213. {
  3214.   FRAME_PTR f = XFRAME (WINDOW_FRAME (window));
  3215.   int top = XINT (window->top);
  3216.   int left = WINDOW_VERTICAL_SCROLL_BAR_COLUMN (window);
  3217.   int height = WINDOW_VERTICAL_SCROLL_BAR_HEIGHT (window);
  3218.  
  3219.   /* Where should this scroll bar be, pixelwise?  */
  3220.   int pixel_top  = CHAR_TO_PIXEL_ROW (f, top);
  3221.   int pixel_left = CHAR_TO_PIXEL_COL (f, left);
  3222.   int pixel_width
  3223.     = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
  3224.        ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
  3225.        : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.x->font)));
  3226.   int pixel_height = VERTICAL_SCROLL_BAR_PIXEL_HEIGHT (f, height);
  3227.  
  3228.   struct scroll_bar *bar;
  3229.  
  3230.   /* Does the scroll bar exist yet?  */
  3231.   if (NILP (window->vertical_scroll_bar))
  3232.     bar = x_scroll_bar_create (window,
  3233.                   pixel_top, pixel_left,
  3234.                   pixel_width, pixel_height);
  3235.   else
  3236.     {
  3237.       /* It may just need to be moved and resized.  */
  3238.       bar = XSCROLL_BAR (window->vertical_scroll_bar);
  3239.       x_scroll_bar_move (bar, pixel_top, pixel_left, pixel_width, pixel_height);
  3240.     }
  3241.  
  3242.   /* Set the scroll bar's current state, unless we're currently being
  3243.      dragged.  */
  3244.   if (NILP (bar->dragging))
  3245.     {
  3246.       int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, pixel_height);
  3247.  
  3248.       if (whole == 0)
  3249.     x_scroll_bar_set_handle (bar, 0, top_range, 0);
  3250.       else
  3251.     {
  3252.       int start = ((double) position * top_range) / whole;
  3253.       int end = ((double) (position + portion) * top_range) / whole;
  3254.  
  3255.       x_scroll_bar_set_handle (bar, start, end, 0);
  3256.     }
  3257.     }
  3258.  
  3259.   XSETVECTOR (window->vertical_scroll_bar, bar);
  3260. }
  3261.  
  3262.  
  3263. /* The following three hooks are used when we're doing a thorough
  3264.    redisplay of the frame.  We don't explicitly know which scroll bars
  3265.    are going to be deleted, because keeping track of when windows go
  3266.    away is a real pain - "Can you say set-window-configuration, boys
  3267.    and girls?"  Instead, we just assert at the beginning of redisplay
  3268.    that *all* scroll bars are to be removed, and then save a scroll bar
  3269.    from the fiery pit when we actually redisplay its window.  */
  3270.  
  3271. /* Arrange for all scroll bars on FRAME to be removed at the next call
  3272.    to `*judge_scroll_bars_hook'.  A scroll bar may be spared if
  3273.    `*redeem_scroll_bar_hook' is applied to its window before the judgement.  */
  3274. static void
  3275. XTcondemn_scroll_bars (frame)
  3276.      FRAME_PTR frame;
  3277. {
  3278.   /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS.  */
  3279.   while (! NILP (FRAME_SCROLL_BARS (frame)))
  3280.     {
  3281.       Lisp_Object bar;
  3282.       bar = FRAME_SCROLL_BARS (frame);
  3283.       FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
  3284.       XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
  3285.       XSCROLL_BAR (bar)->prev = Qnil;
  3286.       if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
  3287.     XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
  3288.       FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
  3289.     }
  3290. }
  3291.  
  3292. /* Unmark WINDOW's scroll bar for deletion in this judgement cycle.
  3293.    Note that WINDOW isn't necessarily condemned at all.  */
  3294. static void
  3295. XTredeem_scroll_bar (window)
  3296.      struct window *window;
  3297. {
  3298.   struct scroll_bar *bar;
  3299.  
  3300.   /* We can't redeem this window's scroll bar if it doesn't have one.  */
  3301.   if (NILP (window->vertical_scroll_bar))
  3302.     abort ();
  3303.  
  3304.   bar = XSCROLL_BAR (window->vertical_scroll_bar);
  3305.  
  3306.   /* Unlink it from the condemned list.  */
  3307.   {
  3308.     FRAME_PTR f = XFRAME (WINDOW_FRAME (window));
  3309.  
  3310.     if (NILP (bar->prev))
  3311.       {
  3312.     /* If the prev pointer is nil, it must be the first in one of
  3313.            the lists.  */
  3314.     if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
  3315.       /* It's not condemned.  Everything's fine.  */
  3316.       return;
  3317.     else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
  3318.              window->vertical_scroll_bar))
  3319.       FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
  3320.     else
  3321.       /* If its prev pointer is nil, it must be at the front of
  3322.              one or the other!  */
  3323.       abort ();
  3324.       }
  3325.     else
  3326.       XSCROLL_BAR (bar->prev)->next = bar->next;
  3327.  
  3328.     if (! NILP (bar->next))
  3329.       XSCROLL_BAR (bar->next)->prev = bar->prev;
  3330.  
  3331.     bar->next = FRAME_SCROLL_BARS (f);
  3332.     bar->prev = Qnil;
  3333.     XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
  3334.     if (! NILP (bar->next))
  3335.       XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
  3336.   }
  3337. }
  3338.  
  3339. /* Remove all scroll bars on FRAME that haven't been saved since the
  3340.    last call to `*condemn_scroll_bars_hook'.  */
  3341. static void
  3342. XTjudge_scroll_bars (f)
  3343.      FRAME_PTR f;
  3344. {
  3345.   Lisp_Object bar, next;
  3346.  
  3347.   bar = FRAME_CONDEMNED_SCROLL_BARS (f);
  3348.  
  3349.   /* Clear out the condemned list now so we won't try to process any
  3350.      more events on the hapless scroll bars.  */
  3351.   FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
  3352.  
  3353.   for (; ! NILP (bar); bar = next)
  3354.     {
  3355.       struct scroll_bar *b = XSCROLL_BAR (bar);
  3356.  
  3357.       x_scroll_bar_remove (b);
  3358.  
  3359.       next = b->next;
  3360.       b->next = b->prev = Qnil;
  3361.     }
  3362.  
  3363.   /* Now there should be no references to the condemned scroll bars,
  3364.      and they should get garbage-collected.  */
  3365. }
  3366.  
  3367.  
  3368. /* Handle an Expose or GraphicsExpose event on a scroll bar.
  3369.  
  3370.    This may be called from a signal handler, so we have to ignore GC
  3371.    mark bits.  */
  3372. static void
  3373. x_scroll_bar_expose (bar, event)
  3374.      struct scroll_bar *bar;
  3375.      XEvent *event;
  3376. {
  3377.   Window w = SCROLL_BAR_X_WINDOW (bar);
  3378.   FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
  3379.   GC gc = f->output_data.x->normal_gc;
  3380.   int width_trim = VERTICAL_SCROLL_BAR_WIDTH_TRIM;
  3381.  
  3382.   BLOCK_INPUT;
  3383.  
  3384.   x_scroll_bar_set_handle (bar, XINT (bar->start), XINT (bar->end), 1);
  3385.  
  3386.   /* Draw a one-pixel border just inside the edges of the scroll bar. */
  3387.   XDrawRectangle (FRAME_X_DISPLAY (f), w, gc,
  3388.  
  3389.           /* x, y, width, height */
  3390.           0, 0,
  3391.           XINT (bar->width) - 1 - width_trim - width_trim,
  3392.           XINT (bar->height) - 1);
  3393.     
  3394.   UNBLOCK_INPUT;
  3395. }
  3396.  
  3397. /* Handle a mouse click on the scroll bar BAR.  If *EMACS_EVENT's kind
  3398.    is set to something other than no_event, it is enqueued.
  3399.  
  3400.    This may be called from a signal handler, so we have to ignore GC
  3401.    mark bits.  */
  3402. static void
  3403. x_scroll_bar_handle_click (bar, event, emacs_event)
  3404.      struct scroll_bar *bar;
  3405.      XEvent *event;
  3406.      struct input_event *emacs_event;
  3407. {
  3408.   if (! GC_WINDOWP (bar->window))
  3409.     abort ();
  3410.  
  3411.   emacs_event->kind = scroll_bar_click;
  3412.   emacs_event->code = event->xbutton.button - Button1;
  3413.   emacs_event->modifiers
  3414.     = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO 
  3415.                    (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
  3416.                    event->xbutton.state)
  3417.        | (event->type == ButtonRelease
  3418.       ? up_modifier
  3419.       : down_modifier));
  3420.   emacs_event->frame_or_window = bar->window;
  3421.   emacs_event->timestamp = event->xbutton.time;
  3422.   {
  3423.     FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
  3424.     int internal_height
  3425.       = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, XINT (bar->height));
  3426.     int top_range
  3427.       = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
  3428.     int y = event->xbutton.y - VERTICAL_SCROLL_BAR_TOP_BORDER;
  3429.  
  3430.     if (y < 0) y = 0;
  3431.     if (y > top_range) y = top_range;
  3432.  
  3433.     if (y < XINT (bar->start))
  3434.       emacs_event->part = scroll_bar_above_handle;
  3435.     else if (y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
  3436.       emacs_event->part = scroll_bar_handle;
  3437.     else
  3438.       emacs_event->part = scroll_bar_below_handle;
  3439.  
  3440.     /* Just because the user has clicked on the handle doesn't mean
  3441.        they want to drag it.  Lisp code needs to be able to decide
  3442.        whether or not we're dragging.  */
  3443. #if 0
  3444.     /* If the user has just clicked on the handle, record where they're
  3445.        holding it.  */
  3446.     if (event->type == ButtonPress
  3447.     && emacs_event->part == scroll_bar_handle)
  3448.       XSETINT (bar->dragging, y - XINT (bar->start));
  3449. #endif
  3450.  
  3451.     /* If the user has released the handle, set it to its final position.  */
  3452.     if (event->type == ButtonRelease
  3453.     && ! NILP (bar->dragging))
  3454.       {
  3455.     int new_start = y - XINT (bar->dragging);
  3456.     int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
  3457.  
  3458.     x_scroll_bar_set_handle (bar, new_start, new_end, 0);
  3459.     bar->dragging = Qnil;
  3460.       }
  3461.  
  3462.     /* Same deal here as the other #if 0.  */
  3463. #if 0
  3464.     /* Clicks on the handle are always reported as occurring at the top of
  3465.        the handle.  */
  3466.     if (emacs_event->part == scroll_bar_handle)
  3467.       emacs_event->x = bar->start;
  3468.     else
  3469.       XSETINT (emacs_event->x, y);
  3470. #else
  3471.     XSETINT (emacs_event->x, y);
  3472. #endif
  3473.  
  3474.     XSETINT (emacs_event->y, top_range);
  3475.   }
  3476. }
  3477.  
  3478. /* Handle some mouse motion while someone is dragging the scroll bar.
  3479.  
  3480.    This may be called from a signal handler, so we have to ignore GC
  3481.    mark bits.  */
  3482. static void
  3483. x_scroll_bar_note_movement (bar, event)
  3484.      struct scroll_bar *bar;
  3485.      XEvent *event;
  3486. {
  3487.   FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
  3488.  
  3489.   last_mouse_movement_time = event->xmotion.time;
  3490.  
  3491.   f->mouse_moved = 1;
  3492.   XSETVECTOR (last_mouse_scroll_bar, bar);
  3493.  
  3494.   /* If we're dragging the bar, display it.  */
  3495.   if (! GC_NILP (bar->dragging))
  3496.     {
  3497.       /* Where should the handle be now?  */
  3498.       int new_start = event->xmotion.y - XINT (bar->dragging);
  3499.  
  3500.       if (new_start != XINT (bar->start))
  3501.     {
  3502.       int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
  3503.  
  3504.       x_scroll_bar_set_handle (bar, new_start, new_end, 0);
  3505.     }
  3506.     }
  3507. }
  3508.  
  3509. /* Return information to the user about the current position of the mouse
  3510.    on the scroll bar.  */
  3511. static void
  3512. x_scroll_bar_report_motion (fp, bar_window, part, x, y, time)
  3513.      FRAME_PTR *fp;
  3514.      Lisp_Object *bar_window;
  3515.      enum scroll_bar_part *part;
  3516.      Lisp_Object *x, *y;
  3517.      unsigned long *time;
  3518. {
  3519.   struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
  3520.   Window w = SCROLL_BAR_X_WINDOW (bar);
  3521.   FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
  3522.   int win_x, win_y;
  3523.   Window dummy_window;
  3524.   int dummy_coord;
  3525.   unsigned int dummy_mask;
  3526.  
  3527.   BLOCK_INPUT;
  3528.  
  3529.   /* Get the mouse's position relative to the scroll bar window, and
  3530.      report that.  */
  3531.   if (! XQueryPointer (FRAME_X_DISPLAY (f), w,
  3532.  
  3533.                /* Root, child, root x and root y.  */
  3534.                &dummy_window, &dummy_window,
  3535.                &dummy_coord, &dummy_coord,
  3536.  
  3537.                /* Position relative to scroll bar.  */
  3538.                &win_x, &win_y,
  3539.  
  3540.                /* Mouse buttons and modifier keys.  */
  3541.                &dummy_mask))
  3542.     ;
  3543.   else
  3544.     {
  3545.       int inside_height
  3546.     = VERTICAL_SCROLL_BAR_INSIDE_HEIGHT (f, XINT (bar->height));
  3547.       int top_range
  3548.     = VERTICAL_SCROLL_BAR_TOP_RANGE     (f, XINT (bar->height));
  3549.  
  3550.       win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
  3551.  
  3552.       if (! NILP (bar->dragging))
  3553.     win_y -= XINT (bar->dragging);
  3554.  
  3555.       if (win_y < 0)
  3556.     win_y = 0;
  3557.       if (win_y > top_range)
  3558.     win_y = top_range;
  3559.  
  3560.       *fp = f;
  3561.       *bar_window = bar->window;
  3562.  
  3563.       if (! NILP (bar->dragging))
  3564.     *part = scroll_bar_handle;
  3565.       else if (win_y < XINT (bar->start))
  3566.     *part = scroll_bar_above_handle;
  3567.       else if (win_y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
  3568.     *part = scroll_bar_handle;
  3569.       else
  3570.     *part = scroll_bar_below_handle;
  3571.  
  3572.       XSETINT (*x, win_y);
  3573.       XSETINT (*y, top_range);
  3574.  
  3575.       f->mouse_moved = 0;
  3576.       last_mouse_scroll_bar = Qnil;
  3577.     }
  3578.  
  3579.   *time = last_mouse_movement_time;
  3580.  
  3581.   UNBLOCK_INPUT;
  3582. }
  3583.  
  3584.  
  3585. /* The screen has been cleared so we may have changed foreground or
  3586.    background colors, and the scroll bars may need to be redrawn.
  3587.    Clear out the scroll bars, and ask for expose events, so we can
  3588.    redraw them.  */
  3589.  
  3590. void
  3591. x_scroll_bar_clear (f)
  3592.      FRAME_PTR f;
  3593. {
  3594.   Lisp_Object bar;
  3595.  
  3596.   /* We can have scroll bars even if this is 0,
  3597.      if we just turned off scroll bar mode.
  3598.      But in that case we should not clear them.  */
  3599.   if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
  3600.     for (bar = FRAME_SCROLL_BARS (f); VECTORP (bar);
  3601.      bar = XSCROLL_BAR (bar)->next)
  3602.       XClearArea (FRAME_X_DISPLAY (f), SCROLL_BAR_X_WINDOW (XSCROLL_BAR (bar)),
  3603.           0, 0, 0, 0, True);
  3604. }
  3605.  
  3606. /* This processes Expose events from the menubar specific X event
  3607.    loop in xmenu.c.  This allows to redisplay the frame if necessary
  3608.    when handling menubar or popup items.  */
  3609.  
  3610. void
  3611. process_expose_from_menu (event)
  3612.      XEvent event;
  3613. {
  3614.   FRAME_PTR f;
  3615.   struct x_display_info *dpyinfo;
  3616.  
  3617.   BLOCK_INPUT;
  3618.  
  3619.   dpyinfo = x_display_info_for_display (event.xexpose.display);
  3620.   f = x_window_to_frame (dpyinfo, event.xexpose.window);
  3621.   if (f)
  3622.     {
  3623.       if (f->async_visible == 0)
  3624.     {
  3625.       f->async_visible = 1;
  3626.       f->async_iconified = 0;
  3627.       f->output_data.x->has_been_visible = 1;
  3628.       SET_FRAME_GARBAGED (f);
  3629.     }
  3630.       else
  3631.     {
  3632.       dumprectangle (x_window_to_frame (dpyinfo, event.xexpose.window),
  3633.              event.xexpose.x, event.xexpose.y,
  3634.              event.xexpose.width, event.xexpose.height);
  3635.     }
  3636.     }
  3637.   else
  3638.     {
  3639.       struct scroll_bar *bar
  3640.     = x_window_to_scroll_bar (event.xexpose.window);
  3641.  
  3642.       if (bar)
  3643.     x_scroll_bar_expose (bar, &event);
  3644.     }
  3645.  
  3646.   UNBLOCK_INPUT;
  3647. }
  3648.  
  3649. /* Define a queue to save up SelectionRequest events for later handling.  */
  3650.  
  3651. struct selection_event_queue
  3652.   {
  3653.     XEvent event;
  3654.     struct selection_event_queue *next;
  3655.   };
  3656.  
  3657. static struct selection_event_queue *queue;
  3658.  
  3659. /* Nonzero means queue up certain events--don't process them yet.  */
  3660. static int x_queue_selection_requests;
  3661.  
  3662. /* Queue up an X event *EVENT, to be processed later.  */
  3663.  
  3664. static void
  3665. x_queue_event (f, event)
  3666.      FRAME_PTR f;
  3667.      XEvent *event;
  3668. {
  3669.   struct selection_event_queue *queue_tmp
  3670.     = (struct selection_event_queue *) malloc (sizeof (struct selection_event_queue));
  3671.  
  3672.   if (queue_tmp != NULL)
  3673.     {
  3674.       queue_tmp->event = *event;
  3675.       queue_tmp->next = queue;
  3676.       queue = queue_tmp;
  3677.     }
  3678. }
  3679.  
  3680. /* Take all the queued events and put them back
  3681.    so that they get processed afresh.  */
  3682.  
  3683. static void
  3684. x_unqueue_events (display)
  3685.      Display *display;
  3686. {
  3687.   while (queue != NULL)
  3688.     {
  3689.       struct selection_event_queue *queue_tmp = queue;
  3690.       XPutBackEvent (display, &queue_tmp->event);
  3691.       queue = queue_tmp->next;
  3692.       free ((char *)queue_tmp);
  3693.     }
  3694. }
  3695.  
  3696. /* Start queuing SelectionRequest events.  */
  3697.  
  3698. void
  3699. x_start_queuing_selection_requests (display)
  3700.      Display *display;
  3701. {
  3702.   x_queue_selection_requests++;
  3703. }
  3704.  
  3705. /* Stop queuing SelectionRequest events.  */
  3706.  
  3707. void
  3708. x_stop_queuing_selection_requests (display)
  3709.      Display *display;
  3710. {
  3711.   x_queue_selection_requests--;
  3712.   x_unqueue_events (display);
  3713. }
  3714.  
  3715. /* The main X event-reading loop - XTread_socket.  */
  3716.  
  3717. /* Timestamp of enter window event.  This is only used by XTread_socket,
  3718.    but we have to put it out here, since static variables within functions
  3719.    sometimes don't work.  */
  3720. static Time enter_timestamp;
  3721.  
  3722. /* This holds the state XLookupString needs to implement dead keys
  3723.    and other tricks known as "compose processing".  _X Window System_
  3724.    says that a portable program can't use this, but Stephen Gildea assures
  3725.    me that letting the compiler initialize it to zeros will work okay.
  3726.  
  3727.    This must be defined outside of XTread_socket, for the same reasons
  3728.    given for enter_timestamp, above.  */
  3729. static XComposeStatus compose_status;
  3730.  
  3731. /* Record the last 100 characters stored
  3732.    to help debug the loss-of-chars-during-GC problem.  */
  3733. static int temp_index;
  3734. static short temp_buffer[100];
  3735.  
  3736. /* Set this to nonzero to fake an "X I/O error"
  3737.    on a particular display.  */
  3738. struct x_display_info *XTread_socket_fake_io_error;
  3739.  
  3740. /* When we find no input here, we occasionally do a no-op command
  3741.    to verify that the X server is still running and we can still talk with it.
  3742.    We try all the open displays, one by one.
  3743.    This variable is used for cycling thru the displays.  */
  3744. static struct x_display_info *next_noop_dpyinfo;
  3745.  
  3746. #define SET_SAVED_MENU_EVENT(size) { \
  3747.   if (f->output_data.x->saved_menu_event == 0) \
  3748.     f->output_data.x->saved_menu_event = (XEvent*)xmalloc (sizeof (XEvent)); \
  3749.   bcopy (&event, f->output_data.x->saved_menu_event, size); \
  3750.   if (numchars >= 1) \
  3751.     { \
  3752.       bufp->kind = menu_bar_activate_event; \
  3753.       XSETFRAME (bufp->frame_or_window, f); \
  3754.       bufp++; \
  3755.       count++; \
  3756.       numchars--; \
  3757.     } \
  3758.   }
  3759. #define SET_SAVED_BUTTON_EVENT SET_SAVED_MENU_EVENT (sizeof (XButtonEvent))
  3760. #define SET_SAVED_KEY_EVENT SET_SAVED_MENU_EVENT (sizeof (XKeyEvent))
  3761.  
  3762. /* Read events coming from the X server.
  3763.    This routine is called by the SIGIO handler.
  3764.    We return as soon as there are no more events to be read.
  3765.  
  3766.    Events representing keys are stored in buffer BUFP,
  3767.    which can hold up to NUMCHARS characters.
  3768.    We return the number of characters stored into the buffer,
  3769.    thus pretending to be `read'.
  3770.  
  3771.    EXPECTED is nonzero if the caller knows input is available.  */
  3772.  
  3773. int
  3774. XTread_socket (sd, bufp, numchars, expected)
  3775.      register int sd;
  3776.      /* register */ struct input_event *bufp;
  3777.      /* register */ int numchars;
  3778.      int expected;
  3779. {
  3780.   int count = 0;
  3781.   int nbytes = 0;
  3782.   int mask;
  3783.   int items_pending;        /* How many items are in the X queue. */
  3784.   XEvent event;
  3785.   struct frame *f;
  3786.   int event_found = 0;
  3787.   int prefix;
  3788.   Lisp_Object part;
  3789.   struct x_display_info *dpyinfo;
  3790. #ifdef HAVE_X_I18N
  3791.   Status status_return;
  3792. #endif
  3793.  
  3794.   if (interrupt_input_blocked)
  3795.     {
  3796.       interrupt_input_pending = 1;
  3797.       return -1;
  3798.     }
  3799.  
  3800.   interrupt_input_pending = 0;
  3801.   BLOCK_INPUT;
  3802.  
  3803.   /* So people can tell when we have read the available input.  */
  3804.   input_signal_count++;
  3805.  
  3806.   if (numchars <= 0)
  3807.     abort ();            /* Don't think this happens. */
  3808.  
  3809.   /* Find the display we are supposed to read input for.
  3810.      It's the one communicating on descriptor SD.  */
  3811.   for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
  3812.     {
  3813. #if 0 /* This ought to be unnecessary; let's verify it.  */
  3814. #ifdef FIOSNBIO
  3815.       /* If available, Xlib uses FIOSNBIO to make the socket
  3816.      non-blocking, and then looks for EWOULDBLOCK.  If O_NDELAY is set,
  3817.      FIOSNBIO is ignored, and instead of signaling EWOULDBLOCK,
  3818.      a read returns 0, which Xlib interprets as equivalent to EPIPE. */
  3819.       fcntl (dpyinfo->connection, F_SETFL, 0);
  3820. #endif /* ! defined (FIOSNBIO) */
  3821. #endif
  3822.  
  3823. #if 0 /* This code can't be made to work, with multiple displays,
  3824.      and appears not to be used on any system any more.
  3825.      Also keyboard.c doesn't turn O_NDELAY on and off
  3826.      for X connections.  */
  3827. #ifndef SIGIO
  3828. #ifndef HAVE_SELECT
  3829.       if (! (fcntl (dpyinfo->connection, F_GETFL, 0) & O_NDELAY))
  3830.     {
  3831.       extern int read_alarm_should_throw;
  3832.       read_alarm_should_throw = 1;
  3833.       XPeekEvent (dpyinfo->display, &event);
  3834.       read_alarm_should_throw = 0;
  3835.     }
  3836. #endif /* HAVE_SELECT */
  3837. #endif /* SIGIO */
  3838. #endif
  3839.  
  3840.       /* For debugging, this gives a way to fake an I/O error.  */
  3841.       if (dpyinfo == XTread_socket_fake_io_error)
  3842.     {
  3843.       XTread_socket_fake_io_error = 0;
  3844.       x_io_error_quitter (dpyinfo->display);
  3845.     }
  3846.  
  3847.       while (XPending (dpyinfo->display) != 0)
  3848.     {
  3849. #ifdef USE_X_TOOLKIT
  3850.           /* needed to raise Motif submenus */
  3851.       XtAppNextEvent (Xt_app_con, &event);
  3852. #else
  3853.       XNextEvent (dpyinfo->display, &event);
  3854. #endif
  3855. #ifdef HAVE_X_I18N
  3856.       {
  3857.         struct frame *f1 = x_any_window_to_frame (dpyinfo,
  3858.                               event.xclient.window);
  3859.         /* The necessity of the following line took me
  3860.            a full work-day to decipher from the docs!!  */
  3861.         if (f1 != 0 && FRAME_XIC (f1) && XFilterEvent (&event, None))
  3862.           break;
  3863.       }
  3864. #endif
  3865.       event_found = 1;
  3866.  
  3867.       switch (event.type)
  3868.         {
  3869.         case ClientMessage:
  3870.           {
  3871.         if (event.xclient.message_type
  3872.             == dpyinfo->Xatom_wm_protocols
  3873.             && event.xclient.format == 32)
  3874.           {
  3875.             if (event.xclient.data.l[0]
  3876.             == dpyinfo->Xatom_wm_take_focus)
  3877.               {
  3878.             /* Use x_any_window_to_frame because this
  3879.                could be the shell widget window
  3880.                if the frame has no title bar.  */
  3881.             f = x_any_window_to_frame (dpyinfo, event.xclient.window);
  3882. #ifdef HAVE_X_I18N
  3883.             /* Not quite sure this is needed -pd */
  3884.             if (f && FRAME_XIC (f))
  3885.               XSetICFocus (FRAME_XIC (f));
  3886. #endif
  3887.             /* Since we set WM_TAKE_FOCUS, we must call
  3888.                XSetInputFocus explicitly.  But not if f is null,
  3889.                since that might be an event for a deleted frame.  */
  3890.             if (f)
  3891.               {
  3892.                 Display *d = event.xclient.display;
  3893.                 /* Catch and ignore errors, in case window has been
  3894.                    iconified by a window manager such as GWM.  */
  3895.                 int count = x_catch_errors (d);
  3896.                 XSetInputFocus (d, event.xclient.window,
  3897.                         RevertToPointerRoot,
  3898.                         event.xclient.data.l[1]);
  3899.                 /* This is needed to detect the error
  3900.                    if there is an error.  */
  3901.                 XSync (d, False);
  3902.                 x_uncatch_errors (d, count);
  3903.               }  
  3904.             /* Not certain about handling scroll bars here */
  3905.               }
  3906.             else if (event.xclient.data.l[0]
  3907.                  == dpyinfo->Xatom_wm_save_yourself)
  3908.               {
  3909.             /* Save state modify the WM_COMMAND property to
  3910.                something which can reinstate us. This notifies
  3911.                the session manager, who's looking for such a
  3912.                PropertyNotify.  Can restart processing when
  3913.                a keyboard or mouse event arrives. */
  3914.             if (numchars > 0)
  3915.               {
  3916.                 f = x_top_window_to_frame (dpyinfo,
  3917.                                event.xclient.window);
  3918.  
  3919.                 /* This is just so we only give real data once
  3920.                    for a single Emacs process.  */
  3921.                 if (f == selected_frame)
  3922.                   XSetCommand (FRAME_X_DISPLAY (f),
  3923.                        event.xclient.window,
  3924.                        initial_argv, initial_argc);
  3925.                 else if (f)
  3926.                   XSetCommand (FRAME_X_DISPLAY (f),
  3927.                        event.xclient.window,
  3928.                        0, 0);
  3929.               }
  3930.               }
  3931.             else if (event.xclient.data.l[0]
  3932.                  == dpyinfo->Xatom_wm_delete_window)
  3933.               {
  3934.             struct frame *f
  3935.               = x_any_window_to_frame (dpyinfo,
  3936.                            event.xclient.window);
  3937.  
  3938.             if (f)
  3939.               {
  3940.                 if (numchars == 0)
  3941.                   abort ();
  3942.  
  3943.                 bufp->kind = delete_window_event;
  3944.                 XSETFRAME (bufp->frame_or_window, f);
  3945.                 bufp++;
  3946.  
  3947.                 count += 1;
  3948.                 numchars -= 1;
  3949.               }
  3950.               }
  3951.           }
  3952.         else if (event.xclient.message_type
  3953.              == dpyinfo->Xatom_wm_configure_denied)
  3954.           {
  3955.           }
  3956.         else if (event.xclient.message_type
  3957.              == dpyinfo->Xatom_wm_window_moved)
  3958.           {
  3959.             int new_x, new_y;
  3960.             struct frame *f
  3961.               = x_window_to_frame (dpyinfo, event.xclient.window);
  3962.  
  3963.             new_x = event.xclient.data.s[0];
  3964.             new_y = event.xclient.data.s[1];
  3965.  
  3966.             if (f)
  3967.               {
  3968.             f->output_data.x->left_pos = new_x;
  3969.             f->output_data.x->top_pos = new_y;
  3970.               }
  3971.           }
  3972. #ifdef HACK_EDITRES
  3973.         else if (event.xclient.message_type
  3974.              == dpyinfo->Xatom_editres)
  3975.           {
  3976.             struct frame *f
  3977.               = x_any_window_to_frame (dpyinfo, event.xclient.window);
  3978.             _XEditResCheckMessages (f->output_data.x->widget, NULL,
  3979.                         &event, NULL);
  3980.           }
  3981. #endif /* HACK_EDITRES */
  3982.           }
  3983.           break;
  3984.  
  3985.         case SelectionNotify:
  3986. #ifdef USE_X_TOOLKIT
  3987.           if (! x_window_to_frame (dpyinfo, event.xselection.requestor))
  3988.         goto OTHER;
  3989. #endif /* not USE_X_TOOLKIT */
  3990.           x_handle_selection_notify (&event.xselection);
  3991.           break;
  3992.  
  3993.         case SelectionClear:    /* Someone has grabbed ownership. */
  3994. #ifdef USE_X_TOOLKIT
  3995.           if (! x_window_to_frame (dpyinfo, event.xselectionclear.window))
  3996.         goto OTHER;
  3997. #endif /* USE_X_TOOLKIT */
  3998.           {
  3999.         XSelectionClearEvent *eventp = (XSelectionClearEvent *) &event;
  4000.  
  4001.         if (numchars == 0)
  4002.           abort ();
  4003.  
  4004.         bufp->kind = selection_clear_event;
  4005.         SELECTION_EVENT_DISPLAY (bufp) = eventp->display;
  4006.         SELECTION_EVENT_SELECTION (bufp) = eventp->selection;
  4007.         SELECTION_EVENT_TIME (bufp) = eventp->time;
  4008.         bufp->frame_or_window = Qnil;
  4009.         bufp++;
  4010.  
  4011.         count += 1;
  4012.         numchars -= 1;
  4013.           }
  4014.           break;
  4015.  
  4016.         case SelectionRequest:    /* Someone wants our selection. */
  4017. #ifdef USE_X_TOOLKIT
  4018.           if (!x_window_to_frame (dpyinfo, event.xselectionrequest.owner))
  4019.         goto OTHER;
  4020. #endif /* USE_X_TOOLKIT */
  4021.           if (x_queue_selection_requests)
  4022.         x_queue_event (x_window_to_frame (dpyinfo, event.xselectionrequest.owner),
  4023.                    &event);
  4024.           else
  4025.         {
  4026.           XSelectionRequestEvent *eventp = (XSelectionRequestEvent *) &event;
  4027.  
  4028.           if (numchars == 0)
  4029.             abort ();
  4030.  
  4031.           bufp->kind = selection_request_event;
  4032.           SELECTION_EVENT_DISPLAY (bufp) = eventp->display;
  4033.           SELECTION_EVENT_REQUESTOR (bufp) = eventp->requestor;
  4034.           SELECTION_EVENT_SELECTION (bufp) = eventp->selection;
  4035.           SELECTION_EVENT_TARGET (bufp) = eventp->target;
  4036.           SELECTION_EVENT_PROPERTY (bufp) = eventp->property;
  4037.           SELECTION_EVENT_TIME (bufp) = eventp->time;
  4038.           bufp->frame_or_window = Qnil;
  4039.           bufp++;
  4040.  
  4041.           count += 1;
  4042.           numchars -= 1;
  4043.         }
  4044.           break;
  4045.  
  4046.         case PropertyNotify:
  4047. #ifdef USE_X_TOOLKIT
  4048.           if (!x_any_window_to_frame (dpyinfo, event.xproperty.window))
  4049.         goto OTHER;
  4050. #endif /* not USE_X_TOOLKIT */
  4051.           x_handle_property_notify (&event.xproperty);
  4052.           break;
  4053.  
  4054.         case ReparentNotify:
  4055.           f = x_top_window_to_frame (dpyinfo, event.xreparent.window);
  4056.           if (f)
  4057.         {
  4058.           int x, y;
  4059.           f->output_data.x->parent_desc = event.xreparent.parent;
  4060.           x_real_positions (f, &x, &y);
  4061.           f->output_data.x->left_pos = x;
  4062.           f->output_data.x->top_pos = y;
  4063.         }
  4064.           break;
  4065.  
  4066.         case Expose:
  4067.           f = x_window_to_frame (dpyinfo, event.xexpose.window);
  4068.           if (f)
  4069.         {
  4070.           if (f->async_visible == 0)
  4071.             {
  4072.               f->async_visible = 1;
  4073.               f->async_iconified = 0;
  4074.               f->output_data.x->has_been_visible = 1;
  4075.               SET_FRAME_GARBAGED (f);
  4076.             }
  4077.           else
  4078.             dumprectangle (x_window_to_frame (dpyinfo,
  4079.                               event.xexpose.window),
  4080.                    event.xexpose.x, event.xexpose.y,
  4081.                    event.xexpose.width, event.xexpose.height);
  4082.         }
  4083.           else
  4084.         {
  4085.           struct scroll_bar *bar
  4086.             = x_window_to_scroll_bar (event.xexpose.window);
  4087.  
  4088.           if (bar)
  4089.             x_scroll_bar_expose (bar, &event);
  4090. #ifdef USE_X_TOOLKIT
  4091.           else
  4092.             goto OTHER;
  4093. #endif /* USE_X_TOOLKIT */
  4094.         }
  4095.           break;
  4096.  
  4097.         case GraphicsExpose:    /* This occurs when an XCopyArea's
  4098.                       source area was obscured or not
  4099.                       available.*/
  4100.           f = x_window_to_frame (dpyinfo, event.xgraphicsexpose.drawable);
  4101.           if (f)
  4102.         {
  4103.           dumprectangle (f,
  4104.                  event.xgraphicsexpose.x, event.xgraphicsexpose.y,
  4105.                  event.xgraphicsexpose.width,
  4106.                  event.xgraphicsexpose.height);
  4107.         }
  4108. #ifdef USE_X_TOOLKIT
  4109.           else
  4110.         goto OTHER;
  4111. #endif /* USE_X_TOOLKIT */
  4112.           break;
  4113.  
  4114.         case NoExpose:        /* This occurs when an XCopyArea's
  4115.                       source area was completely
  4116.                       available */
  4117.           break;
  4118.  
  4119.         case UnmapNotify:
  4120.           f = x_top_window_to_frame (dpyinfo, event.xunmap.window);
  4121.           if (f)        /* F may no longer exist if
  4122.                        the frame was deleted.  */
  4123.         {
  4124.           /* While a frame is unmapped, display generation is
  4125.              disabled; you don't want to spend time updating a
  4126.              display that won't ever be seen.  */
  4127.           f->async_visible = 0;
  4128.           /* We can't distinguish, from the event, whether the window
  4129.              has become iconified or invisible.  So assume, if it
  4130.              was previously visible, than now it is iconified.
  4131.              But x_make_frame_invisible clears both
  4132.              the visible flag and the iconified flag;
  4133.              and that way, we know the window is not iconified now.  */
  4134.           if (FRAME_VISIBLE_P (f) || FRAME_ICONIFIED_P (f))
  4135.             {
  4136.               f->async_iconified = 1;
  4137.  
  4138.               bufp->kind = iconify_event;
  4139.               XSETFRAME (bufp->frame_or_window, f);
  4140.               bufp++;
  4141.               count++;
  4142.               numchars--;
  4143.             }
  4144.         }
  4145.           goto OTHER;
  4146.  
  4147.         case MapNotify:
  4148.           /* We use x_top_window_to_frame because map events can come
  4149.          for subwindows and they don't mean that the frame is visible.  */
  4150.           f = x_top_window_to_frame (dpyinfo, event.xmap.window);
  4151.           if (f)
  4152.         {
  4153.           f->async_visible = 1;
  4154.           f->async_iconified = 0;
  4155.           f->output_data.x->has_been_visible = 1;
  4156.  
  4157.           /* wait_reading_process_input will notice this and update
  4158.              the frame's display structures.  */
  4159.           SET_FRAME_GARBAGED (f);
  4160.  
  4161.           if (f->iconified)
  4162.             {
  4163.               bufp->kind = deiconify_event;
  4164.               XSETFRAME (bufp->frame_or_window, f);
  4165.               bufp++;
  4166.               count++;
  4167.               numchars--;
  4168.             }
  4169.           else if (! NILP (Vframe_list)
  4170.                && ! NILP (XCONS (Vframe_list)->cdr))
  4171.             /* Force a redisplay sooner or later
  4172.                to update the frame titles
  4173.                in case this is the second frame.  */
  4174.             record_asynch_buffer_change ();
  4175.         }
  4176.           goto OTHER;
  4177.  
  4178.           /* Turn off processing if we become fully obscured. */
  4179.         case VisibilityNotify:
  4180.           break;
  4181.  
  4182.         case KeyPress:
  4183.           f = x_any_window_to_frame (dpyinfo, event.xkey.window);
  4184.  
  4185.           if (f != 0)
  4186.         {
  4187.           KeySym keysym, orig_keysym;
  4188.           /* al%imercury@uunet.uu.net says that making this 81 instead of
  4189.              80 fixed a bug whereby meta chars made his Emacs hang.  */
  4190.           unsigned char copy_buffer[81];
  4191.           int modifiers;
  4192.  
  4193. #if 0 /* This was how we made f10 work in Motif.
  4194.      The drawback is, you can't type at Emacs when the
  4195.      the mouse is in the menu bar.  So it is better to
  4196.      turn off f10 in Motif and let Emacs handle it.  */
  4197. #ifdef USE_MOTIF
  4198.                   if (lw_window_is_in_menubar (event.xkey.window,
  4199.                                                f->output_data.x->menubar_widget
  4200.                                                ))
  4201.                     {
  4202.                       SET_SAVED_KEY_EVENT;
  4203.                       break;
  4204.                     }
  4205. #endif /* USE_MOTIF */
  4206. #endif /* 0 */
  4207.  
  4208.           event.xkey.state
  4209.             |= x_emacs_to_x_modifiers (FRAME_X_DISPLAY_INFO (f),
  4210.                            extra_keyboard_modifiers);
  4211.           modifiers = event.xkey.state;
  4212.  
  4213.           /* This will have to go some day...  */
  4214.  
  4215.           /* make_lispy_event turns chars into control chars.
  4216.              Don't do it here because XLookupString is too eager.  */
  4217.           event.xkey.state &= ~ControlMask;
  4218.           event.xkey.state &= ~(dpyinfo->meta_mod_mask
  4219.                     | dpyinfo->super_mod_mask
  4220.                     | dpyinfo->hyper_mod_mask
  4221.                     | dpyinfo->alt_mod_mask);
  4222.  
  4223.           /* In case Meta is ComposeCharacter,
  4224.              clear its status.  According to Markus Ehrnsperger
  4225.              Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
  4226.              this enables ComposeCharacter to work whether or
  4227.              not it is combined with Meta.  */
  4228.           if (modifiers & dpyinfo->meta_mod_mask)
  4229.             bzero (&compose_status, sizeof (compose_status));
  4230.  
  4231. #ifdef HAVE_X_I18N
  4232.           if (FRAME_XIC (f))
  4233.             {
  4234.               /* The necessity of the following line took me
  4235.              a full work-day to decipher from the docs!!  */
  4236.               if (XFilterEvent (&event, None))
  4237.             break;
  4238.               nbytes = XmbLookupString (FRAME_XIC (f),
  4239.                         &event.xkey, copy_buffer,
  4240.                         80, &keysym,
  4241.                         &status_return);
  4242.             }
  4243.           else
  4244.             nbytes = XLookupString (&event.xkey, copy_buffer,
  4245.                         80, &keysym, &compose_status);
  4246. #else
  4247.           nbytes = XLookupString (&event.xkey, copy_buffer,
  4248.                       80, &keysym, &compose_status);
  4249. #endif
  4250.  
  4251.           orig_keysym = keysym;
  4252.  
  4253.           if (numchars > 1)
  4254.             {
  4255.               if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
  4256.                || keysym == XK_Delete
  4257. #ifdef XK_ISO_Left_Tab
  4258.                || (keysym >= XK_ISO_Left_Tab && keysym <= XK_ISO_Enter)
  4259. #endif
  4260.                || (keysym >= XK_Kanji && keysym <= XK_Eisu_toggle)
  4261.                || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
  4262.                || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
  4263. #ifdef HPUX
  4264.                /* This recognizes the "extended function keys".
  4265.                   It seems there's no cleaner way.
  4266.                   Test IsModifierKey to avoid handling mode_switch
  4267.                   incorrectly.  */
  4268.                || ((unsigned) (keysym) >= XK_Select
  4269.                    && (unsigned)(keysym) < XK_KP_Space)
  4270. #endif
  4271. #ifdef XK_dead_circumflex
  4272.                || orig_keysym == XK_dead_circumflex
  4273. #endif
  4274. #ifdef XK_dead_grave
  4275.                || orig_keysym == XK_dead_grave
  4276. #endif
  4277. #ifdef XK_dead_tilde
  4278.                || orig_keysym == XK_dead_tilde
  4279. #endif
  4280. #ifdef XK_dead_diaeresis
  4281.                || orig_keysym == XK_dead_diaeresis
  4282. #endif
  4283. #ifdef XK_dead_macron
  4284.                || orig_keysym == XK_dead_macron
  4285. #endif
  4286. #ifdef XK_dead_degree
  4287.                || orig_keysym == XK_dead_degree
  4288. #endif
  4289. #ifdef XK_dead_acute
  4290.                || orig_keysym == XK_dead_acute
  4291. #endif
  4292. #ifdef XK_dead_cedilla
  4293.                || orig_keysym == XK_dead_cedilla
  4294. #endif
  4295. #ifdef XK_dead_breve
  4296.                || orig_keysym == XK_dead_breve
  4297. #endif
  4298. #ifdef XK_dead_ogonek
  4299.                || orig_keysym == XK_dead_ogonek
  4300. #endif
  4301. #ifdef XK_dead_caron
  4302.                || orig_keysym == XK_dead_caron
  4303. #endif
  4304. #ifdef XK_dead_doubleacute
  4305.                || orig_keysym == XK_dead_doubleacute
  4306. #endif
  4307. #ifdef XK_dead_abovedot
  4308.                || orig_keysym == XK_dead_abovedot
  4309. #endif
  4310.                || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
  4311.                || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
  4312.                /* Any "vendor-specific" key is ok.  */
  4313.                || (orig_keysym & (1 << 28)))
  4314.               && ! (IsModifierKey (orig_keysym)
  4315. #ifndef HAVE_X11R5
  4316. #ifdef XK_Mode_switch
  4317.                 || ((unsigned)(orig_keysym) == XK_Mode_switch)
  4318. #endif
  4319. #ifdef XK_Num_Lock
  4320.                 || ((unsigned)(orig_keysym) == XK_Num_Lock)
  4321. #endif
  4322. #endif /* not HAVE_X11R5 */
  4323.                 ))
  4324.             {
  4325.               if (temp_index == sizeof temp_buffer / sizeof (short))
  4326.                 temp_index = 0;
  4327.               temp_buffer[temp_index++] = keysym;
  4328.               bufp->kind = non_ascii_keystroke;
  4329.               bufp->code = keysym;
  4330.               XSETFRAME (bufp->frame_or_window, f);
  4331.               bufp->modifiers
  4332.                 = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
  4333.                               modifiers);
  4334.               bufp->timestamp = event.xkey.time;
  4335.               bufp++;
  4336.               count++;
  4337.               numchars--;
  4338.             }
  4339.               else if (numchars > nbytes)
  4340.             {
  4341.               register int i;
  4342.  
  4343.               for (i = 0; i < nbytes; i++)
  4344.                 {
  4345.                   if (temp_index == sizeof temp_buffer / sizeof (short))
  4346.                 temp_index = 0;
  4347.                   temp_buffer[temp_index++] = copy_buffer[i];
  4348.                   bufp->kind = ascii_keystroke;
  4349.                   bufp->code = copy_buffer[i];
  4350.                   XSETFRAME (bufp->frame_or_window, f);
  4351.                   bufp->modifiers
  4352.                 = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
  4353.                               modifiers);
  4354.                   bufp->timestamp = event.xkey.time;
  4355.                   bufp++;
  4356.                 }
  4357.  
  4358.               count += nbytes;
  4359.               numchars -= nbytes;
  4360.             }
  4361.               else
  4362.             abort ();
  4363.             }
  4364.           else
  4365.             abort ();
  4366.         }
  4367.           goto OTHER;
  4368.  
  4369.           /* Here's a possible interpretation of the whole
  4370.          FocusIn-EnterNotify FocusOut-LeaveNotify mess.  If you get a
  4371.          FocusIn event, you have to get a FocusOut event before you
  4372.          relinquish the focus.  If you haven't received a FocusIn event,
  4373.          then a mere LeaveNotify is enough to free you.  */
  4374.  
  4375.         case EnterNotify:
  4376.           f = x_any_window_to_frame (dpyinfo, event.xcrossing.window);
  4377.  
  4378.           if (event.xcrossing.focus)        /* Entered Window */
  4379.         {
  4380.           /* Avoid nasty pop/raise loops. */
  4381.           if (f && (!(f->auto_raise)
  4382.                 || !(f->auto_lower)
  4383.                 || (event.xcrossing.time - enter_timestamp) > 500))
  4384.             {
  4385.               x_new_focus_frame (dpyinfo, f);
  4386.               enter_timestamp = event.xcrossing.time;
  4387.             }
  4388.         }
  4389.           else if (f == dpyinfo->x_focus_frame)
  4390.         x_new_focus_frame (dpyinfo, 0);
  4391.           /* EnterNotify counts as mouse movement,
  4392.          so update things that depend on mouse position.  */
  4393.           if (f)
  4394.         note_mouse_movement (f, &event.xmotion);
  4395.           goto OTHER;
  4396.  
  4397.         case FocusIn:
  4398.           f = x_any_window_to_frame (dpyinfo, event.xfocus.window);
  4399.           if (event.xfocus.detail != NotifyPointer)
  4400.         dpyinfo->x_focus_event_frame = f;
  4401.           if (f)
  4402.         x_new_focus_frame (dpyinfo, f);
  4403.  
  4404. #ifdef HAVE_X_I18N
  4405.           if (f && FRAME_XIC (f))
  4406.         XSetICFocus (FRAME_XIC (f));
  4407. #endif
  4408.  
  4409.           goto OTHER;
  4410.  
  4411.         case LeaveNotify:
  4412.           f = x_top_window_to_frame (dpyinfo, event.xcrossing.window);
  4413.           if (f)
  4414.         {
  4415.           if (f == dpyinfo->mouse_face_mouse_frame)
  4416.             /* If we move outside the frame,
  4417.                then we're certainly no longer on any text in the frame.  */
  4418.             clear_mouse_face (dpyinfo);
  4419.  
  4420.           if (event.xcrossing.focus)
  4421.             x_mouse_leave (dpyinfo);
  4422.           else
  4423.             {
  4424.               if (f == dpyinfo->x_focus_event_frame)
  4425.             dpyinfo->x_focus_event_frame = 0;
  4426.               if (f == dpyinfo->x_focus_frame)
  4427.             x_new_focus_frame (dpyinfo, 0);
  4428.             }
  4429.         }
  4430.           goto OTHER;
  4431.  
  4432.         case FocusOut:
  4433.           f = x_any_window_to_frame (dpyinfo, event.xfocus.window);
  4434.           if (event.xfocus.detail != NotifyPointer
  4435.           && f == dpyinfo->x_focus_event_frame)
  4436.         dpyinfo->x_focus_event_frame = 0;
  4437.           if (f && f == dpyinfo->x_focus_frame)
  4438.         x_new_focus_frame (dpyinfo, 0);
  4439.  
  4440. #ifdef HAVE_X_I18N
  4441.           if (f && FRAME_XIC (f))
  4442.         XUnsetICFocus (FRAME_XIC (f));
  4443. #endif
  4444.  
  4445.           goto OTHER;
  4446.  
  4447.         case MotionNotify:
  4448.           {
  4449.         if (dpyinfo->grabbed && last_mouse_frame
  4450.             && FRAME_LIVE_P (last_mouse_frame))
  4451.           f = last_mouse_frame;
  4452.         else
  4453.           f = x_window_to_frame (dpyinfo, event.xmotion.window);
  4454.         if (f)
  4455.           note_mouse_movement (f, &event.xmotion);
  4456.         else
  4457.           {
  4458.             struct scroll_bar *bar
  4459.               = x_window_to_scroll_bar (event.xmotion.window);
  4460.  
  4461.             if (bar)
  4462.               x_scroll_bar_note_movement (bar, &event);
  4463.  
  4464.             /* If we move outside the frame,
  4465.                then we're certainly no longer on any text in the frame.  */
  4466.             clear_mouse_face (dpyinfo);
  4467.           }
  4468.           }
  4469.           goto OTHER;
  4470.  
  4471.         case ConfigureNotify:
  4472.           f = x_top_window_to_frame (dpyinfo, event.xconfigure.window);
  4473.           if (f)
  4474.         {
  4475. #ifndef USE_X_TOOLKIT
  4476.           /* In the toolkit version, change_frame_size
  4477.              is called by the code that handles resizing
  4478.              of the EmacsFrame widget.  */
  4479.  
  4480.           int rows = PIXEL_TO_CHAR_HEIGHT (f, event.xconfigure.height);
  4481.           int columns = PIXEL_TO_CHAR_WIDTH (f, event.xconfigure.width);
  4482.  
  4483.           /* Even if the number of character rows and columns has
  4484.              not changed, the font size may have changed, so we need
  4485.              to check the pixel dimensions as well.  */
  4486.           if (columns != f->width
  4487.               || rows != f->height
  4488.               || event.xconfigure.width != f->output_data.x->pixel_width
  4489.               || event.xconfigure.height != f->output_data.x->pixel_height)
  4490.             {
  4491.               change_frame_size (f, rows, columns, 0, 1);
  4492.               SET_FRAME_GARBAGED (f);
  4493.               cancel_mouse_face (f);
  4494.             }
  4495. #endif
  4496.  
  4497.           f->output_data.x->pixel_width = event.xconfigure.width;
  4498.           f->output_data.x->pixel_height = event.xconfigure.height;
  4499.  
  4500.           /* What we have now is the position of Emacs's own window.
  4501.              Convert that to the position of the window manager window.  */
  4502.           x_real_positions (f, &f->output_data.x->left_pos,
  4503.                     &f->output_data.x->top_pos);
  4504.  
  4505.           if (f->output_data.x->parent_desc != FRAME_X_DISPLAY_INFO (f)->root_window)
  4506.             {
  4507.               /* Since the WM decorations come below top_pos now,
  4508.              we must put them below top_pos in the future.  */
  4509.               f->output_data.x->win_gravity = NorthWestGravity;
  4510.               x_wm_set_size_hint (f, (long) 0, 0);
  4511.             }
  4512. #ifdef USE_MOTIF
  4513.           /* Some window managers pass (0,0) as the location of
  4514.              the window, and the Motif event handler stores it
  4515.              in the emacs widget, which messes up Motif menus.  */
  4516.           if (event.xconfigure.x == 0 && event.xconfigure.y == 0)
  4517.             {
  4518.               event.xconfigure.x = f->output_data.x->widget->core.x;
  4519.               event.xconfigure.y = f->output_data.x->widget->core.y;
  4520.             }
  4521. #endif
  4522.         }
  4523.           goto OTHER;
  4524.  
  4525.         case ButtonPress:
  4526.         case ButtonRelease:
  4527.           {
  4528.         /* If we decide we want to generate an event to be seen
  4529.            by the rest of Emacs, we put it here.  */
  4530.         struct input_event emacs_event;
  4531.         emacs_event.kind = no_event;
  4532.  
  4533.         bzero (&compose_status, sizeof (compose_status));
  4534.  
  4535.         if (dpyinfo->grabbed && last_mouse_frame
  4536.             && FRAME_LIVE_P (last_mouse_frame))
  4537.           f = last_mouse_frame;
  4538.         else
  4539.           f = x_window_to_frame (dpyinfo, event.xbutton.window);
  4540.  
  4541.         if (f)
  4542.           {
  4543.             if (!dpyinfo->x_focus_frame || f == dpyinfo->x_focus_frame)
  4544.               construct_mouse_click (&emacs_event, &event, f);
  4545.           }
  4546.         else
  4547.           {
  4548.             struct scroll_bar *bar
  4549.               = x_window_to_scroll_bar (event.xbutton.window);
  4550.  
  4551.             if (bar)
  4552.               x_scroll_bar_handle_click (bar, &event, &emacs_event);
  4553.           }
  4554.  
  4555.         if (event.type == ButtonPress)
  4556.           {
  4557.             dpyinfo->grabbed |= (1 << event.xbutton.button);
  4558.             last_mouse_frame = f;
  4559.           }
  4560.         else
  4561.           {
  4562.             dpyinfo->grabbed &= ~(1 << event.xbutton.button);
  4563.           }
  4564.  
  4565.         if (numchars >= 1 && emacs_event.kind != no_event)
  4566.           {
  4567.             bcopy (&emacs_event, bufp, sizeof (struct input_event));
  4568.             bufp++;
  4569.             count++;
  4570.             numchars--;
  4571.           }
  4572.  
  4573. #ifdef USE_X_TOOLKIT
  4574.         f = x_menubar_window_to_frame (dpyinfo, event.xbutton.window);
  4575.         /* For a down-event in the menu bar,
  4576.            don't pass it to Xt right now.
  4577.            Instead, save it away
  4578.            and we will pass it to Xt from kbd_buffer_get_event.
  4579.            That way, we can run some Lisp code first.  */
  4580.         if (f && event.type == ButtonPress
  4581.             /* Verify the event is really within the menu bar
  4582.                and not just sent to it due to grabbing.  */
  4583.             && event.xbutton.x >= 0
  4584.             && event.xbutton.x < f->output_data.x->pixel_width
  4585.             && event.xbutton.y >= 0
  4586.             && event.xbutton.y < f->output_data.x->menubar_height
  4587.             && event.xbutton.same_screen)
  4588.           {
  4589.             SET_SAVED_BUTTON_EVENT;
  4590.             XSETFRAME (last_mouse_press_frame, f);
  4591.           }
  4592.         else if (event.type == ButtonPress)
  4593.           {
  4594.             last_mouse_press_frame = Qnil;
  4595.             goto OTHER;
  4596.           }
  4597. #ifdef USE_MOTIF /* This should do not harm for Lucid,
  4598.             but I am trying to be cautious.  */
  4599.         else if (event.type == ButtonRelease)
  4600.           {
  4601.             if (!NILP (last_mouse_press_frame))
  4602.               {
  4603.             f = XFRAME (last_mouse_press_frame);
  4604.             if (f->output_data.x)
  4605.               {
  4606.                 SET_SAVED_BUTTON_EVENT;
  4607.               }
  4608.               }
  4609.             else 
  4610.               goto OTHER;
  4611.           }
  4612. #endif /* USE_MOTIF */
  4613.         else
  4614.           goto OTHER;
  4615. #endif /* USE_X_TOOLKIT */
  4616.           }
  4617.           break;
  4618.  
  4619.         case CirculateNotify:
  4620.           break;
  4621.         case CirculateRequest:
  4622.           break;
  4623.  
  4624.         case MappingNotify:
  4625.           /* Someone has changed the keyboard mapping - update the
  4626.          local cache.  */
  4627.           switch (event.xmapping.request)
  4628.         {
  4629.         case MappingModifier:
  4630.           x_find_modifier_meanings (dpyinfo);
  4631.           /* This is meant to fall through.  */
  4632.         case MappingKeyboard:
  4633.           XRefreshKeyboardMapping (&event.xmapping);
  4634.         }
  4635.           goto OTHER;
  4636.  
  4637.         default:
  4638.         OTHER:
  4639. #ifdef USE_X_TOOLKIT
  4640.           BLOCK_INPUT;
  4641.           XtDispatchEvent (&event);
  4642.           UNBLOCK_INPUT;
  4643. #endif /* USE_X_TOOLKIT */
  4644.           break;
  4645.         }
  4646.     }
  4647.     }
  4648.  
  4649.   /* On some systems, an X bug causes Emacs to get no more events
  4650.      when the window is destroyed.  Detect that.  (1994.)  */
  4651.   if (! event_found)
  4652.     {
  4653.       /* Emacs and the X Server eats up CPU time if XNoOp is done every time.
  4654.      One XNOOP in 100 loops will make Emacs terminate.
  4655.      B. Bretthauer, 1994 */
  4656.       x_noop_count++;
  4657.       if (x_noop_count >= 100)
  4658.     {
  4659.       x_noop_count=0;
  4660.  
  4661.       if (next_noop_dpyinfo == 0)
  4662.         next_noop_dpyinfo = x_display_list;
  4663.  
  4664.       XNoOp (next_noop_dpyinfo->display);
  4665.  
  4666.       /* Each time we get here, cycle through the displays now open.  */
  4667.       next_noop_dpyinfo = next_noop_dpyinfo->next;
  4668.     }
  4669.     }
  4670.  
  4671.   /* If the focus was just given to an autoraising frame,
  4672.      raise it now.  */
  4673.   /* ??? This ought to be able to handle more than one such frame.  */
  4674.   if (pending_autoraise_frame)
  4675.     {
  4676.       x_raise_frame (pending_autoraise_frame);
  4677.       pending_autoraise_frame = 0;
  4678.     }
  4679.  
  4680.   UNBLOCK_INPUT;
  4681.   return count;
  4682. }
  4683.  
  4684. /* Drawing the cursor.  */
  4685.  
  4686.  
  4687. /* Draw a hollow box cursor on frame F at X, Y.
  4688.    Don't change the inside of the box.  */
  4689.  
  4690. static void
  4691. x_draw_box (f, x, y)
  4692.      struct frame *f;
  4693.      int x, y;
  4694. {
  4695.   int left = CHAR_TO_PIXEL_COL (f, x);
  4696.   int top  = CHAR_TO_PIXEL_ROW (f, y);
  4697.   int width = FONT_WIDTH (f->output_data.x->font);
  4698.   int height = f->output_data.x->line_height;
  4699.   int c = FAST_GLYPH_CHAR (f->phys_cursor_glyph);
  4700.   int charset = CHAR_CHARSET (c);
  4701.  
  4702.   XGCValues xgcv;
  4703.   unsigned long mask = GCForeground;
  4704.  
  4705.   xgcv.foreground = f->output_data.x->cursor_pixel;
  4706.  
  4707.   /* cursor_gc's foreground color is typically the same as the normal
  4708.      background color, which can cause the cursor box to be invisible.  */
  4709.   if (FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc)
  4710.     XChangeGC (FRAME_X_DISPLAY (f),
  4711.                FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc,
  4712.                mask, &xgcv);
  4713.   else
  4714.     FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc
  4715.       = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), mask, &xgcv);
  4716.  
  4717.   /* If cursor is on a multi-column character, multiply WIDTH by columns.  */
  4718.   width *= (charset == CHARSET_COMPOSITION
  4719.         ? cmpchar_table[COMPOSITE_CHAR_ID (c)]->width
  4720.         : CHARSET_WIDTH (charset));
  4721.   XDrawRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  4722.                   FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc,
  4723.           left, top, width - 1, height - 1);
  4724. }
  4725.  
  4726. /* Clear the cursor of frame F to background color,
  4727.    and mark the cursor as not shown.
  4728.    This is used when the text where the cursor is
  4729.    is about to be rewritten.  */
  4730.  
  4731. static void
  4732. clear_cursor (f)
  4733.      struct frame *f;
  4734. {
  4735.   int mask;
  4736.  
  4737.   if (! FRAME_VISIBLE_P (f)
  4738.       || ! f->phys_cursor_on)
  4739.     return;
  4740.  
  4741.   x_update_cursor (f, 0);
  4742.   f->phys_cursor_on = 0;
  4743. }
  4744.  
  4745. /* Redraw the glyph at ROW, COLUMN on frame F, in the style
  4746.    HIGHLIGHT.  HIGHLIGHT is as defined for dumpglyphs.  Return the
  4747.    glyph drawn.  */
  4748.  
  4749. static void
  4750. x_draw_single_glyph (f, row, column, glyph, highlight)
  4751.      struct frame *f;
  4752.      int row, column;
  4753.      GLYPH glyph;
  4754.      int highlight;
  4755. {
  4756.   dumpglyphs (f,
  4757.           CHAR_TO_PIXEL_COL (f, column),
  4758.           CHAR_TO_PIXEL_ROW (f, row),
  4759.           &glyph, 1, highlight, 0, NULL);
  4760. }
  4761.  
  4762. static void
  4763. x_display_bar_cursor (f, on, x, y)
  4764.      struct frame *f;
  4765.      int on;
  4766.      int x, y;
  4767. {
  4768.   struct frame_glyphs *current_glyphs = FRAME_CURRENT_GLYPHS (f);
  4769.  
  4770.   /* This is pointless on invisible frames, and dangerous on garbaged
  4771.      frames; in the latter case, the frame may be in the midst of
  4772.      changing its size, and x and y may be off the frame.  */
  4773.   if (! FRAME_VISIBLE_P (f) || FRAME_GARBAGED_P (f))
  4774.     return;
  4775.  
  4776.   if (! on && ! f->phys_cursor_on)
  4777.     return;
  4778.  
  4779.   /* If there is anything wrong with the current cursor state, remove it.  */
  4780.   if (f->phys_cursor_on
  4781.       && (!on
  4782.       || f->phys_cursor_x != x
  4783.       || f->phys_cursor_y != y
  4784.       || f->output_data.x->current_cursor != bar_cursor))
  4785.     {
  4786.       /* Erase the cursor by redrawing the character underneath it.  */
  4787.       x_draw_single_glyph (f, f->phys_cursor_y, f->phys_cursor_x,
  4788.                f->phys_cursor_glyph,
  4789.                current_glyphs->highlight[f->phys_cursor_y]);
  4790.       f->phys_cursor_on = 0;
  4791.     }
  4792.  
  4793.   /* If we now need a cursor in the new place or in the new form, do it so.  */
  4794.   if (on
  4795.       && (! f->phys_cursor_on
  4796.       || (f->output_data.x->current_cursor != bar_cursor)))
  4797.     {
  4798.       f->phys_cursor_glyph
  4799.     = ((current_glyphs->enable[y]
  4800.         && x < current_glyphs->used[y])
  4801.        ? current_glyphs->glyphs[y][x]
  4802.        : SPACEGLYPH);
  4803.       XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  4804.               f->output_data.x->cursor_gc,
  4805.               CHAR_TO_PIXEL_COL (f, x),
  4806.               CHAR_TO_PIXEL_ROW (f, y),
  4807.               max (f->output_data.x->cursor_width, 1),
  4808.               f->output_data.x->line_height);
  4809.  
  4810.       f->phys_cursor_x = x;
  4811.       f->phys_cursor_y = y;
  4812.       f->phys_cursor_on = 1;
  4813.  
  4814.       f->output_data.x->current_cursor = bar_cursor;
  4815.     }
  4816.  
  4817.   if (updating_frame != f)
  4818.     XFlush (FRAME_X_DISPLAY (f));
  4819. }
  4820.  
  4821.  
  4822. /* Turn the displayed cursor of frame F on or off according to ON.
  4823.    If ON is nonzero, where to put the cursor is specified by X and Y.  */
  4824.  
  4825. static void
  4826. x_display_box_cursor (f, on, x, y)
  4827.      struct frame *f;
  4828.      int on;
  4829.      int x, y;
  4830. {
  4831.   struct frame_glyphs *current_glyphs = FRAME_CURRENT_GLYPHS (f);
  4832.  
  4833.   /* This is pointless on invisible frames, and dangerous on garbaged
  4834.      frames; in the latter case, the frame may be in the midst of
  4835.      changing its size, and x and y may be off the frame.  */
  4836.   if (! FRAME_VISIBLE_P (f) || FRAME_GARBAGED_P (f))
  4837.     return;
  4838.  
  4839.   /* If cursor is off and we want it off, return quickly.  */
  4840.   if (!on && ! f->phys_cursor_on)
  4841.     return;
  4842.  
  4843.   /* If cursor is currently being shown and we don't want it to be
  4844.      or it is in the wrong place,
  4845.      or we want a hollow box and it's not so, (pout!)
  4846.      erase it.  */
  4847.   if (f->phys_cursor_on
  4848.       && (!on
  4849.       || f->phys_cursor_x != x
  4850.       || f->phys_cursor_y != y
  4851.       || (f->output_data.x->current_cursor != hollow_box_cursor
  4852.           && (f != FRAME_X_DISPLAY_INFO (f)->x_highlight_frame))))
  4853.     {
  4854.       int mouse_face_here = 0;
  4855.       struct frame_glyphs *active_glyphs = FRAME_CURRENT_GLYPHS (f);
  4856.  
  4857.       /* If the cursor is in the mouse face area, redisplay that when
  4858.      we clear the cursor.  */
  4859.       if (f == FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_frame
  4860.       &&
  4861.       (f->phys_cursor_y > FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_row
  4862.        || (f->phys_cursor_y == FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_row
  4863.            && f->phys_cursor_x >= FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_col))
  4864.       &&
  4865.       (f->phys_cursor_y < FRAME_X_DISPLAY_INFO (f)->mouse_face_end_row
  4866.        || (f->phys_cursor_y == FRAME_X_DISPLAY_INFO (f)->mouse_face_end_row
  4867.            && f->phys_cursor_x < FRAME_X_DISPLAY_INFO (f)->mouse_face_end_col))
  4868.       /* Don't redraw the cursor's spot in mouse face
  4869.          if it is at the end of a line (on a newline).
  4870.          The cursor appears there, but mouse highlighting does not.  */
  4871.       && active_glyphs->used[f->phys_cursor_y] > f->phys_cursor_x)
  4872.     mouse_face_here = 1;
  4873.  
  4874.       /* If the font is not as tall as a whole line,
  4875.      we must explicitly clear the line's whole height.  */
  4876.       if (FONT_HEIGHT (f->output_data.x->font) != f->output_data.x->line_height)
  4877.     XClearArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  4878.             CHAR_TO_PIXEL_COL (f, f->phys_cursor_x),
  4879.             CHAR_TO_PIXEL_ROW (f, f->phys_cursor_y),
  4880.             FONT_WIDTH (f->output_data.x->font),
  4881.             f->output_data.x->line_height, False);
  4882.       /* Erase the cursor by redrawing the character underneath it.  */
  4883.       x_draw_single_glyph (f, f->phys_cursor_y, f->phys_cursor_x,
  4884.                f->phys_cursor_glyph,
  4885.                (mouse_face_here
  4886.                 ? 3
  4887.                 : current_glyphs->highlight[f->phys_cursor_y]));
  4888.       f->phys_cursor_on = 0;
  4889.     }
  4890.  
  4891.   /* If we want to show a cursor,
  4892.      or we want a box cursor and it's not so,
  4893.      write it in the right place.  */
  4894.   if (on
  4895.       && (! f->phys_cursor_on
  4896.       || (f->output_data.x->current_cursor != filled_box_cursor
  4897.           && f == FRAME_X_DISPLAY_INFO (f)->x_highlight_frame)))
  4898.     {
  4899.       f->phys_cursor_glyph
  4900.     = ((current_glyphs->enable[y]
  4901.         && x < current_glyphs->used[y])
  4902.        ? current_glyphs->glyphs[y][x]
  4903.        : SPACEGLYPH);
  4904.       if (f != FRAME_X_DISPLAY_INFO (f)->x_highlight_frame)
  4905.     {
  4906.       x_draw_box (f, x, y);
  4907.       f->output_data.x->current_cursor = hollow_box_cursor;
  4908.     }
  4909.       else
  4910.     {
  4911.       x_draw_single_glyph (f, y, x,
  4912.                    f->phys_cursor_glyph, 2);
  4913.       f->output_data.x->current_cursor = filled_box_cursor;
  4914.     }
  4915.  
  4916.       f->phys_cursor_x = x;
  4917.       f->phys_cursor_y = y;
  4918.       f->phys_cursor_on = 1;
  4919.     }
  4920.  
  4921.   if (updating_frame != f)
  4922.     XFlush (FRAME_X_DISPLAY (f));
  4923. }
  4924.  
  4925. /* Display the cursor on frame F, or clear it, according to ON.
  4926.    Also set the frame's cursor position to X and Y.  */
  4927.  
  4928. void
  4929. x_display_cursor (f, on, x, y)
  4930.      struct frame *f;
  4931.      int on;
  4932.      int x, y;
  4933. {
  4934.   BLOCK_INPUT;
  4935.  
  4936.  if ((unsigned) x >= FRAME_CURSOR_X_LIMIT (f)
  4937.       || (unsigned) y >= FRAME_HEIGHT (f))
  4938.     abort ();
  4939.  
  4940.   if (FRAME_DESIRED_CURSOR (f) == filled_box_cursor)
  4941.     x_display_box_cursor (f, on, x, y);
  4942.   else if (FRAME_DESIRED_CURSOR (f) == bar_cursor)
  4943.     x_display_bar_cursor (f, on, x, y);
  4944.   else
  4945.     /* Those are the only two we have implemented!  */
  4946.     abort ();
  4947.  
  4948.   UNBLOCK_INPUT;
  4949. }
  4950.  
  4951. /* Display the cursor on frame F, or clear it, according to ON.
  4952.    Don't change the cursor's position.  */
  4953.  
  4954. void
  4955. x_update_cursor (f, on)
  4956.      struct frame *f;
  4957.      int on;
  4958. {
  4959.   BLOCK_INPUT;
  4960.  
  4961.   if (FRAME_DESIRED_CURSOR (f) == filled_box_cursor)
  4962.     x_display_box_cursor (f, on, f->phys_cursor_x, f->phys_cursor_y);
  4963.   else if (FRAME_DESIRED_CURSOR (f) == bar_cursor)
  4964.     x_display_bar_cursor (f, on, f->phys_cursor_x, f->phys_cursor_y);
  4965.   else
  4966.     /* Those are the only two we have implemented!  */
  4967.     abort ();
  4968.  
  4969.   UNBLOCK_INPUT;
  4970. }
  4971.  
  4972. /* Icons.  */
  4973.  
  4974. /* Refresh bitmap kitchen sink icon for frame F
  4975.    when we get an expose event for it. */
  4976.  
  4977. void
  4978. refreshicon (f)
  4979.      struct frame *f;
  4980. {
  4981.   /* Normally, the window manager handles this function. */
  4982. }
  4983.  
  4984. /* Make the x-window of frame F use the gnu icon bitmap.  */
  4985.  
  4986. int
  4987. x_bitmap_icon (f, file)
  4988.      struct frame *f;
  4989.      Lisp_Object file;
  4990. {
  4991.   int mask, bitmap_id;
  4992.   Window icon_window;
  4993.  
  4994.   if (FRAME_X_WINDOW (f) == 0)
  4995.     return 1;
  4996.  
  4997.   /* Free up our existing icon bitmap if any.  */
  4998.   if (f->output_data.x->icon_bitmap > 0)
  4999.     x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
  5000.   f->output_data.x->icon_bitmap = 0;
  5001.  
  5002.   if (STRINGP (file))
  5003.     bitmap_id = x_create_bitmap_from_file (f, file);
  5004.   else
  5005.     {
  5006.       /* Create the GNU bitmap if necessary.  */
  5007.       if (FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id < 0)
  5008.     FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id
  5009.       = x_create_bitmap_from_data (f, gnu_bits,
  5010.                        gnu_width, gnu_height);
  5011.  
  5012.       /* The first time we create the GNU bitmap,
  5013.      this increments the refcount one extra time.
  5014.      As a result, the GNU bitmap is never freed.
  5015.      That way, we don't have to worry about allocating it again.  */
  5016.       x_reference_bitmap (f, FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id);
  5017.  
  5018.       bitmap_id = FRAME_X_DISPLAY_INFO (f)->icon_bitmap_id;
  5019.     }
  5020.  
  5021.   x_wm_set_icon_pixmap (f, bitmap_id);
  5022.   f->output_data.x->icon_bitmap = bitmap_id;
  5023.  
  5024.   return 0;
  5025. }
  5026.  
  5027.  
  5028. /* Make the x-window of frame F use a rectangle with text.
  5029.    Use ICON_NAME as the text.  */
  5030.  
  5031. int
  5032. x_text_icon (f, icon_name)
  5033.      struct frame *f;
  5034.      char *icon_name;
  5035. {
  5036.   if (FRAME_X_WINDOW (f) == 0)
  5037.     return 1;
  5038.  
  5039. #ifdef HAVE_X11R4
  5040.   {
  5041.     XTextProperty text;
  5042.     text.value = (unsigned char *) icon_name;
  5043.     text.encoding = XA_STRING;
  5044.     text.format = 8;
  5045.     text.nitems = strlen (icon_name);
  5046. #ifdef USE_X_TOOLKIT
  5047.     XSetWMIconName (FRAME_X_DISPLAY (f), XtWindow (f->output_data.x->widget),
  5048.             &text);
  5049. #else /* not USE_X_TOOLKIT */
  5050.     XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), &text);
  5051. #endif /* not USE_X_TOOLKIT */
  5052.   }
  5053. #else /* not HAVE_X11R4 */
  5054.   XSetIconName (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), icon_name);
  5055. #endif /* not HAVE_X11R4 */
  5056.  
  5057.   if (f->output_data.x->icon_bitmap > 0)
  5058.     x_destroy_bitmap (f, f->output_data.x->icon_bitmap);
  5059.   f->output_data.x->icon_bitmap = 0;
  5060.   x_wm_set_icon_pixmap (f, 0);
  5061.  
  5062.   return 0;
  5063. }
  5064.  
  5065. #define X_ERROR_MESSAGE_SIZE 200
  5066.  
  5067. /* If non-nil, this should be a string.
  5068.    It means catch X errors  and store the error message in this string.  */
  5069.  
  5070. static Lisp_Object x_error_message_string;
  5071.  
  5072. /* An X error handler which stores the error message in
  5073.    x_error_message_string.  This is called from x_error_handler if
  5074.    x_catch_errors is in effect.  */
  5075.  
  5076. static int
  5077. x_error_catcher (display, error)
  5078.      Display *display;
  5079.      XErrorEvent *error;
  5080. {
  5081.   XGetErrorText (display, error->error_code,
  5082.          XSTRING (x_error_message_string)->data,
  5083.          X_ERROR_MESSAGE_SIZE);
  5084. }
  5085.  
  5086. /* Begin trapping X errors for display DPY.  Actually we trap X errors
  5087.    for all displays, but DPY should be the display you are actually
  5088.    operating on.
  5089.  
  5090.    After calling this function, X protocol errors no longer cause
  5091.    Emacs to exit; instead, they are recorded in the string
  5092.    stored in x_error_message_string.
  5093.  
  5094.    Calling x_check_errors signals an Emacs error if an X error has
  5095.    occurred since the last call to x_catch_errors or x_check_errors.
  5096.  
  5097.    Calling x_uncatch_errors resumes the normal error handling.  */
  5098.  
  5099. void x_check_errors ();
  5100. static Lisp_Object x_catch_errors_unwind ();
  5101.  
  5102. int
  5103. x_catch_errors (dpy)
  5104.      Display *dpy;
  5105. {
  5106.   int count = specpdl_ptr - specpdl;
  5107.  
  5108.   /* Make sure any errors from previous requests have been dealt with.  */
  5109.   XSync (dpy, False);
  5110.  
  5111.   record_unwind_protect (x_catch_errors_unwind, x_error_message_string);
  5112.  
  5113.   x_error_message_string = make_uninit_string (X_ERROR_MESSAGE_SIZE);
  5114.   XSTRING (x_error_message_string)->data[0] = 0;
  5115.  
  5116.   return count;
  5117. }
  5118.  
  5119. /* Unbind the binding that we made to check for X errors.  */
  5120.  
  5121. static Lisp_Object
  5122. x_catch_errors_unwind (old_val)
  5123.      Lisp_Object old_val;
  5124. {
  5125.   x_error_message_string = old_val;
  5126.   return Qnil;
  5127. }
  5128.  
  5129. /* If any X protocol errors have arrived since the last call to
  5130.    x_catch_errors or x_check_errors, signal an Emacs error using
  5131.    sprintf (a buffer, FORMAT, the x error message text) as the text.  */
  5132.  
  5133. void
  5134. x_check_errors (dpy, format)
  5135.      Display *dpy;
  5136.      char *format;
  5137. {
  5138.   /* Make sure to catch any errors incurred so far.  */
  5139.   XSync (dpy, False);
  5140.  
  5141.   if (XSTRING (x_error_message_string)->data[0])
  5142.     error (format, XSTRING (x_error_message_string)->data);
  5143. }
  5144.  
  5145. /* Nonzero if we had any X protocol errors
  5146.    since we did x_catch_errors on DPY.  */
  5147.  
  5148. int
  5149. x_had_errors_p (dpy)
  5150.      Display *dpy;
  5151. {
  5152.   /* Make sure to catch any errors incurred so far.  */
  5153.   XSync (dpy, False);
  5154.  
  5155.   return XSTRING (x_error_message_string)->data[0] != 0;
  5156. }
  5157.  
  5158. /* Forget about any errors we have had, since we did x_catch_errors on DPY.  */
  5159.  
  5160. int
  5161. x_clear_errors (dpy)
  5162.      Display *dpy;
  5163. {
  5164.   XSTRING (x_error_message_string)->data[0] = 0;
  5165. }
  5166.  
  5167. /* Stop catching X protocol errors and let them make Emacs die.
  5168.    DPY should be the display that was passed to x_catch_errors.
  5169.    COUNT should be the value that was returned by
  5170.    the corresponding call to x_catch_errors.  */
  5171.  
  5172. void
  5173. x_uncatch_errors (dpy, count)
  5174.      Display *dpy;
  5175.      int count;
  5176. {
  5177.   unbind_to (count, Qnil);
  5178. }
  5179.  
  5180. #if 0
  5181. static unsigned int x_wire_count;
  5182. x_trace_wire ()
  5183. {
  5184.   fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
  5185. }
  5186. #endif /* ! 0 */
  5187.  
  5188.  
  5189. /* Handle SIGPIPE, which can happen when the connection to a server
  5190.    simply goes away.  SIGPIPE is handled by x_connection_signal.
  5191.    Don't need to do anything, because the write which caused the 
  5192.    SIGPIPE will fail, causing Xlib to invoke the X IO error handler,
  5193.    which will do the appropriate cleanup for us. */
  5194.    
  5195. static SIGTYPE
  5196. x_connection_signal (signalnum)    /* If we don't have an argument, */
  5197.      int signalnum;        /* some compilers complain in signal calls. */
  5198. {
  5199. #ifdef USG
  5200.   /* USG systems forget handlers when they are used;
  5201.      must reestablish each time */
  5202.   signal (signalnum, x_connection_signal);
  5203. #endif /* USG */
  5204. }
  5205.  
  5206. /* Handling X errors.  */
  5207.  
  5208. /* Handle the loss of connection to display DISPLAY.  */
  5209.  
  5210. static SIGTYPE
  5211. x_connection_closed (display, error_message)
  5212.      Display *display;
  5213.      char *error_message;
  5214. {
  5215.   struct x_display_info *dpyinfo = x_display_info_for_display (display);
  5216.   Lisp_Object frame, tail;
  5217.  
  5218.   /* Indicate that this display is dead.  */
  5219.  
  5220. #ifdef USE_X_TOOLKIT
  5221.   XtCloseDisplay (display);
  5222. #endif
  5223.  
  5224.   dpyinfo->display = 0;
  5225.  
  5226.   /* First delete frames whose minibuffers are on frames
  5227.      that are on the dead display.  */
  5228.   FOR_EACH_FRAME (tail, frame)
  5229.     {
  5230.       Lisp_Object minibuf_frame;
  5231.       minibuf_frame
  5232.     = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
  5233.       if (FRAME_X_P (XFRAME (frame))
  5234.       && FRAME_X_P (XFRAME (minibuf_frame))
  5235.       && ! EQ (frame, minibuf_frame)
  5236.       && FRAME_X_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
  5237.     Fdelete_frame (frame, Qt);
  5238.     }
  5239.  
  5240.   /* Now delete all remaining frames on the dead display.
  5241.      We are now sure none of these is used as the minibuffer
  5242.      for another frame that we need to delete.  */
  5243.   FOR_EACH_FRAME (tail, frame)
  5244.     if (FRAME_X_P (XFRAME (frame))
  5245.     && FRAME_X_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
  5246.       {
  5247.     /* Set this to t so that Fdelete_frame won't get confused
  5248.        trying to find a replacement.  */
  5249.     FRAME_KBOARD (XFRAME (frame))->Vdefault_minibuffer_frame = Qt;
  5250.     Fdelete_frame (frame, Qt);
  5251.       }
  5252.  
  5253.   if (dpyinfo)
  5254.     x_delete_display (dpyinfo);
  5255.  
  5256.   if (x_display_list == 0)
  5257.     {
  5258.       fprintf (stderr, "%s\n", error_message);
  5259.       shut_down_emacs (0, 0, Qnil);
  5260.       exit (70);
  5261.     }
  5262.  
  5263.   /* Ordinary stack unwind doesn't deal with these.  */
  5264. #ifdef SIGIO
  5265.   sigunblock (sigmask (SIGIO));
  5266. #endif
  5267.   sigunblock (sigmask (SIGALRM));
  5268.   TOTALLY_UNBLOCK_INPUT;
  5269.  
  5270.   clear_waiting_for_input ();
  5271.   error ("%s", error_message);
  5272. }
  5273.  
  5274. /* This is the usual handler for X protocol errors.
  5275.    It kills all frames on the display that we got the error for.
  5276.    If that was the only one, it prints an error message and kills Emacs.  */
  5277.  
  5278. static int
  5279. x_error_quitter (display, error)
  5280.      Display *display;
  5281.      XErrorEvent *error;
  5282. {
  5283.   char buf[256], buf1[356];
  5284.  
  5285.   /* Note that there is no real way portable across R3/R4 to get the
  5286.      original error handler.  */
  5287.  
  5288.   XGetErrorText (display, error->error_code, buf, sizeof (buf));
  5289.   sprintf (buf1, "X protocol error: %s on protocol request %d",
  5290.        buf, error->request_code);
  5291.   x_connection_closed (display, buf1);
  5292. }
  5293.  
  5294. /* This is the first-level handler for X protocol errors.
  5295.    It calls x_error_quitter or x_error_catcher.  */
  5296.  
  5297. static int
  5298. x_error_handler (display, error)
  5299.      Display *display;
  5300.      XErrorEvent *error;
  5301. {
  5302.   char buf[256], buf1[356];
  5303.  
  5304.   if (! NILP (x_error_message_string))
  5305.     x_error_catcher (display, error);
  5306.   else
  5307.     x_error_quitter (display, error);
  5308. }
  5309.  
  5310. /* This is the handler for X IO errors, always.
  5311.    It kills all frames on the display that we lost touch with.
  5312.    If that was the only one, it prints an error message and kills Emacs.  */
  5313.  
  5314. static int
  5315. x_io_error_quitter (display)
  5316.      Display *display;
  5317. {
  5318.   char buf[256];
  5319.  
  5320.   sprintf (buf, "Connection lost to X server `%s'", DisplayString (display));
  5321.   x_connection_closed (display, buf);
  5322. }
  5323.  
  5324. /* Changing the font of the frame.  */
  5325.  
  5326. /* Give frame F the font named FONTNAME as its default font, and
  5327.    return the full name of that font.  FONTNAME may be a wildcard
  5328.    pattern; in that case, we choose some font that fits the pattern.
  5329.    The return value shows which font we chose.  */
  5330.  
  5331. Lisp_Object
  5332. x_new_font (f, fontname)
  5333.      struct frame *f;
  5334.      register char *fontname;
  5335. {
  5336.   struct font_info *fontp
  5337.     = fs_load_font (f, FRAME_X_FONT_TABLE (f), CHARSET_ASCII, fontname, -1);
  5338.  
  5339.   if (!fontp)
  5340.     return Qnil;
  5341.  
  5342.   f->output_data.x->font = (XFontStruct *) (fontp->font);
  5343.   f->output_data.x->font_baseline
  5344.     = (f->output_data.x->font->ascent + fontp->baseline_offset);
  5345.   f->output_data.x->fontset = -1;
  5346.   
  5347.   /* Compute the scroll bar width in character columns.  */
  5348.   if (f->scroll_bar_pixel_width > 0)
  5349.     {
  5350.       int wid = FONT_WIDTH (f->output_data.x->font);
  5351.       f->scroll_bar_cols = (f->scroll_bar_pixel_width + wid-1) / wid;
  5352.     }
  5353.   else
  5354.     {
  5355.       int wid = FONT_WIDTH (f->output_data.x->font);
  5356.       f->scroll_bar_cols = (14 + wid - 1) / wid;
  5357.     }
  5358.  
  5359.   /* Now make the frame display the given font.  */
  5360.   if (FRAME_X_WINDOW (f) != 0)
  5361.     {
  5362.       XSetFont (FRAME_X_DISPLAY (f), f->output_data.x->normal_gc,
  5363.         f->output_data.x->font->fid);
  5364.       XSetFont (FRAME_X_DISPLAY (f), f->output_data.x->reverse_gc,
  5365.         f->output_data.x->font->fid);
  5366.       XSetFont (FRAME_X_DISPLAY (f), f->output_data.x->cursor_gc,
  5367.         f->output_data.x->font->fid);
  5368.  
  5369.       frame_update_line_height (f);
  5370.       x_set_window_size (f, 0, f->width, f->height);
  5371.     }
  5372.   else
  5373.     /* If we are setting a new frame's font for the first time,
  5374.        there are no faces yet, so this font's height is the line height.  */
  5375.     f->output_data.x->line_height = FONT_HEIGHT (f->output_data.x->font);
  5376.  
  5377.   return build_string (fontp->full_name);
  5378. }
  5379.  
  5380. /* Give frame F the fontset named FONTSETNAME as its default font, and
  5381.    return the full name of that fontset.  FONTSETNAME may be a wildcard
  5382.    pattern; in that case, we choose some fontset that fits the pattern.
  5383.    The return value shows which fontset we chose.  */
  5384.  
  5385. Lisp_Object
  5386. x_new_fontset (f, fontsetname)
  5387.      struct frame *f;
  5388.      char *fontsetname;
  5389. {
  5390.   int fontset = fs_query_fontset (f, fontsetname);
  5391.   struct fontset_info *fontsetp;
  5392.   Lisp_Object result;
  5393.  
  5394.   if (fontset < 0)
  5395.     return Qnil;
  5396.  
  5397.   if (f->output_data.x->fontset == fontset)
  5398.     /* This fontset is already set in frame F.  There's nothing more
  5399.        to do.  */
  5400.     return build_string (fontsetname);
  5401.  
  5402.   fontsetp = FRAME_FONTSET_DATA (f)->fontset_table[fontset];
  5403.  
  5404.   if (!fontsetp->fontname[CHARSET_ASCII])
  5405.     /* This fontset doesn't contain ASCII font.  */
  5406.     return Qnil;
  5407.  
  5408.   result = x_new_font (f, fontsetp->fontname[CHARSET_ASCII]);
  5409.  
  5410.   if (!STRINGP (result))
  5411.     /* Can't load ASCII font.  */
  5412.     return Qnil;
  5413.  
  5414.   /* Since x_new_font doesn't update any fontset information, do it now.  */
  5415.   f->output_data.x->fontset = fontset;
  5416.   FS_LOAD_FONT (f, FRAME_X_FONT_TABLE (f),
  5417.         CHARSET_ASCII, XSTRING (result)->data, fontset);
  5418.  
  5419.   return build_string (fontsetname);
  5420. }
  5421.  
  5422. /* Calculate the absolute position in frame F
  5423.    from its current recorded position values and gravity.  */
  5424.  
  5425. void
  5426. x_calc_absolute_position (f)
  5427.      struct frame *f;
  5428. {
  5429.   Window win, child;
  5430.   int win_x = 0, win_y = 0;
  5431.   int flags = f->output_data.x->size_hint_flags;
  5432.   int this_window;
  5433.  
  5434.   /* We have nothing to do if the current position
  5435.      is already for the top-left corner.  */
  5436.   if (! ((flags & XNegative) || (flags & YNegative)))
  5437.     return;
  5438.  
  5439. #ifdef USE_X_TOOLKIT
  5440.   this_window = XtWindow (f->output_data.x->widget);
  5441. #else
  5442.   this_window = FRAME_X_WINDOW (f);
  5443. #endif
  5444.  
  5445.   /* Find the position of the outside upper-left corner of
  5446.      the inner window, with respect to the outer window.
  5447.      But do this only if we will need the results.  */
  5448.   if (f->output_data.x->parent_desc != FRAME_X_DISPLAY_INFO (f)->root_window)
  5449.     {
  5450.       int count;
  5451.  
  5452.       BLOCK_INPUT;
  5453.       count = x_catch_errors (FRAME_X_DISPLAY (f));
  5454.       while (1)
  5455.     {
  5456.       x_clear_errors (FRAME_X_DISPLAY (f));
  5457.       XTranslateCoordinates (FRAME_X_DISPLAY (f),
  5458.  
  5459.                  /* From-window, to-window.  */
  5460.                  this_window,
  5461.                  f->output_data.x->parent_desc,
  5462.  
  5463.                  /* From-position, to-position.  */
  5464.                  0, 0, &win_x, &win_y,
  5465.  
  5466.                  /* Child of win.  */
  5467.                  &child);
  5468.       if (x_had_errors_p (FRAME_X_DISPLAY (f)))
  5469.         {
  5470.           Window newroot, newparent = 0xdeadbeef;
  5471.           Window *newchildren;
  5472.           int nchildren;
  5473.  
  5474.           if (! XQueryTree (FRAME_X_DISPLAY (f), this_window, &newroot,
  5475.                 &newparent, &newchildren, &nchildren))
  5476.         break;
  5477.  
  5478.           XFree (newchildren);
  5479.  
  5480.           f->output_data.x->parent_desc = newparent;
  5481.         }
  5482.       else
  5483.         break;
  5484.     }
  5485.  
  5486.       x_uncatch_errors (FRAME_X_DISPLAY (f), count);
  5487.       UNBLOCK_INPUT;
  5488.     }
  5489.  
  5490.   /* Treat negative positions as relative to the leftmost bottommost
  5491.      position that fits on the screen.  */
  5492.   if (flags & XNegative)
  5493.     f->output_data.x->left_pos = (FRAME_X_DISPLAY_INFO (f)->width
  5494.                   - 2 * f->output_data.x->border_width - win_x
  5495.                   - PIXEL_WIDTH (f)
  5496.                   + f->output_data.x->left_pos);
  5497.  
  5498.   if (flags & YNegative)
  5499.     /* We used to subtract f->output_data.x->menubar_height here
  5500.        in the toolkit case, but PIXEL_HEIGHT already includes that.  */
  5501.     f->output_data.x->top_pos = (FRAME_X_DISPLAY_INFO (f)->height
  5502.                  - 2 * f->output_data.x->border_width - win_y
  5503.                  - PIXEL_HEIGHT (f)
  5504.                  + f->output_data.x->top_pos);
  5505.  
  5506.   /* The left_pos and top_pos
  5507.      are now relative to the top and left screen edges,
  5508.      so the flags should correspond.  */
  5509.   f->output_data.x->size_hint_flags &= ~ (XNegative | YNegative);
  5510. }
  5511.  
  5512. /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
  5513.    to really change the position, and 0 when calling from
  5514.    x_make_frame_visible (in that case, XOFF and YOFF are the current
  5515.    position values).  It is -1 when calling from x_set_frame_parameters,
  5516.    which means, do adjust for borders but don't change the gravity.  */
  5517.  
  5518. void
  5519. x_set_offset (f, xoff, yoff, change_gravity)
  5520.      struct frame *f;
  5521.      register int xoff, yoff;
  5522.      int change_gravity;
  5523. {
  5524.   int modified_top, modified_left;
  5525.  
  5526.   if (change_gravity > 0)
  5527.     {
  5528.       f->output_data.x->top_pos = yoff;
  5529.       f->output_data.x->left_pos = xoff;
  5530.       f->output_data.x->size_hint_flags &= ~ (XNegative | YNegative);
  5531.       if (xoff < 0)
  5532.     f->output_data.x->size_hint_flags |= XNegative;
  5533.       if (yoff < 0)
  5534.     f->output_data.x->size_hint_flags |= YNegative;
  5535.       f->output_data.x->win_gravity = NorthWestGravity;
  5536.     }
  5537.   x_calc_absolute_position (f);
  5538.  
  5539.   BLOCK_INPUT;
  5540.   x_wm_set_size_hint (f, (long) 0, 0);
  5541.  
  5542.   modified_left = f->output_data.x->left_pos;
  5543.   modified_top = f->output_data.x->top_pos;
  5544. #if 0 /* Running on psilocin (Debian), and displaying on the NCD X-terminal,
  5545.      this seems to be unnecessary and incorrect.  rms, 4/17/97.  */
  5546.   /* It is a mystery why we need to add the border_width here
  5547.      when the frame is already visible, but experiment says we do.  */
  5548.   if (change_gravity != 0)
  5549.     {
  5550.       modified_left += f->output_data.x->border_width;
  5551.       modified_top += f->output_data.x->border_width;
  5552.     }
  5553. #endif
  5554.  
  5555. #ifdef USE_X_TOOLKIT
  5556.   XMoveWindow (FRAME_X_DISPLAY (f), XtWindow (f->output_data.x->widget),
  5557.            modified_left, modified_top);
  5558. #else /* not USE_X_TOOLKIT */
  5559.   XMoveWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  5560.            modified_left, modified_top);
  5561. #endif /* not USE_X_TOOLKIT */
  5562.   UNBLOCK_INPUT;
  5563. }
  5564.  
  5565. /* Call this to change the size of frame F's x-window.
  5566.    If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
  5567.    for this size change and subsequent size changes.
  5568.    Otherwise we leave the window gravity unchanged.  */
  5569.  
  5570. void
  5571. x_set_window_size (f, change_gravity, cols, rows)
  5572.      struct frame *f;
  5573.      int change_gravity;
  5574.      int cols, rows;
  5575. {
  5576.   int pixelwidth, pixelheight;
  5577.   int mask;
  5578.   struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
  5579.  
  5580.   BLOCK_INPUT;
  5581.  
  5582. #ifdef USE_X_TOOLKIT
  5583.   {
  5584.     /* The x and y position of the widget is clobbered by the
  5585.        call to XtSetValues within EmacsFrameSetCharSize.
  5586.        This is a real kludge, but I don't understand Xt so I can't
  5587.        figure out a correct fix.  Can anyone else tell me? -- rms.  */
  5588.     int xpos = f->output_data.x->widget->core.x;
  5589.     int ypos = f->output_data.x->widget->core.y;
  5590.     EmacsFrameSetCharSize (f->output_data.x->edit_widget, cols, rows);
  5591.     f->output_data.x->widget->core.x = xpos;
  5592.     f->output_data.x->widget->core.y = ypos;
  5593.   }
  5594.  
  5595. #else /* not USE_X_TOOLKIT */
  5596.  
  5597.   check_frame_size (f, &rows, &cols);
  5598.   f->output_data.x->vertical_scroll_bar_extra
  5599.     = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
  5600.        ? 0
  5601.        : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
  5602.        ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
  5603.        : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.x->font)));
  5604.   pixelwidth = CHAR_TO_PIXEL_WIDTH (f, cols);
  5605.   pixelheight = CHAR_TO_PIXEL_HEIGHT (f, rows);
  5606.  
  5607.   f->output_data.x->win_gravity = NorthWestGravity;
  5608.   x_wm_set_size_hint (f, (long) 0, 0);
  5609.  
  5610.   XSync (FRAME_X_DISPLAY (f), False);
  5611.   XResizeWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  5612.          pixelwidth, pixelheight);
  5613.  
  5614.   /* Now, strictly speaking, we can't be sure that this is accurate,
  5615.      but the window manager will get around to dealing with the size
  5616.      change request eventually, and we'll hear how it went when the
  5617.      ConfigureNotify event gets here.
  5618.  
  5619.      We could just not bother storing any of this information here,
  5620.      and let the ConfigureNotify event set everything up, but that
  5621.      might be kind of confusing to the lisp code, since size changes
  5622.      wouldn't be reported in the frame parameters until some random
  5623.      point in the future when the ConfigureNotify event arrives.  */
  5624.   change_frame_size (f, rows, cols, 0, 0);
  5625.   PIXEL_WIDTH (f) = pixelwidth;
  5626.   PIXEL_HEIGHT (f) = pixelheight;
  5627.  
  5628.   /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
  5629.      receive in the ConfigureNotify event; if we get what we asked
  5630.      for, then the event won't cause the screen to become garbaged, so
  5631.      we have to make sure to do it here.  */
  5632.   SET_FRAME_GARBAGED (f);
  5633.  
  5634.   XFlush (FRAME_X_DISPLAY (f));
  5635.  
  5636. #endif /* not USE_X_TOOLKIT */
  5637.  
  5638.   /* If cursor was outside the new size, mark it as off.  */
  5639.   if (f->phys_cursor_y >= rows
  5640.       || f->phys_cursor_x >= cols)
  5641.     {
  5642.       f->phys_cursor_x = 0;
  5643.       f->phys_cursor_y = 0;
  5644.       f->phys_cursor_on = 0;
  5645.     }
  5646.  
  5647.   /* Clear out any recollection of where the mouse highlighting was,
  5648.      since it might be in a place that's outside the new frame size. 
  5649.      Actually checking whether it is outside is a pain in the neck,
  5650.      so don't try--just let the highlighting be done afresh with new size.  */
  5651.   cancel_mouse_face (f);
  5652.  
  5653.   UNBLOCK_INPUT;
  5654. }
  5655.  
  5656. /* Mouse warping.  */
  5657.  
  5658. void
  5659. x_set_mouse_position (f, x, y)
  5660.      struct frame *f;
  5661.      int x, y;
  5662. {
  5663.   int pix_x, pix_y;
  5664.  
  5665.   pix_x = CHAR_TO_PIXEL_COL (f, x) + FONT_WIDTH  (f->output_data.x->font) / 2;
  5666.   pix_y = CHAR_TO_PIXEL_ROW (f, y) + f->output_data.x->line_height / 2;
  5667.  
  5668.   if (pix_x < 0) pix_x = 0;
  5669.   if (pix_x > PIXEL_WIDTH (f)) pix_x = PIXEL_WIDTH (f);
  5670.  
  5671.   if (pix_y < 0) pix_y = 0;
  5672.   if (pix_y > PIXEL_HEIGHT (f)) pix_y = PIXEL_HEIGHT (f);
  5673.  
  5674.   BLOCK_INPUT;
  5675.  
  5676.   XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
  5677.         0, 0, 0, 0, pix_x, pix_y);
  5678.   UNBLOCK_INPUT;
  5679. }
  5680.  
  5681. /* Move the mouse to position pixel PIX_X, PIX_Y relative to frame F.  */
  5682.  
  5683. void
  5684. x_set_mouse_pixel_position (f, pix_x, pix_y)
  5685.      struct frame *f;
  5686.      int pix_x, pix_y;
  5687. {
  5688.   BLOCK_INPUT;
  5689.  
  5690.   XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
  5691.         0, 0, 0, 0, pix_x, pix_y);
  5692.   UNBLOCK_INPUT;
  5693. }
  5694.  
  5695. /* focus shifting, raising and lowering.  */
  5696.  
  5697. void
  5698. x_focus_on_frame (f)
  5699.      struct frame *f;
  5700. {
  5701. #if 0  /* This proves to be unpleasant.  */
  5702.   x_raise_frame (f);
  5703. #endif
  5704. #if 0
  5705.   /* I don't think that the ICCCM allows programs to do things like this
  5706.      without the interaction of the window manager.  Whatever you end up
  5707.      doing with this code, do it to x_unfocus_frame too.  */
  5708.   XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
  5709.           RevertToPointerRoot, CurrentTime);
  5710. #endif /* ! 0 */
  5711. }
  5712.  
  5713. void
  5714. x_unfocus_frame (f)
  5715.      struct frame *f;
  5716. {
  5717. #if 0
  5718.   /* Look at the remarks in x_focus_on_frame.  */
  5719.   if (FRAME_X_DISPLAY_INFO (f)->x_focus_frame == f)
  5720.     XSetInputFocus (FRAME_X_DISPLAY (f), PointerRoot,
  5721.             RevertToPointerRoot, CurrentTime);
  5722. #endif /* ! 0 */
  5723. }
  5724.  
  5725. /* Raise frame F.  */
  5726.  
  5727. void
  5728. x_raise_frame (f)
  5729.      struct frame *f;
  5730. {
  5731.   if (f->async_visible)
  5732.     {
  5733.       BLOCK_INPUT;
  5734. #ifdef USE_X_TOOLKIT
  5735.       XRaiseWindow (FRAME_X_DISPLAY (f), XtWindow (f->output_data.x->widget));
  5736. #else /* not USE_X_TOOLKIT */
  5737.       XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
  5738. #endif /* not USE_X_TOOLKIT */
  5739.       XFlush (FRAME_X_DISPLAY (f));
  5740.       UNBLOCK_INPUT;
  5741.     }
  5742. }
  5743.  
  5744. /* Lower frame F.  */
  5745.  
  5746. void
  5747. x_lower_frame (f)
  5748.      struct frame *f;
  5749. {
  5750.   if (f->async_visible)
  5751.     {
  5752.       BLOCK_INPUT;
  5753. #ifdef USE_X_TOOLKIT
  5754.       XLowerWindow (FRAME_X_DISPLAY (f), XtWindow (f->output_data.x->widget));
  5755. #else /* not USE_X_TOOLKIT */
  5756.       XLowerWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
  5757. #endif /* not USE_X_TOOLKIT */
  5758.       XFlush (FRAME_X_DISPLAY (f));
  5759.       UNBLOCK_INPUT;
  5760.     }
  5761. }
  5762.  
  5763. static void
  5764. XTframe_raise_lower (f, raise_flag)
  5765.      FRAME_PTR f;
  5766.      int raise_flag;
  5767. {
  5768.   if (raise_flag)
  5769.     x_raise_frame (f);
  5770.   else
  5771.     x_lower_frame (f);
  5772. }
  5773.  
  5774. /* Change of visibility.  */
  5775.  
  5776. /* This tries to wait until the frame is really visible.
  5777.    However, if the window manager asks the user where to position
  5778.    the frame, this will return before the user finishes doing that.
  5779.    The frame will not actually be visible at that time,
  5780.    but it will become visible later when the window manager
  5781.    finishes with it.  */
  5782.  
  5783. void
  5784. x_make_frame_visible (f)
  5785.      struct frame *f;
  5786. {
  5787.   int mask;
  5788.   Lisp_Object type;
  5789.   int starting_flags = f->output_data.x->size_hint_flags;
  5790.   int original_top, original_left;
  5791.  
  5792.   BLOCK_INPUT;
  5793.  
  5794.   type = x_icon_type (f);
  5795.   if (!NILP (type))
  5796.     x_bitmap_icon (f, type);
  5797.  
  5798.   if (! FRAME_VISIBLE_P (f))
  5799.     {
  5800.       /* We test FRAME_GARBAGED_P here to make sure we don't
  5801.      call x_set_offset a second time
  5802.      if we get to x_make_frame_visible a second time
  5803.      before the window gets really visible.  */
  5804.       if (! FRAME_ICONIFIED_P (f)
  5805.       && ! f->output_data.x->asked_for_visible)
  5806.     x_set_offset (f, f->output_data.x->left_pos, f->output_data.x->top_pos, 0);
  5807.  
  5808.       f->output_data.x->asked_for_visible = 1;
  5809.  
  5810.       if (! EQ (Vx_no_window_manager, Qt))
  5811.     x_wm_set_window_state (f, NormalState);
  5812. #ifdef USE_X_TOOLKIT
  5813.       /* This was XtPopup, but that did nothing for an iconified frame.  */
  5814.       XtMapWidget (f->output_data.x->widget);
  5815. #else /* not USE_X_TOOLKIT */
  5816.       XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
  5817. #endif /* not USE_X_TOOLKIT */
  5818. #if 0 /* This seems to bring back scroll bars in the wrong places
  5819.      if the window configuration has changed.  They seem
  5820.      to come back ok without this.  */
  5821.       if (FRAME_HAS_VERTICAL_SCROLL_BARS (f))
  5822.     XMapSubwindows (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
  5823. #endif
  5824.     }
  5825.  
  5826.   XFlush (FRAME_X_DISPLAY (f));
  5827.  
  5828.   /* Synchronize to ensure Emacs knows the frame is visible
  5829.      before we do anything else.  We do this loop with input not blocked
  5830.      so that incoming events are handled.  */
  5831.   {
  5832.     Lisp_Object frame;
  5833.     int count = input_signal_count;
  5834.     /* This must be before UNBLOCK_INPUT
  5835.        since events that arrive in response to the actions above
  5836.        will set it when they are handled.  */
  5837.     int previously_visible = f->output_data.x->has_been_visible;
  5838.  
  5839.     original_left = f->output_data.x->left_pos;
  5840.     original_top = f->output_data.x->top_pos;
  5841.  
  5842.     /* This must come after we set COUNT.  */
  5843.     UNBLOCK_INPUT;
  5844.  
  5845.     /* We unblock here so that arriving X events are processed.  */
  5846.  
  5847.     /* Now move the window back to where it was "supposed to be".
  5848.        But don't do it if the gravity is negative.
  5849.        When the gravity is negative, this uses a position
  5850.        that is 3 pixels too low.  Perhaps that's really the border width.
  5851.  
  5852.        Don't do this if the window has never been visible before,
  5853.        because the window manager may choose the position
  5854.        and we don't want to override it.  */
  5855.  
  5856.     if (! FRAME_VISIBLE_P (f) && ! FRAME_ICONIFIED_P (f)
  5857.     && f->output_data.x->win_gravity == NorthWestGravity
  5858.     && previously_visible)
  5859.       {
  5860.     Drawable rootw;
  5861.     int x, y;
  5862.     unsigned int width, height, border, depth;
  5863.  
  5864.     BLOCK_INPUT;
  5865.  
  5866.     /* On some window managers (Such as FVWM) moving an existing window,
  5867.        even to the same place, causes the window manager to introduce
  5868.        an offset.  This can cause the window to move to an unexpected
  5869.        location.  Check the geometry (A little slow here) and then verify
  5870.        that the window is in the right place.  If the window is not in
  5871.        the right place, move it there, and take the potential window
  5872.        manager hit. */
  5873.  
  5874.     XGetGeometry (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
  5875.               &rootw, &x, &y, &width, &height, &border, &depth);
  5876.  
  5877.     if (original_left != x || original_top != y)
  5878.       XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
  5879.                original_left, original_top);
  5880.  
  5881.     UNBLOCK_INPUT;
  5882.       }
  5883.  
  5884.     XSETFRAME (frame, f);
  5885.  
  5886.     while (1)
  5887.       {
  5888.     x_sync (f);
  5889.     /* Once we have handled input events,
  5890.        we should have received the MapNotify if one is coming.
  5891.        So if we have not got it yet, stop looping.
  5892.        Some window managers make their own decisions
  5893.        about visibility.  */
  5894.     if (input_signal_count != count)
  5895.       break;
  5896.     /* Machines that do polling rather than SIGIO have been observed
  5897.        to go into a busy-wait here.  So we'll fake an alarm signal
  5898.        to let the handler know that there's something to be read.
  5899.        We used to raise a real alarm, but it seems that the handler
  5900.        isn't always enabled here.  This is probably a bug.  */
  5901.     if (input_polling_used ())
  5902.       {
  5903.         /* It could be confusing if a real alarm arrives while processing
  5904.            the fake one.  Turn it off and let the handler reset it.  */
  5905.         alarm (0);
  5906.         input_poll_signal (0);
  5907.       }
  5908.     /* Once we have handled input events,
  5909.        we should have received the MapNotify if one is coming.
  5910.        So if we have not got it yet, stop looping.
  5911.        Some window managers make their own decisions
  5912.        about visibility.  */
  5913.     if (input_signal_count != count)
  5914.       break;
  5915.       }
  5916.     FRAME_SAMPLE_VISIBILITY (f);
  5917.   }
  5918. }
  5919.  
  5920. /* Change from mapped state to withdrawn state. */
  5921.  
  5922. /* Make the frame visible (mapped and not iconified).  */
  5923.  
  5924. void
  5925. x_make_frame_invisible (f)
  5926.      struct frame *f;
  5927. {
  5928.   int mask;
  5929.   Window window;
  5930.  
  5931. #ifdef USE_X_TOOLKIT
  5932.   /* Use the frame's outermost window, not the one we normally draw on.  */
  5933.   window = XtWindow (f->output_data.x->widget);
  5934. #else /* not USE_X_TOOLKIT */
  5935.   window = FRAME_X_WINDOW (f);
  5936. #endif /* not USE_X_TOOLKIT */
  5937.  
  5938.   /* Don't keep the highlight on an invisible frame.  */
  5939.   if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
  5940.     FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
  5941.  
  5942. #if 0/* This might add unreliability; I don't trust it -- rms.  */
  5943.   if (! f->async_visible && ! f->async_iconified)
  5944.     return;
  5945. #endif
  5946.  
  5947.   BLOCK_INPUT;
  5948.  
  5949.   /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
  5950.      that the current position of the window is user-specified, rather than
  5951.      program-specified, so that when the window is mapped again, it will be
  5952.      placed at the same location, without forcing the user to position it
  5953.      by hand again (they have already done that once for this window.)  */
  5954.   x_wm_set_size_hint (f, (long) 0, 1);
  5955.  
  5956. #ifdef HAVE_X11R4
  5957.  
  5958.   if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
  5959.              DefaultScreen (FRAME_X_DISPLAY (f))))
  5960.     {
  5961.       UNBLOCK_INPUT_RESIGNAL;
  5962.       error ("Can't notify window manager of window withdrawal");
  5963.     }
  5964. #else /* ! defined (HAVE_X11R4) */
  5965.  
  5966.   /*  Tell the window manager what we're going to do.  */
  5967.   if (! EQ (Vx_no_window_manager, Qt))
  5968.     {
  5969.       XEvent unmap;
  5970.  
  5971.       unmap.xunmap.type = UnmapNotify;
  5972.       unmap.xunmap.window = window;
  5973.       unmap.xunmap.event = DefaultRootWindow (FRAME_X_DISPLAY (f));
  5974.       unmap.xunmap.from_configure = False;
  5975.       if (! XSendEvent (FRAME_X_DISPLAY (f),
  5976.             DefaultRootWindow (FRAME_X_DISPLAY (f)),
  5977.             False,
  5978.             SubstructureRedirectMask|SubstructureNotifyMask,
  5979.             &unmap))
  5980.     {
  5981.       UNBLOCK_INPUT_RESIGNAL;
  5982.       error ("Can't notify window manager of withdrawal");
  5983.     }
  5984.     }
  5985.  
  5986.   /* Unmap the window ourselves.  Cheeky!  */
  5987.   XUnmapWindow (FRAME_X_DISPLAY (f), window);
  5988. #endif /* ! defined (HAVE_X11R4) */
  5989.  
  5990.   /* We can't distinguish this from iconification
  5991.      just by the event that we get from the server.
  5992.      So we can't win using the usual strategy of letting
  5993.      FRAME_SAMPLE_VISIBILITY set this.  So do it by hand,
  5994.      and synchronize with the server to make sure we agree.  */
  5995.   f->visible = 0;
  5996.   FRAME_ICONIFIED_P (f) = 0;
  5997.   f->async_visible = 0;
  5998.   f->async_iconified = 0;
  5999.  
  6000.   x_sync (f);
  6001.  
  6002.   UNBLOCK_INPUT;
  6003. }
  6004.  
  6005. /* Change window state from mapped to iconified. */
  6006.  
  6007. void
  6008. x_iconify_frame (f)
  6009.      struct frame *f;
  6010. {
  6011.   int mask;
  6012.   int result;
  6013.   Lisp_Object type;
  6014.  
  6015.   /* Don't keep the highlight on an invisible frame.  */
  6016.   if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
  6017.     FRAME_X_DISPLAY_INFO (f)->x_highlight_frame = 0;
  6018.  
  6019.   if (f->async_iconified)
  6020.     return;
  6021.  
  6022.   BLOCK_INPUT;
  6023.  
  6024.   FRAME_SAMPLE_VISIBILITY (f);
  6025.  
  6026.   type = x_icon_type (f);
  6027.   if (!NILP (type))
  6028.     x_bitmap_icon (f, type);
  6029.  
  6030. #ifdef USE_X_TOOLKIT
  6031.  
  6032.   if (! FRAME_VISIBLE_P (f))
  6033.     {
  6034.       if (! EQ (Vx_no_window_manager, Qt))
  6035.     x_wm_set_window_state (f, IconicState);
  6036.       /* This was XtPopup, but that did nothing for an iconified frame.  */
  6037.       XtMapWidget (f->output_data.x->widget);
  6038.       /* The server won't give us any event to indicate
  6039.      that an invisible frame was changed to an icon,
  6040.      so we have to record it here.  */
  6041.       f->iconified = 1;
  6042.       f->visible = 1;
  6043.       f->async_iconified = 1;
  6044.       f->async_visible = 0;
  6045.       UNBLOCK_INPUT;
  6046.       return;
  6047.     }
  6048.  
  6049.   result = XIconifyWindow (FRAME_X_DISPLAY (f),
  6050.                XtWindow (f->output_data.x->widget),
  6051.                DefaultScreen (FRAME_X_DISPLAY (f)));
  6052.   UNBLOCK_INPUT;
  6053.  
  6054.   if (!result)
  6055.     error ("Can't notify window manager of iconification");
  6056.  
  6057.   f->async_iconified = 1;
  6058.   f->async_visible = 0;
  6059.  
  6060.  
  6061.   BLOCK_INPUT;
  6062.   XFlush (FRAME_X_DISPLAY (f));
  6063.   UNBLOCK_INPUT;
  6064. #else /* not USE_X_TOOLKIT */
  6065.  
  6066.   /* Make sure the X server knows where the window should be positioned,
  6067.      in case the user deiconifies with the window manager.  */
  6068.   if (! FRAME_VISIBLE_P (f) && !FRAME_ICONIFIED_P (f))
  6069.     x_set_offset (f, f->output_data.x->left_pos, f->output_data.x->top_pos, 0);
  6070.  
  6071.   /* Since we don't know which revision of X we're running, we'll use both
  6072.      the X11R3 and X11R4 techniques.  I don't know if this is a good idea.  */
  6073.  
  6074.   /* X11R4: send a ClientMessage to the window manager using the
  6075.      WM_CHANGE_STATE type.  */
  6076.   {
  6077.     XEvent message;
  6078.  
  6079.     message.xclient.window = FRAME_X_WINDOW (f);
  6080.     message.xclient.type = ClientMessage;
  6081.     message.xclient.message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_change_state;
  6082.     message.xclient.format = 32;
  6083.     message.xclient.data.l[0] = IconicState;
  6084.  
  6085.     if (! XSendEvent (FRAME_X_DISPLAY (f),
  6086.               DefaultRootWindow (FRAME_X_DISPLAY (f)),
  6087.               False,
  6088.               SubstructureRedirectMask | SubstructureNotifyMask,
  6089.               &message))
  6090.       {
  6091.     UNBLOCK_INPUT_RESIGNAL;
  6092.     error ("Can't notify window manager of iconification");
  6093.       }
  6094.   }
  6095.  
  6096.   /* X11R3: set the initial_state field of the window manager hints to
  6097.      IconicState.  */
  6098.   x_wm_set_window_state (f, IconicState);
  6099.  
  6100.   if (!FRAME_VISIBLE_P (f))
  6101.     {
  6102.       /* If the frame was withdrawn, before, we must map it.  */
  6103.       XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
  6104.     }
  6105.  
  6106.   f->async_iconified = 1;
  6107.   f->async_visible = 0;
  6108.  
  6109.   XFlush (FRAME_X_DISPLAY (f));
  6110.   UNBLOCK_INPUT;
  6111. #endif /* not USE_X_TOOLKIT */
  6112. }
  6113.  
  6114. /* Destroy the X window of frame F.  */
  6115.  
  6116. void
  6117. x_destroy_window (f)
  6118.      struct frame *f;
  6119. {
  6120.   struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
  6121.  
  6122.   BLOCK_INPUT;
  6123.  
  6124.   /* If a display connection is dead, don't try sending more
  6125.      commands to the X server.  */
  6126.   if (dpyinfo->display != 0)
  6127.     {
  6128.       if (f->output_data.x->icon_desc != 0)
  6129.     XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
  6130. #ifdef HAVE_X_I18N
  6131.       if (FRAME_XIM (f))
  6132.     {
  6133.       XDestroyIC (FRAME_XIC (f));
  6134. #if ! defined (SOLARIS2) || defined (HAVE_X11R6)
  6135.       /* This line causes crashes on Solaris with Openwin,
  6136.          due to an apparent bug in XCloseIM.
  6137.          X11R6 seems not to have the bug.  */
  6138.       XCloseIM (FRAME_XIM (f));
  6139. #endif
  6140.     }
  6141. #endif
  6142.       XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->window_desc);
  6143. #ifdef USE_X_TOOLKIT
  6144.       XtDestroyWidget (f->output_data.x->widget);
  6145.       free_frame_menubar (f);
  6146. #endif /* USE_X_TOOLKIT */
  6147.  
  6148.       free_frame_faces (f);
  6149.       XFlush (FRAME_X_DISPLAY (f));
  6150.     }
  6151.  
  6152.   if (f->output_data.x->saved_menu_event)
  6153.     free (f->output_data.x->saved_menu_event);
  6154.  
  6155.   xfree (f->output_data.x);
  6156.   f->output_data.x = 0;
  6157.   if (f == dpyinfo->x_focus_frame)
  6158.     dpyinfo->x_focus_frame = 0;
  6159.   if (f == dpyinfo->x_focus_event_frame)
  6160.     dpyinfo->x_focus_event_frame = 0;
  6161.   if (f == dpyinfo->x_highlight_frame)
  6162.     dpyinfo->x_highlight_frame = 0;
  6163.  
  6164.   dpyinfo->reference_count--;
  6165.  
  6166.   if (f == dpyinfo->mouse_face_mouse_frame)
  6167.     {
  6168.       dpyinfo->mouse_face_beg_row
  6169.     = dpyinfo->mouse_face_beg_col = -1;
  6170.       dpyinfo->mouse_face_end_row
  6171.     = dpyinfo->mouse_face_end_col = -1;
  6172.       dpyinfo->mouse_face_window = Qnil;
  6173.       dpyinfo->mouse_face_deferred_gc = 0;
  6174.       dpyinfo->mouse_face_mouse_frame = 0;
  6175.     }
  6176.  
  6177.   UNBLOCK_INPUT;
  6178. }
  6179.  
  6180. /* Setting window manager hints.  */
  6181.  
  6182. /* Set the normal size hints for the window manager, for frame F.
  6183.    FLAGS is the flags word to use--or 0 meaning preserve the flags
  6184.    that the window now has.
  6185.    If USER_POSITION is nonzero, we set the USPosition
  6186.    flag (this is useful when FLAGS is 0).  */
  6187.  
  6188. void
  6189. x_wm_set_size_hint (f, flags, user_position)
  6190.      struct frame *f;
  6191.      long flags;
  6192.      int user_position;
  6193. {
  6194.   XSizeHints size_hints;
  6195.  
  6196. #ifdef USE_X_TOOLKIT
  6197.   Arg al[2];
  6198.   int ac = 0;
  6199.   Dimension widget_width, widget_height;
  6200.   Window window = XtWindow (f->output_data.x->widget);
  6201. #else /* not USE_X_TOOLKIT */
  6202.   Window window = FRAME_X_WINDOW (f);
  6203. #endif /* not USE_X_TOOLKIT */
  6204.  
  6205.   /* Setting PMaxSize caused various problems.  */
  6206.   size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
  6207.  
  6208.   flexlines = f->height;
  6209.  
  6210.   size_hints.x = f->output_data.x->left_pos;
  6211.   size_hints.y = f->output_data.x->top_pos;
  6212.  
  6213. #ifdef USE_X_TOOLKIT
  6214.   XtSetArg (al[ac], XtNwidth, &widget_width); ac++;
  6215.   XtSetArg (al[ac], XtNheight, &widget_height); ac++;
  6216.   XtGetValues (f->output_data.x->widget, al, ac);
  6217.   size_hints.height = widget_height;
  6218.   size_hints.width = widget_width;
  6219. #else /* not USE_X_TOOLKIT */
  6220.   size_hints.height = PIXEL_HEIGHT (f);
  6221.   size_hints.width = PIXEL_WIDTH (f);
  6222. #endif /* not USE_X_TOOLKIT */
  6223.  
  6224.   size_hints.width_inc = FONT_WIDTH (f->output_data.x->font);
  6225.   size_hints.height_inc = f->output_data.x->line_height;
  6226.   size_hints.max_width
  6227.     = FRAME_X_DISPLAY_INFO (f)->width - CHAR_TO_PIXEL_WIDTH (f, 0);
  6228.   size_hints.max_height
  6229.     = FRAME_X_DISPLAY_INFO (f)->height - CHAR_TO_PIXEL_HEIGHT (f, 0);
  6230.  
  6231.   /* Calculate the base and minimum sizes.
  6232.  
  6233.      (When we use the X toolkit, we don't do it here.
  6234.      Instead we copy the values that the widgets are using, below.)  */
  6235. #ifndef USE_X_TOOLKIT
  6236.   {
  6237.     int base_width, base_height;
  6238.     int min_rows = 0, min_cols = 0;
  6239.  
  6240.     base_width = CHAR_TO_PIXEL_WIDTH (f, 0);
  6241.     base_height = CHAR_TO_PIXEL_HEIGHT (f, 0);
  6242.  
  6243.     check_frame_size (f, &min_rows, &min_cols);
  6244.  
  6245.     /* The window manager uses the base width hints to calculate the
  6246.        current number of rows and columns in the frame while
  6247.        resizing; min_width and min_height aren't useful for this
  6248.        purpose, since they might not give the dimensions for a
  6249.        zero-row, zero-column frame.
  6250.  
  6251.        We use the base_width and base_height members if we have
  6252.        them; otherwise, we set the min_width and min_height members
  6253.        to the size for a zero x zero frame.  */
  6254.  
  6255. #ifdef HAVE_X11R4
  6256.     size_hints.flags |= PBaseSize;
  6257.     size_hints.base_width = base_width;
  6258.     size_hints.base_height = base_height;
  6259.     size_hints.min_width  = base_width + min_cols * size_hints.width_inc;
  6260.     size_hints.min_height = base_height + min_rows * size_hints.height_inc;
  6261. #else
  6262.     size_hints.min_width = base_width;
  6263.     size_hints.min_height = base_height;
  6264. #endif
  6265.   }
  6266.  
  6267.   /* If we don't need the old flags, we don't need the old hint at all.  */
  6268.   if (flags)
  6269.     {
  6270.       size_hints.flags |= flags;
  6271.       goto no_read;
  6272.     }
  6273. #endif /* not USE_X_TOOLKIT */
  6274.  
  6275.   {
  6276.     XSizeHints hints;        /* Sometimes I hate X Windows... */
  6277.     long supplied_return;
  6278.     int value;
  6279.  
  6280. #ifdef HAVE_X11R4
  6281.     value = XGetWMNormalHints (FRAME_X_DISPLAY (f), window, &hints,
  6282.                    &supplied_return);
  6283. #else
  6284.     value = XGetNormalHints (FRAME_X_DISPLAY (f), window, &hints);
  6285. #endif
  6286.  
  6287. #ifdef USE_X_TOOLKIT
  6288.     size_hints.base_height = hints.base_height;
  6289.     size_hints.base_width = hints.base_width;
  6290.     size_hints.min_height = hints.min_height;
  6291.     size_hints.min_width = hints.min_width;
  6292. #endif
  6293.  
  6294.     if (flags)
  6295.       size_hints.flags |= flags;
  6296.     else
  6297.       {
  6298.     if (value == 0)
  6299.       hints.flags = 0;
  6300.     if (hints.flags & PSize)
  6301.       size_hints.flags |= PSize;
  6302.     if (hints.flags & PPosition)
  6303.       size_hints.flags |= PPosition;
  6304.     if (hints.flags & USPosition)
  6305.       size_hints.flags |= USPosition;
  6306.     if (hints.flags & USSize)
  6307.       size_hints.flags |= USSize;
  6308.       }
  6309.   }
  6310.  
  6311.  no_read:
  6312.  
  6313. #ifdef PWinGravity
  6314.   size_hints.win_gravity = f->output_data.x->win_gravity;
  6315.   size_hints.flags |= PWinGravity;
  6316.  
  6317.   if (user_position)
  6318.     {
  6319.       size_hints.flags &= ~ PPosition;
  6320.       size_hints.flags |= USPosition;
  6321.     }
  6322. #endif /* PWinGravity */
  6323.  
  6324. #ifdef HAVE_X11R4
  6325.   XSetWMNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
  6326. #else
  6327.   XSetNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
  6328. #endif
  6329. }
  6330.  
  6331. /* Used for IconicState or NormalState */
  6332. void
  6333. x_wm_set_window_state (f, state)
  6334.      struct frame *f;
  6335.      int state;
  6336. {
  6337. #ifdef USE_X_TOOLKIT
  6338.   Arg al[1];
  6339.  
  6340.   XtSetArg (al[0], XtNinitialState, state);
  6341.   XtSetValues (f->output_data.x->widget, al, 1);
  6342. #else /* not USE_X_TOOLKIT */
  6343.   Window window = FRAME_X_WINDOW (f);
  6344.  
  6345.   f->output_data.x->wm_hints.flags |= StateHint;
  6346.   f->output_data.x->wm_hints.initial_state = state;
  6347.  
  6348.   XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
  6349. #endif /* not USE_X_TOOLKIT */
  6350. }
  6351.  
  6352. void
  6353. x_wm_set_icon_pixmap (f, pixmap_id)
  6354.      struct frame *f;
  6355.      int pixmap_id;
  6356. {
  6357.   Pixmap icon_pixmap;
  6358.  
  6359. #ifdef USE_X_TOOLKIT
  6360.   Window window = XtWindow (f->output_data.x->widget);
  6361. #else
  6362.   Window window = FRAME_X_WINDOW (f);
  6363. #endif
  6364.  
  6365.   if (pixmap_id > 0)
  6366.     {
  6367.       icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
  6368.       f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
  6369.     }
  6370.   else
  6371.     {
  6372.       /* It seems there is no way to turn off use of an icon pixmap.
  6373.      The following line does it, only if no icon has yet been created,
  6374.      for some window managers.  But with mwm it crashes.
  6375.      Some people say it should clear the IconPixmapHint bit in this case,
  6376.      but that doesn't work, and the X consortium said it isn't the
  6377.      right thing at all.  Since there is no way to win,
  6378.      best to explicitly give up.  */
  6379. #if 0
  6380.       f->output_data.x->wm_hints.icon_pixmap = None;
  6381. #else
  6382.       return;
  6383. #endif
  6384.     }
  6385.  
  6386. #ifdef USE_X_TOOLKIT /* same as in x_wm_set_window_state.  */
  6387.  
  6388.   {
  6389.     Arg al[1];
  6390.     XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
  6391.     XtSetValues (f->output_data.x->widget, al, 1);
  6392.   }
  6393.  
  6394. #else /* not USE_X_TOOLKIT */
  6395.   
  6396.   f->output_data.x->wm_hints.flags |= IconPixmapHint;
  6397.   XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
  6398.  
  6399. #endif /* not USE_X_TOOLKIT */
  6400. }
  6401.  
  6402. void
  6403. x_wm_set_icon_position (f, icon_x, icon_y)
  6404.      struct frame *f;
  6405.      int icon_x, icon_y;
  6406. {
  6407. #ifdef USE_X_TOOLKIT
  6408.   Window window = XtWindow (f->output_data.x->widget);
  6409. #else
  6410.   Window window = FRAME_X_WINDOW (f);
  6411. #endif
  6412.  
  6413.   f->output_data.x->wm_hints.flags |= IconPositionHint;
  6414.   f->output_data.x->wm_hints.icon_x = icon_x;
  6415.   f->output_data.x->wm_hints.icon_y = icon_y;
  6416.  
  6417.   XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
  6418. }
  6419.  
  6420.  
  6421. /* Interface to fontset handler.  */
  6422.  
  6423. /* Return a pointer to struct font_info of font FONT_IDX of frame F.  */
  6424. struct font_info *
  6425. x_get_font_info (f, font_idx)
  6426.      FRAME_PTR f;
  6427.      int font_idx;
  6428. {
  6429.   return (FRAME_X_FONT_TABLE (f) + font_idx);
  6430. }
  6431.  
  6432.  
  6433. /* Return a list of names of available fonts matching PATTERN on frame
  6434.    F.  If SIZE is not 0, it is the size (maximum bound width) of fonts
  6435.    to be listed.  Frame F NULL means we have not yet created any
  6436.    frame on X, and consult the first display in x_display_list.
  6437.    MAXNAMES sets a limit on how many fonts to match.  */
  6438.  
  6439. Lisp_Object
  6440. x_list_fonts (f, pattern, size, maxnames)
  6441.      FRAME_PTR f;
  6442.      Lisp_Object pattern;
  6443.      int size;
  6444.      int maxnames;
  6445. {
  6446.   Lisp_Object list = Qnil, patterns, newlist = Qnil, key, tem, second_best;
  6447.   Display *dpy = f != NULL ? FRAME_X_DISPLAY (f) : x_display_list->display;
  6448.   int try_XLoadQueryFont = 0;
  6449.  
  6450.   patterns = Fassoc (pattern, Valternate_fontname_alist);
  6451.   if (NILP (patterns))
  6452.     patterns = Fcons (pattern, Qnil);
  6453.  
  6454.   if (maxnames == 1 && !size)
  6455.     /* We can return any single font matching PATTERN.  */
  6456.     try_XLoadQueryFont = 1;
  6457.   else
  6458.     {
  6459.       /* We try at least 10 fonts because XListFonts will return
  6460.      auto-scaled fonts at the head.  */
  6461.       if (maxnames < 10) maxnames = 10;
  6462.     }
  6463.  
  6464.   for (; CONSP (patterns); patterns = XCONS (patterns)->cdr)
  6465.     {
  6466.       int num_fonts;
  6467.       char **names;
  6468.  
  6469.       pattern = XCONS (patterns)->car;
  6470.       /* See if we cached the result for this particular query.
  6471.          The cache is an alist of the form:
  6472.        (((PATTERN . MAXNAMES) (FONTNAME . WIDTH) ...) ...)
  6473.       */
  6474.       if (f && (tem = XCONS (FRAME_X_DISPLAY_INFO (f)->name_list_element)->cdr,
  6475.         key = Fcons (pattern, make_number (maxnames)),
  6476.         !NILP (list = Fassoc (key, tem))))
  6477.     {
  6478.       list = Fcdr_safe (list);
  6479.       /* We have a cashed list.  Don't have to get the list again.  */
  6480.       goto label_cached;
  6481.     }
  6482.  
  6483.       /* At first, put PATTERN in the cache.  */
  6484.  
  6485.       BLOCK_INPUT;
  6486.       if (try_XLoadQueryFont)
  6487.     {
  6488.       XFontStruct *font;
  6489.       unsigned long value;
  6490.  
  6491.       font = XLoadQueryFont (dpy, XSTRING (pattern)->data);
  6492.       if (font
  6493.           && XGetFontProperty (font, XA_FONT, &value))
  6494.         {
  6495.           char *name = (char *) XGetAtomName (dpy, (Atom) value);
  6496.           int len = strlen (name);
  6497.           char *tmp;
  6498.  
  6499.           num_fonts = 1;
  6500.           names = (char **) alloca (sizeof (char *));
  6501.           /* Some systems only allow alloca assigned to a simple var.  */
  6502.           tmp = (char *) alloca (len + 1);  names[0] = tmp;
  6503.           bcopy (name, names[0], len + 1);
  6504.           XFree (name);
  6505.         }
  6506.       else
  6507.         try_XLoadQueryFont = 0;
  6508.  
  6509.       if (font)
  6510.         XFreeFont (dpy, font);
  6511.     }
  6512.  
  6513.       if (!try_XLoadQueryFont)
  6514.     names = XListFonts (dpy, XSTRING (pattern)->data, maxnames,
  6515.                 &num_fonts);
  6516.       UNBLOCK_INPUT;
  6517.  
  6518.       if (names)
  6519.     {
  6520.       int i;
  6521.  
  6522.       /* Make a list of all the fonts we got back.
  6523.          Store that in the font cache for the display.  */
  6524.       for (i = 0; i < num_fonts; i++)
  6525.         {
  6526.           char *p = names[i];
  6527.           int average_width = -1, dashes = 0, width = 0;
  6528.  
  6529.           /* Count the number of dashes in NAMES[I].  If there are
  6530.         14 dashes, and the field value following 12th dash
  6531.         (AVERAGE_WIDTH) is 0, this is a auto-scaled font which
  6532.         is usually too ugly to be used for editing.  Let's
  6533.         ignore it.  */
  6534.           while (*p)
  6535.         if (*p++ == '-')
  6536.           {
  6537.             dashes++;
  6538.             if (dashes == 7) /* PIXEL_SIZE field */
  6539.               width = atoi (p);
  6540.             else if (dashes == 12) /* AVERAGE_WIDTH field */
  6541.               average_width = atoi (p);
  6542.           }
  6543.           if (dashes < 14 || average_width != 0)
  6544.         {
  6545.           tem = build_string (names[i]);
  6546.           if (NILP (Fassoc (tem, list)))
  6547.             {
  6548.               if (STRINGP (Vx_pixel_size_width_font_regexp)
  6549.               && ((fast_c_string_match_ignore_case
  6550.                    (Vx_pixel_size_width_font_regexp, names[i]))
  6551.                   >= 0))
  6552.             /* We can set the value of PIXEL_SIZE to the
  6553.               width of this font.  */
  6554.             list = Fcons (Fcons (tem, make_number (width)), list);
  6555.               else
  6556.             /* For the moment, width is not known.  */
  6557.             list = Fcons (Fcons (tem, Qnil), list);
  6558.             }
  6559.         }
  6560.         }
  6561.       if (!try_XLoadQueryFont)
  6562.         XFreeFontNames (names);
  6563.     }
  6564.  
  6565.       /* Now store the result in the cache.  */
  6566.       if (f != NULL)
  6567.     XCONS (FRAME_X_DISPLAY_INFO (f)->name_list_element)->cdr
  6568.       = Fcons (Fcons (key, list),
  6569.            XCONS (FRAME_X_DISPLAY_INFO (f)->name_list_element)->cdr);
  6570.  
  6571.     label_cached:
  6572.       if (NILP (list)) continue; /* Try the remaining alternatives.  */
  6573.  
  6574.       newlist = second_best = Qnil;
  6575.       /* Make a list of the fonts that have the right width.  */
  6576.       for (; CONSP (list); list = XCONS (list)->cdr)
  6577.     {
  6578.       int found_size;
  6579.  
  6580.       tem = XCONS (list)->car;
  6581.  
  6582.       if (!CONSP (tem) || NILP (XCONS (tem)->car))
  6583.         continue;
  6584.       if (!size)
  6585.         {
  6586.           newlist = Fcons (XCONS (tem)->car, newlist);
  6587.           continue;
  6588.         }
  6589.  
  6590.       if (!INTEGERP (XCONS (tem)->cdr))
  6591.         {
  6592.           /* Since we have not yet known the size of this font, we
  6593.         must try slow function call XLoadQueryFont.  */
  6594.           XFontStruct *thisinfo;
  6595.  
  6596.           BLOCK_INPUT;
  6597.           thisinfo = XLoadQueryFont (dpy,
  6598.                      XSTRING (XCONS (tem)->car)->data);
  6599.           UNBLOCK_INPUT;
  6600.  
  6601.           if (thisinfo)
  6602.         {
  6603.           XCONS (tem)->cdr
  6604.             = (thisinfo->min_bounds.width == 0
  6605.                ? make_number (0)
  6606.                : make_number (thisinfo->max_bounds.width));
  6607.           XFreeFont (dpy, thisinfo);
  6608.         }
  6609.           else
  6610.         /* For unknown reason, the previous call of XListFont had
  6611.           retruned a font which can't be opened.  Record the size
  6612.           as 0 not to try to open it again.  */
  6613.         XCONS (tem)->cdr = make_number (0);
  6614.         }
  6615.  
  6616.       found_size = XINT (XCONS (tem)->cdr);
  6617.       if (found_size == size)
  6618.         newlist = Fcons (XCONS (tem)->car, newlist);
  6619.       else if (found_size > 0)
  6620.         {
  6621.           if (NILP (second_best))
  6622.         second_best = tem;
  6623.           else if (found_size < size)
  6624.         {
  6625.           if (XINT (XCONS (second_best)->cdr) > size
  6626.               || XINT (XCONS (second_best)->cdr) < found_size)
  6627.             second_best = tem;
  6628.         }
  6629.           else
  6630.         {
  6631.           if (XINT (XCONS (second_best)->cdr) > size
  6632.               && XINT (XCONS (second_best)->cdr) > found_size)
  6633.             second_best = tem;
  6634.         }
  6635.         }
  6636.     }
  6637.       if (!NILP (newlist))
  6638.     break;
  6639.       else if (!NILP (second_best))
  6640.     {
  6641.       newlist = Fcons (XCONS (second_best)->car, Qnil);
  6642.       break;
  6643.     }
  6644.     }
  6645.  
  6646.   return newlist;
  6647. }  
  6648.  
  6649. /* Load font named FONTNAME of the size SIZE for frame F, and return a
  6650.    pointer to the structure font_info while allocating it dynamically.
  6651.    If SIZE is 0, load any size of font.
  6652.    If loading is failed, return NULL.  */
  6653.  
  6654. struct font_info *
  6655. x_load_font (f, fontname, size)
  6656.      struct frame *f;
  6657.      register char *fontname;
  6658.      int size;
  6659. {
  6660.   struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
  6661.   Lisp_Object font_names;
  6662.  
  6663.   /* Get a list of all the fonts that match this name.  Once we
  6664.      have a list of matching fonts, we compare them against the fonts
  6665.      we already have by comparing names.  */
  6666.   font_names = x_list_fonts (f, build_string (fontname), size, 1);
  6667.  
  6668.   if (!NILP (font_names))
  6669.     {
  6670.       Lisp_Object tail;
  6671.       int i;
  6672.  
  6673.       for (i = 0; i < dpyinfo->n_fonts; i++)
  6674.     for (tail = font_names; CONSP (tail); tail = XCONS (tail)->cdr)
  6675.       if (!strcmp (dpyinfo->font_table[i].name,
  6676.                XSTRING (XCONS (tail)->car)->data)
  6677.           || !strcmp (dpyinfo->font_table[i].full_name,
  6678.               XSTRING (XCONS (tail)->car)->data))
  6679.         return (dpyinfo->font_table + i);
  6680.     }
  6681.  
  6682.   /* Load the font and add it to the table.  */
  6683.   {
  6684.     char *full_name;
  6685.     XFontStruct *font;
  6686.     struct font_info *fontp;
  6687.     unsigned long value;
  6688.  
  6689.     /* If we have found fonts by x_list_font, load one of them.  If
  6690.        not, we still try to load a font by the name given as FONTNAME
  6691.        because XListFonts (called in x_list_font) of some X server has
  6692.        a bug of not finding a font even if the font surely exists and
  6693.        is loadable by XLoadQueryFont.  */
  6694.     if (!NILP (font_names))
  6695.       fontname = (char *) XSTRING (XCONS (font_names)->car)->data;
  6696.  
  6697.     BLOCK_INPUT;
  6698.     font = (XFontStruct *) XLoadQueryFont (FRAME_X_DISPLAY (f), fontname);
  6699.     UNBLOCK_INPUT;
  6700.     if (!font)
  6701.       return NULL;
  6702.  
  6703.     /* Do we need to create the table?  */
  6704.     if (dpyinfo->font_table_size == 0)
  6705.       {
  6706.     dpyinfo->font_table_size = 16;
  6707.     dpyinfo->font_table
  6708.       = (struct font_info *) xmalloc (dpyinfo->font_table_size
  6709.                       * sizeof (struct font_info));
  6710.       }
  6711.     /* Do we need to grow the table?  */
  6712.     else if (dpyinfo->n_fonts
  6713.          >= dpyinfo->font_table_size)
  6714.       {
  6715.     dpyinfo->font_table_size *= 2;
  6716.     dpyinfo->font_table
  6717.       = (struct font_info *) xrealloc (dpyinfo->font_table,
  6718.                        (dpyinfo->font_table_size
  6719.                         * sizeof (struct font_info)));
  6720.       }
  6721.  
  6722.     fontp = dpyinfo->font_table + dpyinfo->n_fonts;
  6723.  
  6724.     /* Now fill in the slots of *FONTP.  */
  6725.     BLOCK_INPUT;
  6726.     fontp->font = font;
  6727.     fontp->font_idx = dpyinfo->n_fonts;
  6728.     fontp->name = (char *) xmalloc (strlen (fontname) + 1);
  6729.     bcopy (fontname, fontp->name, strlen (fontname) + 1);
  6730.  
  6731.     /* Try to get the full name of FONT.  Put it in FULL_NAME.  */
  6732.     full_name = 0;
  6733.     if (XGetFontProperty (font, XA_FONT, &value))
  6734.       {
  6735.     char *name = (char *) XGetAtomName (FRAME_X_DISPLAY (f), (Atom) value);
  6736.     char *p = name;
  6737.     int dashes = 0;
  6738.  
  6739.     /* Count the number of dashes in the "full name".
  6740.        If it is too few, this isn't really the font's full name,
  6741.        so don't use it.
  6742.        In X11R4, the fonts did not come with their canonical names
  6743.        stored in them.  */
  6744.     while (*p)
  6745.       {
  6746.         if (*p == '-')
  6747.           dashes++;
  6748.         p++;
  6749.       }
  6750.  
  6751.     if (dashes >= 13)
  6752.       {
  6753.         full_name = (char *) xmalloc (p - name + 1);
  6754.         bcopy (name, full_name, p - name + 1);
  6755.       }
  6756.  
  6757.     XFree (name);
  6758.       }
  6759.     
  6760.     if (full_name != 0)
  6761.       fontp->full_name = full_name;
  6762.     else
  6763.       fontp->full_name = fontp->name;
  6764.  
  6765.     fontp->size = font->max_bounds.width;
  6766.     fontp->height = font->max_bounds.ascent + font->max_bounds.descent;
  6767.  
  6768.     if (NILP (font_names))
  6769.       {
  6770.     /* We come here because of a bug of XListFonts mentioned at
  6771.        the head of this block.  Let's store this information in
  6772.        the cache for x_list_fonts.  */
  6773.     Lisp_Object lispy_name = build_string (fontname);
  6774.     Lisp_Object lispy_full_name = build_string (fontp->full_name);
  6775.  
  6776.     XCONS (dpyinfo->name_list_element)->cdr
  6777.       = Fcons (Fcons (Fcons (lispy_name, make_number (256)),
  6778.               Fcons (Fcons (lispy_full_name,
  6779.                     make_number (fontp->size)),
  6780.                  Qnil)),
  6781.            XCONS (dpyinfo->name_list_element)->cdr);
  6782.     if (full_name)
  6783.       XCONS (dpyinfo->name_list_element)->cdr
  6784.         = Fcons (Fcons (Fcons (lispy_full_name, make_number (256)),
  6785.                 Fcons (Fcons (lispy_full_name,
  6786.                       make_number (fontp->size)),
  6787.                    Qnil)),
  6788.              XCONS (dpyinfo->name_list_element)->cdr);
  6789.       }
  6790.  
  6791.     /* The slot `encoding' specifies how to map a character
  6792.        code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
  6793.        the font code-points (0:0x20..0x7F, 1:0xA0..0xFF, 0:0x2020..0x7F7F,
  6794.        the font code-points (0:0x20..0x7F, 1:0xA0..0xFF,
  6795.        0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF, or
  6796.        2:0xA020..0xFF7F).  For the moment, we don't know which charset
  6797.        uses this font.  So, we set informatoin in fontp->encoding[1]
  6798.        which is never used by any charset.  If mapping can't be
  6799.        decided, set FONT_ENCODING_NOT_DECIDED.  */
  6800.     fontp->encoding[1]
  6801.       = (font->max_byte1 == 0
  6802.      /* 1-byte font */
  6803.      ? (font->min_char_or_byte2 < 0x80
  6804.         ? (font->max_char_or_byte2 < 0x80
  6805.            ? 0        /* 0x20..0x7F */
  6806.            : FONT_ENCODING_NOT_DECIDED) /* 0x20..0xFF */
  6807.         : 1)        /* 0xA0..0xFF */
  6808.      /* 2-byte font */
  6809.      : (font->min_byte1 < 0x80
  6810.         ? (font->max_byte1 < 0x80
  6811.            ? (font->min_char_or_byte2 < 0x80
  6812.           ? (font->max_char_or_byte2 < 0x80
  6813.              ? 0        /* 0x2020..0x7F7F */
  6814.              : FONT_ENCODING_NOT_DECIDED) /* 0x2020..0x7FFF */
  6815.           : 3)        /* 0x20A0..0x7FFF */
  6816.            : FONT_ENCODING_NOT_DECIDED) /* 0x20??..0xA0?? */
  6817.         : (font->min_char_or_byte2 < 0x80
  6818.            ? (font->max_char_or_byte2 < 0x80
  6819.           ? 2        /* 0xA020..0xFF7F */
  6820.           : FONT_ENCODING_NOT_DECIDED) /* 0xA020..0xFFFF */
  6821.            : 1)));        /* 0xA0A0..0xFFFF */
  6822.  
  6823.     fontp->baseline_offset
  6824.       = (XGetFontProperty (font, dpyinfo->Xatom_MULE_BASELINE_OFFSET, &value)
  6825.      ? (long) value : 0);
  6826.     fontp->relative_compose
  6827.       = (XGetFontProperty (font, dpyinfo->Xatom_MULE_RELATIVE_COMPOSE, &value)
  6828.      ? (long) value : 0);
  6829.     fontp->default_ascent
  6830.       = (XGetFontProperty (font, dpyinfo->Xatom_MULE_DEFAULT_ASCENT, &value)
  6831.      ? (long) value : 0);
  6832.  
  6833.     UNBLOCK_INPUT;
  6834.     dpyinfo->n_fonts++;
  6835.  
  6836.     return fontp;
  6837.   }
  6838. }
  6839.  
  6840. /* Return a pointer to struct font_info of a font named FONTNAME for frame F.
  6841.    If no such font is loaded, return NULL.  */
  6842. struct font_info *
  6843. x_query_font (f, fontname)
  6844.      struct frame *f;
  6845.      register char *fontname;
  6846. {
  6847.   struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
  6848.   int i;
  6849.  
  6850.   for (i = 0; i < dpyinfo->n_fonts; i++)
  6851.     if (!strcmp (dpyinfo->font_table[i].name, fontname)
  6852.     || !strcmp (dpyinfo->font_table[i].full_name, fontname))
  6853.       return (dpyinfo->font_table + i);
  6854.   return NULL;
  6855. }
  6856.  
  6857. /* Find a CCL program for a font specified by FONTP, and set the memer
  6858.  `encoder' of the structure.  */
  6859.  
  6860. void
  6861. x_find_ccl_program (fontp)
  6862.      struct font_info *fontp;
  6863. {
  6864.   extern Lisp_Object Vfont_ccl_encoder_alist, Vccl_program_table;
  6865.   extern Lisp_Object Qccl_program_idx;
  6866.   extern Lisp_Object resolve_symbol_ccl_program ();
  6867.   Lisp_Object list, elt, ccl_prog, ccl_id;
  6868.  
  6869.   for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCONS (list)->cdr)
  6870.     {
  6871.       elt = XCONS (list)->car;
  6872.       if (CONSP (elt)
  6873.       && STRINGP (XCONS (elt)->car)
  6874.       && (fast_c_string_match_ignore_case (XCONS (elt)->car, fontp->name)
  6875.           >= 0))
  6876.     {
  6877.       if (SYMBOLP (XCONS (elt)->cdr) &&
  6878.           (!NILP (ccl_id = Fget (XCONS (elt)->cdr, Qccl_program_idx))))
  6879.         {
  6880.           ccl_prog = XVECTOR (Vccl_program_table)->contents[XUINT (ccl_id)];
  6881.           if (!CONSP (ccl_prog)) continue;
  6882.           ccl_prog = XCONS (ccl_prog)->cdr;
  6883.         }
  6884.       else
  6885.         {
  6886.           ccl_prog = XCONS (elt)->cdr;
  6887.           if (!VECTORP (ccl_prog)) continue;
  6888.         }
  6889.         
  6890.       fontp->font_encoder
  6891.         = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
  6892.       setup_ccl_program (fontp->font_encoder,
  6893.                  resolve_symbol_ccl_program (ccl_prog));
  6894.       break;
  6895.     }
  6896.     }
  6897. }
  6898.  
  6899.  
  6900. /* Initialization.  */
  6901.  
  6902. #ifdef USE_X_TOOLKIT
  6903. static XrmOptionDescRec emacs_options[] = {
  6904.   {"-geometry",    ".geometry", XrmoptionSepArg, NULL},
  6905.   {"-iconic",    ".iconic", XrmoptionNoArg, (XtPointer) "yes"},
  6906.  
  6907.   {"-internal-border-width", "*EmacsScreen.internalBorderWidth",
  6908.      XrmoptionSepArg, NULL},
  6909.   {"-ib",    "*EmacsScreen.internalBorderWidth", XrmoptionSepArg, NULL},
  6910.  
  6911.   {"-T",    "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
  6912.   {"-wn",    "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
  6913.   {"-title",    "*EmacsShell.title", XrmoptionSepArg, (XtPointer) NULL},
  6914.   {"-iconname",    "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
  6915.   {"-in",    "*EmacsShell.iconName", XrmoptionSepArg, (XtPointer) NULL},
  6916.   {"-mc",    "*pointerColor", XrmoptionSepArg, (XtPointer) NULL},
  6917.   {"-cr",    "*cursorColor", XrmoptionSepArg, (XtPointer) NULL}
  6918. };
  6919. #endif /* USE_X_TOOLKIT */
  6920.  
  6921. static int x_initialized;
  6922.  
  6923. #ifdef MULTI_KBOARD
  6924. /* Test whether two display-name strings agree up to the dot that separates
  6925.    the screen number from the server number.  */
  6926. static int
  6927. same_x_server (name1, name2)
  6928.      char *name1, *name2;
  6929. {
  6930.   int seen_colon = 0;
  6931.   for (; *name1 != '\0' && *name1 == *name2; name1++, name2++)
  6932.     {
  6933.       if (*name1 == ':')
  6934.     seen_colon++;
  6935.       if (seen_colon && *name1 == '.')
  6936.     return 1;
  6937.     }
  6938.   return (seen_colon
  6939.       && (*name1 == '.' || *name1 == '\0')
  6940.       && (*name2 == '.' || *name2 == '\0'));
  6941. }
  6942. #endif
  6943.  
  6944. struct x_display_info *
  6945. x_term_init (display_name, xrm_option, resource_name)
  6946.      Lisp_Object display_name;
  6947.      char *xrm_option;
  6948.      char *resource_name;
  6949. {
  6950.   Lisp_Object frame;
  6951.   char *defaultvalue;
  6952.   int connection;
  6953.   Display *dpy;
  6954.   struct x_display_info *dpyinfo;
  6955.   XrmDatabase xrdb;
  6956.  
  6957.   BLOCK_INPUT;
  6958.  
  6959.   if (!x_initialized)
  6960.     {
  6961.       x_initialize ();
  6962.       x_initialized = 1;
  6963.     }
  6964.  
  6965. #ifdef HAVE_X_I18N
  6966.   setlocale (LC_ALL, "");
  6967.   /* In case we just overrode what init_lread did, redo it.  */
  6968.   setlocale (LC_NUMERIC, "C");
  6969. #endif
  6970.  
  6971. #ifdef USE_X_TOOLKIT
  6972.   /* weiner@footloose.sps.mot.com reports that this causes
  6973.      errors with X11R5:
  6974.        X protocol error: BadAtom (invalid Atom parameter)
  6975.        on protocol request 18skiloaf.
  6976.      So let's not use it until R6.  */
  6977. #ifdef HAVE_X11XTR6
  6978.   XtSetLanguageProc (NULL, NULL, NULL);
  6979. #endif
  6980.  
  6981.   {
  6982.     int argc = 0;
  6983.     char *argv[3];
  6984.  
  6985.     argv[0] = "";
  6986.     argc = 1;
  6987.     if (xrm_option)
  6988.       {
  6989.     argv[argc++] = "-xrm";
  6990.     argv[argc++] = xrm_option;
  6991.       }
  6992.     dpy = XtOpenDisplay (Xt_app_con, XSTRING (display_name)->data,
  6993.              resource_name, EMACS_CLASS,
  6994.              emacs_options, XtNumber (emacs_options),
  6995.              &argc, argv);
  6996.  
  6997. #ifdef HAVE_X11XTR6
  6998.     /* I think this is to compensate for XtSetLanguageProc.  */
  6999.     setlocale (LC_NUMERIC, "C");
  7000. #endif
  7001.   }
  7002.  
  7003. #else /* not USE_X_TOOLKIT */
  7004. #ifdef HAVE_X11R5
  7005.   XSetLocaleModifiers ("");
  7006. #endif
  7007.   dpy = XOpenDisplay (XSTRING (display_name)->data);
  7008. #endif /* not USE_X_TOOLKIT */
  7009.  
  7010.   /* Detect failure.  */
  7011.   if (dpy == 0)
  7012.     {
  7013.       UNBLOCK_INPUT;
  7014.       return 0;
  7015.     }
  7016.  
  7017.   /* We have definitely succeeded.  Record the new connection.  */
  7018.  
  7019.   dpyinfo = (struct x_display_info *) xmalloc (sizeof (struct x_display_info));
  7020.  
  7021. #ifdef MULTI_KBOARD
  7022.   {
  7023.     struct x_display_info *share;
  7024.     Lisp_Object tail;
  7025.  
  7026.     for (share = x_display_list, tail = x_display_name_list; share;
  7027.      share = share->next, tail = XCONS (tail)->cdr)
  7028.       if (same_x_server (XSTRING (XCONS (XCONS (tail)->car)->car)->data,
  7029.              XSTRING (display_name)->data))
  7030.     break;
  7031.     if (share)
  7032.       dpyinfo->kboard = share->kboard;
  7033.     else
  7034.       {
  7035.     dpyinfo->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
  7036.     init_kboard (dpyinfo->kboard);
  7037.     if (!EQ (XSYMBOL (Qvendor_specific_keysyms)->function, Qunbound))
  7038.       {
  7039.         char *vendor = ServerVendor (dpy);
  7040.         dpyinfo->kboard->Vsystem_key_alist
  7041.           = call1 (Qvendor_specific_keysyms,
  7042.                build_string (vendor ? vendor : ""));
  7043.       }
  7044.  
  7045.     dpyinfo->kboard->next_kboard = all_kboards;
  7046.     all_kboards = dpyinfo->kboard;
  7047.     /* Don't let the initial kboard remain current longer than necessary.
  7048.        That would cause problems if a file loaded on startup tries to
  7049.        prompt in the minibuffer.  */
  7050.     if (current_kboard == initial_kboard)
  7051.       current_kboard = dpyinfo->kboard;
  7052.       }
  7053.     dpyinfo->kboard->reference_count++;
  7054.   }
  7055. #endif
  7056.  
  7057.   /* Put this display on the chain.  */
  7058.   dpyinfo->next = x_display_list;
  7059.   x_display_list = dpyinfo;
  7060.  
  7061.   /* Put it on x_display_name_list as well, to keep them parallel.  */ 
  7062.   x_display_name_list = Fcons (Fcons (display_name, Qnil),
  7063.                    x_display_name_list);
  7064.   dpyinfo->name_list_element = XCONS (x_display_name_list)->car;
  7065.  
  7066.   dpyinfo->display = dpy;
  7067.  
  7068. #if 0
  7069.   XSetAfterFunction (x_current_display, x_trace_wire);
  7070. #endif /* ! 0 */
  7071.  
  7072.   dpyinfo->x_id_name
  7073.     = (char *) xmalloc (STRING_BYTES (XSTRING (Vinvocation_name))
  7074.             + STRING_BYTES (XSTRING (Vsystem_name))
  7075.             + 2);
  7076.   sprintf (dpyinfo->x_id_name, "%s@%s",
  7077.        XSTRING (Vinvocation_name)->data, XSTRING (Vsystem_name)->data);
  7078.  
  7079.   /* Figure out which modifier bits mean what.  */
  7080.   x_find_modifier_meanings (dpyinfo);
  7081.  
  7082.   /* Get the scroll bar cursor.  */
  7083.   dpyinfo->vertical_scroll_bar_cursor
  7084.     = XCreateFontCursor (dpyinfo->display, XC_sb_v_double_arrow);
  7085.  
  7086.   xrdb = x_load_resources (dpyinfo->display, xrm_option,
  7087.                resource_name, EMACS_CLASS);
  7088. #ifdef HAVE_XRMSETDATABASE
  7089.   XrmSetDatabase (dpyinfo->display, xrdb);
  7090. #else
  7091.   dpyinfo->display->db = xrdb;
  7092. #endif
  7093.   /* Put the rdb where we can find it in a way that works on
  7094.      all versions.  */
  7095.   dpyinfo->xrdb = xrdb;
  7096.  
  7097.   dpyinfo->screen = ScreenOfDisplay (dpyinfo->display,
  7098.                      DefaultScreen (dpyinfo->display));
  7099.   dpyinfo->visual = select_visual (dpyinfo->display, dpyinfo->screen,
  7100.                    &dpyinfo->n_planes);
  7101.   dpyinfo->height = HeightOfScreen (dpyinfo->screen);
  7102.   dpyinfo->width = WidthOfScreen (dpyinfo->screen);
  7103.   dpyinfo->root_window = RootWindowOfScreen (dpyinfo->screen);
  7104.   dpyinfo->grabbed = 0;
  7105.   dpyinfo->reference_count = 0;
  7106.   dpyinfo->icon_bitmap_id = -1;
  7107.   dpyinfo->n_fonts = 0;
  7108.   dpyinfo->font_table_size = 0;
  7109.   dpyinfo->bitmaps = 0;
  7110.   dpyinfo->bitmaps_size = 0;
  7111.   dpyinfo->bitmaps_last = 0;
  7112.   dpyinfo->scratch_cursor_gc = 0;
  7113.   dpyinfo->mouse_face_mouse_frame = 0;
  7114.   dpyinfo->mouse_face_deferred_gc = 0;
  7115.   dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
  7116.   dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
  7117.   dpyinfo->mouse_face_face_id = 0;
  7118.   dpyinfo->mouse_face_window = Qnil;
  7119.   dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
  7120.   dpyinfo->mouse_face_defer = 0;
  7121.   dpyinfo->x_focus_frame = 0;
  7122.   dpyinfo->x_focus_event_frame = 0;
  7123.   dpyinfo->x_highlight_frame = 0;
  7124.  
  7125.   dpyinfo->Xatom_wm_protocols
  7126.     = XInternAtom (dpyinfo->display, "WM_PROTOCOLS", False);
  7127.   dpyinfo->Xatom_wm_take_focus
  7128.     = XInternAtom (dpyinfo->display, "WM_TAKE_FOCUS", False);
  7129.   dpyinfo->Xatom_wm_save_yourself
  7130.     = XInternAtom (dpyinfo->display, "WM_SAVE_YOURSELF", False);
  7131.   dpyinfo->Xatom_wm_delete_window
  7132.     = XInternAtom (dpyinfo->display, "WM_DELETE_WINDOW", False);
  7133.   dpyinfo->Xatom_wm_change_state
  7134.     = XInternAtom (dpyinfo->display, "WM_CHANGE_STATE", False);
  7135.   dpyinfo->Xatom_wm_configure_denied
  7136.     = XInternAtom (dpyinfo->display, "WM_CONFIGURE_DENIED", False);
  7137.   dpyinfo->Xatom_wm_window_moved
  7138.     = XInternAtom (dpyinfo->display, "WM_MOVED", False);
  7139.   dpyinfo->Xatom_editres
  7140.     = XInternAtom (dpyinfo->display, "Editres", False);
  7141.   dpyinfo->Xatom_CLIPBOARD
  7142.     = XInternAtom (dpyinfo->display, "CLIPBOARD", False);
  7143.   dpyinfo->Xatom_TIMESTAMP
  7144.     = XInternAtom (dpyinfo->display, "TIMESTAMP", False);
  7145.   dpyinfo->Xatom_TEXT
  7146.     = XInternAtom (dpyinfo->display, "TEXT", False);
  7147.   dpyinfo->Xatom_COMPOUND_TEXT
  7148.     = XInternAtom (dpyinfo->display, "COMPOUND_TEXT", False);
  7149.   dpyinfo->Xatom_DELETE
  7150.     = XInternAtom (dpyinfo->display, "DELETE", False);
  7151.   dpyinfo->Xatom_MULTIPLE
  7152.     = XInternAtom (dpyinfo->display, "MULTIPLE", False);
  7153.   dpyinfo->Xatom_INCR
  7154.     = XInternAtom (dpyinfo->display, "INCR", False);
  7155.   dpyinfo->Xatom_EMACS_TMP
  7156.     = XInternAtom (dpyinfo->display, "_EMACS_TMP_", False);
  7157.   dpyinfo->Xatom_TARGETS
  7158.     = XInternAtom (dpyinfo->display, "TARGETS", False);
  7159.   dpyinfo->Xatom_NULL
  7160.     = XInternAtom (dpyinfo->display, "NULL", False);
  7161.   dpyinfo->Xatom_ATOM_PAIR
  7162.     = XInternAtom (dpyinfo->display, "ATOM_PAIR", False);
  7163.   /* For properties of font.  */
  7164.   dpyinfo->Xatom_PIXEL_SIZE
  7165.     = XInternAtom (dpyinfo->display, "PIXEL_SIZE", False);
  7166.   dpyinfo->Xatom_MULE_BASELINE_OFFSET
  7167.     = XInternAtom (dpyinfo->display, "_MULE_BASELINE_OFFSET", False);
  7168.   dpyinfo->Xatom_MULE_RELATIVE_COMPOSE
  7169.     = XInternAtom (dpyinfo->display, "_MULE_RELATIVE_COMPOSE", False);
  7170.   dpyinfo->Xatom_MULE_DEFAULT_ASCENT
  7171.     = XInternAtom (dpyinfo->display, "_MULE_DEFAULT_ASCENT", False);
  7172.  
  7173.   dpyinfo->cut_buffers_initialized = 0;
  7174.  
  7175.   connection = ConnectionNumber (dpyinfo->display);
  7176.   dpyinfo->connection = connection;
  7177.  
  7178.   {
  7179.     char null_bits[1];
  7180.  
  7181.     null_bits[0] = 0x00;
  7182.  
  7183.     dpyinfo->null_pixel
  7184.       = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window, 
  7185.                      null_bits, 1, 1, (long) 0, (long) 0,
  7186.                      1);
  7187.   }
  7188.  
  7189. #ifdef subprocesses
  7190.   /* This is only needed for distinguishing keyboard and process input.  */
  7191.   if (connection != 0)
  7192.     add_keyboard_wait_descriptor (connection);
  7193. #endif
  7194.  
  7195. #ifndef F_SETOWN_BUG
  7196. #ifdef F_SETOWN
  7197. #ifdef F_SETOWN_SOCK_NEG
  7198.   /* stdin is a socket here */
  7199.   fcntl (connection, F_SETOWN, -getpid ());
  7200. #else /* ! defined (F_SETOWN_SOCK_NEG) */
  7201.   fcntl (connection, F_SETOWN, getpid ());
  7202. #endif /* ! defined (F_SETOWN_SOCK_NEG) */
  7203. #endif /* ! defined (F_SETOWN) */
  7204. #endif /* F_SETOWN_BUG */
  7205.  
  7206. #ifdef SIGIO
  7207.   if (interrupt_input)
  7208.     init_sigio (connection);
  7209. #endif /* ! defined (SIGIO) */
  7210.  
  7211. #ifdef USE_LUCID
  7212. #ifdef HAVE_X11R5 /* It seems X11R4 lacks XtCvtStringToFont, and XPointer.  */
  7213.   /* Make sure that we have a valid font for dialog boxes
  7214.      so that Xt does not crash.  */
  7215.   {
  7216.     Display *dpy = dpyinfo->display;
  7217.     XrmValue d, fr, to;
  7218.     Font font;
  7219.     int count;
  7220.     
  7221.     d.addr = (XPointer)&dpy;
  7222.     d.size = sizeof (Display *);
  7223.     fr.addr = XtDefaultFont;
  7224.     fr.size = sizeof (XtDefaultFont);
  7225.     to.size = sizeof (Font *);
  7226.     to.addr = (XPointer)&font;
  7227.     count = x_catch_errors (dpy);
  7228.     if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
  7229.       abort ();
  7230.     if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
  7231.       XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
  7232.     x_uncatch_errors (dpy, count);
  7233.   }
  7234. #endif
  7235. #endif
  7236.  
  7237.  
  7238.   UNBLOCK_INPUT;
  7239.  
  7240.   return dpyinfo;
  7241. }
  7242.  
  7243. /* Get rid of display DPYINFO, assuming all frames are already gone,
  7244.    and without sending any more commands to the X server.  */
  7245.  
  7246. void
  7247. x_delete_display (dpyinfo)
  7248.      struct x_display_info *dpyinfo;
  7249. {
  7250.   delete_keyboard_wait_descriptor (dpyinfo->connection);
  7251.  
  7252.   /* Discard this display from x_display_name_list and x_display_list.
  7253.      We can't use Fdelq because that can quit.  */
  7254.   if (! NILP (x_display_name_list)
  7255.       && EQ (XCONS (x_display_name_list)->car, dpyinfo->name_list_element))
  7256.     x_display_name_list = XCONS (x_display_name_list)->cdr;
  7257.   else
  7258.     {
  7259.       Lisp_Object tail;
  7260.  
  7261.       tail = x_display_name_list;
  7262.       while (CONSP (tail) && CONSP (XCONS (tail)->cdr))
  7263.     {
  7264.       if (EQ (XCONS (XCONS (tail)->cdr)->car,
  7265.           dpyinfo->name_list_element))
  7266.         {
  7267.           XCONS (tail)->cdr = XCONS (XCONS (tail)->cdr)->cdr;
  7268.           break;
  7269.         }
  7270.       tail = XCONS (tail)->cdr;
  7271.     }
  7272.     }
  7273.  
  7274.   if (x_display_list == dpyinfo)
  7275.     x_display_list = dpyinfo->next;
  7276.   else
  7277.     {
  7278.       struct x_display_info *tail;
  7279.  
  7280.       for (tail = x_display_list; tail; tail = tail->next)
  7281.     if (tail->next == dpyinfo)
  7282.       tail->next = tail->next->next;
  7283.     }
  7284.  
  7285. #ifndef USE_X_TOOLKIT   /* I'm told Xt does this itself.  */
  7286. #ifndef AIX        /* On AIX, XCloseDisplay calls this.  */
  7287.   XrmDestroyDatabase (dpyinfo->xrdb);
  7288. #endif
  7289. #endif
  7290. #ifdef MULTI_KBOARD
  7291.   if (--dpyinfo->kboard->reference_count == 0)
  7292.     delete_kboard (dpyinfo->kboard);
  7293. #endif
  7294.   xfree (dpyinfo->font_table);
  7295.   xfree (dpyinfo->x_id_name);
  7296.   xfree (dpyinfo);
  7297. }
  7298.  
  7299. /* Set up use of X before we make the first connection.  */
  7300.  
  7301. void
  7302. x_initialize ()
  7303. {
  7304.   clear_frame_hook = XTclear_frame;
  7305.   clear_end_of_line_hook = XTclear_end_of_line;
  7306.   ins_del_lines_hook = XTins_del_lines;
  7307.   change_line_highlight_hook = XTchange_line_highlight;
  7308.   insert_glyphs_hook = XTinsert_glyphs;
  7309.   write_glyphs_hook = XTwrite_glyphs;
  7310.   delete_glyphs_hook = XTdelete_glyphs;
  7311.   ring_bell_hook = XTring_bell;
  7312.   reset_terminal_modes_hook = XTreset_terminal_modes;
  7313.   set_terminal_modes_hook = XTset_terminal_modes;
  7314.   update_begin_hook = XTupdate_begin;
  7315.   update_end_hook = XTupdate_end;
  7316.   set_terminal_window_hook = XTset_terminal_window;
  7317.   read_socket_hook = XTread_socket;
  7318.   frame_up_to_date_hook = XTframe_up_to_date;
  7319.   cursor_to_hook = XTcursor_to;
  7320.   reassert_line_highlight_hook = XTreassert_line_highlight;
  7321.   mouse_position_hook = XTmouse_position;
  7322.   frame_rehighlight_hook = XTframe_rehighlight;
  7323.   frame_raise_lower_hook = XTframe_raise_lower;
  7324.   set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
  7325.   condemn_scroll_bars_hook = XTcondemn_scroll_bars;
  7326.   redeem_scroll_bar_hook = XTredeem_scroll_bar;
  7327.   judge_scroll_bars_hook = XTjudge_scroll_bars;
  7328.  
  7329.   scroll_region_ok = 1;        /* we'll scroll partial frames */
  7330.   char_ins_del_ok = 0;        /* just as fast to write the line */
  7331.   line_ins_del_ok = 1;        /* we'll just blt 'em */
  7332.   fast_clear_end_of_line = 1;    /* X does this well */
  7333.   memory_below_frame = 0;    /* we don't remember what scrolls
  7334.                    off the bottom */
  7335.   baud_rate = 19200;
  7336.  
  7337.   x_noop_count = 0;
  7338.  
  7339.   /* Try to use interrupt input; if we can't, then start polling.  */
  7340.   Fset_input_mode (Qt, Qnil, Qt, Qnil);
  7341.  
  7342. #ifdef USE_X_TOOLKIT
  7343.   XtToolkitInitialize ();
  7344.   Xt_app_con = XtCreateApplicationContext ();
  7345.   XtAppSetFallbackResources (Xt_app_con, Xt_default_resources);
  7346. #endif
  7347.  
  7348.   /* Note that there is no real way portable across R3/R4 to get the
  7349.      original error handler.  */
  7350.   XSetErrorHandler (x_error_handler);
  7351.   XSetIOErrorHandler (x_io_error_quitter);
  7352.  
  7353.   /* Disable Window Change signals;  they are handled by X events. */
  7354. #ifdef SIGWINCH
  7355.   signal (SIGWINCH, SIG_DFL);
  7356. #endif /* ! defined (SIGWINCH) */
  7357.  
  7358.   signal (SIGPIPE, x_connection_signal);
  7359. }
  7360.  
  7361. void
  7362. syms_of_xterm ()
  7363. {
  7364.   staticpro (&x_error_message_string);
  7365.   x_error_message_string = Qnil;
  7366.  
  7367.   staticpro (&x_display_name_list);
  7368.   x_display_name_list = Qnil;
  7369.  
  7370.   staticpro (&last_mouse_scroll_bar);
  7371.   last_mouse_scroll_bar = Qnil;
  7372.  
  7373.   staticpro (&Qvendor_specific_keysyms);
  7374.   Qvendor_specific_keysyms = intern ("vendor-specific-keysyms");
  7375.  
  7376.   staticpro (&last_mouse_press_frame);
  7377.   last_mouse_press_frame = Qnil;
  7378. }
  7379.  
  7380. #endif /* not HAVE_X_WINDOWS */
  7381.