# include "Ximage.h"

/* # define IgnoreMask (long) (ClientMessage | ButtonReleaseMask) */
# define IgnoreMask (long) (~(StructureNotifyMask | SubstructureNotifyMask | ExposureMask | KeyPressMask | ButtonPressMask | PointerMotionMask))

int LastEvent (Display *display, int type, XEvent *event) {

  int found;

  found = FALSE;
  while (XCheckTypedEvent (display, type, event)) {
    found = TRUE;
  }
  return (found);
}

int EventLoop (Graphic *graphic, Layout *layout) {
  
  XEvent          event;
  int             status;
  Display        *display;
  
  if (USE_XWINDOW) Refresh (graphic, layout, 1);

  status = TRUE;
  while (status) {
    
    if (!CheckPipe (graphic, layout))
      return (FALSE);
    
    if (!USE_XWINDOW) {
      usleep (50000);
      continue;
    }

    if (XEventsQueued (graphic[0].display, QueuedAfterFlush) < 1) {
      usleep (10000);
      continue;
    }

    display = graphic[0].display;

    /* grab the last entry for these events */
    if (LastEvent (display, ConfigureNotify, &event)) Reconfig (graphic, layout, &event);
    if (LastEvent (display, CirculateNotify, &event)) Reconfig (graphic, layout, &event);
    if (LastEvent (display, Expose,          &event)) Refresh (graphic, layout, 1);
    if (LastEvent (display, MotionNotify,    &event)) UpdatePointer (graphic, layout, (XMotionEvent *) &event);
    if (LastEvent (display, ButtonPress,     &event)) InterpretPresses (graphic, layout, (XButtonEvent *) &event);
    if (LastEvent (display, KeyPress,        &event)) InterpretKeys (graphic, layout, &event);

    if (LastEvent (display, MappingNotify,   &event)) XRefreshKeyboardMapping ((XMappingEvent *) &event);

    /* drop and ignore the following StructureNotifyMask events */
    LastEvent (display, GravityNotify, &event);
    LastEvent (display, ReparentNotify, &event);
    LastEvent (display, MapNotify, &event);
    LastEvent (display, UnmapNotify, &event);

    /* remove those events we will ignore */
    while (XCheckMaskEvent (display, IgnoreMask, &event)) continue;

    /* events to remove which have no mask component */
    while (XCheckTypedEvent (display, MappingNotify, &event)) continue;
    while (XCheckTypedEvent (display, ClientMessage, &event)) continue;
    while (XCheckTypedEvent (display, SelectionClear, &event)) continue;
    while (XCheckTypedEvent (display, SelectionNotify, &event)) continue;
    while (XCheckTypedEvent (display, SelectionRequest, &event)) continue;
  }
  return (status);
}

# if (0)
/* WARNING: this is defined because the HP UX installation i have does not
seem to know this structure, though it should.  Clearly a need for autoconf.. */
struct Ktimeval {
  unsigned long tv_sec;         /* seconds */
  long          tv_usec;        /* and microseconds */
};
# endif

