示例#1
0
/**
 * gst_tag_image_data_to_image_buffer:
 * @image_data: the (encoded) image
 * @image_data_len: the length of the encoded image data at @image_data
 * @image_type: type of the image, or #GST_TAG_IMAGE_TYPE_UNDEFINED. Pass
 *     #GST_TAG_IMAGE_TYPE_NONE if no image type should be set at all (e.g.
 *     for preview images)
 *
 * Helper function for tag-reading plugins to create a #GstBuffer suitable to
 * add to a #GstTagList as an image tag (such as #GST_TAG_IMAGE or
 * #GST_TAG_PREVIEW_IMAGE) from the encoded image data and an (optional) image
 * type.
 *
 * Background: cover art and other images in tags are usually stored as a
 * blob of binary image data, often accompanied by a MIME type or some other
 * content type string (e.g. 'png', 'jpeg', 'jpg'). Sometimes there is also an
 * 'image type' to indicate what kind of image this is (e.g. front cover,
 * back cover, artist, etc.). The image data may also be an URI to the image
 * rather than the image itself.
 *
 * In GStreamer, image tags are #GstBuffer<!-- -->s containing the raw image
 * data, with the buffer caps describing the content type of the image
 * (e.g. image/jpeg, image/png, text/uri-list). The buffer caps may contain
 * an additional 'image-type' field of #GST_TYPE_TAG_IMAGE_TYPE to describe
 * the type of image (front cover, back cover etc.). #GST_TAG_PREVIEW_IMAGE
 * tags should not carry an image type, their type is already indicated via
 * the special tag name.
 *
 * This function will do various checks and typefind the encoded image
 * data (we can't trust the declared mime type).
 *
 * Returns: a newly-allocated image buffer for use in tag lists, or NULL
 *
 * Since: 0.10.20
 */
GstBuffer *
gst_tag_image_data_to_image_buffer (const guint8 * image_data,
    guint image_data_len, GstTagImageType image_type)
{
  const gchar *name;

  GstBuffer *image;

  GstCaps *caps;

  g_return_val_if_fail (image_data != NULL, NULL);
  g_return_val_if_fail (image_data_len > 0, NULL);
  g_return_val_if_fail (gst_tag_image_type_is_valid (image_type), NULL);

  GST_DEBUG ("image data len: %u bytes", image_data_len);

  /* allocate space for a NUL terminator for an uri too */
  image = gst_buffer_try_new_and_alloc (image_data_len + 1);
  if (image == NULL) {
    GST_WARNING ("failed to allocate buffer of %d for image", image_data_len);
    return NULL;
  }

  memcpy (GST_BUFFER_DATA (image), image_data, image_data_len);
  GST_BUFFER_DATA (image)[image_data_len] = '\0';

  /* Find GStreamer media type, can't trust declared type */
  caps = gst_type_find_helper_for_buffer (NULL, image, NULL);

  if (caps == NULL)
    goto no_type;

  GST_DEBUG ("Found GStreamer media type: %" GST_PTR_FORMAT, caps);

  /* sanity check: make sure typefound/declared caps are either URI or image */
  name = gst_structure_get_name (gst_caps_get_structure (caps, 0));

  if (!g_str_has_prefix (name, "image/") &&
      !g_str_has_prefix (name, "video/") &&
      !g_str_equal (name, "text/uri-list")) {
    GST_DEBUG ("Unexpected image type '%s', ignoring image frame", name);
    goto error;
  }

  /* Decrease size by 1 if we don't have an URI list
   * to keep the original size of the image
   */
  if (!g_str_equal (name, "text/uri-list"))
    GST_BUFFER_SIZE (image) = image_data_len;

  if (image_type != GST_TAG_IMAGE_TYPE_NONE) {
    GST_LOG ("Setting image type: %d", image_type);
    caps = gst_caps_make_writable (caps);
    gst_caps_set_simple (caps, "image-type", GST_TYPE_TAG_IMAGE_TYPE,
        image_type, NULL);
  }

  gst_buffer_set_caps (image, caps);
  gst_caps_unref (caps);
  return image;

/* ERRORS */
no_type:
  {
    GST_DEBUG ("Could not determine GStreamer media type, ignoring image");
    /* fall through */
  }
error:
  {
    if (image)
      gst_buffer_unref (image);
    if (caps)
      gst_caps_unref (caps);
    return NULL;
  }
}
示例#2
0
static void
server_callback (SoupServer *server, SoupMessage *msg,
                 const char *path, GHashTable *query,
                 SoupClientContext *context, gpointer data)
{
    char *remainder;
    guint status_code;

    if (g_str_has_prefix (path, "/bad")) {
        if (!strcmp (path, "/bad")) {
            soup_message_set_status (msg, SOUP_STATUS_FOUND);
            soup_message_headers_replace (msg->response_headers,
                                          "Location",
                                          "/bad with spaces");
        } else if (!strcmp (path, "/bad with spaces"))
            soup_message_set_status (msg, SOUP_STATUS_OK);
        else
            soup_message_set_status (msg, SOUP_STATUS_NOT_FOUND);
        return;
    }

    if (!strcmp (path, "/")) {
        if (msg->method != SOUP_METHOD_GET &&
                msg->method != SOUP_METHOD_HEAD) {
            soup_message_set_status (msg, SOUP_STATUS_METHOD_NOT_ALLOWED);
            return;
        }

        /* Make sure that redirecting a POST clears the body */
        if (msg->request_body->length) {
            soup_message_set_status (msg, SOUP_STATUS_BAD_REQUEST);
            return;
        }

        /* Make sure that a HTTP/1.0 redirect doesn't cause an
         * HTTP/1.0 re-request. (#521848)
         */
        if (soup_message_get_http_version (msg) == SOUP_HTTP_1_0) {
            soup_message_set_status (msg, SOUP_STATUS_BAD_REQUEST);
            return;
        }

        soup_message_set_status (msg, SOUP_STATUS_OK);

        /* FIXME: this is wrong, though it doesn't matter for
         * the purposes of this test, and to do the right
         * thing currently we'd have to set Content-Length by
         * hand.
         */
        if (msg->method != SOUP_METHOD_HEAD) {
            soup_message_set_response (msg, "text/plain",
                                       SOUP_MEMORY_STATIC,
                                       "OK\r\n", 4);
        }
        return;
    }

    status_code = strtoul (path + 1, &remainder, 10);
    if (!SOUP_STATUS_IS_REDIRECTION (status_code) ||
            (*remainder && *remainder != '/')) {
        soup_message_set_status (msg, SOUP_STATUS_NOT_FOUND);
        return;
    }

    /* See above comment re bug 521848. */
    soup_message_set_http_version (msg, SOUP_HTTP_1_0);

    soup_message_set_status (msg, status_code);
    if (*remainder) {
        soup_message_headers_replace (msg->response_headers,
                                      "Location", remainder);
    } else {
        soup_message_headers_replace (msg->response_headers,
                                      "Location", "/");
    }
}
static void
client_message (Client * client, const gchar * data, guint len)
{
  gchar **lines = g_strsplit_set (data, "\r\n", -1);

  if (g_str_has_prefix (lines[0], "HEAD")) {
    gchar **parts = g_strsplit (lines[0], " ", -1);
    gchar *response;
    const gchar *http_version;

    if (parts[1] && parts[2] && *parts[2] != '\0')
      http_version = parts[2];
    else
      http_version = "HTTP/1.0";

    if (parts[1] && strcmp (parts[1], "/") == 0) {
      response = g_strdup_printf ("%s 200 OK\r\n" "\r\n", http_version);
    } else {
      response = g_strdup_printf ("%s 404 Not Found\r\n\r\n", http_version);
    }
    write_bytes (client, response, strlen (response));
    g_free (response);
    g_strfreev (parts);
  } else if (g_str_has_prefix (lines[0], "GET")) {
    gchar **parts = g_strsplit (lines[0], " ", -1);
    gchar *response;
    const gchar *http_version;
    gboolean ok = FALSE;

    if (parts[1] && parts[2] && *parts[2] != '\0')
      http_version = parts[2];
    else
      http_version = "HTTP/1.0";

    if (parts[1] && strcmp (parts[1], "/") == 0) {
      response = g_strdup_printf ("%s 200 OK\r\n" "\r\n", http_version);
      ok = TRUE;
    } else {
      response = g_strdup_printf ("%s 404 Not Found\r\n\r\n", http_version);
    }
    write_bytes (client, response, strlen (response));
    g_free (response);
    g_strfreev (parts);

    if (ok) {
      g_source_destroy (client->isource);
      g_source_unref (client->isource);
      client->isource = NULL;
      g_source_destroy (client->tosource);
      g_source_unref (client->tosource);
      client->tosource = NULL;
      g_print ("Starting to stream to %s\n", client->name);
      g_signal_emit_by_name (multisocketsink, "add", client->socket);

      if (!started) {
        g_print ("Starting pipeline\n");
        if (gst_element_set_state (pipeline,
                GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
          g_print ("Failed to start pipeline\n");
          g_main_loop_quit (loop);
        }
        started = TRUE;
      }
    }
  } else {
    gchar **parts = g_strsplit (lines[0], " ", -1);
    gchar *response;
    const gchar *http_version;

    if (parts[1] && parts[2] && *parts[2] != '\0')
      http_version = parts[2];
    else
      http_version = "HTTP/1.0";

    response = g_strdup_printf ("%s 400 Bad Request\r\n\r\n", http_version);
    write_bytes (client, response, strlen (response));
    g_free (response);
    g_strfreev (parts);
    remove_client (client);
  }

  g_strfreev (lines);
}
示例#4
0
gboolean SidebarIndexPage::treeSearchFunction(GtkTreeModel* model, gint column,
                                              const gchar* key, GtkTreeIter* iter, SidebarIndexPage* sidebar)
{
	XOJ_CHECK_TYPE_OBJ(sidebar, SidebarIndexPage);


	if (sidebar->searchTimeout)
	{
		g_source_remove(sidebar->searchTimeout);
		sidebar->searchTimeout = 0;
	}
	sidebar->searchTimeout = g_timeout_add_seconds_full(G_PRIORITY_DEFAULT_IDLE, 2,
	                                                    (GSourceFunc) searchTimeoutFunc, sidebar, NULL);


	// Source: Pidgin
	gchar* enteredstring;
	gchar* tmp;
	gchar* text;
	gchar* normalized;
	gboolean result;
	size_t i;
	size_t len;
	PangoLogAttr* log_attrs;
	gchar* word;

	gtk_tree_model_get(model, iter, DOCUMENT_LINKS_COLUMN_NAME, &text, -1);
	if (text == NULL)
		return TRUE;

	tmp = g_utf8_normalize(key, -1, G_NORMALIZE_DEFAULT);
	enteredstring = g_utf8_casefold(tmp, -1);
	g_free(tmp);

	tmp = g_utf8_normalize(text, -1, G_NORMALIZE_DEFAULT);
	normalized = g_utf8_casefold(tmp, -1);
	g_free(tmp);

	if (g_str_has_prefix(normalized, enteredstring))
	{
		g_free(enteredstring);
		g_free(normalized);
		return FALSE;
	}

	/* Use Pango to separate by words. */
	len = g_utf8_strlen(normalized, -1);
	log_attrs = g_new(PangoLogAttr, len + 1);

	pango_get_log_attrs(normalized, strlen(normalized), -1, NULL, log_attrs,
	                    len + 1);

	word = normalized;
	result = TRUE;
	for (i = 0; i < (len - 1); i++)
	{
		if (log_attrs[i].is_word_start && g_str_has_prefix(word, enteredstring))
		{
			result = FALSE;
			break;
		}
		word = g_utf8_next_char(word);
	}
	g_free(log_attrs);

	g_free(enteredstring);
	g_free(normalized);

	return result;
}
示例#5
0
gboolean plugin_init(GKeyFile *config)
{
	GSList *list;
	GDir *dir;
	const gchar *file;
	gchar **disabled;
	unsigned int i;

	/* Make a call to BtIO API so its symbols got resolved before the
	 * plugins are loaded. */
	bt_io_error_quark();

	if (config)
		disabled = g_key_file_get_string_list(config, "General",
							"DisablePlugins",
							NULL, NULL);
	else
		disabled = NULL;

	DBG("Loading builtin plugins");

	for (i = 0; __bluetooth_builtin[i]; i++) {
		if (is_disabled(__bluetooth_builtin[i]->name, disabled))
			continue;

		add_plugin(NULL,  __bluetooth_builtin[i]);
	}

	if (strlen(PLUGINDIR) == 0) {
		g_strfreev(disabled);
		goto start;
	}

	DBG("Loading plugins %s", PLUGINDIR);

	dir = g_dir_open(PLUGINDIR, 0, NULL);
	if (!dir) {
		g_strfreev(disabled);
		goto start;
	}

	while ((file = g_dir_read_name(dir)) != NULL) {
		struct bluetooth_plugin_desc *desc;
		void *handle;
		gchar *filename;

		if (g_str_has_prefix(file, "lib") == TRUE ||
				g_str_has_suffix(file, ".so") == FALSE)
			continue;

		if (is_disabled(file, disabled))
			continue;

		filename = g_build_filename(PLUGINDIR, file, NULL);

		handle = dlopen(filename, RTLD_NOW);
		if (handle == NULL) {
			error("Can't load plugin %s: %s", filename,
								dlerror());
			g_free(filename);
			continue;
		}

		g_free(filename);

		desc = dlsym(handle, "bluetooth_plugin_desc");
		if (desc == NULL) {
			error("Can't load plugin description: %s", dlerror());
			dlclose(handle);
			continue;
		}

		if (add_plugin(handle, desc) == FALSE)
			dlclose(handle);
	}

	g_dir_close(dir);

	g_strfreev(disabled);

start:
	for (list = plugins; list; list = list->next) {
		struct bluetooth_plugin *plugin = list->data;

		if (plugin->desc->init() < 0) {
			error("Failed to init %s plugin", plugin->desc->name);
			continue;
		}

		plugin->active = TRUE;
	}

	return TRUE;
}
void
gs_screenshot_image_load_async (GsScreenshotImage *ssimg,
				GCancellable *cancellable)
{
	AsImage *im = NULL;
	const gchar *url;
	g_autofree gchar *basename = NULL;
	g_autofree gchar *cache_kind = NULL;
	g_autofree gchar *cachefn_thumb = NULL;
	g_autofree gchar *sizedir = NULL;
	g_autoptr(SoupURI) base_uri = NULL;

	g_return_if_fail (GS_IS_SCREENSHOT_IMAGE (ssimg));

	g_return_if_fail (AS_IS_SCREENSHOT (ssimg->screenshot));
	g_return_if_fail (ssimg->width != 0);
	g_return_if_fail (ssimg->height != 0);

	/* load an image according to the scale factor */
	ssimg->scale = (guint) gtk_widget_get_scale_factor (GTK_WIDGET (ssimg));
	im = as_screenshot_get_image (ssimg->screenshot,
				      ssimg->width * ssimg->scale,
				      ssimg->height * ssimg->scale);

	/* if we've failed to load a HiDPI image, fallback to LoDPI */
	if (im == NULL && ssimg->scale > 1) {
		ssimg->scale = 1;
		im = as_screenshot_get_image (ssimg->screenshot,
					      ssimg->width,
					      ssimg->height);
	}
	if (im == NULL) {
		/* TRANSLATORS: this is when we request a screenshot size that
		 * the generator did not create or the parser did not add */
		gs_screenshot_image_set_error (ssimg, _("Screenshot size not found"));
		return;
	}

	/* check if the URL points to a local file */
	url = as_image_get_url (im);
	if (g_str_has_prefix (url, "file://")) {
		g_free (ssimg->filename);
		ssimg->filename = g_strdup (url + 7);
		if (g_file_test (ssimg->filename, G_FILE_TEST_EXISTS)) {
			as_screenshot_show_image (ssimg);
			return;
		}
	}

	basename = gs_screenshot_get_cachefn_for_url (url);
	if (ssimg->width == G_MAXUINT || ssimg->height == G_MAXUINT) {
		sizedir = g_strdup ("unknown");
	} else {
		sizedir = g_strdup_printf ("%ux%u", ssimg->width * ssimg->scale, ssimg->height * ssimg->scale);
	}
	cache_kind = g_build_filename ("screenshots", sizedir, NULL);
	g_free (ssimg->filename);
	ssimg->filename = gs_utils_get_cache_filename (cache_kind,
						       basename,
						       GS_UTILS_CACHE_FLAG_NONE,
						       NULL);
	if (ssimg->filename == NULL) {
		/* TRANSLATORS: this is when we try create the cache directory
		 * but we were out of space or permission was denied */
		gs_screenshot_image_set_error (ssimg, _("Could not create cache"));
		return;
	}

	/* does local file already exist and has recently been downloaded */
	if (g_file_test (ssimg->filename, G_FILE_TEST_EXISTS)) {
		guint64 age_max;
		g_autoptr(GFile) file = NULL;

		/* show the image we have in cache while we're checking for the
		 * new screenshot (which probably won't have changed) */
		as_screenshot_show_image (ssimg);

		/* verify the cache age against the maximum allowed */
		age_max = g_settings_get_uint (ssimg->settings,
					       "screenshot-cache-age-maximum");
		file = g_file_new_for_path (ssimg->filename);
		/* image new enough, not re-requesting from server */
		if (age_max > 0 && gs_utils_get_file_age (file) < age_max)
			return;
	}

	/* if we're not showing a full-size image, we try loading a blurred
	 * smaller version of it straight away */
	if (!ssimg->showing_image &&
	    ssimg->width > AS_IMAGE_THUMBNAIL_WIDTH &&
	    ssimg->height > AS_IMAGE_THUMBNAIL_HEIGHT) {
		const gchar *url_thumb;
		g_autofree gchar *basename_thumb = NULL;
		g_autofree gchar *cache_kind_thumb = NULL;
		im = as_screenshot_get_image (ssimg->screenshot,
					      AS_IMAGE_THUMBNAIL_WIDTH * ssimg->scale,
					      AS_IMAGE_THUMBNAIL_HEIGHT * ssimg->scale);
		url_thumb = as_image_get_url (im);
		basename_thumb = gs_screenshot_get_cachefn_for_url (url_thumb);
		cache_kind_thumb = g_build_filename ("screenshots", "112x63", NULL);
		cachefn_thumb = gs_utils_get_cache_filename (cache_kind_thumb,
							     basename_thumb,
							     GS_UTILS_CACHE_FLAG_NONE,
							     NULL);
		if (cachefn_thumb == NULL)
			return;
		if (g_file_test (cachefn_thumb, G_FILE_TEST_EXISTS))
			gs_screenshot_image_show_blurred (ssimg, cachefn_thumb);
	}

	/* re-request the cache filename, which might be different as it needs
	 * to be writable this time */
	g_free (ssimg->filename);
	ssimg->filename = gs_utils_get_cache_filename (cache_kind,
						       basename,
						       GS_UTILS_CACHE_FLAG_WRITEABLE,
						       NULL);

	/* download file */
	g_debug ("downloading %s to %s", url, ssimg->filename);
	base_uri = soup_uri_new (url);
	if (base_uri == NULL || !SOUP_URI_VALID_FOR_HTTP (base_uri)) {
		/* TRANSLATORS: this is when we try to download a screenshot
		 * that was not a valid URL */
		gs_screenshot_image_set_error (ssimg, _("Screenshot not valid"));
		return;
	}

	/* cancel any previous messages */
	if (ssimg->message != NULL) {
		soup_session_cancel_message (ssimg->session,
		                             ssimg->message,
		                             SOUP_STATUS_CANCELLED);
		g_clear_object (&ssimg->message);
	}

	ssimg->message = soup_message_new_from_uri (SOUP_METHOD_GET, base_uri);
	if (ssimg->message == NULL) {
		/* TRANSLATORS: this is when networking is not available */
		gs_screenshot_image_set_error (ssimg, _("Screenshot not available"));
		return;
	}

	/* not all servers support If-Modified-Since, but worst case we just
	 * re-download the entire file again every 30 days */
	if (g_file_test (ssimg->filename, G_FILE_TEST_EXISTS)) {
		g_autoptr(GFile) file = g_file_new_for_path (ssimg->filename);
		gs_screenshot_soup_msg_set_modified_request (ssimg->message, file);
	}

	/* send async */
	soup_session_queue_message (ssimg->session,
				    g_object_ref (ssimg->message) /* transfer full */,
				    gs_screenshot_image_complete_cb,
				    g_object_ref (ssimg));
}
示例#7
0
static void
gb_vim_complete_edit_files (GtkSourceView *source_view,
                            const gchar   *command,
                            GPtrArray     *ar,
                            const gchar   *prefix)
{
  GbWorkbench *workbench;
  IdeContext *context;
  IdeVcs *vcs;
  GFile *workdir;
  g_autoptr(GFile) child = NULL;
  g_autoptr(GFile) parent = NULL;

  IDE_ENTRY;

  g_assert (command);
  g_assert (ar);
  g_assert (prefix);

  if (!(workbench = gb_widget_get_workbench (GTK_WIDGET (source_view))) ||
      !(context = gb_workbench_get_context (workbench)) ||
      !(vcs = ide_context_get_vcs (context)) ||
      !(workdir = ide_vcs_get_working_directory (vcs)))
    IDE_EXIT;

  child = g_file_get_child (workdir, prefix);

  if (g_file_query_exists (child, NULL))
    {
      if (g_file_query_file_type (child, 0, NULL) == G_FILE_TYPE_DIRECTORY)
        {
          g_autoptr(GFileEnumerator) fe = NULL;
          GFileInfo *descendent;

          if (!g_str_has_suffix (prefix, "/"))
            {
              g_ptr_array_add (ar, g_strdup_printf ("%s %s/", command, prefix));
              IDE_EXIT;
            }

          fe = g_file_enumerate_children (child,
                                          G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
                                          G_FILE_QUERY_INFO_NONE,
                                          NULL, NULL);

          if (fe == NULL)
            IDE_EXIT;

          while ((descendent = g_file_enumerator_next_file (fe, NULL, NULL)))
            {
              const gchar *name;

              name = g_file_info_get_display_name (descendent);
              g_ptr_array_add (ar, g_strdup_printf ("%s %s%s", command, prefix, name));
              g_object_unref (descendent);
            }

          IDE_EXIT;
        }
    }

  parent = g_file_get_parent (child);

  if (parent != NULL)
    {
      g_autoptr(GFileEnumerator) fe = NULL;
      g_autofree gchar *relpath = NULL;
      GFileInfo *descendent;
      const gchar *slash;

      relpath = g_file_get_relative_path (workdir, parent);

      if (relpath && g_str_has_prefix (relpath, "./"))
        {
          gchar *tmp = relpath;
          relpath = g_strdup (relpath + 2);
          g_free (tmp);
        }

#ifdef IDE_ENABLE_TRACE
      {
        g_autofree gchar *parent_path = g_file_get_path (parent);
        IDE_TRACE_MSG ("parent_path: %s", parent_path);
      }
#endif

      if ((slash = strrchr (prefix, G_DIR_SEPARATOR)))
        prefix = slash + 1;

      fe = g_file_enumerate_children (parent,
                                      G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
                                      G_FILE_QUERY_INFO_NONE,
                                      NULL, NULL);

      if (fe == NULL)
        IDE_EXIT;

      while ((descendent = g_file_enumerator_next_file (fe, NULL, NULL)))
        {
          const gchar *name;

          name = g_file_info_get_display_name (descendent);

          IDE_TRACE_MSG ("name=%s prefix=%s", name, prefix);

          if (name && g_str_has_prefix (name, prefix))
            {
              gchar *path;

              if (relpath)
                path = g_strdup_printf ("%s %s/%s", command, relpath, name);
              else
                path = g_strdup_printf ("%s %s", command, name);

              IDE_TRACE_MSG ("edit completion: %s", path);

              g_ptr_array_add (ar, path);
            }
          g_object_unref (descendent);
        }

      IDE_EXIT;
    }

  IDE_EXIT;
}
/* Common XML format for both Bijiben / Tomboy */
static void
processNode (BijiLazyDeserializer *self) 
{
  xmlTextReaderPtr r = self->priv->r;
  BijiNoteObj * n = self->priv->note;
  xmlChar   *name;
  GdkRGBA    color;
  gchar     *tag, *color_str;
  GString   *norm;

  name = xmlTextReaderName (r);

  if ( g_strcmp0((gchar*)name,"title") == 0 )
    biji_process_string (r, (BijiReaderFunc*) biji_note_obj_set_title, n);

  if ( g_strcmp0((gchar*)name,"text") == 0 )
  {
    if (self->priv->type == BIJIBEN_1)
    {
      process_bijiben_html_content (self, r);
    }

    else if (self->priv->type == TOMBOY_1 ||
             self->priv->type == TOMBOY_2 ||
             self->priv->type == TOMBOY_3 )
    {
      self->priv->content = (gchar*) xmlTextReaderReadInnerXml (r);
      process_tomboy_xml_content (self);
    }
  }

  if (g_strcmp0 ((gchar*) name, "last-change-date") == 0)
  {
    xmlChar *result = xmlTextReaderReadString (r);
    biji_note_obj_set_mtime (n, str_to_gint64 (result));
    free (result);
  }

  if (g_strcmp0 ((gchar*) name, "last-metadata-change-date") == 0)
  {
    xmlChar *result = xmlTextReaderReadString (r);
    biji_note_obj_set_last_metadata_change_date (n, str_to_gint64 (result));
    free (result);
  }

  if (g_strcmp0 ((gchar*) name, "create-date") == 0)
  {
    xmlChar *result = xmlTextReaderReadString (r);
    biji_note_obj_set_create_date (n, str_to_gint64 (result));
    free (result);
  }

  if (g_strcmp0 ((gchar*) name, "color") == 0 )  
  {
    color_str = (gchar*) xmlTextReaderReadString (r);

    if (gdk_rgba_parse (&color, color_str))
      biji_note_obj_set_rgba (n, &color);

    else
      g_warning ("color invalid:%s", color_str);

    free (color_str);
  }

  if ( g_strcmp0((gchar*)name,"tag") == 0 )  
  {
    tag = (gchar*) xmlTextReaderReadString(r);

    if (g_str_has_prefix (tag,"system:template"))
    {
      note_obj_set_is_template(n,TRUE);
    }

    else if (g_str_has_prefix (tag,"system:notebook:"))
    {
      norm = g_string_new (tag);
      g_string_erase (norm,0,16);
      biji_item_add_collection (BIJI_ITEM (n), NULL, norm->str);
      g_string_free (norm, TRUE);
    }

    free (tag);
  }

  xmlFree(name);
}
static gboolean
export_dir (int            source_parent_fd,
            const char    *source_name,
            const char    *source_relpath,
            int            destination_parent_fd,
            const char    *destination_name,
            const char    *required_prefix,
            GCancellable  *cancellable,
            GError       **error)
{
  int res;
  g_auto(GLnxDirFdIterator) source_iter = {0};
  glnx_fd_close int destination_dfd = -1;
  struct dirent *dent;

  if (!glnx_dirfd_iterator_init_at (source_parent_fd, source_name, FALSE, &source_iter, error))
    return FALSE;

  do
    res = mkdirat (destination_parent_fd, destination_name, 0755);
  while (G_UNLIKELY (res == -1 && errno == EINTR));
  if (res == -1)
    {
      if (errno != EEXIST)
        {
          glnx_set_error_from_errno (error);
          return FALSE;
        }
    }

  if (!gs_file_open_dir_fd_at (destination_parent_fd, destination_name,
                               &destination_dfd,
                               cancellable, error))
    return FALSE;

  while (TRUE)
    {
      struct stat stbuf;
      g_autofree char *source_printable = NULL;

      if (!glnx_dirfd_iterator_next_dent (&source_iter, &dent, cancellable, error))
        return FALSE;

      if (dent == NULL)
        break;

      if (fstatat (source_iter.fd, dent->d_name, &stbuf, AT_SYMLINK_NOFOLLOW) == -1)
        {
          if (errno == ENOENT)
            continue;
          else
            {
              glnx_set_error_from_errno (error);
              return FALSE;
            }
        }

      /* Don't export any hidden files or backups */
      if (g_str_has_prefix (dent->d_name, ".") ||
          g_str_has_suffix (dent->d_name, "~"))
        continue;

      if (S_ISDIR (stbuf.st_mode))
        {
          g_autofree gchar *child_relpath = g_build_filename(source_relpath, dent->d_name, NULL);

          if (!export_dir (source_iter.fd, dent->d_name, child_relpath, destination_dfd, dent->d_name,
                           required_prefix, cancellable, error))
            return FALSE;
        }
      else if (S_ISREG (stbuf.st_mode))
        {
          source_printable = g_build_filename (source_relpath, dent->d_name, NULL);


          if (!xdg_app_has_name_prefix (dent->d_name, required_prefix))
            {
              g_print ("Not exporting %s, wrong prefix\n", source_printable);
              continue;
            }

          g_print ("Exporting %s\n", source_printable);

          if (!glnx_file_copy_at (source_iter.fd, dent->d_name, &stbuf,
                                  destination_dfd, dent->d_name,
                                  GLNX_FILE_COPY_NOXATTRS,
                                  cancellable,
                                  error))
            return FALSE;
        }
      else
        {
          source_printable = g_build_filename (source_relpath, dent->d_name, NULL);
          g_print ("Not exporting non-regular file %s\n", source_printable);
        }
    }

  /* Try to remove the directory, as we don't want to export empty directories.
   * However, don't fail if the unlink fails due to the directory not being empty */
  do
    res = unlinkat (destination_parent_fd, destination_name, AT_REMOVEDIR);
  while (G_UNLIKELY (res == -1 && errno == EINTR));
  if (res == -1)
    {
      if (errno != ENOTEMPTY)
        {
          glnx_set_error_from_errno (error);
          return FALSE;
        }
    }

  return TRUE;
}
示例#10
0
gboolean
mm_mbm_parse_cfun_test (const gchar *response,
                        guint32 *supported_mask,
                        GError **error)
{
    gchar **groups;
    guint32 mask = 0;

    g_assert (supported_mask);

    if (!response || !g_str_has_prefix (response, CFUN_TAG)) {
        g_set_error_literal (error, MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                             "Missing " CFUN_TAG " prefix");
        return FALSE;
    }

    /*
     * AT+CFUN=?
     * +CFUN: (0,1,4-6),(0,1)
     * OK
     */

    /* Strip tag from response */
    response = mm_strip_tag (response, CFUN_TAG);

    /* Split response in (groups) */
    groups = mm_split_string_groups (response);

    /* First group is the one listing supported modes */
    if (groups && groups[0]) {
        gchar **supported_modes;

        supported_modes = g_strsplit_set (groups[0], ", ", -1);
        if (supported_modes) {
            guint i;

            for (i = 0; supported_modes[i]; i++) {
                gchar *separator;
                guint mode;

                if (!supported_modes[i][0])
                    continue;

                /* Check if this is a range that's being given to us */
                separator = strchr (supported_modes[i], '-');
                if (separator) {
                    gchar *first_str;
                    gchar *last_str;
                    guint first;
                    guint last;

                    *separator = '\0';
                    first_str = supported_modes[i];
                    last_str = separator + 1;

                    if (!mm_get_uint_from_str (first_str, &first))
                        g_warning ("Couldn't match range start: '%s'", first_str);
                    else if (!mm_get_uint_from_str (last_str, &last))
                        g_warning ("Couldn't match range stop: '%s'", last_str);
                    else if (first >= last)
                        g_warning ("Couldn't match range: wrong first '%s' and last '%s' items", first_str, last_str);
                    else {
                        for (mode = first; mode <= last; mode++)
                            add_supported_mode (&mask, mode);
                    }
                } else {
                    if (!mm_get_uint_from_str (supported_modes[i], &mode))
                        g_warning ("Couldn't match mode: '%s'", supported_modes[i]);
                    else
                        add_supported_mode (&mask, mode);
                }
            }

            g_strfreev (supported_modes);
        }
    }
    g_strfreev (groups);

    if (mask)
        *supported_mask = mask;
    return !!mask;
}
示例#11
0
gboolean
mm_mbm_parse_e2ipcfg_response (const gchar *response,
                               MMBearerIpConfig **out_ip4_config,
                               MMBearerIpConfig **out_ip6_config,
                               GError **error)
{
    MMBearerIpConfig **ip_config = NULL;
    gboolean got_address = FALSE, got_gw = FALSE, got_dns = FALSE;
    GRegex *r;
    GMatchInfo *match_info = NULL;
    GError *match_error = NULL;
    gchar *dns[3] = { 0 };
    guint dns_idx = 0;
    int family = AF_INET;
    MMBearerIpMethod method = MM_BEARER_IP_METHOD_STATIC;

    g_return_val_if_fail (out_ip4_config, FALSE);
    g_return_val_if_fail (out_ip6_config, FALSE);

    if (!response || !g_str_has_prefix (response, E2IPCFG_TAG)) {
        g_set_error (error, MM_CORE_ERROR, MM_CORE_ERROR_FAILED, "Missing " E2IPCFG_TAG " prefix");
        return FALSE;
    }

    response = mm_strip_tag (response, "*E2IPCFG: ");

    if (strchr (response, ':')) {
        family = AF_INET6;
        ip_config = out_ip6_config;
        method = MM_BEARER_IP_METHOD_DHCP;
    } else if (strchr (response, '.')) {
        family = AF_INET;
        ip_config = out_ip4_config;
        method = MM_BEARER_IP_METHOD_STATIC;
    } else {
        g_set_error (error, MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                     "Failed to detect " E2IPCFG_TAG " address family");
        return FALSE;
    }

    /* *E2IPCFG: (1,<IP>)(2,<gateway>)(3,<DNS>)(3,<DNS>)
     *
     * *E2IPCFG: (1,"46.157.32.246")(2,"46.157.32.243")(3,"193.213.112.4")(3,"130.67.15.198")
     * *E2IPCFG: (1,"fe80:0000:0000:0000:0000:0000:e537:1801")(3,"2001:4600:0004:0fff:0000:0000:0000:0054")(3,"2001:4600:0004:1fff:0000:0000:0000:0054")
     * *E2IPCFG: (1,"fe80:0000:0000:0000:0000:0027:b7fe:9401")(3,"fd00:976a:0000:0000:0000:0000:0000:0009")
     */
    r = g_regex_new ("\\((\\d),\"([0-9a-fA-F.:]+)\"\\)", 0, 0, NULL);
    g_assert (r != NULL);

    if (!g_regex_match_full (r, response, -1, 0, 0, &match_info, &match_error)) {
        if (match_error) {
            g_propagate_error (error, match_error);
            g_prefix_error (error, "Could not parse " E2IPCFG_TAG " results: ");
        } else {
            g_set_error_literal (error,
                                 MM_CORE_ERROR,
                                 MM_CORE_ERROR_FAILED,
                                 "Couldn't match " E2IPCFG_TAG " reply");
        }
        goto done;
    }

    *ip_config = mm_bearer_ip_config_new ();
    mm_bearer_ip_config_set_method (*ip_config, method);
    while (g_match_info_matches (match_info)) {
        char *id = g_match_info_fetch (match_info, 1);
        char *str = g_match_info_fetch (match_info, 2);

        switch (atoi (id)) {
        case 1:
            if (validate_address (family, str)) {
                mm_bearer_ip_config_set_address (*ip_config, str);
                mm_bearer_ip_config_set_prefix (*ip_config, (family == AF_INET6) ? 64 : 28);
                got_address = TRUE;
            }
            break;
        case 2:
            if ((family == AF_INET) && validate_address (family, str)) {
                mm_bearer_ip_config_set_gateway (*ip_config, str);
                got_gw = TRUE;
            }
            break;
        case 3:
            if (validate_address (family, str)) {
                dns[dns_idx++] = g_strdup (str);
                got_dns = TRUE;
            }
            break;
        default:
            break;
        }
        g_free (id);
        g_free (str);
        g_match_info_next (match_info, NULL);
    }

    if (got_dns) {
        mm_bearer_ip_config_set_dns (*ip_config, (const gchar **) dns);
        g_free (dns[0]);
        g_free (dns[1]);
    }

    if (!got_address || (family == AF_INET && !got_gw)) {
        g_object_unref (*ip_config);
        *ip_config = NULL;
        g_set_error_literal (error, MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                             "Got incomplete IP configuration from " E2IPCFG_TAG);
    }

done:
    if (match_info)
        g_match_info_free (match_info);
    g_regex_unref (r);
    return !!*ip_config;
}
示例#12
0
/**
 * gst_rtsp_sdp_from_media:
 * @sdp: a #GstSDPMessage
 * @info: info
 * @media: a #GstRTSPMedia
 *
 * Add @media specific info to @sdp. @info is used to configure the connection
 * information in the SDP.
 *
 * Returns: TRUE on success.
 */
gboolean
gst_rtsp_sdp_from_media (GstSDPMessage * sdp, GstSDPInfo * info,
    GstRTSPMedia * media)
{
  guint i, n_streams;
  gchar *rangestr;

  n_streams = gst_rtsp_media_n_streams (media);

  rangestr = gst_rtsp_media_get_range_string (media, FALSE, GST_RTSP_RANGE_NPT);
  if (rangestr == NULL)
    goto not_prepared;

  gst_sdp_message_add_attribute (sdp, "range", rangestr);
  g_free (rangestr);

  for (i = 0; i < n_streams; i++) {
    GstRTSPStream *stream;
    GstSDPMedia *smedia;
    GstStructure *s;
    const gchar *caps_str, *caps_enc, *caps_params;
    gchar *tmp;
    gint caps_pt, caps_rate;
    guint n_fields, j;
    gboolean first;
    GString *fmtp;
    GstCaps *caps;

    stream = gst_rtsp_media_get_stream (media, i);
    caps = gst_rtsp_stream_get_caps (stream);

    if (caps == NULL) {
      g_warning ("ignoring stream %d without media type", i);
      continue;
    }

    s = gst_caps_get_structure (caps, 0);
    if (s == NULL) {
      gst_caps_unref (caps);
      g_warning ("ignoring stream %d without media type", i);
      continue;
    }

    gst_sdp_media_new (&smedia);

    /* get media type and payload for the m= line */
    caps_str = gst_structure_get_string (s, "media");
    gst_sdp_media_set_media (smedia, caps_str);

    gst_structure_get_int (s, "payload", &caps_pt);
    tmp = g_strdup_printf ("%d", caps_pt);
    gst_sdp_media_add_format (smedia, tmp);
    g_free (tmp);

    gst_sdp_media_set_port_info (smedia, 0, 1);
    gst_sdp_media_set_proto (smedia, "RTP/AVP");

    /* for the c= line */
    if (info->is_ipv6) {
      gst_sdp_media_add_connection (smedia, "IN", "IP6", "::", 16, 0);
    } else {
      gst_sdp_media_add_connection (smedia, "IN", "IP4", "0.0.0.0", 16, 0);
    }

    /* get clock-rate, media type and params for the rtpmap attribute */
    gst_structure_get_int (s, "clock-rate", &caps_rate);
    caps_enc = gst_structure_get_string (s, "encoding-name");
    caps_params = gst_structure_get_string (s, "encoding-params");

    if (caps_enc) {
      if (caps_params)
        tmp = g_strdup_printf ("%d %s/%d/%s", caps_pt, caps_enc, caps_rate,
            caps_params);
      else
        tmp = g_strdup_printf ("%d %s/%d", caps_pt, caps_enc, caps_rate);

      gst_sdp_media_add_attribute (smedia, "rtpmap", tmp);
      g_free (tmp);
    }

    /* the config uri */
    tmp = gst_rtsp_stream_get_control (stream);
    gst_sdp_media_add_attribute (smedia, "control", tmp);
    g_free (tmp);

    /* collect all other properties and add them to fmtp or attributes */
    fmtp = g_string_new ("");
    g_string_append_printf (fmtp, "%d ", caps_pt);
    first = TRUE;
    n_fields = gst_structure_n_fields (s);
    for (j = 0; j < n_fields; j++) {
      const gchar *fname, *fval;

      fname = gst_structure_nth_field_name (s, j);

      /* filter out standard properties */
      if (!strcmp (fname, "media"))
        continue;
      if (!strcmp (fname, "payload"))
        continue;
      if (!strcmp (fname, "clock-rate"))
        continue;
      if (!strcmp (fname, "encoding-name"))
        continue;
      if (!strcmp (fname, "encoding-params"))
        continue;
      if (!strcmp (fname, "ssrc"))
        continue;
      if (!strcmp (fname, "clock-base"))
        continue;
      if (!strcmp (fname, "seqnum-base"))
        continue;

      if (g_str_has_prefix (fname, "a-")) {
        /* attribute */
        if ((fval = gst_structure_get_string (s, fname)))
          gst_sdp_media_add_attribute (smedia, fname + 2, fval);
        continue;
      }
      if (g_str_has_prefix (fname, "x-")) {
        /* attribute */
        if ((fval = gst_structure_get_string (s, fname)))
          gst_sdp_media_add_attribute (smedia, fname, fval);
        continue;
      }

      if ((fval = gst_structure_get_string (s, fname))) {
        g_string_append_printf (fmtp, "%s%s=%s", first ? "" : ";", fname, fval);
        first = FALSE;
      }
    }
    if (!first) {
      tmp = g_string_free (fmtp, FALSE);
      gst_sdp_media_add_attribute (smedia, "fmtp", tmp);
      g_free (tmp);
    } else {
      g_string_free (fmtp, TRUE);
    }

    update_sdp_from_tags (stream, smedia);

    gst_sdp_message_add_media (sdp, smedia);
    gst_sdp_media_free (smedia);
    gst_caps_unref (caps);
  }

  {
    GstNetTimeProvider *provider;

    if ((provider =
            gst_rtsp_media_get_time_provider (media, info->server_ip, 0))) {
      GstClock *clock;
      gchar *address, *str;
      gint port;

      g_object_get (provider, "clock", &clock, "address", &address, "port",
          &port, NULL);

      str = g_strdup_printf ("GstNetTimeProvider %s %s:%d %" G_GUINT64_FORMAT,
          g_type_name (G_TYPE_FROM_INSTANCE (clock)), address, port,
          gst_clock_get_time (clock));

      gst_sdp_message_add_attribute (sdp, "x-gst-clock", str);
      g_free (str);
      gst_object_unref (clock);
      g_free (address);
      gst_object_unref (provider);
    }
  }

  return TRUE;

  /* ERRORS */
not_prepared:
  {
    GST_ERROR ("media %p is not prepared", media);
    return FALSE;
  }
}
示例#13
0
void
mm_plugin_supports_port (MMPlugin *self,
                         MMDevice *device,
                         GUdevDevice *port,
                         GAsyncReadyCallback callback,
                         gpointer user_data)
{
    MMPortProbe *probe;
    GSimpleAsyncResult *async_result;
    PortProbeRunContext *ctx;
    gboolean need_vendor_probing;
    gboolean need_product_probing;
    MMPortProbeFlag probe_run_flags;
    gchar *probe_list_str;

    async_result = g_simple_async_result_new (G_OBJECT (self),
                                              callback,
                                              user_data,
                                              mm_plugin_supports_port);

    /* Apply filters before launching the probing */
    if (apply_pre_probing_filters (self,
                                   device,
                                   port,
                                   &need_vendor_probing,
                                   &need_product_probing)) {
        /* Filtered! */
        g_simple_async_result_set_op_res_gpointer (async_result,
                                                   GUINT_TO_POINTER (MM_PLUGIN_SUPPORTS_PORT_UNSUPPORTED),
                                                   NULL);
        g_simple_async_result_complete_in_idle (async_result);
        goto out;
    }

    /* Need to launch new probing */
    probe = MM_PORT_PROBE (mm_device_get_port_probe (device, port));
    if (!probe) {
        /* This may happen if the ports get removed from the device while
         * probing is ongoing */
        g_simple_async_result_set_error (async_result,
                                         MM_CORE_ERROR,
                                         MM_CORE_ERROR_FAILED,
                                         "(%s) Missing port probe for port (%s/%s)",
                                         self->priv->name,
                                         g_udev_device_get_subsystem (port),
                                         g_udev_device_get_name (port));
        g_simple_async_result_complete_in_idle (async_result);
        goto out;
    }

    /* Before launching any probing, check if the port is a net device. */
    if (g_str_equal (g_udev_device_get_subsystem (port), "net")) {
        mm_dbg ("(%s) [%s] probing deferred until result suggested",
                self->priv->name,
                g_udev_device_get_name (port));
        g_simple_async_result_set_op_res_gpointer (
            async_result,
            GUINT_TO_POINTER (MM_PLUGIN_SUPPORTS_PORT_DEFER_UNTIL_SUGGESTED),
            NULL);
        g_simple_async_result_complete_in_idle (async_result);
        goto out;
    }

    /* Build flags depending on what probing needed */
    if (!g_str_has_prefix (g_udev_device_get_name (port), "cdc-wdm")) {
        /* Serial ports... */
        probe_run_flags = MM_PORT_PROBE_NONE;
        if (self->priv->at)
            probe_run_flags |= MM_PORT_PROBE_AT;
        else if (self->priv->single_at)
            probe_run_flags |= MM_PORT_PROBE_AT;
        if (need_vendor_probing)
            probe_run_flags |= (MM_PORT_PROBE_AT | MM_PORT_PROBE_AT_VENDOR);
        if (need_product_probing)
            probe_run_flags |= (MM_PORT_PROBE_AT | MM_PORT_PROBE_AT_PRODUCT);
        if (self->priv->qcdm)
            probe_run_flags |= MM_PORT_PROBE_QCDM;
        if (self->priv->icera_probe || self->priv->allowed_icera || self->priv->forbidden_icera)
            probe_run_flags |= (MM_PORT_PROBE_AT | MM_PORT_PROBE_AT_ICERA);
    } else {
        /* cdc-wdm ports... */
        probe_run_flags = MM_PORT_PROBE_QMI;
    }

    g_assert (probe_run_flags != MM_PORT_PROBE_NONE);

    /* If a modem is already available and the plugin says that only one AT port is
     * expected, check if we alredy got the single AT port. And if so, we know this
     * port being probed won't be AT. */
    if (self->priv->single_at &&
        mm_port_probe_list_has_at_port (mm_device_peek_port_probe_list (device)) &&
        !mm_port_probe_is_at (probe)) {
        mm_dbg ("(%s) [%s] not setting up AT probing tasks: "
                "modem already has the expected single AT port",
                self->priv->name,
                g_udev_device_get_name (port));

        /* Assuming it won't be an AT port. We still run the probe anyway, in
         * case we need to check for other port types (e.g. QCDM) */
        mm_port_probe_set_result_at (probe, FALSE);
    }

    /* Setup async call context */
    ctx = g_new (PortProbeRunContext, 1);
    ctx->self = g_object_ref (self);
    ctx->device = g_object_ref (device);
    ctx->result = g_object_ref (async_result);
    ctx->flags = probe_run_flags;

    /* Launch the probe */
    probe_list_str = mm_port_probe_flag_build_string_from_mask (ctx->flags);
    mm_dbg ("(%s) [%s] probe required: '%s'",
            self->priv->name,
            g_udev_device_get_name (port),
            probe_list_str);
    g_free (probe_list_str);

    mm_port_probe_run (probe,
                       ctx->flags,
                       self->priv->send_delay,
                       self->priv->remove_echo,
                       self->priv->custom_at_probe,
                       self->priv->custom_init,
                       (GAsyncReadyCallback)port_probe_run_ready,
                       ctx);

out:
    g_object_unref (async_result);
}
示例#14
0
static void
fr_command_7z_add (FrCommand  *command,
		   const char *from_file,
		   GList      *file_list,
		   const char *base_dir,
		   gboolean    update,
		   gboolean    follow_links)
{
	FrArchive *archive = FR_ARCHIVE (command);
	GList     *scan;

	fr_process_use_standard_locale (command->process, TRUE);
	fr_process_set_out_line_func (command->process,
				      process_line__add,
				      command);

	fr_command_7z_begin_command (command);

	if (update)
		fr_process_add_arg (command->process, "u");
	else
		fr_process_add_arg (command->process, "a");

	if (base_dir != NULL)
		fr_process_set_working_dir (command->process, base_dir);

	if (_g_mime_type_matches (archive->mime_type, "application/zip")
	    || _g_mime_type_matches (archive->mime_type, "application/x-cbz"))
	{
		fr_process_add_arg (command->process, "-tzip");
		fr_process_add_arg (command->process, "-mem=AES128");
	}

	fr_process_add_arg (command->process, "-bd");
	fr_process_add_arg (command->process, "-y");
	if (follow_links)
		fr_process_add_arg (command->process, "-l");
	add_password_arg (command, archive->password, FALSE);
	if ((archive->password != NULL)
	    && (*archive->password != 0)
	    && archive->encrypt_header
	    && fr_archive_is_capable_of (archive, FR_ARCHIVE_CAN_ENCRYPT_HEADER))
	{
		fr_process_add_arg (command->process, "-mhe=on");
	}

	/* fr_process_add_arg (command->process, "-ms=off"); FIXME: solid mode off? */

	switch (archive->compression) {
	case FR_COMPRESSION_VERY_FAST:
		fr_process_add_arg (command->process, "-mx=1");
		break;
	case FR_COMPRESSION_FAST:
		fr_process_add_arg (command->process, "-mx=5");
		break;
	case FR_COMPRESSION_NORMAL:
		fr_process_add_arg (command->process, "-mx=7");
		break;
	case FR_COMPRESSION_MAXIMUM:
		fr_process_add_arg (command->process, "-mx=9");
		if (! _g_mime_type_matches (archive->mime_type, "application/zip")
		    && ! _g_mime_type_matches (archive->mime_type, "application/x-cbz"))
		{
			fr_process_add_arg (command->process, "-m0=lzma2");;
		}
		break;
	}

	if (_g_mime_type_matches (archive->mime_type, "application/x-ms-dos-executable"))
		fr_process_add_arg (command->process, "-sfx");

	if (archive->volume_size > 0)
		fr_process_add_arg_printf (command->process, "-v%ub", archive->volume_size);

	if (from_file != NULL)
		fr_process_add_arg_concat (command->process, "-i@", from_file, NULL);

	if (from_file == NULL)
		for (scan = file_list; scan; scan = scan->next)
			/* Files prefixed with '@' need to be handled specially */
			if (g_str_has_prefix (scan->data, "@"))
				fr_process_add_arg_concat (command->process, "-i!", scan->data, NULL);

	fr_process_add_arg (command->process, "--");
	fr_process_add_arg (command->process, command->filename);

	if (from_file == NULL)
		for (scan = file_list; scan; scan = scan->next)
			/* Skip files prefixed with '@', already added */
			if (!g_str_has_prefix (scan->data, "@"))
				fr_process_add_arg (command->process, scan->data);

	fr_process_end_command (command->process);
}
示例#15
0
/*
 * @data: a m3u8 playlist text data, taking ownership
 */
static gboolean
gst_m3u8_update (GstM3U8 * self, gchar * data, gboolean * updated)
{
    gint val, duration;
    gchar *title, *end;
//  gboolean discontinuity;
    GstM3U8 *list;

    g_return_val_if_fail (self != NULL, FALSE);
    g_return_val_if_fail (data != NULL, FALSE);
    g_return_val_if_fail (updated != NULL, FALSE);

    *updated = TRUE;

    /* check if the data changed since last update */
    if (self->last_data && g_str_equal (self->last_data, data)) {
        GST_DEBUG ("Playlist is the same as previous one");
        *updated = FALSE;
        g_free (data);
        return TRUE;
    }

    if (!g_str_has_prefix (data, "#EXTM3U")) {
        GST_WARNING ("Data doesn't start with #EXTM3U");
        *updated = FALSE;
        g_free (data);
        return FALSE;
    }

    g_free (self->last_data);
    self->last_data = data;

    if (self->files) {
        g_list_foreach (self->files, (GFunc) gst_m3u8_media_file_free, NULL);
        g_list_free (self->files);
        self->files = NULL;
    }

    list = NULL;
    duration = -1;
    title = NULL;
    data += 7;
    while (TRUE) {
        end = g_utf8_strchr (data, -1, '\n');
        if (end)
            *end = '\0';

        if (data[0] != '#') {
            gchar *r;

            if (duration < 0 && list == NULL) {
                GST_LOG ("%s: got line without EXTINF or EXTSTREAMINF, dropping", data);
                goto next_line;
            }

            if (!gst_uri_is_valid (data)) {
                gchar *slash;
                if (!self->uri) {
                    GST_WARNING ("uri not set, can't build a valid uri");
                    goto next_line;
                }
                slash = g_utf8_strrchr (self->uri, -1, '/');
                if (!slash) {
                    GST_WARNING ("Can't build a valid uri");
                    goto next_line;
                }

                *slash = '\0';
                data = g_strdup_printf ("%s/%s", self->uri, data);
                *slash = '/';
            } else {
                data = g_strdup (data);
            }

            r = g_utf8_strchr (data, -1, '\r');
            if (r)
                *r = '\0';

            if (list != NULL) {
                if (g_list_find_custom (self->lists, data,
                                        (GCompareFunc) _m3u8_compare_uri)) {
                    GST_DEBUG ("Already have a list with this URI");
                    gst_m3u8_free (list);
                    g_free (data);
                } else {
                    gst_m3u8_set_uri (list, data);
                    self->lists = g_list_append (self->lists, list);
                }
                list = NULL;
            } else {
                GstM3U8MediaFile *file;
                file =
                    gst_m3u8_media_file_new (data, title, duration,
                                             self->mediasequence++);
                duration = -1;
                title = NULL;
                self->files = g_list_append (self->files, file);
            }

        } else if (g_str_has_prefix (data, "#EXT-X-ENDLIST")) {
            self->endlist = TRUE;
        } else if (g_str_has_prefix (data, "#EXT-X-VERSION:")) {
            if (int_from_string (data + 15, &data, &val))
                self->version = val;
        } else if (g_str_has_prefix (data, "#EXT-X-STREAM-INF:")) {
            gchar *v, *a;

            if (list != NULL) {
                GST_WARNING ("Found a list without a uri..., dropping");
                gst_m3u8_free (list);
            }

            list = gst_m3u8_new ();
            data = data + 18;
            while (data && parse_attributes (&data, &a, &v)) {
                if (g_str_equal (a, "BANDWIDTH")) {
                    if (!int_from_string (v, NULL, &list->bandwidth))
                        GST_WARNING ("Error while reading BANDWIDTH");
                } else if (g_str_equal (a, "PROGRAM-ID")) {
                    if (!int_from_string (v, NULL, &list->program_id))
                        GST_WARNING ("Error while reading PROGRAM-ID");
                } else if (g_str_equal (a, "CODECS")) {
                    g_free (list->codecs);
                    list->codecs = g_strdup (v);
                } else if (g_str_equal (a, "RESOLUTION")) {
                    if (!int_from_string (v, &v, &list->width))
                        GST_WARNING ("Error while reading RESOLUTION width");
                    if (!v || *v != '=') {
                        GST_WARNING ("Missing height");
                    } else {
                        v = g_utf8_next_char (v);
                        if (!int_from_string (v, NULL, &list->height))
                            GST_WARNING ("Error while reading RESOLUTION height");
                    }
                }
            }
        } else if (g_str_has_prefix (data, "#EXT-X-TARGETDURATION:")) {
            if (int_from_string (data + 22, &data, &val))
                self->targetduration = val;
        } else if (g_str_has_prefix (data, "#EXT-X-MEDIA-SEQUENCE:")) {
            if (int_from_string (data + 22, &data, &val))
                self->mediasequence = val;
        } else if (g_str_has_prefix (data, "#EXT-X-DISCONTINUITY")) {
            /* discontinuity = TRUE; */
        } else if (g_str_has_prefix (data, "#EXT-X-PROGRAM-DATE-TIME:")) {
            /* <YYYY-MM-DDThh:mm:ssZ> */
            GST_DEBUG ("FIXME parse date");
        } else if (g_str_has_prefix (data, "#EXT-X-ALLOW-CACHE:")) {
            g_free (self->allowcache);
            self->allowcache = g_strdup (data + 19);
        } else if (g_str_has_prefix (data, "#EXTINF:")) {
            if (!int_from_string (data + 8, &data, &val)) {
                GST_WARNING ("Can't read EXTINF duration");
                goto next_line;
            }
            duration = val;
            if (duration > self->targetduration)
                GST_WARNING ("EXTINF duration > TARGETDURATION");
            if (!data || *data != ',')
                goto next_line;
            data = g_utf8_next_char (data);
            if (data != end) {
                g_free (title);
                title = g_strdup (data);
            }
        } else {
            GST_LOG ("Ignored line: %s", data);
        }

next_line:
        if (!end)
            break;
        data = g_utf8_next_char (end);      /* skip \n */
    }

    /* redorder playlists by bitrate */
    if (self->lists) {
        gchar *top_variant_uri = NULL;

        if (!self->current_variant)
            top_variant_uri = GST_M3U8 (self->lists->data)->uri;
        else
            top_variant_uri = GST_M3U8 (self->current_variant->data)->uri;

        self->lists =
            g_list_sort (self->lists,
                         (GCompareFunc) gst_m3u8_compare_playlist_by_bitrate);

        self->current_variant = g_list_find_custom (self->lists, top_variant_uri,
                                (GCompareFunc) _m3u8_compare_uri);
    }

    return TRUE;
}
示例#16
0
gboolean
tinyurl_valid(char *url)
{
    return (g_str_has_prefix(url, "http://") ||
        g_str_has_prefix(url, "https://"));
}
示例#17
0
static void
set_metadata_from_media (MexContent          *content,
                         GrlMedia            *media,
                         MexContentMetadata   mex_key)
{
  gchar       *string;
  const gchar *cstring;
  GrlKeyID     grl_key = _get_grl_key_from_mex (mex_key);
  gint n;

  if (!grl_key)
    return;

  switch (G_PARAM_SPEC (grl_key)->value_type) {
  case G_TYPE_STRING:
    cstring = grl_data_get_string (GRL_DATA (media), grl_key);

    if (cstring)
      {
        if (mex_key == MEX_CONTENT_METADATA_TITLE)
          {
            gchar *showname = NULL, *title, *season_str;
            gint season, episode;
            gchar *replacement;
            const gchar *mimetype;

            mimetype = mex_content_get_metadata (content,
                                                 MEX_CONTENT_METADATA_MIMETYPE);

            if (!mimetype)
              mimetype = "";

            if (g_str_has_prefix (mimetype, "video/"))
              {
                mex_metadata_from_uri (cstring, &title, &showname, NULL,
                                       &season, &episode);
              }

            if (showname)
              {
                replacement = g_strdup_printf (_("Episode %d"), episode);
              }
            else
              {
                GRegex *regex;

                /* strip off any file extensions */
                regex = g_regex_new ("\\.....?$", 0, 0, NULL);
                replacement = g_regex_replace (regex, cstring, -1, 0, "", 0, NULL);

                g_regex_unref (regex);
              }

            if (!replacement)
              replacement = g_strdup (cstring);

            mex_content_set_metadata (content, mex_key, replacement);
            mex_content_set_metadata (content, MEX_CONTENT_METADATA_SERIES_NAME,
                                      showname);
            season_str = g_strdup_printf (_("Season %d"), season);
            mex_content_set_metadata (content, MEX_CONTENT_METADATA_SEASON,
                                      season_str);
            g_free (season_str);

            g_free (replacement);
          }
        else
          mex_content_set_metadata (content, mex_key, cstring);
      }
    break;

  case G_TYPE_INT:
    n = grl_data_get_int (GRL_DATA (media), grl_key);

    string = g_strdup_printf ("%i", n);
    mex_content_set_metadata (content, mex_key, string);
    g_free (string);
    break;

  case G_TYPE_FLOAT:
    string = g_strdup_printf ("%f", grl_data_get_float (GRL_DATA (media),
                                                        grl_key));
    mex_content_set_metadata (content, mex_key, string);
    g_free (string);
    break;
  }
}
示例#18
0
/*
 * _peas_plugin_info_new:
 * @filename: The filename where to read the plugin information.
 * @module_dir: The module directory.
 * @data_dir: The data directory.
 *
 * Creates a new #PeasPluginInfo from a file on the disk.
 *
 * Return value: a newly created #PeasPluginInfo.
 */
PeasPluginInfo *
_peas_plugin_info_new (const gchar *filename,
                       const gchar *module_dir,
                       const gchar *data_dir)
{
    PeasPluginInfo *info;
    GKeyFile *plugin_file = NULL;
    gchar *str;
    gchar **strv;
    gboolean b;
    GError *error = NULL;
    gchar **keys;
    gsize i;

    g_return_val_if_fail (filename != NULL, NULL);

    info = g_new0 (PeasPluginInfo, 1);
    info->refcount = 1;

    plugin_file = g_key_file_new ();
    if (!g_key_file_load_from_file (plugin_file, filename, G_KEY_FILE_NONE, NULL))
    {
        g_warning ("Bad plugin file: '%s'", filename);
        goto error;
    }

    /* Get module name */
    str = g_key_file_get_string (plugin_file, "Plugin", "Module", NULL);

    if ((str != NULL) && (*str != '\0'))
    {
        info->module_name = str;
    }
    else
    {
        g_warning ("Could not find 'Module' in '[Plugin]' section in '%s'", filename);
        goto error;
    }

    /* Get Name */
    str = g_key_file_get_locale_string (plugin_file, "Plugin",
                                        "Name", NULL, NULL);
    if (str)
        info->name = str;
    else
    {
        g_warning ("Could not find 'Name' in '[Plugin]' section in '%s'", filename);
        goto error;
    }

    /* Get the dependency list */
    info->dependencies = g_key_file_get_string_list (plugin_file,
                         "Plugin",
                         "Depends", NULL, NULL);
    if (info->dependencies == NULL)
        info->dependencies = g_new0 (gchar *, 1);

    /* Get the loader for this plugin */
    str = g_key_file_get_string (plugin_file, "Plugin", "Loader", NULL);

    if ((str != NULL) && (*str != '\0'))
    {
        info->loader = str;
    }
    else
    {
        /* default to the C loader */
        info->loader = g_strdup ("C");
    }

    /* Get Description */
    str = g_key_file_get_locale_string (plugin_file, "Plugin",
                                        "Description", NULL, NULL);
    if (str)
        info->desc = str;

    /* Get Icon */
    str = g_key_file_get_locale_string (plugin_file, "Plugin",
                                        "Icon", NULL, NULL);
    if (str)
        info->icon_name = str;

    /* Get Authors */
    info->authors = g_key_file_get_string_list (plugin_file, "Plugin",
                    "Authors", NULL, NULL);
    if (info->authors == NULL)
        info->authors = g_new0 (gchar *, 1);

    /* Get Copyright */
    strv = g_key_file_get_string_list (plugin_file, "Plugin",
                                       "Copyright", NULL, NULL);
    if (strv)
    {
        info->copyright = g_strjoinv ("\n", strv);

        g_strfreev (strv);
    }

    /* Get Website */
    str = g_key_file_get_string (plugin_file, "Plugin", "Website", NULL);
    if (str)
        info->website = str;

    /* Get Version */
    str = g_key_file_get_string (plugin_file, "Plugin", "Version", NULL);
    if (str)
        info->version = str;

    /* Get Help URI */
    str = g_key_file_get_string (plugin_file, "Plugin", OS_HELP_KEY, NULL);
    if (str)
        info->help_uri = str;
    else
    {
        str = g_key_file_get_string (plugin_file, "Plugin", "Help", NULL);
        if (str)
            info->help_uri = str;
    }

    /* Get Builtin */
    b = g_key_file_get_boolean (plugin_file, "Plugin", "Builtin", &error);
    if (error != NULL)
        g_clear_error (&error);
    else
        info->builtin = b;

    /* Get Hidden */
    b = g_key_file_get_boolean (plugin_file, "Plugin", "Hidden", &error);
    if (error != NULL)
        g_clear_error (&error);
    else
        info->hidden = b;

    keys = g_key_file_get_keys (plugin_file, "Plugin", NULL, NULL);

    for (i = 0; keys[i] != NULL; ++i)
    {
        if (!g_str_has_prefix (keys[i], "X-"))
            continue;

        if (info->external_data == NULL)
            info->external_data = g_hash_table_new_full (g_str_hash, g_str_equal,
                                  (GDestroyNotify) g_free,
                                  (GDestroyNotify) g_free);

        g_hash_table_insert (info->external_data,
                             g_strdup (keys[i] + 2),
                             g_key_file_get_string (plugin_file, "Plugin",
                                     keys[i], NULL));
    }

    g_strfreev (keys);

    g_key_file_free (plugin_file);

    info->module_dir = g_strdup (module_dir);
    info->data_dir = g_build_filename (data_dir, info->module_name, NULL);

    /* If we know nothing about the availability of the plugin,
       set it as available */
    info->available = TRUE;

    return info;

error:
    g_free (info->module_name);
    g_free (info->name);
    g_free (info);
    g_key_file_free (plugin_file);

    return NULL;
}
示例#19
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;
}
示例#20
0
static const gchar*
channel_title_to_units(const gchar *title)
{
    /* If the title becomes empty here will end up as Volts anyway which is
     * fine for DAC. */
    if (g_str_has_prefix(title, "DAC"))
        title += 3;

    if (g_str_has_prefix(title, "Height")
        || g_str_has_prefix(title, "ZSensor")
        || g_str_has_prefix(title, "Deflection")
        || g_str_has_prefix(title, "Amplitude"))
        return "m";
    if (g_str_has_prefix(title, "Phase"))
        return "deg";
    if (g_str_has_prefix(title, "Current"))
        return "A";
    if (g_str_has_prefix(title, "Frequency"))
        return "Hz";
    if (g_str_has_prefix(title, "Capacitance"))
        return "F";
    if (g_str_has_prefix(title, "Potential"))
        return "V";
    if (g_str_has_prefix(title, "Count")
        || g_str_has_prefix(title, "QFactor"))
        return "";
    /* Everything else is in Volts. */
    return "V";
}
示例#21
0
static gboolean
gb_vim_command_search (GtkSourceView  *source_view,
                       const gchar    *command,
                       const gchar    *options,
                       GError        **error)
{
  GtkTextBuffer *buffer;
  const gchar *search_begin = NULL;
  const gchar *search_end = NULL;
  const gchar *replace_begin = NULL;
  const gchar *replace_end = NULL;
  gchar *search_text = NULL;
  gchar *replace_text = NULL;
  gunichar separator;

  g_assert (g_str_has_prefix (command, "%s") || g_str_has_prefix (command, "s"));

  if (*command == '%')
    command++;
  command++;

  separator = g_utf8_get_char (command);
  if (!separator)
    goto invalid_request;

  search_begin = command = g_utf8_next_char (command);

  for (; *command; command = g_utf8_next_char (command))
    {
      if (*command == '\\')
        {
          command = g_utf8_next_char (command);
          if (!*command)
            goto invalid_request;
          continue;
        }

      if (g_utf8_get_char (command) == separator)
        {
          search_end = command;
          break;
        }
    }

  if (!search_end)
    goto invalid_request;

  replace_begin = command = g_utf8_next_char (command);

  for (; *command; command = g_utf8_next_char (command))
    {
      if (*command == '\\')
        {
          command = g_utf8_next_char (command);
          if (!*command)
            goto invalid_request;
          continue;
        }

      if (g_utf8_get_char (command) == separator)
        {
          replace_end = command;
          break;
        }
    }

  if (!replace_end)
    goto invalid_request;

  command = g_utf8_next_char (command);

  if (*command)
    {
      for (; *command; command++)
        {
          switch (*command)
            {
            case 'g':
              break;

            /* what other options are supported? */
            default:
              break;
            }
        }
    }

  search_text = g_strndup (search_begin, search_end - search_begin);
  replace_text = g_strndup (replace_begin, replace_end - replace_begin);

  buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (source_view));

  if (gtk_text_buffer_get_has_selection (buffer))
    {
      GtkTextIter begin;
      GtkTextIter end;

      gtk_text_buffer_get_selection_bounds (buffer, &begin, &end);
      gtk_text_iter_order (&begin, &end);
      gb_vim_do_search_and_replace (buffer, &begin, &end, search_text, replace_text, FALSE);
    }
  else
    gb_vim_do_search_and_replace (buffer, NULL, NULL, search_text, replace_text, TRUE);

  g_free (search_text);
  g_free (replace_text);

  return TRUE;

invalid_request:
  g_set_error (error,
               GB_VIM_ERROR,
               GB_VIM_ERROR_UNKNOWN_OPTION,
               _("Invalid search and replace request"));
  return FALSE;
}
示例#22
0
文件: asycii.c 项目: abraxa/libsigrok
/**
 * Parse unit and flags from text buffer, bytes 7-14.
 *
 * The unit and flags optionally follow the number value for the
 * measurement. Either can be present or absent. The scale factor
 * is always at index 7. The unit starts at index 8, and is of
 * variable length. Flags immediately follow the unit. The remainder
 * of the text buffer is SPACE padded, and terminated with CR.
 *
 * Notice the implementation detail of case @b sensitive comparison.
 * Since the measurement unit and flags are directly adjacent and are
 * not separated from each other, case insensitive comparison would
 * yield wrong results. It's essential that e.g. "Vac" gets split into
 * the "V" unit and the "ac" flag, not into "VA" and the unknown "c"
 * flag!
 *
 * Notice, too, that order of comparison matters in the absence of
 * separators or fixed positions and with ambiguous text (note that we do
 * partial comparison). It's essential to e.g. correctly tell "VA" from "V".
 *
 * @param[in]	buf The text buffer received from the DMM.
 * @param[out]	info Broken down measurement details.
 */
static void parse_flags(const char *buf, struct asycii_info *info)
{
	int i, cnt;
	char unit[8 + 1];
	const char *u;

	/* Bytes 0-6: Number value, see parse_value(). */

	/* Strip spaces from bytes 7-14. */
	cnt = 0;
	for (i = 7; i < 15; i++) {
		if (buf[i] != ' ')
			unit[cnt++] = buf[i];
	}
	unit[cnt] = '\0';
	u = &unit[0];
	sr_spew("%s(): unit/flag buffer [%s]", __func__, u);

	/* Scan for the scale factor. */
	sr_spew("%s(): scanning factor, buffer [%s]", __func__, u);
	if (*u == 'p') {
		u++;
		info->is_pico = TRUE;
	} else if (*u == 'n') {
		u++;
		info->is_nano = TRUE;
	} else if (*u == 'u') {
		u++;
		info->is_micro = TRUE;
	} else if (*u == 'm') {
		u++;
		info->is_milli = TRUE;
	} else if (*u == ' ') {
		u++;
	} else if (*u == 'k') {
		u++;
		info->is_kilo = TRUE;
	} else if (*u == 'M') {
		u++;
		info->is_mega = TRUE;
	} else {
		/* Absence of a scale modifier is perfectly fine. */
	}

	/* Scan for the measurement unit. */
	sr_spew("%s(): scanning unit, buffer [%s]", __func__, u);
	if (g_str_has_prefix(u, "A")) {
		u += strlen("A");
		info->is_ampere = TRUE;
	} else if (g_str_has_prefix(u, "VA")) {
		u += strlen("VA");
		info->is_volt_ampere = TRUE;
	} else if (g_str_has_prefix(u, "V")) {
		u += strlen("V");
		info->is_volt = TRUE;
	} else if (g_str_has_prefix(u, "ohm")) {
		u += strlen("ohm");
		info->is_resistance = TRUE;
		info->is_ohm = TRUE;
	} else if (g_str_has_prefix(u, "F")) {
		u += strlen("F");
		info->is_capacitance = TRUE;
		info->is_farad = TRUE;
	} else if (g_str_has_prefix(u, "dB")) {
		u += strlen("dB");
		info->is_gain = TRUE;
		info->is_decibel = TRUE;
	} else if (g_str_has_prefix(u, "Hz")) {
		u += strlen("Hz");
		info->is_frequency = TRUE;
		info->is_hertz = TRUE;
	} else if (g_str_has_prefix(u, "%")) {
		u += strlen("%");
		info->is_duty_cycle = TRUE;
		if (*u == '+') {
			u++;
			info->is_duty_pos = TRUE;
		} else if (*u == '-') {
			u++;
			info->is_duty_neg = TRUE;
		} else {
			info->is_invalid = TRUE;
		}
	} else if (g_str_has_prefix(u, "Cnt")) {
		u += strlen("Cnt");
		info->is_pulse_count = TRUE;
		info->is_unitless = TRUE;
		if (*u == '+') {
			u++;
			info->is_count_pos = TRUE;
		} else if (*u == '-') {
			u++;
			info->is_count_neg = TRUE;
		} else {
			info->is_invalid = TRUE;
		}
	} else if (g_str_has_prefix(u, "s")) {
		u += strlen("s");
		info->is_pulse_width = TRUE;
		info->is_seconds = TRUE;
		if (*u == '+') {
			u++;
			info->is_period_pos = TRUE;
		} else if (*u == '-') {
			u++;
			info->is_period_neg = TRUE;
		} else {
			info->is_invalid = TRUE;
		}
	} else {
		/* Not strictly illegal, but unknown/unsupported. */
		sr_spew("%s(): measurement: unsupported", __func__);
		info->is_invalid = TRUE;
	}

	/* Scan for additional flags. */
	sr_spew("%s(): scanning flags, buffer [%s]", __func__, u);
	if (g_str_has_prefix(u, "ac+dc")) {
		u += strlen("ac+dc");
		info->is_ac_and_dc = TRUE;
	} else if (g_str_has_prefix(u, "ac")) {
		u += strlen("ac");
		info->is_ac = TRUE;
	} else if (g_str_has_prefix(u, "dc")) {
		u += strlen("dc");
		info->is_dc = TRUE;
	} else if (g_str_has_prefix(u, "d")) {
		u += strlen("d");
		info->is_diode = TRUE;
	} else if (g_str_has_prefix(u, "Pk")) {
		u += strlen("Pk");
		if (*u == '+') {
			u++;
			info->is_peak_max = TRUE;
		} else if (*u == '-') {
			u++;
			info->is_peak_min = TRUE;
		} else {
			info->is_invalid = TRUE;
		}
	} else if (*u == '\0') {
		/* Absence of any flags is acceptable. */
	} else {
		/* Presence of unknown flags is not. */
		sr_dbg("%s(): flag: unknown", __func__);
		info->is_invalid = TRUE;
	}

	/* Was all of the received data consumed? */
	if (*u != '\0')
		info->is_invalid = TRUE;

	/*
	 * Note:
	 * - The protocol does not distinguish between "resistance"
	 *   and "continuity".
	 * - Relative measurement and hold cannot get recognized.
	 */
}
示例#23
0
void
mono_gc_base_init (void)
{
	MonoThreadInfoCallbacks cb;
	const char *env;

	if (gc_initialized)
		return;

	/*
	 * Handle the case when we are called from a thread different from the main thread,
	 * confusing libgc.
	 * FIXME: Move this to libgc where it belongs.
	 *
	 * we used to do this only when running on valgrind,
	 * but it happens also in other setups.
	 */
#if defined(HAVE_PTHREAD_GETATTR_NP) && defined(HAVE_PTHREAD_ATTR_GETSTACK) && !defined(__native_client__)
	{
		size_t size;
		void *sstart;
		pthread_attr_t attr;
		pthread_getattr_np (pthread_self (), &attr);
		pthread_attr_getstack (&attr, &sstart, &size);
		pthread_attr_destroy (&attr); 
		/*g_print ("stackbottom pth is: %p\n", (char*)sstart + size);*/
#ifdef __ia64__
		/*
		 * The calculation above doesn't seem to work on ia64, also we need to set
		 * GC_register_stackbottom as well, but don't know how.
		 */
#else
		/* apparently with some linuxthreads implementations sstart can be NULL,
		 * fallback to the more imprecise method (bug# 78096).
		 */
		if (sstart) {
			GC_stackbottom = (char*)sstart + size;
		} else {
			int dummy;
			gsize stack_bottom = (gsize)&dummy;
			stack_bottom += 4095;
			stack_bottom &= ~4095;
			GC_stackbottom = (char*)stack_bottom;
		}
#endif
	}
#elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
		GC_stackbottom = (char*)pthread_get_stackaddr_np (pthread_self ());
#elif defined(__OpenBSD__)
#  include <pthread_np.h>
	{
		stack_t ss;
		int rslt;

		rslt = pthread_stackseg_np(pthread_self(), &ss);
		g_assert (rslt == 0);

		GC_stackbottom = (char*)ss.ss_sp;
	}
#elif defined(__native_client__)
	/* Do nothing, GC_stackbottom is set correctly in libgc */
#else
	{
		int dummy;
		gsize stack_bottom = (gsize)&dummy;
		stack_bottom += 4095;
		stack_bottom &= ~4095;
		/*g_print ("stackbottom is: %p\n", (char*)stack_bottom);*/
		GC_stackbottom = (char*)stack_bottom;
	}
#endif

#if !defined(PLATFORM_ANDROID)
	/* If GC_no_dls is set to true, GC_find_limit is not called. This causes a seg fault on Android. */
	GC_no_dls = TRUE;
#endif
	GC_init ();
	GC_oom_fn = mono_gc_out_of_memory;
	GC_set_warn_proc (mono_gc_warning);
	GC_finalize_on_demand = 1;
	GC_finalizer_notifier = mono_gc_finalize_notify;

#ifdef HAVE_GC_GCJ_MALLOC
	GC_init_gcj_malloc (5, NULL);
#endif

#ifdef HAVE_GC_ALLOW_REGISTER_THREADS
	GC_allow_register_threads();
#endif

	if ((env = g_getenv ("MONO_GC_PARAMS"))) {
		char **ptr, **opts = g_strsplit (env, ",", -1);
		for (ptr = opts; *ptr; ++ptr) {
			char *opt = *ptr;
			if (g_str_has_prefix (opt, "max-heap-size=")) {
				glong max_heap;

				opt = strchr (opt, '=') + 1;
				if (*opt && mono_gc_parse_environment_string_extract_number (opt, &max_heap)) {
					if (max_heap < MIN_BOEHM_MAX_HEAP_SIZE) {
						fprintf (stderr, "max-heap-size must be at least %dMb.\n", MIN_BOEHM_MAX_HEAP_SIZE_IN_MB);
						exit (1);
					}
					GC_set_max_heap_size (max_heap);
				} else {
					fprintf (stderr, "max-heap-size must be an integer.\n");
					exit (1);
				}
				continue;
			} else {
				/* Could be a parameter for sgen */
				/*
				fprintf (stderr, "MONO_GC_PARAMS must be a comma-delimited list of one or more of the following:\n");
				fprintf (stderr, "  max-heap-size=N (where N is an integer, possibly with a k, m or a g suffix)\n");
				exit (1);
				*/
			}
		}
		g_strfreev (opts);
	}

	memset (&cb, 0, sizeof (cb));
	cb.thread_register = boehm_thread_register;
	cb.mono_method_is_critical = (gpointer)mono_runtime_is_critical_method;
#ifndef HOST_WIN32
	cb.mono_gc_pthread_create = (gpointer)mono_gc_pthread_create;
#endif
	
	mono_threads_init (&cb, sizeof (MonoThreadInfo));

	mono_gc_enable_events ();
	gc_initialized = TRUE;
}
示例#24
0
/*!
  \brief load_table() physically handles loading the table datafrom disk, 
  populating and array and sotring a pointer to that array in the lookuptables
  hashtable referenced by the table_name passed
  \param table_name is the key to lookuptables hashtable
  \param filename is the filename to load table data from
  \returns TRUE on success, FALSE on failure
  */
G_MODULE_EXPORT gboolean load_table(gchar *table_name, gchar *filename)
{
	GIOStatus status;
	GIOChannel *iochannel;
	gboolean done = FALSE;
	GHashTable *lookuptables = NULL;
	gchar * str = NULL;
	gchar * tmp = NULL;
	gchar * end = NULL;
	GString *a_line; 
	LookupTable *lookuptable = NULL;
	gint tmparray[2048]; /* bad idea being static!!*/
	gchar ** vector = NULL;
	gint i = 0;

	iochannel = g_io_channel_new_file(filename,"r", NULL);
	status = g_io_channel_seek_position(iochannel,0,G_SEEK_SET,NULL);
	if (status != G_IO_STATUS_NORMAL)
	{
		MTXDBG(CRITICAL,_("Error seeking to beginning of the file\n"));
	}
	while (!done)	
	{
		a_line = g_string_new("\0");
		status = g_io_channel_read_line_string(iochannel, a_line, NULL, NULL);
		if (status == G_IO_STATUS_EOF)
			done = TRUE;
		else
		{
			/*	str = g_strchug(g_strdup(a_line->str));*/
			str = g_strchug(a_line->str);
			if (g_str_has_prefix(str,"DB"))
			{
				str+=2; /* move 2 places in	*/
				end = g_strrstr(str,"T");
				tmp = g_strndup(str,end-str);
				tmparray[i]=atoi(tmp);
				g_free(tmp);
				i++;
			}
		}
		g_string_free(a_line,TRUE);
	}
	g_io_channel_shutdown(iochannel,TRUE,NULL);
	g_io_channel_unref(iochannel);

	vector = g_strsplit(filename,PSEP,-1);
	lookuptable = g_new0(LookupTable, 1);
	lookuptable->array = (gint *)g_memdup(&tmparray,i*sizeof(gint));
	lookuptable->filename = g_strdup(vector[g_strv_length(vector)-1]);
	g_strfreev(vector);
	lookuptables = (GHashTable *)DATA_GET(global_data,"lookuptables");
	if (!lookuptables)
	{
		lookuptables = g_hash_table_new_full(g_str_hash,g_str_equal,g_free,dealloc_lookuptable);
		DATA_SET_FULL(global_data,"lookuptables",lookuptables,g_hash_table_destroy);
	}
	g_hash_table_replace((GHashTable *)DATA_GET(global_data,"lookuptables"),g_strdup(table_name),lookuptable);
	/*g_hash_table_foreach(DATA_GET(global_data,"lookuptables"),dump_lookuptables,NULL);*/

	return TRUE;
}
示例#25
0
static gboolean
panel_layout_maybe_append_object_instance_config (GKeyFile    *keyfile,
                                                  const char  *group,
                                                  const char  *key,
                                                  const char  *path_prefix,
                                                  const char  *unique_id,
                                                  gboolean     dry_run,
                                                  gboolean    *key_handled,
                                                  GError     **error)
{
        char       *value_str;
        const char *keyname;
        GVariant   *variant;

        *key_handled = FALSE;

        if (!g_str_has_prefix(key, PANEL_LAYOUT_INSTANCE_CONFIG_SUBPATH))
                return TRUE;

        *key_handled = TRUE;

        value_str = g_key_file_get_string (
                                keyfile,
                                group, key,
                                error);
        if (!value_str)
                return FALSE;

        variant = g_variant_parse (NULL, value_str,
                                   NULL, NULL, error);

        if (!variant) {
                g_free (value_str);
                return FALSE;
        }

        keyname = key + strlen (PANEL_LAYOUT_INSTANCE_CONFIG_SUBPATH);

        if (dry_run) {
                /* the key can actually be in a subdirectory
                 * like instance-config/foo/key, so we split
                 * the tokens to validate all of them */
                char **tokens;
                char **token;

                tokens = g_strsplit (keyname, "/", -1);

                for (token = tokens; *token; token++) {
                        if (!panel_gsettings_is_valid_keyname (*token,
                                                               error)) {
                                g_strfreev (tokens);
                                g_variant_unref (variant);
                                g_free (value_str);
                                return FALSE;
                        }
                }

                g_strfreev (tokens);
        } else {
                char *key;

                key = g_strdup_printf ("%s%s/%s%s",
                                       path_prefix, unique_id,
                                       PANEL_LAYOUT_OBJECT_CONFIG_SUFFIX,
                                       keyname);
                panel_dconf_write_sync (key, variant, NULL);
                g_free (key);
        }

        g_variant_unref (variant);
        g_free (value_str);

        return TRUE;
}
示例#26
0
static void
subprocess_wait_cb (GObject      *object,
                    GAsyncResult *res,
                    gpointer      user_data)
{
  GSubprocess *subprocess = (GSubprocess *)object;
  g_autofree gchar *input_prefix = NULL;
  g_autoptr(IdeDiagnostics) local_diags = NULL;
  g_autoptr(GTask) task = user_data;
  g_autoptr(GPtrArray) array = NULL;
  g_autoptr(GDataInputStream) stderr_data_input = NULL;
  GInputStream *stderr_input = NULL;
  g_autoptr(IdeGettextDiagnostics) diags = NULL;
  TranslationUnit *unit;
  GError *error = NULL;

  g_assert (G_IS_SUBPROCESS (subprocess));
  g_assert (G_IS_TASK (task));

  unit = g_task_get_task_data (task);

  g_assert (unit != NULL);

  if (!g_subprocess_wait_finish (subprocess, res, &error))
    {
      g_task_return_error (task, error);
      return;
    }

  array = g_ptr_array_new_with_free_func ((GDestroyNotify)ide_diagnostic_unref);
  if (g_subprocess_get_exit_status (subprocess) == 0)
    goto out;

  stderr_input = g_subprocess_get_stderr_pipe (subprocess);
  stderr_data_input = g_data_input_stream_new (stderr_input);
  input_prefix = g_strdup_printf ("%s:", ide_unsaved_file_get_temp_path (unit->unsaved_file));

  for (;;)
    {
      g_autofree gchar *line = NULL;
      gsize length;

      line = g_data_input_stream_read_line (stderr_data_input,
                                            &length,
                                            g_task_get_cancellable (task),
                                            &error);
      if (line == NULL)
        break;

      if (g_str_has_prefix (line, input_prefix))
        {
          gchar *p = line + strlen (input_prefix);

          if (g_ascii_isdigit (*p))
            {
              gulong line_number = strtoul (p, &p, 10);
              IdeSourceLocation *loc;
              IdeDiagnostic *diag;

              loc = ide_source_location_new (unit->file,
                                             line_number - 1,
                                             0,
                                             0);
              diag = ide_diagnostic_new (IDE_DIAGNOSTIC_WARNING,
                                         g_strstrip (p + 1),
                                         loc);
              g_ptr_array_add (array, diag);
            }
        }
    }

 out:
  local_diags = ide_diagnostics_new (g_steal_pointer (&array));
  diags = g_object_new (IDE_TYPE_GETTEXT_DIAGNOSTICS,
                        "diagnostics", local_diags,
                        "sequence", ide_unsaved_file_get_sequence (unit->unsaved_file),
                        NULL);
  g_task_return_pointer (task, g_steal_pointer (&diags), g_object_unref);
}
示例#27
0
static gboolean
RpcInSend(RpcChannel *chan,
          char const *data,
          size_t dataLen,
          char **result,
          size_t *resultLen)
{
   gboolean ret = FALSE;
   const char *reply;
   size_t replyLen;
   BackdoorChannel *bdoor = chan->_private;

   g_static_mutex_lock(&bdoor->outLock);
   if (!bdoor->outStarted) {
      goto exit;
   }

   ret = RpcOut_send(bdoor->out, data, dataLen, &reply, &replyLen);

   /*
    * This is a hack to try to work around bug 393650 without having to revert
    * to the old behavior of opening and closing an RpcOut channel for every
    * outgoing message. The issue here is that it's possible for the code to
    * try to write to the channel when a "reset" has just happened. In these
    * cases, the current RpcOut channel is not valid anymore, and we'll get an
    * error. The RpcOut lib doesn't really reply with a useful error, but it
    * does have consistent error messages starting with "RpcOut:".
    *
    * So, if the error is one of those messages, restart the RpcOut channel and
    * try to send the message again. If this second attempt fails, then give up.
    *
    * This is not 100% break-proof: a reset can still occur after we open the
    * new channel and before we try to re-send the message. But that's a race
    * that we can't easily fix, and exists even in code that just uses the
    * RpcOut_SendOne() API. Also, if some host handler returns an error that
    * starts with "RpcOut:", it will trigger this; but I don't think we have
    * any such handlers.
    */
   if (!ret && reply != NULL && replyLen > sizeof "RpcOut: " &&
       g_str_has_prefix(reply, "RpcOut: ")) {
      g_debug("RpcOut failure, restarting channel.\n");
      RpcOut_stop(bdoor->out);
      if (RpcOut_start(bdoor->out)) {
         ret = RpcOut_send(bdoor->out, data, dataLen, &reply, &replyLen);
      } else {
         g_warning("Couldn't restart RpcOut channel; bad things may happen "
                   "until the RPC channel is reset.\n");
         bdoor->outStarted = FALSE;
      }
   }

   /*
    * A lot of this logic is just replicated from rpcout.c:RpcOut_SendOneRaw().
    * Look there for comments about a few details.
    */
   if (result != NULL) {
      if (reply != NULL) {
         *result = Util_SafeMalloc(replyLen + 1);
         memcpy(*result, reply, replyLen);
         (*result)[replyLen] = '\0';
      } else {
         *result = NULL;
      }
   }

   if (resultLen != NULL) {
      *resultLen = replyLen;
   }

exit:
   g_static_mutex_unlock(&bdoor->outLock);
   return ret;
}
示例#28
0
/*------------------------- read command line options ------------------------*/
void
readOpts(int argc,char *argv[], struct GLOBAL *global)
{
	gchar *device=NULL;
	gchar *format=NULL;
	gchar *size = NULL;
	gchar *image = NULL;
	gchar *video=NULL;
	gchar *profile=NULL;
	gchar *separateur=NULL;
	gboolean help = FALSE;
	gboolean help_gtk = FALSE;
	gboolean help_all = FALSE;
	gboolean vers = FALSE;
	gchar *help_str = NULL;
	gchar *help_gtk_str = NULL;
	gchar *help_all_str = NULL;
	gchar *config = NULL;
	int hwaccel=-1;
	int FpsCount=-1;
	int cap_meth=-1;

	GOptionEntry entries[] =
	{
		{ "help-all", 'h', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &help_all, "Display all help options", NULL},
		{ "help-gtk", '!', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &help_gtk, "DISPLAY GTK+ help", NULL},
		{ "help", '?', G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &help, "Display help", NULL},
		{ "version", 0, 0, G_OPTION_ARG_NONE, &vers, N_("Prints version"), NULL},
		{ "verbose", 'v', 0, G_OPTION_ARG_NONE, &global->debug, N_("Displays debug information"), NULL },
		{ "device", 'd', 0, G_OPTION_ARG_STRING, &device, N_("Video Device to use [default: /dev/video0]"), "VIDEO_DEVICE" },
		{ "add_ctrls", 'a', 0, G_OPTION_ARG_NONE, &global->add_ctrls, N_("Exit after adding UVC extension controls (needs root/sudo)"), NULL},
		{ "control_only", 'o', 0, G_OPTION_ARG_NONE, &global->control_only, N_("Don't stream video (image controls only)"), NULL},
        { "no_display", 0,0, G_OPTION_ARG_NONE, &global->no_display, N_("Don't display a GUI"), NULL},
		{ "capture_method", 'r', 0, G_OPTION_ARG_INT, &cap_meth, N_("Capture method (1-mmap (default)  2-read)"), "[1 | 2]"},
		{ "config", 'g', 0, G_OPTION_ARG_STRING, &config, N_("Configuration file"), "FILENAME" },
		{ "hwd_acel", 'w', 0, G_OPTION_ARG_INT, &hwaccel, N_("Hardware accelaration (enable(1) | disable(0))"), "[1 | 0]" },
		{ "format", 'f', 0, G_OPTION_ARG_STRING, &format, N_("Pixel format(mjpg|jpeg|yuyv|yvyu|uyvy|yyuv|yu12|yv12|nv12|nv21|nv16|nv61|y41p|grey|y10b|y16 |s501|s505|s508|gbrg|grbg|ba81|rggb|bgr3|rgb3)"), "FORMAT" },
		{ "size", 's', 0, G_OPTION_ARG_STRING, &size, N_("Frame size, default: 640x480"), "WIDTHxHEIGHT"},
		{ "image", 'i', 0, G_OPTION_ARG_STRING, &image, N_("Image File name"), "FILENAME"},
		{ "cap_time", 'c', 0, G_OPTION_ARG_INT, &global->image_timer, N_("Image capture interval in seconds"), "TIME"},
		{ "npics", 'm', 0, G_OPTION_ARG_INT, &global->image_npics, N_("Number of Pictures to capture"), "NUMPIC"},
		{ "video", 'n', 0, G_OPTION_ARG_STRING, &video, N_("Video File name (capture from start)"), "FILENAME"},
		{ "vid_time", 't', 0, G_OPTION_ARG_INT, &global->Capture_time,N_("Video capture time (in seconds)"), "TIME"},
		{ "exit_on_close", 0, 0, G_OPTION_ARG_NONE, &global->exit_on_close, N_("Exits guvcview after closing video"), NULL},
		{ "skip", 'j', 0, G_OPTION_ARG_INT, &global->skip_n, N_("Number of initial frames to skip"), "N_FRAMES"},
		{ "show_fps", 'p', 0, G_OPTION_ARG_INT, &FpsCount, N_("Show FPS value (enable(1) | disable (0))"), "[1 | 0]"},
		{ "profile", 'l', 0, G_OPTION_ARG_STRING, &profile, N_("Load Profile at start"), "FILENAME"},
		{ "lctl_method", 'k', 0, G_OPTION_ARG_INT, &global->lctl_method, N_("List controls method (0:loop, 1:next_ctrl flag [def])"), "[0 |1]"},
		{ NULL }
	};

	GError *error = NULL;
	GOptionContext *context;
	context = g_option_context_new (N_("- local options"));
	g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
	g_option_context_add_group (context, gtk_get_option_group (TRUE));
	g_set_prgname (PACKAGE);
	help_str = g_option_context_get_help (context, TRUE, NULL);
	help_gtk_str = g_option_context_get_help (context, FALSE, gtk_get_option_group (TRUE));
	help_all_str = g_option_context_get_help (context, FALSE, NULL);
	/*disable automatic help parsing - must clean global before exit*/
	g_option_context_set_help_enabled (context, FALSE);
	if (!g_option_context_parse (context, &argc, &argv, &error))
	{
		g_printerr ("option parsing failed: %s\n", error->message);
		g_error_free ( error );
		closeGlobals(global);
		global=NULL;
		g_print("%s",help_all_str);
		g_free(help_all_str);
		g_free(help_str);
		g_free(help_gtk_str);
		g_option_context_free (context);
		exit (1);
	}

	if(vers)
	{
		//print version and exit
		//version already printed in guvcview.c
		closeGlobals(global);
		global=NULL;
		g_free(help_all_str);
		g_free(help_str);
		g_free(help_gtk_str);
		g_option_context_free (context);
		exit(0);
	}
	/*Display help message and exit*/
	if(help_all)
	{
		closeGlobals(global);
		global=NULL;
		g_print("%s",help_all_str);
		g_free(help_all_str);
		g_free(help_str);
		g_free(help_gtk_str);
		g_option_context_free (context);
		exit(0);
	}
	else if(help)
	{
		closeGlobals(global);
		global=NULL;
		g_print("%s",help_str);
		g_free(help_str);
		g_free(help_gtk_str);
		g_free(help_all_str);
		g_option_context_free (context);
		exit(0);
	} else if(help_gtk)
	{
		closeGlobals(global);
		global=NULL;
		g_print("%s",help_gtk_str);
		g_free(help_str);
		g_free(help_gtk_str);
		g_free(help_all_str);
		g_option_context_free (context);
		exit(0);
	}

	/*regular options*/
	if(device)
	{
		gchar *basename = NULL;
		gchar *dirname = NULL;
		basename = g_path_get_basename(device);
		if(!(g_str_has_prefix(basename,"video")))
		{
			g_printerr("%s not a valid video device name\n",
				basename);
		}
		else
		{
			g_free(global->videodevice);
			global->videodevice=NULL;
			dirname = g_path_get_dirname(device);
			if(g_strcmp0(".",dirname)==0)
			{
				g_free(dirname);
				dirname=g_strdup("/dev");
			}

			global->videodevice = g_strjoin("/",
				dirname,
				basename,
				NULL);
			if(global->flg_config < 1)
			{
				if(g_strcmp0("video0",basename) !=0 )
				{
					g_free(global->confPath);
					global->confPath=NULL;
					global->confPath = g_strjoin("/",
						g_get_home_dir(),
						".config",
						"guvcview",
						basename,
						NULL);
				}
			}
		}
		g_free(dirname);
		g_free(basename);
	}
	if(config)
	{
		g_free(global->confPath);
		global->confPath=NULL;
		global->confPath = g_strdup(config);
		global->flg_config = 1;
	}
	if(format)
	{
		/*use fourcc but keep compatability with luvcview*/
		if(g_strcmp0("yuv",format)==0)
			g_snprintf(global->mode,5,"yuyv");
		else if (g_strcmp0("bggr",format)==0) // be compatible with guvcview < 1.1.4
			g_snprintf(global->mode,5,"ba81");
		else
			g_snprintf(global->mode,5,"%s ",format);

	    printf("requested format \"%s\" from command line\n", global->mode);

		global->flg_mode = TRUE;
	}
	if(size)
	{
		global->width = (int) g_ascii_strtoull(size, &separateur, 10);
		if (*separateur != 'x')
		{
			g_printerr("Error in size usage: -s[--size] WIDTHxHEIGHT \n");
		}
		else
		{
			++separateur;
			global->height = (int) g_ascii_strtoull(separateur, &separateur, 10);
			if (*separateur != 0)
				g_printerr("hmm.. don't like that!! trying this height \n");
		}

		global->flg_res = 1;
	}
	if(image)
	{
		global->imgFPath=splitPath(image,global->imgFPath);
		/*get the file type*/
		global->imgFormat = check_image_type(global->imgFPath[0]);
		global->flg_imgFPath = TRUE;

		if(global->image_inc>0)
		{
			uint64_t suffix = get_file_suffix(global->imgFPath[1], global->imgFPath[0]);
			fprintf(stderr, "Image file suffix detected: %" PRIu64 "\n", suffix);
			if(suffix >= G_MAXUINT64)
			{
				global->imgFPath[0] = add_file_suffix(global->imgFPath[0], suffix);
				suffix = 0;
			}
			if(suffix > 0) {
				global->image_inc = suffix + 1;
      }
		}
	}
	if(global->image_timer > 0 )
	{
		g_print("capturing images every %i seconds\n",global->image_timer);
	}
	if(video)
	{
		global->vidFPath=splitPath(video, global->vidFPath);
		if(global->vid_inc>0)
		{
			uint64_t suffix = get_file_suffix(global->vidFPath[1], global->vidFPath[0]);
			fprintf(stderr, "Video file suffix detected: %" PRIu64 "\n", suffix);
			if(suffix >= G_MAXUINT64)
			{
				global->vidFPath[0] = add_file_suffix(global->vidFPath[0], suffix);
				suffix = 0;
			}
			if(suffix > 0)
				global->vid_inc = suffix + 1;
		}

		global->vidfile = joinPath(global->vidfile, global->vidFPath);

		g_print("capturing video: %s , from start\n",global->vidfile);
		/*get the file type*/
		global->VidFormat = check_video_type(global->vidFPath[0]);
	}
	if(profile)
	{
		global->lprofile=1;
		global->profile_FPath=splitPath(profile,global->profile_FPath);
	}
	if(hwaccel != -1 )
	{
		global->hwaccel = hwaccel;
		global->flg_hwaccel = 1;
	}
	if(FpsCount != -1)
	{
		global->FpsCount = FpsCount;
		global->flg_FpsCount = 1;
	}
	if(cap_meth != -1)
	{
		global->flg_cap_meth = TRUE;
		global->cap_meth = cap_meth;
	}

	//g_print("option capture meth is %i\n", global->cap_meth);
	g_free(help_str);
	g_free(help_gtk_str);
	g_free(help_all_str);
	g_free(device);
	g_free(config);
	g_free(format);
	g_free(size);
	g_free(image);
	g_free(video);
	g_free(profile);
	g_option_context_free (context);
}
示例#29
0
static gchar * system_stat ()
{
        gchar *std_out, *p, **pp1, **pp2, model_name[128], *result;
        gint count;
        GError *err = NULL;

        /* cpu mode */
        result = g_strdup ("{\n");
        if (!g_file_get_contents ("/proc/cpuinfo", &p, NULL, &err)) {
                GST_ERROR ("read /proc/cpuinfo failure: %s", err->message);
                g_free (result);
                result = g_strdup_printf ("{\n    \"result\": \"failure\",\n    \"reason\": \"%s\"\n}", err->message);
                g_error_free (err);
                return result;
        }

        pp1 = pp2 = g_strsplit (p, "\n", 0);
        g_free (p);
        while (*pp1 != NULL) {
                if (!g_str_has_prefix (*pp1, "model name")) {
                        pp1++;
                        continue;
                }
                sscanf (*pp1, "%*[^:]: %[^\n]$", model_name);
                break;
        }
        g_strfreev (pp2);
        p = result;
        result = g_strdup_printf ("%s    \"CPU_Model\": \"%s\"", p, model_name);
        g_free (p);

        if (!g_spawn_command_line_sync ("lscpu", &std_out, NULL, NULL, &err)) {
                GST_ERROR ("invoke lscpu failure: %s", err->message);
                g_free (result);
                result = g_strdup_printf ("{\n    \"result\": \"failure\",\n    \"reason\": \"%s\"\n}", err->message);
                g_error_free (err);
                return result;
        }
        pp1 = pp2 = g_strsplit (std_out, "\n", 0);
        while (*pp1 != NULL) {
                if (g_str_has_prefix (*pp1, "CPU(s)")) {
                        sscanf (*pp1, "CPU(s):%*[ ]%d", &count);
                        p = result;
                        result = g_strdup_printf ("%s,\n    \"CPU_Count\": %d", p, count);
                        g_free (p);

                } else if (g_str_has_prefix (*pp1, "Thread(s) per core")) {
                        sscanf (*pp1, "Thread(s) per core:%*[ ]%d", &count);
                        p = result;
                        result = g_strdup_printf ("%s,\n    \"Threads_per_Core\": %d", p, count);
                        g_free (p);

                } else if (g_str_has_prefix (*pp1, "Core(s) per socket")) {
                        sscanf (*pp1, "Core(s) per socket:%*[ ]%d", &count);
                        p = result;
                        result = g_strdup_printf ("%s,\n    \"Core_per_Socket\": %d", p, count);
                        g_free (p);

                } else if (g_str_has_prefix (*pp1, "Socket(s)")) {
                        sscanf (*pp1, "Socket(s):%*[ ]%d", &count);
                        p = result;
                        result = g_strdup_printf ("%s,\n    \"Sockets_Count\": %d", p, count);
                        g_free (p);

                } else if (g_str_has_prefix (*pp1, "CPU MHz")){
                        sscanf (*pp1, "CPU MHz:%*[ ]%d", &count);
                        p = result;
                        result = g_strdup_printf ("%s,\n    \"CPU_MHz\": %d", p, count);
                        g_free (p);
                }
                pp1++;
        }
        g_strfreev (pp2);
        g_free (std_out);

        p = result;
        result = g_strdup_printf ("%s\n}", p);
        g_free (p);

        return result;
}
示例#30
0
static gboolean
file_read_header(GPtrArray *ezdfile,
                 gchar *buffer,
                 GError **error)
{
    EZDSection *section = NULL;
    gchar *p, *line;
    guint len;

    while ((line = gwy_str_next_line(&buffer))) {
        line = g_strstrip(line);
        if (!(len = strlen(line)))
            continue;
        if (line[0] == '[' && line[len-1] == ']') {
            section = g_new0(EZDSection, 1);
            g_ptr_array_add(ezdfile, section);
            line[len-1] = '\0';
            section->name = g_strdup(line + 1);
            section->meta = g_hash_table_new_full(g_str_hash, g_str_equal,
                                                  g_free, g_free);
            gwy_debug("Section <%s>", section->name);
            continue;
        }
        if (!section) {
            g_set_error(error, GWY_MODULE_FILE_ERROR,
                        GWY_MODULE_FILE_ERROR_DATA,
                        _("Garbage before first header section."));
            return FALSE;
        }
        /* Skip comments */
        if (g_str_has_prefix(line, "--"))
            continue;

        p = strchr(line, '=');
        if (!p) {
            g_set_error(error, GWY_MODULE_FILE_ERROR,
                        GWY_MODULE_FILE_ERROR_DATA,
                        _("Malformed header line (missing =)."));
            return FALSE;
        }
        *p = '\0';
        p++;

        if (gwy_strequal(line, "SaveMode")) {
            if (strcmp(p, "Binary"))
                g_warning("SaveMode is not Binary, this is not supported");
        }
        else if (gwy_strequal(line, "SaveBits"))
            section->bitdepth = atol(p);
        else if (gwy_strequal(line, "SaveSign")) {
            section->sign = gwy_strequal(p, "Signed");
            if (!section->sign)
                g_warning("SaveSign is not Signed, this is not supported");
        }
        else if (gwy_strequal(line, "SaveOrder")) {
            if (gwy_strequal(p, "Intel"))
                section->byteorder = G_LITTLE_ENDIAN;
            else
                g_warning("SaveOrder is not Intel, this is not supported");
        }
        else if (gwy_strequal(line, "Frame")) {
            if (gwy_strequal(p, "Scan forward"))
                section->direction = SCAN_FORWARD;
            else if (gwy_strequal(p, "Scan backward"))
                section->direction = SCAN_BACKWARD;
        }
        else if (gwy_strequal(line, "Points"))
            section->xres = atol(p);
        else if (gwy_strequal(line, "Lines"))
            section->yres = atol(p);
        /* FIXME: this is ugly, and incorrect for non-2D data */
        else if (gwy_strequal(line, "Dim0Name"))
            section->xrange.name = g_strdup(p);
        else if (gwy_strequal(line, "Dim1Name"))
            section->yrange.name = g_strdup(p);
        else if (gwy_strequal(line, "Dim2Name"))
            section->zrange.name = g_strdup(p);
        else if (gwy_strequal(line, "Dim0Unit"))
            section->xrange.unit = g_strdup(p);
        else if (gwy_strequal(line, "Dim1Unit"))
            section->yrange.unit = g_strdup(p);
        else if (gwy_strequal(line, "Dim2Unit"))
            section->zrange.unit = g_strdup(p);
        else if (gwy_strequal(line, "Dim0Min"))
            section->xrange.min = g_ascii_strtod(p, NULL);
        else if (gwy_strequal(line, "Dim1Min"))
            section->yrange.min = g_ascii_strtod(p, NULL);
        else if (gwy_strequal(line, "Dim2Min"))
            section->zrange.min = g_ascii_strtod(p, NULL);
        else if (gwy_strequal(line, "Dim0Range"))
            section->xrange.range = g_ascii_strtod(p, NULL);
        else if (gwy_strequal(line, "Dim1Range"))
            section->yrange.range = g_ascii_strtod(p, NULL);
        else if (gwy_strequal(line, "Dim2Range"))
            section->zrange.range = g_ascii_strtod(p, NULL);
        else
            g_hash_table_replace(section->meta, g_strdup(line), g_strdup(p));
    }
    return TRUE;
}