]> icculus.org git repositories - dana/openbox.git/blob - openbox/event.c
when a window is fully maxed, make clicking on the titlebar past the edge buttons...
[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 "menu.h"
32 #include "menuframe.h"
33 #include "keyboard.h"
34 #include "modkeys.h"
35 #include "propwin.h"
36 #include "mouse.h"
37 #include "mainloop.h"
38 #include "framerender.h"
39 #include "focus.h"
40 #include "moveresize.h"
41 #include "group.h"
42 #include "stacking.h"
43 #include "extensions.h"
44 #include "translate.h"
45
46 #include <X11/Xlib.h>
47 #include <X11/Xatom.h>
48 #include <glib.h>
49
50 #ifdef HAVE_SYS_SELECT_H
51 #  include <sys/select.h>
52 #endif
53 #ifdef HAVE_SIGNAL_H
54 #  include <signal.h>
55 #endif
56 #ifdef HAVE_UNISTD_H
57 #  include <unistd.h> /* for usleep() */
58 #endif
59 #ifdef XKB
60 #  include <X11/XKBlib.h>
61 #endif
62
63 #ifdef USE_SM
64 #include <X11/ICE/ICElib.h>
65 #endif
66
67 typedef struct
68 {
69     gboolean ignored;
70 } ObEventData;
71
72 typedef struct
73 {
74     ObClient *client;
75     Time time;
76 } ObFocusDelayData;
77
78 static void event_process(const XEvent *e, gpointer data);
79 static void event_handle_root(XEvent *e);
80 static gboolean event_handle_menu_keyboard(XEvent *e);
81 static gboolean event_handle_menu(XEvent *e);
82 static void event_handle_dock(ObDock *s, XEvent *e);
83 static void event_handle_dockapp(ObDockApp *app, XEvent *e);
84 static void event_handle_client(ObClient *c, XEvent *e);
85 static void event_handle_user_time_window_clients(GSList *l, XEvent *e);
86 static void event_handle_user_input(ObClient *client, XEvent *e);
87
88 static void focus_delay_dest(gpointer data);
89 static gboolean focus_delay_cmp(gconstpointer d1, gconstpointer d2);
90 static gboolean focus_delay_func(gpointer data);
91 static void focus_delay_client_dest(ObClient *client, gpointer data);
92
93 static gboolean menu_hide_delay_func(gpointer data);
94
95 /* The time for the current event being processed */
96 Time event_curtime = CurrentTime;
97
98 static guint ignore_enter_focus = 0;
99 static gboolean menu_can_hide;
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_destructor(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_destructor(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_root = ce.xmotion.x_root;
271                 e->xmotion.y_root = ce.xmotion.y_root;
272             }
273         }
274         break;
275     }
276 }
277
278 static gboolean wanted_focusevent(XEvent *e, gboolean in_client_only)
279 {
280     gint mode = e->xfocus.mode;
281     gint detail = e->xfocus.detail;
282     Window win = e->xany.window;
283
284     if (e->type == FocusIn) {
285         /* These are ones we never want.. */
286
287         /* This means focus was given by a keyboard/mouse grab. */
288         if (mode == NotifyGrab)
289             return FALSE;
290         /* This means focus was given back from a keyboard/mouse grab. */
291         if (mode == NotifyUngrab)
292             return FALSE;
293
294         /* These are the ones we want.. */
295
296         if (win == RootWindow(ob_display, ob_screen) && !in_client_only) {
297             /* This means focus reverted off of a client */
298             if (detail == NotifyPointerRoot || detail == NotifyDetailNone ||
299                 detail == NotifyInferior)
300                 return TRUE;
301             else
302                 return FALSE;
303         }
304
305         /* This means focus moved from the root window to a client */
306         if (detail == NotifyVirtual)
307             return TRUE;
308         /* This means focus moved from one client to another */
309         if (detail == NotifyNonlinearVirtual)
310             return TRUE;
311         /* This means focus moved to the frame window */
312         if (detail == NotifyInferior && !in_client_only)
313             return TRUE;
314
315         /* Otherwise.. */
316         return FALSE;
317     } else {
318         g_assert(e->type == FocusOut);
319
320         /* These are ones we never want.. */
321
322         /* This means focus was taken by a keyboard/mouse grab. */
323         if (mode == NotifyGrab)
324             return FALSE;
325
326         /* Focus left the root window revertedto state */
327         if (win == RootWindow(ob_display, ob_screen))
328             return FALSE;
329
330         /* These are the ones we want.. */
331
332         /* This means focus moved from a client to the root window */
333         if (detail == NotifyVirtual)
334             return TRUE;
335         /* This means focus moved from one client to another */
336         if (detail == NotifyNonlinearVirtual)
337             return TRUE;
338         /* This means focus had moved to our frame window and now moved off */
339         if (detail == NotifyNonlinear)
340             return TRUE;
341
342         /* Otherwise.. */
343         return FALSE;
344     }
345 }
346
347 static Bool look_for_focusin(Display *d, XEvent *e, XPointer arg)
348 {
349     return e->type == FocusIn && wanted_focusevent(e, FALSE);
350 }
351
352 static Bool look_for_focusin_client(Display *d, XEvent *e, XPointer arg)
353 {
354     return e->type == FocusIn && wanted_focusevent(e, TRUE);
355 }
356
357 static void print_focusevent(XEvent *e)
358 {
359     gint mode = e->xfocus.mode;
360     gint detail = e->xfocus.detail;
361     Window win = e->xany.window;
362     const gchar *modestr, *detailstr;
363
364     switch (mode) {
365     case NotifyNormal:       modestr="NotifyNormal";       break;
366     case NotifyGrab:         modestr="NotifyGrab";         break;
367     case NotifyUngrab:       modestr="NotifyUngrab";       break;
368     case NotifyWhileGrabbed: modestr="NotifyWhileGrabbed"; break;
369     }
370     switch (detail) {
371     case NotifyAncestor:    detailstr="NotifyAncestor";    break;
372     case NotifyVirtual:     detailstr="NotifyVirtual";     break;
373     case NotifyInferior:    detailstr="NotifyInferior";    break;
374     case NotifyNonlinear:   detailstr="NotifyNonlinear";   break;
375     case NotifyNonlinearVirtual: detailstr="NotifyNonlinearVirtual"; break;
376     case NotifyPointer:     detailstr="NotifyPointer";     break;
377     case NotifyPointerRoot: detailstr="NotifyPointerRoot"; break;
378     case NotifyDetailNone:  detailstr="NotifyDetailNone";  break;
379     }
380
381     g_assert(modestr);
382     g_assert(detailstr);
383     ob_debug_type(OB_DEBUG_FOCUS, "Focus%s 0x%x mode=%s detail=%s\n",
384                   (e->xfocus.type == FocusIn ? "In" : "Out"),
385                   win,
386                   modestr, detailstr);
387
388 }
389
390 static gboolean event_ignore(XEvent *e, ObClient *client)
391 {
392     switch(e->type) {
393     case FocusIn:
394         print_focusevent(e);
395         if (!wanted_focusevent(e, FALSE))
396             return TRUE;
397         break;
398     case FocusOut:
399         print_focusevent(e);
400         if (!wanted_focusevent(e, FALSE))
401             return TRUE;
402         break;
403     }
404     return FALSE;
405 }
406
407 static void event_process(const XEvent *ec, gpointer data)
408 {
409     Window window;
410     ObClient *client = NULL;
411     ObDock *dock = NULL;
412     ObDockApp *dockapp = NULL;
413     ObWindow *obwin = NULL;
414     GSList *timewinclients = NULL;
415     XEvent ee, *e;
416     ObEventData *ed = data;
417
418     /* make a copy we can mangle */
419     ee = *ec;
420     e = &ee;
421
422     window = event_get_window(e);
423     if (e->type != PropertyNotify ||
424         !(timewinclients = propwin_get_clients(window,
425                                                OB_PROPWIN_USER_TIME)))
426         if ((obwin = g_hash_table_lookup(window_map, &window))) {
427             switch (obwin->type) {
428             case Window_Dock:
429                 dock = WINDOW_AS_DOCK(obwin);
430                 break;
431             case Window_DockApp:
432                 dockapp = WINDOW_AS_DOCKAPP(obwin);
433                 break;
434             case Window_Client:
435                 client = WINDOW_AS_CLIENT(obwin);
436                 break;
437             case Window_Menu:
438             case Window_Internal:
439                 /* not to be used for events */
440                 g_assert_not_reached();
441                 break;
442             }
443         }
444
445     event_set_curtime(e);
446     event_hack_mods(e);
447     if (event_ignore(e, client)) {
448         if (ed)
449             ed->ignored = TRUE;
450         return;
451     } else if (ed)
452             ed->ignored = FALSE;
453
454     /* deal with it in the kernel */
455
456     if (menu_frame_visible &&
457         (e->type == EnterNotify || e->type == LeaveNotify))
458     {
459         /* crossing events for menu */
460         event_handle_menu(e);
461     } else if (e->type == FocusIn) {
462         if (e->xfocus.detail == NotifyPointerRoot ||
463             e->xfocus.detail == NotifyDetailNone ||
464             e->xfocus.detail == NotifyInferior)
465         {
466             XEvent ce;
467             ob_debug_type(OB_DEBUG_FOCUS,
468                           "Focus went to pointer root/none or to our frame "
469                           "window\n");
470
471             /* If another FocusIn is in the queue then don't fallback yet. This
472                fixes the fun case of:
473                window map -> send focusin
474                window unmap -> get focusout
475                window map -> send focusin
476                get first focus out -> fall back to something (new window
477                  hasn't received focus yet, so something else) -> send focusin
478                which means the "something else" is the last thing to get a
479                focusin sent to it, so the new window doesn't end up with focus.
480
481                But if the other focus in is something like PointerRoot then we
482                still want to fall back.
483             */
484             if (XCheckIfEvent(ob_display, &ce, look_for_focusin_client, NULL)){
485                 XPutBackEvent(ob_display, &ce);
486                 ob_debug_type(OB_DEBUG_FOCUS,
487                               "  but another FocusIn is coming\n");
488             } else {
489                 /* Focus has been reverted to the root window, nothing, or to
490                    our frame window.
491
492                    FocusOut events come after UnmapNotify, so we don't need to
493                    worry about focusing an invalid window
494                 */
495
496                 /* In this case we know focus is in our screen */
497                 if (e->xfocus.detail == NotifyInferior)
498                     focus_left_screen = FALSE;
499
500                 if (!focus_left_screen)
501                     focus_fallback(TRUE);
502             }
503         } else if (client && client != focus_client) {
504             focus_left_screen = FALSE;
505             frame_adjust_focus(client->frame, TRUE);
506             focus_set_client(client);
507             client_calc_layer(client);
508             client_bring_helper_windows(client);
509         }
510     } else if (e->type == FocusOut) {
511         gboolean nomove = FALSE;
512         XEvent ce;
513
514         /* Look for the followup FocusIn */
515         if (!XCheckIfEvent(ob_display, &ce, look_for_focusin, NULL)) {
516             /* There is no FocusIn, this means focus went to a window that
517                is not being managed, or a window on another screen. */
518             Window win, root;
519             gint i;
520             guint u;
521             xerror_set_ignore(TRUE);
522             if (XGetInputFocus(ob_display, &win, &i) != 0 &&
523                 XGetGeometry(ob_display, win, &root, &i,&i,&u,&u,&u,&u) != 0 &&
524                 root != RootWindow(ob_display, ob_screen))
525             {
526                 ob_debug_type(OB_DEBUG_FOCUS,
527                               "Focus went to another screen !\n");
528                 focus_left_screen = TRUE;
529             }
530             else
531                 ob_debug_type(OB_DEBUG_FOCUS,
532                               "Focus went to a black hole !\n");
533             xerror_set_ignore(FALSE);
534             /* nothing is focused */
535             focus_set_client(NULL);
536         } else if (ce.xany.window == e->xany.window) {
537             ob_debug_type(OB_DEBUG_FOCUS, "Focus didn't go anywhere\n");
538             /* If focus didn't actually move anywhere, there is nothing to do*/
539             nomove = TRUE;
540         } else {
541             /* Focus did move, so process the FocusIn event */
542             ObEventData ed = { .ignored = FALSE };
543             event_process(&ce, &ed);
544             if (ed.ignored) {
545                 /* The FocusIn was ignored, this means it was on a window
546                    that isn't a client. */
547                 ob_debug_type(OB_DEBUG_FOCUS,
548                               "Focus went to an unmanaged window 0x%x !\n",
549                               ce.xfocus.window);
550                 focus_fallback(TRUE);
551             }
552         }
553
554         if (client && !nomove) {
555             frame_adjust_focus(client->frame, FALSE);
556             /* focus_set_client has already been called for sure */
557             client_calc_layer(client);
558         }
559     } else if (timewinclients)
560         event_handle_user_time_window_clients(timewinclients, e);
561     else if (client)
562         event_handle_client(client, e);
563     else if (dockapp)
564         event_handle_dockapp(dockapp, e);
565     else if (dock)
566         event_handle_dock(dock, e);
567     else if (window == RootWindow(ob_display, ob_screen))
568         event_handle_root(e);
569     else if (e->type == MapRequest)
570         client_manage(window);
571     else if (e->type == ClientMessage) {
572         /* This is for _NET_WM_REQUEST_FRAME_EXTENTS messages. They come for
573            windows that are not managed yet. */
574         if (e->xclient.message_type == prop_atoms.net_request_frame_extents) {
575             /* Pretend to manage the client, getting information used to
576                determine its decorations */
577             ObClient *c = client_fake_manage(e->xclient.window);
578             gulong vals[4];
579
580             /* adjust the decorations so we know the sizes */
581             frame_adjust_area(c->frame, FALSE, TRUE, TRUE);
582
583             /* set the frame extents on the window */
584             vals[0] = c->frame->size.left;
585             vals[1] = c->frame->size.right;
586             vals[2] = c->frame->size.top;
587             vals[3] = c->frame->size.bottom;
588             PROP_SETA32(e->xclient.window, net_frame_extents,
589                         cardinal, vals, 4);
590
591             /* Free the pretend client */
592             client_fake_unmanage(c);
593         }
594     }
595     else if (e->type == ConfigureRequest) {
596         /* unhandled config5Aure requests must be used to configure the
597            window directly */
598         XWindowChanges xwc;
599
600         xwc.x = e->xconfigurerequest.x;
601         xwc.y = e->xconfigurerequest.y;
602         xwc.width = e->xconfigurerequest.width;
603         xwc.height = e->xconfigurerequest.height;
604         xwc.border_width = e->xconfigurerequest.border_width;
605         xwc.sibling = e->xconfigurerequest.above;
606         xwc.stack_mode = e->xconfigurerequest.detail;
607        
608         /* we are not to be held responsible if someone sends us an
609            invalid request! */
610         xerror_set_ignore(TRUE);
611         XConfigureWindow(ob_display, window,
612                          e->xconfigurerequest.value_mask, &xwc);
613         xerror_set_ignore(FALSE);
614     }
615 #ifdef SYNC
616     else if (extensions_sync &&
617         e->type == extensions_sync_event_basep + XSyncAlarmNotify)
618     {
619         XSyncAlarmNotifyEvent *se = (XSyncAlarmNotifyEvent*)e;
620         if (se->alarm == moveresize_alarm && moveresize_in_progress)
621             moveresize_event(e);
622     }
623 #endif
624
625     if (e->type == ButtonPress || e->type == ButtonRelease ||
626         e->type == MotionNotify || e->type == KeyPress ||
627         e->type == KeyRelease)
628     {
629         event_handle_user_input(client, e);
630     }
631
632     /* if something happens and it's not from an XEvent, then we don't know
633        the time */
634     event_curtime = CurrentTime;
635 }
636
637 static void event_handle_root(XEvent *e)
638 {
639     Atom msgtype;
640      
641     switch(e->type) {
642     case SelectionClear:
643         ob_debug("Another WM has requested to replace us. Exiting.\n");
644         ob_exit_replace();
645         break;
646
647     case ClientMessage:
648         if (e->xclient.format != 32) break;
649
650         msgtype = e->xclient.message_type;
651         if (msgtype == prop_atoms.net_current_desktop) {
652             guint d = e->xclient.data.l[0];
653             if (d < screen_num_desktops) {
654                 event_curtime = e->xclient.data.l[1];
655                 if (event_curtime == 0)
656                     ob_debug_type(OB_DEBUG_APP_BUGS,
657                                   "_NET_CURRENT_DESKTOP message is missing "
658                                   "a timestamp\n");
659                 screen_set_desktop(d, TRUE);
660             }
661         } else if (msgtype == prop_atoms.net_number_of_desktops) {
662             guint d = e->xclient.data.l[0];
663             if (d > 0)
664                 screen_set_num_desktops(d);
665         } else if (msgtype == prop_atoms.net_showing_desktop) {
666             screen_show_desktop(e->xclient.data.l[0] != 0, TRUE);
667         } else if (msgtype == prop_atoms.openbox_control) {
668             if (e->xclient.data.l[0] == 1)
669                 ob_reconfigure();
670             else if (e->xclient.data.l[0] == 2)
671                 ob_restart();
672         }
673         break;
674     case PropertyNotify:
675         if (e->xproperty.atom == prop_atoms.net_desktop_names)
676             screen_update_desktop_names();
677         else if (e->xproperty.atom == prop_atoms.net_desktop_layout)
678             screen_update_layout();
679         break;
680     case ConfigureNotify:
681 #ifdef XRANDR
682         XRRUpdateConfiguration(e);
683 #endif
684         screen_resize();
685         break;
686     default:
687         ;
688     }
689 }
690
691 void event_enter_client(ObClient *client)
692 {
693     g_assert(config_focus_follow);
694
695     if (client_enter_focusable(client) && client_can_focus(client)) {
696         if (config_focus_delay) {
697             ObFocusDelayData *data;
698
699             ob_main_loop_timeout_remove(ob_main_loop, focus_delay_func);
700
701             data = g_new(ObFocusDelayData, 1);
702             data->client = client;
703             data->time = event_curtime;
704
705             ob_main_loop_timeout_add(ob_main_loop,
706                                      config_focus_delay,
707                                      focus_delay_func,
708                                      data, focus_delay_cmp, focus_delay_dest);
709         } else {
710             ObFocusDelayData data;
711             data.client = client;
712             data.time = event_curtime;
713             focus_delay_func(&data);
714         }
715     }
716 }
717
718 static void event_handle_user_time_window_clients(GSList *l, XEvent *e)
719 {
720     g_assert(e->type == PropertyNotify);
721     if (e->xproperty.atom == prop_atoms.net_wm_user_time) {
722         for (; l; l = g_slist_next(l))
723             client_update_user_time(l->data);
724     }
725 }
726
727 static void event_handle_client(ObClient *client, XEvent *e)
728 {
729     XEvent ce;
730     Atom msgtype;
731     ObFrameContext con;
732     static gint px = -1, py = -1;
733      
734     switch (e->type) {
735     case ButtonPress:
736         /* save where the press occured for the first button pressed */
737         if (px == -1) px = e->xbutton.x;
738         if (py == -1) py = e->xbutton.y;
739     case ButtonRelease:
740         /* Wheel buttons don't draw because they are an instant click, so it
741            is a waste of resources to go drawing it.
742            if the user is doing an intereactive thing, or has a menu open then
743            the mouse is grabbed (possibly) and if we get these events we don't
744            want to deal with them
745         */
746         if (!(e->xbutton.button == 4 || e->xbutton.button == 5) &&
747             !keyboard_interactively_grabbed() &&
748             !menu_frame_visible)
749         {
750             /* use where the press occured */
751             con = frame_context(client, e->xbutton.window, px, py);
752             con = mouse_button_frame_context(con, e->xbutton.button);
753
754             if (e->type == ButtonRelease)
755                 px = py = -1;
756
757             switch (con) {
758             case OB_FRAME_CONTEXT_MAXIMIZE:
759                 client->frame->max_press = (e->type == ButtonPress);
760                 framerender_frame(client->frame);
761                 break;
762             case OB_FRAME_CONTEXT_CLOSE:
763                 client->frame->close_press = (e->type == ButtonPress);
764                 framerender_frame(client->frame);
765                 break;
766             case OB_FRAME_CONTEXT_ICONIFY:
767                 client->frame->iconify_press = (e->type == ButtonPress);
768                 framerender_frame(client->frame);
769                 break;
770             case OB_FRAME_CONTEXT_ALLDESKTOPS:
771                 client->frame->desk_press = (e->type == ButtonPress);
772                 framerender_frame(client->frame);
773                 break; 
774             case OB_FRAME_CONTEXT_SHADE:
775                 client->frame->shade_press = (e->type == ButtonPress);
776                 framerender_frame(client->frame);
777                 break;
778             default:
779                 /* nothing changes with clicks for any other contexts */
780                 break;
781             }
782         }
783         break;
784     case LeaveNotify:
785         con = frame_context(client, e->xcrossing.window,
786                             e->xcrossing.x, e->xcrossing.y);
787         switch (con) {
788         case OB_FRAME_CONTEXT_MAXIMIZE:
789             client->frame->max_hover = FALSE;
790             frame_adjust_state(client->frame);
791             break;
792         case OB_FRAME_CONTEXT_ALLDESKTOPS:
793             client->frame->desk_hover = FALSE;
794             frame_adjust_state(client->frame);
795             break;
796         case OB_FRAME_CONTEXT_SHADE:
797             client->frame->shade_hover = FALSE;
798             frame_adjust_state(client->frame);
799             break;
800         case OB_FRAME_CONTEXT_ICONIFY:
801             client->frame->iconify_hover = FALSE;
802             frame_adjust_state(client->frame);
803             break;
804         case OB_FRAME_CONTEXT_CLOSE:
805             client->frame->close_hover = FALSE;
806             frame_adjust_state(client->frame);
807             break;
808         case OB_FRAME_CONTEXT_FRAME:
809             /* When the mouse leaves an animating window, don't use the
810                corresponding enter events. Pretend like the animating window
811                doesn't even exist..! */
812             if (frame_iconify_animating(client->frame))
813                 event_ignore_queued_enters();
814
815             ob_debug_type(OB_DEBUG_FOCUS,
816                           "%sNotify mode %d detail %d on %lx\n",
817                           (e->type == EnterNotify ? "Enter" : "Leave"),
818                           e->xcrossing.mode,
819                           e->xcrossing.detail, (client?client->window:0));
820             if (keyboard_interactively_grabbed())
821                 break;
822             if (config_focus_follow && config_focus_delay &&
823                 /* leave inferior events can happen when the mouse goes onto
824                    the window's border and then into the window before the
825                    delay is up */
826                 e->xcrossing.detail != NotifyInferior)
827             {
828                 ob_main_loop_timeout_remove_data(ob_main_loop,
829                                                  focus_delay_func,
830                                                  client, FALSE);
831             }
832             break;
833         default:
834             break;
835         }
836         break;
837     case EnterNotify:
838     {
839         gboolean nofocus = FALSE;
840
841         if (ignore_enter_focus) {
842             ignore_enter_focus--;
843             nofocus = TRUE;
844         }
845
846         con = frame_context(client, e->xcrossing.window,
847                             e->xcrossing.x, e->xcrossing.y);
848         switch (con) {
849         case OB_FRAME_CONTEXT_MAXIMIZE:
850             client->frame->max_hover = TRUE;
851             frame_adjust_state(client->frame);
852             break;
853         case OB_FRAME_CONTEXT_ALLDESKTOPS:
854             client->frame->desk_hover = TRUE;
855             frame_adjust_state(client->frame);
856             break;
857         case OB_FRAME_CONTEXT_SHADE:
858             client->frame->shade_hover = TRUE;
859             frame_adjust_state(client->frame);
860             break;
861         case OB_FRAME_CONTEXT_ICONIFY:
862             client->frame->iconify_hover = TRUE;
863             frame_adjust_state(client->frame);
864             break;
865         case OB_FRAME_CONTEXT_CLOSE:
866             client->frame->close_hover = TRUE;
867             frame_adjust_state(client->frame);
868             break;
869         case OB_FRAME_CONTEXT_FRAME:
870             if (keyboard_interactively_grabbed())
871                 break;
872             if (e->xcrossing.mode == NotifyGrab ||
873                 e->xcrossing.mode == NotifyUngrab ||
874                 /*ignore enters when we're already in the window */
875                 e->xcrossing.detail == NotifyInferior)
876             {
877                 ob_debug_type(OB_DEBUG_FOCUS,
878                               "%sNotify mode %d detail %d on %lx IGNORED\n",
879                               (e->type == EnterNotify ? "Enter" : "Leave"),
880                               e->xcrossing.mode,
881                               e->xcrossing.detail, client?client->window:0);
882             } else {
883                 ob_debug_type(OB_DEBUG_FOCUS,
884                               "%sNotify mode %d detail %d on %lx, "
885                               "focusing window: %d\n",
886                               (e->type == EnterNotify ? "Enter" : "Leave"),
887                               e->xcrossing.mode,
888                               e->xcrossing.detail, (client?client->window:0),
889                               !nofocus);
890                 if (!nofocus && config_focus_follow)
891                     event_enter_client(client);
892             }
893             break;
894         default:
895             break;
896         }
897         break;
898     }
899     case ConfigureRequest:
900         /* dont compress these unless you're going to watch for property
901            notifies in between (these can change what the configure would
902            do to the window).
903            also you can't compress stacking events
904         */
905
906         ob_debug("ConfigureRequest desktop %d wmstate %d vis %d\n",
907                  screen_desktop, client->wmstate, client->frame->visible);
908
909         /* don't allow clients to move shaded windows (fvwm does this) */
910         if (client->shaded) {
911             e->xconfigurerequest.value_mask &= ~CWX;
912             e->xconfigurerequest.value_mask &= ~CWY;
913         }
914
915         /* resize, then move, as specified in the EWMH section 7.7 */
916         if (e->xconfigurerequest.value_mask & (CWWidth | CWHeight |
917                                                CWX | CWY |
918                                                CWBorderWidth)) {
919             gint x, y, w, h;
920
921             if (e->xconfigurerequest.value_mask & CWBorderWidth)
922                 client->border_width = e->xconfigurerequest.border_width;
923
924             x = (e->xconfigurerequest.value_mask & CWX) ?
925                 e->xconfigurerequest.x : client->area.x;
926             y = (e->xconfigurerequest.value_mask & CWY) ?
927                 e->xconfigurerequest.y : client->area.y;
928             w = (e->xconfigurerequest.value_mask & CWWidth) ?
929                 e->xconfigurerequest.width : client->area.width;
930             h = (e->xconfigurerequest.value_mask & CWHeight) ?
931                 e->xconfigurerequest.height : client->area.height;
932
933             ob_debug("ConfigureRequest x %d %d y %d %d\n",
934                      e->xconfigurerequest.value_mask & CWX, x,
935                      e->xconfigurerequest.value_mask & CWY, y);
936
937             /* check for broken apps moving to their root position
938
939                XXX remove this some day...that would be nice. right now all
940                kde apps do this when they try activate themselves on another
941                desktop. eg. open amarok window on desktop 1, switch to desktop
942                2, click amarok tray icon. it will move by its decoration size.
943             */
944             if (x != client->area.x &&
945                 x == (client->frame->area.x + client->frame->size.left -
946                       (gint)client->border_width) &&
947                 y != client->area.y &&
948                 y == (client->frame->area.y + client->frame->size.top -
949                       (gint)client->border_width))
950             {
951                 ob_debug_type(OB_DEBUG_APP_BUGS,
952                               "Application %s is trying to move via "
953                               "ConfigureRequest to it's root window position "
954                               "but it is not using StaticGravity\n",
955                               client->title);
956                 /* don't move it */
957                 x = client->area.x;
958                 y = client->area.y;
959             }
960
961             client_find_onscreen(client, &x, &y, w, h, FALSE);
962             client_configure_full(client, x, y, w, h, FALSE, TRUE, TRUE);
963         }
964
965         if (e->xconfigurerequest.value_mask & CWStackMode) {
966             switch (e->xconfigurerequest.detail) {
967             case Below:
968             case BottomIf:
969                 /* Apps are so rude. And this is totally disconnected from
970                    activation/focus. Bleh. */
971                 /*client_lower(client);*/
972                 break;
973
974             case Above:
975             case TopIf:
976             default:
977                 /* Apps are so rude. And this is totally disconnected from
978                    activation/focus. Bleh. */
979                 /*client_raise(client);*/
980                 break;
981             }
982         }
983         break;
984     case UnmapNotify:
985         if (client->ignore_unmaps) {
986             client->ignore_unmaps--;
987             break;
988         }
989         ob_debug("UnmapNotify for window 0x%x eventwin 0x%x sendevent %d "
990                  "ignores left %d\n",
991                  client->window, e->xunmap.event, e->xunmap.from_configure,
992                  client->ignore_unmaps);
993         client_unmanage(client);
994         break;
995     case DestroyNotify:
996         ob_debug("DestroyNotify for window 0x%x\n", client->window);
997         client_unmanage(client);
998         break;
999     case ReparentNotify:
1000         /* this is when the client is first taken captive in the frame */
1001         if (e->xreparent.parent == client->frame->plate) break;
1002
1003         /*
1004           This event is quite rare and is usually handled in unmapHandler.
1005           However, if the window is unmapped when the reparent event occurs,
1006           the window manager never sees it because an unmap event is not sent
1007           to an already unmapped window.
1008         */
1009
1010         /* we don't want the reparent event, put it back on the stack for the
1011            X server to deal with after we unmanage the window */
1012         XPutBackEvent(ob_display, e);
1013      
1014         ob_debug("ReparentNotify for window 0x%x\n", client->window);
1015         client_unmanage(client);
1016         break;
1017     case MapRequest:
1018         ob_debug("MapRequest for 0x%lx\n", client->window);
1019         if (!client->iconic) break; /* this normally doesn't happen, but if it
1020                                        does, we don't want it!
1021                                        it can happen now when the window is on
1022                                        another desktop, but we still don't
1023                                        want it! */
1024         client_activate(client, FALSE, TRUE);
1025         break;
1026     case ClientMessage:
1027         /* validate cuz we query stuff off the client here */
1028         if (!client_validate(client)) break;
1029
1030         if (e->xclient.format != 32) return;
1031
1032         msgtype = e->xclient.message_type;
1033         if (msgtype == prop_atoms.wm_change_state) {
1034             /* compress changes into a single change */
1035             while (XCheckTypedWindowEvent(ob_display, client->window,
1036                                           e->type, &ce)) {
1037                 /* XXX: it would be nice to compress ALL messages of a
1038                    type, not just messages in a row without other
1039                    message types between. */
1040                 if (ce.xclient.message_type != msgtype) {
1041                     XPutBackEvent(ob_display, &ce);
1042                     break;
1043                 }
1044                 e->xclient = ce.xclient;
1045             }
1046             client_set_wm_state(client, e->xclient.data.l[0]);
1047         } else if (msgtype == prop_atoms.net_wm_desktop) {
1048             /* compress changes into a single change */
1049             while (XCheckTypedWindowEvent(ob_display, client->window,
1050                                           e->type, &ce)) {
1051                 /* XXX: it would be nice to compress ALL messages of a
1052                    type, not just messages in a row without other
1053                    message types between. */
1054                 if (ce.xclient.message_type != msgtype) {
1055                     XPutBackEvent(ob_display, &ce);
1056                     break;
1057                 }
1058                 e->xclient = ce.xclient;
1059             }
1060             if ((unsigned)e->xclient.data.l[0] < screen_num_desktops ||
1061                 (unsigned)e->xclient.data.l[0] == DESKTOP_ALL)
1062                 client_set_desktop(client, (unsigned)e->xclient.data.l[0],
1063                                    FALSE);
1064         } else if (msgtype == prop_atoms.net_wm_state) {
1065             /* can't compress these */
1066             ob_debug("net_wm_state %s %ld %ld for 0x%lx\n",
1067                      (e->xclient.data.l[0] == 0 ? "Remove" :
1068                       e->xclient.data.l[0] == 1 ? "Add" :
1069                       e->xclient.data.l[0] == 2 ? "Toggle" : "INVALID"),
1070                      e->xclient.data.l[1], e->xclient.data.l[2],
1071                      client->window);
1072             client_set_state(client, e->xclient.data.l[0],
1073                              e->xclient.data.l[1], e->xclient.data.l[2]);
1074         } else if (msgtype == prop_atoms.net_close_window) {
1075             ob_debug("net_close_window for 0x%lx\n", client->window);
1076             client_close(client);
1077         } else if (msgtype == prop_atoms.net_active_window) {
1078             ob_debug("net_active_window for 0x%lx source=%s\n",
1079                      client->window,
1080                      (e->xclient.data.l[0] == 0 ? "unknown" :
1081                       (e->xclient.data.l[0] == 1 ? "application" :
1082                        (e->xclient.data.l[0] == 2 ? "user" : "INVALID"))));
1083             /* XXX make use of data.l[2] !? */
1084             event_curtime = e->xclient.data.l[1];
1085             if (event_curtime == 0)
1086                 ob_debug_type(OB_DEBUG_APP_BUGS,
1087                               "_NET_ACTIVE_WINDOW message for window %s is "
1088                               "missing a timestamp\n", client->title);
1089             client_activate(client, FALSE,
1090                             (e->xclient.data.l[0] == 0 ||
1091                              e->xclient.data.l[0] == 2));
1092         } else if (msgtype == prop_atoms.net_wm_moveresize) {
1093             ob_debug("net_wm_moveresize for 0x%lx direction %d\n",
1094                      client->window, e->xclient.data.l[2]);
1095             if ((Atom)e->xclient.data.l[2] ==
1096                 prop_atoms.net_wm_moveresize_size_topleft ||
1097                 (Atom)e->xclient.data.l[2] ==
1098                 prop_atoms.net_wm_moveresize_size_top ||
1099                 (Atom)e->xclient.data.l[2] ==
1100                 prop_atoms.net_wm_moveresize_size_topright ||
1101                 (Atom)e->xclient.data.l[2] ==
1102                 prop_atoms.net_wm_moveresize_size_right ||
1103                 (Atom)e->xclient.data.l[2] ==
1104                 prop_atoms.net_wm_moveresize_size_right ||
1105                 (Atom)e->xclient.data.l[2] ==
1106                 prop_atoms.net_wm_moveresize_size_bottomright ||
1107                 (Atom)e->xclient.data.l[2] ==
1108                 prop_atoms.net_wm_moveresize_size_bottom ||
1109                 (Atom)e->xclient.data.l[2] ==
1110                 prop_atoms.net_wm_moveresize_size_bottomleft ||
1111                 (Atom)e->xclient.data.l[2] ==
1112                 prop_atoms.net_wm_moveresize_size_left ||
1113                 (Atom)e->xclient.data.l[2] ==
1114                 prop_atoms.net_wm_moveresize_move ||
1115                 (Atom)e->xclient.data.l[2] ==
1116                 prop_atoms.net_wm_moveresize_size_keyboard ||
1117                 (Atom)e->xclient.data.l[2] ==
1118                 prop_atoms.net_wm_moveresize_move_keyboard) {
1119
1120                 moveresize_start(client, e->xclient.data.l[0],
1121                                  e->xclient.data.l[1], e->xclient.data.l[3],
1122                                  e->xclient.data.l[2]);
1123             }
1124             else if ((Atom)e->xclient.data.l[2] ==
1125                      prop_atoms.net_wm_moveresize_cancel)
1126                 moveresize_end(TRUE);
1127         } else if (msgtype == prop_atoms.net_moveresize_window) {
1128             gint grav, x, y, w, h;
1129
1130             if (e->xclient.data.l[0] & 0xff)
1131                 grav = e->xclient.data.l[0] & 0xff;
1132             else 
1133                 grav = client->gravity;
1134
1135             if (e->xclient.data.l[0] & 1 << 8)
1136                 x = e->xclient.data.l[1];
1137             else
1138                 x = client->area.x;
1139             if (e->xclient.data.l[0] & 1 << 9)
1140                 y = e->xclient.data.l[2];
1141             else
1142                 y = client->area.y;
1143             if (e->xclient.data.l[0] & 1 << 10)
1144                 w = e->xclient.data.l[3];
1145             else
1146                 w = client->area.width;
1147             if (e->xclient.data.l[0] & 1 << 11)
1148                 h = e->xclient.data.l[4];
1149             else
1150                 h = client->area.height;
1151
1152             ob_debug("MOVERESIZE x %d %d y %d %d\n",
1153                      e->xclient.data.l[0] & 1 << 8, x,
1154                      e->xclient.data.l[0] & 1 << 9, y);
1155             client_convert_gravity(client, grav, &x, &y, w, h);
1156             client_find_onscreen(client, &x, &y, w, h, FALSE);
1157             client_configure(client, x, y, w, h, FALSE, TRUE);
1158         }
1159         break;
1160     case PropertyNotify:
1161         /* validate cuz we query stuff off the client here */
1162         if (!client_validate(client)) break;
1163   
1164         /* compress changes to a single property into a single change */
1165         while (XCheckTypedWindowEvent(ob_display, client->window,
1166                                       e->type, &ce)) {
1167             Atom a, b;
1168
1169             /* XXX: it would be nice to compress ALL changes to a property,
1170                not just changes in a row without other props between. */
1171
1172             a = ce.xproperty.atom;
1173             b = e->xproperty.atom;
1174
1175             if (a == b)
1176                 continue;
1177             if ((a == prop_atoms.net_wm_name ||
1178                  a == prop_atoms.wm_name ||
1179                  a == prop_atoms.net_wm_icon_name ||
1180                  a == prop_atoms.wm_icon_name)
1181                 &&
1182                 (b == prop_atoms.net_wm_name ||
1183                  b == prop_atoms.wm_name ||
1184                  b == prop_atoms.net_wm_icon_name ||
1185                  b == prop_atoms.wm_icon_name)) {
1186                 continue;
1187             }
1188             if (a == prop_atoms.net_wm_icon &&
1189                 b == prop_atoms.net_wm_icon)
1190                 continue;
1191
1192             XPutBackEvent(ob_display, &ce);
1193             break;
1194         }
1195
1196         msgtype = e->xproperty.atom;
1197         if (msgtype == XA_WM_NORMAL_HINTS) {
1198             client_update_normal_hints(client);
1199             /* normal hints can make a window non-resizable */
1200             client_setup_decor_and_functions(client);
1201         } else if (msgtype == XA_WM_HINTS) {
1202             client_update_wmhints(client);
1203         } else if (msgtype == XA_WM_TRANSIENT_FOR) {
1204             client_update_transient_for(client);
1205             client_get_type_and_transientness(client);
1206             /* type may have changed, so update the layer */
1207             client_calc_layer(client);
1208             client_setup_decor_and_functions(client);
1209         } else if (msgtype == prop_atoms.net_wm_name ||
1210                    msgtype == prop_atoms.wm_name ||
1211                    msgtype == prop_atoms.net_wm_icon_name ||
1212                    msgtype == prop_atoms.wm_icon_name) {
1213             client_update_title(client);
1214         } else if (msgtype == prop_atoms.wm_protocols) {
1215             client_update_protocols(client);
1216             client_setup_decor_and_functions(client);
1217         }
1218         else if (msgtype == prop_atoms.net_wm_strut) {
1219             client_update_strut(client);
1220         }
1221         else if (msgtype == prop_atoms.net_wm_icon) {
1222             client_update_icons(client);
1223         }
1224         else if (msgtype == prop_atoms.net_wm_icon_geometry) {
1225             client_update_icon_geometry(client);
1226         }
1227         else if (msgtype == prop_atoms.net_wm_user_time) {
1228             client_update_user_time(client);
1229         }
1230         else if (msgtype == prop_atoms.net_wm_user_time_window) {
1231             client_update_user_time_window(client);
1232         }
1233 #ifdef SYNC
1234         else if (msgtype == prop_atoms.net_wm_sync_request_counter) {
1235             client_update_sync_request_counter(client);
1236         }
1237 #endif
1238     case ColormapNotify:
1239         client_update_colormap(client, e->xcolormap.colormap);
1240         break;
1241     default:
1242         ;
1243 #ifdef SHAPE
1244         if (extensions_shape && e->type == extensions_shape_event_basep) {
1245             client->shaped = ((XShapeEvent*)e)->shaped;
1246             frame_adjust_shape(client->frame);
1247         }
1248 #endif
1249     }
1250 }
1251
1252 static void event_handle_dock(ObDock *s, XEvent *e)
1253 {
1254     switch (e->type) {
1255     case ButtonPress:
1256         if (e->xbutton.button == 1)
1257             stacking_raise(DOCK_AS_WINDOW(s));
1258         else if (e->xbutton.button == 2)
1259             stacking_lower(DOCK_AS_WINDOW(s));
1260         break;
1261     case EnterNotify:
1262         dock_hide(FALSE);
1263         break;
1264     case LeaveNotify:
1265         dock_hide(TRUE);
1266         break;
1267     }
1268 }
1269
1270 static void event_handle_dockapp(ObDockApp *app, XEvent *e)
1271 {
1272     switch (e->type) {
1273     case MotionNotify:
1274         dock_app_drag(app, &e->xmotion);
1275         break;
1276     case UnmapNotify:
1277         if (app->ignore_unmaps) {
1278             app->ignore_unmaps--;
1279             break;
1280         }
1281         dock_remove(app, TRUE);
1282         break;
1283     case DestroyNotify:
1284         dock_remove(app, FALSE);
1285         break;
1286     case ReparentNotify:
1287         dock_remove(app, FALSE);
1288         break;
1289     case ConfigureNotify:
1290         dock_app_configure(app, e->xconfigure.width, e->xconfigure.height);
1291         break;
1292     }
1293 }
1294
1295 static ObMenuFrame* find_active_menu()
1296 {
1297     GList *it;
1298     ObMenuFrame *ret = NULL;
1299
1300     for (it = menu_frame_visible; it; it = g_list_next(it)) {
1301         ret = it->data;
1302         if (ret->selected)
1303             break;
1304         ret = NULL;
1305     }
1306     return ret;
1307 }
1308
1309 static ObMenuFrame* find_active_or_last_menu()
1310 {
1311     ObMenuFrame *ret = NULL;
1312
1313     ret = find_active_menu();
1314     if (!ret && menu_frame_visible)
1315         ret = menu_frame_visible->data;
1316     return ret;
1317 }
1318
1319 static gboolean event_handle_menu_keyboard(XEvent *ev)
1320 {
1321     guint keycode, state;
1322     gunichar unikey;
1323     ObMenuFrame *frame;
1324     gboolean ret = TRUE;
1325
1326     keycode = ev->xkey.keycode;
1327     state = ev->xkey.state;
1328     unikey = translate_unichar(keycode);
1329
1330     frame = find_active_or_last_menu();
1331     if (frame == NULL)
1332         ret = FALSE;
1333
1334     else if (keycode == ob_keycode(OB_KEY_ESCAPE) && state == 0) {
1335         /* Escape closes the active menu */
1336         menu_frame_hide(frame);
1337     }
1338
1339     else if (keycode == ob_keycode(OB_KEY_RETURN) && (state == 0 ||
1340                                                       state == ControlMask))
1341     {
1342         /* Enter runs the active item or goes into the submenu.
1343            Control-Enter runs it without closing the menu. */
1344         if (frame->child)
1345             menu_frame_select_next(frame->child);
1346         else
1347             menu_entry_frame_execute(frame->selected, state, ev->xkey.time);
1348     }
1349
1350     else if (keycode == ob_keycode(OB_KEY_LEFT) && ev->xkey.state == 0) {
1351         /* Left goes to the parent menu */
1352         menu_frame_select(frame, NULL, TRUE);
1353     }
1354
1355     else if (keycode == ob_keycode(OB_KEY_RIGHT) && ev->xkey.state == 0) {
1356         /* Right goes to the selected submenu */
1357         if (frame->child) menu_frame_select_next(frame->child);
1358     }
1359
1360     else if (keycode == ob_keycode(OB_KEY_UP) && state == 0) {
1361         menu_frame_select_previous(frame);
1362     }
1363
1364     else if (keycode == ob_keycode(OB_KEY_DOWN) && state == 0) {
1365         menu_frame_select_next(frame);
1366     }
1367
1368     /* keyboard accelerator shortcuts. */
1369     else if (ev->xkey.state == 0 &&
1370              /* was it a valid key? */
1371              unikey != 0 &&
1372              /* don't bother if the menu is empty. */
1373              frame->entries)
1374     {
1375         GList *start;
1376         GList *it;
1377         ObMenuEntryFrame *found = NULL;
1378         guint num_found = 0;
1379
1380         /* start after the selected one */
1381         start = frame->entries;
1382         if (frame->selected) {
1383             for (it = start; frame->selected != it->data; it = g_list_next(it))
1384                 g_assert(it != NULL); /* nothing was selected? */
1385             /* next with wraparound */
1386             start = g_list_next(it);
1387             if (start == NULL) start = frame->entries;
1388         }
1389
1390         it = start;
1391         do {
1392             ObMenuEntryFrame *e = it->data;
1393             gunichar entrykey = 0;
1394
1395             if (e->entry->type == OB_MENU_ENTRY_TYPE_NORMAL)
1396                 entrykey = e->entry->data.normal.shortcut;
1397             else if (e->entry->type == OB_MENU_ENTRY_TYPE_SUBMENU)
1398                 entrykey = e->entry->data.submenu.submenu->shortcut;
1399
1400             if (unikey == entrykey) {
1401                 if (found == NULL) found = e;
1402                 ++num_found;
1403             }
1404
1405             /* next with wraparound */
1406             it = g_list_next(it);
1407             if (it == NULL) it = frame->entries;
1408         } while (it != start);
1409
1410         if (found) {
1411             if (found->entry->type == OB_MENU_ENTRY_TYPE_NORMAL &&
1412                 num_found == 1)
1413             {
1414                 menu_frame_select(frame, found, TRUE);
1415                 usleep(50000); /* highlight the item for a short bit so the
1416                                   user can see what happened */
1417                 menu_entry_frame_execute(found, state, ev->xkey.time);
1418             } else {
1419                 menu_frame_select(frame, found, TRUE);
1420                 if (num_found == 1)
1421                     menu_frame_select_next(frame->child);
1422             }
1423         } else
1424             ret = FALSE;
1425     }
1426     else
1427         ret = FALSE;
1428
1429     return ret;
1430 }
1431
1432 static gboolean event_handle_menu(XEvent *ev)
1433 {
1434     ObMenuFrame *f;
1435     ObMenuEntryFrame *e;
1436     gboolean ret = TRUE;
1437
1438     switch (ev->type) {
1439     case ButtonRelease:
1440         if ((ev->xbutton.button < 4 || ev->xbutton.button > 5)
1441             && menu_can_hide)
1442         {
1443             if ((e = menu_entry_frame_under(ev->xbutton.x_root,
1444                                             ev->xbutton.y_root)))
1445                 menu_entry_frame_execute(e, ev->xbutton.state,
1446                                          ev->xbutton.time);
1447             else
1448                 menu_frame_hide_all();
1449         }
1450         break;
1451     case EnterNotify:
1452         if ((e = g_hash_table_lookup(menu_frame_map, &ev->xcrossing.window))) {
1453             if (e->ignore_enters)
1454                 --e->ignore_enters;
1455             else
1456                 menu_frame_select(e->frame, e, FALSE);
1457         }
1458         break;
1459     case LeaveNotify:
1460         if ((e = g_hash_table_lookup(menu_frame_map, &ev->xcrossing.window)) &&
1461             (f = find_active_menu()) && f->selected == e &&
1462             e->entry->type != OB_MENU_ENTRY_TYPE_SUBMENU)
1463         {
1464             menu_frame_select(e->frame, NULL, FALSE);
1465         }
1466     case MotionNotify:   
1467         if ((e = menu_entry_frame_under(ev->xmotion.x_root,   
1468                                         ev->xmotion.y_root)))
1469             menu_frame_select(e->frame, e, FALSE);
1470         break;
1471     case KeyPress:
1472         ret = event_handle_menu_keyboard(ev);
1473         break;
1474     }
1475     return ret;
1476 }
1477
1478 static void event_handle_user_input(ObClient *client, XEvent *e)
1479 {
1480     g_assert(e->type == ButtonPress || e->type == ButtonRelease ||
1481              e->type == MotionNotify || e->type == KeyPress ||
1482              e->type == KeyRelease);
1483
1484     if (menu_frame_visible) {
1485         if (event_handle_menu(e))
1486             /* don't use the event if the menu used it, but if the menu
1487                didn't use it and it's a keypress that is bound, it will
1488                close the menu and be used */
1489             return;
1490     }
1491
1492     /* if the keyboard interactive action uses the event then dont
1493        use it for bindings. likewise is moveresize uses the event. */
1494     if (!keyboard_process_interactive_grab(e, &client) &&
1495         !(moveresize_in_progress && moveresize_event(e)))
1496     {
1497         if (moveresize_in_progress)
1498             /* make further actions work on the client being
1499                moved/resized */
1500             client = moveresize_client;
1501
1502         menu_can_hide = FALSE;
1503         ob_main_loop_timeout_add(ob_main_loop,
1504                                  config_menu_hide_delay * 1000,
1505                                  menu_hide_delay_func,
1506                                  NULL, g_direct_equal, NULL);
1507
1508         if (e->type == ButtonPress ||
1509             e->type == ButtonRelease ||
1510             e->type == MotionNotify)
1511         {
1512             /* the frame may not be "visible" but they can still click on it
1513                in the case where it is animating before disappearing */
1514             if (!client || !frame_iconify_animating(client->frame))
1515                 mouse_event(client, e);
1516         } else if (e->type == KeyPress) {
1517             keyboard_event((focus_cycle_target ? focus_cycle_target :
1518                             (client ? client : focus_client)), e);
1519         }
1520     }
1521 }
1522
1523 static gboolean menu_hide_delay_func(gpointer data)
1524 {
1525     menu_can_hide = TRUE;
1526     return FALSE; /* no repeat */
1527 }
1528
1529 static void focus_delay_dest(gpointer data)
1530 {
1531     g_free(data);
1532 }
1533
1534 static gboolean focus_delay_cmp(gconstpointer d1, gconstpointer d2)
1535 {
1536     const ObFocusDelayData *f1 = d1;
1537     return f1->client == d2;
1538 }
1539
1540 static gboolean focus_delay_func(gpointer data)
1541 {
1542     ObFocusDelayData *d = data;
1543     Time old = event_curtime;
1544
1545     event_curtime = d->time;
1546     if (focus_client != d->client) {
1547         if (client_focus(d->client) && config_focus_raise)
1548             client_raise(d->client);
1549     }
1550     event_curtime = old;
1551     return FALSE; /* no repeat */
1552 }
1553
1554 static void focus_delay_client_dest(ObClient *client, gpointer data)
1555 {
1556     ob_main_loop_timeout_remove_data(ob_main_loop, focus_delay_func,
1557                                      client, FALSE);
1558 }
1559
1560 void event_halt_focus_delay()
1561 {
1562     ob_main_loop_timeout_remove(ob_main_loop, focus_delay_func);
1563 }
1564
1565 void event_ignore_queued_enters()
1566 {
1567     GSList *saved = NULL, *it;
1568     XEvent *e;
1569                 
1570     XSync(ob_display, FALSE);
1571
1572     /* count the events */
1573     while (TRUE) {
1574         e = g_new(XEvent, 1);
1575         if (XCheckTypedEvent(ob_display, EnterNotify, e)) {
1576             ObWindow *win;
1577             
1578             win = g_hash_table_lookup(window_map, &e->xany.window);
1579             if (win && WINDOW_IS_CLIENT(win))
1580                 ++ignore_enter_focus;
1581             
1582             saved = g_slist_append(saved, e);
1583         } else {
1584             g_free(e);
1585             break;
1586         }
1587     }
1588     /* put the events back */
1589     for (it = saved; it; it = g_slist_next(it)) {
1590         XPutBackEvent(ob_display, it->data);
1591         g_free(it->data);
1592     }
1593     g_slist_free(saved);
1594 }
1595
1596 gboolean event_time_after(Time t1, Time t2)
1597 {
1598     g_assert(t1 != CurrentTime);
1599     g_assert(t2 != CurrentTime);
1600
1601     /*
1602       Timestamp values wrap around (after about 49.7 days). The server, given
1603       its current time is represented by timestamp T, always interprets
1604       timestamps from clients by treating half of the timestamp space as being
1605       later in time than T.
1606       - http://tronche.com/gui/x/xlib/input/pointer-grabbing.html
1607     */
1608
1609     /* TIME_HALF is half of the number space of a Time type variable */
1610 #define TIME_HALF (Time)(1 << (sizeof(Time)*8-1))
1611
1612     if (t2 >= TIME_HALF)
1613         /* t2 is in the second half so t1 might wrap around and be smaller than
1614            t2 */
1615         return t1 >= t2 || t1 < (t2 + TIME_HALF);
1616     else
1617         /* t2 is in the first half so t1 has to come after it */
1618         return t1 >= t2 && t1 < (t2 + TIME_HALF);
1619 }