コード例 #1
0
ファイル: recorder.c プロジェクト: Byrnesz/ardesia-1
/*
 * Start the dialog that ask to the user where save the video
 * containing the screencast.
 * This function take as input the recorder tool button in ardesia bar
 * return true is the recorder is started.
 */
gboolean start_save_video_dialog (GtkToolButton *toolbutton,
                                  GtkWindow     *parent)
{
  gboolean status = FALSE;

  gchar *filename = g_strdup_printf ("%s", get_project_name ());

  GtkWidget *chooser = gtk_file_chooser_dialog_new (gettext ("Save video as ogv"),
                                                    parent,
                                                    GTK_FILE_CHOOSER_ACTION_SAVE,
                                                    GTK_STOCK_CANCEL,
                                                    GTK_RESPONSE_CANCEL,
                                                    GTK_STOCK_SAVE_AS,
                                                    GTK_RESPONSE_ACCEPT,
                                                    NULL);

  gtk_window_set_modal (GTK_WINDOW (chooser), TRUE);
  gtk_window_set_keep_above (GTK_WINDOW (chooser), TRUE);

  gtk_window_set_title (GTK_WINDOW (chooser), gettext ("Choose a file"));

  gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (chooser), get_project_dir ());

  gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (chooser), filename);

  start_virtual_keyboard ();

  if (gtk_dialog_run (GTK_DIALOG (chooser)) == GTK_RESPONSE_ACCEPT)
    {
      gchar *supported_extension = ".ogv";
      gchar *filename_copy = (gchar *) NULL;
      g_free (filename);
      filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (chooser));
      filename_copy = g_strdup_printf ("%s", filename); 

      if (!g_str_has_suffix (filename, supported_extension))
        {
          g_free (filename_copy);
          filename_copy = g_strdup_printf ("%s%s", filename, supported_extension);
        }

      g_free (filename);
      filename = filename_copy;

      if (file_exists (filename))
        {
          gint result = show_override_dialog (GTK_WINDOW (chooser));
          if ( result  == GTK_RESPONSE_NO)
            {
              g_free (filename);
              filename = NULL;
              gtk_widget_destroy (chooser);
              chooser = NULL;
              return status;
            }
        }
      else
        {
           FILE *stream = g_fopen (filename, "w");
           if (stream == NULL)
            {
              show_could_not_write_dialog (GTK_WINDOW (chooser));
            }
           else
            {
              fclose (stream);
            }
        }

      recorder_pid = call_recorder (filename, "start");
      status = (recorder_pid > 0);
    }
  stop_virtual_keyboard ();

  if (chooser)
    {
      gtk_widget_destroy (chooser);
      chooser = NULL;
    }

  g_free (filename);
  filename = NULL;
  return status;
}
コード例 #2
0
ファイル: gimppalette-load.c プロジェクト: jiapei100/gimp
GimpPaletteFileFormat
gimp_palette_load_detect_format (GFile        *file,
                                 GInputStream *input)
{
  GimpPaletteFileFormat format = GIMP_PALETTE_FILE_FORMAT_UNKNOWN;
  gchar                 header[16];
  gsize                 bytes_read;

  if (g_input_stream_read_all (input, &header, sizeof (header),
                               &bytes_read, NULL, NULL) &&
      bytes_read == sizeof (header))
    {
      if (g_str_has_prefix (header + 0, "RIFF") &&
          g_str_has_prefix (header + 8, "PAL data"))
        {
          format = GIMP_PALETTE_FILE_FORMAT_RIFF_PAL;
        }
      else if (g_str_has_prefix (header, "GIMP Palette"))
        {
          format = GIMP_PALETTE_FILE_FORMAT_GPL;
        }
      else if (g_str_has_prefix (header, "JASC-PAL"))
        {
          format = GIMP_PALETTE_FILE_FORMAT_PSP_PAL;
        }
    }

  if (format == GIMP_PALETTE_FILE_FORMAT_UNKNOWN)
    {
      gchar *lower = g_ascii_strdown (gimp_file_get_utf8_name (file), -1);

      if (g_str_has_suffix (lower, ".aco"))
        {
          format = GIMP_PALETTE_FILE_FORMAT_ACO;
        }
      else if (g_str_has_suffix (lower, ".css"))
        {
          format = GIMP_PALETTE_FILE_FORMAT_CSS;
        }

      g_free (lower);
    }

  if (format == GIMP_PALETTE_FILE_FORMAT_UNKNOWN)
    {
      GFileInfo *info = g_file_query_info (file,
                                           G_FILE_ATTRIBUTE_STANDARD_SIZE,
                                           G_FILE_QUERY_INFO_NONE,
                                           NULL, NULL);

      if (info)
        {
          goffset size = g_file_info_get_size (info);

          if (size == 768)
            format = GIMP_PALETTE_FILE_FORMAT_ACT;

          g_object_unref (info);
        }
    }

  g_seekable_seek (G_SEEKABLE (input), 0, G_SEEK_SET, NULL, NULL);

  return format;
}
コード例 #3
0
ファイル: gb-vim.c プロジェクト: GNOME/gnome-builder
static void
gb_vim_complete_edit_files (GtkWidget   *active_widget,
                            const gchar *command,
                            GPtrArray   *ar,
                            const gchar *prefix)
{
  g_autoptr(GFile) child = NULL;
  g_autoptr(GFile) parent = NULL;
  g_autoptr(GFile) workdir = NULL;

  IDE_ENTRY;

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

  if (!(workdir = find_workdir (active_widget)))
    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;
      GFileInfo *descendent;
      const gchar *slash;
      const gchar *partial_name;
      g_autofree gchar *prefix_dir = NULL;

#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)))
        {
          partial_name = slash + 1;
          prefix_dir = g_strndup (prefix, slash - prefix + 1);
        }
      else
        {
          partial_name = prefix;
        }

      fe = g_file_enumerate_children (parent,
                                      G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME","
                                      G_FILE_ATTRIBUTE_STANDARD_TYPE,
                                      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;
          GFileType file_type;

          name = g_file_info_get_display_name (descendent);
          file_type = g_file_info_get_file_type (descendent);

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

          if (name && g_str_has_prefix (name, partial_name))
            {
              gchar *completed_command;
              const gchar *descendent_name;
              g_autofree gchar *full_path = NULL;
              g_autofree gchar *parent_path = NULL;

              parent_path = g_file_get_path (parent);
              descendent_name = g_file_info_get_name (descendent);
              full_path = g_build_filename (parent_path, descendent_name, NULL);

              if (prefix[0] == G_DIR_SEPARATOR)
                completed_command = g_strdup_printf ("%s %s%s", command, full_path,
                                                     file_type == G_FILE_TYPE_DIRECTORY ? G_DIR_SEPARATOR_S : "");
              else if (strchr (prefix, G_DIR_SEPARATOR) == NULL)
                completed_command = g_strdup_printf ("%s %s%s", command, descendent_name,
                                                     file_type == G_FILE_TYPE_DIRECTORY ? G_DIR_SEPARATOR_S : "");
              else
                completed_command = g_strdup_printf ("%s %s%s%s", command, prefix_dir, descendent_name,
                                                     file_type == G_FILE_TYPE_DIRECTORY ? G_DIR_SEPARATOR_S : "");

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

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

      IDE_EXIT;
    }

  IDE_EXIT;
}
コード例 #4
0
static gboolean
workaround_selinux_cross_labeling_recurse (GFile         *dir,
                                           GCancellable  *cancellable,
                                           GError       **error)
{
  gboolean ret = FALSE;
  gs_unref_object GFileEnumerator *direnum = NULL;

  direnum = g_file_enumerate_children (dir, "standard::name,standard::type,time::modified,time::access",
                                       G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
                                       cancellable, error);
  if (!direnum)
    goto out;

  while (TRUE)
    {
      GFileInfo *file_info;
      GFile *child;
      const char *name;

      if (!gs_file_enumerator_iterate (direnum, &file_info, &child,
                                       cancellable, error))
        goto out;
      if (!file_info)
        break;

      name = g_file_info_get_name (file_info);

      if (g_file_info_get_file_type (file_info) == G_FILE_TYPE_DIRECTORY)
        {
          if (!workaround_selinux_cross_labeling_recurse (child, cancellable, error))
            goto out;
        }
      else if (g_str_has_suffix (name, ".bin"))
        {
          const char *lastdot;
          gs_free char *nonbin_name = NULL;
          gs_unref_object GFile *nonbin_path = NULL;
          guint64 mtime = g_file_info_get_attribute_uint64 (file_info, "time::modified");
          guint64 atime = g_file_info_get_attribute_uint64 (file_info, "time::access");
          struct utimbuf times;

          lastdot = strrchr (name, '.');
          g_assert (lastdot);

          nonbin_name = g_strndup (name, lastdot - name);
          nonbin_path = g_file_get_child (dir, nonbin_name);

          times.actime = (time_t)atime;
          times.modtime = ((time_t)mtime) + 60;

          g_print ("Setting mtime of '%s' to newer than '%s'\n",
                   gs_file_get_path_cached (nonbin_path),
                   gs_file_get_path_cached (child));
          if (utime (gs_file_get_path_cached (nonbin_path), &times) == -1)
            {
              int errsv = errno;
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "utime(%s): %s", gs_file_get_path_cached (nonbin_path),
                           strerror (errsv));
              goto out;
            }
        }
    }

  ret = TRUE;
 out:
  return ret;
}
コード例 #5
0
ファイル: as-validator.c プロジェクト: lucasmoura/appstream
/**
 * as_validator_validate_component_node:
 **/
static AsComponent*
as_validator_validate_component_node (AsValidator *validator, AsXMLData *xdt, xmlNode *root)
{
	xmlNode *iter;
	AsComponent *cpt;
	guint i;
	g_autofree gchar *metadata_license = NULL;
	g_autofree gchar *cpttype = NULL;
	g_autoptr(GHashTable) found_tags = NULL;
	g_auto(GStrv) cid_parts = NULL;
	const gchar *summary;
	const gchar *cid;
	AsParserMode mode;

	found_tags = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
	mode = as_xmldata_get_parser_mode (xdt);

	/* validate the resulting AsComponent for sanity */
	cpt = as_component_new ();
	as_xmldata_parse_component_node (xdt, root, cpt, NULL);
	as_validator_set_current_cpt (validator, cpt);

	/* check if component type is valid */
	cpttype = (gchar*) xmlGetProp (root, (xmlChar*) "type");
	if (cpttype != NULL) {
		if (as_component_kind_from_string (cpttype) == AS_COMPONENT_KIND_UNKNOWN) {
			as_validator_add_issue (validator,
						AS_ISSUE_IMPORTANCE_ERROR,
						AS_ISSUE_KIND_VALUE_WRONG,
						"Invalid component type found: %s",
						cpttype);
		}
	}

	/* validate the AppStream ID */
	cid = as_component_get_id (cpt);
	cid_parts = g_strsplit (cid, ".", 3);
	if (g_strv_length (cid_parts) != 3) {
		if (as_component_get_kind (cpt) == AS_COMPONENT_KIND_DESKTOP_APP) {
			/* since the ID and .desktop-file-id are tied together, we can't make this an error for desktop apps */
			as_validator_add_issue (validator,
					AS_ISSUE_IMPORTANCE_WARNING,
					AS_ISSUE_KIND_VALUE_WRONG,
					"The component ID is not a reverse domain-name. Please update the ID and that of the accompanying .desktop file to follow the latest version of the specifications and avoid future issues.");
		} else {
			/* anything which isn't a .desktop app should follow the schema though */
			as_validator_add_issue (validator,
					AS_ISSUE_IMPORTANCE_ERROR,
					AS_ISSUE_KIND_VALUE_WRONG,
					"The component ID is no reverse domain-name.");
		}
	} else {
		/* some people just add random dots to their ID - check if we have an actual known TLD as first part, to be more certain that this is a reverse domain name
		 * (this issue happens quite often with old .desktop files) */
		if (!as_utils_is_tld (cid_parts[0])) {
			as_validator_add_issue (validator,
						AS_ISSUE_IMPORTANCE_INFO,
						AS_ISSUE_KIND_VALUE_WRONG,
						"The component ID might not follow the reverse domain-name schema (we do not know about the TLD '%s').", cid_parts[0]);
		}
	}

	/* validate characters in AppStream ID */
	for (i = 0; cid[i] != '\0'; i++) {
		/* check if we have a printable, alphanumeric ASCII character or a dot, hyphen or underscore */
		if ((!g_ascii_isalnum (cid[i])) &&
		    (cid[i] != '.') &&
		    (cid[i] != '-') &&
		    (cid[i] != '_')) {
			g_autofree gchar *c = NULL;
			c = g_utf8_substring (cid, i, i + 1);
			as_validator_add_issue (validator,
					AS_ISSUE_IMPORTANCE_ERROR,
					AS_ISSUE_KIND_VALUE_WRONG,
					"The component ID contains an invalid character: '%s'", c);
		}
	}



	for (iter = root->children; iter != NULL; iter = iter->next) {
		const gchar *node_name;
		g_autofree gchar *node_content = NULL;
		gboolean tag_valid = TRUE;
		/* discard spaces */
		if (iter->type != XML_ELEMENT_NODE)
			continue;
		node_name = (const gchar*) iter->name;
		node_content = (gchar*) xmlNodeGetContent (iter);

		if (g_strcmp0 (node_name, "id") == 0) {
			gchar *prop;
			prop = (gchar*) xmlGetProp (iter, (xmlChar*) "type");
			if (prop != NULL) {
				as_validator_add_issue (validator,
							AS_ISSUE_IMPORTANCE_INFO,
							AS_ISSUE_KIND_PROPERTY_INVALID,
							"The id tag for \"%s\" still contains a 'type' property, probably from an old conversion.",
							node_content);
			}
			g_free (prop);
			if (as_component_get_kind (cpt) == AS_COMPONENT_KIND_DESKTOP_APP) {
				if (!g_str_has_suffix (node_content, ".desktop"))
					as_validator_add_issue (validator,
								AS_ISSUE_IMPORTANCE_WARNING,
								AS_ISSUE_KIND_VALUE_WRONG,
								"Component id belongs to a desktop-application, but does not resemble the .desktop file name: \"%s\"",
								node_content);
			}
		} else if (g_strcmp0 (node_name, "metadata_license") == 0) {
			metadata_license = g_strdup (node_content);
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
		} else if (g_strcmp0 (node_name, "pkgname") == 0) {
			if (g_hash_table_contains (found_tags, node_name)) {
				as_validator_add_issue (validator,
							AS_ISSUE_IMPORTANCE_PEDANTIC,
							AS_ISSUE_KIND_TAG_DUPLICATED,
							"The tag 'pkgname' appears multiple times. You should evaluate creating a metapackage containing the data in order to avoid defining multiple package names per component.");
			}
		} else if (g_strcmp0 (node_name, "source_pkgname") == 0) {
			if (g_hash_table_contains (found_tags, node_name)) {
				as_validator_add_issue (validator,
							AS_ISSUE_IMPORTANCE_ERROR,
							AS_ISSUE_KIND_TAG_DUPLICATED,
							"The tag 'source_pkgname' appears multiple times.");
			}
		} else if (g_strcmp0 (node_name, "name") == 0) {
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
		} else if (g_strcmp0 (node_name, "summary") == 0) {
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
		} else if (g_strcmp0 (node_name, "description") == 0) {
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
			as_validator_check_description_tag (validator, iter, cpt, mode);
		} else if (g_strcmp0 (node_name, "icon") == 0) {
			gchar *prop;
			prop = as_validator_check_type_property (validator, cpt, iter);
			if ((g_strcmp0 (prop, "cached") == 0) || (g_strcmp0 (prop, "stock") == 0)) {
				if (g_strrstr (node_content, "/") != NULL)
					as_validator_add_issue (validator,
								AS_ISSUE_IMPORTANCE_ERROR,
								AS_ISSUE_KIND_VALUE_WRONG,
								"Icons of type 'stock' or 'cached' must not contain a full or relative path to the icon.");
			}
			g_free (prop);
		} else if (g_strcmp0 (node_name, "url") == 0) {
			gchar *prop;
			prop = as_validator_check_type_property (validator, cpt, iter);
			if (as_url_kind_from_string (prop) == AS_URL_KIND_UNKNOWN) {
				as_validator_add_issue (validator,
							AS_ISSUE_IMPORTANCE_ERROR,
							AS_ISSUE_KIND_PROPERTY_INVALID,
							"Invalid property for 'url' tag: \"%s\"",
							prop);
			}
			g_free (prop);
		} else if (g_strcmp0 (node_name, "categories") == 0) {
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
			as_validator_check_children_quick (validator, iter, "category", cpt);
		} else if (g_strcmp0 (node_name, "keywords") == 0) {
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
			as_validator_check_children_quick (validator, iter, "keyword", cpt);
		} else if (g_strcmp0 (node_name, "mimetypes") == 0) {
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
			as_validator_check_children_quick (validator, iter, "mimetype", cpt);
		} else if (g_strcmp0 (node_name, "provides") == 0) {
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
		} else if (g_strcmp0 (node_name, "screenshots") == 0) {
			as_validator_check_children_quick (validator, iter, "screenshot", cpt);
		} else if (g_strcmp0 (node_name, "project_license") == 0) {
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
		} else if (g_strcmp0 (node_name, "project_group") == 0) {
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
		} else if (g_strcmp0 (node_name, "developer_name") == 0) {
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
		} else if (g_strcmp0 (node_name, "compulsory_for_desktop") == 0) {
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
		} else if (g_strcmp0 (node_name, "releases") == 0) {
			as_validator_check_children_quick (validator, iter, "release", cpt);
		} else if ((g_strcmp0 (node_name, "languages") == 0) && (mode == AS_PARSER_MODE_DISTRO)) {
			as_validator_check_appear_once (validator, iter, found_tags, cpt);
			as_validator_check_children_quick (validator, iter, "lang", cpt);
		} else if ((g_strcmp0 (node_name, "translation") == 0) && (mode == AS_PARSER_MODE_UPSTREAM)) {
			g_autofree gchar *prop = NULL;
			AsTranslationKind trkind;
			prop = as_validator_check_type_property (validator, cpt, iter);
			trkind = as_translation_kind_from_string (prop);
			if (trkind == AS_TRANSLATION_KIND_UNKNOWN) {
				as_validator_add_issue (validator,
							AS_ISSUE_IMPORTANCE_ERROR,
							AS_ISSUE_KIND_VALUE_WRONG,
							"Unknown type '%s' for <translation/> tag.", prop);
			}
		} else if (g_strcmp0 (node_name, "extends") == 0) {
		} else if (g_strcmp0 (node_name, "bundle") == 0) {
			g_autofree gchar *prop = NULL;
			prop = as_validator_check_type_property (validator, cpt, iter);
			if ((g_strcmp0 (prop, "limba") != 0) && (g_strcmp0 (prop, "flatpak") != 0)) {
				as_validator_add_issue (validator,
							AS_ISSUE_IMPORTANCE_ERROR,
							AS_ISSUE_KIND_VALUE_WRONG,
							"Unknown type '%s' for <bundle/> tag.", prop);
			}
		} else if (g_strcmp0 (node_name, "update_contact") == 0) {
			if (mode == AS_PARSER_MODE_DISTRO) {
				as_validator_add_issue (validator,
							AS_ISSUE_IMPORTANCE_WARNING,
							AS_ISSUE_KIND_TAG_NOT_ALLOWED,
							"The 'update_contact' tag should not be included in distro AppStream XML.");
			} else {
				as_validator_check_appear_once (validator, iter, found_tags, cpt);
			}
		} else if (g_strcmp0 (node_name, "metadata") == 0) {
			as_validator_add_issue (validator,
						AS_ISSUE_IMPORTANCE_PEDANTIC,
						AS_ISSUE_KIND_TAG_UNKNOWN,
						"Found custom metadata in <metadata/> tag. Use of this tag is common, but should be avoided if possible.");
			tag_valid = FALSE;
		} else if (!g_str_has_prefix (node_name, "x-")) {
			as_validator_add_issue (validator,
						AS_ISSUE_IMPORTANCE_WARNING,
						AS_ISSUE_KIND_TAG_UNKNOWN,
						"Found invalid tag: '%s'. Non-standard tags must be prefixed with \"x-\".",
				node_name);
			tag_valid = FALSE;
		}

		if (tag_valid) {
			as_validator_check_content_empty (validator,
							node_content,
							node_name,
							AS_ISSUE_IMPORTANCE_WARNING,
							cpt);
		}
	}

	if (metadata_license == NULL) {
		if (mode == AS_PARSER_MODE_UPSTREAM)
			as_validator_add_issue (validator,
						AS_ISSUE_IMPORTANCE_ERROR,
						AS_ISSUE_KIND_TAG_MISSING,
						"The essential tag 'metadata_license' is missing.");
	}

	/* check if the summary is sane */
	summary = as_component_get_summary (cpt);
	if ((summary != NULL) && ((strstr (summary, "\n") != NULL) || (strstr (summary, "\t") != NULL))) {
		as_validator_add_issue (validator,
					AS_ISSUE_IMPORTANCE_ERROR,
					AS_ISSUE_KIND_VALUE_WRONG,
					"The summary tag must not contain tabs or linebreaks.");
	}

	/* check if we have a description */
	if (as_str_empty (as_component_get_description (cpt))) {
		AsComponentKind cpt_kind;
		cpt_kind = as_component_get_kind (cpt);

		if ((cpt_kind == AS_COMPONENT_KIND_DESKTOP_APP) ||
			(cpt_kind == AS_COMPONENT_KIND_FONT)) {
			as_validator_add_issue (validator,
					AS_ISSUE_IMPORTANCE_ERROR,
					AS_ISSUE_KIND_TAG_MISSING,
					"The component is missing a long description. Components of this type must have a long description.");
		} else if (cpt_kind != AS_COMPONENT_KIND_GENERIC) {
			as_validator_add_issue (validator,
					AS_ISSUE_IMPORTANCE_INFO,
					AS_ISSUE_KIND_TAG_MISSING,
					"The component is missing a long description. It is recommended to add one.");
		}
	}

	/* validate font specific stuff */
	if (as_component_get_kind (cpt) == AS_COMPONENT_KIND_FONT) {
		if (!g_str_has_suffix (as_component_get_id (cpt), ".font"))
			as_validator_add_issue (validator,
					AS_ISSUE_IMPORTANCE_ERROR,
					AS_ISSUE_KIND_VALUE_WRONG,
					"Components of type 'font' must have an AppStream ID with a '.font' suffix.");
		if (as_component_get_provided_for_kind (cpt, AS_PROVIDED_KIND_FONT) == NULL)
			as_validator_add_issue (validator,
					AS_ISSUE_IMPORTANCE_WARNING,
					AS_ISSUE_KIND_TAG_MISSING,
					"Type 'font' component, but no font information was provided via a provides/font tag.");
	}

	/* validate addon specific stuff */
	if (as_component_get_extends (cpt)->len > 0) {
		if (as_component_get_kind (cpt) != AS_COMPONENT_KIND_ADDON)
			as_validator_add_issue (validator,
						AS_ISSUE_IMPORTANCE_ERROR,
						AS_ISSUE_KIND_TAG_NOT_ALLOWED,
						"An 'extends' tag is specified, but the component is not an addon.");
	} else {
		if (as_component_get_kind (cpt) == AS_COMPONENT_KIND_ADDON)
			as_validator_add_issue (validator,
						AS_ISSUE_IMPORTANCE_ERROR,
						AS_ISSUE_KIND_TAG_MISSING,
						"The component is an addon, but no 'extends' tag was specified.");
	}

	as_validator_clear_current_cpt (validator);
	return cpt;
}
コード例 #6
0
static gboolean
add_ref (ParserState               *parser_state,
	 const gchar               *ref,
	 GtkSourceContextRefOptions options,
	 const gchar               *style,
	 GError	                  **error)
{
	gboolean all = FALSE;
	gchar *ref_id;
	gchar *lang_id = NULL;
	GError *tmp_error = NULL;

	/* Return if an error is already set */
	g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

	if (id_is_decorated (ref, &lang_id))
	{
		if (!lang_id_is_already_loaded (parser_state, lang_id))
		{
			GtkSourceLanguageManager *lm;
			GtkSourceLanguage *imported_language;

			lm = _gtk_source_language_get_language_manager (parser_state->language);
			imported_language = gtk_source_language_manager_get_language (lm, lang_id);

			if (imported_language == NULL)
			{
				g_set_error (&tmp_error,
						PARSER_ERROR,
						PARSER_ERROR_WRONG_ID,
						"unable to resolve language '%s' in ref '%s'",
						lang_id, ref);
			}
			else
			{
				file_parse (imported_language->priv->lang_file_name,
					    parser_state->language,
					    parser_state->ctx_data,
					    parser_state->defined_regexes,
					    parser_state->styles_mapping,
					    parser_state->loaded_lang_ids,
					    parser_state->replacements,
					    &tmp_error);

				if (tmp_error != NULL)
				{
					GError *tmp_error2 = NULL;
					g_set_error (&tmp_error2, PARSER_ERROR, tmp_error->code,
						     "In file '%s' referenced from '%s': %s",
						     imported_language->priv->lang_file_name,
						     parser_state->language->priv->lang_file_name,
						     tmp_error->message);
					g_clear_error (&tmp_error);
					tmp_error = tmp_error2;
				}
			}
		}
		ref_id = g_strdup (ref);
	}
	else
	{
		ref_id = decorate_id (parser_state, ref);
	}

	if (tmp_error == NULL && parser_state->ctx_data != NULL)
	{
		if (g_str_has_suffix (ref, ":*"))
		{
			all = TRUE;
			ref_id [strlen (ref_id) - 2] = '\0';
		}

		if (all && (options & (GTK_SOURCE_CONTEXT_IGNORE_STYLE | GTK_SOURCE_CONTEXT_OVERRIDE_STYLE)))
		{
			g_set_error (&tmp_error, PARSER_ERROR,
				     PARSER_ERROR_WRONG_STYLE,
				     "style override used with wildcard context reference"
				     " in language '%s' in ref '%s'",
				     lang_id != NULL ? lang_id : parser_state->current_lang_id, ref);
		}
	}

	if (tmp_error == NULL && parser_state->ctx_data != NULL)
	{
		gchar *container_id;

		container_id = g_queue_peek_head (parser_state->curr_parents);

		/* If the document is validated container_id is never NULL */
		g_assert (container_id);

		_gtk_source_context_data_add_ref (parser_state->ctx_data,
						  container_id,
						  ref_id,
						  options,
						  style,
						  all,
						  &tmp_error);

		DEBUG (g_message ("appended %s in %s", ref_id, container_id));
	}

	g_free (lang_id);
	g_free (ref_id);

	if (tmp_error != NULL)
	{
		g_propagate_error (error, tmp_error);
		return FALSE;
	}

	return TRUE;
}
コード例 #7
0
void initializeFontConfigSetting()
{
    if (g_getenv("WEBKIT_SKIP_WEBKITTESTRUNNER_FONTCONFIG_INITIALIZATION"))
        return;

    FcInit();

    // If a test resulted a font being added or removed via the @font-face rule, then
    // we want to reset the FontConfig configuration to prevent it from affecting other tests.
    static int numFonts = 0;
    FcFontSet* appFontSet = FcConfigGetFonts(0, FcSetApplication);
    if (appFontSet && numFonts && appFontSet->nfont == numFonts)
        return;

    // Load our configuration file, which sets up proper aliases for family
    // names like sans, serif and monospace.
    FcConfig* config = FcConfigCreate();
    GOwnPtr<gchar> fontConfigFilename(g_build_filename(FONTS_CONF_DIR, "fonts.conf", NULL));
    if (!g_file_test(fontConfigFilename.get(), G_FILE_TEST_IS_REGULAR))
        g_error("Cannot find fonts.conf at %s\n", fontConfigFilename.get());
    if (!FcConfigParseAndLoad(config, reinterpret_cast<FcChar8*>(fontConfigFilename.get()), true))
        g_error("Couldn't load font configuration file from: %s", fontConfigFilename.get());

    CString fontsPath = getFontsPath();
    if (fontsPath.isNull())
        g_error("Could not locate test fonts at %s. Is WEBKIT_TOP_LEVEL set?", fontsPath.data());

    GOwnPtr<GDir> fontsDirectory(g_dir_open(fontsPath.data(), 0, 0));
    while (const char* directoryEntry = g_dir_read_name(fontsDirectory.get())) {
        if (!g_str_has_suffix(directoryEntry, ".ttf") && !g_str_has_suffix(directoryEntry, ".otf"))
            continue;
        GOwnPtr<gchar> fontPath(g_build_filename(fontsPath.data(), directoryEntry, NULL));
        if (!FcConfigAppFontAddFile(config, reinterpret_cast<const FcChar8*>(fontPath.get())))
            g_error("Could not load font at %s!", fontPath.get());
    }

    // Ahem is used by many layout tests.
    GOwnPtr<gchar> ahemFontFilename(g_build_filename(FONTS_CONF_DIR, "AHEM____.TTF", NULL));
    if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(ahemFontFilename.get())))
        g_error("Could not load font at %s!", ahemFontFilename.get()); 

    static const char* fontFilenames[] = {
        "WebKitWeightWatcher100.ttf",
        "WebKitWeightWatcher200.ttf",
        "WebKitWeightWatcher300.ttf",
        "WebKitWeightWatcher400.ttf",
        "WebKitWeightWatcher500.ttf",
        "WebKitWeightWatcher600.ttf",
        "WebKitWeightWatcher700.ttf",
        "WebKitWeightWatcher800.ttf",
        "WebKitWeightWatcher900.ttf",
        0
    };

    for (size_t i = 0; fontFilenames[i]; ++i) {
        GOwnPtr<gchar> fontFilename(g_build_filename(FONTS_CONF_DIR, "..", "..", "fonts", fontFilenames[i], NULL));
        if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(fontFilename.get())))
            g_error("Could not load font at %s!", fontFilename.get()); 
    }

    // A font with no valid Fontconfig encoding to test https://bugs.webkit.org/show_bug.cgi?id=47452
    GOwnPtr<gchar> fontWithNoValidEncodingFilename(g_build_filename(FONTS_CONF_DIR, "FontWithNoValidEncoding.fon", NULL));
    if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(fontWithNoValidEncodingFilename.get())))
        g_error("Could not load font at %s!", fontWithNoValidEncodingFilename.get()); 

    if (!FcConfigSetCurrent(config))
        g_error("Could not set the current font configuration!");

    numFonts = FcConfigGetFonts(config, FcSetApplication)->nfont;
}
コード例 #8
0
ファイル: djvu-links.c プロジェクト: mate-desktop/atril
/**
 * Builds the index GtkTreeModel from DjVu s-expr
 *
 * (bookmarks
 *   ("title1" "dest1"
 *     ("title12" "dest12"
 *       ... )
 *     ... )
 *   ("title2" "dest2"
 *     ... )
 *   ... )
 */
static void
build_tree (const DjvuDocument *djvu_document,
	    GtkTreeModel       *model,
	    GtkTreeIter        *parent,
	    miniexp_t           iter)
{
	const char *title, *link_dest;
	char *title_markup;

	EvLinkAction *ev_action = NULL;
	EvLink *ev_link = NULL;
	GtkTreeIter tree_iter;

	if (miniexp_car (iter) == miniexp_symbol ("bookmarks")) {
		/* The (bookmarks) cons */
		iter = miniexp_cdr (iter);
	} else if ( miniexp_length (iter) >= 2 ) {
		gchar *utf8_title = NULL;
		
		/* An entry */
		if (!string_from_miniexp (miniexp_car (iter), &title)) goto unknown_entry;
		if (!string_from_miniexp (miniexp_cadr (iter), &link_dest)) goto unknown_entry;

		
		if (!g_utf8_validate (title, -1, NULL)) {
			utf8_title = str_to_utf8 (title);
			title_markup = g_markup_escape_text (utf8_title, -1);
		} else {
			title_markup = g_markup_escape_text (title, -1);
		}

		ev_action = get_djvu_link_action (djvu_document, link_dest, -1);
		
		if (g_str_has_suffix (link_dest, ".djvu")) {
			/* FIXME: component file identifiers */
		} else if (ev_action) {
			ev_link = ev_link_new (utf8_title ? utf8_title : title, ev_action);
			gtk_tree_store_append (GTK_TREE_STORE (model), &tree_iter, parent);
			gtk_tree_store_set (GTK_TREE_STORE (model), &tree_iter,
					    EV_DOCUMENT_LINKS_COLUMN_MARKUP, title_markup,
					    EV_DOCUMENT_LINKS_COLUMN_LINK, ev_link,
					    EV_DOCUMENT_LINKS_COLUMN_EXPAND, FALSE,
					    -1);
			g_object_unref (ev_link);
		} else {
			gtk_tree_store_append (GTK_TREE_STORE (model), &tree_iter, parent);
			gtk_tree_store_set (GTK_TREE_STORE (model), &tree_iter,
					    EV_DOCUMENT_LINKS_COLUMN_MARKUP, title_markup,
					    EV_DOCUMENT_LINKS_COLUMN_EXPAND, FALSE,
					    -1);
		}

		g_free (title_markup);
		g_free (utf8_title);
		iter = miniexp_cddr (iter);
		parent = &tree_iter;
	} else {
		goto unknown_entry;
	}

	for (; iter != miniexp_nil; iter = miniexp_cdr (iter)) {
		build_tree (djvu_document, model, parent, miniexp_car (iter));
	}
	return;

 unknown_entry:
	g_warning ("DjvuLibre error: Unknown entry in bookmarks");
	return;
}
コード例 #9
0
/* The main function */
int main(int arch, const char *argv[])
{
	int ifd;
	unsigned i;
	MafwRegistry *regi;

	/* Don't log debug messages. */
	mafw_log_init(":warning");

	/* Init wrapping */
	g_type_init();
	regi = MAFW_REGISTRY(mafw_registry_get_instance());
	mafw_shared_init(regi, NULL);
	wrapper_init();

	/* Load the plugins specified on the command line. */
	if ((ifd = inotify_init()) < 0)
		g_warning("inotify_init: %m");
	for (i = 1; argv[i]; i++) {
		DIR *hdir;
		gchar entry[PATH_MAX];
		const struct dirent *dent;

		strncpy(entry, argv[i], PATH_MAX);
		if (entry[PATH_MAX - 1] != '\0') {
			g_warning("Argument %d is too long, skipping", i-1);
			continue;
		}

		hdir = opendir(entry);
		if (hdir != NULL) {
			while ((dent = readdir(hdir)) != NULL) {
				gchar *path;

				/* Try to ignore non-shared object files. */
				if (!g_str_has_suffix(dent->d_name, ".so")
				    && !strstr(dent->d_name, ".so."))
					continue;
				path = g_strjoin("/", entry, dent->d_name,
						 NULL);
				if (load(regi, path))
					watch(ifd, path);
				g_free(path);
			} /* while */
			closedir(hdir);
			watch(ifd, entry);
		} else if (errno == ENOTDIR) {
			if (load(regi, entry))
				watch(ifd, entry);
		} else if (errno == ENOENT)
			load(regi, entry);
		else
			g_error("%s: %m", entry);
	} /* for */

	/* Watch $ifd. */
	if (ifd >= 0)
		g_io_add_watch(g_io_channel_unix_new(ifd), G_IO_IN,
			       (GIOFunc)renaissance, argv);

	/* The main loop should not return. */
	g_main_loop_run(g_main_loop_new(NULL, FALSE));
	return 1;
}
コード例 #10
0
ファイル: gvfsmountinfo.c プロジェクト: DarkProfit/gvfs
static void
on_autorun_loaded (GObject      *source_object,
                   GAsyncResult *res,
                   gpointer      user_data)
{
  GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
  GFile *autorun_file;
  gchar *content;
  gchar *relative_icon_path;
  gsize content_length;
  GError *error;

  relative_icon_path = NULL;

  autorun_file = G_FILE (source_object);

  error = NULL;
  if (g_file_load_contents_finish (autorun_file,
                                   res,
                                   &content,
                                   &content_length,
                                   NULL,
                                   &error))
    {
      /* Scan through for an "icon=" line. Can't use GKeyFile,
       * because .inf files aren't always valid key files
       **/
      GRegex *icon_regex;
      GMatchInfo *match_info;

      /* [^,] is because sometimes the icon= line
       * has a comma at the end
       **/
      icon_regex = g_regex_new ("icon=([^,\\r\\n]+)",
                                G_REGEX_CASELESS, 0, NULL);
      g_regex_match (icon_regex, content, 0,
                     &match_info);

      /* Even if there are multiple matches, pick only the
       * first.
       **/
      if (g_match_info_matches (match_info))
        {
          gchar *chr;
          gchar *word = g_match_info_fetch (match_info, 1);

          /* Replace '\' with '/' */
          while ((chr = strchr (word, '\\')) != NULL)
            *chr = '/';

          /* If the file name's not valid UTF-8,
           * don't even try to load it
           **/
          if (g_utf8_validate (word, -1, NULL))
            {
              relative_icon_path = word;
            }
          else
            {
              /* TODO: mark for translation. Strictly, this isn't very important; this string
               * will never be displayed since all current users of g_vfs_mount_info_query_autorun_info()
               * passes NULL for the GError**.
               */
              error = g_error_new_literal (G_IO_ERROR,
                                           G_IO_ERROR_FAILED,
                                           "Icon name is not valid UTF-8");
              g_free (word);
            }
        }

      g_match_info_free (match_info);

      g_regex_unref (icon_regex);
      g_free (content);
    }

  /* some autorun.in points to the .exe file for the icon; make sure we avoid using that */
  if (relative_icon_path != NULL)
    {
      if (!g_str_has_suffix (relative_icon_path, ".exe"))
        {
          GFile *root;

          root = g_file_get_parent (autorun_file);

          _g_find_file_insensitive_async (root,
                                          relative_icon_path,
                                          NULL,
                                          on_icon_file_located,
                                          simple);

          g_object_unref (root);
        }
      else
        {
          /* TODO: mark for translation. Strictly, this isn't very important; this string
           * will never be displayed since all current users of g_vfs_mount_info_query_autorun_info()
           * passes NULL for the GError**.
           */
          error = g_error_new_literal (G_IO_ERROR,
                                       G_IO_ERROR_FAILED,
                                       "Icon is an .exe file");
        }
    }

  if (error != NULL)
    {
      g_simple_async_result_set_from_error (simple, error);
      g_simple_async_result_complete_in_idle (simple);
      g_object_unref (simple);
      g_error_free (error);
    }

  g_free (relative_icon_path);
}
コード例 #11
0
ファイル: plugin.c プロジェクト: balabit/syslog-ng-3.3
void
plugin_list_modules(FILE *out, gboolean verbose)
{
  GlobalConfig *cfg;
  GModule *mod;
  gchar **mod_paths;
  gint i, j, k;
  gboolean first = TRUE;

  cfg = cfg_new(CFG_CURRENT_VERSION);
  mod_paths = g_strsplit(module_path, ":", 0);
  for (i = 0; mod_paths[i]; i++)
    {
      GDir *dir;
      const gchar *fname;

      dir = g_dir_open(mod_paths[i], 0, NULL);
      if (!dir)
        continue;
      while ((fname = g_dir_read_name(dir)))
        {
          if (g_str_has_suffix(fname, G_MODULE_SUFFIX))
            {
              gchar *module_name;
              ModuleInfo *module_info;
              gboolean success;

              if (g_str_has_prefix(fname, "lib"))
                fname += 3;
              module_name = g_strndup(fname, (gint) (strlen(fname) - strlen(G_MODULE_SUFFIX) - 1));

              mod = plugin_dlopen_module(module_name, module_path);
              if (mod)
                success = g_module_symbol(mod, "module_info", (gpointer *) &module_info);
              else
                success = FALSE;
              if (verbose)
                {
                  fprintf(out, "Module: %s\n", module_name);
                  if (mod)
                    {
                      if (!success || !module_info)
                        {
                          fprintf(out, "Status: Unable to resolve module_info variable, probably not a syslog-ng module\n");
                        }
                      else
                        {
                          if (strcmp(module_info->canonical_name, module_name) != 0)
                            {
                              fprintf(out, "Status: This module is to be loaded under the name %s instead of %s\n", module_info->canonical_name, module_name);
                            }
                          else
                            {
                              gchar **lines;

                              fprintf(out, "Status: ok\n"
                                           "Version: %s\n"
                                           "Core-Revision: %s\n"
                                           "Description:\n", module_info->version, module_info->core_revision);

                              lines = g_strsplit(module_info->description, "\n", 0);
                              for (k = 0; lines[k]; k++)
                                fprintf(out, "  %s\n", lines[k][0] ? lines[k] : ".");
                              g_strfreev(lines);

                              fprintf(out, "Plugins:\n");
                              for (j = 0; j < module_info->plugins_len; j++)
                                {
                                  Plugin *plugin = &module_info->plugins[j];

                                  fprintf(out, "  %-15s %s\n", cfg_lexer_lookup_context_name_by_type(plugin->type), plugin->name);
                                }
                            }
                        }
                      g_module_close(mod);
                    }
                  else
                    {
                      fprintf(out, "Status: Unable to dlopen shared object, probably not a syslog-ng module\n");
                    }
                  fprintf(out, "\n");
                }
              else if (success && module_info)
                {
                  fprintf(out, "%s%s", first ? "" : ",", module_name);
                  first = FALSE;
                }
              g_free(module_name);
            }
        }
      g_dir_close(dir);
    }
  g_strfreev(mod_paths);
  if (!verbose)
    fprintf(out, "\n");
}
コード例 #12
0
ファイル: appmenugen.c プロジェクト: kostelnik/jwmtools
int main(int argc, char * argv[]) {
  ///g_warning("Sample warning");
  ///g_message("Loading *.desktop files");
  
  // pointer array for storing menu items
  GPtrArray *items = g_ptr_array_new ();
  
  // read all files from applications directory
  gchar *path = g_strdup("/usr/share/applications");
  GDir *d = g_dir_open(path,0,NULL);
  const gchar *n;
  while ( (n = g_dir_read_name(d)) ) {
    // get filename from dir content
    gchar *fn = g_build_filename(path,n,NULL);
    //printf("--> fn=%s\n",fn);
    // is it .desktop file
    if (!g_str_has_suffix(fn,".desktop"))
      continue;
    // load .desktop file
    GKeyFile *kf = g_key_file_new();
    gboolean b = g_key_file_load_from_file(kf, fn, G_KEY_FILE_NONE, NULL);
    if (!b) {
        fprintf(stderr, "error: cannot load .desktop file %s\n", fn);
        g_key_file_free(kf);
        continue;
    }
    g_assert(b);
    // load categories
    gsize length = 0;
    char **cats = g_key_file_get_string_list(kf,"Desktop Entry","Categories",&length,NULL);
    gchar *name = g_key_file_get_value(kf,"Desktop Entry","Name",NULL);
    gchar *exec = g_key_file_get_value(kf,"Desktop Entry","Exec",NULL);
 
    fix(exec);

    gchar *icon = g_key_file_get_value(kf,"Desktop Entry","Icon",NULL);
    gchar *type = g_key_file_get_value(kf,"Desktop Entry","Type",NULL);
    gboolean no_display = g_key_file_get_boolean(kf,"Desktop Entry","NoDisplay",NULL);
    // sort it to categories in application menu

    // determine best matching category
    ItemCategory c = icOther;
    for (guint i=0; i<length; i++) {
      //printf("  Category[%d]: %s\n",i,cats[i]);
      if (strstr("DesktopSettings, HardwareSettings, Monitor, PackageManager, Settings, System, X-GNOME-NetworkSettings, X-GNOME-PersonalSettings, X-LXDE-Settings, X-SuSE-ControlCenter-System, X-XFCE",cats[i]))
        c = icSettings;
      if (strstr("ArcadeGame, BlocksGame, BoardGame, CardGame, Game, LogicGame",cats[i]))
        c = icGames;
      if (strstr("Archiving, Compression, Core, DiscBurning, Documentation, FileManager, TerminalEmulator, Utility",cats[i]))
        c = icUtility;
      if (strstr("Astronomy, Dictionary, Education, Math, Science, Translation",cats[i]))
        c = icScienceEducation;
      if (strstr("Audio, AudioVideo, AudioVideoEditing, Mixer, Player, Recorder, Video",cats[i]))
        c = icAudioVideo;
      if (strstr("Calculator, Calendar, ContactManagement, Office, Presentation, Printing, TextEditor, Spreadsheet, WordProcessor",cats[i]))
        c = icOffice;
      if (strstr("Development, Emulator, Engineering, GTK, GUIDesigner, IDE, Qt",cats[i]))
        c = icDevelopment;
      if (strstr("Email, FileTransfer, Chat, InstantMessaging, Internet, IRCClient, Network, P2P, RemoteAccess, Security, WebBrowser",cats[i]))
        c = icInternet;
      if (strstr("Graphics, Photography, RasterGraphics, Scanning, VectorGraphics, Viewer, 2DGraphics, 3DGraphics",cats[i]))
        c = icGraphics;
    }
    
    // add items to array
    if ((!no_display)&&(name)&&(exec)&&(icon))
      g_ptr_array_add (items, item_new(c, name, exec, icon));

    // free temp vars
    g_strfreev(cats);
    g_free(name);
    g_free(exec);
    g_free(icon);
    g_free(type);
    g_key_file_free(kf);
  }
  // close dir
  g_dir_close(d);

  // sort items by categories and by name
  g_ptr_array_sort(items,&item_compare);
  
  // print what we get
  printf("<?xml version=\"1.0\"?>\n");
  printf("<JWM>\n");
  //jwm_category(items,"Accessibility",icAccessibility);
  jwm_category(items,"Audio and video",icAudioVideo);
  jwm_category(items,"Development",icDevelopment);
  jwm_category(items,"Games",icGames);
  jwm_category(items,"Graphics",icGraphics);
  jwm_category(items,"Internet",icInternet);
  jwm_category(items,"Office",icOffice);
  jwm_category(items,"Other",icOther);
  jwm_category(items,"Science and education",icScienceEducation);
  jwm_category(items,"Settings",icSettings);
  jwm_category(items,"Utility",icUtility);
  printf("</JWM>\n");
    
  ///g_error("dont know what to do now");
  return 0;
}
コード例 #13
0
ファイル: myloader.c プロジェクト: cezmunsta/mydumper
void restore_data(MYSQL *conn, char *database, char *table, const char *filename, gboolean is_schema, gboolean need_use) {
	void *infile;
	gboolean is_compressed= FALSE;
	gboolean eof= FALSE;
	guint query_counter= 0;
	GString *data= g_string_sized_new(512);

	gchar* path= g_build_filename(directory, filename, NULL);

	if (!g_str_has_suffix(path, ".gz")) {
		infile= g_fopen(path, "r");
		is_compressed= FALSE;
	} else {
		infile= (void*) gzopen(path, "r");
		is_compressed= TRUE;
	}

	if (!infile) {
		g_critical("cannot open file %s (%d)", filename, errno);
		errors++;
		return;
	}


	if(need_use){
		gchar *query= g_strdup_printf("USE `%s`", db ? db : database);

		if (mysql_query(conn, query)) {
			g_critical("Error switching to database %s whilst restoring table %s", db ? db : database, table);
			g_free(query);
			errors++;
			return;
		}

		g_free(query);
	}

	
	if (!is_schema)
		mysql_query(conn, "START TRANSACTION");

	while (eof == FALSE) {
		if (read_data(infile, is_compressed, data, &eof)) {
			// Search for ; in last 5 chars of line
			if (g_strrstr(&data->str[data->len >= 5 ? data->len - 5 : 0], ";\n")) { 
				if (mysql_real_query(conn, data->str, data->len)) {
					g_critical("Error restoring %s.%s from file %s: %s", db ? db : database, table, filename, mysql_error(conn));
					errors++;
					return;
				}
				query_counter++;
				if (!is_schema &&(query_counter == commit_count)) {
					query_counter= 0;
					if (mysql_query(conn, "COMMIT")) {
						g_critical("Error committing data for %s.%s: %s", db ? db : database, table, mysql_error(conn));
						errors++;
						return;
					}
					mysql_query(conn, "START TRANSACTION");
				}

				g_string_set_size(data, 0);
			}
		} else {
			g_critical("error reading file %s (%d)", filename, errno);
			errors++;
			return;
		}
	}
	if (!is_schema && mysql_query(conn, "COMMIT")) {
		g_critical("Error committing data for %s.%s from file %s: %s", db ? db : database, table, filename, mysql_error(conn));
		errors++;
	}
	g_string_free(data, TRUE);
	g_free(path);
	if (!is_compressed) {
		fclose(infile);
	} else {
		gzclose((gzFile)infile);
	}	
	return;
}
コード例 #14
0
ファイル: tle-update.c プロジェクト: nfischer/gpredict
/** \brief Update TLE files from local files.
 *  \param dir Directory where files are located.
 *  \param filter File filter, e.g. *.txt (not used at the moment!)
 *  \param silent TRUE if function should execute without graphical status indicator.
 *  \param label1 Activity label (can be NULL)
 *  \param label2 Statistics label (can be NULL)
 *  \param progress Pointer to progress indicator.
 *  \param init_prgs Initial value of progress indicator, e.g 0.5 if we are updating
 *                   from network.
 *
 * This function is used to update the TLE data from local files.
 *
 * Functional description: TBD
 *
 */
void tle_update_from_files (const gchar *dir, const gchar *filter,
                            gboolean silent, GtkWidget *progress,
                            GtkWidget *label1, GtkWidget *label2)
{
    static GMutex tle_file_in_progress;

    GHashTable  *data;        /* hash table with fresh TLE data */
    GDir        *cache_dir;   /* directory to scan fresh TLE */
    GDir        *loc_dir;     /* directory for gpredict TLE files */
    GError      *err = NULL;
    gchar       *text;
    gchar       *ldname;
    gchar       *userconfdir;
    const gchar *fnam;
    guint        num = 0;
    guint        updated,updated_tmp;
    guint        skipped,skipped_tmp;
    guint        nodata,nodata_tmp;
    guint        newsats = 0;
    guint        total,total_tmp;
    gdouble      fraction = 0.0;
    gdouble      start = 0.0;

    (void) filter; /* avoid unused parameter compiler warning */

    if (g_mutex_trylock(&tle_file_in_progress) == FALSE)
    {
        sat_log_log (SAT_LOG_LEVEL_ERROR,
                     _("%s: A TLE update process is already running. Aborting."),
                     __FUNCTION__);

        return;
    }

    /* create hash table */
    data = g_hash_table_new_full (g_int_hash, g_int_equal, g_free, free_new_tle);

    /* open directory and read files one by one */
    cache_dir = g_dir_open (dir, 0, &err);

    if (err != NULL) {

        /* send an error message */
        sat_log_log (SAT_LOG_LEVEL_ERROR,
                     _("%s: Error opening directory %s (%s)"),
                     __FUNCTION__, dir, err->message);

        /* insert error message into the status string, too */
        if (!silent && (label1 != NULL)) {
            text = g_strdup_printf (_("<b>ERROR</b> opening directory %s\n%s"),
                                    dir, err->message);

            gtk_label_set_markup (GTK_LABEL (label1), text);
            g_free (text);

        }

        g_clear_error (&err);
        err = NULL;
    }
    else {

        /* scan directory for tle files */
        while ((fnam = g_dir_read_name (cache_dir)) != NULL) {
            /* check that we got a TLE file */
            if (is_tle_file(dir, fnam)) {
                
                /* status message */
                if (!silent && (label1 != NULL)) {
                    text = g_strdup_printf (_("Reading data from %s"), fnam);
                    gtk_label_set_text (GTK_LABEL (label1), text);
                    g_free (text);

                    /* Force the drawing queue to be processed otherwise there will
                        not be any visual feedback, ie. frozen GUI
                        - see Gtk+ FAQ http://www.gtk.org/faq/#AEN602
                    */
                    while (g_main_context_iteration (NULL, FALSE));

                    /* give user a chance to follow progress */
                    g_usleep (G_USEC_PER_SEC / 100);
                }

                /* now, do read the fresh data */
                num = read_fresh_tle (dir, fnam, data);
            } else {
                num = 0;
            }

            if (num < 1) {
                sat_log_log (SAT_LOG_LEVEL_ERROR,
                             _("%s: No valid TLE data found in %s"),
                             __FUNCTION__, fnam);
            }
            else {
                sat_log_log (SAT_LOG_LEVEL_INFO,
                             _("%s: Read %d sats from %s into memory"),
                             __FUNCTION__, num, fnam);
            }
        }

        /* close directory since we don't need it anymore */
        g_dir_close (cache_dir);

        /* now we load each .sat file and update if we have new data */
        userconfdir = get_user_conf_dir ();
        ldname = g_strconcat (userconfdir, G_DIR_SEPARATOR_S, "satdata", NULL);
        g_free (userconfdir);

        /* open directory and read files one by one */
        loc_dir = g_dir_open (ldname, 0, &err);

        if (err != NULL) {

            /* send an error message */
            sat_log_log (SAT_LOG_LEVEL_ERROR,
                         _("%s: Error opening directory %s (%s)"),
                         __FUNCTION__, dir, err->message);

            /* insert error message into the status string, too */
            if (!silent && (label1 != NULL)) {
                text = g_strdup_printf (_("<b>ERROR</b> opening directory %s\n%s"),
                                        dir, err->message);

                gtk_label_set_markup (GTK_LABEL (label1), text);
                g_free (text);
            }

            g_clear_error (&err);
            err = NULL;
        }
        else {
            /* clear statistics */
            updated = 0;
            skipped = 0;
            nodata = 0;
            total = 0;

            /* get initial value of progress indicator */
            if (progress != NULL)
                start = gtk_progress_bar_get_fraction (GTK_PROGRESS_BAR (progress));

            /* This is insane but I don't know how else to count the number of sats */
            num = 0;
            while ((fnam = g_dir_read_name (loc_dir)) != NULL) {
                /* only consider .sat files */
                if (g_str_has_suffix (fnam, ".sat")) {
                    num++;
                }
            }

            g_dir_rewind (loc_dir);

            /* update TLE files one by one */
            while ((fnam = g_dir_read_name (loc_dir)) != NULL) {
                /* only consider .sat files */
                if (g_str_has_suffix (fnam, ".sat")) {

                    /* clear stat bufs */
                    updated_tmp = 0;
                    skipped_tmp = 0;
                    nodata_tmp = 0;
                    total_tmp = 0;

                    /* update TLE data in this file */
                    update_tle_in_file (ldname, fnam, data, 
                                        &updated_tmp,
                                        &skipped_tmp,
                                        &nodata_tmp,
                                        &total_tmp);

                    /* update statistics */
                    updated += updated_tmp;
                    skipped += skipped_tmp;
                    nodata  += nodata_tmp;
                    total   = updated+skipped+nodata;

                    if (!silent) {

                        if (label1 != NULL) {
                            gtk_label_set_text (GTK_LABEL (label1),
                                                _("Updating data..."));
                        }

                        if (label2 != NULL) {
                            text = g_strdup_printf (_("Satellites updated:\t %d\n"\
                                                      "Satellites skipped:\t %d\n"\
                                                      "Missing Satellites:\t %d\n"),
                                                    updated, skipped, nodata);
                            gtk_label_set_text (GTK_LABEL (label2), text);
                            g_free (text);
                        }

                        if (progress != NULL) {
                            /* two different calculations for completeness depending on whether 
                               we are adding new satellites or not. */
                            if (sat_cfg_get_bool (SAT_CFG_BOOL_TLE_ADD_NEW)) {
                                /* In this case we are possibly processing more than num satellites
                                   How many more? We do not know yet.  Worst case is g_hash_table_size more.
                                   
                                   As we update skipped and updated we can reduce the denominator count
                                   as those are in both pools (files and hash table). When we have processed 
                                   all the files, updated and skipped are completely correct and the progress 
                                   is correct. It may be correct sooner if the missed satellites are the 
                                   last files to process.
                                   
                                   Until then, if we eliminate the ones that are updated and skipped from being 
                                   double counted, our progress will shown will always be less or equal to our 
                                   true progress since the denominator will be larger than is correct.
                                   
                                   Advantages to this are that the progress bar does not stall close to 
                                   finished when there are a large number of new satellites.
                                */
                                fraction = start + (1.0-start) * ((gdouble) total) / 
                                    ((gdouble) num + g_hash_table_size(data) - updated - skipped);
                            } else {
                                /* here we only process satellites we have have files for so divide by num */
                                fraction = start + (1.0-start) * ((gdouble) total) / ((gdouble) num);
                            }
                            gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (progress),
                                                           fraction);

                        }

                        /* update the gui only every so often to speed up the process */
                        /* 47 was selected empirically to balance the update looking smooth but not take too much time. */
                        /* it also tumbles all digits in the numbers so that there is no obvious pattern. */
                        /* on a developer machine this improved an update from 5 minutes to under 20 seconds. */
                        if (total%47 == 0) {
                            /* Force the drawing queue to be processed otherwise there will
                               not be any visual feedback, ie. frozen GUI
                               - see Gtk+ FAQ http://www.gtk.org/faq/#AEN602
                            */
                            while (g_main_context_iteration (NULL, FALSE));
                        
                            /* give user a chance to follow progress */
                            g_usleep (G_USEC_PER_SEC / 1000);
                        }
                    }
                }
            }
            
            /* force gui update */
            while (g_main_context_iteration (NULL, FALSE));


            /* close directory handle */
            g_dir_close (loc_dir);
            
            /* see if we have any new sats that need to be added */
            if (sat_cfg_get_bool (SAT_CFG_BOOL_TLE_ADD_NEW)) {
                
                newsats = add_new_sats (data);
                
                if (!silent && (label2 != NULL)) {
                    text = g_strdup_printf (_("Satellites updated:\t %d\n"\
                                              "Satellites skipped:\t %d\n"\
                                              "Missing Satellites:\t %d\n"\
                                              "New Satellites:\t\t %d"),
                                            updated, skipped, nodata, newsats);
                    gtk_label_set_text (GTK_LABEL (label2), text);
                    g_free (text);

                }
                
                sat_log_log (SAT_LOG_LEVEL_INFO,
                             _("%s: Added %d new satellites to local database"),
                             __FUNCTION__, newsats);
            }

            /* store time of update if we have updated something */
            if ((updated > 0) || (newsats > 0)) {
                GTimeVal tval;
                
                g_get_current_time (&tval);
                sat_cfg_set_int (SAT_CFG_INT_TLE_LAST_UPDATE, tval.tv_sec);
            }

        }

        g_free (ldname);

        sat_log_log (SAT_LOG_LEVEL_INFO,
                     _("%s: TLE elements updated."),
                     __FUNCTION__);
    }

    /* destroy hash tables */
    g_hash_table_destroy (data);

    g_mutex_unlock(&tle_file_in_progress);
}
コード例 #15
0
/**
 * main:
 **/
int
main (int argc, char *argv[])
{
	GError *error = NULL;
	GOptionContext *context;
	gchar *options_help;
	gboolean ret;
	gchar *filename = NULL;
	PkClient *client = NULL;
	PkControl *control = NULL;
	PkBitfield roles;
	gchar *tempdir = NULL;
	gboolean exists;
	gboolean overwrite;
	gchar **excludes = NULL;
	gchar *package_id = NULL;
	PkServicePack *pack = NULL;
	gchar *directory = NULL;
	gchar *package_list = NULL;
	gchar *package = NULL;
	gboolean updates = FALSE;
	gint retval = 1;

	const GOptionEntry options[] = {
		{ "with-package-list", 'l', 0, G_OPTION_ARG_STRING, &package_list,
			/* TRANSLATORS: we can exclude certain packages (glibc) when we know they'll exist on the target */
			_("Set the file name of dependencies to be excluded"), NULL},
		{ "output", 'o', 0, G_OPTION_ARG_STRING, &directory,
			/* TRANSLATORS: the output location */
			_("The output file or directory (the current directory is used if omitted)"), NULL},
		{ "package", 'p', 0, G_OPTION_ARG_STRING, &package,
			/* TRANSLATORS: put a list of packages in the pack */
			_("The package to be put into the service pack"), NULL},
		{ "updates", 'u', 0, G_OPTION_ARG_NONE, &updates,
			/* TRANSLATORS: put all pending updates in the pack */
			_("Put all updates available in the service pack"), NULL},
		{ NULL}
	};

	setlocale (LC_ALL, "");
	bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);

#if (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION < 31)
	if (! g_thread_supported ())
		g_thread_init (NULL);
#endif

	g_type_init ();

	/* do stuff on ctrl-c */
	signal (SIGINT, pk_generate_pack_sigint_cb);

	context = g_option_context_new ("PackageKit Pack Generator");
	g_option_context_add_main_entries (context, options, NULL);
	g_option_context_add_group (context, pk_debug_get_option_group ());
	g_option_context_parse (context, &argc, &argv, NULL);
	/* Save the usage string in case command parsing fails. */
	options_help = g_option_context_get_help (context, TRUE, NULL);
	g_option_context_free (context);

	client = pk_client_new ();
	pack = pk_service_pack_new ();
	cancellable = g_cancellable_new ();
	progressbar = pk_progress_bar_new ();
	pk_progress_bar_set_size (progressbar, 25);
	pk_progress_bar_set_padding (progressbar, 20);

	/* neither options selected */
	if (package == NULL && !updates) {
		/* TRANSLATORS: This is when the user fails to supply the correct arguments */
		g_print ("%s\n", _("Neither --package or --updates option selected."));
		retval = 1;
		goto out;
	}

	/* both options selected */
	if (package != NULL && updates) {
		/* TRANSLATORS: This is when the user fails to supply just one argument */
		g_print ("%s\n", _("Both options selected."));
		retval = 1;
		goto out;
	}

	/* no argument given to --package */
	if (package != NULL && package[0] == '\0') {
		/* TRANSLATORS: This is when the user fails to supply the package name */
		g_print ("%s\n", _("A package name is required"));
		retval = 1;
		goto out;
	}

	/* no argument given to --output */
	if (directory != NULL && directory[0] == '\0') {
		/* TRANSLATORS: This is when the user fails to supply the output */
		g_print ("%s\n", _("A output directory or file name is required"));
		retval = 1;
		goto out;
	}

	/* fall back to the system copy */
	if (package_list == NULL)
		package_list = g_strdup (PK_SYSTEM_PACKAGE_LIST_FILENAME);

	/* fall back to CWD */
	if (directory == NULL)
		directory = g_get_current_dir ();

	/* are we dumb and can't do some actions */
	control = pk_control_new ();
	ret = pk_control_get_properties (control, NULL, &error);
	if (!ret) {
		/* TRANSLATORS: This is when the daemon is not-installed/broken and fails to startup */
		g_print ("%s: %s\n", _("The daemon failed to startup"), error->message);
		goto out;
	}

	/* get data */
	g_object_get (control,
		      "roles", &roles,
		      NULL);

	if (!pk_bitfield_contain (roles, PK_ROLE_ENUM_GET_DEPENDS)) {
		/* TRANSLATORS: This is when the backend doesn't have the capability to get-depends */
		g_print ("%s (GetDepends)\n", _("The package manager cannot perform this type of operation."));
		retval = 1;
		goto out;
	}
	if (!pk_bitfield_contain (roles, PK_ROLE_ENUM_DOWNLOAD_PACKAGES)) {
		/* TRANSLATORS: This is when the backend doesn't have the capability to download */
		g_print ("%s (DownloadPackage)\n", _("The package manager cannot perform this type of operation."));
		retval = 1;
		goto out;
	}

#ifndef HAVE_ARCHIVE_H
	/* TRANSLATORS: This is when the distro didn't include libarchive support into PK */
	g_print ("%s\n", _("Service packs cannot be created as PackageKit was not built with libarchive support."));
	goto out;
#endif

	/* the user can speciify a complete path */
	ret = g_file_test (directory, G_FILE_TEST_IS_DIR);
	if (ret) {
		filename = pk_generate_pack_get_filename (package, directory);
	} else {
		if (!g_str_has_suffix (directory, PK_SERVICE_PACK_FILE_EXTENSION)) {
			/* TRANSLATORS: the user specified an absolute path, but didn't get the extension correct */
			g_print ("%s .%s \n", _("If specifying a file, the service pack name must end with"), PK_SERVICE_PACK_FILE_EXTENSION);
			retval = 1;
			goto out;
		}
		filename = g_strdup (directory);
	}

	/* download packages to a temporary directory */
	tempdir = g_build_filename (g_get_tmp_dir (), "pack", NULL);

	/* check if file exists before we overwrite it */
	exists = g_file_test (filename, G_FILE_TEST_EXISTS);

	/*ask user input*/
	if (exists) {
		/* TRANSLATORS: This is when file already exists */
		overwrite = pk_console_get_prompt (_("A pack with the same name already exists, do you want to overwrite it?"), FALSE);
		if (!overwrite) {
			/* TRANSLATORS: This is when the pack was not overwritten */
			g_print ("%s\n", _("The pack was not overwritten."));
			retval = 1;
			goto out;
		}
	}

	/* get rid of temp directory if it already exists */
	g_rmdir (tempdir);

	/* make the temporary directory */
	retval = g_mkdir_with_parents (tempdir, 0777);
	if (retval != 0) {
		/* TRANSLATORS: This is when the temporary directory cannot be created, the directory name follows */
		g_print ("%s '%s'\n", _("Failed to create directory:"), tempdir);
		retval = 1;
		goto out;
	}
	pk_service_pack_set_temp_directory (pack, tempdir);

	/* get the exclude list */
	excludes = NULL;
#if 0
	ret = pk_obj_list_from_file (PK_OBJ_LIST(list), package_list);
	if (!ret) {
		/* TRANSLATORS: This is when the list of packages from the remote computer cannot be opened */
		g_print ("%s: '%s'\n", _("Failed to open package list."), package_list);
		retval = 1;
		goto out;
	}
#endif

	/* resolve package name to package_id */
	if (!updates) {
		/* TRANSLATORS: The package name is being matched up to available packages */
		g_print ("%s\n", _("Finding package name."));
		package_id = pk_console_resolve_package (client, pk_bitfield_value (PK_FILTER_ENUM_NONE), package, &error);
		if (package_id == NULL) {
			/* TRANSLATORS: This is when the package cannot be found in any software source. The detailed error follows */
			g_print (_("Failed to find package '%s': %s"), package, error->message);
			g_error_free (error);
			retval = 1;
			goto out;
		}
	}

	/* TRANSLATORS: This is telling the user we are in the process of making the pack */
	g_print ("%s\n", _("Creating service pack..."));
	if (updates)
		ret = pk_generate_pack_create_for_updates (pack, filename, excludes, &error);
	else {
		gchar **package_ids;
		package_ids = pk_package_ids_from_id (package_id);
		ret = pk_generate_pack_create_for_package_ids (pack, filename, package_ids, excludes, &error);
		g_strfreev (package_ids);
	}

	/* no more progress */
	pk_progress_bar_end (progressbar);

	if (ret) {
		/* TRANSLATORS: we succeeded in making the file */
		g_print (_("Service pack created '%s'"), filename);
		g_print ("\n");
		retval = 0;
	} else {
		/* TRANSLATORS: we failed to make te file */
		g_print (_("Failed to create '%s': %s"), filename, error->message);
		g_print ("\n");
		g_error_free (error);
	}

out:
	/* get rid of temp directory */
	g_rmdir (tempdir);

	g_object_unref (cancellable);
	if (progressbar != NULL)
		g_object_unref (progressbar);
	if (pack != NULL)
		g_object_unref (pack);
	if (client != NULL)
		g_object_unref (client);
	if (control != NULL)
		g_object_unref (control);
	g_free (tempdir);
	g_free (filename);
	g_free (package_id);
	g_free (directory);
	g_free (package_list);
	g_free (options_help);
	g_strfreev (excludes);
	return retval;
}
コード例 #16
0
ファイル: utils_str.c プロジェクト: wazari972/Grisbi
/**
 * recherche des mots séparés par des jokers "%*" dans une chaine
 *
 * \param haystack
 * \param needle
 *
 * \return TRUE si trouvé FALSE autrement
 */
gboolean gsb_string_is_trouve ( const gchar *payee_name, const gchar *needle )
{
    gchar **tab_str;
    gchar *tmpstr;
    gint i;
    gboolean is_prefix = FALSE, is_suffix = FALSE;

    if ( g_strstr_len ( needle, -1, "%" ) == NULL &&
                        g_strstr_len ( needle, -1, "*" ) == NULL )
    {
        if ( my_strcasecmp ( payee_name, needle ) == 0 )
            return TRUE;
        else
            return FALSE;
    }
    if ( g_str_has_prefix ( needle, "%" ) == FALSE &&
                        g_str_has_prefix ( needle, "*" ) == FALSE )
        is_prefix = TRUE;

    if ( g_str_has_suffix ( needle, "%" ) == FALSE &&
                        g_str_has_suffix ( needle, "*" ) == FALSE )
        is_suffix = TRUE;

    if ( is_prefix && is_suffix )
    {
        tab_str = g_strsplit_set ( needle, "%*", 0 );
        is_prefix = g_str_has_prefix ( payee_name, tab_str[0] );
        is_suffix = g_str_has_suffix ( payee_name, tab_str[1] );
        if ( is_prefix && is_suffix )
            return TRUE;
        else
            return FALSE;
    }
    else if ( is_prefix && ! is_suffix )
    {
        tmpstr = gsb_string_supprime_joker ( needle );
        is_prefix = g_str_has_prefix (payee_name, tmpstr);
        g_free (tmpstr);
        return is_prefix;
    }
    else if ( is_suffix && ! is_prefix )
    {
        tmpstr = gsb_string_supprime_joker ( needle );
        is_suffix = g_str_has_suffix (payee_name, tmpstr);
        g_free (tmpstr);
        return is_suffix;
    }

    tab_str = g_strsplit_set ( needle, "%*", 0 );

    for (i = 0; tab_str[i] != NULL; i++)
	{
        if ( tab_str[i] && strlen (tab_str[i]) > 0)
        {
            if ( g_strstr_len (payee_name, -1, tab_str[i]))
            {
                g_strfreev ( tab_str );
                return TRUE;
            }
        }
    }

    g_strfreev ( tab_str );

    return FALSE;
}
コード例 #17
0
ファイル: medialib-runner.c プロジェクト: vdust/xmms2-devel
static void
filter_databases (const gchar *path, xmmsv_t *list)
{
	if (g_str_has_suffix (path, ".s4"))
		xmmsv_list_append_string (list, path);
}
コード例 #18
0
ファイル: domain.c プロジェクト: adnandzebic/dwb
gboolean 
domain_match(char **domains, const char *host, const char *base_domain) 
{
    g_return_val_if_fail(domains != NULL, false);
    g_return_val_if_fail(host != NULL, false);
    g_return_val_if_fail(base_domain != NULL, false);
    g_return_val_if_fail(g_str_has_suffix(host, base_domain), false);

    const char *subdomains[SUBDOMAIN_MAX];
    int sdc = 0;

    gboolean domain_exc = false;
    gboolean has_positive = false;
    gboolean has_exception = false;
    gboolean found_positive = false;
    gboolean found_exception = false;

    char *real_domain;
    char *nextdot;
    /* extract subdomains */
    subdomains[sdc++] = host;
    while (g_strcmp0(host, base_domain)) 
    {
        nextdot = strchr(host, '.');
        host = nextdot + 1;
        subdomains[sdc++] = host;
        if (sdc == SUBDOMAIN_MAX-1)
            break;
    }
    subdomains[sdc++] = NULL;

    for (int k=0; domains[k]; k++) 
    {
        for (int j=0; subdomains[j]; j++) 
        {
            real_domain = domains[k];
            if (*real_domain == '~') 
            {
                domain_exc = true;
                real_domain++;
                has_exception = true;
            }
            else 
            {
                domain_exc = false;
                has_positive = true;
            }

            if (!g_strcmp0(subdomains[j], real_domain)) 
            {
                if (domain_exc) 
                    found_exception = true;
                else 
                    found_positive = true;
            }
        }
    }
    if ((has_positive && found_positive && !found_exception) || (has_exception && !has_positive && !found_exception))
        return true;

    return false;
}/*}}}*/
コード例 #19
0
ファイル: plugin.c プロジェクト: VujinovM/anjuta
static void
toggle_comment_singleline (CppJavaPlugin *plugin, IAnjutaEditor *editor,
                           gint line)
{
    IAnjutaIterable *begin, *end, *begin_copy, *end_copy;
    gchar *text, *text_stripped, **text_diff = NULL;

    begin = ianjuta_editor_get_line_begin_position (editor, line, NULL);
    end = ianjuta_editor_get_line_end_position (editor, line, NULL);
    begin_copy = ianjuta_iterable_clone (begin, NULL);
    end_copy = ianjuta_iterable_clone (end, NULL);

    if (is_commented_multiline (editor, begin_copy, end_copy))
    {
        toggle_comment_multiline (editor, begin_copy, end_copy);
        g_object_unref (begin);
        g_object_unref (end);
        g_object_unref (begin_copy);
        g_object_unref (end_copy);
        return;
    }
    g_object_unref (begin_copy);
    g_object_unref (end_copy);

    text = ianjuta_editor_get_text (editor, begin, end, NULL);
    text_stripped = g_strstrip (g_strdup (text));
    text_diff = g_strsplit (text, text_stripped, 2);

    if (plugin->current_language &&
        (g_str_equal (plugin->current_language, "C")))
    {
        if (g_str_has_prefix (text_stripped, "/*") &&
            g_str_has_suffix (text_stripped, "*/"))
        {
            ianjuta_editor_erase (editor, begin, end, NULL);
            ianjuta_editor_insert (editor, begin, text_stripped + 2,
                                   (strlen (text_stripped) - 4), NULL);
            if (text_diff != NULL)
                ianjuta_editor_insert (editor, begin, *text_diff, -1, NULL);
        }
        else
        {
            ianjuta_editor_insert (editor, end, "*/", -1, NULL);
            ianjuta_editor_insert (editor, begin, "/*", -1, NULL);
        }
    }
    else
    {
        if (g_str_has_prefix (text_stripped, "//"))
        {
            ianjuta_editor_erase (editor, begin, end, NULL);
            ianjuta_editor_insert (editor, begin, text_stripped + 2, -1, NULL);
            if (text_diff != NULL)
                ianjuta_editor_insert (editor, begin, *text_diff, -1, NULL);
        }
        else
        {
            ianjuta_editor_insert (editor, begin, "//", -1, NULL);
        }
    }

    g_object_unref (begin);
    g_object_unref (end);
    g_free (text);
    g_free (text_stripped);
    g_strfreev (text_diff);
}
コード例 #20
0
ファイル: gimptext.c プロジェクト: davidyang5405/gimp
static void
gimp_text_set_property (GObject      *object,
                        guint         property_id,
                        const GValue *value,
                        GParamSpec   *pspec)
{
  GimpText    *text = GIMP_TEXT (object);
  GimpRGB     *color;
  GimpMatrix2 *matrix;

  switch (property_id)
    {
    case PROP_TEXT:
      g_free (text->text);
      text->text = g_value_dup_string (value);
      if (text->text && text->markup)
        {
          g_free (text->markup);
          text->markup = NULL;
          g_object_notify (object, "markup");
        }
      break;
    case PROP_MARKUP:
      g_free (text->markup);
      text->markup = g_value_dup_string (value);
      if (text->markup && text->text)
        {
          g_free (text->text);
          text->text = NULL;
          g_object_notify (object, "text");
        }
      break;
    case PROP_FONT:
      {
        const gchar *font = g_value_get_string (value);

        g_free (text->font);

        if (font)
          {
            gsize len = strlen (font);

            if (g_str_has_suffix (font, " Not-Rotated"))
              len -= strlen ( " Not-Rotated");

            text->font = g_strndup (font, len);
          }
        else
          {
            text->font = NULL;
          }
      }
      break;
    case PROP_FONT_SIZE:
      text->font_size = g_value_get_double (value);
      break;
    case PROP_UNIT:
      text->unit = g_value_get_int (value);
      break;
    case PROP_ANTIALIAS:
      text->antialias = g_value_get_boolean (value);
      break;
    case PROP_HINT_STYLE:
      text->hint_style = g_value_get_enum (value);
      break;
    case PROP_KERNING:
      text->kerning = g_value_get_boolean (value);
      break;
    case PROP_LANGUAGE:
      g_free (text->language);
      text->language = g_value_dup_string (value);
      break;
    case PROP_BASE_DIR:
      text->base_dir = g_value_get_enum (value);
      break;
    case PROP_COLOR:
      color = g_value_get_boxed (value);
      text->color = *color;
      break;
    case PROP_OUTLINE:
      text->outline = g_value_get_enum (value);
      break;
    case PROP_JUSTIFICATION:
      text->justify = g_value_get_enum (value);
      break;
    case PROP_INDENTATION:
      text->indent = g_value_get_double (value);
      break;
    case PROP_LINE_SPACING:
      text->line_spacing = g_value_get_double (value);
      break;
    case PROP_LETTER_SPACING:
      text->letter_spacing = g_value_get_double (value);
      break;
    case PROP_BOX_MODE:
      text->box_mode = g_value_get_enum (value);
      break;
    case PROP_BOX_WIDTH:
      text->box_width = g_value_get_double (value);
      break;
    case PROP_BOX_HEIGHT:
      text->box_height = g_value_get_double (value);
      break;
    case PROP_BOX_UNIT:
      text->box_unit = g_value_get_int (value);
      break;
    case PROP_TRANSFORMATION:
      matrix = g_value_get_boxed (value);
      text->transformation = *matrix;
      break;
    case PROP_OFFSET_X:
      text->offset_x = g_value_get_double (value);
      break;
    case PROP_OFFSET_Y:
      text->offset_y = g_value_get_double (value);
      break;
    case PROP_BORDER:
      text->border = g_value_get_int (value);
      break;
    case PROP_HINTING:
      /* interpret "hinting" only if "hint-style" has its default
       * value, so we don't overwrite a serialized new hint-style with
       * a compat "hinting" that is only there for old GIMP versions
       */
      if (text->hint_style == GIMP_TEXT_HINT_STYLE_MEDIUM)
        text->hint_style = (g_value_get_boolean (value) ?
                            GIMP_TEXT_HINT_STYLE_MEDIUM :
                            GIMP_TEXT_HINT_STYLE_NONE);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
      break;
    }
}
コード例 #21
0
static HashSet<String> mimeTypeCache()
{

    do_gst_init();

    static HashSet<String> cache;
    static bool typeListInitialized = false;

    if (!typeListInitialized) {
        // These subtypes are already beeing supported by WebKit itself
        HashSet<String> ignoredApplicationSubtypes;
        ignoredApplicationSubtypes.add(String("javascript"));
        ignoredApplicationSubtypes.add(String("ecmascript"));
        ignoredApplicationSubtypes.add(String("x-javascript"));
        ignoredApplicationSubtypes.add(String("xml"));
        ignoredApplicationSubtypes.add(String("xhtml+xml"));
        ignoredApplicationSubtypes.add(String("rss+xml"));
        ignoredApplicationSubtypes.add(String("atom+xml"));
        ignoredApplicationSubtypes.add(String("x-ftp-directory"));
        ignoredApplicationSubtypes.add(String("x-java-applet"));
        ignoredApplicationSubtypes.add(String("x-java-bean"));
        ignoredApplicationSubtypes.add(String("x-java-vm"));
        ignoredApplicationSubtypes.add(String("x-shockwave-flash"));

        GList* factories = gst_type_find_factory_get_list();
        for (GList* iterator = factories; iterator; iterator = iterator->next) {
            GstTypeFindFactory* factory = GST_TYPE_FIND_FACTORY(iterator->data);
            GstCaps* caps = gst_type_find_factory_get_caps(factory);

            // Splitting the capability by comma and taking the first part
            // as capability can be something like "audio/x-wavpack, framed=(boolean)false"
            GOwnPtr<gchar> capabilityString(gst_caps_to_string(caps));
            gchar** capability = g_strsplit(capabilityString.get(), ",", 2);
            gchar** mimetype = g_strsplit(capability[0], "/", 2);

            // GStreamer plugins can be capable of supporting types which WebKit supports
            // by default. In that case, we should not consider these types supportable by GStreamer.
            // Examples of what GStreamer can support but should not be added:
            // text/plain, text/html, image/jpeg, application/xml
            if (g_str_equal(mimetype[0], "audio") ||
                    g_str_equal(mimetype[0], "video") ||
                    (g_str_equal(mimetype[0], "application") &&
                        !ignoredApplicationSubtypes.contains(String(mimetype[1])))) {
                cache.add(String(capability[0]));

                // These formats are supported by GStreamer, but not correctly advertised
                if (g_str_equal(capability[0], "video/x-h264") ||
                    g_str_equal(capability[0], "audio/x-m4a")) {
                    cache.add(String("video/mp4"));
                    cache.add(String("audio/aac"));
                }

                if (g_str_equal(capability[0], "video/x-theora"))
                    cache.add(String("video/ogg"));

                if (g_str_equal(capability[0], "audio/x-wav"))
                    cache.add(String("audio/wav"));

                if (g_str_equal(capability[0], "audio/mpeg")) {
                    // This is what we are handling: mpegversion=(int)1, layer=(int)[ 1, 3 ]
                    gchar** versionAndLayer = g_strsplit(capability[1], ",", 2);

                    if (g_str_has_suffix (versionAndLayer[0], "(int)1")) {
                        for (int i = 0; versionAndLayer[1][i] != '\0'; i++) {
                            if (versionAndLayer[1][i] == '1')
                                cache.add(String("audio/mp1"));
                            else if (versionAndLayer[1][i] == '2')
                                cache.add(String("audio/mp2"));
                            else if (versionAndLayer[1][i] == '3')
                                cache.add(String("audio/mp3"));
                        }
                    }

                    g_strfreev(versionAndLayer);
                }
            }

            g_strfreev(capability);
            g_strfreev(mimetype);
        }

        gst_plugin_feature_list_free(factories);
        typeListInitialized = true;
    }

    return cache;
}
コード例 #22
0
ファイル: rhk-spm32.c プロジェクト: DavidMercier/gwyddion
static GwySpectra*
rhkspm32_read_spectra(RHKPage *rhkpage)
{
    guint i, j;
    gdouble *data;
    GwySIUnit *siunit = NULL;
    GwyDataLine *dline;
    GwySpectra *spectra = NULL;
    GPtrArray *spectrum = NULL;
    // i'm leaving this alone, though it probably doesn't make sense,
    // and i should just create graphs straight away - but in case of
    // future use, i'll just convert the data later to graphs

    // xres stores number of data points per spectra,
    // yres stores the number of spectra

    // reading data
    gwy_debug("rhk-spm32: %d spectra in this page\n", rhkpage->yres);
    for (i = 0; i < rhkpage->yres; i++) {
        dline = gwy_data_line_new(rhkpage->xres, rhkpage->x.scale, FALSE);
        gwy_data_line_set_offset(dline, (rhkpage->x.offset));
        data = gwy_data_line_get_data(dline);
        // store line data in physical units - which are the z values, not y
        if ((rhkpage->data_type) == RHK_DATA_INT16) {
                const guint16 *p = (const guint16*)(rhkpage->buffer
                                                    + rhkpage->data_offset);
                for (j = 0; j < rhkpage->xres; j++) {
                    data[j] = GINT16_FROM_LE(p[i*(rhkpage->xres) + j])
                            *(rhkpage->z.scale)+(rhkpage->z.offset);
                }
        }
        else if ((rhkpage->data_type) == RHK_DATA_SINGLE) {
                const guchar *p = (const guchar*)(rhkpage->buffer
                                                  + rhkpage->data_offset);
                for (j = 0; j < rhkpage->xres; j++) {
                    data[j] = gwy_get_gfloat_le(&p)*rhkpage->z.scale
                              + rhkpage->z.offset;
                }
        }
        siunit = gwy_si_unit_new(rhkpage->x.units);
        gwy_data_line_set_si_unit_x(dline, siunit);
        g_object_unref(siunit);

        // the y units (and data) for a 1D graph are stored in Z in the rhk
        // spm32 format!
        /* Fix "/\xfbHz" to "/Hz".
         * XXX: It might be still wrong as the strange character might mean
         * sqrt. */
        if (g_str_has_suffix(rhkpage->z.units, "/\xfbHz")) {
            gchar *s = gwy_strkill(g_strdup(rhkpage->z.units), "\xfb");
            siunit = gwy_si_unit_new(s);
            g_free(s);
        }
        else
            siunit = gwy_si_unit_new(rhkpage->z.units);
        gwy_data_line_set_si_unit_y(dline, siunit);
        g_object_unref(siunit);

        if (!spectrum)
            spectrum = g_ptr_array_sized_new(rhkpage->yres);
        g_ptr_array_add(spectrum, dline);
    }
    gwy_debug("rhk-spm32: finished parsing sps data\n");
    spectra = gwy_spectra_new();

    for (i = 0; i < rhkpage->yres; i++) {
        dline = g_ptr_array_index(spectrum, i);
        // since RHK spm32 does not record where it took the spectra,
        // i'm setting these to zero
        gwy_spectra_add_spectrum(spectra, dline, 0, 0);
        g_object_unref(dline);
    }
    gwy_spectra_set_title(spectra, rhkpage->label);

    if (spectrum)
        g_ptr_array_free(spectrum, TRUE);

    return spectra;
}
コード例 #23
0
static const gchar *
xfdesktop_regular_file_icon_peek_tooltip(XfdesktopIcon *icon)
{
    XfdesktopRegularFileIcon *regular_file_icon = XFDESKTOP_REGULAR_FILE_ICON(icon);
    
    if(!regular_file_icon->priv->tooltip) {
        GFileInfo *info = xfdesktop_file_icon_peek_file_info(XFDESKTOP_FILE_ICON(icon));
        const gchar *content_type, *comment = NULL;
        gchar *description, *size_string, *time_string;
        guint64 size, mtime;
        gboolean is_desktop_file = FALSE;

        if(!info)
            return NULL;

        if(g_content_type_equals(g_file_info_get_content_type(info),
                                 "application/x-desktop"))
        {
            is_desktop_file = TRUE;
        }
        else
        {
          gchar *uri = g_file_get_uri(regular_file_icon->priv->file);
          if(g_str_has_suffix(uri, ".desktop"))
              is_desktop_file = TRUE;
          g_free(uri);
        }

        content_type = g_file_info_get_content_type(info);
        description = g_content_type_get_description(content_type);

        size = g_file_info_get_attribute_uint64(info,
                                                G_FILE_ATTRIBUTE_STANDARD_SIZE);

        size_string = g_format_size(size);

        mtime = g_file_info_get_attribute_uint64(info,
                                                 G_FILE_ATTRIBUTE_TIME_MODIFIED);
        time_string = xfdesktop_file_utils_format_time_for_display(mtime);

        regular_file_icon->priv->tooltip =
            g_strdup_printf(_("Type: %s\nSize: %s\nLast modified: %s"),
                            description, size_string, time_string);

        /* Extract the Comment entry from the .desktop file */
        if(is_desktop_file)
        {
            gchar *path = g_file_get_path(regular_file_icon->priv->file);
            XfceRc *rcfile = xfce_rc_simple_open(path, TRUE);
            g_free(path);

            if(rcfile) {
                xfce_rc_set_group(rcfile, "Desktop Entry");
                comment = xfce_rc_read_entry(rcfile, "Comment", NULL);
            }
            /* Prepend the comment to the tooltip */
            if(comment != NULL && *comment != '\0') {
                gchar *tooltip = regular_file_icon->priv->tooltip;
                regular_file_icon->priv->tooltip = g_strdup_printf("%s\n%s",
                                                                   comment,
                                                                   tooltip);
                g_free(tooltip);
            }

            xfce_rc_close(rcfile);
        }

        g_free(time_string);
        g_free(size_string);
        g_free(description);
    }
    
    return regular_file_icon->priv->tooltip;
}
コード例 #24
0
ファイル: ostree-sysroot.c プロジェクト: resin-io/ostree
gboolean
_ostree_sysroot_read_boot_loader_configs (OstreeSysroot *self,
                                          int            bootversion,
                                          GPtrArray    **out_loader_configs,
                                          GCancellable  *cancellable,
                                          GError       **error)
{
  gboolean ret = FALSE;
  int fd; /* Temporary owned by iterator */
  g_autofree char *entries_path = g_strdup_printf ("boot/loader.%d/entries", bootversion);
  g_autoptr(GPtrArray) ret_loader_configs = NULL;
  g_auto(GLnxDirFdIterator) dfd_iter = { 0, };

  if (!ensure_sysroot_fd (self, error))
    goto out;

  ret_loader_configs = g_ptr_array_new_with_free_func ((GDestroyNotify)g_object_unref);

  fd = glnx_opendirat_with_errno (self->sysroot_fd, entries_path, TRUE);
  if (fd == -1)
    {
      if (errno == ENOENT)
        goto done;
      else
        {
          glnx_set_error_from_errno (error);
          goto out;
        }
    }

  if (!glnx_dirfd_iterator_init_take_fd (fd, &dfd_iter, error))
    goto out;

  while (TRUE)
    {
      struct dirent *dent;
      struct stat stbuf;

      if (!glnx_dirfd_iterator_next_dent (&dfd_iter, &dent, cancellable, error))
        goto out;
          
      if (dent == NULL)
        break;

      if (fstatat (dfd_iter.fd, dent->d_name, &stbuf, 0) != 0)
        {
          glnx_set_error_from_errno (error);
          goto out;
        }

      if (g_str_has_prefix (dent->d_name, "ostree-") &&
          g_str_has_suffix (dent->d_name, ".conf") &&
          S_ISREG (stbuf.st_mode))
        {
          glnx_unref_object OstreeBootconfigParser *config = ostree_bootconfig_parser_new ();
  
          if (!ostree_bootconfig_parser_parse_at (config, dfd_iter.fd, dent->d_name, cancellable, error))
            {
              g_prefix_error (error, "Parsing %s: ", dent->d_name);
              goto out;
            }

          g_ptr_array_add (ret_loader_configs, g_object_ref (config));
        }
    }

 done:
  gs_transfer_out_value (out_loader_configs, &ret_loader_configs);
  ret = TRUE;
 out:
  return ret;
}
コード例 #25
0
ファイル: as-validator.c プロジェクト: lucasmoura/appstream
/**
 * as_validator_analyze_component_metainfo_relation_cb:
 *
 * Helper function for GHashTable foreach iteration.
 */
static void
as_validator_analyze_component_metainfo_relation_cb (const gchar *fname, AsComponent *cpt, struct MInfoCheckData *data)
{
	g_autofree gchar *cid_base = NULL;

	/* if we have no component-id, we can't check anything */
	if (as_component_get_id (cpt) == NULL)
		return;

	as_validator_set_current_cpt (data->validator, cpt);
	as_validator_set_current_fname (data->validator, fname);

	/* check if the fname and the component-id match */
	if (g_str_has_suffix (as_component_get_id (cpt), ".desktop")) {
		cid_base = g_strndup (as_component_get_id (cpt),
					g_strrstr (as_component_get_id (cpt), ".") - as_component_get_id (cpt));
	} else {
		cid_base = g_strdup (as_component_get_id (cpt));
	}
	if (!as_matches_metainfo (fname, cid_base)) {
		/* the name-without-type didn't match - check for the full id in the component name */
		if (!as_matches_metainfo (fname, as_component_get_id (cpt))) {
			as_validator_add_issue (data->validator,
					AS_ISSUE_IMPORTANCE_WARNING,
					AS_ISSUE_KIND_WRONG_NAME,
					"The metainfo filename does not match the component ID.");
		}
	}

	/* check if the referenced .desktop file exists */
	if (as_component_get_kind (cpt) == AS_COMPONENT_KIND_DESKTOP_APP) {
		if (g_hash_table_contains (data->desktop_fnames, as_component_get_id (cpt))) {
			g_autofree gchar *desktop_fname_full = NULL;
			g_autoptr(GKeyFile) dfile = NULL;
			GError *tmp_error = NULL;

			desktop_fname_full = g_build_filename (data->apps_dir, as_component_get_id (cpt), NULL);
			dfile = g_key_file_new ();

			g_key_file_load_from_file (dfile, desktop_fname_full, G_KEY_FILE_NONE, &tmp_error);
			if (tmp_error != NULL) {
				as_validator_add_issue (data->validator,
						AS_ISSUE_IMPORTANCE_WARNING,
						AS_ISSUE_KIND_READ_ERROR,
						"Unable to read associated .desktop file: %s", tmp_error->message);
				g_error_free (tmp_error);
				tmp_error = NULL;
			} else {
				/* we successfully opened the .desktop file, now perform some checks */

				/* name */
				if ((g_strcmp0 (as_component_get_name (cpt), "") == 0) &&
				    (!g_key_file_has_key (dfile, G_KEY_FILE_DESKTOP_GROUP,
								 G_KEY_FILE_DESKTOP_KEY_NAME, NULL))) {
					/* we don't have a summary, and there is also none in the .desktop file - this is bad. */
					as_validator_add_issue (data->validator,
							AS_ISSUE_IMPORTANCE_ERROR,
							AS_ISSUE_KIND_VALUE_MISSING,
							"The component is missing a name (none found in its metainfo or .desktop file)");
				}

				/* summary */
				if ((g_strcmp0 (as_component_get_summary (cpt), "") == 0) &&
				    (!g_key_file_has_key (dfile, G_KEY_FILE_DESKTOP_GROUP,
								 G_KEY_FILE_DESKTOP_KEY_COMMENT, NULL))) {
					/* we don't have a summary, and there is also none in the .desktop file - this is bad. */
					as_validator_add_issue (data->validator,
							AS_ISSUE_IMPORTANCE_ERROR,
							AS_ISSUE_KIND_VALUE_MISSING,
							"The component is missing a summary (none found in its metainfo or .desktop file)");
				}

				/* categories */
				if (g_key_file_has_key (dfile, G_KEY_FILE_DESKTOP_GROUP,
								G_KEY_FILE_DESKTOP_KEY_CATEGORIES, NULL)) {
					g_autofree gchar *cats_str = NULL;
					g_auto(GStrv) cats = NULL;
					guint i;

					cats_str = g_key_file_get_string (dfile, G_KEY_FILE_DESKTOP_GROUP,
										 G_KEY_FILE_DESKTOP_KEY_CATEGORIES, NULL);
					cats = g_strsplit (cats_str, ";", -1);
					for (i = 0; cats[i] != NULL; i++) {
						if (as_str_empty (cats[i]))
							continue;
						if (!as_utils_is_category_name (cats[i])) {
							as_validator_add_issue (data->validator,
										AS_ISSUE_IMPORTANCE_ERROR,
										AS_ISSUE_KIND_VALUE_WRONG,
										"The category '%s' defined in the .desktop file does not exist.", cats[i]);
						}
					}
				}

			}
		} else {
			as_validator_add_issue (data->validator,
					AS_ISSUE_IMPORTANCE_ERROR,
					AS_ISSUE_KIND_FILE_MISSING,
					"Component metadata refers to a non-existing .desktop file.");
		}
	}

	as_validator_clear_current_cpt (data->validator);
	as_validator_clear_current_fname (data->validator);
}
コード例 #26
0
static void
hd_plugin_configuration_plugin_dir_changed (GFileMonitor      *monitor,
                                            GFile             *monitor_file,
                                            GFile             *info,
                                            GFileMonitorEvent  event_type,
                                            HDPluginConfiguration *configuration)
{
  gchar *info_uri = g_file_get_uri (info);
  HDPluginConfigurationPrivate *priv = configuration->priv;
  /*
  static char* event_string[] = {"changed", "deleted", "startexecuting", "stopexecuting",
  "created", "metadate-changed"};

  g_debug ("%s. Uri: %s. Event: %s",
           __FUNCTION__,
           info_uri,
           event_string [event_type]);
           */

  /* Ignore the temporary dpkg files */
  if (!g_str_has_suffix (info_uri, ".desktop"))
    {
      g_free (info_uri);
      return;
    }

  if (event_type == G_FILE_MONITOR_EVENT_CREATED ||
      event_type == G_FILE_MONITOR_EVENT_CHANGED)
    {
      if (g_hash_table_lookup (priv->available_plugins, info_uri))
        {
          g_debug ("plugin-updated: %s", info_uri);

          g_signal_emit (configuration,
                         plugin_configuration_signals[PLUGIN_MODULE_UPDATED], 0,
                         info_uri);
        }
      else
        {
          g_debug ("plugin-added: %s", info_uri);

          g_hash_table_insert (priv->available_plugins,
                               g_strdup (info_uri),
                               GUINT_TO_POINTER (1));

          g_signal_emit (configuration,
                         plugin_configuration_signals[PLUGIN_MODULE_ADDED], 0,
                         info_uri);
        }
    }
  else if (event_type == G_FILE_MONITOR_EVENT_DELETED)
    {
      g_debug ("plugin-removed: %s", info_uri);

      g_hash_table_remove (priv->available_plugins, info_uri);

      g_signal_emit (configuration,
                     plugin_configuration_signals[PLUGIN_MODULE_REMOVED], 0,
                     info_uri);
    }

    g_free (info_uri);
}
コード例 #27
0
gint
tracker_control_general_run (void)
{
	GError *error = NULL;
	GSList *pids;
	GSList *l;
	gchar *str;
	gpointer verbosity_type_enum_class_pointer = NULL;
	TrackerVerbosity set_log_verbosity_value = TRACKER_VERBOSITY_ERRORS;

	/* Constraints */

	if (kill_option != TERM_NONE && terminate_option != TERM_NONE) {
		g_printerr ("%s\n",
		            _("You can not use the --kill and --terminate arguments together"));
		return EXIT_FAILURE;
	}

	if ((hard_reset || soft_reset) && terminate_option != TERM_NONE) {
		g_printerr ("%s\n",
		            _("You can not use the --terminate with --hard-reset or --soft-reset, --kill is implied"));
		return EXIT_FAILURE;
	}

	if (hard_reset && soft_reset) {
		g_printerr ("%s\n",
		            _("You can not use the --hard-reset and --soft-reset arguments together"));
		return EXIT_FAILURE;
	}

	if (get_log_verbosity && set_log_verbosity) {
		g_printerr ("%s\n",
		            _("You can not use the --get-logging and --set-logging arguments together"));
		return EXIT_FAILURE;
	}

	if (set_log_verbosity) {
		if (g_ascii_strcasecmp (set_log_verbosity, "debug") == 0) {
			set_log_verbosity_value = TRACKER_VERBOSITY_DEBUG;
		} else if (g_ascii_strcasecmp (set_log_verbosity, "detailed") == 0) {
			set_log_verbosity_value = TRACKER_VERBOSITY_DETAILED;
		} else if (g_ascii_strcasecmp (set_log_verbosity, "minimal") == 0) {
			set_log_verbosity_value = TRACKER_VERBOSITY_MINIMAL;
		} else if (g_ascii_strcasecmp (set_log_verbosity, "errors") == 0) {
			set_log_verbosity_value = TRACKER_VERBOSITY_ERRORS;
		} else {
			g_printerr ("%s\n",
			            _("Invalid log verbosity, try 'debug', 'detailed', 'minimal' or 'errors'"));
			return EXIT_FAILURE;
		}
	}

	if (hard_reset || soft_reset) {
		/* Imply --kill */
		kill_option = TERM_ALL;
	}

	if (get_log_verbosity || set_log_verbosity) {
		GType etype;

		/* Since we don't reference this enum anywhere, we do
		 * it here to make sure it exists when we call
		 * g_type_class_peek(). This wouldn't be necessary if
		 * it was a param in a GObject for example.
		 *
		 * This does mean that we are leaking by 1 reference
		 * here and should clean it up, but it doesn't grow so
		 * this is acceptable.
		 */
		etype = tracker_verbosity_get_type ();
		verbosity_type_enum_class_pointer = g_type_class_ref (etype);
	}

	/* Unless we are stopping processes or listing processes,
	 * don't iterate them.
	 */
	if (kill_option != TERM_NONE ||
	    terminate_option != TERM_NONE ||
	    list_processes) {
		guint32 own_pid;
		guint32 own_uid;
		gchar *own_pid_str;

		pids = get_pids ();
		str = g_strdup_printf (g_dngettext (NULL,
		                                    "Found %d PID…",
		                                    "Found %d PIDs…",
		                                    g_slist_length (pids)),
		                       g_slist_length (pids));
		g_print ("%s\n", str);
		g_free (str);

		/* Establish own uid/pid */
		own_pid = (guint32) getpid ();
		own_pid_str = g_strdup_printf ("%d", own_pid);
		own_uid = get_uid_for_pid (own_pid_str, NULL);
		g_free (own_pid_str);

		for (l = pids; l; l = l->next) {
			GError *error = NULL;
			gchar *filename;
			gchar *contents = NULL;
			gchar **strv;
			guint uid;

			uid = get_uid_for_pid (l->data, &filename);

			/* Stat the file and make sure current user == file owner */
			if (uid != own_uid) {
				continue;
			}

			/* Get contents to determine basename */
			if (!g_file_get_contents (filename, &contents, NULL, &error)) {
				str = g_strdup_printf (_("Could not open '%s'"), filename);
				g_printerr ("%s, %s\n",
				            str,
				            error ? error->message : _("no error given"));
				g_free (str);
				g_clear_error (&error);
				g_free (contents);
				g_free (filename);

				continue;
			}

			strv = g_strsplit (contents, "^@", 2);
			if (strv && strv[0]) {
				gchar *basename;

				basename = g_path_get_basename (strv[0]);

				if ((g_str_has_prefix (basename, "tracker") == TRUE ||
				     g_str_has_prefix (basename, "lt-tracker") == TRUE) &&
				    g_str_has_suffix (basename, "-control") == FALSE &&
				    g_str_has_suffix (basename, "-status-icon") == FALSE) {
					pid_t pid;

					pid = atoi (l->data);
					str = g_strdup_printf (_("Found process ID %d for '%s'"), pid, basename);
					g_print ("%s\n", str);
					g_free (str);

					if (terminate_option != TERM_NONE) {
						if ((terminate_option == TERM_STORE &&
						     !g_str_has_suffix (basename, "tracker-store")) ||
						    (terminate_option == TERM_MINERS &&
						     !strstr (basename, "tracker-miner"))) {
							continue;
						}

						if (kill (pid, SIGTERM) == -1) {
							const gchar *errstr = g_strerror (errno);

							str = g_strdup_printf (_("Could not terminate process %d"), pid);
							g_printerr ("  %s, %s\n",
							            str,
							            errstr ? errstr : _("no error given"));
							g_free (str);
						} else {
							str = g_strdup_printf (_("Terminated process %d"), pid);
							g_print ("  %s\n", str);
							g_free (str);
						}
					} else if (kill_option != TERM_NONE) {
						if ((kill_option == TERM_STORE &&
						     !g_str_has_suffix (basename, "tracker-store")) ||
						    (kill_option == TERM_MINERS &&
						     !strstr (basename, "tracker-miner"))) {
							continue;
						}

						if (kill (pid, SIGKILL) == -1) {
							const gchar *errstr = g_strerror (errno);

							str = g_strdup_printf (_("Could not kill process %d"), pid);
							g_printerr ("  %s, %s\n",
							            str,
							            errstr ? errstr : _("no error given"));
							g_free (str);
						} else {
							str = g_strdup_printf (_("Killed process %d"), pid);
							g_print ("  %s\n", str);
							g_free (str);
						}
					}
				}

				g_free (basename);
			}

			g_strfreev (strv);
			g_free (contents);
			g_free (filename);
		}

		g_slist_foreach (pids, (GFunc) g_free, NULL);
		g_slist_free (pids);

		/* If we just wanted to list processes, all done */
		if (list_processes &&
		    terminate_option == TERM_NONE &&
		    kill_option == TERM_NONE) {
			return EXIT_SUCCESS;
		}
	}

	if (hard_reset || soft_reset) {
		guint log_handler_id;
#ifndef DISABLE_JOURNAL
		gchar *rotate_to;
		TrackerDBConfig *db_config;
		gsize chunk_size;
		gint chunk_size_mb;
#endif /* DISABLE_JOURNAL */

		/* Set log handler for library messages */
		log_handler_id = g_log_set_handler (NULL,
		                                    G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL,
		                                    log_handler,
		                                    NULL);

		g_log_set_default_handler (log_handler, NULL);

#ifndef DISABLE_JOURNAL
		db_config = tracker_db_config_new ();

		chunk_size_mb = tracker_db_config_get_journal_chunk_size (db_config);
		chunk_size = (gsize) ((gsize) chunk_size_mb * (gsize) 1024 * (gsize) 1024);
		rotate_to = tracker_db_config_get_journal_rotate_destination (db_config);

		/* This call is needed to set the journal's filename */
		tracker_db_journal_set_rotating ((chunk_size_mb != -1),
		                                 chunk_size, rotate_to);

		g_free (rotate_to);
		g_object_unref (db_config);

#endif /* DISABLE_JOURNAL */

		/* Clean up (select_cache_size and update_cache_size don't matter here) */
		if (!tracker_db_manager_init (TRACKER_DB_MANAGER_REMOVE_ALL,
		                              NULL,
		                              FALSE,
		                              FALSE,
		                              100,
		                              100,
		                              NULL,
		                              NULL,
		                              NULL,
		                              &error)) {

			g_message ("Error initializing database: %s", error->message);
			g_free (error);

			return EXIT_FAILURE;
		}
#ifndef DISABLE_JOURNAL
		tracker_db_journal_init (NULL, FALSE, NULL);
#endif /* DISABLE_JOURNAL */

		tracker_db_manager_remove_all (hard_reset);
		tracker_db_manager_shutdown ();
#ifndef DISABLE_JOURNAL
		tracker_db_journal_shutdown (NULL);
#endif /* DISABLE_JOURNAL */

		/* Unset log handler */
		g_log_remove_handler (NULL, log_handler_id);
	}

	if (remove_config) {
		GMainLoop *main_loop;
		GFile *file;
		TrackerCrawler *crawler;
		const gchar *suffix = ".cfg";
		const gchar *home_conf_dir;
		gchar *path;
		GSList *all, *l;

		crawler = tracker_crawler_new ();
		main_loop = g_main_loop_new (NULL, FALSE);

		g_signal_connect (crawler, "check-file",
		                  G_CALLBACK (crawler_check_file_cb),
		                  &suffix);
		g_signal_connect (crawler, "finished",
		                  G_CALLBACK (crawler_finished_cb),
		                  main_loop);

		/* Go through service files */

		/* Check the default XDG_DATA_HOME location */
		home_conf_dir = g_getenv ("XDG_CONFIG_HOME");

		if (home_conf_dir && tracker_path_has_write_access_or_was_created (home_conf_dir)) {
			path = g_build_path (G_DIR_SEPARATOR_S, home_conf_dir, "tracker", NULL);
		} else {
			home_conf_dir = g_getenv ("HOME");

			if (!home_conf_dir || !tracker_path_has_write_access_or_was_created (home_conf_dir)) {
				home_conf_dir = g_get_home_dir ();
			}
			path = g_build_path (G_DIR_SEPARATOR_S, home_conf_dir, ".config", "tracker", NULL);
		}

		file = g_file_new_for_path (path);
		g_free (path);

		g_print ("%s\n", _("Removing configuration files…"));

		tracker_crawler_start (crawler, file, FALSE);
		g_object_unref (file);

		g_main_loop_run (main_loop);
		g_object_unref (crawler);

		g_print ("%s\n", _("Resetting existing configuration…"));

		all = tracker_gsettings_get_all (NULL);

		if (!all) {
			return EXIT_FAILURE;
		}

		for (l = all; l; l = l->next) {
			ComponentGSettings *c = l->data;
			gchar **keys, **p;

			if (!c) {
				continue;
			}

			g_print ("  %s\n", c->name);

			keys = g_settings_list_keys (c->settings);
			for (p = keys; p && *p; p++) {
				g_print ("    %s\n", *p);
				g_settings_reset (c->settings, *p);
			}

			if (keys) {
				g_strfreev (keys);
			}

			g_settings_apply (c->settings);
		}

		tracker_gsettings_free (all);
	}

	/* Deal with logging changes AFTER the config may have been
	 * reset, this way users can actually use --remove-config with
	 * the --set-logging switch.
	 */
	if (get_log_verbosity) {
		GSList *all;
		gint longest = 0;

		all = tracker_gsettings_get_all (&longest);

		if (!all) {
			return EXIT_FAILURE;
		}

		g_print ("%s:\n", _("Components"));
		tracker_gsettings_print_verbosity (all, longest, TRUE);
		g_print ("\n");

		/* Miners */
		g_print ("%s (%s):\n",
		         _("Miners"),
		         _("Only those with config listed"));
		tracker_gsettings_print_verbosity (all, longest, FALSE);
		g_print ("\n");

		tracker_gsettings_free (all);
	}

	if (set_log_verbosity) {
		GSList *all;
		gchar *str;
		gint longest = 0;

		all = tracker_gsettings_get_all (&longest);

		if (!all) {
			return EXIT_FAILURE;
		}

		str = g_strdup_printf (_("Setting log verbosity for all components to '%s'…"), set_log_verbosity);
		g_print ("%s\n", str);
		g_print ("\n");
		g_free (str);

		tracker_gsettings_set_all (all, set_log_verbosity_value);
		tracker_gsettings_free (all);

		/* We free to make sure we get new settings and that
		 * they're saved properly.
		 */
		all = tracker_gsettings_get_all (&longest);

		if (!all) {
			return EXIT_FAILURE;
		}

		g_print ("%s:\n", _("Components"));
		tracker_gsettings_print_verbosity (all, longest, TRUE);
		g_print ("\n");

		/* Miners */
		g_print ("%s (%s):\n",
		         _("Miners"),
		         _("Only those with config listed"));
		tracker_gsettings_print_verbosity (all, longest, FALSE);
		g_print ("\n");

		tracker_gsettings_free (all);
	}

	if (verbosity_type_enum_class_pointer) {
		g_type_class_unref (verbosity_type_enum_class_pointer);
	}

	if (start) {
		TrackerMinerManager *manager;
		GSList *miners, *l;

		if (hard_reset || soft_reset) {
			g_print ("%s\n", _("Waiting one second before starting miners…"));

			/* Give a second's grace to avoid race conditions */
			g_usleep (G_USEC_PER_SEC);
		}

		g_print ("%s\n", _("Starting miners…"));


		/* Auto-start the miners here */
		manager = tracker_miner_manager_new_full (TRUE, &error);
		if (!manager) {
			g_printerr (_("Could not start miners, manager could not be created, %s"),
			            error ? error->message : "unknown error");
			g_printerr ("\n");
			g_clear_error (&error);
			return EXIT_FAILURE;
		}

		miners = tracker_miner_manager_get_available (manager);

		/* Get the status of all miners, this will start all
		 * miners not already running.
		 */
		for (l = miners; l; l = l->next) {
			const gchar *display_name;
			gdouble progress = 0.0;

			display_name = tracker_miner_manager_get_display_name (manager, l->data);

			if (!tracker_miner_manager_get_status (manager,
			                                       l->data,
			                                       NULL,
			                                       &progress,
			                                       NULL)) {
				g_printerr ("  ✗ %s (%s)\n",
				            display_name,
				            _("perhaps a disabled plugin?"));
			} else {
				g_print ("  ✓ %s\n",
				         display_name);
			}

			g_free (l->data);
		}

		g_slist_free (miners);
		g_object_unref (manager);
	}

	if (backup) {
		GDBusConnection *connection;
		GDBusProxy *proxy;
		GError *error = NULL;
		GVariant *v;
		gchar *uri;

		uri = get_uri_from_arg (backup);

		g_print ("%s\n", _("Backing up database"));
		g_print ("  %s\n", uri);

		connection = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);

		if (!connection) {
			g_critical ("Could not connect to the D-Bus session bus, %s",
			            error ? error->message : "no error given.");
			g_clear_error (&error);
			g_free (uri);

			return EXIT_FAILURE;
		}

		proxy = g_dbus_proxy_new_sync (connection,
		                               G_DBUS_PROXY_FLAGS_NONE,
		                               NULL,
		                               "org.freedesktop.Tracker1",
		                               "/org/freedesktop/Tracker1/Backup",
		                               "org.freedesktop.Tracker1.Backup",
		                               NULL,
		                               &error);

		if (error) {
			g_critical ("Could not create proxy on the D-Bus session bus, %s",
			            error ? error->message : "no error given.");
			g_clear_error (&error);
			g_free (uri);

			return EXIT_FAILURE;
		}

		/* Backup/Restore can take some time */
		g_dbus_proxy_set_default_timeout (proxy, G_MAXINT);

		v = g_dbus_proxy_call_sync (proxy,
		                            "Save",
		                            g_variant_new ("(s)", uri),
		                            G_DBUS_CALL_FLAGS_NONE,
		                            -1,
		                            NULL,
		                            &error);

		if (proxy) {
			g_object_unref (proxy);
		}

		if (error) {
			g_critical ("Could not backup database, %s",
			            error ? error->message : "no error given.");
			g_clear_error (&error);
			g_free (uri);

			return EXIT_FAILURE;
		}

		if (v) {
			g_variant_unref (v);
		}

		g_free (uri);
	}

	if (restore) {
		GDBusConnection *connection;
		GDBusProxy *proxy;
		GError *error = NULL;
		GVariant *v;
		gchar *uri;

		uri = get_uri_from_arg (restore);

		g_print ("%s\n", _("Restoring database from backup"));
		g_print ("  %s\n", uri);

		connection = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);

		if (!connection) {
			g_critical ("Could not connect to the D-Bus session bus, %s",
			            error ? error->message : "no error given.");
			g_clear_error (&error);
			g_free (uri);

			return EXIT_FAILURE;
		}

		proxy = g_dbus_proxy_new_sync (connection,
		                               G_DBUS_PROXY_FLAGS_NONE,
		                               NULL,
		                               "org.freedesktop.Tracker1",
		                               "/org/freedesktop/Tracker1/Backup",
		                               "org.freedesktop.Tracker1.Backup",
		                               NULL,
		                               &error);

		if (error) {
			g_critical ("Could not create proxy on the D-Bus session bus, %s",
			            error ? error->message : "no error given.");
			g_clear_error (&error);
			g_free (uri);

			return EXIT_FAILURE;
		}

		/* Backup/Restore can take some time */
		g_dbus_proxy_set_default_timeout (proxy, G_MAXINT);

		v = g_dbus_proxy_call_sync (proxy,
		                            "Restore",
		                            g_variant_new ("(s)", uri),
		                            G_DBUS_CALL_FLAGS_NONE,
		                            -1,
		                            NULL,
		                            &error);

		if (proxy) {
			g_object_unref (proxy);
		}

		if (error) {
			g_critical ("Could not restore database, %s",
			            error ? error->message : "no error given.");
			g_clear_error (&error);
			g_free (uri);

			return EXIT_FAILURE;
		}

		if (v) {
			g_variant_unref (v);
		}

		g_free (uri);
	}

	return EXIT_SUCCESS;
}
コード例 #28
0
static void
hd_plugin_configuration_configuration_loaded (HDPluginConfiguration *configuration,
                                              GKeyFile        *keyfile)
{
  HDPluginConfigurationPrivate *priv = configuration->priv;
  GError *error = NULL;
  gsize n_plugin_dir;
  gchar *items_config_filename;

  /* free old configuration */
  if (priv->plugin_dirs != NULL)
    {
      guint i;

      for (i = 0; priv->plugin_dirs[i] != NULL; i++)
        {
          g_file_monitor_cancel (priv->plugin_dir_monitors[i]);
          g_object_unref (priv->plugin_dir_monitors[i]);
          g_object_unref (priv->plugin_dir_files[i]);
        }

      priv->plugin_dir_monitors = (g_free (priv->plugin_dir_monitors), NULL);
      priv->plugin_dir_files = (g_free (priv->plugin_dir_files), NULL);
      priv->plugin_dirs = (g_strfreev (priv->plugin_dirs), NULL);
    }
  if (priv->items_config_file)
    priv->items_config_file = (g_object_unref (priv->items_config_file), NULL);

  g_hash_table_remove_all (priv->available_plugins);

  /* Load configuration ([X-PluginConfiguration] group) */
  if (!g_key_file_has_group (keyfile, HD_PLUGIN_CONFIGURATION_CONFIG_GROUP))
    {
      g_warning ("Error configuration file doesn't contain group '%s'",
                 HD_PLUGIN_CONFIGURATION_CONFIG_GROUP);

      return;
    }

  priv->plugin_dirs = g_key_file_get_string_list (keyfile,
                                                  HD_PLUGIN_CONFIGURATION_CONFIG_GROUP,
                                                  HD_DESKTOP_CONFIG_KEY_PLUGIN_DIR,
                                                  &n_plugin_dir,
                                                  &error);

  if (!priv->plugin_dirs)
    {
      g_warning ("Error loading configuration file. No plugin dirs defined: %s",
                 error->message);

      g_error_free (error);

      return;
    }
  else 
    {
      guint i;

      priv->plugin_dir_files = g_new0 (GFile*, n_plugin_dir);
      priv->plugin_dir_monitors = g_new0 (GFileMonitor*, n_plugin_dir);

      for (i = 0; priv->plugin_dirs[i] != NULL; i++)
        {
          GDir *dir;
          GError *error = NULL;
          const gchar *name;

          /* Strip spaces */
          g_strstrip (priv->plugin_dirs[i]);

          /* Add monitor */
          priv->plugin_dir_files[i] = g_file_new_for_path (priv->plugin_dirs[i]);
          priv->plugin_dir_monitors[i] =
            g_file_monitor_directory (priv->plugin_dir_files[i],
                                      G_FILE_MONITOR_NONE,
                                      NULL,NULL);
          g_signal_connect (G_OBJECT (priv->plugin_dir_monitors[i]),
                            "changed",
                            G_CALLBACK (hd_plugin_configuration_plugin_dir_changed),
                            (gpointer)configuration);

          /* Get available .desktop files */
          dir = g_dir_open (priv->plugin_dirs[i], 0, &error);

          if (dir == NULL)
            {
              g_warning ("%s. Couldn't read plugin_paths in dir %s. Error: %s",
                         __FUNCTION__,
                         priv->plugin_dirs[i],
                         error->message);
              g_error_free (error);
              continue;
            }

          for (name = g_dir_read_name (dir); name != NULL; name = g_dir_read_name (dir))
            {
              gchar *filename;

              /* Ignore non .desktop files. */
              if (!g_str_has_suffix (name, ".desktop"))
                continue;

              filename = g_build_filename (priv->plugin_dirs[i], name, NULL);

              g_hash_table_insert (priv->available_plugins,
                                   filename,
                                   GUINT_TO_POINTER (1));
            }

          g_dir_close (dir);
        }
    }

  items_config_filename = g_key_file_get_string (keyfile, 
                                                 HD_PLUGIN_CONFIGURATION_CONFIG_GROUP, 
                                                 HD_PLUGIN_CONFIGURATION_CONFIG_KEY_PLUGIN_CONFIGURATION,
                                                 NULL);
  if (items_config_filename)
    {
      gchar *system_conf_dir, *user_conf_dir;

      g_strstrip (items_config_filename);

      /* Get config file directories */
      g_object_get (G_OBJECT (priv->config_file),
                    "system-conf-dir", &system_conf_dir,
                    "user-conf-dir", &user_conf_dir,
                    NULL);

      priv->items_config_file = hd_config_file_new (system_conf_dir,
                                                    user_conf_dir,
                                                    items_config_filename);
      g_signal_connect_object (priv->items_config_file, "changed",
                               G_CALLBACK (hd_plugin_configuration_load_plugin_configuration),
                               configuration, G_CONNECT_SWAPPED);

      g_free (system_conf_dir);
      g_free (user_conf_dir);
    }
  g_free (items_config_filename);

  hd_plugin_configuration_load_plugin_configuration (configuration);
}
コード例 #29
0
/**
 * rpmostreed_refspec_parse_partial:
 * @new_provided_refspec: The provided refspec
 * @base_refspec: The refspec string to base on.
 * @out_refspec: Pointer to the new refspec
 * @error: Pointer to an error pointer.
 *
 * Takes a refspec string and adds any missing bits based on the
 * base_refspec argument. Errors if a full valid refspec can't
 * be derived.
 *
 * Returns: True on success.
 */
gboolean
rpmostreed_refspec_parse_partial (const gchar *new_provided_refspec,
                                  gchar *base_refspec,
                                  gchar **out_refspec,
                                  GError **error)
{

  g_autofree gchar *ref = NULL;
  g_autofree gchar *remote = NULL;
  g_autofree gchar *origin_ref = NULL;
  g_autofree gchar *origin_remote = NULL;
  GError *parse_error = NULL;

  gboolean ret = FALSE;

  /* Allow just switching remotes */
  if (g_str_has_suffix (new_provided_refspec, ":"))
    {
      remote = g_strdup (new_provided_refspec);
      remote[strlen (remote) - 1] = '\0';
    }
  else
    {
      if (!ostree_parse_refspec (new_provided_refspec, &remote,
                                 &ref, &parse_error))
        {
          g_set_error_literal (error, RPM_OSTREED_ERROR,
                       RPM_OSTREED_ERROR_INVALID_REFSPEC,
                       parse_error->message);
          g_clear_error (&parse_error);
          goto out;
        }
    }

  if (base_refspec != NULL)
    {
      if (!ostree_parse_refspec (base_refspec, &origin_remote,
                               &origin_ref, &parse_error))
        goto out;
    }

  if (ref == NULL)
    {
      if (origin_ref)
        {
          ref = g_strdup (origin_ref);
        }

      else
        {
          g_set_error (error, RPM_OSTREED_ERROR,
                       RPM_OSTREED_ERROR_INVALID_REFSPEC,
                      "Could not determine default ref to pull.");
          goto out;
        }

    }
  else if (remote == NULL)
    {
      if (origin_remote)
        {
          remote = g_strdup (origin_remote);
        }
      else
        {
          g_set_error (error, RPM_OSTREED_ERROR,
                       RPM_OSTREED_ERROR_INVALID_REFSPEC,
                       "Could not determine default remote to pull.");
          goto out;
        }
    }

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

  *out_refspec = g_strconcat (remote, ":", ref, NULL);
  ret = TRUE;

out:
  return ret;
}
コード例 #30
0
static void
foreach_test_func(const gchar* testfile,
                  gpointer user_data)
{
  test_result* result;
  xmlDocPtr doc;
  xmlNodePtr root;
  xmlNodePtr child;

  GSList* requests;
  InfTextChunk* initial;
  GSList* users;
  guint max_total_log_size;
  GError* error;
  gboolean res;

  /* Only process XML files, not the Makefiles or other stuff */
  if(!g_str_has_suffix(testfile, ".xml"))
    return;

  result = (test_result*)user_data;
  doc = xmlParseFile(testfile);

  requests = NULL;
  initial = NULL;
  users = NULL;
  max_total_log_size = 0;
  error = NULL;

  printf("%s... ", testfile);
  fflush(stdout);

  ++ result->total;

  if(doc != NULL)
  {
    root = xmlDocGetRootElement(doc);
    for(child = root->children; child != NULL; child = child->next)
    {
      if(child->type != XML_ELEMENT_NODE) continue;

      if(strcmp((const char*)child->name, "log") == 0)
      {
        res = inf_xml_util_get_attribute_uint_required(
          child,
          "size",
          &max_total_log_size,
          &error
        );

        if(!res)
          break;
      }
      else if(strcmp((const char*)child->name, "initial-buffer") == 0)
      {
        if(initial != NULL) inf_text_chunk_free(initial);
        initial = inf_test_util_parse_buffer(child, &error);
        if(initial == NULL) break;
      }
      else if(strcmp((const char*)child->name, "user") == 0)
      {
        if(inf_test_util_parse_user(child, &users, &error) == FALSE)
          break;
      }
      else if(strcmp((const char*)child->name, "request") == 0 ||
              strcmp((const char*)child->name, "verify") == 0)
      {
        requests = g_slist_prepend(requests, child);
      }
      else
      {
        g_set_error(
          &error,
          inf_test_util_parse_error_quark(),
          INF_TEST_UTIL_PARSE_ERROR_UNEXPECTED_NODE,
          "Node '%s' unexpected",
          (const gchar*)child->name
        );

        break;
      }
    }

    if(error != NULL)
    {
      printf("Failed to parse: %s\n", error->message);
      g_error_free(error);
      xmlFreeDoc(doc);

      g_slist_free(requests);
      if(initial != NULL) inf_text_chunk_free(initial);
      g_slist_free(users);
    }
    else
    {
      g_assert(initial != NULL);

      requests = g_slist_reverse(requests);
      if(perform_test(max_total_log_size, initial, users, requests, &error) ==
         TRUE)
      {
        ++ result->passed;
        printf("OK\n");
      }
      else
      {
        printf("FAILED (%s)\n", error->message);
        g_error_free(error);
      }

      xmlFreeDoc(doc);
      g_slist_free(requests);
      inf_text_chunk_free(initial);
      g_slist_free(users);
    }
  }
}