Debian Codegraph @

gdk/macos/gdkmacoseventsource.c

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