summaryrefslogtreecommitdiff
path: root/gmain.c
blob: 94740a3c61428d3a03a8c354e96ed5771b7904af (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
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * gmain.c: Main loop abstraction, timeouts, and idle functions
 * Copyright 1998 Owen Taylor
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/*
 * Modified by the GLib Team and others 1997-1999.  See the AUTHORS
 * file for a list of people on the GLib Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GLib at ftp://ftp.gtk.org/pub/gtk/. 
 */

/* 
 * MT safe
 */

#include "config.h"

/* uncomment the next line to get poll() debugging info */
/* #define G_MAIN_POLL_DEBUG */



#include "glib.h"
#include <sys/types.h>
#include <time.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif /* HAVE_SYS_TIME_H */
#ifdef GLIB_HAVE_SYS_POLL_H
#  include <sys/poll.h>
#  undef events	 /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
#  undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
#endif /* GLIB_HAVE_SYS_POLL_H */
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#include <errno.h>

#ifdef NATIVE_WIN32
#define STRICT
#include <windows.h>
#endif /* NATIVE_WIN32 */

#ifdef _MSC_VER
#include <fcntl.h>
#include <io.h>
#endif /* _MSC_VER */

/* Types */

typedef struct _GTimeoutData GTimeoutData;
typedef struct _GSource GSource;
typedef struct _GPollRec GPollRec;

typedef enum
{
  G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
  G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
} GSourceFlags;

struct _GSource
{
  GHook hook;
  gint priority;
  gpointer source_data;
};

struct _GMainLoop
{
  gboolean is_running;
};

struct _GTimeoutData
{
  GTimeVal    expiration;
  gint        interval;
  GSourceFunc callback;
};

struct _GPollRec
{
  gint priority;
  GPollFD *fd;
  GPollRec *next;
};

/* Forward declarations */

static gint     g_source_compare          (GHook      *a,
					   GHook      *b);
static void     g_source_destroy_func     (GHookList  *hook_list,
					   GHook      *hook);
static void     g_main_poll               (gint      timeout,
					   gboolean  use_priority, 
					   gint      priority);
static void     g_main_add_poll_unlocked  (gint      priority,
					   GPollFD  *fd);
static void     g_main_wakeup             (void);

static gboolean g_timeout_prepare      (gpointer  source_data, 
					GTimeVal *current_time,
					gint     *timeout,
					gpointer  user_data);
static gboolean g_timeout_check        (gpointer  source_data,
					GTimeVal *current_time,
					gpointer  user_data);
static gboolean g_timeout_dispatch     (gpointer  source_data,
					GTimeVal *current_time,
					gpointer  user_data);
static gboolean g_idle_prepare         (gpointer  source_data, 
					GTimeVal *current_time,
					gint     *timeout,
					gpointer  user_data);
static gboolean g_idle_check           (gpointer  source_data,
					GTimeVal *current_time,
					gpointer  user_data);
static gboolean g_idle_dispatch        (gpointer  source_data,
					GTimeVal *current_time,
					gpointer  user_data);

/* Data */

static GSList *pending_dispatches = NULL;
static GHookList source_list = { 0 };
static gint in_check_or_prepare = 0;

/* The following lock is used for both the list of sources
 * and the list of poll records
 */
G_LOCK_DEFINE_STATIC (main_loop);

static GSourceFuncs timeout_funcs =
{
  g_timeout_prepare,
  g_timeout_check,
  g_timeout_dispatch,
  g_free,
};

static GSourceFuncs idle_funcs =
{
  g_idle_prepare,
  g_idle_check,
  g_idle_dispatch,
  NULL,
};

static GPollRec *poll_records = NULL;
static GPollRec *poll_free_list = NULL;
static GMemChunk *poll_chunk;
static guint n_poll_records = 0;

#ifdef G_THREADS_ENABLED
#ifndef NATIVE_WIN32
/* this pipe is used to wake up the main loop when a source is added.
 */
static gint wake_up_pipe[2] = { -1, -1 };
#else /* NATIVE_WIN32 */
static HANDLE wake_up_semaphore = NULL;
#endif /* NATIVE_WIN32 */
static GPollFD wake_up_rec;
static gboolean poll_waiting = FALSE;

/* Flag indicating whether the set of fd's changed during a poll */
static gboolean poll_changed = FALSE;
#endif /* G_THREADS_ENABLED */

#ifdef HAVE_POLL
/* SunOS has poll, but doesn't provide a prototype. */
#  if defined (sun) && !defined (__SVR4)
extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
#  endif  /* !sun */
static GPollFunc poll_func = (GPollFunc) poll;
#else	/* !HAVE_POLL */
#ifdef NATIVE_WIN32

static gint
g_poll (GPollFD *fds, guint nfds, gint timeout)
{
  HANDLE handles[MAXIMUM_WAIT_OBJECTS];
  GPollFD *f;
  DWORD ready;
  MSG msg;
  UINT timer;
  LONG prevcnt;
  gint poll_msgs = -1;
  gint nhandles = 0;

  for (f = fds; f < &fds[nfds]; ++f)
    if (f->fd >= 0)
      {
	if (f->events & G_IO_IN)
	  if (f->fd == G_WIN32_MSG_HANDLE)
	    poll_msgs = f - fds;
	  else
	    {
	      /* g_print ("g_poll: waiting for handle %#x\n", f->fd); */
	      handles[nhandles++] = (HANDLE) f->fd;
	    }
      }

  if (timeout == -1)
    timeout = INFINITE;

  if (poll_msgs >= 0)
    {
      /* Waiting for messages, and maybe events */
      if (nhandles == 0)
	{
	  if (timeout == INFINITE)
	    {
	      /* Waiting just for messages, infinite timeout
	       * -> Use PeekMessage, then WaitMessage
	       */
	      /* g_print ("WaitMessage, PeekMessage\n"); */
	      if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
		ready = WAIT_OBJECT_0;
	      else if (!WaitMessage ())
		g_warning ("g_poll: WaitMessage failed");
	      ready = WAIT_OBJECT_0;
	    }
	  else if (timeout == 0)
	    {
	      /* Waiting just for messages, zero timeout
	       * -> Use PeekMessage
	       */
	      /* g_print ("PeekMessage\n"); */
	      if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
		ready = WAIT_OBJECT_0;
	      else
		ready = WAIT_TIMEOUT;
	    }
	  else
	    {
	      /* Waiting just for messages, some timeout
	       * -> First try PeekMessage, then set a timer, wait for message,
	       * kill timer, use PeekMessage
	       */
	      /* g_print ("PeekMessage\n"); */
	      if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
		ready = WAIT_OBJECT_0;
	      else if ((timer = SetTimer (NULL, 0, timeout, NULL)) == 0)
		g_warning ("g_poll: SetTimer failed");
	      else
		{
		  /* g_print ("WaitMessage\n"); */
		  WaitMessage ();
		  KillTimer (NULL, timer);
		  if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
		    ready = WAIT_OBJECT_0;
		  else
		    ready = WAIT_TIMEOUT;
		}
	    }
	}
      else
	{
	  /* Wait for either message or event
	   * -> Use MsgWaitForMultipleObjects
	   */
	  /* g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout); */
	  ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
					     timeout, QS_ALLINPUT);
	  /* g_print("=%d\n", ready); */
	  if (ready == WAIT_FAILED)
	    g_warning ("g_poll: MsgWaitForMultipleObjects failed");
	}
    }
  else if (nhandles == 0)
    {
      /* Wait for nothing (huh?) */
      return 0;
    }
  else
    {
      /* Wait for just events
       * -> Use WaitForMultipleObjects
       */
      /* g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout); */
      ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
      /* g_print("=%d\n", ready); */
      if (ready == WAIT_FAILED)
	g_warning ("g_poll: WaitForMultipleObjects failed");
    }

  for (f = fds; f < &fds[nfds]; ++f)
    f->revents = 0;

  if (ready == WAIT_FAILED)
    return -1;
  else if (poll_msgs >= 0 && ready == WAIT_OBJECT_0 + nhandles)
    {
      fds[poll_msgs].revents |= G_IO_IN;
    }
  else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
    for (f = fds; f < &fds[nfds]; ++f)
      {
	if ((f->events & G_IO_IN)
	    && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
	  {
	    f->revents |= G_IO_IN;
	    /* g_print ("event %#x\n", f->fd); */
	    ResetEvent ((HANDLE) f->fd);
	  }
      }
    
  if (ready == WAIT_TIMEOUT)
    return 0;
  else
    return 1;
}

#else  /* !NATIVE_WIN32 */

/* The following implementation of poll() comes from the GNU C Library.
 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
 */

#include <string.h> /* for bzero on BSD systems */

#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif /* HAVE_SYS_SELECT_H_ */

#ifndef NO_FD_SET
#  define SELECT_MASK fd_set
#else /* !NO_FD_SET */
#  ifndef _AIX
typedef long fd_mask;
#  endif /* _AIX */
#  ifdef _IBMR2
#    define SELECT_MASK void
#  else /* !_IBMR2 */
#    define SELECT_MASK int
#  endif /* !_IBMR2 */
#endif /* !NO_FD_SET */

static gint 
g_poll (GPollFD *fds,
	guint    nfds,
	gint     timeout)
{
  struct timeval tv;
  SELECT_MASK rset, wset, xset;
  GPollFD *f;
  int ready;
  int maxfd = 0;

  FD_ZERO (&rset);
  FD_ZERO (&wset);
  FD_ZERO (&xset);

  for (f = fds; f < &fds[nfds]; ++f)
    if (f->fd >= 0)
      {
	if (f->events & G_IO_IN)
	  FD_SET (f->fd, &rset);
	if (f->events & G_IO_OUT)
	  FD_SET (f->fd, &wset);
	if (f->events & G_IO_PRI)
	  FD_SET (f->fd, &xset);
	if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
	  maxfd = f->fd;
      }

  tv.tv_sec = timeout / 1000;
  tv.tv_usec = (timeout % 1000) * 1000;

  ready = select (maxfd + 1, &rset, &wset, &xset,
		  timeout == -1 ? NULL : &tv);
  if (ready > 0)
    for (f = fds; f < &fds[nfds]; ++f)
      {
	f->revents = 0;
	if (f->fd >= 0)
	  {
	    if (FD_ISSET (f->fd, &rset))
	      f->revents |= G_IO_IN;
	    if (FD_ISSET (f->fd, &wset))
	      f->revents |= G_IO_OUT;
	    if (FD_ISSET (f->fd, &xset))
	      f->revents |= G_IO_PRI;
	  }
      }

  return ready;
}

#endif /* !NATIVE_WIN32 */

static GPollFunc poll_func = g_poll;
#endif	/* !HAVE_POLL */

/* Hooks for adding to the main loop */

/* Use knowledge of insert_sorted algorithm here to make
 * sure we insert at the end of equal priority items
 */
static gint
g_source_compare (GHook *a,
		  GHook *b)
{
  GSource *source_a = (GSource *)a;
  GSource *source_b = (GSource *)b;

  return (source_a->priority < source_b->priority) ? -1 : 1;
}

/* HOLDS: main_loop lock */
static void
g_source_destroy_func (GHookList *hook_list,
		       GHook     *hook)
{
  GSource *source = (GSource*) hook;
  GDestroyNotify destroy;

  G_UNLOCK (main_loop);

  destroy = hook->destroy;
  if (destroy)
    destroy (hook->data);

  destroy = ((GSourceFuncs*) hook->func)->destroy;
  if (destroy)
    destroy (source->source_data);

  G_LOCK (main_loop);
}

guint 
g_source_add (gint           priority,
	      gboolean       can_recurse,
	      GSourceFuncs  *funcs,
	      gpointer       source_data, 
	      gpointer       user_data,
	      GDestroyNotify notify)
{
  guint return_val;
  GSource *source;

  G_LOCK (main_loop);

  if (!source_list.is_setup)
    {
      g_hook_list_init (&source_list, sizeof (GSource));

      source_list.hook_destroy = G_HOOK_DEFERRED_DESTROY;
      source_list.hook_free = g_source_destroy_func;
    }

  source = (GSource*) g_hook_alloc (&source_list);
  source->priority = priority;
  source->source_data = source_data;
  source->hook.func = funcs;
  source->hook.data = user_data;
  source->hook.destroy = notify;
  
  g_hook_insert_sorted (&source_list, 
			(GHook *)source, 
			g_source_compare);

  if (can_recurse)
    source->hook.flags |= G_SOURCE_CAN_RECURSE;

  return_val = source->hook.hook_id;

#ifdef G_THREADS_ENABLED
  /* Now wake up the main loop if it is waiting in the poll() */
  g_main_wakeup ();
#endif

  G_UNLOCK (main_loop);

  return return_val;
}

gboolean
g_source_remove (guint tag)
{
  GHook *hook;

  g_return_val_if_fail (tag > 0, FALSE);

  G_LOCK (main_loop);

  hook = g_hook_get (&source_list, tag);
  if (hook)
    g_hook_destroy_link (&source_list, hook);

  G_UNLOCK (main_loop);

  return hook != NULL;
}

gboolean
g_source_remove_by_user_data (gpointer user_data)
{
  GHook *hook;
  
  G_LOCK (main_loop);
  
  hook = g_hook_find_data (&source_list, TRUE, user_data);
  if (hook)
    g_hook_destroy_link (&source_list, hook);

  G_UNLOCK (main_loop);

  return hook != NULL;
}

static gboolean
g_source_find_source_data (GHook	*hook,
			   gpointer	 data)
{
  GSource *source = (GSource *)hook;

  return (source->source_data == data);
}

gboolean
g_source_remove_by_source_data (gpointer source_data)
{
  GHook *hook;

  G_LOCK (main_loop);

  hook = g_hook_find (&source_list, TRUE, 
		      g_source_find_source_data, source_data);
  if (hook)
    g_hook_destroy_link (&source_list, hook);

  G_UNLOCK (main_loop);

  return hook != NULL;
}

static gboolean
g_source_find_funcs_user_data (GHook   *hook,
			       gpointer data)
{
  gpointer *d = data;

  return hook->func == d[0] && hook->data == d[1];
}

gboolean
g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
				    gpointer      user_data)
{
  gpointer d[2];
  GHook *hook;

  g_return_val_if_fail (funcs != NULL, FALSE);

  G_LOCK (main_loop);

  d[0] = funcs;
  d[1] = user_data;

  hook = g_hook_find (&source_list, TRUE,
		      g_source_find_funcs_user_data, d);
  if (hook)
    g_hook_destroy_link (&source_list, hook);

  G_UNLOCK (main_loop);

  return hook != NULL;
}

void
g_get_current_time (GTimeVal *result)
{
#ifndef _MSC_VER
  struct timeval r;
  g_return_if_fail (result != NULL);

  /*this is required on alpha, there the timeval structs are int's
    not longs and a cast only would fail horribly*/
  gettimeofday (&r, NULL);
  result->tv_sec = r.tv_sec;
  result->tv_usec = r.tv_usec;
#else
  /* Avoid calling time() except for the first time.
   * GetTickCount() should be pretty fast and low-level?
   * I could also use ftime() but it seems unnecessarily overheady.
   */
  static DWORD start_tick = 0;
  static time_t start_time;
  DWORD tick;
  time_t t;

  g_return_if_fail (result != NULL);
 
  if (start_tick == 0)
    {
      start_tick = GetTickCount ();
      time (&start_time);
    }

  tick = GetTickCount ();

  result->tv_sec = (tick - start_tick) / 1000 + start_time;
  result->tv_usec = ((tick - start_tick) % 1000) * 1000;
#endif
}

/* Running the main loop */

/* HOLDS: main_loop_lock */
static void
g_main_dispatch (GTimeVal *current_time)
{
  while (pending_dispatches != NULL)
    {
      gboolean need_destroy;
      GSource *source = pending_dispatches->data;
      GSList *tmp_list;

      tmp_list = pending_dispatches;
      pending_dispatches = g_slist_remove_link (pending_dispatches, pending_dispatches);
      g_slist_free_1 (tmp_list);

      if (G_HOOK_IS_VALID (source))
	{
	  gboolean was_in_call;
	  gpointer hook_data = source->hook.data;
	  gpointer source_data = source->source_data;
	  gboolean (*dispatch) (gpointer,
				GTimeVal *,
				gpointer);

	  dispatch = ((GSourceFuncs *) source->hook.func)->dispatch;
	  
	  was_in_call = G_HOOK_IN_CALL (source);
	  source->hook.flags |= G_HOOK_FLAG_IN_CALL;

	  G_UNLOCK (main_loop);
	  need_destroy = ! dispatch (source_data,
				     current_time,
				     hook_data);
	  G_LOCK (main_loop);

	  if (!was_in_call)
	    source->hook.flags &= ~G_HOOK_FLAG_IN_CALL;
	  
	  if (need_destroy && G_HOOK_IS_VALID (source))
	    g_hook_destroy_link (&source_list, (GHook *) source);
	}

      g_hook_unref (&source_list, (GHook*) source);
    }
}

/* g_main_iterate () runs a single iteration of the mainloop, or,
 * if !dispatch checks to see if any sources need dispatching.
 * basic algorithm for dispatch=TRUE:
 *
 * 1) while the list of currently pending sources is non-empty,
 *    we call (*dispatch) on those that are !IN_CALL or can_recurse,
 *    removing sources from the list after each returns.
 *    the return value of (*dispatch) determines whether the source
 *    itself is kept alive.
 *
 * 2) call (*prepare) for sources that are not yet SOURCE_READY and
 *    are !IN_CALL or can_recurse. a return value of TRUE determines
 *    that the source would like to be dispatched immediatedly, it
 *    is then flagged as SOURCE_READY.
 *
 * 3) poll with the pollfds from all sources at the priority of the
 *    first source flagged as SOURCE_READY. if there are any sources
 *    flagged as SOURCE_READY, we use a timeout of 0 or the minimum
 *    of all timouts otherwise.
 *
 * 4) for each source !IN_CALL or can_recurse, if SOURCE_READY or
 *    (*check) returns true, add the source to the pending list.
 *    once one source returns true, stop after checking all sources
 *    at that priority.
 *
 * 5) while the list of currently pending sources is non-empty,
 *    call (*dispatch) on each source, removing the source
 *    after the call.
 *
 */
static gboolean
g_main_iterate (gboolean block,
		gboolean dispatch)
{
  GHook *hook;
  GTimeVal current_time  ={ 0, 0 };
  gint n_ready = 0;
  gint current_priority = 0;
  gint timeout;
  gboolean retval = FALSE;

  g_return_val_if_fail (!block || dispatch, FALSE);

  g_get_current_time (&current_time);

  G_LOCK (main_loop);

#ifdef G_THREADS_ENABLED
  if (poll_waiting)
    {
      g_warning("g_main_iterate(): main loop already active in another thread");
      G_UNLOCK (main_loop);
      return FALSE;
    }
#endif G_THREADS_ENABLED  
  
  /* If recursing, finish up current dispatch, before starting over */
  if (pending_dispatches)
    {
      if (dispatch)
	g_main_dispatch (&current_time);
      
      G_UNLOCK (main_loop);

      return TRUE;
    }

  /* Prepare all sources */

  timeout = block ? -1 : 0;
  
  hook = g_hook_first_valid (&source_list, TRUE);
  while (hook)
    {
      GSource *source = (GSource*) hook;
      gint source_timeout = -1;

      if ((n_ready > 0) && (source->priority > current_priority))
	{
	  g_hook_unref (&source_list, hook);
	  break;
	}
      if (G_HOOK_IN_CALL (hook) && !(hook->flags & G_SOURCE_CAN_RECURSE))
	{
	  hook = g_hook_next_valid (&source_list, hook, TRUE);
	  continue;
	}

      if (!(hook->flags & G_SOURCE_READY))
	{
	  gboolean (*prepare)  (gpointer  source_data, 
				GTimeVal *current_time,
				gint     *timeout,
				gpointer  user_data);

	  prepare = ((GSourceFuncs *) hook->func)->prepare;
	  in_check_or_prepare++;
	  G_UNLOCK (main_loop);

	  if ((*prepare) (source->source_data, &current_time, &source_timeout, source->hook.data))
	    hook->flags |= G_SOURCE_READY;
	  
	  G_LOCK (main_loop);
	  in_check_or_prepare--;
	}

      if (hook->flags & G_SOURCE_READY)
	{
	  if (!dispatch)
	    {
	      g_hook_unref (&source_list, hook);
	      G_UNLOCK (main_loop);

	      return TRUE;
	    }
	  else
	    {
	      n_ready++;
	      current_priority = source->priority;
	      timeout = 0;
	    }
	}
      
      if (source_timeout >= 0)
	{
	  if (timeout < 0)
	    timeout = source_timeout;
	  else
	    timeout = MIN (timeout, source_timeout);
	}

      hook = g_hook_next_valid (&source_list, hook, TRUE);
    }

  /* poll(), if necessary */

  g_main_poll (timeout, n_ready > 0, current_priority);

  /* Check to see what sources need to be dispatched */

  n_ready = 0;
  
  hook = g_hook_first_valid (&source_list, TRUE);
  while (hook)
    {
      GSource *source = (GSource *)hook;

      if ((n_ready > 0) && (source->priority > current_priority))
	{
	  g_hook_unref (&source_list, hook);
	  break;
	}
      if (G_HOOK_IN_CALL (hook) && !(hook->flags & G_SOURCE_CAN_RECURSE))
	{
	  hook = g_hook_next_valid (&source_list, hook, TRUE);
	  continue;
	}

      if (!(hook->flags & G_SOURCE_READY))
	{
	  gboolean (*check) (gpointer  source_data,
			     GTimeVal *current_time,
			     gpointer  user_data);

	  check = ((GSourceFuncs *) hook->func)->check;
	  in_check_or_prepare++;
	  G_UNLOCK (main_loop);
	  
	  if ((*check) (source->source_data, &current_time, source->hook.data))
	    hook->flags |= G_SOURCE_READY;

	  G_LOCK (main_loop);
	  in_check_or_prepare--;
	}

      if (hook->flags & G_SOURCE_READY)
	{
	  if (dispatch)
	    {
	      hook->flags &= ~G_SOURCE_READY;
	      g_hook_ref (&source_list, hook);
	      pending_dispatches = g_slist_prepend (pending_dispatches, source);
	      current_priority = source->priority;
	      n_ready++;
	    }
	  else
	    {
	      g_hook_unref (&source_list, hook);
	      G_UNLOCK (main_loop);

	      return TRUE;
	    }
	}
      
      hook = g_hook_next_valid (&source_list, hook, TRUE);
    }
 
  /* Now invoke the callbacks */

  if (pending_dispatches)
    {
      pending_dispatches = g_slist_reverse (pending_dispatches);
      g_main_dispatch (&current_time);
      retval = TRUE;
    }

  G_UNLOCK (main_loop);

  return retval;
}

/* See if any events are pending
 */
gboolean 
g_main_pending (void)
{
  return in_check_or_prepare ? FALSE : g_main_iterate (FALSE, FALSE);
}

/* Run a single iteration of the mainloop. If block is FALSE,
 * will never block
 */
gboolean
g_main_iteration (gboolean block)
{
  if (in_check_or_prepare)
    {
      g_warning ("g_main_iteration(): called recursively from within a source's check() or "
		 "prepare() member or from a second thread, iteration not possible");
      return FALSE;
    }
  else
    return g_main_iterate (block, TRUE);
}

GMainLoop*
g_main_new (gboolean is_running)
{
  GMainLoop *loop;

  loop = g_new0 (GMainLoop, 1);
  loop->is_running = is_running != FALSE;

  return loop;
}

void 
g_main_run (GMainLoop *loop)
{
  g_return_if_fail (loop != NULL);

  if (in_check_or_prepare)
    {
      g_warning ("g_main_run(): called recursively from within a source's check() or "
		 "prepare() member or from a second thread, iteration not possible");
      return;
    }
  
  loop->is_running = TRUE;
  while (loop->is_running)
    g_main_iterate (TRUE, TRUE);
}

void 
g_main_quit (GMainLoop *loop)
{
  g_return_if_fail (loop != NULL);

  loop->is_running = FALSE;
}

void 
g_main_destroy (GMainLoop *loop)
{
  g_return_if_fail (loop != NULL);

  g_free (loop);
}

gboolean
g_main_is_running (GMainLoop *loop)
{
  g_return_val_if_fail (loop != NULL, FALSE);

  return loop->is_running;
}

/* HOLDS: main_loop_lock */
static void
g_main_poll (gint     timeout,
	     gboolean use_priority,
	     gint     priority)
{
#ifdef  G_MAIN_POLL_DEBUG
  GTimer *poll_timer;
#endif
  GPollFD *fd_array;
  GPollRec *pollrec;
  gint i;
  gint npoll;

#ifdef G_THREADS_ENABLED
#ifndef NATIVE_WIN32
  if (wake_up_pipe[0] < 0)
    {
      if (pipe (wake_up_pipe) < 0)
	g_error ("Cannot create pipe main loop wake-up: %s\n",
		 g_strerror (errno));

      wake_up_rec.fd = wake_up_pipe[0];
      wake_up_rec.events = G_IO_IN;
      g_main_add_poll_unlocked (0, &wake_up_rec);
    }
#else
  if (wake_up_semaphore == NULL)
    {
      if ((wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL)) == NULL)
	g_error ("Cannot create wake-up semaphore: %d", GetLastError ());
      wake_up_rec.fd = (gint) wake_up_semaphore;
      wake_up_rec.events = G_IO_IN;
      g_main_add_poll_unlocked (0, &wake_up_rec);
    }
#endif
#endif
  fd_array = g_new (GPollFD, n_poll_records);
 
  pollrec = poll_records;
  i = 0;
  while (pollrec && (!use_priority || priority >= pollrec->priority))
    {
      if (pollrec->fd->events)
	{
	  fd_array[i].fd = pollrec->fd->fd;
	  /* In direct contradiction to the Unix98 spec, IRIX runs into
	   * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
	   * flags in the events field of the pollfd while it should
	   * just ignoring them. So we mask them out here.
	   */
	  fd_array[i].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
	  fd_array[i].revents = 0;
	  i++;
	}
      
      pollrec = pollrec->next;
    }
#ifdef G_THREADS_ENABLED
  poll_waiting = TRUE;
  poll_changed = FALSE;
#endif
  
  npoll = i;
  if (npoll || timeout != 0)
    {
#ifdef	G_MAIN_POLL_DEBUG
      g_print ("g_main_poll(%d) timeout: %d\r", npoll, timeout);
      poll_timer = g_timer_new ();
#endif
      
      G_UNLOCK (main_loop);
      (*poll_func) (fd_array, npoll, timeout);
      G_LOCK (main_loop);
      
#ifdef	G_MAIN_POLL_DEBUG
      g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
	       npoll,
	       timeout,
	       g_timer_elapsed (poll_timer, NULL));
      g_timer_destroy (poll_timer);
      pollrec = poll_records;
      i = 0;
      while (i < npoll)
	{
	  if (pollrec->fd->events)
	    {
	      if (fd_array[i].revents)
		{
		  g_print (" [%d:", fd_array[i].fd);
		  if (fd_array[i].revents & G_IO_IN)
		    g_print ("i");
		  if (fd_array[i].revents & G_IO_OUT)
		    g_print ("o");
		  if (fd_array[i].revents & G_IO_PRI)
		    g_print ("p");
		  if (fd_array[i].revents & G_IO_ERR)
		    g_print ("e");
		  if (fd_array[i].revents & G_IO_HUP)
		    g_print ("h");
		  if (fd_array[i].revents & G_IO_NVAL)
		    g_print ("n");
		  g_print ("]");
		}
	      i++;
	    }
	  pollrec = pollrec->next;
	}
      g_print ("\n");
#endif
    } /* if (npoll || timeout != 0) */
  
#ifdef G_THREADS_ENABLED
  if (!poll_waiting)
    {
#ifndef NATIVE_WIN32
      gchar c;
      read (wake_up_pipe[0], &c, 1);
#endif
    }
  else
    poll_waiting = FALSE;

  /* If the set of poll file descriptors changed, bail out
   * and let the main loop rerun
   */
  if (poll_changed)
    {
      g_free (fd_array);
      return;
    }
#endif

  pollrec = poll_records;
  i = 0;
  while (i < npoll)
    {
      if (pollrec->fd->events)
	{
	  pollrec->fd->revents = fd_array[i].revents;
	  i++;
	}
      pollrec = pollrec->next;
    }

  g_free (fd_array);
}

void 
g_main_add_poll (GPollFD *fd,
		 gint     priority)
{
  G_LOCK (main_loop);
  g_main_add_poll_unlocked (priority, fd);
  G_UNLOCK (main_loop);
}

/* HOLDS: main_loop_lock */
static void 
g_main_add_poll_unlocked (gint     priority,
			  GPollFD *fd)
{
  GPollRec *lastrec, *pollrec, *newrec;

  if (!poll_chunk)
    poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);

  if (poll_free_list)
    {
      newrec = poll_free_list;
      poll_free_list = newrec->next;
    }
  else
    newrec = g_chunk_new (GPollRec, poll_chunk);

  newrec->fd = fd;
  newrec->priority = priority;

  lastrec = NULL;
  pollrec = poll_records;
  while (pollrec && priority >= pollrec->priority)
    {
      lastrec = pollrec;
      pollrec = pollrec->next;
    }
  
  if (lastrec)
    lastrec->next = newrec;
  else
    poll_records = newrec;

  newrec->next = pollrec;

  n_poll_records++;

#ifdef G_THREADS_ENABLED
  poll_changed = TRUE;

  /* Now wake up the main loop if it is waiting in the poll() */
  g_main_wakeup ();
#endif
}

void 
g_main_remove_poll (GPollFD *fd)
{
  GPollRec *pollrec, *lastrec;

  G_LOCK (main_loop);
  
  lastrec = NULL;
  pollrec = poll_records;

  while (pollrec)
    {
      if (pollrec->fd == fd)
	{
	  if (lastrec != NULL)
	    lastrec->next = pollrec->next;
	  else
	    poll_records = pollrec->next;

	  pollrec->next = poll_free_list;
	  poll_free_list = pollrec;

	  n_poll_records--;
	  break;
	}
      lastrec = pollrec;
      pollrec = pollrec->next;
    }

#ifdef G_THREADS_ENABLED
  poll_changed = TRUE;
  
  /* Now wake up the main loop if it is waiting in the poll() */
  g_main_wakeup ();
#endif

  G_UNLOCK (main_loop);
}

void 
g_main_set_poll_func (GPollFunc func)
{
  if (func)
    poll_func = func;
  else
#ifdef HAVE_POLL
    poll_func = (GPollFunc) poll;
#else
    poll_func = (GPollFunc) g_poll;
#endif
}

/* Wake the main loop up from a poll() */
static void
g_main_wakeup (void)
{
#ifdef G_THREADS_ENABLED
  if (poll_waiting)
    {
      poll_waiting = FALSE;
#ifndef NATIVE_WIN32
      write (wake_up_pipe[1], "A", 1);
#else
      ReleaseSemaphore (wake_up_semaphore, 1, NULL);
#endif
    }
#endif
}

/* Timeouts */

static gboolean 
g_timeout_prepare  (gpointer  source_data, 
		    GTimeVal *current_time,
		    gint     *timeout,
		    gpointer  user_data)
{
  glong msec;
  GTimeoutData *data = source_data;

  msec = (data->expiration.tv_sec  - current_time->tv_sec) * 1000 +
         (data->expiration.tv_usec - current_time->tv_usec) / 1000;

  *timeout = (msec <= 0) ? 0 : msec;

  return (msec <= 0);
}

static gboolean 
g_timeout_check (gpointer  source_data,
		 GTimeVal *current_time,
		 gpointer  user_data)
{
  GTimeoutData *data = source_data;

  return (data->expiration.tv_sec < current_time->tv_sec) ||
         ((data->expiration.tv_sec == current_time->tv_sec) &&
	  (data->expiration.tv_usec <= current_time->tv_usec));
}

static gboolean
g_timeout_dispatch (gpointer source_data, 
		    GTimeVal *current_time,
		    gpointer user_data)
{
  GTimeoutData *data = source_data;

  if (data->callback (user_data))
    {
      guint seconds = data->interval / 1000;
      guint msecs = data->interval - seconds * 1000;

      data->expiration.tv_sec = current_time->tv_sec + seconds;
      data->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
      if (data->expiration.tv_usec >= 1000000)
	{
	  data->expiration.tv_usec -= 1000000;
	  data->expiration.tv_sec++;
	}
      return TRUE;
    }
  else
    return FALSE;
}

guint 
g_timeout_add_full (gint           priority,
		    guint          interval, 
		    GSourceFunc    function,
		    gpointer       data,
		    GDestroyNotify notify)
{
  guint seconds;
  guint msecs;
  GTimeoutData *timeout_data = g_new (GTimeoutData, 1);

  timeout_data->interval = interval;
  timeout_data->callback = function;
  g_get_current_time (&timeout_data->expiration);

  seconds = timeout_data->interval / 1000;
  msecs = timeout_data->interval - seconds * 1000;

  timeout_data->expiration.tv_sec += seconds;
  timeout_data->expiration.tv_usec += msecs * 1000;
  if (timeout_data->expiration.tv_usec >= 1000000)
    {
      timeout_data->expiration.tv_usec -= 1000000;
      timeout_data->expiration.tv_sec++;
    }

  return g_source_add (priority, FALSE, &timeout_funcs, timeout_data, data, notify);
}

guint 
g_timeout_add (guint32        interval,
	       GSourceFunc    function,
	       gpointer       data)
{
  return g_timeout_add_full (G_PRIORITY_DEFAULT, 
			     interval, function, data, NULL);
}

/* Idle functions */

static gboolean 
g_idle_prepare  (gpointer  source_data, 
		 GTimeVal *current_time,
		 gint     *timeout,
		 gpointer  user_data)
{
  timeout = 0;
  return TRUE;
}

static gboolean 
g_idle_check    (gpointer  source_data,
		 GTimeVal *current_time,
		 gpointer  user_data)
{
  return TRUE;
}

static gboolean
g_idle_dispatch (gpointer source_data, 
		 GTimeVal *current_time,
		 gpointer user_data)
{
  GSourceFunc func = source_data;

  return func (user_data);
}

guint 
g_idle_add_full (gint           priority,
		 GSourceFunc    function,
		 gpointer       data,
		 GDestroyNotify notify)
{
  g_return_val_if_fail (function != NULL, 0);

  return g_source_add (priority, FALSE, &idle_funcs, function, data, notify);
}

guint 
g_idle_add (GSourceFunc    function,
	    gpointer       data)
{
  return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
}

gboolean
g_idle_remove_by_data (gpointer data)
{
  return g_source_remove_by_funcs_user_data (&idle_funcs, data);
}