Debian Codegraph @

clutter/osx/clutter-event-loop-osx.c

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