gmain.c 31.5 KB
Newer Older
1 2 3 4 5 6 7
/* 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
8
 * modify it under the terms of the GNU Lesser General Public
9 10 11 12 13 14
 * 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
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18 19 20 21 22
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

23
/*
24
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
25 26 27 28 29
 * 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/. 
 */

30 31 32 33
/* 
 * MT safe
 */

34 35
#include "config.h"

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

39
#include "glib.h"
40
#include <sys/types.h>
41 42
#include <time.h>
#ifdef HAVE_SYS_TIME_H
43
#include <sys/time.h>
44 45
#endif /* HAVE_SYS_TIME_H */
#ifdef GLIB_HAVE_SYS_POLL_H
46 47 48
#  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 */
49
#endif /* GLIB_HAVE_SYS_POLL_H */
50
#ifdef HAVE_UNISTD_H
51
#include <unistd.h>
52
#endif /* HAVE_UNISTD_H */
53
#include <errno.h>
54

55
#ifdef G_OS_WIN32
56 57
#define STRICT
#include <windows.h>
58
#endif /* G_OS_WIN32 */
59

60
#ifdef G_OS_BEOS
61
#include <net/socket.h>
62
#endif /* G_OS_BEOS */
63

64 65 66 67 68 69
/* Types */

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

70 71
typedef enum
{
72 73 74 75
  G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
  G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
} GSourceFlags;

76 77
struct _GSource
{
78 79 80 81 82
  GHook hook;
  gint priority;
  gpointer source_data;
};

83 84
struct _GMainLoop
{
85
  gboolean is_running;
86 87
};

88 89
struct _GTimeoutData
{
90 91 92 93 94
  GTimeVal    expiration;
  gint        interval;
  GSourceFunc callback;
};

95 96
struct _GPollRec
{
97 98 99 100 101 102 103
  gint priority;
  GPollFD *fd;
  GPollRec *next;
};

/* Forward declarations */

104 105
static gint     g_source_compare          (GHook      *a,
					   GHook      *b);
106
static void     g_source_destroy_func     (GHookList  *hook_list,
107
					   GHook      *hook);
108 109 110
static void     g_main_poll               (gint      timeout,
					   gboolean  use_priority, 
					   gint      priority);
111
static void     g_main_add_poll_unlocked  (gint      priority,
112
					   GPollFD  *fd);
113
static void     g_main_wakeup             (void);
114

115 116
static gboolean g_timeout_prepare      (gpointer  source_data, 
					GTimeVal *current_time,
117 118
					gint     *timeout,
					gpointer  user_data);
119
static gboolean g_timeout_check        (gpointer  source_data,
120 121
					GTimeVal *current_time,
					gpointer  user_data);
122
static gboolean g_timeout_dispatch     (gpointer  source_data,
123
					GTimeVal *dispatch_time,
124 125 126
					gpointer  user_data);
static gboolean g_idle_prepare         (gpointer  source_data, 
					GTimeVal *current_time,
127 128
					gint     *timeout,
					gpointer  user_data);
129
static gboolean g_idle_check           (gpointer  source_data,
130 131
					GTimeVal *current_time,
					gpointer  user_data);
132
static gboolean g_idle_dispatch        (gpointer  source_data,
133
					GTimeVal *dispatch_time,
134 135 136 137 138 139
					gpointer  user_data);

/* Data */

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

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

147 148
static GSourceFuncs timeout_funcs =
{
149 150 151
  g_timeout_prepare,
  g_timeout_check,
  g_timeout_dispatch,
152
  g_free,
153 154
};

155 156
static GSourceFuncs idle_funcs =
{
157 158 159
  g_idle_prepare,
  g_idle_check,
  g_idle_dispatch,
160
  NULL,
161 162
};

163 164 165 166 167
static GPollRec *poll_records = NULL;
static GPollRec *poll_free_list = NULL;
static GMemChunk *poll_chunk;
static guint n_poll_records = 0;

168
#ifdef G_THREADS_ENABLED
169
#ifndef G_OS_WIN32
170 171 172
/* this pipe is used to wake up the main loop when a source is added.
 */
static gint wake_up_pipe[2] = { -1, -1 };
173
#else /* G_OS_WIN32 */
174
static HANDLE wake_up_semaphore = NULL;
175
#endif /* G_OS_WIN32 */
176 177
static GPollFD wake_up_rec;
static gboolean poll_waiting = FALSE;
178 179 180

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

183
#ifdef HAVE_POLL
184 185 186 187
/* 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 */
188 189
static GPollFunc poll_func = (GPollFunc) poll;
#else	/* !HAVE_POLL */
190
#ifdef G_OS_WIN32
191 192

static gint
193 194 195
g_poll (GPollFD *fds,
	guint    nfds,
	gint     timeout)
196 197
{
  HANDLE handles[MAXIMUM_WAIT_OBJECTS];
198
  gboolean poll_msgs = FALSE;
199 200 201 202 203 204 205 206 207 208
  GPollFD *f;
  DWORD ready;
  MSG msg;
  UINT timer;
  gint nhandles = 0;

  for (f = fds; f < &fds[nfds]; ++f)
    if (f->fd >= 0)
      {
	if (f->events & G_IO_IN)
209 210 211 212 213 214 215 216 217 218 219
	  {
	    if (f->fd == G_WIN32_MSG_HANDLE)
	      poll_msgs = TRUE;
	    else
	      {
#ifdef G_MAIN_POLL_DEBUG
		g_print ("g_poll: waiting for %#x\n", f->fd);
#endif
		handles[nhandles++] = (HANDLE) f->fd;
	      }
	  }
220 221 222 223 224
      }

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

225
  if (poll_msgs)
226 227 228 229 230 231 232 233 234
    {
      /* Waiting for messages, and maybe events */
      if (nhandles == 0)
	{
	  if (timeout == INFINITE)
	    {
	      /* Waiting just for messages, infinite timeout
	       * -> Use PeekMessage, then WaitMessage
	       */
235 236 237
#ifdef G_MAIN_POLL_DEBUG
	      g_print ("PeekMessage, then WaitMessage\n");
#endif
238 239 240 241 242 243 244 245 246 247 248
	      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
	       */
249 250 251
#ifdef G_MAIN_POLL_DEBUG
	      g_print ("PeekMessage\n");
#endif
252 253 254 255 256 257 258 259 260 261 262
	      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
	       */
263 264 265
#ifdef G_MAIN_POLL_DEBUG
	      g_print ("PeekMessage\n");
#endif
266 267 268 269 270 271
	      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
		{
272 273 274
#ifdef G_MAIN_POLL_DEBUG
		  g_print ("WaitMessage\n");
#endif
275 276
		  WaitMessage ();
		  KillTimer (NULL, timer);
277 278
		  if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
		      && msg.message != WM_TIMER)
279 280 281 282 283 284 285 286 287 288 289
		    ready = WAIT_OBJECT_0;
		  else
		    ready = WAIT_TIMEOUT;
		}
	    }
	}
      else
	{
	  /* Wait for either message or event
	   * -> Use MsgWaitForMultipleObjects
	   */
290 291 292
#ifdef G_MAIN_POLL_DEBUG
	  g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
#endif
293 294
	  ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
					     timeout, QS_ALLINPUT);
295

296 297 298 299 300 301 302 303 304 305 306 307 308 309
	  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
       */
310 311 312
#ifdef G_MAIN_POLL_DEBUG
      g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
#endif
313 314 315 316 317 318 319 320 321 322
      ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
      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;
323 324 325
  else if (ready == WAIT_TIMEOUT)
    return 0;
  else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
326
    {
327 328 329 330 331 332 333
      for (f = fds; f < &fds[nfds]; ++f)
	if (f->fd >= 0)
	  {
	    if (f->events & G_IO_IN)
	      if (f->fd == G_WIN32_MSG_HANDLE)
		f->revents |= G_IO_IN;
	  }
334 335 336 337 338 339 340 341
    }
  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;
342 343 344 345
#ifdef G_MAIN_POLL_DEBUG
	    g_print ("g_poll: got event %#x\n", f->fd);
#endif
#if 0
346
	    ResetEvent ((HANDLE) f->fd);
347
#endif
348 349 350
	  }
      }
    
351 352
  if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
    return ready - WAIT_OBJECT_0 + 1;
353
  else
354
    return 0;
355 356
}

357
#else  /* !G_OS_WIN32 */
358 359 360 361 362

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

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

365 366
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
367
#endif /* HAVE_SYS_SELECT_H */
368

369
#ifdef G_OS_BEOS
370
#undef NO_FD_SET
371
#endif /* G_OS_BEOS */
372

373 374
#ifndef NO_FD_SET
#  define SELECT_MASK fd_set
375
#else /* !NO_FD_SET */
376 377 378
#  ifndef _AIX
typedef long fd_mask;
#  endif /* _AIX */
379
#  ifdef _IBMR2
380
#    define SELECT_MASK void
381
#  else /* !_IBMR2 */
382
#    define SELECT_MASK int
383 384
#  endif /* !_IBMR2 */
#endif /* !NO_FD_SET */
385 386

static gint 
387 388 389
g_poll (GPollFD *fds,
	guint    nfds,
	gint     timeout)
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
{
  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);
410
	if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
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
	  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;
}
436

437
#endif /* !G_OS_WIN32 */
438

439
static GPollFunc poll_func = g_poll;
440
#endif	/* !HAVE_POLL */
441 442 443 444 445 446 447

/* 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
448 449
g_source_compare (GHook *a,
		  GHook *b)
450 451 452 453 454 455 456
{
  GSource *source_a = (GSource *)a;
  GSource *source_b = (GSource *)b;

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

457
/* HOLDS: main_loop lock */
458
static void
459 460
g_source_destroy_func (GHookList *hook_list,
		       GHook     *hook)
461
{
462 463
  GSource *source = (GSource*) hook;
  GDestroyNotify destroy;
464

465 466 467 468 469 470 471 472 473 474 475
  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);
476 477
}

478 479 480 481 482 483 484 485
guint 
g_source_add (gint           priority,
	      gboolean       can_recurse,
	      GSourceFuncs  *funcs,
	      gpointer       source_data, 
	      gpointer       user_data,
	      GDestroyNotify notify)
{
486
  guint return_val;
487 488
  GSource *source;

489
  G_LOCK (main_loop);
490

491
  if (!source_list.is_setup)
492 493
    {
      g_hook_list_init (&source_list, sizeof (GSource));
494

495 496 497
      source_list.hook_destroy = G_HOOK_DEFERRED_DESTROY;
      source_list.hook_free = g_source_destroy_func;
    }
498

499
  source = (GSource*) g_hook_alloc (&source_list);
500 501 502 503 504 505 506 507 508 509 510 511 512
  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;

513 514
  return_val = source->hook.hook_id;

515
#ifdef G_THREADS_ENABLED
516
  /* Now wake up the main loop if it is waiting in the poll() */
517
  g_main_wakeup ();
518
#endif
519
  
520
  G_UNLOCK (main_loop);
521 522

  return return_val;
523 524
}

525
gboolean
526 527
g_source_remove (guint tag)
{
528 529
  GHook *hook;

530 531
  g_return_val_if_fail (tag > 0, FALSE);

532
  G_LOCK (main_loop);
533 534

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

538
  G_UNLOCK (main_loop);
539 540

  return hook != NULL;
541 542
}

543
gboolean
544 545
g_source_remove_by_user_data (gpointer user_data)
{
546 547
  GHook *hook;
  
548
  G_LOCK (main_loop);
549 550
  
  hook = g_hook_find_data (&source_list, TRUE, user_data);
551
  if (hook)
552
    g_hook_destroy_link (&source_list, hook);
553

554
  G_UNLOCK (main_loop);
555 556

  return hook != NULL;
557 558 559 560 561 562 563
}

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

565 566 567
  return (source->source_data == data);
}

568
gboolean
569 570
g_source_remove_by_source_data (gpointer source_data)
{
571 572
  GHook *hook;

573
  G_LOCK (main_loop);
574 575

  hook = g_hook_find (&source_list, TRUE, 
576
		      g_source_find_source_data, source_data);
577
  if (hook)
578
    g_hook_destroy_link (&source_list, hook);
579

580
  G_UNLOCK (main_loop);
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

  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;
616 617
}

618 619
void
g_get_current_time (GTimeVal *result)
620
{
621
#ifndef G_OS_WIN32
622 623
  struct timeval r;

624 625
  g_return_if_fail (result != NULL);

626 627 628 629 630
  /*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;
631
#else
632 633
  FILETIME filetime;
  gint64 t;
634

635 636
  g_return_if_fail (result != NULL);

637 638 639
  GetSystemTimeAsFileTime (&filetime);
  t = ((gint64) filetime.dwLowDateTime) +
    ((gint64) filetime.dwHighDateTime) * G_GINT64_CONSTANT (0x100000000);
640

641 642
  result->tv_sec = (t - G_GINT64_CONSTANT (0x19db1ded53e8000)) / 10000000;
  result->tv_usec = (t % 10000000) / 10;
643
#endif
644 645 646 647
}

/* Running the main loop */

648
/* HOLDS: main_loop_lock */
649
static void
650
g_main_dispatch (GTimeVal *dispatch_time)
651 652 653 654 655 656 657 658 659 660 661 662 663
{
  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))
	{
664
	  gboolean was_in_call;
665 666
	  gpointer hook_data = source->hook.data;
	  gpointer source_data = source->source_data;
667 668 669
	  gboolean (*dispatch) (gpointer,
				GTimeVal *,
				gpointer);
670

671
	  dispatch = ((GSourceFuncs *) source->hook.func)->dispatch;
672
	  
673
	  was_in_call = G_HOOK_IN_CALL (source);
674
	  source->hook.flags |= G_HOOK_FLAG_IN_CALL;
675

676
	  G_UNLOCK (main_loop);
677
	  need_destroy = ! dispatch (source_data,
678
				     dispatch_time,
679
				     hook_data);
680
	  G_LOCK (main_loop);
681

682 683
	  if (!was_in_call)
	    source->hook.flags &= ~G_HOOK_FLAG_IN_CALL;
684
	  
685
	  if (need_destroy && G_HOOK_IS_VALID (source))
686
	    g_hook_destroy_link (&source_list, (GHook *) source);
687 688
	}

689
      g_hook_unref (&source_list, (GHook*) source);
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
/* 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.
 *
722 723
 */
static gboolean
724 725
g_main_iterate (gboolean block,
		gboolean dispatch)
726 727
{
  GHook *hook;
728
  GTimeVal current_time  = { 0, 0 };
729
  gint n_ready = 0;
730 731
  gint current_priority = 0;
  gint timeout;
732
  gboolean retval = FALSE;
733 734 735 736

  g_return_val_if_fail (!block || dispatch, FALSE);

  g_get_current_time (&current_time);
737

738
  G_LOCK (main_loop);
739 740 741 742 743 744 745 746 747

#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  
748 749 750 751 752 753 754
  
  /* If recursing, finish up current dispatch, before starting over */
  if (pending_dispatches)
    {
      if (dispatch)
	g_main_dispatch (&current_time);
      
755
      G_UNLOCK (main_loop);
756

757 758 759 760 761 762 763 764 765 766
      return TRUE;
    }

  /* Prepare all sources */

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

770
      if ((n_ready > 0) && (source->priority > current_priority))
771 772 773 774
	{
	  g_hook_unref (&source_list, hook);
	  break;
	}
775
      if (G_HOOK_IN_CALL (hook) && !(hook->flags & G_SOURCE_CAN_RECURSE))
776
	{
777
	  hook = g_hook_next_valid (&source_list, hook, TRUE);
778 779 780
	  continue;
	}

781
      if (!(hook->flags & G_SOURCE_READY))
782
	{
783 784
	  gboolean (*prepare)  (gpointer  source_data, 
				GTimeVal *current_time,
785 786
				gint     *timeout,
				gpointer  user_data);
787 788 789 790 791

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

792
	  if ((*prepare) (source->source_data, &current_time, &source_timeout, source->hook.data))
793 794 795
	    hook->flags |= G_SOURCE_READY;
	  
	  G_LOCK (main_loop);
796
	  in_check_or_prepare--;
797 798 799 800
	}

      if (hook->flags & G_SOURCE_READY)
	{
801 802 803
	  if (!dispatch)
	    {
	      g_hook_unref (&source_list, hook);
804
	      G_UNLOCK (main_loop);
805

806 807 808 809
	      return TRUE;
	    }
	  else
	    {
810
	      n_ready++;
811 812 813 814 815 816 817 818 819 820 821 822 823
	      current_priority = source->priority;
	      timeout = 0;
	    }
	}
      
      if (source_timeout >= 0)
	{
	  if (timeout < 0)
	    timeout = source_timeout;
	  else
	    timeout = MIN (timeout, source_timeout);
	}

824
      hook = g_hook_next_valid (&source_list, hook, TRUE);
825 826 827 828
    }

  /* poll(), if necessary */

829
  g_main_poll (timeout, n_ready > 0, current_priority);
830

831 832 833
  if (timeout != 0)
    g_get_current_time (&current_time);
  
834 835
  /* Check to see what sources need to be dispatched */

836
  n_ready = 0;
837 838 839 840 841 842
  
  hook = g_hook_first_valid (&source_list, TRUE);
  while (hook)
    {
      GSource *source = (GSource *)hook;

843
      if ((n_ready > 0) && (source->priority > current_priority))
844 845 846 847
	{
	  g_hook_unref (&source_list, hook);
	  break;
	}
848
      if (G_HOOK_IN_CALL (hook) && !(hook->flags & G_SOURCE_CAN_RECURSE))
849
	{
850
	  hook = g_hook_next_valid (&source_list, hook, TRUE);
851 852 853
	  continue;
	}

854
      if (!(hook->flags & G_SOURCE_READY))
855
	{
856
	  gboolean (*check) (gpointer  source_data,
857 858
			     GTimeVal *current_time,
			     gpointer  user_data);
859 860 861 862 863

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

	  G_LOCK (main_loop);
868
	  in_check_or_prepare--;
869 870 871 872
	}

      if (hook->flags & G_SOURCE_READY)
	{
873 874 875 876 877 878
	  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;
879
	      n_ready++;
880 881 882 883
	    }
	  else
	    {
	      g_hook_unref (&source_list, hook);
884
	      G_UNLOCK (main_loop);
885

886 887 888 889
	      return TRUE;
	    }
	}
      
890
      hook = g_hook_next_valid (&source_list, hook, TRUE);
891
    }
892
 
893 894 895 896 897 898
  /* Now invoke the callbacks */

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

902
  G_UNLOCK (main_loop);
903 904

  return retval;
905 906 907 908 909
}

/* See if any events are pending
 */
gboolean 
910
g_main_pending (void)
911
{
912
  return in_check_or_prepare ? FALSE : g_main_iterate (FALSE, FALSE);
913 914 915 916 917 918 919 920
}

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

931 932
GMainLoop*
g_main_new (gboolean is_running)
933
{
934 935 936 937
  GMainLoop *loop;

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

939
  return loop;
940 941 942 943 944
}

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

947 948 949
  if (in_check_or_prepare)
    {
      g_warning ("g_main_run(): called recursively from within a source's check() or "
950
		 "prepare() member or from a second thread, iteration not possible");
951 952
      return;
    }
953
  
954 955
  loop->is_running = TRUE;
  while (loop->is_running)
956 957 958 959 960 961
    g_main_iterate (TRUE, TRUE);
}

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

  loop->is_running = FALSE;
965 966 967 968 969
}

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

972 973 974
  g_free (loop);
}

975 976 977 978 979 980 981 982
gboolean
g_main_is_running (GMainLoop *loop)
{
  g_return_val_if_fail (loop != NULL, FALSE);

  return loop->is_running;
}

983
/* HOLDS: main_loop_lock */
984
static void
985 986 987
g_main_poll (gint     timeout,
	     gboolean use_priority,
	     gint     priority)
988
{
989 990 991
#ifdef  G_MAIN_POLL_DEBUG
  GTimer *poll_timer;
#endif
992
  GPollFD *fd_array;
993 994 995
  GPollRec *pollrec;
  gint i;
  gint npoll;
996

997
#ifdef G_THREADS_ENABLED
998
#ifndef G_OS_WIN32
999 1000 1001 1002
  if (wake_up_pipe[0] < 0)
    {
      if (pipe (wake_up_pipe) < 0)
	g_error ("Cannot create pipe main loop wake-up: %s\n",
1003
		 g_strerror (errno));
1004 1005 1006

      wake_up_rec.fd = wake_up_pipe[0];
      wake_up_rec.events = G_IO_IN;
1007
      g_main_add_poll_unlocked (0, &wake_up_rec);
1008
    }
1009 1010 1011 1012
#else
  if (wake_up_semaphore == NULL)
    {
      if ((wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL)) == NULL)
1013
	g_error ("Cannot create wake-up semaphore: %s", g_win32_error_message (GetLastError ()));
1014 1015
      wake_up_rec.fd = (gint) wake_up_semaphore;
      wake_up_rec.events = G_IO_IN;
1016 1017 1018
#ifdef G_MAIN_POLL_DEBUG
      g_print ("wake-up semaphore: %#x\n", (guint) wake_up_semaphore);
#endif
1019 1020 1021 1022
      g_main_add_poll_unlocked (0, &wake_up_rec);
    }
#endif
#endif
1023 1024
  fd_array = g_new (GPollFD, n_poll_records);
 
1025 1026 1027 1028
  pollrec = poll_records;
  i = 0;
  while (pollrec && (!use_priority || priority >= pollrec->priority))
    {
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
      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++;
	}
      
1042 1043
      pollrec = pollrec->next;
    }
1044
#ifdef G_THREADS_ENABLED
1045
  poll_waiting = TRUE;
1046
  poll_changed = FALSE;
1047
#endif
1048
  
1049
  npoll = i;
1050 1051 1052
  if (npoll || timeout != 0)
    {
#ifdef	G_MAIN_POLL_DEBUG
1053
      g_print ("g_main_poll(%d) timeout: %d\n", npoll, timeout);
1054 1055 1056 1057
      poll_timer = g_timer_new ();
#endif
      
      G_UNLOCK (main_loop);
1058 1059 1060
      if ((*poll_func) (fd_array, npoll, timeout) < 0)
	g_warning ("poll(2) failed due to: %s.",
		   g_strerror (errno));
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
      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) */
  
1100
#ifdef G_THREADS_ENABLED
1101 1102
  if (!poll_waiting)
    {
1103
#ifndef G_OS_WIN32
1104 1105
      gchar c;
      read (wake_up_pipe[0], &c, 1);
1106
#endif
1107 1108 1109
    }
  else
    poll_waiting = FALSE;
1110 1111 1112 1113 1114 1115 1116 1117 1118

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

  pollrec = poll_records;
  i = 0;
  while (i < npoll)
    {
1125 1126 1127 1128 1129
      if (pollrec->fd->events)
	{
	  pollrec->fd->revents = fd_array[i].revents;
	  i++;
	}
1130 1131 1132 1133 1134 1135 1136
      pollrec = pollrec->next;
    }

  g_free (fd_array);
}

void 
1137 1138
g_main_add_poll (GPollFD *fd,
		 gint     priority)
1139
{
1140
  G_LOCK (main_loop);
1141
  g_main_add_poll_unlocked (priority, fd);
1142
  G_UNLOCK (main_loop);
1143 1144
}

1145
/* HOLDS: main_loop_lock */
1146
static void 
1147 1148
g_main_add_poll_unlocked (gint     priority,
			  GPollFD *fd)
1149 1150 1151 1152 1153 1154
{
  GPollRec *lastrec, *pollrec, *newrec;

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

1155 1156 1157 1158 1159 1160 1161 1162
  if (poll_free_list)
    {
      newrec = poll_free_list;
      poll_free_list = newrec->next;
    }
  else
    newrec = g_chunk_new (GPollRec, poll_chunk);

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
  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++;
1182 1183 1184 1185 1186 1187 1188

#ifdef G_THREADS_ENABLED
  poll_changed = TRUE;

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

void 
1192
g_main_remove_poll (GPollFD *fd)
1193 1194 1195
{
  GPollRec *pollrec, *lastrec;

1196
  G_LOCK (main_loop);
1197
  
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
  lastrec = NULL;
  pollrec = poll_records;

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

1210 1211 1212 1213
#ifdef ENABLE_GC_FRIENDLY
	  pollrec->fd = NULL;  
#endif /* ENABLE_GC_FRIENDLY */

1214 1215
	  pollrec->next = poll_free_list;
	  poll_free_list = pollrec;
1216 1217 1218

	  n_poll_records--;
	  break;
1219 1220 1221 1222 1223
	}
      lastrec = pollrec;
      pollrec = pollrec->next;
    }

1224 1225 1226 1227 1228 1229 1230
#ifdef G_THREADS_ENABLED
  poll_changed = TRUE;
  
  /* Now wake up the main loop if it is waiting in the poll() */
  g_main_wakeup ();
#endif

1231
  G_UNLOCK (main_loop);
1232 1233 1234 1235 1236 1237 1238 1239
}

void 
g_main_set_poll_func (GPollFunc func)
{
  if (func)
    poll_func = func;
  else
1240
#ifdef HAVE_POLL
1241
    poll_func = (GPollFunc) poll;
Manish Singh's avatar