mssing a break; *^^;*
[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 "client.h"
26 #include "xerror.h"
27 #include "prop.h"
28 #include "config.h"
29 #include "screen.h"
30 #include "frame.h"
31 #include "grab.h"
32 #include "menu.h"
33 #include "menuframe.h"
34 #include "keyboard.h"
35 #include "modkeys.h"
36 #include "propwin.h"
37 #include "mouse.h"
38 #include "mainloop.h"
39 #include "framerender.h"
40 #include "focus.h"
41 #include "focus_cycle.h"
42 #include "moveresize.h"
43 #include "group.h"
44 #include "stacking.h"
45 #include "extensions.h"
46 #include "translate.h"
47
48 #include <X11/Xlib.h>
49 #include <X11/Xatom.h>
50 #include <glib.h>
51
52 #ifdef HAVE_SYS_SELECT_H
53 #  include <sys/select.h>
54 #endif
55 #ifdef HAVE_SIGNAL_H
56 #  include <signal.h>
57 #endif
58 #ifdef HAVE_UNISTD_H
59 #  include <unistd.h> /* for usleep() */
60 #endif
61 #ifdef XKB
62 #  include <X11/XKBlib.h>
63 #endif
64
65 #ifdef USE_SM
66 #include <X11/ICE/ICElib.h>
67 #endif
68
69 typedef struct
70 {
71     gboolean ignored;
72 } ObEventData;
73
74 typedef struct
75 {
76     ObClient *client;
77     Time time;
78 } ObFocusDelayData;
79
80 static void event_process(const XEvent *e, gpointer data);
81 static void event_handle_root(XEvent *e);
82 static gboolean event_handle_menu_keyboard(XEvent *e);
83 static gboolean event_handle_menu(XEvent *e);
84 static void event_handle_dock(ObDock *s, XEvent *e);
85 static void event_handle_dockapp(ObDockApp *app, XEvent *e);
86 static void event_handle_client(ObClient *c, XEvent *e);
87 static void event_handle_user_time_window_clients(GSList *l, XEvent *e);
88 static void event_handle_user_input(ObClient *client, XEvent *e);
89 static gboolean is_enter_focus_event_ignored(XEvent *e);
90
91 static void focus_delay_dest(gpointer data);
92 static gboolean focus_delay_cmp(gconstpointer d1, gconstpointer d2);
93 static gboolean focus_delay_func(gpointer data);
94 static void focus_delay_client_dest(ObClient *client, gpointer data);
95
96 static gboolean menu_hide_delay_func(gpointer data);
97
98 /* The time for the current event being processed */
99 Time event_curtime = CurrentTime;
100
101 static guint ignore_enter_focus = 0;
102 static gboolean menu_can_hide;
103 static gboolean focus_left_screen = FALSE;
104
105 #ifdef USE_SM
106 static void ice_handler(gint fd, gpointer conn)
107 {
108     Bool b;
109     IceProcessMessages(conn, NULL, &b);
110 }
111
112 static void ice_watch(IceConn conn, IcePointer data, Bool opening,
113                       IcePointer *watch_data)
114 {
115     static gint fd = -1;
116
117     if (opening) {
118         fd = IceConnectionNumber(conn);
119         ob_main_loop_fd_add(ob_main_loop, fd, ice_handler, conn, NULL);
120     } else {
121         ob_main_loop_fd_remove(ob_main_loop, fd);
122         fd = -1;
123     }
124 }
125 #endif
126
127 void event_startup(gboolean reconfig)
128 {
129     if (reconfig) return;
130
131     ob_main_loop_x_add(ob_main_loop, event_process, NULL, NULL);
132
133 #ifdef USE_SM
134     IceAddConnectionWatch(ice_watch, NULL);
135 #endif
136
137     client_add_destroy_notify(focus_delay_client_dest, NULL);
138 }
139
140 void event_shutdown(gboolean reconfig)
141 {
142     if (reconfig) return;
143
144 #ifdef USE_SM
145     IceRemoveConnectionWatch(ice_watch, NULL);
146 #endif
147
148     client_remove_destroy_notify(focus_delay_client_dest);
149 }
150
151 static Window event_get_window(XEvent *e)
152 {
153     Window window;
154
155     /* pick a window */
156     switch (e->type) {
157     case SelectionClear:
158         window = RootWindow(ob_display, ob_screen);
159         break;
160     case MapRequest:
161         window = e->xmap.window;
162         break;
163     case UnmapNotify:
164         window = e->xunmap.window;
165         break;
166     case DestroyNotify:
167         window = e->xdestroywindow.window;
168         break;
169     case ConfigureRequest:
170         window = e->xconfigurerequest.window;
171         break;
172     case ConfigureNotify:
173         window = e->xconfigure.window;
174         break;
175     default:
176 #ifdef XKB
177         if (extensions_xkb && e->type == extensions_xkb_event_basep) {
178             switch (((XkbAnyEvent*)e)->xkb_type) {
179             case XkbBellNotify:
180                 window = ((XkbBellNotifyEvent*)e)->window;
181             default:
182                 window = None;
183             }
184         } else
185 #endif
186 #ifdef SYNC
187         if (extensions_sync &&
188             e->type == extensions_sync_event_basep + XSyncAlarmNotify)
189         {
190             window = None;
191         } else
192 #endif
193             window = e->xany.window;
194     }
195     return window;
196 }
197
198 static void event_set_curtime(XEvent *e)
199 {
200     Time t = CurrentTime;
201
202     /* grab the lasttime and hack up the state */
203     switch (e->type) {
204     case ButtonPress:
205     case ButtonRelease:
206         t = e->xbutton.time;
207         break;
208     case KeyPress:
209         t = e->xkey.time;
210         break;
211     case KeyRelease:
212         t = e->xkey.time;
213         break;
214     case MotionNotify:
215         t = e->xmotion.time;
216         break;
217     case PropertyNotify:
218         t = e->xproperty.time;
219         break;
220     case EnterNotify:
221     case LeaveNotify:
222         t = e->xcrossing.time;
223         break;
224     default:
225 #ifdef SYNC
226         if (extensions_sync &&
227             e->type == extensions_sync_event_basep + XSyncAlarmNotify)
228         {
229             t = ((XSyncAlarmNotifyEvent*)e)->time;
230         }
231 #endif
232         /* if more event types are anticipated, get their timestamp
233            explicitly */
234         break;
235     }
236
237     event_curtime = t;
238 }
239
240 static void event_hack_mods(XEvent *e)
241 {
242 #ifdef XKB
243     XkbStateRec xkb_state;
244 #endif
245
246     switch (e->type) {
247     case ButtonPress:
248     case ButtonRelease:
249         e->xbutton.state = modkeys_only_modifier_masks(e->xbutton.state);
250         break;
251     case KeyPress:
252         e->xkey.state = modkeys_only_modifier_masks(e->xkey.state);
253         break;
254     case KeyRelease:
255         e->xkey.state = modkeys_only_modifier_masks(e->xkey.state);
256 #ifdef XKB
257         if (XkbGetState(ob_display, XkbUseCoreKbd, &xkb_state) == Success) {
258             e->xkey.state = xkb_state.compat_state;
259             break;
260         }
261 #endif
262         /* remove from the state the mask of the modifier key being released,
263            if it is a modifier key being released that is */
264         e->xkey.state &= ~modkeys_keycode_to_mask(e->xkey.keycode);
265         break;
266     case MotionNotify:
267         e->xmotion.state = modkeys_only_modifier_masks(e->xmotion.state);
268         /* compress events */
269         {
270             XEvent ce;
271             while (XCheckTypedWindowEvent(ob_display, e->xmotion.window,
272                                           e->type, &ce)) {
273                 e->xmotion.x_root = ce.xmotion.x_root;
274                 e->xmotion.y_root = ce.xmotion.y_root;
275             }
276         }
277         break;
278     }
279 }
280
281 static gboolean wanted_focusevent(XEvent *e, gboolean in_client_only)
282 {
283     gint mode = e->xfocus.mode;
284     gint detail = e->xfocus.detail;
285     Window win = e->xany.window;
286
287     if (e->type == FocusIn) {
288         /* These are ones we never want.. */
289
290         /* This means focus was given by a keyboard/mouse grab. */
291         if (mode == NotifyGrab)
292             return FALSE;
293         /* This means focus was given back from a keyboard/mouse grab. */
294         if (mode == NotifyUngrab)
295             return FALSE;
296
297         /* These are the ones we want.. */
298
299         if (win == RootWindow(ob_display, ob_screen)) {
300             /* If looking for a focus in on a client, then always return
301                FALSE for focus in's to the root window */
302             if (in_client_only)
303                 return FALSE;
304             /* This means focus reverted off of a client */
305             else if (detail == NotifyPointerRoot ||
306                      detail == NotifyDetailNone ||
307                      detail == NotifyInferior)
308                 return TRUE;
309             else
310                 return FALSE;
311         }
312
313         /* It was on a client, was it a valid one?
314            It's possible to get a FocusIn event for a client that was managed
315            but has disappeared.
316         */
317         if (in_client_only) {
318             ObWindow *w = g_hash_table_lookup(window_map, &e->xfocus.window);
319             if (!w || !WINDOW_IS_CLIENT(w))
320                 return FALSE;
321         }
322         else {
323             /* This means focus reverted to parent from the client (this
324                happens often during iconify animation) */
325             if (detail == NotifyInferior)
326                 return TRUE;
327         }
328
329         /* This means focus moved from the root window to a client */
330         if (detail == NotifyVirtual)
331             return TRUE;
332         /* This means focus moved from one client to another */
333         if (detail == NotifyNonlinearVirtual)
334             return TRUE;
335
336         /* Otherwise.. */
337         return FALSE;
338     } else {
339         g_assert(e->type == FocusOut);
340
341         /* These are ones we never want.. */
342
343         /* This means focus was taken by a keyboard/mouse grab. */
344         if (mode == NotifyGrab)
345             return FALSE;
346
347         /* Focus left the root window revertedto state */
348         if (win == RootWindow(ob_display, ob_screen))
349             return FALSE;
350
351         /* These are the ones we want.. */
352
353         /* This means focus moved from a client to the root window */
354         if (detail == NotifyVirtual)
355             return TRUE;
356         /* This means focus moved from one client to another */
357         if (detail == NotifyNonlinearVirtual)
358             return TRUE;
359
360         /* Otherwise.. */
361         return FALSE;
362     }
363 }
364
365 static Bool event_look_for_focusin(Display *d, XEvent *e, XPointer arg)
366 {
367     return e->type == FocusIn && wanted_focusevent(e, FALSE);
368 }
369
370 static Bool event_look_for_focusin_client(Display *d, XEvent *e, XPointer arg)
371 {
372     return e->type == FocusIn && wanted_focusevent(e, TRUE);
373 }
374
375 static void print_focusevent(XEvent *e)
376 {
377     gint mode = e->xfocus.mode;
378     gint detail = e->xfocus.detail;
379     Window win = e->xany.window;
380     const gchar *modestr, *detailstr;
381
382     switch (mode) {
383     case NotifyNormal:       modestr="NotifyNormal";       break;
384     case NotifyGrab:         modestr="NotifyGrab";         break;
385     case NotifyUngrab:       modestr="NotifyUngrab";       break;
386     case NotifyWhileGrabbed: modestr="NotifyWhileGrabbed"; break;
387     }
388     switch (detail) {
389     case NotifyAncestor:    detailstr="NotifyAncestor";    break;
390     case NotifyVirtual:     detailstr="NotifyVirtual";     break;
391     case NotifyInferior:    detailstr="NotifyInferior";    break;
392     case NotifyNonlinear:   detailstr="NotifyNonlinear";   break;
393     case NotifyNonlinearVirtual: detailstr="NotifyNonlinearVirtual"; break;
394     case NotifyPointer:     detailstr="NotifyPointer";     break;
395     case NotifyPointerRoot: detailstr="NotifyPointerRoot"; break;
396     case NotifyDetailNone:  detailstr="NotifyDetailNone";  break;
397     }
398
399     if (mode == NotifyGrab || mode == NotifyUngrab)
400         return;
401
402     g_assert(modestr);
403     g_assert(detailstr);
404     ob_debug_type(OB_DEBUG_FOCUS, "Focus%s 0x%x mode=%s detail=%s\n",
405                   (e->xfocus.type == FocusIn ? "In" : "Out"),
406                   win,
407                   modestr, detailstr);
408
409 }
410
411 static gboolean event_ignore(XEvent *e, ObClient *client)
412 {
413     switch(e->type) {
414     case FocusIn:
415         print_focusevent(e);
416         if (!wanted_focusevent(e, FALSE))
417             return TRUE;
418         break;
419     case FocusOut:
420         print_focusevent(e);
421         if (!wanted_focusevent(e, FALSE))
422             return TRUE;
423         break;
424     }
425     return FALSE;
426 }
427
428 static void event_process(const XEvent *ec, gpointer data)
429 {
430     Window window;
431     ObClient *client = NULL;
432     ObDock *dock = NULL;
433     ObDockApp *dockapp = NULL;
434     ObWindow *obwin = NULL;
435     GSList *timewinclients = NULL;
436     XEvent ee, *e;
437     ObEventData *ed = data;
438
439     /* make a copy we can mangle */
440     ee = *ec;
441     e = &ee;
442
443     window = event_get_window(e);
444     if (e->type != PropertyNotify ||
445         !(timewinclients = propwin_get_clients(window,
446                                                OB_PROPWIN_USER_TIME)))
447         if ((obwin = g_hash_table_lookup(window_map, &window))) {
448             switch (obwin->type) {
449             case Window_Dock:
450                 dock = WINDOW_AS_DOCK(obwin);
451                 break;
452             case Window_DockApp:
453                 dockapp = WINDOW_AS_DOCKAPP(obwin);
454                 break;
455             case Window_Client:
456                 client = WINDOW_AS_CLIENT(obwin);
457                 break;
458             case Window_Menu:
459             case Window_Internal:
460                 /* not to be used for events */
461                 g_assert_not_reached();
462                 break;
463             }
464         }
465
466     event_set_curtime(e);
467     event_hack_mods(e);
468     if (event_ignore(e, client)) {
469         if (ed)
470             ed->ignored = TRUE;
471         return;
472     } else if (ed)
473             ed->ignored = FALSE;
474
475     /* deal with it in the kernel */
476
477     if (menu_frame_visible &&
478         (e->type == EnterNotify || e->type == LeaveNotify))
479     {
480         /* crossing events for menu */
481         event_handle_menu(e);
482     } else if (e->type == FocusIn) {
483         if (e->xfocus.detail == NotifyPointerRoot ||
484             e->xfocus.detail == NotifyDetailNone ||
485             e->xfocus.detail == NotifyInferior)
486         {
487             XEvent ce;
488
489             ob_debug_type(OB_DEBUG_FOCUS, "Focus went to pointer root/none or"
490                           " the frame window\n");
491
492             /* If another FocusIn is in the queue then don't fallback yet. This
493                fixes the fun case of:
494                window map -> send focusin
495                window unmap -> get focusout
496                window map -> send focusin
497                get first focus out -> fall back to something (new window
498                  hasn't received focus yet, so something else) -> send focusin
499                which means the "something else" is the last thing to get a
500                focusin sent to it, so the new window doesn't end up with focus.
501
502                But if the other focus in is something like PointerRoot then we
503                still want to fall back.
504             */
505             if (XCheckIfEvent(ob_display, &ce, event_look_for_focusin_client,
506                               NULL))
507             {
508                 XPutBackEvent(ob_display, &ce);
509                 ob_debug_type(OB_DEBUG_FOCUS,
510                               "  but another FocusIn is coming\n");
511             } else {
512                 /* Focus has been reverted.
513
514                    FocusOut events come after UnmapNotify, so we don't need to
515                    worry about focusing an invalid window
516                 */
517
518                 if (!focus_left_screen)
519                     focus_fallback(TRUE);
520             }
521         }
522         else if (!client)
523         {
524             ob_debug_type(OB_DEBUG_FOCUS,
525                           "Focus went to a window that is already gone\n");
526
527             /* If you send focus to a window and then it disappears, you can
528                get the FocusIn for it, after it is unmanaged.
529                Just wait for the next FocusOut/FocusIn pair. */
530         }
531         else if (client != focus_client) {
532             focus_left_screen = FALSE;
533             frame_adjust_focus(client->frame, TRUE);
534             focus_set_client(client);
535             client_calc_layer(client);
536             client_bring_helper_windows(client);
537         }
538     } else if (e->type == FocusOut) {
539         XEvent ce;
540
541         /* Look for the followup FocusIn */
542         if (!XCheckIfEvent(ob_display, &ce, event_look_for_focusin, NULL)) {
543             /* There is no FocusIn, this means focus went to a window that
544                is not being managed, or a window on another screen. */
545             Window win, root;
546             gint i;
547             guint u;
548             xerror_set_ignore(TRUE);
549             if (XGetInputFocus(ob_display, &win, &i) != 0 &&
550                 XGetGeometry(ob_display, win, &root, &i,&i,&u,&u,&u,&u) != 0 &&
551                 root != RootWindow(ob_display, ob_screen))
552             {
553                 ob_debug_type(OB_DEBUG_FOCUS,
554                               "Focus went to another screen !\n");
555                 focus_left_screen = TRUE;
556             }
557             else
558                 ob_debug_type(OB_DEBUG_FOCUS,
559                               "Focus went to a black hole !\n");
560             xerror_set_ignore(FALSE);
561             /* nothing is focused */
562             focus_set_client(NULL);
563         } else {
564             /* Focus moved, so process the FocusIn event */
565             ObEventData ed = { .ignored = FALSE };
566             event_process(&ce, &ed);
567             if (ed.ignored) {
568                 /* The FocusIn was ignored, this means it was on a window
569                    that isn't a client. */
570                 ob_debug_type(OB_DEBUG_FOCUS,
571                               "Focus went to an unmanaged window 0x%x !\n",
572                               ce.xfocus.window);
573                 focus_fallback(TRUE);
574             }
575         }
576
577         if (client && client != focus_client) {
578             frame_adjust_focus(client->frame, FALSE);
579             /* focus_set_client(NULL) has already been called in this
580                section or by focus_fallback */
581             client_calc_layer(client);
582         }
583     } else if (timewinclients)
584         event_handle_user_time_window_clients(timewinclients, e);
585     else if (client)
586         event_handle_client(client, e);
587     else if (dockapp)
588         event_handle_dockapp(dockapp, e);
589     else if (dock)
590         event_handle_dock(dock, e);
591     else if (window == RootWindow(ob_display, ob_screen))
592         event_handle_root(e);
593     else if (e->type == MapRequest)
594         client_manage(window);
595     else if (e->type == ClientMessage) {
596         /* This is for _NET_WM_REQUEST_FRAME_EXTENTS messages. They come for
597            windows that are not managed yet. */
598         if (e->xclient.message_type == prop_atoms.net_request_frame_extents) {
599             /* Pretend to manage the client, getting information used to
600                determine its decorations */
601             ObClient *c = client_fake_manage(e->xclient.window);
602             gulong vals[4];
603
604             /* set the frame extents on the window */
605             vals[0] = c->frame->size.left;
606             vals[1] = c->frame->size.right;
607             vals[2] = c->frame->size.top;
608             vals[3] = c->frame->size.bottom;
609             PROP_SETA32(e->xclient.window, net_frame_extents,
610                         cardinal, vals, 4);
611
612             /* Free the pretend client */
613             client_fake_unmanage(c);
614         }
615     }
616     else if (e->type == ConfigureRequest) {
617         /* unhandled configure requests must be used to configure the
618            window directly */
619         XWindowChanges xwc;
620
621         xwc.x = e->xconfigurerequest.x;
622         xwc.y = e->xconfigurerequest.y;
623         xwc.width = e->xconfigurerequest.width;
624         xwc.height = e->xconfigurerequest.height;
625         xwc.border_width = e->xconfigurerequest.border_width;
626         xwc.sibling = e->xconfigurerequest.above;
627         xwc.stack_mode = e->xconfigurerequest.detail;
628        
629         /* we are not to be held responsible if someone sends us an
630            invalid request! */
631         xerror_set_ignore(TRUE);
632         XConfigureWindow(ob_display, window,
633                          e->xconfigurerequest.value_mask, &xwc);
634         xerror_set_ignore(FALSE);
635     }
636 #ifdef SYNC
637     else if (extensions_sync &&
638         e->type == extensions_sync_event_basep + XSyncAlarmNotify)
639     {
640         XSyncAlarmNotifyEvent *se = (XSyncAlarmNotifyEvent*)e;
641         if (se->alarm == moveresize_alarm && moveresize_in_progress)
642             moveresize_event(e);
643     }
644 #endif
645
646     if (e->type == ButtonPress || e->type == ButtonRelease ||
647         e->type == MotionNotify || e->type == KeyPress ||
648         e->type == KeyRelease)
649     {
650         event_handle_user_input(client, e);
651     }
652
653     /* if something happens and it's not from an XEvent, then we don't know
654        the time */
655     event_curtime = CurrentTime;
656 }
657
658 static void event_handle_root(XEvent *e)
659 {
660     Atom msgtype;
661      
662     switch(e->type) {
663     case SelectionClear:
664         ob_debug("Another WM has requested to replace us. Exiting.\n");
665         ob_exit_replace();
666         break;
667
668     case ClientMessage:
669         if (e->xclient.format != 32) break;
670
671         msgtype = e->xclient.message_type;
672         if (msgtype == prop_atoms.net_current_desktop) {
673             guint d = e->xclient.data.l[0];
674             if (d < screen_num_desktops) {
675                 event_curtime = e->xclient.data.l[1];
676                 if (event_curtime == 0)
677                     ob_debug_type(OB_DEBUG_APP_BUGS,
678                                   "_NET_CURRENT_DESKTOP message is missing "
679                                   "a timestamp\n");
680                 screen_set_desktop(d, TRUE);
681             }
682         } else if (msgtype == prop_atoms.net_number_of_desktops) {
683             guint d = e->xclient.data.l[0];
684             if (d > 0 && d <= 1000)
685                 screen_set_num_desktops(d);
686         } else if (msgtype == prop_atoms.net_showing_desktop) {
687             screen_show_desktop(e->xclient.data.l[0] != 0, NULL);
688         } else if (msgtype == prop_atoms.ob_control) {
689             if (e->xclient.data.l[0] == 1)
690                 ob_reconfigure();
691             else if (e->xclient.data.l[0] == 2)
692                 ob_restart();
693         }
694         break;
695     case PropertyNotify:
696         if (e->xproperty.atom == prop_atoms.net_desktop_names)
697             screen_update_desktop_names();
698         else if (e->xproperty.atom == prop_atoms.net_desktop_layout)
699             screen_update_layout();
700         break;
701     case ConfigureNotify:
702 #ifdef XRANDR
703         XRRUpdateConfiguration(e);
704 #endif
705         screen_resize();
706         break;
707     default:
708         ;
709     }
710 }
711
712 void event_enter_client(ObClient *client)
713 {
714     g_assert(config_focus_follow);
715
716     if (client_enter_focusable(client) && client_can_focus(client)) {
717         if (config_focus_delay) {
718             ObFocusDelayData *data;
719
720             ob_main_loop_timeout_remove(ob_main_loop, focus_delay_func);
721
722             data = g_new(ObFocusDelayData, 1);
723             data->client = client;
724             data->time = event_curtime;
725
726             ob_main_loop_timeout_add(ob_main_loop,
727                                      config_focus_delay,
728                                      focus_delay_func,
729                                      data, focus_delay_cmp, focus_delay_dest);
730         } else {
731             ObFocusDelayData data;
732             data.client = client;
733             data.time = event_curtime;
734             focus_delay_func(&data);
735         }
736     }
737 }
738
739 static void event_handle_user_time_window_clients(GSList *l, XEvent *e)
740 {
741     g_assert(e->type == PropertyNotify);
742     if (e->xproperty.atom == prop_atoms.net_wm_user_time) {
743         for (; l; l = g_slist_next(l))
744             client_update_user_time(l->data);
745     }
746 }
747
748 static void event_handle_client(ObClient *client, XEvent *e)
749 {
750     XEvent ce;
751     Atom msgtype;
752     ObFrameContext con;
753     static gint px = -1, py = -1;
754     static guint pb = 0;
755      
756     switch (e->type) {
757     case ButtonPress:
758         /* save where the press occured for the first button pressed */
759         if (!pb) {
760             pb = e->xbutton.button;
761             px = e->xbutton.x;
762             py = e->xbutton.y;
763         }
764     case ButtonRelease:
765         /* Wheel buttons don't draw because they are an instant click, so it
766            is a waste of resources to go drawing it.
767            if the user is doing an intereactive thing, or has a menu open then
768            the mouse is grabbed (possibly) and if we get these events we don't
769            want to deal with them
770         */
771         if (!(e->xbutton.button == 4 || e->xbutton.button == 5) &&
772             !keyboard_interactively_grabbed() &&
773             !menu_frame_visible)
774         {
775             /* use where the press occured */
776             con = frame_context(client, e->xbutton.window, px, py);
777             con = mouse_button_frame_context(con, e->xbutton.button,
778                                              e->xbutton.state);
779
780             if (e->type == ButtonRelease && e->xbutton.button == pb)
781                 pb = 0, px = py = -1;
782
783             switch (con) {
784             case OB_FRAME_CONTEXT_MAXIMIZE:
785                 client->frame->max_press = (e->type == ButtonPress);
786                 framerender_frame(client->frame);
787                 break;
788             case OB_FRAME_CONTEXT_CLOSE:
789                 client->frame->close_press = (e->type == ButtonPress);
790                 framerender_frame(client->frame);
791                 break;
792             case OB_FRAME_CONTEXT_ICONIFY:
793                 client->frame->iconify_press = (e->type == ButtonPress);
794                 framerender_frame(client->frame);
795                 break;
796             case OB_FRAME_CONTEXT_ALLDESKTOPS:
797                 client->frame->desk_press = (e->type == ButtonPress);
798                 framerender_frame(client->frame);
799                 break; 
800             case OB_FRAME_CONTEXT_SHADE:
801                 client->frame->shade_press = (e->type == ButtonPress);
802                 framerender_frame(client->frame);
803                 break;
804             default:
805                 /* nothing changes with clicks for any other contexts */
806                 break;
807             }
808         }
809         break;
810     case MotionNotify:
811         con = frame_context(client, e->xmotion.window,
812                             e->xmotion.x, e->xmotion.y);
813         switch (con) {
814         case OB_FRAME_CONTEXT_TITLEBAR:
815         case OB_FRAME_CONTEXT_TLCORNER:
816         case OB_FRAME_CONTEXT_TRCORNER:
817             /* we've left the button area inside the titlebar */
818             if (client->frame->max_hover || client->frame->desk_hover ||
819                 client->frame->shade_hover || client->frame->iconify_hover ||
820                 client->frame->close_hover)
821             {
822                 client->frame->max_hover = FALSE;
823                 client->frame->desk_hover = FALSE;
824                 client->frame->shade_hover = FALSE;
825                 client->frame->iconify_hover = FALSE;
826                 client->frame->close_hover = FALSE;
827                 frame_adjust_state(client->frame);
828             }
829             break;
830         case OB_FRAME_CONTEXT_MAXIMIZE:
831             if (!client->frame->max_hover) {
832                 client->frame->max_hover = TRUE;
833                 frame_adjust_state(client->frame);
834             }
835             break;
836         case OB_FRAME_CONTEXT_ALLDESKTOPS:
837             if (!client->frame->desk_hover) {
838                 client->frame->desk_hover = TRUE;
839                 frame_adjust_state(client->frame);
840             }
841             break;
842         case OB_FRAME_CONTEXT_SHADE:
843             if (!client->frame->shade_hover) {
844                 client->frame->shade_hover = TRUE;
845                 frame_adjust_state(client->frame);
846             }
847             break;
848         case OB_FRAME_CONTEXT_ICONIFY:
849             if (!client->frame->iconify_hover) {
850                 client->frame->iconify_hover = TRUE;
851                 frame_adjust_state(client->frame);
852             }
853             break;
854         case OB_FRAME_CONTEXT_CLOSE:
855             if (!client->frame->close_hover) {
856                 client->frame->close_hover = TRUE;
857                 frame_adjust_state(client->frame);
858             }
859             break;
860         default:
861             break;
862         }
863         break;
864     case LeaveNotify:
865         con = frame_context(client, e->xcrossing.window,
866                             e->xcrossing.x, e->xcrossing.y);
867         switch (con) {
868         case OB_FRAME_CONTEXT_TITLEBAR:
869         case OB_FRAME_CONTEXT_TLCORNER:
870         case OB_FRAME_CONTEXT_TRCORNER:
871             /* we've left the button area inside the titlebar */
872             if (client->frame->max_hover || client->frame->desk_hover ||
873                 client->frame->shade_hover || client->frame->iconify_hover ||
874                 client->frame->close_hover)
875             {
876                 client->frame->max_hover = FALSE;
877                 client->frame->desk_hover = FALSE;
878                 client->frame->shade_hover = FALSE;
879                 client->frame->iconify_hover = FALSE;
880                 client->frame->close_hover = FALSE;
881                 frame_adjust_state(client->frame);
882             }
883             break;
884         case OB_FRAME_CONTEXT_MAXIMIZE:
885             client->frame->max_hover = FALSE;
886             frame_adjust_state(client->frame);
887             break;
888         case OB_FRAME_CONTEXT_ALLDESKTOPS:
889             client->frame->desk_hover = FALSE;
890             frame_adjust_state(client->frame);
891             break;
892         case OB_FRAME_CONTEXT_SHADE:
893             client->frame->shade_hover = FALSE;
894             frame_adjust_state(client->frame);
895             break;
896         case OB_FRAME_CONTEXT_ICONIFY:
897             client->frame->iconify_hover = FALSE;
898             frame_adjust_state(client->frame);
899             break;
900         case OB_FRAME_CONTEXT_CLOSE:
901             client->frame->close_hover = FALSE;
902             frame_adjust_state(client->frame);
903             break;
904         case OB_FRAME_CONTEXT_FRAME:
905             /* When the mouse leaves an animating window, don't use the
906                corresponding enter events. Pretend like the animating window
907                doesn't even exist..! */
908             if (frame_iconify_animating(client->frame))
909                 event_ignore_all_queued_enters();
910
911             ob_debug_type(OB_DEBUG_FOCUS,
912                           "%sNotify mode %d detail %d on %lx\n",
913                           (e->type == EnterNotify ? "Enter" : "Leave"),
914                           e->xcrossing.mode,
915                           e->xcrossing.detail, (client?client->window:0));
916             if (keyboard_interactively_grabbed())
917                 break;
918             if (config_focus_follow && config_focus_delay &&
919                 /* leave inferior events can happen when the mouse goes onto
920                    the window's border and then into the window before the
921                    delay is up */
922                 e->xcrossing.detail != NotifyInferior)
923             {
924                 ob_main_loop_timeout_remove_data(ob_main_loop,
925                                                  focus_delay_func,
926                                                  client, FALSE);
927             }
928             break;
929         default:
930             break;
931         }
932         break;
933     case EnterNotify:
934     {
935         con = frame_context(client, e->xcrossing.window,
936                             e->xcrossing.x, e->xcrossing.y);
937         switch (con) {
938         case OB_FRAME_CONTEXT_MAXIMIZE:
939             client->frame->max_hover = TRUE;
940             frame_adjust_state(client->frame);
941             break;
942         case OB_FRAME_CONTEXT_ALLDESKTOPS:
943             client->frame->desk_hover = TRUE;
944             frame_adjust_state(client->frame);
945             break;
946         case OB_FRAME_CONTEXT_SHADE:
947             client->frame->shade_hover = TRUE;
948             frame_adjust_state(client->frame);
949             break;
950         case OB_FRAME_CONTEXT_ICONIFY:
951             client->frame->iconify_hover = TRUE;
952             frame_adjust_state(client->frame);
953             break;
954         case OB_FRAME_CONTEXT_CLOSE:
955             client->frame->close_hover = TRUE;
956             frame_adjust_state(client->frame);
957             break;
958         case OB_FRAME_CONTEXT_FRAME:
959             if (keyboard_interactively_grabbed())
960                 break;
961             if (e->xcrossing.mode == NotifyGrab ||
962                 e->xcrossing.mode == NotifyUngrab ||
963                 /*ignore enters when we're already in the window */
964                 e->xcrossing.detail == NotifyInferior ||
965                 is_enter_focus_event_ignored(e))
966             {
967                 ob_debug_type(OB_DEBUG_FOCUS,
968                               "%sNotify mode %d detail %d on %lx IGNORED\n",
969                               (e->type == EnterNotify ? "Enter" : "Leave"),
970                               e->xcrossing.mode,
971                               e->xcrossing.detail, client?client->window:0);
972             }
973             else {
974                 ob_debug_type(OB_DEBUG_FOCUS,
975                               "%sNotify mode %d detail %d on %lx, "
976                               "focusing window\n",
977                               (e->type == EnterNotify ? "Enter" : "Leave"),
978                               e->xcrossing.mode,
979                               e->xcrossing.detail, (client?client->window:0));
980                 if (config_focus_follow)
981                     event_enter_client(client);
982             }
983             break;
984         default:
985             break;
986         }
987         break;
988     }
989     case ConfigureRequest:
990     {
991         /* dont compress these unless you're going to watch for property
992            notifies in between (these can change what the configure would
993            do to the window).
994            also you can't compress stacking events
995         */
996
997         gint x, y, w, h, b;
998         gboolean move = FALSE;
999         gboolean resize = FALSE;
1000         gboolean border = FALSE;
1001
1002         /* get the current area */
1003         RECT_TO_DIMS(client->area, x, y, w, h);
1004         b = client->border_width;
1005
1006         ob_debug("ConfigureRequest desktop %d wmstate %d visibile %d\n",
1007                  screen_desktop, client->wmstate, client->frame->visible);
1008
1009         if (e->xconfigurerequest.value_mask & CWBorderWidth)
1010             if (client->border_width != e->xconfigurerequest.border_width) {
1011                 b = e->xconfigurerequest.border_width;
1012                 border = TRUE;
1013             }
1014
1015
1016         if (e->xconfigurerequest.value_mask & CWStackMode) {
1017             ObClient *sibling = NULL;
1018
1019             /* get the sibling */
1020             if (e->xconfigurerequest.value_mask & CWSibling) {
1021                 ObWindow *win;
1022                 win = g_hash_table_lookup(window_map,
1023                                           &e->xconfigurerequest.above);
1024                 if (WINDOW_IS_CLIENT(win) && WINDOW_AS_CLIENT(win) != client)
1025                     sibling = WINDOW_AS_CLIENT(win);
1026             }
1027
1028             /* activate it rather than just focus it */
1029             stacking_restack_request(client, sibling,
1030                                      e->xconfigurerequest.detail, TRUE);
1031
1032             /* if a stacking change moves the window without resizing */
1033             move = TRUE;
1034         }
1035
1036         if (e->xconfigurerequest.value_mask & CWX ||
1037             e->xconfigurerequest.value_mask & CWY ||
1038             e->xconfigurerequest.value_mask & CWWidth ||
1039             e->xconfigurerequest.value_mask & CWHeight)
1040         {
1041             if (e->xconfigurerequest.value_mask & CWX) {
1042                 /* don't allow clients to move shaded windows (fvwm does this)
1043                  */
1044                 if (!client->shaded)
1045                     x = e->xconfigurerequest.x;
1046                 move = TRUE;
1047             }
1048             if (e->xconfigurerequest.value_mask & CWY) {
1049                 /* don't allow clients to move shaded windows (fvwm does this)
1050                  */
1051                 if (!client->shaded)
1052                     y = e->xconfigurerequest.y;
1053                 move = TRUE;
1054             }
1055
1056             if (e->xconfigurerequest.value_mask & CWWidth) {
1057                 w = e->xconfigurerequest.width;
1058                 resize = TRUE;
1059
1060                 /* if x was not given, then use gravity to figure out the new
1061                    x.  the reference point should not be moved */
1062                 if (!(e->xconfigurerequest.value_mask & CWX))
1063                     client_gravity_resize_w(client, &x, client->area.width, w);
1064             }
1065             if (e->xconfigurerequest.value_mask & CWHeight) {
1066                 h = e->xconfigurerequest.height;
1067                 resize = TRUE;
1068
1069                 /* if y was not given, then use gravity to figure out the new
1070                    y.  the reference point should not be moved */
1071                 if (!(e->xconfigurerequest.value_mask & CWY))
1072                     client_gravity_resize_h(client, &y, client->area.height,h);
1073             }
1074         }
1075
1076         ob_debug("ConfigureRequest x(%d) %d y(%d) %d w(%d) %d h(%d) %d "
1077                  "move %d resize %d\n",
1078                  e->xconfigurerequest.value_mask & CWX, x,
1079                  e->xconfigurerequest.value_mask & CWY, y,
1080                  e->xconfigurerequest.value_mask & CWWidth, w,
1081                  e->xconfigurerequest.value_mask & CWHeight, h,
1082                  move, resize);
1083
1084         /* check for broken apps moving to their root position
1085
1086            XXX remove this some day...that would be nice. right now all
1087            kde apps do this when they try activate themselves on another
1088            desktop. eg. open amarok window on desktop 1, switch to desktop
1089            2, click amarok tray icon. it will move by its decoration size.
1090         */
1091         if (move && !resize &&
1092             x != client->area.x &&
1093             x == (client->frame->area.x + client->frame->size.left -
1094                   (gint)client->border_width) &&
1095             y != client->area.y &&
1096             y == (client->frame->area.y + client->frame->size.top -
1097                   (gint)client->border_width))
1098         {
1099             ob_debug_type(OB_DEBUG_APP_BUGS,
1100                           "Application %s is trying to move via "
1101                           "ConfigureRequest to it's root window position "
1102                           "but it is not using StaticGravity\n",
1103                           client->title);
1104             /* don't move it */
1105             x = client->area.x;
1106             y = client->area.y;
1107
1108             /* they still requested a move, so don't change whether a
1109                notify is sent or not */
1110         }
1111
1112         if (move || resize || border) {
1113             gint lw,lh;
1114
1115             if (move || resize) {
1116                 client_find_onscreen(client, &x, &y, w, h, FALSE);
1117                 client_try_configure(client, &x, &y, &w, &h, &lw, &lh, FALSE);
1118             }
1119             /* if they requested something that moves the window, or if
1120                the window is actually being changed then configure it and
1121                send a configure notify to them */
1122             if (move || !RECT_EQUAL_DIMS(client->area, x, y, w, h) ||
1123                 border)
1124             {
1125                 ob_debug("Doing configure\n");
1126                 client_configure(client, x, y, w, h, b, FALSE, TRUE);
1127             }
1128
1129             /* ignore enter events caused by these like ob actions do */
1130             event_ignore_all_queued_enters();
1131         }
1132         break;
1133     }
1134     case UnmapNotify:
1135         if (client->ignore_unmaps) {
1136             client->ignore_unmaps--;
1137             break;
1138         }
1139         ob_debug("UnmapNotify for window 0x%x eventwin 0x%x sendevent %d "
1140                  "ignores left %d\n",
1141                  client->window, e->xunmap.event, e->xunmap.from_configure,
1142                  client->ignore_unmaps);
1143         client_unmanage(client);
1144         break;
1145     case DestroyNotify:
1146         ob_debug("DestroyNotify for window 0x%x\n", client->window);
1147         client_unmanage(client);
1148         break;
1149     case ReparentNotify:
1150         /* this is when the client is first taken captive in the frame */
1151         if (e->xreparent.parent == client->frame->plate) break;
1152
1153         /*
1154           This event is quite rare and is usually handled in unmapHandler.
1155           However, if the window is unmapped when the reparent event occurs,
1156           the window manager never sees it because an unmap event is not sent
1157           to an already unmapped window.
1158         */
1159
1160         /* we don't want the reparent event, put it back on the stack for the
1161            X server to deal with after we unmanage the window */
1162         XPutBackEvent(ob_display, e);
1163      
1164         ob_debug("ReparentNotify for window 0x%x\n", client->window);
1165         client_unmanage(client);
1166         break;
1167     case MapRequest:
1168         ob_debug("MapRequest for 0x%lx\n", client->window);
1169         if (!client->iconic) break; /* this normally doesn't happen, but if it
1170                                        does, we don't want it!
1171                                        it can happen now when the window is on
1172                                        another desktop, but we still don't
1173                                        want it! */
1174         client_activate(client, FALSE, TRUE);
1175         break;
1176     case ClientMessage:
1177         /* validate cuz we query stuff off the client here */
1178         if (!client_validate(client)) break;
1179
1180         if (e->xclient.format != 32) return;
1181
1182         msgtype = e->xclient.message_type;
1183         if (msgtype == prop_atoms.wm_change_state) {
1184             /* compress changes into a single change */
1185             while (XCheckTypedWindowEvent(ob_display, client->window,
1186                                           e->type, &ce)) {
1187                 /* XXX: it would be nice to compress ALL messages of a
1188                    type, not just messages in a row without other
1189                    message types between. */
1190                 if (ce.xclient.message_type != msgtype) {
1191                     XPutBackEvent(ob_display, &ce);
1192                     break;
1193                 }
1194                 e->xclient = ce.xclient;
1195             }
1196             client_set_wm_state(client, e->xclient.data.l[0]);
1197         } else if (msgtype == prop_atoms.net_wm_desktop) {
1198             /* compress changes into a single change */
1199             while (XCheckTypedWindowEvent(ob_display, client->window,
1200                                           e->type, &ce)) {
1201                 /* XXX: it would be nice to compress ALL messages of a
1202                    type, not just messages in a row without other
1203                    message types between. */
1204                 if (ce.xclient.message_type != msgtype) {
1205                     XPutBackEvent(ob_display, &ce);
1206                     break;
1207                 }
1208                 e->xclient = ce.xclient;
1209             }
1210             if ((unsigned)e->xclient.data.l[0] < screen_num_desktops ||
1211                 (unsigned)e->xclient.data.l[0] == DESKTOP_ALL)
1212                 client_set_desktop(client, (unsigned)e->xclient.data.l[0],
1213                                    FALSE);
1214         } else if (msgtype == prop_atoms.net_wm_state) {
1215             /* can't compress these */
1216             ob_debug("net_wm_state %s %ld %ld for 0x%lx\n",
1217                      (e->xclient.data.l[0] == 0 ? "Remove" :
1218                       e->xclient.data.l[0] == 1 ? "Add" :
1219                       e->xclient.data.l[0] == 2 ? "Toggle" : "INVALID"),
1220                      e->xclient.data.l[1], e->xclient.data.l[2],
1221                      client->window);
1222             client_set_state(client, e->xclient.data.l[0],
1223                              e->xclient.data.l[1], e->xclient.data.l[2]);
1224
1225             /* ignore enter events caused by these like ob actions do */
1226             event_ignore_all_queued_enters();
1227         } else if (msgtype == prop_atoms.net_close_window) {
1228             ob_debug("net_close_window for 0x%lx\n", client->window);
1229             client_close(client);
1230         } else if (msgtype == prop_atoms.net_active_window) {
1231             ob_debug("net_active_window for 0x%lx source=%s\n",
1232                      client->window,
1233                      (e->xclient.data.l[0] == 0 ? "unknown" :
1234                       (e->xclient.data.l[0] == 1 ? "application" :
1235                        (e->xclient.data.l[0] == 2 ? "user" : "INVALID"))));
1236             /* XXX make use of data.l[2] !? */
1237             if (e->xclient.data.l[0] == 1 || e->xclient.data.l[0] == 2) {
1238                 event_curtime = e->xclient.data.l[1];
1239                 if (event_curtime == 0)
1240                     ob_debug_type(OB_DEBUG_APP_BUGS,
1241                                   "_NET_ACTIVE_WINDOW message for window %s is"
1242                                   " missing a timestamp\n", client->title);
1243             } else
1244                 ob_debug_type(OB_DEBUG_APP_BUGS,
1245                               "_NET_ACTIVE_WINDOW message for window %s is "
1246                               "missing source indication\n");
1247             client_activate(client, FALSE,
1248                             (e->xclient.data.l[0] == 0 ||
1249                              e->xclient.data.l[0] == 2));
1250         } else if (msgtype == prop_atoms.net_wm_moveresize) {
1251             ob_debug("net_wm_moveresize for 0x%lx direction %d\n",
1252                      client->window, e->xclient.data.l[2]);
1253             if ((Atom)e->xclient.data.l[2] ==
1254                 prop_atoms.net_wm_moveresize_size_topleft ||
1255                 (Atom)e->xclient.data.l[2] ==
1256                 prop_atoms.net_wm_moveresize_size_top ||
1257                 (Atom)e->xclient.data.l[2] ==
1258                 prop_atoms.net_wm_moveresize_size_topright ||
1259                 (Atom)e->xclient.data.l[2] ==
1260                 prop_atoms.net_wm_moveresize_size_right ||
1261                 (Atom)e->xclient.data.l[2] ==
1262                 prop_atoms.net_wm_moveresize_size_right ||
1263                 (Atom)e->xclient.data.l[2] ==
1264                 prop_atoms.net_wm_moveresize_size_bottomright ||
1265                 (Atom)e->xclient.data.l[2] ==
1266                 prop_atoms.net_wm_moveresize_size_bottom ||
1267                 (Atom)e->xclient.data.l[2] ==
1268                 prop_atoms.net_wm_moveresize_size_bottomleft ||
1269                 (Atom)e->xclient.data.l[2] ==
1270                 prop_atoms.net_wm_moveresize_size_left ||
1271                 (Atom)e->xclient.data.l[2] ==
1272                 prop_atoms.net_wm_moveresize_move ||
1273                 (Atom)e->xclient.data.l[2] ==
1274                 prop_atoms.net_wm_moveresize_size_keyboard ||
1275                 (Atom)e->xclient.data.l[2] ==
1276                 prop_atoms.net_wm_moveresize_move_keyboard) {
1277
1278                 moveresize_start(client, e->xclient.data.l[0],
1279                                  e->xclient.data.l[1], e->xclient.data.l[3],
1280                                  e->xclient.data.l[2]);
1281             }
1282             else if ((Atom)e->xclient.data.l[2] ==
1283                      prop_atoms.net_wm_moveresize_cancel)
1284                 moveresize_end(TRUE);
1285         } else if (msgtype == prop_atoms.net_moveresize_window) {
1286             gint ograv, x, y, w, h;
1287
1288             ograv = client->gravity;
1289
1290             if (e->xclient.data.l[0] & 0xff)
1291                 client->gravity = e->xclient.data.l[0] & 0xff;
1292
1293             if (e->xclient.data.l[0] & 1 << 8)
1294                 x = e->xclient.data.l[1];
1295             else
1296                 x = client->area.x;
1297             if (e->xclient.data.l[0] & 1 << 9)
1298                 y = e->xclient.data.l[2];
1299             else
1300                 y = client->area.y;
1301
1302             if (e->xclient.data.l[0] & 1 << 10) {
1303                 w = e->xclient.data.l[3];
1304
1305                 /* if x was not given, then use gravity to figure out the new
1306                    x.  the reference point should not be moved */
1307                 if (!(e->xclient.data.l[0] & 1 << 8))
1308                     client_gravity_resize_w(client, &x, client->area.width, w);
1309             }
1310             else
1311                 w = client->area.width;
1312
1313             if (e->xclient.data.l[0] & 1 << 11) {
1314                 h = e->xclient.data.l[4];
1315
1316                 /* if y was not given, then use gravity to figure out the new
1317                    y.  the reference point should not be moved */
1318                 if (!(e->xclient.data.l[0] & 1 << 9))
1319                     client_gravity_resize_h(client, &y, client->area.height,h);
1320             }
1321             else
1322                 h = client->area.height;
1323
1324             ob_debug("MOVERESIZE x %d %d y %d %d (gravity %d)\n",
1325                      e->xclient.data.l[0] & 1 << 8, x,
1326                      e->xclient.data.l[0] & 1 << 9, y,
1327                      client->gravity);
1328
1329             client_find_onscreen(client, &x, &y, w, h, FALSE);
1330
1331             client_configure(client, x, y, w, h, client->border_width,
1332                              FALSE, TRUE);
1333
1334             client->gravity = ograv;
1335
1336             /* ignore enter events caused by these like ob actions do */
1337             event_ignore_all_queued_enters();
1338         } else if (msgtype == prop_atoms.net_restack_window) {
1339             if (e->xclient.data.l[0] != 2) {
1340                 ob_debug_type(OB_DEBUG_APP_BUGS,
1341                               "_NET_RESTACK_WINDOW sent for window %s with "
1342                               "invalid source indication %ld\n",
1343                               client->title, e->xclient.data.l[0]);
1344             } else {
1345                 ObClient *sibling = NULL;
1346                 if (e->xclient.data.l[1]) {
1347                     ObWindow *win = g_hash_table_lookup
1348                         (window_map, &e->xclient.data.l[1]);
1349                     if (WINDOW_IS_CLIENT(win) &&
1350                         WINDOW_AS_CLIENT(win) != client)
1351                     {
1352                         sibling = WINDOW_AS_CLIENT(win);
1353                     }
1354                     if (sibling == NULL)
1355                         ob_debug_type(OB_DEBUG_APP_BUGS,
1356                                       "_NET_RESTACK_WINDOW sent for window %s "
1357                                       "with invalid sibling 0x%x\n",
1358                                  client->title, e->xclient.data.l[1]);
1359                 }
1360                 if (e->xclient.data.l[2] == Below ||
1361                     e->xclient.data.l[2] == BottomIf ||
1362                     e->xclient.data.l[2] == Above ||
1363                     e->xclient.data.l[2] == TopIf ||
1364                     e->xclient.data.l[2] == Opposite)
1365                 {
1366                     /* just raise, don't activate */
1367                     stacking_restack_request(client, sibling,
1368                                              e->xclient.data.l[2], FALSE);
1369                     /* send a synthetic ConfigureNotify, cuz this is supposed
1370                        to be like a ConfigureRequest. */
1371                     client_reconfigure(client);
1372                 } else
1373                     ob_debug_type(OB_DEBUG_APP_BUGS,
1374                                   "_NET_RESTACK_WINDOW sent for window %s "
1375                                   "with invalid detail %d\n",
1376                                   client->title, e->xclient.data.l[2]);
1377             }
1378         }
1379         break;
1380     case PropertyNotify:
1381         /* validate cuz we query stuff off the client here */
1382         if (!client_validate(client)) break;
1383   
1384         /* compress changes to a single property into a single change */
1385         while (XCheckTypedWindowEvent(ob_display, client->window,
1386                                       e->type, &ce)) {
1387             Atom a, b;
1388
1389             /* XXX: it would be nice to compress ALL changes to a property,
1390                not just changes in a row without other props between. */
1391
1392             a = ce.xproperty.atom;
1393             b = e->xproperty.atom;
1394
1395             if (a == b)
1396                 continue;
1397             if ((a == prop_atoms.net_wm_name ||
1398                  a == prop_atoms.wm_name ||
1399                  a == prop_atoms.net_wm_icon_name ||
1400                  a == prop_atoms.wm_icon_name)
1401                 &&
1402                 (b == prop_atoms.net_wm_name ||
1403                  b == prop_atoms.wm_name ||
1404                  b == prop_atoms.net_wm_icon_name ||
1405                  b == prop_atoms.wm_icon_name)) {
1406                 continue;
1407             }
1408             if (a == prop_atoms.net_wm_icon &&
1409                 b == prop_atoms.net_wm_icon)
1410                 continue;
1411
1412             XPutBackEvent(ob_display, &ce);
1413             break;
1414         }
1415
1416         msgtype = e->xproperty.atom;
1417         if (msgtype == XA_WM_NORMAL_HINTS) {
1418             client_update_normal_hints(client);
1419             /* normal hints can make a window non-resizable */
1420             client_setup_decor_and_functions(client);
1421         } else if (msgtype == XA_WM_HINTS) {
1422             client_update_wmhints(client);
1423         } else if (msgtype == XA_WM_TRANSIENT_FOR) {
1424             client_update_transient_for(client);
1425             client_get_type_and_transientness(client);
1426             /* type may have changed, so update the layer */
1427             client_calc_layer(client);
1428             client_setup_decor_and_functions(client);
1429         } else if (msgtype == prop_atoms.net_wm_name ||
1430                    msgtype == prop_atoms.wm_name ||
1431                    msgtype == prop_atoms.net_wm_icon_name ||
1432                    msgtype == prop_atoms.wm_icon_name) {
1433             client_update_title(client);
1434         } else if (msgtype == prop_atoms.wm_protocols) {
1435             client_update_protocols(client);
1436             client_setup_decor_and_functions(client);
1437         }
1438         else if (msgtype == prop_atoms.net_wm_strut) {
1439             client_update_strut(client);
1440         }
1441         else if (msgtype == prop_atoms.net_wm_icon) {
1442             client_update_icons(client);
1443         }
1444         else if (msgtype == prop_atoms.net_wm_icon_geometry) {
1445             client_update_icon_geometry(client);
1446         }
1447         else if (msgtype == prop_atoms.net_wm_user_time) {
1448             client_update_user_time(client);
1449         }
1450         else if (msgtype == prop_atoms.net_wm_user_time_window) {
1451             client_update_user_time_window(client);
1452         }
1453 #ifdef SYNC
1454         else if (msgtype == prop_atoms.net_wm_sync_request_counter) {
1455             client_update_sync_request_counter(client);
1456         }
1457 #endif
1458         break;
1459     case ColormapNotify:
1460         client_update_colormap(client, e->xcolormap.colormap);
1461         break;
1462     default:
1463         ;
1464 #ifdef SHAPE
1465         if (extensions_shape && e->type == extensions_shape_event_basep) {
1466             client->shaped = ((XShapeEvent*)e)->shaped;
1467             frame_adjust_shape(client->frame);
1468         }
1469 #endif
1470     }
1471 }
1472
1473 static void event_handle_dock(ObDock *s, XEvent *e)
1474 {
1475     switch (e->type) {
1476     case ButtonPress:
1477         if (e->xbutton.button == 1)
1478             stacking_raise(DOCK_AS_WINDOW(s));
1479         else if (e->xbutton.button == 2)
1480             stacking_lower(DOCK_AS_WINDOW(s));
1481         break;
1482     case EnterNotify:
1483         dock_hide(FALSE);
1484         break;
1485     case LeaveNotify:
1486         dock_hide(TRUE);
1487         break;
1488     }
1489 }
1490
1491 static void event_handle_dockapp(ObDockApp *app, XEvent *e)
1492 {
1493     switch (e->type) {
1494     case MotionNotify:
1495         dock_app_drag(app, &e->xmotion);
1496         break;
1497     case UnmapNotify:
1498         if (app->ignore_unmaps) {
1499             app->ignore_unmaps--;
1500             break;
1501         }
1502         dock_remove(app, TRUE);
1503         break;
1504     case DestroyNotify:
1505         dock_remove(app, FALSE);
1506         break;
1507     case ReparentNotify:
1508         dock_remove(app, FALSE);
1509         break;
1510     case ConfigureNotify:
1511         dock_app_configure(app, e->xconfigure.width, e->xconfigure.height);
1512         break;
1513     }
1514 }
1515
1516 static ObMenuFrame* find_active_menu()
1517 {
1518     GList *it;
1519     ObMenuFrame *ret = NULL;
1520
1521     for (it = menu_frame_visible; it; it = g_list_next(it)) {
1522         ret = it->data;
1523         if (ret->selected)
1524             break;
1525         ret = NULL;
1526     }
1527     return ret;
1528 }
1529
1530 static ObMenuFrame* find_active_or_last_menu()
1531 {
1532     ObMenuFrame *ret = NULL;
1533
1534     ret = find_active_menu();
1535     if (!ret && menu_frame_visible)
1536         ret = menu_frame_visible->data;
1537     return ret;
1538 }
1539
1540 static gboolean event_handle_menu_keyboard(XEvent *ev)
1541 {
1542     guint keycode, state;
1543     gunichar unikey;
1544     ObMenuFrame *frame;
1545     gboolean ret = TRUE;
1546
1547     keycode = ev->xkey.keycode;
1548     state = ev->xkey.state;
1549     unikey = translate_unichar(keycode);
1550
1551     frame = find_active_or_last_menu();
1552     if (frame == NULL)
1553         ret = FALSE;
1554
1555     else if (keycode == ob_keycode(OB_KEY_ESCAPE) && state == 0) {
1556         /* Escape goes to the parent menu or closes the last one */
1557         if (frame->parent)
1558             menu_frame_select(frame, NULL, TRUE);
1559         else
1560             menu_frame_hide_all();
1561     }
1562
1563     else if (keycode == ob_keycode(OB_KEY_RETURN) && (state == 0 ||
1564                                                       state == ControlMask))
1565     {
1566         /* Enter runs the active item or goes into the submenu.
1567            Control-Enter runs it without closing the menu. */
1568         if (frame->child)
1569             menu_frame_select_next(frame->child);
1570         else if (frame->selected)
1571             menu_entry_frame_execute(frame->selected, state, ev->xkey.time);
1572     }
1573
1574     else if (keycode == ob_keycode(OB_KEY_LEFT) && ev->xkey.state == 0) {
1575         /* Left goes to the parent menu */
1576         menu_frame_select(frame, NULL, TRUE);
1577     }
1578
1579     else if (keycode == ob_keycode(OB_KEY_RIGHT) && ev->xkey.state == 0) {
1580         /* Right goes to the selected submenu */
1581         if (frame->child) menu_frame_select_next(frame->child);
1582     }
1583
1584     else if (keycode == ob_keycode(OB_KEY_UP) && state == 0) {
1585         menu_frame_select_previous(frame);
1586     }
1587
1588     else if (keycode == ob_keycode(OB_KEY_DOWN) && state == 0) {
1589         menu_frame_select_next(frame);
1590     }
1591
1592     /* keyboard accelerator shortcuts. (allow controlmask) */
1593     else if ((ev->xkey.state & ~ControlMask) == 0 &&
1594              /* was it a valid key? */
1595              unikey != 0 &&
1596              /* don't bother if the menu is empty. */
1597              frame->entries)
1598     {
1599         GList *start;
1600         GList *it;
1601         ObMenuEntryFrame *found = NULL;
1602         guint num_found = 0;
1603
1604         /* start after the selected one */
1605         start = frame->entries;
1606         if (frame->selected) {
1607             for (it = start; frame->selected != it->data; it = g_list_next(it))
1608                 g_assert(it != NULL); /* nothing was selected? */
1609             /* next with wraparound */
1610             start = g_list_next(it);
1611             if (start == NULL) start = frame->entries;
1612         }
1613
1614         it = start;
1615         do {
1616             ObMenuEntryFrame *e = it->data;
1617             gunichar entrykey = 0;
1618
1619             if (e->entry->type == OB_MENU_ENTRY_TYPE_NORMAL)
1620                 entrykey = e->entry->data.normal.shortcut;
1621             else if (e->entry->type == OB_MENU_ENTRY_TYPE_SUBMENU)
1622                 entrykey = e->entry->data.submenu.submenu->shortcut;
1623
1624             if (unikey == entrykey) {
1625                 if (found == NULL) found = e;
1626                 ++num_found;
1627             }
1628
1629             /* next with wraparound */
1630             it = g_list_next(it);
1631             if (it == NULL) it = frame->entries;
1632         } while (it != start);
1633
1634         if (found) {
1635             if (found->entry->type == OB_MENU_ENTRY_TYPE_NORMAL &&
1636                 num_found == 1)
1637             {
1638                 menu_frame_select(frame, found, TRUE);
1639                 usleep(50000); /* highlight the item for a short bit so the
1640                                   user can see what happened */
1641                 menu_entry_frame_execute(found, state, ev->xkey.time);
1642             } else {
1643                 menu_frame_select(frame, found, TRUE);
1644                 if (num_found == 1)
1645                     menu_frame_select_next(frame->child);
1646             }
1647         } else
1648             ret = FALSE;
1649     }
1650     else
1651         ret = FALSE;
1652
1653     return ret;
1654 }
1655
1656 static gboolean event_handle_menu(XEvent *ev)
1657 {
1658     ObMenuFrame *f;
1659     ObMenuEntryFrame *e;
1660     gboolean ret = TRUE;
1661
1662     switch (ev->type) {
1663     case ButtonRelease:
1664         if ((ev->xbutton.button < 4 || ev->xbutton.button > 5)
1665             && menu_can_hide)
1666         {
1667             if ((e = menu_entry_frame_under(ev->xbutton.x_root,
1668                                             ev->xbutton.y_root)))
1669                 menu_entry_frame_execute(e, ev->xbutton.state,
1670                                          ev->xbutton.time);
1671             else
1672                 menu_frame_hide_all();
1673         }
1674         break;
1675     case EnterNotify:
1676         if ((e = g_hash_table_lookup(menu_frame_map, &ev->xcrossing.window))) {
1677             if (e->ignore_enters)
1678                 --e->ignore_enters;
1679             else
1680                 menu_frame_select(e->frame, e, FALSE);
1681         }
1682         break;
1683     case LeaveNotify:
1684         /*ignore leaves when we're already in the window */
1685         if (ev->xcrossing.detail == NotifyInferior)
1686             break;
1687
1688         if ((e = g_hash_table_lookup(menu_frame_map, &ev->xcrossing.window)) &&
1689             (f = find_active_menu()) && f->selected == e &&
1690             e->entry->type != OB_MENU_ENTRY_TYPE_SUBMENU)
1691         {
1692             menu_frame_select(e->frame, NULL, FALSE);
1693         }
1694         break;
1695     case MotionNotify:   
1696         if ((e = menu_entry_frame_under(ev->xmotion.x_root,   
1697                                         ev->xmotion.y_root)))
1698             menu_frame_select(e->frame, e, FALSE);
1699         break;
1700     case KeyPress:
1701         ret = event_handle_menu_keyboard(ev);
1702         break;
1703     }
1704     return ret;
1705 }
1706
1707 static void event_handle_user_input(ObClient *client, XEvent *e)
1708 {
1709     g_assert(e->type == ButtonPress || e->type == ButtonRelease ||
1710              e->type == MotionNotify || e->type == KeyPress ||
1711              e->type == KeyRelease);
1712
1713     if (menu_frame_visible) {
1714         if (event_handle_menu(e))
1715             /* don't use the event if the menu used it, but if the menu
1716                didn't use it and it's a keypress that is bound, it will
1717                close the menu and be used */
1718             return;
1719     }
1720
1721     /* if the keyboard interactive action uses the event then dont
1722        use it for bindings. likewise is moveresize uses the event. */
1723     if (!keyboard_process_interactive_grab(e, &client) &&
1724         !(moveresize_in_progress && moveresize_event(e)))
1725     {
1726         if (moveresize_in_progress)
1727             /* make further actions work on the client being
1728                moved/resized */
1729             client = moveresize_client;
1730
1731         menu_can_hide = FALSE;
1732         ob_main_loop_timeout_add(ob_main_loop,
1733                                  config_menu_hide_delay * 1000,
1734                                  menu_hide_delay_func,
1735                                  NULL, g_direct_equal, NULL);
1736
1737         if (e->type == ButtonPress ||
1738             e->type == ButtonRelease ||
1739             e->type == MotionNotify)
1740         {
1741             /* the frame may not be "visible" but they can still click on it
1742                in the case where it is animating before disappearing */
1743             if (!client || !frame_iconify_animating(client->frame))
1744                 mouse_event(client, e);
1745         } else if (e->type == KeyPress) {
1746             keyboard_event((focus_cycle_target ? focus_cycle_target :
1747                             (client ? client : focus_client)), e);
1748         }
1749     }
1750 }
1751
1752 static gboolean menu_hide_delay_func(gpointer data)
1753 {
1754     menu_can_hide = TRUE;
1755     return FALSE; /* no repeat */
1756 }
1757
1758 static void focus_delay_dest(gpointer data)
1759 {
1760     g_free(data);
1761 }
1762
1763 static gboolean focus_delay_cmp(gconstpointer d1, gconstpointer d2)
1764 {
1765     const ObFocusDelayData *f1 = d1;
1766     return f1->client == d2;
1767 }
1768
1769 static gboolean focus_delay_func(gpointer data)
1770 {
1771     ObFocusDelayData *d = data;
1772     Time old = event_curtime;
1773
1774     event_curtime = d->time;
1775     if (focus_client != d->client) {
1776         if (client_focus(d->client) && config_focus_raise)
1777             stacking_raise(CLIENT_AS_WINDOW(d->client));
1778     }
1779     event_curtime = old;
1780     return FALSE; /* no repeat */
1781 }
1782
1783 static void focus_delay_client_dest(ObClient *client, gpointer data)
1784 {
1785     ob_main_loop_timeout_remove_data(ob_main_loop, focus_delay_func,
1786                                      client, FALSE);
1787 }
1788
1789 void event_halt_focus_delay()
1790 {
1791     ob_main_loop_timeout_remove(ob_main_loop, focus_delay_func);
1792 }
1793
1794 static Bool event_look_for_enters(Display *d, XEvent *e, XPointer arg)
1795 {
1796     if (e->type == EnterNotify &&
1797         /* these types aren't used for focusing */
1798         !(e->xcrossing.mode == NotifyGrab ||
1799           e->xcrossing.mode == NotifyUngrab ||
1800           e->xcrossing.detail == NotifyInferior))
1801     {
1802         ObWindow *win;
1803
1804         /* found an enter for that leave, ignore it if it's going to
1805            another window */
1806         win = g_hash_table_lookup(window_map, &e->xany.window);
1807         if (win && WINDOW_IS_CLIENT(win))
1808             ++ignore_enter_focus;
1809     }
1810     return False; /* don't disrupt the queue order, just count them */
1811 }
1812
1813 void event_ignore_all_queued_enters()
1814 {
1815     XEvent e;
1816
1817     XSync(ob_display, FALSE);
1818
1819     /* count the events without disrupting them */
1820     ignore_enter_focus = 0;
1821     XCheckIfEvent(ob_display, &e, event_look_for_enters, NULL);
1822 }
1823
1824 static gboolean is_enter_focus_event_ignored(XEvent *e)
1825 {
1826     g_assert(e->type == EnterNotify &&
1827              !(e->xcrossing.mode == NotifyGrab ||
1828                e->xcrossing.mode == NotifyUngrab ||
1829                e->xcrossing.detail == NotifyInferior));
1830
1831     ob_debug_type(OB_DEBUG_FOCUS, "# enters ignored: %d\n",
1832                   ignore_enter_focus);
1833
1834     if (ignore_enter_focus) {
1835         --ignore_enter_focus;
1836         return TRUE;
1837     }
1838     return FALSE;
1839 }
1840
1841 void event_cancel_all_key_grabs()
1842 {
1843     if (keyboard_interactively_grabbed())
1844         keyboard_interactive_cancel();
1845     else if (menu_frame_visible)
1846         menu_frame_hide_all();
1847     else if (grab_on_keyboard())
1848         ungrab_keyboard();
1849     else
1850         /* If we don't have the keyboard grabbed, then ungrab it with
1851            XUngrabKeyboard, so that there is not a passive grab left
1852            on from the KeyPress. If the grab is left on, and focus
1853            moves during that time, it will be NotifyWhileGrabbed, and
1854            applications like to ignore those! */
1855         if (!keyboard_interactively_grabbed())
1856             XUngrabKeyboard(ob_display, CurrentTime);
1857
1858 }
1859
1860 gboolean event_time_after(Time t1, Time t2)
1861 {
1862     g_assert(t1 != CurrentTime);
1863     g_assert(t2 != CurrentTime);
1864
1865     /*
1866       Timestamp values wrap around (after about 49.7 days). The server, given
1867       its current time is represented by timestamp T, always interprets
1868       timestamps from clients by treating half of the timestamp space as being
1869       later in time than T.
1870       - http://tronche.com/gui/x/xlib/input/pointer-grabbing.html
1871     */
1872
1873     /* TIME_HALF is half of the number space of a Time type variable */
1874 #define TIME_HALF (Time)(1 << (sizeof(Time)*8-1))
1875
1876     if (t2 >= TIME_HALF)
1877         /* t2 is in the second half so t1 might wrap around and be smaller than
1878            t2 */
1879         return t1 >= t2 || t1 < (t2 + TIME_HALF);
1880     else
1881         /* t2 is in the first half so t1 has to come after it */
1882         return t1 >= t2 && t1 < (t2 + TIME_HALF);
1883 }