Esempio n. 1
0
static void
log_io_error (GError * error, gchar * event)
{
  GST_WARNING ("iochannel error when reading '%s': %s", event, error->message);
  g_error_free (error);
}
Esempio n. 2
0
/*
 * the DBus.Tracker.Properties1 interface returns a list of strings
 * where each selected item brings up both its URI and its Caja
 * mime type.
 *
 * We return to the caller a GList of NASelectedInfo objects
 */
static GList *
targets_from_selection( void )
{
	static const gchar *thisfn = "caja_actions_run_targets_from_selection";
	GList *selection;
	GError *error;
	gchar **paths;

	g_debug( "%s", thisfn );

	selection = NULL;
	error = NULL;
	paths = NULL;

#ifdef HAVE_GDBUS
	GDBusObjectManager *manager;
	gchar *name_owner;
	GDBusObject *object;
	GDBusInterface *iface;

	manager = na_tracker_object_manager_client_new_for_bus_sync(
			G_BUS_TYPE_SESSION,
			G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE,
			CAJA_ACTIONS_DBUS_SERVICE,
			CAJA_ACTIONS_DBUS_TRACKER_PATH,
			NULL,
			&error );

	if( !manager ){
		g_printerr( "%s: unable to allocate an ObjectManagerClient: %s\n", thisfn, error->message );
		g_error_free( error );
		return( NULL );
	}

	name_owner = g_dbus_object_manager_client_get_name_owner( G_DBUS_OBJECT_MANAGER_CLIENT( manager ));
	g_debug( "%s: name_owner=%s", thisfn, name_owner );
	g_free( name_owner );

	object = g_dbus_object_manager_get_object( manager, CAJA_ACTIONS_DBUS_TRACKER_PATH "/0" );
	if( !object ){
		g_printerr( "%s: unable to get object at %s path\n", thisfn, CAJA_ACTIONS_DBUS_TRACKER_PATH "/0" );
		g_object_unref( manager );
		return( NULL );
	}

	iface = g_dbus_object_get_interface( object, CAJA_ACTIONS_DBUS_TRACKER_IFACE );
	if( !iface ){
		g_printerr( "%s: unable to get %s interface\n", thisfn, CAJA_ACTIONS_DBUS_TRACKER_IFACE );
		g_object_unref( object );
		g_object_unref( manager );
		return( NULL );
	}

	/* note that @iface is really a GDBusProxy instance
	 * and additionally also a NATrackerProperties1 instance
	 */
	na_tracker_properties1_call_get_selected_paths_sync(
			NA_TRACKER_PROPERTIES1( iface ),
			&paths,
			NULL,
			&error );

#else
# ifdef HAVE_DBUS_GLIB
	DBusGConnection *connection;
	DBusGProxy *proxy = NULL;

	connection = dbus_g_bus_get( DBUS_BUS_SESSION, &error );
	if( !connection ){
		if( error ){
			g_printerr( _( "Error: unable to get a connection to session DBus: %s" ), error->message );
			g_error_free( error );
		}
		return( NULL );
	}
	g_debug( "%s: connection is ok", thisfn );

	proxy = dbus_g_proxy_new_for_name( connection,
			CAJA_ACTIONS_DBUS_SERVICE,
			CAJA_ACTIONS_DBUS_TRACKER_PATH "/0",
			CAJA_ACTIONS_DBUS_TRACKER_IFACE );

	if( !proxy ){
		g_printerr( _( "Error: unable to get a proxy on %s service" ), CAJA_ACTIONS_DBUS_SERVICE );
		dbus_g_connection_unref( connection );
		return( NULL );
	}
	g_debug( "%s: proxy is ok", thisfn );

	if( !dbus_g_proxy_call( proxy, "GetSelectedPaths", &error,
			G_TYPE_INVALID,
			G_TYPE_STRV, &paths, G_TYPE_INVALID )){

		g_printerr( _( "Error on GetSelectedPaths call: %s" ), error->message );
		g_error_free( error );
		/* TODO: unref proxy */
		dbus_g_connection_unref( connection );
		return( NULL );
	}
	g_debug( "%s: function call is ok", thisfn );

	/* TODO: unref proxy */
	dbus_g_connection_unref( connection );
# endif
#endif

	selection = get_selection_from_strv(( const gchar ** ) paths, TRUE );

	g_strfreev( paths );

	return( selection );
}
Esempio n. 3
0
G_MODULE_EXPORT gboolean
tracker_extract_get_metadata (TrackerExtractInfo *info)
{
    TrackerConfig *config;
    GTime creation_date;
    GError *error = NULL;
    TrackerResource *metadata;
    TrackerXmpData *xd = NULL;
    PDFData pd = { 0 }; /* actual data */
    PDFData md = { 0 }; /* for merging */
    PopplerDocument *document;
    gchar *xml = NULL;
    gchar *content, *uri;
    guint n_bytes;
    GPtrArray *keywords;
    guint i;
    GFile *file;
    gchar *filename;
    int fd;
    gchar *contents = NULL;
    gsize len;
    struct stat st;

    file = tracker_extract_info_get_file (info);
    filename = g_file_get_path (file);

    fd = tracker_file_open_fd (filename);

    if (fd == -1) {
        g_warning ("Could not open pdf file '%s': %s\n",
                   filename,
                   g_strerror (errno));
        g_free (filename);
        return FALSE;
    }

    if (fstat (fd, &st) == -1) {
        g_warning ("Could not fstat pdf file '%s': %s\n",
                   filename,
                   g_strerror (errno));
        close (fd);
        g_free (filename);
        return FALSE;
    }

    if (st.st_size == 0) {
        contents = NULL;
        len = 0;
    } else {
        contents = (gchar *) mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
        if (contents == NULL || contents == MAP_FAILED) {
            g_warning ("Could not mmap pdf file '%s': %s\n",
                       filename,
                       g_strerror (errno));
            close (fd);
            g_free (filename);
            return FALSE;
        }
        len = st.st_size;
    }

    g_free (filename);
    uri = g_file_get_uri (file);

    document = poppler_document_new_from_data (contents, len, NULL, &error);

    if (error) {
        if (error->code == POPPLER_ERROR_ENCRYPTED) {
            metadata = tracker_resource_new (NULL);

            tracker_resource_add_uri (metadata, "rdf:type", "nfo:PaginatedTextDocument");
            tracker_resource_set_boolean (metadata, "nfo:isContentEncrypted", TRUE);

            tracker_extract_info_set_resource (info, metadata);
            g_object_unref (metadata);

            g_error_free (error);
            g_free (uri);
            close (fd);

            return TRUE;
        } else {
            g_warning ("Couldn't create PopplerDocument from uri:'%s', %s",
                       uri,
                       error->message ? error->message : "no error given");

            g_error_free (error);
            g_free (uri);
            close (fd);

            return FALSE;
        }
    }

    if (!document) {
        g_warning ("Could not create PopplerDocument from uri:'%s', "
                   "NULL returned without an error",
                   uri);
        g_free (uri);
        close (fd);
        return FALSE;
    }

    metadata = tracker_resource_new (NULL);
    tracker_resource_add_uri (metadata, "rdf:type", "nfo:PaginatedTextDocument");

    g_object_get (document,
                  "title", &pd.title,
                  "author", &pd.author,
                  "subject", &pd.subject,
                  "keywords", &pd.keywords,
                  "creation-date", &creation_date,
                  "metadata", &xml,
                  NULL);

    if (creation_date > 0) {
        pd.creation_date = tracker_date_to_string ((time_t) creation_date);
    }

    keywords = g_ptr_array_new_with_free_func ((GDestroyNotify) g_free);

    if (xml && *xml &&
            (xd = tracker_xmp_new (xml, strlen (xml), uri)) != NULL) {
        /* The casts here are well understood and known */
        md.title = (gchar *) tracker_coalesce_strip (4, pd.title, xd->title, xd->title2, xd->pdf_title);
        md.subject = (gchar *) tracker_coalesce_strip (2, pd.subject, xd->subject);
        md.date = (gchar *) tracker_coalesce_strip (3, pd.creation_date, xd->date, xd->time_original);
        md.author = (gchar *) tracker_coalesce_strip (2, pd.author, xd->creator);

        write_pdf_data (md, metadata, keywords);

        if (xd->keywords) {
            tracker_keywords_parse (keywords, xd->keywords);
        }

        if (xd->pdf_keywords) {
            tracker_keywords_parse (keywords, xd->pdf_keywords);
        }

        if (xd->publisher) {
            TrackerResource *publisher = tracker_extract_new_contact (xd->publisher);
            tracker_resource_set_relation (metadata, "nco:publisher", publisher);
            g_object_unref (publisher);
        }

        if (xd->type) {
            tracker_resource_set_string (metadata, "dc:type", xd->type);
        }

        if (xd->format) {
            tracker_resource_set_string (metadata, "dc:format", xd->format);
        }

        if (xd->identifier) {
            tracker_resource_set_string (metadata, "dc:identifier", xd->identifier);
        }

        if (xd->source) {
            tracker_resource_set_string (metadata, "dc:source", xd->source);
        }

        if (xd->language) {
            tracker_resource_set_string (metadata, "dc:language", xd->language);
        }

        if (xd->relation) {
            tracker_resource_set_string (metadata, "dc:relation", xd->relation);
        }

        if (xd->coverage) {
            tracker_resource_set_string (metadata, "dc:coverage", xd->coverage);
        }

        if (xd->license) {
            tracker_resource_set_string (metadata, "nie:license", xd->license);
        }

        if (xd->make || xd->model) {
            TrackerResource *equipment = tracker_extract_new_equipment (xd->make, xd->model);
            tracker_resource_set_relation (metadata, "nfo:equipment", equipment);
            g_object_unref (equipment);
        }

        if (xd->orientation) {
            tracker_resource_set_string (metadata, "nfo:orientation", xd->orientation);
        }

        if (xd->rights) {
            tracker_resource_set_string (metadata, "nie:copyright", xd->rights);
        }

        if (xd->white_balance) {
            tracker_resource_set_string (metadata, "nmm:whiteBalance", xd->white_balance);
        }

        if (xd->fnumber) {
            gdouble value;

            value = g_strtod (xd->fnumber, NULL);
            tracker_resource_set_double (metadata, "nmm:fnumber", value);
        }

        if (xd->flash) {
            tracker_resource_set_string (metadata, "nmm:flash", xd->flash);
        }

        if (xd->focal_length) {
            gdouble value;

            value = g_strtod (xd->focal_length, NULL);
            tracker_resource_set_double (metadata, "nmm:focalLength", value);
        }

        /* Question: Shouldn't xd->Artist be merged with md.author instead? */

        if (xd->artist || xd->contributor) {
            TrackerResource *artist;
            const gchar *artist_name;

            artist_name = tracker_coalesce_strip (2, xd->artist, xd->contributor);

            artist = tracker_extract_new_contact (artist_name);

            tracker_resource_set_relation (metadata, "nco:contributor", artist);

            g_object_unref (artist);
        }

        if (xd->exposure_time) {
            gdouble value;

            value = g_strtod (xd->exposure_time, NULL);
            tracker_resource_set_double (metadata, "nmm:exposureTime", value);
        }

        if (xd->iso_speed_ratings) {
            gdouble value;

            value = g_strtod (xd->iso_speed_ratings, NULL);
            tracker_resource_set_double (metadata, "nmm:isoSpeed", value);
        }

        if (xd->description) {
            tracker_resource_set_string (metadata, "nie:description", xd->description);
        }

        if (xd->metering_mode) {
            tracker_resource_set_string (metadata, "nmm:meteringMode", xd->metering_mode);
        }

        if (xd->address || xd->state || xd->country || xd->city ||
                xd->gps_altitude || xd->gps_latitude || xd-> gps_longitude) {

            TrackerResource *location = tracker_extract_new_location (xd->address,
                                        xd->state, xd->city, xd->country, xd->gps_altitude,
                                        xd->gps_latitude, xd->gps_longitude);

            tracker_resource_set_relation (metadata, "slo:location", location);

            g_object_unref (location);
        }

        if (xd->regions) {
            tracker_xmp_apply_regions_to_resource (metadata, xd);
        }

        tracker_xmp_free (xd);
    } else {
        /* So if we are here we have NO XMP data and we just
         * write what we know from Poppler.
         */
        write_pdf_data (pd, metadata, keywords);
    }

    for (i = 0; i < keywords->len; i++) {
        TrackerResource *tag;
        const gchar *p;

        p = g_ptr_array_index (keywords, i);
        tag = tracker_extract_new_tag (p);

        tracker_resource_add_relation (metadata, "nao:hasTag", tag);

        g_object_unref (tag);
    }
    g_ptr_array_free (keywords, TRUE);

    tracker_resource_set_int64 (metadata, "nfo:pageCount", poppler_document_get_n_pages(document));

    config = tracker_main_get_config ();
    n_bytes = tracker_config_get_max_bytes (config);
    content = extract_content_text (document, n_bytes);

    if (content) {
        tracker_resource_set_string (metadata, "nie:plainTextContent", content);
        g_free (content);
    }

    read_outline (document, metadata);

    g_free (xml);
    g_free (pd.keywords);
    g_free (pd.title);
    g_free (pd.subject);
    g_free (pd.creation_date);
    g_free (pd.author);
    g_free (pd.date);
    g_free (uri);

    g_object_unref (document);

    if (contents) {
        munmap (contents, len);
    }

    close (fd);

    tracker_extract_info_set_resource (info, metadata);
    g_object_unref (metadata);

    return TRUE;
}
Esempio n. 4
0
static void
git_status_pane_init (GitStatusPane *self)
{
	gchar *objects[] = {"status_pane",
						"status_model",
						NULL};
	GError *error = NULL;
	GtkTreeView *status_view;
	GtkTreeViewColumn *status_column;
	GtkCellRenderer *selected_renderer;
	GtkCellRenderer *status_icon_renderer;
	GtkCellRenderer *status_name_renderer;
	GtkCellRenderer *path_renderer;
	GtkWidget *refresh_button;
	GtkWidget *select_all_button;
	GtkWidget *clear_button;

	self->priv = g_new0 (GitStatusPanePriv, 1);
	self->priv->builder = gtk_builder_new ();
	self->priv->selected_commit_items = g_hash_table_new_full (g_str_hash, 
	                                                           g_str_equal,
	                                                           g_free, 
	                                                           NULL);
	self->priv->selected_not_updated_items = g_hash_table_new_full (g_str_hash,
	                                                                g_str_equal,
	                                                                g_free,
	                                                                NULL);
	
	if (!gtk_builder_add_objects_from_file (self->priv->builder, BUILDER_FILE, 
	                                        objects, 
	                                        &error))
	{
		g_warning ("Couldn't load builder file: %s", error->message);
		g_error_free (error);
	}

	status_view = GTK_TREE_VIEW (gtk_builder_get_object (self->priv->builder,
	                                                     "status_view"));
	status_column = GTK_TREE_VIEW_COLUMN (gtk_builder_get_object (self->priv->builder,
	                                                              "status_column"));
	selected_renderer = GTK_CELL_RENDERER (gtk_builder_get_object (self->priv->builder,
	                                   							   "selected_renderer"));
	status_icon_renderer = GTK_CELL_RENDERER (gtk_builder_get_object (self->priv->builder,
	                                                                  "status_icon_renderer"));
	status_name_renderer = GTK_CELL_RENDERER (gtk_builder_get_object (self->priv->builder,
	                                                                  "status_name_renderer"));
	path_renderer = GTK_CELL_RENDERER (gtk_builder_get_object (self->priv->builder,
	                                                           "path_renderer"));
	refresh_button = GTK_WIDGET (gtk_builder_get_object (self->priv->builder,
	                                                     "refresh_button"));
	select_all_button = GTK_WIDGET (gtk_builder_get_object (self->priv->builder,
	                                                        "select_all_button"));
	clear_button = GTK_WIDGET (gtk_builder_get_object (self->priv->builder,
	                                                   "clear_button"));
										   
	gtk_tree_view_column_set_cell_data_func (status_column, selected_renderer,
	                                         (GtkTreeCellDataFunc) selected_renderer_data_func,
	                                         NULL, NULL);

	gtk_tree_view_column_set_cell_data_func (status_column, status_icon_renderer,
	                                         (GtkTreeCellDataFunc) status_icon_renderer_data_func,
	                                         NULL, NULL);

	gtk_tree_view_column_set_cell_data_func (status_column, status_name_renderer,
	                                         (GtkTreeCellDataFunc) status_name_renderer_data_func,
	                                         NULL, NULL);

	gtk_tree_view_column_set_cell_data_func (status_column, path_renderer,
	                                         (GtkTreeCellDataFunc) path_renderer_data_func,
	                                         NULL, NULL);

	g_signal_connect (G_OBJECT (selected_renderer), "toggled",
	                  G_CALLBACK (on_selected_renderer_toggled),
	                  self);

	g_signal_connect_swapped (G_OBJECT (refresh_button), "clicked",
	                          G_CALLBACK (anjuta_dock_pane_refresh),
	                          self);

	g_signal_connect (G_OBJECT (select_all_button), "clicked",
	                  G_CALLBACK (on_select_all_button_clicked),
	                  self);

	g_signal_connect (G_OBJECT (clear_button), "clicked",
	                  G_CALLBACK (on_clear_button_clicked),
	                  self);

	/* DND */
	gtk_drag_dest_set (GTK_WIDGET (status_view), 
	                   GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT, 
	                   drag_target_targets,
	                   G_N_ELEMENTS (drag_target_targets), 
	                   GDK_ACTION_COPY | GDK_ACTION_MOVE);
	
	g_signal_connect (G_OBJECT (status_view), "drag-drop",
	                  G_CALLBACK (on_status_view_drag_drop),
	                  self);

	g_signal_connect (G_OBJECT (status_view), "drag-data-received",
	                  G_CALLBACK (on_status_view_drag_data_received),
	                  self);

	/* Popup menus */
	g_signal_connect (G_OBJECT (status_view), "button-press-event",
	                  G_CALLBACK (on_status_view_button_press_event),
	                  self);
}
Esempio n. 5
0
static void
on_depth_frame (GFreenectDevice *kinect, gpointer user_data)
{
  gboolean smoothing_enabled;
  gint width, height;
  gint dimension_factor;
  guchar *grayscale_buffer;
  guint16 *depth;
  BufferInfo *buffer_info;
  gsize len;
  GError *error = NULL;
  GFreenectFrameMode frame_mode;
  ClutterContent *content;

  depth = (guint16 *) gfreenect_device_get_depth_frame_raw (kinect,
                                                            &len,
                                                            &frame_mode);

  width = frame_mode.width;
  height = frame_mode.height;

  g_object_get (skeleton, "dimension-reduction", &dimension_factor, NULL);

  buffer_info = process_buffer (depth,
                                width,
                                height,
                                dimension_factor,
                                THRESHOLD_BEGIN,
                                THRESHOLD_END);

  skeltrack_skeleton_track_joints (skeleton,
                                   buffer_info->reduced_buffer,
                                   buffer_info->reduced_width,
                                   buffer_info->reduced_height,
                                   NULL,
                                   on_track_joints,
                                   buffer_info);


  content = clutter_actor_get_content (depth_tex);
  if (!SHOW_SKELETON)
    {
      grayscale_buffer = create_grayscale_buffer (buffer_info,
                                                  dimension_factor);

      if (depth_image == NULL)
        depth_image = clutter_image_new ();

      /* ref because we don't want it to be freed */
      if (depth_canvas == content)
        g_object_ref (depth_canvas);

      clutter_actor_set_content (depth_tex, depth_image);
      if (! clutter_image_set_data (CLUTTER_IMAGE (depth_image),
                                    grayscale_buffer,
                                    COGL_PIXEL_FORMAT_RGB_888,
                                    width, height,
                                    0,
                                    &error))
        {
          g_debug ("Error setting texture area: %s", error->message);
          g_error_free (error);
        }
      g_slice_free1 (width * height * sizeof (guchar) * 3, grayscale_buffer);
    }
  else {
    /* ref because we don't want it to be freed */
    if (depth_image && depth_image == content)
      g_object_ref (depth_image);

    clutter_actor_set_content (depth_tex, depth_canvas);
  }
}
Esempio n. 6
0
/**
 * as_pool_load_appstream:
 *
 * Load fresh metadata from AppStream directories.
 */
static gboolean
as_pool_load_appstream (AsPool *pool, GError **error)
{
	GPtrArray *cpts;
	g_autoptr(GPtrArray) merge_cpts = NULL;
	guint i;
	gboolean ret;
	g_autoptr(AsMetadata) metad = NULL;
	g_autoptr(GPtrArray) mdata_files = NULL;
	GError *tmp_error = NULL;
	AsPoolPrivate *priv = GET_PRIVATE (pool);

	/* see if we can use the caches */
	if (!as_pool_metadata_changed (pool)) {
		g_autofree gchar *fname = NULL;
		g_debug ("Caches are up to date.");

		if (as_flags_contains (priv->cache_flags, AS_CACHE_FLAG_USE_SYSTEM)) {
			g_debug ("Using cached data.");

			fname = g_strdup_printf ("%s/%s.gvz", priv->sys_cache_path, priv->locale);
			if (g_file_test (fname, G_FILE_TEST_EXISTS)) {
				return as_pool_load_cache_file (pool, fname, error);
			} else {
				g_debug ("Missing cache for language '%s', attempting to load fresh data.", priv->locale);
			}
		} else {
			g_debug ("Not using system cache.");
		}
	}

	/* prepare metadata parser */
	metad = as_metadata_new ();
	as_metadata_set_format_style (metad, AS_FORMAT_STYLE_COLLECTION);
	as_metadata_set_locale (metad, priv->locale);

	/* find AppStream metadata */
	ret = TRUE;
	mdata_files = g_ptr_array_new_with_free_func (g_free);

	/* find XML data */
	for (i = 0; i < priv->xml_dirs->len; i++) {
		const gchar *xml_path = (const gchar *) g_ptr_array_index (priv->xml_dirs, i);
		guint j;

		if (g_file_test (xml_path, G_FILE_TEST_IS_DIR)) {
			g_autoptr(GPtrArray) xmls = NULL;

			g_debug ("Searching for data in: %s", xml_path);
			xmls = as_utils_find_files_matching (xml_path, "*.xml*", FALSE, NULL);
			if (xmls != NULL) {
				for (j = 0; j < xmls->len; j++) {
					const gchar *val;
					val = (const gchar *) g_ptr_array_index (xmls, j);
					g_ptr_array_add (mdata_files,
								g_strdup (val));
				}
			}
		}
	}

	/* find YAML metadata */
	for (i = 0; i < priv->yaml_dirs->len; i++) {
		const gchar *yaml_path = (const gchar *) g_ptr_array_index (priv->yaml_dirs, i);
		guint j;

		if (g_file_test (yaml_path, G_FILE_TEST_IS_DIR)) {
			g_autoptr(GPtrArray) yamls = NULL;

			g_debug ("Searching for data in: %s", yaml_path);
			yamls = as_utils_find_files_matching (yaml_path, "*.yml*", FALSE, NULL);
			if (yamls != NULL) {
				for (j = 0; j < yamls->len; j++) {
					const gchar *val;
					val = (const gchar *) g_ptr_array_index (yamls, j);
					g_ptr_array_add (mdata_files,
								g_strdup (val));
				}
			}
		}
	}

	/* parse the found data */
	for (i = 0; i < mdata_files->len; i++) {
		g_autoptr(GFile) infile = NULL;
		const gchar *fname;

		fname = (const gchar*) g_ptr_array_index (mdata_files, i);
		g_debug ("Reading: %s", fname);

		infile = g_file_new_for_path (fname);
		if (!g_file_query_exists (infile, NULL)) {
			g_warning ("Metadata file '%s' does not exist.", fname);
			continue;
		}

		as_metadata_parse_file (metad,
					infile,
					AS_FORMAT_KIND_UNKNOWN,
					&tmp_error);
		if (tmp_error != NULL) {
			g_debug ("WARNING: %s", tmp_error->message);
			g_error_free (tmp_error);
			tmp_error = NULL;
			ret = FALSE;
		}
	}

	/* add found components to the metadata pool */
	cpts = as_metadata_get_components (metad);
	merge_cpts = g_ptr_array_new ();
	for (i = 0; i < cpts->len; i++) {
		AsComponent *cpt = AS_COMPONENT (g_ptr_array_index (cpts, i));

		/* TODO: We support only system components at time */
		as_component_set_scope (cpt, AS_COMPONENT_SCOPE_SYSTEM);

		/* deal with merge-components later */
		if (as_component_get_merge_kind (cpt) != AS_MERGE_KIND_NONE) {
			g_ptr_array_add (merge_cpts, cpt);
			continue;
		}

		as_pool_add_component (pool, cpt, &tmp_error);
		if (tmp_error != NULL) {
			g_debug ("Metadata ignored: %s", tmp_error->message);
			g_error_free (tmp_error);
			tmp_error = NULL;
		}
	}

	/* we need to merge the merge-components into the pool last, so the merge process can fetch
	 * all components with matching IDs from the pool */
	for (i = 0; i < merge_cpts->len; i++) {
		AsComponent *mcpt = AS_COMPONENT (g_ptr_array_index (merge_cpts, i));

		as_pool_add_component (pool, mcpt, &tmp_error);
		if (tmp_error != NULL) {
			g_debug ("Merge component ignored: %s", tmp_error->message);
			g_error_free (tmp_error);
			tmp_error = NULL;
		}
	}

	return ret;
}
Esempio n. 7
0
static void
add_clicked_cb (GtkWidget  *widget,
		DialogData *data)
{
	FrWindow   *window = data->window;
	char       *archive_name;
	char       *archive_dir;
	char       *archive_file;
	char       *tmp;
	const char *archive_ext;
	gboolean    do_not_add = FALSE;
	GError     *error = NULL;

	data->add_clicked = TRUE;

	/* Collect data */

	archive_name = g_uri_escape_string (gtk_entry_get_text (GTK_ENTRY (data->a_add_to_entry)), NULL, FALSE);

	/* Check whether the user entered a valid archive name. */

	if ((archive_name == NULL) || (*archive_name == '\0')) {
		GtkWidget *d;

		d = _gtk_error_dialog_new (GTK_WINDOW (window),
					   GTK_DIALOG_DESTROY_WITH_PARENT,
					   NULL,
					   _("Could not create the archive"),
					   "%s",
					   _("You have to specify an archive name."));
		gtk_dialog_run (GTK_DIALOG (d));
		gtk_widget_destroy (GTK_WIDGET (d));
		g_free (archive_name);

		return;
	}
	else if (strchrs (archive_name, BAD_CHARS)) {
		GtkWidget *d;
		char      *utf8_name = g_filename_display_name (archive_name);

		d = _gtk_error_dialog_new (GTK_WINDOW (window),
					   GTK_DIALOG_DESTROY_WITH_PARENT,
					   NULL,
					   _("Could not create the archive"),
					   _("The name \"%s\" is not valid because it cannot contain the characters: %s\n\n%s"),
					   utf8_name,
					   BAD_CHARS,
					   _("Please use a different name."));
		gtk_dialog_run (GTK_DIALOG (d));
		gtk_widget_destroy (GTK_WIDGET (d));

		g_free (utf8_name);
		g_free (archive_name);

		return;
	}

	/* Check directory existence. */

	archive_dir = gtk_file_chooser_get_uri (GTK_FILE_CHOOSER (data->a_location_filechooserbutton));
	if (archive_dir == NULL) {
		g_free (archive_dir);
		g_free (archive_name);
		return;
	}

	if (! check_permissions (archive_dir, R_OK|W_OK|X_OK)) {
		GtkWidget  *d;

		d = _gtk_error_dialog_new (GTK_WINDOW (window),
					   GTK_DIALOG_DESTROY_WITH_PARENT,
					   NULL,
					   _("Could not create the archive"),
					   "%s",
					   _("You don't have the right permissions to create an archive in the destination folder."));
		gtk_dialog_run (GTK_DIALOG (d));
		gtk_widget_destroy (GTK_WIDGET (d));

		g_free (archive_dir);
		g_free (archive_name);
		return;
	}

	if (! uri_is_dir (archive_dir)) {
		GtkWidget *d;
		int        r;
		char      *folder_name;
		char      *msg;

		folder_name = g_filename_display_name (archive_dir);
		msg = g_strdup_printf (_("Destination folder \"%s\" does not exist.\n\nDo you want to create it?"), folder_name);
		g_free (folder_name);

		d = _gtk_message_dialog_new (GTK_WINDOW (data->dialog),
					     GTK_DIALOG_MODAL,
					     GTK_STOCK_DIALOG_QUESTION,
					     msg,
					     NULL,
					     GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
					     _("Create _Folder"), GTK_RESPONSE_YES,
					     NULL);

		gtk_dialog_set_default_response (GTK_DIALOG (d), GTK_RESPONSE_YES);
		r = gtk_dialog_run (GTK_DIALOG (d));
		gtk_widget_destroy (GTK_WIDGET (d));

		g_free (msg);

		do_not_add = (r != GTK_RESPONSE_YES);
	}

	if (! do_not_add && ! ensure_dir_exists (archive_dir, 0755, &error)) {
		GtkWidget  *d;

		d = _gtk_error_dialog_new (GTK_WINDOW (window),
					   GTK_DIALOG_DESTROY_WITH_PARENT,
					   NULL,
					   _("Could not create the archive"),
					   _("Could not create the destination folder: %s."),
					   error->message);
		gtk_dialog_run (GTK_DIALOG (d));
		gtk_widget_destroy (GTK_WIDGET (d));

		g_error_free (error);
		g_free (archive_dir);
		g_free (archive_name);
		return;
	}

	if (do_not_add) {
		GtkWidget *d;

		d = _gtk_message_dialog_new (GTK_WINDOW (window),
					     GTK_DIALOG_DESTROY_WITH_PARENT,
					     GTK_STOCK_DIALOG_WARNING,
					     _("Archive not created"),
					     NULL,
					     GTK_STOCK_OK, GTK_RESPONSE_OK,
					     NULL);
		gtk_dialog_set_default_response (GTK_DIALOG (d), GTK_RESPONSE_OK);
		gtk_dialog_run (GTK_DIALOG (d));
		gtk_widget_destroy (GTK_WIDGET (d));

		g_free (archive_dir);
		g_free (archive_name);

		return;
	}

	/**/

	archive_ext = get_ext (data);
	tmp = archive_name;
	archive_name = g_strconcat (tmp, archive_ext, NULL);
	g_free (tmp);
	archive_file = g_strconcat (archive_dir, "/", archive_name, NULL);

	if (uri_is_dir (archive_file)) {
		GtkWidget  *d;

		d = _gtk_error_dialog_new (GTK_WINDOW (window),
					   GTK_DIALOG_DESTROY_WITH_PARENT,
					   NULL,
					   _("Could not create the archive"),
					   "%s",
					   _("You have to specify an archive name."));
		gtk_dialog_run (GTK_DIALOG (d));
		gtk_widget_destroy (GTK_WIDGET (d));

		g_free (archive_name);
		g_free (archive_dir);
		g_free (archive_file);

		return;
	}

	if (uri_exists (archive_file)) {
		GtkWidget *d;
		int        r;

		d = _gtk_message_dialog_new (GTK_WINDOW (data->dialog),
					     GTK_DIALOG_MODAL,
					     GTK_STOCK_DIALOG_QUESTION,
					     _("The archive is already present.  Do you want to overwrite it?"),
					     NULL,
					     GTK_STOCK_NO, GTK_RESPONSE_NO,
					     _("_Overwrite"), GTK_RESPONSE_YES,
					     NULL);

		gtk_dialog_set_default_response (GTK_DIALOG (d), GTK_RESPONSE_YES);
		r = gtk_dialog_run (GTK_DIALOG (d));
		gtk_widget_destroy (GTK_WIDGET (d));

		if (r == GTK_RESPONSE_YES) {
			GFile  *file;
			GError *err = NULL;

			/* FIXME: convert this code in a function in file-utils.c */
			file = g_file_new_for_uri (archive_file);
			g_file_delete (file, NULL, &err);
			if (err != NULL) {
				g_warning ("Failed to delete file %s: %s",
					   archive_file,
					   err->message);
				g_clear_error (&err);
			}
			g_object_unref (file);
		}
		else {
			g_free (archive_name);
			g_free (archive_dir);
			g_free (archive_file);
			return;
		}
	}
	set_archive_options (data);
	gtk_widget_destroy (data->dialog);

	fr_window_archive_new (window, archive_file);

	g_free (archive_name);
	g_free (archive_dir);
	g_free (archive_file);
}
Esempio n. 8
0
G_MODULE_EXPORT gint
test_shader_main (gint argc, gchar *argv[])
{
  ClutterActor  *actor;
  ClutterActor  *stage;
  ClutterColor   stage_color = { 0x61, 0x64, 0x8c, 0xff };
  ClutterShader *shader;
  GError        *error;
  gchar         *file;

  clutter_init (&argc, &argv);

  stage = clutter_stage_get_default ();
  clutter_actor_set_size (stage, 512, 384);

  g_print ("applying shaders[%i] named '%s'\n",
           shader_no,
           shaders[shader_no].name);

  shader = clutter_shader_new ();

  error = NULL;
  clutter_shader_set_fragment_source (shader, shaders[shader_no].source, -1);
  clutter_shader_compile (shader, &error);
  if (error)
    {
      g_print ("unable to load shaders[%d] named '%s': %s\n",
               shader_no,
               shaders[shader_no].name,
               error->message);
      g_error_free (error);

      return EXIT_FAILURE;
    }

  clutter_stage_set_title (CLUTTER_STAGE (stage), "Shader Test");
  clutter_stage_set_color (CLUTTER_STAGE (stage), &stage_color);

  file = g_build_filename (TESTS_DATADIR, "redhand.png", NULL);

#ifndef TEST_GROUP
  actor = clutter_texture_new_from_file (file, &error);
  if (!actor)
    g_error("pixbuf load failed: %s", error ? error->message : "Unknown");
#else
  actor = clutter_group_new ();

  {
    ClutterActor *child1, *child2, *child3, *child4;
    ClutterColor  color = { 0xff, 0x22, 0x66, 0x99 };

    child1 = clutter_texture_new_from_file (file, &error);
    if (!child1)
      g_error("pixbuf load failed: %s", error ? error->message : "Unknown");

    child2 = clutter_texture_new_from_file (file, &error);
    if (!child2)
      g_error("pixbuf load failed: %s", error ? error->message : "Unknown");

    child3 = clutter_rectangle_new ();
    child4 = clutter_text_new_with_text ("Sans 20px", "Shady stuff");

    clutter_rectangle_set_color (CLUTTER_RECTANGLE (child3), &color);
    clutter_actor_set_size (child3, 50, 50);

    clutter_actor_set_position (child1, 0, 0);
    clutter_actor_set_position (child2, 50, 100);
    clutter_actor_set_position (child3, 30, -30);
    clutter_actor_set_position (child4, -50, 20);

    clutter_container_add (CLUTTER_CONTAINER (actor),
                           child1,
                           child2,
                           child3,
                           child4,
                           NULL);

    clutter_actor_show_all (actor);
  }
#endif /* !TEST_GROUP */

  g_free (file);

  clutter_actor_set_shader (actor, shader);
  clutter_actor_set_position (actor, 100, 100);

  g_object_unref (shader);

  clutter_container_add_actor (CLUTTER_CONTAINER (stage), actor);

  clutter_actor_set_shader_param_int (actor, "tex", 0);
  clutter_actor_set_shader_param_float (actor, "brightness", 0.4);
  clutter_actor_set_shader_param_float (actor, "contrast", -1.9);

  clutter_actor_set_reactive (actor, TRUE);
  g_signal_connect (actor, "button-release-event",
                    G_CALLBACK (button_release_cb), NULL);

#ifdef COGL_HAS_GLES
  /* On an embedded platform it is difficult to right click so we will
     cycle through the shaders automatically */
  g_timeout_add_seconds (3, timeout_cb, actor);
#endif

  /* Show everying ( and map window ) */
  clutter_actor_show_all (stage);

  clutter_main ();

  return EXIT_SUCCESS;
}
static void
cc_date_time_panel_init (CcDateTimePanel *self)
{
  CcDateTimePanelPrivate *priv;
  GtkWidget *widget;
  GError *error;
  GtkTreeModelSort *city_modelsort;
  int ret;
  const char *date_grid_name;
  char *tmp;

  priv = self->priv = DATE_TIME_PANEL_PRIVATE (self);
  g_resources_register (cc_datetime_get_resource ());

  priv->cancellable = g_cancellable_new ();
  error = NULL;
  priv->dtm = timedate1_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM,
                                                G_DBUS_PROXY_FLAGS_NONE,
                                                "org.freedesktop.timedate1",
                                                "/org/freedesktop/timedate1",
                                                priv->cancellable,
                                                &error);
  if (priv->dtm == NULL) {
        g_warning ("could not get proxy for DateTimeMechanism: %s", error->message);
        g_clear_error (&error);
        return;
  }

  priv->builder = gtk_builder_new ();
  ret = gtk_builder_add_from_resource (priv->builder,
                                       "/org/gnome/control-center/datetime/datetime.ui",
                                       &error);

  if (ret == 0)
    {
      g_warning ("Could not load ui: %s", error ? error->message : "No reason");
      if (error)
        g_error_free (error);
      return;
    }

  switch (date_endian_get_default (FALSE)) {
  case DATE_ENDIANESS_BIG:
    date_grid_name = "big";
    break;
  case DATE_ENDIANESS_LITTLE:
    date_grid_name = "little";
    break;
  case DATE_ENDIANESS_MIDDLE:
    date_grid_name = "middle";
    break;
  case DATE_ENDIANESS_YDM:
    date_grid_name = "ydm";
    break;
  default:
    g_assert_not_reached ();
  }

  tmp = g_strdup_printf ("/org/gnome/control-center/datetime/%s.ui", date_grid_name);
  ret = gtk_builder_add_from_resource (priv->builder, tmp, NULL);
  g_free (tmp);

  gtk_box_pack_end (GTK_BOX (W ("time-box")), W ("date_grid"), FALSE, TRUE, 0);

  /* add the lock button */
  priv->permission = polkit_permission_new_sync (DATETIME_PERMISSION, NULL, NULL, NULL);
  if (priv->permission != NULL)
    {
      g_signal_connect (priv->permission, "notify",
                        G_CALLBACK (on_permission_changed), self);
      on_permission_changed (priv->permission, NULL, self);
    }
  else
    {
      g_warning ("Your system does not have the '%s' PolicyKit files installed. Please check your installation",
                 DATETIME_PERMISSION);
    }

  priv->date = g_date_time_new_now_local ();

  /* Top level windows from GtkBuilder that need to be destroyed explicitly */
  priv->toplevels = g_list_append (priv->toplevels, W ("datetime-dialog"));
  priv->toplevels = g_list_append (priv->toplevels, W ("timezone-dialog"));

  setup_timezone_dialog (self);
  setup_datetime_dialog (self);

  setup_listbox (self, W ("listbox1"));
  setup_listbox (self, W ("listbox2"));

  /* set up network time switch */
  bind_switch_to_row (self,
                      W ("network_time_switch"),
                      W ("datetime-button"));
  g_object_bind_property (priv->dtm, "ntp",
                          W ("network_time_switch"), "active",
                          G_BINDING_SYNC_CREATE);
  g_signal_connect (W("network_time_switch"), "notify::active",
                    G_CALLBACK (change_ntp), self);

  gtk_widget_set_visible (W ("auto-datetime-row"), is_ntp_available (self));

  /* Timezone settings */
  bind_switch_to_row (self,
                      W ("auto_timezone_switch"),
                      W ("timezone-button"));

  priv->datetime_settings = g_settings_new (DATETIME_SCHEMA);
  g_settings_bind (priv->datetime_settings, AUTO_TIMEZONE_KEY,
                   W ("auto_timezone_switch"), "active",
                   G_SETTINGS_BIND_DEFAULT);

  /* Clock settings */
  priv->clock_settings = g_settings_new (CLOCK_SCHEMA);

  widget = W ("vbox_datetime");
  gtk_container_add (GTK_CONTAINER (self), widget);

  /* setup the time itself */
  priv->clock_tracker = g_object_new (GNOME_TYPE_WALL_CLOCK, NULL);
  g_signal_connect (priv->clock_tracker, "notify::clock", G_CALLBACK (on_clock_changed), self);

  clock_settings_changed_cb (priv->clock_settings, CLOCK_FORMAT_KEY, self);
  g_signal_connect (priv->clock_settings, "changed::" CLOCK_FORMAT_KEY,
                    G_CALLBACK (clock_settings_changed_cb), self);

  g_signal_connect (W("format_combobox"), "notify::active-id",
                    G_CALLBACK (change_clock_settings), self);

  update_time (self);

  load_regions_model (GTK_LIST_STORE (gtk_builder_get_object (priv->builder,
                                                              "city-liststore")));

  city_modelsort = GTK_TREE_MODEL_SORT (gtk_builder_get_object (priv->builder, "city-modelsort"));
  gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (city_modelsort), CITY_COL_CITY_HUMAN_READABLE,
                                        GTK_SORT_ASCENDING);

  /* After the initial setup, so we can be sure that
   * the model is filled up */
  get_initial_timezone (self);

  widget = (GtkWidget*) gtk_builder_get_object (self->priv->builder,
                                                "timezone-searchentry");
  g_signal_connect (gtk_entry_get_completion (GTK_ENTRY (widget)),
                    "match-selected", G_CALLBACK (city_changed_cb), self);

  g_signal_connect (self->priv->map, "location-changed",
                    G_CALLBACK (location_changed_cb), self);

  /* Watch changes of timedated remote service properties */
  g_signal_connect (priv->dtm, "g-properties-changed",
                    G_CALLBACK (on_timedated_properties_changed), self);
  g_signal_connect_swapped (priv->dtm, "notify::can-ntp",
                            G_CALLBACK (on_can_ntp_changed), self);
  g_signal_connect_swapped (priv->dtm, "notify::timezone",
                            G_CALLBACK (on_timezone_changed), self);
  /* We ignore UTC <--> LocalRTC changes at the moment */

  priv->filechooser_settings = g_settings_new (FILECHOOSER_SCHEMA);
}
Esempio n. 10
0
static int
extract_cb (GtkWidget   *w,
	    DialogData  *data)
{
	FrWindow   *window = data->window;
	gboolean    do_not_extract = FALSE;
	char       *extract_to_dir;
	gboolean    overwrite;
	gboolean    skip_newer;
	gboolean    selected_files;
	gboolean    pattern_files;
	gboolean    junk_paths;
	GList      *file_list;
	char       *base_dir = NULL;
	GError     *error = NULL;

	data->extract_clicked = TRUE;

	/* collect extraction options. */

	extract_to_dir = gtk_file_chooser_get_uri (GTK_FILE_CHOOSER (data->dialog));

	/* check directory existence. */

	if (! uri_is_dir (extract_to_dir)) {
		if (! ForceDirectoryCreation) {
			GtkWidget *d;
			int        r;
			char      *folder_name;
			char      *msg;

			folder_name = g_filename_display_name (extract_to_dir);
			msg = g_strdup_printf (_("Destination folder \"%s\" does not exist.\n\nDo you want to create it?"), folder_name);
			g_free (folder_name);

			d = _gtk_message_dialog_new (GTK_WINDOW (data->dialog),
						     GTK_DIALOG_MODAL,
						     GTK_STOCK_DIALOG_QUESTION,
						     msg,
						     NULL,
						     GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
						     _("Create _Folder"), GTK_RESPONSE_YES,
						     NULL);

			gtk_dialog_set_default_response (GTK_DIALOG (d), GTK_RESPONSE_YES);
			r = gtk_dialog_run (GTK_DIALOG (d));
			gtk_widget_destroy (GTK_WIDGET (d));

			g_free (msg);

			if (r != GTK_RESPONSE_YES)
				do_not_extract = TRUE;
		}

		if (! do_not_extract && ! ensure_dir_exists (extract_to_dir, 0755, &error)) {
			GtkWidget  *d;

			d = _gtk_error_dialog_new (GTK_WINDOW (window),
						   GTK_DIALOG_DESTROY_WITH_PARENT,
						   NULL,
						   _("Extraction not performed"),
						   _("Could not create the destination folder: %s."),
						   error->message);
			gtk_dialog_run (GTK_DIALOG (d));
			gtk_widget_destroy (GTK_WIDGET (d));

			g_error_free (error);

			return FALSE;
		}
	}

	if (do_not_extract) {
		GtkWidget *d;

		d = _gtk_message_dialog_new (GTK_WINDOW (window),
					     GTK_DIALOG_DESTROY_WITH_PARENT,
					     GTK_STOCK_DIALOG_WARNING,
					     _("Extraction not performed"),
					     NULL,
					     GTK_STOCK_OK, GTK_RESPONSE_OK,
					     NULL);
		gtk_dialog_set_default_response (GTK_DIALOG (d), GTK_RESPONSE_OK);
		gtk_dialog_run (GTK_DIALOG (d));
		gtk_widget_destroy (GTK_WIDGET (d));

		if (fr_window_is_batch_mode (data->window))
			gtk_widget_destroy (data->dialog);

		return FALSE;
	}

	/* check extraction directory permissions. */

	if (uri_is_dir (extract_to_dir)
	    && ! check_permissions (extract_to_dir, R_OK | W_OK)) 
	{
		GtkWidget *d;
		char      *utf8_path;

		utf8_path = g_filename_display_name (extract_to_dir);

		d = _gtk_error_dialog_new (GTK_WINDOW (window),
					   GTK_DIALOG_DESTROY_WITH_PARENT,
					   NULL,
					   _("Extraction not performed"),
					   _("You don't have the right permissions to extract archives in the folder \"%s\""),
					   utf8_path);
		gtk_dialog_run (GTK_DIALOG (d));
		gtk_widget_destroy (GTK_WIDGET (d));

		g_free (utf8_path);
		g_free (extract_to_dir);

		return FALSE;
	}

	fr_window_set_extract_default_dir (window, extract_to_dir, TRUE);

	overwrite = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (data->e_overwrite_checkbutton));
	skip_newer = ! gtk_toggle_button_get_inconsistent (GTK_TOGGLE_BUTTON (data->e_not_newer_checkbutton)) && gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (data->e_not_newer_checkbutton));
	junk_paths = ! gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (data->e_recreate_dir_checkbutton));

	g_settings_set_boolean (data->settings, PREF_EXTRACT_OVERWRITE, overwrite);
	if (! gtk_toggle_button_get_inconsistent (GTK_TOGGLE_BUTTON (data->e_not_newer_checkbutton)))
	g_settings_set_boolean (data->settings, PREF_EXTRACT_SKIP_NEWER, skip_newer);
	g_settings_set_boolean (data->settings, PREF_EXTRACT_RECREATE_FOLDERS, ! junk_paths);

	selected_files = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (data->e_selected_radiobutton));
	pattern_files = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (data->e_files_radiobutton));

	/* create the file list. */

	file_list = NULL;

	if (selected_files) {
		file_list = data->selected_files;
		data->selected_files = NULL;       /* do not the list when destroying the dialog. */
	}
	else if (pattern_files) {
		const char *pattern;

		pattern = gtk_entry_get_text (GTK_ENTRY (data->e_files_entry));
		file_list = fr_window_get_file_list_pattern (window, pattern);
		if (file_list == NULL) {
			gtk_widget_destroy (data->dialog);
			g_free (extract_to_dir);
			return FALSE;
		}
	}

	if (selected_files) {
		base_dir = data->base_dir_for_selection;
		data->base_dir_for_selection = NULL;
	}
	else
		base_dir = NULL;

	/* close the dialog. */

	gtk_widget_destroy (data->dialog);

	/* extract ! */

	fr_window_archive_extract (window,
				   file_list,
				   extract_to_dir,
				   base_dir,
				   skip_newer,
				   overwrite ? FR_OVERWRITE_YES : FR_OVERWRITE_NO,
				   junk_paths,
				   TRUE);

	path_list_free (file_list);
	g_free (extract_to_dir);
	g_free (base_dir);

	return TRUE;
}
Esempio n. 11
0
static void
set_shader_num (ClutterActor *actor, gint new_no)
{
  int  tex_width;
  int  tex_height;

  if (new_no >= 0 && shaders[new_no].name)
    {
      ClutterShader *shader;
      GError *error;
      shader_no = new_no;
      
      g_print ("setting shaders[%i] named '%s'\n",
               shader_no,
               shaders[shader_no].name);

      shader = clutter_shader_new ();
      
      error = NULL;
      g_object_set (G_OBJECT (shader),
                    "fragment-source", shaders[shader_no].source,
                    NULL);

      /* try to bind the shader, provoking an error we catch if there is issues
       * with the shader sources we've provided. At a later stage it should be
       * possible to iterate through a set of alternate shader sources (glsl ->
       * asm -> cg?) and the one that succesfully compiles is used.
       */
      clutter_shader_compile (shader, &error);
      if (error)
        {
          g_print ("unable to set shaders[%i] named '%s': %s",
                   shader_no, shaders[shader_no].name,
                   error->message);
          g_error_free (error);
          clutter_actor_set_shader (actor, NULL);
        }
      else
        {
          clutter_actor_set_shader (actor, NULL);
          clutter_actor_set_shader (actor, shader);
          clutter_actor_set_shader_param_int (actor, "tex", 0);
          clutter_actor_set_shader_param_float (actor, "radius", 3.0);
          clutter_actor_set_shader_param_float (actor, "brightness", 0.4);
          clutter_actor_set_shader_param_float (actor, "contrast", -1.9);

	  if (CLUTTER_IS_TEXTURE (actor))
	    {
              /* XXX - this assumes *a lot* about how things are done
               * internally on *some* hardware and driver
               */
	      tex_width = clutter_actor_get_width (actor);
	      tex_width = next_p2 (tex_width);

	      tex_height = clutter_actor_get_height (actor);
	      tex_height = next_p2 (tex_height);

	      clutter_actor_set_shader_param_float (actor, "x_step",
					            1.0f / tex_width);
	      clutter_actor_set_shader_param_float (actor, "y_step",
					            1.0f / tex_height);
  	    }
        }

      g_object_unref (shader);
    }
}
Esempio n. 12
0
static void
cc_screen_panel_init (CcScreenPanel *self)
{
    GError     *error;
    GtkWidget  *widget;

    self->priv = SCREEN_PANEL_PRIVATE (self);

    self->priv->builder = gtk_builder_new ();

    error = NULL;
    gtk_builder_add_from_file (self->priv->builder,
                               GNOMECC_UI_DIR "/screen.ui",
                               &error);

    if (error != NULL)
    {
        g_warning ("Could not load interface file: %s", error->message);
        g_error_free (error);
        return;
    }

    self->priv->cancellable = g_cancellable_new ();

    /* get initial brightness version */
    g_dbus_proxy_new_for_bus (G_BUS_TYPE_SESSION,
                              G_DBUS_PROXY_FLAGS_NONE,
                              NULL,
                              "org.gnome.SettingsDaemon",
                              "/org/gnome/SettingsDaemon/Power",
                              "org.gnome.SettingsDaemon.Power.Screen",
                              self->priv->cancellable,
                              got_power_proxy_cb,
                              self);

    self->priv->lock_settings = g_settings_new ("org.gnome.desktop.screensaver");
    g_signal_connect (self->priv->lock_settings,
                      "changed",
                      G_CALLBACK (on_lock_settings_changed),
                      self);
    self->priv->gsd_settings = g_settings_new ("org.gnome.settings-daemon.plugins.power");
    self->priv->session_settings = g_settings_new ("org.gnome.desktop.session");
    self->priv->lockdown_settings = g_settings_new ("org.gnome.desktop.lockdown");
    g_signal_connect (self->priv->lockdown_settings,
                      "changed",
                      G_CALLBACK (on_lockdown_settings_changed),
                      self);

    /* bind the auto dim checkbox */
    widget = WID ("screen_auto_reduce_checkbutton");
    g_settings_bind (self->priv->gsd_settings,
                     "idle-dim-battery",
                     widget, "active",
                     G_SETTINGS_BIND_DEFAULT);

    /* display off time */
    widget = WID ("screen_brightness_combobox");
    set_dpms_value_for_combo (GTK_COMBO_BOX (widget), self);
    g_signal_connect (widget, "changed",
                      G_CALLBACK (dpms_combo_changed_cb),
                      self);

    /* bind the screen lock checkbox */
    widget = WID ("screen_lock_on_switch");
    g_settings_bind (self->priv->lock_settings,
                     "lock-enabled",
                     widget, "active",
                     G_SETTINGS_BIND_DEFAULT);

    /* lock time */
    widget = WID ("screen_lock_combobox");
    set_lock_value_for_combo (GTK_COMBO_BOX (widget), self);
    g_signal_connect (widget, "changed",
                      G_CALLBACK (lock_combo_changed_cb),
                      self);

    widget = WID ("screen_lock_hbox");
    g_settings_bind (self->priv->lock_settings,
                     "lock-enabled",
                     widget, "sensitive",
                     G_SETTINGS_BIND_GET);

    widget = WID ("show_notifications_check");
    g_settings_bind (self->priv->lock_settings,
                     "show-notifications",
                     widget, "active",
                     G_SETTINGS_BIND_DEFAULT);
    if (!g_strcmp0(g_getenv("XDG_CURRENT_DESKTOP"), "Unity"))
        gtk_widget_hide (widget);

    update_lock_screen_sensitivity (self);

    /* bind the screen lock suspend checkbutton */
    widget = WID ("screen_lock_suspend_checkbutton");
    g_settings_bind (self->priv->lock_settings,
                     "ubuntu-lock-on-suspend",
                     widget, "active",
                     G_SETTINGS_BIND_DEFAULT);

    widget = WID ("screen_vbox");
    gtk_widget_reparent (widget, (GtkWidget *) self);
    g_object_set (self, "valign", GTK_ALIGN_START, NULL);
}
Esempio n. 13
0
/* TODO: this should be optimized so we don't allocate network and call open()/close() all the time */
static void
collect (DiskIOMonitor *monitor)
{
    gchar *contents = NULL;
    gsize len;
    GError *error;
    gchar **lines = NULL;
    guint n;
    gint64 now;
    Sample *sample = NULL;
    Sample *last = NULL;
    GVariantBuilder builder;

    error = NULL;
    if (!g_file_get_contents ("/proc/diskstats",
                              &contents,
                              &len,
                              &error))
    {
        g_warning ("Error loading contents /proc/vmstat: %s (%s, %d)",
                   error->message, g_quark_to_string (error->domain), error->code);
        g_error_free (error);
        goto out;
    }

    now = g_get_real_time ();

    sample = &(monitor->samples[monitor->samples_next]);
    sample->timestamp = now;
    sample->bytes_read = 0;
    sample->bytes_written = 0;
    sample->num_ops = 0;

    if (monitor->samples_prev != -1)
        last = &(monitor->samples[monitor->samples_prev]);

    lines = g_strsplit (contents, "\n", -1);
    for (n = 0; lines != NULL && lines[n] != NULL; n++)
    {
        const gchar *line = lines[n];
        guint num_parsed;
        gint dev_major, dev_minor;
        gchar dev_name[64]; /* TODO: big enough? */
        guint64 num_reads,  num_reads_merged,  num_sectors_read,    num_msec_reading;
        guint64 num_writes, num_writes_merged, num_sectors_written, num_msec_writing;
        guint64 num_io_in_progress, num_msec_doing_io, weighted_num_msec_doing_io;

        if (strlen (line) == 0)
            continue;

        /* From http://www.kernel.org/doc/Documentation/iostats.txt
         *
         * Field  1 -- # of reads completed
         *     This is the total number of reads completed successfully.
         * Field  2 -- # of reads merged, field 6 -- # of writes merged
         *     Reads and writes which are adjacent to each other may be merged for
         *     efficiency.  Thus two 4K reads may become one 8K read before it is
         *     ultimately handed to the disk, and so it will be counted (and queued)
         *     as only one I/O.  This field lets you know how often this was done.
         * Field  3 -- # of sectors read
         *     This is the total number of sectors read successfully.
         * Field  4 -- # of milliseconds spent reading
         *     This is the total number of milliseconds spent by all reads (as
         *     measured from __make_request() to end_that_request_last()).
         * Field  5 -- # of writes completed
         *     This is the total number of writes completed successfully.
         * Field  7 -- # of sectors written
         *     This is the total number of sectors written successfully.
         * Field  8 -- # of milliseconds spent writing
         *     This is the total number of milliseconds spent by all writes (as
         *     measured from __make_request() to end_that_request_last()).
         * Field  9 -- # of I/Os currently in progress
         *     The only field that should go to zero. Incremented as requests are
         *     given to appropriate struct request_queue and decremented as they finish.
         * Field 10 -- # of milliseconds spent doing I/Os
         *     This field increases so long as field 9 is nonzero.
         * Field 11 -- weighted # of milliseconds spent doing I/Os
         *     This field is incremented at each I/O start, I/O completion, I/O
         *     merge, or read of these stats by the number of I/Os in progress
         *     (field 9) times the number of milliseconds spent doing I/O since the
         *     last update of this field.  This can provide an easy measure of both
         *     I/O completion time and the backlog that may be accumulating.
         */

        num_parsed = sscanf (line,
                             "%d %d %s"
                             " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT
                             " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT
                             " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT,
                             &dev_major, &dev_minor, dev_name,
                             &num_reads,  &num_reads_merged, &num_sectors_read, &num_msec_reading,
                             &num_writes, &num_writes_merged, &num_sectors_written, &num_msec_writing,
                             &num_io_in_progress, &num_msec_doing_io, &weighted_num_msec_doing_io);
        if (num_parsed != 14)
        {
            g_warning ("Error parsing line %d of file /proc/diskstats (num_parsed=%d): `%s'", n, num_parsed, line);
            continue;
        }

        /* skip mapped devices and partitions... otherwise we'll count their
         * I/O more than once
         *
         * TODO: the way we identify dm devices and partitions is not
         * very elegant... we should consult sysfs via libgudev1
         * instead.
         */
        if (dev_major == 253)
            continue;

        if (g_str_has_prefix (dev_name, "sd") && g_ascii_isdigit (dev_name[strlen (dev_name) - 1]))
            continue;

        sample->bytes_read += num_sectors_read * 512;
        sample->bytes_written += num_sectors_written * 512;
        sample->num_ops += num_reads_merged + num_writes_merged;
    }

    if (last != NULL)
    {
        sample->bytes_read_per_sec = calc_bandwidth (monitor, sample, last, sample->bytes_read, last->bytes_read);
        sample->bytes_written_per_sec = calc_bandwidth (monitor, sample, last, sample->bytes_written, last->bytes_written);
        sample->io_operations_per_sec = calc_bandwidth (monitor, sample, last, sample->num_ops, last->num_ops);
    }

out:
    g_strfreev (lines);
    g_free (contents);
    if (sample != NULL)
    {
        g_variant_builder_init (&builder, G_VARIANT_TYPE ("ad"));
        g_variant_builder_add (&builder, "d", sample->bytes_read_per_sec);
        g_variant_builder_add (&builder, "d", sample->bytes_written_per_sec);
        g_variant_builder_add (&builder, "d", sample->io_operations_per_sec);
        cockpit_resource_monitor_emit_new_sample (COCKPIT_RESOURCE_MONITOR(monitor),
                now, g_variant_builder_end (&builder));
    }

    monitor->samples_prev = monitor->samples_next;
    monitor->samples_next += 1;
    if (monitor->samples_next == monitor->samples_max)
        monitor->samples_next = 0;
}
Esempio n. 14
0
static gboolean
io_handler (GIOChannel * channel, GIOCondition condition, gpointer user_data)
{
  BtIcMidiDevice *self = BTIC_MIDI_DEVICE (user_data);
  BtIcControl *control;
  GError *error = NULL;
  gsize bytes_read;
  guchar midi_event[3], cmd;
  static guchar prev_cmd = 0;
  guint key;
  gboolean res = TRUE;

  if (condition & (G_IO_IN | G_IO_PRI)) {
    g_io_channel_read_chars (self->priv->io_channel, (gchar *) midi_event, 1,
        &bytes_read, &error);
    if (error) {
      GST_WARNING ("iochannel error when reading: %s", error->message);
      g_error_free (error);
      //res=FALSE;
    } else {
      gint have_read = 0;
      guchar *midi_data = &midi_event[1];

      GST_LOG ("command: %02x", midi_event[0]);
      cmd = midi_event[0] & MIDI_CMD_MASK;
      if (cmd < 0x80 && prev_cmd) {
        have_read = 1;
        midi_event[1] = midi_event[0];
        midi_event[0] = prev_cmd;
        midi_data = &midi_event[2];
        cmd = prev_cmd & MIDI_CMD_MASK;
      }
      // http://www.midi.org/techspecs/midimessages.php
      // http://www.cs.cf.ac.uk/Dave/Multimedia/node158.html
      switch (cmd) {
        case MIDI_NOTE_OFF:
          g_io_channel_read_chars (self->priv->io_channel, (gchar *) midi_data,
              2 - have_read, &bytes_read, &error);
          if (error)
            log_io_error (error, "NOTE-OFF");
          else {
            GST_DEBUG ("note-off: %02x %02x %02x", midi_event[0], midi_event[1],
                midi_event[2]);

#if 0
            // we probably need to make this another controller that just sends
            // note-off, sending this as part of the key-controler causes trouble
            // for the enum scaling
            // we still need a way to ensure note-off is send to the voice
            // matching the note, maybe a user_data field in the
            // BtPolyControlData struct
            key = MIDI_CTRL_NOTE_KEY;
            if ((control =
                    btic_device_get_control_by_id (BTIC_DEVICE (self), key))) {
              g_object_set (control, "value", (glong) 255 /* GSTBT_NOTE_OFF */ ,
                  NULL);
            }
            // also handle note-off velocity
#endif
            prev_cmd = midi_event[0];
          }
          break;
        case MIDI_NOTE_ON:
          g_io_channel_read_chars (self->priv->io_channel, (gchar *) midi_data,
              2 - have_read, &bytes_read, &error);
          if (error)
            log_io_error (error, "NOTE-ON");
          else {
            /* this CMD drives two controllers, key and velocity, thus we need
             * to do the lean in two steps
             * TODO(ensonic): maybe we can add a callback and a extra info message
             * to update_learn_info. The info message can tell, that this will name
             * multiple controllers. The callback can actually register them.
             * TODO(ensonic): we could also define one regular abs-range controller
             * for each key - then we can play drums with the key - each drum
             * controlled by one key. The downside is, that this will cause the
             * controller menu to explode.
             *
             * Maybe we should change the machine-window to have tabs:
             * - properties
             * - interactions
             * - settings (the preferences)
             * This would fold the preferences window into the machine-window as
             * a tab. The downside is that some of the toolbar items (about and
             * help) would be related to all tabs, while the preset, randomize,
             * reset ones would be related to the properties tab only.
             * The 'interaction' tab would have a list/tree of parameters
             * and a list/tree of controls. The control list could show if a
             * control is bound already (e.g. to another machine). We would need
             * a drawable between the lists to show the connections with lines.
             *
             * An alternative would be to only list the devices in the
             * controller menu. When selecting a device we ensure its running
             * and set the learn mode. As soon as controls changed, we list them
             * and let the user pick one. For each control we could show where
             * it is bound currently. If we go that route, we would actually not
             * need the controller profiles.
             *
             * If we keep the menu, we should show where to a controller is
             * bound.
             */
            gboolean learn_1st = FALSE;
            GST_DEBUG ("note-on: %02x %02x %02x", midi_event[0], midi_event[1],
                midi_event[2]);

            key = MIDI_CTRL_NOTE_KEY;
            if ((control =
                    btic_device_get_control_by_id (BTIC_DEVICE (self), key))) {
              g_object_set (control, "value", (gint32) (midi_event[1]), NULL);
            } else if (G_UNLIKELY (self->priv->learn_mode)) {
              update_learn_info (self, "note-key", key, 7);
              learn_1st = TRUE;
            }
            key = MIDI_CTRL_NOTE_VELOCITY;
            if ((control =
                    btic_device_get_control_by_id (BTIC_DEVICE (self), key))) {
              g_object_set (control, "value", (gint32) (midi_event[2]), NULL);
            } else if (G_UNLIKELY (self->priv->learn_mode) && !learn_1st) {
              update_learn_info (self, "note-velocity", key, 7);
            }
            prev_cmd = midi_event[0];
          }
          break;
        case MIDI_CONTROL_CHANGE:
          g_io_channel_read_chars (self->priv->io_channel, (gchar *) midi_data,
              2 - have_read, &bytes_read, &error);
          if (error)
            log_io_error (error, "CONTROL-CHANGE");
          else {
            GST_DEBUG ("control-change: %02x %02x %02x", midi_event[0],
                midi_event[1], midi_event[2]);

            key = (guint) midi_event[1];        // 0-119 (normal controls), 120-127 (channel mode message)
            if ((control =
                    btic_device_get_control_by_id (BTIC_DEVICE (self), key))) {
              g_object_set (control, "value", (gint32) (midi_event[2]), NULL);
            } else if (G_UNLIKELY (self->priv->learn_mode)) {
              static gchar name[20];

              sprintf (name, "control-change %u", key);
              update_learn_info (self, name, key, 7);
            }
            prev_cmd = midi_event[0];
          }
          break;
        case MIDI_PITCH_WHEEL_CHANGE:
          g_io_channel_read_chars (self->priv->io_channel, (gchar *) midi_data,
              2 - have_read, &bytes_read, &error);
          if (error)
            log_io_error (error, "PITCH-WHEEL-CHANGE");
          else {
            GST_DEBUG ("pitch-wheel-change: %02x %02x %02x", midi_event[0],
                midi_event[1], midi_event[2]);

            key = MIDI_CTRL_PITCH_WHEEL;
            if ((control =
                    btic_device_get_control_by_id (BTIC_DEVICE (self), key))) {
              gint32 v = (((gint32) midi_event[2]) << 7) | (midi_event[1]);

              g_object_set (control, "value", v, NULL);
            } else if (G_UNLIKELY (self->priv->learn_mode)) {
              update_learn_info (self, "pitch-wheel-change", key, 14);
            }
            prev_cmd = midi_event[0];
          }
          break;
#if 0
        case MIDI_TRANSPORT_START:
          GST_DEBUG ("transport-start");

          key = MIDI_CTRL_TRANSPORT_START;
          if ((control =
                  btic_device_get_control_by_id (BTIC_DEVICE (self), key))) {
            gint32 v = 1;

            g_object_set (control, "value", v, NULL);
          } else if (G_UNLIKELY (self->priv->learn_mode)) {
            update_learn_info (self, "transport-start", key, 1);
          }
          break;
        case MIDI_TRANSPORT_CONTINUE:
          break;
        case MIDI_TRANSPORT_STOP:
          break;
#endif
        case 0xf0:             /* system common/realtime */
          break;
        default:
          GST_LOG ("unhandled message: %02x", midi_event[0]);
          break;
      }
    }
  }
  if (condition & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
    res = FALSE;
  }
  if (!res) {
    GST_INFO ("closing connection");
    self->priv->io_source = 0;
  }
  return res;
}
Esempio n. 15
0
gboolean deep_count_gio(FmDeepCountJob* job, GFileInfo* inf, GFile* gf)
{
    FmJob* fmjob = FM_JOB(job);
    GError* err = NULL;
    GFileType type;
    guint64 blk;
    guint32 blk_size;
    const char* fs_id;
    gboolean descend;

    if(inf)
        g_object_ref(inf);
    else
    {
_retry_query_info:
        inf = g_file_query_info(gf, query_str,
                                (job->flags & FM_DC_JOB_FOLLOW_LINKS) ? 0 : G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
                                fm_job_get_cancellable(fmjob), &err);
        if(!inf)
        {
            FmJobErrorAction act = fm_job_emit_error(FM_JOB(job), err, FM_JOB_ERROR_MILD);
            g_error_free(err);
            err = NULL;
            if(act == FM_JOB_RETRY)
                goto _retry_query_info;
            return FALSE;
        }
    }
    if(fm_job_is_cancelled(fmjob))
    {
        g_object_unref(gf);
        g_object_unref(inf);
        return FALSE;
    }

    type = g_file_info_get_file_type(inf);
    blk = g_file_info_get_attribute_uint64(inf, G_FILE_ATTRIBUTE_UNIX_BLOCKS);
    blk_size= g_file_info_get_attribute_uint32(inf, G_FILE_ATTRIBUTE_UNIX_BLOCK_SIZE);
    descend = TRUE;

    ++job->count;
    job->total_size += g_file_info_get_size(inf);
    job->total_block_size += (blk * blk_size);

    /* prepare for moving across different devices */
    if( job->flags & FM_DC_JOB_PREPARE_MOVE )
    {
        fs_id = g_file_info_get_attribute_string(inf, G_FILE_ATTRIBUTE_ID_FILESYSTEM);
        if( g_strcmp0(fs_id, job->dest_fs_id) != 0 )
        {
            /* files on different device requires an additional 'delete' for the source file. */
            ++job->total_size; /* this is for the additional delete */
            ++job->total_block_size;
            ++job->count;
        }
        else
            descend = FALSE;
    }

    if( type == G_FILE_TYPE_DIRECTORY )
    {
        FmPath* fm_path = fm_path_new_for_gfile(gf);
        /* check if we need to decends into the dir. */
        /* trash:/// doesn't support deleting files recursively */
        if(job->flags & FM_DC_JOB_PREPARE_DELETE && fm_path_is_trash_file(fm_path) && ! fm_path_is_trash_root(fm_path))
            descend = FALSE;
        else
        {
            /* only descends into files on the same filesystem */
            if( job->flags & FM_DC_JOB_SAME_FS )
            {
                fs_id = g_file_info_get_attribute_string(inf, G_FILE_ATTRIBUTE_ID_FILESYSTEM);
                descend = (g_strcmp0(fs_id, job->dest_fs_id) == 0);
            }
        }
        fm_path_unref(fm_path);
        g_object_unref(inf);
        inf = NULL;

        if(descend)
        {
            GFileEnumerator* enu;
_retry_enum_children:
            enu = g_file_enumerate_children(gf, query_str,
                                            G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
                                            fm_job_get_cancellable(fmjob), &err);
            if(enu)
            {
                while( !fm_job_is_cancelled(fmjob) )
                {
                    inf = g_file_enumerator_next_file(enu, fm_job_get_cancellable(fmjob), &err);
                    if(inf)
                    {
                        GFile* child = g_file_get_child(gf, g_file_info_get_name(inf));
                        deep_count_gio(job, inf, child);
                        g_object_unref(child);
                        g_object_unref(inf);
                    }
                    else
                    {
                        if(err) /* error! */
                        {
                            /* FM_JOB_RETRY is not supported */
                            FmJobErrorAction act = fm_job_emit_error(FM_JOB(job), err, FM_JOB_ERROR_MILD);
                            g_error_free(err);
                            err = NULL;
                        }
                        else
                        {
                            /* EOF is reached, do nothing. */
                            break;
                        }
                    }
                }
                g_file_enumerator_close(enu, NULL, NULL);
                g_object_unref(enu);
            }
            else
            {
                FmJobErrorAction act = fm_job_emit_error(FM_JOB(job), err, FM_JOB_ERROR_MILD);
                g_error_free(err);
                err = NULL;
                if(act == FM_JOB_RETRY)
                    goto _retry_enum_children;
            }
        }
    }
    else
        g_object_unref(inf);

    return TRUE;
}
Esempio n. 16
0
static void
load_config (void)
{
  gchar  *path;
  GError *err = NULL;
  
  G_settings = gwh_settings_get_default ();
  
  gwh_settings_install_property (G_settings, g_param_spec_boolean (
    "browser-auto-reload",
    _("Browser auto reload"),
    _("Whether the browser reloads itself upon document saving"),
    TRUE,
    G_PARAM_READWRITE));
  gwh_settings_install_property (G_settings, g_param_spec_string (
    "browser-last-uri",
    _("Browser last URI"),
    _("Last URI visited by the browser"),
    "about:blank",
    G_PARAM_READWRITE));
  gwh_settings_install_property (G_settings, g_param_spec_boxed (
    "browser-bookmarks",
    _("Bookmarks"),
    _("List of bookmarks"),
    G_TYPE_STRV,
    G_PARAM_READWRITE));
  gwh_settings_install_property (G_settings, g_param_spec_enum (
    "browser-orientation",
    _("Browser orientation"),
    _("Orientation of the browser widget"),
    GTK_TYPE_ORIENTATION,
    GTK_ORIENTATION_VERTICAL,
    G_PARAM_READWRITE));
  gwh_settings_install_property (G_settings, g_param_spec_enum (
    "browser-position",
    _("Browser position"),
    _("Position of the browser widget in Geany's UI"),
    GWH_TYPE_BROWSER_POSITION,
    GWH_BROWSER_POSITION_MESSAGE_WINDOW,
    G_PARAM_READWRITE));
  gwh_settings_install_property (G_settings, g_param_spec_string (
    "browser-separate-window-geometry",
    _("Browser separate window geometry"),
    _("Last geometry of the separated browser's window"),
    "400x300",
    G_PARAM_READWRITE));
  gwh_settings_install_property (G_settings, g_param_spec_string (
    "inspector-window-geometry",
    _("Inspector window geometry"),
    _("Last geometry of the inspector window"),
    "400x300",
    G_PARAM_READWRITE));
  gwh_settings_install_property (G_settings, g_param_spec_boolean (
    "inspector-detached",
    _("Inspector detached"),
    _("Whether the inspector is in a separate window or docked in the browser"),
    FALSE,
    G_PARAM_READWRITE));
  gwh_settings_install_property (G_settings, g_param_spec_boolean (
    "wm-secondary-windows-skip-taskbar",
    _("Secondary windows skip task bar"),
    _("Whether to tell the window manager not to show the secondary windows in the task bar"),
    TRUE,
    G_PARAM_READWRITE));
  gwh_settings_install_property (G_settings, g_param_spec_boolean (
    "wm-secondary-windows-are-transient",
    _("Secondary windows are transient"),
    _("Whether secondary windows are transient children of their parent"),
    TRUE,
    G_PARAM_READWRITE));
  gwh_settings_install_property (G_settings, g_param_spec_enum (
    "wm-secondary-windows-type",
    _("Secondary windows type"),
    _("The type of the secondary windows"),
    GWH_TYPE_WINDOW_TYPE,
    GWH_WINDOW_TYPE_NORMAL,
    G_PARAM_READWRITE));
  
  path = get_config_filename ();
  if (! gwh_settings_load_from_file (G_settings, path, &err)) {
    g_warning ("Failed to load configuration: %s", err->message);
    g_error_free (err);
  }
  g_free (path);
}
Esempio n. 17
0
/**
 * as_pool_refresh_cache:
 * @pool: An instance of #AsPool.
 * @force: Enforce refresh, even if source data has not changed.
 *
 * Update the AppStream cache. There is normally no need to call this function manually, because cache updates are handled
 * transparently in the background.
 *
 * Returns: %TRUE if the cache was updated, %FALSE on error or if the cache update was not necessary and has been skipped.
 */
gboolean
as_pool_refresh_cache (AsPool *pool, gboolean force, GError **error)
{
	AsPoolPrivate *priv = GET_PRIVATE (pool);
	gboolean ret = FALSE;
	gboolean ret_poolupdate;
	g_autofree gchar *cache_fname = NULL;
	g_autoptr(GError) tmp_error = NULL;

	/* try to create cache directory, in case it doesn't exist */
	g_mkdir_with_parents (priv->sys_cache_path, 0755);
	if (!as_utils_is_writable (priv->sys_cache_path)) {
		g_set_error (error,
				AS_POOL_ERROR,
				AS_POOL_ERROR_TARGET_NOT_WRITABLE,
				_("Cache location '%s' is not writable."), priv->sys_cache_path);
		return FALSE;
	}

	/* collect metadata */
#ifdef HAVE_APT_SUPPORT
	/* currently, we only do something here if we are running with explicit APT support compiled in */
	as_pool_scan_apt (pool, force, &tmp_error);
	if (tmp_error != NULL) {
		/* the exact error is not forwarded here, since we might be able to partially update the cache */
		g_warning ("Error while collecting metadata: %s", tmp_error->message);
		g_error_free (tmp_error);
		tmp_error = NULL;
	}
#endif

	/* create the filename of our cache */
	cache_fname = g_strdup_printf ("%s/%s.gvz", priv->sys_cache_path, priv->locale);

	/* check if we need to refresh the cache
	 * (which is only necessary if the AppStream data has changed) */
	if (!as_pool_metadata_changed (pool)) {
		g_debug ("Data did not change, no cache refresh needed.");
		if (force) {
			g_debug ("Forcing refresh anyway.");
		} else {
			return FALSE;
		}
	}
	g_debug ("Refreshing AppStream cache");

	/* ensure we start with an empty pool */
	as_pool_clear (pool);

	/* NOTE: we will only cache AppStream metadata, no .desktop file metadata etc. */

	/* find them wherever they are */
	ret = as_pool_load_appstream (pool, &tmp_error);
	ret_poolupdate = as_pool_refine_data (pool) && ret;
	if (tmp_error != NULL) {
		/* the exact error is not forwarded here, since we might be able to partially update the cache */
		g_warning ("Error while updating the in-memory data pool: %s", tmp_error->message);
		g_error_free (tmp_error);
		tmp_error = NULL;
	}

	/* save the cache object */
	as_pool_save_cache_file (pool, cache_fname, &tmp_error);
	if (tmp_error != NULL) {
		/* the exact error is not forwarded here, since we might be able to partially update the cache */
		g_warning ("Error while updating the cache: %s", tmp_error->message);
		g_error_free (tmp_error);
		tmp_error = NULL;
		ret = FALSE;
	} else {
		ret = TRUE;
	}

	if (ret) {
		if (!ret_poolupdate) {
			g_set_error (error,
				AS_POOL_ERROR,
				AS_POOL_ERROR_INCOMPLETE,
				_("AppStream data pool was loaded, but some metadata was ignored due to errors."));
		}
		/* update the cache mtime, to not needlessly rebuild it again */
		as_touch_location (cache_fname);
		as_pool_check_cache_ctime (pool);
	} else {
		g_set_error (error,
				AS_POOL_ERROR,
				AS_POOL_ERROR_FAILED,
				_("AppStream cache update failed."));
	}

	return TRUE;
}
static gboolean
find_max_width_and_height (const gchar *uri,
                           guint       *width,
                           guint       *height)
{
	GError *error = NULL;
	GFile *file;
	GFileInputStream *stream;
	guint n_images;
	guint i;
	guint16 header [ICON_HEADER_SIZE_16];

	*width = 0;
	*height = 0;

	file = g_file_new_for_uri (uri);
	stream = g_file_read (file, NULL, &error);
	if (error) {
		g_message ("Could not read file '%s': %s",
		           uri,
		           error->message);
		g_error_free (error);
		g_object_unref (file);

		return FALSE;
	}

	/* Header consists of:
	 *  - 2bytes, reserved, must be 0
	 *  - 2bytes, image type (1:icon, 2:cursor, other values invalid)
	 *  - 2bytes, number of images in the file.
	 *
	 * Right now we just need the number of images in the file.
	 */
	if (!g_input_stream_read_all (G_INPUT_STREAM (stream),
	                              header,
	                              ICON_HEADER_SIZE_16 * 2,
	                              NULL,
	                              NULL,
	                              &error)) {
		g_message ("Error reading icon header from stream: '%s'",
		           error->message);
		g_error_free (error);
		g_object_unref (stream);
		g_object_unref (file);
		return FALSE;
	}

	n_images = GUINT16_FROM_LE (header[2]);
	g_debug ("Found '%u' images in the icon file...", n_images);

	/* Loop images looking for the biggest one... */
	for (i = 0; i < n_images; i++) {
		guint8 image_metadata [ICON_IMAGE_METADATA_SIZE_8];

		/* Image metadata chunk consists of:
		 *  - 1 byte, width in pixels, 0 means 256
		 *  - 1 byte, height in pixels, 0 means 256
		 *  - Plus some other stuff we don't care about...
		 */
		if (!g_input_stream_read_all (G_INPUT_STREAM (stream),
		                              image_metadata,
		                              ICON_IMAGE_METADATA_SIZE_8,
		                              NULL,
		                              NULL,
		                              &error)) {
			g_message ("Error reading icon image metadata '%u' from stream: '%s'",
			           i,
			           error->message);
			g_error_free (error);
			break;
		}

		g_debug ("  Image '%u'; width:%u height:%u",
		         i,
		         image_metadata[0],
		         image_metadata[1]);

		/* Width... */
		if (image_metadata[0] == 0) {
			*width = 256;
		} else if (image_metadata[0] > *width) {
			*width = image_metadata[0];
		}

		/* Height... */
		if (image_metadata[1] == 0) {
			*height = 256;
		} else if (image_metadata[1] > *width) {
			*height = image_metadata[0];
		}
	}

	g_input_stream_close (G_INPUT_STREAM (stream), NULL, NULL);
	g_object_unref (stream);
	g_object_unref (file);
	return TRUE;
}
Esempio n. 19
0
/**
 * as_pool_load_desktop_entries:
 *
 * Load fresh metadata from .desktop files.
 */
static void
as_pool_load_desktop_entries (AsPool *pool)
{
	GPtrArray *cpts;
	guint i;
	g_autoptr(AsMetadata) metad = NULL;
	g_autoptr(GPtrArray) de_files = NULL;
	GError *error = NULL;
	AsPoolPrivate *priv = GET_PRIVATE (pool);

	/* prepare metadata parser */
	metad = as_metadata_new ();
	as_metadata_set_locale (metad, priv->locale);

	/* find .desktop files */
	g_debug ("Searching for data in: %s", APPLICATIONS_DIR);
	de_files = as_utils_find_files_matching (APPLICATIONS_DIR, "*.desktop", FALSE, NULL);
	if (de_files == NULL) {
		g_debug ("Unable find .desktop files.");
		return;
	}

	/* parse the found data */
	for (i = 0; i < de_files->len; i++) {
		g_autoptr(GFile) infile = NULL;
		const gchar *fname;

		fname = (const gchar*) g_ptr_array_index (de_files, i);
		g_debug ("Reading: %s", fname);

		infile = g_file_new_for_path (fname);
		if (!g_file_query_exists (infile, NULL)) {
			g_warning ("Metadata file '%s' does not exist.", fname);
			continue;
		}

		as_metadata_parse_file (metad,
					infile,
					AS_FORMAT_KIND_UNKNOWN,
					&error);
		if (error != NULL) {
			g_debug ("WARNING: %s", error->message);
			g_error_free (error);
			error = NULL;
		}
	}

	/* add found components to the metadata pool */
	cpts = as_metadata_get_components (metad);
	for (i = 0; i < cpts->len; i++) {
		AsComponent *cpt = AS_COMPONENT (g_ptr_array_index (cpts, i));

		/* We only read .desktop files from system directories at time */
		as_component_set_scope (cpt, AS_COMPONENT_SCOPE_SYSTEM);

		as_pool_add_component_internal (pool, cpt, FALSE, &error);
		if (error != NULL) {
			g_debug ("Metadata ignored: %s", error->message);
			g_error_free (error);
			error = NULL;
		}
	}
}
Esempio n. 20
0
static gboolean
fish_read_output (GIOChannel   *source,
		  GIOCondition  condition,
		  gpointer      data)
{
	char        output[4096];
	char       *utf8_output;
	gsize       bytes_read;
	GError     *error = NULL;
	GIOStatus   status;
	FishApplet *fish;

	fish = (FishApplet *) data;

	if (!(condition & G_IO_IN)) {
		fish->source_id = 0;
		fish_close_channel (fish);
		return FALSE;
	}

	status = g_io_channel_read_chars (source, output, 4096, &bytes_read,
					  &error);

	if (error) {
		char *message;

		message = g_strdup_printf (_("Unable to read output from command\n\nDetails: %s"),
					   error->message);
		something_fishy_going_on (fish, message);
		g_free (message);
		g_error_free (error);
		fish->source_id = 0;
		fish_close_channel (fish);
		return FALSE;
	}

	if (status == G_IO_STATUS_AGAIN)
		return TRUE;

	if (bytes_read > 0) {
		/* The output is not guarantied to be in UTF-8 format, most
		 * likely it's just in ASCII-7 or in the user locale
		 */
		if (!g_utf8_validate (output, -1, NULL))
			utf8_output = g_locale_to_utf8 (output, bytes_read,
							NULL, NULL, NULL);
		else
			utf8_output = g_strndup (output, bytes_read);

		if (utf8_output)
			insert_fortune_text (fish, utf8_output);

		g_free (utf8_output);
	}

	if (status == G_IO_STATUS_EOF) {
		fish->source_id = 0;
		fish_close_channel (fish);
	}
	return (status != G_IO_STATUS_EOF);
}
Esempio n. 21
0
static gboolean
gst_net_client_internal_clock_start (GstNetClientInternalClock * self)
{
  GSocketAddress *servaddr;
  GSocketAddress *myaddr;
  GSocketAddress *anyaddr;
  GInetAddress *inetaddr;
  GSocket *socket;
  GError *error = NULL;
  GSocketFamily family;
  GPollFD dummy_pollfd;
  GResolver *resolver = NULL;
  GError *err = NULL;

  g_return_val_if_fail (self->address != NULL, FALSE);
  g_return_val_if_fail (self->servaddr == NULL, FALSE);

  /* create target address */
  inetaddr = g_inet_address_new_from_string (self->address);
  if (inetaddr == NULL) {
    GList *results;

    resolver = g_resolver_get_default ();

    results = g_resolver_lookup_by_name (resolver, self->address, NULL, &err);
    if (!results)
      goto failed_to_resolve;

    inetaddr = G_INET_ADDRESS (g_object_ref (results->data));
    g_resolver_free_addresses (results);
    g_object_unref (resolver);
  }

  family = g_inet_address_get_family (inetaddr);

  servaddr = g_inet_socket_address_new (inetaddr, self->port);
  g_object_unref (inetaddr);

  g_assert (servaddr != NULL);

  GST_DEBUG_OBJECT (self, "will communicate with %s:%d", self->address,
      self->port);

  socket = g_socket_new (family, G_SOCKET_TYPE_DATAGRAM,
      G_SOCKET_PROTOCOL_UDP, &error);

  if (socket == NULL)
    goto no_socket;

  GST_DEBUG_OBJECT (self, "binding socket");
  inetaddr = g_inet_address_new_any (family);
  anyaddr = g_inet_socket_address_new (inetaddr, 0);
  g_socket_bind (socket, anyaddr, TRUE, &error);
  g_object_unref (anyaddr);
  g_object_unref (inetaddr);

  if (error != NULL)
    goto bind_error;

  /* check address we're bound to, mostly for debugging purposes */
  myaddr = g_socket_get_local_address (socket, &error);

  if (myaddr == NULL)
    goto getsockname_error;

  GST_DEBUG_OBJECT (self, "socket opened on UDP port %d",
      g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (myaddr)));

  g_object_unref (myaddr);

  self->cancel = g_cancellable_new ();
  self->made_cancel_fd =
      g_cancellable_make_pollfd (self->cancel, &dummy_pollfd);

  self->socket = socket;
  self->servaddr = G_SOCKET_ADDRESS (servaddr);

  self->thread = g_thread_try_new ("GstNetClientInternalClock",
      gst_net_client_internal_clock_thread, self, &error);

  if (error != NULL)
    goto no_thread;

  return TRUE;

  /* ERRORS */
no_socket:
  {
    GST_ERROR_OBJECT (self, "socket_new() failed: %s", error->message);
    g_error_free (error);
    return FALSE;
  }
bind_error:
  {
    GST_ERROR_OBJECT (self, "bind failed: %s", error->message);
    g_error_free (error);
    g_object_unref (socket);
    return FALSE;
  }
getsockname_error:
  {
    GST_ERROR_OBJECT (self, "get_local_address() failed: %s", error->message);
    g_error_free (error);
    g_object_unref (socket);
    return FALSE;
  }
failed_to_resolve:
  {
    GST_ERROR_OBJECT (self, "resolving '%s' failed: %s",
        self->address, err->message);
    g_clear_error (&err);
    g_object_unref (resolver);
    return FALSE;
  }
no_thread:
  {
    GST_ERROR_OBJECT (self, "could not create thread: %s", error->message);
    g_object_unref (self->servaddr);
    self->servaddr = NULL;
    g_object_unref (self->socket);
    self->socket = NULL;
    g_error_free (error);
    return FALSE;
  }
}
Esempio n. 22
0
static void 
display_fortune_dialog (FishApplet *fish)
{
	GError      *error = NULL;
	gboolean     user_command;
	int          output;
	const char  *charset;
	int          argc;
	char       **argv;
	GdkScreen   *screen;
	char        *display;

	/* if there is still a pipe, close it */
	if (fish->source_id)
		g_source_remove (fish->source_id);
	fish->source_id = 0;
	fish_close_channel (fish);

	user_command = locate_fortune_command (fish, &argc, &argv);
	if (!argv)
		return;

	if (!fish->fortune_dialog) {
		GtkWidget *scrolled;
		GtkWidget *vbox;
		GdkScreen *screen;
		int        screen_width;
		int        screen_height;
      
		fish->fortune_dialog = 
			gtk_dialog_new_with_buttons (
				"", NULL, 0,
				_("_Speak again"), FISH_RESPONSE_SPEAK,
				_("_Close"), GTK_RESPONSE_CLOSE,
				NULL);

		gtk_window_set_icon_name (GTK_WINDOW (fish->fortune_dialog),
					  FISH_ICON);

		gtk_dialog_set_default_response (
			GTK_DIALOG (fish->fortune_dialog), GTK_RESPONSE_CLOSE);

		g_signal_connect (fish->fortune_dialog, "delete_event",
				  G_CALLBACK (delete_event), fish);
		g_signal_connect (fish->fortune_dialog, "response",
				  G_CALLBACK (handle_fortune_response), fish);

		gtk_window_set_wmclass (GTK_WINDOW (fish->fortune_dialog), "fish", "Fish");

		screen = gtk_widget_get_screen (GTK_WIDGET (fish));

		screen_width  = gdk_screen_get_width (screen);
		screen_height = gdk_screen_get_height (screen);

		gtk_window_set_default_size (GTK_WINDOW (fish->fortune_dialog),
					     MIN (600, screen_width  * 0.9),
					     MIN (350, screen_height * 0.9));

		fish->fortune_view = gtk_text_view_new ();
		gtk_text_view_set_editable (GTK_TEXT_VIEW (fish->fortune_view), FALSE);
		gtk_text_view_set_cursor_visible (GTK_TEXT_VIEW (fish->fortune_view), FALSE);
		gtk_text_view_set_left_margin (GTK_TEXT_VIEW (fish->fortune_view), 10);
		gtk_text_view_set_right_margin (GTK_TEXT_VIEW (fish->fortune_view), 10);
		fish->fortune_buffer =
			gtk_text_view_get_buffer (GTK_TEXT_VIEW (fish->fortune_view));

		gtk_text_buffer_create_tag (GTK_TEXT_BUFFER (fish->fortune_buffer),
					    "monospace_tag", "family",
					    "Monospace", NULL);

		scrolled = gtk_scrolled_window_new (NULL, NULL);
		gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled),
						GTK_POLICY_AUTOMATIC,
						GTK_POLICY_AUTOMATIC);
		gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolled),
						     GTK_SHADOW_IN);

		gtk_container_add (GTK_CONTAINER (scrolled), fish->fortune_view);

		fish->fortune_label = gtk_label_new ("");
		gtk_label_set_ellipsize (GTK_LABEL (fish->fortune_label),
					 PANGO_ELLIPSIZE_MIDDLE);
		fish->fortune_cmd_label = gtk_label_new ("");
		gtk_misc_set_alignment (GTK_MISC (fish->fortune_cmd_label),
					0, 0.5);

		vbox = gtk_dialog_get_content_area (GTK_DIALOG (fish->fortune_dialog));
		gtk_box_pack_start (GTK_BOX (vbox),
				    fish->fortune_label,
				    FALSE, FALSE, 6);

		gtk_box_pack_start (GTK_BOX (vbox),
				    scrolled,
				    TRUE, TRUE, 6);

		gtk_box_pack_start (GTK_BOX (vbox),
				    fish->fortune_cmd_label,
				    FALSE, FALSE, 6);

		update_fortune_dialog (fish);

		/* We don't show_all for the dialog since fortune_cmd_label
		 * might need to be hidden 
		 * The dialog will be shown with gtk_window_present later */
		gtk_widget_show (scrolled);
		gtk_widget_show (fish->fortune_view);
		gtk_widget_show (fish->fortune_label);
	}

	if (!user_command) {
		char *command;
		char * text;

		command = g_markup_printf_escaped ("<tt>%s</tt>", argv[0]);
		text = g_strdup_printf (_("The configured command is not "
					  "working and has been replaced by: "
					  "%s"), command);
		gtk_label_set_markup (GTK_LABEL (fish->fortune_cmd_label),
				      text);
		g_free (command);
		g_free (text);
		gtk_widget_show (fish->fortune_cmd_label);
	} else {
		gtk_widget_hide (fish->fortune_cmd_label);
	}

	clear_fortune_text (fish);

	screen = gtk_widget_get_screen (GTK_WIDGET (fish));
	display = gdk_screen_make_display_name (screen);

	g_spawn_async_with_pipes (NULL, /* working directory */
				  argv,
				  NULL, /* envp */
				  G_SPAWN_SEARCH_PATH|G_SPAWN_STDERR_TO_DEV_NULL,
				  set_environment,
				  &display,
				  NULL, /* child pid */
				  NULL, /* stdin */
				  &output,
				  NULL, /* stderr */
				  &error);

	g_free (display);

	if (error) {
		char *message;

		message = g_strdup_printf (_("Unable to execute '%s'\n\nDetails: %s"),
					   argv[0], error->message);
		something_fishy_going_on (fish, message);
		g_free (message);
		g_error_free (error);
		g_strfreev (argv);
		return;
	}

	fish->io_channel = g_io_channel_unix_new (output);
	/* set the correct encoding if the locale is not using UTF-8 */
	if (!g_get_charset (&charset))
		g_io_channel_set_encoding(fish->io_channel, charset, &error);
	if (error) {
		char *message;

		message = g_strdup_printf (_("Unable to read from '%s'\n\nDetails: %s"),
					   argv[0], error->message);
		something_fishy_going_on (fish, message);
		g_free (message);
		g_error_free (error);
		g_strfreev (argv);
		return;
	}

	g_strfreev (argv);

	fish->source_id = g_io_add_watch (fish->io_channel,
					  G_IO_IN|G_IO_ERR|G_IO_HUP|G_IO_NVAL,
					  fish_read_output, fish);

	gtk_window_set_screen (GTK_WINDOW (fish->fortune_dialog),
			       gtk_widget_get_screen (GTK_WIDGET (fish)));
	gtk_window_present (GTK_WINDOW (fish->fortune_dialog));
}
static gboolean
_list_preferences_dialog_validate_username(GtkWidget *dialog)
{
	_ListPreferencesWindowData *windata;
	gchar *name;
	TwitterDbHandle *handle;
	GError *err = NULL;
	gboolean result = TRUE;

	g_assert(GTK_IS_DELETABLE_DIALOG(dialog));

	windata = (_ListPreferencesWindowData *)g_object_get_data(G_OBJECT(dialog), "windata");

	/* get entered name */
	name = g_strdup(gtk_entry_get_text(GTK_ENTRY(windata->entry_name)));
	name = g_strstrip(name);

	/* check if name has been modified */
	if(g_strcmp0(windata->previous_listname, name))
	{
		result = FALSE;

		/* check if name is empty */
		if(strlen(name))
		{
			/* check if list does already exist */
			if((handle = twitterdb_get_handle(&err)))
			{
				if(twitterdb_list_exists(handle, windata->owner, name, &err))
				{
					_list_preferences_dialog_show_failure(GTK_WIDGET(dialog), _("A list with the given name does already exist."));
				}
				else if(err)
				{
					_list_preferences_dialog_show_failure(GTK_WIDGET(dialog), err->message);
					g_error_free(err);
				}
				else
				{
					result = TRUE;
				}

				twitterdb_close_handle(handle);
			}
			else
			{
				if(err)
				{
					_list_preferences_dialog_show_failure(GTK_WIDGET(dialog), err->message);
					g_error_free(err);
				}
				else
				{
					_list_preferences_dialog_show_failure(GTK_WIDGET(dialog), _("Couldn't update list, an internal failure occured."));
				}
			}
		}
		else
		{
			_list_preferences_dialog_show_failure(GTK_WIDGET(dialog), _("Please enter a name for the list."));
		}
	}

	if(!result)
	{
		gtk_widget_grab_focus(windata->entry_name);
	}

	g_free(name);

	return result;
}
static void stdin_read_complete(GObject *src, GAsyncResult *res, gpointer data)
{
    char *s, *ep;
    GError *err = NULL;
    gsize len;

    s = g_data_input_stream_read_line_finish(G_DATA_INPUT_STREAM(src), res,
                                             &len, &err);
    if (!s) {
        if (err) {
            FATAL_ERROR("Reading from stdin: %s\n", err->message);
            g_error_free(err);
            return;
        }

        switch (state) {
        case STATE_WAITING_FOR_BUS_N_DEV:
            FATAL_ERROR("EOF while waiting for bus and device num\n");
            break;
        case STATE_WAITING_FOR_POL_KIT:
            ERROR("Cancelled while waiting for authorization\n");
            break;
        case STATE_WAITING_FOR_STDIN_EOF:
            cleanup();
            break;
        }
        return;
    }

    switch (state) {
    case STATE_WAITING_FOR_BUS_N_DEV:
        busnum = strtol(s, &ep, 10);
        if (!isspace(*ep)) {
            FATAL_ERROR("Invalid busnum / devnum: %s\n", s);
            break;
        }
        devnum = strtol(ep, &ep, 10);
        if (*ep != '\0') {
            FATAL_ERROR("Invalid busnum / devnum: %s\n", s);
            break;
        }

        /*
         * The set_facl() call is a no-op for root, so no need to ask PolKit
         * and then if ok call set_facl(), when called by a root process.
         */
        if (getuid() != 0) {
            polkit_cancellable = g_cancellable_new();
            polkit_authority_check_authorization(
                authority, subject, "org.spice-space.lowlevelusbaccess", NULL,
                POLKIT_CHECK_AUTHORIZATION_FLAGS_ALLOW_USER_INTERACTION,
                polkit_cancellable,
                (GAsyncReadyCallback)check_authorization_cb, NULL);
            state = STATE_WAITING_FOR_POL_KIT;
        } else {
            fprintf(stdout, "SUCCESS\n");
            fflush(stdout);
            state = STATE_WAITING_FOR_STDIN_EOF;
        }

        g_data_input_stream_read_line_async(stdin_stream, G_PRIORITY_DEFAULT,
                                            NULL, stdin_read_complete, NULL);
        break;
    default:
        FATAL_ERROR("Unexpected extra input in state %d: %s\n", state, s);
    }
    g_free(s);
}
Esempio n. 25
0
static void
on_new_kinect_device (GObject      *obj,
                      GAsyncResult *res,
                      gpointer      user_data)
{
  ClutterActor *stage, *instructions;
  GError *error = NULL;
  gint width = 640;
  gint height = 480;

  kinect = gfreenect_device_new_finish (res, &error);
  if (kinect == NULL)
    {
      g_debug ("Failed to created kinect device: %s", error->message);
      g_error_free (error);
      clutter_main_quit ();
      return;
    }

  g_debug ("Kinect device created!");

  stage = clutter_stage_new ();
  clutter_stage_set_title (CLUTTER_STAGE (stage), "Kinect Test");
  clutter_actor_set_size (stage, width * 2, height + 250);
  clutter_stage_set_user_resizable (CLUTTER_STAGE (stage), TRUE);

  g_signal_connect (stage, "destroy", G_CALLBACK (on_destroy), kinect);
  g_signal_connect (stage,
                    "key-release-event",
                    G_CALLBACK (on_key_release),
                    kinect);

  depth_tex = clutter_actor_new ();
  depth_canvas = clutter_canvas_new ();
  clutter_actor_set_content (depth_tex, depth_canvas);
  clutter_canvas_set_size (CLUTTER_CANVAS (depth_canvas), width, height);
  clutter_actor_set_size (depth_tex, width, height);
  clutter_actor_add_child (stage, depth_tex);

  video_tex = clutter_actor_new ();
  clutter_actor_set_content (video_tex, clutter_image_new ());
  clutter_actor_set_size (video_tex, width, height);
  clutter_actor_set_position (video_tex, width, 0.0);
  clutter_actor_add_child (stage, video_tex);

  info_text = clutter_text_new ();
  clutter_actor_set_position (info_text, 50, height + 20);
  clutter_actor_add_child (stage, info_text);

  instructions = create_instructions ();
  clutter_actor_set_position (instructions, 50, height + 70);
  clutter_actor_add_child (stage, instructions);

  skeleton = skeltrack_skeleton_new ();
  g_object_get (skeleton, "smoothing-factor", &SMOOTHING_FACTOR, NULL);

  set_info_text ();

  g_signal_connect (kinect,
                    "depth-frame",
                    G_CALLBACK (on_depth_frame),
                    NULL);

  g_signal_connect (kinect,
                    "video-frame",
                    G_CALLBACK (on_video_frame),
                    NULL);

  g_signal_connect (depth_canvas,
                    "draw",
                    G_CALLBACK (on_skeleton_draw),
                    NULL);

  gfreenect_device_set_tilt_angle (kinect, 0, NULL, NULL, NULL);

  gfreenect_device_start_depth_stream (kinect,
                                       GFREENECT_DEPTH_FORMAT_MM,
                                       NULL);

  gfreenect_device_start_video_stream (kinect,
                                       GFREENECT_RESOLUTION_MEDIUM,
                                       GFREENECT_VIDEO_FORMAT_RGB, NULL);

  clutter_actor_show (stage);
}
Esempio n. 26
0
void
cockpit_block_samples (CockpitSamples *samples)
{
  gchar *contents = NULL;
  gsize len;
  GError *error = NULL;
  gchar **lines = NULL;
  guint n;

  if (!g_file_get_contents ("/proc/diskstats", &contents, &len, &error))
    {
      g_message ("error loading contents /proc/diskstats: %s", error->message);
      g_error_free (error);
      goto out;
    }

  lines = g_strsplit (contents, "\n", -1);
  for (n = 0; lines != NULL && lines[n] != NULL; n++)
    {
      const gchar *line = lines[n];
      guint num_parsed;
      gint dev_major, dev_minor;
      gchar dev_name[64]; /* TODO: big enough? */
      guint64 num_reads,  num_reads_merged,  num_sectors_read,    num_msec_reading;
      guint64 num_writes, num_writes_merged, num_sectors_written, num_msec_writing;
      guint64 num_io_in_progress, num_msec_doing_io, weighted_num_msec_doing_io;

      if (strlen (line) == 0)
        continue;

      /* From http://www.kernel.org/doc/Documentation/iostats.txt
       *
       * Field  1 -- # of reads completed
       *     This is the total number of reads completed successfully.
       * Field  2 -- # of reads merged, field 6 -- # of writes merged
       *     Reads and writes which are adjacent to each other may be merged for
       *     efficiency.  Thus two 4K reads may become one 8K read before it is
       *     ultimately handed to the disk, and so it will be counted (and queued)
       *     as only one I/O.  This field lets you know how often this was done.
       * Field  3 -- # of sectors read
       *     This is the total number of sectors read successfully.
       * Field  4 -- # of milliseconds spent reading
       *     This is the total number of milliseconds spent by all reads (as
       *     measured from __make_request() to end_that_request_last()).
       * Field  5 -- # of writes completed
       *     This is the total number of writes completed successfully.
       * Field  7 -- # of sectors written
       *     This is the total number of sectors written successfully.
       * Field  8 -- # of milliseconds spent writing
       *     This is the total number of milliseconds spent by all writes (as
       *     measured from __make_request() to end_that_request_last()).
       * Field  9 -- # of I/Os currently in progress
       *     The only field that should go to zero. Incremented as requests are
       *     given to appropriate struct request_queue and decremented as they finish.
       * Field 10 -- # of milliseconds spent doing I/Os
       *     This field increases so long as field 9 is nonzero.
       * Field 11 -- weighted # of milliseconds spent doing I/Os
       *     This field is incremented at each I/O start, I/O completion, I/O
       *     merge, or read of these stats by the number of I/Os in progress
       *     (field 9) times the number of milliseconds spent doing I/O since the
       *     last update of this field.  This can provide an easy measure of both
       *     I/O completion time and the backlog that may be accumulating.
       */

      num_parsed = sscanf (line,
                           "%d %d %64s"
                           " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT
                           " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT
                           " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT,
                           &dev_major, &dev_minor, dev_name,
                           &num_reads,  &num_reads_merged, &num_sectors_read, &num_msec_reading,
                           &num_writes, &num_writes_merged, &num_sectors_written, &num_msec_writing,
                           &num_io_in_progress, &num_msec_doing_io, &weighted_num_msec_doing_io);
      if (num_parsed != 14)
        {
          g_message ("error parsing line %d of file /proc/diskstats (num_parsed = %d): %s", n, num_parsed, line);
          continue;
        }

      cockpit_samples_sample (samples, "block.device.read", dev_name, num_sectors_read * 512);
      cockpit_samples_sample (samples, "block.device.written", dev_name, num_sectors_written * 512);
    }

out:
  g_clear_error (&error);
  g_strfreev (lines);
  g_free (contents);
}
Esempio n. 27
0
int
main( int argc, char** argv )
{
	static const gchar *thisfn = "caja_actions_run_main";
	int status = EXIT_SUCCESS;
	GOptionContext *context;
	GError *error = NULL;
	gchar *help;
	gint errors;
	NAObjectAction *action;
	NAObjectProfile *profile;
	GList *targets;

	g_type_init();
	setlocale( LC_ALL, "" );
	console_init_log_handler();

	/* pwi 2011-01-05
	 * run MateConf migration tools before doing anything else
	 * above all before allocating a new NAPivot
	 */
	na_mateconf_migration_run();

	context = init_options();

	if( argc == 1 ){
		g_set_prgname( argv[0] );
		help = g_option_context_get_help( context, FALSE, NULL );
		g_print( "\n%s", help );
		g_free( help );
		exit( status );
	}

	if( !g_option_context_parse( context, &argc, &argv, &error )){
		g_printerr( _( "Syntax error: %s\n" ), error->message );
		g_error_free (error);
		exit_with_usage();
	}

	g_option_context_free( context );

	if( version ){
		na_core_utils_print_version();
		exit( status );
	}

	errors = 0;

	if( !id || !strlen( id )){
		g_printerr( _( "Error: action id is mandatory.\n" ));
		errors += 1;
	}

	action = get_action( id );
	if( !action ){
		errors += 1;
	} else {
		g_debug( "%s: action %s have been found, and is enabled and valid", thisfn, id );
	}

	if( errors ){
		exit_with_usage();
	}

	if( targets_array ){
		targets = targets_from_commandline();

	} else {
		targets = targets_from_selection();
	}

	dump_targets( targets );

	if( g_list_length( targets ) == 0 ){
		g_print( _( "No current selection. Nothing to do. Exiting.\n" ));
		exit( status );
	}

	if( !na_icontext_is_candidate( NA_ICONTEXT( action ), ITEM_TARGET_ANY, targets )){
		g_printerr( _( "Action %s is not a valid candidate. Exiting.\n" ), id );
		exit( status );
	}

	profile = get_profile_for_targets( action, targets );
	if( !profile ){
		g_print( _( "No valid profile is candidate to execution. Exiting.\n" ));
		exit( status );
	}
	g_debug( "%s: profile %p found", thisfn, ( void * ) profile );

	execute_action( action, profile, targets );

	na_selected_info_free_list( targets );
	exit( status );
}
Esempio n. 28
0
gboolean deep_count_posix(FmDeepCountJob* job, FmPath* fm_path)
{
    FmJob* fmjob = (FmJob*)job;
    char* path = fm_path_to_str(fm_path);
    struct stat st;
    int ret;

_retry_stat:
    if( G_UNLIKELY(job->flags & FM_DC_JOB_FOLLOW_LINKS) )
        ret = stat(path, &st);
    else
        ret = lstat(path, &st);

    if( ret == 0 )
    {
        ++job->count;
        job->total_size += (goffset)st.st_size;
        job->total_block_size += (st.st_blocks * st.st_blksize);

        /* NOTE: if job->dest_dev is 0, that means our destination
         * folder is not on native UNIX filesystem. Hence it's not
         * on the same device. Our st.st_dev will always be non-zero
         * since our file is on a native UNIX filesystem. */

        /* only descends into files on the same filesystem */
        if( job->flags & FM_DC_JOB_SAME_FS )
        {
            if( st.st_dev != job->dest_dev )
                return TRUE;
        }
        /* only descends into files on the different filesystem */
        else if( job->flags & FM_DC_JOB_PREPARE_MOVE )
        {
            if( st.st_dev == job->dest_dev )
                return TRUE;
        }
    }
    else
    {
        GError* err = g_error_new(G_IO_ERROR, g_io_error_from_errno(errno), "%s", g_strerror(errno));
        FmJobErrorAction act = fm_job_emit_error(FM_JOB(job), err, FM_JOB_ERROR_MILD);
        g_error_free(err);
        err = NULL;
        if(act == FM_JOB_RETRY)
            goto _retry_stat;
        return FALSE;
    }
    if(fm_job_is_cancelled(fmjob))
        return FALSE;

    if( S_ISDIR(st.st_mode) ) /* if it's a dir */
    {
        GDir* dir_ent = g_dir_open(path, 0, NULL);
        if(dir_ent)
        {
            const char* basename;
            while( !fm_job_is_cancelled(fmjob)
                    && (basename = g_dir_read_name(dir_ent)) )
            {
                FmPath* sub = fm_path_new_child(fm_path, basename);
                if(!fm_job_is_cancelled(fmjob))
                {
                    if(deep_count_posix(job, sub))
                    {
                        /* for moving across different devices, an additional 'delete'
                         * for source file is needed. so let's +1 for the delete.*/
                        if(job->flags & FM_DC_JOB_PREPARE_MOVE)
                        {
                            ++job->total_size;
                            ++job->total_block_size;
                            ++job->count;
                        }
                    }
                }
                fm_path_unref(sub);
            }
            g_dir_close(dir_ent);
        }
    }
    g_free(path);
    return TRUE;
}
Esempio n. 29
0
void
entry_fill_from_node(Entry* e)
{
  gchar* tmp;
  GError* error = NULL;

  g_return_if_fail(e->node != NULL);
  
  tmp = my_xmlGetProp(e->node, "schema");
  
  if (tmp != NULL)
    {
      /* Filter any crap schemas that appear, some speed cost */
      gchar* why_bad = NULL;
      if (gconf_valid_key(tmp, &why_bad))
        {
          g_assert(why_bad == NULL);
          e->schema_name = g_strdup(tmp);
        }
      else
        {
          e->schema_name = NULL;
          gconf_log(GCL_WARNING, _("Ignoring schema name `%s', invalid: %s"),
                    tmp, why_bad);
          g_free(why_bad);
        }
          
      xmlFree(tmp);
    }
      
  tmp = my_xmlGetProp(e->node, "mtime");

  if (tmp != NULL)
    {
      e->mod_time = gconf_string_to_gulong(tmp);
      xmlFree(tmp);
    }
  else
    e->mod_time = 0;

  tmp = my_xmlGetProp(e->node, "muser");

  if (tmp != NULL)
    {
      e->mod_user = g_strdup(tmp);
      xmlFree(tmp);
    }
  else
    e->mod_user = NULL;

  entry_sync_if_needed(e);
  
  if (e->cached_value != NULL)
    gconf_value_free(e->cached_value);
  
  e->cached_value = node_extract_value(e->node, NULL, /* FIXME current locale as a guess */
                                       &error);

  if (e->cached_value)
    {
      g_return_if_fail(error == NULL);
      return;
    }
  else if (error != NULL)
    {
      /* Ignore errors from node_extract_value() if we got a schema name,
       * since the node's only purpose may be to store the schema name.
       */
      if (e->schema_name == NULL)
        gconf_log (GCL_WARNING,
                   _("Ignoring XML node `%s': %s"),
                   e->name, error->message);
      g_error_free(error);
    }
}
Esempio n. 30
0
bool_t mpris2_init (void)
{
    GError * error = NULL;
    GDBusConnection * bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, & error);

    if (! bus)
    {
        fprintf (stderr, "mpris2: %s\n", error->message);
        g_error_free (error);
        return FALSE;
    }

    g_bus_own_name_on_connection (bus, "org.mpris.MediaPlayer2.audacious", 0,
     NULL, NULL, NULL, NULL);

    object_core = (GObject *) mpris_media_player2_skeleton_new ();

    g_object_set (object_core,
     "can-quit", TRUE,
     "can-raise", TRUE,
     "desktop-entry", "audacious",
     "identity", "Audacious",
     NULL);

    g_signal_connect (object_core, "handle-quit", (GCallback) quit_cb, NULL);
    g_signal_connect (object_core, "handle-raise", (GCallback) raise_cb, NULL);

    object_player = (GObject *) mpris_media_player2_player_skeleton_new ();

    g_object_set (object_player,
     "can-control", TRUE,
     "can-go-next", TRUE,
     "can-go-previous", TRUE,
     "can-pause", TRUE,
     "can-play", TRUE,
     "can-seek", TRUE,
     NULL);

    update_timer = g_timeout_add (250, (GSourceFunc) update, object_player);
    update_playback_status (NULL, object_player);

    if (aud_drct_get_playing () && aud_drct_get_ready ())
        emit_seek (NULL, object_player);

    hook_associate ("playback begin", (HookFunction) update_playback_status, object_player);
    hook_associate ("playback pause", (HookFunction) update_playback_status, object_player);
    hook_associate ("playback stop", (HookFunction) update_playback_status, object_player);
    hook_associate ("playback unpause", (HookFunction) update_playback_status, object_player);

    hook_associate ("playlist set playing", (HookFunction) update_metadata, object_player);
    hook_associate ("playlist position", (HookFunction) update_metadata, object_player);
    hook_associate ("playlist update", (HookFunction) update_metadata, object_player);

    hook_associate ("current art ready", (HookFunction) update_image, object_player);

    hook_associate ("playback ready", (HookFunction) emit_seek, object_player);
    hook_associate ("playback seek", (HookFunction) emit_seek, object_player);

    g_signal_connect (object_player, "handle-next", (GCallback) next_cb, NULL);
    g_signal_connect (object_player, "handle-pause", (GCallback) pause_cb, NULL);
    g_signal_connect (object_player, "handle-play", (GCallback) play_cb, NULL);
    g_signal_connect (object_player, "handle-play-pause", (GCallback) play_pause_cb, NULL);
    g_signal_connect (object_player, "handle-previous", (GCallback) previous_cb, NULL);
    g_signal_connect (object_player, "handle-seek", (GCallback) seek_cb, NULL);
    g_signal_connect (object_player, "handle-set-position", (GCallback) set_position_cb, NULL);
    g_signal_connect (object_player, "handle-stop", (GCallback) stop_cb, NULL);

    g_signal_connect (object_player, "notify::volume", (GCallback) volume_changed, NULL);

    if (! g_dbus_interface_skeleton_export ((GDBusInterfaceSkeleton *)
     object_core, bus, "/org/mpris/MediaPlayer2", & error) ||
     ! g_dbus_interface_skeleton_export ((GDBusInterfaceSkeleton *)
     object_player, bus, "/org/mpris/MediaPlayer2", & error))
    {
        mpris2_cleanup ();
        fprintf (stderr, "mpris2: %s\n", error->message);
        g_error_free (error);
        return FALSE;
    }

    return TRUE;
}