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