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