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