/* The event_stream interface for X11 with Xt, and/or tty frames.
   Copyright (C) 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
   Copyright (C) 1994, 1995 Amdahl Corporation.

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 2, 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; see the file COPYING.  If not, write to the Free
Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */

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

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

#include "device-x.h"
#include "frame-x.h"
#include "lwlib.h"
#include "EmacsFrame.h"

#include "blocktype.h"
#include "commands.h"
#include "device-tty.h"
#include "events.h"
#include "process.h"
#include "redisplay.h"

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

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 send by other clients? */
int x_allow_sendevents;

#ifdef DEBUG_XEMACS
int x_debug_events;
#endif

static int process_events_occurred;
static int tty_events_occurred;

/* Mask of bits indicating the tty descriptors that we wait for input on */
static SELECT_TYPE tty_device_mask;

static String 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 };

void emacs_Xt_mapping_action (Widget w, XEvent *event);
void debug_process_finalization (struct Lisp_Process *p);
Lisp_Object dequeue_Xt_dispatch_event (void);
void emacs_Xt_event_handler (Widget wid, XtPointer closure, XEvent *event,
			     Boolean *continue_to_dispatch);

static int last_sigio_tick_count;

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

/* 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
   prints an error message on the standard-error-output.  (Perhaps it should
   use a pop-up-window instead.)
 */

static void
x_reset_key_mapping (struct device *d)
{
  Display *display = DEVICE_X_DISPLAY (d);
  struct x_device *xd = DEVICE_X_DATA (d);
  int max_code;
  if (xd->x_keysym_map)
    XFree ((char *) xd->x_keysym_map);
  XDisplayKeycodes (display, &xd->x_keysym_map_min_code,
		    &max_code);
  xd->x_keysym_map =
    XGetKeyboardMapping (display, xd->x_keysym_map_min_code,
			 max_code - xd->x_keysym_map_min_code + 1,
			 &xd->x_keysym_map_keysyms_per_code);
}

static CONST char *
index_to_name (int indice)
{
  return ((indice == ShiftMapIndex ? "ModShift"
           : (indice == LockMapIndex ? "ModLock"
              : (indice == ControlMapIndex ? "ModControl"
                 : (indice == Mod1MapIndex ? "Mod1"
                    : (indice == Mod2MapIndex ? "Mod2"
                       : (indice == Mod3MapIndex ? "Mod3"
                          : (indice == Mod4MapIndex ? "Mod4"
                             : (indice == Mod5MapIndex ? "Mod5"
                                : "???")))))))));
}

/* Boy, I really wish C had local functions... */
struct c_doesnt_have_closures   /* #### not yet used */
{
  int warned_about_overlapping_modifiers;
  int warned_about_predefined_modifiers;
  int warned_about_duplicate_modifiers;
  int meta_bit;
  int hyper_bit;
  int super_bit;
  int alt_bit;
  int mode_bit;
};

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);

  x_reset_key_mapping (d);

  xd->x_modifier_keymap = XGetModifierMapping (display);

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

  /* The call to warn_when_safe must be on the same line as the string or
     make-msgfile won't pick it up properly (the newline doesn't confuse
     it, but the backslash does). */

#define modwarn(name,old,other)						\
  warn_when_safe ("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 ("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 ("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 ("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 char *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
	    ("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 ("\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 ("\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).");

  /* Don\'t need to say anything more for warned_about_duplicate_modifiers. */

  if (warned_about_overlapping_modifiers || warned_about_predefined_modifiers)
    warn_when_safe ("\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)
{
  DEVICE_X_DATA (d)->x_keysym_map = 0;
  DEVICE_X_DATA (d)->x_modifier_keymap = 0;
  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 = &xd->x_keysym_map [(keycode - xd->x_keysym_map_min_code) *
				    xd->x_keysym_map_keysyms_per_code];
  int i;
  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;
}

static int
keysym_obeys_caps_lock_p (KeySym sym, struct device *d)
{
  struct x_device *xd = DEVICE_X_DATA (d);
  /* 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;
  if (((sym >= XK_A) && (sym <= XK_Z)) ||
      ((sym >= XK_a) && (sym <= XK_z)) ||
      ((sym >= XK_Agrave) && (sym <= XK_Odiaeresis)) ||
      ((sym >= XK_agrave) && (sym <= XK_odiaeresis)) ||
      ((sym >= XK_Ooblique) && (sym <= XK_Thorn)) ||
      ((sym >= XK_oslash) && (sym <= XK_thorn)))
    return 1;
  else
    return 0;
}

/* called from EmacsFrame.c (actually from Xt itself) when a
   MappingNotify event is received.  For non-obvious reasons,
   our event handler does not see these events, so we need a
   special translation. */
void
emacs_Xt_mapping_action (Widget w, XEvent* event)
{
  struct device *d = get_device_from_display (event->xany.display);
#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.
     */
  if (event->xmapping.request == MappingKeyboard)
    x_reset_key_mapping (d);
  else if (event->xmapping.request == MappingModifier)
    x_reset_modifier_mapping (d);
}

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

#if (defined(sun) || defined(__sun)) && defined(__GNUC__)
# define SUNOS_GCC_L0_BUG
#endif

#ifdef SUNOS_GCC_L0_BUG
static void
x_to_emacs_keysym_sunos_bug (Lisp_Object *return_value_sunos_bug, /* #### */
                             XEvent *event, int simple_p)
#else /* !SUNOS_GCC_L0_BUG */
static Lisp_Object
x_to_emacs_keysym (XEvent *event, int simple_p)
#endif /* !SUNOS_GCC_L0_BUG */
     /* simple_p means don't try too hard (ASCII only) */
{
  char *name;
  KeySym keysym = 0;
  struct device *d = get_device_from_display (event->xany.display);

#ifdef SUNOS_GCC_L0_BUG
# define return(lose) \
	do {*return_value_sunos_bug = (lose); goto return_it; } while (0)
#endif

  XLookupString (&event->xkey, 0, 0, &keysym,
		 &DEVICE_X_X_COMPOSE_STATUS (d));
  
  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_number (keysym));

  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);
      /* #### without return_value_sunos_bug, %l0 (GCC struct return pointer)
       * ####  gets roached (top 8 bits cleared) around this call.
       */
      name = XKeysymToString (keysym);
      if (!name || !name[0])	/* this shouldn't happen... */
	{
	  char buf [255];
	  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_number (name[0]));
      
      /* 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) & (~0xFF)) == ((unsigned int) 0xFF00))
	{
	  char buf [255];
	  char *s1, *s2;
	  for (s1 = name, s2 = buf; *s1; s1++, s2++)
	    *s2 = tolower (* (unsigned char *) s1);
	  *s2 = 0;
	  return (KEYSYM (buf));
	}
      return (KEYSYM (name));
    }
#ifdef SUNOS_GCC_L0_BUG
# undef return
 return_it:
  return;
#endif
}

#ifdef SUNOS_GCC_L0_BUG
/* #### */
static Lisp_Object
x_to_emacs_keysym (XEvent *event, int simple_p)
{
  Lisp_Object return_value_sunos_bug;
  x_to_emacs_keysym_sunos_bug (&return_value_sunos_bug, event, simple_p);
  return (return_value_sunos_bug);
}
#endif

static void
set_last_server_timestamp (struct device *d, XEvent *x_event)
{
  switch (x_event->xany.type)
    {
    case KeyPress:
    case KeyRelease:
      DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xkey.time;
      break;

    case ButtonPress:
    case ButtonRelease:
      DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xbutton.time;
      break;

    case MotionNotify:
      DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xmotion.time;
      break;

    case EnterNotify:
    case LeaveNotify:
      DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xcrossing.time;
      break;
      
    case PropertyNotify:
      DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xproperty.time;
      break;

    case SelectionClear:
      DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xselectionclear.time;
      break;

    case SelectionRequest:
      DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xselectionrequest.time;
      break;

    case SelectionNotify:
      DEVICE_X_LAST_SERVER_TIMESTAMP (d) = x_event->xselection.time;
      break;
    }
}

static void
x_event_to_emacs_event (XEvent *x_event, struct 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);
  struct frame *sel_frame = XFRAME (DEVICE_SELECTED_FRAME (d));

  XSETDEVICE (emacs_event->device, d);
  set_last_server_timestamp (d, x_event);

  switch (x_event->xany.type)
    {
    case KeyPress:
    case ButtonPress:
    case ButtonRelease:
      {
	unsigned int modifiers = 0;
	int shift_p = x_event->xkey.state & ShiftMask;
	int lock_p  = x_event->xkey.state & LockMask;
#ifdef EXTERNAL_WIDGET
	struct frame *f = x_any_window_to_frame (d, x_event->xany.window);
#endif
	
	/* 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.  (Actually, turn it into a no-op XAnyEvent,
	   and turn that into a magic event.  XtDispatchEvent will ignore
	   it.  We have to return some kind of event here, we're committed.
	   */
	if (((x_event->xany.type == KeyPress)
	     ? 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 (f)
#endif
	    && !x_allow_sendevents)
	  {
	    x_event->xany.type = 0;
	    goto MAGIC;
	  }
	
	if (x_event->xany.type == KeyPress)
	  DEVICE_X_GLOBAL_MOUSE_TIMESTAMP (d) = x_event->xkey.time;
	else
	  DEVICE_X_GLOBAL_MOUSE_TIMESTAMP (d) = x_event->xbutton.time;
	
	/* Ignore the caps-lock key w.r.t. mouse presses and releases. */
	if (x_event->xany.type != KeyPress)
	  lock_p = 0;
	
	if (x_event->xkey.state & ControlMask) modifiers |= MOD_CONTROL;
	if (x_event->xkey.state & xd->MetaMask)    modifiers |= MOD_META;
	if (x_event->xkey.state & xd->SuperMask)   modifiers |= MOD_SUPER;
	if (x_event->xkey.state & xd->HyperMask)   modifiers |= MOD_HYPER;
	if (x_event->xkey.state & xd->AltMask)     modifiers |= MOD_ALT;

	/* Ignore the caps-lock key if any other modifiers are down; this is
	   so that Caps doesn't turn C-x into C-X, which would suck. */
	if (modifiers)
	  {
	    x_event->xkey.state &= (~LockMask);
	    lock_p = 0;
	  }
	
	if (shift_p || lock_p)
	  modifiers |= MOD_SHIFT;
	
	DEVICE_X_MOUSE_TIMESTAMP (d) = DEVICE_X_GLOBAL_MOUSE_TIMESTAMP (d);
	
	switch (x_event->xany.type)
	  {
	  case KeyPress:
	    {
	      Lisp_Object keysym;
	      struct frame *frame = 0;
	      KeyCode keycode = x_event->xkey.keycode;
	      
#ifdef I18N4
	      /* "A KeyPress event with a KeyCode of zero is used
		 exclusively as a signal that an input method has
		 composed input which can be returned..." -- X11
		 R5 Xlib - C Library manual, section 13.14.2.
		 We treat the signal itself as a magic event --
		 i.e., ignore it.
		 */
	      if (keycode == 0)
		{
		  get_composed_input (&(x_event->xkey),
				      FRAME_X_INPUT_CONTEXT (sel_frame));
		  goto MAGIC;
		}
#endif
	      
	      if (x_key_is_modifier_p (keycode, d)) /* it's a modifier key */
		goto MAGIC;
	      
	      if (!frame)
		frame = x_any_window_to_frame (d, x_event->xkey.window);
	      
	      /* This doesn't seem right to me: shouldn't this be
		 "goto MAGIC"? */
	      if (! frame)
		frame = sel_frame;
	      
	      /* At this point, FRAME_X_INPUT_P (frame) may be false.
		 That's ok, because you can get keyboard input even if you
		 don't have focus...
		 */
	      XSETFRAME (emacs_event->channel, frame);
	      keysym = x_to_emacs_keysym (x_event, 0);
	      
	      /* If the emacs keysym is nil, then that means that the
		 X keysym was NoSymbol, which probably means that
		 we're in the midst of reading a Multi_key sequence,
		 or a "dead" key prefix.  Ignore it. */
	      if (NILP (keysym))
		goto MAGIC;
	      
	      /* 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 retch. */
	      /* #### type lossage: assuming equivalence of emacs and
		 X keysyms */
	      if (! keysym_obeys_caps_lock_p ((KeySym) XINT (keysym), d)
		  && lock_p
		  && !shift_p)
		modifiers &= (~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 & MOD_SHIFT)
		{
		  KeySym top, bot;
		  if (x_event->xkey.state & xd->ModeMask)
		    bot = XLookupKeysym (&x_event->xkey, 2),
		    top = XLookupKeysym (&x_event->xkey, 3);
		  else
		    bot = XLookupKeysym (&x_event->xkey, 0),
		    top = XLookupKeysym (&x_event->xkey, 1);
		  if (top && bot && top != bot)
		    modifiers &= ~MOD_SHIFT;
		}
	      emacs_event->event_type	   = key_press_event;
	      emacs_event->timestamp	   = x_event->xkey.time;
	      emacs_event->event.key.modifiers = modifiers;
	      emacs_event->event.key.keysym   = keysym;
	      break;
	    }
	  case ButtonPress:
	  case ButtonRelease:
	    {
	      struct frame *frame =
		x_window_to_frame (d, x_event->xbutton.window);
	      if (! frame)
		goto MAGIC;	/* not for us */
	      XSETFRAME (emacs_event->channel, frame);
	    }
	    
	    if (x_event->type == ButtonPress)
	      emacs_event->event_type    = button_press_event;
	    else emacs_event->event_type = button_release_event;
	    emacs_event->timestamp		    = x_event->xbutton.time;
	    emacs_event->event.button.modifiers = modifiers;
	    emacs_event->event.button.button    = x_event->xbutton.button;
	    emacs_event->event.button.x         = x_event->xbutton.x;
	    emacs_event->event.button.y         = x_event->xbutton.y;
	    break;
	  }
      }
      break;
      
    case MotionNotify:
      {
	Window w = x_event->xmotion.window;
	struct frame *frame = x_window_to_frame (d, w);
	XEvent event2;
	
	if (! frame)
	  goto MAGIC; /* 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 = *x_event;
	if (XQueryPointer (x_event->xmotion.display, event2.xmotion.window,
			   &event2.xmotion.root, &event2.xmotion.subwindow,
			   &event2.xmotion.x_root, &event2.xmotion.y_root,
			   &event2.xmotion.x, &event2.xmotion.y,
			   &event2.xmotion.state))
	  *x_event = event2;
	
	DEVICE_X_MOUSE_TIMESTAMP (d) = x_event->xmotion.time;
	
	XSETFRAME (emacs_event->channel, frame);
	emacs_event->event_type	  = pointer_motion_event;
	emacs_event->timestamp	  = x_event->xmotion.time;
	emacs_event->event.motion.x = x_event->xmotion.x;
	emacs_event->event.motion.y = x_event->xmotion.y;
	{
	  unsigned int modifiers = 0;
	  if (x_event->xmotion.state & ShiftMask)   modifiers |= MOD_SHIFT;
	  if (x_event->xmotion.state & ControlMask) modifiers |= MOD_CONTROL;
	  if (x_event->xmotion.state & xd->MetaMask)    modifiers |= MOD_META;
	  if (x_event->xmotion.state & xd->SuperMask)   modifiers |= MOD_SUPER;
	  if (x_event->xmotion.state & xd->HyperMask)   modifiers |= MOD_HYPER;
	  if (x_event->xmotion.state & xd->AltMask)     modifiers |= MOD_ALT;
	  /* Currently ignores Shift_Lock but probably shouldn't
	     (but it definitely should ignore Caps_Lock). */
	  emacs_event->event.motion.modifiers = modifiers;
	}
      }
      break;
      
    case ClientMessage:
#ifdef I18N4
      if (x_event->xclient.message_type == wc_atom)
	{
	  struct frame *frame = 0;
	  
	  frame = x_any_window_to_frame (d, x_event->xkey.window);
	  if (! frame)
	    frame = sel_frame;
	  
	  This is currently broken.  Should be a key event, not a
	    wchar_event.
	      XSETFRAME (emacs_event->channel, frame);
	  emacs_event->event_type       = wchar_event;
	  emacs_event->timestamp        = x_event->xclient.data.l[0];
	  emacs_event->event.wchar.data = x_event->xclient.data.l[1];
	  break;
	}
#endif
      /* Patch bogus TAKE_FOCUS messages from MWM; CurrentTime is passed as the
	 timestamp of the TAKE_FOCUS, which the ICCCM explicitly prohibits. */
      if (x_event->xclient.message_type == DEVICE_XATOM_WM_PROTOCOLS (d)
	  && x_event->xclient.data.l[0] == DEVICE_XATOM_WM_TAKE_FOCUS (d)
	  && x_event->xclient.data.l[1] == 0)
	{
	  x_event->xclient.data.l[1] = DEVICE_X_LAST_SERVER_TIMESTAMP (d);
	}
      goto MAGIC;
      
    default:
    MAGIC:
      emacs_event->event_type = magic_event;
      emacs_event->channel = Qnil; /* #### */
      memcpy ((char *) &emacs_event->event.magic.underlying_event,
	      (char *) x_event,
	      sizeof (XEvent));
      break;
    }
}

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

static void
handle_focus_event_1 (struct frame *f, int in_p)
{
#ifdef I18N4
  if (FRAME_X_INPUT_CONTEXT (f))
    {
      if (in_p)
	XSetICFocus (FRAME_X_INPUT_CONTEXT (f));
      else
	XUnsetICFocus (FRAME_X_INPUT_CONTEXT (f));
    }
#endif
  emacs_handle_focus_change (f, in_p);
}

void emacs_Xt_handle_focus_event (XEvent *event);
void
emacs_Xt_handle_focus_event (XEvent *event)
{
  /*
   * 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.
   */
  
  struct frame *f =
    x_any_window_to_frame (get_device_from_display (event->xany.display),
			   event->xfocus.window);
  if (!f)
    /* focus events are sometimes generated just before
       a frame is destroyed. */
    return;
  handle_focus_event_1 (f, event->xany.type == FocusIn);
}

static void
handle_map_event (XEvent *event)
{
  Lisp_Object frame = Qnil;
  struct frame *f =
    x_any_window_to_frame (get_device_from_display (event->xany.display),
			   event->xmap.window);

  if (!f)
    return;
  XSETFRAME (frame, f);
  if (event->xany.type == MapNotify)
    {
      FRAME_X_TOTALLY_VISIBLE_P (f) = 1;
      /* 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 window manager
	 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 (!f->visible && NILP (Fframe_iconified_p (frame)))
	{
	  f->visible = 1;
	  /* 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. */
	  MARK_FRAME_WINDOWS_STRUCTURE_CHANGED (f);
	  run_hook_with_args (Qmap_frame_hook, 1, frame);
#ifdef EPOCH
	  dispatch_epoch_event (event, Qx_map);
#endif
	}
    }
  else
    {
      FRAME_X_TOTALLY_VISIBLE_P (f) = 0;
      if (f->visible)
	{
	  f->visible = 0;
	  run_hook_with_args (Qunmap_frame_hook, 1, frame);
#ifdef EPOCH
	  dispatch_epoch_event (event, Qx_unmap);
#endif
	}
    }
}

static void
handle_client_message (XEvent *event)
{
  Display *display = event->xany.display;
  struct device *d = get_device_from_display (display);
  struct frame *f = x_any_window_to_frame (d, event->xclient.window);
  if (!f)
    return;
  if (event->xclient.message_type == DEVICE_XATOM_WM_PROTOCOLS (d) &&
      event->xclient.data.l[0] == DEVICE_XATOM_WM_DELETE_WINDOW (d))
    {
      Lisp_Object frm, dev;
      Lisp_Object next;
      
      XSETFRAME (frm, f);
      XSETDEVICE (dev, d);
      next = next_frame (frm, Qt);
      /* 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.
	 */
      /* #### Review this. */
      if (EQ (next, frm) || EQ (frm, Vdefault_minibuffer_frame))
	enqueue_misc_user_event (Qdelete_device, dev);
      else
	enqueue_misc_user_event (Qdelete_frame, frm);
    }
  else if (event->xclient.message_type == DEVICE_XATOM_WM_PROTOCOLS (d) &&
	   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
    }
#ifdef EPOCH
  dispatch_epoch_event (event, Qx_client_message);
#endif
}

static void
emacs_Xt_handle_magic_event (struct Lisp_Event *emacs_event)
{
  /* This function can GC */
  XEvent *event = (XEvent *) &emacs_event->event.magic.underlying_event;
  struct frame *f;
  struct device *d = XDEVICE (EVENT_DEVICE (emacs_event));

  switch (event->type)
    {
    case SelectionRequest:
      if (x_window_to_frame (d, event->xselectionrequest.owner))
	x_handle_selection_request (&event->xselectionrequest);
      break;
      
    case SelectionClear:
      if (x_window_to_frame (d, event->xselectionclear.window))
	x_handle_selection_clear (&event->xselectionclear);
      break;
      
    case SelectionNotify:
      if (x_window_to_frame (d, event->xselection.requestor))
	x_handle_selection_notify (&event->xselection);
      break;
      
    case PropertyNotify:
      if (x_window_to_frame (d, event->xproperty.window))
	{
	  x_handle_property_notify (&event->xproperty);
#ifdef EPOCH
	  dispatch_epoch_event (emacs_event, Qx_property_change);
#endif
	}
      break;
      
    case Expose:
      if ((f = x_window_to_frame (d, event->xexpose.window)))
	x_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. */
      if ((f = x_window_to_frame (d, event->xexpose.window)))
	x_redraw_exposed_area (f, event->xexpose.x, event->xexpose.y,
			       event->xexpose.width, event->xexpose.height);
      break;
      
    case MapNotify:
    case UnmapNotify:
      handle_map_event (event);
      break;
      
    case EnterNotify:
      if ((f = x_any_window_to_frame (d, event->xcrossing.window)) &&
	  (event->xcrossing.detail != NotifyInferior))
	{
	  Lisp_Object frame;
	  
	  XSETFRAME (frame, f);
	  /* FRAME_X_MOUSE_P (f) = 1; */
	  run_hook_with_args (Qmouse_enter_frame_hook, 1, frame);
	}
      break;
      
    case LeaveNotify:
      if ((f = x_any_window_to_frame (d, event->xcrossing.window)) &&
	  (event->xcrossing.detail != NotifyInferior))
	{
	  Lisp_Object frame;
	  
	  XSETFRAME (frame, f);
	  /* FRAME_X_MOUSE_P (f) = 0; */
	  run_hook_with_args (Qmouse_leave_frame_hook, 1, frame);
	}
      break;
      
    case FocusIn:
    case FocusOut:
#ifdef EXTERNAL_WIDGET
      if (! (f = x_any_window_to_frame (d, event->xfocus.window)))
	break;
      
      /* 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
      emacs_Xt_handle_focus_event (event);
      break;
      
    case ClientMessage:
      handle_client_message (event);
      break;
      
#if 0
      /* this is where we ought to be handling this event, but
	 we don't see it here. --ben */
    case MappingNotify:	/* The user has run xmodmap */
#endif    
      
    case VisibilityNotify: /* window visiblity has changed */
      if (! (f = x_any_window_to_frame (d, event->xvisibility.window)))
	break;
      if (event->xvisibility.state == VisibilityUnobscured)
	FRAME_X_TOTALLY_VISIBLE_P (f) = 1;
      else
	FRAME_X_TOTALLY_VISIBLE_P (f) = 0;
      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. */

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

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

/* called by XtAppNextEvent() */
static void
Xt_timeout_callback (XtPointer closure, XtIntervalId *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 (unsigned int milliseconds)
{
  struct Xt_timeout *timeout = Blocktype_alloc (the_Xt_timeout_blocktype);

  timeout->id = timeout_id_tick++;
  timeout->next = pending_timeouts;
  pending_timeouts = timeout;
  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;

  /* Find the timeout on the list of pending ones, if it's still there. */
  if (!pending_timeouts) return;
  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) return;
      timeout = t2->next;
      t2->next = t2->next->next;
    }

  /* At this point, we've found the thing on the list of pending timeouts,
     and removed it.
   */

  XtRemoveTimeOut (timeout->interval_id);
  Blocktype_free (the_Xt_timeout_blocktype, timeout);
}

static void
Xt_timeout_to_emacs_event (struct Lisp_Event *emacs_event)
{
  struct Xt_timeout *timeout = completed_timeouts;
  assert (timeout);
  completed_timeouts = completed_timeouts->next;
  emacs_event->event_type = timeout_event;
  emacs_event->timestamp  = 0; /* #### wrong!! */
  emacs_event->event.timeout.interval_id = timeout->id;
  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 = (Lisp_Object *)
    xmalloc (MAXDESC * sizeof (Lisp_Object));
  filedesc_to_what_closure = (struct what_is_ready_closure **)
    xmalloc (MAXDESC * sizeof (struct what_is_ready_closure *));

  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]))
    {
      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 *source, XtInputId *id)
{
  mark_what_as_being_ready ((struct what_is_ready_closure *) closure);
}

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 = (struct what_is_ready_closure *) xmalloc (sizeof (*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 (struct Lisp_Process *p)
{
  int infd, outfd;
  Lisp_Object process;

  get_process_file_descriptors (p, &infd, &outfd);
  XSETPROCESS (process, p);
  select_filedesc (infd, process);
}

static void
emacs_Xt_unselect_process (struct Lisp_Process *p)
{
  int infd, outfd;

  get_process_file_descriptors (p, &infd, &outfd);

  /* If the infd is < 0, it has already been deleted, and Xt will freak
     because its calls to select() will fail.
   */
  if (infd < 0)
    abort ();
  unselect_filedesc (infd);
}

/* 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 (struct Lisp_Process *p)
{
#if 0 /* #### */
  int i;
  int infd, outfd;
  get_process_file_descriptors (p, &infd, &outfd);
  /* if it still has fds, then it hasn't been killed yet. */
  assert (infd < 0);
  assert (outfd < 0);
  /* 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 (struct Lisp_Event *emacs_event)
{
  int i;
  Lisp_Object process;

  assert (process_events_occurred > 0);
  for (i = 0; i < MAXDESC; i++)
    {
      process = filedesc_with_input[i];
      if (PROCESSP (process))
	break;
    }
  assert (i < MAXDESC);
  filedesc_with_input[i] = Qnil;
  process_events_occurred--;
  emacs_event->event_type = process_event;
  emacs_event->timestamp  = 0; /* #### */
  emacs_event->event.process.process = process;
}

static void
emacs_Xt_select_device (struct device *d)
{
  Lisp_Object device;
  int infd;

  if (DEVICE_IS_X (d))
    return; /* X devices are automatically selected for when we
	       initialize them in Xt */
  XSETDEVICE (device, d);
  infd = DEVICE_INFD (d);
  select_filedesc (infd, device);
  FD_SET (infd, &tty_device_mask);
}

static void
emacs_Xt_unselect_device (struct device *d)
{
  int infd;

  if (DEVICE_IS_X (d))
    return;
  infd = DEVICE_INFD (d);

  /* If the infd is < 0, it has already been deleted, and Xt will freak
     because its calls to select() will fail.
   */
  if (infd < 0)
    abort ();
  unselect_filedesc (infd);
  FD_CLR (infd, &tty_device_mask);
}

/* 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 (struct Lisp_Event *emacs_event)
{
  int i;

  assert (tty_events_occurred > 0);
  if (maybe_read_quit_event (emacs_event))
    return 1;
  for (i = 0; i < MAXDESC; i++)
    {
      Lisp_Object device = filedesc_with_input[i];
      if (DEVICEP (device))
	{
	  assert (tty_events_occurred > 0);
	  tty_events_occurred--;
	  filedesc_with_input[i] = Qnil;
	  if (read_event_from_tty_or_stream_desc (emacs_event,
						  XDEVICE (device), i))
	    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)
{
  struct frame *f;
  Widget w;
  stderr_out ("   window: 0x%x", (int) window);
  w = XtWindowToWidget (display, window);
  if (w)
    stderr_out (" %s", w->core.widget_class->core_class.class_name);
  f = x_any_window_to_frame (get_device_from_display (display), window);
  if (f)
    stderr_out (" \"%s\"", string_ext_data (XSTRING (f->name)));
  stderr_out ("\n");
}

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

  sprintf (buf, "%s%s", x_event_name (event->xany.type),
	   event->xany.send_event ? " (send)" : "");
  stderr_out ("%-30s", buf);
  switch (event->xany.type)
    {
    case FocusIn:
    case FocusOut:
      describe_event_window (event->xfocus.window, event->xfocus.display);
      stderr_out ("     mode: %s\n",
		  (event->xfocus.mode == NotifyNormal ? "Normal"
		   :(event->xfocus.mode == NotifyGrab ? "Grab"
		     :(event->xfocus.mode == NotifyUngrab ? "Ungrab"
		       :(event->xfocus.mode == NotifyWhileGrabbed ?
			 "WhileGrabbed" : "?")))));
      stderr_out ("   detail: %s\n",
		  (event->xfocus.detail == NotifyAncestor ? "Ancestor"
		   :(event->xfocus.detail == NotifyVirtual ? "Virtual"
		     :(event->xfocus.detail == NotifyInferior ? "Inferior"
		       :(event->xfocus.detail == NotifyNonlinear ? "Nonlinear"
			 :(event->xfocus.detail == NotifyNonlinearVirtual ?
			   "NonlinearVirtual"
			   :(event->xfocus.detail == NotifyPointer ? "Pointer"
			     :(event->xfocus.detail == NotifyPointerRoot ?
			       "PointerRoot"
			       :(event->xfocus.detail == NotifyDetailNone ?
				 "DetailNone" : "?")))))))));
      break;
      
    case KeyPress:
      {
	Lisp_Object keysym;
	describe_event_window (event->xkey.window, event->xkey.display);
	stderr_out ("   subwindow: %ld\n", event->xkey.subwindow);
	stderr_out ("    state: ");
	if (event->xkey.state & ShiftMask)   stderr_out ("Shift ");
	if (event->xkey.state & LockMask)    stderr_out ("Lock ");
	if (event->xkey.state & ControlMask) stderr_out ("Control ");
	if (event->xkey.state & Mod1Mask)    stderr_out ("Mod1 ");
	if (event->xkey.state & Mod2Mask)    stderr_out ("Mod2 ");
	if (event->xkey.state & Mod3Mask)    stderr_out ("Mod3 ");
	if (event->xkey.state & Mod4Mask)    stderr_out ("Mod4 ");
	if (event->xkey.state & Mod5Mask)    stderr_out ("Mod5 ");
#if 0 /* Apparently these don't exist? */
	if (event->xkey.state & MetaMask)    stderr_out ("Meta ");
	if (event->xkey.state & SuperMask)   stderr_out ("Super ");
	if (event->xkey.state & HyperMask)   stderr_out ("Hyper ");
	if (event->xkey.state & AltMask)     stderr_out ("Alt ");
	if (event->xkey.state & ModeMask)    stderr_out ("Mode_switch ");
#endif
	
	if (! event->xkey.state)
	  stderr_out ("vanilla\n");
	else
	  stderr_out ("\n");
	if (x_key_is_modifier_p (event->xkey.keycode, d))
	  stderr_out ("   Modifier key");
	stderr_out ("  keycode: 0x%x\n", event->xkey.keycode);
	keysym = x_to_emacs_keysym (event, 0);
	if (INTP (keysym) && XINT (keysym) > 32 && XINT (keysym) <= 255)
	  stderr_out ("   keysym: %c\n", XINT (keysym));
	else
	  stderr_out ("   keysym: %s\n", string_data (XSYMBOL (keysym)->name));
      }
      break;

    case Expose:
      if (x_debug_events > 1)
	{
	  describe_event_window (event->xexpose.window,
				 event->xexpose.display);
	  stderr_out ("   region: %d %d %d %d\n", event->xexpose.x,
		      event->xexpose.y, event->xexpose.width,
		      event->xexpose.height);
	  stderr_out ("    count: %d\n", event->xexpose.count);
	}
      else
	stderr_out ("\n");
      break;

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

    case EnterNotify:
    case LeaveNotify:
      if (x_debug_events > 1)
	{
	  describe_event_window (event->xcrossing.window,
				 event->xcrossing.display);
#if 0
	  stderr_out (" subwindow: 0x%x\n", event->xcrossing.subwindow);
	  stderr_out ("      pos: %d %d\n", event->xcrossing.x,
		      event->xcrossing.y);
	  stderr_out (" root pos: %d %d\n",
		      event->xcrossing.x_root, event->xcrossing.y_root);
#endif
	  stderr_out ("     mode: %s\n",
		      (event->xcrossing.mode == NotifyNormal ? "Normal"
		       :(event->xcrossing.mode == NotifyGrab ? "Grab"
			 :(event->xcrossing.mode == NotifyUngrab ? "Ungrab"
			   :(event->xcrossing.mode == NotifyWhileGrabbed ?
			     "WhileGrabbed" : "?")))));
	  stderr_out ("   detail: %s\n",
		      (event->xcrossing.detail == NotifyAncestor ? "Ancestor"
		       :(event->xcrossing.detail == NotifyVirtual ? "Virtual"
			 :(event->xcrossing.detail == NotifyInferior ?
			   "Inferior"
			   :(event->xcrossing.detail == NotifyNonlinear ?
			     "Nonlinear"
			     :(event->xcrossing.detail ==
			       NotifyNonlinearVirtual ?
			       "NonlinearVirtual"
			       :(event->xcrossing.detail == NotifyPointer ?
				 "Pointer"
				 :(event->xcrossing.detail ==
				   NotifyPointerRoot ?
				   "PointerRoot"
				   :(event->xcrossing.detail ==
				     NotifyDetailNone ?
				     "DetailNone" : "?")))))))));
	  stderr_out ("    focus: %d\n", event->xcrossing.focus);
#if 0
	  stderr_out ("    state: 0x%x\n", event->xcrossing.state);
#endif
	}
      else
	stderr_out ("\n");
      break;

    case ConfigureNotify:
      if (x_debug_events > 1)
	{
	  describe_event_window (event->xconfigure.window,
				 event->xconfigure.display);
	  stderr_out ("    above: 0x%lx\n", event->xconfigure.above);
	  stderr_out ("     size: %d %d %d %d\n", event->xconfigure.x,
		      event->xconfigure.y,
		      event->xconfigure.width, event->xconfigure.height);
	  stderr_out ("  redirect: %d\n", event->xconfigure.override_redirect);
	}
      else
	stderr_out ("\n");
      break;

    case VisibilityNotify:
      if (x_debug_events > 1)
	{
	  describe_event_window (event->xvisibility.window,
				 event->xvisibility.display);
	  stderr_out ("    state: %s\n",
		      (event->xvisibility.state == VisibilityUnobscured ?
		       "Unobscured"
		       :(event->xvisibility.state ==
			 VisibilityPartiallyObscured ?
			 "PartiallyObscured"
			 :(event->xvisibility.state ==
			   VisibilityFullyObscured ?
			   "FullyObscured" : "?"))));
	}
      else
	stderr_out ("\n");
      break;

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

  fflush (stdout);
}
#endif /* include describe_event definition */

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

static Lisp_Object dispatch_event_queue;
static struct Lisp_Event *dispatch_event_queue_tail;

static void
enqueue_Xt_dispatch_event (Lisp_Object event)
{
  enqueue_event (event, &dispatch_event_queue, &dispatch_event_queue_tail);
}

Lisp_Object
dequeue_Xt_dispatch_event (void)
{
  return dequeue_event (&dispatch_event_queue, &dispatch_event_queue_tail);
}

/* 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 function, Lisp_Object object)
{
  Lisp_Object event;

  event = Fallocate_event ();

  XEVENT (event)->event_type = misc_user_event;
  XEVENT (event)->event.eval.function = function;
  XEVENT (event)->event.eval.object = object;

  enqueue_Xt_dispatch_event (event);
}  

static void
emacs_Xt_next_event (struct Lisp_Event *emacs_event)
{
 we_didnt_get_an_event:

  while (NILP (dispatch_event_queue) &&
	 !completed_timeouts && 
	 !process_events_occurred &&
	 !tty_events_occurred)
    {
      /* 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 rest;

	  /* 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. */
	  for (rest = Vdevice_list ; !NILP (rest) ; rest = XCDR (rest))
	    {
	      struct device *d;
	      d = XDEVICE (XCAR (rest));

	      if (DEVICE_IS_X (d) && DEVICE_X_DISPLAY (d))
		/* emacs may be exiting */
		XFlush (DEVICE_X_DISPLAY (d));
	    }
	  XtAppProcessEvent (Xt_app_con, XtIMAll);
	}
    }

  if (!NILP (dispatch_event_queue))
    {
      Lisp_Object event, event2;
      XSETEVENT (event2, emacs_event);
      event = dequeue_Xt_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 (process_events_occurred) */
    Xt_process_to_emacs_event (emacs_event);

  /* #### No I18N4 stuff here.  There appears to be no obvious place
     to call XFilterEvent().  I don't really understand that junk,
     anyway. */
}

void
emacs_Xt_event_handler (Widget wid /* unused */,
			XtPointer closure /* unused */,
			XEvent *event,
			Boolean *continue_to_dispatch /* unused */)
{
  Lisp_Object emacs_event = Fallocate_event ();

#ifdef DEBUG_XEMACS
  if (x_debug_events > 0)
    describe_event (event);
#endif

  x_event_to_emacs_event (event, XEVENT (emacs_event));
  enqueue_Xt_dispatch_event (emacs_event);
}


/************************************************************************/
/*                      input pending / C-g checking                    */
/************************************************************************/

static Bool
quit_char_predicate (Display *display, XEvent *event, XPointer data)
{
  struct device *d = get_device_from_display (display);
  struct x_device *xd = DEVICE_X_DATA (d);
  char c, quit_char;
  Bool *critical = (Bool *) data;
  Lisp_Object keysym;

  if (critical) *critical = False;
  if (event->type != KeyPress) return 0;
  if (! x_any_window_to_frame (d, event->xany.window)) return 0;
  if (event->xkey.state
      & (xd->MetaMask | xd->HyperMask | xd->SuperMask | xd->AltMask))
    return 0;

  /* This duplicates some code that exists elsewhere, but it's relatively
     fast and doesn't cons.
   */
  keysym = x_to_emacs_keysym (event, 1);
  if (NILP (keysym)) return 0;
  if (INTP (keysym))
    c = XINT (keysym);
  /* Highly doubtful that these are the quit character, but... */
  else if (EQ (keysym, QKbackspace))	c = '\b';
  else if (EQ (keysym, QKtab))		c = '\t';
  else if (EQ (keysym, QKlinefeed))	c = '\n';
  else if (EQ (keysym, QKreturn))	c = '\r';
  else if (EQ (keysym, QKescape))	c = 27;
  else if (EQ (keysym, QKspace))	c = ' ';
  else if (EQ (keysym, QKdelete))	c = 127;
  else return 0;

  if (event->xkey.state & xd->MetaMask)     c |= 0x80;
  if ((event->xkey.state & ControlMask) && !(c >= 'A' && c <= 'Z'))
    c &= 0x1F;			/* unshifted control characters */
  quit_char = DEVICE_QUIT_CHAR (d);
  if (c == quit_char)
    return True;
  /* If we've got Control-Shift-G instead of Control-G, that means
     we have a critical_quit.  Caps_Lock is its own modifier, so it
     won't cause ^G to act differently than before. */
  if (event->xkey.state & ControlMask)  c &= 0x1F;
  if (c == quit_char)
    {
      if (critical) *critical = True;
      return True;
    }
  return False;
}

/* This scans the X input queue for a KeyPress event that matches the
   quit character, and sets Vquit_flag.  This is called from the
   QUIT macro to determine whether we should quit.

   In a SIGIO world, this won't be called unless a SIGIO has happened
   since the last time we checked.

   In a non-SIGIO world, this is called from emacs_Xt_event_pending_p
   (which is called from input_pending_p).
 */
static void
x_check_for_quit_char (Display *display)
{
  XEvent event;
  int queued;
  Bool critical_quit = False;
  XEventsQueued (display, QueuedAfterReading);
  queued = XCheckIfEvent (display, &event,
			  quit_char_predicate,
			  (XtPointer)&critical_quit);
  if (queued)
    {
      Vquit_flag = (critical_quit ? Qcritical : Qt);
      /* don't put the event back onto the queue.  Those functions that
	 wanted to read a ^G directly have arranged to do this. */
    }
}

static void
check_for_tty_quit_char (struct device *d)
{
  SELECT_TYPE temp_mask;
  int infd = DEVICE_INFD (d);
  char quit_char = DEVICE_QUIT_CHAR (d);

  FD_ZERO (&temp_mask);
  FD_SET (infd, &temp_mask);

  while (1)
    {
      Lisp_Object event;
      Emchar the_char;

      if (!poll_fds_for_input (temp_mask))
	return;

      event = Fallocate_event ();
      if (!read_event_from_tty_or_stream_desc (XEVENT (event), d, infd))
	/* EOF, or something ... */
	return;
      /* #### bogus.  quit-char should be allowed to be any sort
	 of event. */
      the_char = event_to_character (XEVENT (event), 1, 0, 0);
      if (the_char >= 0 && the_char == quit_char)
	{
	  Vquit_flag = Qt;
	  /* do not queue the C-g.  See above. */
	  return;
	}

      /* queue the read event to be read for real later. */
      enqueue_Xt_dispatch_event (event);
    }
}

static void
emacs_Xt_quit_p (void)
{
  Lisp_Object rest;
  DEVICE_LOOP (rest)
    {
      struct device *d;
      d = XDEVICE (XCAR (rest));

      if (!d->input_enabled)
	continue;

      if (DEVICE_IS_X (d) && DEVICE_X_DISPLAY (d)) /* emacs may be exiting */
	x_check_for_quit_char (DEVICE_X_DISPLAY (d));
      else if (DEVICE_IS_TTY (d))
	check_for_tty_quit_char (d);
    }
}

static void
drain_X_queue (void)
{
  while (XtAppPending (Xt_app_con) & XtIMXEvent)
    XtAppProcessEvent (Xt_app_con, XtIMXEvent);
}

static int
emacs_Xt_event_pending_p (int user_p)
{
  int tick_count_val;

  /* If `user_p' is false, then this function returns whether there are any
     X, timeout, or fd events pending (that is, whether emacs_Xt_next_event()
     would return immediately without blocking).

     if `user_p' is true, then this function returns whether there are any
     *user generated* events available (that is, whether there are keyboard
     or mouse-click events ready to be read).  This also implies that
     emacs_Xt_next_event() would not block.

     In a non-SIGIO world, this also checks whether the user has typed ^G,
     since this is a convenient place to do so.  We don't need to do this
     in a SIGIO world, since input causes an interrupt.
   */

#if 0
  /* I don't think there's any point to this and it will nullify
     the speed gains achieved by the sigio_happened checking below.
     Its only advantage is that it may possibly make C-g response
     a bit faster.  The C-g will be noticed within a second, anyway,
     even without this. */
#ifndef SIGIO
  /* First check for C-g if necessary */
  emacs_Xt_quit_p ();
#endif
#endif

  /* This function used to simply check whether there were any X
     events (or is user_p was 1, it iterated over all the pending
     X events using XCheckIfEvent(), looking for keystrokes and
     button events).  That worked in the old cheesoid event loop,
     which didn't go through XtAppDispatchEvent(), but it doesn't
     work any more -- X events may not result in anything.  For
     example, a button press in a blank part of the menubar appears
     as an X event but will not result in any Emacs events (a
     button press that activates the menubar results in an Emacs
     event through the stop_next_event mechanism).

     The only accurate way of determining whether these X events
     translate into Emacs events is to go ahead and dispatch them
     until there's something on the dispatch queue. */

  if (!NILP (dispatch_event_queue))
    {
      /* See if there are any user events already on the queue. */
      struct Lisp_Event *event;

      if (!user_p)
        return 1;

      for (event = XEVENT (dispatch_event_queue); event;
	   event = event_next (event))
	if (command_event_p (event))
	  return 1;
    }

  /* See if there's any TTY input available */
  if (poll_fds_for_input (tty_device_mask))
    return 1;

  if (!user_p)
    {
      /* If not user_p and there are any timer or file-desc events
	 pending, we know there will be an event so we're through. */
      XtInputMask pending_value = XtAppPending (Xt_app_con);
      if ((pending_value & XtIMTimer) ||
	  (pending_value & XtIMAlternateInput))
	return 1;
    }

  /* XtAppPending() can be super-slow, esp. over a network connection.
     Quantify results have indicated that in some cases the
     call to detect_input_pending() completely dominates the
     running time of redisplay().  Fortunately, in a SIGIO world
     we can more quickly determine whether there are any X events:
     if an event has happened since the last time we checked, then
     a SIGIO will have happened.  On a machine with broken SIGIO,
     we'll still be in an OK state -- the sigio_happened flag
     will get set at least once a second, so we'll be no more than
     one second behind reality. (In general it's OK if we
     erroneously report no input pending when input is actually
     pending() -- preemption is just a bit less efficient, that's
     all.  It's bad bad bad if you err the other way -- you've
     promised that `next-event' won't block but it actually will,
     and some action might get delayed until the next time you
     hit a key.)
     */

  /* sigio_tick_count is volatile so try to avoid race conditions
     by using a temporary variable */
  tick_count_val = sigio_tick_count;
  if (last_sigio_tick_count != tick_count_val)
    {
      struct Lisp_Event *event;

      last_sigio_tick_count = tick_count_val;

      /* We need to drain the entire queue now -- if we only
         drain part of it, we may later on end up with events
         actually pending but detect_input_pending() returning
         false because there wasn't another SIGIO. */
      drain_X_queue ();

      for (event = dispatch_event_queue_tail; event;
	   event = event_next (event))
	if (!user_p || command_event_p (event))
	  return 1;
    }

  return 0;
}

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

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, x_fallback_resources);
  
  /* In xselect.c */
  x_selection_timeout = (XtAppGetSelectionTimeout (Xt_app_con) / 1000);
  XSetErrorHandler (x_error_handler);
  XSetIOErrorHandler (x_IO_error_handler);
}

void
syms_of_event_Xt (void)
{
  dispatch_event_queue = Qnil;
  staticpro (&dispatch_event_queue);

  init_what_input_once ();

  Xt_event_stream =
    (struct event_stream *) xmalloc (sizeof (struct event_stream));
  Xt_event_stream->event_pending_p 	= emacs_Xt_event_pending_p;
  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->add_timeout_cb 	= emacs_Xt_add_timeout;
  Xt_event_stream->remove_timeout_cb 	= emacs_Xt_remove_timeout;
  Xt_event_stream->select_device_cb 	= emacs_Xt_select_device;
  Xt_event_stream->unselect_device_cb 	= emacs_Xt_unselect_device;
  Xt_event_stream->select_process_cb 	= emacs_Xt_select_process;
  Xt_event_stream->unselect_process_cb 	= emacs_Xt_unselect_process;
  Xt_event_stream->quit_p_cb		= emacs_Xt_quit_p;

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

#ifdef DEBUG_XEMACS
  DEFVAR_INT ("x-debug-events", &x_debug_events,
    "If non-zero, display debug information about events that XEmacs sees.\n\
Information is displayed on stderr.  Currently defined values are:\n\
\n\
1 == non-verbose output\n\
2 == verbose output");
  x_debug_events = 0;
#endif

  the_Xt_timeout_blocktype = Blocktype_new (struct Xt_timeout_blocktype);

  FD_ZERO (&tty_device_mask);

  last_sigio_tick_count = 0;
}
