Debian Codegraph @

gdk/quartz/gdkeventloop-quartz.c

raw
1 #include "config.h"
2
3 #include <glib.h>
4 #include <pthread.h>
5 #include <sys/types.h>
6 #include <sys/uio.h>
7 #include <unistd.h>
8
9 #include "gdkprivate-quartz.h"
10 #include "gdkinternal-quartz.h"
11 #include <gdk/gdkdisplayprivate.h>
12
13 /*
14 * This file implementations integration between the GLib main loop and
15 * the native system of the Core Foundation run loop and Cocoa event
16 * handling. There are basically two different cases that we need to
17 * handle: either the GLib main loop is in control (the application
18 * has called gtk_main(), or is otherwise iterating the main loop), or
19 * CFRunLoop is in control (we are in a modal operation such as window
20 * resizing or drag-and-drop.)
21 *
22 * When the GLib main loop is in control we integrate in native event
23 * handling in two ways: first we add a GSource that handles checking
24 * whether there are native events available, translating native events
25 * to GDK events, and dispatching GDK events. Second we replace the
26 * "poll function" of the GLib main loop with our own version that knows
27 * how to wait for both the file descriptors and timeouts that GLib is
28 * interested in and also for incoming native events.
29 *
30 * When CFRunLoop is in control, we integrate in GLib main loop handling
31 * by adding a "run loop observer" that gives us notification at various
32 * points in the run loop cycle. We map these points onto the corresponding
33 * stages of the GLib main loop (prepare, check, dispatch), and make the
34 * appropriate calls into GLib.
35 *
36 * Both cases share a single problem: the OS X API’s don’t allow us to
37 * wait simultaneously for file descriptors and for events. So when we
38 * need to do a blocking wait that includes file descriptor activity, we
39 * push the actual work of calling select() to a helper thread (the
40 * "select thread") and wait for native events in the main thread.
41 *
42 * The main known limitation of this code is that if a callback is triggered
43 * via the OS X run loop while we are "polling" (in either case described
44 * above), iteration of the GLib main loop is not possible from within
45 * that callback. If the programmer tries to do so explicitly, then they
46 * will get a warning from GLib "main loop already active in another thread".
47 */
48
49 /******* State for run loop iteration *******/
50
51 /* Count of number of times we've gotten an "Entry" notification for
52 * our run loop observer.
53 */
54 static int current_loop_level = 0;
55
56 /* Run loop level at which we acquired ownership of the GLib main
57 * loop. See note in run_loop_entry(). -1 means that we don’t have
58 * ownership
59 */
60 static int acquired_loop_level = -1;
61
62 /* Between run_loop_before_waiting() and run_loop_after_waiting();
63 * whether we we need to call select_thread_collect_poll()
64 */
65 static gboolean run_loop_polling_async = FALSE;
66
67 /* Between run_loop_before_waiting() and run_loop_after_waiting();
68 * max_prioritiy to pass to g_main_loop_check()
69 */
70 static gint run_loop_max_priority;
71
72 /* Timer that we've added to wake up the run loop when a GLib timeout
73 */
74 static CFRunLoopTimerRef run_loop_timer = NULL;
75
76 /* These are the file descriptors that are we are polling out of
77 * the run loop. (We keep the array around and reuse it to avoid
78 * constant allocations.)
79 */
80 #define RUN_LOOP_POLLFDS_INITIAL_SIZE 16
81 static GPollFD *run_loop_pollfds;
82 static guint run_loop_pollfds_size; /* Allocated size of the array */
83 static guint run_loop_n_pollfds; /* Number of file descriptors in the array */
84
85 /******* Other global variables *******/
86
87 /* Since we count on replacing the GLib main loop poll function as our
88 * method of integrating Cocoa event handling into the GLib main loop
89 * we need to make sure that the poll function is always called even
90 * when there are no file descriptors that need to be polled. To do
91 * this, we add a dummy GPollFD to our event source with a file
92 * descriptor of “-1”. Then any time that GLib is polling the event
93 * source, it will call our poll function.
94 */
95 static GPollFD event_poll_fd;
96
97 /* Current NSEvents that we've gotten from Cocoa but haven't yet converted
98 * to GdkEvents. We wait until our dispatch() function to do the conversion
99 * since the conversion can conceivably cause signals to be emmitted
100 * or other things that shouldn’t happen inside a poll function.
101 */
102 static GQueue *current_events;
103
104 /* The default poll function for GLib; we replace this with our own
105 * Cocoa-aware version and then call the old version to do actual
106 * file descriptor polling. There’s no actual need to chain to the
107 * old one; we could reimplement the same functionality from scratch,
108 * but since the default implementation does the right thing, why
109 * bother.
110 */
111 static GPollFunc old_poll_func;
112
113 /* Reference to the run loop of the main thread. (There is a unique
114 * CFRunLoop per thread.)
115 */
116 static CFRunLoopRef main_thread_run_loop;
117
118 /* Normally the Cocoa main loop maintains an NSAutoReleasePool and frees
119 * it on every iteration. Since we are replacing the main loop we have
120 * to provide this functionality ourself. We free and replace the
121 * auto-release pool in our sources prepare() function.
122 */
123 static NSAutoreleasePool *autorelease_pool;
124
125 /* Flag when we've called nextEventMatchingMask ourself; this triggers
126 * a run loop iteration, so we need to detect that and avoid triggering
127 * our "run the GLib main looop while the run loop is active machinery.
128 */
129 static gint getting_events = 0;
130
131 /************************************************************
132 ********* Select Thread *********
133 ************************************************************/
134
135 /* The states in our state machine, see comments in select_thread_func()
136 * for descriptiions of each state
137 */
138 typedef enum {
139 BEFORE_START,
140 WAITING,
141 POLLING_QUEUED,
142 POLLING_RESTART,
143 POLLING_DESCRIPTORS,
144 } SelectThreadState;
145
146 #ifdef G_ENABLE_DEBUG
147 static const char *const state_names[] = {
148 "BEFORE_START",
149 "WAITING",
150 "POLLING_QUEUED",
151 "POLLING_RESTART",
152 "POLLING_DESCRIPTORS"
153 };
154 #endif
155
156 #if MAC_OS_X_VERSION_MIN_REQUIRED < 101200
157 typedef enum
158 {
159 GDK_QUARTZ_EVENT_MASK_ANY = NSAnyEventMask,
160 } GdkQuartzEventMask;
161 #else
162 typedef enum
163 {
164 GDK_QUARTZ_EVENT_MASK_ANY = NSEventMaskAny,
165 } GdkQuartzEventMask;
166 #endif
167
168 static SelectThreadState select_thread_state = BEFORE_START;
169
170 static pthread_t select_thread;
171 static pthread_mutex_t select_thread_mutex = PTHREAD_MUTEX_INITIALIZER;
172 static pthread_cond_t select_thread_cond = PTHREAD_COND_INITIALIZER;
173
174 #define SELECT_THREAD_LOCK() pthread_mutex_lock (&select_thread_mutex)
175 #define SELECT_THREAD_UNLOCK() pthread_mutex_unlock (&select_thread_mutex)
176 #define SELECT_THREAD_SIGNAL() pthread_cond_signal (&select_thread_cond)
177 #define SELECT_THREAD_WAIT() pthread_cond_wait (&select_thread_cond, &select_thread_mutex)
178
179 /* These are the file descriptors that the select thread is currently
180 * polling.
181 */
182 static GPollFD *current_pollfds;
183 static guint current_n_pollfds;
184
185 /* These are the file descriptors that the select thread should pick
186 * up and start polling when it has a chance.
187 */
188 static GPollFD *next_pollfds;
189 static guint next_n_pollfds;
190
191 /* Pipe used to wake up the select thread */
192 static gint select_thread_wakeup_pipe[2];
193
194 /* Run loop source used to wake up the main thread */
195 static CFRunLoopSourceRef select_main_thread_source;
196
197 static void
198 select_thread_set_state (SelectThreadState new_state)
199 {
200 gboolean old_state;
201
202 if (select_thread_state == new_state)
203 return;
204
205 GDK_NOTE (EVENTLOOP, g_message ("EventLoop: Select thread state: %s => %s", state_names[select_thread_state], state_names[new_state]));
206
207 old_state = select_thread_state;
208 select_thread_state = new_state;
209 if (old_state == WAITING && new_state != WAITING)
210 SELECT_THREAD_SIGNAL ();
211 }
212
213 static void
214 signal_main_thread (void)
215 {
216 GDK_NOTE (EVENTLOOP, g_message ("EventLoop: Waking up main thread"));
217
218 /* If we are in nextEventMatchingMask, then we need to make sure an
219 * event gets queued, otherwise it's enough to simply wake up the
220 * main thread run loop
221 */
222 if (!run_loop_polling_async)
223 CFRunLoopSourceSignal (select_main_thread_source);
224
225 /* Don't check for CFRunLoopIsWaiting() here because it causes a
226 * race condition (the loop could go into waiting state right after
227 * we checked).
228 */
229 CFRunLoopWakeUp (main_thread_run_loop);
230 }
231
232 static void *
233 select_thread_func (void *arg)
234 {
235 char c;
236
237 SELECT_THREAD_LOCK ();
238
239 while (TRUE)
240 {
241 switch (select_thread_state)
242 {
243 case BEFORE_START:
244 /* The select thread has not been started yet
245 */
246 g_assert_not_reached ();
247
248 case WAITING:
249 /* Waiting for a set of file descriptors to be submitted by the main thread
250 *
251 * => POLLING_QUEUED: main thread thread submits a set of file descriptors
252 */
253 SELECT_THREAD_WAIT ();
254 break;
255
256 case POLLING_QUEUED:
257 /* Waiting for a set of file descriptors to be submitted by the main thread
258 *
259 * => POLLING_DESCRIPTORS: select thread picks up the file descriptors to begin polling
260 */
261 g_free (current_pollfds);
262
263 current_pollfds = next_pollfds;
264 current_n_pollfds = next_n_pollfds;
265
266 next_pollfds = NULL;
267 next_n_pollfds = 0;
268
269 select_thread_set_state (POLLING_DESCRIPTORS);
270 break;
271
272 case POLLING_RESTART:
273 /* Select thread is currently polling a set of file descriptors, main thread has
274 * began a new iteration with the same set of file descriptors. We don't want to
275 * wake the select thread up and wait for it to restart immediately, but to avoid
276 * a race (described below in select_thread_start_polling()) we need to recheck after
277 * polling completes.
278 *
279 * => POLLING_DESCRIPTORS: select completes, main thread rechecks by polling again
280 * => POLLING_QUEUED: main thread submits a new set of file descriptors to be polled
281 */
282 select_thread_set_state (POLLING_DESCRIPTORS);
283 break;
284
285 case POLLING_DESCRIPTORS:
286 /* In the process of polling the file descriptors
287 *
288 * => WAITING: polling completes when a file descriptor becomes active
289 * => POLLING_QUEUED: main thread submits a new set of file descriptors to be polled
290 * => POLLING_RESTART: main thread begins a new iteration with the same set file descriptors
291 */
292 SELECT_THREAD_UNLOCK ();
293 old_poll_func (current_pollfds, current_n_pollfds, -1);
294 SELECT_THREAD_LOCK ();
295
296 read (select_thread_wakeup_pipe[0], &c, 1);
297
298 if (select_thread_state == POLLING_DESCRIPTORS)
299 {
300 signal_main_thread ();
301 select_thread_set_state (WAITING);
302 }
303 break;
304 }
305 }
306 }
307
308 #if MAC_OS_X_VERSION_MIN_REQUIRED < 101200
309 #define GDK_QUARTZ_APPLICATION_DEFINED NSApplicationDefined
310 #else
311 #define GDK_QUARTZ_APPLICATION_DEFINED NSEventTypeApplicationDefined
312 #endif
313
314 static void
315 got_fd_activity (void *info)
316 {
317 NSEvent *event;
318
319 /* Post a message so we'll break out of the message loop */
320 event = [NSEvent otherEventWithType: GDK_QUARTZ_APPLICATION_DEFINED
321 location: NSZeroPoint
322 modifierFlags: 0
323 timestamp: 0
324 windowNumber: 0
325 context: nil
326 subtype: GDK_QUARTZ_EVENT_SUBTYPE_EVENTLOOP
327 data1: 0
328 data2: 0];
329
330 [NSApp postEvent:event atStart:YES];
331 }
332
333 static void
334 select_thread_start (void)
335 {
336 g_return_if_fail (select_thread_state == BEFORE_START);
337
338 pipe (select_thread_wakeup_pipe);
339 fcntl (select_thread_wakeup_pipe[0], F_SETFL, O_NONBLOCK);
340
341 CFRunLoopSourceContext source_context = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, got_fd_activity };
342 select_main_thread_source = CFRunLoopSourceCreate (NULL, 0, &source_context);
343
344 CFRunLoopAddSource (main_thread_run_loop, select_main_thread_source, kCFRunLoopCommonModes);
345
346 select_thread_state = WAITING;
347
348 while (TRUE)
349 {
350 if (pthread_create (&select_thread, NULL, select_thread_func, NULL) == 0)
351 break;
352
353 g_warning ("Failed to create select thread, sleeping and trying again");
354 sleep (1);
355 }
356 }
357
358 #ifdef G_ENABLE_DEBUG
359 static void
360 dump_poll_result (GPollFD *ufds,
361 guint nfds)
362 {
363 GString *s;
364 gint i;
365
366 s = g_string_new ("");
367 for (i = 0; i < nfds; i++)
368 {
369 if (ufds[i].fd >= 0 && ufds[i].revents)
370 {
371 g_string_append_printf (s, " %d:", ufds[i].fd);
372 if (ufds[i].revents & G_IO_IN)
373 g_string_append (s, " in");
374 if (ufds[i].revents & G_IO_OUT)
375 g_string_append (s, " out");
376 if (ufds[i].revents & G_IO_PRI)
377 g_string_append (s, " pri");
378 g_string_append (s, "\n");
379 }
380 }
381 g_message ("%s", s->str);
382 g_string_free (s, TRUE);
383 }
384 #endif
385
386 gboolean
387 pollfds_equal (GPollFD *old_pollfds,
388 guint old_n_pollfds,
389 GPollFD *new_pollfds,
390 guint new_n_pollfds)
391 {
392 gint i;
393
394 if (old_n_pollfds != new_n_pollfds)
395 return FALSE;
396
397 for (i = 0; i < old_n_pollfds; i++)
398 {
399 if (old_pollfds[i].fd != new_pollfds[i].fd ||
400 old_pollfds[i].events != new_pollfds[i].events)
401 return FALSE;
402 }
403
404 return TRUE;
405 }
406
407 /* Begins a polling operation with the specified GPollFD array; the
408 * timeout is used only to tell if the polling operation is blocking
409 * or non-blocking.
410 *
411 * Returns:
412 * -1: No file descriptors ready, began asynchronous poll
413 * 0: No file descriptors ready, asynchronous poll not needed
414 * > 0: Number of file descriptors ready
415 */
416 static gint
417 select_thread_start_poll (GPollFD *ufds,
418 guint nfds, gint timeout)
419 {
420 gint n_ready;
421 gboolean have_new_pollfds = FALSE;
422 gint poll_fd_index = -1;
423 gint i;
424
425 for (i = 0; i < nfds; i++)
426 if (ufds[i].fd == -1)
427 {
428 poll_fd_index = i;
429 break;
430 }
431
432 if (nfds == 0 ||
433 (nfds == 1 && poll_fd_index >= 0))
434 {
435 GDK_NOTE (EVENTLOOP, g_message ("EventLoop: Nothing to poll"));
436 return 0;
437 }
438
439 /* If we went immediately to an async poll, then we might decide to
440 * dispatch idle functions when higher priority file descriptor sources
441 * are ready to be dispatched. So we always need to first check
442 * check synchronously with a timeout of zero, and only when no
443 * sources are immediately ready, go to the asynchronous poll.
444 *
445 * Of course, if the timeout passed in is 0, then the synchronous
446 * check is sufficient and we never need to do the asynchronous poll.
447 */
448 n_ready = old_poll_func (ufds, nfds, 0);
449 if (n_ready > 0 || timeout == 0)
450 {
451 #ifdef G_ENABLE_DEBUG
452 if ((_gdk_debug_flags & GDK_DEBUG_EVENTLOOP) && n_ready > 0)
453 {
454 g_message ("EventLoop: Found ready file descriptors before waiting");
455 dump_poll_result (ufds, nfds);
456 }
457 #endif
458
459 return n_ready;
460 }
461
462 SELECT_THREAD_LOCK ();
463
464 if (select_thread_state == BEFORE_START)
465 {
466 select_thread_start ();
467 }
468
469 if (select_thread_state == POLLING_QUEUED)
470 {
471 /* If the select thread hasn't picked up the set of file descriptors yet
472 * then we can simply replace an old stale set with a new set.
473 */
474 if (!pollfds_equal (ufds, nfds, next_pollfds, next_n_pollfds - 1))
475 {
476 g_free (next_pollfds);
477 next_pollfds = NULL;
478 next_n_pollfds = 0;
479
480 have_new_pollfds = TRUE;
481 }
482 }
483 else if (select_thread_state == POLLING_RESTART || select_thread_state == POLLING_DESCRIPTORS)
484 {
485 /* If we are already in the process of polling the right set of file descriptors,
486 * there's no need for us to immediately force the select thread to stop polling
487 * and then restart again. And avoiding doing so increases the efficiency considerably
488 * in the common case where we have a set of basically inactive file descriptors that
489 * stay unchanged present as we process many events.
490 *
491 * However, we have to be careful that we don't hit the following race condition
492 * Select Thread Main Thread
493 * ----------------- ---------------
494 * Polling Completes
495 * Reads data or otherwise changes file descriptor state
496 * Checks if polling is current
497 * Does nothing (*)
498 * Releases lock
499 * Acquires lock
500 * Marks polling as complete
501 * Wakes main thread
502 * Receives old stale file descriptor state
503 *
504 * To avoid this, when the new set of poll descriptors is the same as the current
505 * one, we transition to the POLLING_RESTART stage at the point marked (*). When
506 * the select thread wakes up from the poll because a file descriptor is active, if
507 * the state is POLLING_RESTART it immediately begins polling same the file descriptor
508 * set again. This normally will just return the same set of active file descriptors
509 * as the first time, but in sequence described above will properly update the
510 * file descriptor state.
511 *
512 * Special case: this RESTART logic is not needed if the only FD is the internal GLib
513 * "wakeup pipe" that is presented when threads are initialized.
514 *
515 * P.S.: The harm in the above sequence is mostly that sources can be signalled
516 * as ready when they are no longer ready. This may prompt a blocking read
517 * from a file descriptor that hangs.
518 */
519 if (!pollfds_equal (ufds, nfds, current_pollfds, current_n_pollfds - 1))
520 have_new_pollfds = TRUE;
521 else
522 {
523 if (!((nfds == 1 && poll_fd_index < 0 && g_thread_supported ()) ||
524 (nfds == 2 && poll_fd_index >= 0 && g_thread_supported ())))
525 select_thread_set_state (POLLING_RESTART);
526 }
527 }
528 else
529 have_new_pollfds = TRUE;
530
531 if (have_new_pollfds)
532 {
533 GDK_NOTE (EVENTLOOP, g_message ("EventLoop: Submitting a new set of file descriptor to the select thread"));
534
535 g_assert (next_pollfds == NULL);
536
537 next_n_pollfds = nfds + 1;
538 next_pollfds = g_new (GPollFD, nfds + 1);
539 memcpy (next_pollfds, ufds, nfds * sizeof (GPollFD));
540
541 next_pollfds[nfds].fd = select_thread_wakeup_pipe[0];
542 next_pollfds[nfds].events = G_IO_IN;
543
544 if (select_thread_state != POLLING_QUEUED && select_thread_state != WAITING)
545 {
546 if (select_thread_wakeup_pipe[1])
547 {
548 char c = 'A';
549 write (select_thread_wakeup_pipe[1], &c, 1);
550 }
551 }
552
553 select_thread_set_state (POLLING_QUEUED);
554 }
555
556 SELECT_THREAD_UNLOCK ();
557
558 return -1;
559 }
560
561 /* End an asynchronous polling operation started with
562 * select_thread_collect_poll(). This must be called if and only if
563 * select_thread_start_poll() return -1. The GPollFD array passed
564 * in must be identical to the one passed to select_thread_start_poll().
565 *
566 * The results of the poll are written into the GPollFD array passed in.
567 *
568 * Returns: number of file descriptors ready
569 */
570 static int
571 select_thread_collect_poll (GPollFD *ufds, guint nfds)
572 {
573 gint i;
574 gint n_ready = 0;
575
576 SELECT_THREAD_LOCK ();
577
578 if (select_thread_state == WAITING) /* The poll completed */
579 {
580 for (i = 0; i < nfds; i++)
581 {
582 if (ufds[i].fd == -1)
583 continue;
584
585 g_assert (ufds[i].fd == current_pollfds[i].fd);
586 g_assert (ufds[i].events == current_pollfds[i].events);
587
588 if (current_pollfds[i].revents)
589 {
590 ufds[i].revents = current_pollfds[i].revents;
591 n_ready++;
592 }
593 }
594
595 #ifdef G_ENABLE_DEBUG
596 if (_gdk_debug_flags & GDK_DEBUG_EVENTLOOP)
597 {
598 g_message ("EventLoop: Found ready file descriptors after waiting");
599 dump_poll_result (ufds, nfds);
600 }
601 #endif
602 }
603
604 SELECT_THREAD_UNLOCK ();
605
606 return n_ready;
607 }
608
609 /************************************************************
610 ********* Main Loop Source *********
611 ************************************************************/
612
613 gboolean
614 _gdk_quartz_event_loop_check_pending (void)
615 {
616 return current_events && current_events->head;
617 }
618
619 NSEvent*
620 _gdk_quartz_event_loop_get_pending (void)
621 {
622 NSEvent *event = NULL;
623
624 if (current_events)
625 event = g_queue_pop_tail (current_events);
626
627 return event;
628 }
629
630 void
631 _gdk_quartz_event_loop_release_event (NSEvent *event)
632 {
633 [event release];
634 }
635
636 static gboolean
637 gdk_event_prepare (GSource *source,
638 gint *timeout)
639 {
640 gboolean retval;
641
642 gdk_threads_enter ();
643
644 /* The prepare stage is the stage before the main loop starts polling
645 * and dispatching events. The autorelease poll is drained here for
646 * the preceding main loop iteration or, in case of the first iteration,
647 * for the operations carried out between event loop initialization and
648 * this first iteration.
649 *
650 * The autorelease poll must only be drained when the following conditions
651 * apply:
652 * - We are at the base CFRunLoop level (indicated by current_loop_level),
653 * - We are at the base g_main_loop level (indicated by
654 * g_main_depth())
655 * - We are at the base poll_func level (indicated by getting events).
656 *
657 * Messing with the autorelease pool at any level of nesting can cause access
658 * to deallocated memory because autorelease_pool is static and releasing a
659 * pool will cause all pools allocated inside of it to be released as well.
660 */
661 if (current_loop_level == 0 && g_main_depth() == 0 && getting_events == 0)
662 {
663 if (autorelease_pool)
664 [autorelease_pool drain];
665
666 autorelease_pool = [[NSAutoreleasePool alloc] init];
667 }
668
669 *timeout = -1;
670
671 if (_gdk_display->event_pause_count > 0)
672 retval = _gdk_event_queue_find_first (_gdk_display) != NULL;
673 else
674 retval = (_gdk_event_queue_find_first (_gdk_display) != NULL ||
675 _gdk_quartz_event_loop_check_pending ());
676
677 gdk_threads_leave ();
678
679 return retval;
680 }
681
682 static gboolean
683 gdk_event_check (GSource *source)
684 {
685 gboolean retval;
686
687 gdk_threads_enter ();
688
689 if (_gdk_display->event_pause_count > 0)
690 retval = _gdk_event_queue_find_first (_gdk_display) != NULL;
691 else
692 retval = (_gdk_event_queue_find_first (_gdk_display) != NULL ||
693 _gdk_quartz_event_loop_check_pending ());
694
695 gdk_threads_leave ();
696
697 return retval;
698 }
699
700 static gboolean
701 gdk_event_dispatch (GSource *source,
702 GSourceFunc callback,
703 gpointer user_data)
704 {
705 GdkEvent *event;
706
707 gdk_threads_enter ();
708
709 _gdk_quartz_display_queue_events (_gdk_display);
710
711 event = _gdk_event_unqueue (_gdk_display);
712
713 if (event)
714 {
715 _gdk_event_emit (event);
716
717 gdk_event_free (event);
718 }
719
720 gdk_threads_leave ();
721
722 return TRUE;
723 }
724
725 static GSourceFuncs event_funcs = {
726 gdk_event_prepare,
727 gdk_event_check,
728 gdk_event_dispatch,
729 NULL
730 };
731
732 /************************************************************
733 ********* Our Poll Function *********
734 ************************************************************/
735
736 #if MAC_OS_X_VERSION_MIN_REQUIRED < 101200
737 #define GDK_QUARTZ_EVENT_MASK_ANY NSAnyEventMask
738 #else
739 #define GDK_QUARTZ_EVENT_MASK_ANY NSEventMaskAny
740 #endif
741
742 static gint
743 poll_func (GPollFD *ufds,
744 guint nfds,
745 gint timeout_)
746 {
747 NSEvent *event;
748 NSDate *limit_date;
749 gint n_ready;
750
751 static GPollFD *last_ufds;
752
753 last_ufds = ufds;
754
755 n_ready = select_thread_start_poll (ufds, nfds, timeout_);
756 if (n_ready > 0)
757 timeout_ = 0;
758
759 if (timeout_ == -1)
760 limit_date = [NSDate distantFuture];
761 else if (timeout_ == 0)
762 limit_date = [NSDate distantPast];
763 else
764 limit_date = [NSDate dateWithTimeIntervalSinceNow:timeout_/1000.0];
765
766 getting_events++;
767 event = [NSApp nextEventMatchingMask: GDK_QUARTZ_EVENT_MASK_ANY
768 untilDate: limit_date
769 inMode: NSDefaultRunLoopMode
770 dequeue: YES];
771 getting_events--;
772
773 /* We check if last_ufds did not change since the time this function was
774 * called. It is possible that a recursive main loop (and thus recursive
775 * invocation of this poll function) is triggered while in
776 * nextEventMatchingMask:. If during that time new fds are added,
777 * the cached fds array might be replaced in g_main_context_iterate().
778 * So, we should avoid accessing the old fd array (still pointed at by
779 * ufds) here in that case, since it might have been freed. We avoid this
780 * by not calling the collect stage.
781 */
782 if (last_ufds == ufds && n_ready < 0)
783 n_ready = select_thread_collect_poll (ufds, nfds);
784
785 if (event &&
786 [event type] == GDK_QUARTZ_APPLICATION_DEFINED &&
787 [event subtype] == GDK_QUARTZ_EVENT_SUBTYPE_EVENTLOOP)
788 {
789 /* Just used to wake us up; if an event and a FD arrived at the same
790 * time; could have come from a previous iteration in some cases,
791 * but the spurious wake up is harmless if a little inefficient.
792 */
793 event = NULL;
794 }
795
796 if (event)
797 {
798 if (!current_events)
799 current_events = g_queue_new ();
800 g_queue_push_head (current_events, [event retain]);
801 }
802
803 return n_ready;
804 }
805
806 /************************************************************
807 ********* Running the main loop out of CFRunLoop *********
808 ************************************************************/
809
810 /* Wrapper around g_main_context_query() that handles reallocating
811 * run_loop_pollfds up to the proper size
812 */
813 static gint
814 query_main_context (GMainContext *context,
815 int max_priority,
816 int *timeout)
817 {
818 gint nfds;
819
820 if (!run_loop_pollfds)
821 {
822 run_loop_pollfds_size = RUN_LOOP_POLLFDS_INITIAL_SIZE;
823 run_loop_pollfds = g_new (GPollFD, run_loop_pollfds_size);
824 }
825
826 while ((nfds = g_main_context_query (context, max_priority, timeout,
827 run_loop_pollfds,
828 run_loop_pollfds_size)) > run_loop_pollfds_size)
829 {
830 g_free (run_loop_pollfds);
831 run_loop_pollfds_size = nfds;
832 run_loop_pollfds = g_new (GPollFD, nfds);
833 }
834
835 return nfds;
836 }
837
838 static void
839 run_loop_entry (void)
840 {
841 if (acquired_loop_level == -1)
842 {
843 if (g_main_context_acquire (NULL))
844 {
845 GDK_NOTE (EVENTLOOP, g_message ("EventLoop: Beginning tracking run loop activity"));
846 acquired_loop_level = current_loop_level;
847 }
848 else
849 {
850 /* If we fail to acquire the main context, that means someone is iterating
851 * the main context in a different thread; we simply wait until this loop
852 * exits and then try again at next entry. In general, iterating the loop
853 * from a different thread is rare: it is only possible when GDK threading
854 * is initialized and is not frequently used even then. So, we hope that
855 * having GLib main loop iteration blocked in the combination of that and
856 * a native modal operation is a minimal problem. We could imagine using a
857 * thread that does g_main_context_wait() and then wakes us back up, but
858 * the gain doesn't seem worth the complexity.
859 */
860 GDK_NOTE (EVENTLOOP, g_message ("EventLoop: Can't acquire main loop; skipping tracking run loop activity"));
861 }
862 }
863 }
864
865 static void
866 run_loop_before_timers (void)
867 {
868 }
869
870 static void
871 run_loop_before_sources (void)
872 {
873 GMainContext *context = g_main_context_default ();
874 gint max_priority;
875 gint nfds;
876
877 /* Before we let the CFRunLoop process sources, we want to check if there
878 * are any pending GLib main loop sources more urgent than
879 * G_PRIORITY_DEFAULT that need to be dispatched. (We consider all activity
880 * from the CFRunLoop to have a priority of G_PRIORITY_DEFAULT.) If no
881 * sources are processed by the CFRunLoop, then processing will continue
882 * on to the BeforeWaiting stage where we check for lower priority sources.
883 */
884
885 g_main_context_prepare (context, &max_priority);
886 max_priority = MIN (max_priority, G_PRIORITY_DEFAULT);
887
888 /* We ignore the timeout that query_main_context () returns since we'll
889 * always query again before waiting.
890 */
891 nfds = query_main_context (context, max_priority, NULL);
892
893 if (nfds)
894 old_poll_func (run_loop_pollfds, nfds, 0);
895
896 if (g_main_context_check (context, max_priority, run_loop_pollfds, nfds))
897 {
898 GDK_NOTE (EVENTLOOP, g_message ("EventLoop: Dispatching high priority sources"));
899 g_main_context_dispatch (context);
900 }
901 }
902
903 static void
904 dummy_timer_callback (CFRunLoopTimerRef timer,
905 void *info)
906 {
907 /* Nothing; won't normally even be called */
908 }
909
910 static void
911 run_loop_before_waiting (void)
912 {
913 GMainContext *context = g_main_context_default ();
914 gint timeout;
915 gint n_ready;
916
917 /* At this point, the CFRunLoop is ready to wait. We start a GMain loop
918 * iteration by calling the check() and query() stages. We start a
919 * poll, and if it doesn't complete immediately we let the run loop
920 * go ahead and sleep. Before doing that, if there was a timeout from
921 * GLib, we set up a CFRunLoopTimer to wake us up.
922 */
923
924 g_main_context_prepare (context, &run_loop_max_priority);
925
926 run_loop_n_pollfds = query_main_context (context, run_loop_max_priority, &timeout);
927
928 n_ready = select_thread_start_poll (run_loop_pollfds, run_loop_n_pollfds, timeout);
929
930 if (n_ready > 0 || timeout == 0)
931 {
932 /* We have stuff to do, no sleeping allowed! */
933 CFRunLoopWakeUp (main_thread_run_loop);
934 }
935 else if (timeout > 0)
936 {
937 /* We need to get the run loop to break out of its wait when our timeout
938 * expires. We do this by adding a dummy timer that we'll remove immediately
939 * after the wait wakes up.
940 */
941 GDK_NOTE (EVENTLOOP, g_message ("EventLoop: Adding timer to wake us up in %d milliseconds", timeout));
942
943 run_loop_timer = CFRunLoopTimerCreate (NULL, /* allocator */
944 CFAbsoluteTimeGetCurrent () + timeout / 1000.,
945 0, /* interval (0=does not repeat) */
946 0, /* flags */
947 0, /* order (priority) */
948 dummy_timer_callback,
949 NULL);
950
951 CFRunLoopAddTimer (main_thread_run_loop, run_loop_timer, kCFRunLoopCommonModes);
952 }
953
954 run_loop_polling_async = n_ready < 0;
955 }
956
957 static void
958 run_loop_after_waiting (void)
959 {
960 GMainContext *context = g_main_context_default ();
961
962 /* After sleeping, we finish of the GMain loop iteratin started in before_waiting()
963 * by doing the check() and dispatch() stages.
964 */
965
966 if (run_loop_timer)
967 {
968 CFRunLoopRemoveTimer (main_thread_run_loop, run_loop_timer, kCFRunLoopCommonModes);
969 CFRelease (run_loop_timer);
970 run_loop_timer = NULL;
971 }
972
973 if (run_loop_polling_async)
974 {
975 select_thread_collect_poll (run_loop_pollfds, run_loop_n_pollfds);
976 run_loop_polling_async = FALSE;
977 }
978
979 if (g_main_context_check (context, run_loop_max_priority, run_loop_pollfds, run_loop_n_pollfds))
980 {
981 GDK_NOTE (EVENTLOOP, g_message ("EventLoop: Dispatching after waiting"));
982 g_main_context_dispatch (context);
983 }
984 }
985
986 static void
987 run_loop_exit (void)
988 {
989 /* + 1 because we decrement current_loop_level separately in observer_callback() */
990 if ((current_loop_level + 1) == acquired_loop_level)
991 {
992 g_main_context_release (NULL);
993 acquired_loop_level = -1;
994 GDK_NOTE (EVENTLOOP, g_message ("EventLoop: Ended tracking run loop activity"));
995 }
996 }
997
998 static void
999 run_loop_observer_callback (CFRunLoopObserverRef observer,
1000 CFRunLoopActivity activity,
1001 void *info)
1002 {
1003 switch (activity)
1004 {
1005 case kCFRunLoopEntry:
1006 current_loop_level++;
1007 break;
1008 case kCFRunLoopExit:
1009 g_return_if_fail (current_loop_level > 0);
1010 current_loop_level--;
1011 break;
1012 default:
1013 break;
1014 }
1015
1016 if (getting_events > 0) /* Activity we triggered */
1017 return;
1018
1019 switch (activity)
1020 {
1021 case kCFRunLoopEntry:
1022 run_loop_entry ();
1023 break;
1024 case kCFRunLoopBeforeTimers:
1025 run_loop_before_timers ();
1026 break;
1027 case kCFRunLoopBeforeSources:
1028 run_loop_before_sources ();
1029 break;
1030 case kCFRunLoopBeforeWaiting:
1031 run_loop_before_waiting ();
1032 break;
1033 case kCFRunLoopAfterWaiting:
1034 run_loop_after_waiting ();
1035 break;
1036 case kCFRunLoopExit:
1037 run_loop_exit ();
1038 break;
1039 default:
1040 break;
1041 }
1042 }
1043
1044 /************************************************************/
1045
1046 void
1047 _gdk_quartz_event_loop_init (void)
1048 {
1049 GSource *source;
1050 CFRunLoopObserverRef observer;
1051
1052 /* Hook into the GLib main loop */
1053
1054 event_poll_fd.events = G_IO_IN;
1055 event_poll_fd.fd = -1;
1056
1057 source = g_source_new (&event_funcs, sizeof (GSource));
1058 g_source_set_name (source, "GDK Quartz event source");
1059 g_source_add_poll (source, &event_poll_fd);
1060 g_source_set_priority (source, GDK_PRIORITY_EVENTS);
1061 g_source_set_can_recurse (source, TRUE);
1062 g_source_attach (source, NULL);
1063
1064 old_poll_func = g_main_context_get_poll_func (NULL);
1065 g_main_context_set_poll_func (NULL, poll_func);
1066
1067 /* Hook into the the CFRunLoop for the main thread */
1068
1069 main_thread_run_loop = CFRunLoopGetCurrent ();
1070
1071 observer = CFRunLoopObserverCreate (NULL, /* default allocator */
1072 kCFRunLoopAllActivities,
1073 true, /* repeats: not one-shot */
1074 0, /* order (priority) */
1075 run_loop_observer_callback,
1076 NULL);
1077
1078 CFRunLoopAddObserver (main_thread_run_loop, observer, kCFRunLoopCommonModes);
1079
1080 /* Initialize our autorelease pool */
1081
1082 autorelease_pool = [[NSAutoreleasePool alloc] init];
1083 }