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