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