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