Esempio n. 1
0
static void
sleep_in_main_loop (double fraction)
{
  /* process all pending idles and events */
  while (g_main_context_pending (NULL))
    g_main_context_iteration (NULL, FALSE);
  /* sleeping probably isn't strictly necessary here */
  gdk_threads_add_timeout_full (G_MAXINT, fraction * SLEEP_DURATION, sleep_timeout_cb, NULL, NULL);
  gtk_main ();
  /* process any pending idles or events that arrived during sleep */
  while (g_main_context_pending (NULL))
    g_main_context_iteration (NULL, FALSE);
}
Esempio n. 2
0
static void ncl_prv_parse_script_file(char *filename)
{
	char *line = NULL;
	size_t len = 0;
	FILE *file = fopen(filename, "r");

	if (file == NULL) {
		gNclCtx.errOnExit = NCLERR_GLOBAL_ERROR;
		return;
	}

	while (getline(&line, &len, file) != -1) {

		NCL_CMD_PRINT("$$$$$$$$$$$$$$$$$$$$$$$$$'\n");
		NCL_CMD_PRINT("Executing '%s'", line);
		NCL_CMD_PRINT("$$$$$$$$$$$$$$$$$$$$$$$$$'\n");

		if ((gNclCtx.errOnExit = ncl_exec(line)) != NCLERR_NOERROR)
			break;

		while (g_main_context_pending(NULL))
			g_main_context_iteration(NULL, FALSE);
	}
	g_free(line);
	fclose(file);
}
extern void ProcessEvents(void)
{
  {
    while (g_main_context_pending(NULL))
      g_main_context_iteration(NULL, TRUE);
  }
}
Esempio n. 4
0
  void Process(bool blocking)
  {
    if (maincontext == NULL)
      return;

    while(g_main_context_pending(maincontext)) {
      g_main_context_iteration(maincontext, blocking);
    }
  }
Esempio n. 5
0
static void
do_early_abort_test (void)
{
	SoupSession *session;
	SoupMessage *msg;
	GMainContext *context;
	GMainLoop *loop;

	debug_printf (1, "\nAbort with pending connection\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);
}
Esempio n. 6
0
static void
glide_window_export_pdf_real (GlideWindow *w,
			      const gchar *filename)
{
  cairo_surface_t *pdf_surface;
  cairo_t *cr;
  gint width, height;
  gint o_slide;
  int i = 0;
  
  glide_window_fullscreen_stage (w);  
  while (g_main_context_pending (NULL))
    g_main_context_iteration (NULL, TRUE);
  
  width = clutter_actor_get_width (w->priv->stage);
  height = clutter_actor_get_height (w->priv->stage);

  pdf_surface = cairo_pdf_surface_create (filename, width, height);
  cr = cairo_create (pdf_surface);
  
  o_slide = glide_stage_manager_get_current_slide (w->priv->manager);
  
  for (i = 0; i < glide_document_get_n_slides (w->priv->document); i++)
    {
      guchar *pixels;
      guchar *p;
      GdkPixbuf *pb;

      glide_stage_manager_set_current_slide (w->priv->manager, i);

      pixels = clutter_stage_read_pixels (CLUTTER_STAGE (w->priv->stage), 0, 0, width, height);
      for (p = pixels + width * height * 4; p > pixels; p -= 3)
	*(--p) = 255; 


      pb = gdk_pixbuf_new_from_data (pixels, GDK_COLORSPACE_RGB, TRUE,
				     8, width, height, width * 4,
				     (GdkPixbufDestroyNotify) g_free,
				     NULL); 
      
      gdk_cairo_set_source_pixbuf (cr, pb, 0, 0);
      cairo_rectangle (cr, 0, 0, width, height);
      cairo_fill (cr);

      cairo_surface_show_page (pdf_surface);      
      
      g_object_unref (G_OBJECT (pb));
    }
  cairo_surface_flush (pdf_surface);

  cairo_destroy (cr);
  cairo_surface_destroy (pdf_surface);
  
  glide_window_unfullscreen_stage (w);
  glide_stage_manager_set_current_slide (w->priv->manager, o_slide);
}
Esempio n. 7
0
static GstElement *
make_pipeline (TumblerFileInfo *info, GCancellable *cancellable)
{
  GstElement *playbin, *audio_sink, *video_sink;
  int count = 0, n_video = 0;
  GstStateChangeReturn state;

  g_assert (info);

  playbin = gst_element_factory_make ("playbin2", "playbin");
  g_assert (playbin);
  audio_sink = gst_element_factory_make ("fakesink", "audiosink");
  g_assert (audio_sink);
  video_sink = gst_element_factory_make ("fakesink", "videosink");
  g_assert (video_sink);

  g_object_set (playbin,
                "uri", tumbler_file_info_get_uri (info),
                "audio-sink", audio_sink,
                "video-sink", video_sink,
                NULL);

  g_object_set (video_sink,
                "sync", TRUE,
                NULL);

  /* Change to paused state so we're ready to seek */
  state = gst_element_set_state (playbin, GST_STATE_PAUSED);
  while (state == GST_STATE_CHANGE_ASYNC
         && count < 5
         && !g_cancellable_is_cancelled (cancellable)) {
    state = gst_element_get_state (playbin, NULL, 0, 1 * GST_SECOND);
    count++;

    /* Spin mainloop so we can pick up the cancels */
    while (g_main_context_pending (NULL)) {
      g_main_context_iteration (NULL, FALSE);
    }
  }

  if (state == GST_STATE_CHANGE_FAILURE || state == GST_STATE_CHANGE_ASYNC) {
    LOG ("failed to or still changing state, aborting (state change %d)", state);
    g_object_unref (playbin);
    return NULL;
  }

  g_object_get (playbin, "n-video", &n_video, NULL);
  if (n_video == 0) {
    LOG ("no video stream, aborting");
    g_object_unref (playbin);
    return NULL;
  }

  return playbin;
}
Esempio n. 8
0
int GTK2_Gui_Dialog_Run(GWEN_DIALOG *dlg, int untilEnd) {
  GTK2_GUI_DIALOG *xdlg;
  GtkWidget *g;

  assert(dlg);
  xdlg=GWEN_INHERIT_GETDATA(GWEN_DIALOG, GTK2_GUI_DIALOG, dlg);
  assert(xdlg);

  g=Gtk2Gui_Dialog_GetMainWidget(dlg);
  if (g==NULL) {
    DBG_ERROR(GWEN_LOGDOMAIN, "No main widget");
    Gtk2Gui_Dialog_Unextend(dlg);
    return GWEN_ERROR_INVALID;
  }

  xdlg->unmap_handler =
    g_signal_connect(g,
                     "unmap",
                     G_CALLBACK (run_unmap_handler),
                     dlg);

  xdlg->delete_handler =
    g_signal_connect(g,
                     "delete-event",
                     G_CALLBACK (run_delete_handler),
                     dlg);

  xdlg->destroy_handler =
    g_signal_connect(g,
                     "destroy",
                     G_CALLBACK (run_destroy_handler),
                     dlg);

  xdlg->loop=g_main_loop_new(NULL, FALSE);
  if (untilEnd)
    g_main_loop_run(xdlg->loop);
  else {
    GMainContext *ctx;

    ctx=g_main_loop_get_context(xdlg->loop);
    while(g_main_context_pending(ctx))
      g_main_context_iteration(ctx, FALSE);
  }
  g_main_loop_unref(xdlg->loop);

  if (!xdlg->destroyed) {
    g_signal_handler_disconnect(g, xdlg->unmap_handler);
    g_signal_handler_disconnect(g, xdlg->delete_handler);
    g_signal_handler_disconnect(g, xdlg->destroy_handler);
  }

  return xdlg->response;
}
Esempio n. 9
0
void
pragha_process_gtk_events ()
{
#ifdef DEBUG
	extern GThread *pragha_main_thread;
	if (g_thread_self () != pragha_main_thread)
		g_warning ("THREAD SAFETY ERROR!");
#endif
	while (g_main_context_pending (NULL)) {
		g_main_context_iteration (NULL, FALSE);
	}
}
Esempio n. 10
0
void
gimp_progress_update_and_flush (gint     min,
                                gint     max,
                                gint     current,
                                gpointer data)
{
  gimp_progress_set_value (GIMP_PROGRESS (data),
                           (gdouble) (current - min) / (gdouble) (max - min));

  while (g_main_context_pending (NULL))
    g_main_context_iteration (NULL, TRUE);
}
Esempio n. 11
0
MessageQueueWaitResult WorkerRunLoop::runInMode(WorkerGlobalScope* context, const ModePredicate& predicate, WaitMode waitMode)
{
    ASSERT(context);
    ASSERT(context->thread().threadID() == currentThread());

#if PLATFORM(GTK) || PLATFORM(WPE)
    GMainContext* mainContext = g_main_context_get_thread_default();
    if (g_main_context_pending(mainContext))
        g_main_context_iteration(mainContext, FALSE);
#endif

    double deadline = MessageQueue<Task>::infiniteTime();

#if USE(CF)
    CFAbsoluteTime nextCFRunLoopTimerFireDate = CFRunLoopGetNextTimerFireDate(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
    double timeUntilNextCFRunLoopTimerInSeconds = nextCFRunLoopTimerFireDate - CFAbsoluteTimeGetCurrent();
    deadline = currentTime() + std::max(0.0, timeUntilNextCFRunLoopTimerInSeconds);
#endif

    double absoluteTime = 0.0;
    if (waitMode == WaitForMessage) {
        if (predicate.isDefaultMode() && m_sharedTimer->isActive())
            absoluteTime = std::min(deadline, m_sharedTimer->fireTime());
        else
            absoluteTime = deadline;
    }
    MessageQueueWaitResult result;
    auto task = m_messageQueue.waitForMessageFilteredWithTimeout(result, predicate, absoluteTime);

    // If the context is closing, don't execute any further JavaScript tasks (per section 4.1.1 of the Web Workers spec).  However, there may be implementation cleanup tasks in the queue, so keep running through it.

    switch (result) {
    case MessageQueueTerminated:
        break;

    case MessageQueueMessageReceived:
        task->performTask(*this, context);
        break;

    case MessageQueueTimeout:
        if (!context->isClosing())
            m_sharedTimer->fire();
#if USE(CF)
        if (nextCFRunLoopTimerFireDate <= CFAbsoluteTimeGetCurrent())
            CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, /*returnAfterSourceHandled*/ false);
#endif
        break;
    }

    return result;
}
Esempio n. 12
0
static void
tab_scroll_right_down_clicked (GtkWidget *widget, chanview *cv)
{
    GtkAdjustment *adj;
    gint viewport_size;
    gfloat new_value;
    GtkWidget *inner;
    GdkWindow *parent_win;
    gdouble i;

    inner = ((tabview *)cv)->inner;
    parent_win = gtk_widget_get_window (gtk_widget_get_parent (inner));

    if (cv->vertical)
    {
        adj = gtk_viewport_get_vadjustment (GTK_VIEWPORT (gtk_widget_get_parent(inner)));
        gdk_window_get_geometry (parent_win, 0, 0, 0, &viewport_size, 0);
    } else
    {
        adj = gtk_viewport_get_hadjustment (GTK_VIEWPORT (gtk_widget_get_parent(inner)));
        gdk_window_get_geometry (parent_win, 0, 0, &viewport_size, 0, 0);
    }

    new_value = tab_search_offset (inner, gtk_adjustment_get_value (adj), 1, cv->vertical);

    if (new_value == 0 || new_value + viewport_size > gtk_adjustment_get_upper (adj))
        new_value = gtk_adjustment_get_upper (adj) - viewport_size;

    if (!tab_right_is_moving)
    {
        tab_right_is_moving = 1;

        for (i = gtk_adjustment_get_value (adj); ((i < new_value) && (tab_right_is_moving)); i += 0.1)
        {
            gtk_adjustment_set_value (adj, i);
            while (g_main_context_pending (NULL))
                g_main_context_iteration (NULL, TRUE);
        }

        gtk_adjustment_set_value (adj, new_value);

        tab_right_is_moving = 0;                /* hSP: set to false in case we didnt get stopped (the normal case) */
    }
    else
    {
        tab_right_is_moving = 0;                /* hSP: jump directly to next element if user is clicking faster than we can scroll.. */
    }
}
static void
mainloop_for (gulong interval)
{
    gboolean mainloop_done = FALSE;

    if (!interval) /* Wait for another process */
        interval = 50;

    g_timeout_add (interval, timeout_cb, &mainloop_done);

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

    while (g_main_context_iteration (NULL, TRUE) && !mainloop_done)
        ;
}
int
main (int argc,
      char * argv[])
{
  GumScriptBackend * backend;
  GCancellable * cancellable = NULL;
  GError * error = NULL;
  GumScript * script;
  GMainContext * context;

  gum_init_embedded ();

  backend = gum_script_backend_obtain_duk ();

  script = gum_script_backend_create_sync (backend, "example",
      "Interceptor.attach(Module.findExportByName(null, 'open'), {\n"
      "  onEnter: function (args) {\n"
      "    console.log('[*] open(\"' + Memory.readUtf8String(args[0]) + '\")');\n"
      "  }\n"
      "});\n"
      "Interceptor.attach(Module.findExportByName(null, \"close\"), {\n"
      "  onEnter: function (args) {\n"
      "    console.log('[*] close(' + args[0].toInt32() + ')');\n"
      "  }\n"
      "});",
      cancellable, &error);
  g_assert (error == NULL);

  gum_script_set_message_handler (script, on_message, NULL, NULL);

  gum_script_load_sync (script, cancellable);

  close (open ("/etc/hosts", O_RDONLY));
  close (open ("/etc/fstab", O_RDONLY));

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

  gum_script_unload_sync (script, cancellable);

  g_object_unref (script);

  gum_deinit_embedded ();

  return 0;
}
Esempio n. 15
0
void GlibEvents::process()
    {
    if( !checkedEventLoop )
        {
        // If Qt is already running a Glib event loop, disable our own's timer
        if (QLatin1String(QAbstractEventDispatcher::instance()->metaObject()->className())
            == "QGuiEventDispatcherGlib")
               {
               kDebug(1430) << "Qt already providing Glib integration, dropping ours";
               timer.stop();
               }
            else
               kDebug(1430) << "Qt using pure Xlib event loop; keeping Glib integration active";

            checkedEventLoop = true;
        }
    if( g_main_depth() > 0 )
        return; // avoid reentrancy when Qt's Glib integration is used
    while( g_main_context_pending( g_main_context_default()))
        g_main_context_iteration( g_main_context_default(), false );
    }
Esempio n. 16
0
static void run_test (gconstpointer data)
{
    GFileInputStream *stream;
    gchar contents[1024];
    gsize bytes;
    gchar *curi, *newline;
    gchar **uriv;
    GFile *file = G_FILE (data);
    YelpUri *uri;
    GOutputStream *outstream;
    gchar *out;

    stream = g_file_read (file, NULL, NULL);
    g_assert (g_input_stream_read_all (G_INPUT_STREAM (stream),
                                       contents, 1024, &bytes,
                                       NULL, NULL));
    newline = strchr (contents, '\n');
    curi = g_strndup (contents, newline - contents);
    uriv = g_strsplit (curi, " ", 2);
    uri = yelp_uri_new (uriv[0]);
    if (uriv[1] != NULL)
        uri = yelp_uri_new_relative (uri, uriv[1]);
    g_strfreev (uriv);

    yelp_uri_resolve (uri);

    while (!yelp_uri_is_resolved (uri))
        while (g_main_context_pending (NULL))
            g_main_context_iteration (NULL, FALSE);

    outstream = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
    print_uri (curi, uri, outstream);
    out = (gchar *) g_memory_output_stream_get_data (G_MEMORY_OUTPUT_STREAM (outstream));
    g_free (curi);
    g_assert (!strncmp (out, contents, bytes));
}
bool
MediaPluginGStreamer010::update(int milliseconds)
{
	if (!mDoneInit)
		return false; // error

	DEBUGMSG("updating media...");
	
	// sanity check
	if (NULL == mPump ||
	    NULL == mPlaybin)
	{
		DEBUGMSG("dead media...");
		return false;
	}

	// see if there's an outstanding seek wanted
	if (mSeekWanted &&
	    // bleh, GST has to be happy that the movie is really truly playing
	    // or it may quietly ignore the seek (with rtsp:// at least).
	    (GST_STATE(mPlaybin) == GST_STATE_PLAYING))
	{
		seek(mSeekDestination);
		mSeekWanted = false;
	}

	// *TODO: time-limit - but there isn't a lot we can do here, most
	// time is spent in gstreamer's own opaque worker-threads.  maybe
	// we can do something sneaky like only unlock the video object
	// for 'milliseconds' and otherwise hold the lock.
	while (g_main_context_pending(g_main_loop_get_context(mPump)))
	{
	       g_main_context_iteration(g_main_loop_get_context(mPump), FALSE);
	}

	// check for availability of a new frame
	
	if (mVideoSink)
	{
	        GST_OBJECT_LOCK(mVideoSink);
		if (mVideoSink->retained_frame_ready)
		{
			DEBUGMSG("NEW FRAME READY");

			if (mVideoSink->retained_frame_width != mCurrentWidth ||
			    mVideoSink->retained_frame_height != mCurrentHeight)
				// *TODO: also check for change in format
			{
				// just resize container, don't consume frame
				int neww = mVideoSink->retained_frame_width;
				int newh = mVideoSink->retained_frame_height;

				int newd = 4;
				mTextureFormatPrimary = GL_RGBA;
				mTextureFormatType = GL_UNSIGNED_INT_8_8_8_8_REV;

				/*
				int newd = SLVPixelFormatBytes[mVideoSink->retained_frame_format];
				if (SLV_PF_BGRX == mVideoSink->retained_frame_format)
				{
					mTextureFormatPrimary = GL_BGRA;
					mTextureFormatType = GL_UNSIGNED_INT_8_8_8_8_REV;
				}
				else
				{
					mTextureFormatPrimary = GL_RGBA;
					mTextureFormatType = GL_UNSIGNED_INT_8_8_8_8_REV;
				}
				*/

				GST_OBJECT_UNLOCK(mVideoSink);

				mCurrentRowbytes = neww * newd;
				DEBUGMSG("video container resized to %dx%d",
					 neww, newh);

				mDepth = newd;
				mCurrentWidth = neww;
				mCurrentHeight = newh;
				sizeChanged();
				return true;
			}

			if (mPixels &&
			    mCurrentHeight <= mHeight &&
			    mCurrentWidth <= mWidth &&
			    !mTextureSegmentName.empty())
			{
				// we're gonna totally consume this frame - reset 'ready' flag
				mVideoSink->retained_frame_ready = FALSE;
				int destination_rowbytes = mWidth * mDepth;
				for (int row=0; row<mCurrentHeight; ++row)
				{
					memcpy(&mPixels
					        [destination_rowbytes * row],
					       &mVideoSink->retained_frame_data
					        [mCurrentRowbytes * row],
					       mCurrentRowbytes);
				}

				GST_OBJECT_UNLOCK(mVideoSink);
				DEBUGMSG("NEW FRAME REALLY TRULY CONSUMED, TELLING HOST");

				setDirty(0,0,mCurrentWidth,mCurrentHeight);
			}
			else
			{
				// new frame ready, but we're not ready to
				// consume it.

				GST_OBJECT_UNLOCK(mVideoSink);

				DEBUGMSG("NEW FRAME not consumed, still waiting for a shm segment and/or shm resize");
			}

			return true;
		}
		else
		{
			// nothing to do yet.
			GST_OBJECT_UNLOCK(mVideoSink);
			return true;
		}
	}

	return true;
}
Esempio n. 18
0
static void
file_remote_progress_callback (goffset  current_num_bytes,
                               goffset  total_num_bytes,
                               gpointer user_data)
{
  RemoteProgress *progress = user_data;
  GTimeVal        now;

  /*  update the progress only up to 10 times a second  */
  g_get_current_time (&now);

  if (progress->last_time.tv_sec &&
      ((now.tv_sec - progress->last_time.tv_sec) * 1000 +
       (now.tv_usec - progress->last_time.tv_usec) / 1000) < 100)
    return;

  progress->last_time = now;

  if (total_num_bytes > 0)
    {
      const gchar *format;
      gchar       *done  = g_format_size (current_num_bytes);
      gchar       *total = g_format_size (total_num_bytes);

      switch (progress->mode)
        {
        case DOWNLOAD:
          format = _("Downloading image (%s of %s)");
          break;

        case UPLOAD:
          format = _("Uploading image (%s of %s)");
          break;

        default:
          g_assert_not_reached ();
        }

      gimp_progress_set_text (progress->progress, format, done, total);
      g_free (total);
      g_free (done);

      gimp_progress_set_value (progress->progress,
                               (gdouble) current_num_bytes /
                               (gdouble) total_num_bytes);
    }
  else
    {
      const gchar *format;
      gchar       *done = g_format_size (current_num_bytes);

      switch (progress->mode)
        {
        case DOWNLOAD:
          format = _("Downloaded %s of image data");
          break;

        case UPLOAD:
          format = _("Uploaded %s of image data");
          break;

        default:
          g_assert_not_reached ();
        }

      gimp_progress_set_text (progress->progress, format, done);
      g_free (done);

      gimp_progress_pulse (progress->progress);
    }

  while (! progress->cancel && g_main_context_pending (NULL))
    g_main_context_iteration (NULL, FALSE);
}
Esempio n. 19
0
int main(int argc, char *argv[])
{
	NCLError err;
	GOptionContext *context;
	GError *error = NULL;
	char **opt_command = NULL;
	char *opt_script = NULL;
	gboolean opt_keep_running = FALSE, show_help = FALSE;
	GOptionEntry options[] = {
		{ "exec", 'e', 0, G_OPTION_ARG_STRING_ARRAY, &opt_command,
		  "Execute command", "command" },
		{ "script", 's', 0, G_OPTION_ARG_STRING	, &opt_script,
		  "Execute script", "filename" },
		{ "keep", 'k', 0, G_OPTION_ARG_NONE, &opt_keep_running,
		  "Keep running after command/script execution" },
		{ NULL }
	};

	neardal_output_cb = ncl_trace;
	rl_callback_handler_install(NCL_PROMPT, ncl_parse_line);

	NCL_CMD_PRINT("Compiled at %s : %s\n\n", __DATE__, __TIME__);

	context = g_option_context_new(NULL);
	g_option_context_add_main_entries(context, options, NULL);
	if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
		NCL_CMD_PRINTERR("%s\n", error->message);
		g_error_free(error);
		return NCLERR_INIT;
	}
	g_option_context_free(context);

	if ((err = ncl_prv_init()) != NCLERR_NOERROR)
		goto exit;

	if (!opt_script && !opt_command) {
		opt_keep_running = TRUE;
		show_help = TRUE;
	}

	if (opt_script)
		ncl_prv_parse_script_file(opt_script);

	while (opt_command) {
		gNclCtx.errOnExit = ncl_exec(*opt_command);
		while (g_main_context_pending(NULL))
			g_main_context_iteration(NULL, FALSE);
		g_free(*opt_command++);
		if (!*opt_command)
			opt_command = NULL;
	}

	if (opt_keep_running) {
		gNclCtx.channel = g_io_channel_unix_new(STDIN_FILENO);
		gNclCtx.tag = g_io_add_watch(gNclCtx.channel, G_IO_IN,
					(GIOFunc) ncl_prv_kbinput_cb, &gNclCtx);
		g_io_channel_unref(gNclCtx.channel);

		if (show_help)
			ncl_exec(LISTCMD_NAME);

		g_main_loop_run(gNclCtx.main_loop);
	}

	err = gNclCtx.errOnExit;
exit:
	ncl_finalize();

	if (err != NCLERR_NOERROR)
		NCL_CMD_PRINTERR("Exit with error %d\n", err);

	return err;
}
Esempio n. 20
0
int
main (int argc, char *argv[])
{
  ClutterActor   *video;
  GdkPixbuf      *shot = NULL;
  gint            duration;
  CoglHandle      tex_id;
  CoglPixelFormat format;
  gint            size;
  gint            width;
  gint            height; 
  gint            rowstride;
  guchar         *data = NULL;

#ifdef USE_HELIX
  clutter_helix_init (&argc, &argv);
#else
  gst_init (&argc, &argv);
#endif
  clutter_init (&argc, &argv);

  if (argc < 3)
    {
      g_print ("Usage: %s <path to movie file> <output png>\n", argv[0]);
      exit(-1);
    }

  totem_resources_monitor_start (argv[1], 60 * G_USEC_PER_SEC);

#ifdef USE_HELIX
  video = clutter_helix_video_texture_new ();
#else
  video = clutter_gst_video_texture_new ();
#endif

  if (argv[1][0] == '/')
    clutter_media_set_filename(CLUTTER_MEDIA(video), argv[1]);
  else
    clutter_media_set_uri(CLUTTER_MEDIA(video), argv[1]);
  clutter_media_set_volume (CLUTTER_MEDIA(video), 0);
  clutter_media_set_playing (CLUTTER_MEDIA(video), TRUE);

  do {

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

    duration = clutter_media_get_duration (CLUTTER_MEDIA(video));

  } while (duration == 0);

  clutter_actor_realize (video);

  clutter_media_set_position (CLUTTER_MEDIA(video), duration/3);

  do {

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

  } while (clutter_media_get_position (CLUTTER_MEDIA(video)) <= duration/3);

  tex_id = clutter_texture_get_cogl_texture (CLUTTER_TEXTURE (video));
  if (tex_id)
    {
      format = cogl_texture_get_format (tex_id);
      size = cogl_texture_get_data (tex_id, format, 0, NULL);
      width = cogl_texture_get_width (tex_id);
      height = cogl_texture_get_height (tex_id);
      rowstride = cogl_texture_get_rowstride (tex_id);
      
      data = (guchar*) g_malloc (sizeof(guchar) * size);
      if (!data)
	g_error ("malloc");;

      cogl_texture_get_data (tex_id, format, rowstride, data);


      shot = gdk_pixbuf_new_from_data (data, 
				       GDK_COLORSPACE_RGB, 
				       FALSE, 
				       8,
				       width, 
				       height, 
				       rowstride, 
				       NULL, 
				       NULL);
      
    }

  totem_resources_monitor_stop ();

  if (shot)
    {
      GdkPixbuf *thumb, *pic;
      gint       x, y, nw, nh, w, h, size;
      
      size = 128;

      /* FIXME swap RGB pixels */

      w = clutter_actor_get_width (video);
      h = clutter_actor_get_height (video);
      
      nh = ( h * size) / w;

      if (nh <= size)
	{
	  nw = size;
	  x = 0;
	  y = (size - nh) / 2;
	}
      else
	{
	  nw  = ( w * size ) / h;
	  nh = size;
	  x = (size - nw) / 2;
	  y = 0;
	}

      thumb = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, size, size);
      gdk_pixbuf_fill (thumb, 0x000000FF);

      pic = gdk_pixbuf_scale_simple (shot, nw, nh, GDK_INTERP_BILINEAR);
      gdk_pixbuf_copy_area  (pic, 0, 0, nw, nh, thumb, x, y);
      
      if (!gdk_pixbuf_save (thumb, argv[2], "png", NULL, NULL))
	{
	  g_error ("%s: Pixbuf save failed\n", argv[0]);
	  exit(-1);
	}

      g_object_unref (shot);
      g_object_unref (thumb);
      g_object_unref (pic);

      exit(0);
    }

  exit (-1);
}
Esempio n. 21
0
void main_loop_test()
{
	GMainContext *default_context;
	int depth;
	int id;
	GTimeVal time ={0,};
	int user_data = 0,fd_data = 0;
	GPollFD pollfd;
	GSource *source3;

	GSourceFuncs SourceFuncs =
	{
		prepare,
		check,
		dispatch,
		NULL
	};

	GSourceFuncs fd_SourceFuncs =
	{
		fd_prepare,
		fd_check,
		fd_dispatch,
		NULL
	};

	e1_complete = FALSE;
	e2_complete = FALSE;

	pipe(fd);

	pollfd.fd = fd[0];
	pollfd.events = G_IO_IN | G_IO_HUP | G_IO_ERR;
	pollfd.revents = 0;

	pthread_create(&thread1, NULL, thread_function, NULL);

	context = g_main_context_new();

	//g_main_context_add_poll(context,&pollfd,0);

	source1 = g_source_new(&SourceFuncs,sizeof(GSource));
	g_source_set_callback(source1,(GSourceFunc)my_callback,&user_data,NULL);

	id = g_source_attach(source1,context);

	g_assert(g_source_get_id(source1) == id);

	g_source_set_priority(source1,0);

	g_assert(g_source_get_priority(source1) == 0);

	loop = g_main_loop_new(context, FALSE);

	default_context = g_main_loop_get_context(loop);

	//checks g_main_loop_get_context
	g_assert(default_context == context);

	//checks g_main_loop_is_running
	g_assert(g_main_loop_is_running(loop) == FALSE);

	depth = g_main_depth();

	//checks g_main_depth
	g_assert(depth == 0);

	g_source_get_current_time(source1,&time);

	g_assert(time.tv_usec > 0);

	g_source_set_can_recurse(source1,TRUE);

	g_assert(g_source_get_can_recurse(source1) == TRUE);

	source2 = g_source_new(&fd_SourceFuncs,sizeof(GSource));
	g_source_set_callback(source2,(GSourceFunc)fd_callback,&fd_data,NULL);
	g_source_add_poll(source2,&pollfd);

	g_source_remove_poll(source2,&pollfd);

	// checks g_source_remove_poll
	g_assert(source2->poll_fds == NULL);

	g_source_add_poll(source2,&pollfd);

	// checks whether g_source_add_poll is successful.
	// one more check is done in fd_callback.
	// If that function is callled we are sure that add poll was successful
	g_assert(source2->poll_fds->data == &pollfd);

	source3 = g_source_ref(source2);

	g_assert(source3 == source2 && source2->ref_count == 2);

	g_source_unref(source3);

	id = g_source_attach(source2,context);

	//checks g_main_context_pending
	g_assert(g_main_context_pending(context));

	g_main_loop_run(loop);

	// ref is called here. Thats why two unrefs are called. If the 2nd unref is
	// callled with the unref, code should crash
	g_main_loop_ref(loop);

	g_main_loop_unref(loop);

	g_main_loop_unref(loop);

	//checks the number of times the call back function is called
	g_assert(user_data == 100);

	// checks whether set poll was successful and call back for the same
	// was called
	g_assert(fd_data == 1);
}
Esempio n. 22
0
int
xg_select (int fds_lim, SELECT_TYPE *rfds, SELECT_TYPE *wfds, SELECT_TYPE *efds,
	   EMACS_TIME *timeout, sigset_t *sigmask)
{
  SELECT_TYPE all_rfds, all_wfds;
  EMACS_TIME tmo, *tmop = timeout;

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

  if (! (x_in_use
	 && g_main_context_pending (context = g_main_context_default ())))
    return pselect (fds_lim, rfds, wfds, efds, timeout, sigmask);

  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_emacs_time (tmo_in_millisec / 1000,
			     1000 * 1000 * (tmo_in_millisec % 1000));
      if (!timeout || EMACS_TIME_LT (tmo, *timeout))
	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 (our_fds > 0 || (nfds == 0 && tmop == &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;
}
Esempio n. 23
0
bool QEventDispatcherGlib::hasPendingEvents()
{
    Q_D(QEventDispatcherGlib);
    return g_main_context_pending(d->mainContext);
}
Esempio n. 24
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)
      {
        while (n_gfds > gfds_size)
          gfds_size *= 2;
        xfree (gfds);
        gfds = xmalloc (sizeof (*gfds) * gfds_size);
      }

    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;
}
Esempio n. 25
0
static gboolean
launch_test_binary (const char *binary,
                    guint       skip_tests)
{
  GTestLogBuffer *tlb;
  GSList *slist, *free_list = NULL;
  GError *error = NULL;
  int argc = 0;
  const gchar **argv;
  GPid pid = 0;
  gint report_pipe[2] = { -1, -1 };
  guint child_report_cb_id = 0;
  gboolean loop_pending;
  gint i = 0;

  if (!g_unix_open_pipe (report_pipe, FD_CLOEXEC, &error))
    {
      if (subtest_mode_fatal)
        g_error ("Failed to open pipe for test binary: %s: %s", binary, error->message);
      else
        g_warning ("Failed to open pipe for test binary: %s: %s", binary, error->message);
      g_clear_error (&error);
      return FALSE;
    }

  /* setup argc */
  for (slist = subtest_args; slist; slist = slist->next)
    argc++;
  /* argc++; */
  if (subtest_quiet)
    argc++;
  if (subtest_verbose)
    argc++;
  if (!subtest_mode_fatal)
    argc++;
  /* Either -m=quick or -m=slow is always appended. */
  argc++;
  if (subtest_mode_perf)
    argc++;
  if (!subtest_mode_undefined)
    argc++;
  if (gtester_list_tests)
    argc++;
  if (subtest_seedstr)
    argc++;
  argc++;
  if (skip_tests)
    argc++;
  for (slist = subtest_paths; slist; slist = slist->next)
    argc++;
  for (slist = skipped_paths; slist; slist = slist->next)
    argc++;

  /* setup argv */
  argv = g_malloc ((argc + 2) * sizeof(gchar *));
  argv[i++] = binary;
  for (slist = subtest_args; slist; slist = slist->next)
    argv[i++] = (gchar*) slist->data;
  /* argv[i++] = "--debug-log"; */
  if (subtest_quiet)
    argv[i++] = "--quiet";
  if (subtest_verbose)
    argv[i++] = "--verbose";
  if (!subtest_mode_fatal)
    argv[i++] = "--keep-going";
  if (subtest_mode_quick)
    argv[i++] = "-m=quick";
  else
    argv[i++] = "-m=slow";
  if (subtest_mode_perf)
    argv[i++] = "-m=perf";
  if (!subtest_mode_undefined)
    argv[i++] = "-m=no-undefined";
  if (gtester_list_tests)
    argv[i++] = "-l";
  if (subtest_seedstr)
    argv[i++] = queue_gfree (&free_list, g_strdup_printf ("--seed=%s", subtest_seedstr));
  argv[i++] = queue_gfree (&free_list, g_strdup_printf ("--GTestLogFD=%u", report_pipe[1]));
  if (skip_tests)
    argv[i++] = queue_gfree (&free_list, g_strdup_printf ("--GTestSkipCount=%u", skip_tests));
  for (slist = subtest_paths; slist; slist = slist->next)
    argv[i++] = queue_gfree (&free_list, g_strdup_printf ("-p=%s", (gchar*) slist->data));
  for (slist = skipped_paths; slist; slist = slist->next)
    argv[i++] = queue_gfree (&free_list, g_strdup_printf ("-s=%s", (gchar*) slist->data));
  argv[i++] = NULL;

  g_spawn_async_with_pipes (NULL, /* g_get_current_dir() */
                            (gchar**) argv,
                            NULL, /* envp */
                            G_SPAWN_DO_NOT_REAP_CHILD, /* G_SPAWN_SEARCH_PATH */
                            unset_cloexec_fdp, &report_pipe[1], /* pre-exec callback */
                            &pid,
                            NULL,       /* standard_input */
                            NULL,       /* standard_output */
                            NULL,       /* standard_error */
                            &error);
  g_slist_foreach (free_list, (void(*)(void*,void*)) g_free, NULL);
  g_slist_free (free_list);
  free_list = NULL;
  close (report_pipe[1]);

  if (!gtester_quiet)
    g_print ("(pid=%lu)\n", (unsigned long) pid);

  if (error)
    {
      close (report_pipe[0]);
      if (subtest_mode_fatal)
        g_error ("Failed to execute test binary: %s: %s", argv[0], error->message);
      else
        g_warning ("Failed to execute test binary: %s: %s", argv[0], error->message);
      g_clear_error (&error);
      g_free (argv);
      return FALSE;
    }
  g_free (argv);

  subtest_running = TRUE;
  subtest_io_pending = TRUE;
  tlb = g_test_log_buffer_new();
  if (report_pipe[0] >= 0)
    {
      ioc_report = g_io_channel_unix_new (report_pipe[0]);
      g_io_channel_set_flags (ioc_report, G_IO_FLAG_NONBLOCK, NULL);
      g_io_channel_set_encoding (ioc_report, NULL, NULL);
      g_io_channel_set_buffered (ioc_report, FALSE);
      child_report_cb_id = g_io_add_watch_full (ioc_report, G_PRIORITY_DEFAULT - 1, G_IO_IN | G_IO_ERR | G_IO_HUP, child_report_cb, tlb, NULL);
      g_io_channel_unref (ioc_report);
    }
  g_child_watch_add_full (G_PRIORITY_DEFAULT + 1, pid, child_watch_cb, NULL, NULL);

  loop_pending = g_main_context_pending (NULL);
  while (subtest_running ||     /* FALSE once child exits */
         subtest_io_pending ||  /* FALSE once ioc_report closes */
         loop_pending)          /* TRUE while idler, etc are running */
    {
      /* g_print ("LOOPSTATE: subtest_running=%d subtest_io_pending=%d\n", subtest_running, subtest_io_pending); */
      /* check for unexpected hangs that are not signalled on report_pipe */
      if (!subtest_running &&   /* child exited */
          subtest_io_pending && /* no EOF detected on report_pipe */
          !loop_pending)        /* no IO events pending however */
        break;
      g_main_context_iteration (NULL, TRUE);
      loop_pending = g_main_context_pending (NULL);
    }

  if (subtest_io_pending)
    g_source_remove (child_report_cb_id);

  close (report_pipe[0]);
  g_test_log_buffer_free (tlb);

  return TRUE;
}
Esempio n. 26
0
static void test_dom_document_garbage_collection(DomDocumentFixture* fixture, gconstpointer data)
{
    guint count = 0;
    g_assert(fixture);
    WebKitWebView* view = (WebKitWebView*)fixture->webView;
    g_assert(view);
    WebKitDOMDocument* document = webkit_web_view_get_dom_document(view);
    g_assert(document);
    g_object_weak_ref(G_OBJECT(document), (GWeakNotify)weak_notify, &count);
    WebKitDOMHTMLHeadElement* head = webkit_dom_document_get_head(document);
    g_assert(head);
    g_object_weak_ref(G_OBJECT(head), (GWeakNotify)weak_notify, &count);
    WebKitDOMHTMLElement* body = webkit_dom_document_get_body(document);
    g_assert(body);
    g_object_weak_ref(G_OBJECT(body), (GWeakNotify)weak_notify, &count);
    WebKitDOMHTMLCollection *collection = webkit_dom_document_get_links(document);
    g_assert(collection);
    g_object_weak_ref(G_OBJECT(collection), (GWeakNotify)weak_notify, &count);

    webkit_web_view_load_string(WEBKIT_WEB_VIEW(view), HTML_DOCUMENT_LINKS, NULL, NULL, NULL);

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

    g_assert_cmpuint(count, ==, 3);

    g_object_unref(collection);
    g_assert_cmpuint(count, ==, 4);

    count = 0;

    document = webkit_web_view_get_dom_document(view);
    g_assert(document);
    g_object_weak_ref(G_OBJECT(document), (GWeakNotify)weak_notify, &count);
    head = webkit_dom_document_get_head(document);
    g_assert(head);
    g_object_weak_ref(G_OBJECT(head), (GWeakNotify)weak_notify, &count);
    body = webkit_dom_document_get_body(document);
    g_assert(body);
    g_object_weak_ref(G_OBJECT(body), (GWeakNotify)weak_notify, &count);
    collection = webkit_dom_document_get_links(document);
    g_assert(collection);
    g_object_weak_ref(G_OBJECT(collection), (GWeakNotify)weak_notify, &count);
    /* Ask twice for the same object */
    WebKitDOMHTMLCollection* collection2 = webkit_dom_document_get_links(document);
    g_assert(collection2);
    g_object_weak_ref(G_OBJECT(collection2), (GWeakNotify)weak_notify, &count);

    g_object_unref(document);
    g_object_unref(head);
    g_object_unref(body);
    g_object_unref(collection);
    g_object_unref(collection2);

    g_assert_cmpuint(count, ==, 5);

    webkit_web_view_load_string(WEBKIT_WEB_VIEW(view), HTML_DOCUMENT_IFRAME, NULL, NULL, NULL);

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

    count = 0;

    document = webkit_web_view_get_dom_document(view);
    WebKitDOMElement* div = webkit_dom_document_get_element_by_id(document, "test");
    g_assert(div);
    g_object_weak_ref(G_OBJECT(div), (GWeakNotify)weak_notify, &count);
    WebKitDOMElement* iframe = webkit_dom_document_get_element_by_id(document, "iframe");
    g_assert(iframe);

    webkit_dom_element_set_attribute(iframe, "src", "data:<html><head></head></html>", NULL);

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

    WebKitDOMDocument* iframeDocument = webkit_dom_html_iframe_element_get_content_document(WEBKIT_DOM_HTML_IFRAME_ELEMENT(iframe));
    g_assert(iframeDocument);
    head = webkit_dom_document_get_head(iframeDocument);
    g_assert(head);
    g_object_weak_ref(G_OBJECT(head), (GWeakNotify)weak_notify, &count);

    webkit_dom_element_set_attribute(iframe, "src", "about:blank", NULL);

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

    g_assert_cmpuint(count, ==, 1);

    webkit_web_view_load_string(WEBKIT_WEB_VIEW(view), HTML_DOCUMENT_LINKS, NULL, NULL, NULL);

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

    g_assert_cmpuint(count, ==, 2);

    count = 0;

    document = webkit_web_view_get_dom_document(view);
    g_assert(document);
    g_object_weak_ref(G_OBJECT(document), (GWeakNotify)weak_notify, &count);
    /* Ask twice for the Document */
    WebKitDOMDocument* document2 = webkit_web_view_get_dom_document(view);
    g_assert(document2);
    g_object_weak_ref(G_OBJECT(document2), (GWeakNotify)weak_notify, &count);
    head = webkit_dom_document_get_head(document);
    g_assert(head);
    g_object_weak_ref(G_OBJECT(head), (GWeakNotify)weak_notify, &count);
    body = webkit_dom_document_get_body(document);
    g_assert(body);
    g_object_weak_ref(G_OBJECT(body), (GWeakNotify)weak_notify, &count);
    collection = webkit_dom_document_get_links(document);
    g_assert(collection);
    g_object_weak_ref(G_OBJECT(collection), (GWeakNotify)weak_notify, &count);

    gtk_widget_destroy(fixture->webView);
    fixture->webView = NULL;

    g_assert_cmpuint(count, ==, 4);

    g_object_unref(collection);

    g_assert_cmpuint(count, ==, 5);
}
Esempio n. 27
0
int main()
{
    Samoyed::Scheduler scheduler(8);

    AlarmDriver d1(scheduler, 1, 1, 1),
                d2(scheduler, 2, 2, 2),
                d3(scheduler, 3, 3, 3),
                d4(scheduler, 4, 4, 4),
                d5(scheduler, 5, 5, 5);
    boost::system_time t = boost::get_system_time();
    printf("Alarm 1 runs 10 times\n");
    d1.run(10, false);
    printf("Scheduler starts 3 threads\n");
    scheduler.size_controller().resize(3);
    printf("Alarm 2 runs 1 more time\n");
    d2.run(1, true);
    t += boost::posix_time::seconds(5);
    boost::thread::sleep(t);
    printf("Alarm 1 runs 1 time\n");
    d1.run(1, false);
    printf("Alarm 2 runs 2 more times\n");
    d2.run(2, true);
    printf("Alarm 3 runs 1 more time\n");
    d3.run(1, true);
    printf("Alarm 4 runs 7 more times\n");
    d4.run(7, true);
    printf("Alarm 5 runs 5 more times\n");
    d5.run(5, true);
    t += boost::posix_time::seconds(7);
    boost::thread::sleep(t);
    printf("Scheduler resizes to 2 threads\n");
    scheduler.size_controller().resize(2);
    printf("Alarm 1 runs 1 time\n");
    d1.run(1, false);
    printf("Alarm 2 runs 7 more times\n");
    d2.run(7, true);
    printf("Alarm 3 runs 11 more times\n");
    d3.run(11, true);
    printf("Alarm 4 runs 5 more times\n");
    d4.run(5, true);
    printf("Alarm 5 runs 7 times\n");
    d5.run(7, false);

    scheduler.wait();

    GMainContext *ctx = g_main_context_default();
    while (g_main_context_pending(ctx))
        g_main_context_iteration(ctx, TRUE);

    boost::shared_ptr<Alarm> a1(new Alarm(scheduler, 1, 1, 1, 1)),
                             a2(new Alarm(scheduler, 2, 2, 2, 2)),
                             a3(new Alarm(scheduler, 3, 3, 3, 3)),
                             a4(new Alarm(scheduler, 4, 4, 4, 4)),
                             a5(new Alarm(scheduler, 5, 5, 5, 5));
    a2->addDependency(a1);
    a3->addDependency(a1);
    a4->addDependency(a2);
    a4->addDependency(a3);
    a5->addDependency(a1);
    a5->addDependency(a2);
    a5->addDependency(a3);

    printf("Submit all\n");
    a5->submit(a5);
    a4->submit(a4);
    a3->submit(a3);
    a2->submit(a2);
    a1->submit(a1);

    a1.reset();
    a2.reset();
    a3.reset();
    a4.reset();

    t = boost::get_system_time() + boost::posix_time::seconds(5);
    boost::thread::sleep(t);
    printf("Cancel alarm 5\n");
    a5->cancel(a5);
    a5.reset();

    scheduler.wait();

    while (g_main_context_pending(ctx))
        g_main_context_iteration(ctx, TRUE);
    return 0;
}
Esempio n. 28
0
GdkPixbuf *
gst_video_thumbnailer_get_shot (const gchar  *location,
          GCancellable *cancellable)
{
    GstElement *playbin, *audio_sink, *video_sink;
    GstStateChangeReturn state;
    GdkPixbuf *shot = NULL;
    int count = 0;
    gchar *uri = g_strconcat ("file://", location, NULL);
    GMainContext *context = g_main_context_new ();

    g_main_context_push_thread_default  (context);

    playbin = gst_element_factory_make ("playbin", "playbin");
    audio_sink = gst_element_factory_make ("fakesink", "audiosink");
    video_sink = gst_element_factory_make ("fakesink", "videosink");

    g_object_set (playbin,
                  "uri", uri,
                  "audio-sink", audio_sink,
                  "video-sink", video_sink,
                  NULL);
    g_object_set (video_sink,
                  "sync", TRUE,
                  NULL);
    state = gst_element_set_state (playbin, GST_STATE_PAUSED);
    while (state == GST_STATE_CHANGE_ASYNC
           && count < 5
           && !g_cancellable_is_cancelled (cancellable)) {
        state = gst_element_get_state (playbin, NULL, 0, 1 * GST_SECOND);
        count++;

        /* Spin mainloop so we can pick up the cancels */
        while (g_main_context_pending (context)) {
            g_main_context_iteration (context, FALSE);
        }
    }


    if (g_cancellable_is_cancelled (cancellable)) {
        g_print ("Video %s was cancelled\n", uri);
        state = GST_STATE_CHANGE_FAILURE;
    }

    if (state != GST_STATE_CHANGE_FAILURE &&
        state != GST_STATE_CHANGE_ASYNC) {
        GstFormat format = GST_FORMAT_TIME;
        gint64 duration;

        if (gst_element_query_duration (playbin, &format, &duration)) {
            gint64 seekpos;
            GstBuffer *frame;

            if (duration > 0) {
                if (duration / (3 * GST_SECOND) > 90) {
                    seekpos = (rand () % (duration / (3 * GST_SECOND))) * GST_SECOND;
                } else {
                    seekpos = (rand () % (duration / (GST_SECOND))) * GST_SECOND;
                }
            } else {
                seekpos = 5 * GST_SECOND;
            }

            gst_element_seek_simple (playbin, GST_FORMAT_TIME,
                                     GST_SEEK_FLAG_FLUSH |
                                     GST_SEEK_FLAG_ACCURATE, seekpos);

            /* Wait for seek to complete */
            count = 0;
            state = gst_element_get_state (playbin, NULL, 0,
                                           0.2 * GST_SECOND);
            while (state == GST_STATE_CHANGE_ASYNC && count < 3) {
                state = gst_element_get_state (playbin, NULL, 0, 1 * GST_SECOND);
                count++;
            }

            g_object_get (playbin,
                          "frame", &frame,
                          NULL);
            if (frame == NULL) {
                g_warning ("No frame for %s", uri);
                shot = NULL;
                goto finish;
            }

            shot = convert_buffer_to_pixbuf (frame, cancellable);
        }
    }

    gst_element_set_state (playbin, GST_STATE_NULL);
    g_object_unref (playbin);
    g_free (uri);

 finish:

    g_main_context_pop_thread_default (context);
    g_main_context_unref (context);

    return shot;
}
Esempio n. 29
0
///////////////////////////////////////////////////////////////////////////////
// virtual
bool LLMediaImplGStreamer::updateMedia()
{
	//LL_DEBUGS("MediaImpl") << "updating media..." << LL_ENDL;
	
	// sanity check
	if (mPump == NULL || mPlaybin == NULL)
	{
#ifdef LL_GST_REPORT_STATE_CHANGES
		LL_DEBUGS("MediaImpl") << "dead media..." << LL_ENDL;
#endif
		mState = GST_STATE_NULL;
		setStatus(LLMediaBase::STATUS_DEAD);
		return false;
	}

	if (mState == GST_STATE_VOID_PENDING || mState == GST_STATE_NULL)
		return false;

	// process next outstanding command
	switch (nextCommand())
	{
	case LLMediaBase::COMMAND_START:
		LL_DEBUGS("MediaImpl") << "COMMAND_START" << LL_ENDL;
		if (getStatus() == LLMediaBase::STATUS_PAUSED ||
		    getStatus() == LLMediaBase::STATUS_NAVIGATING ||
		    getStatus() == LLMediaBase::STATUS_STOPPED)
		{
			play();
			setStatus(LLMediaBase::STATUS_STARTED);
			clearCommand();
		}
		break;
	case LLMediaBase::COMMAND_STOP:
		LL_DEBUGS("MediaImpl") << "COMMAND_STOP" << LL_ENDL;
		stop();
		setStatus(LLMediaBase::STATUS_STOPPED);
		clearCommand();
		break;
	case LLMediaBase::COMMAND_PAUSE:
		LL_DEBUGS("MediaImpl") << "COMMAND_PAUSE" << LL_ENDL;
		if (getStatus() == LLMediaBase::STATUS_STARTED)
		{
			pause();
			setStatus(LLMediaBase::STATUS_PAUSED);
			clearCommand();
		}
		break;
	default:
		LL_INFOS("MediaImpl") << "Unknown command" << LL_ENDL;
		clearCommand();
		break;
	case LLMediaBase::COMMAND_NONE:
		break;
	}

	// deal with results
	if (g_main_context_pending(g_main_loop_get_context(mPump)))
	{
	       g_main_context_iteration(g_main_loop_get_context(mPump), FALSE);
	}

	if (mVideoSink)
	{
	        GST_OBJECT_LOCK(mVideoSink);
		if (mVideoSink->retained_frame_ready)
		{
#ifdef LL_GST_REPORT_STATE_CHANGES
			LL_DEBUGS("MediaImpl") <<"NEW FRAME " << LL_ENDL;
#endif
			if (mVideoSink->retained_frame_width != getMediaWidth() ||
			    mVideoSink->retained_frame_height != getMediaHeight())
				// *TODO: also check for change in format
			{
				// just resize containe
				int neww = mVideoSink->retained_frame_width;
				int newh = mVideoSink->retained_frame_height;
				int newd = SLVPixelFormatBytes[mVideoSink->retained_frame_format];
				if (SLV_PF_RGBX == mVideoSink->retained_frame_format)
				{
					mTextureFormatPrimary = LL_MEDIA_RGBA;
					mTextureFormatType = LL_MEDIA_UNSIGNED_INT_8_8_8_8_REV;
				}
				else
				{
					mTextureFormatPrimary = LL_MEDIA_BGRA;
					mTextureFormatType = LL_MEDIA_UNSIGNED_INT_8_8_8_8_REV;
				}
				mMediaRowbytes = neww * newd;
				LL_DEBUGS("MediaImpl")
				    << "video container resized to " <<
				    neww <<"x"<< newh << LL_ENDL;
				
				delete[] mediaData;
				mediaData = new unsigned char[mMediaRowbytes *
							      newh];
				
				GST_OBJECT_UNLOCK(mVideoSink);

				setMediaDepth(newd);
				setMediaSize(neww, newh);
				return true;
			}

			// we're gonna totally consume this frame - reset 'ready' flag
			mVideoSink->retained_frame_ready = FALSE;
			memcpy(mediaData, mVideoSink->retained_frame_data,
			       mMediaRowbytes * getMediaHeight());
			
			GST_OBJECT_UNLOCK(mVideoSink);
			LLMediaEvent event( this );
			mEventEmitter.update( &LLMediaObserver::onMediaContentsChange, event );
			return true;
		}
		else
		{
			// nothing to do yet.
			GST_OBJECT_UNLOCK(mVideoSink);
			return true;
		}
	}

	return true;
}
Esempio n. 30
0
S32
LLMediaImplGStreamer::
updateMedia ()
{
	//llinfos << "updating media..." << llendl;
	if (g_main_context_pending(g_main_loop_get_context(mPump)))
	{
	       g_main_context_iteration(g_main_loop_get_context(mPump), FALSE);
	}

	if (mVideoSink)
	{
	        GST_OBJECT_LOCK(mVideoSink);
		if (mVideoSink->retained_frame_ready)
		{
			//llinfos << "NEW FRAME " << llendl;
			if (mVideoSink->retained_frame_width != mMediaWidth ||
			    mVideoSink->retained_frame_height != mMediaHeight)
				// *TODO: also check for change in format
			{
				// just resize container
				mMediaWidth = mVideoSink->retained_frame_width;
				mMediaHeight = mVideoSink->retained_frame_height;
				mTextureWidth = mMediaWidth;
				mTextureHeight = mMediaHeight;
				mMediaDepthBytes = mTextureDepth =
					SLVPixelFormatBytes[mVideoSink->retained_frame_format];
				if (SLV_PF_RGBX == mVideoSink->retained_frame_format)
				{
					mTextureFormatPrimary = GL_RGBA;
					mTextureFormatType=GL_UNSIGNED_INT_8_8_8_8_REV;
				}
				else
				{
					mTextureFormatPrimary = GL_BGRA;
					mTextureFormatType=GL_UNSIGNED_INT_8_8_8_8_REV;
				}
				mMediaRowbytes = mMediaWidth * mMediaDepthBytes;
				llinfos << "video container resized to " <<
					mMediaWidth << "x" << mMediaHeight << llendl;
				
				if (ownBuffer)
				{
					// we manage the buffer, so we need to realloc
					delete[] mediaData;
					mediaData = new U8[mMediaRowbytes *
							   mMediaHeight];
				}
				
				GST_OBJECT_UNLOCK(mVideoSink);
				return updateMediaNeedsSizeChange;
			}

			// we're gonna totally consume this frame - reset 'ready' flag
			mVideoSink->retained_frame_ready = FALSE;
			memcpy(mediaData, mVideoSink->retained_frame_data,
			       mMediaRowbytes * mMediaHeight);
			
			GST_OBJECT_UNLOCK(mVideoSink);
			return updateMediaNeedsUpdate;
		}
		else
		{
			// nothing to do yet.
			GST_OBJECT_UNLOCK(mVideoSink);
			return updateMediaNoChanges;
		}
	}

	return updateMediaNoChanges;
}