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