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