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