Пример #1
0
void
_gtk_builder_parser_parse_buffer (GtkBuilder   *builder,
                                  const gchar  *filename,
                                  const gchar  *buffer,
                                  gsize         length,
                                  gchar       **requested_objs,
                                  GError      **error)
{
  const gchar* domain;
  ParserData *data;
  GSList *l;
  
  /* Store the original domain so that interface domain attribute can be
   * applied for the builder and the original domain can be restored after
   * parsing has finished. This allows subparsers to translate elements with
   * gtk_builder_get_translation_domain() without breaking the ABI or API
   */
  domain = gtk_builder_get_translation_domain (builder);

  data = g_new0 (ParserData, 1);
  data->builder = builder;
  data->filename = filename;
  data->domain = g_strdup (domain);
  data->object_ids = g_hash_table_new_full (g_str_hash, g_str_equal,
					    (GDestroyNotify)g_free, NULL);

  data->requested_objects = NULL;
  if (requested_objs)
    {
      gint i;

      data->inside_requested_object = FALSE;
      for (i = 0; requested_objs[i]; ++i)
        {
          data->requested_objects = g_slist_prepend (data->requested_objects,
                                                     g_strdup (requested_objs[i]));	
        }
    }
  else
    {
      /* get all the objects */
      data->inside_requested_object = TRUE;
    }

  data->ctx = g_markup_parse_context_new (&parser, 
                                          G_MARKUP_TREAT_CDATA_AS_TEXT, 
                                          data, NULL);

  if (!g_markup_parse_context_parse (data->ctx, buffer, length, error))
    goto out;

  _gtk_builder_finish (builder);

  /* Custom parser_finished */
  data->custom_finalizers = g_slist_reverse (data->custom_finalizers);
  for (l = data->custom_finalizers; l; l = l->next)
    {
      SubParser *sub = (SubParser*)l->data;
      
      gtk_buildable_custom_finished (GTK_BUILDABLE (sub->object),
                                     builder,
                                     sub->child,
                                     sub->tagname,
                                     sub->data);
    }
  
  /* Common parser_finished, for all created objects */
  data->finalizers = g_slist_reverse (data->finalizers);
  for (l = data->finalizers; l; l = l->next)
    {
      GtkBuildable *buildable = (GtkBuildable*)l->data;
      gtk_buildable_parser_finished (GTK_BUILDABLE (buildable), builder);
    }

 out:

  g_slist_foreach (data->stack, (GFunc)free_info, NULL);
  g_slist_free (data->stack);
  g_slist_foreach (data->custom_finalizers, (GFunc)free_subparser, NULL);
  g_slist_free (data->custom_finalizers);
  g_slist_free (data->finalizers);
  g_slist_foreach (data->requested_objects, (GFunc) g_free, NULL);
  g_slist_free (data->requested_objects);
  g_free (data->domain);
  g_hash_table_destroy (data->object_ids);
  g_markup_parse_context_free (data->ctx);
  g_free (data);

  /* restore the original domain */
  gtk_builder_set_translation_domain (builder, domain);
}
G_MODULE_EXPORT gboolean
tracker_extract_get_metadata (TrackerExtractInfo *extract_info)
{
	TrackerResource *metadata;
	TrackerConfig *config;
	ODTMetadataParseInfo info = { 0 };
	ODTFileType file_type;
	GFile *file;
	gchar *uri;
	const gchar *mime_used;
	GMarkupParseContext *context;
	GMarkupParser parser = {
		xml_start_element_handler_metadata,
		xml_end_element_handler_metadata,
		xml_text_handler_metadata,
		NULL,
		NULL
	};

	if (G_UNLIKELY (maximum_size_error_quark == 0)) {
		maximum_size_error_quark = g_quark_from_static_string ("maximum_size_error");
	}

	metadata = tracker_resource_new (NULL);
	mime_used = tracker_extract_info_get_mimetype (extract_info);

	file = tracker_extract_info_get_file (extract_info);
	uri = g_file_get_uri (file);

	/* Setup conf */
	config = tracker_main_get_config ();

	g_debug ("Extracting OASIS metadata and contents from '%s'", uri);

	/* First, parse metadata */

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

	/* Create parse info */
	info.metadata = metadata;
	info.current = ODT_TAG_TYPE_UNKNOWN;
	info.uri = uri;

	/* Create parsing context */
	context = g_markup_parse_context_new (&parser, 0, &info, NULL);

	/* Load the internal XML file from the Zip archive, and parse it
	 * using the given context */
	tracker_gsf_parse_xml_in_zip (uri, "meta.xml", context, NULL);
	g_markup_parse_context_free (context);

	if (g_ascii_strcasecmp (mime_used, "application/vnd.oasis.opendocument.text") == 0) {
		file_type = FILE_TYPE_ODT;
	} else if (g_ascii_strcasecmp (mime_used, "application/vnd.oasis.opendocument.presentation") == 0) {
		file_type = FILE_TYPE_ODP;
	} else if (g_ascii_strcasecmp (mime_used, "application/vnd.oasis.opendocument.spreadsheet") == 0) {
		file_type = FILE_TYPE_ODS;
	} else if (g_ascii_strcasecmp (mime_used, "application/vnd.oasis.opendocument.graphics") == 0) {
		file_type = FILE_TYPE_ODG;
	} else {
		g_message ("Mime type was not recognised:'%s'", mime_used);
		file_type = FILE_TYPE_INVALID;
	}

	/* Extract content with the given limitations */
	extract_oasis_content (uri,
	                       tracker_config_get_max_bytes (config),
	                       file_type,
	                       metadata);

	g_free (uri);

	tracker_extract_info_set_resource (extract_info, metadata);
	g_object_unref (metadata);

	return TRUE;
}
Пример #3
0
void dt_styles_import_from_file(const char *style_path)
{

  FILE *style_file;
  StyleData *style;
  GMarkupParseContext *parser;
  gchar buf[1024];
  size_t num_read;

  style = dt_styles_style_data_new();
  parser = g_markup_parse_context_new(&dt_style_parser, 0, style, NULL);

  if((style_file = fopen(style_path, "r")))
  {

    while(!feof(style_file))
    {
      num_read = fread(buf, sizeof(gchar), sizeof(buf), style_file);

      if(num_read == 0)
      {
        break;
      }
      else if(num_read == -1)
      {
        // FIXME: ferror?
        // ERROR !
        break;
      }

      if(!g_markup_parse_context_parse(parser, buf, num_read, NULL))
      {
        g_markup_parse_context_free(parser);
        dt_styles_style_data_free(style, TRUE);
        fclose(style_file);
        return;
      }
    }
  }
  else
  {
    // Failed to open file, clean up.
    g_markup_parse_context_free(parser);
    dt_styles_style_data_free(style, TRUE);
    return;
  }

  if(!g_markup_parse_context_end_parse(parser, NULL))
  {
    g_markup_parse_context_free(parser);
    dt_styles_style_data_free(style, TRUE);
    fclose(style_file);
    return;
  }
  g_markup_parse_context_free(parser);
  // save data
  dt_style_save(style);
  //
  dt_styles_style_data_free(style, TRUE);
  fclose(style_file);
}
Пример #4
0
void stor_parse(char *fname, const char *text, size_t len)
{
	GMarkupParseContext* parser;
	struct config_context ctx;

	memset(&ctx, 0, sizeof(struct config_context));
	ctx.fname = fname;

	parser = g_markup_parse_context_new(&cfg_parse_ops, 0, &ctx, NULL);
	if (!parser) {
		applog(LOG_ERR, "g_markup_parse_context_new failed");
		return;
	}

	if (!g_markup_parse_context_parse(parser, text, len, NULL)) {
		applog(LOG_ERR, "Parse failure for Chunk in %s", fname);
		g_markup_parse_context_free(parser);
		goto out_free_all;
	}

	g_markup_parse_context_free(parser);

	switch (ctx.stor_type) {
	case CFG_TYPE_FS:
		if (!stor_verify_fs(fname, &ctx))
			goto out_free_all;
		stor_add_node(ctx.nid, STT_POSIX, ctx.stor_base,
			      NULL, NULL, &ctx.loc);
		break;
	case CFG_TYPE_SWIFT:	/* same as chunk for now */
		if (!stor_verify_chunk(fname, &ctx))
			goto out_free_all;
		stor_add_node(ctx.nid, STT_SWIFT, NULL,
			      ctx.stor_ok_host, ctx.stor_ok_port, &ctx.loc);
		break;
	case CFG_TYPE_UNKNOWN:
		if (debugging)
			applog(LOG_DEBUG, "%s: Unknown storage type", fname);
		break;
	case CFG_TYPE_CHUNK:
	default:
		if (!stor_verify_chunk(fname, &ctx))
			goto out_free_all;
		stor_add_node(ctx.nid, STT_CHUNK, NULL,
			      ctx.stor_ok_host, ctx.stor_ok_port, &ctx.loc);
	}

out_free_all:
	free(ctx.text);

	free(ctx.stor_host);
	free(ctx.stor_port);

	free(ctx.stor_ok_host);
	free(ctx.stor_ok_port);

	free(ctx.loc.area);
	free(ctx.loc.zone);
	free(ctx.loc.rack);

	free(ctx.stor_base);
	return;
}
static void on_get_http_response(char *buffer, size_t buffer_len, gpointer userdata)
{
	if (!buffer)
		return;
	const char *p = g_strstr_len(buffer, buffer_len, "\r\n\r\n");
	if (!p) {
		return;
	}
	p += 4;
	if(g_str_has_prefix(p, UTF8_BOM))
		p += (sizeof(UTF8_BOM)-1); // better than strlen(UTF8_BOM);
	updateinfo_ParseUserData Data;
	Data.latest_version_num = 0;
	const gchar* const *languages = g_get_language_names();
	const char *locale = languages[0];
	if (locale && locale[0] != '\0') {
		const char *p = strchr(locale, '.');
		if (p) {
			Data.locale_name.assign(locale, p - locale);
		} else {
			Data.locale_name = locale;
		}
	}
	GMarkupParser parser;
	parser.start_element = NULL;
	parser.end_element = NULL;
	parser.text = updateinfo_parse_text;
	parser.passthrough = NULL;
	parser.error = NULL;
	GMarkupParseContext* context = g_markup_parse_context_new(&parser, (GMarkupParseFlags)0, &Data, NULL);
	g_markup_parse_context_parse(context, p, buffer_len - (p - buffer), NULL);
	g_markup_parse_context_end_parse(context, NULL);
	g_markup_parse_context_free(context);

	bool updated = false;
	if (Data.latest_version_num != latest_version_num) {
		updated = true;
		latest_version_num = Data.latest_version_num;
		version_msg_title = Data.version_msg_title;
		version_msg_content = Data.version_msg_content;
	}
	if (Data.latest_version_num > my_version_num && Data.latest_version_num != last_prompt_num) {
		std::string content = version_msg_content;
		content += "\n\n";
		content += _("Visit StarDict website now?");
		GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(plugin_info->mainwin), GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_YES_NO, "%s", content.c_str());
		GtkWidget *prompt = gtk_check_button_new_with_mnemonic(_("_Don't show this until the next update."));
		gtk_widget_show(prompt);
		gtk_container_add (GTK_CONTAINER (gtk_dialog_get_content_area(GTK_DIALOG(dialog))), prompt);
		gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_YES);
		gtk_window_set_title (GTK_WINDOW (dialog), version_msg_title.c_str());
		if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_YES) {
			plugin_service->show_url("http://www.stardict.org");
		}
		if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(prompt))) {
			updated = true;
			last_prompt_num = Data.latest_version_num;
		}
		gtk_widget_destroy (dialog);
	}
	if (Data.latest_news != latest_news) {
		updated = true;
		latest_news = Data.latest_news;
	}
	if (updated) {
		GKeyFile *keyfile = g_key_file_new();
		g_key_file_set_string(keyfile, "update", "version_msg_title", version_msg_title.c_str());
		g_key_file_set_string(keyfile, "update", "version_msg_content", version_msg_content.c_str());
		g_key_file_set_string(keyfile, "update", "latest_news", latest_news.c_str());
		g_key_file_set_integer(keyfile, "update", "latest_version_num", latest_version_num);
		g_key_file_set_integer(keyfile, "update", "last_prompt_num", last_prompt_num);
		g_key_file_set_boolean(keyfile, "misc", "show_ads", show_ads);
		gsize length;
		gchar *content = g_key_file_to_data(keyfile, &length, NULL);
		std::string res = get_cfg_filename();
		g_file_set_contents(res.c_str(), content, length, NULL);
		g_free(content);
	}
	if (show_ads) {
		plugin_service->set_news(latest_news.c_str(), Data.links.c_str());
	}
}
Пример #6
0
gboolean
purple_prefs_load()
{
	gchar *filename = g_build_filename(purple_user_dir(), "prefs.xml", NULL);
	gchar *contents = NULL;
	gsize length;
	GMarkupParseContext *context;
	GError *error = NULL;

	if (!filename) {
		prefs_loaded = TRUE;
		return FALSE;
	}

	purple_debug_info("prefs", "Reading %s\n", filename);

	if(!g_file_get_contents(filename, &contents, &length, &error)) {
#ifdef _WIN32
		gchar *common_appdata = wpurple_get_special_folder(CSIDL_COMMON_APPDATA);
#endif
		g_free(filename);
		g_error_free(error);

		error = NULL;

                /* BEGIN SPICEBIRD CHANGES */
                filename = g_build_filename(g_getenv("MOZILLA_FIVE_HOME"),
                                            "purple", "prefs.xml", NULL);
#if 0
#ifdef _WIN32
		filename = g_build_filename(common_appdata ? common_appdata : "", "purple", "prefs.xml", NULL);
		g_free(common_appdata);
#else
		filename = g_build_filename(SYSCONFDIR, "purple", "prefs.xml", NULL);
#endif
#endif
                /* END SPICEBIRD CHANGES */


		purple_debug_info("prefs", "Reading %s\n", filename);

		if (!g_file_get_contents(filename, &contents, &length, &error)) {
			purple_debug_error("prefs", "Error reading prefs: %s\n",
					error->message);
			g_error_free(error);
			g_free(filename);
			prefs_loaded = TRUE;

			return FALSE;
		}
	}

	context = g_markup_parse_context_new(&prefs_parser, 0, NULL, NULL);

	if(!g_markup_parse_context_parse(context, contents, length, NULL)) {
		g_markup_parse_context_free(context);
		g_free(contents);
		g_free(filename);
		prefs_loaded = TRUE;

		return FALSE;
	}

	if(!g_markup_parse_context_end_parse(context, NULL)) {
		purple_debug_error("prefs", "Error parsing %s\n", filename);
		g_markup_parse_context_free(context);
		g_free(contents);
		g_free(filename);
		prefs_loaded = TRUE;

		return FALSE;
	}

	purple_debug_info("prefs", "Finished reading %s\n", filename);
	g_markup_parse_context_free(context);
	g_free(contents);
	g_free(filename);
	prefs_loaded = TRUE;

	return TRUE;
}
Пример #7
0
/**
 * shell_mobile_providers_parse:
 * @country_codes: (allow-none) File with the list of country codes.
 * @service_providers: (allow-none) File with the list of service providers.
 *
 * Returns: (element-type utf8 Shell.CountryMobileProvider) (transfer full): a
 *   hash table where keys are country names #gchar and values are #ShellCountryMobileProvider.
 *   Everything is destroyed with g_hash_table_destroy().
 */
GHashTable *
shell_mobile_providers_parse (const gchar *country_codes,
                              const gchar *service_providers)
{
    GMarkupParseContext *ctx;
    GIOChannel *channel;
    MobileParser parser;
    GError *error = NULL;
    char buffer[4096];
    GIOStatus status;
    gsize len = 0;

    /* Use default paths if none given */
    if (!country_codes)
        country_codes = ISO_3166_COUNTRY_CODES;
    if (!service_providers)
        service_providers = MOBILE_BROADBAND_PROVIDER_INFO;

    memset (&parser, 0, sizeof (MobileParser));

    parser.table = read_country_codes (country_codes);
    if (!parser.table)
        goto out;

    channel = g_io_channel_new_file (service_providers, "r", &error);
    if (!channel) {
        if (error) {
            g_warning ("Could not read %s: %s", service_providers, error->message);
            g_error_free (error);
        } else
            g_warning ("Could not read %s: Unknown error", service_providers);

        goto out;
    }

    parser.state = PARSER_TOPLEVEL;

    ctx = g_markup_parse_context_new (&mobile_parser, 0, &parser, NULL);

    status = G_IO_STATUS_NORMAL;
    while (status == G_IO_STATUS_NORMAL) {
        status = g_io_channel_read_chars (channel, buffer, sizeof (buffer), &len, &error);

        switch (status) {
        case G_IO_STATUS_NORMAL:
            if (!g_markup_parse_context_parse (ctx, buffer, len, &error)) {
                status = G_IO_STATUS_ERROR;
                g_warning ("Error while parsing XML: %s", error->message);
                g_error_free (error);;
            }
            break;
        case G_IO_STATUS_EOF:
            break;
        case G_IO_STATUS_ERROR:
            g_warning ("Error while reading: %s", error->message);
            g_error_free (error);
            break;
        case G_IO_STATUS_AGAIN:
            /* FIXME: Try again a few times, but really, it never happes, right? */
            break;
        }
    }

    g_io_channel_unref (channel);
    g_markup_parse_context_free (ctx);

    if (parser.current_provider) {
        g_warning ("pending current provider");
        shell_mobile_provider_unref (parser.current_provider);
    }

    if (parser.current_providers) {
        g_warning ("pending current providers");
        provider_list_free (parser.current_providers);
    }

    g_free (parser.current_country);
    g_free (parser.text_buffer);

out:

    return parser.table;
}
Пример #8
0
static void
migrate_history ()
{
  GFileInputStream *input;
  GMarkupParseContext *context;
  GError *error = NULL;
  GFile *file;
  char *filename;
  char buffer[1024];
  HistoryParseData parse_data;

  gchar *temporary_file = g_build_filename (ephy_dot_dir (), "ephy-history.db", NULL);
  /* Do nothing if the history file already exists. Safer than wiping
   * it out. */
  if (g_file_test (temporary_file, G_FILE_TEST_EXISTS)) {
    g_warning ("Did not migrate Epiphany's history, the ephy-history.db file already exists");
    g_free (temporary_file);
    return;
  }

  history_service = ephy_history_service_new (temporary_file);
  g_free (temporary_file);

  memset (&parse_data, 0, sizeof (HistoryParseData));
  parse_data.location = NULL;
  parse_data.title = NULL;
  parse_data.visits = NULL;

  filename = g_build_filename (ephy_dot_dir (),
                               "ephy-history.xml",
                               NULL);

  file = g_file_new_for_path (filename);
  g_free (filename);

  input = g_file_read (file, NULL, &error);
  g_object_unref (file);

  if (error) {
    if (error->code != G_IO_ERROR_NOT_FOUND)
      g_warning ("Could not load Epiphany history data, migration aborted: %s", error->message);

    g_error_free (error);
    return;
  }

  context = g_markup_parse_context_new (&history_parse_funcs, 0, &parse_data, NULL);
  while (TRUE) {
    gssize count = g_input_stream_read (G_INPUT_STREAM (input), buffer, sizeof (buffer), NULL, &error);
    if (count <= 0)
      break;

    if (!g_markup_parse_context_parse (context, buffer, count, &error))
      break;
  }

  g_markup_parse_context_free (context);
  g_input_stream_close (G_INPUT_STREAM (input), NULL, NULL);
  g_object_unref (input);

  if (parse_data.visits) {
    ephy_history_service_add_visits (history_service, parse_data.visits, NULL, (EphyHistoryJobCallback)visit_cb, NULL);
    ephy_history_page_visit_list_free (parse_data.visits);

    while (!all_done)
      g_main_context_iteration (NULL, FALSE);
  }

  g_object_unref (history_service);
}
Пример #9
0
gboolean
gaim_pounces_load(void)
{
	gchar *filename = g_build_filename(gaim_user_dir(), "pounces.xml", NULL);
	gchar *contents = NULL;
	gsize length;
	GMarkupParseContext *context;
	GError *error = NULL;
	PounceParserData *parser_data;

	if (filename == NULL) {
		pounces_loaded = TRUE;
		return FALSE;
	}

	if (!g_file_get_contents(filename, &contents, &length, &error)) {
		gaim_debug(GAIM_DEBUG_ERROR, "pounces",
				   "Error reading pounces: %s\n", error->message);

		g_free(filename);
		g_error_free(error);

		pounces_loaded = TRUE;
		return FALSE;
	}

	parser_data = g_new0(PounceParserData, 1);

	context = g_markup_parse_context_new(&pounces_parser, 0,
										 parser_data, free_parser_data);

	if (!g_markup_parse_context_parse(context, contents, length, NULL)) {
		g_markup_parse_context_free(context);
		g_free(contents);
		g_free(filename);

		pounces_loaded = TRUE;

		return FALSE;
	}

	if (!g_markup_parse_context_end_parse(context, NULL)) {
		gaim_debug(GAIM_DEBUG_ERROR, "pounces", "Error parsing %s\n",
				   filename);

		g_markup_parse_context_free(context);
		g_free(contents);
		g_free(filename);
		pounces_loaded = TRUE;

		return FALSE;
	}

	g_markup_parse_context_free(context);
	g_free(contents);
	g_free(filename);

	pounces_loaded = TRUE;

	return TRUE;
}
Пример #10
0
static storage_status_t xml_load_real( irc_t *irc, const char *my_nick, const char *password, xml_pass_st action )
{
	GMarkupParseContext *ctx;
	struct xml_parsedata *xd;
	char *fn, buf[512];
	GError *gerr = NULL;
	int fd, st;
	
	xd = g_new0( struct xml_parsedata, 1 );
	xd->irc = irc;
	xd->given_nick = g_strdup( my_nick );
	xd->given_pass = g_strdup( password );
	xd->pass_st = action;
	nick_lc( xd->given_nick );
	
	fn = g_strdup_printf( "%s%s%s", global.conf->configdir, xd->given_nick, ".xml" );
	if( ( fd = open( fn, O_RDONLY ) ) < 0 )
	{
		xml_destroy_xd( xd );
		g_free( fn );
		return STORAGE_NO_SUCH_USER;
	}
	g_free( fn );
	
	ctx = g_markup_parse_context_new( &xml_parser, 0, xd, xml_destroy_xd );
	
	while( ( st = read( fd, buf, sizeof( buf ) ) ) > 0 )
	{
		if( !g_markup_parse_context_parse( ctx, buf, st, &gerr ) || gerr )
		{
			xml_pass_st pass_st = xd->pass_st;
			
			g_markup_parse_context_free( ctx );
			close( fd );
			
			if( pass_st == XML_PASS_WRONG )
			{
				g_clear_error( &gerr );
				return STORAGE_INVALID_PASSWORD;
			}
			else
			{
				if( gerr && irc )
					irc_usermsg( irc, "Error from XML-parser: %s", gerr->message );
				
				g_clear_error( &gerr );
				return STORAGE_OTHER_ERROR;
			}
		}
	}
	/* Just to be sure... */
	g_clear_error( &gerr );
	
	g_markup_parse_context_free( ctx );
	close( fd );
	
	if( action == XML_PASS_CHECK_ONLY )
		return STORAGE_OK;
	
	return STORAGE_OK;
}
static gboolean
read_service_providers (GHashTable *countries,
                        const gchar *service_providers,
                        GCancellable *cancellable,
                        GError **error)
{
	GMarkupParseContext *ctx;
	GIOChannel *channel;
	MobileParser parser;
	char buffer[4096];
	GIOStatus status;
	gsize len = 0;

	memset (&parser, 0, sizeof (MobileParser));
    parser.table = countries;

	channel = g_io_channel_new_file (service_providers, "r", error);
	if (!channel) {
		g_prefix_error (error,
		                "Could not read '%s': ",
		                service_providers);
		return FALSE;
	}

	parser.state = PARSER_TOPLEVEL;

	ctx = g_markup_parse_context_new (&mobile_parser, 0, &parser, NULL);

	status = G_IO_STATUS_NORMAL;
	while (status == G_IO_STATUS_NORMAL) {
		status = g_io_channel_read_chars (channel, buffer, sizeof (buffer), &len, error);

		switch (status) {
		case G_IO_STATUS_NORMAL:
			if (!g_markup_parse_context_parse (ctx, buffer, len, error)) {
				status = G_IO_STATUS_ERROR;
				g_prefix_error (error,
				                "Error while parsing XML at '%s': ",
				                service_providers);
			}
			break;
		case G_IO_STATUS_EOF:
			break;
		case G_IO_STATUS_ERROR:
			g_prefix_error (error,
			                "Error while reading '%s': ",
			                service_providers);
			break;
		case G_IO_STATUS_AGAIN:
			/* FIXME: Try again a few times, but really, it never happens, right? */
			break;
		}

		if (g_cancellable_set_error_if_cancelled (cancellable, error))
			status = G_IO_STATUS_ERROR;
	}

	g_io_channel_unref (channel);
	g_markup_parse_context_free (ctx);

	if (parser.current_provider) {
		g_warning ("pending current provider");
		nma_mobile_provider_unref (parser.current_provider);
	}

	if (parser.current_providers) {
		g_warning ("pending current providers");
		provider_list_free (parser.current_providers);
	}

	g_free (parser.current_country);
	g_free (parser.text_buffer);

	return (status == G_IO_STATUS_EOF);
}
/**
 * shell_mobile_providers_parse:
 * @out_ccs: (out) (allow-none): (element-type utf8 utf8): a #GHashTable containing
 *   country codes
 *
 * Returns: (element-type utf8 GList) (transfer container): a
 *   hash table where keys are country names #gchar, values are a #GSList
 *   of #ShellMobileProvider. Everything is destroyed with g_hash_table_destroy().
*/
GHashTable *
shell_mobile_providers_parse (GHashTable **out_ccs)
{
    GMarkupParseContext *ctx;
    GIOChannel *channel;
    MobileParser parser;
    GError *error = NULL;
    char buffer[4096];
    GIOStatus status;
    gsize len = 0;

    memset (&parser, 0, sizeof (MobileParser));

    parser.country_codes = read_country_codes ();
    if (!parser.country_codes)
        goto out;

    channel = g_io_channel_new_file (MOBILE_BROADBAND_PROVIDER_INFO, "r", &error);
    if (!channel) {
        if (error) {
            g_warning ("Could not read " MOBILE_BROADBAND_PROVIDER_INFO ": %s", error->message);
            g_error_free (error);
        } else
            g_warning ("Could not read " MOBILE_BROADBAND_PROVIDER_INFO ": Unknown error");

        goto out;
    }

    parser.table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, provider_list_free);
    parser.state = PARSER_TOPLEVEL;

    ctx = g_markup_parse_context_new (&mobile_parser, 0, &parser, NULL);

    status = G_IO_STATUS_NORMAL;
    while (status == G_IO_STATUS_NORMAL) {
        status = g_io_channel_read_chars (channel, buffer, sizeof (buffer), &len, &error);

        switch (status) {
        case G_IO_STATUS_NORMAL:
            if (!g_markup_parse_context_parse (ctx, buffer, len, &error)) {
                status = G_IO_STATUS_ERROR;
                g_warning ("Error while parsing XML: %s", error->message);
                g_error_free (error);;
            }
            break;
        case G_IO_STATUS_EOF:
            break;
        case G_IO_STATUS_ERROR:
            g_warning ("Error while reading: %s", error->message);
            g_error_free (error);
            break;
        case G_IO_STATUS_AGAIN:
            /* FIXME: Try again a few times, but really, it never happes, right? */
            break;
        }
    }

    g_io_channel_unref (channel);
    g_markup_parse_context_free (ctx);

    if (parser.current_provider) {
        g_warning ("pending current provider");
        shell_mobile_provider_unref (parser.current_provider);
    }

    if (parser.current_providers) {
        g_warning ("pending current providers");
        provider_list_free (parser.current_providers);
    }

    g_free (parser.current_country);
    g_free (parser.text_buffer);

 out:
    if (parser.country_codes) {
        if (out_ccs)
            *out_ccs = parser.country_codes;
        else
            g_hash_table_destroy (parser.country_codes);
    }

    return parser.table;
}
static void wordnet2result(const char *p, size_t sec_size, ParseResult &result, const char *oword)
{
	WnUserData Data;
	Data.oword = oword;
	GMarkupParser parser;
	parser.start_element = NULL;
	parser.end_element = NULL;
	parser.text = func_parse_text;
	parser.passthrough = NULL;
	parser.error = NULL;
	GMarkupParseContext* context = g_markup_parse_context_new(&parser, (GMarkupParseFlags)0, &Data, NULL);
	g_markup_parse_context_parse(context, p, sec_size, NULL);
	g_markup_parse_context_end_parse(context, NULL);
	g_markup_parse_context_free(context);

	LinksPosList links_list;
	std::string res;
	std::string::size_type cur_pos = 0;
	char *eword;
	if (Data.type == "n") {
		res += "Noun\n";
		cur_pos += sizeof("Noun\n")-1;
	} else if (Data.type == "v") {
		res += "Verb\n";
		cur_pos += sizeof("Verb\n")-1;
	} else if (Data.type == "a") {
		res += "Adjective\n";
		cur_pos += sizeof("Adjective\n")-1;
	} else if (Data.type == "s") {
		res += "Adjective satellite\n";
		cur_pos += sizeof("Adjective satellite\n")-1;
	} else if (Data.type == "r") {
		res += "Adverb\n";
		cur_pos += sizeof("Adverb\n")-1;
	} else {
		eword = g_markup_escape_text(Data.type.c_str(), Data.type.length());
		res += eword;
		g_free(eword);
		cur_pos += g_utf8_strlen(Data.type.c_str(), Data.type.length());
	}
	size_t utf8_len;
	for (std::list<std::string>::iterator i = Data.wordlist.begin(); i != Data.wordlist.end(); ++i) {
		if (i != Data.wordlist.begin()) {
			res += '\t';
			cur_pos++;
		}
		res += "<span foreground=\"blue\" underline=\"single\">";
		utf8_len = g_utf8_strlen(i->c_str(), i->length());
		std::string link;
		link = "query://";
		link += *i;
		links_list.push_back(LinkDesc(cur_pos, utf8_len, link));
		eword = g_markup_escape_text(i->c_str(), i->length());
		res += eword;
		g_free(eword);
		res += "</span>";
		cur_pos += utf8_len;
	}
	if (!Data.wordlist.empty()) {
		res += '\n';
		//cur_pos++;
	}
	eword = g_markup_escape_text(Data.gloss.c_str(), Data.gloss.length());
	res += eword;
	g_free(eword);
	//cur_pos += g_utf8_strlen(Data.gloss.c_str(), Data.gloss.length());
	ParseResultItem item;
	item.type = ParseResultItemType_link;
	item.link = new ParseResultLinkItem;
	item.link->pango = res;
	item.link->links_list = links_list;
	result.item_list.push_back(item);
}
static void on_get_http_response(char *buffer, size_t buffer_len, gpointer userdata)
{
	if (!buffer) {
		return;
	}
	const char *p = g_strstr_len(buffer, buffer_len, "\r\n\r\n");
	if (!p) {
		return;
	}
	p += 4;
	QueryInfo *qi = (QueryInfo *)userdata;
	NetDictResponse *resp = new NetDictResponse;
	resp->bookname = _("Dict.cn");
	resp->booklink = "http://www.dict.cn";
	resp->word = qi->word; // So neen't free qi->word;
	if (use_html_or_xml) {
		std::string charset;
		char *p3 = g_strstr_len(p, buffer_len - (p - buffer), "charset=");
		if (p3) {
			p3 += sizeof("charset=") -1;
			char *p4 = strchr(p3, '\"');
			if (p4) {
				charset.assign(p3, p4-p3);
			}
		}
		gchar *content;
		if (charset.empty()) {
			content = NULL;
		} else {
			content = g_convert(p, buffer_len - (p - buffer), "UTF-8", charset.c_str(), NULL, NULL, NULL);
			p = content;
		}
		resp->data = NULL;
		if (p) {
			const char *body = strcasestr(p, "<body");
			if (body) {
				const char *body_end = strcasestr(p, "</body>");
				if (body_end) {
					body_end += sizeof("</body>") -1;
					std::string html(body, body_end - body);
					resp->data = build_dictdata('h', html.c_str());
				}
			}
		}
		g_free(content);
	} else {
		const char *xml = g_strstr_len(p, buffer_len - (p - buffer), "<dict>");
		if (!xml) {
			return;
		}
		const char *xml_end = g_strstr_len(xml+6, buffer_len - (xml+6 - buffer), "</dict>");
		if (!xml_end) {
			return;
		}
		xml_end += 7;
		dict_ParseUserData Data;
		GMarkupParser parser;
		parser.start_element = dict_parse_start_element;
		parser.end_element = dict_parse_end_element;
		parser.text = dict_parse_text;
		parser.passthrough = NULL;
		parser.error = NULL;
		GMarkupParseContext* context = g_markup_parse_context_new(&parser, (GMarkupParseFlags)0, &Data, NULL);
		g_markup_parse_context_parse(context, xml, xml_end - xml, NULL);
		g_markup_parse_context_end_parse(context, NULL);
		g_markup_parse_context_free(context);
		if (Data.def == "Not Found") {
			resp->data = NULL;
		} else {
			std::string definition;
			if (!Data.pron.empty()) {
				definition += "[";
				definition += Data.pron;
				definition += "]\n";
			}
			definition += Data.def;
			if (!Data.rel.empty()) {
				definition += "\n";
				definition += Data.rel;
			}
			if (!Data.sentences.empty()) {
				definition += "\n\n例句与用法:";
				int index = 1;
				char *tmp_str;
				for (std::list<std::pair<std::string, std::string> >::iterator i = Data.sentences.begin(); i != Data.sentences.end(); ++i) {
					tmp_str = g_strdup_printf("\n%d. %s\n   %s", index, i->first.c_str(), i->second.c_str());
					definition += tmp_str;
					g_free(tmp_str);
					index++;
				}
			}
			resp->data = build_dictdata('m', definition.c_str());
		}
	}
	plugin_service->netdict_save_cache_resp(DICTDOTCN, qi->word, resp);
	plugin_service->show_netdict_resp(resp, qi->ismainwin);
	delete qi;
	keyword_list.remove(qi);
}
Пример #15
0
static char*
load_state (const char *previous_save_file)
{
  GMarkupParseContext *context;
  GError *error;
  ParseData parse_data;
  char *text;
  gsize length;
  char *session_file;

  session_file = g_strconcat (g_get_user_config_dir (),
                              G_DIR_SEPARATOR_S "metacity"
                              G_DIR_SEPARATOR_S "sessions" G_DIR_SEPARATOR_S,
                              previous_save_file,
                              NULL);

  error = NULL;
  if (!g_file_get_contents (session_file,
                            &text,
                            &length,
                            &error))
    {
      char *canonical_session_file = session_file;

      /* Maybe they were doing it the old way, with ~/.metacity */
      session_file = g_strconcat (g_get_home_dir (),
                                  G_DIR_SEPARATOR_S ".metacity"
                                  G_DIR_SEPARATOR_S "sessions"
                                  G_DIR_SEPARATOR_S,
                                  previous_save_file,
                                  NULL);
      
      if (!g_file_get_contents (session_file,
                                &text,
                                &length,
                                NULL))
        {
          /* oh, just give up */

          meta_warning (_("Failed to read saved session file %s: %s\n"),
                    canonical_session_file, error->message);
          g_error_free (error);
          g_free (session_file);
          g_free (canonical_session_file);
          return NULL;
        }

      g_free (canonical_session_file);
    }

  meta_topic (META_DEBUG_SM, "Parsing saved session file %s\n", session_file);
  g_free (session_file);
  session_file = NULL;
  
  parse_data.info = NULL;
  parse_data.previous_id = NULL;
  
  context = g_markup_parse_context_new (&metacity_session_parser,
                                        0, &parse_data, NULL);

  error = NULL;
  if (!g_markup_parse_context_parse (context,
                                     text,
                                     length,
                                     &error))
    goto error;
  
  
  error = NULL;
  if (!g_markup_parse_context_end_parse (context, &error))
    goto error;

  g_markup_parse_context_free (context);

  goto out;

 error:
  
  meta_warning (_("Failed to parse saved session file: %s\n"),
                error->message);
  g_error_free (error);

  if (parse_data.info)
    session_info_free (parse_data.info);

  g_free (parse_data.previous_id);
  parse_data.previous_id = NULL;
  
 out:
  
  g_free (text);

  return parse_data.previous_id;
}
Пример #16
0
static GHashTable *
parse_resource_file (const gchar *filename,
                     gboolean     collect_data,
                     GHashTable  *files)
{
  GMarkupParser parser = { start_element, end_element, text };
  ParseState state = { 0, };
  GMarkupParseContext *context;
  GError *error = NULL;
  gchar *contents;
  GHashTable *table = NULL;
  gsize size;

  if (!g_file_get_contents (filename, &contents, &size, &error))
    {
      g_printerr ("%s\n", error->message);
      g_clear_error (&error);
      return NULL;
    }

  state.collect_data = collect_data;
  state.table = g_hash_table_ref (files);

  context = g_markup_parse_context_new (&parser,
					G_MARKUP_TREAT_CDATA_AS_TEXT |
					G_MARKUP_PREFIX_ERROR_POSITION,
					&state, NULL);

  if (!g_markup_parse_context_parse (context, contents, size, &error) ||
      !g_markup_parse_context_end_parse (context, &error))
    {
      g_printerr ("%s: %s.\n", filename, error->message);
      g_clear_error (&error);
    }
  else
    {
      GHashTableIter iter;
      const char *key;
      char *mykey;
      gsize key_len;
      FileData *data;
      GVariant *v_data;
      GVariantBuilder builder;
      GvdbItem *item;

      table = gvdb_hash_table_new (NULL, NULL);

      g_hash_table_iter_init (&iter, state.table);
      while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
	{
	  key_len = strlen (key);
	  mykey = g_strdup (key);

	  item = gvdb_hash_table_insert (table, key);
	  gvdb_item_set_parent (item,
				get_parent (table, mykey, key_len));

	  g_free (mykey);

	  g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));

	  g_variant_builder_add (&builder, "u", data->size); /* Size */
	  g_variant_builder_add (&builder, "u", data->flags); /* Flags */

	  v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
					    data->content, data->content_size, TRUE,
					    g_free, data->content);
	  g_variant_builder_add_value (&builder, v_data);
	  data->content = NULL; /* Take ownership */

	  gvdb_item_set_value (item,
			       g_variant_builder_end (&builder));
	}
    }

  g_hash_table_unref (state.table);
  g_markup_parse_context_free (context);
  g_free (contents);

  return table;
}
Пример #17
0
/**********************************************************************
 * errlog2event_hash_init:
 * @custom_handle: Plugin's data pointer.
 * 
 * Initializes the Error Log to event translation hash table.
 *
 * Returns:
 * SA_OK - Normal operation.
 * SA_ERR_HPI_OUT_OF_SPACE - No memory to allocate hash table structures.
 * SA_ERR_HPI_INVALID_PARAMS - @custom_handle NULL
 **********************************************************************/
SaErrorT errlog2event_hash_init(struct snmp_bc_hnd *custom_handle) {
        GMarkupParser parser;
        GMarkupParseContext *pcontext;
        gboolean rc;
        GError *err;
        struct errlog2event_hash_info user_data;
        if (!custom_handle) {
                dbg("Invalid parameter.");
                return(SA_ERR_HPI_INVALID_PARAMS);
        }
	
        err = NULL;
        snmp_bc_lock(snmp_bc_plock);
	/* Initialize hash table */
        errlog2event_hash = g_hash_table_new(g_str_hash, g_str_equal);
        if (errlog2event_hash == NULL) {
                dbg("No memory.");
                snmp_bc_unlock(snmp_bc_plock);
                return(SA_ERR_HPI_OUT_OF_SPACE);
	}
	
	/* Initialize user data used in parsing XML events */
	user_data.hashtable = errlog2event_hash;

        /* Initialize XML parser */
        memset(&parser, 0, sizeof(parser));
        parser.start_element = event_start_element;
        pcontext = g_markup_parse_context_new(&parser, 0, &user_data, NULL);
        if (pcontext == NULL) {
		dbg("No memory.");
                snmp_bc_unlock(snmp_bc_plock);
		return(SA_ERR_HPI_OUT_OF_SPACE);
        }

        /* Parse XML events */
        rc = g_markup_parse_context_parse(pcontext,
                                          (const gchar *)eventxml,
                                          (gssize)strlen(eventxml), &err);
        if (rc == FALSE || err != NULL) {
                if (err != NULL) {
                        dbg("Parse error=%s.", err->message);
                        g_error_free(err);
                }
                else {
                        dbg("Unknown XML parse error.");
                }
                g_markup_parse_context_free(pcontext);
                snmp_bc_unlock(snmp_bc_plock);
                return(SA_ERR_HPI_INTERNAL_ERROR);
        }
        g_markup_parse_context_end_parse(pcontext, &err);
        g_markup_parse_context_free(pcontext);

        /* Make sure there are elements in the hash table */
        if (g_hash_table_size(errlog2event_hash) == 0) {
                dbg("Hash table is empty.");
                snmp_bc_unlock(snmp_bc_plock);
                return(SA_ERR_HPI_INTERNAL_ERROR);
        }
        
        snmp_bc_unlock(snmp_bc_plock);
	return(SA_OK);
}
Пример #18
0
/**
 * Function reading an XML file specifying a cup.
 * @param cup_name name of the xml file (e.g. 'cup_england_fa.xml')
 * to be read. Full path is not necessary, if the file is located in
 * one of the suppport directories; neither are the prefix 'cup_'
 * or the suffix '.xml'.
 * @param cups The array we append the new cup to.
 */
void
xml_cup_read(const gchar *cup_name, GArray *cups)
{
#ifdef DEBUG
    printf("xml_cup_read\n");
#endif

    gchar *file_name = file_find_support_file(cup_name, FALSE);
    GMarkupParser parser = {xml_cup_read_start_element,
			    xml_cup_read_end_element,
			    xml_cup_read_text, NULL, NULL};
    GMarkupParseContext *context;
    gchar *file_contents;
    gsize length;
    GError *error = NULL;
    gchar buf[SMALL];
    gint i;

    context = 
	g_markup_parse_context_new(&parser, 0, NULL, NULL);

    if(file_name == NULL)
    {
	sprintf(buf, "cup_%s.xml", cup_name);
	file_name = file_find_support_file(buf, TRUE);
    }

    if(!g_file_get_contents(file_name, &file_contents, &length, &error))
    {
	debug_print_message("xml_cup_read: error reading file %s\n", file_name);
	misc_print_error(&error, FALSE);
	return;
    }

    state = STATE_CUP;
    strcpy(buf, file_name);
    g_free(file_name);

    if(g_markup_parse_context_parse(context, file_contents, length, &error))
    {
	g_markup_parse_context_end_parse(context, NULL);	
	g_markup_parse_context_free(context);
	g_free(file_contents);
    }
    else
    {
	g_critical("xml_cup_read: error parsing file %s\n", buf);
	misc_print_error(&error, TRUE);
    }

    new_cup.id = cup_id_new;
    league_cup_adjust_week_breaks(new_cup.week_breaks, new_cup.week_gap);

    for(i = 0; i < new_cup.rounds->len; i++)
        if(g_array_index(new_cup.rounds, CupRound, i).name == NULL)
        {
            cup_get_round_name(&new_cup, i, buf);
            g_array_index(new_cup.rounds, CupRound, i).name = g_strdup(buf);
        }

    g_array_append_val(cups, new_cup);
}