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