summaryrefslogtreecommitdiff
path: root/recipes/glib/0009-Implementation-of-Cocoa-event-loop-integration-in-GM.patch
blob: a968448c8a3917fad4c355a72a7e91ed50ba45c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
From 4d5183a847b0f958d1fa8ac8cc1d4f6166c384ab Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20Dr=C3=B6ge?= <sebastian@centricular.com>
Date: Fri, 12 Dec 2014 16:40:23 +0100
Subject: [PATCH 09/13] Implementation of Cocoa event loop integration in
 GMainContext

---
 configure.ac     |   2 +-
 glib/Makefile.am |   6 +-
 glib/gmain.c     | 985 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 991 insertions(+), 2 deletions(-)

diff --git a/glib/gmain.c b/glib/gmain.c
index 27c0234..2a88474 100644
--- a/glib/gmain.c
+++ b/glib/gmain.c
@@ -72,6 +72,10 @@
 #include <windows.h>
 #endif /* G_OS_WIN32 */
 
+#ifdef HAVE_COCOA
+#include <Cocoa/Cocoa.h>
+#endif
+
 #ifdef HAVE_MACH_MACH_TIME_H
 #include <mach/mach_time.h>
 #endif
@@ -450,6 +454,85 @@ static GMainContext *glib_worker_context;
 G_LOCK_DEFINE_STATIC (main_loop);
 static GMainContext *default_main_context;
 
+#ifdef HAVE_COCOA
+/* Main context that is acquired on the NS main thread */
+static GMainContext *cocoa_main_context;
+
+/******* State for run loop iteration *******/
+
+/* Count of number of times we've gotten an "Entry" notification for
+ * our run loop observer.
+ */
+static int cocoa_current_loop_level = 0;
+
+/* Run loop level at which we acquired ownership of the GLib main
+ * loop. See note in run_loop_entry(). -1 means that we don’t have
+ * ownership
+ */ 
+static int cocoa_acquired_loop_level = -1;
+
+/* Between run_loop_before_waiting() and run_loop_after_waiting();
+ * whether we we need to call select_thread_collect_poll()
+ */
+static gboolean cocoa_run_loop_polling_async = FALSE;
+
+/* Between run_loop_before_waiting() and run_loop_after_waiting();
+ * max_prioritiy to pass to g_main_loop_check()
+ */
+static gint cocoa_run_loop_max_priority;
+
+/* Timer that we've added to wake up the run loop when a GLib timeout
+ */
+static CFRunLoopTimerRef cocoa_run_loop_timer = NULL;
+
+/* These are the file descriptors that are we are polling out of
+ * the run loop. (We keep the array around and reuse it to avoid
+ * constant allocations.)
+ */
+#define RUN_LOOP_POLLFDS_INITIAL_SIZE 16
+static GPollFD *cocoa_run_loop_pollfds;
+static guint cocoa_run_loop_pollfds_size; /* Allocated size of the array */
+static guint cocoa_run_loop_n_pollfds;    /* Number of file descriptors in the array */
+
+/******* Other global variables *******/
+
+/* The default poll function for GLib; we replace this with our own
+ * Cocoa-aware version and then call the old version to do actual
+ * file descriptor polling. There’s no actual need to chain to the
+ * old one; we could reimplement the same functionality from scratch,
+ * but since the default implementation does the right thing, why
+ * bother.
+ */
+static GPollFunc cocoa_old_poll_func;
+
+/* Reference to our run loop observer */
+static CFRunLoopObserverRef cocoa_observer;
+
+/* Normally the Cocoa main loop maintains an NSAutoReleasePool and frees
+ * it on every iteration. Since we are replacing the main loop we have
+ * to provide this functionality ourself. We free and replace the
+ * auto-release pool in our sources prepare() function.
+ */
+static NSAutoreleasePool *cocoa_autorelease_pool;
+
+/* Flag when we've called nextEventMatchingMask ourself; this triggers
+ * a run loop iteration, so we need to detect that and avoid triggering
+ * our "run the GLib main looop while the run loop is active machinery.
+ */
+static gint cocoa_getting_events = 0;
+
+static gint cocoa_poll_func (GPollFD *fds, guint nfds, gint timeout);
+static void
+cocoa_run_loop_observer_callback (CFRunLoopObserverRef observer,
+			    CFRunLoopActivity    activity,
+			    void                *info);
+
+/* FIXME: Random number that hopefully is not used by any application on
+ * top of GLib
+ */
+#define GMAIN_COCOA_EVENT_SUBTYPE_EVENTLOOP ((short)31722)
+#endif /* HAVE_COCOA */
+
 #ifndef G_OS_WIN32
 
 
@@ -3298,6 +3381,35 @@ g_main_context_acquire (GMainContext *context)
     {
       context->owner = self;
       g_assert (context->owner_count == 0);
+#ifdef HAVE_COCOA
+      /* FIXME: Also for other poll funcs? GDK? */
+      if ([NSThread isMainThread] && context->poll_func == g_poll) {
+        if (g_atomic_pointer_compare_and_exchange (&cocoa_main_context, NULL, context))
+          {
+#ifdef G_MAIN_POLL_DEBUG
+            g_print("%p became new cocoa main context\n", context);
+#endif
+
+            /* Make sure the NSApplication is initialized */
+            [NSApplication sharedApplication];
+
+            cocoa_old_poll_func = context->poll_func;
+            context->poll_func = cocoa_poll_func;
+
+            cocoa_observer = CFRunLoopObserverCreate (NULL, /* default allocator */
+                                                kCFRunLoopAllActivities,
+                                                true, /* repeats: not one-shot */
+                                                0, /* order (priority) */
+                                                cocoa_run_loop_observer_callback,
+                                                NULL);
+            CFRunLoopAddObserver (CFRunLoopGetMain (), cocoa_observer, kCFRunLoopCommonModes);
+
+            /* Initialize our autorelease pool */
+            cocoa_autorelease_pool = [[NSAutoreleasePool alloc] init];
+          }
+      }
+#endif
+
       TRACE (GLIB_MAIN_CONTEXT_ACQUIRE (context, TRUE  /* success */));
     }
 
@@ -3354,6 +3466,24 @@ g_main_context_release (GMainContext *context)
 	  if (!loop_internal_waiter)
 	    g_mutex_unlock (waiter->mutex);
 	}
+
+#ifdef HAVE_COCOA
+      if (g_atomic_pointer_compare_and_exchange (&cocoa_main_context, context, NULL))
+        {
+#ifdef G_MAIN_POLL_DEBUG
+          g_print ("%p stopped being the cocoa default main context\n", context);
+#endif
+          context->poll_func = cocoa_old_poll_func;
+          cocoa_old_poll_func = NULL;
+
+          CFRunLoopRemoveObserver (CFRunLoopGetMain (), cocoa_observer, kCFRunLoopCommonModes);
+          CFRelease (cocoa_observer);
+          cocoa_observer = NULL;
+
+          [cocoa_autorelease_pool release];
+          cocoa_autorelease_pool = NULL;
+        }
+#endif
     }
 
   UNLOCK_CONTEXT (context); 
@@ -5857,3 +5987,858 @@ g_get_worker_context (void)
 
   return glib_worker_context;
 }
+
+#ifdef HAVE_COCOA
+
+/* 
+ * Here follows the integration between the GLib main loop and
+ * the native system of the Core Foundation run loop and Cocoa event
+ * handling. There are basically two different cases that we need to
+ * handle: either the GLib main loop is in control (the application
+ * has called gtk_main(), or is otherwise iterating the main loop), or
+ * CFRunLoop is in control (we are in a modal operation such as window
+ * resizing or drag-and-drop.)
+ *
+ * When the GLib main loop is in control we integrate in native event
+ * handling in two ways: first we add a GSource that handles checking
+ * whether there are native events available, translating native events
+ * to GDK events, and dispatching GDK events. Second we replace the
+ * "poll function" of the GLib main loop with our own version that knows
+ * how to wait for both the file descriptors and timeouts that GLib is
+ * interested in and also for incoming native events.
+ *
+ * When CFRunLoop is in control, we integrate in GLib main loop handling
+ * by adding a "run loop observer" that gives us notification at various
+ * points in the run loop cycle. We map these points onto the corresponding
+ * stages of the GLib main loop (prepare, check, dispatch), and make the
+ * appropriate calls into GLib.
+ *
+ * Both cases share a single problem: the OS X API’s don’t allow us to
+ * wait simultaneously for file descriptors and for events. So when we
+ * need to do a blocking wait that includes file descriptor activity, we
+ * push the actual work of calling select() to a helper thread (the
+ * "select thread") and wait for native events in the main thread.
+ *
+ * The main known limitation of this code is that if a callback is triggered
+ * via the OS X run loop while we are "polling" (in either case described
+ * above), iteration of the GLib main loop is not possible from within
+ * that callback. If the programmer tries to do so explicitly, then they
+ * will get a warning from GLib "main loop already active in another thread".
+ */
+
+/************************************************************
+ *********              Select Thread               *********
+ ************************************************************/
+
+/* The states in our state machine, see comments in select_thread_func()
+ * for descriptiions of each state
+ */
+typedef enum {
+  COCOA_BEFORE_START,
+  COCOA_WAITING,
+  COCOA_POLLING_QUEUED,
+  COCOA_POLLING_RESTART,
+  COCOA_POLLING_DESCRIPTORS,
+} CocoaSelectThreadState;
+
+#ifdef G_MAIN_POLL_DEBUG
+static const char *const cocoa_state_names[]  = {
+  "BEFORE_START",
+  "WAITING",
+  "POLLING_QUEUED",
+  "POLLING_RESTART",
+  "POLLING_DESCRIPTORS"
+};
+#endif
+
+static CocoaSelectThreadState cocoa_select_thread_state = COCOA_BEFORE_START;
+
+static GThread *cocoa_select_thread;
+static GMutex cocoa_select_thread_mutex;
+static GCond cocoa_select_thread_cond;
+
+#define COCOA_SELECT_THREAD_LOCK() g_mutex_lock (&cocoa_select_thread_mutex)
+#define COCOA_SELECT_THREAD_UNLOCK() g_mutex_unlock (&cocoa_select_thread_mutex)
+#define COCOA_SELECT_THREAD_SIGNAL() g_cond_signal (&cocoa_select_thread_cond)
+#define COCOA_SELECT_THREAD_WAIT() g_cond_wait (&cocoa_select_thread_cond, &cocoa_select_thread_mutex)
+
+/* These are the file descriptors that the select thread is currently
+ * polling.
+ */
+static GPollFD *cocoa_current_pollfds;
+static guint cocoa_current_n_pollfds;
+
+/* These are the file descriptors that the select thread should pick
+ * up and start polling when it has a chance.
+ */
+static GPollFD *cocoa_next_pollfds;
+static guint cocoa_next_n_pollfds;
+
+/* Pipe used to wake up the select thread */
+static gint cocoa_select_thread_wakeup_pipe[2];
+
+/* Run loop source used to wake up the main thread */
+static CFRunLoopSourceRef cocoa_select_main_thread_source;
+
+static void
+cocoa_select_thread_set_state (CocoaSelectThreadState new_state)
+{
+  gboolean old_state;
+
+  if (cocoa_select_thread_state == new_state)
+    return;
+
+#ifdef G_MAIN_POLL_DEBUG
+  g_print ("EventLoop: Select thread state: %s => %s\n", cocoa_state_names[cocoa_select_thread_state], cocoa_state_names[new_state]);
+#endif
+
+  old_state = cocoa_select_thread_state;
+  cocoa_select_thread_state = new_state;
+  if (old_state == COCOA_WAITING && new_state != COCOA_WAITING)
+    COCOA_SELECT_THREAD_SIGNAL ();
+}
+
+static void
+cocoa_signal_main_thread (void)
+{
+#ifdef G_MAIN_POLL_DEBUG
+  g_print ("EventLoop: Waking up main thread\n");
+#endif
+
+  /* If we are in nextEventMatchingMask, then we need to make sure an
+   * event gets queued, otherwise it's enough to simply wake up the
+   * main thread run loop
+   */
+  if (!cocoa_run_loop_polling_async)
+    CFRunLoopSourceSignal (cocoa_select_main_thread_source);
+
+  /* Don't check for CFRunLoopIsWaiting() here because it causes a
+   * race condition (the loop could go into waiting state right after
+   * we checked).
+   */
+  CFRunLoopWakeUp (CFRunLoopGetMain ());
+}
+
+static void *
+cocoa_select_thread_func (void *arg)
+{
+  char c;
+  
+  COCOA_SELECT_THREAD_LOCK ();
+
+  while (TRUE)
+    {
+      switch (cocoa_select_thread_state)
+	{
+	case COCOA_BEFORE_START:
+	  /* The select thread has not been started yet
+	   */
+	  g_assert_not_reached ();
+	  
+	case COCOA_WAITING:
+	  /* Waiting for a set of file descriptors to be submitted by the main thread
+	   *
+	   *  => POLLING_QUEUED: main thread thread submits a set of file descriptors
+	   */ 
+	  COCOA_SELECT_THREAD_WAIT ();
+	  break;
+	  
+	case COCOA_POLLING_QUEUED:
+	  /* Waiting for a set of file descriptors to be submitted by the main thread
+	   *
+	   *  => POLLING_DESCRIPTORS: select thread picks up the file descriptors to begin polling
+	   */ 
+	  g_free (cocoa_current_pollfds);
+	  
+	  cocoa_current_pollfds = cocoa_next_pollfds;
+	  cocoa_current_n_pollfds = cocoa_next_n_pollfds;
+
+	  cocoa_next_pollfds = NULL;
+	  cocoa_next_n_pollfds = 0;
+
+	  cocoa_select_thread_set_state (COCOA_POLLING_DESCRIPTORS);
+	  break;
+	  
+	case COCOA_POLLING_RESTART:
+	  /* Select thread is currently polling a set of file descriptors, main thread has
+	   * began a new iteration with the same set of file descriptors. We don't want to
+	   * wake the select thread up and wait for it to restart immediately, but to avoid
+	   * a race (described below in select_thread_start_polling()) we need to recheck after
+	   * polling completes.
+	   *
+	   * => POLLING_DESCRIPTORS: select completes, main thread rechecks by polling again
+	   * => POLLING_QUEUED: main thread submits a new set of file descriptors to be polled
+	   */
+	  cocoa_select_thread_set_state (COCOA_POLLING_DESCRIPTORS);
+	  break;
+
+	case COCOA_POLLING_DESCRIPTORS:
+	  /* In the process of polling the file descriptors
+	   *
+	   *  => WAITING: polling completes when a file descriptor becomes active
+	   *  => POLLING_QUEUED: main thread submits a new set of file descriptors to be polled
+	   *  => POLLING_RESTART: main thread begins a new iteration with the same set file descriptors
+	   */ 
+	  COCOA_SELECT_THREAD_UNLOCK ();
+	  cocoa_old_poll_func (cocoa_current_pollfds, cocoa_current_n_pollfds, -1);
+	  COCOA_SELECT_THREAD_LOCK ();
+
+	  read (cocoa_select_thread_wakeup_pipe[0], &c, 1);
+
+	  if (cocoa_select_thread_state == COCOA_POLLING_DESCRIPTORS)
+	    {
+	      cocoa_signal_main_thread ();
+	      cocoa_select_thread_set_state (COCOA_WAITING);
+	    }
+	  break;
+	}
+    }
+}
+
+static void 
+cocoa_got_fd_activity (void *info)
+{
+  NSEvent *event;
+
+  /* Post a message so we'll break out of the message loop */
+  event = [NSEvent otherEventWithType: NSApplicationDefined
+	                     location: NSZeroPoint
+	                modifierFlags: 0
+	                    timestamp: 0
+	                 windowNumber: 0
+	                      context: nil
+                              subtype: GMAIN_COCOA_EVENT_SUBTYPE_EVENTLOOP
+	                        data1: 0 
+	                        data2: 0];
+
+  [NSApp postEvent:event atStart:YES];
+}
+
+static void
+cocoa_select_thread_start (void)
+{
+  g_return_if_fail (cocoa_select_thread_state == COCOA_BEFORE_START);
+
+  pipe (cocoa_select_thread_wakeup_pipe);
+  fcntl (cocoa_select_thread_wakeup_pipe[0], F_SETFL, O_NONBLOCK);
+
+  CFRunLoopSourceContext source_context = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, cocoa_got_fd_activity };
+  cocoa_select_main_thread_source = CFRunLoopSourceCreate (NULL, 0, &source_context);
+  
+  CFRunLoopAddSource (CFRunLoopGetMain (), cocoa_select_main_thread_source, kCFRunLoopCommonModes);
+
+  cocoa_select_thread_state = COCOA_WAITING;
+  
+  while (TRUE)
+    {
+      if ((cocoa_select_thread = g_thread_new ("CocoaSelectThread", cocoa_select_thread_func, NULL)))
+	  break;
+
+      g_warning ("Failed to create select thread, sleeping and trying again");
+      sleep (1);
+    }
+}
+
+#ifdef G_ENABLE_DEBUG
+#ifdef G_MAIN_POLL_DEBUG
+static void
+cocoa_dump_poll_result (GPollFD *ufds,
+		  guint    nfds)
+{
+  gint i;
+
+  for (i = 0; i < nfds; i++)
+    {
+      if (ufds[i].fd >= 0 && ufds[i].revents)
+	{
+	  g_print (" %d:", ufds[i].fd);
+	  if (ufds[i].revents & G_IO_IN)
+	    g_print (" in");
+	  if (ufds[i].revents & G_IO_OUT)
+	    g_print (" out");
+	  if (ufds[i].revents & G_IO_PRI)
+	    g_print (" pri");
+	  g_print ("\n");
+	}
+    }
+}
+#endif
+#endif
+
+static gboolean
+cocoa_pollfds_equal (GPollFD *old_pollfds,
+	       guint    old_n_pollfds,
+	       GPollFD *new_pollfds,
+	       guint    new_n_pollfds)
+{
+  gint i;
+  
+  if (old_n_pollfds != new_n_pollfds)
+    return FALSE;
+
+  for (i = 0; i < old_n_pollfds; i++)
+    {
+      if (old_pollfds[i].fd != new_pollfds[i].fd ||
+	  old_pollfds[i].events != new_pollfds[i].events)
+	return FALSE;
+    }
+
+  return TRUE;
+}
+
+/* Begins a polling operation with the specified GPollFD array; the 
+ * timeout is used only to tell if the polling operation is blocking
+ * or non-blocking.
+ *
+ * Returns:
+ *  -1: No file descriptors ready, began asynchronous poll
+ *   0: No file descriptors ready, asynchronous poll not needed
+ * > 0: Number of file descriptors ready
+ */
+static gint
+cocoa_select_thread_start_poll (GPollFD *ufds,
+                                guint    nfds,
+                                gint     timeout)
+{
+  gint n_ready;
+  gboolean have_new_pollfds = FALSE;
+  gint poll_fd_index = -1;
+  gint i;
+
+  for (i = 0; i < nfds; i++)
+    if (ufds[i].fd == -1)
+      {
+	poll_fd_index = i;
+	break;
+      }
+  
+  if (nfds == 0 ||
+      (nfds == 1 && poll_fd_index >= 0))
+    {
+#ifdef G_MAIN_POLL_DEBUG
+      g_print ("EventLoop: Nothing to poll\n");
+#endif
+      return 0;
+    }
+
+  /* If we went immediately to an async poll, then we might decide to
+   * dispatch idle functions when higher priority file descriptor sources
+   * are ready to be dispatched. So we always need to first check
+   * check synchronously with a timeout of zero, and only when no
+   * sources are immediately ready, go to the asynchronous poll.
+   *
+   * Of course, if the timeout passed in is 0, then the synchronous
+   * check is sufficient and we never need to do the asynchronous poll.
+   */
+  n_ready = cocoa_old_poll_func (ufds, nfds, 0);
+  if (n_ready > 0 || timeout == 0)
+    {
+#ifdef G_ENABLE_DEBUG
+#ifdef G_MAIN_POLL_DEBUG
+      if (n_ready > 0)
+	{
+	  g_print ("EventLoop: Found ready file descriptors before waiting\n");
+	  cocoa_dump_poll_result (ufds, nfds);
+	}
+#endif
+#endif
+  
+      return n_ready;
+    }
+  
+  COCOA_SELECT_THREAD_LOCK ();
+
+  if (cocoa_select_thread_state == COCOA_BEFORE_START)
+    {
+      cocoa_select_thread_start ();
+    }
+  
+  if (cocoa_select_thread_state == COCOA_POLLING_QUEUED)
+    {
+      /* If the select thread hasn't picked up the set of file descriptors yet
+       * then we can simply replace an old stale set with a new set.
+       */
+      if (!cocoa_pollfds_equal (ufds, nfds, cocoa_next_pollfds, cocoa_next_n_pollfds - 1))
+	{
+	  g_free (cocoa_next_pollfds);
+	  cocoa_next_pollfds = NULL;
+	  cocoa_next_n_pollfds = 0;
+	  
+	  have_new_pollfds = TRUE;
+	}
+    }
+  else if (cocoa_select_thread_state == COCOA_POLLING_RESTART || cocoa_select_thread_state == COCOA_POLLING_DESCRIPTORS)
+    {
+      /* If we are already in the process of polling the right set of file descriptors,
+       * there's no need for us to immediately force the select thread to stop polling
+       * and then restart again. And avoiding doing so increases the efficiency considerably
+       * in the common case where we have a set of basically inactive file descriptors that
+       * stay unchanged present as we process many events.
+       *
+       * However, we have to be careful that we don't hit the following race condition
+       *  Select Thread              Main Thread
+       *  -----------------          ---------------
+       *  Polling Completes
+       *                             Reads data or otherwise changes file descriptor state
+       *                             Checks if polling is current
+       *                             Does nothing (*)
+       *                             Releases lock
+       *  Acquires lock
+       *  Marks polling as complete
+       *  Wakes main thread
+       *                             Receives old stale file descriptor state
+       * 
+       * To avoid this, when the new set of poll descriptors is the same as the current
+       * one, we transition to the POLLING_RESTART stage at the point marked (*). When
+       * the select thread wakes up from the poll because a file descriptor is active, if
+       * the state is POLLING_RESTART it immediately begins polling same the file descriptor
+       * set again. This normally will just return the same set of active file descriptors
+       * as the first time, but in sequence described above will properly update the
+       * file descriptor state.
+       *
+       * Special case: this RESTART logic is not needed if the only FD is the internal GLib
+       * "wakeup pipe" that is presented when threads are initialized.
+       *
+       * P.S.: The harm in the above sequence is mostly that sources can be signalled
+       *   as ready when they are no longer ready. This may prompt a blocking read
+       *   from a file descriptor that hangs.
+       */
+      if (!cocoa_pollfds_equal (ufds, nfds, cocoa_current_pollfds, cocoa_current_n_pollfds - 1))
+	have_new_pollfds = TRUE;
+      else
+	{
+	  if (!((nfds == 1 && poll_fd_index < 0 && g_thread_supported ()) ||
+		(nfds == 2 && poll_fd_index >= 0 && g_thread_supported ())))
+	    cocoa_select_thread_set_state (COCOA_POLLING_RESTART);
+	}
+    }
+  else
+    have_new_pollfds = TRUE;
+
+  if (have_new_pollfds)
+    {
+#ifdef G_MAIN_POLL_DEBUG
+      g_print ("EventLoop: Submitting a new set of file descriptor to the select thread\n");
+#endif
+      
+      g_assert (cocoa_next_pollfds == NULL);
+      
+      cocoa_next_n_pollfds = nfds + 1;
+      cocoa_next_pollfds = g_new (GPollFD, nfds + 1);
+      memcpy (cocoa_next_pollfds, ufds, nfds * sizeof (GPollFD));
+  
+      cocoa_next_pollfds[nfds].fd = cocoa_select_thread_wakeup_pipe[0];
+      cocoa_next_pollfds[nfds].events = G_IO_IN;
+  
+      if (cocoa_select_thread_state != COCOA_POLLING_QUEUED && cocoa_select_thread_state != COCOA_WAITING)
+	{
+	  if (cocoa_select_thread_wakeup_pipe[1])
+	    {
+	      char c = 'A';
+	      write (cocoa_select_thread_wakeup_pipe[1], &c, 1);
+	    }
+	}
+      
+      cocoa_select_thread_set_state (COCOA_POLLING_QUEUED);
+    }
+  
+  COCOA_SELECT_THREAD_UNLOCK ();
+
+  return -1;
+}
+
+/* End an asynchronous polling operation started with
+ * select_thread_collect_poll(). This must be called if and only if
+ * select_thread_start_poll() return -1. The GPollFD array passed
+ * in must be identical to the one passed to select_thread_start_poll().
+ *
+ * The results of the poll are written into the GPollFD array passed in.
+ *
+ * Returns: number of file descriptors ready
+ */
+static int
+cocoa_select_thread_collect_poll (GPollFD *ufds, guint nfds)
+{
+  gint i;
+  gint n_ready = 0;
+  
+  COCOA_SELECT_THREAD_LOCK ();
+
+  if (cocoa_select_thread_state == COCOA_WAITING) /* The poll completed */
+    {
+      for (i = 0; i < nfds; i++)
+	{
+	  if (ufds[i].fd == -1)
+	    continue;
+	  
+	  g_assert (ufds[i].fd == cocoa_current_pollfds[i].fd);
+	  g_assert (ufds[i].events == cocoa_current_pollfds[i].events);
+
+	  if (cocoa_current_pollfds[i].revents)
+	    {
+	      ufds[i].revents = cocoa_current_pollfds[i].revents;
+	      n_ready++;
+	    }
+	}
+
+#ifdef G_ENABLE_DEBUG
+#ifdef G_MAIN_POLL_DEBUG
+      g_print ("EventLoop: Found ready file descriptors after waiting\n");
+      cocoa_dump_poll_result (ufds, nfds);
+#endif
+#endif
+    }
+
+  COCOA_SELECT_THREAD_UNLOCK ();
+
+  return n_ready;
+}
+
+/************************************************************
+ *********             Our Poll Function            *********
+ ************************************************************/
+
+static gint
+cocoa_poll_func (GPollFD *ufds,
+	   guint    nfds,
+	   gint     timeout_)
+{
+  NSEvent *event;
+  NSDate *limit_date;
+  gint n_ready;
+
+  static GPollFD *last_ufds;
+
+  last_ufds = ufds;
+
+  n_ready = cocoa_select_thread_start_poll (ufds, nfds, timeout_);
+  if (n_ready > 0)
+    timeout_ = 0;
+
+  if (timeout_ == -1)
+    limit_date = [NSDate distantFuture];
+  else if (timeout_ == 0)
+    limit_date = [NSDate distantPast];
+  else
+    limit_date = [NSDate dateWithTimeIntervalSinceNow:timeout_/1000.0];
+
+  cocoa_getting_events++;
+  event = [NSApp nextEventMatchingMask: NSAnyEventMask
+	                     untilDate: limit_date
+	                        inMode: NSDefaultRunLoopMode
+                               dequeue: YES];
+  cocoa_getting_events--;
+
+  /* We check if last_ufds did not change since the time this function was
+   * called. It is possible that a recursive main loop (and thus recursive
+   * invocation of this poll function) is triggered while in
+   * nextEventMatchingMask:. If during that time new fds are added,
+   * the cached fds array might be replaced in g_main_context_iterate().
+   * So, we should avoid accessing the old fd array (still pointed at by
+   * ufds) here in that case, since it might have been freed. We avoid this
+   * by not calling the collect stage.
+   */
+  if (last_ufds == ufds && n_ready < 0)
+    n_ready = cocoa_select_thread_collect_poll (ufds, nfds);
+
+  if (event &&
+      [event type] == NSApplicationDefined &&
+      (NSInteger) [event subtype] == GMAIN_COCOA_EVENT_SUBTYPE_EVENTLOOP)
+    {
+      /* Just used to wake us up; if an event and a FD arrived at the same
+       * time; could have come from a previous iteration in some cases,
+       * but the spurious wake up is harmless if a little inefficient.
+       */
+      event = NULL;
+    }
+
+  if (event)
+    {
+      /* TODO: Allow the application to intercept events before sending them.
+       * GDK needs this for translating Cocoa events into GDK events
+       */
+#ifdef G_MAIN_POLL_DEBUG
+      g_print ("sending event\n");
+#endif
+      [NSApp sendEvent:event];
+    }
+
+  /* The prepare stage is the stage before the main loop starts polling
+   * and dispatching events. The autorelease poll is drained here for
+   * the preceding main loop iteration or, in case of the first iteration,
+   * for the operations carried out between event loop initialization and
+   * this first iteration.
+   *
+   * The autorelease poll must only be drained when the following conditions
+   * apply:
+   *  - We are at the base CFRunLoop level (indicated by current_loop_level),
+   *  - We are at the base g_main_loop level (indicated by
+   *    g_main_depth())
+   *  - We are at the base poll_func level (indicated by getting events).
+   *
+   * Messing with the autorelease pool at any level of nesting can cause access
+   * to deallocated memory because autorelease_pool is static and releasing a
+   * pool will cause all pools allocated inside of it to be released as well.
+   */
+  if (cocoa_current_loop_level == 0 && g_main_depth() == 0 && cocoa_getting_events == 0)
+    {
+      if (cocoa_autorelease_pool)
+        [cocoa_autorelease_pool release];
+
+      cocoa_autorelease_pool = [[NSAutoreleasePool alloc] init];
+    }
+
+  return n_ready;
+}
+
+/************************************************************
+ *********  Running the main loop out of CFRunLoop  *********
+ ************************************************************/
+
+/* Wrapper around g_main_context_query() that handles reallocating
+ * run_loop_pollfds up to the proper size
+ */
+static gint
+cocoa_query_main_context (GMainContext *context,
+		    int           max_priority,
+		    int          *timeout)
+{
+  gint nfds;
+  
+  if (!cocoa_run_loop_pollfds)
+    {
+      cocoa_run_loop_pollfds_size = RUN_LOOP_POLLFDS_INITIAL_SIZE;
+      cocoa_run_loop_pollfds = g_new (GPollFD, cocoa_run_loop_pollfds_size);
+    }
+
+  while ((nfds = g_main_context_query (context, max_priority, timeout,
+				       cocoa_run_loop_pollfds,
+				       cocoa_run_loop_pollfds_size)) > cocoa_run_loop_pollfds_size)
+    {
+      g_free (cocoa_run_loop_pollfds);
+      cocoa_run_loop_pollfds_size = nfds;
+      cocoa_run_loop_pollfds = g_new (GPollFD, nfds);
+    }
+
+  return nfds;
+}
+
+static void
+cocoa_run_loop_entry (void)
+{
+  if (cocoa_acquired_loop_level == -1)
+    {
+      if (g_main_context_acquire (cocoa_main_context))
+	{
+#ifdef G_MAIN_POLL_DEBUG
+	  g_print ("EventLoop: Beginning tracking run loop activity\n");
+#endif
+	  cocoa_acquired_loop_level = cocoa_current_loop_level;
+	}
+      else
+	{
+	  /* If we fail to acquire the main context, that means someone is iterating
+	   * the main context in a different thread; we simply wait until this loop
+	   * exits and then try again at next entry. In general, iterating the loop
+	   * from a different thread is rare: it is only possible when GDK threading
+	   * is initialized and is not frequently used even then. So, we hope that
+	   * having GLib main loop iteration blocked in the combination of that and
+	   * a native modal operation is a minimal problem. We could imagine using a
+	   * thread that does g_main_context_wait() and then wakes us back up, but
+	   * the gain doesn't seem worth the complexity.
+	   */
+#ifdef G_MAIN_POLL_DEBUG
+	  g_print ("EventLoop: Can't acquire main loop; skipping tracking run loop activity\n");
+#endif
+	}
+    }
+}
+
+static void
+cocoa_run_loop_before_timers (void)
+{
+}
+
+static void
+cocoa_run_loop_before_sources (void)
+{
+  GMainContext *context = cocoa_main_context;
+  gint max_priority;
+  gint nfds;
+
+  /* Before we let the CFRunLoop process sources, we want to check if there
+   * are any pending GLib main loop sources more urgent than
+   * G_PRIORITY_DEFAULT that need to be dispatched. (We consider all activity
+   * from the CFRunLoop to have a priority of G_PRIORITY_DEFAULT.) If no
+   * sources are processed by the CFRunLoop, then processing will continue
+   * on to the BeforeWaiting stage where we check for lower priority sources.
+   */
+
+  g_main_context_prepare (context, &max_priority); 
+  max_priority = MIN (max_priority, G_PRIORITY_DEFAULT);
+
+  /* We ignore the timeout that query_main_context () returns since we'll
+   * always query again before waiting.
+   */
+  nfds = cocoa_query_main_context (context, max_priority, NULL);
+
+  if (nfds)
+    cocoa_old_poll_func (cocoa_run_loop_pollfds, nfds, 0);
+
+  if (g_main_context_check (context, max_priority, cocoa_run_loop_pollfds, nfds))
+    {
+#ifdef G_MAIN_POLL_DEBUG
+      g_print ("EventLoop: Dispatching high priority sources\n");
+#endif
+      g_main_context_dispatch (context);
+    }
+}
+
+static void
+cocoa_dummy_timer_callback (CFRunLoopTimerRef  timer,
+		      void              *info)
+{
+  /* Nothing; won't normally even be called */
+}
+
+static void
+cocoa_run_loop_before_waiting (void)
+{
+  GMainContext *context = cocoa_main_context;
+  gint timeout;
+  gint n_ready;
+
+  /* At this point, the CFRunLoop is ready to wait. We start a GMain loop
+   * iteration by calling the check() and query() stages. We start a
+   * poll, and if it doesn't complete immediately we let the run loop
+   * go ahead and sleep. Before doing that, if there was a timeout from
+   * GLib, we set up a CFRunLoopTimer to wake us up.
+   */
+  
+  g_main_context_prepare (context, &cocoa_run_loop_max_priority); 
+  
+  cocoa_run_loop_n_pollfds = cocoa_query_main_context (context, cocoa_run_loop_max_priority, &timeout);
+
+  n_ready = cocoa_select_thread_start_poll (cocoa_run_loop_pollfds, cocoa_run_loop_n_pollfds, timeout);
+
+  if (n_ready > 0 || timeout == 0)
+    {
+      /* We have stuff to do, no sleeping allowed! */
+      CFRunLoopWakeUp (CFRunLoopGetMain ());
+    }
+  else if (timeout > 0)
+    {
+      /* We need to get the run loop to break out of its wait when our timeout
+       * expires. We do this by adding a dummy timer that we'll remove immediately
+       * after the wait wakes up.
+       */
+#ifdef G_MAIN_POLL_DEBUG
+      g_print ("EventLoop: Adding timer to wake us up in %d milliseconds\n", timeout);
+#endif
+      
+      cocoa_run_loop_timer = CFRunLoopTimerCreate (NULL, /* allocator */
+					     CFAbsoluteTimeGetCurrent () + timeout / 1000.,
+					     0, /* interval (0=does not repeat) */
+					     0, /* flags */
+					     0, /* order (priority) */
+					     cocoa_dummy_timer_callback,
+					     NULL);
+
+      CFRunLoopAddTimer (CFRunLoopGetMain (), cocoa_run_loop_timer, kCFRunLoopCommonModes);
+    }
+  
+  cocoa_run_loop_polling_async = n_ready < 0;
+}
+
+static void
+cocoa_run_loop_after_waiting (void)
+{
+  GMainContext *context = cocoa_main_context;
+
+  /* After sleeping, we finish of the GMain loop iteratin started in before_waiting()
+   * by doing the check() and dispatch() stages.
+   */
+
+  if (cocoa_run_loop_timer)
+    {
+      CFRunLoopRemoveTimer (CFRunLoopGetMain (), cocoa_run_loop_timer, kCFRunLoopCommonModes);
+      CFRelease (cocoa_run_loop_timer);
+      cocoa_run_loop_timer = NULL;
+    }
+  
+  if (cocoa_run_loop_polling_async)
+    {
+      cocoa_select_thread_collect_poll (cocoa_run_loop_pollfds, cocoa_run_loop_n_pollfds);
+      cocoa_run_loop_polling_async = FALSE;
+    }
+  
+  if (g_main_context_check (context, cocoa_run_loop_max_priority, cocoa_run_loop_pollfds, cocoa_run_loop_n_pollfds))
+    {
+#ifdef G_MAIN_POLL_DEBUG
+      g_print ("EventLoop: Dispatching after waiting\n");
+#endif
+      g_main_context_dispatch (context);
+    }
+}
+
+static void
+cocoa_run_loop_exit (void)
+{
+  /* + 1 because we decrement current_loop_level separately in observer_callback() */
+  if ((cocoa_current_loop_level + 1) == cocoa_acquired_loop_level)
+    {
+      g_main_context_release (cocoa_main_context);
+      cocoa_acquired_loop_level = -1;
+#ifdef G_MAIN_POLL_DEBUG
+      g_print ("EventLoop: Ended tracking run loop activity\n");
+#endif
+    }
+}
+
+static void
+cocoa_run_loop_observer_callback (CFRunLoopObserverRef observer,
+			    CFRunLoopActivity    activity,
+			    void                *info)
+{
+  switch (activity)
+    {
+    case kCFRunLoopEntry:
+      cocoa_current_loop_level++;
+      break;
+    case kCFRunLoopExit:
+      g_return_if_fail (cocoa_current_loop_level > 0);
+      cocoa_current_loop_level--;
+      break;
+    default:
+      break;
+    }
+
+  if (cocoa_getting_events > 0) /* Activity we triggered */
+    return;
+
+  switch (activity)
+    {
+    case kCFRunLoopEntry:
+      cocoa_run_loop_entry ();
+      break;
+    case kCFRunLoopBeforeTimers:
+      cocoa_run_loop_before_timers ();
+      break;
+    case kCFRunLoopBeforeSources:
+      cocoa_run_loop_before_sources ();
+      break;
+    case kCFRunLoopBeforeWaiting:
+      cocoa_run_loop_before_waiting ();
+      break;
+    case kCFRunLoopAfterWaiting:
+      cocoa_run_loop_after_waiting ();
+      break;
+    case kCFRunLoopExit:
+      cocoa_run_loop_exit ();
+      break;
+    default:
+      break;
+    }
+}
+
+#endif
-- 
2.7.4

From a21db5fbba13c5bdf693a9ea4e4253cc41fcc1ba Mon Sep 17 00:00:00 2001
From: Matthew Waters <matthew@centricular.com>
Date: Fri, 3 Aug 2018 12:08:31 +1000
Subject: [PATCH] build: fix GMainLoop on macos for meson

Meson only takes the filename extension into account when choosing what
compiler to run so we need to copy the gmain.c which now contains objc
files and rename it to .m

Note: this is not upstream because it's only needed by us in Cerbero
because we apply an upstream WONTFIX patch that adds Cocoa event loop
integration to GMainContext.
---
 glib/meson.build | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/glib/meson.build b/glib/meson.build
index ea9bf41..9f3e087 100644
--- a/glib/meson.build
+++ b/glib/meson.build
@@ -145,7 +145,7 @@ glib_sources = files(
   'glib-init.c',
   'glib-private.c',
   'glist.c',
-  'gmain.c',
+#  'gmain.c',
   'gmappedfile.c',
   'gmarkup.c',
   'gmem.c',
@@ -196,6 +196,14 @@ glib_sources = files(
   'gprintf.c',
 )
 
+if host_system == 'darwin'
+  glib_sources += configure_file(input : 'gmain.c',
+                                output : 'gmain.m',
+                                  copy : true)
+else
+  glib_sources += 'gmain.c'
+endif
+
 if host_system == 'windows'
   glib_win_rc = configure_file(
     input: 'glib.rc.in',
-- 
2.14.3 (Apple Git-98)