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