missing a header
[mikachu/openbox.git] / openbox / event.c
1 /* -*- indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*-
2
3    event.c for the Openbox window manager
4    Copyright (c) 2006        Mikael Magnusson
5    Copyright (c) 2003-2007   Dana Jansens
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    See the COPYING file for a copy of the GNU General Public License.
18 */
19
20 #include "event.h"
21 #include "debug.h"
22 #include "window.h"
23 #include "openbox.h"
24 #include "dock.h"
25 #include "actions.h"
26 #include "client.h"
27 #include "config.h"
28 #include "screen.h"
29 #include "frame.h"
30 #include "grab.h"
31 #include "menu.h"
32 #include "prompt.h"
33 #include "menuframe.h"
34 #include "keyboard.h"
35 #include "mouse.h"
36 #include "hooks.h"
37 #include "focus.h"
38 #include "focus_cycle.h"
39 #include "moveresize.h"
40 #include "group.h"
41 #include "stacking.h"
42 #include "ping.h"
43 #include "obt/display.h"
44 #include "obt/prop.h"
45 #include "obt/keyboard.h"
46
47 #include <X11/Xlib.h>
48 #include <X11/Xatom.h>
49 #include <glib.h>
50
51 #ifdef HAVE_SYS_SELECT_H
52 #  include <sys/select.h>
53 #endif
54 #ifdef HAVE_SIGNAL_H
55 #  include <signal.h>
56 #endif
57 #ifdef HAVE_UNISTD_H
58 #  include <unistd.h> /* for usleep() */
59 #endif
60 #ifdef XKB
61 #  include <X11/XKBlib.h>
62 #endif
63
64 #ifdef USE_SM
65 #include <X11/ICE/ICElib.h>
66 #endif
67
68 typedef struct
69 {
70     gboolean ignored;
71 } ObEventData;
72
73 typedef struct
74 {
75     ObClient *client;
76     Time time;
77     gulong serial;
78 } ObFocusDelayData;
79
80 typedef struct
81 {
82     gulong start; /* inclusive */
83     gulong end;   /* inclusive */
84 } ObSerialRange;
85
86 static void event_process(const XEvent *e, gpointer data);
87 static void event_handle_root(XEvent *e);
88 static gboolean event_handle_menu_input(XEvent *e);
89 static void event_handle_menu(ObMenuFrame *frame, XEvent *e);
90 static gboolean event_handle_prompt(ObPrompt *p, XEvent *e);
91 static void event_handle_dock(ObDock *s, XEvent *e);
92 static void event_handle_dockapp(ObDockApp *app, XEvent *e);
93 static void event_handle_client(ObClient *c, XEvent *e);
94 static void event_handle_user_input(ObClient *client, XEvent *e);
95 static gboolean is_enter_focus_event_ignored(gulong serial);
96 static void event_ignore_enter_range(gulong start, gulong end);
97
98 static void focus_delay_dest(gpointer data);
99 static gboolean focus_delay_cmp(gconstpointer d1, gconstpointer d2);
100 static gboolean focus_delay_func(gpointer data);
101 static void focus_delay_client_dest(ObClient *client, gpointer data);
102
103 Time event_curtime = CurrentTime;
104 Time event_last_user_time = CurrentTime;
105 /*! The serial of the current X event */
106
107 static gulong event_curserial;
108 static gboolean focus_left_screen = FALSE;
109 /*! A list of ObSerialRanges which are to be ignored for mouse enter events */
110 static GSList *ignore_serials = NULL;
111
112 #ifdef USE_SM
113 static void ice_handler(gint fd, gpointer conn)
114 {
115     Bool b;
116     IceProcessMessages(conn, NULL, &b);
117 }
118
119 static void ice_watch(IceConn conn, IcePointer data, Bool opening,
120                       IcePointer *watch_data)
121 {
122     static gint fd = -1;
123
124     if (opening) {
125         fd = IceConnectionNumber(conn);
126         obt_main_loop_fd_add(ob_main_loop, fd, ice_handler, conn, NULL);
127     } else {
128         obt_main_loop_fd_remove(ob_main_loop, fd);
129         fd = -1;
130     }
131 }
132 #endif
133
134 void event_startup(gboolean reconfig)
135 {
136     if (reconfig) return;
137
138     obt_main_loop_x_add(ob_main_loop, event_process, NULL, NULL);
139
140 #ifdef USE_SM
141     IceAddConnectionWatch(ice_watch, NULL);
142 #endif
143
144     client_add_destroy_notify(focus_delay_client_dest, NULL);
145 }
146
147 void event_shutdown(gboolean reconfig)
148 {
149     if (reconfig) return;
150
151 #ifdef USE_SM
152     IceRemoveConnectionWatch(ice_watch, NULL);
153 #endif
154
155     client_remove_destroy_notify(focus_delay_client_dest);
156 }
157
158 static Window event_get_window(XEvent *e)
159 {
160     Window window;
161
162     /* pick a window */
163     switch (e->type) {
164     case SelectionClear:
165         window = obt_root(ob_screen);
166         break;
167     case CreateNotify:
168         window = e->xcreatewindow.window;
169         break;
170     case MapRequest:
171         window = e->xmaprequest.window;
172         break;
173     case MapNotify:
174         window = e->xmap.window;
175         break;
176     case UnmapNotify:
177         window = e->xunmap.window;
178         break;
179     case DestroyNotify:
180         window = e->xdestroywindow.window;
181         break;
182     case ConfigureRequest:
183         window = e->xconfigurerequest.window;
184         break;
185     case ConfigureNotify:
186         window = e->xconfigure.window;
187         break;
188     default:
189 #ifdef XKB
190         if (obt_display_extension_xkb &&
191             e->type == obt_display_extension_xkb_basep)
192         {
193             switch (((XkbAnyEvent*)e)->xkb_type) {
194             case XkbBellNotify:
195                 window = ((XkbBellNotifyEvent*)e)->window;
196             default:
197                 window = None;
198             }
199         } else
200 #endif
201 #ifdef SYNC
202         if (obt_display_extension_sync &&
203             e->type == obt_display_extension_sync_basep + XSyncAlarmNotify)
204         {
205             window = None;
206         } else
207 #endif
208             window = e->xany.window;
209     }
210     return window;
211 }
212
213 static void event_set_curtime(XEvent *e)
214 {
215     Time t = CurrentTime;
216
217     /* grab the lasttime and hack up the state */
218     switch (e->type) {
219     case ButtonPress:
220     case ButtonRelease:
221         t = e->xbutton.time;
222         break;
223     case KeyPress:
224         t = e->xkey.time;
225         break;
226     case KeyRelease:
227         t = e->xkey.time;
228         break;
229     case MotionNotify:
230         t = e->xmotion.time;
231         break;
232     case PropertyNotify:
233         t = e->xproperty.time;
234         break;
235     case EnterNotify:
236     case LeaveNotify:
237         t = e->xcrossing.time;
238         break;
239     default:
240 #ifdef SYNC
241         if (obt_display_extension_sync &&
242             e->type == obt_display_extension_sync_basep + XSyncAlarmNotify)
243         {
244             t = ((XSyncAlarmNotifyEvent*)e)->time;
245         }
246 #endif
247         /* if more event types are anticipated, get their timestamp
248            explicitly */
249         break;
250     }
251
252     /* watch that if we get an event earlier than the last specified user_time,
253        which can happen if the clock goes backwards, we erase the last
254        specified user_time */
255     if (t && event_last_user_time && event_time_after(event_last_user_time, t))
256         event_last_user_time = CurrentTime;
257
258     event_curtime = t;
259 }
260
261 static void event_hack_mods(XEvent *e)
262 {
263 #ifdef XKB
264     XkbStateRec xkb_state;
265 #endif
266
267     switch (e->type) {
268     case ButtonPress:
269     case ButtonRelease:
270         e->xbutton.state = obt_keyboard_only_modmasks(e->xbutton.state);
271         break;
272     case KeyPress:
273         e->xkey.state = obt_keyboard_only_modmasks(e->xkey.state);
274         break;
275     case KeyRelease:
276 #ifdef XKB
277         /* If XKB is present, then the modifiers are all strange from its
278            magic.  Our X core protocol stuff won't work, so we use this to
279            find what the modifier state is instead. */
280         if (XkbGetState(obt_display, XkbUseCoreKbd, &xkb_state) == Success)
281             e->xkey.state =
282                 obt_keyboard_only_modmasks(xkb_state.compat_state);
283         else
284 #endif
285         {
286             e->xkey.state = obt_keyboard_only_modmasks(e->xkey.state);
287             /* remove from the state the mask of the modifier key being
288                released, if it is a modifier key being released that is */
289             e->xkey.state &= ~obt_keyboard_keycode_to_modmask(e->xkey.keycode);
290         }
291         break;
292     case MotionNotify:
293         e->xmotion.state = obt_keyboard_only_modmasks(e->xmotion.state);
294         /* compress events */
295         {
296             XEvent ce;
297             while (XCheckTypedWindowEvent(obt_display, e->xmotion.window,
298                                           e->type, &ce)) {
299                 e->xmotion.x = ce.xmotion.x;
300                 e->xmotion.y = ce.xmotion.y;
301                 e->xmotion.x_root = ce.xmotion.x_root;
302                 e->xmotion.y_root = ce.xmotion.y_root;
303             }
304         }
305         break;
306     }
307 }
308
309 static gboolean wanted_focusevent(XEvent *e, gboolean in_client_only)
310 {
311     gint mode = e->xfocus.mode;
312     gint detail = e->xfocus.detail;
313     Window win = e->xany.window;
314
315     if (e->type == FocusIn) {
316         /* These are ones we never want.. */
317
318         /* This means focus was given by a keyboard/mouse grab. */
319         if (mode == NotifyGrab)
320             return FALSE;
321         /* This means focus was given back from a keyboard/mouse grab. */
322         if (mode == NotifyUngrab)
323             return FALSE;
324
325         /* These are the ones we want.. */
326
327         if (win == obt_root(ob_screen)) {
328             /* If looking for a focus in on a client, then always return
329                FALSE for focus in's to the root window */
330             if (in_client_only)
331                 return FALSE;
332             /* This means focus reverted off of a client */
333             else if (detail == NotifyPointerRoot ||
334                      detail == NotifyDetailNone ||
335                      detail == NotifyInferior ||
336                      /* This means focus got here from another screen */
337                      detail == NotifyNonlinear)
338                 return TRUE;
339             else
340                 return FALSE;
341         }
342
343         /* It was on a client, was it a valid one?
344            It's possible to get a FocusIn event for a client that was managed
345            but has disappeared.
346         */
347         if (in_client_only) {
348             ObWindow *w = window_find(e->xfocus.window);
349             if (!w || !WINDOW_IS_CLIENT(w))
350                 return FALSE;
351         }
352         else {
353             /* This means focus reverted to parent from the client (this
354                happens often during iconify animation) */
355             if (detail == NotifyInferior)
356                 return TRUE;
357         }
358
359         /* This means focus moved from the root window to a client */
360         if (detail == NotifyVirtual)
361             return TRUE;
362         /* This means focus moved from one client to another */
363         if (detail == NotifyNonlinearVirtual)
364             return TRUE;
365
366         /* Otherwise.. */
367         return FALSE;
368     } else {
369         g_assert(e->type == FocusOut);
370
371         /* These are ones we never want.. */
372
373         /* This means focus was taken by a keyboard/mouse grab. */
374         if (mode == NotifyGrab)
375             return FALSE;
376         /* This means focus was grabbed on a window and it was released. */
377         if (mode == NotifyUngrab)
378             return FALSE;
379
380         /* Focus left the root window revertedto state */
381         if (win == obt_root(ob_screen))
382             return FALSE;
383
384         /* These are the ones we want.. */
385
386         /* This means focus moved from a client to the root window */
387         if (detail == NotifyVirtual)
388             return TRUE;
389         /* This means focus moved from one client to another */
390         if (detail == NotifyNonlinearVirtual)
391             return TRUE;
392
393         /* Otherwise.. */
394         return FALSE;
395     }
396 }
397
398 static Bool event_look_for_focusin(Display *d, XEvent *e, XPointer arg)
399 {
400     return e->type == FocusIn && wanted_focusevent(e, FALSE);
401 }
402
403 static Bool event_look_for_focusin_client(Display *d, XEvent *e, XPointer arg)
404 {
405     return e->type == FocusIn && wanted_focusevent(e, TRUE);
406 }
407
408 static void print_focusevent(XEvent *e)
409 {
410     gint mode = e->xfocus.mode;
411     gint detail = e->xfocus.detail;
412     Window win = e->xany.window;
413     const gchar *modestr, *detailstr;
414
415     switch (mode) {
416     case NotifyNormal:       modestr="NotifyNormal";       break;
417     case NotifyGrab:         modestr="NotifyGrab";         break;
418     case NotifyUngrab:       modestr="NotifyUngrab";       break;
419     case NotifyWhileGrabbed: modestr="NotifyWhileGrabbed"; break;
420     }
421     switch (detail) {
422     case NotifyAncestor:    detailstr="NotifyAncestor";    break;
423     case NotifyVirtual:     detailstr="NotifyVirtual";     break;
424     case NotifyInferior:    detailstr="NotifyInferior";    break;
425     case NotifyNonlinear:   detailstr="NotifyNonlinear";   break;
426     case NotifyNonlinearVirtual: detailstr="NotifyNonlinearVirtual"; break;
427     case NotifyPointer:     detailstr="NotifyPointer";     break;
428     case NotifyPointerRoot: detailstr="NotifyPointerRoot"; break;
429     case NotifyDetailNone:  detailstr="NotifyDetailNone";  break;
430     }
431
432     if (mode == NotifyGrab || mode == NotifyUngrab)
433         return;
434
435     g_assert(modestr);
436     g_assert(detailstr);
437     ob_debug_type(OB_DEBUG_FOCUS, "Focus%s 0x%x mode=%s detail=%s",
438                   (e->xfocus.type == FocusIn ? "In" : "Out"),
439                   win,
440                   modestr, detailstr);
441
442 }
443
444 static gboolean event_ignore(XEvent *e, ObClient *client)
445 {
446     switch(e->type) {
447     case FocusIn:
448         print_focusevent(e);
449         if (!wanted_focusevent(e, FALSE))
450             return TRUE;
451         break;
452     case FocusOut:
453         print_focusevent(e);
454         if (!wanted_focusevent(e, FALSE))
455             return TRUE;
456         break;
457     }
458     return FALSE;
459 }
460
461 static void event_process(const XEvent *ec, gpointer data)
462 {
463     XEvent ee, *e;
464     ObEventData *ed = data;
465
466     Window window;
467     ObClient *client = NULL;
468     ObDock *dock = NULL;
469     ObDockApp *dockapp = NULL;
470     ObWindow *obwin = NULL;
471     ObMenuFrame *menu = NULL;
472     ObPrompt *prompt = NULL;
473
474     /* make a copy we can mangle */
475     ee = *ec;
476     e = &ee;
477
478     window = event_get_window(e);
479     if (window == obt_root(ob_screen))
480         /* don't do any lookups, waste of cpu */;
481     else if ((obwin = window_find(window))) {
482         switch (obwin->type) {
483         case OB_WINDOW_CLASS_DOCK:
484             dock = WINDOW_AS_DOCK(obwin);
485             break;
486         case OB_WINDOW_CLASS_CLIENT:
487             client = WINDOW_AS_CLIENT(obwin);
488             /* events on clients can be events on prompt windows too */
489             prompt = client->prompt;
490             break;
491         case OB_WINDOW_CLASS_MENUFRAME:
492             menu = WINDOW_AS_MENUFRAME(obwin);
493             break;
494         case OB_WINDOW_CLASS_INTERNAL:
495             /* we don't do anything with events directly on these windows */
496             break;
497         case OB_WINDOW_CLASS_PROMPT:
498             prompt = WINDOW_AS_PROMPT(obwin);
499             break;
500         }
501     }
502     else
503         dockapp = dock_find_dockapp(window);
504
505     event_set_curtime(e);
506     event_curserial = e->xany.serial;
507     event_hack_mods(e);
508     if (event_ignore(e, client)) {
509         if (ed)
510             ed->ignored = TRUE;
511         return;
512     } else if (ed)
513             ed->ignored = FALSE;
514
515     /* deal with it in the kernel */
516
517     if (e->type == FocusIn) {
518         if (client &&
519             e->xfocus.detail == NotifyInferior)
520         {
521             ob_debug_type(OB_DEBUG_FOCUS,
522                           "Focus went to the frame window");
523
524             focus_left_screen = FALSE;
525
526             focus_fallback(FALSE, config_focus_under_mouse, TRUE, TRUE);
527
528             /* We don't get a FocusOut for this case, because it's just moving
529                from our Inferior up to us. This happens when iconifying a
530                window with RevertToParent focus */
531             frame_adjust_focus(client->frame, FALSE);
532             /* focus_set_client(NULL) has already been called */
533         }
534         else if (e->xfocus.detail == NotifyPointerRoot ||
535                  e->xfocus.detail == NotifyDetailNone ||
536                  e->xfocus.detail == NotifyInferior ||
537                  e->xfocus.detail == NotifyNonlinear)
538         {
539             XEvent ce;
540
541             ob_debug_type(OB_DEBUG_FOCUS,
542                           "Focus went to root or pointer root/none");
543
544             if (e->xfocus.detail == NotifyInferior ||
545                 e->xfocus.detail == NotifyNonlinear)
546             {
547                 focus_left_screen = FALSE;
548             }
549
550             /* If another FocusIn is in the queue then don't fallback yet. This
551                fixes the fun case of:
552                window map -> send focusin
553                window unmap -> get focusout
554                window map -> send focusin
555                get first focus out -> fall back to something (new window
556                  hasn't received focus yet, so something else) -> send focusin
557                which means the "something else" is the last thing to get a
558                focusin sent to it, so the new window doesn't end up with focus.
559
560                But if the other focus in is something like PointerRoot then we
561                still want to fall back.
562             */
563             if (XCheckIfEvent(obt_display, &ce, event_look_for_focusin_client,
564                               NULL))
565             {
566                 XPutBackEvent(obt_display, &ce);
567                 ob_debug_type(OB_DEBUG_FOCUS,
568                               "  but another FocusIn is coming");
569             } else {
570                 /* Focus has been reverted.
571
572                    FocusOut events come after UnmapNotify, so we don't need to
573                    worry about focusing an invalid window
574                 */
575
576                 if (!focus_left_screen)
577                     focus_fallback(FALSE, config_focus_under_mouse,
578                                    TRUE, TRUE);
579             }
580         }
581         else if (!client)
582         {
583             ob_debug_type(OB_DEBUG_FOCUS,
584                           "Focus went to a window that is already gone");
585
586             /* If you send focus to a window and then it disappears, you can
587                get the FocusIn for it, after it is unmanaged.
588                Just wait for the next FocusOut/FocusIn pair, but make note that
589                the window that was focused no longer is. */
590             focus_set_client(NULL);
591         }
592         else if (client != focus_client) {
593             focus_left_screen = FALSE;
594             frame_adjust_focus(client->frame, TRUE);
595             focus_set_client(client);
596             client_calc_layer(client);
597             client_bring_helper_windows(client);
598         }
599     } else if (e->type == FocusOut) {
600         XEvent ce;
601
602         /* Look for the followup FocusIn */
603         if (!XCheckIfEvent(obt_display, &ce, event_look_for_focusin, NULL)) {
604             /* There is no FocusIn, this means focus went to a window that
605                is not being managed, or a window on another screen. */
606             Window win, root;
607             gint i;
608             guint u;
609             obt_display_ignore_errors(TRUE);
610             if (XGetInputFocus(obt_display, &win, &i) &&
611                 XGetGeometry(obt_display, win, &root, &i,&i,&u,&u,&u,&u) &&
612                 root != obt_root(ob_screen))
613             {
614                 ob_debug_type(OB_DEBUG_FOCUS,
615                               "Focus went to another screen !");
616                 focus_left_screen = TRUE;
617             }
618             else
619                 ob_debug_type(OB_DEBUG_FOCUS,
620                               "Focus went to a black hole !");
621             obt_display_ignore_errors(FALSE);
622             /* nothing is focused */
623             focus_set_client(NULL);
624         } else {
625             /* Focus moved, so process the FocusIn event */
626             ObEventData ed = { .ignored = FALSE };
627             event_process(&ce, &ed);
628             if (ed.ignored) {
629                 /* The FocusIn was ignored, this means it was on a window
630                    that isn't a client. */
631                 ob_debug_type(OB_DEBUG_FOCUS,
632                               "Focus went to an unmanaged window 0x%x !",
633                               ce.xfocus.window);
634                 focus_fallback(TRUE, config_focus_under_mouse, TRUE, TRUE);
635             }
636         }
637
638         if (client && client != focus_client) {
639             frame_adjust_focus(client->frame, FALSE);
640             /* focus_set_client(NULL) has already been called in this
641                section or by focus_fallback */
642         }
643     }
644     else if (client)
645         event_handle_client(client, e);
646     else if (dockapp)
647         event_handle_dockapp(dockapp, e);
648     else if (dock)
649         event_handle_dock(dock, e);
650     else if (menu)
651         event_handle_menu(menu, e);
652     else if (window == obt_root(ob_screen))
653         event_handle_root(e);
654     else if (e->type == MapRequest)
655         window_manage(window);
656     else if (e->type == MappingNotify) {
657         /* keyboard layout changes for modifier mapping changes. reload the
658            modifier map, and rebind all the key bindings as appropriate */
659         ob_debug("Kepboard map changed. Reloading keyboard bindings.");
660         obt_keyboard_reload();
661         keyboard_rebind();
662     }
663     else if (e->type == ClientMessage) {
664         /* This is for _NET_WM_REQUEST_FRAME_EXTENTS messages. They come for
665            windows that are not managed yet. */
666         if (e->xclient.message_type ==
667             OBT_PROP_ATOM(NET_REQUEST_FRAME_EXTENTS))
668         {
669             /* Pretend to manage the client, getting information used to
670                determine its decorations */
671             ObClient *c = client_fake_manage(e->xclient.window);
672             gulong vals[4];
673
674             /* set the frame extents on the window */
675             vals[0] = c->frame->size.left;
676             vals[1] = c->frame->size.right;
677             vals[2] = c->frame->size.top;
678             vals[3] = c->frame->size.bottom;
679             OBT_PROP_SETA32(e->xclient.window, NET_FRAME_EXTENTS,
680                             CARDINAL, vals, 4);
681
682             /* Free the pretend client */
683             client_fake_unmanage(c);
684         }
685     }
686     else if (e->type == ConfigureRequest) {
687         /* unhandled configure requests must be used to configure the
688            window directly */
689         XWindowChanges xwc;
690
691         xwc.x = e->xconfigurerequest.x;
692         xwc.y = e->xconfigurerequest.y;
693         xwc.width = e->xconfigurerequest.width;
694         xwc.height = e->xconfigurerequest.height;
695         xwc.border_width = e->xconfigurerequest.border_width;
696         xwc.sibling = e->xconfigurerequest.above;
697         xwc.stack_mode = e->xconfigurerequest.detail;
698
699         /* we are not to be held responsible if someone sends us an
700            invalid request! */
701         obt_display_ignore_errors(TRUE);
702         XConfigureWindow(obt_display, window,
703                          e->xconfigurerequest.value_mask, &xwc);
704         obt_display_ignore_errors(FALSE);
705     }
706 #ifdef SYNC
707     else if (obt_display_extension_sync &&
708              e->type == obt_display_extension_sync_basep + XSyncAlarmNotify)
709     {
710         XSyncAlarmNotifyEvent *se = (XSyncAlarmNotifyEvent*)e;
711         if (se->alarm == moveresize_alarm && moveresize_in_progress)
712             moveresize_event(e);
713     }
714 #endif
715
716     if (prompt && event_handle_prompt(prompt, e))
717         ;
718     else if (e->type == ButtonPress || e->type == ButtonRelease) {
719         /* If the button press was on some non-root window, or was physically
720            on the root window, then process it */
721         if (window != obt_root(ob_screen) ||
722             e->xbutton.subwindow == None)
723         {
724             event_handle_user_input(client, e);
725         }
726         /* Otherwise only process it if it was physically on an openbox
727            internal window */
728         else {
729             ObWindow *w;
730
731             if ((w = window_find(e->xbutton.subwindow)) &&
732                 WINDOW_IS_INTERNAL(w))
733             {
734                 event_handle_user_input(client, e);
735             }
736         }
737     }
738     else if (e->type == KeyPress || e->type == KeyRelease ||
739              e->type == MotionNotify)
740         event_handle_user_input(client, e);
741
742     XFlush(obt_display);
743
744     /* run all the hooks at once */
745     hooks_run_queue();
746
747     /* if something happens and it's not from an XEvent, then we don't know
748        the time */
749     event_curtime = CurrentTime;
750     event_curserial = 0;
751 }
752
753 static void event_handle_root(XEvent *e)
754 {
755     Atom msgtype;
756
757     switch(e->type) {
758     case SelectionClear:
759         ob_debug("Another WM has requested to replace us. Exiting.");
760         ob_exit_replace();
761         break;
762
763     case ClientMessage:
764         if (e->xclient.format != 32) break;
765
766         msgtype = e->xclient.message_type;
767         if (msgtype == OBT_PROP_ATOM(NET_CURRENT_DESKTOP)) {
768             guint d = e->xclient.data.l[0];
769             if (d < screen_num_desktops) {
770                 event_curtime = e->xclient.data.l[1];
771                 if (event_curtime == 0)
772                     ob_debug_type(OB_DEBUG_APP_BUGS,
773                                   "_NET_CURRENT_DESKTOP message is missing "
774                                   "a timestamp");
775                 screen_set_desktop(d, TRUE);
776             }
777         } else if (msgtype == OBT_PROP_ATOM(NET_NUMBER_OF_DESKTOPS)) {
778             guint d = e->xclient.data.l[0];
779             if (d > 0 && d <= 1000)
780                 screen_set_num_desktops(d);
781         } else if (msgtype == OBT_PROP_ATOM(NET_SHOWING_DESKTOP)) {
782             screen_show_desktop(e->xclient.data.l[0] != 0, NULL);
783         } else if (msgtype == OBT_PROP_ATOM(OB_CONTROL)) {
784             ob_debug("OB_CONTROL: %d", e->xclient.data.l[0]);
785             if (e->xclient.data.l[0] == 1)
786                 ob_reconfigure();
787             else if (e->xclient.data.l[0] == 2)
788                 ob_restart();
789             else if (e->xclient.data.l[0] == 3)
790                 ob_exit(0);
791         } else if (msgtype == OBT_PROP_ATOM(WM_PROTOCOLS)) {
792             if ((Atom)e->xclient.data.l[0] == OBT_PROP_ATOM(NET_WM_PING))
793                 ping_got_pong(e->xclient.data.l[1]);
794         }
795         break;
796     case PropertyNotify:
797         if (e->xproperty.atom == OBT_PROP_ATOM(NET_DESKTOP_NAMES)) {
798             ob_debug("UPDATE DESKTOP NAMES");
799             screen_update_desktop_names();
800         }
801         else if (e->xproperty.atom == OBT_PROP_ATOM(NET_DESKTOP_LAYOUT))
802             screen_update_layout();
803         break;
804     case ConfigureNotify:
805 #ifdef XRANDR
806         XRRUpdateConfiguration(e);
807 #endif
808         screen_resize();
809         break;
810     default:
811         ;
812     }
813 }
814
815 void event_enter_client(ObClient *client)
816 {
817     g_assert(config_focus_follow);
818
819     if (is_enter_focus_event_ignored(event_curserial)) {
820         ob_debug_type(OB_DEBUG_FOCUS, "Ignoring enter event with serial %lu\n"
821                       "on client 0x%x", event_curserial, client->window);
822         return;
823     }
824
825     if (client_enter_focusable(client) && client_can_focus(client)) {
826         if (config_focus_delay) {
827             ObFocusDelayData *data;
828
829             obt_main_loop_timeout_remove(ob_main_loop, focus_delay_func);
830
831             data = g_new(ObFocusDelayData, 1);
832             data->client = client;
833             data->time = event_curtime;
834             data->serial = event_curserial;
835
836             obt_main_loop_timeout_add(ob_main_loop,
837                                       config_focus_delay * 1000,
838                                       focus_delay_func,
839                                       data, focus_delay_cmp, focus_delay_dest);
840         } else {
841             ObFocusDelayData data;
842             data.client = client;
843             data.time = event_curtime;
844             data.serial = event_curserial;
845             focus_delay_func(&data);
846         }
847     }
848 }
849
850 static gboolean *context_to_button(ObFrame *f, ObFrameContext con, gboolean press)
851 {
852     if (press) {
853         switch (con) {
854         case OB_FRAME_CONTEXT_MAXIMIZE:
855             return &f->max_press;
856         case OB_FRAME_CONTEXT_CLOSE:
857             return &f->close_press;
858         case OB_FRAME_CONTEXT_ICONIFY:
859             return &f->iconify_press;
860         case OB_FRAME_CONTEXT_ALLDESKTOPS:
861             return &f->desk_press;
862         case OB_FRAME_CONTEXT_SHADE:
863             return &f->shade_press;
864         default:
865             return NULL;
866         }
867     } else {
868         switch (con) {
869         case OB_FRAME_CONTEXT_MAXIMIZE:
870             return &f->max_hover;
871         case OB_FRAME_CONTEXT_CLOSE:
872             return &f->close_hover;
873         case OB_FRAME_CONTEXT_ICONIFY:
874             return &f->iconify_hover;
875         case OB_FRAME_CONTEXT_ALLDESKTOPS:
876             return &f->desk_hover;
877         case OB_FRAME_CONTEXT_SHADE:
878             return &f->shade_hover;
879         default:
880             return NULL;
881         }
882     }
883 }
884
885 static void compress_client_message_event(XEvent *e, XEvent *ce, Window window,
886                                           Atom msgtype)
887 {
888     /* compress changes into a single change */
889     while (XCheckTypedWindowEvent(obt_display, window, e->type, ce)) {
890         /* XXX: it would be nice to compress ALL messages of a
891            type, not just messages in a row without other
892            message types between. */
893         if (ce->xclient.message_type != msgtype) {
894             XPutBackEvent(obt_display, ce);
895             break;
896         }
897         e->xclient = ce->xclient;
898     }
899 }
900
901 static void event_handle_client(ObClient *client, XEvent *e)
902 {
903     XEvent ce;
904     Atom msgtype;
905     ObFrameContext con;
906     gboolean *but;
907     static gint px = -1, py = -1;
908     static guint pb = 0;
909     static ObFrameContext pcon = OB_FRAME_CONTEXT_NONE;
910
911     switch (e->type) {
912     case ButtonPress:
913         /* save where the press occured for the first button pressed */
914         if (!pb) {
915             pb = e->xbutton.button;
916             px = e->xbutton.x;
917             py = e->xbutton.y;
918
919             pcon = frame_context(client, e->xbutton.window, px, py);
920             pcon = mouse_button_frame_context(pcon, e->xbutton.button,
921                                               e->xbutton.state);
922         }
923     case ButtonRelease:
924         /* Wheel buttons don't draw because they are an instant click, so it
925            is a waste of resources to go drawing it.
926            if the user is doing an interactive thing, or has a menu open then
927            the mouse is grabbed (possibly) and if we get these events we don't
928            want to deal with them
929         */
930         if (!(e->xbutton.button == 4 || e->xbutton.button == 5) &&
931             !grab_on_keyboard())
932         {
933             /* use where the press occured */
934             con = frame_context(client, e->xbutton.window, px, py);
935             con = mouse_button_frame_context(con, e->xbutton.button,
936                                              e->xbutton.state);
937
938             /* button presses on CLIENT_CONTEXTs are not accompanied by a
939                release because they are Replayed to the client */
940             if ((e->type == ButtonRelease || CLIENT_CONTEXT(con, client)) &&
941                 e->xbutton.button == pb)
942                 pb = 0, px = py = -1, pcon = OB_FRAME_CONTEXT_NONE;
943
944             but = context_to_button(client->frame, con, TRUE);
945             if (but) {
946                 *but = (e->type == ButtonPress);
947                 frame_adjust_state(client->frame);
948             }
949         }
950         break;
951     case MotionNotify:
952         /* when there is a grab on the pointer, we won't get enter/leave
953            notifies, but we still get motion events */
954         if (grab_on_pointer()) break;
955
956         con = frame_context(client, e->xmotion.window,
957                             e->xmotion.x, e->xmotion.y);
958         switch (con) {
959         case OB_FRAME_CONTEXT_TITLEBAR:
960         case OB_FRAME_CONTEXT_TLCORNER:
961         case OB_FRAME_CONTEXT_TRCORNER:
962             /* we've left the button area inside the titlebar */
963             if (client->frame->max_hover || client->frame->desk_hover ||
964                 client->frame->shade_hover || client->frame->iconify_hover ||
965                 client->frame->close_hover)
966             {
967                 client->frame->max_hover =
968                     client->frame->desk_hover =
969                     client->frame->shade_hover =
970                     client->frame->iconify_hover =
971                     client->frame->close_hover = FALSE;
972                 frame_adjust_state(client->frame);
973             }
974             break;
975         default:
976             but = context_to_button(client->frame, con, FALSE);
977             if (but && !*but && !pb) {
978                 *but = TRUE;
979                 frame_adjust_state(client->frame);
980             }
981             break;
982         }
983         break;
984     case LeaveNotify:
985         con = frame_context(client, e->xcrossing.window,
986                             e->xcrossing.x, e->xcrossing.y);
987         switch (con) {
988         case OB_FRAME_CONTEXT_TITLEBAR:
989         case OB_FRAME_CONTEXT_TLCORNER:
990         case OB_FRAME_CONTEXT_TRCORNER:
991             /* we've left the button area inside the titlebar */
992             client->frame->max_hover =
993                 client->frame->desk_hover =
994                 client->frame->shade_hover =
995                 client->frame->iconify_hover =
996                 client->frame->close_hover = FALSE;
997             if (e->xcrossing.mode == NotifyGrab) {
998                 client->frame->max_press =
999                     client->frame->desk_press =
1000                     client->frame->shade_press =
1001                     client->frame->iconify_press =
1002                     client->frame->close_press = FALSE;
1003             }
1004             break;
1005         case OB_FRAME_CONTEXT_FRAME:
1006             /* When the mouse leaves an animating window, don't use the
1007                corresponding enter events. Pretend like the animating window
1008                doesn't even exist..! */
1009             if (frame_iconify_animating(client->frame))
1010                 event_end_ignore_all_enters(event_start_ignore_all_enters());
1011
1012             ob_debug_type(OB_DEBUG_FOCUS,
1013                           "%sNotify mode %d detail %d on %lx",
1014                           (e->type == EnterNotify ? "Enter" : "Leave"),
1015                           e->xcrossing.mode,
1016                           e->xcrossing.detail, (client?client->window:0));
1017             if (grab_on_keyboard())
1018                 break;
1019             if (config_focus_follow && config_focus_delay &&
1020                 /* leave inferior events can happen when the mouse goes onto
1021                    the window's border and then into the window before the
1022                    delay is up */
1023                 e->xcrossing.detail != NotifyInferior)
1024             {
1025                 obt_main_loop_timeout_remove_data(ob_main_loop,
1026                                                   focus_delay_func,
1027                                                   client, FALSE);
1028             }
1029             break;
1030         default:
1031             but = context_to_button(client->frame, con, FALSE);
1032             if (but) {
1033                 *but = FALSE;
1034                 if (e->xcrossing.mode == NotifyGrab) {
1035                     but = context_to_button(client->frame, con, TRUE);
1036                     *but = FALSE;
1037                 }
1038                 frame_adjust_state(client->frame);
1039             }
1040             break;
1041         }
1042         break;
1043     case EnterNotify:
1044     {
1045         con = frame_context(client, e->xcrossing.window,
1046                             e->xcrossing.x, e->xcrossing.y);
1047         switch (con) {
1048         case OB_FRAME_CONTEXT_FRAME:
1049             if (grab_on_keyboard())
1050                 break;
1051             if (e->xcrossing.mode == NotifyGrab ||
1052                 e->xcrossing.mode == NotifyUngrab ||
1053                 /*ignore enters when we're already in the window */
1054                 e->xcrossing.detail == NotifyInferior)
1055             {
1056                 ob_debug_type(OB_DEBUG_FOCUS,
1057                               "%sNotify mode %d detail %d serial %lu on %lx "
1058                               "IGNORED",
1059                               (e->type == EnterNotify ? "Enter" : "Leave"),
1060                               e->xcrossing.mode,
1061                               e->xcrossing.detail,
1062                               e->xcrossing.serial,
1063                               client?client->window:0);
1064             }
1065             else {
1066                 ob_debug_type(OB_DEBUG_FOCUS,
1067                               "%sNotify mode %d detail %d serial %lu on %lx, "
1068                               "focusing window",
1069                               (e->type == EnterNotify ? "Enter" : "Leave"),
1070                               e->xcrossing.mode,
1071                               e->xcrossing.detail,
1072                               e->xcrossing.serial,
1073                               (client?client->window:0));
1074                 if (config_focus_follow)
1075                     event_enter_client(client);
1076             }
1077             break;
1078         default:
1079             but = context_to_button(client->frame, con, FALSE);
1080             if (but) {
1081                 *but = TRUE;
1082                 if (e->xcrossing.mode == NotifyUngrab) {
1083                     but = context_to_button(client->frame, con, TRUE);
1084                     *but = (con == pcon);
1085                 }
1086                 frame_adjust_state(client->frame);
1087             }
1088             break;
1089         }
1090         break;
1091     }
1092     case ConfigureRequest:
1093     {
1094         /* dont compress these unless you're going to watch for property
1095            notifies in between (these can change what the configure would
1096            do to the window).
1097            also you can't compress stacking events
1098         */
1099
1100         gint x, y, w, h;
1101         gboolean move = FALSE;
1102         gboolean resize = FALSE;
1103
1104         /* get the current area */
1105         RECT_TO_DIMS(client->area, x, y, w, h);
1106
1107         ob_debug("ConfigureRequest for \"%s\" desktop %d wmstate %d "
1108                  "visible %d",
1109                  client->title,
1110                  screen_desktop, client->wmstate, client->frame->visible);
1111         ob_debug("                     x %d y %d w %d h %d b %d",
1112                  x, y, w, h, client->border_width);
1113
1114         if (e->xconfigurerequest.value_mask & CWBorderWidth)
1115             if (client->border_width != e->xconfigurerequest.border_width) {
1116                 client->border_width = e->xconfigurerequest.border_width;
1117
1118                 /* if the border width is changing then that is the same
1119                    as requesting a resize, but we don't actually change
1120                    the client's border, so it will change their root
1121                    coordinates (since they include the border width) and
1122                    we need to a notify then */
1123                 move = TRUE;
1124             }
1125
1126
1127         if (e->xconfigurerequest.value_mask & CWStackMode) {
1128             ObClient *sibling = NULL;
1129             gulong ignore_start;
1130             gboolean ok = TRUE;
1131
1132             /* get the sibling */
1133             if (e->xconfigurerequest.value_mask & CWSibling) {
1134                 ObWindow *win;
1135                 win = window_find(e->xconfigurerequest.above);
1136                 if (win && WINDOW_IS_CLIENT(win) &&
1137                     WINDOW_AS_CLIENT(win) != client)
1138                 {
1139                     sibling = WINDOW_AS_CLIENT(win);
1140                 }
1141                 else
1142                     /* an invalid sibling was specified so don't restack at
1143                        all, it won't make sense no matter what we do */
1144                     ok = FALSE;
1145             }
1146
1147             if (ok) {
1148                 if (!config_focus_under_mouse)
1149                     ignore_start = event_start_ignore_all_enters();
1150                 stacking_restack_request(client, sibling,
1151                                          e->xconfigurerequest.detail);
1152                 if (!config_focus_under_mouse)
1153                     event_end_ignore_all_enters(ignore_start);
1154             }
1155
1156             /* a stacking change moves the window without resizing */
1157             move = TRUE;
1158         }
1159
1160         if ((e->xconfigurerequest.value_mask & CWX) ||
1161             (e->xconfigurerequest.value_mask & CWY) ||
1162             (e->xconfigurerequest.value_mask & CWWidth) ||
1163             (e->xconfigurerequest.value_mask & CWHeight))
1164         {
1165             /* don't allow clients to move shaded windows (fvwm does this)
1166             */
1167             if (e->xconfigurerequest.value_mask & CWX) {
1168                 if (!client->shaded)
1169                     x = e->xconfigurerequest.x;
1170                 move = TRUE;
1171             }
1172             if (e->xconfigurerequest.value_mask & CWY) {
1173                 if (!client->shaded)
1174                     y = e->xconfigurerequest.y;
1175                 move = TRUE;
1176             }
1177
1178             if (e->xconfigurerequest.value_mask & CWWidth) {
1179                 w = e->xconfigurerequest.width;
1180                 resize = TRUE;
1181             }
1182             if (e->xconfigurerequest.value_mask & CWHeight) {
1183                 h = e->xconfigurerequest.height;
1184                 resize = TRUE;
1185             }
1186         }
1187
1188         ob_debug("ConfigureRequest x(%d) %d y(%d) %d w(%d) %d h(%d) %d "
1189                  "move %d resize %d",
1190                  e->xconfigurerequest.value_mask & CWX, x,
1191                  e->xconfigurerequest.value_mask & CWY, y,
1192                  e->xconfigurerequest.value_mask & CWWidth, w,
1193                  e->xconfigurerequest.value_mask & CWHeight, h,
1194                  move, resize);
1195
1196         /* check for broken apps moving to their root position
1197
1198            XXX remove this some day...that would be nice. right now all
1199            kde apps do this when they try activate themselves on another
1200            desktop. eg. open amarok window on desktop 1, switch to desktop
1201            2, click amarok tray icon. it will move by its decoration size.
1202         */
1203         if (x != client->area.x &&
1204             x == (client->frame->area.x + client->frame->size.left -
1205                   (gint)client->border_width) &&
1206             y != client->area.y &&
1207             y == (client->frame->area.y + client->frame->size.top -
1208                   (gint)client->border_width) &&
1209             w == client->area.width &&
1210             h == client->area.height)
1211         {
1212             ob_debug_type(OB_DEBUG_APP_BUGS,
1213                           "Application %s is trying to move via "
1214                           "ConfigureRequest to it's root window position "
1215                           "but it is not using StaticGravity",
1216                           client->title);
1217             /* don't move it */
1218             x = client->area.x;
1219             y = client->area.y;
1220
1221             /* they still requested a move, so don't change whether a
1222                notify is sent or not */
1223         }
1224
1225         {
1226             gint lw, lh;
1227
1228             client_try_configure(client, &x, &y, &w, &h, &lw, &lh, FALSE);
1229
1230             /* if x was not given, then use gravity to figure out the new
1231                x.  the reference point should not be moved */
1232             if ((e->xconfigurerequest.value_mask & CWWidth &&
1233                  !(e->xconfigurerequest.value_mask & CWX)))
1234                 client_gravity_resize_w(client, &x, client->area.width, w);
1235             /* same for y */
1236             if ((e->xconfigurerequest.value_mask & CWHeight &&
1237                  !(e->xconfigurerequest.value_mask & CWY)))
1238                 client_gravity_resize_h(client, &y, client->area.height,h);
1239
1240             client_find_onscreen(client, &x, &y, w, h, FALSE);
1241
1242             ob_debug("Granting ConfigureRequest x %d y %d w %d h %d",
1243                      x, y, w, h);
1244             client_configure(client, x, y, w, h, FALSE, TRUE, TRUE);
1245         }
1246         break;
1247     }
1248     case UnmapNotify:
1249         ob_debug("UnmapNotify for window 0x%x eventwin 0x%x sendevent %d "
1250                  "ignores left %d",
1251                  client->window, e->xunmap.event, e->xunmap.from_configure,
1252                  client->ignore_unmaps);
1253         if (client->ignore_unmaps) {
1254             client->ignore_unmaps--;
1255             break;
1256         }
1257         client_unmanage(client);
1258         break;
1259     case DestroyNotify:
1260         ob_debug("DestroyNotify for window 0x%x", client->window);
1261         client_unmanage(client);
1262         break;
1263     case ReparentNotify:
1264         /* this is when the client is first taken captive in the frame */
1265         if (e->xreparent.parent == client->frame->window) break;
1266
1267         /*
1268           This event is quite rare and is usually handled in unmapHandler.
1269           However, if the window is unmapped when the reparent event occurs,
1270           the window manager never sees it because an unmap event is not sent
1271           to an already unmapped window.
1272         */
1273
1274         /* we don't want the reparent event, put it back on the stack for the
1275            X server to deal with after we unmanage the window */
1276         XPutBackEvent(obt_display, e);
1277
1278         ob_debug("ReparentNotify for window 0x%x", client->window);
1279         client_unmanage(client);
1280         break;
1281     case MapRequest:
1282         ob_debug("MapRequest for 0x%lx", client->window);
1283         if (!client->iconic) break; /* this normally doesn't happen, but if it
1284                                        does, we don't want it!
1285                                        it can happen now when the window is on
1286                                        another desktop, but we still don't
1287                                        want it! */
1288         client_activate(client, FALSE, TRUE, TRUE, TRUE);
1289         break;
1290     case ClientMessage:
1291         /* validate cuz we query stuff off the client here */
1292         if (!client_validate(client)) break;
1293
1294         if (e->xclient.format != 32) return;
1295
1296         msgtype = e->xclient.message_type;
1297         if (msgtype == OBT_PROP_ATOM(WM_CHANGE_STATE)) {
1298             compress_client_message_event(e, &ce, client->window, msgtype);
1299             client_set_wm_state(client, e->xclient.data.l[0]);
1300         } else if (msgtype == OBT_PROP_ATOM(NET_WM_DESKTOP)) {
1301             compress_client_message_event(e, &ce, client->window, msgtype);
1302             if ((unsigned)e->xclient.data.l[0] < screen_num_desktops ||
1303                 (unsigned)e->xclient.data.l[0] == DESKTOP_ALL)
1304                 client_set_desktop(client, (unsigned)e->xclient.data.l[0],
1305                                    FALSE, FALSE);
1306         } else if (msgtype == OBT_PROP_ATOM(NET_WM_STATE)) {
1307             gulong ignore_start;
1308
1309             /* can't compress these */
1310             ob_debug("net_wm_state %s %ld %ld for 0x%lx",
1311                      (e->xclient.data.l[0] == 0 ? "Remove" :
1312                       e->xclient.data.l[0] == 1 ? "Add" :
1313                       e->xclient.data.l[0] == 2 ? "Toggle" : "INVALID"),
1314                      e->xclient.data.l[1], e->xclient.data.l[2],
1315                      client->window);
1316
1317             /* ignore enter events caused by these like ob actions do */
1318             if (!config_focus_under_mouse)
1319                 ignore_start = event_start_ignore_all_enters();
1320             client_set_state(client, e->xclient.data.l[0],
1321                              e->xclient.data.l[1], e->xclient.data.l[2]);
1322             if (!config_focus_under_mouse)
1323                 event_end_ignore_all_enters(ignore_start);
1324         } else if (msgtype == OBT_PROP_ATOM(NET_CLOSE_WINDOW)) {
1325             ob_debug("net_close_window for 0x%lx", client->window);
1326             client_close(client);
1327         } else if (msgtype == OBT_PROP_ATOM(NET_ACTIVE_WINDOW)) {
1328             ob_debug("net_active_window for 0x%lx source=%s",
1329                      client->window,
1330                      (e->xclient.data.l[0] == 0 ? "unknown" :
1331                       (e->xclient.data.l[0] == 1 ? "application" :
1332                        (e->xclient.data.l[0] == 2 ? "user" : "INVALID"))));
1333             /* XXX make use of data.l[2] !? */
1334             if (e->xclient.data.l[0] == 1 || e->xclient.data.l[0] == 2) {
1335                 /* don't use the user's timestamp for client_focus, cuz if it's
1336                    an old broken timestamp (happens all the time) then focus
1337                    won't move even though we're trying to move it
1338                   event_curtime = e->xclient.data.l[1];*/
1339                 if (e->xclient.data.l[1] == 0)
1340                     ob_debug_type(OB_DEBUG_APP_BUGS,
1341                                   "_NET_ACTIVE_WINDOW message for window %s is"
1342                                   " missing a timestamp", client->title);
1343             } else
1344                 ob_debug_type(OB_DEBUG_APP_BUGS,
1345                               "_NET_ACTIVE_WINDOW message for window %s is "
1346                               "missing source indication");
1347             client_activate(client, TRUE, TRUE, TRUE,
1348                             (e->xclient.data.l[0] == 0 ||
1349                              e->xclient.data.l[0] == 2));
1350         } else if (msgtype == OBT_PROP_ATOM(NET_WM_MOVERESIZE)) {
1351             ob_debug("net_wm_moveresize for 0x%lx direction %d",
1352                      client->window, e->xclient.data.l[2]);
1353             if ((Atom)e->xclient.data.l[2] ==
1354                 OBT_PROP_ATOM(NET_WM_MOVERESIZE_SIZE_TOPLEFT) ||
1355                 (Atom)e->xclient.data.l[2] ==
1356                 OBT_PROP_ATOM(NET_WM_MOVERESIZE_SIZE_TOP) ||
1357                 (Atom)e->xclient.data.l[2] ==
1358                 OBT_PROP_ATOM(NET_WM_MOVERESIZE_SIZE_TOPRIGHT) ||
1359                 (Atom)e->xclient.data.l[2] ==
1360                 OBT_PROP_ATOM(NET_WM_MOVERESIZE_SIZE_RIGHT) ||
1361                 (Atom)e->xclient.data.l[2] ==
1362                 OBT_PROP_ATOM(NET_WM_MOVERESIZE_SIZE_RIGHT) ||
1363                 (Atom)e->xclient.data.l[2] ==
1364                 OBT_PROP_ATOM(NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT) ||
1365                 (Atom)e->xclient.data.l[2] ==
1366                 OBT_PROP_ATOM(NET_WM_MOVERESIZE_SIZE_BOTTOM) ||
1367                 (Atom)e->xclient.data.l[2] ==
1368                 OBT_PROP_ATOM(NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT) ||
1369                 (Atom)e->xclient.data.l[2] ==
1370                 OBT_PROP_ATOM(NET_WM_MOVERESIZE_SIZE_LEFT) ||
1371                 (Atom)e->xclient.data.l[2] ==
1372                 OBT_PROP_ATOM(NET_WM_MOVERESIZE_MOVE) ||
1373                 (Atom)e->xclient.data.l[2] ==
1374                 OBT_PROP_ATOM(NET_WM_MOVERESIZE_SIZE_KEYBOARD) ||
1375                 (Atom)e->xclient.data.l[2] ==
1376                 OBT_PROP_ATOM(NET_WM_MOVERESIZE_MOVE_KEYBOARD))
1377             {
1378                 moveresize_start(client, e->xclient.data.l[0],
1379                                  e->xclient.data.l[1], e->xclient.data.l[3],
1380                                  e->xclient.data.l[2]);
1381             }
1382             else if ((Atom)e->xclient.data.l[2] ==
1383                      OBT_PROP_ATOM(NET_WM_MOVERESIZE_CANCEL))
1384                 moveresize_end(TRUE);
1385         } else if (msgtype == OBT_PROP_ATOM(NET_MOVERESIZE_WINDOW)) {
1386             gint ograv, x, y, w, h;
1387
1388             ograv = client->gravity;
1389
1390             if (e->xclient.data.l[0] & 0xff)
1391                 client->gravity = e->xclient.data.l[0] & 0xff;
1392
1393             if (e->xclient.data.l[0] & 1 << 8)
1394                 x = e->xclient.data.l[1];
1395             else
1396                 x = client->area.x;
1397             if (e->xclient.data.l[0] & 1 << 9)
1398                 y = e->xclient.data.l[2];
1399             else
1400                 y = client->area.y;
1401
1402             if (e->xclient.data.l[0] & 1 << 10) {
1403                 w = e->xclient.data.l[3];
1404
1405                 /* if x was not given, then use gravity to figure out the new
1406                    x.  the reference point should not be moved */
1407                 if (!(e->xclient.data.l[0] & 1 << 8))
1408                     client_gravity_resize_w(client, &x, client->area.width, w);
1409             }
1410             else
1411                 w = client->area.width;
1412
1413             if (e->xclient.data.l[0] & 1 << 11) {
1414                 h = e->xclient.data.l[4];
1415
1416                 /* same for y */
1417                 if (!(e->xclient.data.l[0] & 1 << 9))
1418                     client_gravity_resize_h(client, &y, client->area.height,h);
1419             }
1420             else
1421                 h = client->area.height;
1422
1423             ob_debug("MOVERESIZE x %d %d y %d %d (gravity %d)",
1424                      e->xclient.data.l[0] & 1 << 8, x,
1425                      e->xclient.data.l[0] & 1 << 9, y,
1426                      client->gravity);
1427
1428             client_find_onscreen(client, &x, &y, w, h, FALSE);
1429
1430             client_configure(client, x, y, w, h, FALSE, TRUE, FALSE);
1431
1432             client->gravity = ograv;
1433         } else if (msgtype == OBT_PROP_ATOM(NET_RESTACK_WINDOW)) {
1434             if (e->xclient.data.l[0] != 2) {
1435                 ob_debug_type(OB_DEBUG_APP_BUGS,
1436                               "_NET_RESTACK_WINDOW sent for window %s with "
1437                               "invalid source indication %ld",
1438                               client->title, e->xclient.data.l[0]);
1439             } else {
1440                 ObClient *sibling = NULL;
1441                 if (e->xclient.data.l[1]) {
1442                     ObWindow *win = window_find(e->xclient.data.l[1]);
1443                     if (WINDOW_IS_CLIENT(win) &&
1444                         WINDOW_AS_CLIENT(win) != client)
1445                     {
1446                         sibling = WINDOW_AS_CLIENT(win);
1447                     }
1448                     if (sibling == NULL)
1449                         ob_debug_type(OB_DEBUG_APP_BUGS,
1450                                       "_NET_RESTACK_WINDOW sent for window %s "
1451                                       "with invalid sibling 0x%x",
1452                                  client->title, e->xclient.data.l[1]);
1453                 }
1454                 if (e->xclient.data.l[2] == Below ||
1455                     e->xclient.data.l[2] == BottomIf ||
1456                     e->xclient.data.l[2] == Above ||
1457                     e->xclient.data.l[2] == TopIf ||
1458                     e->xclient.data.l[2] == Opposite)
1459                 {
1460                     gulong ignore_start;
1461
1462                     if (!config_focus_under_mouse)
1463                         ignore_start = event_start_ignore_all_enters();
1464                     /* just raise, don't activate */
1465                     stacking_restack_request(client, sibling,
1466                                              e->xclient.data.l[2]);
1467                     if (!config_focus_under_mouse)
1468                         event_end_ignore_all_enters(ignore_start);
1469
1470                     /* send a synthetic ConfigureNotify, cuz this is supposed
1471                        to be like a ConfigureRequest. */
1472                     client_reconfigure(client, TRUE);
1473                 } else
1474                     ob_debug_type(OB_DEBUG_APP_BUGS,
1475                                   "_NET_RESTACK_WINDOW sent for window %s "
1476                                   "with invalid detail %d",
1477                                   client->title, e->xclient.data.l[2]);
1478             }
1479         }
1480         break;
1481     case PropertyNotify:
1482         /* validate cuz we query stuff off the client here */
1483         if (!client_validate(client)) break;
1484
1485         /* compress changes to a single property into a single change */
1486         while (XCheckTypedWindowEvent(obt_display, client->window,
1487                                       e->type, &ce)) {
1488             Atom a, b;
1489
1490             /* XXX: it would be nice to compress ALL changes to a property,
1491                not just changes in a row without other props between. */
1492
1493             a = ce.xproperty.atom;
1494             b = e->xproperty.atom;
1495
1496             if (a == b)
1497                 continue;
1498             if ((a == OBT_PROP_ATOM(NET_WM_NAME) ||
1499                  a == OBT_PROP_ATOM(WM_NAME) ||
1500                  a == OBT_PROP_ATOM(NET_WM_ICON_NAME) ||
1501                  a == OBT_PROP_ATOM(WM_ICON_NAME))
1502                 &&
1503                 (b == OBT_PROP_ATOM(NET_WM_NAME) ||
1504                  b == OBT_PROP_ATOM(WM_NAME) ||
1505                  b == OBT_PROP_ATOM(NET_WM_ICON_NAME) ||
1506                  b == OBT_PROP_ATOM(WM_ICON_NAME))) {
1507                 continue;
1508             }
1509             if (a == OBT_PROP_ATOM(NET_WM_ICON) &&
1510                 b == OBT_PROP_ATOM(NET_WM_ICON))
1511                 continue;
1512
1513             XPutBackEvent(obt_display, &ce);
1514             break;
1515         }
1516
1517         msgtype = e->xproperty.atom;
1518         if (msgtype == XA_WM_NORMAL_HINTS) {
1519             ob_debug("Update NORMAL hints");
1520             client_update_normal_hints(client);
1521             /* normal hints can make a window non-resizable */
1522             client_setup_decor_and_functions(client, FALSE);
1523
1524             /* make sure the client's sizes are within its bounds, but only
1525                reconfigure the window if it needs to. emacs will update its
1526                normal hints every time it receives a conigurenotify */
1527             client_reconfigure(client, FALSE);
1528         } else if (msgtype == XA_WM_HINTS) {
1529             client_update_wmhints(client);
1530         } else if (msgtype == XA_WM_TRANSIENT_FOR) {
1531             client_update_transient_for(client);
1532             client_get_type_and_transientness(client);
1533             /* type may have changed, so update the layer */
1534             client_calc_layer(client);
1535             client_setup_decor_and_functions(client, TRUE);
1536         } else if (msgtype == OBT_PROP_ATOM(NET_WM_NAME) ||
1537                    msgtype == OBT_PROP_ATOM(WM_NAME) ||
1538                    msgtype == OBT_PROP_ATOM(NET_WM_ICON_NAME) ||
1539                    msgtype == OBT_PROP_ATOM(WM_ICON_NAME)) {
1540             client_update_title(client);
1541         } else if (msgtype == OBT_PROP_ATOM(WM_PROTOCOLS)) {
1542             client_update_protocols(client);
1543             client_setup_decor_and_functions(client, TRUE);
1544         }
1545         else if (msgtype == OBT_PROP_ATOM(NET_WM_STRUT) ||
1546                  msgtype == OBT_PROP_ATOM(NET_WM_STRUT_PARTIAL)) {
1547             client_update_strut(client);
1548         }
1549         else if (msgtype == OBT_PROP_ATOM(NET_WM_ICON)) {
1550             client_update_icons(client);
1551         }
1552         else if (msgtype == OBT_PROP_ATOM(NET_WM_ICON_GEOMETRY)) {
1553             client_update_icon_geometry(client);
1554         }
1555         else if (msgtype == OBT_PROP_ATOM(NET_WM_USER_TIME)) {
1556             guint32 t;
1557             if (client == focus_client &&
1558                 OBT_PROP_GET32(client->window, NET_WM_USER_TIME, CARDINAL, &t)
1559                 && t && !event_time_after(t, e->xproperty.time) &&
1560                 (!event_last_user_time ||
1561                  event_time_after(t, event_last_user_time)))
1562             {
1563                 event_last_user_time = t;
1564             }
1565         }
1566 #ifdef SYNC
1567         else if (msgtype == OBT_PROP_ATOM(NET_WM_SYNC_REQUEST_COUNTER)) {
1568             client_update_sync_request_counter(client);
1569         }
1570 #endif
1571         break;
1572     case ColormapNotify:
1573         client_update_colormap(client, e->xcolormap.colormap);
1574         break;
1575     default:
1576         ;
1577 #ifdef SHAPE
1578         if (obt_display_extension_shape &&
1579             e->type == obt_display_extension_shape_basep)
1580         {
1581             client->shaped = ((XShapeEvent*)e)->shaped;
1582             frame_adjust_shape(client->frame);
1583         }
1584 #endif
1585     }
1586 }
1587
1588 static void event_handle_dock(ObDock *s, XEvent *e)
1589 {
1590     switch (e->type) {
1591     case ButtonPress:
1592         if (e->xbutton.button == 1)
1593             stacking_raise(DOCK_AS_WINDOW(s));
1594         else if (e->xbutton.button == 2)
1595             stacking_lower(DOCK_AS_WINDOW(s));
1596         break;
1597     case EnterNotify:
1598         dock_hide(FALSE);
1599         break;
1600     case LeaveNotify:
1601         /* don't hide when moving into a dock app */
1602         if (e->xcrossing.detail != NotifyInferior)
1603             dock_hide(TRUE);
1604         break;
1605     }
1606 }
1607
1608 static void event_handle_dockapp(ObDockApp *app, XEvent *e)
1609 {
1610     switch (e->type) {
1611     case MotionNotify:
1612         dock_app_drag(app, &e->xmotion);
1613         break;
1614     case UnmapNotify:
1615         if (app->ignore_unmaps) {
1616             app->ignore_unmaps--;
1617             break;
1618         }
1619         dock_unmanage(app, TRUE);
1620         break;
1621     case DestroyNotify:
1622     case ReparentNotify:
1623         dock_unmanage(app, FALSE);
1624         break;
1625     case ConfigureNotify:
1626         dock_app_configure(app, e->xconfigure.width, e->xconfigure.height);
1627         break;
1628     }
1629 }
1630
1631 static ObMenuFrame* find_active_menu(void)
1632 {
1633     GList *it;
1634     ObMenuFrame *ret = NULL;
1635
1636     for (it = menu_frame_visible; it; it = g_list_next(it)) {
1637         ret = it->data;
1638         if (ret->selected)
1639             break;
1640         ret = NULL;
1641     }
1642     return ret;
1643 }
1644
1645 static ObMenuFrame* find_active_or_last_menu(void)
1646 {
1647     ObMenuFrame *ret = NULL;
1648
1649     ret = find_active_menu();
1650     if (!ret && menu_frame_visible)
1651         ret = menu_frame_visible->data;
1652     return ret;
1653 }
1654
1655 static gboolean event_handle_prompt(ObPrompt *p, XEvent *e)
1656 {
1657     switch (e->type) {
1658     case ButtonPress:
1659     case ButtonRelease:
1660     case MotionNotify:
1661         return prompt_mouse_event(p, e);
1662         break;
1663     case KeyPress:
1664         return prompt_key_event(p, e);
1665         break;
1666     }
1667     return FALSE;
1668 }
1669
1670 static gboolean event_handle_menu_input(XEvent *ev)
1671 {
1672     gboolean ret = FALSE;
1673
1674     if (ev->type == ButtonRelease || ev->type == ButtonPress) {
1675         ObMenuEntryFrame *e;
1676
1677         if (menu_hide_delay_reached() &&
1678             (ev->xbutton.button < 4 || ev->xbutton.button > 5))
1679         {
1680             if ((e = menu_entry_frame_under(ev->xbutton.x_root,
1681                                             ev->xbutton.y_root)))
1682             {
1683                 if (ev->type == ButtonPress && e->frame->child)
1684                     menu_frame_select(e->frame->child, NULL, TRUE);
1685                 menu_frame_select(e->frame, e, TRUE);
1686                 if (ev->type == ButtonRelease)
1687                     menu_entry_frame_execute(e, ev->xbutton.state);
1688             }
1689             else if (ev->type == ButtonRelease)
1690                 menu_frame_hide_all();
1691         }
1692         ret = TRUE;
1693     }
1694     else if (ev->type == MotionNotify) {
1695         ObMenuFrame *f;
1696         ObMenuEntryFrame *e;
1697
1698         if ((e = menu_entry_frame_under(ev->xmotion.x_root,
1699                                         ev->xmotion.y_root)))
1700             if (!(f = find_active_menu()) ||
1701                 f == e->frame ||
1702                 f->parent == e->frame ||
1703                 f->child == e->frame)
1704                 menu_frame_select(e->frame, e, FALSE);
1705     }
1706     else if (ev->type == KeyPress || ev->type == KeyRelease) {
1707         guint keycode, state;
1708         gunichar unikey;
1709         ObMenuFrame *frame;
1710
1711         keycode = ev->xkey.keycode;
1712         state = ev->xkey.state;
1713         unikey = obt_keyboard_keycode_to_unichar(keycode);
1714
1715         frame = find_active_or_last_menu();
1716         if (frame == NULL)
1717             g_assert_not_reached(); /* there is no active menu */
1718
1719         /* Allow control while going thru the menu */
1720         else if (ev->type == KeyPress && (state & ~ControlMask) == 0) {
1721             frame->got_press = TRUE;
1722
1723             if (keycode == ob_keycode(OB_KEY_ESCAPE)) {
1724                 menu_frame_hide_all();
1725                 ret = TRUE;
1726             }
1727
1728             else if (keycode == ob_keycode(OB_KEY_LEFT)) {
1729                 /* Left goes to the parent menu */
1730                 if (frame->parent)
1731                     menu_frame_select(frame, NULL, TRUE);
1732                 ret = TRUE;
1733             }
1734
1735             else if (keycode == ob_keycode(OB_KEY_RIGHT)) {
1736                 /* Right goes to the selected submenu */
1737                 if (frame->child) menu_frame_select_next(frame->child);
1738                 ret = TRUE;
1739             }
1740
1741             else if (keycode == ob_keycode(OB_KEY_UP)) {
1742                 menu_frame_select_previous(frame);
1743                 ret = TRUE;
1744             }
1745
1746             else if (keycode == ob_keycode(OB_KEY_DOWN)) {
1747                 menu_frame_select_next(frame);
1748                 ret = TRUE;
1749             }
1750         }
1751
1752         /* Use KeyRelease events for running things so that the key release
1753            doesn't get sent to the focused application.
1754
1755            Allow ControlMask only, and don't bother if the menu is empty */
1756         else if (ev->type == KeyRelease && (state & ~ControlMask) == 0 &&
1757                  frame->entries && frame->got_press)
1758         {
1759             if (keycode == ob_keycode(OB_KEY_RETURN)) {
1760                 /* Enter runs the active item or goes into the submenu.
1761                    Control-Enter runs it without closing the menu. */
1762                 if (frame->child)
1763                     menu_frame_select_next(frame->child);
1764                 else if (frame->selected)
1765                     menu_entry_frame_execute(frame->selected, state);
1766
1767                 ret = TRUE;
1768             }
1769
1770             /* keyboard accelerator shortcuts. (if it was a valid key) */
1771             else if (unikey != 0) {
1772                 GList *start;
1773                 GList *it;
1774                 ObMenuEntryFrame *found = NULL;
1775                 guint num_found = 0;
1776
1777                 /* start after the selected one */
1778                 start = frame->entries;
1779                 if (frame->selected) {
1780                     for (it = start; frame->selected != it->data;
1781                          it = g_list_next(it))
1782                         g_assert(it != NULL); /* nothing was selected? */
1783                     /* next with wraparound */
1784                     start = g_list_next(it);
1785                     if (start == NULL) start = frame->entries;
1786                 }
1787
1788                 it = start;
1789                 do {
1790                     ObMenuEntryFrame *e = it->data;
1791                     gunichar entrykey = 0;
1792
1793                     if (e->entry->type == OB_MENU_ENTRY_TYPE_NORMAL)
1794                         entrykey = e->entry->data.normal.shortcut;
1795                     else if (e->entry->type == OB_MENU_ENTRY_TYPE_SUBMENU)
1796                         entrykey = e->entry->data.submenu.submenu->shortcut;
1797
1798                     if (unikey == entrykey) {
1799                         if (found == NULL) found = e;
1800                         ++num_found;
1801                     }
1802
1803                     /* next with wraparound */
1804                     it = g_list_next(it);
1805                     if (it == NULL) it = frame->entries;
1806                 } while (it != start);
1807
1808                 if (found) {
1809                     if (found->entry->type == OB_MENU_ENTRY_TYPE_NORMAL &&
1810                         num_found == 1)
1811                     {
1812                         menu_frame_select(frame, found, TRUE);
1813                         usleep(50000); /* highlight the item for a short bit so
1814                                           the user can see what happened */
1815                         menu_entry_frame_execute(found, state);
1816                     } else {
1817                         menu_frame_select(frame, found, TRUE);
1818                         if (num_found == 1)
1819                             menu_frame_select_next(frame->child);
1820                     }
1821
1822                     ret = TRUE;
1823                 }
1824             }
1825         }
1826     }
1827
1828     return ret;
1829 }
1830
1831 static void event_handle_menu(ObMenuFrame *frame, XEvent *ev)
1832 {
1833     ObMenuFrame *f;
1834     ObMenuEntryFrame *e;
1835
1836     switch (ev->type) {
1837     case EnterNotify:
1838         if ((e = g_hash_table_lookup(menu_frame_map, &ev->xcrossing.window))) {
1839             if (e->ignore_enters)
1840                 --e->ignore_enters;
1841             else if (!(f = find_active_menu()) ||
1842                      f == e->frame ||
1843                      f->parent == e->frame ||
1844                      f->child == e->frame)
1845                 menu_frame_select(e->frame, e, FALSE);
1846         }
1847         break;
1848     case LeaveNotify:
1849         /*ignore leaves when we're already in the window */
1850         if (ev->xcrossing.detail == NotifyInferior)
1851             break;
1852
1853         if ((e = g_hash_table_lookup(menu_frame_map, &ev->xcrossing.window)) &&
1854             (f = find_active_menu()) && f->selected == e &&
1855             e->entry->type != OB_MENU_ENTRY_TYPE_SUBMENU)
1856         {
1857             menu_frame_select(e->frame, NULL, FALSE);
1858         }
1859         break;
1860     }
1861 }
1862
1863 static void event_handle_user_input(ObClient *client, XEvent *e)
1864 {
1865     g_assert(e->type == ButtonPress || e->type == ButtonRelease ||
1866              e->type == MotionNotify || e->type == KeyPress ||
1867              e->type == KeyRelease);
1868
1869     if (menu_frame_visible) {
1870         if (event_handle_menu_input(e))
1871             /* don't use the event if the menu used it, but if the menu
1872                didn't use it and it's a keypress that is bound, it will
1873                close the menu and be used */
1874             return;
1875     }
1876
1877     /* if the keyboard interactive action uses the event then dont
1878        use it for bindings. likewise is moveresize uses the event. */
1879     if (!actions_interactive_input_event(e) && !moveresize_event(e)) {
1880         if (moveresize_in_progress)
1881             /* make further actions work on the client being
1882                moved/resized */
1883             client = moveresize_client;
1884
1885         if (e->type == ButtonPress ||
1886             e->type == ButtonRelease ||
1887             e->type == MotionNotify)
1888         {
1889             /* the frame may not be "visible" but they can still click on it
1890                in the case where it is animating before disappearing */
1891             if (!client || !frame_iconify_animating(client->frame))
1892                 mouse_event(client, e);
1893         } else
1894             keyboard_event(event_target_client(client), e);
1895     }
1896 }
1897
1898 ObClient* event_target_client(ObClient *client)
1899 {
1900     return (focus_cycle_target ? focus_cycle_target :
1901             (client ? client : focus_client));
1902 }
1903
1904 static void focus_delay_dest(gpointer data)
1905 {
1906     g_free(data);
1907 }
1908
1909 static gboolean focus_delay_cmp(gconstpointer d1, gconstpointer d2)
1910 {
1911     const ObFocusDelayData *f1 = d1;
1912     return f1->client == d2;
1913 }
1914
1915 static gboolean focus_delay_func(gpointer data)
1916 {
1917     ObFocusDelayData *d = data;
1918     Time old = event_curtime;
1919
1920     /* don't move focus and kill the menu or the move/resize */
1921     if (menu_frame_visible || moveresize_in_progress) return FALSE;
1922
1923     event_curtime = d->time;
1924     event_curserial = d->serial;
1925     if (client_focus(d->client) && config_focus_raise)
1926         stacking_raise(CLIENT_AS_WINDOW(d->client));
1927     event_curtime = old;
1928     return FALSE; /* no repeat */
1929 }
1930
1931 static void focus_delay_client_dest(ObClient *client, gpointer data)
1932 {
1933     obt_main_loop_timeout_remove_data(ob_main_loop, focus_delay_func,
1934                                       client, FALSE);
1935 }
1936
1937 void event_halt_focus_delay(void)
1938 {
1939     /* ignore all enter events up till the event which caused this to occur */
1940     if (event_curserial) event_ignore_enter_range(1, event_curserial);
1941     obt_main_loop_timeout_remove(ob_main_loop, focus_delay_func);
1942 }
1943
1944 gulong event_start_ignore_all_enters(void)
1945 {
1946     return NextRequest(obt_display);
1947 }
1948
1949 static void event_ignore_enter_range(gulong start, gulong end)
1950 {
1951     ObSerialRange *r;
1952
1953     g_assert(start != 0);
1954     g_assert(end != 0);
1955
1956     r = g_new(ObSerialRange, 1);
1957     r->start = start;
1958     r->end = end;
1959     ignore_serials = g_slist_prepend(ignore_serials, r);
1960
1961     ob_debug_type(OB_DEBUG_FOCUS, "ignoring enters from %lu until %lu",
1962                   r->start, r->end);
1963
1964     /* increment the serial so we don't ignore events we weren't meant to */
1965     OBT_PROP_ERASE(screen_support_win, MOTIF_WM_HINTS);
1966 }
1967
1968 void event_end_ignore_all_enters(gulong start)
1969 {
1970     /* Use (NextRequest-1) so that we ignore up to the current serial only.
1971        Inside event_ignore_enter_range, we increment the serial by one, but if
1972        we ignore that serial too, then any enter events generated by mouse
1973        movement will be ignored until we create some further network traffic.
1974        Instead ignore up to NextRequest-1, then when we increment the serial,
1975        we will be *past* the range of ignored serials */
1976     event_ignore_enter_range(start, NextRequest(obt_display)-1);
1977 }
1978
1979 static gboolean is_enter_focus_event_ignored(gulong serial)
1980 {
1981     GSList *it, *next;
1982
1983     for (it = ignore_serials; it; it = next) {
1984         ObSerialRange *r = it->data;
1985
1986         next = g_slist_next(it);
1987
1988         if ((glong)(serial - r->end) > 0) {
1989             /* past the end */
1990             ignore_serials = g_slist_delete_link(ignore_serials, it);
1991             g_free(r);
1992         }
1993         else if ((glong)(serial - r->start) >= 0)
1994             return TRUE;
1995     }
1996     return FALSE;
1997 }
1998
1999 void event_cancel_all_key_grabs(void)
2000 {
2001     if (actions_interactive_act_running()) {
2002         actions_interactive_cancel_act();
2003         ob_debug("KILLED interactive action");
2004     }
2005     else if (menu_frame_visible) {
2006         menu_frame_hide_all();
2007         ob_debug("KILLED open menus");
2008     }
2009     else if (moveresize_in_progress) {
2010         moveresize_end(TRUE);
2011         ob_debug("KILLED interactive moveresize");
2012     }
2013     else if (grab_on_keyboard()) {
2014         ungrab_keyboard();
2015         ob_debug("KILLED active grab on keyboard");
2016     }
2017     else
2018         ungrab_passive_key();
2019
2020     XSync(obt_display, FALSE);
2021 }
2022
2023 gboolean event_time_after(Time t1, Time t2)
2024 {
2025     g_assert(t1 != CurrentTime);
2026     g_assert(t2 != CurrentTime);
2027
2028     /*
2029       Timestamp values wrap around (after about 49.7 days). The server, given
2030       its current time is represented by timestamp T, always interprets
2031       timestamps from clients by treating half of the timestamp space as being
2032       later in time than T.
2033       - http://tronche.com/gui/x/xlib/input/pointer-grabbing.html
2034     */
2035
2036     /* TIME_HALF is half of the number space of a Time type variable */
2037 #define TIME_HALF (Time)(1 << (sizeof(Time)*8-1))
2038
2039     if (t2 >= TIME_HALF)
2040         /* t2 is in the second half so t1 might wrap around and be smaller than
2041            t2 */
2042         return t1 >= t2 || t1 < (t2 + TIME_HALF);
2043     else
2044         /* t2 is in the first half so t1 has to come after it */
2045         return t1 >= t2 && t1 < (t2 + TIME_HALF);
2046 }
2047
2048 Time event_get_server_time(void)
2049 {
2050     /* Generate a timestamp */
2051     XEvent event;
2052
2053     XChangeProperty(obt_display, screen_support_win,
2054                     OBT_PROP_ATOM(WM_CLASS), OBT_PROP_ATOM(STRING),
2055                     8, PropModeAppend, NULL, 0);
2056     XWindowEvent(obt_display, screen_support_win, PropertyChangeMask, &event);
2057     return event.xproperty.time;
2058 }