Exemple #1
0
static void
mx_adjustment_clamp_page (MxAdjustment *adjustment,
                          gdouble       lower,
                          gdouble       upper)
{
  MxAdjustmentPrivate *priv;
  gboolean changed;

  g_return_if_fail (MX_IS_ADJUSTMENT (adjustment));

  priv = adjustment->priv;

  lower = CLAMP (lower, priv->lower, priv->upper - priv->page_size);
  upper = CLAMP (upper, priv->lower + priv->page_size, priv->upper);

  changed = FALSE;

  if (priv->value + priv->page_size > upper)
    {
      priv->value = upper - priv->page_size;
      changed = TRUE;
    }

  if (priv->value < lower)
    {
      priv->value = lower;
      changed = TRUE;
    }

  if (changed && !priv->value_source)
    priv->value_source =
      g_idle_add_full (CLUTTER_PRIORITY_REDRAW,
                       (GSourceFunc)mx_adjustment_value_notify_cb,
                       adjustment,
                       NULL);
}
Exemple #2
0
static void
fcitx_im_context_focus_in(ClutterIMContext *context)
{
    FcitxLog(LOG_LEVEL, "fcitx_im_context_focus_in");
    FcitxIMContext *fcitxcontext = FCITX_IM_CONTEXT(context);

    if (fcitxcontext->has_focus)
        return;

    fcitxcontext->has_focus = true;

    if (IsFcitxIMClientValid(fcitxcontext->client)) {
        FcitxIMClientFocusIn(fcitxcontext->client);
    }

    /* set_cursor_location_internal() will get origin from X server,
     * it blocks UI. So delay it to idle callback. */
    g_idle_add_full(G_PRIORITY_DEFAULT_IDLE,
                    (GSourceFunc) _set_cursor_location_internal,
                    g_object_ref(fcitxcontext),
                    (GDestroyNotify) g_object_unref);

    return;
}
Exemple #3
0
static gboolean
_mx_adjustment_set_page_increment (MxAdjustment *adjustment,
                                   gdouble       page)
{
  MxAdjustmentPrivate *priv = adjustment->priv;

  if (priv->page_increment != page)
    {
      priv->page_increment = page;

      mx_adjustment_emit_changed (adjustment);

      if (!priv->page_inc_source)
        priv->page_inc_source =
          g_idle_add_full (CLUTTER_PRIORITY_REDRAW,
                           (GSourceFunc)mx_adjustment_page_inc_notify_cb,
                           adjustment,
                           NULL);

      return TRUE;
    }

  return FALSE;
}
static void
xfce_panel_image_size_allocate (GtkWidget     *widget,
                                GtkAllocation *allocation)
{
  XfcePanelImagePrivate *priv = XFCE_PANEL_IMAGE (widget)->priv;


  widget->allocation = *allocation;

  /* check if the available size changed */
  if ((priv->pixbuf != NULL || priv->source != NULL)
      && allocation->width > 0
      && allocation->height > 0
      && (allocation->width != priv->width
      || allocation->height != priv->height))
    {
      /* store the new size */
      priv->width = allocation->width;
      priv->height = allocation->height;

      /* free cache */
      xfce_panel_image_unref_null (priv->cache);

      if (priv->pixbuf == NULL)
        {
          /* delay icon loading */
          priv->idle_load_id = g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, xfce_panel_image_load,
                                                widget, xfce_panel_image_load_destroy);
        }
      else
        {
          /* directly render pixbufs */
          xfce_panel_image_load (widget);
        }
    }
}
/* This will schedule a move of the thumbnail for source image to dest when idle.
 * We do this so that file renaming or moving speed is not sacrificed by
 * moving the thumbnails at the same time because:
 *
 * This cache design requires the tedious task of loading the png thumbnails and saving them.
 *
 * The thumbnails are processed when the app is idle. If the app
 * exits early well too bad - they can simply be regenerated from scratch.
 *
 * This does not manage local thumbnails (fixme ?)
 */
void thumb_std_maint_moved(const gchar *source, const gchar *dest)
{
	TMaintMove *tm;

	tm = g_new0(TMaintMove, 1);
	tm->source = g_strdup(source);
	tm->dest = g_strdup(dest);

	if (!thumb_std_maint_move_list)
		{
		g_idle_add_full(G_PRIORITY_LOW, thumb_std_maint_move_idle, NULL, NULL);
		}

	if (thumb_std_maint_move_tail)
		{
		thumb_std_maint_move_tail = g_list_append(thumb_std_maint_move_tail, tm);
		thumb_std_maint_move_tail = thumb_std_maint_move_tail->next;
		}
	else
		{
		thumb_std_maint_move_list = g_list_append(thumb_std_maint_move_list, tm);
		thumb_std_maint_move_tail = thumb_std_maint_move_list;
		}
}
static void channel_destroy(SpiceSession *s, SpiceChannel *channel, gpointer data)
{
    //__android_log_write(ANDROID_LOG_DEBUG, TAG, "channel_destroy called");

    struct spice_context *ctx = data;
    int id;

    g_object_get(channel, "channel-id", &id, NULL);

    if (SPICE_IS_DISPLAY_CHANNEL(channel)) {
        if (ctx->display && ctx->display_channel == id) {
            SPICE_DEBUG("zap display channel (#%d)", id);
            g_object_unref(ctx->display);
            ctx->display = NULL;
        }
    }

    ctx->channels--;
    //__android_log_print(ANDROID_LOG_DEBUG, TAG, "Number of channels: %d", ctx->channels);
    if (ctx->channels == 0) {
        g_idle_add_full(G_PRIORITY_DEFAULT, destroy_context_callback, ctx,
                NULL);
    }
}
static DBusHandlerResult
dbus_filter_function (DBusConnection *connection,
                      DBusMessage *message,
                      void *user_data)
{
  if (dbus_message_is_signal (message, DBUS_INTERFACE_LOCAL, "Disconnected") &&
      !tp_strdiff (dbus_message_get_path (message), DBUS_PATH_LOCAL))
    {
      /* MC initialization sets exit on disconnect - turn it off again, so we
       * get a graceful exit instead (to keep gcov happy) */
      dbus_connection_set_exit_on_disconnect (connection, FALSE);

      g_message ("Got disconnected from the session bus");

      mcd_mission_abort ((McdMission *) mcd);
    }
  else if (dbus_message_is_method_call (message,
        "org.freedesktop.Telepathy.MissionControl5.RegressionTests",
        "Abort"))
    {
      DBusMessage *reply;

      g_idle_add (delayed_abort, NULL);

      reply = dbus_message_new_method_return (message);

      if (reply == NULL || !dbus_connection_send (connection, reply, NULL))
        g_error ("Out of memory");

      dbus_message_unref (reply);

      return DBUS_HANDLER_RESULT_HANDLED;
    }
  else if (dbus_message_is_method_call (message,
        "org.freedesktop.Telepathy.MissionControl5.RegressionTests",
        "BillyIdle"))
    {
      /* Used to drive a souped-up version of sync_dbus(), where we need to
       * ensure that all idles have fired, on top of the D-Bus queue being
       * drained.
       */
      DBusMessage *reply = dbus_message_new_method_return (message);
      GVariant *variant;
      GDBusConnection *system_bus;

      if (reply == NULL)
        g_error ("Out of memory");

      /* Sync GDBus, too, to make sure we have received any pending
       * FakeNetworkMonitor messages. */
      system_bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, NULL);
      g_assert (system_bus != NULL);
      variant = g_dbus_connection_call_sync (system_bus,
          "org.freedesktop.DBus", "/org/freedesktop/DBus",
          "org.freedesktop.DBus", "ListNames",
          NULL, NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL);
      g_assert (variant != NULL);
      g_variant_unref (variant);
      g_object_unref (system_bus);

      g_idle_add_full (G_PRIORITY_LOW, billy_idle, reply,
          (GDestroyNotify) dbus_message_unref);

      return DBUS_HANDLER_RESULT_HANDLED;
    }

  return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
Exemple #8
0
void fm_volume_manager_init()
{
    /* init the volume manager when idle */
    on_idle_handler = g_idle_add_full(G_PRIORITY_LOW, fm_volume_manager_delay_init, NULL, NULL);
}
void
symbol_db_view_locals_update_list (SymbolDBViewLocals *dbvl, SymbolDBEngine *dbe,
							  const gchar* filepath, gboolean force_update)
{
	SymbolDBViewLocalsPriv *priv;
	SymbolDBEngineIterator *iterator;
	GtkTreeStore *store;	
	FileSymbolsStatus *fsstatus;
	
	g_return_if_fail (dbvl != NULL);
	g_return_if_fail (filepath != NULL);
	g_return_if_fail (dbe != NULL);

	priv = dbvl->priv;

	DEBUG_PRINT ("filepath %s", filepath);
	
	/* we're not interested in giving user an updated gtktreestore if recv signals
	 * is false. In that case we can have a project importing...
	 * We should pass on this test if the force option is activated (i.e. is TRUE)
	 */
	if (priv->recv_signals == FALSE && force_update == FALSE)
	{		
		gtk_tree_view_set_model (GTK_TREE_VIEW (dbvl), NULL);
		DEBUG_PRINT ("recv signals is false");
		return;
	}
	
	/* it's a good thing to enable the gtktreewidget */
	gtk_widget_set_sensitive (GTK_WIDGET (dbvl), TRUE);
	
	/* ok, we can have a case where we're revisiting an old file with an already 
	 * populated GtkTreeStore. We're gonna set that gtktreestore along with the
	 * GTree(s) for nodes_displayed and waiting_for.
	 */
	fsstatus = NULL;
	
	if (priv->current_db_file != NULL)
	{
		FileSymbolsStatus *hash_node;
		/* save current symbols status - e.g. gtktreestore, symbols_displayed etc.,
		 * if it hasn't already been done.
		 */
		hash_node = g_hash_table_lookup (priv->files_view_status, 
										 priv->current_db_file);
		
		/* did we find something? yes? well, then we should save nothing... */
		if (hash_node == NULL)
		{
			/* found nothing? ok, save the status */
			GtkTreeStore * store;
		
			/* remove the GSourceFunc, if it's running */
			if (priv->insertion_idle_handler > 0)
			{				
				g_source_remove (priv->insertion_idle_handler);
				priv->insertion_idle_handler = 0;
			}
			
			store = GTK_TREE_STORE (gtk_tree_view_get_model (GTK_TREE_VIEW (dbvl)));	
			
			if (store != NULL && priv->nodes_displayed != NULL 
				&& priv->waiting_for != NULL)
			{
				FileSymbolsStatus *fss;
				fss = g_new0 (FileSymbolsStatus, 1);
				fss->store = store;
				fss->nodes_displayed = priv->nodes_displayed;
				fss->waiting_for = priv->waiting_for;
				fss->symbols_inserted_ids = priv->symbols_inserted_ids;
				
				/*DEBUG_PRINT ("%s", "symbol_db_view_locals_update_list (): "
					"g_hash_table_insert ");*/
				/* insert it */
				g_hash_table_insert (priv->files_view_status, 
									 g_strdup (priv->current_db_file), fss);
			}			
		}
	}
	

	/* adjust some vars */
	g_free (priv->current_db_file);
	priv->current_db_file = NULL;
	
	g_free (priv->current_local_file_path);
	priv->current_local_file_path = NULL;

	priv->current_db_file = 
		symbol_db_util_get_file_db_path (dbe, filepath);
	if (priv->current_db_file == NULL) 
	{
		/* the file simply isn't in the db. Don't display nothing. */
		return;
	}
	priv->current_local_file_path = g_strdup (filepath);
	
	/* try to see if we had something saved before in the hash table */
	fsstatus = g_hash_table_lookup (priv->files_view_status,
									priv->current_db_file);	

	if (fsstatus != NULL)
	{
		/* restore the previous saved status ... */
		
		/* set the nodes_displayed */
		priv->nodes_displayed = fsstatus->nodes_displayed;
		
		/* ... the waiting_for ... */
		priv->waiting_for = fsstatus->waiting_for;
	
		/* ... the pending symbols_id to be inserted ... */
		priv->symbols_inserted_ids = fsstatus->symbols_inserted_ids;

		/* and last but not the least the store */
		store = fsstatus->store;		

		/* with this set there's no need to re-retrieve the symbols from db,
		 * speeding up the things.
		 */
		/*DEBUG_PRINT ("%s", "symbol_db_view_locals_update_list (): "
					 "setting gtk_tree_view_set_model to the saved one");*/
		gtk_tree_view_set_model (GTK_TREE_VIEW (dbvl), GTK_TREE_MODEL (store));
		
		
		/* check if we left some ids on the queue. In case restart the idle_function */
		if (g_queue_get_length (priv->symbols_inserted_ids) > 0)
		{
			TraverseData *tdata;
			
			tdata = g_new0 (TraverseData, 1);
			tdata->dbvl = dbvl;
			tdata->data = dbe;
			
			priv->insertion_idle_handler = g_idle_add_full (G_PRIORITY_LOW, 
						 (GSourceFunc) consume_symbols_inserted_queue_idle,
						 (gpointer) tdata,
						 (GDestroyNotify) consume_symbols_inserted_queue_idle_destroy);			
		}

		/* fine, but some symbol-remove signals can have been left. Check if they
		 * can be removed 
		 */
		GList *removed_list;
		TraverseData *tdata;

		tdata = g_new0 (TraverseData, 1);
		tdata->dbvl = dbvl;

		g_tree_foreach (priv->nodes_not_yet_removed, 
		    traverse_check_for_unremoved_symbols, tdata);

		/* the result */
		removed_list = tdata->data;
		
		/* have we removed something? We'll know that checking the list */
		if (removed_list != NULL)
		{
			GList *node = removed_list;
			while (node != NULL)
			{
				g_tree_remove (priv->nodes_not_yet_removed, node->data);

				node = node->next;
			}			
		}
		
		g_list_free (removed_list);
		g_free (tdata);	
	}
	else 
	{	
		priv->nodes_displayed = g_tree_new_full ((GCompareDataFunc)&symbol_db_gtree_compare_func, 
										 NULL,
										 NULL,
										 (GDestroyNotify)&gtk_tree_row_reference_free);		

		priv->waiting_for = g_tree_new_full ((GCompareDataFunc)&symbol_db_gtree_compare_func, 
										 NULL,
										 NULL,
										 NULL);
		
		priv->symbols_inserted_ids = g_queue_new ();

		/*DEBUG_PRINT ("%s", "symbol_db_view_locals_update_list (): creating new store"); */
		store = sdb_view_locals_create_new_store ();
		gtk_tree_view_set_model (GTK_TREE_VIEW (dbvl), GTK_TREE_MODEL (store));
		
		/* Removes all rows from tree_store */
		gtk_tree_store_clear (store);

		iterator = symbol_db_engine_get_file_symbols (dbe, filepath, 
													  	SYMINFO_SIMPLE |
												  		SYMINFO_ACCESS |
														SYMINFO_KIND);		
		
		if (iterator != NULL)
		{
			do {
				gint curr_symbol_id;
				SymbolDBEngineIteratorNode *iter_node;

				iter_node = SYMBOL_DB_ENGINE_ITERATOR_NODE (iterator);
			
				curr_symbol_id = symbol_db_engine_iterator_node_get_symbol_id (iter_node);

				/* we can just call the symbol inserted function. It'll take care of
			 	* building the tree and populating it
			 	*/
				on_symbol_inserted (dbe, curr_symbol_id, (gpointer)dbvl);
			} while (symbol_db_engine_iterator_move_next (iterator) == TRUE);
		
			g_object_unref (iterator);
		}

		/* ok, there may be some symbols left on the waiting_for_list...
 	 	 * launch the callback function by hand, flushing the list it in case 
		 * The 0 stays for an unused process_id
		 */		
		on_scan_end (dbe, 0, dbvl);		
	}
	
	/* only gtk 2.12 ...
	 * gtk_tree_view_set_show_expanders (GTK_TREE_VIEW (dbvl)); */
	
	gtk_tree_view_expand_all (GTK_TREE_VIEW (dbvl));	
}
static gboolean
backup_job (GIOSchedulerJob *job,
            GCancellable    *cancellable,
            gpointer         user_data)
{
	BackupInfo *info = user_data;

	const gchar *src_path;
	GFile *parent_file, *temp_file;
	gchar *temp_path;

	sqlite3 *src_db = NULL;
	sqlite3 *temp_db = NULL;
	sqlite3_backup *backup = NULL;

	src_path = tracker_db_manager_get_file (TRACKER_DB_METADATA);
	parent_file = g_file_get_parent (info->destination);
	temp_file = g_file_get_child (parent_file, TRACKER_DB_BACKUP_META_FILENAME_T);
	g_file_delete (temp_file, NULL, NULL);
	temp_path = g_file_get_path (temp_file);

	if (sqlite3_open_v2 (src_path, &src_db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) {
		g_set_error (&info->error, TRACKER_DB_BACKUP_ERROR, TRACKER_DB_BACKUP_ERROR_UNKNOWN,
		             "Could not open sqlite3 database:'%s'", src_path);
	}

	if (!info->error && sqlite3_open (temp_path, &temp_db) != SQLITE_OK) {
		g_set_error (&info->error, TRACKER_DB_BACKUP_ERROR, TRACKER_DB_BACKUP_ERROR_UNKNOWN,
		             "Could not open sqlite3 database:'%s'", temp_path);
	}

	if (!info->error) {
		backup = sqlite3_backup_init (temp_db, "main", src_db, "main");

		if (!backup) {
			g_set_error (&info->error, TRACKER_DB_BACKUP_ERROR, TRACKER_DB_BACKUP_ERROR_UNKNOWN,
				     "Unable to initialize sqlite3 backup from '%s' to '%s'", src_path, temp_path);
		}
	}

	if (!info->error && sqlite3_backup_step (backup, -1) != SQLITE_DONE) {
		g_set_error (&info->error, TRACKER_DB_BACKUP_ERROR, TRACKER_DB_BACKUP_ERROR_UNKNOWN,
		             "Unable to complete sqlite3 backup");
	}

	if (backup) {
		if (sqlite3_backup_finish (backup) != SQLITE_OK) {
			if (info->error) {
				/* sqlite3_backup_finish can provide more detailed error message */
				g_clear_error (&info->error);
			}
			g_set_error (&info->error,
			             TRACKER_DB_BACKUP_ERROR,
			             TRACKER_DB_BACKUP_ERROR_UNKNOWN,
				     "Unable to finish sqlite3 backup: %s",
				     sqlite3_errmsg (temp_db));
		}
		backup = NULL;
	}

	if (temp_db) {
		sqlite3_close (temp_db);
		temp_db = NULL;
	}

	if (src_db) {
		sqlite3_close (src_db);
		src_db = NULL;
	}

	if (!info->error) {
		g_file_move (temp_file, info->destination,
		             G_FILE_COPY_OVERWRITE,
		             NULL, NULL, NULL,
		             &info->error);
	}

	g_free (temp_path);
	g_object_unref (temp_file);
	g_object_unref (parent_file);

	g_idle_add_full (G_PRIORITY_DEFAULT, perform_callback, info,
	                 backup_info_free);

	return FALSE;
}
Exemple #11
0
Extension *PluginManager::acquireExtension(const char *extensionId)
{
    std::string pluginId(extensionId, strrchr(extensionId, '/') - extensionId);
    PluginInfo *info = m_registry.find(pluginId.c_str())->second;

    // Retrieve the plugin if it is active, fetch the plugin from the cache if
    // it is cached or create it.
    Plugin *plugin;
    bool newPlugin;
    Table::const_iterator it = m_table.find(pluginId.c_str());
    if (it != m_table.end())
    {
        plugin = it->second;
        if (plugin->cached())
        {
            plugin->removeFromCache(m_lruCachedPlugin, m_mruCachedPlugin);
            --m_nCachedPlugins;
            newPlugin = true;
        }
        else
            newPlugin = false;
    }
    else
    {
        char *module = g_module_build_path(m_modulesDirName.c_str(),
                                           info->module.c_str());
        std::string error;
        plugin = Plugin::activate(*this, pluginId.c_str(), module, error);
        g_free(module);
        if (!plugin)
        {
            GtkWidget *dialog;
            dialog = gtk_message_dialog_new(
                NULL,
                GTK_DIALOG_DESTROY_WITH_PARENT,
                GTK_MESSAGE_ERROR,
                GTK_BUTTONS_CLOSE,
                _("Samoyed failed to activate plugin \"%s\"."),
                pluginId.c_str());
            if (!error.empty())
                Samoyed::gtkMessageDialogAddDetails(
                    dialog,
                    _("%s"),
                    error.c_str());
            gtk_dialog_set_default_response(GTK_DIALOG(dialog),
                                            GTK_RESPONSE_CLOSE);
            gtk_dialog_run(GTK_DIALOG(dialog));
            gtk_widget_destroy(dialog);
            return NULL;
        }
        m_table.insert(std::make_pair(plugin->id(), plugin));
        newPlugin = true;
    }

    // Acquire the extension from the plugin.
    Extension *ext = plugin->acquireExtension(extensionId);
    if (!ext && newPlugin)
    {
        plugin->addToCache(m_lruCachedPlugin, m_mruCachedPlugin);
        if (++m_nCachedPlugins > m_cacheSize)
        {
            Plugin *p = m_lruCachedPlugin;
            m_table.erase(p->id());
            p->removeFromCache(m_lruCachedPlugin, m_mruCachedPlugin);
            --m_nCachedPlugins;
            // Defer destroying the plugin.
            g_idle_add_full(G_PRIORITY_LOW,
                            destroyPluginDeferred,
                            new std::pair<PluginManager *, Plugin *>(this, p),
                            NULL);
        }
    }
    return ext;
}
static guint
ToolsCorePoolSubmit(ToolsAppCtx *ctx,
                    ToolsCorePoolCb cb,
                    gpointer data,
                    GDestroyNotify dtor)
{
   guint id = 0;
   WorkerTask *task = g_malloc0(sizeof *task);

   task->srcId = 0;
   task->cb = cb;
   task->data = data;
   task->dtor = dtor;

   g_mutex_lock(gState.lock);

   if (!gState.active) {
      g_free(task);
      goto exit;
   }

   /*
    * XXX: a reeeeeeeeeally long running task could cause clashes (e.g., reusing
    * the same task ID after the counter wraps). That shouldn't really happen in
    * practice (and is an abuse of the thread pool, and could cause issues if
    * someone sets the pool size to 0 or 1), but it might be good to have more
    * fail-safe code here.
    */
   if (gState.nextWorkId + 1 == UINT_MAX) {
      task->id = UINT_MAX;
      gState.nextWorkId = 0;
   } else {
      task->id = ++gState.nextWorkId;
   }

   id = task->id;

   /*
    * We always add the task to the queue, even in single threaded mode, so
    * that it can be canceled. In single threaded mode, it's unlikely someone
    * will be able to cancel it before it runs, but they can try.
    */
   g_queue_push_head(gState.workQueue, task);

   if (gState.pool != NULL) {
      GError *err = NULL;

      /* The client data pointer is bogus, just to avoid passing NULL. */
      g_thread_pool_push(gState.pool, &gState, &err);
      if (err == NULL) {
         goto exit;
      } else {
         g_warning("error sending work request, executing in service thread: %s",
                   err->message);
         g_clear_error(&err);
      }
   }

   /* Run the task in the service's thread. */
   task->srcId = g_idle_add_full(G_PRIORITY_DEFAULT_IDLE,
                                 ToolsCorePoolDoWork,
                                 task,
                                 ToolsCorePoolDestroyTask);

exit:
   g_mutex_unlock(gState.lock);
   return id;
}
Exemple #13
0
GtkWidget *
create_applications_menu (const char *menu_file,
			  const char *menu_path,
			  gboolean    always_show_image)
{
	GMenuTree *tree;
	GtkWidget *menu;
	guint      idle_id;
	GError *error = NULL;

	menu = create_empty_menu ();

	if (always_show_image)
		g_object_set_data (G_OBJECT (menu),
				   "panel-menu-force-icon-for-categories",
				   GINT_TO_POINTER (TRUE));

	tree = gmenu_tree_new (menu_file, GMENU_TREE_FLAGS_SORT_DISPLAY_NAME);

	if (!gmenu_tree_load_sync (tree, &error)) {
		g_warning ("Failed to load applications: %s", error->message);
		g_clear_error (&error);
		return menu;
	}

	g_object_set_data_full (G_OBJECT (menu),
				"panel-menu-tree",
				g_object_ref (tree),
				(GDestroyNotify) g_object_unref);

	g_object_set_data_full (G_OBJECT (menu),
				"panel-menu-tree-path",
				g_strdup (menu_path ? menu_path : "/"),
				(GDestroyNotify) g_free);
	
	g_object_set_data (G_OBJECT (menu),
			   "panel-menu-needs-loading",
			   GUINT_TO_POINTER (TRUE));

	g_signal_connect (menu, "show",
			  G_CALLBACK (submenu_to_display), NULL);

	idle_id = g_idle_add_full (G_PRIORITY_LOW,
				   submenu_to_display_in_idle,
				   menu,
				   NULL);
	g_object_set_data_full (G_OBJECT (menu),
				"panel-menu-idle-id",
				GUINT_TO_POINTER (idle_id),
				remove_submenu_to_display_idle);

	g_signal_connect (menu, "button_press_event",
			  G_CALLBACK (menu_dummy_button_press_event), NULL);

	g_signal_connect (tree, "changed", G_CALLBACK (handle_gmenu_tree_changed), menu);
	g_signal_connect (menu, "destroy", G_CALLBACK (remove_gmenu_tree_monitor), tree);

	g_object_unref (tree);

	return menu;
}
Exemple #14
0
void
restraint_append_message (SoupSession *session,
                          SoupMessage *msg,
                          gpointer msg_data,
                          MessageFinishCallback finish_callback,
                          GCancellable *cancellable,
                          gpointer user_data)
{
    ClientData *client_data = (ClientData *) msg_data;
    time_t result;
    result = time(NULL);
    static time_t transaction_id = 0;
    // calculate the transaction id. base it off of epoch
    // incase the host reboots we shouldn't collide
    if (transaction_id == 0) {
        transaction_id = result;
    }
    MessageData *message_data;
    message_data = g_slice_new0 (MessageData);
    message_data->msg = msg;
    message_data->user_data = user_data;
    message_data->finish_callback = finish_callback;

    if (client_data != NULL) {
        GString *body = g_string_new("");
        SoupURI *uri = soup_message_get_uri (msg);
        soup_message_headers_foreach (msg->request_headers, append_header,
                                      body);
        // if we are doing a POST transaction
        // increment transaction_id and add it to headers
        // populate Location header in msg->reponse_headers
        const gchar *path = soup_uri_get_path (uri);
        if (g_strcmp0 (msg->method, "POST") == 0) {
            g_string_append_printf (body,
                                    "transaction-id: %jd\n", (intmax_t) transaction_id);
            gchar *location_url = g_strdup_printf ("%s%jd", path, (intmax_t) transaction_id);
            soup_message_headers_append (msg->response_headers, "Location", location_url);
            g_free (location_url);
            transaction_id++;
        }
        soup_message_set_status (msg, SOUP_STATUS_OK);
        g_string_append_printf (body,
                                "rstrnt-path: %s\n"
                                "rstrnt-method: %s\n"
                                "Content-Length: %d\r\n\r\n",
                                path,
                                msg->method,
                                (guint) msg->request_body->length);
        SoupBuffer *request = soup_message_body_flatten (msg->request_body);
        body = g_string_append_len (body, request->data,
                                          request->length);
        g_string_append_printf (body,
                           "\r\n--cut-here\n");

        soup_buffer_free (request);

        soup_message_body_append (client_data->client_msg->response_body,
                                  SOUP_MEMORY_TAKE,
                                  body->str, body->len);

        g_string_free (body, FALSE);

        soup_server_unpause_message (client_data->server, client_data->client_msg);
    }

    if (finish_callback) {
        g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
                         message_finish,
                         message_data,
                         message_destroy);
    } else {
        g_object_unref (msg);
        message_destroy (message_data);
    }
}
static gboolean
convert_metadata_file (const gchar *filename)
{
	ConvertData *data;
	xmlDocPtr doc;
	xmlNodePtr cur;

	if (!g_file_test (filename, G_FILE_TEST_EXISTS))
		return FALSE;

	doc = xmlParseFile (filename);
	if (!doc) {
		g_printerr ("Error loading metadata file %s\n", filename);
		return FALSE;
	}

	cur = xmlDocGetRootElement (doc);
	if (!cur) {
		g_printerr ("Metadata file %s is empty\n", filename);
		xmlFreeDoc (doc);
		return TRUE;
	}

	if (xmlStrcmp (cur->name, (const xmlChar *) "metadata")) {
		g_printerr ("File %s is not a valid atril metadata file\n", filename);
		xmlFreeDoc (doc);
		return FALSE;
	}

	data = g_new0 (ConvertData, 1);
	data->doc = doc;

	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
		xmlChar *uri;
		DocItem *item;

		if (xmlStrcmp (cur->name, (const xmlChar *)"document") != 0)
			continue;

		uri = xmlGetProp (cur, (const xmlChar *)"uri");
		if (!uri)
			continue;

		item = g_new (DocItem, 1);
		item->uri = uri;
		item->cur = cur;
		data->items = g_list_prepend (data->items, item);
	}

	if (!data->items) {
		xmlFreeDoc (data->doc);
		g_free (data);

		return TRUE;
	}

	show_progress_dialog (data);

	data->current = data->items;
	g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
			 (GSourceFunc)convert_file,
			 data,
			 (GDestroyNotify)convert_finish);

	return TRUE;
}
guint 
g_idle_add (GSourceFunc    function,
	    gpointer       data)
{
  return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
}
static void
_controller_changed_cb (GController          *controller,
                        GControllerAction     action,
                        GControllerReference *ref,
                        MexQueueModel        *model)
{
  MexQueueModelPrivate *priv = model->priv;
  guint index_;
  MexContent *content;

  /*
   * MexGenericContent only does single items at a time so we have an
   * assumption here that our reference only contains a single item
   */

  if (action == G_CONTROLLER_ADD || action == G_CONTROLLER_REMOVE)
    {
      index_ = g_controller_reference_get_index_uint (ref, 0);
      content = mex_model_get_content (MEX_MODEL (model), index_);
    }

  if (action == G_CONTROLLER_ADD)
    {
      mex_content_set_metadata (content,
                                MEX_CONTENT_METADATA_QUEUED,
                                "yes");
    }
  else if (action == G_CONTROLLER_REMOVE)
    {
      mex_content_set_metadata (content,
                                MEX_CONTENT_METADATA_QUEUED,
                                NULL);
    }
  else if (action == G_CONTROLLER_CLEAR)
    {
      gint model_length;
      model_length = mex_model_get_length (MEX_MODEL (model));

      for (index_=0; index_ < model_length; index_++)
        {
          content = mex_model_get_content (MEX_MODEL (model), index_);

          mex_content_set_metadata (content,
                                    MEX_CONTENT_METADATA_QUEUED,
                                    NULL);
        }
    }
  else
    {
      GEnumClass *enum_class;

      enum_class = g_type_class_ref (G_TYPE_CONTROLLER_ACTION);

      g_critical (G_STRLOC ": Unexpected GController action: %s",
                  (g_enum_get_value (enum_class,
                                     action))->value_name);

      g_type_class_unref (enum_class);
    }

  if (priv->serialise_idle_id)
    return;

  /* Need to use a high priority idle here since we want to try and write
   * *after* the content has been removed from the model
   */
  priv->serialise_idle_id = g_idle_add_full (G_PRIORITY_DEFAULT,
                                             (GSourceFunc)_serialise_idle_cb,
                                             g_object_ref (model),
                                             g_object_unref);
}
Exemple #18
0
void cb_notify_main_thread(sp_session* session) {
    g_idle_add_full(G_PRIORITY_DEFAULT, session_libspotify_event, NULL, NULL);
}
Exemple #19
0
void cb_end_of_track(sp_session* session) {
    g_debug("End of track.");
    g_idle_add_full(G_PRIORITY_DEFAULT, session_next_track_event, NULL, NULL);
}
Exemple #20
0
gpointer thumbnail_loader_thread( VFSAsyncTask* task, VFSThumbnailLoader* loader )
{
    ThumbnailRequest* req;
    int i;
    gboolean load_big, need_update;

    while( G_LIKELY( ! vfs_async_task_is_cancelled(task) ))
    {
        vfs_async_task_lock( task );
        req = (ThumbnailRequest*)g_queue_pop_head( loader->queue );
        vfs_async_task_unlock( task );
        if( G_UNLIKELY( ! req ) )
            break;
        /* g_debug("pop: %s", req->file->name); */

        /* Only we have the reference. That means, no body is using the file */
        if( req->file->n_ref == 1 )
        {
            thumbnail_request_free( req );
            continue;
        }

        need_update = FALSE;
        for ( i = 0; i < 2; ++i )
        {
            if ( 0 == req->n_requests[ i ] )
                continue;
            load_big = ( i == LOAD_BIG_THUMBNAIL );
            if ( ! vfs_file_info_is_thumbnail_loaded( req->file, load_big ) )
            {
                char* full_path;
                full_path = g_build_filename( loader->dir->path,
                                              vfs_file_info_get_name( req->file ),
                                              NULL );
                vfs_file_info_load_thumbnail( req->file, full_path, load_big );
                g_free( full_path );
                /*  Slow down for displaying. */
                g_usleep(G_USEC_PER_SEC/1000);

                /* g_debug( "thumbnail loaded: %s", req->file ); */
            }
            need_update = TRUE;
        }

        if( ! vfs_async_task_is_cancelled(task) && need_update )
        {
            vfs_async_task_lock( task );
            g_queue_push_tail( loader->update_queue, vfs_file_info_ref(req->file) );
            if( 0 == loader->idle_handler)
                loader->idle_handler = g_idle_add_full( G_PRIORITY_LOW, (GSourceFunc) on_thumbnail_idle, loader, NULL );
            vfs_async_task_unlock( task );
        }
        /* g_debug( "NEED_UPDATE: %d", need_update ); */
        thumbnail_request_free( req );
    }

    if( vfs_async_task_is_cancelled(task) )
    {
        /* g_debug( "THREAD CANCELLED!!!" ); */
        vfs_async_task_lock( task );
        if( loader->idle_handler)
        {
            g_source_remove( loader->idle_handler );
            loader->idle_handler = 0;
        }
        vfs_async_task_unlock( task );
    }
    else
    {
        if( 0 == loader->idle_handler)
        {
            /* g_debug( "ADD IDLE HANDLER BEFORE THREAD ENDING" ); */
            loader->idle_handler = g_idle_add_full( G_PRIORITY_LOW, (GSourceFunc) on_thumbnail_idle, loader, NULL );
        }
    }
    /* g_debug("THREAD ENDED!");  */
    return NULL;
}
Exemple #21
0
static void
nm_ip6_device_sync_from_netlink (NMIP6Device *device, gboolean config_changed)
{
	NMIP6Manager *manager = device->manager;
	NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
	struct rtnl_addr *rtnladdr;
	struct nl_addr *nladdr;
	struct in6_addr *addr;
	CallbackInfo *info;
	guint dhcp_opts = IP6_DHCP_OPT_NONE;
	gboolean found_linklocal = FALSE, found_other = FALSE;

	nm_log_dbg (LOGD_IP6, "(%s): syncing with netlink (ra_flags 0x%X) (state/target '%s'/'%s')",
	            device->iface, device->ra_flags,
	            state_to_string (device->state),
	            state_to_string (device->target_state));

	/* Look for any IPv6 addresses the kernel may have set for the device */
	for (rtnladdr = (struct rtnl_addr *) nl_cache_get_first (priv->addr_cache);
		 rtnladdr;
		 rtnladdr = (struct rtnl_addr *) nl_cache_get_next ((struct nl_object *) rtnladdr)) {
		char buf[INET6_ADDRSTRLEN];

		if (rtnl_addr_get_ifindex (rtnladdr) != device->ifindex)
			continue;

		nladdr = rtnl_addr_get_local (rtnladdr);
		if (!nladdr || nl_addr_get_family (nladdr) != AF_INET6)
			continue;

		addr = nl_addr_get_binary_addr (nladdr);

		if (inet_ntop (AF_INET6, addr, buf, INET6_ADDRSTRLEN) > 0) {
			nm_log_dbg (LOGD_IP6, "(%s): netlink address: %s",
			            device->iface, buf);
		}

		if (IN6_IS_ADDR_LINKLOCAL (addr)) {
			if (device->state == NM_IP6_DEVICE_UNCONFIGURED)
				device->state = NM_IP6_DEVICE_GOT_LINK_LOCAL;
			found_linklocal = TRUE;
		} else {
			if (device->state < NM_IP6_DEVICE_GOT_ADDRESS)
				device->state = NM_IP6_DEVICE_GOT_ADDRESS;
			found_other = TRUE;
		}
	}

	/* There might be a LL address hanging around on the interface from
	 * before in the initial run, but if it goes away later, make sure we
	 * regress from GOT_LINK_LOCAL back to UNCONFIGURED.
	 */
	if ((device->state == NM_IP6_DEVICE_GOT_LINK_LOCAL) && !found_linklocal)
		device->state = NM_IP6_DEVICE_UNCONFIGURED;

	nm_log_dbg (LOGD_IP6, "(%s): addresses synced (state %s)",
	            device->iface, state_to_string (device->state));

	/* We only care about router advertisements if we want a real IPv6 address */
	if (   (device->target_state == NM_IP6_DEVICE_GOT_ADDRESS)
	    && (device->ra_flags & IF_RA_RCVD)) {

		if (device->state < NM_IP6_DEVICE_GOT_ROUTER_ADVERTISEMENT)
			device->state = NM_IP6_DEVICE_GOT_ROUTER_ADVERTISEMENT;

		if (device->ra_flags & IF_RA_MANAGED) {
			dhcp_opts = IP6_DHCP_OPT_MANAGED;
			nm_log_dbg (LOGD_IP6, "router advertisement deferred to DHCPv6");
		} else if (device->ra_flags & IF_RA_OTHERCONF) {
			dhcp_opts = IP6_DHCP_OPT_OTHERCONF;
			nm_log_dbg (LOGD_IP6, "router advertisement requests parallel DHCPv6");
		}
	}

	if (!device->addrconf_complete) {
		/* Managed mode (ie DHCP only) short-circuits automatic addrconf, so
		 * we don't bother waiting for the device's target state to be reached
		 * when the RA requests managed mode.
		 */
		if (   (device->state >= device->target_state)
		    || (dhcp_opts == IP6_DHCP_OPT_MANAGED)) {
			/* device->finish_addrconf_id may currently be a timeout
			 * rather than an idle, so we remove the existing source.
			 */
			if (device->finish_addrconf_id)
				g_source_remove (device->finish_addrconf_id);

			nm_log_dbg (LOGD_IP6, "(%s): reached target state or Managed-mode requested (state '%s') (dhcp opts 0x%X)",
			            device->iface, state_to_string (device->state),
			            dhcp_opts);

			info = callback_info_new (device, dhcp_opts, TRUE);
			device->finish_addrconf_id = g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
			                                              finish_addrconf,
			                                              info,
			                                              (GDestroyNotify) g_free);
		}
	} else if (config_changed) {
		if (!device->config_changed_id) {
			gboolean success = TRUE;

			/* If for some reason an RA-provided address disappeared, we need
			 * to make sure we fail the connection as it's no longer valid.
			 */
			if (   (device->state == NM_IP6_DEVICE_GOT_ADDRESS)
			    && (device->target_state == NM_IP6_DEVICE_GOT_ADDRESS)
			    && !found_other) {
				nm_log_dbg (LOGD_IP6, "(%s): RA-provided address no longer valid",
				            device->iface);
				success = FALSE;
			}

			info = callback_info_new (device, dhcp_opts, success);
			device->config_changed_id = g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
			                                             emit_config_changed,
			                                             info,
			                                             (GDestroyNotify) g_free);
		}
	}
}
Exemple #22
0
/* We double buffer the image.  It looks nice and it enables
 * grabbing the graph with the pointer and translating it.
 * We draw on our own larger surface and then copy part of that
 * to the gdk surface.
 *
 * We assume that this function is drawing to an exposed/showing
 * drawing area, so the status update will reflect the current
 * exposed/showing drawing area. */
void qp_graph_draw(struct qp_graph *gr, cairo_t *gdk_cr)
{
  GtkAllocation allocation;

  if(gr->waiting_to_resize_draw && !gr->qp->shape)
  {
    //WARN("gr=%p gr->name=\"%s\" gr->ref_count=%d\n", gr, gr->name, gr->ref_count);
    cairo_set_source_rgba(gdk_cr, gr->background_color.r,
      gr->background_color.g, gr->background_color.b,
      gr->background_color.a);

    cairo_paint(gdk_cr);

    g_idle_add_full(G_PRIORITY_LOW, idle_callback, gr, NULL);
    /* fight qp_graph_destroy() race condition with flag */
    ++gr->ref_count;
    /* We draw after the other widgets are drawn, in case drawing
     * takes a long time.  This waiting also gives a chance
     * for the watch cursor to show.  But that seems to only
     * show if the window had focus at the right time. */
    return;
  }

  gtk_widget_get_allocation(gr->drawing_area, &allocation);
  
  if(gr->pixbuf_needs_draw)
  {
    cairo_t *db_cr; /* double buffer cr */

    db_cr = cairo_create(gr->pixbuf_surface);
    graph_draw(gr, db_cr, gr->pixbuf_x, gr->pixbuf_y,
                  gr->pixbuf_width, gr->pixbuf_height);
    cairo_destroy(db_cr);
    // debuging
    //cairo_surface_write_to_png(gr->pixbuf_surface, "x.png");
    qp_win_set_status(gr->qp);
  }

  /* the GTK cairo_t *gdk_cr has no alpha bits so all the
   * alpha drawn to it will be smushed. */
  //WARN("content=0x%lx\n", (unsigned long)cairo_get_target(gdk_cr));


  if(!gr->qp->shape)
  {
    /* Not using the shape X11 extension */

    /* This is where we go from the back buffer to the drawing area */
    draw_from_pixbuf(gdk_cr, gr, allocation.width, allocation.height);

    if(gr->draw_zoom_box == 1)
      draw_zoom_box(gdk_cr, gr);
    if(gr->draw_value_pick)
      draw_value_pick_line(gdk_cr, gr, allocation.width, allocation.height);


    if(gr->pixbuf_needs_draw)
    {
      gdk_window_set_cursor(gtk_widget_get_window(gr->qp->window), NULL);
      gr->pixbuf_needs_draw = 0;
      // gr->qp->wait_warning_showing = 0;
    }
  }
  else
  {
    /* Use the X11 shape extension */


    /* TODO: This is a resource pig.  Fix it. */

    cairo_region_t *reg_draw_area, *window_region;
    /* empty flag */ 
    int empty;
    cairo_surface_t *mask_surface;
    GtkAllocation all;

    /* Make sure the surface is up to date */
    //cairo_surface_flush(gr->pixbuf_surface);

    /* make a sub surface that is the size of the graph drawing area */
    mask_surface = cairo_surface_create_for_rectangle(gr->pixbuf_surface,
        INT(gr->pixbuf_x+gr->grab_x),
        INT(gr->pixbuf_y+gr->grab_y),
        allocation.width, allocation.height);
    
    reg_draw_area = get_cairo_region_create_from_surface(gr,
        mask_surface, allocation.width, allocation.height);

    cairo_surface_destroy(mask_surface);

    cairo_region_translate(reg_draw_area, allocation.x, allocation.y);

    gtk_widget_get_allocation(gr->qp->window, &all);
    all.x = all.y = 0;

    window_region = cairo_region_create_rectangle(&all);

    cairo_region_subtract_rectangle(window_region, &allocation);

    empty = cairo_region_is_empty(reg_draw_area);

    if(!empty)  
      cairo_region_union(window_region, reg_draw_area);

    cairo_region_destroy(reg_draw_area);

    /* window_region is a region with a hole in it the
     * size of the drawing area with the graph and grid added back. */


    if(gr->draw_zoom_box && !empty)
    {
      cairo_rectangle_int_t rec;
      rec.x = allocation.x + gr->z_x;
      rec.y = allocation.y + gr->z_y;
      rec.width = gr->z_w;
      rec.height = gr->z_h;
      /* regions do not like negitive values or
       * maybe shapes do not like negitive values
       * in any case we keep width and height
       * positive */
      if(rec.width < 0)
      {
        rec.width *= -1;
        rec.x -= rec.width;
      }
      if(rec.height < 0)
      {
        rec.height *= -1;
        rec.y -= rec.height;
      }
        
      cairo_region_union_rectangle(window_region, &rec);
      /* now we have the zoom box added to window_region */
    }


    /* This is where we go from the back buffer to the drawing area */
    draw_from_pixbuf(gdk_cr, gr, allocation.width, allocation.height);
    if(gr->draw_zoom_box)
      draw_zoom_box(gdk_cr, gr);
    if(gr->draw_value_pick)
      draw_value_pick_line(gdk_cr, gr, allocation.width, allocation.height);


    if(empty)
    {
      /* we have nothing to make a shape with */
      if(gr->qp->last_shape_region)
      {
        cairo_region_destroy(gr->qp->last_shape_region);
        gr->qp->last_shape_region = NULL;
      }
      cairo_region_destroy(window_region);
      /* remove the old shape region */
      gtk_widget_shape_combine_region(gr->qp->window, NULL);
    }
    else if(!gr->qp->last_shape_region ||
        !cairo_region_equal(gr->qp->last_shape_region, window_region))
    {
      // DEBUG("creating new shape region\n");
      
      /* We need to undo the old shape first */
      gtk_widget_shape_combine_region(gr->qp->window, NULL);

      gtk_widget_shape_combine_region(gr->qp->window, window_region);

      if(gr->qp->last_shape_region)
        cairo_region_destroy(gr->qp->last_shape_region);

      gr->qp->last_shape_region = window_region;
    }
    else
      cairo_region_destroy(window_region);


    gr->pixbuf_needs_draw = 0;

    gdk_window_set_cursor(gtk_widget_get_window(gr->qp->window), NULL);
    // debuging
    //cairo_surface_write_to_png(cairo_get_target(gdk_cr), "y.png");
  }

  if(gr->qp->update_graph_detail && gr->qp->graph_detail)
  {
    gr->qp->update_graph_detail = 0;
    /* make the graph configure window show stuff about this graph */
    qp_win_graph_detail_init(gr->qp);
  }
}
Exemple #23
0
/****f* callback/create
 * AUTHOR
 *	PGB
 * SOURCE
 */
static int create ( Tcl_Interp *interp, int objc, Tcl_Obj * const objv[] )
{
	GnoclOption options[] =
	{
		{ "-interval", GNOCL_OBJ, NULL },    /* 0 */
		{ "-priority", GNOCL_INT, NULL },    /* 1 */
		{ NULL }
	};
	const int intervalIdx = 0;
	const int priorityIdx = 1;

	int interval = -1;
	int priority = 0;
	int id;
	GnoclCommandData *cs;

	if ( objc < 3 )
	{
		Tcl_WrongNumArgs ( interp, 2, objv, "script" );
		return TCL_ERROR;
	}

	if ( gnoclParseOptions ( interp, objc - 2, objv + 2, options ) != TCL_OK )
		goto errorExit;

	if ( options[priorityIdx].status == GNOCL_STATUS_CHANGED )
		priority = options[priorityIdx].val.i;

	/* TODO? test priority range? */

	if ( options[intervalIdx].status == GNOCL_STATUS_CHANGED )
	{
		Tcl_Obj * const obj = options[intervalIdx].val.obj;

		if ( Tcl_GetIntFromObj ( NULL, obj, &interval ) != TCL_OK )
		{
			if ( strcmp ( Tcl_GetString ( obj ), "idle" ) != 0 )
			{
				Tcl_AppendResult ( interp,
								   "Expected integer or \"idle\", but got \"",
								   Tcl_GetString ( obj ), "\"", NULL );
				goto errorExit;
			}
		}

		else if ( interval <= 0 )
		{
			Tcl_SetResult ( interp, "interval must be greater zero.",
							TCL_STATIC );
			goto errorExit;
		}

	}

	gnoclClearOptions ( options );

	cs = g_new ( GnoclCommandData, 1 );
	cs->command = g_strdup ( Tcl_GetString ( objv[2] ) );
	cs->interp = interp;


	if ( interval <= 0 ) /* idle */
	{
		id = g_idle_add_full ( G_PRIORITY_DEFAULT_IDLE - priority,
							   doCommand, cs, destroyCmd );
	}

	else
	{
		id = g_timeout_add_full ( G_PRIORITY_DEFAULT_IDLE - priority, interval,
								  doCommand, cs, destroyCmd );
	}

	Tcl_SetObjResult ( interp, Tcl_NewIntObj ( id ) );

	return TCL_OK;


errorExit:
	gnoclClearOptions ( options );

	return TCL_ERROR;
}
void
nautilus_create_thumbnail (NautilusFile *file)
{
	time_t file_mtime = 0;
	NautilusThumbnailInfo *info;
	NautilusThumbnailInfo *existing_info;
	GList *existing, *node;

	nautilus_file_set_is_thumbnailing (file, TRUE);

	info = g_new0 (NautilusThumbnailInfo, 1);
	info->image_uri = nautilus_file_get_uri (file);
	info->mime_type = nautilus_file_get_mime_type (file);
	
	/* Hopefully the NautilusFile will already have the image file mtime,
	   so we can just use that. Otherwise we have to get it ourselves. */
	if (file->details->got_file_info &&
	    file->details->file_info_is_up_to_date &&
	    file->details->mtime != 0) {
		file_mtime = file->details->mtime;
	} else {
		get_file_mtime (info->image_uri, &file_mtime);
	}
	
	info->original_file_mtime = file_mtime;


#ifdef DEBUG_THUMBNAILS
	g_message ("(Main Thread) Locking mutex\n");
#endif
	pthread_mutex_lock (&thumbnails_mutex);
	
	/*********************************
	 * MUTEX LOCKED
	 *********************************/

	if (thumbnails_to_make_hash == NULL) {
		thumbnails_to_make_hash = g_hash_table_new (g_str_hash,
							    g_str_equal);
	}

	/* Check if it is already in the list of thumbnails to make. */
	existing = g_hash_table_lookup (thumbnails_to_make_hash, info->image_uri);
	if (existing == NULL) {
		/* Add the thumbnail to the list. */
#ifdef DEBUG_THUMBNAILS
		g_message ("(Main Thread) Adding thumbnail: %s\n",
			   info->image_uri);
#endif
		g_queue_push_tail ((GQueue *)&thumbnails_to_make, info);
		node = g_queue_peek_tail_link ((GQueue *)&thumbnails_to_make);
		g_hash_table_insert (thumbnails_to_make_hash,
				     info->image_uri,
				     node);
		/* If the thumbnail thread isn't running, and we haven't
		   scheduled an idle function to start it up, do that now.
		   We don't want to start it until all the other work is done,
		   so the GUI will be updated as quickly as possible.*/
		if (thumbnail_thread_is_running == FALSE &&
		    thumbnail_thread_starter_id == 0) {
			thumbnail_thread_starter_id = g_idle_add_full (G_PRIORITY_LOW, thumbnail_thread_starter_cb, NULL, NULL);
		}
	} else {
#ifdef DEBUG_THUMBNAILS
		g_message ("(Main Thread) Updating non-current mtime: %s\n",
			   info->image_uri);
#endif
		/* The file in the queue might need a new original mtime */
		existing_info = existing->data;
		existing_info->original_file_mtime = info->original_file_mtime;
		free_thumbnail_info (info);
	}   

	/*********************************
	 * MUTEX UNLOCKED
	 *********************************/

#ifdef DEBUG_THUMBNAILS
	g_message ("(Main Thread) Unlocking mutex\n");
#endif
	pthread_mutex_unlock (&thumbnails_mutex);
}
/* thumbnail_thread is invoked as a separate thread to to make thumbnails. */
static gpointer
thumbnail_thread_start (gpointer data)
{
	NautilusThumbnailInfo *info = NULL;
	GdkPixbuf *pixbuf;
	time_t current_orig_mtime = 0;
	time_t current_time;
	GList *node;

	/* We loop until there are no more thumbails to make, at which point
	   we exit the thread. */
	for (;;) {
#ifdef DEBUG_THUMBNAILS
		g_message ("(Thumbnail Thread) Locking mutex\n");
#endif
		pthread_mutex_lock (&thumbnails_mutex);

		/*********************************
		 * MUTEX LOCKED
		 *********************************/

		/* Pop the last thumbnail we just made off the head of the
		   list and free it. I did this here so we only have to lock
		   the mutex once per thumbnail, rather than once before
		   creating it and once after.
		   Don't pop the thumbnail off the queue if the original file
		   mtime of the request changed. Then we need to redo the thumbnail.
		*/
		if (currently_thumbnailing &&
		    currently_thumbnailing->original_file_mtime == current_orig_mtime) {
			g_assert (info == currently_thumbnailing);
			node = g_hash_table_lookup (thumbnails_to_make_hash, info->image_uri);
			g_assert (node != NULL);
			g_hash_table_remove (thumbnails_to_make_hash, info->image_uri);
			free_thumbnail_info (info);
			g_queue_delete_link ((GQueue *)&thumbnails_to_make, node);
		}
		currently_thumbnailing = NULL;

		/* If there are no more thumbnails to make, reset the
		   thumbnail_thread_is_running flag, unlock the mutex, and
		   exit the thread. */
		if (g_queue_is_empty ((GQueue *)&thumbnails_to_make)) {
#ifdef DEBUG_THUMBNAILS
			g_message ("(Thumbnail Thread) Exiting\n");
#endif
			thumbnail_thread_is_running = FALSE;
			pthread_mutex_unlock (&thumbnails_mutex);
			pthread_exit (NULL);
		}

		/* Get the next one to make. We leave it on the list until it
		   is created so the main thread doesn't add it again while we
		   are creating it. */
		info = g_queue_peek_head ((GQueue *)&thumbnails_to_make);
		currently_thumbnailing = info;
		current_orig_mtime = info->original_file_mtime;
		/*********************************
		 * MUTEX UNLOCKED
		 *********************************/

#ifdef DEBUG_THUMBNAILS
		g_message ("(Thumbnail Thread) Unlocking mutex\n");
#endif
		pthread_mutex_unlock (&thumbnails_mutex);

		time (&current_time);

		/* Don't try to create a thumbnail if the file was modified recently.
		   This prevents constant re-thumbnailing of changing files. */ 
		if (current_time < current_orig_mtime + THUMBNAIL_CREATION_DELAY_SECS &&
		    current_time >= current_orig_mtime) {
#ifdef DEBUG_THUMBNAILS
			g_message ("(Thumbnail Thread) Skipping: %s\n",
				   info->image_uri);
#endif
			/* Reschedule thumbnailing via a change notification */
			g_timeout_add_seconds (1, thumbnail_thread_notify_file_changed,
				       g_strdup (info->image_uri));
 			continue;
		}

		/* Create the thumbnail. */
#ifdef DEBUG_THUMBNAILS
		g_message ("(Thumbnail Thread) Creating thumbnail: %s\n",
			   info->image_uri);
#endif

		pixbuf = gnome_desktop_thumbnail_factory_generate_thumbnail (thumbnail_factory,
									     info->image_uri,
									     info->mime_type);

		if (pixbuf) {
			gnome_desktop_thumbnail_factory_save_thumbnail (thumbnail_factory,
									pixbuf,
									info->image_uri,
									current_orig_mtime);
			g_object_unref (pixbuf);
		} else {
			gnome_desktop_thumbnail_factory_create_failed_thumbnail (thumbnail_factory, 
										 info->image_uri,
										 current_orig_mtime);
		}
		/* We need to call nautilus_file_changed(), but I don't think that is
		   thread safe. So add an idle handler and do it from the main loop. */
		g_idle_add_full (G_PRIORITY_HIGH_IDLE,
				 thumbnail_thread_notify_file_changed,
				 g_strdup (info->image_uri), NULL);
	}
}
Exemple #26
0
static gboolean
do_mail_to_event (AsyncData *data)
{
	EClient *client;
	CamelFolder *folder = data->folder;
	GPtrArray *uids = data->uids;
	GError *error = NULL;

	client = e_client_cache_get_client_sync (data->client_cache,
		data->source, data->extension_name, 30, NULL, &error);

	/* Sanity check. */
	g_return_val_if_fail (
		((client != NULL) && (error == NULL)) ||
		((client == NULL) && (error != NULL)), TRUE);

	if (error != NULL) {
		report_error_idle (_("Cannot open calendar. %s"), error->message);
	} else if (e_client_is_readonly (E_CLIENT (client))) {
		switch (data->source_type) {
		case E_CAL_CLIENT_SOURCE_TYPE_EVENTS:
			report_error_idle (_("Selected calendar is read only, thus cannot create event there. Select other calendar, please."), NULL);
			break;
		case E_CAL_CLIENT_SOURCE_TYPE_TASKS:
			report_error_idle (_("Selected task list is read only, thus cannot create task there. Select other task list, please."), NULL);
			break;
		case E_CAL_CLIENT_SOURCE_TYPE_MEMOS:
			report_error_idle (_("Selected memo list is read only, thus cannot create memo there. Select other memo list, please."), NULL);
			break;
		default:
			g_warn_if_reached ();
			break;
		}
	} else {
		gint i;
		ECalComponentDateTime dt, dt2;
		struct icaltimetype tt, tt2;
		struct _manage_comp *oldmc = NULL;

		#define cache_backend_prop(prop) { \
			gchar *val = NULL; \
			e_client_get_backend_property_sync (E_CLIENT (client), prop, &val, NULL, NULL); \
			g_free (val); \
		}

		/* precache backend properties, thus editor have them ready when needed */
		cache_backend_prop (CAL_BACKEND_PROPERTY_CAL_EMAIL_ADDRESS);
		cache_backend_prop (CAL_BACKEND_PROPERTY_ALARM_EMAIL_ADDRESS);
		cache_backend_prop (CAL_BACKEND_PROPERTY_DEFAULT_OBJECT);
		e_client_get_capabilities (E_CLIENT (client));

		#undef cache_backend_prop

		/* set start day of the event as today, without time - easier than looking for a calendar's time zone */
		tt = icaltime_today ();
		dt.value = &tt;
		dt.tzid = NULL;

		tt2 = tt;
		icaltime_adjust (&tt2, 1, 0, 0, 0);
		dt2.value = &tt2;
		dt2.tzid = NULL;

		for (i = 0; i < (uids ? uids->len : 0); i++) {
			CamelMimeMessage *message;
			ECalComponent *comp;
			ECalComponentText text;
			icalproperty *icalprop;
			icalcomponent *icalcomp;
			struct _manage_comp *mc;

			/* retrieve the message from the CamelFolder */
			/* FIXME Not passing a GCancellable or GError. */
			message = camel_folder_get_message_sync (
				folder, g_ptr_array_index (uids, i),
				NULL, NULL);
			if (!message) {
				continue;
			}

			comp = e_cal_component_new ();

			switch (data->source_type) {
			case E_CAL_CLIENT_SOURCE_TYPE_EVENTS:
				e_cal_component_set_new_vtype (comp, E_CAL_COMPONENT_EVENT);
				break;
			case E_CAL_CLIENT_SOURCE_TYPE_TASKS:
				e_cal_component_set_new_vtype (comp, E_CAL_COMPONENT_TODO);
				break;
			case E_CAL_CLIENT_SOURCE_TYPE_MEMOS:
				e_cal_component_set_new_vtype (comp, E_CAL_COMPONENT_JOURNAL);
				break;
			default:
				g_warn_if_reached ();
				break;
			}

			e_cal_component_set_uid (comp, camel_mime_message_get_message_id (message));
			e_cal_component_set_dtstart (comp, &dt);

			if (data->source_type == E_CAL_CLIENT_SOURCE_TYPE_EVENTS) {
				/* make it an all-day event */
				e_cal_component_set_dtend (comp, &dt2);
			}

			/* set the summary */
			text.value = camel_mime_message_get_subject (message);
			text.altrep = NULL;
			e_cal_component_set_summary (comp, &text);

			/* set all fields */
			if (data->selected_text) {
				GSList sl;

				text.value = data->selected_text;
				text.altrep = NULL;
				sl.next = NULL;
				sl.data = &text;

				e_cal_component_set_description_list (comp, &sl);
			} else
				set_description (comp, message);

			if (data->with_attendees) {
				gchar *organizer;

				/* set actual user as organizer, to be able to change event's properties */
				organizer = set_organizer (comp, data->folder);
				set_attendees (comp, message, organizer);
				g_free (organizer);
			}

			/* set attachment files */
			set_attachments (E_CAL_CLIENT (client), comp, message);

			/* priority */
			set_priority (comp, CAMEL_MIME_PART (message));

			/* no need to increment a sequence number, this is a new component */
			e_cal_component_abort_sequence (comp);

			icalcomp = e_cal_component_get_icalcomponent (comp);

			icalprop = icalproperty_new_x ("1");
			icalproperty_set_x_name (icalprop, "X-EVOLUTION-MOVE-CALENDAR");
			icalcomponent_add_property (icalcomp, icalprop);

			mc = g_new0 (struct _manage_comp, 1);
			mc->client = g_object_ref (client);
			mc->comp = g_object_ref (comp);
			g_mutex_init (&mc->mutex);
			g_cond_init (&mc->cond);
			mc->mails_count = uids->len;
			mc->mails_done = i + 1; /* Current task */
			mc->editor_title = NULL;
			mc->can_continue = TRUE;

			if (oldmc) {
				/* Wait for user to quit the editor created in previous iteration
				 * before displaying next one */
				gboolean can_continue;
				g_mutex_lock (&oldmc->mutex);
				g_cond_wait (&oldmc->cond, &oldmc->mutex);
				g_mutex_unlock (&oldmc->mutex);
				can_continue = oldmc->can_continue;
				free_manage_comp_struct (oldmc);
				oldmc = NULL;

				if (!can_continue)
					break;
			}

			e_cal_client_get_object_sync (
				E_CAL_CLIENT (client),
				icalcomponent_get_uid (icalcomp),
				NULL, &mc->stored_comp, NULL, NULL);

			/* Prioritize ahead of GTK+ redraws. */
			g_idle_add_full (
				G_PRIORITY_HIGH_IDLE,
				(GSourceFunc) do_manage_comp_idle, mc, NULL);

			oldmc = mc;

			g_object_unref (comp);
			g_object_unref (message);

		}

		/* Wait for the last editor and then clean up */
		if (oldmc) {
			g_mutex_lock (&oldmc->mutex);
			g_cond_wait (&oldmc->cond, &oldmc->mutex);
			g_mutex_unlock (&oldmc->mutex);
			free_manage_comp_struct (oldmc);
		}
	}

	/* free memory */
	if (client != NULL)
		g_object_unref (client);
	g_ptr_array_unref (uids);
	g_object_unref (folder);

	g_object_unref (data->client_cache);
	g_object_unref (data->source);
	g_free (data->selected_text);
	g_free (data);
	data = NULL;

	if (error != NULL)
		g_error_free (error);

	return TRUE;
}
Exemple #27
0
void
overview_ui_queue_update (void)
{
  g_idle_add_full (G_PRIORITY_LOW, on_update_overview_later, NULL, NULL);
}
Exemple #28
0
int
main (int argc, char *argv[])
{
    struct sigaction sig_callback;

    g_thread_init (NULL);
    gdk_threads_init ();

    gtk_init (&argc, &argv);

    bindtextdomain (GETTEXT_PACKAGE, SNES9XLOCALEDIR);
    bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
    textdomain (GETTEXT_PACKAGE);

    ZeroMemory (&Settings, sizeof (Settings));

    /* Allow original config file for backend settings */
    S9xLoadConfigFiles (argv, argc);

    /* Perform our config here */
    gui_config = new Snes9xConfig ();

    S9xInitInputDevices ();

    gui_config->load_config_file ();

    char *rom_filename = S9xParseArgs (argv, argc);

    S9xReportControllers ();

    if (!Memory.Init () || !S9xInitAPU ())
        exit (3);

    g_set_application_name ("Snes9x");

    top_level = new Snes9xWindow (gui_config);

    /* If we're going to fullscreen, do it before showing window to avoid flicker. */
    if ((gui_config->full_screen_on_open && rom_filename) || (gui_config->fullscreen))
        gtk_window_fullscreen (top_level->get_window ());

    top_level->show ();

    S9xInitDisplay (argc, argv);

    Memory.PostRomInitFunc = S9xPostRomInit;

    S9xPortSoundInit ();

    gui_config->reconfigure ();
    top_level->update_accels ();

    Settings.Paused = TRUE;
    syncing = 0;
    idle_func_id = g_idle_add_full (IDLE_FUNC_PRIORITY,
                                    S9xIdleFunc,
                                    NULL,
                                    NULL);

    g_timeout_add (10000, S9xScreenSaverCheckFunc, NULL);

    S9xNoROMLoaded ();

    if (rom_filename)
    {
        if (S9xOpenROM (rom_filename) && gui_config->full_screen_on_open)
            gtk_window_unfullscreen (top_level->get_window());
    }

    memset (&sig_callback, 0, sizeof (struct sigaction));
    sig_callback.sa_handler = S9xTerm;

    sigaction (15 /* SIGTERM */, &sig_callback, NULL);
    sigaction (3  /* SIGQUIT */, &sig_callback, NULL);
    sigaction (2  /* SIGINT  */, &sig_callback, NULL);

    if (gui_config->fullscreen)
    {
        gui_config->fullscreen = 0;
        needs_fullscreening = 1;
    }

#ifdef USE_JOYSTICK
    gui_config->flush_joysticks ();
#endif

    gtk_window_present (top_level->get_window ());

    gdk_threads_lock ();

    gtk_main ();

    return 0;
}
Exemple #29
0
void Worker::operator()(const boost::shared_ptr<Worker> &self)
{
    assert(this == self.get());

    {
        // Before entering the execution, check to see if we are canceled or
        // blocked.
        boost::mutex::scoped_lock lock(m_mutex);
        assert(m_state == STATE_QUEUED);
        if (m_cancel)
        {
            m_state = STATE_CANCELED;
            m_cancel = false;
            m_block = false;
            goto CANCELED;
        }
        if (m_block)
        {
            m_state = STATE_BLOCKED;
            m_block = false;
            return;
        }
        unsigned int hpp = m_scheduler.highestPendingWorkerPriority();
        if (hpp > m_priority)
        {
            m_state = STATE_QUEUED;
            m_scheduler.schedule(WorkerAdapter(self));
#ifdef SMYD_WORKER_UNIT_TEST
            printf("%s: Priority %u preempted by priority %u\n",
                   description(), m_priority, hpp);
#endif
            return;
        }
        m_state = STATE_RUNNING;
    }

    {
        ExecutionWrapper wrapper(self);
        m_bypassWrapper = false;
        {
            // After preparing for the execution but before entering the
            // execution, check to see if we are updated.
            boost::mutex::scoped_lock lock(m_mutex);
            assert(m_state == STATE_RUNNING);
            if (m_update)
            {
                m_update = false;
                updateInternally();
            }
        }

        // Enter the execution loop.  Check the external requests periodically.
        for (;;)
        {
            bool done = step();
            {
                boost::mutex::scoped_lock lock(m_mutex);
                assert(m_state == STATE_RUNNING);
                // Note that we should check to see if we are updated, done,
                // canceled, blocked or preempted, strictly in that order.
                if (m_update)
                {
                    m_update = false;
                    updateInternally();
                }
                else if (done)
                {
                    m_state = STATE_FINISHED;
                    m_cancel = false;
                    m_block = false;
                    goto FINISHED;
                }
                if (m_cancel)
                {
                    m_state = STATE_CANCELED;
                    m_cancel = false;
                    m_block = false;
                    cancelInternally();
                    goto CANCELED;
                }
                if (m_block)
                {
                    m_state = STATE_BLOCKED;
                    m_block = false;
                    m_bypassWrapper = true;
                    return;
                }
                unsigned int hpp = m_scheduler.highestPendingWorkerPriority();
                if (hpp > m_priority)
                {
                    // FIXME It is possible that multiple low priority workers
                    // are preempted by a higher priority.  But actually only
                    // one worker is needed.
                    m_state = STATE_QUEUED;
                    m_bypassWrapper = true;
                    m_scheduler.schedule(WorkerAdapter(self));
#ifdef SMYD_WORKER_UNIT_TEST
                    printf("%s: Priority %u preempted by priority %u\n",
                           description(), m_priority, hpp);
#endif
                    return;
                }
            }
        }
    }

FINISHED:
    m_finished(self);
    g_idle_add_full(G_PRIORITY_HIGH,
                    onFinishedInMainThread,
                    new boost::shared_ptr<Worker>(self),
                    NULL);
    return;

CANCELED:
    m_canceled(self);
    g_idle_add_full(G_PRIORITY_HIGH,
                    onCanceledInMainThread,
                    new boost::shared_ptr<Worker>(self),
                    NULL);
}
Exemple #30
-1
static void
handle_gmenu_tree_changed (GMenuTree *tree,
			   GtkWidget *menu)
{
	guint idle_id;
	GList *list, *l;
	GError *error = NULL;

	/* Remove existing items */
	list = gtk_container_get_children (GTK_CONTAINER (menu));
	for (l = list; l; l = l->next)
		gtk_widget_destroy (l->data);
	g_list_free (list);

	g_object_set_data_full (G_OBJECT (menu),
				"panel-menu-tree-directory",
				NULL, NULL);

	if (!gmenu_tree_load_sync (tree, &error)) {
		g_warning ("Failed to load applications: %s", error->message);
		g_clear_error (&error);
	}

	g_object_set_data (G_OBJECT (menu),
			   "panel-menu-needs-loading",
			   GUINT_TO_POINTER (TRUE));

	idle_id = g_idle_add_full (G_PRIORITY_LOW,
				   submenu_to_display_in_idle,
				   menu,
				   NULL);
	g_object_set_data_full (G_OBJECT (menu),
				"panel-menu-idle-id",
				GUINT_TO_POINTER (idle_id),
				remove_submenu_to_display_idle);
}