/**
 * @brief Unlocks GDK mutex if necessary.
 *
 * @see maybe_lock_gdk
 */
static inline void
maybe_unlock_gdk(void)
{
	if (!g_main_context_is_owner(g_main_context_default()))
		gdk_threads_leave();
}
示例#2
0
guint
egg_spawn_async_with_callbacks (const gchar *working_directory, gchar **argv,
                                gchar **envp, GSpawnFlags flags, GPid *child_pid,
                                EggSpawnCallbacks *cbs, gpointer user_data,
                                GMainContext *context, GError **error)
{
	gint in_fd, out_fd, err_fd;
	CallbackSource *cb_source;
	GSource *source;
	guint tag;

	g_return_val_if_fail (argv != NULL, FALSE);
	g_return_val_if_fail ((cbs && cbs->standard_input == NULL) ||
	                      !(flags & G_SPAWN_CHILD_INHERITS_STDIN), 0);
	g_return_val_if_fail ((cbs && cbs->standard_output == NULL) ||
	                      !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), 0);
	g_return_val_if_fail ((cbs && cbs->standard_error == NULL) ||
	                      !(flags & G_SPAWN_STDERR_TO_DEV_NULL), 0);

	in_fd = out_fd = err_fd = -1;

	if (!g_spawn_async_with_pipes (working_directory, argv, envp, flags,
	                               cbs ? cbs->child_setup : NULL,
	                               user_data, child_pid,
	                               cbs && cbs->standard_input ? &in_fd : NULL,
	                               cbs && cbs->standard_output ? &out_fd : NULL,
	                               cbs && cbs->standard_error ? &err_fd : NULL,
	                               error))
		return 0;

	source = g_source_new (&cb_source_funcs, sizeof (CallbackSource));

	cb_source = (CallbackSource*)source;
	if (cbs != NULL)
		memcpy (&cb_source->callbacks, cbs, sizeof (EggSpawnCallbacks));

	cb_source->polls[0].fd = in_fd;
	if (in_fd >= 0) {
		g_assert (cb_source->callbacks.standard_input);
		cb_source->polls[0].events = G_IO_ERR | G_IO_OUT;
		g_source_add_poll (source, &cb_source->polls[0]);
	}
	cb_source->polls[1].fd = out_fd;
	if (out_fd >= 0) {
		g_assert (cb_source->callbacks.standard_output);
		cb_source->polls[1].events = G_IO_ERR | G_IO_HUP | G_IO_IN;
		g_source_add_poll (source, &cb_source->polls[1]);
	}
	cb_source->polls[2].fd = err_fd;
	if (err_fd >= 0) {
		g_assert (cb_source->callbacks.standard_error);
		cb_source->polls[2].events = G_IO_ERR | G_IO_HUP | G_IO_IN;
		g_source_add_poll (source, &cb_source->polls[2]);
	}

	if (context == NULL)
		context = g_main_context_default ();
	g_source_set_callback (source, unused_callback, user_data,
	                       cbs ? cbs->finalize_func : NULL);
	tag = g_source_attach (source, context);
	g_source_unref (source);

	return tag;
}
示例#3
0
QEventDispatcherGlibPrivate::QEventDispatcherGlibPrivate(GMainContext *context)
    : mainContext(context)
{
    if (qgetenv("QT_NO_THREADED_GLIB").isEmpty()) {
#if GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION < 32
        static int dummyValue = 0; // only used for its address
        QMutexLocker locker(QMutexPool::instance()->get(&dummyValue));
        if (!g_thread_supported())
            g_thread_init(NULL);
#else
    } else {
        qWarning("QEventDispatcherGlib: it is not possible to disable GLib threading");
#endif
    }

    if (mainContext) {
        g_main_context_ref(mainContext);
    } else {
        QCoreApplication *app = QCoreApplication::instance();
        if (app && QThread::currentThread() == app->thread()) {
            mainContext = g_main_context_default();
            g_main_context_ref(mainContext);
        } else {
            mainContext = g_main_context_new();
        }
    }

#if GLIB_CHECK_VERSION (2, 22, 0)
    g_main_context_push_thread_default (mainContext);
#endif

    // setup post event source
    postEventSource = reinterpret_cast<GPostEventSource *>(g_source_new(&postEventSourceFuncs,
                                                                        sizeof(GPostEventSource)));
    postEventSource->serialNumber = 1;
    postEventSource->d = this;
    g_source_set_can_recurse(&postEventSource->source, true);
    g_source_attach(&postEventSource->source, mainContext);

    // setup socketNotifierSource
    socketNotifierSource =
        reinterpret_cast<GSocketNotifierSource *>(g_source_new(&socketNotifierSourceFuncs,
                                                               sizeof(GSocketNotifierSource)));
    (void) new (&socketNotifierSource->pollfds) QList<GPollFDWithQSocketNotifier *>();
    g_source_set_can_recurse(&socketNotifierSource->source, true);
    g_source_attach(&socketNotifierSource->source, mainContext);

    // setup normal and idle timer sources
    timerSource = reinterpret_cast<GTimerSource *>(g_source_new(&timerSourceFuncs,
                                                                sizeof(GTimerSource)));
    (void) new (&timerSource->timerList) QTimerInfoList();
    timerSource->processEventsFlags = QEventLoop::AllEvents;
    timerSource->runWithIdlePriority = false;
    g_source_set_can_recurse(&timerSource->source, true);
    g_source_attach(&timerSource->source, mainContext);

    idleTimerSource = reinterpret_cast<GIdleTimerSource *>(g_source_new(&idleTimerSourceFuncs,
                                                                        sizeof(GIdleTimerSource)));
    idleTimerSource->timerSource = timerSource;
    g_source_set_can_recurse(&idleTimerSource->source, true);
    g_source_set_priority(&idleTimerSource->source, G_PRIORITY_DEFAULT_IDLE);
    g_source_attach(&idleTimerSource->source, mainContext);
}
示例#4
0
int
xg_select (int fds_lim, fd_set *rfds, fd_set *wfds, fd_set *efds,
	   struct timespec *timeout, sigset_t *sigmask)
{
  fd_set all_rfds, all_wfds;
  struct timespec tmo;
  struct timespec *tmop = timeout;

  GMainContext *context;
  bool have_wfds = wfds != NULL;
  GPollFD gfds_buf[128];
  GPollFD *gfds = gfds_buf;
  int gfds_size = ARRAYELTS (gfds_buf);
  int n_gfds, retval = 0, our_fds = 0, max_fds = fds_lim - 1;
  bool context_acquired = false;
  int i, nfds, tmo_in_millisec, must_free = 0;
  bool need_to_dispatch;

  context = g_main_context_default ();
  context_acquired = g_main_context_acquire (context);
  /* FIXME: If we couldn't acquire the context, we just silently proceed
     because this function handles more than just glib file descriptors.
     Note that, as implemented, this failure is completely silent: there is
     no feedback to the caller.  */

  if (rfds) all_rfds = *rfds;
  else FD_ZERO (&all_rfds);
  if (wfds) all_wfds = *wfds;
  else FD_ZERO (&all_wfds);

  n_gfds = (context_acquired
	    ? g_main_context_query (context, G_PRIORITY_LOW, &tmo_in_millisec,
				    gfds, gfds_size)
	    : -1);

  if (gfds_size < n_gfds)
    {
      /* Avoid using SAFE_NALLOCA, as that implicitly refers to the
	 current thread.  Using xnmalloc avoids thread-switching
	 problems here.  */
      gfds = xnmalloc (n_gfds, sizeof *gfds);
      must_free = 1;
      gfds_size = n_gfds;
      n_gfds = g_main_context_query (context, G_PRIORITY_LOW, &tmo_in_millisec,
				     gfds, gfds_size);
    }

  for (i = 0; i < n_gfds; ++i)
    {
      if (gfds[i].events & G_IO_IN)
        {
          FD_SET (gfds[i].fd, &all_rfds);
          if (gfds[i].fd > max_fds) max_fds = gfds[i].fd;
        }
      if (gfds[i].events & G_IO_OUT)
        {
          FD_SET (gfds[i].fd, &all_wfds);
          if (gfds[i].fd > max_fds) max_fds = gfds[i].fd;
          have_wfds = true;
        }
    }

  if (must_free)
    xfree (gfds);

  if (n_gfds >= 0 && tmo_in_millisec >= 0)
    {
      tmo = make_timespec (tmo_in_millisec / 1000,
			   1000 * 1000 * (tmo_in_millisec % 1000));
      if (!timeout || timespec_cmp (tmo, *timeout) < 0)
	tmop = &tmo;
    }

  fds_lim = max_fds + 1;
  nfds = thread_select (pselect, fds_lim,
			&all_rfds, have_wfds ? &all_wfds : NULL, efds,
			tmop, sigmask);
  if (nfds < 0)
    retval = nfds;
  else if (nfds > 0)
    {
      for (i = 0; i < fds_lim; ++i)
        {
          if (FD_ISSET (i, &all_rfds))
            {
              if (rfds && FD_ISSET (i, rfds)) ++retval;
              else ++our_fds;
            }
          else if (rfds)
            FD_CLR (i, rfds);

          if (have_wfds && FD_ISSET (i, &all_wfds))
            {
              if (wfds && FD_ISSET (i, wfds)) ++retval;
              else ++our_fds;
            }
          else if (wfds)
            FD_CLR (i, wfds);

          if (efds && FD_ISSET (i, efds))
            ++retval;
        }
    }

  /* If Gtk+ is in use eventually gtk_main_iteration will be called,
     unless retval is zero.  */
#ifdef USE_GTK
  need_to_dispatch = retval == 0;
#else
  need_to_dispatch = true;
#endif
  if (need_to_dispatch && context_acquired)
    {
      int pselect_errno = errno;
      /* Prevent g_main_dispatch recursion, that would occur without
         block_input wrapper, because event handlers call
         unblock_input.  Event loop recursion was causing Bug#15801.  */
      block_input ();
      while (g_main_context_pending (context))
        g_main_context_dispatch (context);
      unblock_input ();
      errno = pselect_errno;
    }

  if (context_acquired)
    g_main_context_release (context);

  /* To not have to recalculate timeout, return like this.  */
  if ((our_fds > 0 || (nfds == 0 && tmop == &tmo)) && (retval == 0))
    {
      retval = -1;
      errno = EINTR;
    }

  return retval;
}
示例#5
0
文件: mgobj.c 项目: LordJagged/mosh
MOSHEXPORT
void
mglib_loop_acquire(void){
    g_main_context_acquire(g_main_context_default());
}
示例#6
0
char *
battstat_hal_initialise (void (*callback) (void))
{
  DBusConnection *connection;
  LibHalContext *ctx;
  DBusError error;
  char *error_str;
  char **devices;
  int i, num;

  status_updated_callback = callback;

  if( battstat_hal_ctx != NULL )
    return g_strdup( "Already initialised!" );

  dbus_error_init( &error );

  if( (connection = dbus_bus_get( DBUS_BUS_SYSTEM, &error )) == NULL )
    goto error_out;

  dbus_connection_setup_with_g_main( connection, g_main_context_default() );

  if( (ctx = libhal_ctx_new()) == NULL )
  {
    dbus_set_error( &error, _("HAL error"), _("Could not create libhal_ctx") );
    goto error_out;
  }

  libhal_ctx_set_device_property_modified( ctx, property_callback );
  libhal_ctx_set_device_added( ctx, device_added_callback );
  libhal_ctx_set_device_removed( ctx, device_removed_callback );
  libhal_ctx_set_dbus_connection( ctx, connection );

  if( libhal_ctx_init( ctx, &error ) == 0 )
    goto error_freectx;
  
  devices = libhal_find_device_by_capability( ctx, "battery", &num, &error );

  if( devices == NULL )
    goto error_shutdownctx;

  /* FIXME: for now, if 0 battery devices are present on first scan, then fail.
   * This allows fallover to the legacy (ACPI, APM, etc) backends if the
   * installed version of HAL doesn't know about batteries.  This check should
   * be removed at some point in the future (maybe circa MATE 2.13..).
   */
  if( num == 0 )
  {
    dbus_free_string_array( devices );
    dbus_set_error( &error, _("HAL error"), _("No batteries found") );
    goto error_shutdownctx;
  }

  for( i = 0; i < num; i++ )
  {
    char *type = libhal_device_get_property_string( ctx, devices[i],
                                                    "battery.type",
                                                    &error );

    if( type )
    {
      /* We only track 'primary' batteries (ie: to avoid monitoring
       * batteries in cordless mice or UPSes etc.)
       */
      if( !strcmp( type, "primary" ) )
        add_to_list( ctx, &batteries, devices[i],
                     sizeof (struct battery_info) );

      libhal_free_string( type );
    }
  }
  dbus_free_string_array( devices );

  devices = libhal_find_device_by_capability( ctx, "ac_adapter", &num, &error );

  if( devices == NULL )
  {
    batteries = free_entire_list( batteries );
    goto error_shutdownctx;
  }

  for( i = 0; i < num; i++ )
    add_to_list( ctx, &adaptors, devices[i], sizeof (struct adaptor_info) );
  dbus_free_string_array( devices );

  dbus_error_free( &error );

  battstat_hal_ctx = ctx;

  return NULL;

error_shutdownctx:
  libhal_ctx_shutdown( ctx, NULL );

error_freectx:
  libhal_ctx_free( ctx );

error_out:
  error_str = g_strdup_printf( _("Unable to initialise HAL: %s: %s"),
                               error.name, error.message );
  dbus_error_free( &error );
  return error_str;
}
示例#7
0
int
xg_select (int fds_lim, fd_set *rfds, fd_set *wfds, fd_set *efds,
	   struct timespec const *timeout, sigset_t const *sigmask)
{
  fd_set all_rfds, all_wfds;
  struct timespec tmo;
  struct timespec const *tmop = timeout;

  GMainContext *context;
  int have_wfds = wfds != NULL;
  GPollFD gfds_buf[128];
  GPollFD *gfds = gfds_buf;
  int gfds_size = ARRAYELTS (gfds_buf);
  int n_gfds, retval = 0, our_fds = 0, max_fds = fds_lim - 1;
  int i, nfds, tmo_in_millisec;
  bool need_to_dispatch;
  USE_SAFE_ALLOCA;

  context = g_main_context_default ();

  if (rfds) all_rfds = *rfds;
  else FD_ZERO (&all_rfds);
  if (wfds) all_wfds = *wfds;
  else FD_ZERO (&all_wfds);

  n_gfds = g_main_context_query (context, G_PRIORITY_LOW, &tmo_in_millisec,
				 gfds, gfds_size);
  if (gfds_size < n_gfds)
    {
      SAFE_NALLOCA (gfds, sizeof *gfds, n_gfds);
      gfds_size = n_gfds;
      n_gfds = g_main_context_query (context, G_PRIORITY_LOW, &tmo_in_millisec,
				     gfds, gfds_size);
    }

  for (i = 0; i < n_gfds; ++i)
    {
      if (gfds[i].events & G_IO_IN)
        {
          FD_SET (gfds[i].fd, &all_rfds);
          if (gfds[i].fd > max_fds) max_fds = gfds[i].fd;
        }
      if (gfds[i].events & G_IO_OUT)
        {
          FD_SET (gfds[i].fd, &all_wfds);
          if (gfds[i].fd > max_fds) max_fds = gfds[i].fd;
          have_wfds = 1;
        }
    }

  SAFE_FREE ();

  if (tmo_in_millisec >= 0)
    {
      tmo = make_timespec (tmo_in_millisec / 1000,
			   1000 * 1000 * (tmo_in_millisec % 1000));
      if (!timeout || timespec_cmp (tmo, *timeout) < 0)
	tmop = &tmo;
    }

  fds_lim = max_fds + 1;
  nfds = pselect (fds_lim, &all_rfds, have_wfds ? &all_wfds : NULL,
		  efds, tmop, sigmask);

  if (nfds < 0)
    retval = nfds;
  else if (nfds > 0)
    {
      for (i = 0; i < fds_lim; ++i)
        {
          if (FD_ISSET (i, &all_rfds))
            {
              if (rfds && FD_ISSET (i, rfds)) ++retval;
              else ++our_fds;
            }
          else if (rfds)
            FD_CLR (i, rfds);

          if (have_wfds && FD_ISSET (i, &all_wfds))
            {
              if (wfds && FD_ISSET (i, wfds)) ++retval;
              else ++our_fds;
            }
          else if (wfds)
            FD_CLR (i, wfds);

          if (efds && FD_ISSET (i, efds))
            ++retval;
        }
    }

  /* If Gtk+ is in use eventually gtk_main_iteration will be called,
     unless retval is zero.  */
#ifdef USE_GTK
  need_to_dispatch = retval == 0;
#else
  need_to_dispatch = true;
#endif
  if (need_to_dispatch)
    {
      int pselect_errno = errno;
      /* Prevent g_main_dispatch recursion, that would occur without
         block_input wrapper, because event handlers call
         unblock_input.  Event loop recursion was causing Bug#15801.  */
      block_input ();
      while (g_main_context_pending (context))
        g_main_context_dispatch (context);
      unblock_input ();
      errno = pselect_errno;
    }

  /* To not have to recalculate timeout, return like this.  */
  if ((our_fds > 0 || (nfds == 0 && tmop == &tmo)) && (retval == 0))
    {
      retval = -1;
      errno = EINTR;
    }

  return retval;
}
/**
 * mate_bg_crossfade_start:
 * @fade: a #MateBGCrossfade
 * @window: The #GdkWindow to draw crossfade on
 *
 * This function initiates a quick crossfade between two surfaces on
 * the background of @window. Before initiating the crossfade both
 * mate_bg_crossfade_set_start_surface() and
 * mate_bg_crossfade_set_end_surface() need to be called. If animations
 * are disabled, the crossfade is skipped, and the window background is
 * set immediately to the end surface.
 **/
void
mate_bg_crossfade_start (MateBGCrossfade *fade,
                         GdkWindow       *window)
{
	GSource *source;
	GMainContext *context;

	g_return_if_fail (MATE_IS_BG_CROSSFADE (fade));
	g_return_if_fail (window != NULL);
	g_return_if_fail (fade->priv->start_surface != NULL);
	g_return_if_fail (fade->priv->end_surface != NULL);
	g_return_if_fail (!mate_bg_crossfade_is_started (fade));
	g_return_if_fail (gdk_window_get_window_type (window) != GDK_WINDOW_FOREIGN);

	/* If drawing is done on the root window,
	 * it is essential to have the root pixmap.
	 */
	if (gdk_window_get_window_type (window) == GDK_WINDOW_ROOT) {
		GdkDisplay *display = gdk_window_get_display (window);
		cairo_surface_t *surface = get_root_pixmap_id_surface (display);

		g_return_if_fail (surface != NULL);
		cairo_surface_destroy (surface);
	}

	if (fade->priv->fading_surface != NULL) {
		cairo_surface_destroy (fade->priv->fading_surface);
		fade->priv->fading_surface = NULL;
	}

	fade->priv->window = window;
	if (gdk_window_get_window_type (fade->priv->window) != GDK_WINDOW_ROOT) {
		fade->priv->fading_surface = tile_surface (fade->priv->start_surface,
		                                           fade->priv->width,
		                                           fade->priv->height);
		if (fade->priv->widget != NULL) {
			g_signal_connect (fade->priv->widget, "draw",
			                  (GCallback) on_widget_draw, fade);
		}
	} else {
		cairo_t   *cr;
		GdkDisplay *display = gdk_window_get_display (fade->priv->window);

		fade->priv->fading_surface = get_root_pixmap_id_surface (display);
		cr = cairo_create (fade->priv->fading_surface);
		cairo_set_source_surface (cr, fade->priv->start_surface, 0, 0);
		cairo_paint (cr);
		cairo_destroy (cr);
	}
	draw_background (fade);

	source = g_timeout_source_new (1000 / 60.0);
	g_source_set_callback (source,
			       (GSourceFunc) on_tick,
			       fade,
			       (GDestroyNotify) on_finished);
	context = g_main_context_default ();
	fade->priv->timeout_id = g_source_attach (source, context);
	g_source_unref (source);

	fade->priv->is_first_frame = TRUE;
	fade->priv->total_duration = .75;
	fade->priv->start_time = get_current_time ();
}
示例#9
0
static gboolean
_parse_data(TrepiaSession *session, char *buf)
{
	GHashTable *info;
	GaimAccount *account;
	TrepiaMessageType type = 0;
	TrepiaProfile *profile = NULL;
	int ret;
	char *buffer;
	GaimBuddy *b;
	int id = 0;
	const char *value;
	char *username;
	int *int_p;
	GMainContext *ctx;

	account = gaim_connection_get_account(session->gc);

	ret = __parse_message(buf, &type, &info);

	if (ret == 1)
		return TRUE;

	if (info != NULL) {
		switch (type) {
			case TREPIA_USER_LIST:
				gaim_connection_update_progress(session->gc,
						_("Retrieving buddy list"), 2, TREPIA_CONNECT_STEPS);

				gaim_connection_set_state(session->gc, GAIM_CONNECTED);
				serv_finish_login(session->gc);
				break;

			case TREPIA_MSG_INCOMING: /* Incoming Message */
				id = atoi(g_hash_table_lookup(info, "a"));

				profile = g_hash_table_lookup(session->user_profiles, &id);
				serv_got_im(session->gc,
							trepia_profile_get_login(profile),
							(char *)g_hash_table_lookup(info, "b"),
							0, time(NULL));
				break;

			case TREPIA_MEMBER_UPDATE:
				profile = trepia_profile_new();

				if ((value = g_hash_table_lookup(info, "a")) != NULL) {
					id = atoi(value);
					trepia_profile_set_id(profile, id);
				}

				if ((value = g_hash_table_lookup(info, "b")) != NULL)
					trepia_profile_set_login_time(profile, atoi(value));

				if ((value = g_hash_table_lookup(info, "c")) != NULL)
					trepia_profile_set_type(profile, atoi(value));
				else
					trepia_profile_set_type(profile, 2);

				session->pending_users = g_list_append(session->pending_users,
													   profile);


#if 0
				if (trepia_profile_get_type(profile) == 1) {
					buffer = g_strdup_printf(
						"<D>"
						"<a>%d</a>"
						"<b>1</b>"
						"</D>",
						id);
				}
				else {
#endif
					buffer = g_strdup_printf(
						"<D>"
						"<a>%d</a>"
						"<b>1</b>"
						"</D>"
						"<D>"
						"<a>%d</a>"
						"<b>2</b>"
						"</D>",
						id,
						id);
#if 0
				}
#endif

				if (trepia_write(session->fd, buffer, strlen(buffer)) < 0) {
					gaim_connection_error(session->gc, _("Write error"));
					g_free(buffer);
					return 1;
				}

				g_free(buffer);
				break;

			case TREPIA_MEMBER_PROFILE:
				if ((value = g_hash_table_lookup(info, "a")) != NULL) {
					GList *l;

					id = atoi(value);

					for (l = session->pending_users; l != NULL; l = l->next) {
						profile = l->data;

						if (trepia_profile_get_id(profile) == id)
							break;

						profile = NULL;
					}
				}
				else
					break;

				if (profile == NULL) {
					profile = g_hash_table_lookup(session->user_profiles, &id);

					if (profile == NULL)
						break;
				}

				/* Age */
				if ((value = g_hash_table_lookup(info, "m")) != NULL)
					trepia_profile_set_age(profile, atoi(value));

				/* ICQ */
				if ((value = g_hash_table_lookup(info, "i")) != NULL)
					trepia_profile_set_icq(profile, atoi(value));

				/* Sex */
				if ((value = g_hash_table_lookup(info, "n")) != NULL)
					trepia_profile_set_sex(profile, *value);

				/* Location */
				if ((value = g_hash_table_lookup(info, "p")) != NULL)
					trepia_profile_set_location(profile, value);

				/* First Name */
				if ((value = g_hash_table_lookup(info, "g")) != NULL)
					trepia_profile_set_first_name(profile, value);

				/* Last Name */
				if ((value = g_hash_table_lookup(info, "h")) != NULL)
					trepia_profile_set_last_name(profile, value);

				/* Profile */
				if ((value = g_hash_table_lookup(info, "o")) != NULL)
					trepia_profile_set_profile(profile, value);

				/* E-mail */
				if ((value = g_hash_table_lookup(info, "e")) != NULL)
					trepia_profile_set_email(profile, value);

				/* AIM */
				if ((value = g_hash_table_lookup(info, "j")) != NULL)
					trepia_profile_set_aim(profile, value);

				/* MSN */
				if ((value = g_hash_table_lookup(info, "k")) != NULL)
					trepia_profile_set_msn(profile, value);

				/* Yahoo */
				if ((value = g_hash_table_lookup(info, "l")) != NULL)
					trepia_profile_set_yahoo(profile, value);

				/* Homepage */
				if ((value = g_hash_table_lookup(info, "f")) != NULL)
					trepia_profile_set_homepage(profile, value);

				/* Country */
				if ((value = g_hash_table_lookup(info, "r")) != NULL)
					trepia_profile_set_country(profile, value);

				/* State */
				if ((value = g_hash_table_lookup(info, "s")) != NULL)
					trepia_profile_set_state(profile, value);

				/* City */
				if ((value = g_hash_table_lookup(info, "t")) != NULL)
					trepia_profile_set_city(profile, value);

				/* Languages */
				if ((value = g_hash_table_lookup(info, "u")) != NULL)
					trepia_profile_set_languages(profile, value);

				/* School */
				if ((value = g_hash_table_lookup(info, "v")) != NULL)
					trepia_profile_set_school(profile, value);

				/* Company */
				if ((value = g_hash_table_lookup(info, "w")) != NULL)
					trepia_profile_set_company(profile, value);

				/* Login Name */
				if ((value = g_hash_table_lookup(info, "d")) != NULL) {
					trepia_profile_set_login(profile, value);
					username = g_strdup(value);
				}
				else if ((value = trepia_profile_get_login(profile)) != NULL) {
					username = g_strdup(value);
				}
				else {
					username = g_strdup_printf("%d", id);
					trepia_profile_set_login(profile, username);
				}

				b = gaim_find_buddy(account, username);

				if (b == NULL) {
					GaimGroup *g;

					g = gaim_find_group(_("Local Users"));

					if (g == NULL) {
						g = gaim_group_new(_("Local Users"));
						gaim_blist_add_group(g, NULL);
					}

					b = gaim_buddy_new(account, username, NULL);

					gaim_blist_add_buddy(b, NULL, g, NULL);
				}

				profile->buddy = b;

				b->proto_data = profile;

				session->pending_users = g_list_remove(session->pending_users,
													   profile);

				int_p = g_new0(int, 1);
				*int_p = id;
				g_hash_table_insert(session->user_profiles, int_p, profile);

				serv_got_update(session->gc,
								username, TRUE, 0,
								trepia_profile_get_login_time(profile), 0, 0);

				/* Buddy Icon */
				if ((value = g_hash_table_lookup(info, "q")) != NULL) {
					char *icon;
					int icon_len;

					gaim_base64_decode(value, &icon, &icon_len);

					gaim_buddy_icons_set_for_user(session->gc->account,
							username, icon, icon_len);

					g_free(icon);

					serv_got_update(session->gc, username, TRUE, 0, 0, 0, 0);
				}

				/*
				 * XXX
				 * This does nothing when using a non-gtk event loop.
				 * What is it supposed to accomplish anyway?
				 */
				ctx = g_main_context_default();

				while (g_main_context_pending(ctx))
					g_main_context_iteration(ctx, FALSE);

				g_free(username);

				break;

			case TREPIA_MEMBER_OFFLINE:
				if ((value = g_hash_table_lookup(info, "a")) != NULL)
					id = atoi(value);
				else
					break;

				profile = g_hash_table_lookup(session->user_profiles, &id);

				if (profile == NULL)
					break;

				g_hash_table_remove(session->user_profiles, &id);

				b = profile->buddy;

				if (b != NULL)
					serv_got_update(session->gc,
									trepia_profile_get_login(profile),
									FALSE, 0, 0, 0, 0);

				gaim_blist_remove_buddy(b);

				break;

			default:
				break;
		}

		g_hash_table_destroy(info);
	}
	else {
示例#10
0
static void
do_early_abort_test (void)
{
	SoupSession *session;
	SoupMessage *msg;
	GMainContext *context;
	GMainLoop *loop;

	debug_printf (1, "\nAbort with pending connection (msg api)\n");

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	msg = soup_message_new_from_uri ("GET", base_uri);

	context = g_main_context_default ();
	loop = g_main_loop_new (context, TRUE);
	soup_session_queue_message (session, msg, ea_msg_completed_one, loop);
	g_main_context_iteration (context, FALSE);

	soup_session_abort (session);
	while (g_main_context_pending (context))
		g_main_context_iteration (context, FALSE);
	g_main_loop_unref (loop);
	soup_test_session_abort_unref (session);

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	msg = soup_message_new_from_uri ("GET", base_uri);

	g_signal_connect (session, "connection-created",
			  G_CALLBACK (ea_connection_created), NULL);
	soup_session_send_message (session, msg);
	debug_printf (2, "  Message 2 completed\n");

	if (msg->status_code != SOUP_STATUS_CANCELLED) {
		debug_printf (1, "    Unexpected response: %d %s\n",
			      msg->status_code, msg->reason_phrase);
		errors++;
	}
	g_object_unref (msg);

	while (g_main_context_pending (context))
		g_main_context_iteration (context, FALSE);

	soup_test_session_abort_unref (session);

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC, NULL);
	msg = soup_message_new_from_uri ("GET", base_uri);

	g_signal_connect (session, "request-started",
			  G_CALLBACK (ea_request_started), NULL);
	soup_session_send_message (session, msg);
	debug_printf (2, "  Message 3 completed\n");

	if (msg->status_code != SOUP_STATUS_CANCELLED) {
		debug_printf (1, "    Unexpected response: %d %s\n",
			      msg->status_code, msg->reason_phrase);
		errors++;
	}
	g_object_unref (msg);

	while (g_main_context_pending (context))
		g_main_context_iteration (context, FALSE);

	soup_test_session_abort_unref (session);
}
示例#11
0
static void
do_early_abort_req_test (void)
{
	SoupSession *session;
	SoupRequest *req;
	GMainContext *context;
	GMainLoop *loop;
	GCancellable *cancellable;

	debug_printf (1, "\nAbort with pending connection (request api)\n");

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC,
					 SOUP_SESSION_USE_THREAD_CONTEXT, TRUE,
					 NULL);
	req = soup_session_request_uri (session, base_uri, NULL);

	context = g_main_context_default ();
	loop = g_main_loop_new (context, TRUE);
	soup_request_send_async (req, NULL, ear_one_completed, NULL);
	g_object_unref (req);
	g_main_context_iteration (context, FALSE);

	soup_session_abort (session);
	while (g_main_context_pending (context))
		g_main_context_iteration (context, FALSE);
	soup_test_session_abort_unref (session);

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC,
					 SOUP_SESSION_USE_THREAD_CONTEXT, TRUE,
					 NULL);
	req = soup_session_request_uri (session, base_uri, NULL);

	g_signal_connect (session, "connection-created",
			  G_CALLBACK (ea_connection_created), NULL);
	soup_request_send_async (req, NULL, ear_two_completed, loop);
	g_main_loop_run (loop);
	g_object_unref (req);

	while (g_main_context_pending (context))
		g_main_context_iteration (context, FALSE);

	soup_test_session_abort_unref (session);

	session = soup_test_session_new (SOUP_TYPE_SESSION_ASYNC,
					 SOUP_SESSION_USE_THREAD_CONTEXT, TRUE,
					 NULL);
	req = soup_session_request_uri (session, base_uri, NULL);

	cancellable = g_cancellable_new ();
	g_signal_connect (session, "request-started",
			  G_CALLBACK (ear_request_started), cancellable);
	soup_request_send_async (req, cancellable, ear_three_completed, loop);
	g_main_loop_run (loop);
	g_object_unref (req);
	g_object_unref (cancellable);

	while (g_main_context_pending (context))
		g_main_context_iteration (context, FALSE);

	soup_test_session_abort_unref (session);
	g_main_loop_unref (loop);
}
示例#12
0
void WakeUpGuiThread()
{
	g_main_context_wakeup(g_main_context_default());
}
示例#13
0
/*
 * main
 */
int
main ( int argc,
       char *argv[] )
{
  GMainContext *context;
  gint retval;
  struct sockaddr_un server_addr;
  socklen_t server_len;
  FILE *flock = NULL;
  ajax_worker *aw1;
  ajax_worker *aw2;

  /* configure daemon */
  parse_options ( argc, argv );

  if ( access("/tmp/chainrefd.lock", F_OK ) == 0 )
    {
      fprintf ( stderr, "chainrefd seems to be running already, aborting...\n" );
      fprintf ( stderr, "remove /tmp/chainrefd.lock to override\n" );
      return 2;
    }

  flock = fopen ( "/tmp/chainrefd.lock", "w" );
  fclose ( flock );

  /* spawn log */
  if ( log_open(logname) )
    {
      unlink ( "/tmp/chainrefd.lock" );
      return 1;
    }

  /* daemonization */
  if ( daemonize )
    {
      if ( logname == NULL )
        {
          logname = g_strdup ( "chainrefd.log" );
          log_open ( logname );
        }

      retval = daemon ( 1, 1 );

      if ( retval )
        {
          log_print ( "core: unable to daemonize: %s.\n", strerror(errno) );
          unlink ( "/tmp/chainrefd.lock" );
          return 1;
        }
    }

  log_print ( "chainrefd version %s (api %s)\n", CHAINREFD_VERSION, CHAINREF_API_VERSION );

  /* spawn blockchain descriptor */
  BLOCKCHAIN = blockchain_new ( CHAIN_BITCOIN, "btc", "data" );

  if ( BLOCKCHAIN == NULL )
    {
      log_print ( "core: unable to load blockchain data.\n" );
      unlink ( "/tmp/chainrefd.lock" );
      return 1;
    }

  /* spawn main loop driver */
  context = g_main_context_default ( );
  mainloop = g_main_loop_new ( context, FALSE );
  signal ( SIGTERM, handle_shutdown );
  signal ( SIGINT, handle_shutdown );
  signal ( SIGQUIT, handle_shutdown );
  signal ( SIGPIPE, SIG_IGN );

  /* spawn network listener */
  server_socket = socket ( AF_UNIX, SOCK_STREAM, 0 );
  if ( server_socket == -1 )
    {
      log_print ( "core: unable to create socket: %s.\n", strerror(errno) );
      unlink ( "/tmp/chainrefd.lock" );
      return 1;
    }

  unlink ( "/tmp/chainrefd" );
  memset ( &server_addr, 0, sizeof(struct sockaddr_un) );
  server_addr.sun_family = AF_UNIX;
  strcpy ( server_addr.sun_path, "/tmp/chainrefd" );
  server_len = strlen(server_addr.sun_path) + sizeof(server_addr.sun_family);

  retval = bind ( server_socket, (struct sockaddr *) &server_addr, server_len );
  if ( retval != 0 )
    {
      log_print ( "core: unable to bind socket: %s.\n", strerror(errno) );
      unlink ( "/tmp/chainrefd.lock" );
      return 1;
    }

  if ( listen(server_socket, CHAINREFD_QUEUE_SIZE) != 0 )
    {
      log_print ( "core: unable to listen on socket: %s", strerror(errno) );
      unlink ( "/tmp/chainrefd.lock" );
      return 1;
    }

  server_chan = g_io_channel_unix_new ( server_socket );

  g_io_add_watch ( server_chan, G_IO_IN, (GIOFunc)handle_new_connection, NULL );

  /* run one ajax worker */
  aw1 = ajax_worker_new ( 0 );
  aw2 = ajax_worker_new ( 1 );

  /* enter main loop */
  handle_alive_timeout ( NULL ); /* print startup status */
  g_timeout_add_seconds ( 60, (GSourceFunc)handle_alive_timeout, NULL );
  g_main_loop_run ( mainloop );

  /* prepare for exit */
  log_print ( "core: shut down ordered.\n" );

  ajax_worker_shutdown ( aw1 );
  ajax_worker_free ( aw1 );
  ajax_worker_shutdown ( aw2 );
  ajax_worker_free ( aw2 );

  g_io_channel_shutdown ( server_chan, TRUE, NULL );
  g_io_channel_unref ( server_chan );
  g_main_loop_unref ( mainloop );

  /* dump, clean up and exit */
  unlink ( "/tmp/chainrefd.lock" );

  blockchain_free ( BLOCKCHAIN );

  log_close ( );
  if ( logname != NULL )
    g_free ( logname );

  return 0;
}
    void update(int milliseconds)
    {
#if LL_QTLINUX_DOESNT_HAVE_GLIB
        // pump glib generously, as Linux browser plugins are on the
        // glib main loop, even if the browser itself isn't - ugh
        // This is NOT NEEDED if Qt itself was built with glib
        // mainloop integration.
        GMainContext *mainc = g_main_context_default();
        while(g_main_context_iteration(mainc, FALSE));
#endif // LL_QTLINUX_DOESNT_HAVE_GLIB

        // pump qt
        LLQtWebKit::getInstance()->pump( milliseconds );

        mVolumeCatcher.pump();

        checkEditState();

        if(mInitState == INIT_STATE_NAVIGATE_COMPLETE)
        {
            if(!mInitialNavigateURL.empty())
            {
                // We already have the initial navigate URL -- kick off the navigate.
                LLQtWebKit::getInstance()->navigateTo( mBrowserWindowId, mInitialNavigateURL );
                mInitialNavigateURL.clear();
            }
        }

        if ( (mInitState > INIT_STATE_WAIT_REDRAW) && mNeedsUpdate )
        {
            const unsigned char* browser_pixels = LLQtWebKit::getInstance()->grabBrowserWindow( mBrowserWindowId );

            unsigned int rowspan = LLQtWebKit::getInstance()->getBrowserRowSpan( mBrowserWindowId );
            unsigned int height = LLQtWebKit::getInstance()->getBrowserHeight( mBrowserWindowId );
#if !LL_QTWEBKIT_USES_PIXMAPS
            unsigned int buffer_size = rowspan * height;
#endif // !LL_QTWEBKIT_USES_PIXMAPS

//			std::cerr << "webkit plugin: updating" << std::endl;

            // TODO: should get rid of this memcpy if possible
            if ( mPixels && browser_pixels )
            {
//				std::cerr << "    memcopy of " << buffer_size << " bytes" << std::endl;

#if LL_QTWEBKIT_USES_PIXMAPS
                // copy the pixel data upside-down because of the co-ord system
                for (int y=0; y<height; ++y)
                {
                    memcpy( &mPixels[(height-y-1)*rowspan], &browser_pixels[y*rowspan], rowspan );
                }
#else
                memcpy( mPixels, browser_pixels, buffer_size );
#endif // LL_QTWEBKIT_USES_PIXMAPS
            }

            if ( mWidth > 0 && mHeight > 0 )
            {
//				std::cerr << "Setting dirty, " << mWidth << " x " << mHeight << std::endl;
                setDirty( 0, 0, mWidth, mHeight );
            }

            mNeedsUpdate = false;
        };
    };
示例#15
0
/**
 * gst_video_convert_sample_async:
 * @sample: a #GstSample
 * @to_caps: the #GstCaps to convert to
 * @timeout: the maximum amount of time allowed for the processing.
 * @callback: %GstVideoConvertSampleCallback that will be called after conversion.
 * @user_data: extra data that will be passed to the @callback
 * @destroy_notify: %GDestroyNotify to be called after @user_data is not needed anymore
 *
 * Converts a raw video buffer into the specified output caps.
 *
 * The output caps can be any raw video formats or any image formats (jpeg, png, ...).
 *
 * The width, height and pixel-aspect-ratio can also be specified in the output caps.
 *
 * @callback will be called after conversion, when an error occured or if conversion didn't
 * finish after @timeout. @callback will always be called from the thread default
 * %GMainContext, see g_main_context_get_thread_default(). If GLib before 2.22 is used,
 * this will always be the global default main context.
 *
 * @destroy_notify will be called after the callback was called and @user_data is not needed
 * anymore.
 */
void
gst_video_convert_sample_async (GstSample * sample,
    const GstCaps * to_caps, GstClockTime timeout,
    GstVideoConvertSampleCallback callback, gpointer user_data,
    GDestroyNotify destroy_notify)
{
  GMainContext *context = NULL;
  GError *error = NULL;
  GstBus *bus;
  GstBuffer *buf;
  GstCaps *from_caps, *to_caps_copy = NULL;
  GstElement *pipeline, *src, *sink;
  guint i, n;
  GSource *source;
  GstVideoConvertSampleContext *ctx;

  g_return_if_fail (sample != NULL);
  buf = gst_sample_get_buffer (sample);
  g_return_if_fail (buf != NULL);

  g_return_if_fail (to_caps != NULL);

  from_caps = gst_sample_get_caps (sample);
  g_return_if_fail (from_caps != NULL);
  g_return_if_fail (callback != NULL);

  context = g_main_context_get_thread_default ();

  if (!context)
    context = g_main_context_default ();

  to_caps_copy = gst_caps_new_empty ();
  n = gst_caps_get_size (to_caps);
  for (i = 0; i < n; i++) {
    GstStructure *s = gst_caps_get_structure (to_caps, i);

    s = gst_structure_copy (s);
    gst_structure_remove_field (s, "framerate");
    gst_caps_append_structure (to_caps_copy, s);
  }

  pipeline =
      build_convert_frame_pipeline (&src, &sink, from_caps,
      gst_buffer_get_video_crop_meta (buf), to_caps_copy, &error);
  if (!pipeline)
    goto no_pipeline;

  bus = gst_element_get_bus (pipeline);

  ctx = g_slice_new0 (GstVideoConvertSampleContext);
  g_mutex_init (&ctx->mutex);
  //ctx->buffer = gst_buffer_ref (buf);
  ctx->sample = gst_sample_ref (sample);
  ctx->callback = callback;
  ctx->user_data = user_data;
  ctx->destroy_notify = destroy_notify;
  ctx->context = g_main_context_ref (context);
  ctx->finished = FALSE;
  ctx->pipeline = pipeline;

  if (timeout != GST_CLOCK_TIME_NONE) {
    ctx->timeout_source = g_timeout_source_new (timeout / GST_MSECOND);
    g_source_set_callback (ctx->timeout_source,
        (GSourceFunc) convert_frame_timeout_callback, ctx, NULL);
    g_source_attach (ctx->timeout_source, context);
  }

  g_signal_connect (src, "need-data",
      G_CALLBACK (convert_frame_need_data_callback), ctx);
  g_signal_connect (sink, "new-preroll",
      G_CALLBACK (convert_frame_new_preroll_callback), ctx);

  source = gst_bus_create_watch (bus);
  g_source_set_callback (source, (GSourceFunc) convert_frame_bus_callback,
      ctx, NULL);
  g_source_attach (source, context);
  g_source_unref (source);

  gst_element_set_state (pipeline, GST_STATE_PLAYING);

  gst_object_unref (bus);
  gst_caps_unref (to_caps_copy);

  return;
  /* ERRORS */
no_pipeline:
  {
    GstVideoConvertSampleCallbackContext *ctx;
    GSource *source;

    gst_caps_unref (to_caps_copy);

    ctx = g_slice_new0 (GstVideoConvertSampleCallbackContext);
    ctx->callback = callback;
    ctx->user_data = user_data;
    ctx->destroy_notify = destroy_notify;
    ctx->sample = NULL;
    ctx->error = error;

    source = g_timeout_source_new (0);
    g_source_set_callback (source,
        (GSourceFunc) convert_frame_dispatch_callback, ctx,
        (GDestroyNotify) gst_video_convert_frame_callback_context_free);
    g_source_attach (source, context);
    g_source_unref (source);
  }
}
示例#16
0
int
xg_select (int max_fds, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
	   EMACS_TIME *timeout)
{
  SELECT_TYPE all_rfds, all_wfds;
  EMACS_TIME tmo, *tmop = timeout;

  GMainContext *context = g_main_context_default ();
  int have_wfds = wfds != NULL;
  int n_gfds = 0, our_tmo = 0, retval = 0, our_fds = 0;
  int i, nfds, tmo_in_millisec;

  if (rfds) memcpy (&all_rfds, rfds, sizeof (all_rfds));
  else FD_ZERO (&all_rfds);
  if (wfds) memcpy (&all_wfds, wfds, sizeof (all_rfds));
  else FD_ZERO (&all_wfds);

  /* Update event sources in GLib. */
  g_main_context_pending (context);

  do {
    if (n_gfds > gfds_size)
      {
        xfree (gfds);
	gfds = xpalloc (0, &gfds_size, n_gfds - gfds_size, INT_MAX,
			sizeof *gfds);
      }

    n_gfds = g_main_context_query (context,
                                   G_PRIORITY_LOW,
                                   &tmo_in_millisec,
                                   gfds,
                                   gfds_size);
  } while (n_gfds > gfds_size);

  for (i = 0; i < n_gfds; ++i)
    {
      if (gfds[i].events & G_IO_IN)
        {
          FD_SET (gfds[i].fd, &all_rfds);
          if (gfds[i].fd > max_fds) max_fds = gfds[i].fd;
        }
      if (gfds[i].events & G_IO_OUT)
        {
          FD_SET (gfds[i].fd, &all_wfds);
          if (gfds[i].fd > max_fds) max_fds = gfds[i].fd;
          have_wfds = 1;
        }
    }

  if (tmo_in_millisec >= 0)
    {
      EMACS_SET_SECS_USECS (tmo, tmo_in_millisec/1000,
                            1000 * (tmo_in_millisec % 1000));
      if (!timeout) our_tmo = 1;
      else
        {
          EMACS_TIME difference;

          EMACS_SUB_TIME (difference, tmo, *timeout);
          if (EMACS_TIME_NEG_P (difference)) our_tmo = 1;
        }

      if (our_tmo) tmop = &tmo;
    }

  nfds = select (max_fds+1, &all_rfds, have_wfds ? &all_wfds : NULL,
                 efds, tmop);

  if (nfds < 0)
    retval = nfds;
  else if (nfds > 0)
    {
      for (i = 0; i < max_fds+1; ++i)
        {
          if (FD_ISSET (i, &all_rfds))
            {
              if (rfds && FD_ISSET (i, rfds)) ++retval;
              else ++our_fds;
            }
          else if (rfds)
            FD_CLR (i, rfds);

          if (have_wfds && FD_ISSET (i, &all_wfds))
            {
              if (wfds && FD_ISSET (i, wfds)) ++retval;
              else ++our_fds;
            }
          else if (wfds)
            FD_CLR (i, wfds);

          if (efds && FD_ISSET (i, efds))
            ++retval;
        }
    }

  if (our_fds > 0 || (nfds == 0 && our_tmo))
    {

      /* If Gtk+ is in use eventually gtk_main_iteration will be called,
         unless retval is zero.  */
#ifdef USE_GTK
      if (retval == 0)
#endif
        while (g_main_context_pending (context))
          g_main_context_dispatch (context);

      /* To not have to recalculate timeout, return like this.  */
      if (retval == 0)
        {
          retval = -1;
          errno = EINTR;
        }
    }

  return retval;
}
示例#17
0
文件: main-loop.c 项目: cminyard/qemu
static int os_host_main_loop_wait(int64_t timeout)
{
    GMainContext *context = g_main_context_default();
    GPollFD poll_fds[1024 * 2]; /* this is probably overkill */
    int select_ret = 0;
    int g_poll_ret, ret, i, n_poll_fds;
    PollingEntry *pe;
    WaitObjects *w = &wait_objects;
    gint poll_timeout;
    int64_t poll_timeout_ns;
    static struct timeval tv0;
    fd_set rfds, wfds, xfds;
    int nfds;

    g_main_context_acquire(context);

    /* XXX: need to suppress polling by better using win32 events */
    ret = 0;
    for (pe = first_polling_entry; pe != NULL; pe = pe->next) {
        ret |= pe->func(pe->opaque);
    }
    if (ret != 0) {
        g_main_context_release(context);
        return ret;
    }

    FD_ZERO(&rfds);
    FD_ZERO(&wfds);
    FD_ZERO(&xfds);
    nfds = pollfds_fill(gpollfds, &rfds, &wfds, &xfds);
    if (nfds >= 0) {
        select_ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv0);
        if (select_ret != 0) {
            timeout = 0;
        }
        if (select_ret > 0) {
            pollfds_poll(gpollfds, nfds, &rfds, &wfds, &xfds);
        }
    }

    g_main_context_prepare(context, &max_priority);
    n_poll_fds = g_main_context_query(context, max_priority, &poll_timeout,
                                      poll_fds, ARRAY_SIZE(poll_fds));
    g_assert(n_poll_fds <= ARRAY_SIZE(poll_fds));

    for (i = 0; i < w->num; i++) {
        poll_fds[n_poll_fds + i].fd = (DWORD_PTR)w->events[i];
        poll_fds[n_poll_fds + i].events = G_IO_IN;
    }

    if (poll_timeout < 0) {
        poll_timeout_ns = -1;
    } else {
        poll_timeout_ns = (int64_t)poll_timeout * (int64_t)SCALE_MS;
    }

    poll_timeout_ns = qemu_soonest_timeout(poll_timeout_ns, timeout);

    qemu_mutex_unlock_iothread();

    replay_mutex_unlock();

    g_poll_ret = qemu_poll_ns(poll_fds, n_poll_fds + w->num, poll_timeout_ns);

    replay_mutex_lock();

    qemu_mutex_lock_iothread();
    if (g_poll_ret > 0) {
        for (i = 0; i < w->num; i++) {
            w->revents[i] = poll_fds[n_poll_fds + i].revents;
        }
        for (i = 0; i < w->num; i++) {
            if (w->revents[i] && w->func[i]) {
                w->func[i](w->opaque[i]);
            }
        }
    }

    if (g_main_context_check(context, max_priority, poll_fds, n_poll_fds)) {
        g_main_context_dispatch(context);
    }

    g_main_context_release(context);

    return select_ret || g_poll_ret;
}
示例#18
0
NiceSocket *
nice_tcp_passive_socket_new (GMainContext *ctx, NiceAddress *addr)
{
  union {
    struct sockaddr_storage storage;
    struct sockaddr addr;
  } name;
  NiceSocket *sock;
  TcpPassivePriv *priv;
  GSocket *gsock = NULL;
  gboolean gret = FALSE;
  GSocketAddress *gaddr;

  if (addr != NULL) {
    nice_address_copy_to_sockaddr(addr, &name.addr);
  } else {
    memset (&name, 0, sizeof (name));
    name.storage.ss_family = AF_UNSPEC;
  }

  if (name.storage.ss_family == AF_UNSPEC || name.storage.ss_family == AF_INET) {
    gsock = g_socket_new (G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM,
        G_SOCKET_PROTOCOL_TCP, NULL);

    name.storage.ss_family = AF_INET;
#ifdef HAVE_SA_LEN
    name.storage.ss_len = sizeof (struct sockaddr_in);
#endif
  } else if (name.storage.ss_family == AF_INET6) {
    gsock = g_socket_new (G_SOCKET_FAMILY_IPV6, G_SOCKET_TYPE_STREAM,
        G_SOCKET_PROTOCOL_TCP, NULL);
    name.storage.ss_family = AF_INET6;
#ifdef HAVE_SA_LEN
    name.storage.ss_len = sizeof (struct sockaddr_in6);
#endif
  }

  if (gsock == NULL) {
    return NULL;
  }

  gaddr = g_socket_address_new_from_native (&name.addr, sizeof (name));

  if (gaddr == NULL) {
    g_object_unref (gsock);
    return NULL;
  }

  /* GSocket: All socket file descriptors are set to be close-on-exec. */
  g_socket_set_blocking (gsock, false);

  gret = g_socket_bind (gsock, gaddr, FALSE, NULL) &&
      g_socket_listen (gsock, NULL);
  g_object_unref (gaddr);

  if (gret == FALSE) {
    g_socket_close (gsock, NULL);
    g_object_unref (gsock);
    return NULL;
  }

  gaddr = g_socket_get_local_address (gsock, NULL);
  if (gaddr == NULL ||
      !g_socket_address_to_native (gaddr, &name.addr, sizeof (name), NULL)) {
    g_socket_close (gsock, NULL);
    g_object_unref (gsock);
    return NULL;
  }
  g_object_unref (gaddr);

  if (ctx == NULL) {
    ctx = g_main_context_default ();
  }

  sock = g_slice_new0 (NiceSocket);

  nice_address_set_from_sockaddr (&sock->addr, &name.addr);

  sock->priv = priv = g_slice_new0 (TcpPassivePriv);
  priv->context = g_main_context_ref (ctx);
  priv->connections = g_hash_table_new_full ((GHashFunc) nice_address_hash,
      (GEqualFunc) nice_address_equal, (
          GDestroyNotify) nice_address_free, NULL);
  priv->writable_cb = NULL;
  priv->writable_data = NULL;

  sock->type = NICE_SOCKET_TYPE_TCP_PASSIVE;
  sock->fileno = gsock;
  sock->send_messages = socket_send_messages;
  sock->send_messages_reliable = socket_send_messages_reliable;
  sock->recv_messages = socket_recv_messages;
  sock->is_reliable = socket_is_reliable;
  sock->can_send = socket_can_send;
  sock->set_writable_callback = socket_set_writable_callback;
  sock->close = socket_close;

  return sock;
}
void VolumeCatcherImpl::pump()
{
	gboolean may_block = FALSE;
	g_main_context_iteration(g_main_context_default(), may_block);
}
示例#20
0
int main(int  argc , char**  argv )
{
    GMainLoop * mainloop ;

    // Set the global C and C++ locale to the user-configured locale,
    // so we can use std::cout with UTF-8, via Glib::ustring, without exceptions.
    std::locale::global(std::locale(""));

    //index used for argument analysis
    int next_option;

    /* Valid letters for short options. */
    const char* const short_options = "hf:i:";
    /* Valid string for long options. */
    const struct option long_options[] = {
        { "help",     0, NULL, 'h' },
        { "file", 1, NULL, 'f' },
        { "internationalisation", 2, NULL, 'i' },
        { NULL,       0, NULL, 0   }   /* Always at the end of the table.  */
    };
    char* database_filename = NULL; //database filename
    QString language = "en"; //english by default

    program_name = argv[0];

    do {
        next_option = getopt_long (argc, argv, short_options,
                                  long_options, NULL);
        switch (next_option)
        {
        case 'h':   /* -h --help */
            print_usage (stdout, 0);
            break;
        case 'f':   /* -f --file database */
            database_filename = argv[2];
            if (!is_readable(database_filename))
                print_usage (stderr, 1);
            break;
        case 'i':   /* -i --internationalisation language */
            language = argv[4];
            break;
        case '?':   /* Invalid option. */
            print_usage (stderr, 1);
        case -1:    /* End of options.  */
            break;
        default:    /* Error  */
            print_usage (stderr, 1);
        }
    }
    while (next_option != -1);

    QApplication a(argc, argv);
    QTranslator translator;
    if (QResource::registerResource("poi-client-resource.rcc",QDir::currentPath()))
    {
        if (translator.load("poi-contentaccess-module_"+ language))
        {
            a.installTranslator(&translator);
            MainWindow mainWindow;

            // creating the dispatcher
            dispatcher = new DBus::Glib::BusDispatcher();
            DBus::default_dispatcher = dispatcher;
            dispatcher->attach(NULL);

            // create a connection on the session bus
            dbusConnection = new DBus::Connection(DBus::Connection::SessionBus());
            dbusConnection->setup(dispatcher);

            // create the server for contentAccessModule
            dbusConnection->request_name(contentAccessModule_SERVICE_NAME);
            servercontentAccessModule=new contentAccessModuleServer(*dbusConnection,database_filename);

            // connect it to the HMI panel
            mainWindow.ConnectTocontentAccessModuleServer(servercontentAccessModule);

            // connect the HMI panel to it
            servercontentAccessModule->connectToHMI(&mainWindow);

            // create a client for poiContentAccess
            clientpoiContentAccess = new poiContentAccess(*dbusConnection);

            // connect it to the HMI panel
            mainWindow.ConnectTopoiContentAccessClient(clientpoiContentAccess);

            // Create a new GMainLoop with default context and initial state of "not running "
            mainloop = g_main_loop_new (g_main_context_default() , FALSE );

           // loop listening
            mainWindow.InitUi();
            mainWindow.show();

            int ret = a.exec();

            // clean memory
            delete servercontentAccessModule;
            delete dbusConnection;
            delete dispatcher;
        }
        else
        {
            print_usage (stderr, 2);
        }
    }
    else
    {
        print_usage (stderr, 3);
    }
    return EXIT_SUCCESS;
}
示例#21
0
int main() {
    GMainContext *ctx = g_main_context_default();
    GMainLoop *loop = g_main_loop_new(ctx, FALSE);

    /* PREPARE FOR RECEIVING */

    OwrPayload *receive_payload;

    owr_init_with_main_context(ctx);

    recv_transport_agent = owr_transport_agent_new(FALSE);
    g_assert(OWR_IS_TRANSPORT_AGENT(recv_transport_agent));

    owr_transport_agent_set_local_port_range(recv_transport_agent, 5000, 5999);
    owr_transport_agent_add_local_address(recv_transport_agent, "127.0.0.1");

    // SEND
    send_transport_agent = owr_transport_agent_new(TRUE);
    g_assert(OWR_IS_TRANSPORT_AGENT(send_transport_agent));

    owr_transport_agent_set_local_port_range(send_transport_agent, 5000, 5999);
    owr_transport_agent_add_local_address(send_transport_agent, "127.0.0.1");

    recv_session_audio = owr_media_session_new(FALSE);
    recv_session_video = owr_media_session_new(FALSE);
    send_session_audio = owr_media_session_new(TRUE);
    send_session_video = owr_media_session_new(TRUE);

    g_signal_connect(recv_session_audio, "on-new-candidate", G_CALLBACK(got_candidate), send_session_audio);
    g_signal_connect(recv_session_video, "on-new-candidate", G_CALLBACK(got_candidate), send_session_video);
    g_signal_connect(send_session_audio, "on-new-candidate", G_CALLBACK(got_candidate), recv_session_audio);
    g_signal_connect(send_session_video, "on-new-candidate", G_CALLBACK(got_candidate), recv_session_video);

    // VIDEO
    g_signal_connect(recv_session_video, "on-incoming-source", G_CALLBACK(got_remote_source), NULL);

    receive_payload = owr_video_payload_new(OWR_CODEC_TYPE_VP8, 103, 90000, TRUE, FALSE);
    g_object_set(receive_payload, "rtx-payload-type", 123, NULL);

    owr_media_session_add_receive_payload(recv_session_video, receive_payload);
    g_object_unref(receive_payload);

    owr_transport_agent_add_session(recv_transport_agent, OWR_SESSION(recv_session_video));


    // AUDIO
    g_signal_connect(recv_session_audio, "on-incoming-source", G_CALLBACK(got_remote_source), NULL);

    receive_payload = owr_audio_payload_new(OWR_CODEC_TYPE_OPUS, 100, 48000, 1);
    owr_media_session_add_receive_payload(recv_session_audio, receive_payload);
    g_object_unref(receive_payload);

    owr_transport_agent_add_session(recv_transport_agent, OWR_SESSION(recv_session_audio));


    /* PREPARE FOR SENDING */

    owr_get_capture_sources(OWR_MEDIA_TYPE_AUDIO|OWR_MEDIA_TYPE_VIDEO, got_sources, NULL);

    g_timeout_add_seconds(5, (GSourceFunc)dump_cb, NULL);

    g_main_loop_run(loop);

    return 0;
}
示例#22
0
GlibEvents::~GlibEvents()
    {
    g_main_context_unref( g_main_context_default());
    }
示例#23
0
/**
 * _gcr_gnupg_process_run_async:
 * @self: The process
 * @argv: (array zero-terminated=1): The arguments for the process, not including executable, terminated with %NULL.
 * @envp: (allow-none) (array zero-terminated=1): The environment for new process, terminated with %NULL.
 * @flags: Flags for starting the process.
 * @cancellable: (allow-none): Cancellation object
 * @callback: Will be called when operation completes.
 * @user_data: (closure): Data passed to callback.
 *
 * Run the gpg process. Only one 'run' operation can run per GcrGnupgProcess
 * object. The GcrGnupgProcess:output_data and GcrGnupgProcess:error_line
 * signals will be emitted when data is received from the gpg process.
 *
 * Unless the %GCR_GNUPG_PROCESS_RESPECT_LOCALE flag is specified, the process
 * will be run in the 'C' locale. If the %GCR_GNUPG_PROCESS_WITH_STATUS or
 * %GCR_GNUPG_PROCESS_WITH_ATTRIBUTES flags are set, then the gpg process
 * will be status and attribute output respectively. The
 * GcrGnupgProcess:status_record and GcrGnupgProcess:attribute_data signals
 * will provide this data.
 */
void
_gcr_gnupg_process_run_async (GcrGnupgProcess *self, const gchar **argv, const gchar **envp,
                              GcrGnupgProcessFlags flags, GCancellable *cancellable,
                              GAsyncReadyCallback callback, gpointer user_data)
{
	GError *error = NULL;
	GPtrArray *args;
	GPtrArray *envs;
	int child_fds[NUM_FDS];
	int status_fds[2] = { -1, -1 };
	int attribute_fds[2] = { -1, -1 };
	int output_fd = -1;
	int error_fd = -1;
	int input_fd = -1;
	GnupgSource *gnupg_source;
	GSource *source;
	GPid pid;
	guint i;

	g_return_if_fail (GCR_IS_GNUPG_PROCESS (self));
	g_return_if_fail (argv);
	g_return_if_fail (callback);
	g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));

	g_return_if_fail (self->pv->running == FALSE);
	g_return_if_fail (self->pv->complete == FALSE);
	g_return_if_fail (self->pv->executable);

	self->pv->async_callback = callback;
	self->pv->user_data = user_data;

	for (i = 0; i < NUM_FDS; i++)
		child_fds[i] = -1;

	/* The command needs to be updated with these status and attribute fds */
	args = g_ptr_array_new_with_free_func (g_free);
	g_ptr_array_add (args, g_strdup (self->pv->executable));

	/* Spawn/child will close all other attributes, besides thesthose in child_fds */
	child_fds[FD_INPUT] = 0;
	child_fds[FD_OUTPUT] = 1;
	child_fds[FD_ERROR] = 2;

	if (flags & GCR_GNUPG_PROCESS_WITH_STATUS) {
		if (pipe (status_fds) < 0)
			g_return_if_reached ();
		child_fds[FD_STATUS] = status_fds[1];
		g_ptr_array_add (args, g_strdup ("--status-fd"));
		g_ptr_array_add (args, g_strdup_printf ("%d", child_fds[FD_STATUS]));
	}
	if (flags & GCR_GNUPG_PROCESS_WITH_ATTRIBUTES) {
		if (pipe (attribute_fds) < 0)
			g_return_if_reached ();
		child_fds[FD_ATTRIBUTE] = attribute_fds[1];
		g_ptr_array_add (args, g_strdup ("--attribute-fd"));
		g_ptr_array_add (args, g_strdup_printf ("%d", child_fds[FD_ATTRIBUTE]));
	}

	if (self->pv->directory) {
		g_ptr_array_add (args, g_strdup ("--homedir"));
		g_ptr_array_add (args, g_strdup (self->pv->directory));
	}

	/* All the remaining arguments */
	for (i = 0; argv[i] != NULL; i++)
		g_ptr_array_add (args, g_strdup (argv[i]));
	g_ptr_array_add (args, NULL);

	envs = g_ptr_array_new ();
	for (i = 0; envp && envp[i] != NULL; i++) {
		if (flags & GCR_GNUPG_PROCESS_RESPECT_LOCALE ||
		    !g_str_has_prefix (envp[i], "LOCALE="))
			g_ptr_array_add (envs, (gpointer)envp[i]);
	}
	if (!(flags & GCR_GNUPG_PROCESS_RESPECT_LOCALE))
		g_ptr_array_add (envs, (gpointer)"LOCALE=C");
	g_ptr_array_add (envs, NULL);

	gchar *command = g_strjoinv (" ", (gchar**)args->pdata);
	gchar *environ = g_strjoinv (", ", (gchar**)envs->pdata);
	g_debug ("running command: %s", command);
	g_debug ("process environment: %s", environ);
	g_free (command);
	g_free (environ);

	g_spawn_async_with_pipes (self->pv->directory, (gchar**)args->pdata,
	                          (gchar**)envs->pdata, G_SPAWN_DO_NOT_REAP_CHILD,
	                          on_gnupg_process_child_setup, child_fds,
	                          &pid, &input_fd, &output_fd, &error_fd, &error);

	g_ptr_array_free (args, TRUE);
	g_ptr_array_free (envs, TRUE);

	/* Close 'wrong' ends of extra file descriptors */
	close_fd (&(status_fds[1]));
	close_fd (&(attribute_fds[1]));

	self->pv->complete = FALSE;
	self->pv->running = TRUE;

	if (error) {
		close_fd (&(status_fds[0]));
		close_fd (&(attribute_fds[0]));
		g_assert (!self->pv->error);
		self->pv->error = error;
		complete_run_process (self);
		run_async_ready_callback_later (self);
		return;
	}

	g_debug ("process started: %d", (int)pid);

	source = g_source_new (&gnupg_source_funcs, sizeof (GnupgSource));

	/* Initialize the source */
	gnupg_source = (GnupgSource*)source;
	for (i = 0; i < NUM_FDS; i++)
		gnupg_source->polls[i].fd = -1;
	gnupg_source->error_buf = g_string_sized_new (128);
	gnupg_source->status_buf = g_string_sized_new (128);
	gnupg_source->process = g_object_ref (self);
	gnupg_source->child_pid = pid;

	gnupg_source->polls[FD_INPUT].fd = input_fd;
	if (input_fd >= 0) {
		gnupg_source->polls[FD_INPUT].events = G_IO_HUP | G_IO_OUT;
		g_source_add_poll (source, &gnupg_source->polls[FD_INPUT]);
	}
	gnupg_source->polls[FD_OUTPUT].fd = output_fd;
	if (output_fd >= 0) {
		gnupg_source->polls[FD_OUTPUT].events = G_IO_HUP | G_IO_IN;
		g_source_add_poll (source, &gnupg_source->polls[FD_OUTPUT]);
	}
	gnupg_source->polls[FD_ERROR].fd = error_fd;
	if (error_fd >= 0) {
		gnupg_source->polls[FD_ERROR].events = G_IO_HUP | G_IO_IN;
		g_source_add_poll (source, &gnupg_source->polls[FD_ERROR]);
	}
	gnupg_source->polls[FD_STATUS].fd = status_fds[0];
	if (status_fds[0] >= 0) {
		gnupg_source->polls[FD_STATUS].events = G_IO_HUP | G_IO_IN;
		g_source_add_poll (source, &gnupg_source->polls[FD_STATUS]);
	}
	gnupg_source->polls[FD_ATTRIBUTE].fd = attribute_fds[0];
	if (attribute_fds[0] >= 0) {
		gnupg_source->polls[FD_ATTRIBUTE].events = G_IO_HUP | G_IO_IN;
		g_source_add_poll (source, &gnupg_source->polls[FD_ATTRIBUTE]);
	}

	if (cancellable) {
		gnupg_source->cancellable = g_object_ref (cancellable);
		gnupg_source->cancel_sig = g_cancellable_connect (cancellable,
		                                                  G_CALLBACK (on_cancellable_cancelled),
		                                                  g_source_ref (source),
		                                                  (GDestroyNotify)g_source_unref);
	}

	g_assert (self->pv->source_sig == 0);
	g_source_set_callback (source, unused_callback, NULL, NULL);
	self->pv->source_sig = g_source_attach (source, g_main_context_default ());

	/* This assumes the outstanding reference to source */
	g_assert (gnupg_source->child_sig == 0);
	gnupg_source->child_sig = g_child_watch_add_full (G_PRIORITY_DEFAULT, pid,
	                                                  on_gnupg_process_child_exited,
	                                                  g_source_ref (source),
	                                                  (GDestroyNotify)g_source_unref);

	/* source is unreffed in complete_if_source_is_done() */
}
示例#24
0
void owl_select_run_loop(void)
{
  main_context = g_main_context_default();
  loop = g_main_loop_new(main_context, FALSE);
  g_main_loop_run(loop);
}
示例#25
0
文件: xmpp.c 项目: phyw/Sigfaultbot
gboolean jid_reg(struct _jid *jid, GMainContext *context) {
  LmConnection  *reg_connect;
  LmMessage     *m, *reply;
  LmMessageNode *query, *node;
  GError        *error = NULL;
  
  // Проверяем context
  if(!context)
    context = g_main_context_default();
  
  // Подключаемся
  reg_connect = lm_connection_new_with_context(jid->server, context);
  // Настраиваем ssl
/*  if(jid->use_ssl) {
    LmSSL *ssl;

    // Проверяем поддержку ssl
    if(!lm_ssl_is_supported()) {
      g_print("Your Loudmouth doesn't support SSL. Reinstall loudmouth.\n");
      jid->use_ssl = FALSE;
    }

    g_print("Configure ssl\n");
    ssl = lm_ssl_new(NULL, LM_SSL_RESPONSE_CONTINUE, NULL, NULL);
    lm_connection_set_ssl(reg_connect, ssl);
    lm_ssl_unref(ssl);

    lm_connection_set_port(reg_connect, LM_CONNECTION_DEFAULT_PORT_SSL);

  }
*/
  // Проверяем коннект
  if(!lm_connection_open_and_block(reg_connect, &error)) {
    fprintf(stderr, "Failed to open connection: %s\n", error->message);
    return FALSE;
  }

  // Определяем сообщение
  m = lm_message_new_with_sub_type(NULL, LM_MESSAGE_TYPE_IQ,
                                    LM_MESSAGE_SUB_TYPE_SET);

  // Составляем запрос
  query = lm_message_node_add_child(m->node, "query", NULL);
  lm_message_node_set_attributes(query, "xmlns", "jabber:iq:register", NULL);
  lm_message_node_add_child(query, "username", jid->username);
  lm_message_node_add_child(query, "password", jid->password);

  // Отпревляем сообщение и ждём ответ
  reply = lm_connection_send_with_reply_and_block(reg_connect, m, &error);

  if(!reply) {
    fprintf(stderr, "Failed to send registration request on server \"%s\":\n %s\n",
             jid->server, error->message);
    return FALSE;
  } 
  
  //Закрываем соединение
  lm_connection_close(reg_connect, NULL);
  lm_connection_unref(reg_connect);    
  
  // Проверяем ответ
  switch(lm_message_get_sub_type(reply)) {
    case LM_MESSAGE_SUB_TYPE_RESULT:
      g_print("Succeeded in register account '%s@%s'\n",
                                   jid->username, jid->server);
      break;

    case LM_MESSAGE_SUB_TYPE_ERROR:
    default:
      g_print("Failed to register account '%s@%s' due to: ",
                        jid->username, jid->server);

      node = lm_message_node_find_child(reply->node, "error");
      if(node)
        g_print("%s\n", lm_message_node_get_value (node));
      else
        g_print("Unknown error\n");

      return FALSE;
      break;
  } 
  
  return TRUE;
}
示例#26
0
verto_ctx *
verto_default_glib(void) {
    return verto_convert_glib(g_main_context_default(), NULL);
}
示例#27
0
CAMLprim value lwt_glib_init()
{
  gc = g_main_context_default();
  g_main_context_ref(gc);
  return Val_unit;
}
示例#28
0
struct audio_service* audio_service_create()
{
	struct audio_service *service;
	LSError error;
	pa_mainloop_api *mainloop_api;
	char name[100];

	service = g_try_new0(struct audio_service, 1);
	if (!service)
		return NULL;

	LSErrorInit(&error);

	if (!LSRegisterPubPriv("org.webosports.audio", &service->handle, false, &error)) {
		g_warning("Failed to register the luna service: %s", error.message);
		LSErrorFree(&error);
		goto error;
	}

	if (!LSRegisterCategory(service->handle, "/", audio_service_methods,
			NULL, NULL, &error)) {
		g_warning("Could not register service category: %s", error.message);
		LSErrorFree(&error);
		goto error;
	}

	if (!LSCategorySetData(service->handle, "/", service, &error)) {
		g_warning("Could not set daa for service category: %s", error.message);
		LSErrorFree(&error);
		goto error;
	}

	if (!LSGmainAttach(service->handle, event_loop, &error)) {
		g_warning("Could not attach service handle to mainloop: %s", error.message);
		LSErrorFree(&error);
		goto error;
	}

	service->pa_mainloop = pa_glib_mainloop_new(g_main_context_default());
	mainloop_api = pa_glib_mainloop_get_api(service->pa_mainloop);

	snprintf(name, 100, "AudioServiceContext:%i", getpid());
	service->context = pa_context_new(mainloop_api, name);
	service->context_initialized = false;
	pa_context_set_state_callback(service->context, context_state_cb, service);

	if (pa_context_connect(service->context, NULL, 0, NULL) < 0) {
		g_warning("Failed to connect to PulseAudio");
		pa_context_unref(service->context);
		pa_glib_mainloop_free(service->pa_mainloop);
		goto error;
	}

	sample_list = g_slist_alloc();

	return service;

error:
	if (service->handle != NULL) {
		LSUnregister(service->handle, &error);
		LSErrorFree(&error);
	}

	g_free(service);

	return NULL;
}