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