]> Pileus Git - ~andy/gtk/blob - gdk/quartz/gdkevents-quartz.c
quartz: GdkQuartzWindow -> GdkQuartzNSWindow was forgotten in one place
[~andy/gtk] / gdk / quartz / gdkevents-quartz.c
1 /* gdkevents-quartz.c
2  *
3  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4  * Copyright (C) 1998-2002 Tor Lillqvist
5  * Copyright (C) 2005-2008 Imendio AB
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library 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 GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library. If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "config.h"
22 #include <sys/types.h>
23 #include <sys/sysctl.h>
24 #include <pthread.h>
25 #include <unistd.h>
26
27 #import <Cocoa/Cocoa.h>
28 #include <Carbon/Carbon.h>
29
30 #include <gdk/gdkdisplayprivate.h>
31
32 #include "gdkscreen.h"
33 #include "gdkkeysyms.h"
34 #include "gdkquartz.h"
35 #include "gdkquartzdisplay.h"
36 #include "gdkprivate-quartz.h"
37 #include "gdkquartzdevicemanager-core.h"
38
39 #define GRIP_WIDTH 15
40 #define GRIP_HEIGHT 15
41 #define GDK_LION_RESIZE 5
42
43 #define WINDOW_IS_TOPLEVEL(window)                   \
44   (GDK_WINDOW_TYPE (window) != GDK_WINDOW_CHILD &&   \
45    GDK_WINDOW_TYPE (window) != GDK_WINDOW_FOREIGN && \
46    GDK_WINDOW_TYPE (window) != GDK_WINDOW_OFFSCREEN)
47
48 /* This is the window corresponding to the key window */
49 static GdkWindow   *current_keyboard_window;
50
51
52 static void append_event                        (GdkEvent  *event,
53                                                  gboolean   windowing);
54
55 static GdkWindow *find_toplevel_under_pointer   (GdkDisplay *display,
56                                                  NSPoint     screen_point,
57                                                  gint       *x,
58                                                  gint       *y);
59
60
61 static void
62 gdk_quartz_ns_notification_callback (CFNotificationCenterRef  center,
63                                      void                    *observer,
64                                      CFStringRef              name,
65                                      const void              *object,
66                                      CFDictionaryRef          userInfo)
67 {
68   GdkEvent new_event;
69
70   new_event.type = GDK_SETTING;
71   new_event.setting.window = gdk_screen_get_root_window (_gdk_screen);
72   new_event.setting.send_event = FALSE;
73   new_event.setting.action = GDK_SETTING_ACTION_CHANGED;
74   new_event.setting.name = NULL;
75
76   /* Translate name */
77   if (CFStringCompare (name,
78                        CFSTR("AppleNoRedisplayAppearancePreferenceChanged"),
79                        0) == kCFCompareEqualTo)
80     new_event.setting.name = "gtk-primary-button-warps-slider";
81
82   if (!new_event.setting.name)
83     return;
84
85   gdk_event_put (&new_event);
86 }
87
88 static void
89 gdk_quartz_events_init_notifications (void)
90 {
91   static gboolean notifications_initialized = FALSE;
92
93   if (notifications_initialized)
94     return;
95   notifications_initialized = TRUE;
96
97   /* Initialize any handlers for notifications we want to push to GTK
98    * through GdkEventSettings.
99    */
100
101   /* This is an undocumented *distributed* notification to listen for changes
102    * in scrollbar jump behavior. It is used by LibreOffice and WebKit as well.
103    */
104   CFNotificationCenterAddObserver (CFNotificationCenterGetDistributedCenter (),
105                                    NULL,
106                                    &gdk_quartz_ns_notification_callback,
107                                    CFSTR ("AppleNoRedisplayAppearancePreferenceChanged"),
108                                    NULL,
109                                    CFNotificationSuspensionBehaviorDeliverImmediately);
110 }
111
112 void
113 _gdk_quartz_events_init (void)
114 {
115   _gdk_quartz_event_loop_init ();
116   gdk_quartz_events_init_notifications ();
117
118   current_keyboard_window = g_object_ref (_gdk_root);
119 }
120
121 gboolean
122 _gdk_quartz_display_has_pending (GdkDisplay *display)
123 {
124   return (_gdk_event_queue_find_first (display) ||
125          (_gdk_quartz_event_loop_check_pending ()));
126 }
127
128 void
129 _gdk_quartz_events_break_all_grabs (guint32 time)
130 {
131   GList *list, *l;
132   GdkDeviceManager *device_manager;
133
134   device_manager = gdk_display_get_device_manager (_gdk_display);
135   list = gdk_device_manager_list_devices (device_manager,
136                                           GDK_DEVICE_TYPE_MASTER);
137   for (l = list; l; l = l->next)
138     {
139       GdkDeviceGrabInfo *grab;
140
141       grab = _gdk_display_get_last_device_grab (_gdk_display, l->data);
142       if (grab)
143         {
144           grab->serial_end = 0;
145           grab->implicit_ungrab = TRUE;
146         }
147
148       _gdk_display_device_grab_update (_gdk_display, l->data, NULL, 0);
149     }
150
151   g_list_free (list);
152 }
153
154 static void
155 fixup_event (GdkEvent *event)
156 {
157   if (event->any.window)
158     g_object_ref (event->any.window);
159   if (((event->any.type == GDK_ENTER_NOTIFY) ||
160        (event->any.type == GDK_LEAVE_NOTIFY)) &&
161       (event->crossing.subwindow != NULL))
162     g_object_ref (event->crossing.subwindow);
163   event->any.send_event = FALSE;
164 }
165
166 static void
167 append_event (GdkEvent *event,
168               gboolean  windowing)
169 {
170   GList *node;
171
172   fixup_event (event);
173   node = _gdk_event_queue_append (_gdk_display, event);
174
175   if (windowing)
176     _gdk_windowing_got_event (_gdk_display, node, event, 0);
177 }
178
179 static gint
180 gdk_event_apply_filters (NSEvent *nsevent,
181                          GdkEvent *event,
182                          GList **filters)
183 {
184   GList *tmp_list;
185   GdkFilterReturn result;
186   
187   tmp_list = *filters;
188
189   while (tmp_list)
190     {
191       GdkEventFilter *filter = (GdkEventFilter*) tmp_list->data;
192       GList *node;
193
194       if ((filter->flags & GDK_EVENT_FILTER_REMOVED) != 0)
195         {
196           tmp_list = tmp_list->next;
197           continue;
198         }
199
200       filter->ref_count++;
201       result = filter->function (nsevent, event, filter->data);
202
203       /* get the next node after running the function since the
204          function may add or remove a next node */
205       node = tmp_list;
206       tmp_list = tmp_list->next;
207
208       filter->ref_count--;
209       if (filter->ref_count == 0)
210         {
211           *filters = g_list_remove_link (*filters, node);
212           g_list_free_1 (node);
213           g_free (filter);
214         }
215
216       if (result !=  GDK_FILTER_CONTINUE)
217         return result;
218     }
219
220   return GDK_FILTER_CONTINUE;
221 }
222
223 static guint32
224 get_time_from_ns_event (NSEvent *event)
225 {
226   double time = [event timestamp];
227
228   /* cast via double->uint64 conversion to make sure that it is
229    * wrapped on 32-bit machines when it overflows
230    */
231   return (guint32) (guint64) (time * 1000.0);
232 }
233
234 static int
235 get_mouse_button_from_ns_event (NSEvent *event)
236 {
237   NSInteger button;
238
239   button = [event buttonNumber];
240
241   switch (button)
242     {
243     case 0:
244       return 1;
245     case 1:
246       return 3;
247     case 2:
248       return 2;
249     default:
250       return button + 1;
251     }
252 }
253
254 static GdkModifierType
255 get_mouse_button_modifiers_from_ns_buttons (NSUInteger nsbuttons)
256 {
257   GdkModifierType modifiers = 0;
258
259   if (nsbuttons & (1 << 0))
260     modifiers |= GDK_BUTTON1_MASK;
261   if (nsbuttons & (1 << 1))
262     modifiers |= GDK_BUTTON3_MASK;
263   if (nsbuttons & (1 << 2))
264     modifiers |= GDK_BUTTON2_MASK;
265   if (nsbuttons & (1 << 3))
266     modifiers |= GDK_BUTTON4_MASK;
267   if (nsbuttons & (1 << 4))
268     modifiers |= GDK_BUTTON5_MASK;
269
270   return modifiers;
271 }
272
273 static GdkModifierType
274 get_mouse_button_modifiers_from_ns_event (NSEvent *event)
275 {
276   int button;
277   GdkModifierType state = 0;
278
279   /* This maps buttons 1 to 5 to GDK_BUTTON[1-5]_MASK */
280   button = get_mouse_button_from_ns_event (event);
281   if (button >= 1 && button <= 5)
282     state = (1 << (button + 7));
283
284   return state;
285 }
286
287 static GdkModifierType
288 get_keyboard_modifiers_from_ns_flags (NSUInteger nsflags)
289 {
290   GdkModifierType modifiers = 0;
291
292   if (nsflags & NSAlphaShiftKeyMask)
293     modifiers |= GDK_LOCK_MASK;
294   if (nsflags & NSShiftKeyMask)
295     modifiers |= GDK_SHIFT_MASK;
296   if (nsflags & NSControlKeyMask)
297     modifiers |= GDK_CONTROL_MASK;
298   if (nsflags & NSAlternateKeyMask)
299     modifiers |= GDK_MOD1_MASK;
300   if (nsflags & NSCommandKeyMask)
301     modifiers |= GDK_MOD2_MASK;
302
303   return modifiers;
304 }
305
306 static GdkModifierType
307 get_keyboard_modifiers_from_ns_event (NSEvent *nsevent)
308 {
309   return get_keyboard_modifiers_from_ns_flags ([nsevent modifierFlags]);
310 }
311
312 /* Return an event mask from an NSEvent */
313 static GdkEventMask
314 get_event_mask_from_ns_event (NSEvent *nsevent)
315 {
316   switch ([nsevent type])
317     {
318     case NSLeftMouseDown:
319     case NSRightMouseDown:
320     case NSOtherMouseDown:
321       return GDK_BUTTON_PRESS_MASK;
322     case NSLeftMouseUp:
323     case NSRightMouseUp:
324     case NSOtherMouseUp:
325       return GDK_BUTTON_RELEASE_MASK;
326     case NSMouseMoved:
327       return GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK;
328     case NSScrollWheel:
329       /* Since applications that want button press events can get
330        * scroll events on X11 (since scroll wheel events are really
331        * button press events there), we need to use GDK_BUTTON_PRESS_MASK too.
332        */
333       return GDK_SCROLL_MASK | GDK_BUTTON_PRESS_MASK;
334     case NSLeftMouseDragged:
335       return (GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK |
336               GDK_BUTTON_MOTION_MASK | GDK_BUTTON1_MOTION_MASK | 
337               GDK_BUTTON1_MASK);
338     case NSRightMouseDragged:
339       return (GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK |
340               GDK_BUTTON_MOTION_MASK | GDK_BUTTON3_MOTION_MASK | 
341               GDK_BUTTON3_MASK);
342     case NSOtherMouseDragged:
343       {
344         GdkEventMask mask;
345
346         mask = (GDK_POINTER_MOTION_MASK |
347                 GDK_POINTER_MOTION_HINT_MASK |
348                 GDK_BUTTON_MOTION_MASK);
349
350         if (get_mouse_button_from_ns_event (nsevent) == 2)
351           mask |= (GDK_BUTTON2_MOTION_MASK | GDK_BUTTON2_MOTION_MASK | 
352                    GDK_BUTTON2_MASK);
353
354         return mask;
355       }
356     case NSKeyDown:
357     case NSKeyUp:
358     case NSFlagsChanged:
359       {
360         switch (_gdk_quartz_keys_event_type (nsevent))
361           {
362           case GDK_KEY_PRESS:
363             return GDK_KEY_PRESS_MASK;
364           case GDK_KEY_RELEASE:
365             return GDK_KEY_RELEASE_MASK;
366           case GDK_NOTHING:
367             return 0;
368           default:
369             g_assert_not_reached ();
370           }
371       }
372       break;
373
374     case NSMouseEntered:
375       return GDK_ENTER_NOTIFY_MASK;
376
377     case NSMouseExited:
378       return GDK_LEAVE_NOTIFY_MASK;
379
380     default:
381       g_assert_not_reached ();
382     }
383
384   return 0;
385 }
386
387 static void
388 get_window_point_from_screen_point (GdkWindow *window,
389                                     NSPoint    screen_point,
390                                     gint      *x,
391                                     gint      *y)
392 {
393   NSPoint point;
394   NSWindow *nswindow;
395
396   nswindow = ((GdkWindowImplQuartz *)window->impl)->toplevel;
397
398   point = [nswindow convertScreenToBase:screen_point];
399
400   *x = point.x;
401   *y = window->height - point.y;
402 }
403
404 static gboolean
405 is_mouse_button_press_event (NSEventType type)
406 {
407   switch (type)
408     {
409       case NSLeftMouseDown:
410       case NSRightMouseDown:
411       case NSOtherMouseDown:
412         return TRUE;
413     }
414
415   return FALSE;
416 }
417
418 static GdkWindow *
419 get_toplevel_from_ns_event (NSEvent *nsevent,
420                             NSPoint *screen_point,
421                             gint    *x,
422                             gint    *y)
423 {
424   GdkWindow *toplevel = NULL;
425
426   if ([nsevent window])
427     {
428       GdkQuartzView *view;
429       NSPoint point, view_point;
430       NSRect view_frame;
431
432       view = (GdkQuartzView *)[[nsevent window] contentView];
433
434       toplevel = [view gdkWindow];
435
436       point = [nsevent locationInWindow];
437       view_point = [view convertPoint:point fromView:nil];
438       view_frame = [view frame];
439
440       /* NSEvents come in with a window set, but with window coordinates
441        * out of window bounds. For e.g. moved events this is fine, we use
442        * this information to properly handle enter/leave notify and motion
443        * events. For mouse button press/release, we want to avoid forwarding
444        * these events however, because the window they relate to is not the
445        * window set in the event. This situation appears to occur when button
446        * presses come in just before (or just after?) a window is resized and
447        * also when a button press occurs on the OS X window titlebar.
448        *
449        * By setting toplevel to NULL, we do another attempt to get the right
450        * toplevel window below.
451        */
452       if (is_mouse_button_press_event ([nsevent type]) &&
453           (view_point.x < view_frame.origin.x ||
454            view_point.x >= view_frame.origin.x + view_frame.size.width ||
455            view_point.y < view_frame.origin.y ||
456            view_point.y >= view_frame.origin.y + view_frame.size.height))
457         {
458           toplevel = NULL;
459
460           /* This is a hack for button presses to break all grabs. E.g. if
461            * a menu is open and one clicks on the title bar (or anywhere
462            * out of window bounds), we really want to pop down the menu (by
463            * breaking the grabs) before OS X handles the action of the title
464            * bar button.
465            *
466            * Because we cannot ingest this event into GDK, we have to do it
467            * here, not very nice.
468            */
469           _gdk_quartz_events_break_all_grabs (get_time_from_ns_event (nsevent));
470         }
471       else
472         {
473           *screen_point = [[nsevent window] convertBaseToScreen:point];
474
475           *x = point.x;
476           *y = toplevel->height - point.y;
477         }
478     }
479
480   if (!toplevel)
481     {
482       /* Fallback used when no NSWindow set.  This happens e.g. when
483        * we allow motion events without a window set in gdk_event_translate()
484        * that occur immediately after the main menu bar was clicked/used.
485        * This fallback will not return coordinates contained in a window's
486        * titlebar.
487        */
488       *screen_point = [NSEvent mouseLocation];
489       toplevel = find_toplevel_under_pointer (_gdk_display,
490                                               *screen_point,
491                                               x, y);
492     }
493
494   return toplevel;
495 }
496
497 static GdkEvent *
498 create_focus_event (GdkWindow *window,
499                     gboolean   in)
500 {
501   GdkEvent *event;
502   GdkQuartzDeviceManagerCore *device_manager;
503
504   event = gdk_event_new (GDK_FOCUS_CHANGE);
505   event->focus_change.window = window;
506   event->focus_change.in = in;
507
508   device_manager = GDK_QUARTZ_DEVICE_MANAGER_CORE (_gdk_display->device_manager);
509   gdk_event_set_device (event, device_manager->core_keyboard);
510
511   return event;
512 }
513
514
515 static void
516 generate_motion_event (GdkWindow *window)
517 {
518   NSPoint screen_point;
519   GdkEvent *event;
520   gint x, y, x_root, y_root;
521
522   event = gdk_event_new (GDK_MOTION_NOTIFY);
523   event->any.window = NULL;
524   event->any.send_event = TRUE;
525
526   screen_point = [NSEvent mouseLocation];
527
528   _gdk_quartz_window_nspoint_to_gdk_xy (screen_point, &x_root, &y_root);
529   get_window_point_from_screen_point (window, screen_point, &x, &y);
530
531   event->any.type = GDK_MOTION_NOTIFY;
532   event->motion.window = window;
533   event->motion.time = GDK_CURRENT_TIME;
534   event->motion.x = x;
535   event->motion.y = y;
536   event->motion.x_root = x_root;
537   event->motion.y_root = y_root;
538   /* FIXME event->axes */
539   event->motion.state = _gdk_quartz_events_get_current_keyboard_modifiers () |
540                         _gdk_quartz_events_get_current_mouse_modifiers ();
541   event->motion.is_hint = FALSE;
542   event->motion.device = _gdk_display->core_pointer;
543
544   append_event (event, TRUE);
545 }
546
547 /* Note: Used to both set a new focus window and to unset the old one. */
548 void
549 _gdk_quartz_events_update_focus_window (GdkWindow *window,
550                                         gboolean   got_focus)
551 {
552   GdkEvent *event;
553
554   if (got_focus && window == current_keyboard_window)
555     return;
556
557   /* FIXME: Don't do this when grabbed? Or make GdkQuartzNSWindow
558    * disallow it in the first place instead?
559    */
560   
561   if (!got_focus && window == current_keyboard_window)
562     {
563       event = create_focus_event (current_keyboard_window, FALSE);
564       append_event (event, FALSE);
565       g_object_unref (current_keyboard_window);
566       current_keyboard_window = NULL;
567     }
568
569   if (got_focus)
570     {
571       if (current_keyboard_window)
572         {
573           event = create_focus_event (current_keyboard_window, FALSE);
574           append_event (event, FALSE);
575           g_object_unref (current_keyboard_window);
576           current_keyboard_window = NULL;
577         }
578       
579       event = create_focus_event (window, TRUE);
580       append_event (event, FALSE);
581       current_keyboard_window = g_object_ref (window);
582
583       /* We just became the active window.  Unlike X11, Mac OS X does
584        * not send us motion events while the window does not have focus
585        * ("is not key").  We send a dummy motion notify event now, so that
586        * everything in the window is set to correct state.
587        */
588       generate_motion_event (window);
589     }
590 }
591
592 void
593 _gdk_quartz_events_send_enter_notify_event (GdkWindow *window)
594 {
595   NSPoint screen_point;
596   GdkEvent *event;
597   gint x, y, x_root, y_root;
598
599   event = gdk_event_new (GDK_ENTER_NOTIFY);
600   event->any.window = NULL;
601   event->any.send_event = FALSE;
602
603   screen_point = [NSEvent mouseLocation];
604
605   _gdk_quartz_window_nspoint_to_gdk_xy (screen_point, &x_root, &y_root);
606   get_window_point_from_screen_point (window, screen_point, &x, &y);
607
608   event->crossing.window = window;
609   event->crossing.subwindow = NULL;
610   event->crossing.time = GDK_CURRENT_TIME;
611   event->crossing.x = x;
612   event->crossing.y = y;
613   event->crossing.x_root = x_root;
614   event->crossing.y_root = y_root;
615   event->crossing.mode = GDK_CROSSING_NORMAL;
616   event->crossing.detail = GDK_NOTIFY_ANCESTOR;
617   event->crossing.state = _gdk_quartz_events_get_current_keyboard_modifiers () |
618                           _gdk_quartz_events_get_current_mouse_modifiers ();
619
620   gdk_event_set_device (event, _gdk_display->core_pointer);
621
622   append_event (event, TRUE);
623 }
624
625 void
626 _gdk_quartz_events_send_map_event (GdkWindow *window)
627 {
628   GdkWindowImplQuartz *impl = GDK_WINDOW_IMPL_QUARTZ (window->impl);
629
630   if (!impl->toplevel)
631     return;
632
633   if (window->event_mask & GDK_STRUCTURE_MASK)
634     {
635       GdkEvent event;
636
637       event.any.type = GDK_MAP;
638       event.any.window = window;
639   
640       gdk_event_put (&event);
641     }
642 }
643
644 static GdkWindow *
645 find_toplevel_under_pointer (GdkDisplay *display,
646                              NSPoint     screen_point,
647                              gint       *x,
648                              gint       *y)
649 {
650   GdkWindow *toplevel;
651   GdkPointerWindowInfo *info;
652
653   info = _gdk_display_get_pointer_info (display, display->core_pointer);
654   toplevel = info->toplevel_under_pointer;
655   if (toplevel && WINDOW_IS_TOPLEVEL (toplevel))
656     get_window_point_from_screen_point (toplevel, screen_point, x, y);
657
658   if (toplevel)
659     {
660       /* If the coordinates are out of window bounds, this toplevel is not
661        * under the pointer and we thus return NULL. This can occur when
662        * toplevel under pointer has not yet been updated due to a very recent
663        * window resize. Alternatively, we should no longer be relying on
664        * the toplevel_under_pointer value which is maintained in gdkwindow.c.
665        */
666       if (*x < 0 || *y < 0 || *x >= toplevel->width || *y >= toplevel->height)
667         return NULL;
668     }
669
670   return toplevel;
671 }
672
673 static GdkWindow *
674 find_toplevel_for_keyboard_event (NSEvent *nsevent)
675 {
676   GList *list, *l;
677   GdkWindow *window;
678   GdkDisplay *display;
679   GdkQuartzView *view;
680   GdkDeviceManager *device_manager;
681
682   view = (GdkQuartzView *)[[nsevent window] contentView];
683   window = [view gdkWindow];
684
685   display = gdk_window_get_display (window);
686
687   device_manager = gdk_display_get_device_manager (display);
688   list = gdk_device_manager_list_devices (device_manager,
689                                           GDK_DEVICE_TYPE_MASTER);
690   for (l = list; l; l = l->next)
691     {
692       GdkDeviceGrabInfo *grab;
693       GdkDevice *device = l->data;
694
695       if (gdk_device_get_source(device) != GDK_SOURCE_KEYBOARD)
696         continue;
697
698       grab = _gdk_display_get_last_device_grab (display, device);
699       if (grab && grab->window && !grab->owner_events)
700         {
701           window = gdk_window_get_effective_toplevel (grab->window);
702           break;
703         }
704     }
705
706   g_list_free (list);
707
708   return window;
709 }
710
711 static GdkWindow *
712 find_toplevel_for_mouse_event (NSEvent    *nsevent,
713                                gint       *x,
714                                gint       *y)
715 {
716   NSPoint screen_point;
717   NSEventType event_type;
718   GdkWindow *toplevel;
719   GdkDisplay *display;
720   GdkDeviceGrabInfo *grab;
721
722   toplevel = get_toplevel_from_ns_event (nsevent, &screen_point, x, y);
723
724   display = gdk_window_get_display (toplevel);
725
726   event_type = [nsevent type];
727
728   /* From the docs for XGrabPointer:
729    *
730    * If owner_events is True and if a generated pointer event
731    * would normally be reported to this client, it is reported
732    * as usual. Otherwise, the event is reported with respect to
733    * the grab_window and is reported only if selected by
734    * event_mask. For either value of owner_events, unreported
735    * events are discarded.
736    */
737   grab = _gdk_display_get_last_device_grab (display,
738                                             display->core_pointer);
739   if (WINDOW_IS_TOPLEVEL (toplevel) && grab)
740     {
741       /* Implicit grabs do not go through XGrabPointer and thus the
742        * event mask should not be checked.
743        */
744       if (!grab->implicit
745           && (grab->event_mask & get_event_mask_from_ns_event (nsevent)) == 0)
746         return NULL;
747
748       if (grab->owner_events)
749         {
750           /* For owner events, we need to use the toplevel under the
751            * pointer, not the window from the NSEvent, since that is
752            * reported with respect to the key window, which could be
753            * wrong.
754            */
755           GdkWindow *toplevel_under_pointer;
756           gint x_tmp, y_tmp;
757
758           toplevel_under_pointer = find_toplevel_under_pointer (display,
759                                                                 screen_point,
760                                                                 &x_tmp, &y_tmp);
761           if (toplevel_under_pointer)
762             {
763               toplevel = toplevel_under_pointer;
764               *x = x_tmp;
765               *y = y_tmp;
766             }
767
768           return toplevel;
769         }
770       else
771         {
772           /* Finally check the grab window. */
773           GdkWindow *grab_toplevel;
774
775           grab_toplevel = gdk_window_get_effective_toplevel (grab->window);
776           get_window_point_from_screen_point (grab_toplevel, screen_point,
777                                               x, y);
778
779           return grab_toplevel;
780         }
781
782       return NULL;
783     }
784   else 
785     {
786       /* The non-grabbed case. */
787       GdkWindow *toplevel_under_pointer;
788       gint x_tmp, y_tmp;
789
790       /* Ignore all events but mouse moved that might be on the title
791        * bar (above the content view). The reason is that otherwise
792        * gdk gets confused about getting e.g. button presses with no
793        * window (the title bar is not known to it).
794        */
795       if (event_type != NSMouseMoved)
796         if (*y < 0)
797           return NULL;
798
799       /* As for owner events, we need to use the toplevel under the
800        * pointer, not the window from the NSEvent.
801        */
802       toplevel_under_pointer = find_toplevel_under_pointer (display,
803                                                             screen_point,
804                                                             &x_tmp, &y_tmp);
805       if (toplevel_under_pointer
806           && WINDOW_IS_TOPLEVEL (toplevel_under_pointer))
807         {
808           GdkWindowImplQuartz *toplevel_impl;
809
810           toplevel = toplevel_under_pointer;
811
812           toplevel_impl = (GdkWindowImplQuartz *)toplevel->impl;
813
814           *x = x_tmp;
815           *y = y_tmp;
816         }
817
818       return toplevel;
819     }
820
821   return NULL;
822 }
823
824 /* This function finds the correct window to send an event to, taking
825  * into account grabs, event propagation, and event masks.
826  */
827 static GdkWindow *
828 find_window_for_ns_event (NSEvent *nsevent, 
829                           gint    *x, 
830                           gint    *y,
831                           gint    *x_root,
832                           gint    *y_root)
833 {
834   GdkQuartzView *view;
835   GdkWindow *toplevel;
836   NSPoint screen_point;
837   NSEventType event_type;
838
839   view = (GdkQuartzView *)[[nsevent window] contentView];
840
841   toplevel = get_toplevel_from_ns_event (nsevent, &screen_point, x, y);
842   if (!toplevel)
843     return NULL;
844   _gdk_quartz_window_nspoint_to_gdk_xy (screen_point, x_root, y_root);
845
846   event_type = [nsevent type];
847
848   switch (event_type)
849     {
850     case NSLeftMouseDown:
851     case NSRightMouseDown:
852     case NSOtherMouseDown:
853     case NSLeftMouseUp:
854     case NSRightMouseUp:
855     case NSOtherMouseUp:
856     case NSMouseMoved:
857     case NSScrollWheel:
858     case NSLeftMouseDragged:
859     case NSRightMouseDragged:
860     case NSOtherMouseDragged:
861       return find_toplevel_for_mouse_event (nsevent, x, y);
862       
863     case NSMouseEntered:
864     case NSMouseExited:
865       /* Only handle our own entered/exited events, not the ones for the
866        * titlebar buttons.
867        */
868       if ([view trackingRect] == [nsevent trackingNumber])
869         return toplevel;
870       else
871         return NULL;
872
873     case NSKeyDown:
874     case NSKeyUp:
875     case NSFlagsChanged:
876       return find_toplevel_for_keyboard_event (nsevent);
877
878     default:
879       /* Ignore everything else. */
880       break;
881     }
882
883   return NULL;
884 }
885
886 static void
887 fill_crossing_event (GdkWindow       *toplevel,
888                      GdkEvent        *event,
889                      NSEvent         *nsevent,
890                      gint             x,
891                      gint             y,
892                      gint             x_root,
893                      gint             y_root,
894                      GdkEventType     event_type,
895                      GdkCrossingMode  mode,
896                      GdkNotifyType    detail)
897 {
898   event->any.type = event_type;
899   event->crossing.window = toplevel;
900   event->crossing.subwindow = NULL;
901   event->crossing.time = get_time_from_ns_event (nsevent);
902   event->crossing.x = x;
903   event->crossing.y = y;
904   event->crossing.x_root = x_root;
905   event->crossing.y_root = y_root;
906   event->crossing.mode = mode;
907   event->crossing.detail = detail;
908   event->crossing.state = get_keyboard_modifiers_from_ns_event (nsevent) |
909                          _gdk_quartz_events_get_current_mouse_modifiers ();
910
911   gdk_event_set_device (event, _gdk_display->core_pointer);
912
913   /* FIXME: Focus and button state? */
914 }
915
916 static void
917 fill_button_event (GdkWindow *window,
918                    GdkEvent  *event,
919                    NSEvent   *nsevent,
920                    gint       x,
921                    gint       y,
922                    gint       x_root,
923                    gint       y_root)
924 {
925   GdkEventType type;
926   gint state;
927
928   state = get_keyboard_modifiers_from_ns_event (nsevent) |
929          _gdk_quartz_events_get_current_mouse_modifiers ();
930
931   switch ([nsevent type])
932     {
933     case NSLeftMouseDown:
934     case NSRightMouseDown:
935     case NSOtherMouseDown:
936       type = GDK_BUTTON_PRESS;
937       state &= ~get_mouse_button_modifiers_from_ns_event (nsevent);
938       break;
939
940     case NSLeftMouseUp:
941     case NSRightMouseUp:
942     case NSOtherMouseUp:
943       type = GDK_BUTTON_RELEASE;
944       state |= get_mouse_button_modifiers_from_ns_event (nsevent);
945       break;
946
947     default:
948       g_assert_not_reached ();
949     }
950
951   event->any.type = type;
952   event->button.window = window;
953   event->button.time = get_time_from_ns_event (nsevent);
954   event->button.x = x;
955   event->button.y = y;
956   event->button.x_root = x_root;
957   event->button.y_root = y_root;
958   /* FIXME event->axes */
959   event->button.state = state;
960   event->button.button = get_mouse_button_from_ns_event (nsevent);
961   event->button.device = _gdk_display->core_pointer;
962 }
963
964 static void
965 fill_motion_event (GdkWindow *window,
966                    GdkEvent  *event,
967                    NSEvent   *nsevent,
968                    gint       x,
969                    gint       y,
970                    gint       x_root,
971                    gint       y_root)
972 {
973   event->any.type = GDK_MOTION_NOTIFY;
974   event->motion.window = window;
975   event->motion.time = get_time_from_ns_event (nsevent);
976   event->motion.x = x;
977   event->motion.y = y;
978   event->motion.x_root = x_root;
979   event->motion.y_root = y_root;
980   /* FIXME event->axes */
981   event->motion.state = get_keyboard_modifiers_from_ns_event (nsevent) |
982                         _gdk_quartz_events_get_current_mouse_modifiers ();
983   event->motion.is_hint = FALSE;
984   event->motion.device = _gdk_display->core_pointer;
985 }
986
987 static void
988 fill_scroll_event (GdkWindow          *window,
989                    GdkEvent           *event,
990                    NSEvent            *nsevent,
991                    gint                x,
992                    gint                y,
993                    gint                x_root,
994                    gint                y_root,
995                    gdouble             delta_x,
996                    gdouble             delta_y,
997                    GdkScrollDirection  direction)
998 {
999   NSPoint point;
1000
1001   point = [nsevent locationInWindow];
1002
1003   event->any.type = GDK_SCROLL;
1004   event->scroll.window = window;
1005   event->scroll.time = get_time_from_ns_event (nsevent);
1006   event->scroll.x = x;
1007   event->scroll.y = y;
1008   event->scroll.x_root = x_root;
1009   event->scroll.y_root = y_root;
1010   event->scroll.state = get_keyboard_modifiers_from_ns_event (nsevent);
1011   event->scroll.direction = direction;
1012   event->scroll.device = _gdk_display->core_pointer;
1013   event->scroll.delta_x = delta_x;
1014   event->scroll.delta_y = delta_y;
1015 }
1016
1017 static void
1018 fill_key_event (GdkWindow    *window,
1019                 GdkEvent     *event,
1020                 NSEvent      *nsevent,
1021                 GdkEventType  type)
1022 {
1023   GdkEventPrivate *priv;
1024   GdkQuartzDeviceManagerCore *device_manager;
1025   gchar buf[7];
1026   gunichar c = 0;
1027
1028   priv = (GdkEventPrivate *) event;
1029   priv->windowing_data = [nsevent retain];
1030
1031   event->any.type = type;
1032   event->key.window = window;
1033   event->key.time = get_time_from_ns_event (nsevent);
1034   event->key.state = get_keyboard_modifiers_from_ns_event (nsevent);
1035   event->key.hardware_keycode = [nsevent keyCode];
1036   event->key.group = ([nsevent modifierFlags] & NSAlternateKeyMask) ? 1 : 0;
1037   event->key.keyval = GDK_KEY_VoidSymbol;
1038
1039   device_manager = GDK_QUARTZ_DEVICE_MANAGER_CORE (_gdk_display->device_manager);
1040   gdk_event_set_device (event, device_manager->core_keyboard);
1041   
1042   gdk_keymap_translate_keyboard_state (gdk_keymap_get_for_display (_gdk_display),
1043                                        event->key.hardware_keycode,
1044                                        event->key.state, 
1045                                        event->key.group,
1046                                        &event->key.keyval,
1047                                        NULL, NULL, NULL);
1048
1049   event->key.is_modifier = _gdk_quartz_keys_is_modifier (event->key.hardware_keycode);
1050
1051   /* If the key press is a modifier, the state should include the mask
1052    * for that modifier but only for releases, not presses. This
1053    * matches the X11 backend behavior.
1054    */
1055   if (event->key.is_modifier)
1056     {
1057       int mask = 0;
1058
1059       switch (event->key.keyval)
1060         {
1061         case GDK_KEY_Meta_R:
1062         case GDK_KEY_Meta_L:
1063           mask = GDK_MOD2_MASK;
1064           break;
1065         case GDK_KEY_Shift_R:
1066         case GDK_KEY_Shift_L:
1067           mask = GDK_SHIFT_MASK;
1068           break;
1069         case GDK_KEY_Caps_Lock:
1070           mask = GDK_LOCK_MASK;
1071           break;
1072         case GDK_KEY_Alt_R:
1073         case GDK_KEY_Alt_L:
1074           mask = GDK_MOD1_MASK;
1075           break;
1076         case GDK_KEY_Control_R:
1077         case GDK_KEY_Control_L:
1078           mask = GDK_CONTROL_MASK;
1079           break;
1080         default:
1081           mask = 0;
1082         }
1083
1084       if (type == GDK_KEY_PRESS)
1085         event->key.state &= ~mask;
1086       else if (type == GDK_KEY_RELEASE)
1087         event->key.state |= mask;
1088     }
1089
1090   event->key.state |= _gdk_quartz_events_get_current_mouse_modifiers ();
1091
1092   /* The X11 backend adds the first virtual modifier MOD2..MOD5 are
1093    * mapped to. Since we only have one virtual modifier in the quartz
1094    * backend, calling the standard function will do.
1095    */
1096   gdk_keymap_add_virtual_modifiers (gdk_keymap_get_for_display (_gdk_display),
1097                                     &event->key.state);
1098
1099   event->key.string = NULL;
1100
1101   /* Fill in ->string since apps depend on it, taken from the x11 backend. */
1102   if (event->key.keyval != GDK_KEY_VoidSymbol)
1103     c = gdk_keyval_to_unicode (event->key.keyval);
1104
1105   if (c)
1106     {
1107       gsize bytes_written;
1108       gint len;
1109
1110       len = g_unichar_to_utf8 (c, buf);
1111       buf[len] = '\0';
1112       
1113       event->key.string = g_locale_from_utf8 (buf, len,
1114                                               NULL, &bytes_written,
1115                                               NULL);
1116       if (event->key.string)
1117         event->key.length = bytes_written;
1118     }
1119   else if (event->key.keyval == GDK_KEY_Escape)
1120     {
1121       event->key.length = 1;
1122       event->key.string = g_strdup ("\033");
1123     }
1124   else if (event->key.keyval == GDK_KEY_Return ||
1125           event->key.keyval == GDK_KEY_KP_Enter)
1126     {
1127       event->key.length = 1;
1128       event->key.string = g_strdup ("\r");
1129     }
1130
1131   if (!event->key.string)
1132     {
1133       event->key.length = 0;
1134       event->key.string = g_strdup ("");
1135     }
1136
1137   GDK_NOTE(EVENTS,
1138     g_message ("key %s:\t\twindow: %p  key: %12s  %d",
1139           type == GDK_KEY_PRESS ? "press" : "release",
1140           event->key.window,
1141           event->key.keyval ? gdk_keyval_name (event->key.keyval) : "(none)",
1142           event->key.keyval));
1143 }
1144
1145 static gboolean
1146 synthesize_crossing_event (GdkWindow *window,
1147                            GdkEvent  *event,
1148                            NSEvent   *nsevent,
1149                            gint       x,
1150                            gint       y,
1151                            gint       x_root,
1152                            gint       y_root)
1153 {
1154   switch ([nsevent type])
1155     {
1156     case NSMouseEntered:
1157       /* Enter events are considered always to be from the root window as we
1158        * can't know for sure from what window we enter.
1159        */
1160       if (!(window->event_mask & GDK_ENTER_NOTIFY_MASK))
1161         return FALSE;
1162
1163       fill_crossing_event (window, event, nsevent,
1164                            x, y,
1165                            x_root, y_root,
1166                            GDK_ENTER_NOTIFY,
1167                            GDK_CROSSING_NORMAL,
1168                            GDK_NOTIFY_ANCESTOR);
1169       return TRUE;
1170
1171     case NSMouseExited:
1172       /* Exited always is to the root window as far as we are concerned,
1173        * since there is no way to reliably get information about what new
1174        * window is entered when exiting one.
1175        */
1176       if (!(window->event_mask & GDK_LEAVE_NOTIFY_MASK))
1177         return FALSE;
1178
1179       fill_crossing_event (window, event, nsevent,
1180                            x, y,
1181                            x_root, y_root,
1182                            GDK_LEAVE_NOTIFY,
1183                            GDK_CROSSING_NORMAL,
1184                            GDK_NOTIFY_ANCESTOR);
1185       return TRUE;
1186
1187     default:
1188       break;
1189     }
1190
1191   return FALSE;
1192 }
1193
1194 GdkModifierType
1195 _gdk_quartz_events_get_current_keyboard_modifiers (void)
1196 {
1197   if (gdk_quartz_osx_version () >= GDK_OSX_SNOW_LEOPARD)
1198     {
1199       return get_keyboard_modifiers_from_ns_flags ([NSClassFromString(@"NSEvent") modifierFlags]);
1200     }
1201   else
1202     {
1203       guint carbon_modifiers = GetCurrentKeyModifiers ();
1204       GdkModifierType modifiers = 0;
1205
1206       if (carbon_modifiers & alphaLock)
1207         modifiers |= GDK_LOCK_MASK;
1208       if (carbon_modifiers & shiftKey)
1209         modifiers |= GDK_SHIFT_MASK;
1210       if (carbon_modifiers & controlKey)
1211         modifiers |= GDK_CONTROL_MASK;
1212       if (carbon_modifiers & optionKey)
1213         modifiers |= GDK_MOD1_MASK;
1214       if (carbon_modifiers & cmdKey)
1215         modifiers |= GDK_MOD2_MASK;
1216
1217       return modifiers;
1218     }
1219 }
1220
1221 GdkModifierType
1222 _gdk_quartz_events_get_current_mouse_modifiers (void)
1223 {
1224   if (gdk_quartz_osx_version () >= GDK_OSX_SNOW_LEOPARD)
1225     {
1226       return get_mouse_button_modifiers_from_ns_buttons ([NSClassFromString(@"NSEvent") pressedMouseButtons]);
1227     }
1228   else
1229     {
1230       return get_mouse_button_modifiers_from_ns_buttons (GetCurrentButtonState ());
1231     }
1232 }
1233
1234 /* Detect window resizing */
1235
1236 static gboolean
1237 test_resize (NSEvent *event, GdkWindow *toplevel, gint x, gint y)
1238 {
1239   GdkWindowImplQuartz *toplevel_impl;
1240   gboolean lion;
1241
1242   /* Resizing from the resize indicator only begins if an NSLeftMouseButton
1243    * event is received in the resizing area.
1244    */
1245   toplevel_impl = (GdkWindowImplQuartz *)toplevel->impl;
1246   if ([toplevel_impl->toplevel showsResizeIndicator])
1247   if ([event type] == NSLeftMouseDown &&
1248       [toplevel_impl->toplevel showsResizeIndicator])
1249     {
1250       NSRect frame;
1251
1252       /* If the resize indicator is visible and the event
1253        * is in the lower right 15x15 corner, we leave these
1254        * events to Cocoa as to be handled as resize events.
1255        * Applications may have widgets in this area.  These
1256        * will most likely be larger than 15x15 and for
1257        * scroll bars there are also other means to move
1258        * the scroll bar.  Since the resize indicator is
1259        * the only way of resizing windows on Mac OS, it
1260        * is too important to not make functional.
1261        */
1262       frame = [toplevel_impl->view bounds];
1263       if (x > frame.size.width - GRIP_WIDTH &&
1264           x < frame.size.width &&
1265           y > frame.size.height - GRIP_HEIGHT &&
1266           y < frame.size.height)
1267         return TRUE;
1268      }
1269
1270   /* If we're on Lion and within 5 pixels of an edge,
1271    * then assume that the user wants to resize, and
1272    * return NULL to let Quartz get on with it. We check
1273    * the selector isRestorable to see if we're on 10.7.
1274    * This extra check is in case the user starts
1275    * dragging before GDK recognizes the grab.
1276    *
1277    * We perform this check for a button press of all buttons, because we
1278    * do receive, for instance, a right mouse down event for a GDK window
1279    * for x-coordinate range [-3, 0], but we do not want to forward this
1280    * into GDK. Forwarding such events into GDK will confuse the pointer
1281    * window finding code, because there are no GdkWindows present in
1282    * the range [-3, 0].
1283    */
1284   lion = gdk_quartz_osx_version () >= GDK_OSX_LION;
1285   if (lion &&
1286       ([event type] == NSLeftMouseDown ||
1287        [event type] == NSRightMouseDown ||
1288        [event type] == NSOtherMouseDown))
1289     {
1290       if (x < GDK_LION_RESIZE ||
1291           x > toplevel->width - GDK_LION_RESIZE ||
1292           y > toplevel->height - GDK_LION_RESIZE)
1293         return TRUE;
1294     }
1295
1296   return FALSE;
1297 }
1298
1299 static gboolean
1300 gdk_event_translate (GdkEvent *event,
1301                      NSEvent  *nsevent)
1302 {
1303   NSEventType event_type;
1304   NSWindow *nswindow;
1305   GdkWindow *window;
1306   int x, y;
1307   int x_root, y_root;
1308   gboolean return_val;
1309
1310   /* There is no support for real desktop wide grabs, so we break
1311    * grabs when the application loses focus (gets deactivated).
1312    */
1313   event_type = [nsevent type];
1314   if (event_type == NSAppKitDefined)
1315     {
1316       if ([nsevent subtype] == NSApplicationDeactivatedEventType)
1317         _gdk_quartz_events_break_all_grabs (get_time_from_ns_event (nsevent));
1318
1319       /* This could potentially be used to break grabs when clicking
1320        * on the title. The subtype 20 is undocumented so it's probably
1321        * not a good idea: else if (subtype == 20) break_all_grabs ();
1322        */
1323
1324       /* Leave all AppKit events to AppKit. */
1325       return FALSE;
1326     }
1327
1328   if (_gdk_default_filters)
1329     {
1330       /* Apply global filters */
1331       GdkFilterReturn result;
1332
1333       result = gdk_event_apply_filters (nsevent, event, &_gdk_default_filters);
1334       if (result != GDK_FILTER_CONTINUE)
1335         {
1336           return_val = (result == GDK_FILTER_TRANSLATE) ? TRUE : FALSE;
1337           goto done;
1338         }
1339     }
1340
1341   nswindow = [nsevent window];
1342
1343   /* Ignore events for windows not created by GDK. */
1344   if (nswindow && ![[nswindow contentView] isKindOfClass:[GdkQuartzView class]])
1345     return FALSE;
1346
1347   /* Ignore events for ones with no windows */
1348   if (!nswindow)
1349     {
1350       GdkWindow *toplevel = NULL;
1351
1352       if (event_type == NSMouseMoved)
1353         {
1354           /* Motion events received after clicking the menu bar do not have the
1355            * window field set.  Instead of giving up on the event immediately,
1356            * we first check whether this event is within our window bounds.
1357            */
1358           NSPoint screen_point = [NSEvent mouseLocation];
1359           gint x_tmp, y_tmp;
1360
1361           toplevel = find_toplevel_under_pointer (_gdk_display,
1362                                                   screen_point,
1363                                                   &x_tmp, &y_tmp);
1364         }
1365
1366       if (!toplevel)
1367         return FALSE;
1368     }
1369
1370   /* Ignore events and break grabs while the window is being
1371    * dragged. This is a workaround for the window getting events for
1372    * the window title.
1373    */
1374   if ([(GdkQuartzNSWindow *)nswindow isInMove])
1375     {
1376       _gdk_quartz_events_break_all_grabs (get_time_from_ns_event (nsevent));
1377       return FALSE;
1378     }
1379
1380   /* Also when in a manual resize, we ignore events so that these are
1381    * pushed to GdkQuartzNSWindow's sendEvent handler.
1382    */
1383   if ([(GdkQuartzNSWindow *)nswindow isInManualResize])
1384     return FALSE;
1385
1386   /* Find the right GDK window to send the event to, taking grabs and
1387    * event masks into consideration.
1388    */
1389   window = find_window_for_ns_event (nsevent, &x, &y, &x_root, &y_root);
1390   if (!window)
1391     return FALSE;
1392
1393   /* Quartz handles resizing on its own, so we want to stay out of the way. */
1394   if (test_resize (nsevent, window, x, y))
1395     return FALSE;
1396
1397   /* Apply any window filters. */
1398   if (GDK_IS_WINDOW (window))
1399     {
1400       GdkFilterReturn result;
1401
1402       if (window->filters)
1403         {
1404           g_object_ref (window);
1405
1406           result = gdk_event_apply_filters (nsevent, event, &window->filters);
1407
1408           g_object_unref (window);
1409
1410           if (result != GDK_FILTER_CONTINUE)
1411             {
1412               return_val = (result == GDK_FILTER_TRANSLATE) ? TRUE : FALSE;
1413               goto done;
1414             }
1415         }
1416     }
1417
1418   /* If the app is not active leave the event to AppKit so the window gets
1419    * focused correctly and don't do click-through (so we behave like most
1420    * native apps). If the app is active, we focus the window and then handle
1421    * the event, also to match native apps.
1422    */
1423   if ((event_type == NSRightMouseDown ||
1424        event_type == NSOtherMouseDown ||
1425        event_type == NSLeftMouseDown))
1426     {
1427       GdkWindowImplQuartz *impl = GDK_WINDOW_IMPL_QUARTZ (window->impl);
1428
1429       if (![NSApp isActive])
1430         {
1431           [NSApp activateIgnoringOtherApps:YES];
1432           return FALSE;
1433         }
1434       else if (![impl->toplevel isKeyWindow])
1435         {
1436           GdkDeviceGrabInfo *grab;
1437
1438           grab = _gdk_display_get_last_device_grab (_gdk_display,
1439                                                     _gdk_display->core_pointer);
1440           if (!grab)
1441             [impl->toplevel makeKeyWindow];
1442         }
1443     }
1444
1445   return_val = TRUE;
1446
1447   switch (event_type)
1448     {
1449     case NSLeftMouseDown:
1450     case NSRightMouseDown:
1451     case NSOtherMouseDown:
1452     case NSLeftMouseUp:
1453     case NSRightMouseUp:
1454     case NSOtherMouseUp:
1455       fill_button_event (window, event, nsevent, x, y, x_root, y_root);
1456       break;
1457
1458     case NSLeftMouseDragged:
1459     case NSRightMouseDragged:
1460     case NSOtherMouseDragged:
1461     case NSMouseMoved:
1462       fill_motion_event (window, event, nsevent, x, y, x_root, y_root);
1463       break;
1464
1465     case NSScrollWheel:
1466       {
1467         GdkScrollDirection direction;
1468         float dx;
1469         float dy;
1470 #ifdef AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER
1471         if (gdk_quartz_osx_version() >= GDK_OSX_LION &&
1472             [nsevent hasPreciseScrollingDeltas])
1473           {
1474             dx = [nsevent scrollingDeltaX];
1475             dy = [nsevent scrollingDeltaY];
1476             direction = GDK_SCROLL_SMOOTH;
1477
1478             fill_scroll_event (window, event, nsevent, x, y, x_root, y_root,
1479                                -dx, -dy, direction);
1480
1481             /* Fall through for scroll buttons emulation */
1482           }
1483 #endif
1484         dx = [nsevent deltaX];
1485         dy = [nsevent deltaY];
1486
1487         if (dy != 0.0)
1488           {
1489             if (dy < 0.0)
1490               direction = GDK_SCROLL_DOWN;
1491             else
1492               direction = GDK_SCROLL_UP;
1493
1494             dy = fabs (dy);
1495             dx = 0.0;
1496           }
1497         else if (dx != 0.0)
1498           {
1499             if (dx < 0.0)
1500               direction = GDK_SCROLL_RIGHT;
1501             else
1502               direction = GDK_SCROLL_LEFT;
1503
1504             dx = fabs (dx);
1505             dy = 0.0;
1506           }
1507
1508         if (dx != 0.0 || dy != 0.0)
1509           {
1510 #ifdef AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER
1511             if (gdk_quartz_osx_version() >= GDK_OSX_LION &&
1512                 [nsevent hasPreciseScrollingDeltas])
1513               {
1514                 GdkEvent *emulated_event;
1515
1516                 emulated_event = gdk_event_new (GDK_SCROLL);
1517                 _gdk_event_set_pointer_emulated (emulated_event, TRUE);
1518                 fill_scroll_event (window, emulated_event, nsevent,
1519                                    x, y, x_root, y_root,
1520                                    dx, dy, direction);
1521                 append_event (emulated_event, TRUE);
1522               }
1523             else
1524 #endif
1525               fill_scroll_event (window, event, nsevent,
1526                                  x, y, x_root, y_root,
1527                                  dx, dy, direction);
1528           }
1529       }
1530       break;
1531
1532     case NSMouseEntered:
1533     case NSMouseExited:
1534       return_val = synthesize_crossing_event (window, event, nsevent, x, y, x_root, y_root);
1535       break;
1536
1537     case NSKeyDown:
1538     case NSKeyUp:
1539     case NSFlagsChanged:
1540       {
1541         GdkEventType type;
1542
1543         type = _gdk_quartz_keys_event_type (nsevent);
1544         if (type == GDK_NOTHING)
1545           return_val = FALSE;
1546         else
1547           fill_key_event (window, event, nsevent, type);
1548       }
1549       break;
1550
1551     default:
1552       /* Ignore everything elsee. */
1553       return_val = FALSE;
1554       break;
1555     }
1556
1557  done:
1558   if (return_val)
1559     {
1560       if (event->any.window)
1561         g_object_ref (event->any.window);
1562       if (((event->any.type == GDK_ENTER_NOTIFY) ||
1563            (event->any.type == GDK_LEAVE_NOTIFY)) &&
1564           (event->crossing.subwindow != NULL))
1565         g_object_ref (event->crossing.subwindow);
1566     }
1567   else
1568     {
1569       /* Mark this event as having no resources to be freed */
1570       event->any.window = NULL;
1571       event->any.type = GDK_NOTHING;
1572     }
1573
1574   return return_val;
1575 }
1576
1577 void
1578 _gdk_quartz_display_queue_events (GdkDisplay *display)
1579 {  
1580   NSEvent *nsevent;
1581
1582   nsevent = _gdk_quartz_event_loop_get_pending ();
1583   if (nsevent)
1584     {
1585       GdkEvent *event;
1586       GList *node;
1587
1588       event = gdk_event_new (GDK_NOTHING);
1589
1590       event->any.window = NULL;
1591       event->any.send_event = FALSE;
1592
1593       ((GdkEventPrivate *)event)->flags |= GDK_EVENT_PENDING;
1594
1595       node = _gdk_event_queue_append (display, event);
1596
1597       if (gdk_event_translate (event, nsevent))
1598         {
1599           ((GdkEventPrivate *)event)->flags &= ~GDK_EVENT_PENDING;
1600           _gdk_windowing_got_event (display, node, event, 0);
1601         }
1602       else
1603         {
1604           _gdk_event_queue_remove_link (display, node);
1605           g_list_free_1 (node);
1606           gdk_event_free (event);
1607
1608           gdk_threads_leave ();
1609           [NSApp sendEvent:nsevent];
1610           gdk_threads_enter ();
1611         }
1612
1613       _gdk_quartz_event_loop_release_event (nsevent);
1614     }
1615 }
1616
1617 void
1618 _gdk_quartz_screen_broadcast_client_message (GdkScreen *screen,
1619                                              GdkEvent  *event)
1620 {
1621   /* Not supported. */
1622 }
1623
1624 gboolean
1625 _gdk_quartz_screen_get_setting (GdkScreen   *screen,
1626                                 const gchar *name,
1627                                 GValue      *value)
1628 {
1629   if (strcmp (name, "gtk-double-click-time") == 0)
1630     {
1631       NSUserDefaults *defaults;
1632       float t;
1633
1634       GDK_QUARTZ_ALLOC_POOL;
1635
1636       defaults = [NSUserDefaults standardUserDefaults];
1637             
1638       t = [defaults floatForKey:@"com.apple.mouse.doubleClickThreshold"];
1639       if (t == 0.0)
1640         {
1641           /* No user setting, use the default in OS X. */
1642           t = 0.5;
1643         }
1644
1645       GDK_QUARTZ_RELEASE_POOL;
1646
1647       g_value_set_int (value, t * 1000);
1648
1649       return TRUE;
1650     }
1651   else if (strcmp (name, "gtk-font-name") == 0)
1652     {
1653       NSString *name;
1654       char *str;
1655
1656       GDK_QUARTZ_ALLOC_POOL;
1657
1658       name = [[NSFont systemFontOfSize:0] familyName];
1659
1660       /* Let's try to use the "views" font size (12pt) by default. This is
1661        * used for lists/text/other "content" which is the largest parts of
1662        * apps, using the "regular control" size (13pt) looks a bit out of
1663        * place. We might have to tweak this.
1664        */
1665
1666       /* The size has to be hardcoded as there doesn't seem to be a way to
1667        * get the views font size programmatically.
1668        */
1669       str = g_strdup_printf ("%s 12", [name UTF8String]);
1670       g_value_set_string (value, str);
1671       g_free (str);
1672
1673       GDK_QUARTZ_RELEASE_POOL;
1674
1675       return TRUE;
1676     }
1677   else if (strcmp (name, "gtk-primary-button-warps-slider") == 0)
1678     {
1679       GDK_QUARTZ_ALLOC_POOL;
1680
1681       BOOL setting = [[NSUserDefaults standardUserDefaults] boolForKey:@"AppleScrollerPagingBehavior"];
1682
1683       /* If the Apple property is YES, it means "warp" */
1684       g_value_set_boolean (value, setting == YES);
1685
1686       GDK_QUARTZ_RELEASE_POOL;
1687
1688       return TRUE;
1689     }
1690   
1691   /* FIXME: Add more settings */
1692
1693   return FALSE;
1694 }
1695
1696 void
1697 _gdk_quartz_display_event_data_copy (GdkDisplay     *display,
1698                                      const GdkEvent *src,
1699                                      GdkEvent       *dst)
1700 {
1701   GdkEventPrivate *priv_src = (GdkEventPrivate *) src;
1702   GdkEventPrivate *priv_dst = (GdkEventPrivate *) dst;
1703
1704   if (priv_src->windowing_data)
1705     {
1706       priv_dst->windowing_data = priv_src->windowing_data;
1707       [(NSEvent *)priv_dst->windowing_data retain];
1708     }
1709 }
1710
1711 void
1712 _gdk_quartz_display_event_data_free (GdkDisplay *display,
1713                                      GdkEvent   *event)
1714 {
1715   GdkEventPrivate *priv = (GdkEventPrivate *) event;
1716
1717   if (priv->windowing_data)
1718     {
1719       [(NSEvent *)priv->windowing_data release];
1720       priv->windowing_data = NULL;
1721     }
1722 }