/* The event_stream interface for X11 with Xt, and/or tty frames.
   Copyright (C) 1991-5, 1997 Free Software Foundation, Inc.
   Copyright (C) 1995 Sun Microsystems, Inc.
   Copyright (C) 1996, 2001, 2002, 2003, 2010 Ben Wing.
   Copyright (C) 2010 Didier Verna

This file is part of XEmacs.

XEmacs is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.

XEmacs is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with XEmacs.  If not, see <http://www.gnu.org/licenses/>. */

/* Synched up with: Not in FSF. */

/* NOTE: It would be possible to fix things so that all of GTK, Windows, X,
   TTY and stream can have consoles at the same time.  We already do lots
   of combinations.  Basically, either call select() directly or some
   interface onto it, and select() over all the filedescs, including the
   X and GTK socket, and under Cygwin, the Windows device.  Then for whichever
   filedesc there's an event, call the appropriate window-system-specific
   method to pull the event(s) and store onto the dispatch queue. --ben */

#include <config.h>
#include "lisp.h"

#include "blocktype.h"
#include "charset.h"
#include "console.h"
#include "device-impl.h"
#include "elhash.h"
#include "events.h"
#include "file-coding.h"
#include "frame-impl.h"
#include "glyphs.h"
#include "lstream.h"
#include "process.h"
#include "redisplay.h"
#include "window.h"

#include "console-tty.h"

#include "console-x-impl.h"
#include "fontcolor-x.h"
#include "../lwlib/lwlib.h"
#include "EmacsFrame.h"

#include "sysproc.h" /* for MAXDESC */
#include "systime.h"

#include "xintrinsicp.h"	/* CoreP.h needs this */
#include <X11/CoreP.h>		/* Numerous places access the fields of
				   a core widget directly.  We could
				   use XtGetValues(), but ... */
#include <X11/ShellP.h>

#if defined (HAVE_XIM) && defined (XIM_MOTIF)
#include "xmotif.h"
#endif

#ifdef HAVE_DRAGNDROP
#include "dragdrop.h"
#endif

#ifdef WIN32_ANY
extern int mswindows_is_blocking;
#endif

/* For Russian C-x processing. */
Lisp_Object Vx_us_keymap_description;
Fixnum Vx_us_keymap_first_keycode;

/* used in glyphs-x.c */
void enqueue_focus_event (Widget wants_it, Lisp_Object frame, int in_p);
static void handle_focus_event_1 (struct frame *f, int in_p);
static void handle_focus_event_2 (Window w, struct frame *f, int in_p);

static struct event_stream *Xt_event_stream;

/* With the new event model, all events go through XtDispatchEvent()
   and are picked up by an event handler that is added to each frame
   widget. (This is how it's supposed to be.) In the old method,
   Emacs sucks out events directly from XtNextEvent() and only
   dispatches the events that it doesn't need to deal with.  This
   old way has lots of corresponding junk that is no longer
   necessary: lwlib extensions, synthetic XAnyEvents, unnecessary
   magic events, etc. */

/* The one and only one application context that Emacs uses. */
XtAppContext Xt_app_con;

/* Do we accept events sent by other clients? */
int x_allow_sendevents;

#ifdef DEBUG_XEMACS
Fixnum debug_x_events;
#endif

static int process_events_occurred;
static int tty_events_occurred;
static Widget widget_with_focus;

/* Mask of bits indicating the descriptors that we wait for input on */
extern SELECT_TYPE input_wait_mask, non_fake_input_wait_mask;
extern SELECT_TYPE process_only_mask, tty_only_mask;

/* #### This should be String, but G++ 4.3 doesn't apply the const
   specifier the same way for String (typedef'd to char*) and char*. */
static const char * x_fallback_resources[] =
{
  /* This file is automatically generated from the app-defaults file
     in ../etc/Emacs.ad.  These resources are consulted only if no
     app-defaults file is found at all.
   */
#include <Emacs.ad.h>
  0
};

static Lisp_Object x_keysym_to_emacs_keysym (KeySym keysym, int simple_p);
void emacs_Xt_mapping_action (Widget w, XEvent *event);
void debug_process_finalization (Lisp_Process *p);
void emacs_Xt_event_handler (Widget wid, XtPointer closure, XEvent *event,
			     Boolean *continue_to_dispatch);

static int last_quit_check_signal_tick_count;

#define THIS_IS_X
#include "event-xlike-inc.c"


/************************************************************************/
/*                            keymap handling                           */
/************************************************************************/

/* See comment near character_to_event(). */
static void
maybe_define_x_key_as_self_inserting_character (KeySym keysym,
						Lisp_Object symbol)
{
  Lisp_Object character = x_keysym_to_character (keysym);

  if (CHARP (character))
    {
      extern Lisp_Object Vcurrent_global_map;
      extern Lisp_Object Qcharacter_of_keysym;
      if (NILP (Flookup_key (Vcurrent_global_map, symbol, Qnil))) 
        {
	  Fput (symbol, Qcharacter_of_keysym, character);
	  Fdefine_key (Vcurrent_global_map, symbol, Qself_insert_command); 
        }
    }
}

void
x_has_keysym (KeySym keysym, Lisp_Object hash_table, int with_modifiers)
{
  KeySym upper_lower[2];
  int j;

  if (keysym < 0x80) /* Optimize for ASCII keysyms */
    return;

  /* If you execute:
     xmodmap -e 'keysym NN = scaron'
     and then press (Shift scaron), X11 will return the different
     keysym `Scaron', but  `xmodmap -pke'  might not even mention `Scaron'.
     So we "register" both `scaron' and `Scaron'. */
#ifdef HAVE_XCONVERTCASE
  XConvertCase (keysym, &upper_lower[0], &upper_lower[1]);
#else
  upper_lower[0] = upper_lower[1] = keysym;
#endif

  for (j = 0; j < (upper_lower[0] == upper_lower[1] ? 1 : 2); j++)
    {
      KeySym ks = upper_lower[j];
      Lisp_Object sym = x_keysym_to_emacs_keysym (ks, 0);
      Lisp_Object new_value = with_modifiers ? Qt : Qsans_modifiers;
      Lisp_Object old_value = Fgethash (sym, hash_table, Qnil);

      if (! EQ (old_value, new_value)
          && ! (EQ (old_value, Qsans_modifiers) &&
                EQ (new_value, Qt)))
        {
          maybe_define_x_key_as_self_inserting_character (ks, sym);
          Fputhash (sym, new_value, hash_table);
	}
    }
}

static void
x_reset_key_mapping (struct device *d)
{
  Display *display = DEVICE_X_DISPLAY (d);
  struct x_device *xd = DEVICE_X_DATA (d);
  KeySym *keysym, *keysym_end;
  Lisp_Object hash_table;
  int key_code_count, keysyms_per_code;

  if (xd->x_keysym_map)
    XFree ((char *) xd->x_keysym_map);
  XDisplayKeycodes (display,
		    &xd->x_keysym_map_min_code,
		    &xd->x_keysym_map_max_code);
  key_code_count = xd->x_keysym_map_max_code - xd->x_keysym_map_min_code + 1;
  xd->x_keysym_map =
    XGetKeyboardMapping (display, xd->x_keysym_map_min_code, key_code_count,
			 &xd->x_keysym_map_keysyms_per_code);

  hash_table = xd->x_keysym_map_hash_table;
  if (HASH_TABLEP (hash_table))
    Fclrhash (hash_table);
  else
    xd->x_keysym_map_hash_table = hash_table =
      make_lisp_hash_table (128, HASH_TABLE_NON_WEAK, Qequal);

  for (keysym = xd->x_keysym_map,
	 keysyms_per_code = xd->x_keysym_map_keysyms_per_code,
	 keysym_end = keysym + (key_code_count * keysyms_per_code);
       keysym < keysym_end;
       keysym += keysyms_per_code)
    {
      int j;

      if (keysym[0] == NoSymbol)
	continue;

      x_has_keysym (keysym[0], hash_table, 0);

      for (j = 1; j < keysyms_per_code; j++)
	{
	  if (keysym[j] != keysym[0] &&
	      keysym[j] != NoSymbol)
	    x_has_keysym (keysym[j], hash_table, 1);
	}
    }
}

static const Ascbyte *
index_to_name (int indice)
{
  switch (indice)
    {
    case ShiftMapIndex:   return "ModShift";
    case LockMapIndex:    return "ModLock";
    case ControlMapIndex: return "ModControl";
    case Mod1MapIndex:    return "Mod1";
    case Mod2MapIndex:    return "Mod2";
    case Mod3MapIndex:    return "Mod3";
    case Mod4MapIndex:    return "Mod4";
    case Mod5MapIndex:    return "Mod5";
    default:              return "???";
    }
}

/* X bogusly doesn't define the interpretations of any bits besides
   ModControl, ModShift, and ModLock; so the Interclient Communication
   Conventions Manual says that we have to bend over backwards to figure
   out what the other modifier bits mean.  According to ICCCM:

   - Any keycode which is assigned ModControl is a "control" key.

   - Any modifier bit which is assigned to a keycode which generates Meta_L
     or Meta_R is the modifier bit meaning "meta".  Likewise for Super, Hyper,
     etc.

   - Any keypress event which contains ModControl in its state should be
     interpreted as a "control" character.

   - Any keypress event which contains a modifier bit in its state which is
     generated by a keycode whose corresponding keysym is Meta_L or Meta_R
     should be interpreted as a "meta" character.  Likewise for Super, Hyper,
     etc.

   - It is illegal for a keysym to be associated with more than one modifier
     bit.

   This means that the only thing that emacs can reasonably interpret as a
   "meta" key is a key whose keysym is Meta_L or Meta_R, and which generates
   one of the modifier bits Mod1-Mod5.

   Unfortunately, many keyboards don't have Meta keys in their default
   configuration.  So, if there are no Meta keys, but there are "Alt" keys,
   emacs will interpret Alt as Meta.  If there are both Meta and Alt keys,
   then the Meta keys mean "Meta", and the Alt keys mean "Alt" (it used to
   mean "Symbol," but that just confused the hell out of way too many people).

   This works with the default configurations of the 19 keyboard-types I've
   checked.

   Emacs detects keyboard configurations which violate the above rules, and
   gives a warning. */

static void
x_reset_modifier_mapping (struct device *d)
{
  Display *display = DEVICE_X_DISPLAY (d);
  struct x_device *xd = DEVICE_X_DATA (d);
  int modifier_index, modifier_key, column, mkpm;
  int warned_about_overlapping_modifiers = 0;
  int warned_about_predefined_modifiers  = 0;
  int warned_about_duplicate_modifiers   = 0;
  int meta_bit  = 0;
  int hyper_bit = 0;
  int super_bit = 0;
  int alt_bit   = 0;
  int mode_bit  = 0;

  xd->lock_interpretation = 0;

  if (xd->x_modifier_keymap)
    {
      XFreeModifiermap (xd->x_modifier_keymap);
      /* Set it to NULL in case we receive two MappingModifier events in a
         row, and the second is processed during some CHECK_QUITs within
         x_reset_key_mapping. If that happens, XFreeModifierMap will be
         called twice on the same map, and we crash.  */
      xd->x_modifier_keymap = NULL;
    }

  x_reset_key_mapping (d);

  xd->x_modifier_keymap = XGetModifierMapping (display);

  /* Boy, I really wish C had local functions...
   */

#define modwarn(name,old,other)					\
  warn_when_safe (Qkey_mapping, Qwarning,			\
 "XEmacs:  %s (0x%x) generates %s, which is generated by %s.",	\
		  name, code, index_to_name (old), other),	\
  warned_about_overlapping_modifiers = 1

#define modbarf(name,other)					\
  warn_when_safe (Qkey_mapping, Qwarning,			\
 "XEmacs:  %s (0x%x) generates %s, which is nonsensical.",	\
		  name, code, other),				\
  warned_about_predefined_modifiers = 1

#define check_modifier(name,mask)					\
  if ((1<<modifier_index) != mask)					\
    warn_when_safe (Qkey_mapping, Qwarning,				\
 "XEmacs:  %s (0x%x) generates %s, which is nonsensical.",		\
		    name, code, index_to_name (modifier_index)),	\
    warned_about_predefined_modifiers = 1

#define store_modifier(name,old)					\
  if (old && old != modifier_index)					\
    warn_when_safe (Qkey_mapping, Qwarning,				\
 "XEmacs:  %s (0x%x) generates both %s and %s, which is nonsensical.",	\
		    name, code, index_to_name (old),			\
		    index_to_name (modifier_index)),			\
    warned_about_duplicate_modifiers = 1;				\
  if (modifier_index == ShiftMapIndex) modbarf (name,"ModShift");	\
  else if (modifier_index == LockMapIndex) modbarf (name,"ModLock");	\
  else if (modifier_index == ControlMapIndex) modbarf (name,"ModControl"); \
  else if (sym == XK_Mode_switch)					\
    mode_bit = modifier_index; /* Mode_switch is special, see below... */ \
  else if (modifier_index == meta_bit && old != meta_bit)		\
    modwarn (name, meta_bit, "Meta");					\
  else if (modifier_index == super_bit && old != super_bit)		\
    modwarn (name, super_bit, "Super");					\
  else if (modifier_index == hyper_bit && old != hyper_bit)		\
    modwarn (name, hyper_bit, "Hyper");					\
  else if (modifier_index == alt_bit && old != alt_bit)			\
    modwarn (name, alt_bit, "Alt");					\
  else									\
    old = modifier_index;

  mkpm = xd->x_modifier_keymap->max_keypermod;
  for (modifier_index = 0; modifier_index < 8; modifier_index++)
    for (modifier_key = 0; modifier_key < mkpm; modifier_key++) {
      KeySym last_sym = 0;
      for (column = 0; column < 4; column += 2) {
	KeyCode code = xd->x_modifier_keymap->modifiermap[modifier_index * mkpm
							  + modifier_key];
	KeySym sym = (code ? XKeycodeToKeysym (display, code, column) : 0);
	if (sym == last_sym) continue;
	last_sym = sym;
	switch (sym) {
	case XK_Mode_switch:store_modifier ("Mode_switch", mode_bit); break;
	case XK_Meta_L:     store_modifier ("Meta_L", meta_bit); break;
	case XK_Meta_R:     store_modifier ("Meta_R", meta_bit); break;
	case XK_Super_L:    store_modifier ("Super_L", super_bit); break;
	case XK_Super_R:    store_modifier ("Super_R", super_bit); break;
	case XK_Hyper_L:    store_modifier ("Hyper_L", hyper_bit); break;
	case XK_Hyper_R:    store_modifier ("Hyper_R", hyper_bit); break;
	case XK_Alt_L:      store_modifier ("Alt_L", alt_bit); break;
	case XK_Alt_R:      store_modifier ("Alt_R", alt_bit); break;
	case XK_Control_L:  check_modifier ("Control_L", ControlMask); break;
	case XK_Control_R:  check_modifier ("Control_R", ControlMask); break;
	case XK_Shift_L:    check_modifier ("Shift_L", ShiftMask); break;
	case XK_Shift_R:    check_modifier ("Shift_R", ShiftMask); break;
	case XK_Shift_Lock: check_modifier ("Shift_Lock", LockMask);
	  xd->lock_interpretation = XK_Shift_Lock; break;
	case XK_Caps_Lock:  check_modifier ("Caps_Lock", LockMask);
	  xd->lock_interpretation = XK_Caps_Lock; break;

	/* It probably doesn't make any sense for a modifier bit to be
	   assigned to a key that is not one of the above, but OpenWindows
	   assigns modifier bits to a couple of random function keys for
	   no reason that I can discern, so printing a warning here would
	   be annoying. */
	}
      }
    }
#undef store_modifier
#undef check_modifier
#undef modwarn
#undef modbarf

  /* If there was no Meta key, then try using the Alt key instead.
     If there is both a Meta key and an Alt key, then the Alt key
     is not disturbed and remains an Alt key. */
  if (! meta_bit && alt_bit)
    meta_bit = alt_bit, alt_bit = 0;

  /* mode_bit overrides everything, since it's processed down inside of
     XLookupString() instead of by us.  If Meta and Mode_switch both
     generate the same modifier bit (which is an error), then we don't
     interpret that bit as Meta, because we can't make XLookupString()
     not interpret it as Mode_switch; and interpreting it as both would
     be totally wrong. */
  if (mode_bit)
    {
      const Ascbyte *warn = 0;
      if      (mode_bit == meta_bit)  warn = "Meta",  meta_bit  = 0;
      else if (mode_bit == hyper_bit) warn = "Hyper", hyper_bit = 0;
      else if (mode_bit == super_bit) warn = "Super", super_bit = 0;
      else if (mode_bit == alt_bit)   warn = "Alt",   alt_bit   = 0;
      if (warn)
	{
	  warn_when_safe
	    (Qkey_mapping, Qwarning,
	     "XEmacs:  %s is being used for both Mode_switch and %s.",
	     index_to_name (mode_bit), warn),
	    warned_about_overlapping_modifiers = 1;
	}
    }
#undef index_to_name

  xd->MetaMask   = (meta_bit   ? (1 << meta_bit)  : 0);
  xd->HyperMask  = (hyper_bit  ? (1 << hyper_bit) : 0);
  xd->SuperMask  = (super_bit  ? (1 << super_bit) : 0);
  xd->AltMask    = (alt_bit    ? (1 << alt_bit)   : 0);
  xd->ModeMask   = (mode_bit   ? (1 << mode_bit)  : 0); /* unused */


  if (warned_about_overlapping_modifiers)
    warn_when_safe (Qkey_mapping, Qwarning, "\n"
"	Two distinct modifier keys (such as Meta and Hyper) cannot generate\n"
"	the same modifier bit, because Emacs won't be able to tell which\n"
"	modifier was actually held down when some other key is pressed.  It\n"
"	won't be able to tell Meta-x and Hyper-x apart, for example.  Change\n"
"	one of these keys to use some other modifier bit.  If you intend for\n"
"	these keys to have the same behavior, then change them to have the\n"
"	same keysym as well as the same modifier bit.");

  if (warned_about_predefined_modifiers)
    warn_when_safe (Qkey_mapping, Qwarning, "\n"
"	The semantics of the modifier bits ModShift, ModLock, and ModControl\n"
"	are predefined.  It does not make sense to assign ModControl to any\n"
"	keysym other than Control_L or Control_R, or to assign any modifier\n"
"	bits to the \"control\" keysyms other than ModControl.  You can't\n"
"	turn a \"control\" key into a \"meta\" key (or vice versa) by simply\n"
"	assigning the key a different modifier bit.  You must also make that\n"
"	key generate an appropriate keysym (Control_L, Meta_L, etc).");

  /* No need to say anything more for warned_about_duplicate_modifiers. */

  if (warned_about_overlapping_modifiers || warned_about_predefined_modifiers)
    warn_when_safe (Qkey_mapping, Qwarning, "\n"
"	The meanings of the modifier bits Mod1 through Mod5 are determined\n"
"	by the keysyms used to control those bits.  Mod1 does NOT always\n"
"	mean Meta, although some non-ICCCM-compliant programs assume that.");
}

void
x_init_modifier_mapping (struct device *d)
{
  struct x_device *xd = DEVICE_X_DATA (d);
  xd->x_keysym_map_hash_table = Qnil;
  xd->x_keysym_map = NULL;
  xd->x_modifier_keymap = NULL;
  x_reset_modifier_mapping (d);
}

static int
x_key_is_modifier_p (KeyCode keycode, struct device *d)
{
  struct x_device *xd = DEVICE_X_DATA (d);
  KeySym *syms;
  int i;

  if (keycode < xd->x_keysym_map_min_code ||
      keycode > xd->x_keysym_map_max_code)
    return 0;

  syms = &xd->x_keysym_map [(keycode - xd->x_keysym_map_min_code) *
			   xd->x_keysym_map_keysyms_per_code];
  for (i = 0; i < xd->x_keysym_map_keysyms_per_code; i++)
    if (IsModifierKey (syms [i]) ||
	syms [i] == XK_Mode_switch) /* why doesn't IsModifierKey count this? */
      return 1;
  return 0;
}

/* key-handling code is always ugly.  It just ends up working out
   that way.

   Here are some pointers:

   -- DOWN_MASK indicates which modifiers should be treated as "down"
      when the corresponding upstroke happens.  It gets reset for
      a particular modifier when that modifier goes up, and reset
      for all modifiers when a non-modifier key is pressed.  Example:

      I press Control-A-Shift and then release Control-A-Shift.
      I want the Shift key to be sticky but not the Control key.

   -- LAST_DOWNKEY and RELEASE_TIME are used to keep track of
      auto-repeat -- see below.

   -- If a modifier key is sticky, I can unstick it by pressing
      the modifier key again. */

static void
x_handle_sticky_modifiers (XEvent *ev, struct device *d)
{
  struct x_device *xd;
  KeyCode keycode;
  int type;

  if (!modifier_keys_are_sticky) /* Optimize for non-sticky modifiers */
    return;

  xd = DEVICE_X_DATA (d);
  keycode = ev->xkey.keycode;
  type = ev->type;

  if (keycode < xd->x_keysym_map_min_code ||
      keycode > xd->x_keysym_map_max_code)
    return;

  if (! ((type == KeyPress || type == KeyRelease) &&
         x_key_is_modifier_p (keycode, d)))
    { /* Not a modifier key */
      Bool key_event_p = (type == KeyPress || type == KeyRelease);

      if (type == ButtonPress
	  || (type == KeyPress
	      && ((xd->last_downkey
		   && ((keycode != xd->last_downkey
			|| ev->xkey.time != xd->release_time)))
		  || (FIXNUMP (Vmodifier_keys_sticky_time)
		      && ev->xkey.time
		      > (xd->modifier_release_time
			 + XFIXNUM (Vmodifier_keys_sticky_time))))))
	{
	  xd->need_to_add_mask = 0;
	  xd->last_downkey = 0;
	}
      else if (type == KeyPress && !xd->last_downkey)
	xd->last_downkey = keycode;

      if (type == KeyPress)
	xd->release_time = 0;
      if (type == KeyPress || type == ButtonPress)
	{
	  xd->down_mask = 0;
	  xd->modifier_release_time = 0;
	}

      if (key_event_p)
        ev->xkey.state    |= xd->need_to_add_mask;
      else
        ev->xbutton.state |= xd->need_to_add_mask;

      if (type == KeyRelease && keycode == xd->last_downkey)
	/* If I hold press-and-release the Control key and then press
	   and hold down the right arrow, I want it to auto-repeat
	   Control-Right.  On the other hand, if I do the same but
	   manually press the Right arrow a bunch of times, I want
	   to see one Control-Right and then a bunch of Rights.
	   This means that we need to distinguish between an
	   auto-repeated key and a key pressed and released a bunch
	   of times.

	   Naturally, the designers of the X spec didn't see fit
	   to provide an obvious way to distinguish these cases.
	   So we assume that if the release and the next press
	   occur at the same time, the key was actually auto-
	   repeated.  Under Open-Windows, at least, this works. */
	xd->modifier_release_time = xd->release_time
	  = key_event_p ? ev->xkey.time : ev->xbutton.time;
    }
  else                          /* Modifier key pressed */
    {
      int i;
      KeySym *syms = &xd->x_keysym_map [(keycode - xd->x_keysym_map_min_code) *
					xd->x_keysym_map_keysyms_per_code];

      /* If a non-modifier key was pressed in the middle of a bunch
	 of modifiers, then it unsticks all the modifiers that were
	 previously pressed.  We cannot unstick the modifiers until
	 now because we want to check for auto-repeat of the
	 non-modifier key. */

      if (xd->last_downkey)
	{
	  xd->last_downkey = 0;
	  xd->need_to_add_mask = 0;
	}

      if (xd->modifier_release_time
	  && FIXNUMP (Vmodifier_keys_sticky_time)
	  && (ev->xkey.time
	      > xd->modifier_release_time + XFIXNUM (Vmodifier_keys_sticky_time)))
	{
	  xd->need_to_add_mask = 0;
	  xd->down_mask = 0;
	}

#define FROB(mask)				\
do {						\
  if (type == KeyPress)				\
    {						\
      /* If modifier key is already sticky,	\
         then unstick it.  Note that we do	\
         not test down_mask to deal with the	\
	 unlikely but possible case that the	\
	 modifier key auto-repeats. */		\
      if (xd->need_to_add_mask & mask)		\
	{					\
	  xd->need_to_add_mask &= ~mask;	\
	  xd->down_mask &= ~mask;		\
	}					\
      else					\
	xd->down_mask |= mask;			\
    }						\
  else						\
    {						\
      if (xd->down_mask & mask)			\
	{					\
	  xd->down_mask &= ~mask;		\
	  xd->need_to_add_mask |= mask;		\
	}					\
    }						\
  xd->modifier_release_time = ev->xkey.time;	\
} while (0)

      for (i = 0; i < xd->x_keysym_map_keysyms_per_code; i++)
        switch (syms[i])
          {
          case XK_Control_L: case XK_Control_R: FROB (ControlMask);   break;
          case XK_Shift_L:   case XK_Shift_R:   FROB (ShiftMask);     break;
          case XK_Meta_L:    case XK_Meta_R:    FROB (xd->MetaMask);  break;
          case XK_Super_L:   case XK_Super_R:   FROB (xd->SuperMask); break;
          case XK_Hyper_L:   case XK_Hyper_R:   FROB (xd->HyperMask); break;
          case XK_Alt_L:     case XK_Alt_R:     FROB (xd->AltMask);   break;
          }
    }
#undef FROB
}

static void
clear_sticky_modifiers (struct device *d)
{
  struct x_device *xd = DEVICE_X_DATA (d);

  xd->need_to_add_mask = 0;
  xd->last_downkey     = 0;
  xd->release_time     = 0;
  xd->down_mask        = 0;
}

static int
keysym_obeys_caps_lock_p (KeySym sym, struct device *d)
{
  struct x_device *xd = DEVICE_X_DATA (d);
  KeySym upper, lower;
  /* Eeeeevil hack.  Don't apply Caps_Lock to things that aren't alphabetic
     characters, where "alphabetic" means something more than simply A-Z.
     That is, if Caps_Lock is down, typing ESC doesn't produce Shift-ESC.
     But if shift-lock is down, then it does. */
  if (xd->lock_interpretation == XK_Shift_Lock)
    return 1;

  XConvertCase (sym, &lower, &upper);

  return !(sym == lower && sym == upper);
}

/* called from EmacsFrame.c (actually from Xt itself) when a
   MappingNotify event is received.  In its infinite wisdom, Xt
   decided that Xt event handlers never get MappingNotify events.
   O'Reilly Xt Programming Manual 9.1.2 says:

   MappingNotify is automatically handled by Xt, so it isn't passed
   to event handlers and you don't need to worry about it.

   Of course, we DO worry about it, so we need a special translation. */
void
emacs_Xt_mapping_action (Widget UNUSED (w), XEvent *event)
{
  struct device *d = get_device_from_display (event->xany.display);

  if (DEVICE_X_BEING_DELETED (d))
    return;
#if 0
  /* nyet.  Now this is handled by Xt. */
  XRefreshKeyboardMapping (&event->xmapping);
#endif
  /* xmodmap generates about a billion MappingKeyboard events, followed
     by a single MappingModifier event, so it might be worthwhile to
     take extra MappingKeyboard events out of the queue before requesting
     the current keymap from the server. */
  switch (event->xmapping.request)
    {
    case MappingKeyboard:  x_reset_key_mapping      (d); break;
    case MappingModifier:  x_reset_modifier_mapping (d); break;
    case MappingPointer:   /* Do something here? */      break;
    default: ABORT();
    }
}


/************************************************************************/
/*                  X to Emacs event conversion                         */
/************************************************************************/

static Lisp_Object
x_keysym_to_emacs_keysym (KeySym keysym, int simple_p)
{
  Extbyte *name;
  DECLARE_EISTRING(einame);

  if (keysym >= XK_exclam && keysym <= XK_asciitilde)
    /* We must assume that the X keysym numbers for the ASCII graphic
       characters are the same as their ASCII codes.  */
    return make_char (keysym);

  if (keysym >= 0x01000000 && keysym <= 0x0110FFFF)
    {
      /* These keysyms malloc with XKeysymToString(), *every time the
         function is called.* Avoid leaking, construct the keysym string
         ourselves. */
      Ascbyte buf [10];
      qxesprintf ((Ibyte *) buf, keysym & 0xff0000 ? "U%06X" : "U%04X",
                  (unsigned int) (keysym & 0xffffff));
      return KEYSYM (buf);
    }

  switch (keysym)
    {
      /* These would be handled correctly by the default case, but by
	 special-casing them here we don't garbage a string or call
	 intern().  */
    case XK_BackSpace:	return QKbackspace;
    case XK_Tab:	return QKtab;
    case XK_Linefeed:	return QKlinefeed;
    case XK_Return:	return QKreturn;
    case XK_Escape:	return QKescape;
    case XK_space:	return QKspace;
    case XK_Delete:	return QKdelete;
    case 0:		return Qnil;
    default:
      if (simple_p) return Qnil;
      name = XKeysymToString (keysym);
      if (!name || !name[0])
	/* This happens if there is a mismatch between the Xlib of
           XEmacs and the Xlib of the X server...

	   Let's hard-code in some knowledge of common keysyms introduced
	   in recent X11 releases.  Snarfed from X11/keysymdef.h

	   Probably we should add some stuff here for X11R6. */
	switch (keysym)
	  {
	  case 0xFF95: return KEYSYM ("kp-home");
	  case 0xFF96: return KEYSYM ("kp-left");
	  case 0xFF97: return KEYSYM ("kp-up");
	  case 0xFF98: return KEYSYM ("kp-right");
	  case 0xFF99: return KEYSYM ("kp-down");
	  case 0xFF9A: return KEYSYM ("kp-prior");
	  case 0xFF9B: return KEYSYM ("kp-next");
	  case 0xFF9C: return KEYSYM ("kp-end");
	  case 0xFF9D: return KEYSYM ("kp-begin");
	  case 0xFF9E: return KEYSYM ("kp-insert");
	  case 0xFF9F: return KEYSYM ("kp-delete");

	  case 0x1005FF10: return KEYSYM ("SunF36"); /* labeled F11 */
	  case 0x1005FF11: return KEYSYM ("SunF37"); /* labeled F12 */
	  default:
	    {
	      Ascbyte buf [64];
	      sprintf (buf, "unknown-keysym-0x%X", (int) keysym);
	      return KEYSYM (buf);
	    }
	  }
      
      /* If it's got a one-character name, that's good enough. */
      if (!name[1])
	return make_char ((Ichar)name[0]);

      /* In theory the Host Portable Character Set is just ASCII, but
         trusting X11 implementors to get that right is likely to lead to
         tears. */
      eicpy_ext(einame, name, Qbinary);

      /* If it's in the "Keyboard" character set, downcase it.
	 The case of those keysyms is too totally random for us to
	 force anyone to remember them.
	 The case of the other character sets is significant, however. */
      if ((((unsigned int) keysym) & (~0x1FF)) == ((unsigned int) 0xFE00))
	{
	  Ibyte *iname;
	  eilwr(einame);
	  
	  for (iname = eidata(einame); *iname != '\0';)
	    {
	      if (*iname == '_')
		{
		  *iname = '-';
		}
	      INC_IBYTEPTR(iname);
	    }
	}
      return KEYSYM ((const CIbyte *) eidata (einame));
    }
}

static Lisp_Object
x_to_emacs_keysym (XKeyPressedEvent *event, int simple_p, KeySym *x_keysym_out)
     /* simple_p means don't try too hard (ASCII only) */
{
  KeySym keysym = NoSymbol;

#ifdef HAVE_XIM
  int len = 0;
  /* Some implementations of XmbLookupString don't return
     XBufferOverflow correctly, so increase the size of the xim input
     buffer from 64 to the more reasonable size 513, as Emacs has done.
     From Kenichi Handa. */
  char buffer[513];
  char *bufptr = buffer;
  int   bufsiz = sizeof (buffer);
  Status status;
#ifdef XIM_XLIB
  XIC xic = FRAME_X_XIC (x_any_window_to_frame
			 (get_device_from_display (event->display),
			  event->window));
#endif /* XIM_XLIB */
#endif /* HAVE_XIM */

  *x_keysym_out = NoSymbol;

  /* We use XLookupString if we're not using XIM, or are using
     XIM_XLIB but input context creation failed. */
#if ! (defined (HAVE_XIM) && defined (XIM_MOTIF))
#if defined (HAVE_XIM) && defined (XIM_XLIB)
     if (!xic)
#endif /* XIM_XLIB */
    {
      /* Apparently it's necessary to specify a dummy here (rather
         than passing in 0) to avoid crashes on German IRIX */
      char dummy[256];
      XLookupString (event, dummy, 200, &keysym, 0);
      *x_keysym_out = keysym;
      return (IsModifierKey (keysym) || keysym == XK_Mode_switch )
	? Qnil : x_keysym_to_emacs_keysym (keysym, simple_p);
    }
#endif /* ! XIM_MOTIF */

#ifdef HAVE_XIM
 Lookup_String: /* Come-From XBufferOverflow */
#ifdef XIM_MOTIF
  len = XmImMbLookupString (XtWindowToWidget (event->display, event->window),
			    event, bufptr, bufsiz, &keysym, &status);
#else /* XIM_XLIB */
  if (xic)
    len = XmbLookupString (xic, event, bufptr, bufsiz, &keysym, &status);
#endif /* XIM_MOTIF */

#ifdef DEBUG_XEMACS
  if (debug_x_events > 0)
    {
      stderr_out ("   status=");
#define print_status_when(S) if (status == S) stderr_out (#S)
      print_status_when (XLookupKeySym);
      print_status_when (XLookupBoth);
      print_status_when (XLookupChars);
      print_status_when (XLookupNone);
      print_status_when (XBufferOverflow);

      if (status == XLookupKeySym || status == XLookupBoth)
	stderr_out (" keysym=%s",  XKeysymToString (keysym));
      if (status == XLookupChars  || status == XLookupBoth)
	{
	  if (len > 1)
	    {
	      int j;
	      stderr_out (" chars=\"");
	      for (j=0; j<len; j++)
		{
		  if (040 <= bufptr[j] && bufptr[j] >= 0177)
		    {
		      stderr_out ("%c", bufptr[j]);
		    }
		  else
		    {
		      stderr_out ("\\%o", (unsigned)(bufptr[j]));
		    }
		}
	      stderr_out ("\"");
	    }
	  else if (bufptr[0] <= 32 || bufptr[0] >= 127)
	    stderr_out (" char=0x%x", bufptr[0]);
	  else
	    stderr_out (" char=%c", bufptr[0]);
	}
      stderr_out ("\n");
    }
#endif /* DEBUG_XEMACS */

  switch (status)
    {
    case XLookupKeySym:
    case XLookupBoth:
      *x_keysym_out = keysym;
      return (IsModifierKey (keysym) || keysym == XK_Mode_switch )
	? Qnil : x_keysym_to_emacs_keysym (keysym, simple_p);

    case XLookupChars:
      {
	/* Generate multiple emacs events */
	struct device *d = get_device_from_display (event->display);
        Ichar ch;
	Lisp_Object instream, fb_instream;
	Lstream *istr;
	struct gcpro gcpro1, gcpro2;

	fb_instream = make_fixed_buffer_input_stream (bufptr, len);

        /* [[ Use get_coding_system_for_text_file
		(Vcomposed_input_coding_system, 0) ]] 

	   Nope. If it is possible for the X libraries to have multiple IM
	   connections on different DISPLAYs active at once, this should be
	   a console-specific variable (like a TTY's coding system) but I've
	   seen no evidence that that is possible. Aidan Kehoe,
	   2005-12-17. */
	
	instream =
	  make_coding_input_stream
	    (XLSTREAM (fb_instream), Qkeyboard, CODING_DECODE, 0);

	istr = XLSTREAM (instream);

	GCPRO2 (instream, fb_instream);
        while ((ch = Lstream_get_ichar (istr)) != EOF)
          {
            Lisp_Object emacs_event = Fmake_event (Qnil, Qnil);
	    Lisp_Event *ev          = XEVENT (emacs_event);
            ev->channel	            = DEVICE_CONSOLE (d);
	    XSET_EVENT_TYPE (emacs_event, key_press_event);
	    /* Make sure space and linefeed and so on get the proper
	       keysyms. */
	    character_to_event (ch, ev, XCONSOLE (ev->channel),
				latin_1_maps_to_itself, 0);
            ev->timestamp	    = event->time;
            enqueue_dispatch_event (emacs_event);
          }
	Lstream_close (istr);
	UNGCPRO;
	Lstream_delete (istr);
	Lstream_delete (XLSTREAM (fb_instream));
	return Qnil;
      }
    case XLookupNone: return Qnil;
    case XBufferOverflow:
      /* !!#### needs work */
      bufptr = (char *) ALLOCA (len+1);
      bufsiz = len+1;
      goto Lookup_String;
    }
  return Qnil; /* not (usually) reached */
#endif /* HAVE_XIM */
}

static void
set_last_server_timestamp (struct device *d, XEvent *x_event)
{
  Time t;
  switch (x_event->type)
    {
    case KeyPress:
    case KeyRelease:       t = x_event->xkey.time;              break;
    case ButtonPress:
    case ButtonRelease:    t = x_event->xbutton.time;           break;
    case EnterNotify:
    case LeaveNotify:      t = x_event->xcrossing.time;         break;
    case MotionNotify:     t = x_event->xmotion.time;           break;
    case PropertyNotify:   t = x_event->xproperty.time;         break;
    case SelectionClear:   t = x_event->xselectionclear.time;   break;
    case SelectionRequest: t = x_event->xselectionrequest.time; break;
    case SelectionNotify:  t = x_event->xselection.time;        break;
    default: return;
    }
  DEVICE_X_LAST_SERVER_TIMESTAMP (d) = t;
}

static int
x_event_to_emacs_event (XEvent *x_event, Lisp_Event *emacs_event)
{
  Display *display    = x_event->xany.display;
  struct device *d    = get_device_from_display (display);
  struct x_device *xd = DEVICE_X_DATA (d);

  if (DEVICE_X_BEING_DELETED (d))
    {
      /* [[ Uh, is this 0 correct? ]] 

         Yup--it means emacs_Xt_event_handler, the only place that calls
         this, doesn't queue the emacs_event dispatch, instead immediately
         deallocating it. */
      return 0;
    }

  set_last_server_timestamp (d, x_event);

  switch (x_event->type)
    {
    case KeyRelease:
      {
	x_handle_sticky_modifiers (x_event, d);
	return 0;
      }
    case KeyPress:
    case ButtonPress:
    case ButtonRelease:
      {
	int modifiers = 0;
	int shift_p, lock_p;
	Bool key_event_p = (x_event->type == KeyPress);
	unsigned int *state =
	  key_event_p ? &x_event->xkey.state : &x_event->xbutton.state;

	/* If this is a synthetic KeyPress or Button event, and the user
	   has expressed a disinterest in this security hole, then drop
	   it on the floor. */
	if ((key_event_p
	     ? x_event->xkey.send_event
	     : x_event->xbutton.send_event)
#ifdef EXTERNAL_WIDGET
	    /* ben: events get sent to an ExternalShell using XSendEvent.
	       This is not a perfect solution. */
	    && !FRAME_X_EXTERNAL_WINDOW_P
	    (x_any_window_to_frame (d, x_event->xany.window))
#endif
	    && !x_allow_sendevents)
	  return 0;

	DEVICE_X_MOUSE_TIMESTAMP (d) =
	  DEVICE_X_GLOBAL_MOUSE_TIMESTAMP (d) =
	  key_event_p ? x_event->xkey.time : x_event->xbutton.time;

	x_handle_sticky_modifiers (x_event, d);

	if (*state & ControlMask)    modifiers |= XEMACS_MOD_CONTROL;
	if (*state & xd->MetaMask)   modifiers |= XEMACS_MOD_META;
	if (*state & xd->SuperMask)  modifiers |= XEMACS_MOD_SUPER;
	if (*state & xd->HyperMask)  modifiers |= XEMACS_MOD_HYPER;
	if (*state & xd->AltMask)    modifiers |= XEMACS_MOD_ALT;
	{
	  int numero_de_botao = -1;

	  if (!key_event_p)
	    numero_de_botao = x_event->xbutton.button;

	  /* the button gets noted either in the button or the modifiers
	     field, but not both. */
	  if (numero_de_botao != 1 && (*state & Button1Mask))
	    modifiers |= XEMACS_MOD_BUTTON1;
	  if (numero_de_botao != 2 && (*state & Button2Mask))
	    modifiers |= XEMACS_MOD_BUTTON2;
	  if (numero_de_botao != 3 && (*state & Button3Mask))
	    modifiers |= XEMACS_MOD_BUTTON3;
	  if (numero_de_botao != 4 && (*state & Button4Mask))
	    modifiers |= XEMACS_MOD_BUTTON4;
	  if (numero_de_botao != 5 && (*state & Button5Mask))
	    modifiers |= XEMACS_MOD_BUTTON5;
	}

	/* Ignore the Caps_Lock key if:
	   - any other modifiers are down, so that Caps_Lock doesn't
	     turn C-x into C-X, which would suck.
	   - the event was a mouse event. */
	if (modifiers || ! key_event_p)
          *state &= (~LockMask);

	shift_p = *state & ShiftMask;
	lock_p  = *state & LockMask;

	if (shift_p || lock_p)
	  modifiers |= XEMACS_MOD_SHIFT;

	if (key_event_p)
	  {
	    Lisp_Object keysym;
	    XKeyEvent *ev = &x_event->xkey;
            KeySym x_keysym = NoSymbol;
	    /* This used to compute the frame from the given X window and
	       store it here, but we really don't care about the frame. */
	    SET_EVENT_CHANNEL (emacs_event, DEVICE_CONSOLE (d));
	    keysym = x_to_emacs_keysym (&x_event->xkey, 0, &x_keysym);

	    /* If the emacs keysym is nil, then that means that the X
	       keysym was either a Modifier or NoSymbol, which
	       probably means that we're in the midst of reading a
	       Multi_key sequence, or a "dead" key prefix, or XIM
	       input. Ignore it. */
	    if (NILP (keysym))
	      return 0;

	    /* If we have the map from keycodes to the US layout for our
	       keyboard available, store the US layout interpretation of
	       that key in the event structure, in case a binding lookup
	       fails and we want to fall back to the US layout binding.

	       This _might_ be possible within an XKB framework, changing
	       the keyboard to a US XKB layout for a moment at startup,
	       storing the correspondance, and changing it back. But that
	       won't work on non-XKB servers, it makes our already slow
	       startup slower, and it's not clear that it's really any
	       easier or more maintainable than storing a correspondence in
	       Lisp. */

	    if (!NILP(Vx_us_keymap_description) && 
		VECTORP(Vx_us_keymap_description) && 
		ev->keycode >= (unsigned)Vx_us_keymap_first_keycode && 
		ev->keycode 
		< (unsigned)XVECTOR_LENGTH(Vx_us_keymap_description)) 
	      {
		Lisp_Object entr = XVECTOR_DATA(Vx_us_keymap_description)
		  [ev->keycode - Vx_us_keymap_first_keycode];
		Ichar alternate = '\0';

		if (!NILP (entr))
		  {
		    if (CHARP(entr)) 
		      {
			alternate = XCHAR(entr);
		      }
		    else if (VECTORP(entr))
		      {
			if (modifiers & XEMACS_MOD_SHIFT
			    && XVECTOR_LENGTH(Vx_us_keymap_description) > 1)
			  {
			    entr = XVECTOR_DATA(entr)[1];
			    if (CHARP(entr))
			      {
				alternate = XCHAR(entr);
			      }
			  }
			else if (XVECTOR_LENGTH(Vx_us_keymap_description) 
				 > 0)
			  {
			    entr = XVECTOR_DATA(entr)[0];
			    if (CHARP(entr))
			      {
				alternate = XCHAR(entr);
			      }
			  }
		      }
		    if ('\0' != alternate)
		      {
			SET_EVENT_KEY_ALT_KEYCHARS(emacs_event, KEYCHAR_QWERTY,
						   alternate);
		      }
		  }
	      }

	    /* More Caps_Lock garbage: Caps_Lock should *only* add the
	       shift modifier to two-case keys (that is, A-Z and
	       related characters). So at this point (after looking up
	       the keysym) if the keysym isn't a dual-case alphabetic,
	       and if the caps lock key was down but the shift key
	       wasn't, then turn off the shift modifier.  Gag barf */

	    if (lock_p && !shift_p &&
		! (x_keysym && keysym_obeys_caps_lock_p (x_keysym, d)))
	      modifiers &= (~XEMACS_MOD_SHIFT);

	    /* If this key contains two distinct keysyms, that is,
	       "shift" generates a different keysym than the
	       non-shifted key, then don't apply the shift modifier
	       bit: it's implicit.  Otherwise, if there would be no
	       other way to tell the difference between the shifted
	       and unshifted version of this key, apply the shift bit.
	       Non-graphics, like Backspace and F1 get the shift bit
	       in the modifiers slot.  Neither the characters "a",
	       "A", "2", nor "@" normally have the shift bit set.
	       However, "F1" normally does. */

	    if (modifiers & XEMACS_MOD_SHIFT)
	      {
		int Mode_switch_p = *state & xd->ModeMask;
		KeySym bot = XLookupKeysym (ev, Mode_switch_p ? 2 : 0);
		if (x_keysym && bot && x_keysym != bot)
		  modifiers &= ~XEMACS_MOD_SHIFT;
	      }
	    set_event_type (emacs_event, key_press_event);
	    SET_EVENT_TIMESTAMP (emacs_event, ev->time);
	    SET_EVENT_KEY_MODIFIERS (emacs_event, modifiers);
	    SET_EVENT_KEY_KEYSYM (emacs_event, keysym);
	  }
	else                    /* Mouse press/release event */
	  {
	    XButtonEvent *ev = &x_event->xbutton;
	    struct frame *frame = x_window_to_frame (d, ev->window);

	    if (! frame)
	      return 0;	/* not for us */
	    set_event_type (emacs_event, (x_event->type == ButtonPress) ?
                        button_press_event : button_release_event);
            SET_EVENT_CHANNEL (emacs_event, wrap_frame (frame));

	    SET_EVENT_BUTTON_MODIFIERS (emacs_event, modifiers);
	    SET_EVENT_TIMESTAMP (emacs_event, ev->time);
	    SET_EVENT_BUTTON_BUTTON (emacs_event, ev->button);
	    SET_EVENT_BUTTON_X (emacs_event, ev->x);
	    SET_EVENT_BUTTON_Y (emacs_event, ev->y);
	    /* because we don't seem to get a FocusIn event for button clicks
	       when a widget-glyph is selected we will assume that we want the
	       focus if a button gets pressed. */
	    if (x_event->type == ButtonPress)
	      handle_focus_event_1 (frame, 1);
	  }
      }
    break;

    case MotionNotify:
      {
        XMotionEvent *ev = &x_event->xmotion;
        struct frame *frame = x_window_to_frame (d, ev->window);
        int modifiers = 0;
        XMotionEvent event2;

        if (! frame)
          return 0; /* not for us */

        /* We use MotionHintMask, so we will get only one motion event
           until the next time we call XQueryPointer or the user
           clicks the mouse.  So call XQueryPointer now (meaning that
           the event will be in sync with the server just before
           Fnext_event() returns).  If the mouse is still in motion,
           then the server will immediately generate exactly one more
           motion event, which will be on the queue waiting for us
           next time around. */
        event2 = *ev;
        if (XQueryPointer (event2.display, event2.window,
                           &event2.root,   &event2.subwindow,
                           &event2.x_root, &event2.y_root,
                           &event2.x,      &event2.y,
                           &event2.state))
          ev = &event2; /* only one structure copy */

        DEVICE_X_MOUSE_TIMESTAMP (d) = ev->time;
        SET_EVENT_CHANNEL (emacs_event, wrap_frame (frame));
        set_event_type (emacs_event, pointer_motion_event);
        SET_EVENT_TIMESTAMP (emacs_event, ev->time);
        SET_EVENT_MOTION_X (emacs_event, ev->x);
        SET_EVENT_MOTION_Y (emacs_event, ev->y);
        if (ev->state & ShiftMask)	modifiers |= XEMACS_MOD_SHIFT;
        if (ev->state & ControlMask)	modifiers |= XEMACS_MOD_CONTROL;
        if (ev->state & xd->MetaMask)	modifiers |= XEMACS_MOD_META;
        if (ev->state & xd->SuperMask)	modifiers |= XEMACS_MOD_SUPER;
        if (ev->state & xd->HyperMask)	modifiers |= XEMACS_MOD_HYPER;
        if (ev->state & xd->AltMask)	modifiers |= XEMACS_MOD_ALT;
        if (ev->state & Button1Mask)	modifiers |= XEMACS_MOD_BUTTON1;
        if (ev->state & Button2Mask)	modifiers |= XEMACS_MOD_BUTTON2;
        if (ev->state & Button3Mask)	modifiers |= XEMACS_MOD_BUTTON3;
        if (ev->state & Button4Mask)	modifiers |= XEMACS_MOD_BUTTON4;
        if (ev->state & Button5Mask)	modifiers |= XEMACS_MOD_BUTTON5;
        /* Currently ignores Shift_Lock but probably shouldn't
           (but it definitely should ignore Caps_Lock). */
        SET_EVENT_MOTION_MODIFIERS (emacs_event, modifiers);
      }
    break;

    case ClientMessage:
      {
        /* Patch bogus TAKE_FOCUS messages from MWM; CurrentTime is
           passed as the timestamp of the TAKE_FOCUS, which the ICCCM
           explicitly prohibits. */
        XClientMessageEvent *ev = &x_event->xclient;

        if (ev->message_type == DEVICE_XATOM_WM_PROTOCOLS (d)
            && (Atom) (ev->data.l[0]) == DEVICE_XATOM_WM_TAKE_FOCUS (d)
            && (Atom) (ev->data.l[1]) == 0)
          {
            ev->data.l[1] = DEVICE_X_LAST_SERVER_TIMESTAMP (d);
          }
      }
    /* fall through */

    default: /* it's a magic event */
      {
        struct frame *frame;
        Window w;
	XEvent *x_event_copy;
	SET_EVENT_TYPE (emacs_event, magic_event);
        x_event_copy = &EVENT_MAGIC_X_EVENT (emacs_event);

#define FROB(event_member, window_member) \
	x_event_copy->event_member = x_event->event_member; \
	w = x_event->event_member.window_member

        switch (x_event->type)
          {
	  case SelectionRequest: FROB(xselectionrequest, owner);  break;
	  case SelectionClear:	 FROB(xselectionclear, window);	  break;
	  case SelectionNotify:	 FROB(xselection, requestor);	  break;
	  case PropertyNotify:	 FROB(xproperty, window);	  break;
	  case ClientMessage:	 FROB(xclient, window);		  break;
	  case ConfigureNotify:	 FROB(xconfigure, window);	  break;
	  case Expose:
	  case GraphicsExpose:	 FROB(xexpose, window);		  break;
	  case MapNotify:
	  case UnmapNotify:	 FROB(xmap, window);		  break;
	  case EnterNotify:
	  case LeaveNotify:	 FROB(xcrossing, window);	  break;
	  case FocusIn:
	  case FocusOut:	 FROB(xfocus, window);		  break;
	  case VisibilityNotify: FROB(xvisibility, window);	  break;
	  case CreateNotify: FROB(xcreatewindow, window);	  break;
          default:
	    w = x_event->xany.window;
	    *x_event_copy = *x_event;
	    break;
          }
#undef FROB
        frame = x_any_window_to_frame (d, w);

        if (!frame)
          return 0;

	SET_EVENT_CHANNEL (emacs_event, wrap_frame (frame));
        break;
      }
    }
  return 1;
}



/************************************************************************/
/*                           magic-event handling                       */
/************************************************************************/

static void
handle_focus_event_1 (struct frame *f, int in_p)
{
  handle_focus_event_2 (XtWindow (FRAME_X_TEXT_WIDGET (f)), f, in_p);
}

static void
handle_focus_event_2 (Window win, struct frame *f, int in_p)
{
  /* Although this treats focus differently for all widgets (including
     the frame) it seems to work ok. */
  Widget needs_it = XtWindowToWidget (FRAME_X_DISPLAY (f), win);

#if XtSpecificationRelease > 5
  widget_with_focus = XtGetKeyboardFocusWidget (FRAME_X_TEXT_WIDGET (f));
#endif
#ifdef HAVE_XIM
  XIM_focus_event (f, in_p);
#endif /* HAVE_XIM */

  /* On focus change, clear all memory of sticky modifiers
     to avoid non-intuitive behavior. */
  clear_sticky_modifiers (XDEVICE (FRAME_DEVICE (f)));

  /* We don't want to handle the focus change now, because we might
     be in an accept-process-output, sleep-for, or sit-for.  So
     we enqueue it.

     Actually, we half handle it: we handle it as far as changing the
     box cursor for redisplay, but we don't call any hooks or do any
     select-frame stuff until after the sit-for.

     Unfortunately native widgets break the model because they grab
     the keyboard focus and nothing sets it back again. I cannot find
     any reasonable way to do this elsewhere so we assert here that
     the keyboard focus is on the emacs text widget. Menus and dialogs
     do this in their selection callback, but we don't want that since
     a button having focus is legitimate. An edit field having focus
     is mandatory. Weirdly you get a FocusOut event when you click in
     a widget-glyph but you don't get a corresponding FocusIn when you
     click in the frame. Why is this?  */
  if (in_p
#if XtSpecificationRelease > 5
      && needs_it != widget_with_focus
#endif
      )
    {
      lw_set_keyboard_focus (FRAME_X_SHELL_WIDGET (f), needs_it);
    }

  /* If we are focusing on a native widget then record and exit. */
  if (needs_it != FRAME_X_TEXT_WIDGET (f)) {
    widget_with_focus = needs_it;
    return;
  }

  /* We have the focus now. See comment in
     emacs_Xt_handle_widget_losing_focus (). */
  if (in_p)
    widget_with_focus = NULL;

  /* do the generic event-stream stuff. */
  {
    Lisp_Object frm;
    Lisp_Object conser;
    struct gcpro gcpro1;

    frm = wrap_frame (f);
    conser = Fcons (frm, Fcons (FRAME_DEVICE (f), in_p ? Qt : Qnil));
    GCPRO1 (conser);
    emacs_handle_focus_change_preliminary (conser);
    enqueue_magic_eval_event (emacs_handle_focus_change_final,
			      conser);
    UNGCPRO;
  }
}

/* Create a synthetic X focus event. */
void emacs_Xt_enqueue_focus_event (Widget wants_it, Lisp_Object frame,
				   int in_p);
void
emacs_Xt_enqueue_focus_event (Widget wants_it, Lisp_Object frame, int in_p)
{
  Lisp_Object emacs_event = Fmake_event (Qnil, Qnil);
  Lisp_Event *ev          = XEVENT (emacs_event);
  XEvent *x_event;

  XSET_EVENT_TYPE (emacs_event, magic_event);
  x_event = &EVENT_MAGIC_X_EVENT (ev);

  x_event->type = in_p ? FocusIn : FocusOut;
  x_event->xfocus.window = XtWindow (wants_it);

  SET_EVENT_CHANNEL (ev, frame);

  enqueue_dispatch_event (emacs_event);
}

/* The idea here is that when a widget glyph gets unmapped we don't
   want the focus to stay with it if it has focus - because it may
   well just get deleted next and then we have lost the focus until the
   user does something. So handle_focus_event_1 records the widget
   with keyboard focus when FocusOut is processed, and then, when a
   widget gets unmapped, it calls this function to restore focus if
   appropriate. */
void emacs_Xt_handle_widget_losing_focus (struct frame *f, Widget losing_widget);
void
emacs_Xt_handle_widget_losing_focus (struct frame *f, Widget losing_widget)
{
  if (losing_widget == widget_with_focus)
    {
      handle_focus_event_1 (f, 1);
    }
}

/* This is called from the external-widget code */

void emacs_Xt_handle_focus_event (XEvent *event);
void
emacs_Xt_handle_focus_event (XEvent *event)
{
  struct device *d = get_device_from_display (event->xany.display);
  struct frame *f;

  if (DEVICE_X_BEING_DELETED (d))
    return;

  /*
   * It's curious that we're using x_any_window_to_frame() instead
   * of x_window_to_frame().  I don't know what the impact of this is.
   */
  f = x_any_window_to_frame (d, event->xfocus.window);
  if (!f)
    /* focus events are sometimes generated just before
       a frame is destroyed. */
    return;
  handle_focus_event_1 (f, event->type == FocusIn);
}

/* both MapNotify and VisibilityNotify can cause this
   JV is_visible has the same semantics as f->visible*/
static void
change_frame_visibility (struct frame *f, int is_visible)
{
  Lisp_Object frame = wrap_frame (f);


  if (!FRAME_VISIBLE_P (f) && is_visible)
    {
      FRAME_VISIBLE_P (f) = is_visible;
      /* [[ This improves the double flicker when uniconifying a frame
	 some.  A lot of it is not showing a buffer which has changed
	 while the frame was iconified.  To fix it further requires
	 the good 'ol double redisplay structure. ]] -- comment is
	 invalid, obviously predates 19.12, when the double redisplay
	 structure (i.e. current + desired) was put back  in. --ben */
      MARK_FRAME_WINDOWS_STRUCTURE_CHANGED (f);
      va_run_hook_with_args (Qmap_frame_hook, 1, frame);
    }
  else if (FRAME_VISIBLE_P (f) && !is_visible)
    {
      FRAME_VISIBLE_P (f) = 0;
      va_run_hook_with_args (Qunmap_frame_hook, 1, frame);
    }
  else if (FRAME_VISIBLE_P (f) * is_visible < 0)
    {
      FRAME_VISIBLE_P(f) = - FRAME_VISIBLE_P(f);
      if (FRAME_REPAINT_P(f))
	      MARK_FRAME_WINDOWS_STRUCTURE_CHANGED (f);
      va_run_hook_with_args (Qmap_frame_hook, 1, frame);
    }
}

static void
update_frame_iconify_status (struct frame *f)
{
  f->iconified = (x_frame_window_state (f) == IconicState);
}

static void
handle_map_event (struct frame *f, XEvent *event)
{

  /* It seems that, given the multiplicity of window managers and X
     implementations, plus the fact that X was designed without
     window managers or icons in mind and this was then grafted on
     with about the skill of a drunk freshman med student attempting
     surgery with a rusty razor blade, we cannot treat any off
     MapNotify/UnmapNotify/VisibilityNotify as more than vague hints
     as to the actual situation.

     So we should just query the actual status.  Unfortunately, things
     are worse because (a) there aren't obvious ways to query some
     of these values (e.g. "totally visible"), and (b) there may be
     race conditions (see below).

     However, according to the ICCCM, there's a specific way to
     ask the window manager whether the state is (a) visible,
     (b) iconic, (c) withdrawn.  It must be one of these three.
     We already use this call to check for the iconified state.
     I'd suggest we do the same for visible (i.e. NormalState),
     and scrap most of the nasty code below.

     --ben
     */

  update_frame_iconify_status (f);

  /* #### Ben suggests rewriting the code below using
     x_frame_window_state (f). */

  if (event->type == MapNotify)
    {
      XWindowAttributes xwa;

      /* Bleagh!!!!!!  Apparently some window managers (e.g. MWM)
	 send synthetic MapNotify events when a window is first
	 created, EVEN IF IT'S CREATED ICONIFIED OR INVISIBLE.
	 Or something like that.  We initially tried a different
	 solution below, but that ran into a different window-
	 manager bug.

	 It seems that the only reliable way is to treat a
	 MapNotify event as a "hint" that the window might or
	 might not be visible, and check explicitly. */

      XGetWindowAttributes (event->xany.display, event->xmap.window,
			    &xwa);
      if (xwa.map_state != IsViewable)
	return;

      FRAME_X_TOTALLY_VISIBLE_P (f) = 1;
#if 0
      /* Bleagh again!!!!  We initially tried the following hack
	 around the MWM problem, but it turns out that TWM
	 has a race condition when you un-iconify, where it maps
	 the window and then tells the server that the window
	 is un-iconified.  Usually, XEmacs wakes up between
	 those two occurrences, and thus thinks that un-iconified
	 windows are still iconified.

	 Ah, the joys of X. */

      /* By Emacs definition, a frame that is iconified is not
	 visible.  Marking a frame as visible will automatically cause
	 frame-iconified-p to return nil, regardless of whether the
	 frame is actually iconified.  Therefore, we have to ignore
	 MapNotify events on iconified frames. (It's not obvious
	 to me why these are being sent, but it happens at startup
	 with frames that are initially iconified; perhaps they are
	 synthetic MapNotify events coming from the window manager.)
	 Note that `frame-iconified-p' queries the server
	 to determine whether the frame is currently iconified,
	 rather than consulting some internal (and likely
	 inaccurate) state flag.  Therefore, ignoring the MapNotify
	 is correct. */
      if (!FRAME_VISIBLE_P (f) && NILP (Fframe_iconified_p (wrap_frame (f))))
#endif /* 0 */
	change_frame_visibility (f, 1);
    }
  else
    {
      FRAME_X_TOTALLY_VISIBLE_P (f) = 0;
      change_frame_visibility (f, 0);
    }
}

static void
handle_client_message (struct frame *f, XEvent *event)
{
  struct device *d = XDEVICE (FRAME_DEVICE (f));
  Lisp_Object frame = wrap_frame (f);

  if (event->xclient.message_type == DEVICE_XATOM_WM_PROTOCOLS (d) &&
      (Atom) (event->xclient.data.l[0]) == DEVICE_XATOM_WM_DELETE_WINDOW (d))
    {
      /* WM_DELETE_WINDOW is a misc-user event, but other ClientMessages,
	 such as WM_TAKE_FOCUS, are eval events.  That's because delete-window
	 was probably executed with a mouse click, while the others could
	 have been sent as a result of mouse motion or some other implicit
	 action.  (Call this a "heuristic"...)  The reason for caring about
	 this is so that clicking on the close-box will make emacs prompt
	 using a dialog box instead of the minibuffer if there are unsaved
	 buffers.
	 */
      enqueue_misc_user_event (frame, Qeval,
			       list3 (Qdelete_frame, frame, Qt));
    }
  else if (event->xclient.message_type == DEVICE_XATOM_WM_PROTOCOLS (d) &&
	   (Atom) event->xclient.data.l[0] == DEVICE_XATOM_WM_TAKE_FOCUS (d))
    {
      handle_focus_event_1 (f, 1);
#if 0
      /* If there is a dialog box up, focus on it.

	 #### Actually, we're raising it too, which is wrong.  We should
	 #### just focus on it, but lwlib doesn't currently give us an
	 #### easy way to do that.  This should be fixed.
	 */
      unsigned long take_focus_timestamp = event->xclient.data.l[1];
      Widget widget = lw_raise_all_pop_up_widgets ();
      if (widget)
	{
	  /* kludge: raise_all returns bottommost widget, but we really
	     want the topmost.  So just raise it for now. */
	  XMapRaised (XtDisplay (widget), XtWindow (widget));
	  /* Grab the focus with the timestamp of the TAKE_FOCUS. */
	  XSetInputFocus (XtDisplay (widget), XtWindow (widget),
			  RevertToParent, take_focus_timestamp);
	}
#endif
    }
}

/* #### I'm struggling to understand how the X event loop really works. 
   Here is the problem:
   
   When widgets get mapped / changed etc the actual display updates
   are done asynchronously via X events being processed - this
   normally happens when XtAppProcessEvent() gets called. However, if
   we are executing lisp code or even doing redisplay we won't
   necessarily process X events for a very long time. This has the
   effect of widgets only getting updated when XEmacs only goes into
   idle, or some other event causes processing of the X event queue.

   XtAppProcessEvent can get called from the following places:

     emacs_Xt_next_event () - this is normal event processing, almost
     any non-X event will take precedence and this means that we
     cannot rely on it to do the right thing at the right time for
     widget display.

     emacs_Xt_drain_queue () - this happens when SIGIO gets tripped,
     processing the event queue allows C-g to be checked for.  It gets
     called from emacs_Xt_event_pending_p (). #### Update this comment.

   In order to solve this I have tried introducing a list primitive -
   dispatch-non-command-events - which forces processing of X events
   related to display. Unfortunately this has a number of problems,
   one is that it is possible for event_stream_event_pending_p to
   block for ever if there isn't actually an event. I guess this can
   happen if we drop the synthetic event for reason. It also relies on
   SIGIO processing which makes things rather fragile.

   People have seen behaviour whereby XEmacs blocks until you move the
   mouse. This seems to indicate that dispatch-non-command-events is
   blocking. It may be that in a SIGIO world forcing SIGIO processing
   does the wrong thing.
*/
static void
emacs_Xt_force_event_pending (struct frame *f)
{
  XEvent event;

  Display *dpy = DEVICE_X_DISPLAY (XDEVICE (FRAME_DEVICE  (f)));
  event.xclient.type		= ClientMessage;
  event.xclient.display		= dpy;
  event.xclient.message_type	= XInternAtom (dpy, "BumpQueue", False);
  event.xclient.format		= 32;
  event.xclient.window		= 0;

  /* Send the drop message */
  XSendEvent(dpy, XtWindow (FRAME_X_SHELL_WIDGET (f)),
	     True, NoEventMask, &event);
  /* We rely on SIGIO and friends to realise we have generated an
     event. */
}

static void
emacs_Xt_format_magic_event (Lisp_Event *event, Lisp_Object pstream)
{
  Lisp_Object console = CDFW_CONSOLE (EVENT_CHANNEL (event));
  if (CONSOLE_X_P (XCONSOLE (console)))
    write_ascstring
      (pstream, x_event_name ((EVENT_MAGIC_X_EVENT (event)).type));
}

static int
emacs_Xt_compare_magic_event (Lisp_Event *e1, Lisp_Event *e2)
{
  if (CONSOLE_X_P (XCONSOLE (CDFW_CONSOLE (EVENT_CHANNEL (e1)))) &&
      CONSOLE_X_P (XCONSOLE (CDFW_CONSOLE (EVENT_CHANNEL (e2)))))
    return ((EVENT_MAGIC_X_EVENT (e1)).xany.serial ==
	    (EVENT_MAGIC_X_EVENT (e2)).xany.serial);
  if (CONSOLE_X_P (XCONSOLE (CDFW_CONSOLE (EVENT_CHANNEL (e1)))) ||
      CONSOLE_X_P (XCONSOLE (CDFW_CONSOLE (EVENT_CHANNEL (e2)))))
    return 0;
  return 1;
}

static Hashcode
emacs_Xt_hash_magic_event (Lisp_Event *e)
{
  Lisp_Object console = CDFW_CONSOLE (EVENT_CHANNEL (e));
  if (CONSOLE_X_P (XCONSOLE (console)))
    return (EVENT_MAGIC_X_EVENT (e)).xany.serial;
  return 0;
}

static void
emacs_Xt_handle_magic_event (Lisp_Event *emacs_event)
{
  /* This function can GC */
  XEvent *event = &EVENT_MAGIC_X_EVENT (emacs_event);
  struct frame *f = XFRAME (EVENT_CHANNEL (emacs_event));

  if (!FRAME_LIVE_P (f) || DEVICE_X_BEING_DELETED (XDEVICE (FRAME_DEVICE (f))))
    return;

  switch (event->type)
    {
    case SelectionRequest:
      x_handle_selection_request (&event->xselectionrequest);
      break;
      
    case SelectionClear:
      x_handle_selection_clear (&event->xselectionclear);
      break;
      
    case SelectionNotify:
      x_handle_selection_notify (&event->xselection);
      break;
      
    case PropertyNotify:
      x_handle_property_notify (&event->xproperty);
      break;
	
    case Expose:
      if (!check_for_ignored_expose (f, event->xexpose.x, event->xexpose.y,
				     event->xexpose.width,
				     event->xexpose.height)
	  &&
	  !find_matching_subwindow (f, event->xexpose.x, event->xexpose.y,
	  event->xexpose.width, event->xexpose.height))
	redisplay_redraw_exposed_area (f, event->xexpose.x, event->xexpose.y,
				       event->xexpose.width,
				       event->xexpose.height);
      break;

    case GraphicsExpose: /* This occurs when an XCopyArea's source area was
			    obscured or not available. */
      redisplay_redraw_exposed_area (f, event->xexpose.x, event->xexpose.y,
				     event->xexpose.width,
				     event->xexpose.height);
      break;

    case MapNotify:
    case UnmapNotify:
      handle_map_event (f, event);
      break;

    case EnterNotify:
      if (event->xcrossing.detail != NotifyInferior)
	{
	  Lisp_Object frame = wrap_frame (f);

	  /* FRAME_X_MOUSE_P (f) = 1; */
	  va_run_hook_with_args (Qmouse_enter_frame_hook, 1, frame);
	}
      break;

    case LeaveNotify:
      if (event->xcrossing.detail != NotifyInferior)
	{
	  Lisp_Object frame = wrap_frame (f);

	  /* FRAME_X_MOUSE_P (f) = 0; */
	  va_run_hook_with_args (Qmouse_leave_frame_hook, 1, frame);
	}
      break;

    case FocusIn:
    case FocusOut:

#ifdef EXTERNAL_WIDGET
      /* External widget lossage: Ben said:
	 YUCK.  The only way to make focus changes work properly is to
	 completely ignore all FocusIn/FocusOut events and depend only
	 on notifications from the ExternalClient widget. */
      if (FRAME_X_EXTERNAL_WINDOW_P (f))
	break;
#endif
      handle_focus_event_2 (event->xfocus.window, f, event->type == FocusIn);
      break;

    case ClientMessage:
      handle_client_message (f, event);
      break;

    case VisibilityNotify: /* window visibility has changed */
      if (event->xvisibility.window == XtWindow (FRAME_X_SHELL_WIDGET (f)))
	{
	  /* See comment in handle_map_event */
	  update_frame_iconify_status (f);

	  /* #### Ben suggests rewriting the code below using
	     x_frame_window_state (f). */
	  FRAME_X_TOTALLY_VISIBLE_P (f) =
	    (event->xvisibility.state == VisibilityUnobscured);
	  /* Note that the fvwm pager only sends VisibilityNotify when
	     changing pages. Is this all we need to do ? JV */
	  /* Nope.  We must at least trigger a redisplay here.
	     Since this case seems similar to MapNotify, I've
	     factored out some code to change_frame_visibility().
	     This triggers the necessary redisplay and runs
	     (un)map-frame-hook.  - dkindred@cs.cmu.edu */
	  /* Changed it again to support the tristate visibility flag */
	  change_frame_visibility (f, (event->xvisibility.state
				       != VisibilityFullyObscured) ? 1 : -1);
	}
      break;

    case ConfigureNotify:
      {
	XEvent xev;
	
	/* Let's eat all events of that type to avoid useless
	   reconfigurations. */
	while (XCheckTypedWindowEvent
	       (DEVICE_X_DISPLAY (XDEVICE (FRAME_DEVICE (f))),
		XtWindow (FRAME_X_TEXT_WIDGET (f)),
		ConfigureNotify,
		&xev)
	       == True);
      }
      /* #### NOTE: in fact, the frame faces didn't really change, but if some
	 #### of them have their background-placement property set to
	 #### absolute, we need a redraw. This is semantically equivalent to
	 #### changing the background pixmap. -- dvl */
      x_get_frame_text_position (f);
      MARK_FRAME_FACES_CHANGED (f);

#ifdef HAVE_XIM
      XIM_SetGeometry (f);
#endif
      break;

    case CreateNotify:
      break;

    default:
      break;
    }
}


/************************************************************************/
/*				timeout events				*/
/************************************************************************/

static int timeout_id_tick;

/* Xt interval id's might not fit into an int (they're pointers, as it
   happens), so we need to provide a conversion list. */

static struct Xt_timeout
{
  int id;
  XtIntervalId interval_id;
  struct Xt_timeout *next;
} *pending_timeouts, *completed_timeouts;

static struct Xt_timeout_blocktype
{
  Blocktype_declare (struct Xt_timeout);
} *the_Xt_timeout_blocktype;

/* called by XtAppNextEvent() */
static void
Xt_timeout_callback (XtPointer closure, XtIntervalId *UNUSED (id))
{
  struct Xt_timeout *timeout = (struct Xt_timeout *) closure;
  struct Xt_timeout *t2 = pending_timeouts;
  /* Remove this one from the list of pending timeouts */
  if (t2 == timeout)
    pending_timeouts = pending_timeouts->next;
  else
    {
      while (t2->next && t2->next != timeout) t2 = t2->next;
      assert (t2->next);
      t2->next = t2->next->next;
    }
  /* Add this one to the list of completed timeouts */
  timeout->next = completed_timeouts;
  completed_timeouts = timeout;
}

static int
emacs_Xt_add_timeout (EMACS_TIME thyme)
{
  struct Xt_timeout *timeout = Blocktype_alloc (the_Xt_timeout_blocktype);
  EMACS_TIME current_time;
  int milliseconds;

  timeout->id = timeout_id_tick++;
  timeout->next = pending_timeouts;
  pending_timeouts = timeout;
  EMACS_GET_TIME (current_time);
  EMACS_SUB_TIME (thyme, thyme, current_time);
  milliseconds = EMACS_SECS (thyme) * 1000 +
    EMACS_USECS (thyme) / 1000;
  if (milliseconds < 1)
    milliseconds = 1;
  timeout->interval_id = XtAppAddTimeOut (Xt_app_con, milliseconds,
					  Xt_timeout_callback,
					  (XtPointer) timeout);
  return timeout->id;
}

static void
emacs_Xt_remove_timeout (int id)
{
  struct Xt_timeout *timeout, *t2;

  timeout = NULL;

  /* Find the timeout on the list of pending ones, if it's still there. */
  if (pending_timeouts)
    {
      if (id == pending_timeouts->id)
	{
	  timeout = pending_timeouts;
	  pending_timeouts = pending_timeouts->next;
	}
      else
	{
	  t2 = pending_timeouts;
	  while (t2->next && t2->next->id != id) t2 = t2->next;
	  if ( t2->next)   /*found it */
	    {
	      timeout = t2->next;
	      t2->next = t2->next->next;
	    }
	}
      /* if it was pending, we have removed it from the list */
      if (timeout)
	XtRemoveTimeOut (timeout->interval_id);
    }

  /* It could be that the Xt call back was already called but we didn't convert
     into an Emacs event yet */
  if (!timeout && completed_timeouts)
    {
      /* Code duplication! */
      if (id == completed_timeouts->id)
	{
	  timeout = completed_timeouts;
	  completed_timeouts = completed_timeouts->next;
	}
      else
	{
	  t2 = completed_timeouts;
	  while (t2->next && t2->next->id != id) t2 = t2->next;
	  if ( t2->next)   /*found it */
	    {
	      timeout = t2->next;
	      t2->next = t2->next->next;
	    }
	}
    }

  /* If we found the thing on the lists of timeouts,
     and removed it, deallocate
  */
  if (timeout)
    Blocktype_free (the_Xt_timeout_blocktype, timeout);
}

static void
Xt_timeout_to_emacs_event (Lisp_Event *emacs_event)
{
  struct Xt_timeout *timeout = completed_timeouts;
  assert (timeout);
  completed_timeouts = completed_timeouts->next;
  /* timeout events have nil as channel */
  set_event_type (emacs_event, timeout_event);
  SET_EVENT_TIMESTAMP_ZERO (emacs_event); /* #### wrong!! */
  SET_EVENT_TIMEOUT_INTERVAL_ID (emacs_event, timeout->id);
  SET_EVENT_TIMEOUT_FUNCTION (emacs_event, Qnil);
  SET_EVENT_TIMEOUT_OBJECT (emacs_event, Qnil);
  Blocktype_free (the_Xt_timeout_blocktype, timeout);
}


/************************************************************************/
/*			process and tty events				*/
/************************************************************************/

struct what_is_ready_closure
{
  int fd;
  Lisp_Object what;
  XtInputId id;
};

static Lisp_Object *filedesc_with_input;
static struct what_is_ready_closure **filedesc_to_what_closure;

static void
init_what_input_once (void)
{
  int i;

  filedesc_with_input = xnew_array (Lisp_Object, MAXDESC);
  filedesc_to_what_closure =
    xnew_array (struct what_is_ready_closure *, MAXDESC);

  for (i = 0; i < MAXDESC; i++)
    {
      filedesc_to_what_closure[i] = 0;
      filedesc_with_input[i] = Qnil;
    }

  process_events_occurred = 0;
  tty_events_occurred = 0;
}

static void
mark_what_as_being_ready (struct what_is_ready_closure *closure)
{
  if (NILP (filedesc_with_input[closure->fd]))
    {
      SELECT_TYPE temp_mask;
      FD_ZERO (&temp_mask);
      FD_SET (closure->fd, &temp_mask);
      /* Check to make sure there's *really* input available.
	 Sometimes things seem to get confused and this gets called
	 for the tty fd when there's really only input available
	 on some process's fd.	(It will subsequently get called
	 for that process's fd, so returning without setting any
	 flags will take care of it.)  To see the problem, uncomment
	 the stderr_out below, turn NORMAL_QUIT_CHECK_TIMEOUT_MSECS
	 down to 25, do sh -c 'xemacs -nw -q -f shell 2>/tmp/log'
	 and press return repeatedly.  (Seen under AIX & Linux.)
	 -dkindred@cs.cmu.edu */
      if (!poll_fds_for_input (temp_mask))
	{
#if 0
	  stderr_out ("mark_what_as_being_ready: no input available (fd=%d)\n",
		      closure->fd);
#endif
	  return;
	}
      filedesc_with_input[closure->fd] = closure->what;
      if (PROCESSP (closure->what))
      /* Don't increment this if the current process is already marked
       *  as having input. */
	process_events_occurred++;
      else
	tty_events_occurred++;
    }
}

static void
Xt_what_callback (void *closure, int *UNUSED (source), XtInputId *UNUSED (id))
{
  /* If closure is 0, then we got a fake event from a signal handler.
     The only purpose of this is to make XtAppProcessEvent() stop
     blocking. */
  if (closure)
    mark_what_as_being_ready ((struct what_is_ready_closure *) closure);
  else
    {
      fake_event_occurred++;
      drain_signal_event_pipe ();
    }
}

static void
select_filedesc (int fd, Lisp_Object what)
{
  struct what_is_ready_closure *closure;

  /* If somebody is trying to select something that's already selected
     for, then something went wrong.  The generic routines ought to
     detect this and error before here. */
  assert (!filedesc_to_what_closure[fd]);

  closure = xnew (struct what_is_ready_closure);
  closure->fd = fd;
  closure->what = what;
  closure->id =
    XtAppAddInput (Xt_app_con, fd,
		   (XtPointer) (XtInputReadMask /* | XtInputExceptMask */),
		   Xt_what_callback, closure);
  filedesc_to_what_closure[fd] = closure;
}

static void
unselect_filedesc (int fd)
{
  struct what_is_ready_closure *closure = filedesc_to_what_closure[fd];

  assert (closure);
  if (!NILP (filedesc_with_input[fd]))
    {
      /* We are unselecting this process before we have drained the rest of
	 the input from it, probably from status_notify() in the command loop.
	 This can happen like so:

	  - We are waiting in XtAppNextEvent()
	  - Process generates output
	  - Process is marked as being ready
	  - Process dies, SIGCHLD gets generated before we return (!?)
	    It could happen I guess.
	  - sigchld_handler() marks process as dead
	  - Somehow we end up getting a new KeyPress event on the queue
	    at the same time (I'm really so sure how that happens but I'm
	    not sure it can't either so let's assume it can...).
	  - Key events have priority so we return that instead of the proc.
	  - Before dispatching the lisp key event we call status_notify()
	  - Which deselects the process that SIGCHLD marked as dead.

	 Thus we never remove it from _with_input and turn it into a lisp
	 event, so we need to do it here.  But this does not mean that we're
	 throwing away the last block of output - status_notify() has already
	 taken care of running the proc filter or whatever.
       */
      filedesc_with_input[fd] = Qnil;
      if (PROCESSP (closure->what))
	{
	  assert (process_events_occurred > 0);
	  process_events_occurred--;
	}
      else
	{
	  assert (tty_events_occurred > 0);
	  tty_events_occurred--;
	}
    }
  XtRemoveInput (closure->id);
  xfree (closure);
  filedesc_to_what_closure[fd] = 0;
}

static void
emacs_Xt_select_process (Lisp_Process *process, int doin, int doerr)
{
  Lisp_Object proc;
  int infd, errfd;

  event_stream_unixoid_select_process (process, doin, doerr, &infd, &errfd);

  proc = wrap_process (process);
  if (doin)
    select_filedesc (infd, proc);
  if (doerr)
    select_filedesc (errfd, proc);
}

static void
emacs_Xt_unselect_process (Lisp_Process *process, int doin, int doerr)
{
  int infd, errfd;

  event_stream_unixoid_unselect_process (process, doin, doerr, &infd, &errfd);

  if (doin)
    unselect_filedesc (infd);
  if (doerr)
    unselect_filedesc (errfd);
}

static void
emacs_Xt_create_io_streams (void *inhandle, void *outhandle,
			    void *errhandle, Lisp_Object *instream,
			    Lisp_Object *outstream,
			    Lisp_Object *errstream,
			    USID *in_usid,
			    USID *err_usid,
			    int flags)
{
  event_stream_unixoid_create_io_streams
    (inhandle, outhandle, errhandle, instream, outstream,
     errstream, in_usid, err_usid, flags);
  if (*in_usid != USID_ERROR)
    *in_usid = USID_DONTHASH;
  if (*err_usid != USID_ERROR)
    *err_usid = USID_DONTHASH;
}

static void
emacs_Xt_delete_io_streams (Lisp_Object instream,
			    Lisp_Object outstream,
			    Lisp_Object errstream,
			    USID *in_usid,
			    USID *err_usid)
{
  event_stream_unixoid_delete_io_streams
    (instream, outstream, errstream, in_usid, err_usid);
  *in_usid = USID_DONTHASH;
  *err_usid = USID_DONTHASH;
}

/* This is called from GC when a process object is about to be freed.
   If we've still got pointers to it in this file, we're gonna lose hard.
 */
void
debug_process_finalization (Lisp_Process *UNUSED (p))
{
#if 0 /* #### */
  int i;
  Lisp_Object instr, outstr, errstr;

  get_process_streams (p, &instr, &outstr, &errstr);
  /* if it still has fds, then it hasn't been killed yet. */
  assert (NILP(instr));
  assert (NILP(outstr));
  assert (NILP(errstr));
  /* Better not still be in the "with input" table; we know it's got no fds. */
  for (i = 0; i < MAXDESC; i++)
    {
      Lisp_Object process = filedesc_fds_with_input [i];
      assert (!PROCESSP (process) || XPROCESS (process) != p);
    }
#endif
}

static void
Xt_process_to_emacs_event (Lisp_Event *emacs_event)
{
  int i;

  assert (process_events_occurred > 0);

  for (i = 0; i < MAXDESC; i++)
    {
      Lisp_Object process = filedesc_with_input[i];
      if (PROCESSP (process))
	{
	  filedesc_with_input[i] = Qnil;
	  process_events_occurred--;
	  /* process events have nil as channel */
	  set_event_type (emacs_event, process_event);
	  SET_EVENT_TIMESTAMP_ZERO (emacs_event); /* #### */
	  SET_EVENT_PROCESS_PROCESS (emacs_event, process);
	  return;
	}
    }
  ABORT ();
}

static void
emacs_Xt_select_console (struct console *con)
{
  Lisp_Object console;
  int infd;

  if (CONSOLE_X_P (con))
    return; /* X consoles are automatically selected for when we
	       initialize them in Xt */
  infd = event_stream_unixoid_select_console (con);
  console = wrap_console (con);
  select_filedesc (infd, console);
}

static void
emacs_Xt_unselect_console (struct console *con)
{
  int infd;

  if (CONSOLE_X_P (con))
    return; /* X consoles are automatically selected for when we
	       initialize them in Xt */
  infd = event_stream_unixoid_unselect_console (con);
  unselect_filedesc (infd);
}

/* read an event from a tty, if one is available.  Returns non-zero
   if an event was available.  Note that when this function is
   called, there should always be a tty marked as ready for input.
   However, the input condition might actually be EOF, so there
   may not really be any input available. (In this case,
   read_event_from_tty_or_stream_desc() will arrange for the TTY device
   to be deleted.) */

static int
Xt_tty_to_emacs_event (Lisp_Event *emacs_event)
{
  int i;

  assert (tty_events_occurred > 0);
  for (i = 0; i < MAXDESC; i++)
    {
      Lisp_Object console = filedesc_with_input[i];
      if (CONSOLEP (console))
	{
	  assert (tty_events_occurred > 0);
	  tty_events_occurred--;
	  filedesc_with_input[i] = Qnil;
	  if (read_event_from_tty_or_stream_desc (emacs_event,
						  XCONSOLE (console)))
	    return 1;
	}
    }

  return 0;
}


/************************************************************************/
/*		debugging functions to decipher an event		*/
/************************************************************************/

#ifdef DEBUG_XEMACS
#include "xintrinsicp.h"	/* only describe_event() needs this */
#include <X11/Xproto.h>		/* only describe_event() needs this */

static void
describe_event_window (Window window, Display *display, Lisp_Object pstream)
{
  struct frame *f;
  Widget w;
  write_fmt_string (pstream, "   window: 0x%lx", (unsigned long) window);
  w = XtWindowToWidget (display, window);
  if (w)
    write_fmt_string (pstream, " %s",
		      w->core.widget_class->core_class.class_name);
  f = x_any_window_to_frame (get_device_from_display (display), window);
  if (f)
    write_fmt_string_lisp (pstream, " \"%s\"", 1, f->name);
  write_fmt_string (pstream, "\n");
}

static const char *
XEvent_mode_to_string (int mode)
{
  switch (mode)
  {
  case NotifyNormal:	   return "Normal";
  case NotifyGrab:	   return "Grab";
  case NotifyUngrab:	   return "Ungrab";
  case NotifyWhileGrabbed: return "WhileGrabbed";
  default:		   return "???";
  }
}

static const char *
XEvent_detail_to_string (int detail)
{
  switch (detail)
  {
  case NotifyAncestor:		return "Ancestor";
  case NotifyInferior:		return "Inferior";
  case NotifyNonlinear:		return "Nonlinear";
  case NotifyNonlinearVirtual:	return "NonlinearVirtual";
  case NotifyPointer:		return "Pointer";
  case NotifyPointerRoot:	return "PointerRoot";
  case NotifyDetailNone:	return "DetailNone";
  default:			return "???";
  }
}

static const char *
XEvent_visibility_to_string (int state)
{
  switch (state)
  {
  case VisibilityFullyObscured:	    return "FullyObscured";
  case VisibilityPartiallyObscured: return "PartiallyObscured";
  case VisibilityUnobscured:        return "Unobscured";
  default:			    return "???";
  }
}

static void
describe_event (XEvent *event, Lisp_Object pstream)
{
  Ascbyte buf[100];
  struct device *d = get_device_from_display (event->xany.display);

  sprintf (buf, "%s%s", x_event_name (event->type),
	   event->xany.send_event ? " (send)" : "");
  write_fmt_string (pstream, "%-30s", buf);
  switch (event->type)
    {
    case FocusIn:
    case FocusOut:
      {
	XFocusChangeEvent *ev = &event->xfocus;
	describe_event_window (ev->window, ev->display, pstream);
	write_fmt_string (pstream, "     mode: %s\n",
			  XEvent_mode_to_string (ev->mode));
	write_fmt_string (pstream, "     detail: %s\n",
			  XEvent_detail_to_string (ev->detail));
	break;
      }

    case KeyPress:
      {
	XKeyEvent *ev = &event->xkey;
	unsigned int state = ev->state;

	describe_event_window (ev->window, ev->display, pstream);
	write_fmt_string (pstream, "   subwindow: %ld\n", ev->subwindow);
	write_fmt_string (pstream, "   state: ");
	/* Complete list of modifier key masks */
	if (state & ShiftMask)   write_fmt_string (pstream, "Shift ");
	if (state & LockMask)    write_fmt_string (pstream, "Lock ");
	if (state & ControlMask) write_fmt_string (pstream, "Control ");
	if (state & Mod1Mask)    write_fmt_string (pstream, "Mod1 ");
	if (state & Mod2Mask)    write_fmt_string (pstream, "Mod2 ");
	if (state & Mod3Mask)    write_fmt_string (pstream, "Mod3 ");
	if (state & Mod4Mask)    write_fmt_string (pstream, "Mod4 ");
	if (state & Mod5Mask)    write_fmt_string (pstream, "Mod5 ");

	if (! state)
	  write_fmt_string (pstream, "vanilla\n");
	else
	  write_fmt_string (pstream, "\n");
	if (x_key_is_modifier_p (ev->keycode, d))
	  write_fmt_string (pstream, "   Modifier key");
	write_fmt_string (pstream, "   keycode: 0x%x\n", ev->keycode);
      }
    break;

    case Expose:
      if (debug_x_events > 1)
	{
	  XExposeEvent *ev = &event->xexpose;
	  describe_event_window (ev->window, ev->display, pstream);
	  write_fmt_string (pstream,
			    "   region: x=%d y=%d width=%d height=%d\n",
                      ev->x, ev->y, ev->width, ev->height);
	  write_fmt_string (pstream, "    count: %d\n", ev->count);
	}
      else
	write_fmt_string (pstream, "\n");
      break;

    case GraphicsExpose:
      if (debug_x_events > 1)
	{
	  XGraphicsExposeEvent *ev = &event->xgraphicsexpose;
	  describe_event_window (ev->drawable, ev->display, pstream);
	  write_fmt_string (pstream, "    major: %s\n",
		      (ev ->major_code == X_CopyArea  ? "CopyArea" :
		       (ev->major_code == X_CopyPlane ? "CopyPlane" : "?")));
	  write_fmt_string (pstream,
			    "   region: x=%d y=%d width=%d height=%d\n",
                      ev->x, ev->y, ev->width, ev->height);
	  write_fmt_string (pstream, "    count: %d\n", ev->count);
	}
      else
	write_fmt_string (pstream, "\n");
      break;

    case EnterNotify:
    case LeaveNotify:
      if (debug_x_events > 1)
	{
	  XCrossingEvent *ev = &event->xcrossing;
	  describe_event_window (ev->window, ev->display, pstream);
#if 0
	  write_fmt_string (pstream, " subwindow: 0x%x\n", ev->subwindow);
	  write_fmt_string (pstream, "      pos: %d %d\n", ev->x, ev->y);
	  write_fmt_string (pstream, " root pos: %d %d\n", ev->x_root,
			    ev->y_root);
#endif
	  write_fmt_string (pstream, "    mode: %s\n",
			    XEvent_mode_to_string(ev->mode));
	  write_fmt_string (pstream, "    detail: %s\n",
			    XEvent_detail_to_string(ev->detail));
	  write_fmt_string (pstream, "    focus: %d\n", ev->focus);
#if 0
	  write_fmt_string (pstream, "    state: 0x%x\n", ev->state);
#endif
	}
      else
	write_fmt_string (pstream, "\n");
      break;

    case ConfigureNotify:
      if (debug_x_events > 1)
	{
	  XConfigureEvent *ev = &event->xconfigure;
	  describe_event_window (ev->window, ev->display, pstream);
	  write_fmt_string (pstream, "    above: 0x%lx\n", ev->above);
	  write_fmt_string (pstream, "     size: %d %d %d %d\n", ev->x, ev->y,
		     ev->width, ev->height);
	  write_fmt_string (pstream, "  redirect: %d\n",
			    ev->override_redirect);
	}
      else
	write_fmt_string (pstream, "\n");
      break;

    case VisibilityNotify:
      if (debug_x_events > 1)
	{
	  XVisibilityEvent *ev = &event->xvisibility;
	  describe_event_window (ev->window, ev->display, pstream);
	  write_fmt_string (pstream, "    state: %s\n",
		      XEvent_visibility_to_string (ev->state));
	}
      else
	write_fmt_string (pstream, "\n");
      break;

    case ClientMessage:
      {
	XClientMessageEvent *ev = &event->xclient;
	char *name = XGetAtomName (ev->display, ev->message_type);
	write_fmt_string (pstream, "%s", name);
	if (!strcmp (name, "WM_PROTOCOLS"))
	  {
	    char *protname = XGetAtomName (ev->display, ev->data.l[0]);
	    write_fmt_string (pstream, "(%s)", protname);
	    XFree (protname);
	  }
	XFree (name);
	write_fmt_string (pstream, "\n");
	break;
      }

    default:
      write_fmt_string (pstream, "\n");
      break;
    }

  fflush (stdout);
}

#endif /* include describe_event definition */


/************************************************************************/
/*			get the next event from Xt			*/
/************************************************************************/

/* This business exists because menu events "happen" when
   menubar_selection_callback() is called from somewhere deep
   within XtAppProcessEvent in emacs_Xt_next_event().  The
   callback needs to terminate the modal loop in that function
   or else it will continue waiting until another event is
   received.

   Same business applies to scrollbar events. */

void
signal_special_Xt_user_event (Lisp_Object channel, Lisp_Object function,
			      Lisp_Object object)
{
  Lisp_Object event = Fmake_event (Qnil, Qnil);

  XSET_EVENT_TYPE (event, misc_user_event);
  XSET_EVENT_CHANNEL (event, channel);
  XSET_EVENT_MISC_USER_FUNCTION (event, function);
  XSET_EVENT_MISC_USER_OBJECT (event, object);
  enqueue_dispatch_event (event);
}

static void
emacs_Xt_next_event (Lisp_Event *emacs_event)
{
 we_didnt_get_an_event:

  while (NILP (dispatch_event_queue) &&
	 !completed_timeouts         &&
	 !fake_event_occurred        &&
	 !process_events_occurred    &&
	 !tty_events_occurred)
    {
      if (in_modal_loop)
	{
	  /* in_modal_loop gets set when we are in the process of
	     dispatching an event (more specifically, when we are inside of
	     a menu callback -- if we get here, it means we called a filter
	     and the filter did something that tried to fetch an event,
	     e.g. sit-for).  In such a case, we cannot safely dispatch any
	     more events.  This is because those dispatching those events
	     could cause lwlib to be entered reentranty, specifically if
	     they are menu events.  lwlib is not designed for this and will
	     crash.  We used to see this crash constantly as a result of
	     QUIT checking, but QUIT will not now function in a modal loop.
	     However, we can't just not process any events at all, because
	     that will make sit-for etc. hang.  So we go ahead and process
	     the non-X kinds of events. */
#ifdef WIN32_ANY
	  mswindows_is_blocking = 1;
#endif
	  XtAppProcessEvent (Xt_app_con, XtIMTimer | XtIMAlternateInput);
#ifdef WIN32_ANY
	  mswindows_is_blocking = 0;
#endif
	}
      else
	{
	  /* Stupid logic in XtAppProcessEvent() dictates that, if process
	     events and X events are both available, the process event gets
	     taken first.  This will cause an infinite loop if we're being
	     called from Fdiscard_input().
	  */

	  if (XtAppPending (Xt_app_con) & XtIMXEvent)
	    XtAppProcessEvent (Xt_app_con, XtIMXEvent);
	  else
	    {
	      Lisp_Object devcons, concons;

	      /* We're about to block.  Xt has a bug in it (big surprise,
		 there) in that it blocks using select() and doesn't
		 flush the Xlib output buffers (XNextEvent() does this
		 automatically before blocking).  So it's necessary
		 for us to do this ourselves.  If we don't do it, then
		 display output may not be seen until the next time
		 an X event is received. (This happens esp. with
		 subprocess output that gets sent to a visible buffer.)

		 #### The above comment may not have any validity. */

	      DEVICE_LOOP_NO_BREAK (devcons, concons)
		{
		  struct device *d;
		  d = XDEVICE (XCAR (devcons));

		  if (DEVICE_X_P (d) && DEVICE_X_DISPLAY (d))
		    /* emacs may be exiting */
		    XFlush (DEVICE_X_DISPLAY (d));
		}
#ifdef WIN32_ANY
	      mswindows_is_blocking = 1;
#endif
	      XtAppProcessEvent (Xt_app_con, XtIMAll);
#ifdef WIN32_ANY
	      mswindows_is_blocking = 0;
#endif
	    }
	}
    }

  if (!NILP (dispatch_event_queue))
    {
      Lisp_Object event, event2;
      event2 = wrap_event (emacs_event);
      event = dequeue_dispatch_event ();
      Fcopy_event (event, event2);
      Fdeallocate_event (event);
    }
  else if (tty_events_occurred)
    {
      if (!Xt_tty_to_emacs_event (emacs_event))
	goto we_didnt_get_an_event;
    }
  else if (completed_timeouts)
    Xt_timeout_to_emacs_event (emacs_event);
  else if (fake_event_occurred)
    {
      /* A dummy event, so that a cycle of the command loop will occur. */
      fake_event_occurred = 0;
      /* eval events have nil as channel */
      set_event_type (emacs_event, eval_event);
      SET_EVENT_EVAL_FUNCTION (emacs_event, Qidentity);
      SET_EVENT_EVAL_OBJECT (emacs_event, Qnil);
    }
  else /* if (process_events_occurred) */
    Xt_process_to_emacs_event (emacs_event);

  /* No need to call XFilterEvent; Xt does it for us */
}

void
emacs_Xt_event_handler (Widget UNUSED (wid),
			XtPointer UNUSED (closure),
			XEvent *event,
			Boolean *UNUSED (continue_to_dispatch))
{
  Lisp_Object emacs_event = Fmake_event (Qnil, Qnil);

#ifdef DEBUG_XEMACS
  if (debug_x_events > 0)
    describe_event (event, Qexternal_debugging_output);
#endif /* DEBUG_XEMACS */
  if (x_event_to_emacs_event (event, XEVENT (emacs_event)))
    enqueue_dispatch_event (emacs_event);
  else
    Fdeallocate_event (emacs_event);
}


/************************************************************************/
/*                            input pending                             */
/************************************************************************/

static void
emacs_Xt_drain_queue (void)
{
  Lisp_Object devcons, concons;
  if (!in_modal_loop)
    {
      CONSOLE_LOOP (concons)
	{
	  struct console *con = XCONSOLE (XCAR (concons));
	  if (!con->input_enabled)
	    continue;

	  CONSOLE_DEVICE_LOOP (devcons, con)
	    {
	      struct device *d;
	      Display *display;
	      d = XDEVICE (XCAR (devcons));
	      if (DEVICE_X_P (d) && DEVICE_X_DISPLAY (d))
		{
		  display = DEVICE_X_DISPLAY (d);
		  while (XEventsQueued (display, QueuedAfterReading))
		    XtAppProcessEvent (Xt_app_con, XtIMXEvent);
		}
	    }
	}
      /*
	while (XtAppPending (Xt_app_con) & XtIMXEvent)
	XtAppProcessEvent (Xt_app_con, XtIMXEvent);
      */
    }

#ifdef HAVE_TTY
  drain_tty_devices ();
#endif
}

int
check_if_pending_expose_event (struct device *dev)
{
  Display *d = DEVICE_X_DISPLAY (dev);
  Lisp_Object event;

  emacs_Xt_drain_queue ();

  EVENT_CHAIN_LOOP (event, dispatch_event_queue)
    if (XEVENT_TYPE (event) == magic_event)
      {
	XEvent *xev = &XEVENT_MAGIC_X_EVENT (event);
	if (xev->type == Expose &&
	    xev->xexpose.display == d)
	  return 1;
      }

  return 0;
}

static int
emacs_Xt_current_event_timestamp (struct console *c)
{
  /* semi-yuck. */
  Lisp_Object devs = CONSOLE_DEVICE_LIST (c);

  if (NILP (devs))
    return 0;
  else
    {
      struct device *d = XDEVICE (XCAR (devs));
      return DEVICE_X_LAST_SERVER_TIMESTAMP (d);
    }
}


/************************************************************************/
/*            replacement for standard string-to-pixel converter        */
/************************************************************************/

/* This was constructed by ripping off the standard string-to-pixel
   converter from Converters.c in the Xt source code and modifying
   appropriately. */

#if 0

/* This is exported by the Xt library (at least by mine).  If this
   isn't the case somewhere, rename this appropriately and remove
   the '#if 0'.  Note, however, that I got "unknown structure"
   errors when I tried this. */
XtConvertArgRec Const colorConvertArgs[] = {
  { XtWidgetBaseOffset, (XtPointer)XtOffsetOf(WidgetRec, core.screen),
    sizeof (Screen *) },
  { XtWidgetBaseOffset, (XtPointer)XtOffsetOf(WidgetRec, core.colormap),
    sizeof (Colormap) }
};

#endif

#define done(type, value)               \
  if (toVal->addr != NULL) {             \
    if (toVal->size < sizeof(type)) {    \
      toVal->size = sizeof(type);        \
      return False;                      \
    }                                    \
    *(type*)(toVal->addr) = (value);     \
  } else {                               \
    static type static_val;              \
    static_val = (value);                \
    toVal->addr = (XPointer)&static_val; \
  }                                      \
  toVal->size = sizeof(type);            \
  return True /* Caller supplies `;' */

/* JH: We use this because I think there's a possibility this
   is called before the device is properly set up, in which case
   I don't want to abort. */
extern struct device *get_device_from_display_1 (Display *dpy);

static
Boolean EmacsXtCvtStringToPixel (
 Display     *dpy,
 XrmValuePtr  args,
 Cardinal    *num_args,
 XrmValuePtr  fromVal,
 XrmValuePtr  toVal,
 XtPointer   *closure_ret)
{
  String       str = (String)fromVal->addr;
  XColor       screenColor;
  XColor       exactColor;
  Screen       *screen;
  Colormap     colormap;
  Visual       *visual;
  struct device *d;
  Status       status;
  String       params[1];
  Cardinal     num_params  = 1;
  XtAppContext the_app_con = XtDisplayToApplicationContext (dpy);

  if (*num_args != 2) {
    XtAppWarningMsg(the_app_con, "wrongParameters", "cvtStringToPixel",
                    "XtToolkitError",
                    "String to pixel conversion needs screen and colormap arguments",
                    (String *)NULL, (Cardinal *)NULL);
    return False;
  }

  screen   = *((Screen **)  args[0].addr);
  colormap = *((Colormap *) args[1].addr);

  /* The original uses the private function CompareISOLatin1().
     Use XmuCompareISOLatin1() if you want, but I don't think it
     makes any difference here. */
  if (strcmp(str, XtDefaultBackground) == 0) {
    *closure_ret = False;
    /* This refers to the display's "*reverseVideo" resource.
       These display resources aren't documented anywhere that
       I can find, so I'm going to ignore this. */
    /* if (pd->rv) done(Pixel, BlackPixelOfScreen(screen)) else */
    done(Pixel, WhitePixelOfScreen(screen));
  }
  if (strcmp(str, XtDefaultForeground) == 0) {
    *closure_ret = False;
    /* if (pd->rv) done(Pixel, WhitePixelOfScreen(screen)) else */
    done(Pixel, BlackPixelOfScreen(screen));
  }

  /* Originally called XAllocNamedColor() here. */
  if ((d = get_device_from_display_1(dpy))) {
    visual = DEVICE_X_VISUAL(d);
    if (colormap != DEVICE_X_COLORMAP(d)) {
      XtAppWarningMsg(the_app_con, "weirdColormap", "cvtStringToPixel",
		      "XtToolkitWarning",
		      "The colormap passed to cvtStringToPixel doesn't match the one registered to the device.\n",
		      NULL, 0);
      status = XAllocNamedColor(dpy, colormap, (char*)str, &screenColor, &exactColor);
    } else {
      status = XParseColor (dpy, colormap, (char*)str, &screenColor);
      if (status) {
	status = x_allocate_nearest_color (dpy, colormap, visual, &screenColor);
      }
    }
  } else {
    /* We haven't set up this device totally yet, so just punt */
    status = XAllocNamedColor(dpy, colormap, (char*)str, &screenColor, &exactColor);
  }
  if (status == 0) {
    params[0] = str;
    /* Server returns a specific error code but Xlib discards it.  Ugh */
    if (XLookupColor(DisplayOfScreen(screen), colormap, (char*) str,
                     &exactColor, &screenColor)) {
      XtAppWarningMsg(the_app_con, "noColormap", "cvtStringToPixel",
                      "XtToolkitError",
                      "Cannot allocate colormap entry for \"%s\"",
                      params, &num_params);

    } else {
      XtAppWarningMsg(the_app_con, "badValue", "cvtStringToPixel",
                      "XtToolkitError",
                      "Color name \"%s\" is not defined", params, &num_params);
    }

    *closure_ret = False;
    return False;
  } else {
    *closure_ret = (char*)True;
    done(Pixel, screenColor.pixel);
  }
}

/* ARGSUSED */
static void EmacsFreePixel (
  XtAppContext app,
  XrmValuePtr  toVal,
  XtPointer    closure,
  XrmValuePtr  args,
  Cardinal    *num_args)
{
  if (*num_args != 2) {
    XtAppWarningMsg(app, "wrongParameters","freePixel","XtToolkitError",
                    "Freeing a pixel requires screen and colormap arguments",
                    (String *)NULL, (Cardinal *)NULL);
    return;
  }

  if (closure) {
    Screen   *screen  = *((Screen **)  args[0].addr);
    Colormap colormap = *((Colormap *) args[1].addr);
    XFreeColors(DisplayOfScreen(screen), colormap,
                (unsigned long*)toVal->addr, 1, (unsigned long)0);
  }
}


/************************************************************************/
/*            handle focus changes for native widgets                  */
/************************************************************************/
static void
emacs_Xt_event_widget_focus_in (Widget   w,
				XEvent   *event,
				String   *UNUSED (params),
				Cardinal *UNUSED (num_params))
{
  struct frame *f =
    x_any_widget_or_parent_to_frame (get_device_from_display (event->xany.display), w);

  XtSetKeyboardFocus (FRAME_X_SHELL_WIDGET (f), w);
}

static void
emacs_Xt_event_widget_focus_out (Widget   UNUSED (w),
				 XEvent   *UNUSED (event),
				 String   *UNUSED (params),
				 Cardinal *UNUSED (num_params))
{
}

static XtActionsRec widgetActionsList[] =
{
  { (String) "widget-focus-in",  emacs_Xt_event_widget_focus_in	 },
  { (String) "widget-focus-out", emacs_Xt_event_widget_focus_out },
};

static void
emacs_Xt_event_add_widget_actions (XtAppContext ctx)
{
  XtAppAddActions (ctx, widgetActionsList, 2);
}


/************************************************************************/
/*                            initialization                            */
/************************************************************************/

void
syms_of_event_Xt (void)
{
}

void
reinit_vars_of_event_Xt (void)
{
  Xt_event_stream = xnew_and_zero (struct event_stream);
  Xt_event_stream->event_pending_p 	 = emacs_Xt_event_pending_p;
  Xt_event_stream->force_event_pending_cb= emacs_Xt_force_event_pending;
  Xt_event_stream->next_event_cb	 = emacs_Xt_next_event;
  Xt_event_stream->handle_magic_event_cb = emacs_Xt_handle_magic_event;
  Xt_event_stream->format_magic_event_cb = emacs_Xt_format_magic_event;
  Xt_event_stream->compare_magic_event_cb= emacs_Xt_compare_magic_event;
  Xt_event_stream->hash_magic_event_cb   = emacs_Xt_hash_magic_event;
  Xt_event_stream->add_timeout_cb 	 = emacs_Xt_add_timeout;
  Xt_event_stream->remove_timeout_cb 	 = emacs_Xt_remove_timeout;
  Xt_event_stream->select_console_cb 	 = emacs_Xt_select_console;
  Xt_event_stream->unselect_console_cb 	 = emacs_Xt_unselect_console;
  Xt_event_stream->select_process_cb 	 = emacs_Xt_select_process;
  Xt_event_stream->unselect_process_cb 	 = emacs_Xt_unselect_process;
  Xt_event_stream->drain_queue_cb	 = emacs_Xt_drain_queue;
  Xt_event_stream->create_io_streams_cb  = emacs_Xt_create_io_streams;
  Xt_event_stream->delete_io_streams_cb  = emacs_Xt_delete_io_streams;
  Xt_event_stream->current_event_timestamp_cb =
    emacs_Xt_current_event_timestamp;

  the_Xt_timeout_blocktype = Blocktype_new (struct Xt_timeout_blocktype);

  last_quit_check_signal_tick_count = 0;

  /* this function only makes safe calls */
  init_what_input_once ();
}

void
vars_of_event_Xt (void)
{
  DEFVAR_BOOL ("x-allow-sendevents", &x_allow_sendevents /*
*Non-nil means to allow synthetic events.  Nil means they are ignored.
Beware: allowing emacs to process SendEvents opens a big security hole.
*/ );
  x_allow_sendevents = 0;

#ifdef DEBUG_XEMACS
  DEFVAR_INT ("debug-x-events", &debug_x_events /*
If non-zero, display debug information about X events that XEmacs sees.
Information is displayed on stderr.  Currently defined values are:

1 == non-verbose output
2 == verbose output
*/ );
  debug_x_events = 0;
#endif
  DEFVAR_LISP ("x-us-keymap-description", &Vx_us_keymap_description /*
X11-specific vector describing the current keyboard hardware, and how to map
from its keycodes to those alphanumeric and punctuation characters that
would be produced by it if a US layout were configured in software.

We use this to make possible the usage of standard key bindings on keyboards
where the keys that those bindings assume are not available; for example, on
a Russian keyboard, one can type C-Cyrillic_che C-Cyrillic_a and have XEmacs
use the binding for C-x C-f, rather than give an error message that
C-Cyrillic_che C-Cyrillic_a is not bound.

Entries are either nil, which means the corresponding key code does not map
to a non-function key in the US layout, a single character, meaning it maps to
that character, or a vector of two characters, the first indicating the
unshifted mapping, the second the shifted mapping for the US layout.

`x-us-keymap-first-keycode' tells XEmacs the keycode of the first entry in
this vector. 
*/ );
  Vx_us_keymap_description = Qnil;

  DEFVAR_INT ("x-us-keymap-first-keycode", &Vx_us_keymap_first_keycode /*
The X11 keycode that the first entry in `x-us-keymap-description'
corresponds to.  See the documentation for that variable. 

The X11 documentation for XDisplayKeycodes says this can never be less than
8, but XEmacs doesn't enforce any limitation on what you set it to. 
*/ );
  Vx_us_keymap_first_keycode = 0;
}

/* This mess is a hack that patches the shell widget to treat visual inheritance
   the same as colormap and depth inheritance */

static XtInitProc orig_shell_init_proc;

static void ShellVisualPatch(Widget wanted, Widget new_,
			     ArgList args, Cardinal *num_args)
{
  Widget p;
  ShellWidget w = (ShellWidget) new_;

  /* first, call the original setup */
  (*orig_shell_init_proc)(wanted, new_, args, num_args);

  /* if the visual isn't explicitly set, grab it from the nearest shell ancestor */
  if (w->shell.visual == CopyFromParent) {
    p = XtParent(w);
    while (p && !XtIsShell(p)) p = XtParent(p);
    if (p) w->shell.visual = ((ShellWidget)p)->shell.visual;
  }
}

void
init_event_Xt_late (void) /* called when already initialized */
{
  timeout_id_tick = 1;
  pending_timeouts = 0;
  completed_timeouts = 0;

  event_stream = Xt_event_stream;

  XtToolkitInitialize ();
  Xt_app_con = XtCreateApplicationContext ();
  XtAppSetFallbackResources (Xt_app_con, (String *) x_fallback_resources);

  /* In select-x.c */
  x_selection_timeout = (XtAppGetSelectionTimeout (Xt_app_con) / 1000);
  XSetErrorHandler (x_error_handler);
  XSetIOErrorHandler (x_IO_error_handler);

#ifndef WIN32_NATIVE
  XtAppAddInput (Xt_app_con, signal_event_pipe[0],
		 (XtPointer) (XtInputReadMask /* | XtInputExceptMask */),
		 Xt_what_callback, 0);
#endif

  XtAppSetTypeConverter (Xt_app_con, XtRString, XtRPixel,
		         EmacsXtCvtStringToPixel,
			 (XtConvertArgList) colorConvertArgs,
			 2, XtCacheByDisplay, EmacsFreePixel);

#ifdef XIM_XLIB
  XtAppSetTypeConverter (Xt_app_con, XtRString, XtRXimStyles,
		         EmacsXtCvtStringToXIMStyles,
			 NULL, 0,
			 XtCacheByDisplay, EmacsFreeXIMStyles);
#endif /* XIM_XLIB */
  /* Add extra actions to native widgets to handle focus and friends. */
  emacs_Xt_event_add_widget_actions (Xt_app_con);

  /* insert the visual inheritance patch/hack described above */
  orig_shell_init_proc = shellClassRec.core_class.initialize;
  shellClassRec.core_class.initialize = ShellVisualPatch;

}
