]> Pileus Git - ~andy/gtk/blob - gdk/quartz/gdkevents-quartz.c
GdkDisplay: handle multiple calls to _gdk_display_pause_events()
[~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 = get_time_from_ns_event ([NSApp currentEvent]);
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_map_event (GdkWindow *window)
594 {
595   GdkWindowImplQuartz *impl = GDK_WINDOW_IMPL_QUARTZ (window->impl);
596
597   if (!impl->toplevel)
598     return;
599
600   if (window->event_mask & GDK_STRUCTURE_MASK)
601     {
602       GdkEvent event;
603
604       event.any.type = GDK_MAP;
605       event.any.window = window;
606   
607       gdk_event_put (&event);
608     }
609 }
610
611 static GdkWindow *
612 find_toplevel_under_pointer (GdkDisplay *display,
613                              NSPoint     screen_point,
614                              gint       *x,
615                              gint       *y)
616 {
617   GdkWindow *toplevel;
618   GdkPointerWindowInfo *info;
619
620   info = _gdk_display_get_pointer_info (display, display->core_pointer);
621   toplevel = info->toplevel_under_pointer;
622   if (toplevel && WINDOW_IS_TOPLEVEL (toplevel))
623     get_window_point_from_screen_point (toplevel, screen_point, x, y);
624
625   if (toplevel)
626     {
627       /* If the coordinates are out of window bounds, this toplevel is not
628        * under the pointer and we thus return NULL. This can occur when
629        * toplevel under pointer has not yet been updated due to a very recent
630        * window resize. Alternatively, we should no longer be relying on
631        * the toplevel_under_pointer value which is maintained in gdkwindow.c.
632        */
633       if (*x < 0 || *y < 0 || *x >= toplevel->width || *y >= toplevel->height)
634         return NULL;
635     }
636
637   return toplevel;
638 }
639
640 static GdkWindow *
641 find_toplevel_for_keyboard_event (NSEvent *nsevent)
642 {
643   GList *list, *l;
644   GdkWindow *window;
645   GdkDisplay *display;
646   GdkQuartzView *view;
647   GdkDeviceManager *device_manager;
648
649   view = (GdkQuartzView *)[[nsevent window] contentView];
650   window = [view gdkWindow];
651
652   display = gdk_window_get_display (window);
653
654   device_manager = gdk_display_get_device_manager (display);
655   list = gdk_device_manager_list_devices (device_manager,
656                                           GDK_DEVICE_TYPE_MASTER);
657   for (l = list; l; l = l->next)
658     {
659       GdkDeviceGrabInfo *grab;
660       GdkDevice *device = l->data;
661
662       if (gdk_device_get_source(device) != GDK_SOURCE_KEYBOARD)
663         continue;
664
665       grab = _gdk_display_get_last_device_grab (display, device);
666       if (grab && grab->window && !grab->owner_events)
667         {
668           window = gdk_window_get_effective_toplevel (grab->window);
669           break;
670         }
671     }
672
673   g_list_free (list);
674
675   return window;
676 }
677
678 static GdkWindow *
679 find_toplevel_for_mouse_event (NSEvent    *nsevent,
680                                gint       *x,
681                                gint       *y)
682 {
683   NSPoint screen_point;
684   NSEventType event_type;
685   GdkWindow *toplevel;
686   GdkDisplay *display;
687   GdkDeviceGrabInfo *grab;
688
689   toplevel = get_toplevel_from_ns_event (nsevent, &screen_point, x, y);
690
691   display = gdk_window_get_display (toplevel);
692
693   event_type = [nsevent type];
694
695   /* From the docs for XGrabPointer:
696    *
697    * If owner_events is True and if a generated pointer event
698    * would normally be reported to this client, it is reported
699    * as usual. Otherwise, the event is reported with respect to
700    * the grab_window and is reported only if selected by
701    * event_mask. For either value of owner_events, unreported
702    * events are discarded.
703    */
704   grab = _gdk_display_get_last_device_grab (display,
705                                             display->core_pointer);
706   if (WINDOW_IS_TOPLEVEL (toplevel) && grab)
707     {
708       /* Implicit grabs do not go through XGrabPointer and thus the
709        * event mask should not be checked.
710        */
711       if (!grab->implicit
712           && (grab->event_mask & get_event_mask_from_ns_event (nsevent)) == 0)
713         return NULL;
714
715       if (grab->owner_events)
716         {
717           /* For owner events, we need to use the toplevel under the
718            * pointer, not the window from the NSEvent, since that is
719            * reported with respect to the key window, which could be
720            * wrong.
721            */
722           GdkWindow *toplevel_under_pointer;
723           gint x_tmp, y_tmp;
724
725           toplevel_under_pointer = find_toplevel_under_pointer (display,
726                                                                 screen_point,
727                                                                 &x_tmp, &y_tmp);
728           if (toplevel_under_pointer)
729             {
730               toplevel = toplevel_under_pointer;
731               *x = x_tmp;
732               *y = y_tmp;
733             }
734
735           return toplevel;
736         }
737       else
738         {
739           /* Finally check the grab window. */
740           GdkWindow *grab_toplevel;
741
742           grab_toplevel = gdk_window_get_effective_toplevel (grab->window);
743           get_window_point_from_screen_point (grab_toplevel, screen_point,
744                                               x, y);
745
746           return grab_toplevel;
747         }
748
749       return NULL;
750     }
751   else 
752     {
753       /* The non-grabbed case. */
754       GdkWindow *toplevel_under_pointer;
755       gint x_tmp, y_tmp;
756
757       /* Ignore all events but mouse moved that might be on the title
758        * bar (above the content view). The reason is that otherwise
759        * gdk gets confused about getting e.g. button presses with no
760        * window (the title bar is not known to it).
761        */
762       if (event_type != NSMouseMoved)
763         if (*y < 0)
764           return NULL;
765
766       /* As for owner events, we need to use the toplevel under the
767        * pointer, not the window from the NSEvent.
768        */
769       toplevel_under_pointer = find_toplevel_under_pointer (display,
770                                                             screen_point,
771                                                             &x_tmp, &y_tmp);
772       if (toplevel_under_pointer
773           && WINDOW_IS_TOPLEVEL (toplevel_under_pointer))
774         {
775           GdkWindowImplQuartz *toplevel_impl;
776
777           toplevel = toplevel_under_pointer;
778
779           toplevel_impl = (GdkWindowImplQuartz *)toplevel->impl;
780
781           *x = x_tmp;
782           *y = y_tmp;
783         }
784
785       return toplevel;
786     }
787
788   return NULL;
789 }
790
791 /* This function finds the correct window to send an event to, taking
792  * into account grabs, event propagation, and event masks.
793  */
794 static GdkWindow *
795 find_window_for_ns_event (NSEvent *nsevent, 
796                           gint    *x, 
797                           gint    *y,
798                           gint    *x_root,
799                           gint    *y_root)
800 {
801   GdkQuartzView *view;
802   GdkWindow *toplevel;
803   NSPoint screen_point;
804   NSEventType event_type;
805
806   view = (GdkQuartzView *)[[nsevent window] contentView];
807
808   toplevel = get_toplevel_from_ns_event (nsevent, &screen_point, x, y);
809   if (!toplevel)
810     return NULL;
811   _gdk_quartz_window_nspoint_to_gdk_xy (screen_point, x_root, y_root);
812
813   event_type = [nsevent type];
814
815   switch (event_type)
816     {
817     case NSLeftMouseDown:
818     case NSRightMouseDown:
819     case NSOtherMouseDown:
820     case NSLeftMouseUp:
821     case NSRightMouseUp:
822     case NSOtherMouseUp:
823     case NSMouseMoved:
824     case NSScrollWheel:
825     case NSLeftMouseDragged:
826     case NSRightMouseDragged:
827     case NSOtherMouseDragged:
828       return find_toplevel_for_mouse_event (nsevent, x, y);
829       
830     case NSMouseEntered:
831     case NSMouseExited:
832       /* Only handle our own entered/exited events, not the ones for the
833        * titlebar buttons.
834        */
835       if ([view trackingRect] == [nsevent trackingNumber])
836         return toplevel;
837       else
838         return NULL;
839
840     case NSKeyDown:
841     case NSKeyUp:
842     case NSFlagsChanged:
843       return find_toplevel_for_keyboard_event (nsevent);
844
845     default:
846       /* Ignore everything else. */
847       break;
848     }
849
850   return NULL;
851 }
852
853 static void
854 fill_crossing_event (GdkWindow       *toplevel,
855                      GdkEvent        *event,
856                      NSEvent         *nsevent,
857                      gint             x,
858                      gint             y,
859                      gint             x_root,
860                      gint             y_root,
861                      GdkEventType     event_type,
862                      GdkCrossingMode  mode,
863                      GdkNotifyType    detail)
864 {
865   event->any.type = event_type;
866   event->crossing.window = toplevel;
867   event->crossing.subwindow = NULL;
868   event->crossing.time = get_time_from_ns_event (nsevent);
869   event->crossing.x = x;
870   event->crossing.y = y;
871   event->crossing.x_root = x_root;
872   event->crossing.y_root = y_root;
873   event->crossing.mode = mode;
874   event->crossing.detail = detail;
875   event->crossing.state = get_keyboard_modifiers_from_ns_event (nsevent) |
876                          _gdk_quartz_events_get_current_mouse_modifiers ();
877
878   gdk_event_set_device (event, _gdk_display->core_pointer);
879
880   /* FIXME: Focus and button state? */
881 }
882
883 static void
884 fill_button_event (GdkWindow *window,
885                    GdkEvent  *event,
886                    NSEvent   *nsevent,
887                    gint       x,
888                    gint       y,
889                    gint       x_root,
890                    gint       y_root)
891 {
892   GdkEventType type;
893   gint state;
894
895   state = get_keyboard_modifiers_from_ns_event (nsevent) |
896          _gdk_quartz_events_get_current_mouse_modifiers ();
897
898   switch ([nsevent type])
899     {
900     case NSLeftMouseDown:
901     case NSRightMouseDown:
902     case NSOtherMouseDown:
903       type = GDK_BUTTON_PRESS;
904       state &= ~get_mouse_button_modifiers_from_ns_event (nsevent);
905       break;
906
907     case NSLeftMouseUp:
908     case NSRightMouseUp:
909     case NSOtherMouseUp:
910       type = GDK_BUTTON_RELEASE;
911       state |= get_mouse_button_modifiers_from_ns_event (nsevent);
912       break;
913
914     default:
915       g_assert_not_reached ();
916     }
917
918   event->any.type = type;
919   event->button.window = window;
920   event->button.time = get_time_from_ns_event (nsevent);
921   event->button.x = x;
922   event->button.y = y;
923   event->button.x_root = x_root;
924   event->button.y_root = y_root;
925   /* FIXME event->axes */
926   event->button.state = state;
927   event->button.button = get_mouse_button_from_ns_event (nsevent);
928   event->button.device = _gdk_display->core_pointer;
929 }
930
931 static void
932 fill_motion_event (GdkWindow *window,
933                    GdkEvent  *event,
934                    NSEvent   *nsevent,
935                    gint       x,
936                    gint       y,
937                    gint       x_root,
938                    gint       y_root)
939 {
940   event->any.type = GDK_MOTION_NOTIFY;
941   event->motion.window = window;
942   event->motion.time = get_time_from_ns_event (nsevent);
943   event->motion.x = x;
944   event->motion.y = y;
945   event->motion.x_root = x_root;
946   event->motion.y_root = y_root;
947   /* FIXME event->axes */
948   event->motion.state = get_keyboard_modifiers_from_ns_event (nsevent) |
949                         _gdk_quartz_events_get_current_mouse_modifiers ();
950   event->motion.is_hint = FALSE;
951   event->motion.device = _gdk_display->core_pointer;
952 }
953
954 static void
955 fill_scroll_event (GdkWindow          *window,
956                    GdkEvent           *event,
957                    NSEvent            *nsevent,
958                    gint                x,
959                    gint                y,
960                    gint                x_root,
961                    gint                y_root,
962                    gdouble             delta_x,
963                    gdouble             delta_y,
964                    GdkScrollDirection  direction)
965 {
966   NSPoint point;
967
968   point = [nsevent locationInWindow];
969
970   event->any.type = GDK_SCROLL;
971   event->scroll.window = window;
972   event->scroll.time = get_time_from_ns_event (nsevent);
973   event->scroll.x = x;
974   event->scroll.y = y;
975   event->scroll.x_root = x_root;
976   event->scroll.y_root = y_root;
977   event->scroll.state = get_keyboard_modifiers_from_ns_event (nsevent);
978   event->scroll.direction = direction;
979   event->scroll.device = _gdk_display->core_pointer;
980   event->scroll.delta_x = delta_x;
981   event->scroll.delta_y = delta_y;
982 }
983
984 static void
985 fill_key_event (GdkWindow    *window,
986                 GdkEvent     *event,
987                 NSEvent      *nsevent,
988                 GdkEventType  type)
989 {
990   GdkEventPrivate *priv;
991   GdkQuartzDeviceManagerCore *device_manager;
992   gchar buf[7];
993   gunichar c = 0;
994
995   priv = (GdkEventPrivate *) event;
996   priv->windowing_data = [nsevent retain];
997
998   event->any.type = type;
999   event->key.window = window;
1000   event->key.time = get_time_from_ns_event (nsevent);
1001   event->key.state = get_keyboard_modifiers_from_ns_event (nsevent);
1002   event->key.hardware_keycode = [nsevent keyCode];
1003   event->key.group = ([nsevent modifierFlags] & NSAlternateKeyMask) ? 1 : 0;
1004   event->key.keyval = GDK_KEY_VoidSymbol;
1005
1006   device_manager = GDK_QUARTZ_DEVICE_MANAGER_CORE (_gdk_display->device_manager);
1007   gdk_event_set_device (event, device_manager->core_keyboard);
1008   
1009   gdk_keymap_translate_keyboard_state (gdk_keymap_get_for_display (_gdk_display),
1010                                        event->key.hardware_keycode,
1011                                        event->key.state, 
1012                                        event->key.group,
1013                                        &event->key.keyval,
1014                                        NULL, NULL, NULL);
1015
1016   event->key.is_modifier = _gdk_quartz_keys_is_modifier (event->key.hardware_keycode);
1017
1018   /* If the key press is a modifier, the state should include the mask
1019    * for that modifier but only for releases, not presses. This
1020    * matches the X11 backend behavior.
1021    */
1022   if (event->key.is_modifier)
1023     {
1024       int mask = 0;
1025
1026       switch (event->key.keyval)
1027         {
1028         case GDK_KEY_Meta_R:
1029         case GDK_KEY_Meta_L:
1030           mask = GDK_MOD2_MASK;
1031           break;
1032         case GDK_KEY_Shift_R:
1033         case GDK_KEY_Shift_L:
1034           mask = GDK_SHIFT_MASK;
1035           break;
1036         case GDK_KEY_Caps_Lock:
1037           mask = GDK_LOCK_MASK;
1038           break;
1039         case GDK_KEY_Alt_R:
1040         case GDK_KEY_Alt_L:
1041           mask = GDK_MOD1_MASK;
1042           break;
1043         case GDK_KEY_Control_R:
1044         case GDK_KEY_Control_L:
1045           mask = GDK_CONTROL_MASK;
1046           break;
1047         default:
1048           mask = 0;
1049         }
1050
1051       if (type == GDK_KEY_PRESS)
1052         event->key.state &= ~mask;
1053       else if (type == GDK_KEY_RELEASE)
1054         event->key.state |= mask;
1055     }
1056
1057   event->key.state |= _gdk_quartz_events_get_current_mouse_modifiers ();
1058
1059   /* The X11 backend adds the first virtual modifier MOD2..MOD5 are
1060    * mapped to. Since we only have one virtual modifier in the quartz
1061    * backend, calling the standard function will do.
1062    */
1063   gdk_keymap_add_virtual_modifiers (gdk_keymap_get_for_display (_gdk_display),
1064                                     &event->key.state);
1065
1066   event->key.string = NULL;
1067
1068   /* Fill in ->string since apps depend on it, taken from the x11 backend. */
1069   if (event->key.keyval != GDK_KEY_VoidSymbol)
1070     c = gdk_keyval_to_unicode (event->key.keyval);
1071
1072   if (c)
1073     {
1074       gsize bytes_written;
1075       gint len;
1076
1077       len = g_unichar_to_utf8 (c, buf);
1078       buf[len] = '\0';
1079       
1080       event->key.string = g_locale_from_utf8 (buf, len,
1081                                               NULL, &bytes_written,
1082                                               NULL);
1083       if (event->key.string)
1084         event->key.length = bytes_written;
1085     }
1086   else if (event->key.keyval == GDK_KEY_Escape)
1087     {
1088       event->key.length = 1;
1089       event->key.string = g_strdup ("\033");
1090     }
1091   else if (event->key.keyval == GDK_KEY_Return ||
1092           event->key.keyval == GDK_KEY_KP_Enter)
1093     {
1094       event->key.length = 1;
1095       event->key.string = g_strdup ("\r");
1096     }
1097
1098   if (!event->key.string)
1099     {
1100       event->key.length = 0;
1101       event->key.string = g_strdup ("");
1102     }
1103
1104   GDK_NOTE(EVENTS,
1105     g_message ("key %s:\t\twindow: %p  key: %12s  %d",
1106           type == GDK_KEY_PRESS ? "press" : "release",
1107           event->key.window,
1108           event->key.keyval ? gdk_keyval_name (event->key.keyval) : "(none)",
1109           event->key.keyval));
1110 }
1111
1112 static gboolean
1113 synthesize_crossing_event (GdkWindow *window,
1114                            GdkEvent  *event,
1115                            NSEvent   *nsevent,
1116                            gint       x,
1117                            gint       y,
1118                            gint       x_root,
1119                            gint       y_root)
1120 {
1121   switch ([nsevent type])
1122     {
1123     case NSMouseEntered:
1124       /* Enter events are considered always to be from another toplevel
1125        * window, this shouldn't negatively affect any app or gtk code,
1126        * and is the only way to make GtkMenu work. EEK EEK EEK.
1127        */
1128       if (!(window->event_mask & GDK_ENTER_NOTIFY_MASK))
1129         return FALSE;
1130
1131       fill_crossing_event (window, event, nsevent,
1132                            x, y,
1133                            x_root, y_root,
1134                            GDK_ENTER_NOTIFY,
1135                            GDK_CROSSING_NORMAL,
1136                            GDK_NOTIFY_NONLINEAR);
1137       return TRUE;
1138
1139     case NSMouseExited:
1140       /* See above */
1141       if (!(window->event_mask & GDK_LEAVE_NOTIFY_MASK))
1142         return FALSE;
1143
1144       fill_crossing_event (window, event, nsevent,
1145                            x, y,
1146                            x_root, y_root,
1147                            GDK_LEAVE_NOTIFY,
1148                            GDK_CROSSING_NORMAL,
1149                            GDK_NOTIFY_NONLINEAR);
1150       return TRUE;
1151
1152     default:
1153       break;
1154     }
1155
1156   return FALSE;
1157 }
1158
1159 GdkModifierType
1160 _gdk_quartz_events_get_current_keyboard_modifiers (void)
1161 {
1162   if (gdk_quartz_osx_version () >= GDK_OSX_SNOW_LEOPARD)
1163     {
1164       return get_keyboard_modifiers_from_ns_flags ([NSClassFromString(@"NSEvent") modifierFlags]);
1165     }
1166   else
1167     {
1168       guint carbon_modifiers = GetCurrentKeyModifiers ();
1169       GdkModifierType modifiers = 0;
1170
1171       if (carbon_modifiers & alphaLock)
1172         modifiers |= GDK_LOCK_MASK;
1173       if (carbon_modifiers & shiftKey)
1174         modifiers |= GDK_SHIFT_MASK;
1175       if (carbon_modifiers & controlKey)
1176         modifiers |= GDK_CONTROL_MASK;
1177       if (carbon_modifiers & optionKey)
1178         modifiers |= GDK_MOD1_MASK;
1179       if (carbon_modifiers & cmdKey)
1180         modifiers |= GDK_MOD2_MASK;
1181
1182       return modifiers;
1183     }
1184 }
1185
1186 GdkModifierType
1187 _gdk_quartz_events_get_current_mouse_modifiers (void)
1188 {
1189   if (gdk_quartz_osx_version () >= GDK_OSX_SNOW_LEOPARD)
1190     {
1191       return get_mouse_button_modifiers_from_ns_buttons ([NSClassFromString(@"NSEvent") pressedMouseButtons]);
1192     }
1193   else
1194     {
1195       return get_mouse_button_modifiers_from_ns_buttons (GetCurrentButtonState ());
1196     }
1197 }
1198
1199 /* Detect window resizing */
1200
1201 static gboolean
1202 test_resize (NSEvent *event, GdkWindow *toplevel, gint x, gint y)
1203 {
1204   GdkWindowImplQuartz *toplevel_impl;
1205   gboolean lion;
1206
1207   /* Resizing from the resize indicator only begins if an NSLeftMouseButton
1208    * event is received in the resizing area.
1209    */
1210   toplevel_impl = (GdkWindowImplQuartz *)toplevel->impl;
1211   if ([toplevel_impl->toplevel showsResizeIndicator])
1212   if ([event type] == NSLeftMouseDown &&
1213       [toplevel_impl->toplevel showsResizeIndicator])
1214     {
1215       NSRect frame;
1216
1217       /* If the resize indicator is visible and the event
1218        * is in the lower right 15x15 corner, we leave these
1219        * events to Cocoa as to be handled as resize events.
1220        * Applications may have widgets in this area.  These
1221        * will most likely be larger than 15x15 and for
1222        * scroll bars there are also other means to move
1223        * the scroll bar.  Since the resize indicator is
1224        * the only way of resizing windows on Mac OS, it
1225        * is too important to not make functional.
1226        */
1227       frame = [toplevel_impl->view bounds];
1228       if (x > frame.size.width - GRIP_WIDTH &&
1229           x < frame.size.width &&
1230           y > frame.size.height - GRIP_HEIGHT &&
1231           y < frame.size.height)
1232         return TRUE;
1233      }
1234
1235   /* If we're on Lion and within 5 pixels of an edge,
1236    * then assume that the user wants to resize, and
1237    * return NULL to let Quartz get on with it. We check
1238    * the selector isRestorable to see if we're on 10.7.
1239    * This extra check is in case the user starts
1240    * dragging before GDK recognizes the grab.
1241    *
1242    * We perform this check for a button press of all buttons, because we
1243    * do receive, for instance, a right mouse down event for a GDK window
1244    * for x-coordinate range [-3, 0], but we do not want to forward this
1245    * into GDK. Forwarding such events into GDK will confuse the pointer
1246    * window finding code, because there are no GdkWindows present in
1247    * the range [-3, 0].
1248    */
1249   lion = gdk_quartz_osx_version () >= GDK_OSX_LION;
1250   if (lion &&
1251       ([event type] == NSLeftMouseDown ||
1252        [event type] == NSRightMouseDown ||
1253        [event type] == NSOtherMouseDown))
1254     {
1255       if (x < GDK_LION_RESIZE ||
1256           x > toplevel->width - GDK_LION_RESIZE ||
1257           y > toplevel->height - GDK_LION_RESIZE)
1258         return TRUE;
1259     }
1260
1261   return FALSE;
1262 }
1263
1264 static gboolean
1265 gdk_event_translate (GdkEvent *event,
1266                      NSEvent  *nsevent)
1267 {
1268   NSEventType event_type;
1269   NSWindow *nswindow;
1270   GdkWindow *window;
1271   int x, y;
1272   int x_root, y_root;
1273   gboolean return_val;
1274
1275   /* There is no support for real desktop wide grabs, so we break
1276    * grabs when the application loses focus (gets deactivated).
1277    */
1278   event_type = [nsevent type];
1279   if (event_type == NSAppKitDefined)
1280     {
1281       if ([nsevent subtype] == NSApplicationDeactivatedEventType)
1282         _gdk_quartz_events_break_all_grabs (get_time_from_ns_event (nsevent));
1283
1284       /* This could potentially be used to break grabs when clicking
1285        * on the title. The subtype 20 is undocumented so it's probably
1286        * not a good idea: else if (subtype == 20) break_all_grabs ();
1287        */
1288
1289       /* Leave all AppKit events to AppKit. */
1290       return FALSE;
1291     }
1292
1293   if (_gdk_default_filters)
1294     {
1295       /* Apply global filters */
1296       GdkFilterReturn result;
1297
1298       result = gdk_event_apply_filters (nsevent, event, &_gdk_default_filters);
1299       if (result != GDK_FILTER_CONTINUE)
1300         {
1301           return_val = (result == GDK_FILTER_TRANSLATE) ? TRUE : FALSE;
1302           goto done;
1303         }
1304     }
1305
1306   nswindow = [nsevent window];
1307
1308   /* Ignore events for windows not created by GDK. */
1309   if (nswindow && ![[nswindow contentView] isKindOfClass:[GdkQuartzView class]])
1310     return FALSE;
1311
1312   /* Ignore events for ones with no windows */
1313   if (!nswindow)
1314     {
1315       GdkWindow *toplevel = NULL;
1316
1317       if (event_type == NSMouseMoved)
1318         {
1319           /* Motion events received after clicking the menu bar do not have the
1320            * window field set.  Instead of giving up on the event immediately,
1321            * we first check whether this event is within our window bounds.
1322            */
1323           NSPoint screen_point = [NSEvent mouseLocation];
1324           gint x_tmp, y_tmp;
1325
1326           toplevel = find_toplevel_under_pointer (_gdk_display,
1327                                                   screen_point,
1328                                                   &x_tmp, &y_tmp);
1329         }
1330
1331       if (!toplevel)
1332         return FALSE;
1333     }
1334
1335   /* Ignore events and break grabs while the window is being
1336    * dragged. This is a workaround for the window getting events for
1337    * the window title.
1338    */
1339   if ([(GdkQuartzNSWindow *)nswindow isInMove])
1340     {
1341       _gdk_quartz_events_break_all_grabs (get_time_from_ns_event (nsevent));
1342       return FALSE;
1343     }
1344
1345   /* Also when in a manual resize, we ignore events so that these are
1346    * pushed to GdkQuartzNSWindow's sendEvent handler.
1347    */
1348   if ([(GdkQuartzNSWindow *)nswindow isInManualResize])
1349     return FALSE;
1350
1351   /* Find the right GDK window to send the event to, taking grabs and
1352    * event masks into consideration.
1353    */
1354   window = find_window_for_ns_event (nsevent, &x, &y, &x_root, &y_root);
1355   if (!window)
1356     return FALSE;
1357
1358   /* Quartz handles resizing on its own, so we want to stay out of the way. */
1359   if (test_resize (nsevent, window, x, y))
1360     return FALSE;
1361
1362   /* Apply any window filters. */
1363   if (GDK_IS_WINDOW (window))
1364     {
1365       GdkFilterReturn result;
1366
1367       if (window->filters)
1368         {
1369           g_object_ref (window);
1370
1371           result = gdk_event_apply_filters (nsevent, event, &window->filters);
1372
1373           g_object_unref (window);
1374
1375           if (result != GDK_FILTER_CONTINUE)
1376             {
1377               return_val = (result == GDK_FILTER_TRANSLATE) ? TRUE : FALSE;
1378               goto done;
1379             }
1380         }
1381     }
1382
1383   /* If the app is not active leave the event to AppKit so the window gets
1384    * focused correctly and don't do click-through (so we behave like most
1385    * native apps). If the app is active, we focus the window and then handle
1386    * the event, also to match native apps.
1387    */
1388   if ((event_type == NSRightMouseDown ||
1389        event_type == NSOtherMouseDown ||
1390        event_type == NSLeftMouseDown))
1391     {
1392       GdkWindowImplQuartz *impl = GDK_WINDOW_IMPL_QUARTZ (window->impl);
1393
1394       if (![NSApp isActive])
1395         {
1396           [NSApp activateIgnoringOtherApps:YES];
1397           return FALSE;
1398         }
1399       else if (![impl->toplevel isKeyWindow])
1400         {
1401           GdkDeviceGrabInfo *grab;
1402
1403           grab = _gdk_display_get_last_device_grab (_gdk_display,
1404                                                     _gdk_display->core_pointer);
1405           if (!grab)
1406             [impl->toplevel makeKeyWindow];
1407         }
1408     }
1409
1410   return_val = TRUE;
1411
1412   switch (event_type)
1413     {
1414     case NSLeftMouseDown:
1415     case NSRightMouseDown:
1416     case NSOtherMouseDown:
1417     case NSLeftMouseUp:
1418     case NSRightMouseUp:
1419     case NSOtherMouseUp:
1420       fill_button_event (window, event, nsevent, x, y, x_root, y_root);
1421       break;
1422
1423     case NSLeftMouseDragged:
1424     case NSRightMouseDragged:
1425     case NSOtherMouseDragged:
1426     case NSMouseMoved:
1427       fill_motion_event (window, event, nsevent, x, y, x_root, y_root);
1428       break;
1429
1430     case NSScrollWheel:
1431       {
1432         GdkScrollDirection direction;
1433         float dx;
1434         float dy;
1435 #ifdef AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER
1436         if (gdk_quartz_osx_version() >= GDK_OSX_LION &&
1437             [nsevent hasPreciseScrollingDeltas])
1438           {
1439             dx = [nsevent scrollingDeltaX];
1440             dy = [nsevent scrollingDeltaY];
1441             direction = GDK_SCROLL_SMOOTH;
1442
1443             fill_scroll_event (window, event, nsevent, x, y, x_root, y_root,
1444                                -dx, -dy, direction);
1445
1446             /* Fall through for scroll buttons emulation */
1447           }
1448 #endif
1449         dx = [nsevent deltaX];
1450         dy = [nsevent deltaY];
1451
1452         if (dy != 0.0)
1453           {
1454             if (dy < 0.0)
1455               direction = GDK_SCROLL_DOWN;
1456             else
1457               direction = GDK_SCROLL_UP;
1458
1459             dy = fabs (dy);
1460             dx = 0.0;
1461           }
1462         else if (dx != 0.0)
1463           {
1464             if (dx < 0.0)
1465               direction = GDK_SCROLL_RIGHT;
1466             else
1467               direction = GDK_SCROLL_LEFT;
1468
1469             dx = fabs (dx);
1470             dy = 0.0;
1471           }
1472
1473         if (dx != 0.0 || dy != 0.0)
1474           {
1475 #ifdef AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER
1476             if (gdk_quartz_osx_version() >= GDK_OSX_LION &&
1477                 [nsevent hasPreciseScrollingDeltas])
1478               {
1479                 GdkEvent *emulated_event;
1480
1481                 emulated_event = gdk_event_new (GDK_SCROLL);
1482                 _gdk_event_set_pointer_emulated (emulated_event, TRUE);
1483                 fill_scroll_event (window, emulated_event, nsevent,
1484                                    x, y, x_root, y_root,
1485                                    dx, dy, direction);
1486                 append_event (emulated_event, TRUE);
1487               }
1488             else
1489 #endif
1490               fill_scroll_event (window, event, nsevent,
1491                                  x, y, x_root, y_root,
1492                                  dx, dy, direction);
1493           }
1494       }
1495       break;
1496
1497     case NSMouseEntered:
1498     case NSMouseExited:
1499       return_val = synthesize_crossing_event (window, event, nsevent, x, y, x_root, y_root);
1500       break;
1501
1502     case NSKeyDown:
1503     case NSKeyUp:
1504     case NSFlagsChanged:
1505       {
1506         GdkEventType type;
1507
1508         type = _gdk_quartz_keys_event_type (nsevent);
1509         if (type == GDK_NOTHING)
1510           return_val = FALSE;
1511         else
1512           fill_key_event (window, event, nsevent, type);
1513       }
1514       break;
1515
1516     default:
1517       /* Ignore everything elsee. */
1518       return_val = FALSE;
1519       break;
1520     }
1521
1522  done:
1523   if (return_val)
1524     {
1525       if (event->any.window)
1526         g_object_ref (event->any.window);
1527       if (((event->any.type == GDK_ENTER_NOTIFY) ||
1528            (event->any.type == GDK_LEAVE_NOTIFY)) &&
1529           (event->crossing.subwindow != NULL))
1530         g_object_ref (event->crossing.subwindow);
1531     }
1532   else
1533     {
1534       /* Mark this event as having no resources to be freed */
1535       event->any.window = NULL;
1536       event->any.type = GDK_NOTHING;
1537     }
1538
1539   return return_val;
1540 }
1541
1542 void
1543 _gdk_quartz_display_queue_events (GdkDisplay *display)
1544 {  
1545   NSEvent *nsevent;
1546
1547   nsevent = _gdk_quartz_event_loop_get_pending ();
1548   if (nsevent)
1549     {
1550       GdkEvent *event;
1551       GList *node;
1552
1553       event = gdk_event_new (GDK_NOTHING);
1554
1555       event->any.window = NULL;
1556       event->any.send_event = FALSE;
1557
1558       ((GdkEventPrivate *)event)->flags |= GDK_EVENT_PENDING;
1559
1560       node = _gdk_event_queue_append (display, event);
1561
1562       if (gdk_event_translate (event, nsevent))
1563         {
1564           ((GdkEventPrivate *)event)->flags &= ~GDK_EVENT_PENDING;
1565           _gdk_windowing_got_event (display, node, event, 0);
1566         }
1567       else
1568         {
1569           _gdk_event_queue_remove_link (display, node);
1570           g_list_free_1 (node);
1571           gdk_event_free (event);
1572
1573           gdk_threads_leave ();
1574           [NSApp sendEvent:nsevent];
1575           gdk_threads_enter ();
1576         }
1577
1578       _gdk_quartz_event_loop_release_event (nsevent);
1579     }
1580 }
1581
1582 void
1583 _gdk_quartz_screen_broadcast_client_message (GdkScreen *screen,
1584                                              GdkEvent  *event)
1585 {
1586   /* Not supported. */
1587 }
1588
1589 gboolean
1590 _gdk_quartz_screen_get_setting (GdkScreen   *screen,
1591                                 const gchar *name,
1592                                 GValue      *value)
1593 {
1594   if (strcmp (name, "gtk-double-click-time") == 0)
1595     {
1596       NSUserDefaults *defaults;
1597       float t;
1598
1599       GDK_QUARTZ_ALLOC_POOL;
1600
1601       defaults = [NSUserDefaults standardUserDefaults];
1602             
1603       t = [defaults floatForKey:@"com.apple.mouse.doubleClickThreshold"];
1604       if (t == 0.0)
1605         {
1606           /* No user setting, use the default in OS X. */
1607           t = 0.5;
1608         }
1609
1610       GDK_QUARTZ_RELEASE_POOL;
1611
1612       g_value_set_int (value, t * 1000);
1613
1614       return TRUE;
1615     }
1616   else if (strcmp (name, "gtk-font-name") == 0)
1617     {
1618       NSString *name;
1619       char *str;
1620
1621       GDK_QUARTZ_ALLOC_POOL;
1622
1623       name = [[NSFont systemFontOfSize:0] familyName];
1624
1625       /* Let's try to use the "views" font size (12pt) by default. This is
1626        * used for lists/text/other "content" which is the largest parts of
1627        * apps, using the "regular control" size (13pt) looks a bit out of
1628        * place. We might have to tweak this.
1629        */
1630
1631       /* The size has to be hardcoded as there doesn't seem to be a way to
1632        * get the views font size programmatically.
1633        */
1634       str = g_strdup_printf ("%s 12", [name UTF8String]);
1635       g_value_set_string (value, str);
1636       g_free (str);
1637
1638       GDK_QUARTZ_RELEASE_POOL;
1639
1640       return TRUE;
1641     }
1642   else if (strcmp (name, "gtk-primary-button-warps-slider") == 0)
1643     {
1644       GDK_QUARTZ_ALLOC_POOL;
1645
1646       BOOL setting = [[NSUserDefaults standardUserDefaults] boolForKey:@"AppleScrollerPagingBehavior"];
1647
1648       /* If the Apple property is YES, it means "warp" */
1649       g_value_set_boolean (value, setting == YES);
1650
1651       GDK_QUARTZ_RELEASE_POOL;
1652
1653       return TRUE;
1654     }
1655   
1656   /* FIXME: Add more settings */
1657
1658   return FALSE;
1659 }
1660
1661 void
1662 _gdk_quartz_display_event_data_copy (GdkDisplay     *display,
1663                                      const GdkEvent *src,
1664                                      GdkEvent       *dst)
1665 {
1666   GdkEventPrivate *priv_src = (GdkEventPrivate *) src;
1667   GdkEventPrivate *priv_dst = (GdkEventPrivate *) dst;
1668
1669   if (priv_src->windowing_data)
1670     {
1671       priv_dst->windowing_data = priv_src->windowing_data;
1672       [(NSEvent *)priv_dst->windowing_data retain];
1673     }
1674 }
1675
1676 void
1677 _gdk_quartz_display_event_data_free (GdkDisplay *display,
1678                                      GdkEvent   *event)
1679 {
1680   GdkEventPrivate *priv = (GdkEventPrivate *) event;
1681
1682   if (priv->windowing_data)
1683     {
1684       [(NSEvent *)priv->windowing_data release];
1685       priv->windowing_data = NULL;
1686     }
1687 }