示例#1
0
static gchar * fileinfo_recursive_get_image (const gchar * path, const gchar *
 file_name, gint depth)
{
    GDir *d;

    if (get_bool (NULL, "recurse_for_cover") && depth > get_int (NULL, "recurse_for_cover_depth"))
        return NULL;

    d = g_dir_open(path, 0, NULL);

    if (d) {
        const gchar *f;

        if (get_bool (NULL, "use_file_cover") && file_name)
        {
            /* Look for images matching file name */
            while((f = g_dir_read_name(d))) {
                gchar *newpath = g_strconcat(path, "/", f, NULL);

                if (!g_file_test(newpath, G_FILE_TEST_IS_DIR) &&
                    has_front_cover_extension(f) &&
                    is_file_image(f, file_name)) {
                    g_dir_close(d);
                    return newpath;
                }

                g_free(newpath);
            }
            g_dir_rewind(d);
        }

        /* Search for files using filter */
        while ((f = g_dir_read_name(d))) {
            gchar *newpath = g_strconcat(path, "/", f, NULL);

            if (!g_file_test(newpath, G_FILE_TEST_IS_DIR) &&
                has_front_cover_extension(f) &&
                is_front_cover_image(f)) {
                g_dir_close(d);
                return newpath;
            }

            g_free(newpath);
        }
        g_dir_rewind(d);

        /* checks whether recursive or not. */
        if (! get_bool (NULL, "recurse_for_cover"))
        {
            g_dir_close(d);
            return NULL;
        }

        /* Descend into directories recursively. */
        while ((f = g_dir_read_name(d))) {
            gchar *newpath = g_strconcat(path, "/", f, NULL);

            if(g_file_test(newpath, G_FILE_TEST_IS_DIR)) {
                gchar *tmp = fileinfo_recursive_get_image(newpath,
                    NULL, depth + 1);
                if(tmp) {
                    g_free(newpath);
                    g_dir_close(d);
                    return tmp;
                }
            }

            g_free(newpath);
        }

        g_dir_close(d);
    }

    return NULL;
}
示例#2
0
/** \brief Select an existing module.
 *
 * This function creates a dialog with a list of existing modules
 * from /homedir/.config/Gpredict/modules/ and lets the user select one
 * of them. The function will return the name of the selected module
 * without the .mod suffix.
 */
static gchar *select_module()
{
    GtkWidget *dialog;          /* the dialog window */
    GtkWidget *modlist;         /* the treeview widget */
    GtkListStore *liststore;    /* the list store data structure */
    GtkCellRenderer *renderer;
    GtkTreeViewColumn *column;
    GtkTreeIter item;           /* new item added to the list store */
    GtkTreeSelection *selection;
    GtkTreeModel *selmod;
    GtkTreeModel *listtreemodel;
    GtkWidget *swin;
    GDir *dir = NULL;           /* directory handle */
    GError *error = NULL;       /* error flag and info */
    gchar *dirname;             /* directory name */
    const gchar *filename;      /* file name */
    gchar **buffv;
    guint count = 0;

    /* create and fill data model */
    liststore = gtk_list_store_new(1, G_TYPE_STRING);

    /* scan for .mod files in the user config directory and
       add the contents of each .mod file to the list store
     */
    dirname = get_modules_dir();
    dir = g_dir_open(dirname, 0, &error);

    if (dir)
    {
        sat_log_log(SAT_LOG_LEVEL_DEBUG,
                    _("%s:%s: Scanning directory %s for modules."),
                    __FILE__, __FUNCTION__, dirname);

        while ((filename = g_dir_read_name(dir)))
        {

            if (g_str_has_suffix(filename, ".mod"))
            {

                /* strip extension and add to list */
                buffv = g_strsplit(filename, ".mod", 0);

                gtk_list_store_append(liststore, &item);
                gtk_list_store_set(liststore, &item, 0, buffv[0], -1);

                g_strfreev(buffv);

                count++;
            }
        }
    }
    else
    {
        sat_log_log(SAT_LOG_LEVEL_ERROR,
                    _("%s:%d: Failed to open module dir %s (%s)"),
                    __FILE__, __LINE__, dirname, error->message);
        g_clear_error(&error);
    }

    g_free(dirname);
    g_dir_close(dir);

    if (count < 1)
    {
        /* tell user that there are no modules, try "New" instead */
        dialog = gtk_message_dialog_new(GTK_WINDOW(app),
                                        GTK_DIALOG_MODAL |
                                        GTK_DIALOG_DESTROY_WITH_PARENT,
                                        GTK_MESSAGE_INFO,
                                        GTK_BUTTONS_OK,
                                        _("You do not have any modules "
                                          "set up yet. Please use File->New "
                                          "in order to create a module."));

        gtk_dialog_run(GTK_DIALOG(dialog));
        gtk_widget_destroy(dialog);

        return NULL;
    }

    /* create tree view */
    modlist = gtk_tree_view_new();
    listtreemodel = GTK_TREE_MODEL(liststore);
    gtk_tree_view_set_model(GTK_TREE_VIEW(modlist), listtreemodel);
    g_object_unref(liststore);
    /* connecting row activated signal postponed so that we can attach dialog window */

    swin = gtk_scrolled_window_new(NULL, NULL);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(swin),
                                   GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
    /* sort the tree by name */
    gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(listtreemodel), 0, compare_func, NULL, NULL);
    gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE(listtreemodel), 0, GTK_SORT_ASCENDING);


    /*** FIXME: Add g_stat info? */

    renderer = gtk_cell_renderer_text_new();
    column = gtk_tree_view_column_new_with_attributes(_("Module"), renderer, "text", 0, NULL);
    gtk_tree_view_insert_column(GTK_TREE_VIEW(modlist), column, -1);

    gtk_widget_show(modlist);

    /* create dialog */
    dialog = gtk_dialog_new_with_buttons(_("Select a module"),
                                         GTK_WINDOW(app),
                                         GTK_DIALOG_MODAL |
                                         GTK_DIALOG_DESTROY_WITH_PARENT,
                                         GTK_STOCK_CANCEL,
                                         GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, NULL);

    gtk_window_set_default_size(GTK_WINDOW(dialog), -1, 200);
    gtk_container_add(GTK_CONTAINER(swin), modlist);
    gtk_widget_show(swin);
    gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), swin);

    /* double clicking in list will open clicked module */
    g_signal_connect(modlist, "row-activated", G_CALLBACK(select_module_row_activated_cb), dialog);


    switch (gtk_dialog_run(GTK_DIALOG(dialog)))
    {

    /* user pressed OK */
    case GTK_RESPONSE_OK:
        selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(modlist));

        if (gtk_tree_selection_get_selected(selection, &selmod, &item))
        {
            gtk_tree_model_get(selmod, &item, 0, &dirname, -1);

            sat_log_log(SAT_LOG_LEVEL_DEBUG,
                        _("%s:%s: Selected module is: %s"), __FILE__, __FUNCTION__, dirname);
        }
        else
        {
            sat_log_log(SAT_LOG_LEVEL_ERROR,
                        _("%s:%s: No selection is list of modules."), __FILE__, __FUNCTION__);

            dirname = NULL;
        }

        break;

    /* everything else is regarded as CANCEL */
    default:
        dirname = NULL;
        break;
    }

    gtk_widget_destroy(dialog);


    return dirname;
}
示例#3
0
static void
read_connections (NMSystemConfigInterface *config)
{
	SCPluginKeyfile *self = SC_PLUGIN_KEYFILE (config);
	SCPluginKeyfilePrivate *priv = SC_PLUGIN_KEYFILE_GET_PRIVATE (self);
	GDir *dir;
	GError *error = NULL;
	const char *item;
	GHashTable *alive_connections;
	GHashTableIter iter;
	NMKeyfileConnection *connection;
	GPtrArray *dead_connections = NULL;
	guint i;
	GPtrArray *filenames;
	GHashTable *paths;

	dir = g_dir_open (KEYFILE_DIR, 0, &error);
	if (!dir) {
		nm_log_warn (LOGD_SETTINGS, "keyfile: cannot read directory '%s': (%d) %s",
		             KEYFILE_DIR,
		             error ? error->code : -1,
		             error && error->message ? error->message : "(unknown)");
		g_clear_error (&error);
		return;
	}

	alive_connections = g_hash_table_new (NULL, NULL);

	filenames = g_ptr_array_new_with_free_func (g_free);
	while ((item = g_dir_read_name (dir))) {
		if (nm_keyfile_plugin_utils_should_ignore_file (item))
			continue;
		g_ptr_array_add (filenames, g_build_filename (KEYFILE_DIR, item, NULL));
	}
	g_dir_close (dir);

	/* While reloading, we don't replace connections that we already loaded while
	 * iterating over the files.
	 *
	 * To have sensible, reproducible behavior, sort the paths by last modification
	 * time prefering older files.
	 */
	paths = _paths_from_connections (priv->connections);
	g_ptr_array_sort_with_data (filenames, (GCompareDataFunc) _sort_paths, paths);
	g_hash_table_destroy (paths);

	for (i = 0; i < filenames->len; i++) {
		connection = update_connection (self, NULL, filenames->pdata[i], NULL, FALSE, alive_connections, NULL);
		if (connection)
			g_hash_table_add (alive_connections, connection);
	}
	g_ptr_array_free (filenames, TRUE);

	g_hash_table_iter_init (&iter, priv->connections);
	while (g_hash_table_iter_next (&iter, NULL, (gpointer *) &connection)) {
		if (   !g_hash_table_contains (alive_connections, connection)
		    && nm_settings_connection_get_filename (NM_SETTINGS_CONNECTION (connection))) {
			if (!dead_connections)
				dead_connections = g_ptr_array_new ();
			g_ptr_array_add (dead_connections, connection);
		}
	}
	g_hash_table_destroy (alive_connections);

	if (dead_connections) {
		for (i = 0; i < dead_connections->len; i++)
			remove_connection (self, dead_connections->pdata[i]);
		g_ptr_array_free (dead_connections, TRUE);
	}
}
示例#4
0
/*
 * Like JSEnumerateOp, but enum provides contextual information as follows:
 *
 * JSENUMERATE_INIT: allocate private enum struct in state_p, return number
 * of elements in *id_p
 * JSENUMERATE_NEXT: return next property id in *id_p, and if no new property
 * free state_p and set to JSVAL_NULL
 * JSENUMERATE_DESTROY : destroy state_p
 *
 * Note that in a for ... in loop, this will be called first on the object,
 * then on its prototype.
 *
 */
static JSBool
importer_new_enumerate(JSContext  *context,
                       JSObject  **object,
                       JSIterateOp enum_op,
                       jsval      *state_p,
                       jsid       *id_p)
{
    ImporterIterator *iter;

    switch (enum_op) {
    case JSENUMERATE_INIT_ALL:
    case JSENUMERATE_INIT: {
        Importer *priv;
        JSObject *search_path;
        jsval search_path_val;
        guint32 search_path_len;
        guint32 i;

        if (state_p)
            *state_p = JSVAL_NULL;

        if (id_p)
            *id_p = INT_TO_JSID(0);

        priv = priv_from_js(context, *object);

        if (!priv)
            /* we are enumerating the prototype properties */
            return JS_TRUE;

        if (!gjs_object_require_property(context, *object, "importer", "searchPath", &search_path_val))
            return JS_FALSE;

        if (!JSVAL_IS_OBJECT(search_path_val)) {
            gjs_throw(context, "searchPath property on importer is not an object");
            return JS_FALSE;
        }

        search_path = JSVAL_TO_OBJECT(search_path_val);

        if (!JS_IsArrayObject(context, search_path)) {
            gjs_throw(context, "searchPath property on importer is not an array");
            return JS_FALSE;
        }

        if (!JS_GetArrayLength(context, search_path, &search_path_len)) {
            gjs_throw(context, "searchPath array has no length");
            return JS_FALSE;
        }

        iter = importer_iterator_new();

        for (i = 0; i < search_path_len; ++i) {
            char *dirname = NULL;
            char *init_path;
            const char *filename;
            jsval elem;
            GDir *dir = NULL;

            elem = JSVAL_VOID;
            if (!JS_GetElement(context, search_path, i, &elem)) {
                /* this means there was an exception, while elem == JSVAL_VOID
                 * means no element found
                 */
                importer_iterator_free(iter);
                return JS_FALSE;
            }

            if (JSVAL_IS_VOID(elem))
                continue;

            if (!JSVAL_IS_STRING(elem)) {
                gjs_throw(context, "importer searchPath contains non-string");
                importer_iterator_free(iter);
                return JS_FALSE;
            }

            if (!gjs_string_to_utf8(context, elem, &dirname)) {
                importer_iterator_free(iter);
                return JS_FALSE; /* Error message already set */
            }

            init_path = g_build_filename(dirname, MODULE_INIT_FILENAME,
                                         NULL);

            load_module_elements(context, *object, iter, init_path);

            g_free(init_path);

            dir = g_dir_open(dirname, 0, NULL);

            if (!dir) {
                g_free(dirname);
                continue;
            }

            while ((filename = g_dir_read_name(dir))) {
                char *full_path;

                /* skip hidden files and directories (.svn, .git, ...) */
                if (filename[0] == '.')
                    continue;

                /* skip module init file */
                if (strcmp(filename, MODULE_INIT_FILENAME) == 0)
                    continue;

                full_path = g_build_filename(dirname, filename, NULL);

                if (g_file_test(full_path, G_FILE_TEST_IS_DIR)) {
                    g_ptr_array_add(iter->elements, g_strdup(filename));
                } else {
                    if (g_str_has_suffix(filename, "."G_MODULE_SUFFIX) ||
                        g_str_has_suffix(filename, ".js")) {
                        g_ptr_array_add(iter->elements,
                                        g_strndup(filename, strlen(filename) - 3));
                    }
                }

                g_free(full_path);
            }
            g_dir_close(dir);

            g_free(dirname);
        }

        if (state_p)
            *state_p = PRIVATE_TO_JSVAL(iter);

        if (id_p)
            *id_p = INT_TO_JSID(iter->elements->len);

        break;
    }

    case JSENUMERATE_NEXT: {
        jsval element_val;

        if (!state_p) {
            gjs_throw(context, "Enumerate with no iterator set?");
            return JS_FALSE;
        }

        if (JSVAL_IS_NULL(*state_p)) /* Iterating prototype */
            return JS_TRUE;

        iter = JSVAL_TO_PRIVATE(*state_p);

        if (iter->index < iter->elements->len) {
            if (!gjs_string_from_utf8(context,
                                         g_ptr_array_index(iter->elements,
                                                           iter->index++),
                                         -1,
                                         &element_val))
                return JS_FALSE;

            if (!JS_ValueToId(context, element_val, id_p))
                return JS_FALSE;

            break;
        }
        /* else fall through to destroying the iterator */
    }

    case JSENUMERATE_DESTROY: {
        if (state_p && !JSVAL_IS_NULL(*state_p)) {
            iter = JSVAL_TO_PRIVATE(*state_p);

            importer_iterator_free(iter);

            *state_p = JSVAL_NULL;
        }
    }
    }

    return JS_TRUE;
}
示例#5
0
static gboolean enable_i8042_debugging(GError **error) {
    GDir *devices_dir = NULL;
    GSList *connected_ports = NULL;
    struct sigaction sigaction_struct;

    devices_dir = g_dir_open(I8042_DEV_DIR, 0, error);
    if (!devices_dir) {
        g_prefix_error(error, "While opening " I8042_DEV_DIR ": ");

        goto error;
    }

    /* Detach the devices before we do anything, this prevents potential race
     * conditions */
    for (gchar const *dir_name = g_dir_read_name(devices_dir);
         dir_name != NULL && *error == NULL;
         dir_name = g_dir_read_name(devices_dir)) {
        gchar *file_name;
        gchar *input_dev_path;

        if (!g_str_has_prefix(dir_name, "serio"))
            continue;

        /* Check if the port's connected */
        input_dev_path = g_build_filename(I8042_DEV_DIR, dir_name, "input",
                                          NULL);
        if (!g_file_test(input_dev_path, G_FILE_TEST_EXISTS)) {
            g_free(input_dev_path);
            continue;
        }

        g_free(input_dev_path);
        connected_ports = g_slist_prepend(connected_ports, strdup(dir_name));

        file_name = g_build_filename(I8042_DEV_DIR, dir_name, "drvctl", NULL);
        if (!write_to_char_dev(file_name, error, "none")) {
            g_free(file_name);
            goto error;
        }

        g_free(file_name);
    }
    if (*error)
        goto error;

    /* We mark when the recording starts, so that we can separate this recording
     * from other recordings ran during this session */
    start_time = g_get_monotonic_time();

    if (!write_to_char_dev("/dev/kmsg", error, "ps2emu: Start recording %ld\n",
                           start_time))
        goto error;

    /* Enable the debugging output for i8042 */
    if (!write_to_char_dev("/sys/module/i8042/parameters/debug", error, "1\n"))
        goto error;

    /* As of Linux 4.3+, data coming out of the KBD port is masked by default */
    if (recording_target == PS2_PORT_KBD &&
        g_file_test("/sys/module/i8042/parameters/unmask_kbd_data",
                    G_FILE_TEST_EXISTS)) {
        if (!write_to_char_dev("/sys/module/i8042/parameters/unmask_kbd_data",
                               error, "1\n"))
            goto error;
    }

    /* Reattach the devices */
    g_dir_rewind(devices_dir);
    for (gchar const *dir_name = g_dir_read_name(devices_dir);
         dir_name != NULL && *error == NULL;
         dir_name = g_dir_read_name(devices_dir)) {
        gchar *file_name;
        gboolean was_connected = FALSE;

        /* Check if the directory was a previously connected port */
        for (GSList *l = connected_ports; l != NULL; l = l->next) {
            if (strcmp(l->data, dir_name) != 0)
                continue;

            was_connected = TRUE;
            break;
        }
        if (!was_connected)
            continue;

        file_name = g_build_filename(I8042_DEV_DIR, dir_name, "drvctl", NULL);
        if (!write_to_char_dev(file_name, error, "rescan")) {
            g_free(file_name);
            goto error;
        }

        g_free(file_name);
    }
    if (*error)
        goto error;

    g_dir_close(devices_dir);
    g_slist_free_full(connected_ports, g_free);

    /* Disable debugging when this application quits */
    memset(&sigaction_struct, 0, sizeof(sigaction_struct));
    sigaction_struct.sa_handler = exit_on_interrupt;

    g_warn_if_fail(sigaction(SIGINT, &sigaction_struct, NULL) == 0);
    g_warn_if_fail(sigaction(SIGTERM, &sigaction_struct, NULL) == 0);
    g_warn_if_fail(sigaction(SIGHUP, &sigaction_struct, NULL) == 0);

    return TRUE;

error:
    if (devices_dir)
        g_dir_close(devices_dir);

    if (connected_ports)
        g_slist_free_full(connected_ports, g_free);

    return FALSE;
}
示例#6
0
static void
import_kmail_folder (struct _import_mbox_msg *m,
                     gchar *k_path_in,
                     GCancellable *cancellable,
                     GError **error)
{
	const gchar *special_folders []= {"cur", "tmp", "new", NULL};
	gchar *special_path;
	const CamelStore *store;
	CamelFolder *folder;
	CamelMimeParser *mp = NULL;
	CamelMessageInfo *info;
	CamelMimeMessage *msg;
	guint32 flags = 0;

	gchar *e_uri, *e_path;
	gchar *k_path;
	const gchar *d;
	gchar *mail_url;
	GDir *dir;
	struct stat st;
	gint fd, i;

	e_uri = kuri_to_euri (k_path_in);
	/* we need to drop some folders, like: Trash */
	if (!e_uri)
		return;

	/* In case we using async way in the future */
	k_path = g_strdup (k_path_in);
	store = evolution_get_local_store ();
	e_path = e_uri + strlen (EVOLUTION_LOCAL_BASE) + 1;
	e_mail_store_create_folder_sync ((CamelStore *)store, e_path, NULL, NULL);
	folder = e_mail_session_uri_to_folder_sync (
			m->session, e_uri, CAMEL_STORE_FOLDER_CREATE,
			cancellable, NULL);

	if (folder == NULL) {
		g_free (k_path);
		g_warning ("evolution error: cannot get the folder\n");
		return;
	}

	camel_operation_push_message (
			cancellable, _("Importing '%s'"),
			camel_folder_get_display_name (folder));
	camel_folder_freeze (folder);

	for (i = 0; special_folders [i]; i++) {
		camel_operation_progress (cancellable, 100*i/3);
		special_path = g_build_filename (k_path, special_folders[i], NULL);
		dir = g_dir_open (special_path, 0, NULL);
		while ((d = g_dir_read_name (dir))) {
			if ((strcmp (d, ".") == 0) || (strcmp (d, "..") == 0)) {
				continue;
			}
			mail_url = g_build_filename (special_path, d, NULL);
			if (g_stat (mail_url, &st) == -1) {
				g_free (mail_url);
				continue;
			}
			if (S_ISREG (st.st_mode)) {
				fd = g_open (mail_url, O_RDONLY | O_BINARY, 0);
				g_free (mail_url);
				if (fd == -1) {
					continue;
				}
				mp = camel_mime_parser_new ();
				camel_mime_parser_scan_from (mp, FALSE);
				if (camel_mime_parser_init_with_fd (mp, fd) == -1) {
					/* will never happen - 0 is unconditionally returned */
					g_object_unref (mp);
					continue;
				}
				msg = camel_mime_message_new ();
				if (!camel_mime_part_construct_from_parser_sync (
						(CamelMimePart *) msg, mp, NULL, NULL)) {
					/* set exception? */
					g_object_unref (mp);
					g_object_unref (msg);
					continue;
				}
				info = camel_message_info_new (NULL);
				if (strcmp (special_folders[i], "cur") == 0) {
					flags |= CAMEL_MESSAGE_SEEN;
				} else if (strcmp (special_folders[i], "tmp") == 0) {
					flags |= CAMEL_MESSAGE_DELETED; /* Mark the 'tmp' mails as 'deleted' */
				}
				camel_message_info_set_flags (info, flags, ~0);
				camel_folder_append_message_sync (
					folder, msg, info, NULL,
					cancellable, error);
				camel_message_info_unref (info);
				g_object_unref (msg);
				g_object_unref (mp);
			} else {
				g_free (mail_url);
			}
		}
	}
	camel_operation_progress (cancellable, 100);
	camel_folder_synchronize_sync (folder, FALSE, NULL, NULL);
	camel_folder_thaw (folder);
	camel_operation_pop_message (cancellable);

	g_free (k_path);
}
/* (fall through - DEPRECATED)
 * enumerates system video devices
 * by checking /sys/class/video4linux
 * args: 
 * videodevice: current device string (default "/dev/video0")
 * 
 * returns: pointer to LDevices struct containing the video devices list */
LDevices *list_devices( gchar *videodevice )
{
	int ret=0;
	int fd=0;
	LDevices *listDevices = NULL;
	listDevices = g_new0( LDevices, 1);
	listDevices->listVidDevices = NULL;
	struct v4l2_capability v4l2_cap;
	GDir *v4l2_dir=NULL;
	GError *error=NULL;
	
	v4l2_dir = g_dir_open("/sys/class/video4linux",0,&error);
	if(v4l2_dir == NULL)
	{
		g_printerr ("opening '/sys/class/video4linux' failed: %s\n", 
			 error->message);
		g_error_free ( error );
		error=NULL;
		return NULL;
	}
	const gchar *v4l2_device;
	int num_dev = 0;
	
	while((v4l2_device = g_dir_read_name(v4l2_dir)) != NULL)
	{
		if(!(g_str_has_prefix(v4l2_device, "video")))
			continue;
		gchar *device = NULL;
		device = g_strjoin("/","/dev",v4l2_device,NULL);
		
		if ((fd = v4l2_open(device, O_RDWR | O_NONBLOCK, 0)) < 0) 
		{
			g_printerr("ERROR opening V4L interface for %s\n",
				device);
			g_free(device);
			continue; /*next dir entry*/
		} 
		else
		{
			ret = xioctl(fd, VIDIOC_QUERYCAP, &v4l2_cap);
			if (ret < 0) 
			{
				perror("VIDIOC_QUERYCAP error");
				g_printerr("   couldn't query device %s\n",
					device);
				g_free(device);
				v4l2_close(fd);
				continue; /*next dir entry*/
			}
			else
			{
				num_dev++;
				g_printf("%s - device %d\n", device, num_dev);
				listDevices->listVidDevices = g_renew(VidDevice, 
					listDevices->listVidDevices, 
					num_dev);
				listDevices->listVidDevices[num_dev-1].device = g_strdup(device);
				listDevices->listVidDevices[num_dev-1].name = g_strdup((gchar *) v4l2_cap.card);
				listDevices->listVidDevices[num_dev-1].driver = g_strdup((gchar *) v4l2_cap.driver);
				listDevices->listVidDevices[num_dev-1].location = g_strdup((gchar *) v4l2_cap.bus_info);
				listDevices->listVidDevices[num_dev-1].valid = 1;
				if(g_strcmp0(videodevice,listDevices->listVidDevices[num_dev-1].device)==0) 
				{
					listDevices->listVidDevices[num_dev-1].current = 1;
					listDevices->current_device = num_dev-1;
				}
				else
					listDevices->listVidDevices[num_dev-1].current = 0;
			}
		}
		g_free(device);
		v4l2_close(fd);
		
		listDevices->listVidDevices[num_dev-1].vendor = 0;
		listDevices->listVidDevices[num_dev-1].product = 0;
		
		gchar *vid_dev_lnk = g_strjoin("/","/sys/class/video4linux",v4l2_device,"device",NULL);
		gchar *device_lnk = g_file_read_link (vid_dev_lnk,&error);
		g_free(vid_dev_lnk);
		
		if(device_lnk == NULL)
		{
			g_printerr ("reading link '/sys/class/video4linux/%s/device' failed: %s\n",
				v4l2_device,
				error->message);
			g_error_free ( error );
			error=NULL;
			//if standard way fails try to get vid, pid from uvc device name 
			//we only need this info for Dynamic controls - uvc driver 
			listDevices->listVidDevices[num_dev-1].vendor = 0;  /*reset vid */
			listDevices->listVidDevices[num_dev-1].product = 0; /*reset pid */
			if(g_strcmp0(listDevices->listVidDevices[num_dev-1].driver,"uvcvideo") == 0)
			{
				sscanf(listDevices->listVidDevices[num_dev-1].name,"UVC Camera (%04x:%04x)",
					&(listDevices->listVidDevices[num_dev-1].vendor),
					&(listDevices->listVidDevices[num_dev-1].product));
			}
		}
		else
		{
			gchar *d_dir = g_strjoin("/","/sys/class/video4linux", v4l2_device, device_lnk, NULL);
			gchar *id_dir = g_path_get_dirname(d_dir);
			g_free(d_dir);
			
			gchar *idVendor = g_strjoin("/", id_dir, "idVendor" ,NULL);
			gchar *idProduct = g_strjoin("/", id_dir, "idProduct" ,NULL);
			
			//g_printf("idVendor: %s\n", idVendor);
			//g_printf("idProduct: %s\n", idProduct);
			FILE *vid_fp = g_fopen(idVendor,"r");
			if(vid_fp != NULL)
			{
				gchar code[5];
				if(fgets(code, sizeof(code), vid_fp) != NULL)
				{
					listDevices->listVidDevices[num_dev-1].vendor = g_ascii_strtoull(code, NULL, 16);
				}
				fclose (vid_fp);
			}
			else
			{
				g_printerr("couldn't open idVendor: %s\n", idVendor);
			}
			
			vid_fp = g_fopen(idProduct,"r");
			if(vid_fp != NULL)
			{
				gchar code[5];
				if(fgets(code, sizeof(code), vid_fp) != NULL)
				{
					listDevices->listVidDevices[num_dev-1].product = g_ascii_strtoull(code, NULL, 16);
				}
				fclose (vid_fp);
			}
			else
			{
				g_printerr("couldn't open idProduct: %s\n", idProduct);
			}
			
			g_free(id_dir);
			g_free(idVendor);
			g_free(idProduct);
		}
		
		g_free(device_lnk);
	}
	
	if(v4l2_dir != NULL) g_dir_close(v4l2_dir);
	
	listDevices->num_devices = num_dev;
	return(listDevices);
}
battery *battery_get(int battery_number) {
    GError * error = NULL;
    const gchar *entry;
    gchar *batt_name = NULL;
    gchar *batt_path = NULL;
    GDir * dir;
    battery *b = NULL;

    /* Try the expected path in sysfs first */
    batt_name = g_strdup_printf(ACPI_BATTERY_DEVICE_NAME "%d", battery_number);
    batt_path = g_strdup_printf(ACPI_PATH_SYS_POWER_SUPPLY "/%s", batt_name);
    if (g_file_test(batt_path, G_FILE_TEST_IS_DIR) == TRUE) {
        b = battery_new();
        b->path = g_strdup( batt_name);
        battery_update ( b );

        if (!b->type_battery) {
            g_warning( "Not a battery: %s", batt_path );
            battery_free(b);
            b = NULL;
        }
    }

    g_free(batt_name);
    g_free(batt_path);

    if (b != NULL)
        return b;

    /*
     * We didn't find the expected path in sysfs.
     * Walk the dir and return any battery.
     */
    dir = g_dir_open( ACPI_PATH_SYS_POWER_SUPPLY, 0, &error );
    if ( dir == NULL )
    {
        g_warning( "NO ACPI/sysfs support in kernel: %s", error->message );
        g_error_free(error);
        return NULL;
    }

    while ( ( entry = g_dir_read_name (dir) ) != NULL )
    {
        b = battery_new();
        b->path = g_strdup( entry );
        battery_update ( b );

        /* We're looking for a battery with the selected ID */
        if (b->type_battery == TRUE) {
            break;
        }
        battery_free(b);
        b = NULL;
    }
    if (b != NULL)
        g_warning( "Battery entry " ACPI_BATTERY_DEVICE_NAME "%d not found, using %s",
            battery_number, b->path);
        // FIXME: update config?
    else
        g_warning( "Battery %d not found", battery_number );

    g_dir_close( dir );
    return b;
}
static gboolean
ldsm_mount_has_trash (LdsmMountInfo *mount)
{
        const gchar *user_data_dir;
        gchar *user_data_attr_id_fs;
        gchar *path_attr_id_fs;
        gboolean mount_uses_user_trash = FALSE;
        gchar *trash_files_dir;
        gboolean has_trash = FALSE;
        GDir *dir;
        const gchar *path;

        user_data_dir = g_get_user_data_dir ();
        user_data_attr_id_fs = ldsm_get_fs_id_for_path (user_data_dir);

        path = g_unix_mount_get_mount_path (mount->mount);
        path_attr_id_fs = ldsm_get_fs_id_for_path (path);

        if (g_strcmp0 (user_data_attr_id_fs, path_attr_id_fs) == 0) {
                /* The volume that is low on space is on the same volume as our home
                 * directory. This means the trash is at $XDG_DATA_HOME/Trash,
                 * not at the root of the volume which is full.
                 */
                mount_uses_user_trash = TRUE;
        }

        g_free (user_data_attr_id_fs);
        g_free (path_attr_id_fs);

        /* I can't think of a better way to find out if a volume has any trash. Any suggestions? */
        if (mount_uses_user_trash) {
                trash_files_dir = g_build_filename (g_get_user_data_dir (), "Trash", "files", NULL);
        } else {
                gchar *uid;

                uid = g_strdup_printf ("%d", getuid ());
                trash_files_dir = g_build_filename (path, ".Trash", uid, "files", NULL);
                if (!g_file_test (trash_files_dir, G_FILE_TEST_IS_DIR)) {
                        gchar *trash_dir;

                        g_free (trash_files_dir);
                        trash_dir = g_strdup_printf (".Trash-%s", uid);
                        trash_files_dir = g_build_filename (path, trash_dir, "files", NULL);
                        g_free (trash_dir);
                        if (!g_file_test (trash_files_dir, G_FILE_TEST_IS_DIR)) {
                                g_free (trash_files_dir);
                                g_free (uid);
                                return has_trash;
                        }
                }
                g_free (uid);
        }

        dir = g_dir_open (trash_files_dir, 0, NULL);
        if (dir) {
                if (g_dir_read_name (dir))
                        has_trash = TRUE;
                g_dir_close (dir);
        }

        g_free (trash_files_dir);

        return has_trash;
}
示例#10
0
文件: main.c 项目: enferex/LilyTerm
int main( int   argc,
	  char *argv[])
#endif
{
	// command_line_path = argv[0];

	// g_debug ("argc = %d", argc);
	// print_array ("argv", argv);
	// i18n support. We need to support i18n under console, too.
	setlocale(LC_ALL, "");
	bindtextdomain (BINARY, LOCALEDIR);
	bind_textdomain_codeset (BINARY, "UTF-8");
	textdomain (BINARY);

	const gchar *user_config_dir = g_get_user_config_dir();

#ifdef OUT_OF_MEMORY
#  undef g_strdup_printf
#endif
	if (user_config_dir) profile_dir = g_strdup_printf("%s/%s", user_config_dir, BINARY);
#ifdef OUT_OF_MEMORY
	#define g_strdup_printf(...) NULL
#endif

	// g_debug("profile_dir = %s", profile_dir);
	proc_exist = g_file_test("/proc", G_FILE_TEST_EXISTS);

	if (proc_exist)
	{
		gboolean proc_is_exist = FALSE;
		GDir *dir  = g_dir_open ("/proc", 0, NULL);
		if (dir)
		{
			const gchar *entry = g_dir_read_name(dir);
			if (entry) proc_is_exist = TRUE;
		}
		g_dir_close(dir);
		// g_debug ("Got proc_is_exist = %d", proc_is_exist);
		proc_exist = proc_is_exist;
	}

	shell = g_getenv("SHELL");
	if (shell==NULL) shell = "";

	pwd = g_getenv("PWD");
	// pwd = g_get_current_dir();
#ifdef SAFEMODE
	if (pwd==NULL) pwd = g_strdup("");
#endif
	// g_debug("Got $PWD = %s", pwd);
	home = g_getenv("HOME");
	if (home==NULL) home = "";
	// g_debug("Get $HOME = %s", home);

	// deal the command line options
	command_option(argc, argv);
	if (wmclass_name==NULL) wmclass_name = g_getenv("RESOURCE_NAME");
	if (wmclass_name==NULL) wmclass_name = "";
	if (wmclass_class==NULL) wmclass_class = "";
	// g_debug("Got wmclass_name = %s, wmclass_class = %s", wmclass_name, wmclass_class);

	// init the gtk+2 engine
#ifndef UNIT_TEST
	gtk_init(&argc, &argv);
#endif
	// FIXME: we should get the single_process from profile. Current is command-line option only.
	if (single_process)
	{
		// init socket data
		if (init_socket_data())
		{
			// trying to connect to an existing LilyTerm
			if (query_socket())
			{
				// success, sent the argc/argv to socket then quit
				// g_debug("A LilyTerm socket server is exist already. exiting...");
				if (send_socket(argc, argv, TRUE))
				{
					g_free(profile_dir);
					exit (0);
				}
			}
			// no LilyTerm exist. create a socket server
			// g_debug("Creating a LilyTerm socket server...");
			init_socket_server();
			g_atexit((GVoidFunc)shutdown_socket_server);
		}
	}

	// start LilyTerm

	// empty_environ = g_strsplit("", " ", -1);
	extern gchar **environ;
	// print_array("main(): environ", environ);
	gchar *environ_str = convert_array_to_string(environ, '\t');
	window_list = NULL;
	// g_debug("Got environ_str (in main.c) = %s", environ_str);
	selection_clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
	selection_primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
	system_locale_list = get_locale_list();
	// g_debug("Got system_locale_list = %s", system_locale_list);
	init_LC_CTYPE = g_strdup(get_default_lc_data(LC_CTYPE));
	// g_debug("Got init_LC_CTYPE = %s", init_LC_CTYPE);
	init_LC_MESSAGES = g_strdup(get_default_lc_data(LC_MESSAGES));
	// g_debug("init_LC_MESSAGES = %s", init_LC_MESSAGES);
	init_encoding = (gchar *)get_encoding_from_locale(NULL);
	if (! compare_strings(init_encoding, "ANSI_X3.4-1968", TRUE))
	{
		g_free(init_encoding);
		init_encoding = g_strdup("UTF-8");
	}
	// g_debug("init_encoding = %s", init_encoding);
	SYSTEM_VTE_CJK_WIDTH_STR = g_getenv("VTE_CJK_WIDTH");
	// g_debug ("Got SYSTEM_VTE_CJK_WIDTH_STR = %s", SYSTEM_VTE_CJK_WIDTH_STR);
	// FIXME: signal(SIGCHLD, SIG_IGN);
	// The first window of LilyTerm

	// g_debug("Got original encoding = %s", get_encoding_from_locale(NULL));
	//GtkNotebook *new_window(int argc,
	//			char *argv[],
	//			gchar *shell,
	//			gchar *environment,
	//			gchar *locale_list,
	//			gchar *PWD,
	//			gchar *HOME,
	//			gchar *VTE_CJK_WIDTH_STR,
	//			gboolean VTE_CJK_WIDTH_STR_overwrite_profile,
	//			gchar *wmclass_name,
	//			gchar *wmclass_class,
	//			gchar *user_environ,
	//			gchar *encoding,
	//			gboolean encoding_overwrite_profile,
	//			gchar *lc_messages,
	//			struct Window *win_data_orig,
	//			struct Page *page_data_orig)

	if ((new_window(argc,
			argv,
			(gchar *) shell,
			environ_str,
			system_locale_list,
			(gchar *) pwd,
			(gchar *) home,
			SYSTEM_VTE_CJK_WIDTH_STR,
			FALSE,
			wmclass_name,
			wmclass_class,
			NULL,
			init_encoding,
			FALSE,
			init_LC_MESSAGES,
			NULL,
			NULL)) ||
	     window_list)
	{
		// The argv of "main" LilyTerm can't be free.
		// Set it to NULL here to avoid double_free().
		argv=NULL;
		// g_debug("gtk_main_level = %d", gtk_main_level());
		if (! gtk_main_level())
			gtk_main();
	}
#ifdef DETAIL
	else
	{
//		g_debug("Got window_list = %p", window_list);
//		GList *win_list = window_list;
//		gint i=0;
//
//		while (win_list)
//		{
//			g_debug("Got %d win_data = %p", ++i, win_list->data);
//			win_list = win_list->next;
//		}
		g_debug("??? The creation of first window is FAIL!!!");
	}
#endif
	extern struct KeyValue system_keys[KEYS];
	gint i;
	// g_debug("Clear function key data!!");
	for (i=KEY_SWITCH_TO_TAB_1; i<=KEY_SWITCH_TO_TAB_12; i++)
	{
		g_free(system_keys[i].name);
		g_free(system_keys[i].topic);
		g_free(system_keys[i].comment);
		g_free(system_keys[i].translation);
#ifdef UNIT_TEST
		system_keys[i].name = NULL;
		system_keys[i].topic = NULL;
		system_keys[i].comment = NULL;
		system_keys[i].translation = NULL;
#endif
	}

	// g_free(pwd);
	// g_strfreev(empty_environ);
	g_free(environ_str);
	g_free(init_encoding);
	g_free(system_locale_list);
	g_free(profile_dir);
	g_free(restricted_locale_message);
	g_list_free(window_list);
	g_free(init_LC_CTYPE);
	g_free(init_LC_MESSAGES);
#ifdef UNIT_TEST
	// empty_environ = NULL;
	environ_str = NULL;
	init_encoding = NULL;
	system_locale_list = NULL;
	profile_dir = NULL;
	restricted_locale_message = NULL;
	window_list = NULL;
	init_LC_CTYPE = NULL;
	init_LC_MESSAGES = NULL;
#endif
	return 0;
}
示例#11
0
// Populate both the drop-down on the import tab and within the file browse dialog
void populate_polsarpro_classification_optionmenu()
{
  // Set up the menus (one on the import tab, the other on the input file browse dialog
  GtkWidget *browse_menu = NULL;
  GtkWidget *browse_option_menu = get_widget_checked("browse_select_colormap_optionmenu");
  if (browse_option_menu) {
    browse_menu = gtk_option_menu_get_menu(GTK_OPTION_MENU(browse_option_menu));
    if (browse_menu) {
      gtk_option_menu_remove_menu(GTK_OPTION_MENU(browse_option_menu));
    }
  }
  browse_menu = gtk_menu_new();

  GtkWidget *browse_item = gtk_menu_item_new_with_label("None");
  gtk_menu_append(GTK_MENU(browse_menu), browse_item);
  gtk_widget_show(browse_item);

  browse_item = gtk_separator_menu_item_new();
  gtk_menu_append(GTK_MENU(browse_menu), browse_item);
  gtk_widget_show(browse_item);

  char lut_loc[1024];
  sprintf(lut_loc, "%s%clook_up_tables", get_asf_share_dir(), DIR_SEPARATOR);
  if (g_polsarpro_classification_optionmenu_ht == NULL) {
    g_polsarpro_classification_optionmenu_ht = g_hash_table_new(g_str_hash,g_str_equal);
  }

  // Open up the share dir's look up tables list, populate dropdown
  // from the files in that directory.
  GDir *lut_dir = g_dir_open(lut_loc, 0, NULL);
  if (lut_dir) {
    unsigned int i, n=0;
    char **names = (char**)MALLOC(sizeof(char*)*MAX_LUTS);

    while (1) {
      const char *name = (char*)g_dir_read_name(lut_dir);
      if (name) {
        char *name_dup = STRDUP(name);
        char *p = findExt(name_dup);
        if (p && strcmp(p, ".pal") == 0 && is_jasc_palette_lut(name)) {
          *p = '\0'; // don't show ".pal" extension in menu
          names[n++] = name_dup;
          // quit when we get too many
          if (n > MAX_LUTS)
            break;
        }
      } else
        break;
    }
    g_dir_close(lut_dir);

    // alphabetize
    qsort(names, n, sizeof(char*), my_strcmp);

    // now populate the menus
    for (i=0; i<n; ++i) {
      browse_item = gtk_menu_item_new_with_label(names[i]);
      g_object_set_data(G_OBJECT(browse_item), "file", (gpointer)names[i]);
      g_object_set_data(G_OBJECT(browse_item), "index", GUINT_TO_POINTER(i+2));
      gtk_menu_append(GTK_MENU(browse_menu), browse_item);
      gtk_widget_show(browse_item);
      g_hash_table_insert(g_polsarpro_classification_optionmenu_ht,
                          (gpointer)g_strdup(names[i]),
                           GUINT_TO_POINTER(i+2));
    }
  }

  browse_option_menu = get_widget_checked("browse_select_colormap_optionmenu");

  gtk_option_menu_set_menu(GTK_OPTION_MENU(browse_option_menu), browse_menu);
  gtk_option_menu_set_history(GTK_OPTION_MENU(browse_option_menu), 0);

  gtk_widget_show(browse_menu);
  gtk_widget_show(browse_option_menu);
}
示例#12
0
/*
 * Do all the bar display and register the events
 */
void
gc_config_start ()
{
  GcomprisProperties	*properties = gc_prop_get();
  gint y_start = 0;
  gint x_start = 0;
  gint x_text_start = 0;
  gint y = 0;
  GooCanvasItem *item;

  /* Pause the board */
  gc_board_pause(TRUE);

  if(rootitem)
    return;

  gc_bar_hide(TRUE);

  rootitem = goo_canvas_group_new (goo_canvas_get_root_item(gc_get_canvas()),
				   NULL);

  item = goo_canvas_svg_new (rootitem,
			     gc_skin_rsvg_get(),
			     "svg-id", "#DIALOG",
			     "pointer-events", GOO_CANVAS_EVENTS_NONE,
			     NULL);

  GooCanvasBounds bounds;
  goo_canvas_item_get_bounds(item, &bounds);
  x_start = bounds.x1;
  y_start = bounds.y1;

  y = bounds.y2 - 26;

  goo_canvas_text_new (rootitem,
		       _("GCompris Configuration"),
		       (gdouble) BOARDWIDTH/2,
		       (gdouble) y_start + 40,
		       -1,
		       GTK_ANCHOR_CENTER,
		       "font", gc_skin_font_title,
		       "fill-color-rgba", gc_skin_color_title,
		       NULL);

  pixmap_checked   = "#CHECKED";
  pixmap_unchecked = "#UNCHECKED";
  pixmap_width = 30;

  x_start += 150;
  x_flag_start = x_start + 50;
  x_text_start = x_start + 115;

  //--------------------------------------------------
  // Locale
  y_start += 105;

  display_previous_next(x_start, y_start, "locale_previous", "locale_next");

  y_flag_start = y_start - pixmap_width/2;

  /* Display a bad icon if this locale is not available */
  item_bad_flag = goo_canvas_svg_new (rootitem,
			     gc_skin_rsvg_get(),
			     "svg-id", "#UNCHECKED",
			     "pointer-events", GOO_CANVAS_EVENTS_NONE,
			     NULL);
  SET_ITEM_LOCATION(item_bad_flag,
		    x_flag_start + 5,
		    y_start - pixmap_width/2);

  /*
   * The current locale is the one found in the config file
   */
  current_locale = properties->locale;
  set_locale_flag(current_locale);

  item_locale_text = goo_canvas_text_new (rootitem,
					  gc_locale_get_name(current_locale),
					  (gdouble) x_text_start,
					  (gdouble) y_start,
					  -1,
					  GTK_ANCHOR_WEST,
					  "font", gc_skin_font_subtitle,
					  "fill-color-rgba", gc_skin_color_content,
					  NULL);

  // Fullscreen / Window
  y_start += Y_GAP;

  item = goo_canvas_svg_new (rootitem,
			     gc_skin_rsvg_get(),
			     "svg-id", (properties->fullscreen ? pixmap_checked : pixmap_unchecked),
			     NULL);
  SET_ITEM_LOCATION(item, x_start, y_start - pixmap_width/2);

  g_signal_connect(item, "button_press_event",
		   (GtkSignalFunc) item_event_ok,
		   "fullscreen");
  gc_item_focus_init(item, NULL);


  goo_canvas_text_new (rootitem,
		       _("Fullscreen"),
		       (gdouble) x_text_start,
		       (gdouble) y_start,
		       -1,
		       GTK_ANCHOR_WEST,
		       "font", gc_skin_font_subtitle,
		       "fill-color-rgba", gc_skin_color_content,
		       NULL);

  // Music
  y_start += Y_GAP;

  item = goo_canvas_svg_new (rootitem,
			     gc_skin_rsvg_get(),
			     "svg-id", (properties->music ? pixmap_checked : pixmap_unchecked),
			     NULL);
  SET_ITEM_LOCATION(item, x_start, y_start - pixmap_width/2);

  g_signal_connect(item, "button_press_event",
		   (GtkSignalFunc) item_event_ok,
		   "music");
  gc_item_focus_init(item, NULL);


  goo_canvas_text_new (rootitem,
		       _("Music"),
		       (gdouble) x_text_start,
		       (gdouble) y_start,
		       -1,
		       GTK_ANCHOR_WEST,
		       "font", gc_skin_font_subtitle,
		       "fill-color-rgba", gc_skin_color_content,
		       NULL);

  // Effect
  y_start += Y_GAP;

  item = goo_canvas_svg_new (rootitem,
			     gc_skin_rsvg_get(),
			     "svg-id", (properties->fx ? pixmap_checked : pixmap_unchecked),
			     NULL);
  SET_ITEM_LOCATION(item, x_start, y_start - pixmap_width/2);

  g_signal_connect(item, "button_press_event",
		   (GtkSignalFunc) item_event_ok,
		   "effect");
  gc_item_focus_init(item, NULL);


  goo_canvas_text_new (rootitem,
		       _("Effect"),
		       (gdouble) x_text_start,
		       (gdouble) y_start,
		       -1,
		       GTK_ANCHOR_WEST,
		       "font", gc_skin_font_subtitle,
		       "fill-color-rgba", gc_skin_color_content,
		       NULL);

  // Zoom
  y_start += Y_GAP;

  item = goo_canvas_svg_new (rootitem,
			     gc_skin_rsvg_get(),
			     "svg-id", (properties->zoom ? pixmap_checked : pixmap_unchecked),
			     NULL);
  SET_ITEM_LOCATION(item, x_start, y_start - pixmap_width/2);

  g_signal_connect(item, "button_press_event",
		   (GtkSignalFunc) item_event_ok,
		   "zoom");
  gc_item_focus_init(item, NULL);

  goo_canvas_text_new (rootitem,
		       _("Zoom"),
		       (gdouble) x_text_start,
		       (gdouble) y_start,
		       -1,
		       GTK_ANCHOR_WEST,
		       "font", gc_skin_font_subtitle,
		       "fill-color-rgba", gc_skin_color_content,
		       NULL);

  // Timer
  y_start += Y_GAP;

  display_previous_next(x_start, y_start, "timer_previous", "timer_next");

  item_timer_text = goo_canvas_text_new (rootitem,
					 gettext(timername[properties->timer]),
					 (gdouble) x_text_start,
					 (gdouble) y_start,
					 -1,
					 GTK_ANCHOR_WEST,
					 "font", gc_skin_font_subtitle,
					 "fill-color-rgba", gc_skin_color_content,
					 NULL);

  // Skin
  {
    const gchar *one_dirent;
    guint  i;
    GDir  *dir;
    gchar *skin_dir;
    gchar *first_skin_name;

    /* Load the Pixpmaps directory file names */
    skin_dir = g_strconcat(properties->package_data_dir, "/skins", NULL);
    dir = g_dir_open(skin_dir, 0, NULL);

    if (!dir)
      g_warning (_("Couldn't open skin dir: %s"), skin_dir);

    /* Fill up the skin list */
    while((one_dirent = g_dir_read_name(dir)) != NULL) {

      if (one_dirent[0] != '.') {
	gchar *filename;
	/* Only directory here are skins */
	filename = g_strdup_printf("%s/%s", properties->package_skin_dir, one_dirent);

	if (g_file_test ((filename), G_FILE_TEST_IS_DIR)) {
	  gchar *skin_name = g_strdup_printf("%s", one_dirent);
	  skinlist = g_list_append (skinlist, skin_name);
	}
	g_free(filename);
      }
    }
    g_dir_close(dir);

    /* Find the current skin index */
    skin_index = 0;
    for(i=0; i<g_list_length(skinlist);  i++)
      if(!strcmp((char *)g_list_nth_data(skinlist, i), properties->skin))
	skin_index = i;

    y_start += Y_GAP;

    /* Should not happen. It the user found the config, there should be a skin */
    if(g_list_length(skinlist) > 0) {
      g_warning("No skin found in %s\n", skin_dir);
      display_previous_next(x_start, y_start, "skin_previous", "skin_next");
      first_skin_name = g_strdup_printf(_("Skin : %s"), (char *)g_list_nth_data(skinlist, skin_index));
    } else {
      first_skin_name = g_strdup(_("SKINS NOT FOUND"));
    }

    item_skin_text = goo_canvas_text_new (rootitem,
					  first_skin_name,
					  (gdouble) x_text_start,
					  (gdouble) y_start,
					  -1,
					  GTK_ANCHOR_WEST,
					  "font", gc_skin_font_subtitle,
					  "fill-color-rgba", gc_skin_color_content,
					  NULL);
    g_free(first_skin_name);
    g_free(skin_dir);

  }

  // Difficulty Filter
  y_start += Y_GAP;

  stars_group_x = x_start + 45;
  stars_group_y = y_start - 25;
  gchar *text = g_strdup_printf("<i>%s</i>", gettext(filtername));
  item_filter_text = goo_canvas_text_new (rootitem,
					  text,
					  x_text_start,
					  y_start,
					  400,
					  GTK_ANCHOR_WEST,
					  "use-markup", TRUE,
					  "font", gc_skin_font_subtitle,
					  "fill-color-rgba", gc_skin_color_content,
					  NULL);
  g_free(text);


  // OK
  gc_util_button_text_svg(rootitem,
			  BOARDWIDTH * 0.5,
			  y,
			  "#BUTTON_TEXT",
			  _("OK"),
			  (GtkSignalFunc) item_event_ok,
			  "ok");

  is_displayed = TRUE;
}
示例#13
0
static gboolean
find_folders_recursive (const gchar *physical_path,
                        const gchar *path,
                        EPathFindFoldersCallback callback,
                        gpointer data)
{
	GDir *dir;
	gchar *subfolder_directory_path;
	gboolean ok;

	if (*path) {
		if (!callback (physical_path, path, data))
			return FALSE;

		subfolder_directory_path = g_strdup_printf ("%s/%s", physical_path, SUBFOLDER_DIR_NAME);
	} else {
		/* On the top level, we have no folders and,
		 * consequently, no subfolder directory.
		 */

		subfolder_directory_path = g_strdup (physical_path);
	}

	/* Now scan the subfolders and load them. */
	dir = g_dir_open (subfolder_directory_path, 0, NULL);
	if (dir == NULL) {
		g_free (subfolder_directory_path);
		return TRUE;
	}

	ok = TRUE;
	while (ok) {
		struct stat file_stat;
		const gchar *dirent;
		gchar *file_path;
		gchar *new_path;

		dirent = g_dir_read_name (dir);
		if (dirent == NULL)
			break;

		file_path = g_strdup_printf ("%s/%s", subfolder_directory_path,
					     dirent);

		if (g_stat (file_path, &file_stat) < 0 ||
		    !S_ISDIR (file_stat.st_mode)) {
			g_free (file_path);
			continue;
		}

		new_path = g_strdup_printf ("%s/%s", path, dirent);

		ok = find_folders_recursive (file_path, new_path, callback, data);

		g_free (file_path);
		g_free (new_path);
	}

	g_dir_close (dir);
	g_free (subfolder_directory_path);

	return ok;
}
示例#14
0
文件: film.c 项目: roggan87/darktable
void dt_film_import1(dt_film_t *film)
{
  gboolean recursive = dt_conf_get_bool("ui_last/import_recursive");

  /* first of all gather all images to import */
  GList *images = NULL;
  images = _film_recursive_get_files(film->dirname, recursive, &images);
  if(g_list_length(images) == 0)
  {
    dt_control_log(_("no supported images were found to be imported"));
    return;
  }

  /* we got ourself a list of images, lets sort and start import */
  images = g_list_sort(images,(GCompareFunc)_film_filename_cmp);

  /* let's start import of images */
  gchar message[512] = {0};
  double fraction = 0;
  uint32_t total = g_list_length(images);
  g_snprintf(message, sizeof(message) - 1,
             ngettext("importing %d image","importing %d images", total), total);
  const guint *jid = dt_control_backgroundjobs_create(darktable.control, 0, message);

  /* loop thru the images and import to current film roll */
  dt_film_t *cfr = film;
  GList *image = g_list_first(images);
  do
  {
    gchar *cdn = g_path_get_dirname((const gchar *)image->data);

    /* check if we need to initialize a new filmroll */
    if(!cfr || g_strcmp0(cfr->dirname, cdn) != 0)
    {

#if GLIB_CHECK_VERSION (2, 26, 0)
      if(cfr && cfr->dir)
      {
        /* check if we can find a gpx data file to be auto applied
           to images in the jsut imported filmroll */
        g_dir_rewind(cfr->dir);
        const gchar *dfn = NULL;
        while ((dfn = g_dir_read_name(cfr->dir)) != NULL)
        {
          /* check if we have a gpx to be auto applied to filmroll */
          if(strcmp(dfn+strlen(dfn)-4,".gpx") == 0 ||
              strcmp(dfn+strlen(dfn)-4,".GPX") == 0)
          {
            gchar *gpx_file = g_build_path (G_DIR_SEPARATOR_S, cfr->dirname, dfn, NULL);
            dt_control_gpx_apply(gpx_file, cfr->id, dt_conf_get_string("plugins/lighttable/geotagging/tz"));
            g_free(gpx_file);
          }
        }
      }
#endif

      /* cleanup previously imported filmroll*/
      if(cfr && cfr!=film)
      {
        dt_film_cleanup(cfr);
        g_free(cfr);
        cfr = NULL;
      }

      /* initialize and create a new film to import to */
      cfr = g_malloc(sizeof(dt_film_t));
      dt_film_init(cfr);
      dt_film_new(cfr, cdn);
    }

    /* import image */
    dt_image_import(cfr->id, (const gchar *)image->data, FALSE);

    fraction+=1.0/total;
    dt_control_backgroundjobs_progress(darktable.control, jid, fraction);

  }
  while( (image = g_list_next(image)) != NULL);

  // only redraw at the end, to not spam the cpu with exposure events
  dt_control_queue_redraw_center();

  dt_control_backgroundjobs_destroy(darktable.control, jid);
  //dt_control_signal_raise(darktable.signals , DT_SIGNAL_FILMROLLS_IMPORTED);

#if GLIB_CHECK_VERSION (2, 26, 0)
  if(cfr && cfr->dir)
  {
    /* check if we can find a gpx data file to be auto applied
       to images in the just imported filmroll */
    g_dir_rewind(cfr->dir);
    const gchar *dfn = NULL;
    while ((dfn = g_dir_read_name(cfr->dir)) != NULL)
    {
      /* check if we have a gpx to be auto applied to filmroll */
      if(strcmp(dfn+strlen(dfn)-4,".gpx") == 0 ||
          strcmp(dfn+strlen(dfn)-4,".GPX") == 0)
      {
        gchar *gpx_file = g_build_path (G_DIR_SEPARATOR_S, cfr->dirname, dfn, NULL);
        dt_control_gpx_apply(gpx_file, cfr->id, dt_conf_get_string("plugins/lighttable/geotagging/tz"));
        g_free(gpx_file);
      }
    }
  }
#endif
}
示例#15
0
static StoragedObject *
wait_for_loop_object (StoragedDaemon *daemon,
                      gpointer        user_data)
{
  WaitForLoopData *data = user_data;
  StoragedObject *ret = NULL;
  StoragedObject *object = NULL;
  StoragedBlock *block;
  StoragedLoop *loop;
  StoragedLinuxDevice *device = NULL;
  GDir *dir;

  /* First see if we have the right loop object */
  object = storaged_daemon_find_block_by_device_file (daemon, data->loop_device);
  if (object == NULL)
    goto out;
  block = storaged_object_peek_block (object);
  loop = storaged_object_peek_loop (object);
  if (block == NULL || loop == NULL)
    goto out;
  if (g_strcmp0 (storaged_loop_get_backing_file (loop), data->path) != 0)
    goto out;

  /* We also need to wait for all partitions to be in place in case
   * the loop device is partitioned... we can do it like this because
   * we are guaranteed that partitions are in sysfs when receiving the
   * uevent for the main block device...
   */
  device = storaged_linux_block_object_get_device (STORAGED_LINUX_BLOCK_OBJECT (object));
  if (device == NULL)
    goto out;

  dir = g_dir_open (g_udev_device_get_sysfs_path (device->udev_device), 0 /* flags */, NULL /* GError */);
  if (dir != NULL)
    {
      const gchar *name;
      const gchar *device_name;
      device_name = g_udev_device_get_name (device->udev_device);
      while ((name = g_dir_read_name (dir)) != NULL)
        {
          if (g_str_has_prefix (name, device_name))
            {
              gchar *sysfs_path;
              StoragedObject *partition_object;
              sysfs_path = g_strconcat (g_udev_device_get_sysfs_path (device->udev_device), "/", name, NULL);
              partition_object = storaged_daemon_find_block_by_sysfs_path (daemon, sysfs_path);
              if (partition_object == NULL)
                {
                  /* nope, not there, bail */
                  g_free (sysfs_path);
                  g_dir_close (dir);
                  goto out;
                }
              g_object_unref (partition_object);
              g_free (sysfs_path);
            }
        }
      g_dir_close (dir);
    }

  /* all, good return the loop object */
  ret = g_object_ref (object);

 out:
  g_clear_object (&object);
  g_clear_object (&device);
  return ret;
}
示例#16
0
文件: vfs.cpp 项目: AEonZR/GtkRadiant
static GSList* vfsGetListInternal (const char *dir, const char *ext, bool directories)
{
  GSList *lst, *lst_aux, *files = NULL;
  char dirname[NAME_MAX], extension[NAME_MAX], filename[NAME_MAX];
  int dirlen;
  char *ptr;
  //struct dirent *dirlist;
  char *dirlist;
  struct stat st;
  GDir *diskdir;
  int i;

  dirname[0] = '\0';
  if (dir != NULL)
  {
    strcat (dirname, dir);
	g_strdown (dirname);
	vfsFixDOSName (dirname);
	vfsAddSlash (dirname);
	Sys_Printf("vfs dirname_1: %s\n", dirname);
  }
  //else
  //  dirname[0] = '\0';
  dirlen = strlen (dirname);

  if (ext != NULL)
    strcpy (extension, ext);
  else
    extension[0] = '\0';
  g_strdown (extension);

  for (lst = g_pakFiles; lst != NULL; lst = g_slist_next (lst))
  {
    VFS_PAKFILE* file = (VFS_PAKFILE*)lst->data;
    gboolean found = FALSE;
    ptr = file->entry.filename;

    // check that the file name begins with dirname
    for (i = 0; (*ptr && i < dirlen); i++, ptr++)
      if (*ptr != dirname[i])
	break;

    if (i != dirlen)
      continue;

    if (directories)
    {
      char *sep = strchr (ptr, '/');
      if (sep == NULL)
	continue;

      i = sep-ptr;

      // check for duplicates
      for (lst_aux = files; lst_aux; lst_aux = g_slist_next (lst_aux))
	if (strncmp ((char*)lst_aux->data, ptr, i) == 0)
        {
	  found = TRUE;
	  break;
	}

      if (!found)
      {
	char *name = g_strndup (ptr, i+1);
	name[i] = '\0';
	files = g_slist_append (files, name);
      }
    }
    else
    {
      // check extension
      if ((ext != NULL) && (strstr (ptr, extension) == NULL))
	continue;

      // check for duplicates
      for (lst_aux = files; lst_aux; lst_aux = g_slist_next (lst_aux))
	if (strcmp ((char*)lst_aux->data, ptr) == 0)
        {
	  found = TRUE;
	  break;
	}

      if (!found)
	files = g_slist_append (files, g_strdup (ptr));
    }
  }

  for (i = 0; i < g_numDirs; i++)
  {
    strcpy (dirname, g_strDirs[i]);
    strcat (dirname, dir);
    g_strdown (dirname);
	vfsFixDOSName (dirname);
	vfsAddSlash (dirname);

    diskdir = g_dir_open (dirname, 0, NULL);

	if (diskdir != NULL)
    {
      while (1)
      {
        const char* name = g_dir_read_name(diskdir);
        if(name == NULL)
          break;

        if (directories && (name[0] == '.'))
          continue;

        sprintf (filename, "%s%s", dirname, name);
        stat (filename, &st);
		Sys_Printf("vfs FileName: %s\n", filename);

        if ((S_ISDIR (st.st_mode) != 0) != directories)
          continue;

        gboolean found = FALSE;

        dirlist = g_strdup(name);

        g_strdown (dirlist);

        char *ptr_ext = strrchr (dirlist, '.');
        if(ext == NULL
          || (ext != NULL && ptr_ext != NULL && ptr_ext[0] != '\0' && strcmp (ptr_ext+1, extension) == 0))
        {

          // check for duplicates
          for (lst_aux = files; lst_aux; lst_aux = g_slist_next (lst_aux))
            if (strcmp ((char*)lst_aux->data, dirlist) == 0)
            {
              found = TRUE;
              break;
            }

          if (!found)
            files = g_slist_append (files, g_strdup (dirlist));
        }

        g_free(dirlist);
      }
      g_dir_close (diskdir);
    }
  }

  return files;
}
示例#17
0
void gaym_buddy_status(struct gaym_conn *gaym, char *name,
                       gboolean online, char *info)
{
    char *bio = NULL;
    char *thumbnail = NULL;
    char *stats = NULL;
    char *url = NULL;
    struct gaym_fetch_thumbnail_data *data;
    gboolean gaymuser = FALSE;

    if (!gaym || !gaym->account || !gaym->buddies || !name) {
        return;
    }

    if (info) {
#ifdef GAYM_TOKEN
        gaymuser = gaym_stats_find_gaym_token(info);
#endif
        bio = gaym_bio_strdup(info);
        if (bio) {
            bio = g_strstrip(bio);
        }

        thumbnail = gaym_thumbnail_strdup(info);
        if (thumbnail) {
            thumbnail = g_strstrip(thumbnail);
        }

        stats = gaym_stats_strdup(info);
        if (stats) {
            stats = g_strstrip(stats);
        }


    }

    GaimConnection *gc = gaim_account_get_connection(gaym->account);

    if (!gc) {
        return;
    }

    struct gaym_buddy *ib = g_hash_table_lookup(gaym->buddies, name);

    char *normalized = g_strdup(gaim_normalize(gaym->account, name));

    if (thumbnail) {
        gboolean do_fetch = 1;
        GError *err = NULL;
        if (!ib || gaim_utf8_strcasecmp(thumbnail, ib->thumbnail)) {
            char *dirname =
                g_build_filename(gaim_user_dir(), "icons", "gaym",
                                 gaim_normalize(gaym->account, name),
                                 NULL);
            GDir *gdir = g_dir_open(dirname, 0, &err);
            if (gdir) {
                const char *filename;

                while ((filename = g_dir_read_name(gdir))) {    /* don't
                                                                   free
                                                                   filename: 
                                                                   owned
                                                                   by
                                                                   glib. */
                    char *thumbnail_base = g_path_get_basename(thumbnail);
                    gaim_debug_misc("gaym", "compared %s and %s\n",
                                    thumbnail_base, filename);
                    if (!gaim_utf8_strcasecmp(thumbnail_base, filename)) {
                        do_fetch = 0;
                        break;
                    }
                    g_free(thumbnail_base);
                }
                g_dir_close(gdir);
            }
            if (do_fetch) {

                gaim_debug_misc("gaym",
                                "********************************************\n");
                gaim_debug_misc("gaym",
                                "*****************FETCH**********************\n");
                gaim_debug_misc("gaym",
                                "********************************************\n");
                char *hashurl = NULL;
                hashurl =
                    g_hash_table_lookup(gaym->confighash,
                                        "mini-profile-panel.thumbnail-prefix");
                g_return_if_fail(hashurl != NULL);
                data = g_new0(struct gaym_fetch_thumbnail_data, 1);
                data->gc = gaim_account_get_connection(gaym->account);
                data->who = g_strdup(gaim_normalize(gaym->account, name));
                data->filename = g_strdup(g_strrstr(thumbnail, "/"));
                gaim_debug_misc("gayminfo", "Found filename: %s\n",
                                data->filename);
                url = g_strdup_printf("%s%s", hashurl, thumbnail);
                gaim_url_fetch(url, FALSE, "Mozilla/4.0", FALSE,
                               gaym_fetch_thumbnail_cb, data);
                g_free(url);
            }

        }
    }
示例#18
0
static CamelFolderInfo *
scan_dir (CamelStore *store,
          GHashTable *visited,
          CamelFolderInfo *parent,
          const gchar *root,
          const gchar *name,
          guint32 flags,
          GError **error)
{
	CamelFolderInfo *folders, *tail, *fi;
	GHashTable *folder_hash;
	const gchar *dent;
	GDir *dir;

	tail = folders = NULL;

	if (!(dir = g_dir_open (root, 0, NULL)))
		return NULL;

	folder_hash = g_hash_table_new (g_str_hash, g_str_equal);

	/* FIXME: it would be better if we queue'd up the recursive
	 * scans till the end so that we can limit the number of
	 * directory descriptors open at any given time... */

	while ((dent = g_dir_read_name (dir))) {
		gchar *short_name, *full_name, *path, *ext;
		struct stat st;

		if (dent[0] == '.')
			continue;

		if (ignore_file (dent, FALSE))
			continue;

		path = g_strdup_printf ("%s/%s", root, dent);
		if (g_stat (path, &st) == -1) {
			g_free (path);
			continue;
		}
#ifndef G_OS_WIN32
		if (S_ISDIR (st.st_mode)) {
			struct _inode in = { st.st_dev, st.st_ino };

			if (g_hash_table_lookup (visited, &in)) {
				g_free (path);
				continue;
			}
		}
#endif
		short_name = g_strdup (dent);
		if ((ext = strrchr (short_name, '.')) && !strcmp (ext, ".sbd"))
			*ext = '\0';

		if (name != NULL)
			full_name = g_strdup_printf ("%s/%s", name, short_name);
		else
			full_name = g_strdup (short_name);

		if ((fi = g_hash_table_lookup (folder_hash, short_name)) != NULL) {
			g_free (short_name);
			g_free (full_name);

			if (S_ISDIR (st.st_mode)) {
				fi->flags = (fi->flags & ~CAMEL_FOLDER_NOCHILDREN) | CAMEL_FOLDER_CHILDREN;
			} else {
				fi->flags &= ~CAMEL_FOLDER_NOSELECT;
			}
		} else {
			fi = camel_folder_info_new ();
			fi->parent = parent;

			fi->full_name = full_name;
			fi->display_name = short_name;
			fi->unread = -1;
			fi->total = -1;

			if (S_ISDIR (st.st_mode))
				fi->flags = CAMEL_FOLDER_NOSELECT;
			else
				fi->flags = CAMEL_FOLDER_NOCHILDREN;

			if (tail == NULL)
				folders = fi;
			else
				tail->next = fi;

			tail = fi;

			g_hash_table_insert (folder_hash, fi->display_name, fi);
		}

		if (!S_ISDIR (st.st_mode)) {
			fill_fi (store, fi, flags);
		} else if ((flags & CAMEL_STORE_FOLDER_INFO_RECURSIVE)) {
			struct _inode in = { st.st_dev, st.st_ino };

			if (g_hash_table_lookup (visited, &in) == NULL) {
#ifndef G_OS_WIN32
				struct _inode *inew = g_new (struct _inode, 1);

				*inew = in;
				g_hash_table_insert (visited, inew, inew);
#endif
				if ((fi->child = scan_dir (store, visited, fi, path, fi->full_name, flags, error)))
					fi->flags |= CAMEL_FOLDER_CHILDREN;
				else
					fi->flags = (fi->flags & ~CAMEL_FOLDER_CHILDREN) | CAMEL_FOLDER_NOCHILDREN;
			}
		}

		g_free (path);
	}

	g_dir_close (dir);

	g_hash_table_destroy (folder_hash);

	return folders;
}
示例#19
0
static void
clean_old_logs()
{
#if !defined(_WIN32)
	const gchar *file;
	gchar *config;

	config = ghb_get_user_config_dir(NULL);

	if (g_file_test(config, G_FILE_TEST_IS_DIR))
	{
		GDir *gdir = g_dir_open(config, 0, NULL);
		file = g_dir_read_name(gdir);
		while (file)
		{
			if (strncmp(file, "Activity.log.", 13) == 0)
			{
				gchar *path;
				int fd, lock = 1;
				int pid;

				sscanf(file, "Activity.log.%d", &pid);

				path = g_strdup_printf("%s/ghb.pid.%d", config, pid);
				if (g_file_test(path, G_FILE_TEST_EXISTS))
				{
					fd = open(path, O_RDWR);
					if (fd >= 0)
					{
						lock = lockf(fd, F_TLOCK, 0);
					}
					g_free(path);
					close(fd);
					if (lock == 0)
					{
						path = g_strdup_printf("%s/%s", config, file);
						g_unlink(path);
						g_free(path);
					}
				}
				else
				{
					g_free(path);
					path = g_strdup_printf("%s/%s", config, file);
					g_unlink(path);
					g_free(path);
				}
			}
			file = g_dir_read_name(gdir);
		}
		g_dir_close(gdir);
	}
	g_free(config);
#else
	const gchar *file;
	gchar *config;

	config = ghb_get_user_config_dir(NULL);

	if (g_file_test(config, G_FILE_TEST_IS_DIR))
	{
		GDir *gdir = g_dir_open(config, 0, NULL);
		file = g_dir_read_name(gdir);
		while (file)
		{
			if (strncmp(file, "Activity.log.", 13) == 0)
			{
				gchar *path;
				int pid;

				sscanf(file, "Activity.log.%d", &pid);

#if 0
				int fd, lock = 1;

				path = g_strdup_printf("%s/ghb.pid.%d", config, pid);
				if (g_file_test(path, G_FILE_TEST_EXISTS))
				{
					fd = open(path, O_RDWR);
					if (fd >= 0)
					{
						lock = lockf(fd, F_TLOCK, 0);
					}
					g_free(path);
					close(fd);
					if (lock == 0)
					{
						path = g_strdup_printf("%s/%s", config, file);
						g_unlink(path);
						g_free(path);
					}
				}
				else
#endif
				{
					//g_free(path);
					path = g_strdup_printf("%s/%s", config, file);
					g_unlink(path);
					g_free(path);
				}
			}
			file = g_dir_read_name(gdir);
		}
		g_dir_close(gdir);
	}
	g_free(config);
#endif
}
示例#20
0
Plugin::List Plugin::scan( TPContext * context , const String & prefix , const StringList & symbols )
{
	Plugin::List result;

    if ( ! g_module_supported() )
    {
        tpwarn( "PLUGINS ARE NOT SUPPORTED ON THIS PLATFORM" );

        return result;
    }

    const gchar * plugins_path = context->get( TP_PLUGINS_PATH );

    if ( ! plugins_path )
    {
        tpwarn( "PLUGINS PATH IS NOT SET" );

        return result;
    }

    if ( ! g_file_test( plugins_path , G_FILE_TEST_IS_DIR ) )
    {
    	return result;
    }

    GError * error = 0;

    GDir * dir = g_dir_open( plugins_path , 0 , & error );

    if ( ! dir )
    {
        tpwarn( "FAILED TO OPEN PLUGINS PATH '%s' : %s" , plugins_path , error->message );

        g_clear_error( & error );

        return result;
    }

    for ( const gchar * name = g_dir_read_name( dir ); name ; name = g_dir_read_name( dir ) )
    {
        if ( g_str_has_prefix( name , prefix.c_str() ) )
        {
            if ( ! g_str_has_suffix( name , ".config" ) )
            {
                gchar * file_name = g_build_filename( plugins_path , name , NULL );

                tplog( "FOUND PLUGIN %s" , file_name );

                GModule * module = g_module_open( file_name , G_MODULE_BIND_LOCAL );

                if ( 0 == module )
                {
                	tpwarn( "  FAILED TO OPEN : %s" , g_module_error() );
                }
                else
                {
                	tplog2( "  LOADED" );

                	StringList all_symbols( symbols );

                	all_symbols.push_front( TP_PLUGIN_SHUTDOWN );
                	all_symbols.push_front( TP_PLUGIN_INITIALIZE );

                	GPointerMap symbols_found;

                	for ( StringList::const_iterator it = all_symbols.begin(); it != all_symbols.end(); ++it )
                	{
                		const char * symbol_name = it->c_str();

                		if ( gpointer symbol = get_symbol( module , symbol_name ) )
                		{
                    		tplog2( "  FOUND SYMBOL '%s'" , symbol_name );
                    		symbols_found[ symbol_name ] = symbol;
                		}
                		else
                		{
                			break;
                		}
                	}

                	if ( symbols_found.size() != all_symbols.size() )
                	{
                		g_module_close( module );
                	}
                	else
                	{
                		result.push_back( new Plugin( module , symbols_found ) );
                	}
                }

                g_free( file_name );
            }
        }
    }

    g_dir_close( dir );

    return result;
}
示例#21
0
static gpointer
verve_env_load_thread (gpointer user_data)
{
  VerveEnv *env = VERVE_ENV (user_data);
  gchar   **paths;
  int       i;
  
  /* Get $PATH directories */
  paths = verve_env_get_path (env);
  
  /* Iterate over paths list */
  for (i=0; !env->load_thread_cancelled && i<g_strv_length (paths); i++)
  {
    const gchar *current;
    gchar       *filename;
    GList       *lp;
    /* Try opening the directory */
    GDir *dir = g_dir_open (paths[i], 0, NULL);

    /* Continue with next directory if this one cant' be opened */
    if (G_UNLIKELY (dir == NULL)) 
      continue;

    /* Iterate over files in this directory */
    while (!env->load_thread_cancelled && (current = g_dir_read_name (dir)) != NULL)
      {
        /* Convert to valid UTF-8 */
        filename = g_filename_display_name (current);

        /* Avoid duplicates */
        for (lp = g_list_first (env->binaries); lp != NULL; lp = lp->next)
          if (g_ascii_strcasecmp (lp->data, filename) == 0)
            break;
       
        /* Check details of file if it's not in the list already */
        if (G_LIKELY (lp == NULL))
          {
            /* Determine the absolute path to the file */
            gchar *path = g_build_filename (paths[i], current, NULL);

            /* Check if the path refers to an executable */
            if (g_file_test (path, G_FILE_TEST_IS_EXECUTABLE) &&
                !g_file_test (path, G_FILE_TEST_IS_DIR))
              {
                /* Add file filename to the list */
                env->binaries = g_list_prepend (env->binaries, filename);

                /* No need to free the filename later in this function */
                filename = NULL;
              }

            /* Free absolute path */
            g_free (path);
          }

        /* Release filename if necessary */
        g_free (filename);
      }

    /* Close directory */
    g_dir_close (dir);
  }

  /* Sort binaries */
  env->binaries = g_list_sort (env->binaries, (GCompareFunc) g_utf8_collate);

  /* Emit 'load-binaries' signal */
  g_signal_emit_by_name (env, "load-binaries");

  return env->binaries;
}
示例#22
0
文件: main.c 项目: mate-desktop/marco
/**
 * This is where the story begins. It parses commandline options and
 * environment variables, sets up the screen, hands control off to
 * GTK, and cleans up afterwards.
 *
 * \param argc Number of arguments (as usual)
 * \param argv Array of arguments (as usual)
 *
 * \bug It's a bit long. It would be good to split it out into separate
 * functions.
 */
int
main (int argc, char **argv)
{
  struct sigaction act;
  sigset_t empty_mask;
  MetaArguments meta_args;
  const gchar *log_domains[] = {
    NULL, G_LOG_DOMAIN, "Gtk", "Gdk", "GLib",
    "Pango", "GLib-GObject", "GThread"
  };
  guint i;
  GIOChannel *channel;

  if (setlocale (LC_ALL, "") == NULL)
    meta_warning ("Locale not understood by C library, internationalization will not work\n");

  sigemptyset (&empty_mask);
  act.sa_handler = SIG_IGN;
  act.sa_mask    = empty_mask;
  act.sa_flags   = 0;
  if (sigaction (SIGPIPE,  &act, NULL) < 0)
    g_printerr ("Failed to register SIGPIPE handler: %s\n",
                g_strerror (errno));
#ifdef SIGXFSZ
  if (sigaction (SIGXFSZ,  &act, NULL) < 0)
    g_printerr ("Failed to register SIGXFSZ handler: %s\n",
                g_strerror (errno));
#endif

  if (pipe (sigterm_pipe_fds) != 0)
    g_printerr ("Failed to create SIGTERM pipe: %s\n",
                g_strerror (errno));

  channel = g_io_channel_unix_new (sigterm_pipe_fds[0]);
  g_io_channel_set_flags (channel, G_IO_FLAG_NONBLOCK, NULL);
  g_io_add_watch (channel, G_IO_IN, on_sigterm, NULL);
  g_io_channel_set_close_on_unref (channel, TRUE);
  g_io_channel_unref (channel);

  act.sa_handler = &sigterm_handler;
  if (sigaction (SIGTERM, &act, NULL) < 0)
    g_printerr ("Failed to register SIGTERM handler: %s\n",
		g_strerror (errno));

  if (g_getenv ("MARCO_VERBOSE"))
    meta_set_verbose (TRUE);
  if (g_getenv ("MARCO_DEBUG"))
    meta_set_debugging (TRUE);

  if (g_get_home_dir ())
    if (chdir (g_get_home_dir ()) < 0)
      meta_warning ("Could not change to home directory %s.\n",
                    g_get_home_dir ());

  meta_print_self_identity ();

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

  /* Parse command line arguments.*/
  meta_parse_options (&argc, &argv, &meta_args);

  meta_set_syncing (meta_args.sync || (g_getenv ("MARCO_SYNC") != NULL));

  if (meta_args.print_version)
    version ();

  meta_select_display (meta_args.display_name);

  if (meta_args.replace_wm)
    meta_set_replace_current_wm (TRUE);

  if (meta_args.save_file && meta_args.client_id)
    meta_fatal ("Can't specify both SM save file and SM client id\n");

  meta_main_loop = g_main_loop_new (NULL, FALSE);

  meta_ui_init (&argc, &argv);

  /* Load prefs */
  meta_prefs_init ();
  meta_prefs_add_listener (prefs_changed_callback, NULL);


#if 1

  for (i=0; i<G_N_ELEMENTS(log_domains); i++)
    g_log_set_handler (log_domains[i],
                       G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION,
                       log_handler, NULL);

#endif

  if (g_getenv ("MARCO_G_FATAL_WARNINGS") != NULL)
    g_log_set_always_fatal (G_LOG_LEVEL_MASK);

  meta_ui_set_current_theme (meta_prefs_get_theme (), FALSE);

  /* Try to find some theme that'll work if the theme preference
   * doesn't exist.  First try Simple (the default theme) then just
   * try anything in the themes directory.
   */
  if (!meta_ui_have_a_theme ())
    meta_ui_set_current_theme ("Simple", FALSE);

  if (!meta_ui_have_a_theme ())
    {
      const char *dir_entry = NULL;
      GError *err = NULL;
      GDir   *themes_dir = NULL;

      if (!(themes_dir = g_dir_open (MARCO_DATADIR"/themes", 0, &err)))
        {
          meta_fatal (_("Failed to scan themes directory: %s\n"), err->message);
          g_error_free (err);
        }
      else
        {
          while (((dir_entry = g_dir_read_name (themes_dir)) != NULL) &&
                 (!meta_ui_have_a_theme ()))
            {
              meta_ui_set_current_theme (dir_entry, FALSE);
            }

          g_dir_close (themes_dir);
        }
    }

  if (!meta_ui_have_a_theme ())
    meta_fatal (_("Could not find a theme! Be sure %s exists and contains the usual themes.\n"),
                MARCO_DATADIR"/themes");

  /* Connect to SM as late as possible - but before managing display,
   * or we might try to manage a window before we have the session
   * info
   */
  if (!meta_args.disable_sm)
    {
      if (meta_args.client_id == NULL)
        {
          const gchar *desktop_autostart_id;

          desktop_autostart_id = g_getenv ("DESKTOP_AUTOSTART_ID");

          if (desktop_autostart_id != NULL)
            meta_args.client_id = g_strdup (desktop_autostart_id);
        }

      /* Unset DESKTOP_AUTOSTART_ID in order to avoid child processes to
       * use the same client id. */
      g_unsetenv ("DESKTOP_AUTOSTART_ID");

      meta_session_init (meta_args.client_id, meta_args.save_file);
    }
  /* Free memory possibly allocated by the argument parsing which are
   * no longer needed.
   */
  g_free (meta_args.save_file);
  g_free (meta_args.display_name);
  g_free (meta_args.client_id);

  if (meta_args.composite || meta_args.no_composite)
    meta_prefs_set_force_compositing_manager (meta_args.composite);

  if (meta_args.no_force_fullscreen)
    meta_prefs_set_force_fullscreen (FALSE);

  if (!meta_display_open ())
    meta_exit (META_EXIT_ERROR);

  g_main_loop_run (meta_main_loop);

  meta_finalize ();

  if (meta_restart_after_quit)
    {
      GError *err;

      err = NULL;
      if (!g_spawn_async (NULL,
                          argv,
                          NULL,
                          G_SPAWN_SEARCH_PATH,
                          NULL,
                          NULL,
                          NULL,
                          &err))
        {
          meta_fatal (_("Failed to restart: %s\n"),
                      err->message);
          g_error_free (err); /* not reached anyhow */
          meta_exit_code = META_EXIT_ERROR;
        }
    }

  return meta_exit_code;
}
示例#23
0
static GtkWidget* pocketvox_setup_get_user_grid(PocketvoxSetup *setup)
{
	setup->priv = G_TYPE_INSTANCE_GET_PRIVATE (setup,
			TYPE_POCKETVOX_SETUP, PocketvoxSetupPrivate);
	PocketvoxSetupPrivate *priv = setup->priv;

	GtkWidget *grid 		 	= gtk_grid_new();
	GtkWidget *label_name 	 	= gtk_label_new(_("Your name"));
	GtkWidget *entry_name 		= gtk_entry_new();
	GtkWidget *label_keyword 	= gtk_label_new(_("Activation keyword"));
	GtkWidget *entry_keyword	= gtk_entry_new();
	GtkWidget *label_voice		= gtk_label_new(("Choose the espeak voice"));
	GtkWidget *combo_voice		= gtk_combo_box_text_new();

	gchar *voicesPath = (gchar *)g_getenv("ESPEAK_VOICES_PATH");

	g_return_val_if_fail(NULL != voicesPath, NULL);

	GDir *dir = g_dir_open(voicesPath, 0, NULL);
	const gchar *file ;

	while ((file = g_dir_read_name(dir)) != NULL)
	{
		gchar *path = g_strdup_printf("%s/%s", voicesPath, file);

		if(g_file_test(path, G_FILE_TEST_IS_DIR) == FALSE)
		{
			gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(combo_voice), g_strdup(file), g_strdup(file));
		}

		g_free(path);
	}

	g_dir_close(dir);

    gtk_misc_set_alignment(GTK_MISC(label_name),        0.0, 0.5);
    gtk_misc_set_alignment(GTK_MISC(label_keyword),     0.0, 0.5);
    gtk_misc_set_alignment(GTK_MISC(label_voice),       0.0, 0.5);
    gtk_widget_set_hexpand(label_voice,        			TRUE);
    gtk_widget_set_hexpand(label_name,        			TRUE);
    gtk_widget_set_hexpand(label_keyword,         		TRUE);

	g_settings_bind(priv->settings, "name", entry_name, "text", G_SETTINGS_BIND_DEFAULT);
	g_settings_bind(priv->settings, "keyword", entry_keyword, "text", G_SETTINGS_BIND_DEFAULT);
	g_settings_bind(priv->settings, "voice", combo_voice, "active-id", G_SETTINGS_BIND_DEFAULT);

    gtk_widget_set_tooltip_text(entry_name, _("What is your name ?"));
    gtk_widget_set_tooltip_text(entry_keyword, _("What is your activation keyword ?"));
    gtk_widget_set_tooltip_text(combo_voice, _("Choose the language"));

    gtk_grid_attach(GTK_GRID(grid), label_name, 		0, 0, 1, 1);
    gtk_grid_attach(GTK_GRID(grid), entry_name, 		1, 0, 2, 1);
    gtk_grid_attach(GTK_GRID(grid), label_keyword, 		0, 1, 1, 1);
    gtk_grid_attach(GTK_GRID(grid), entry_keyword, 		1, 1, 2, 1);
    gtk_grid_attach(GTK_GRID(grid), label_voice,		0, 2, 1, 1);
    gtk_grid_attach(GTK_GRID(grid), combo_voice,		1, 2, 2, 1);

    gtk_widget_show_all(grid);

    return grid;
}
static void
update_directory (GkmFileTracker *self, gboolean force_all, GHashTable *checks)
{
	UpdateDescendants uctx;
	struct stat sb;
	GError *err = NULL;
	const char *filename;
	gchar *file;
	GDir *dir;
	int ret, lasterr;

	g_assert (checks);
	g_assert (GKM_IS_FILE_TRACKER (self));

	if (!self->directory_path)
		return;

	if (stat (self->directory_path, &sb) < 0) {
		if (errno != ENOENT && errno != ENOTDIR && errno != EPERM)
			g_message ("couldn't stat directory: %s: %s",
			           self->directory_path, g_strerror (errno));
		return;
	}

	/* See if it was updated since last seen or not */
	if (!force_all && self->directory_mtime == sb.st_mtime) {

		uctx.checks = checks;
		uctx.tracker = self;

		/* Still need to check for individual file updates */
		g_hash_table_foreach (self->files, update_each_file, &uctx);
		return;
	}

	self->directory_mtime = sb.st_mtime;

	/* Actually list the directory */
	dir = g_dir_open (self->directory_path, 0, &err);
	if (dir == NULL) {
		if (errno != ENOENT && errno != ENOTDIR && errno != EPERM)
			g_message ("couldn't list keyrings at: %s: %s", self->directory_path,
			           egg_error_message (err));
		g_error_free (err);
		return;
	}

	while ((filename = g_dir_read_name (dir)) != NULL) {
		if (filename[0] == '.')
			continue;
		if (self->include && !g_pattern_match_string (self->include, filename))
			continue;
		if (self->exclude && g_pattern_match_string (self->exclude, filename))
			continue;

		file = g_build_filename (self->directory_path, filename, NULL);

		/* If we hadn't yet seen this, then add it */
		if (!g_hash_table_remove (checks, file)) {

			/* Get the last modified time for this one */
			ret = g_stat (file, &sb);
			lasterr = errno;

			/* Couldn't access the file */
			if (ret < 0) {
				g_message ("couldn't stat file: %s: %s", file, g_strerror (lasterr));

			} else {

				/* We don't do directories */
				if (!(sb.st_mode & S_IFDIR)) {
					g_hash_table_replace (self->files, g_strdup (file), GINT_TO_POINTER (sb.st_mtime));
					g_signal_emit (self, signals[FILE_ADDED], 0, file);
				}
			}

		/* Otherwise we already had it, see if it needs updating */
		} else {
			update_file (self, force_all, file);
		}

		g_free (file);
	}

	g_dir_close (dir);
}
/**
 * grub_choose_default_exec:
 * #directory   : the directory to search the script in
 * #script      : the file we should try to execute
 *
 * Searches in directory for script or script* and tries to execute it.
 */
gboolean
grub_choose_default_exec(const gchar * directory, const gchar * script, gboolean sync, GError **error)
{
  gchar * path;
#ifdef G_OS_WIN32
  GDir * dir;
  const gchar * fn;
  gchar * dirname, * basename;
#endif

  g_assert (error == NULL || *error == NULL);

  path = g_build_filename (directory, script, NULL);

#ifdef G_OS_WIN32
  dirname = g_path_get_dirname (path);
  basename = g_path_get_basename (path);
  g_free (path);

  dir = g_dir_open (dirname, 0, NULL);

  if (dir == NULL)
  {
    g_set_error (error, GCHD_ERROR,
                 GCHD_ERROR_FILE_NOT_FOUND,
                 "Could not find or open %s", dirname);
    return FALSE;
  }

  while ((fn = g_dir_read_name (dir)) != NULL)
  {
    DBG ("Considering file %s", fn);
    if (g_str_has_prefix (fn, basename))
    {
      DBG (" -> has prefix %s", basename);
      path = g_build_filename (dirname, fn, NULL);

      break;
    }
  }
  g_dir_close (dir);
#endif

  g_print ("Trying to execute with prefix %s\n", path);

  if (g_file_test (path, G_FILE_TEST_IS_EXECUTABLE))
  {
    gchar *argv[3];
    gboolean r;

#ifdef G_OS_WIN32
    if (g_str_has_suffix (path, ".vbs"))
    {
      argv[0] = "cscript.exe";
      argv[1] = path;
      argv[2] = NULL;
    }
    else
#endif
    {
      argv[0] = path;
      argv[1] = NULL;
    }

    if (sync) {
      r = g_spawn_sync (NULL,
                        argv,
                        NULL,
                        G_SPAWN_SEARCH_PATH,
                        NULL,
                        NULL,
                        NULL,
                        NULL, 
                        NULL, 
                        error);
    } else {
      r = g_spawn_async (NULL,
                         argv,
                         NULL,
                         G_SPAWN_SEARCH_PATH,
                         NULL,
                         NULL,
                         NULL,
                         error);
    }

    g_free (path);
    return r;
  }

  g_free (path);
  g_set_error (error, GCHD_ERROR,
                GCHD_ERROR_FILE_NOT_FOUND,
                "Could not find a script %s in %s", script, directory);
  return FALSE;
}
static void
daemon_read_extension_directory (GHashTable  *ifaces,
                                 const gchar *path)
{
        const gchar *name;
        GDir *dir;

        dir = g_dir_open (path, 0, NULL);
        if (!dir)
                return;

        while ((name = g_dir_read_name (dir))) {
                gchar *filename;
                gchar *symlink;

                /* Extensions are installed as normal D-Bus interface
                 * files with an annotation.
                 *
                 * D-Bus interface files are supposed to be installed in
                 * $(datadir)/dbus-1/interfaces/ but we don't want to
                 * scan all of the files there looking for interfaces
                 * that may contain our annotation.
                 *
                 * The solution is to install a symlink into a directory
                 * private to accountsservice and point it at the file,
                 * as installed in the usual D-Bus directory.
                 *
                 * This ensures compatibility with the future if we ever
                 * decide to check the interfaces directory directly
                 * (which might be a reasonable thing to do if we ever
                 * get an efficient cache of the contents of this
                 * directory).
                 *
                 * By introducing such a restrictive way of doing this
                 * now we ensure that everyone will do it in this
                 * forwards-compatible way.
                 */
                filename = g_build_filename (path, name, NULL);
                symlink = g_file_read_link (filename, NULL);

                if (!symlink) {
                        g_warning ("Found accounts service vendor extension file %s, but file must be a symlink to "
                                   "'../../dbus-1/interfaces/%s' for forwards-compatibility reasons.", filename, name);
                        g_free (filename);
                        continue;
                }

                /* Ensure it looks like "../../dbus-1/interfaces/${name}" */
                const gchar * const prefix = "../../dbus-1/interfaces/";
                if (g_str_has_prefix (symlink, prefix) && g_str_equal (symlink + strlen (prefix), name)) {
                        daemon_read_extension_file (ifaces, filename);
                }
                else {
                        g_warning ("Found accounts service vendor extension symlink %s, but it must be exactly "
                                   "equal to '../../dbus-1/interfaces/%s' for forwards-compatibility reasons.",
                                   filename, name);
                }

                g_free (filename);
                g_free (symlink);
        }

        g_dir_close (dir);
}
static gchar *
recursive_compare (struct stat *localtime_stat,
                   const gchar *localtime_content,
                   gsize localtime_content_len,
                   const gchar *file,
                   CompareFiles compare_func,
                   GHashTable *ical_zones,
                   gint deep_level,
                   gchar **fallback)
{
	struct stat file_stat;

	if (g_stat (file, &file_stat) != 0)
		return NULL;

	if (S_ISREG (file_stat.st_mode)) {
		if (compare_func (localtime_stat,
				  &file_stat,
				  localtime_content,
				  localtime_content_len,
				  file)) {
			gchar *tz = system_timezone_strip_path_if_valid (file);

			if (deep_level <= 1 || (ical_zones && g_hash_table_contains (ical_zones, tz))) {
				update_fallback (fallback, tz, ical_zones);
				return NULL;
			}

			if (ical_zones && !g_hash_table_contains (ical_zones, tz)) {
				g_free (tz);
				return NULL;
			}

			return tz;
		} else
			return NULL;
	} else if (S_ISDIR (file_stat.st_mode)) {
		GDir       *dir = NULL;
		gchar       *ret = NULL;
		const gchar *subfile = NULL;
		gchar       *subpath = NULL;

		dir = g_dir_open (file, 0, NULL);
		if (dir == NULL)
			return NULL;

		while ((subfile = g_dir_read_name (dir)) != NULL) {
			subpath = g_build_filename (file, subfile, NULL);

			ret = recursive_compare (
				localtime_stat,
				localtime_content,
				localtime_content_len,
				subpath,
				compare_func,
				ical_zones,
				deep_level + 1,
				fallback);

			g_free (subpath);

			if (ret != NULL)
				break;
		}

		g_dir_close (dir);

		return ret;
	}

	return NULL;
}
示例#28
0
/**
 * @internal Scan a particular directory for plugins to load
 * @param[in] dir Absolute path to plugins directory
 * @return TRUE if directory successfully scanned for plugins
 */
static gboolean
xmms_plugin_scan_directory (const gchar *dir)
{
	GDir *d;
	const char *name;
	gchar *path;
	gchar *temp;
	gchar *pattern;
	GModule *module;
	gpointer sym;

	temp = get_module_ext (dir);

	XMMS_DBG ("Scanning directory for plugins (%s)", temp);

	pattern = g_path_get_basename (temp);

	g_free (temp);

	d = g_dir_open (dir, 0, NULL);
	if (!d) {
		xmms_log_error ("Failed to open plugin directory (%s)", dir);
		return FALSE;
	}

	while ((name = g_dir_read_name (d))) {

		if (!g_pattern_match_simple (pattern, name))
			continue;

		path = g_build_filename (dir, name, NULL);
		if (!g_file_test (path, G_FILE_TEST_IS_REGULAR)) {
			g_free (path);
			continue;
		}

		XMMS_DBG ("Trying to load file: %s", path);
		module = g_module_open (path, G_MODULE_BIND_LOCAL);
		if (!module) {
			xmms_log_error ("Failed to open plugin %s: %s",
			                path, g_module_error ());
			g_free (path);
			continue;
		}

		if (!g_module_symbol (module, "XMMS_PLUGIN_DESC", &sym)) {
			xmms_log_error ("Failed to find plugin header in %s", path);
			g_module_close (module);
			g_free (path);
			continue;
		}
		g_free (path);

		if (!xmms_plugin_load ((const xmms_plugin_desc_t *) sym, module)) {
			g_module_close (module);
		}
	}

	g_dir_close (d);
	g_free (pattern);

	return TRUE;
}
示例#29
0
/**
 * mono_process_list:
 * @size: a pointer to a location where the size of the returned array is stored
 *
 * Return an array of pid values for the processes currently running on the system.
 * The size of the array is stored in @size.
 */
gpointer*
mono_process_list (int *size)
{
#if USE_SYSCTL
	int res, i;
#ifdef KERN_PROC2
	int mib [6];
	size_t data_len = sizeof (struct kinfo_proc2) * 400;
	struct kinfo_proc2 *processes = malloc (data_len);
#else
	int mib [4];
	size_t data_len = sizeof (struct kinfo_proc) * 400;
	struct kinfo_proc *processes = malloc (data_len);
#endif /* KERN_PROC2 */
	void **buf = NULL;

	if (size)
		*size = 0;
	if (!processes)
		return NULL;

#ifdef KERN_PROC2
	mib [0] = CTL_KERN;
	mib [1] = KERN_PROC2;
	mib [2] = KERN_PROC_ALL;
	mib [3] = 0;
	mib [4] = sizeof(struct kinfo_proc2);
	mib [5] = 400; /* XXX */

	res = sysctl (mib, 6, processes, &data_len, NULL, 0);
#else
	mib [0] = CTL_KERN;
	mib [1] = KERN_PROC;
	mib [2] = KERN_PROC_ALL;
	mib [3] = 0;
	
	res = sysctl (mib, 4, processes, &data_len, NULL, 0);
#endif /* KERN_PROC2 */

	if (res < 0) {
		free (processes);
		return NULL;
	}
#ifdef KERN_PROC2
	res = data_len/sizeof (struct kinfo_proc2);
#else
	res = data_len/sizeof (struct kinfo_proc);
#endif /* KERN_PROC2 */
	buf = g_realloc (buf, res * sizeof (void*));
	for (i = 0; i < res; ++i)
		buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member);
	free (processes);
	if (size)
		*size = res;
	return buf;
#elif defined(__HAIKU__)
	/* FIXME: Add back the code from 9185fcc305e43428d0f40f3ee37c8a405d41c9ae */
	g_assert_not_reached ();
	return NULL;
#else
	const char *name;
	void **buf = NULL;
	int count = 0;
	int i = 0;
	GDir *dir = g_dir_open ("/proc/", 0, NULL);
	if (!dir) {
		if (size)
			*size = 0;
		return NULL;
	}
	while ((name = g_dir_read_name (dir))) {
		int pid;
		char *nend;
		pid = strtol (name, &nend, 10);
		if (pid <= 0 || nend == name || *nend)
			continue;
		if (i >= count) {
			if (!count)
				count = 16;
			else
				count *= 2;
			buf = g_realloc (buf, count * sizeof (void*));
		}
		buf [i++] = GINT_TO_POINTER (pid);
	}
	g_dir_close (dir);
	if (size)
		*size = i;
	return buf;
#endif
}
示例#30
0
文件: gam_kqueue.c 项目: GNOME/gamin
static void
gam_kqueue_sub_monitor_enable_notification (SubMonitor *smon,
					    SubMonitorFlags flags)
{
  Monitor *mon = MONITOR(smon);
  gboolean exists;

  /* we first send CREATED or EXISTS/DELETED+ENDEXISTS events */

  if ((flags & SUB_MONITOR_WAS_MISSING) != 0)
    exists = TRUE;
  else
    {
      struct stat sb;

      exists = lstat(mon->pathname, &sb) >= 0;
      flags |= (exists && (sb.st_mode & S_IFDIR) != 0) ? MONITOR_ISDIR : MONITOR_ISNOTDIR;
    }

  if (exists)
    {
      GaminEventType gevent;

      gevent = (flags & SUB_MONITOR_WAS_MISSING) != 0 ? GAMIN_EVENT_CREATED : GAMIN_EVENT_EXISTS;
      gam_kqueue_sub_monitor_emit_event(smon, gevent, flags);

      if (smon->isdir && (flags & MONITOR_ISDIR) != 0)
	{
	  GDir *dir;
	  GError *err = NULL;
	  
	  dir = g_dir_open(mon->pathname, 0, &err);
	  if (dir)
	    {
	      const char *filename;
	      
	      while ((filename = g_dir_read_name(dir)))
		{
		  FileMonitor *fmon;
		  FileMonitorFlags fmon_flags;
		  
		  fmon = gam_kqueue_file_monitor_new(smon, filename, &fmon_flags);
		  gam_kqueue_file_monitor_emit_event(fmon, gevent, fmon_flags);
		}
	      
	      g_dir_close(dir);
	    }
	  else
	    {
	      GAM_DEBUG(DEBUG_INFO, "unable to open directory %s: %s\n", mon->pathname, err->message);
	      g_error_free(err);
	    }
	}

      if ((flags & SUB_MONITOR_WAS_MISSING) == 0)
	gam_kqueue_sub_monitor_emit_event(smon, GAMIN_EVENT_ENDEXISTS, flags);
    }
  else
    {
      gam_kqueue_sub_monitor_emit_event(smon, GAMIN_EVENT_DELETED, flags);
      gam_kqueue_sub_monitor_emit_event(smon, GAMIN_EVENT_ENDEXISTS, flags);

      return;
    }
    
  /* then we enable kqueue notification, falling back to poll if necessary */

  if (! gam_kqueue_monitor_enable_kqueue(mon))
    gam_kqueue_sub_monitor_set_unsupported(smon);
}