Пример #1
0
static GFileInfo *
g_resource_file_query_info (GFile                *file,
			    const char           *attributes,
			    GFileQueryInfoFlags   flags,
			    GCancellable         *cancellable,
			    GError              **error)
{
  GResourceFile *resource = G_RESOURCE_FILE (file);
  GError *my_error = NULL;
  GFileInfo *info;
  GFileAttributeMatcher *matcher;
  gboolean res;
  gsize size;
  guint32 resource_flags;
  char **children;
  gboolean is_dir;
  char *base;

  is_dir = FALSE;
  children = g_resources_enumerate_children (resource->path, 0, NULL);
  if (children != NULL)
    {
      g_strfreev (children);
      is_dir = TRUE;
    }

  /* root is always there */
  if (strcmp ("/", resource->path) == 0)
    is_dir = TRUE;

  if (!is_dir)
    {
      res = g_resources_get_info (resource->path, 0, &size, &resource_flags, &my_error);
      if (!res)
	{
	  if (g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
	    {
	      g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
			   _("The resource at '%s' does not exist"),
			   resource->path);
	    }
	  else
	    g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                 my_error->message);
	  g_clear_error (&my_error);
	  return FALSE;
	}
    }

  matcher = g_file_attribute_matcher_new (attributes);

  info = g_file_info_new ();
  base = g_resource_file_get_basename (file);
  g_file_info_set_name (info, base);
  g_file_info_set_display_name (info, base);

  _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_READ, TRUE);
  _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_WRITE, FALSE);
  _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_EXECUTE, FALSE);
  _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME, FALSE);
  _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE, FALSE);
  _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH, FALSE);

  if (is_dir)
    {
      g_file_info_set_file_type (info, G_FILE_TYPE_DIRECTORY);
    }
  else
    {
      GBytes *bytes;
      char *content_type;

      g_file_info_set_file_type (info, G_FILE_TYPE_REGULAR);
      g_file_info_set_size (info, size);

      if ((_g_file_attribute_matcher_matches_id (matcher, G_FILE_ATTRIBUTE_ID_STANDARD_CONTENT_TYPE) ||
           ((~resource_flags & G_RESOURCE_FLAGS_COMPRESSED) && 
            _g_file_attribute_matcher_matches_id (matcher, G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE))) &&
          (bytes = g_resources_lookup_data (resource->path, 0, NULL)))
        {
          const guchar *data;
          gsize data_size;

          data = g_bytes_get_data (bytes, &data_size);
          content_type = g_content_type_guess (base, data, data_size, NULL);

          g_bytes_unref (bytes);
        }
      else
        content_type = NULL;

      if (content_type)
        {
          _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_CONTENT_TYPE, content_type);
          _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE, content_type);

          g_free (content_type);
        }
    }

  g_free (base);
  g_file_attribute_matcher_unref (matcher);

  return info;
}
Пример #2
0
static gboolean
ot_static_delta_builtin_generate (int argc, char **argv, GCancellable *cancellable, GError **error)
{
  gboolean ret = FALSE;
  GOptionContext *context;
  glnx_unref_object OstreeRepo *repo = NULL;

  context = g_option_context_new ("Generate static delta files");
  if (!ostree_option_context_parse (context, generate_options, &argc, &argv, OSTREE_BUILTIN_FLAG_NONE, &repo, cancellable, error))
    goto out;

  if (!ostree_ensure_repo_writable (repo, error))
    goto out;

  if (argc >= 3 && opt_to_rev == NULL)
    opt_to_rev = argv[2];

  if (argc < 3 && opt_to_rev == NULL)
    {
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "TO revision must be specified");
      goto out;
    }
  else
    {
      const char *from_source;
      g_autofree char *from_resolved = NULL;
      g_autofree char *to_resolved = NULL;
      g_autofree char *from_parent_str = NULL;
      g_autoptr(GVariantBuilder) parambuilder = NULL;

      g_assert (opt_to_rev);

      if (opt_empty)
        {
          if (opt_from_rev)
            {
              g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                   "Cannot specify both --empty and --from=REV");
              goto out;
            }
          from_source = NULL;
        }
      else if (opt_from_rev == NULL)
        {
          from_parent_str = g_strconcat (opt_to_rev, "^", NULL);
          from_source = from_parent_str;
        }
      else
        {
          from_source = opt_from_rev;
        }

      if (from_source)
        {
          if (!ostree_repo_resolve_rev (repo, from_source, FALSE, &from_resolved, error))
            goto out;
        }
      if (!ostree_repo_resolve_rev (repo, opt_to_rev, FALSE, &to_resolved, error))
        goto out;

      parambuilder = g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
      if (opt_min_fallback_size)
        g_variant_builder_add (parambuilder, "{sv}",
                               "min-fallback-size", g_variant_new_uint32 (g_ascii_strtoull (opt_min_fallback_size, NULL, 10)));
      if (opt_max_bsdiff_size)
        g_variant_builder_add (parambuilder, "{sv}",
                               "max-bsdiff-size", g_variant_new_uint32 (g_ascii_strtoull (opt_max_bsdiff_size, NULL, 10)));
      if (opt_max_chunk_size)
        g_variant_builder_add (parambuilder, "{sv}",
                               "max-chunk-size", g_variant_new_uint32 (g_ascii_strtoull (opt_max_chunk_size, NULL, 10)));
      if (opt_disable_bsdiff)
        g_variant_builder_add (parambuilder, "{sv}",
                               "bsdiff-enabled", g_variant_new_boolean (FALSE));

      g_variant_builder_add (parambuilder, "{sv}", "verbose", g_variant_new_boolean (TRUE));

      g_print ("Generating static delta:\n");
      g_print ("  From: %s\n", from_resolved ? from_resolved : "empty");
      g_print ("  To:   %s\n", to_resolved);
      if (!ostree_repo_static_delta_generate (repo, OSTREE_STATIC_DELTA_GENERATE_OPT_MAJOR,
                                              from_resolved, to_resolved, NULL,
                                              g_variant_builder_end (parambuilder),
                                              cancellable, error))
        goto out;

    }

  ret = TRUE;
 out:
  if (context)
    g_option_context_free (context);
  return ret;
}
Пример #3
0
gboolean
gimp_paint_core_stroke_vectors (GimpPaintCore     *core,
                                GimpDrawable      *drawable,
                                GimpPaintOptions  *paint_options,
                                gboolean           emulate_dynamics,
                                GimpVectors       *vectors,
                                gboolean           push_undo,
                                GError           **error)
{
  GList    *stroke;
  gboolean  initialized = FALSE;
  gboolean  due_to_lack_of_points = FALSE;
  gint      off_x, off_y;
  gint      vectors_off_x, vectors_off_y;

  g_return_val_if_fail (GIMP_IS_PAINT_CORE (core), FALSE);
  g_return_val_if_fail (GIMP_IS_DRAWABLE (drawable), FALSE);
  g_return_val_if_fail (gimp_item_is_attached (GIMP_ITEM (drawable)), FALSE);
  g_return_val_if_fail (GIMP_IS_PAINT_OPTIONS (paint_options), FALSE);
  g_return_val_if_fail (GIMP_IS_VECTORS (vectors), FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  gimp_item_get_offset (GIMP_ITEM (vectors),  &vectors_off_x, &vectors_off_y);
  gimp_item_get_offset (GIMP_ITEM (drawable), &off_x, &off_y);

  off_x -= vectors_off_x;
  off_y -= vectors_off_y;

  for (stroke = vectors->strokes; stroke; stroke = stroke->next)
    {
      GArray   *coords;
      gboolean  closed;

      coords = gimp_stroke_interpolate (GIMP_STROKE (stroke->data),
                                        1.0, &closed);

      if (coords && coords->len)
        {
          gint i;

          for (i = 0; i < coords->len; i++)
            {
              g_array_index (coords, GimpCoords, i).x -= off_x;
              g_array_index (coords, GimpCoords, i).y -= off_y;
            }

          if (emulate_dynamics)
            gimp_paint_core_stroke_emulate_dynamics ((GimpCoords *) coords->data,
                                                     coords->len);

          if (initialized ||
              gimp_paint_core_start (core, drawable, paint_options,
                                     &g_array_index (coords, GimpCoords, 0),
                                     error))
            {
              initialized = TRUE;

              core->cur_coords  = g_array_index (coords, GimpCoords, 0);
              core->last_coords = g_array_index (coords, GimpCoords, 0);

              gimp_paint_core_paint (core, drawable, paint_options,
                                     GIMP_PAINT_STATE_INIT, 0);

              gimp_paint_core_paint (core, drawable, paint_options,
                                     GIMP_PAINT_STATE_MOTION, 0);

              for (i = 1; i < coords->len; i++)
                {
                  gimp_paint_core_interpolate (core, drawable, paint_options,
                                               &g_array_index (coords, GimpCoords, i),
                                               0);
                }

              gimp_paint_core_paint (core, drawable, paint_options,
                                     GIMP_PAINT_STATE_FINISH, 0);
            }
          else
            {
              if (coords)
                g_array_free (coords, TRUE);

              break;
            }
        }
      else
        {
          due_to_lack_of_points = TRUE;
        }

      if (coords)
        g_array_free (coords, TRUE);
    }

  if (initialized)
    {
      gimp_paint_core_finish (core, drawable, push_undo);

      gimp_paint_core_cleanup (core);
    }

  if (! initialized && due_to_lack_of_points && *error == NULL)
    {
      g_set_error_literal (error, GIMP_ERROR, GIMP_FAILED,
                           _("Not enough points to stroke"));
    }

  return initialized;
}
Пример #4
0
/**
 * ev_document_factory_get_document:
 * @uri: an URI
 * @error: a #GError location to store an error, or %NULL
 *
 * Creates a #EvDocument for the document at @uri; or, if no backend handling
 * the document's type is found, or an error occurred on opening the document,
 * returns %NULL and fills in @error.
 * If the document is encrypted, it is returned but also @error is set to
 * %EV_DOCUMENT_ERROR_ENCRYPTED.
 *
 * Returns: (transfer full): a new #EvDocument, or %NULL
 */
EvDocument *
ev_document_factory_get_document (const char *uri, GError **error)
{
	EvDocument *document;
	int result;
	EvCompressionType compression;
	gchar *uri_unc = NULL;
	GError *err = NULL;

	g_return_val_if_fail (uri != NULL, NULL);

	document = new_document_for_uri (uri, TRUE, &compression, &err);
	g_assert (document != NULL || err != NULL);

	if (document != NULL) {
		uri_unc = ev_file_uncompress (uri, compression, &err);
		if (uri_unc) {
			g_object_set_data_full (G_OBJECT (document),
						"uri-uncompressed",
						uri_unc,
						(GDestroyNotify) free_uncompressed_uri);
		} else if (err != NULL) {
			/* Error uncompressing file */
			g_object_unref (document);
			g_propagate_error (error, err);
			return NULL;
		}

		result = ev_document_load (document, uri_unc ? uri_unc : uri, &err);

		if (result == FALSE || err) {
			if (err &&
			    g_error_matches (err, EV_DOCUMENT_ERROR, EV_DOCUMENT_ERROR_ENCRYPTED)) {
				g_propagate_error (error, err);
				return document;
			    }
			/* else fall through to slow mime code section below */
		} else {
			return document;
		}

		g_object_unref (document);
		document = NULL;
	}

	/* Try again with slow mime detection */
	g_clear_error (&err);
	uri_unc = NULL;

	document = new_document_for_uri (uri, FALSE, &compression, &err);
	if (document == NULL) {
		g_assert (err != NULL);
		g_propagate_error (error, err);
		return NULL;
	}

	uri_unc = ev_file_uncompress (uri, compression, &err);
	if (uri_unc) {
		g_object_set_data_full (G_OBJECT (document),
					"uri-uncompressed",
					uri_unc,
					(GDestroyNotify) free_uncompressed_uri);
	} else if (err != NULL) {
		/* Error uncompressing file */
		g_propagate_error (error, err);

		g_object_unref (document);
		return NULL;
	}

	result = ev_document_load (document, uri_unc ? uri_unc : uri, &err);
	if (result == FALSE) {
		if (err == NULL) {
			/* FIXME: this really should not happen; the backend should
			 * always return a meaningful error.
			 */
			g_set_error_literal (&err,
                                             EV_DOCUMENT_ERROR,
                                             EV_DOCUMENT_ERROR_INVALID,
                                             _("Unknown MIME Type"));
		} else if (g_error_matches (err, EV_DOCUMENT_ERROR, EV_DOCUMENT_ERROR_ENCRYPTED)) {
			g_propagate_error (error, err);
			return document;
		}

		g_object_unref (document);
		document = NULL;

		g_propagate_error (error, err);
	}

	return document;
}
/*
 * cheese_camera_device_get_caps:
 * @device: a #CheeseCameraDevice
 *
 * Probe the #GstCaps that the @device supports.
 */
static void
cheese_camera_device_get_caps (CheeseCameraDevice *device)
{
    CheeseCameraDevicePrivate *priv;
  gchar               *pipeline_desc;
  GstElement          *pipeline;
  GstStateChangeReturn ret;
  GstMessage          *msg;
  GstBus              *bus;
  GError              *err = NULL;

    priv = cheese_camera_device_get_instance_private (device);
  pipeline_desc = g_strdup_printf ("%s name=source device=%s ! fakesink",
                                   priv->src, priv->device_node);
  pipeline = gst_parse_launch (pipeline_desc, &err);
  if ((pipeline != NULL) && (err == NULL))
  {
    /* Start the pipeline and wait for max. 10 seconds for it to start up */
    gst_element_set_state (pipeline, GST_STATE_READY);
    ret = gst_element_get_state (pipeline, NULL, NULL, 10 * GST_SECOND);

    /* Check if any error messages were posted on the bus */
    bus = gst_element_get_bus (pipeline);
    msg = gst_bus_pop_filtered (bus, GST_MESSAGE_ERROR);
    gst_object_unref (bus);

    if ((msg == NULL) && (ret == GST_STATE_CHANGE_SUCCESS))
    {
      GstElement *src;
      GstPad     *pad;
      GstCaps    *caps;

      src = gst_bin_get_by_name (GST_BIN (pipeline), "source");

      GST_LOG ("Device: %s (%s)\n", priv->name, priv->device_node);
      pad        = gst_element_get_static_pad (src, "src");
      caps       = gst_pad_get_allowed_caps (pad);

      gst_caps_unref (priv->caps);
      priv->caps = cheese_camera_device_filter_caps (device, caps, supported_formats);

      if (!gst_caps_is_empty (priv->caps))
        cheese_camera_device_update_format_table (device);
      else
      {
        g_set_error_literal (&priv->construct_error,
                             CHEESE_CAMERA_DEVICE_ERROR,
                             CHEESE_CAMERA_DEVICE_ERROR_UNSUPPORTED_CAPS,
                             _("Device capabilities not supported"));
      }

      gst_object_unref (pad);
      gst_caps_unref (caps);
      gst_object_unref (src);
    }
    else
    {
      if (msg)
      {
        gchar *dbg_info = NULL;
        gst_message_parse_error (msg, &err, &dbg_info);
        GST_WARNING ("Failed to start the capability probing pipeline");
        GST_WARNING ("Error from element %s: %s, %s",
                     GST_OBJECT_NAME (msg->src),
                     err->message,
                     (dbg_info) ? dbg_info : "no extra debug detail");
        g_error_free (err);
        err = NULL;

        /* construct_error is meant to be displayed in the UI
         * (although it currently isn't displayed in cheese),
         * err->message from gstreamer is too technical for this
         * purpose, the idea is warn the user about an error and point
         * him to the logs for more info */
        g_set_error (&priv->construct_error,
                     CHEESE_CAMERA_DEVICE_ERROR,
                     CHEESE_CAMERA_DEVICE_ERROR_FAILED_INITIALIZATION,
                     _("Failed to initialize device %s for capability probing"),
                     priv->device_node);
      }
    }
    gst_element_set_state (pipeline, GST_STATE_NULL);
    gst_object_unref (pipeline);
  }

  if (err)
    g_error_free (err);

  g_free (pipeline_desc);
}
Пример #6
0
/**
 * g_vfs_ftp_task_set_error_from_response:
 * @task: the task
 * @response: the response code
 *
 * Sets the @task into an error state. The exact error is determined from the
 * @response code.
 **/
void
g_vfs_ftp_task_set_error_from_response (GVfsFtpTask *task, guint response)
{
  const char *msg;
  int code;

  g_return_if_fail (task != NULL);
  g_return_if_fail (task->error == NULL);

  /* Please keep this list ordered by response code,
   * but group responses with the same message. */
  switch (response)
    {
      case 332: /* Need account for login. */
      case 532: /* Need account for storing files. */
        /* FIXME: implement a sane way to handle accounts. */
        code = G_IO_ERROR_NOT_SUPPORTED;
        msg = _("Accounts are unsupported");
        break;
      case 421: /* Service not available, closing control connection. */
        code = G_IO_ERROR_FAILED;
        msg = _("Host closed connection");
        break;
      case 425: /* Can't open data connection. */
        code = G_IO_ERROR_CLOSED;
        msg = _("Cannot open data connection. Maybe your firewall prevents this?");
        break;
      case 426: /* Connection closed; transfer aborted. */
        code = G_IO_ERROR_CLOSED;
        msg = _("Data connection closed");
        break;
      case 450: /* Requested file action not taken. File unavailable (e.g., file busy). */
      case 550: /* Requested action not taken. File unavailable (e.g., file not found, no access). */
        /* FIXME: This is a lot of different errors. So we have to pretend to
         * be smart here. */
        code = G_IO_ERROR_FAILED;
        msg = _("Operation failed");
        break;
      case 451: /* Requested action aborted: local error in processing. */
        code = G_IO_ERROR_FAILED;
        msg = _("Operation failed");
        break;
      case 452: /* Requested action not taken. Insufficient storage space in system. */
      case 552:
        code = G_IO_ERROR_NO_SPACE;
        msg = _("No space left on server");
        break;
      case 500: /* Syntax error, command unrecognized. */
      case 501: /* Syntax error in parameters or arguments. */
      case 502: /* Command not implemented. */
      case 503: /* Bad sequence of commands. */
      case 504: /* Command not implemented for that parameter. */
        code = G_IO_ERROR_NOT_SUPPORTED;
        msg = _("Operation unsupported");
        break;
      case 522: /* EPRT: unsupported network protocol */
        code = G_IO_ERROR_NOT_SUPPORTED;
        msg = _("Unsupported network protocol");
        break;
      case 530: /* Not logged in. */
        code = G_IO_ERROR_PERMISSION_DENIED;
        msg = _("Permission denied");
        break;
      case 551: /* Requested action aborted: page type unknown. */
        code = G_IO_ERROR_FAILED;
        msg = _("Page type unknown");
        break;
      case 553: /* Requested action not taken. File name not allowed. */
        code = G_IO_ERROR_INVALID_FILENAME;
        msg = _("Invalid filename");
        break;
      default:
        code = G_IO_ERROR_FAILED;
        msg = _("Invalid reply");
        break;
    }

  g_set_error_literal (&task->error, G_IO_ERROR, code, msg);
}
Пример #7
0
static void facq_stream_load_from_key_file(GKeyFile *key_file,const FacqCatalog *cat,FacqStream *stream,GError **err)
{
	GError *local_err = NULL;
	gchar **groups = NULL, **tokens = NULL;
	guint i = 0, n_items = 0, n_operations = 0;
	gsize n_groups = 0;
	gpointer item = NULL;

	/* we are not ready yet, first check that the number of groups it's >
	 * 3 */
	groups = g_key_file_get_groups(key_file,&n_groups);
	if(n_groups < 3){
		g_set_error_literal(&local_err,FACQ_STREAM_ERROR,
					FACQ_STREAM_ERROR_FAILED,"Invalid file");
		goto error;
	}
	n_items = n_groups - 1; //subtract the stream group
	n_operations = n_items - 2;//subtract the source and the sink

	/* start at group 1, cause group 0 is the [Stream] group */

	/* source */
	tokens = g_strsplit(groups[1],",",2);
	item = facq_catalog_item_from_key_file(key_file,
					       groups[1],
					       tokens[0],
					       cat,
					       FACQ_CATALOG_TYPE_SOURCE,
					       &local_err);
	if(local_err)
		goto error;
	facq_stream_set_source(stream,item);
	g_strfreev(tokens);

	for(i = 0;i < n_operations;i++){
		tokens = g_strsplit(groups[i+2],",",2);
		item = facq_catalog_item_from_key_file(key_file,
						       groups[i+2],
						       tokens[0],
						       cat,
						       FACQ_CATALOG_TYPE_OPERATION,
						       &local_err);
		if(local_err)
			goto error;
		facq_stream_append_operation(stream,item);
		g_strfreev(tokens);
	}

	/* sink */
	tokens = g_strsplit(groups[n_groups-1],",",2);
	item = facq_catalog_item_from_key_file(key_file,
					       groups[n_groups-1],
					       tokens[0],
					       cat,
					       FACQ_CATALOG_TYPE_SINK,
					       &local_err);
	g_strfreev(tokens);
	if(local_err)
		goto error;
	facq_stream_set_sink(stream,item);

	g_strfreev(groups);
	return;

	error:
	if(tokens)
		g_strfreev(tokens);
	if(groups)
		g_strfreev(groups);
	if(local_err){
		if(err)
			g_propagate_error(err,local_err);
	}
	else
		g_set_error_literal(err,FACQ_STREAM_ERROR,
					FACQ_STREAM_ERROR_FAILED,"Unknown error loading stream");
	return;
}
Пример #8
0
/**
 * rpmostreed_refspec_parse_partial:
 * @new_provided_refspec: The provided refspec
 * @base_refspec: The refspec string to base on.
 * @out_refspec: Pointer to the new refspec
 * @error: Pointer to an error pointer.
 *
 * Takes a refspec string and adds any missing bits based on the
 * base_refspec argument. Errors if a full valid refspec can't
 * be derived.
 *
 * Returns: True on success.
 */
gboolean
rpmostreed_refspec_parse_partial (const gchar *new_provided_refspec,
                                  const gchar *base_refspec,
                                  gchar **out_refspec,
                                  GError **error)
{

  g_autofree gchar *ref = NULL;
  g_autofree gchar *remote = NULL;
  gboolean infer_remote = TRUE;;

  /* Allow just switching remotes */
  if (g_str_has_suffix (new_provided_refspec, ":"))
    {
      remote = g_strndup (new_provided_refspec, strlen(new_provided_refspec)-1);
    }
  /* Allow switching to a local branch */
  else if (g_str_has_prefix (new_provided_refspec, ":"))
    {
      infer_remote = FALSE;
      ref = g_strdup (new_provided_refspec + 1);
    }
  else
    {
      g_autoptr(GError) parse_error = NULL;
      if (!ostree_parse_refspec (new_provided_refspec, &remote,
                                 &ref, &parse_error))
        {
          g_set_error_literal (error, RPM_OSTREED_ERROR,
                               RPM_OSTREED_ERROR_INVALID_REFSPEC,
                               parse_error->message);
          return FALSE;
        }
    }

  g_autofree gchar *origin_ref = NULL;
  g_autofree gchar *origin_remote = NULL;
  if (base_refspec != NULL)
    {
      g_autoptr(GError) parse_error = NULL;
      if (!ostree_parse_refspec (base_refspec, &origin_remote,
                                 &origin_ref, &parse_error))
        {
          g_set_error_literal (error, RPM_OSTREED_ERROR,
                               RPM_OSTREED_ERROR_INVALID_REFSPEC,
                               parse_error->message);
          return FALSE;
        }
    }

  if (ref == NULL)
    {
      if (origin_ref)
        {
          ref = g_strdup (origin_ref);
        }
      else
        {
          g_set_error (error, RPM_OSTREED_ERROR,
                       RPM_OSTREED_ERROR_INVALID_REFSPEC,
                      "Could not determine default ref to pull.");
          return FALSE;
        }

    }
  else if (infer_remote && remote == NULL)
    {
      if (origin_remote)
        {
          remote = g_strdup (origin_remote);
        }
    }

  if (g_strcmp0 (origin_remote, remote) == 0 &&
      g_strcmp0 (origin_ref, ref) == 0)
    {
      g_set_error (error, RPM_OSTREED_ERROR,
                   RPM_OSTREED_ERROR_INVALID_REFSPEC,
                   "Old and new refs are equal: %s:%s",
                   remote, ref);
      return FALSE;
    }

  if (remote == NULL)
      *out_refspec = g_steal_pointer (&ref);
  else
      *out_refspec = g_strconcat (remote, ":", ref, NULL);

  return TRUE;
}
NMCheckpoint *
nm_checkpoint_manager_create (NMCheckpointManager *self,
                              const char *const *device_paths,
                              guint32 rollback_timeout,
                              NMCheckpointCreateFlags flags,
                              GError **error)
{
	NMManager *manager;
	NMCheckpoint *checkpoint;
	const char * const *path;
	gs_unref_ptrarray GPtrArray *devices = NULL;
	NMDevice *device;
	const char *checkpoint_path;
	gs_free const char **device_paths_free = NULL;
	guint i;

	g_return_val_if_fail (self, FALSE);
	g_return_val_if_fail (!error || !*error, FALSE);
	manager = GET_MANAGER (self);

	if (!device_paths || !device_paths[0]) {
		device_paths_free = nm_manager_get_device_paths (manager);
		device_paths = (const char *const *) device_paths_free;
	} else if (NM_FLAGS_HAS (flags, NM_CHECKPOINT_CREATE_FLAG_DISCONNECT_NEW_DEVICES)) {
		g_set_error_literal (error, NM_MANAGER_ERROR, NM_MANAGER_ERROR_INVALID_ARGUMENTS,
		                     "the DISCONNECT_NEW_DEVICES flag can only be used with an empty device list");
		return NULL;
	}

	devices = g_ptr_array_new ();
	for (path = device_paths; *path; path++) {
		device = nm_manager_get_device_by_path (manager, *path);
		if (!device) {
			g_set_error (error, NM_MANAGER_ERROR, NM_MANAGER_ERROR_UNKNOWN_DEVICE,
			             "device %s does not exist", *path);
			return NULL;
		}
		g_ptr_array_add (devices, device);
	}

	if (!NM_FLAGS_HAS (flags, NM_CHECKPOINT_CREATE_FLAG_DESTROY_ALL)) {
		for (i = 0; i < devices->len; i++) {
			device = devices->pdata[i];
			if (find_checkpoint_for_device (self, device)) {
				g_set_error (error, NM_MANAGER_ERROR, NM_MANAGER_ERROR_INVALID_ARGUMENTS,
				             "a checkpoint for device '%s' already exists",
				             nm_device_get_iface (device));
				return NULL;
			}
		}
	}

	checkpoint = nm_checkpoint_new (manager, devices, rollback_timeout, flags, error);
	if (!checkpoint)
		return NULL;

	if (NM_FLAGS_HAS (flags, NM_CHECKPOINT_CREATE_FLAG_DESTROY_ALL))
		g_hash_table_remove_all (self->checkpoints);

	nm_exported_object_export (NM_EXPORTED_OBJECT (checkpoint));
	checkpoint_path = nm_exported_object_get_path (NM_EXPORTED_OBJECT (checkpoint));

	if (!nm_g_hash_table_insert (self->checkpoints,
	                             (gpointer) checkpoint_path,
	                             checkpoint))
		g_return_val_if_reached (NULL);

	update_rollback_timeout (self);

	return checkpoint;
}
Пример #10
0
gboolean
gimp_curves_config_load_cruft (GimpCurvesConfig  *config,
                               GInputStream      *input,
                               GError           **error)
{
  GDataInputStream *data_input;
  gint              index[5][GIMP_CURVE_N_CRUFT_POINTS];
  gint              value[5][GIMP_CURVE_N_CRUFT_POINTS];
  gchar            *line;
  gsize             line_len;
  gint              i, j;

  g_return_val_if_fail (GIMP_IS_CURVES_CONFIG (config), FALSE);
  g_return_val_if_fail (G_IS_INPUT_STREAM (input), FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  data_input = g_data_input_stream_new (input);

  line_len = 64;
  line = g_data_input_stream_read_line (data_input, &line_len,
                                        NULL, error);
  if (! line)
    return FALSE;

  if (strcmp (line, "# GIMP Curves File") != 0)
    {
      g_set_error_literal (error, GIMP_CONFIG_ERROR, GIMP_CONFIG_ERROR_PARSE,
			   _("not a GIMP Curves file"));
      g_object_unref (data_input);
      g_free (line);
      return FALSE;
    }

  for (i = 0; i < 5; i++)
    {
      for (j = 0; j < GIMP_CURVE_N_CRUFT_POINTS; j++)
        {
          gchar *x_str = NULL;
          gchar *y_str = NULL;

          if (! (x_str = g_data_input_stream_read_upto (data_input, " ", -1,
                                                        NULL, NULL, error)) ||
              ! g_data_input_stream_read_byte (data_input,  NULL, error) ||
              ! (y_str = g_data_input_stream_read_upto (data_input, " ", -1,
                                                        NULL, NULL, error)) ||
              ! g_data_input_stream_read_byte (data_input,  NULL, error))
            {
              g_free (x_str);
              g_free (y_str);
              g_object_unref (data_input);
              return FALSE;
            }

          if (sscanf (x_str, "%d", &index[i][j]) != 1 ||
              sscanf (y_str, "%d", &value[i][j]) != 1)
            {
              g_set_error_literal (error,
				   GIMP_CONFIG_ERROR, GIMP_CONFIG_ERROR_PARSE,
				   _("Parse error, didn't find 2 integers"));
              g_free (x_str);
              g_free (y_str);
              g_object_unref (data_input);
              return FALSE;
            }

          g_free (x_str);
          g_free (y_str);
        }
    }

  g_object_unref (data_input);

  g_object_freeze_notify (G_OBJECT (config));

  for (i = 0; i < 5; i++)
    {
      GimpCurve *curve = config->curve[i];

      gimp_data_freeze (GIMP_DATA (curve));

      gimp_curve_set_curve_type (curve, GIMP_CURVE_SMOOTH);
      gimp_curve_set_n_points (curve, GIMP_CURVE_N_CRUFT_POINTS);

      gimp_curve_reset (curve, FALSE);

      for (j = 0; j < GIMP_CURVE_N_CRUFT_POINTS; j++)
        {
          if (index[i][j] < 0 || value[i][j] < 0)
            gimp_curve_set_point (curve, j, -1.0, -1.0);
          else
            gimp_curve_set_point (curve, j,
                                  (gdouble) index[i][j] / 255.0,
                                  (gdouble) value[i][j] / 255.0);
        }

      gimp_data_thaw (GIMP_DATA (curve));
    }

  g_object_thaw_notify (G_OBJECT (config));

  return TRUE;
}
Пример #11
0
GimpPDBStatusType
file_save (Gimp                *gimp,
           GimpImage           *image,
           GimpProgress        *progress,
           const gchar         *uri,
           GimpPlugInProcedure *file_proc,
           GimpRunMode          run_mode,
           gboolean             change_saved_state,
           gboolean             export_backward,
           gboolean             export_forward,
           GError             **error)
{
  GimpDrawable      *drawable;
  GimpValueArray    *return_vals;
  GimpPDBStatusType  status;
  gchar             *filename;
  gint32             image_ID;
  gint32             drawable_ID;

  g_return_val_if_fail (GIMP_IS_GIMP (gimp), GIMP_PDB_CALLING_ERROR);
  g_return_val_if_fail (GIMP_IS_IMAGE (image), GIMP_PDB_CALLING_ERROR);
  g_return_val_if_fail (progress == NULL || GIMP_IS_PROGRESS (progress),
                        GIMP_PDB_CALLING_ERROR);
  g_return_val_if_fail (uri != NULL, GIMP_PDB_CALLING_ERROR);
  g_return_val_if_fail (GIMP_IS_PLUG_IN_PROCEDURE (file_proc),
                        GIMP_PDB_CALLING_ERROR);
  g_return_val_if_fail ((export_backward && export_forward) == FALSE,
                        GIMP_PDB_CALLING_ERROR);
  g_return_val_if_fail (error == NULL || *error == NULL,
                        GIMP_PDB_CALLING_ERROR);

  drawable = gimp_image_get_active_drawable (image);

  if (! drawable)
    return GIMP_PDB_EXECUTION_ERROR;

  filename = file_utils_filename_from_uri (uri);

  if (filename)
    {
      /* check if we are saving to a file */
      if (g_file_test (filename, G_FILE_TEST_EXISTS))
        {
          if (! g_file_test (filename, G_FILE_TEST_IS_REGULAR))
            {
              g_set_error_literal (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
				   _("Not a regular file"));
              status = GIMP_PDB_EXECUTION_ERROR;
              goto out;
            }

          if (g_access (filename, W_OK) != 0)
            {
              g_set_error_literal (error, G_FILE_ERROR, G_FILE_ERROR_ACCES,
                                   g_strerror (errno));
              status = GIMP_PDB_EXECUTION_ERROR;
              goto out;
            }
        }
    }
  else
    {
      filename = g_strdup (uri);
    }

  /* ref the image, so it can't get deleted during save */
  g_object_ref (image);

  image_ID    = gimp_image_get_ID (image);
  drawable_ID = gimp_item_get_ID (GIMP_ITEM (drawable));

  return_vals =
    gimp_pdb_execute_procedure_by_name (image->gimp->pdb,
                                        gimp_get_user_context (gimp),
                                        progress, error,
                                        gimp_object_get_name (file_proc),
                                        GIMP_TYPE_INT32,       run_mode,
                                        GIMP_TYPE_IMAGE_ID,    image_ID,
                                        GIMP_TYPE_DRAWABLE_ID, drawable_ID,
                                        G_TYPE_STRING,         filename,
                                        G_TYPE_STRING,         uri,
                                        G_TYPE_NONE);

  status = g_value_get_enum (gimp_value_array_index (return_vals, 0));

  gimp_value_array_unref (return_vals);

  if (status == GIMP_PDB_SUCCESS)
    {
      GimpDocumentList *documents;
      GimpImagefile    *imagefile;

      if (change_saved_state)
        {
          gimp_image_set_uri (image, uri);
          gimp_image_set_save_proc (image, file_proc);

          /* Forget the import source when we save. We interpret a
           * save as that the user is not interested in being able
           * to quickly export back to the original any longer
           */
          gimp_image_set_imported_uri (image, NULL);

          gimp_image_clean_all (image);
        }
      else if (export_backward)
        {
          /* We exported the image back to its imported source,
           * change nothing about export/import flags, only set
           * the export state to clean
           */
          gimp_image_export_clean_all (image);

          gimp_object_name_changed (GIMP_OBJECT (image));
        }
      else if (export_forward)
        {
          /* Remeber the last entered Export URI for the image. We
           * only need to do this explicitly when exporting. It
           * happens implicitly when saving since the GimpObject name
           * of a GimpImage is the last-save URI
           */
          gimp_image_set_exported_uri (image, uri);

          /* An image can not be considered both exported and imported
           * at the same time, so stop consider it as imported now
           * that we consider it exported.
           */
          gimp_image_set_imported_uri (image, NULL);

          gimp_image_export_clean_all (image);
        }

      if (export_backward || export_forward)
        gimp_image_exported (image, uri);
      else
        gimp_image_saved (image, uri);

      documents = GIMP_DOCUMENT_LIST (image->gimp->documents);
      imagefile = gimp_document_list_add_uri (documents,
                                              uri,
                                              file_proc->mime_type);

      /* only save a thumbnail if we are saving as XCF, see bug #25272 */
      if (GIMP_PROCEDURE (file_proc)->proc_type == GIMP_INTERNAL)
        gimp_imagefile_save_thumbnail (imagefile, file_proc->mime_type, image);
    }
  else if (status != GIMP_PDB_CANCEL)
    {
      if (error && *error == NULL)
        {
          g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
                       _("%s plug-in could not save image"),
                       gimp_plug_in_procedure_get_label (file_proc));
        }
    }

  gimp_image_flush (image);

  g_object_unref (image);

 out:
  g_free (filename);

  return status;
}
Пример #12
0
static MMBaseModem *
grab_port (MMPluginBase *base,
           MMBaseModem *existing,
           MMPortProbe *probe,
           GError **error)
{
    MMBaseModem *modem = NULL;
    GUdevDevice *port;
    MMPortType ptype;
    const gchar *name, *subsys;
    guint16 vendor = 0, product = 0;
    MMAtPortFlag pflags = MM_AT_PORT_FLAG_NONE;

    /* The Simtech plugin cannot do anything with non-AT non-QCDM ports */
    if (!mm_port_probe_is_at (probe) &&
        !mm_port_probe_is_qcdm (probe)) {
        g_set_error_literal (error,
                             MM_CORE_ERROR,
                             MM_CORE_ERROR_UNSUPPORTED,
                             "Ignoring non-AT non-QCDM port");
        return NULL;
    }

    port = mm_port_probe_get_port (probe); /* transfer none */
    subsys = mm_port_probe_get_port_subsys (probe);
    name = mm_port_probe_get_port_name (probe);

    if (!mm_plugin_base_get_device_ids (base, subsys, name, &vendor, &product)) {
        g_set_error_literal (error,
                             MM_CORE_ERROR,
                             MM_CORE_ERROR_FAILED,
                             "Could not get modem product ID");
        return NULL;
    }

    /* Look for port type hints; just probing can't distinguish which port should
     * be the data/primary port on these devices.  We have to tag them based on
     * what the Windows .INF files say the port layout should be.
     */
    if (g_udev_device_get_property_as_boolean (port, "ID_MM_SIMTECH_PORT_TYPE_MODEM"))
        pflags = MM_AT_PORT_FLAG_PRIMARY;
    else if (g_udev_device_get_property_as_boolean (port, "ID_MM_SIMTECH_PORT_TYPE_AUX"))
        pflags = MM_AT_PORT_FLAG_SECONDARY;

    /* If the port was tagged by the udev rules but isn't a primary or secondary,
     * then ignore it to guard against race conditions if a device just happens
     * to show up with more than two AT-capable ports.
     */
    if (pflags == MM_AT_PORT_FLAG_NONE &&
        g_udev_device_get_property_as_boolean (port, "ID_MM_SIMTECH_TAGGED"))
        ptype = MM_PORT_TYPE_IGNORED;
    else
        ptype = mm_port_probe_get_port_type (probe);

    /* If this is the first port being grabbed, create a new modem object */
    if (!existing)
        modem = MM_BASE_MODEM (mm_broadband_modem_simtech_new (mm_port_probe_get_port_physdev (probe),
                                                               mm_port_probe_get_port_driver (probe),
                                                               mm_plugin_get_name (MM_PLUGIN (base)),
                                                               vendor,
                                                               product));

    if (!mm_base_modem_grab_port (existing ? existing : modem,
                                  subsys,
                                  name,
                                  ptype,
                                  pflags,
                                  error)) {
        if (modem)
            g_object_unref (modem);
        return NULL;
    }

    return existing ? existing : modem;
}
Пример #13
0
gboolean
nm_ppp_manager_start (NMPPPManager *manager,
                      NMActRequest *req,
                      const char *ppp_name,
                      guint32 timeout_secs,
                      GError **err)
{
	NMPPPManagerPrivate *priv;
	NMConnection *connection;
	NMSettingPpp *s_ppp;
	gboolean s_ppp_created = FALSE;
	NMSettingPppoe *pppoe_setting;
	NMSettingAdsl *adsl_setting;
	NMCmdLine *ppp_cmd;
	char *cmd_str;
	struct stat st;

	g_return_val_if_fail (NM_IS_PPP_MANAGER (manager), FALSE);
	g_return_val_if_fail (NM_IS_ACT_REQUEST (req), FALSE);

	priv = NM_PPP_MANAGER_GET_PRIVATE (manager);

#if !WITH_PPP
	/* PPP support disabled */
	g_set_error_literal (err,
	                     NM_MANAGER_ERROR,
	                     NM_MANAGER_ERROR_FAILED,
	                     "PPP support is not enabled.");
	return FALSE;
#endif

	priv->pid = 0;

	/* Make sure /dev/ppp exists (bgo #533064) */
	if (stat ("/dev/ppp", &st) || !S_ISCHR (st.st_mode))
		nm_utils_modprobe (NULL, FALSE, "ppp_generic", NULL);

	connection = nm_act_request_get_applied_connection (req);
	g_assert (connection);

	s_ppp = nm_connection_get_setting_ppp (connection);
	if (!s_ppp) {
		/* If the PPP settings are all default we may not have a PPP setting yet,
		 * so just make a default one here.
		 */
		s_ppp = NM_SETTING_PPP (nm_setting_ppp_new ());
		s_ppp_created = TRUE;
	}
	
	pppoe_setting = nm_connection_get_setting_pppoe (connection);
	if (pppoe_setting)
		pppoe_fill_defaults (s_ppp);

	adsl_setting = (NMSettingAdsl *) nm_connection_get_setting (connection, NM_TYPE_SETTING_ADSL);

	ppp_cmd = create_pppd_cmd_line (manager, s_ppp, pppoe_setting, adsl_setting, ppp_name, err);
	if (!ppp_cmd)
		goto out;

	g_ptr_array_add (ppp_cmd->array, NULL);

	_LOGI ("starting PPP connection");

	cmd_str = nm_cmd_line_to_str (ppp_cmd);
	_LOGD ("command line: %s", cmd_str);
	g_free (cmd_str);

	priv->pid = 0;
	if (!g_spawn_async (NULL, (char **) ppp_cmd->array->pdata, NULL,
	                    G_SPAWN_DO_NOT_REAP_CHILD,
	                    nm_utils_setpgid, NULL,
	                    &priv->pid, err)) {
		goto out;
	}

	_LOGI ("pppd started with pid %d", priv->pid);

	priv->ppp_watch_id = g_child_watch_add (priv->pid, (GChildWatchFunc) ppp_watch_cb, manager);
	priv->ppp_timeout_handler = g_timeout_add_seconds (timeout_secs, pppd_timed_out, manager);
	priv->act_req = g_object_ref (req);

out:
	if (s_ppp_created)
		g_object_unref (s_ppp);

	if (ppp_cmd)
		nm_cmd_line_destroy (ppp_cmd);

	return priv->pid > 0;
}
Пример #14
0
GimpPlugInProcedure *
file_procedure_find (GSList       *procs,
                     const gchar  *uri,
                     GError      **error)
{
  GimpPlugInProcedure *file_proc;
  GSList              *all_procs = procs;
  gchar               *filename;

  g_return_val_if_fail (procs != NULL, NULL);
  g_return_val_if_fail (uri != NULL, NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  /* First, check magicless prefixes/suffixes */
  file_proc = file_proc_find_by_name (all_procs, uri, TRUE);

  if (file_proc)
    return file_proc;

  filename = file_utils_filename_from_uri (uri);

  /* Then look for magics */
  if (filename)
    {
      GimpPlugInProcedure *size_matched_proc = NULL;
      FILE                *ifp               = NULL;
      gint                 head_size         = -2;
      gint                 size_match_count  = 0;
      guchar               head[256];

      while (procs)
        {
          file_proc = procs->data;
          procs = procs->next;

          if (file_proc->magics_list)
            {
              if (head_size == -2)
                {
                  head_size = 0;

                  if ((ifp = g_fopen (filename, "rb")) != NULL)
                    {
                      head_size = fread ((gchar *) head, 1, sizeof (head), ifp);
                    }
                  else
                    {
                      g_set_error_literal (error,
                                           G_FILE_ERROR,
                                           g_file_error_from_errno (errno),
                                           g_strerror (errno));
                    }
                }

              if (head_size >= 4)
                {
                  FileMatchType match_val;

                  match_val = file_check_magic_list (file_proc->magics_list,
                                                     head, head_size,
                                                     ifp);

                  if (match_val == FILE_MATCH_SIZE)
                    {
                      /* Use it only if no other magic matches */
                      size_match_count++;
                      size_matched_proc = file_proc;
                    }
                  else if (match_val != FILE_MATCH_NONE)
                    {
                      fclose (ifp);
                      g_free (filename);

                      return file_proc;
                    }
                }
            }
        }

      if (ifp)
        {
          if (ferror (ifp))
            g_set_error_literal (error, G_FILE_ERROR,
                                 g_file_error_from_errno (errno),
                                 g_strerror (errno));

          fclose (ifp);
        }

      g_free (filename);

      if (size_match_count == 1)
        return size_matched_proc;
    }

  /* As a last resort, try matching by name */
  file_proc = file_proc_find_by_name (all_procs, uri, FALSE);

  if (file_proc)
    {
      /* we found a procedure, clear error that might have been set */
      g_clear_error (error);
    }
  else
    {
      /* set an error message unless one was already set */
      if (error && *error == NULL)
	g_set_error_literal (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
			     _("Unknown file type"));
    }

  return file_proc;
}
Пример #15
0
/**
 * as_app_parse_file_key:
 **/
static gboolean
as_app_parse_file_key (AsApp *app,
		       GKeyFile *kf,
		       const gchar *key,
		       GError **error)
{
	gchar *dot = NULL;
	guint i;
	guint j;
	_cleanup_free_ gchar *locale = NULL;
	_cleanup_free_ gchar *tmp = NULL;
	_cleanup_strv_free_ gchar **list = NULL;

	/* NoDisplay */
	if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY) == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && strcasecmp (tmp, "True") == 0)
			as_app_add_veto (app, "NoDisplay=true");

	/* Type */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_TYPE) == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (g_strcmp0 (tmp, G_KEY_FILE_DESKTOP_TYPE_APPLICATION) != 0) {
			g_set_error_literal (error,
					     AS_APP_ERROR,
					     AS_APP_ERROR_INVALID_TYPE,
					     "not an application");
			return FALSE;
		}

	/* Icon */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_ICON) == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0') {
			_cleanup_object_unref_ AsIcon *icon = NULL;
			icon = as_icon_new ();
			as_icon_set_name (icon, tmp, -1);
			dot = g_strstr_len (tmp, -1, ".");
			if (dot != NULL)
				*dot = '\0';
			if (as_utils_is_stock_icon_name (tmp)) {
				as_icon_set_name (icon, tmp, -1);
				as_icon_set_kind (icon, AS_ICON_KIND_STOCK);
			} else {
				as_icon_set_kind (icon, AS_ICON_KIND_LOCAL);
			}
			as_app_add_icon (app, icon);
		}

	/* Categories */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_CATEGORIES) == 0) {
		list = g_key_file_get_string_list (kf,
						   G_KEY_FILE_DESKTOP_GROUP,
						   key,
						   NULL, NULL);
		for (i = 0; list[i] != NULL; i++) {

			/* check categories that if present would blacklist
			 * the application */
			if (fnmatch ("X-*-Settings-Panel", list[i], 0) == 0 ||
			    fnmatch ("X-*-Settings", list[i], 0) == 0 ||
			    fnmatch ("X-*-SettingsDialog", list[i], 0) == 0) {
				as_app_add_veto (app, "category '%s' blacklisted", list[i]);
				continue;
			}

			/* not a standard category */
			if (g_str_has_prefix (list[i], "X-"))
				continue;

			/* check the category is valid */
			if (!as_utils_is_category_id (list[i]))
				continue;

			/* ignore some useless keys */
			if (g_strcmp0 (list[i], "GTK") == 0)
				continue;
			if (g_strcmp0 (list[i], "Qt") == 0)
				continue;
			if (g_strcmp0 (list[i], "KDE") == 0)
				continue;
			if (g_strcmp0 (list[i], "GNOME") == 0)
				continue;
			as_app_add_category (app, list[i], -1);
		}

	} else if (g_strcmp0 (key, "Keywords") == 0) {
		list = g_key_file_get_string_list (kf,
						   G_KEY_FILE_DESKTOP_GROUP,
						   key,
						   NULL, NULL);
		for (i = 0; list[i] != NULL; i++) {
			_cleanup_strv_free_ gchar **kw_split = NULL;
			kw_split = g_strsplit (list[i], ",", -1);
			for (j = 0; kw_split[j] != NULL; j++) {
				if (kw_split[j][0] == '\0')
					continue;
				as_app_add_keyword (app, "C",
						    kw_split[j], -1);
			}
		}

	} else if (g_str_has_prefix (key, "Keywords")) {
		locale = as_app_desktop_key_get_locale (key);
		list = g_key_file_get_locale_string_list (kf,
							  G_KEY_FILE_DESKTOP_GROUP,
							  key,
							  locale,
							  NULL, NULL);
		for (i = 0; list[i] != NULL; i++) {
			_cleanup_strv_free_ gchar **kw_split = NULL;
			kw_split = g_strsplit (list[i], ",", -1);
			for (j = 0; kw_split[j] != NULL; j++) {
				if (kw_split[j][0] == '\0')
					continue;
				as_app_add_keyword (app, locale,
						    kw_split[j], -1);
			}
		}

	} else if (g_strcmp0 (key, "MimeType") == 0) {
		list = g_key_file_get_string_list (kf,
						   G_KEY_FILE_DESKTOP_GROUP,
						   key,
						   NULL, NULL);
		for (i = 0; list[i] != NULL; i++)
			as_app_add_mimetype (app, list[i], -1);

	} else if (g_strcmp0 (key, "X-AppInstall-Package") == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_add_pkgname (app, tmp, -1);

	/* OnlyShowIn */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN) == 0) {
		/* if an app has only one entry, it's that desktop */
		list = g_key_file_get_string_list (kf,
						   G_KEY_FILE_DESKTOP_GROUP,
						   key,
						   NULL, NULL);
		if (g_strv_length (list) == 1)
			as_app_set_project_group (app, list[0], -1);

	/* Name */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_NAME) == 0 ||
	           g_strcmp0 (key, "_Name") == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_name (app, "C", tmp, -1);

	/* Name[] */
	} else if (g_str_has_prefix (key, G_KEY_FILE_DESKTOP_KEY_NAME)) {
		locale = as_app_desktop_key_get_locale (key);
		tmp = g_key_file_get_locale_string (kf,
						    G_KEY_FILE_DESKTOP_GROUP,
						    G_KEY_FILE_DESKTOP_KEY_NAME,
						    locale,
						    NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_name (app, locale, tmp, -1);

	/* Comment */
	} else if (g_strcmp0 (key, G_KEY_FILE_DESKTOP_KEY_COMMENT) == 0 ||
	           g_strcmp0 (key, "_Comment") == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_comment (app, "C", tmp, -1);

	/* Comment[] */
	} else if (g_str_has_prefix (key, G_KEY_FILE_DESKTOP_KEY_COMMENT)) {
		locale = as_app_desktop_key_get_locale (key);
		tmp = g_key_file_get_locale_string (kf,
						    G_KEY_FILE_DESKTOP_GROUP,
						    G_KEY_FILE_DESKTOP_KEY_COMMENT,
						    locale,
						    NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_comment (app, locale, tmp, -1);

	/* non-standard */
	} else if (g_strcmp0 (key, "X-Ubuntu-Software-Center-Name") == 0) {
		tmp = g_key_file_get_string (kf,
					     G_KEY_FILE_DESKTOP_GROUP,
					     key,
					     NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_name (app, "C", tmp, -1);
	} else if (g_str_has_prefix (key, "X-Ubuntu-Software-Center-Name")) {
		locale = as_app_desktop_key_get_locale (key);
		tmp = g_key_file_get_locale_string (kf,
						    G_KEY_FILE_DESKTOP_GROUP,
						    "X-Ubuntu-Software-Center-Name",
						    locale,
						    NULL);
		if (tmp != NULL && tmp[0] != '\0')
			as_app_set_name (app, locale, tmp, -1);
	}

	return TRUE;
}
Пример #16
0
gboolean
ostree_builtin_checkout (int argc, char **argv, GCancellable *cancellable, GError **error)
{
  GOptionContext *context;
  gs_unref_object OstreeRepo *repo = NULL;
  gboolean ret = FALSE;
  const char *commit;
  const char *destination;
  gs_free char *resolved_commit = NULL;
  gs_unref_object GFile *checkout_target = NULL;

  context = g_option_context_new ("COMMIT [DESTINATION] - Check out a commit into a filesystem tree");

  if (!ostree_option_context_parse (context, options, &argc, &argv, OSTREE_BUILTIN_FLAG_NONE, &repo, cancellable, error))
    goto out;

  if (opt_disable_fsync)
    ostree_repo_set_disable_fsync (repo, TRUE);

  if (argc < 2)
    {
      gchar *help = g_option_context_get_help (context, TRUE, NULL);
      g_printerr ("%s\n", help);
      g_free (help);
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "COMMIT must be specified");
      goto out;
    }

  if (opt_from_stdin || opt_from_file)
    {
      destination = argv[1];
      checkout_target = g_file_new_for_path (destination);

      if (!process_many_checkouts (repo, checkout_target, cancellable, error))
        goto out;
    }
  else
    {
      commit = argv[1];
      if (argc < 3)
        destination = commit;
      else
        destination = argv[2];

      if (!ostree_repo_resolve_rev (repo, commit, FALSE, &resolved_commit, error))
        goto out;

      checkout_target = g_file_new_for_path (destination);

      if (!process_one_checkout (repo, resolved_commit, opt_subpath,
                                 checkout_target,
                                 cancellable, error))
        goto out;
    }

  ret = TRUE;
 out:
  if (context)
    g_option_context_free (context);
  return ret;
}
Пример #17
0
static gboolean
gs_install_appstream_check_content_type (GFile *file, GError **error)
{
	const gchar *type;
	g_autoptr(GError) error_local = NULL;
	g_autoptr(GFileInfo) info = NULL;
	g_autoptr(GPtrArray) components = NULL;
	g_autoptr(XbBuilder) builder = xb_builder_new ();
	g_autoptr(XbBuilderSource) source = xb_builder_source_new ();
	g_autoptr(XbSilo) silo = NULL;

	/* check is correct type */
	info = g_file_query_info (file,
				  G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
				  G_FILE_QUERY_INFO_NONE,
				  NULL, error);
	if (info == NULL)
		return FALSE;
	type = g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE);
	if (g_strcmp0 (type, "application/gzip") != 0 &&
	    g_strcmp0 (type, "application/xml") != 0) {
		g_set_error (error,
			     G_IO_ERROR,
			     G_IO_ERROR_INVALID_DATA,
			     "Invalid type %s: ", type);
		return FALSE;
	}

	/* check is an AppStream file */
	if (!xb_builder_source_load_file (source, file,
					  XB_BUILDER_SOURCE_FLAG_NONE,
					  NULL, &error_local)) {
		g_set_error (error,
			     G_IO_ERROR,
			     G_IO_ERROR_INVALID_DATA,
			     "Failed to import XML: %s", error_local->message);
		return FALSE;
	}
	xb_builder_import_source (builder, source);
	silo = xb_builder_compile (builder, XB_BUILDER_COMPILE_FLAG_NONE,
				   NULL, &error_local);
	if (silo == NULL) {
		g_set_error (error,
			     G_IO_ERROR,
			     G_IO_ERROR_INVALID_DATA,
			     "Failed to parse XML: %s", error_local->message);
		return FALSE;
	}
	components = xb_silo_query (silo, "components/component", 0, &error_local);
	if (components == NULL) {
		if (g_error_matches (error_local, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {
			g_set_error_literal (error,
					     G_IO_ERROR,
					     G_IO_ERROR_INVALID_DATA,
					     "No applications found in the AppStream XML");
			return FALSE;
		}
		g_set_error (error,
			     G_IO_ERROR,
			     G_IO_ERROR_INVALID_DATA,
			     "Failed to query XML: %s", error_local->message);
		return FALSE;
	}

	return TRUE;
}
Пример #18
0
GimpPlugInProcedure *
file_procedure_find (GSList       *procs,
                     const gchar  *uri,
                     GError      **error)
{
  GimpPlugInProcedure *file_proc;
  gchar               *filename;

  g_return_val_if_fail (procs != NULL, NULL);
  g_return_val_if_fail (uri != NULL, NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  /* First, check magicless prefixes/suffixes: */

  if (! file_proc_find_by_extension (procs, uri, FALSE, TRUE))
    {
      /* If there is not any (with or without magic) file proc that
       * can load the URI by extension directly, try to find a proc
       * that can load the prefix
       */
      file_proc = file_proc_find_by_prefix (procs, uri, TRUE);
    }
  else
    {
      /* Otherwise try to find a magicless file proc that handles the
       * extension
       */
      file_proc = file_proc_find_by_extension (procs, uri, TRUE, FALSE);
    }

  if (file_proc)
    return file_proc;

  filename = file_utils_filename_from_uri (uri);

  /* Then look for magics */
  if (filename)
    {
      GSList              *list;
      GimpPlugInProcedure *size_matched_proc = NULL;
      FILE                *ifp               = NULL;
      gboolean             opened            = FALSE;
      gint                 head_size         = 0;
      gint                 size_match_count  = 0;
      guchar               head[256];

      for (list = procs; list; list = g_slist_next (list))
        {
          file_proc = procs->data;

          if (file_proc->magics_list)
            {
              if (G_UNLIKELY (!opened))
                {
                  ifp = g_fopen (filename, "rb");
                  if (ifp != NULL)
                    head_size = fread ((gchar *) head, 1, sizeof (head), ifp);
                  else
                    g_set_error_literal (error,
                                         G_FILE_ERROR,
                                         g_file_error_from_errno (errno),
                                         g_strerror (errno));
                  opened = TRUE;
                }

              if (head_size >= 4)
                {
                  FileMatchType match_val;

                  match_val = file_check_magic_list (file_proc->magics_list,
                                                     head, head_size,
                                                     ifp);

                  if (match_val == FILE_MATCH_SIZE)
                    {
                      /* Use it only if no other magic matches */
                      size_match_count++;
                      size_matched_proc = file_proc;
                    }
                  else if (match_val != FILE_MATCH_NONE)
                    {
                      fclose (ifp);
                      g_free (filename);

                      return file_proc;
                    }
                }
            }
        }

      if (ifp)
        {
          if (ferror (ifp))
            g_set_error_literal (error, G_FILE_ERROR,
                                 g_file_error_from_errno (errno),
                                 g_strerror (errno));

          fclose (ifp);
        }

      g_free (filename);

      if (size_match_count == 1)
        return size_matched_proc;
    }

  /* As a last resort, try matching by name, not skipping magic procs */
  file_proc = file_proc_find_by_name (procs, uri, FALSE);

  if (file_proc)
    {
      /* we found a procedure, clear error that might have been set */
      g_clear_error (error);
    }
  else
    {
      /* set an error message unless one was already set */
      if (error && *error == NULL)
	g_set_error_literal (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
			     _("Unknown file type"));
    }

  return file_proc;
}
Пример #19
0
/**
 * facq_stream_save:
 * @stream: A closed #FacqStream object, see facq_stream_is_closed() for
 * more details.
 * @filename: filename of the file where you want to store stream details.
 * @err: (allow-none): A #GError, it will be set in case of error.
 *
 * Saves the closed #FacqStream, @stream, to the plain text file pointed by
 * @filename, creating it if necessary. You can create a #FacqStream from this
 * file later using facq_stream_load().
 *
 * Returns: %TRUE if successful, %FALSE in other case.
 */
gboolean facq_stream_save(FacqStream *stream,const gchar *filename,GError **err)
{
	GString *key_file_content = NULL;
	GKeyFile *key_file = NULL;
	gchar *txt_key_file_content = NULL;
	gboolean ret = FALSE;
	GError *local_err = NULL;
	guint i = 0, n_operations = 0;
	gpointer item = NULL;

	g_return_val_if_fail(FACQ_IS_STREAM(stream),FALSE);
	g_return_val_if_fail(filename,FALSE);
	g_return_val_if_fail(facq_stream_is_closed(stream),FALSE);

	key_file_content = facq_stream_save_get_group_names(stream);
	key_file = g_key_file_new();
	ret = g_key_file_load_from_data(key_file,
					key_file_content->str,
					-1,
					G_KEY_FILE_NONE,
					&local_err);
	g_string_free(key_file_content,TRUE);
	if(!ret)
		goto error;

	/* save the stream name */
	g_key_file_set_string(key_file,"Stream","name",stream->priv->name);
	
	/* save the source */
	item = stream->priv->src;
	facq_stream_save_item(key_file,item,i);
	i++;

	/* save the operations */
	n_operations = facq_stream_get_operation_num(stream);
	if(n_operations){
		for(i = 0;i < n_operations;i++){
			item = facq_operation_list_get(stream->priv->oplist,i);
			facq_stream_save_item(key_file,item,i+1);
		}
	}

	/* save the sink */
	i = 1 + n_operations;
	item = stream->priv->sink;
	facq_stream_save_item(key_file,item,i);

	txt_key_file_content = g_key_file_to_data(key_file,NULL,NULL);
	facq_log_write_v(FACQ_LOG_MSG_TYPE_DEBUG,"FILE:\n%s\n",txt_key_file_content);
	facq_stream_save_to_file(filename,txt_key_file_content,&local_err);
	g_free(txt_key_file_content);
	g_key_file_free(key_file);

	facq_log_write_v(FACQ_LOG_MSG_TYPE_INFO,"%s","Stream saved without errors");
	return TRUE;

	error:
	if(local_err){
		facq_log_write_v(FACQ_LOG_MSG_TYPE_ERROR,"%s",
						local_err->message);
		g_clear_error(&local_err);
	}
	if(err)
		g_set_error_literal(err,FACQ_STREAM_ERROR,
					FACQ_STREAM_ERROR_FAILED,
					"Error saving stream");
	return FALSE;
}
Пример #20
0
/*
 * nmc_parse_and_build_route:
 * @family: AF_INET or AF_INET6
 * @first: the route destination in the form of "address/prefix"
     (/prefix is optional)
 * @second: (allow-none): next hop address, if third is not NULL. Otherwise it could be
     either next hop address or metric. (It can be NULL when @third is NULL).
 * @third: (allow-none): route metric
 * @error: location to store GError
 *
 * Parse route from strings and return an #NMIPRoute
 *
 * Returns: %TRUE on success, %FALSE on failure
 */
NMIPRoute *
nmc_parse_and_build_route (int family,
                           const char *first,
                           const char *second,
                           const char *third,
                           GError **error)
{
	int max_prefix = (family == AF_INET) ? 32 : 128;
	char *dest = NULL, *plen = NULL;
	const char *next_hop = NULL;
	const char *canon_dest;
	long int prefix = max_prefix, metric = -1;
	NMIPRoute *route = NULL;
	gboolean success = FALSE;
	GError *local = NULL;

	g_return_val_if_fail (family == AF_INET || family == AF_INET6, FALSE);
	g_return_val_if_fail (first != NULL, FALSE);
	g_return_val_if_fail (second || !third, FALSE);
	g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

	dest = g_strdup (first);
	plen = strchr (dest, '/');  /* prefix delimiter */
	if (plen)
		*plen++ = '\0';

	if (plen) {
		if (!nmc_string_to_int (plen, TRUE, 1, max_prefix, &prefix)) {
			g_set_error (error, NMCLI_ERROR, NMC_RESULT_ERROR_USER_INPUT,
			             _("invalid prefix '%s'; <1-%d> allowed"),
			             plen, max_prefix);
			goto finish;
		}
	}

	if (second) {
		if (third || nm_utils_ipaddr_valid (family, second))
			next_hop = second;
		else {
			/* 'second' can be a metric */
			if (!nmc_string_to_int (second, TRUE, 0, G_MAXUINT32, &metric)) {
				g_set_error (error, 1, 0, _("the second component of route ('%s') is neither "
				                            "a next hop address nor a metric"), second);
				goto finish;
			}
		}
	}

	if (third) {
		if (!nmc_string_to_int (third, TRUE, 0, G_MAXUINT32, &metric)) {
			g_set_error (error, 1, 0, _("invalid metric '%s'"), third);
			goto finish;
		}
	}

	route = nm_ip_route_new (family, dest, prefix, next_hop, metric, &local);
	if (!route) {
		g_set_error (error, NMCLI_ERROR, NMC_RESULT_ERROR_USER_INPUT,
		             _("invalid route: %s"), local->message);
		g_clear_error (&local);
		goto finish;
	}

	/* We don't accept default routes as NetworkManager handles it
	 * itself. But we have to check this after @route has normalized the
	 * dest string.
	 */
	canon_dest = nm_ip_route_get_dest (route);
	if (!strcmp (canon_dest, "0.0.0.0") || !strcmp (canon_dest, "::")) {
		g_set_error_literal (error, NMCLI_ERROR, NMC_RESULT_ERROR_USER_INPUT,
		                     _("default route cannot be added (NetworkManager handles it by itself)"));
		g_clear_pointer (&route, nm_ip_route_unref);
		goto finish;
	}

	success = TRUE;

finish:
	g_free (dest);
	return route;
}
Пример #21
0
/**
 * facq_stream_start:
 * @stream: A #FacqStream object, in closed state.
 * @err: (allow-none): A #GError, it will be set in case of error, if not %NULL.
 *
 * Starts the stream, allowing the data to flow from the source to the
 * operations, if any, and to the sink.
 *
 * Returns: %TRUE if successful, %FALSE in other case.
 */
gboolean facq_stream_start(FacqStream *stream,GError **err)
{
	const FacqSource *src = NULL;
	const FacqStreamData *stmd = NULL;
	guint n_channels = 0;
	gsize chunk_size = 0;
	GError *local_err = NULL;

	//check that stream is closed if not set error return false
	if(facq_stream_is_closed(stream) != TRUE){
		if(local_err)
			g_set_error_literal(&local_err,FACQ_STREAM_ERROR,
				FACQ_STREAM_ERROR_CLOSED,
					"The stream should be closed");
		goto error;
	}
	src = stream->priv->src;
	stmd = facq_source_get_stream_data(src);
	n_channels = facq_stream_data_get_n_channels(stmd);
	if(FACQ_IS_PIPELINE(stream->priv->p)){
		facq_pipeline_free(stream->priv->p);
		stream->priv->p = NULL;
	}

	//Empty the monitor from previous messages if any
	facq_pipeline_monitor_clear(stream->priv->mon);
	
	//Calculate a valid chunk size
	if(stmd->period <= 1)
		chunk_size = facq_misc_period_to_chunk_size(stmd->period,
							    sizeof(gdouble),
							    stmd->n_channels);
	else
		chunk_size = 8*n_channels;

	//start the pipeline
	stream->priv->p = facq_pipeline_new(chunk_size,
					    stream->priv->ring_chunks,
					    stream->priv->src,
					    stream->priv->oplist,
					    stream->priv->sink,
					    stream->priv->mon,
					    &local_err);
	if(local_err)
		goto error;

	//attach the monitor to the main thread, it will be polled for new
	//messages one time each second.
	facq_pipeline_monitor_attach(stream->priv->mon);

	if(!facq_pipeline_start(stream->priv->p,&local_err)){
		facq_pipeline_monitor_dettach(stream->priv->mon);
		goto error;
	}

	facq_log_write_v(FACQ_LOG_MSG_TYPE_INFO,"%s","Stream started");
	return TRUE;

	error:
	if(local_err){
		if(err)
			g_propagate_error(err,local_err);
	}
	return FALSE;
}
Пример #22
0
/**
 * clutter_image_set_area:
 * @image: a #ClutterImage
 * @data: (array): the image data, as an array of bytes
 * @pixel_format: the Cogl pixel format of the image data
 * @rect: a rectangle indicating the area that should be set
 * @row_stride: the length of each row inside @data
 * @error: return location for a #GError, or %NULL
 *
 * Sets the image data to be display by @image, using @rect to indicate
 * the position and size of the image data to be set.
 *
 * If the @image does not have any image data set when this function is
 * called, a new texture will be created with the size of the width and
 * height of the rectangle, i.e. calling this function on a newly created
 * #ClutterImage will be the equivalent of calling clutter_image_set_data().
 *
 * If the image data was successfully loaded, the @image will be invalidated.
 *
 * In case of error, the @error value will be set, and this function will
 * return %FALSE.
 *
 * The image data is copied in texture memory.
 *
 * Return value: %TRUE if the image data was successfully loaded,
 *   and %FALSE otherwise.
 *
 * Since: 1.10
 */
gboolean
clutter_image_set_area (ClutterImage                 *image,
                        const guint8                 *data,
                        CoglPixelFormat               pixel_format,
                        const cairo_rectangle_int_t  *area,
                        guint                         row_stride,
                        GError                      **error)
{
  ClutterImagePrivate *priv;

  g_return_val_if_fail (CLUTTER_IS_IMAGE (image), FALSE);
  g_return_val_if_fail (data != NULL, FALSE);
  g_return_val_if_fail (area != NULL, FALSE);

  priv = image->priv;

  if (priv->texture == NULL)
    {
      CoglTextureFlags flags = COGL_TEXTURE_NONE;

      if (area->width >= 512 && area->height >= 512)
        flags |= COGL_TEXTURE_NO_ATLAS;

      priv->texture = cogl_texture_new_from_data (area->width,
                                                  area->height,
                                                  flags,
                                                  pixel_format,
                                                  COGL_PIXEL_FORMAT_ANY,
                                                  row_stride,
                                                  data);
    }
  else
    {
      gboolean res;

      res = cogl_texture_set_region (priv->texture,
                                     0, 0,
                                     area->x, area->y,
                                     area->width, area->height,
                                     area->width, area->height,
                                     pixel_format,
                                     row_stride,
                                     data);

      if (!res)
        {
          cogl_object_unref (priv->texture);
          priv->texture = NULL;
        }
    }

  if (priv->texture == NULL)
    {
      g_set_error_literal (error, CLUTTER_IMAGE_ERROR,
                           CLUTTER_IMAGE_ERROR_INVALID_DATA,
                           _("Unable to load image data"));
      return FALSE;
    }

  clutter_content_invalidate (CLUTTER_CONTENT (image));

  return TRUE;
}
Пример #23
0
static GimpValueArray *
image_convert_indexed_invoker (GimpProcedure         *procedure,
                               Gimp                  *gimp,
                               GimpContext           *context,
                               GimpProgress          *progress,
                               const GimpValueArray  *args,
                               GError               **error)
{
  gboolean success = TRUE;
  GimpImage *image;
  gint32 dither_type;
  gint32 palette_type;
  gint32 num_cols;
  gboolean alpha_dither;
  gboolean remove_unused;
  const gchar *palette;

  image = gimp_value_get_image (gimp_value_array_index (args, 0), gimp);
  dither_type = g_value_get_enum (gimp_value_array_index (args, 1));
  palette_type = g_value_get_enum (gimp_value_array_index (args, 2));
  num_cols = g_value_get_int (gimp_value_array_index (args, 3));
  alpha_dither = g_value_get_boolean (gimp_value_array_index (args, 4));
  remove_unused = g_value_get_boolean (gimp_value_array_index (args, 5));
  palette = g_value_get_string (gimp_value_array_index (args, 6));

  if (success)
    {
      GimpPalette *pal = NULL;

      if (gimp_pdb_image_is_not_base_type (image, GIMP_INDEXED, error) &&
          gimp_pdb_image_is_precision (image, GIMP_PRECISION_U8, error) &&
          gimp_item_stack_is_flat (GIMP_ITEM_STACK (gimp_image_get_layers (image))))
        {
          switch (palette_type)
            {
            case GIMP_MAKE_PALETTE:
              if (num_cols < 1 || num_cols > MAXNUMCOLORS)
                success = FALSE;
              break;

            case GIMP_CUSTOM_PALETTE:
              pal = gimp_pdb_get_palette (gimp, palette, FALSE, error);
              if (! pal)
                {
                  success = FALSE;
                }
              else if (pal->n_colors > MAXNUMCOLORS)
                {
                  g_set_error_literal (error,
                                       GIMP_PDB_ERROR,
                                       GIMP_PDB_ERROR_INVALID_ARGUMENT,
                                       _("Cannot convert to a palette "
                                         "with more than 256 colors."));
                  success = FALSE;
                }
              break;

            default:
              break;
            }
        }
      else
        {
          success = FALSE;
        }

      if (success)
        success = gimp_image_convert_type (image, GIMP_INDEXED,
                                           num_cols, dither_type,
                                           alpha_dither, remove_unused,
                                           palette_type, pal,
                                           NULL, error);
    }

  return gimp_procedure_get_return_values (procedure, success,
                                           error ? *error : NULL);
}
Пример #24
0
static gboolean
check_filter (GVariant *filter,
              GError **error)
{
  const char *name;
  g_autoptr(GVariant) list = NULL;
  int i;

  g_variant_get (filter, "(&s@a(us))", &name, &list);

  if (name[0] == 0)
    {
      g_set_error_literal (error,
                           XDG_DESKTOP_PORTAL_ERROR,
                           XDG_DESKTOP_PORTAL_ERROR_INVALID_ARGUMENT,
                           "name is empty");
      return FALSE;
    }

  if (g_variant_n_children (list) == 0)
    {
      g_set_error_literal (error,
                           XDG_DESKTOP_PORTAL_ERROR,
                           XDG_DESKTOP_PORTAL_ERROR_INVALID_ARGUMENT,
                           "no filters");
      return FALSE;
    }

  for (i = 0; i < g_variant_n_children (list); i++)
    {
      guint32 type;
      const char *string;

      g_variant_get_child (list, i, "(u&s)", &type, &string);
      if (type == 0)
        {
          /* TODO: validate glob */
          if (string[0] == 0)
            {
              g_set_error_literal (error,
                                   XDG_DESKTOP_PORTAL_ERROR,
                                   XDG_DESKTOP_PORTAL_ERROR_INVALID_ARGUMENT,
                                   "invalid glob pattern");
              return FALSE;
            }
        }
      else if (type == 1)
        {
        }
          /* TODO: validate content type */
          if (string[0] == 0)
            {
              g_set_error_literal (error,
                                   XDG_DESKTOP_PORTAL_ERROR,
                                   XDG_DESKTOP_PORTAL_ERROR_INVALID_ARGUMENT,
                                   "invalid content type");
              return FALSE;
            }
      else
        {
          g_set_error (error,
                       XDG_DESKTOP_PORTAL_ERROR,
                       XDG_DESKTOP_PORTAL_ERROR_INVALID_ARGUMENT,
                       "invalid filter type: %u", type);
          return FALSE;
        }
    }

  return TRUE;
}
Пример #25
0
static gboolean
as_app_builder_parse_file_pak (AsAppBuilderContext *ctx,
			       const gchar *locale,
			       const gchar *filename,
			       GError **error)
{
	AsAppBuilderEntry *entry;
	gsize len = 0;
	guint32 nr_resources;
	guint32 version_number;
	guint8 encoding;
	g_autofree gchar *data = NULL;

	if (!g_file_get_contents (filename, &data, &len, error))
		return FALSE;
	if (len < 9) {
		g_set_error (error,
			     AS_APP_ERROR,
			     AS_APP_ERROR_FAILED,
			     "file invalid, %" G_GSIZE_FORMAT "b in size",
			     len);
		return FALSE;
	}

	/* get 4 byte version number */
	memcpy (&version_number, data + 0, 4);
	if (version_number != 4) {
		g_set_error (error,
			     AS_APP_ERROR,
			     AS_APP_ERROR_FAILED,
			     "version number invalid, "
			     "got %" G_GUINT32_FORMAT " expected 4",
			     version_number);
		return FALSE;
	}

	/* get 4 byte number of resources */
	memcpy (&nr_resources, data + 4, 4);
	if (nr_resources == 0) {
		g_set_error_literal (error,
				     AS_APP_ERROR,
				     AS_APP_ERROR_FAILED,
				     "no resources found");
		return FALSE;
	}

	/* get single byte of encoding */
	encoding = (guint8) data[8];
	if (encoding != 0 && encoding != 1) {
		g_set_error (error,
			     AS_APP_ERROR,
			     AS_APP_ERROR_FAILED,
			     "PAK encoding invalid, got %u expected 0 or 1",
			     encoding);
		return FALSE;
	}

	/* create entry without reading resources */
	entry = as_app_builder_entry_new ();
	entry->locale = g_strdup (locale);
	entry->nstrings = nr_resources;
	if (entry->nstrings > ctx->max_nstrings)
		ctx->max_nstrings = entry->nstrings;
	ctx->data = g_list_prepend (ctx->data, entry);
	return TRUE;
}
Пример #26
0
static gboolean
check_choice (GVariant *choice,
              GError **error)
{
  const char *id;
  const char *label;
  g_autoptr(GVariant) options = NULL;
  const char *option;
  int i;
  gboolean seen_option;

  g_variant_get (choice, "(&s&s@a(ss)&s)", &id, &label, &options, &option);

  if (id[0] == 0)
    {
      g_set_error_literal (error,
                           XDG_DESKTOP_PORTAL_ERROR,
                           XDG_DESKTOP_PORTAL_ERROR_INVALID_ARGUMENT,
                           "id is empty");
      return FALSE;
    }

  if (label[0] == 0)
    {
      g_set_error_literal (error,
                           XDG_DESKTOP_PORTAL_ERROR,
                           XDG_DESKTOP_PORTAL_ERROR_INVALID_ARGUMENT,
                           "label is empty");
      return FALSE;
    }

  if (g_variant_n_children (options) == 0)
    {
      const char *values[] = { "", "true", "false", NULL };
      if (!g_strv_contains (values, option))
        {
          g_set_error (error,
                       XDG_DESKTOP_PORTAL_ERROR,
                       XDG_DESKTOP_PORTAL_ERROR_INVALID_ARGUMENT,
                       "bad current option: %s", option);
          return FALSE;
        }

      return TRUE;
    }

  seen_option = FALSE;
  for (i = 0; i < g_variant_n_children (options); i++)
    {
      const char *o_id;
      const char *o_label;

      g_variant_get_child (options, i, "(&s&s)", &o_id, &o_label);

      if (o_id[0] == 0)
        {
          g_set_error_literal (error,
                               XDG_DESKTOP_PORTAL_ERROR,
                               XDG_DESKTOP_PORTAL_ERROR_INVALID_ARGUMENT,
                               "option id is empty");
          return FALSE;
        }
      if (o_label[0] == 0)
        {
          g_set_error_literal (error,
                               XDG_DESKTOP_PORTAL_ERROR,
                               XDG_DESKTOP_PORTAL_ERROR_INVALID_ARGUMENT,
                               "option label is empty");
          return FALSE;
        }

      if (strcmp (o_id, option) == 0)
        seen_option = TRUE;
    }

  if (!seen_option && option[0] != 0)
    {
      g_set_error (error,
                   XDG_DESKTOP_PORTAL_ERROR,
                   XDG_DESKTOP_PORTAL_ERROR_INVALID_ARGUMENT,
                   "bad current option: %s", option);
      return FALSE;
    }

  return TRUE;
}
Пример #27
0
gboolean
ostree_builtin_static_delta (int argc, char **argv, GCancellable *cancellable, GError **error)
{
  gboolean ret = FALSE;
  OstreeCommand *command = NULL;
  const char *cmdname = NULL;
  glnx_unref_object OstreeRepo *repo = NULL;
  int i;
  gboolean want_help = FALSE;

  for (i = 1; i < argc; i++)
    {
      if (argv[i][0] != '-')
        {
          cmdname = argv[i];
          break;
        }
      else if (g_str_equal (argv[i], "--help") || g_str_equal (argv[i], "-h"))
        {
          want_help = TRUE;
          break;
        }
    }

  if (!cmdname && !want_help)
    {
      static_delta_usage (argv, TRUE);
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "No command specified");
      goto out;
    }

  if (cmdname)
    {
      command = static_delta_subcommands;
      while (command->name)
        {
          if (g_strcmp0 (cmdname, command->name) == 0)
            break;
          command++;
        }
    }

  if (want_help && command == NULL)
    {
      static_delta_usage (argv, FALSE);
      ret = TRUE;
      goto out;
    }

  if (!command->fn)
    {
      g_autofree char *msg = g_strdup_printf ("Unknown command '%s'", cmdname);
      static_delta_usage (argv, TRUE);
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED, msg);
      goto out;
    }

  if (!command->fn (argc, argv, cancellable, error))
    goto out;

  ret = TRUE;
 out:
  return ret;
}
Пример #28
0
static gboolean
_ostree_bootloader_syslinux_write_config (OstreeBootloader          *bootloader,
                                     int                    bootversion,
                                     GCancellable          *cancellable,
                                     GError               **error)
{
  gboolean ret = FALSE;
  OstreeBootloaderSyslinux *self = OSTREE_BOOTLOADER_SYSLINUX (bootloader);
  gs_unref_object GFile *new_config_path = NULL;
  gs_free char *config_contents = NULL;
  gs_free char *new_config_contents = NULL;
  gs_unref_ptrarray GPtrArray *new_lines = NULL;
  gs_unref_ptrarray GPtrArray *tmp_lines = NULL;
  gs_free char *kernel_arg = NULL;
  gboolean saw_default = FALSE;
  gboolean regenerate_default = FALSE;
  gboolean parsing_label = FALSE;
  char **lines = NULL;
  char **iter;
  guint i;

  new_config_path = ot_gfile_resolve_path_printf (self->sysroot->path, "boot/loader.%d/syslinux.cfg",
                                                  bootversion);

  /* This should follow the symbolic link to the current bootversion. */
  config_contents = gs_file_load_contents_utf8 (self->config_path, cancellable, error);
  if (!config_contents)
    goto out;

  lines = g_strsplit (config_contents, "\n", -1);
  new_lines = g_ptr_array_new_with_free_func (g_free);
  tmp_lines = g_ptr_array_new_with_free_func (g_free);
  
  /* Note special iteration condition here; we want to also loop one
   * more time at the end where line = NULL to ensure we finish off
   * processing the last LABEL.
   */
  iter = lines;
  while (TRUE)
    {
      char *line = *iter;
      gboolean skip = FALSE;

      if (parsing_label && 
          (line == NULL || !g_str_has_prefix (line, "\t")))
        {
          parsing_label = FALSE;
          if (kernel_arg == NULL)
            {
              g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                   "No KERNEL argument found after LABEL");
              goto out;
            }

          /* If this is a non-ostree kernel, just emit the lines
           * we saw.
           */
          if (!g_str_has_prefix (kernel_arg, "/ostree/"))
            {
              for (i = 0; i < tmp_lines->len; i++)
                {
                  g_ptr_array_add (new_lines, tmp_lines->pdata[i]);
                  tmp_lines->pdata[i] = NULL; /* Transfer ownership */
                }
            }
          else
            {
              /* Otherwise, we drop the config on the floor - it
               * will be regenerated.
               */
              g_ptr_array_set_size (tmp_lines, 0);
            }
        }

      if (line == NULL)
        break;

      if (!parsing_label &&
          (g_str_has_prefix (line, "LABEL ")))
        {
          parsing_label = TRUE;
          g_ptr_array_set_size (tmp_lines, 0);
        }
      else if (parsing_label && g_str_has_prefix (line, "\tKERNEL "))
        {
          g_free (kernel_arg);
          kernel_arg = g_strdup (line + strlen ("\tKERNEL "));
        }
      else if (!parsing_label &&
               (g_str_has_prefix (line, "DEFAULT ")))
        {
          saw_default = TRUE;
          /* XXX Searching for patterns in the title is rather brittle,
           *     but this hack is at least noted in the code that builds
           *     the title to hopefully avoid regressions. */
          if (g_str_has_prefix (line, "DEFAULT ostree:") ||  /* old format */
              strstr (line, "(ostree") != NULL)              /* new format */
            {
              regenerate_default = TRUE;
            }
          skip = TRUE;
        }
      
      if (skip)
        {
          g_free (line);
        }
      else
        {
          if (parsing_label)
            {
              g_ptr_array_add (tmp_lines, line);
            }
          else
            {
              g_ptr_array_add (new_lines, line);
            }
        }
      /* Transfer ownership */
      *iter = NULL;
      iter++;
    }

  if (!saw_default)
    regenerate_default = TRUE;

  if (!append_config_from_boostree_loader_entries (self, regenerate_default,
                                               bootversion, new_lines,
                                               cancellable, error))
    goto out;

  new_config_contents = _ostree_sysroot_join_lines (new_lines);
  {
    gs_unref_bytes GBytes *new_config_contents_bytes =
      g_bytes_new_static (new_config_contents,
                          strlen (new_config_contents));

    if (!ot_gfile_replace_contents_fsync (new_config_path, new_config_contents_bytes,
                                          cancellable, error))
      goto out;
  }
  
  ret = TRUE;
 out:
  g_free (lines); /* Note we freed elements individually */
  return ret;
}
Пример #29
0
/**
 * nm_modem_get_connection_ip_type:
 * @self: the #NMModem
 * @connection: the #NMConnection to determine IP type to use
 *
 * Given a modem and a connection, determine which #NMModemIPTypes to use
 * when connecting.
 *
 * Returns: an array of #NMModemIpType values, in the order in which they
 * should be tried.
 */
GArray *
nm_modem_get_connection_ip_type (NMModem *self,
                                 NMConnection *connection,
                                 GError **error)
{
	NMModemPrivate *priv = NM_MODEM_GET_PRIVATE (self);
	NMSettingIPConfig *s_ip4, *s_ip6;
	const char *method;
	gboolean ip4 = TRUE, ip6 = TRUE;
	gboolean ip4_may_fail = TRUE, ip6_may_fail = TRUE;

	s_ip4 = nm_connection_get_setting_ip4_config (connection);
	if (s_ip4) {
		method = nm_setting_ip_config_get_method (s_ip4);
		if (g_strcmp0 (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0)
			ip4 = FALSE;
		ip4_may_fail = nm_setting_ip_config_get_may_fail (s_ip4);
	}

	s_ip6 = nm_connection_get_setting_ip6_config (connection);
	if (s_ip6) {
		method = nm_setting_ip_config_get_method (s_ip6);
		if (g_strcmp0 (method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE) == 0)
			ip6 = FALSE;
		ip6_may_fail = nm_setting_ip_config_get_may_fail (s_ip6);
	}

	if (ip4 && !ip6) {
		if (!(priv->ip_types & NM_MODEM_IP_TYPE_IPV4)) {
			g_set_error_literal (error,
			                     NM_DEVICE_ERROR,
			                     NM_DEVICE_ERROR_INCOMPATIBLE_CONNECTION,
			                     "Connection requested IPv4 but IPv4 is "
			                     "unsupported by the modem.");
			return NULL;
		}
		return build_single_ip_type_array (NM_MODEM_IP_TYPE_IPV4);
	}

	if (ip6 && !ip4) {
		if (!(priv->ip_types & NM_MODEM_IP_TYPE_IPV6)) {
			g_set_error_literal (error,
			                     NM_DEVICE_ERROR,
			                     NM_DEVICE_ERROR_INCOMPATIBLE_CONNECTION,
			                     "Connection requested IPv6 but IPv6 is "
			                     "unsupported by the modem.");
			return NULL;
		}
		return build_single_ip_type_array (NM_MODEM_IP_TYPE_IPV6);
	}

	if (ip4 && ip6) {
		NMModemIPType type;
		GArray *out;

		out = g_array_sized_new (FALSE, FALSE, sizeof (NMModemIPType), 3);

		/* Modem supports dual-stack? */
		if (priv->ip_types & NM_MODEM_IP_TYPE_IPV4V6) {
			type = NM_MODEM_IP_TYPE_IPV4V6;
			g_array_append_val (out, type);
		}

		/* If IPv6 may-fail=false, we should NOT try IPv4 as fallback */
		if ((priv->ip_types & NM_MODEM_IP_TYPE_IPV4) && ip6_may_fail) {
			type = NM_MODEM_IP_TYPE_IPV4;
			g_array_append_val (out, type);
		}

		/* If IPv4 may-fail=false, we should NOT try IPv6 as fallback */
		if ((priv->ip_types & NM_MODEM_IP_TYPE_IPV6) && ip4_may_fail) {
			type = NM_MODEM_IP_TYPE_IPV6;
			g_array_append_val (out, type);
		}

		if (out->len > 0)
			return out;

		/* Error... */
		g_array_unref (out);
		g_set_error_literal (error,
		                     NM_DEVICE_ERROR,
		                     NM_DEVICE_ERROR_INCOMPATIBLE_CONNECTION,
		                     "Connection requested both IPv4 and IPv6 "
		                     "but dual-stack addressing is unsupported "
		                     "by the modem.");
		return NULL;
	}

	g_set_error_literal (error,
	                     NM_DEVICE_ERROR,
	                     NM_DEVICE_ERROR_INCOMPATIBLE_CONNECTION,
	                     "Connection specified no IP configuration!");
	return NULL;
}
Пример #30
0
GIOChannel *
g_io_channel_new_file (const gchar *filename,
                       const gchar *mode,
                       GError     **error)
{
  int fid, flags;
  mode_t create_mode;
  GIOChannel *channel;
  enum { /* Cheesy hack */
    MODE_R = 1 << 0,
    MODE_W = 1 << 1,
    MODE_A = 1 << 2,
    MODE_PLUS = 1 << 3
  } mode_num;
  struct stat buffer;

  g_return_val_if_fail (filename != NULL, NULL);
  g_return_val_if_fail (mode != NULL, NULL);
  g_return_val_if_fail ((error == NULL) || (*error == NULL), NULL);

  switch (mode[0])
    {
      case 'r':
        mode_num = MODE_R;
        break;
      case 'w':
        mode_num = MODE_W;
        break;
      case 'a':
        mode_num = MODE_A;
        break;
      default:
        g_warning ("Invalid GIOFileMode %s.\n", mode);
        return NULL;
    }

  switch (mode[1])
    {
      case '\0':
        break;
      case '+':
        if (mode[2] == '\0')
          {
            mode_num |= MODE_PLUS;
            break;
          }
        /* Fall through */
      default:
        g_warning ("Invalid GIOFileMode %s.\n", mode);
        return NULL;
    }

  switch (mode_num)
    {
      case MODE_R:
        flags = O_RDONLY;
        break;
      case MODE_W:
        flags = O_WRONLY | O_TRUNC | O_CREAT;
        break;
      case MODE_A:
        flags = O_WRONLY | O_APPEND | O_CREAT;
        break;
      case MODE_R | MODE_PLUS:
        flags = O_RDWR;
        break;
      case MODE_W | MODE_PLUS:
        flags = O_RDWR | O_TRUNC | O_CREAT;
        break;
      case MODE_A | MODE_PLUS:
        flags = O_RDWR | O_APPEND | O_CREAT;
        break;
      default:
        g_assert_not_reached ();
        flags = 0;
    }

  create_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
  fid = open (filename, flags, create_mode);
  if (fid == -1)
    {
      int err = errno;
      g_set_error_literal (error, G_FILE_ERROR,
                           g_file_error_from_errno (err),
                           g_strerror (err));
      return (GIOChannel *)NULL;
    }

  if (fstat (fid, &buffer) == -1) /* In case someone opens a FIFO */
    {
      int err = errno;
      close (fid);
      g_set_error_literal (error, G_FILE_ERROR,
                           g_file_error_from_errno (err),
                           g_strerror (err));
      return (GIOChannel *)NULL;
    }

  channel = (GIOChannel *) g_new (GIOUnixChannel, 1);

  channel->is_seekable = S_ISREG (buffer.st_mode) || S_ISCHR (buffer.st_mode)
                         || S_ISBLK (buffer.st_mode);

  switch (mode_num)
    {
      case MODE_R:
        channel->is_readable = TRUE;
        channel->is_writeable = FALSE;
        break;
      case MODE_W:
      case MODE_A:
        channel->is_readable = FALSE;
        channel->is_writeable = TRUE;
        break;
      case MODE_R | MODE_PLUS:
      case MODE_W | MODE_PLUS:
      case MODE_A | MODE_PLUS:
        channel->is_readable = TRUE;
        channel->is_writeable = TRUE;
        break;
      default:
        g_assert_not_reached ();
    }

  g_io_channel_init (channel);
  channel->close_on_unref = TRUE; /* must be after g_io_channel_init () */
  channel->funcs = &unix_channel_funcs;

  ((GIOUnixChannel *) channel)->fd = fid;
  return channel;
}