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