Ejemplo n.º 1
0
static gint
generate_support_data (const gchar *filename)
{
	GIOChannel *channel;
	GError     *error = NULL;

	if (g_str_equal (filename, "-")) {
		channel = g_io_channel_unix_new (0);
	}
	else if (!(channel = g_io_channel_new_file (filename, "w", &error))) {
		g_printerr ("%s\n", error->message);
		g_error_free (error);
		return EXIT_FAILURE;
	}

	g_io_channel_write_chars (channel, "[system]\n", -1, NULL, NULL);
	generate_date (channel);
	generate_system_info (channel);
	g_io_channel_write_chars (channel, "\n", -1, NULL, NULL);

	g_io_channel_write_chars (channel, "[perfkit]\n", -1, NULL, NULL);
	write_kv (channel, "lib.version", PK_VERSION_S);
	write_kv (channel, "agent.version", PKA_VERSION_S);
	g_io_channel_write_chars (channel, "\n", -1, NULL, NULL);

	generate_channels (channel);

	/* TODO */

	if (!g_io_channel_flush (channel, &error)) {
		g_printerr ("%s\n", error->message);
		g_error_free (error);
		return EXIT_FAILURE;
	}

	g_io_channel_close (channel);

	return EXIT_SUCCESS;
}
Ejemplo n.º 2
0
static void
test_small_writes (void)
{
  GIOChannel *io;
  GIOStatus status;
  guint cnt; 
  gchar tmp;
  GError *error = NULL;

  io = g_io_channel_new_file ("iochannel-test-outfile", "w", &error);
  if (error)
    {
      g_warning ("Unable to open file %s: %s", 
		 "iochannel-test-outfile", 
		 error->message);
      g_error_free (error);
      
      exit (1);
    }

  g_io_channel_set_encoding (io, NULL, NULL);
  g_io_channel_set_buffer_size (io, 1022);

  cnt = 2 * g_io_channel_get_buffer_size (io);
  tmp = 0;
 
  while (cnt)
    {
      status = g_io_channel_write_chars (io, &tmp, 1, NULL, NULL);
      if (status == G_IO_STATUS_ERROR)
	break;
      if (status == G_IO_STATUS_NORMAL)
	cnt--;
    }

  g_assert (status == G_IO_STATUS_NORMAL);

  g_io_channel_unref (io);
}
Ejemplo n.º 3
0
/* SYNTAX: CAT <file> */
static void cmd_cat(const char *data)
{
    char *fname, *fposstr;
    void *free_arg;
    int fpos;
    GIOChannel *handle;
    GString *buf;
    gsize tpos;

    if (!cmd_get_params(data, &free_arg, 2, &fname, &fposstr))
        return;

    fname = convert_home(fname);
    fpos = atoi(fposstr);
    cmd_params_free(free_arg);

    handle = g_io_channel_new_file(fname, "r", NULL);
    g_free(fname);

    if (handle == NULL) {
        /* file not found */
        printtext(NULL, NULL, MSGLEVEL_CLIENTERROR,
                  "%s", g_strerror(errno));
        return;
    }

    g_io_channel_set_encoding(handle, NULL, NULL);
    g_io_channel_seek_position(handle, fpos, G_SEEK_SET, NULL);
    buf = g_string_sized_new(512);
    while (g_io_channel_read_line_string(handle, buf, &tpos, NULL) == G_IO_STATUS_NORMAL) {
        buf->str[tpos] = '\0';
        printtext(NULL, NULL, MSGLEVEL_CLIENTCRAP |
                  MSGLEVEL_NEVER, "%s", buf->str);
    }
    g_string_free(buf, TRUE);

    g_io_channel_unref(handle);
}
Ejemplo n.º 4
0
static gboolean
theora_enc_start (GstVideoEncoder * benc)
{
    GstTheoraEnc *enc;

    GST_DEBUG_OBJECT (benc, "start: init theora");
    enc = GST_THEORA_ENC (benc);

    th_info_init (&enc->info);
    th_comment_init (&enc->comment);
    enc->packetno = 0;

    if (enc->multipass_mode >= MULTIPASS_MODE_FIRST_PASS) {
        GError *err = NULL;

        if (!enc->multipass_cache_file) {
            GST_ELEMENT_ERROR (enc, LIBRARY, SETTINGS, (NULL), (NULL));
            return FALSE;
        }
        enc->multipass_cache_fd =
            g_io_channel_new_file (enc->multipass_cache_file,
                                   (enc->multipass_mode == MULTIPASS_MODE_FIRST_PASS ? "w" : "r"), &err);

        if (enc->multipass_mode == MULTIPASS_MODE_SECOND_PASS)
            enc->multipass_cache_adapter = gst_adapter_new ();

        if (!enc->multipass_cache_fd) {
            GST_ELEMENT_ERROR (enc, RESOURCE, OPEN_READ, (NULL),
                               ("Failed to open multipass cache file: %s", err->message));
            g_error_free (err);
            return FALSE;
        }

        g_io_channel_set_encoding (enc->multipass_cache_fd, NULL, NULL);
    }

    return TRUE;
}
Ejemplo n.º 5
0
G_MODULE_EXPORT gboolean select_vex_for_import(GtkWidget *widget, gpointer data)
{
	MtxFileIO *fileio = NULL;
	gchar *filename = NULL;
	GIOChannel *iochannel = NULL;

	if (!DATA_GET(global_data,"interrogated"))
		return FALSE;

	fileio = g_new0(MtxFileIO ,1);
	fileio->external_path = g_strdup("MTX_VexFiles");
	fileio->title = g_strdup("Select your VEX file to import");
	fileio->parent = lookup_widget_f("main_window");
	fileio->on_top = TRUE;
	fileio->action = GTK_FILE_CHOOSER_ACTION_OPEN;

	filename = choose_file(fileio);
	if (filename == NULL)
	{
		update_logbar_f("tools_view","warning",_("NO FILE chosen for VEX import\n"),FALSE,FALSE,FALSE);
		return FALSE;
	}

	iochannel = g_io_channel_new_file(filename, "r+",NULL);
	if (!iochannel)
	{
		update_logbar_f("tools_view","warning",_("File open FAILURE! \n"),FALSE,FALSE,FALSE);
		return FALSE;
	}
	update_logbar_f("tools_view",NULL,_("VEX File Closed\n"),FALSE,FALSE,FALSE);
	gtk_entry_set_text(GTK_ENTRY(lookup_widget_f("tools_vex_comment_entry")),"");

	all_table_import(iochannel);
	g_io_channel_shutdown(iochannel,TRUE,NULL);
	g_io_channel_unref(iochannel);
	free_mtxfileio(fileio);
	return TRUE;
}
Ejemplo n.º 6
0
Archivo: io.c Proyecto: semarie/vimb
gboolean io_init_fifo(const char *name)
{
    char *fname, *path;

    /* create fifo in directory as vimb-fifo-$PID */
    fname = g_strdup_printf(PROJECT "-fifo-%s", name);
    path  = g_build_filename(g_get_user_config_dir(), PROJECT, fname, NULL);
    g_free(fname);

    /* if the file already exists - remove this first */
    if (g_file_test(path, G_FILE_TEST_IS_REGULAR)) {
        unlink(path);
    }

    if (mkfifo(path, 0666) == 0) {
        GError *error    = NULL;
        /* use r+ to avoid blocking caused by wait of a writer */
        GIOChannel *chan = g_io_channel_new_file(path, "r+", &error);
        if (chan) {
            if (g_io_add_watch(chan, G_IO_IN|G_IO_HUP, (GIOFunc)fifo_watch, NULL)) {
                /* don't free path - because we want to keep the value in
                 * vb.state.fifo_path still accessible */
                vb.state.fifo_path = path;
                g_setenv("VIMB_FIFO", path, TRUE);

                return true;
            }
        } else {
            g_warning ("Can't open fifo: %s", error->message);
            g_error_free(error);
        }
    } else {
        g_warning("Can't create fifo %s", path);
    }
    g_free(path);

    return false;
}
Ejemplo n.º 7
0
/* Result must be freed */
X264_Gtk *
x264_gtk_load (void)
{
  X264_Gtk     *x264_gtk;
  GIOChannel   *file;
  GError       *error = NULL;
  gchar        *filename;

  x264_gtk = (X264_Gtk *)g_malloc0 (sizeof (X264_Gtk));
  if (!x264_gtk)
    return NULL;

  filename = x264_gtk_path ("x264.cfg");
  file = g_io_channel_new_file (filename, "r", &error);
  if (error) {
    g_print (_("x264.cfg: %s\n"), error->message);
    g_print (_("Loading default configuration\n"));
    _default_set (x264_gtk);
  }
  else {
    GIOStatus status;
    gchar    *data = NULL;
    gsize     length;

    g_print (_("Loading configuration from %s\n"), filename);
    g_io_channel_set_encoding (file, NULL, NULL);
    status = g_io_channel_read_to_end (file, &data, &length, &error);
    if ((status == G_IO_STATUS_NORMAL) &&
        (length == sizeof (X264_Gtk))) {
      memcpy (x264_gtk, data, length);
    }
    g_io_channel_shutdown (file, TRUE, NULL);
    g_io_channel_unref (file);
  }
  g_free (filename);

  return x264_gtk;
}
Ejemplo n.º 8
0
Archivo: UgUtils.c Proyecto: Endz0/uget
// ------------------------------------------------------------------
// URI list functions
// get URIs from text file
GList*	ug_text_file_get_uris (const gchar* file_utf8, GError** error)
{
	GIOChannel*		channel;
	GList*			list;
	gchar*			string;
	gchar*			escaped;
	gsize			line_len;

	string = g_filename_from_utf8 (file_utf8, -1, NULL, NULL, NULL);
	channel = g_io_channel_new_file (string, "r", error);
	g_free (string);
	if (channel == NULL)
		return NULL;
	ug_io_channel_decide_encoding (channel);

	list = NULL;
	while (g_io_channel_read_line (channel, &string, NULL, &line_len, NULL) == G_IO_STATUS_NORMAL) {
		if (string == NULL)
			continue;
		string[line_len] = 0;		// clear '\n' in tail
		// check URI scheme
		if (ug_uri_scheme_len (string) == 0)
			g_free (string);
		else {
			// if URI is not valid UTF-8 string, escape it.
			if (g_utf8_validate (string, -1, NULL) == FALSE) {
				escaped = g_uri_escape_string (string,
						G_URI_RESERVED_CHARS_ALLOWED_IN_PATH, FALSE);
				g_free (string);
				string = escaped;
			}
			list = g_list_prepend (list, string);
		}
	}
	g_io_channel_unref (channel);
	return g_list_reverse (list);
}
Ejemplo n.º 9
0
// to be called at program start and anytime the value of auto-log changes
static void
log_toggle (void)
{
	char *key;
	gboolean autolog;

	key = preferences_get_key (PREF_AUTO_LOG);
	autolog = preferences_get_bool (key);
	g_free (key);

	if (autolog && log_file == NULL) {
		GError *err;
		char *filename, *name, *path, *path_key;

		path_key = preferences_get_key (PREF_LOG_PATH);
		path = preferences_get_string (path_key);
		g_free (path_key);

		name = warlock_log_get_name ();

		filename = g_build_filename (path, name, NULL);

		g_free (name);
		g_free (path);

		err = NULL;
		log_file = g_io_channel_new_file (filename, "a", &err);
		if (log_file == NULL) {
			echo_f ("Error: \"%s\" for file \"%s\".\n",
					err->message, filename);
		}
	} else if (!autolog && log_file != NULL) {
		g_io_channel_close (log_file);
		g_io_channel_unref (log_file);
		log_file = NULL;
	}
}
Ejemplo n.º 10
0
static gboolean get_i8042_io_ports(GError **error) {
    GIOChannel *io_ports_file = g_io_channel_new_file("/proc/ioports", "r",
                                                      error);
    gchar *line;
    GIOStatus rc;

    ports = g_hash_table_new(g_direct_hash, g_direct_equal);

    if (!io_ports_file)
        return FALSE;

    for (rc = g_io_channel_read_line(io_ports_file, &line, NULL, NULL, error);
         rc == G_IO_STATUS_NORMAL;
         rc = g_io_channel_read_line(io_ports_file, &line, NULL, NULL, error)) {
        guint min, max;
        gint parsed_count;
        gchar *device_name;

        errno = 0;
        parsed_count = sscanf(line, "%x-%x : %m[^\n]\n",
                              &min, &max, &device_name);
        if (parsed_count != 3 || errno != 0 ||
            strcmp(device_name, "keyboard") != 0)
            goto next;

        for (int i = min; i <= max; i++) {
            g_hash_table_insert(ports, GUINT_TO_POINTER(i),
                                GUINT_TO_POINTER(i));
        }
next:
        g_free(line);
    }

    g_io_channel_unref(io_ports_file);

    return TRUE;
}
/*
  We must save the binary data in separate files because
  mmap wants getpagesize() alignment.  If we append all
  the data to one file then we don't know the appropriate
  padding since the page size isn't fixed.
*/
static void
_file_index_id_save_entries (gpointer * _key,
    GstFileIndexId * ii, gchar * prefix)
{
  GError *err;
  gchar *path;
  GIOChannel *chan;

  if (!ii->array)
    return;

  err = NULL;
  path = g_strdup_printf ("%s/%d", prefix, ii->id);
  chan = g_io_channel_new_file (path, "w", &err);
  g_free (path);
  if (err)
    goto fail;

  g_io_channel_set_encoding (chan, NULL, &err);
  if (err)
    goto fail;

  g_io_channel_write_chars (chan,
      ii->array->data, ARRAY_TOTAL_SIZE (ii), NULL, &err);
  if (err)
    goto fail;

  g_io_channel_shutdown (chan, TRUE, &err);
  if (err)
    goto fail;

  g_io_channel_unref (chan);
  return;

fail:
  GST_ERROR ("%s", err->message);
}
Ejemplo n.º 12
0
gint
gtk_module_init (gint   argc,
                 gchar *argv[])
{
    gchar      *filename;
    GError     *error = NULL;

    /* get our destination filename */
    if (g_getenv ("GDKRECORD_FILENAME"))
        filename = g_strdup (g_getenv ("GDKRECORD_FILENAME"));
    else
        filename = g_strdup_printf ("%d-%s.gdkrecord",
                                    getpid (),
                                    g_get_prgname ());

    /* open the file for writing */
    if (!(channel = g_io_channel_new_file (filename, "w", &error))) {
        g_warning ("Could not initialize gdkrecord: %s",
                   error->message);
        g_error_free (error);
        g_free (filename);
        return -1;
    }

    g_free (filename);

    /* setup our timer for event timings */
    timer = g_timer_new ();

    /* register our event handler to record and then pass to gtk */
    gdk_event_handler_set (gdkrecord_event_handler,
                           channel,
                           gdkrecord_event_destroy);

    return 0;
}
Ejemplo n.º 13
0
/**
 * catch_log_init:
 * @stdout_: Indicates logging should be written to stdout.
 * @filename: An optional file in which to store logs.
 *
 * Initializes the logging subsystem.
 */
void
catch_log_init (gboolean     stdout_,
                const gchar *filename)
{
   static gsize initialized = FALSE;
   GIOChannel *channel;

   if (g_once_init_enter(&initialized)) {
      channels = g_ptr_array_new();
      if (filename) {
         channel = g_io_channel_new_file(filename, "a", NULL);
         g_ptr_array_add(channels, channel);
      }
      if (stdout_) {
         channel = g_io_channel_unix_new(STDOUT_FILENO);
         g_ptr_array_add(channels, channel);
      }

#ifdef __linux__
      {
         struct utsname u;
         uname(&u);
         memcpy(hostname, u.nodename, sizeof(hostname));
      }
#else
#ifdef __APPLE__
      gethostname(hostname, sizeof (hostname));
#else
#error "Target platform not supported"
#endif /* __APPLE__ */
#endif /* __linux__ */

      g_log_set_default_handler(catch_log_handler, NULL);
      g_once_init_leave(&initialized, TRUE);
   }
}
Ejemplo n.º 14
0
static GHashTable *
read_country_codes (void)
{
    GHashTable *table;
    GIOChannel *channel;
    GString *buffer;
    GError *error = NULL;
    GIOStatus status;

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

        return NULL;
    }

    table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
    buffer = g_string_sized_new (32);

    status = G_IO_STATUS_NORMAL;
    while (status == G_IO_STATUS_NORMAL) {
        status = g_io_channel_read_line_string (channel, buffer, NULL, &error);

        switch (status) {
        case G_IO_STATUS_NORMAL:
            if (buffer->str[0] != '#') {
                char **pieces;

                pieces = g_strsplit (buffer->str, "\t", 2);

                /* Hack for rh#556292; iso3166.tab is just wrong */
                pieces[1] = pieces[1] ? g_strchomp (pieces[1]) : NULL;
                if (pieces[1] && !strcmp (pieces[1], "Britain (UK)")) {
                    g_free (pieces[1]);
                    pieces[1] = g_strdup (_("United Kingdom"));
                }

                g_hash_table_insert (table, pieces[0], pieces[1]);
                g_free (pieces);
            }

            g_string_truncate (buffer, 0);
            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_string_free (buffer, TRUE);
    g_io_channel_unref (channel);

    return table;
}
Ejemplo n.º 15
0
void
scrollback_load (session *sess)
{
	char *buf;
	char *text;
	time_t stamp;
	int lines;
	GIOChannel *io;
	GError *file_error = NULL;
	GError *io_err = NULL;

	if (sess->text_scrollback == SET_DEFAULT)
	{
		if (!prefs.hex_text_replay)
			return;
	}
	else
	{
		if (sess->text_scrollback != SET_ON)
			return;
	}

	if ((buf = scrollback_get_filename (sess)) == NULL)
		return;

	io = g_io_channel_new_file (buf, "r", &file_error);
	g_free (buf);
	if (!io)
		return;

	lines = 0;

	while (1)
	{
		gsize n_bytes;
		GIOStatus io_status;

		io_status = g_io_channel_read_line (io, &buf, &n_bytes, NULL, &io_err);
		
		if (io_status == G_IO_STATUS_NORMAL)
		{
			char *buf_tmp;

			/* If nothing but funny trailing matter e.g. 0x0d or 0x0d0a, toss it */
			if (n_bytes >= 1 && buf[0] == 0x0d)
			{
				g_free (buf);
				continue;
			}

			n_bytes--;
			buf_tmp = buf;
			buf = g_strndup (buf_tmp, n_bytes);
			g_free (buf_tmp);

			/*
			 * Some scrollback lines have three blanks after the timestamp and a newline
			 * Some have only one blank and a newline
			 * Some don't even have a timestamp
			 * Some don't have any text at all
			 */
			if (buf[0] == 'T')
			{
				if (sizeof (time_t) == 4)
					stamp = strtoul (buf + 2, NULL, 10);
				else
					stamp = strtoull (buf + 2, NULL, 10); /* in case time_t is 64 bits */
				text = strchr (buf + 3, ' ');
				if (text && text[1])
				{
					if (prefs.hex_text_stripcolor_replay)
					{
						text = strip_color (text + 1, -1, STRIP_COLOR);
					}

					fe_print_text (sess, text, stamp, TRUE);

					if (prefs.hex_text_stripcolor_replay)
					{
						g_free (text);
					}
				}
				else
				{
					fe_print_text (sess, "  ", stamp, TRUE);
				}
			}
			else
			{
				if (strlen (buf))
					fe_print_text (sess, buf, 0, TRUE);
				else
					fe_print_text (sess, "  ", 0, TRUE);
			}
			lines++;

			g_free (buf);
		}

		else
			break;
	}

	g_io_channel_unref (io);

	sess->scrollwritten = lines;

	if (lines)
	{
		text = ctime (&stamp);
		text[24] = 0;	/* get rid of the \n */
		buf = g_strdup_printf ("\n*\t%s %s\n\n", _("Loaded log from"), text);
		fe_print_text (sess, buf, 0, TRUE);
		g_free (buf);
		/*EMIT_SIGNAL (XP_TE_GENMSG, sess, "*", buf);*/
	}
}
Ejemplo n.º 16
0
/** \brief Save configuration data.
 *  \return 0 on success, 1 if an error occured.
 *
 * This function saves the configuration data currently stored in
 * memory to the gpredict.cfg file.
 */
guint sat_cfg_save        ()
{
    gsize       length;
    gsize       written;
    GError     *error = NULL;
    gchar      *cfgstr;
    gchar      *keyfile;
    gchar      *confdir;
    GIOChannel *cfgfile;
    guint       err = 0;

    /* convert configuration data struct to charachter string */
    cfgstr = g_key_file_to_data (config, &length, &error);

    if (error != NULL) {
        sat_log_log (SAT_LOG_LEVEL_ERROR,
                     _("%s: Could not create config data (%s)."),
                     __FUNCTION__, error->message);

        g_clear_error (&error);

        err = 1;
    }
    else {
        /* create and open a file for writing */
        confdir = get_user_conf_dir ();
        keyfile = g_strconcat (confdir, G_DIR_SEPARATOR_S, "gpredict.cfg", NULL);
        g_free (confdir);
        cfgfile = g_io_channel_new_file (keyfile, "w", &error);
        g_free (keyfile);

        if (error != NULL) {
            sat_log_log (SAT_LOG_LEVEL_ERROR,
                         _("%s: Could not create config file (%s)."),
                         __FUNCTION__, error->message);

            g_clear_error (&error);

            err = 1;
        }
        else {
            g_io_channel_write_chars (cfgfile,
                                      cfgstr,
                                      length,
                                      &written,
                                      &error);

            g_io_channel_shutdown (cfgfile, TRUE, NULL);
            g_io_channel_unref (cfgfile);

            if (error != NULL) {
                sat_log_log (SAT_LOG_LEVEL_ERROR,
                             _("%s: Error writing config data (%s)."),
                             __FUNCTION__, error->message);

                g_clear_error (&error);

                err = 1;
            }
            else if (length != written) {
                sat_log_log (SAT_LOG_LEVEL_WARN,
                             _("%s: Wrote only %d out of %d chars."),
                             __FUNCTION__, written, length);

                err = 1;
            }
            else {
                sat_log_log (SAT_LOG_LEVEL_MSG,
                             _("%s: Configuration saved."),
                             __FUNCTION__);

                err = 0;
            }
        }

        g_free (cfgstr);
    }

    return err;
}
Ejemplo n.º 17
0
gint main (gint argc, gchar * argv[])
{
    GIOChannel *gio_r, *gio_w ;
    GError *gerr = NULL;
    GString *buffer;
    char *filename;
    char *srcdir = getenv ("srcdir");
    gint rlength = 0;
    glong wlength = 0;
    gsize length_out;
    const gchar encoding[] = "ISO-8859-5";
    GIOStatus status;
    GIOFlags flags;

  #ifdef SYMBIAN
  g_log_set_handler (NULL,  G_LOG_FLAG_FATAL| G_LOG_FLAG_RECURSION | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG, &mrtLogHandler, NULL);
  g_set_print_handler(mrtPrintHandler);
  #endif /*SYMBIAN*/
	  

    if (!srcdir)
      srcdir = "c:";
    filename = g_strconcat (srcdir, G_DIR_SEPARATOR_S, "iochannel-test-infile", NULL);
  
    setbuf (stdout, NULL); /* For debugging */

    gio_r = g_io_channel_new_file (filename, "r", &gerr);
    if (gerr)
      {
        g_warning ("Unable to open file %s: %s", filename, gerr->message);
        g_error_free (gerr);
        
        g_assert(FALSE && "iochannel-test failed");
        
        #if SYMBIAN
  		testResultXml("iochannel-test");
  		#endif /* EMULATOR */
        
        return 1;
      }
    gio_w = g_io_channel_new_file ("c:\\iochannel-test-outfile", "w", &gerr);
    if (gerr)
      {
        g_warning ("Unable to open file %s: %s", "iochannel-test-outfile", gerr->message);
        g_error_free (gerr);
        
        g_assert(FALSE && "iochannel-test failed");
        
        #if SYMBIAN
  		testResultXml("iochannel-test");
  		#endif /* EMULATOR */
        
        return 1;
      }

    g_io_channel_set_encoding (gio_r, encoding, &gerr);
    if (gerr)
      {
        g_warning (gerr->message);
        g_error_free (gerr);
        
        g_assert(FALSE && "iochannel-test failed");
        
        #if SYMBIAN
  		testResultXml("iochannel-test");
  		#endif /* EMULATOR */
        
        return 1;
      }
    
    g_io_channel_set_buffer_size (gio_r, BUFFER_SIZE);

    status = g_io_channel_set_flags (gio_r, G_IO_FLAG_NONBLOCK, &gerr);
    if (status == G_IO_STATUS_ERROR)
      {
        g_warning (gerr->message);
        g_assert(FALSE && "iochannel-test failed");
        g_error_free (gerr);
        gerr = NULL;
      }
    flags = g_io_channel_get_flags (gio_r);
    buffer = g_string_sized_new (BUFFER_SIZE);

    while (TRUE)
    {
        do
          status = g_io_channel_read_line_string (gio_r, buffer, NULL, &gerr);
        while (status == G_IO_STATUS_AGAIN);
        if (status != G_IO_STATUS_NORMAL)
          break;

        rlength += buffer->len;

        do
          status = g_io_channel_write_chars (gio_w, buffer->str, buffer->len,
            &length_out, &gerr);
        while (status == G_IO_STATUS_AGAIN);
        if (status != G_IO_STATUS_NORMAL)
          break;

        wlength += length_out;

        if (length_out < buffer->len)
        {
        	g_warning ("Only wrote part of the line.");
        	g_assert(FALSE && "iochannel-test failed");
        }
          

#ifdef VERBOSE
        g_print ("%s", buffer->str);
#endif
        g_string_truncate (buffer, 0);
    }

    switch (status)
      {
        case G_IO_STATUS_EOF:
          break;
        case G_IO_STATUS_ERROR:
          g_warning (gerr->message);
          g_error_free (gerr);
          gerr = NULL;
          break;
        default:
          g_warning ("Abnormal exit from write loop.");
          g_assert(FALSE && "iochannel-test failed");
          break;
      }

    do
      status = g_io_channel_flush (gio_w, &gerr);
    while (status == G_IO_STATUS_AGAIN);

    if (status == G_IO_STATUS_ERROR)
      {
        g_warning (gerr->message);
        g_assert(FALSE && "iochannel-test failed");
        g_error_free (gerr);
        gerr = NULL;
      }

#ifdef VERBOSE
    g_print ("read %d bytes, wrote %ld bytes\n", rlength, wlength);
#endif

    g_io_channel_unref(gio_r);
    g_io_channel_unref(gio_w);
    
   	#if SYMBIAN
  	testResultXml("iochannel-test");
  	#endif /* EMULATOR */
  	    
    return 0;
}
Ejemplo n.º 18
0
bool KeyConfig::ReconfigInternal()
{
  g_assert(config);

  // read the file contents
  char *contents;
  gsize length;
  GError *err = NULL;
  if (!g_file_get_contents(config, &contents, &length, &err)) {
    // generate default keybinding file
    err = NULL;
    GIOChannel *chan;
    if (!(chan = g_io_channel_new_file(config, "w", &err))) {
      if (err) {
        g_warning(_("Error opening keybinding file '%s' (%s)."),
            config, err->message);
        g_error_free(err);
        err = NULL;
      }
      else
        g_warning(_("Error opening keybinding file '%s'."), config);
      return false;
    }

#define ERROR()                                                   \
do {                                                              \
if (err) {                                                        \
  g_warning(_("Error writing to keybinding file '%s' (%s)."),     \
      config, err->message);                                      \
  g_error_free(err);                                              \
  err = NULL;                                                     \
}                                                                 \
else                                                              \
  g_warning(_("Error writing to keybinding file '%s'."), config); \
g_io_channel_unref(chan);                                         \
return false;                                                     \
} while (0)

    const char *buf = "<?xml version='1.0' encoding='UTF-8' ?>\n\n"
                      "<keyconfig version='1.0'>\n";
    if (g_io_channel_write_chars(chan, buf, -1, NULL, &err)
        != G_IO_STATUS_NORMAL)
      ERROR();

    for (DefaultKeyBinds::iterator i = default_key_binds.begin();
        i != default_key_binds.end(); i++) {
      char *buf2 = g_strdup_printf(
          "\t<bind context='%s' action='%s' key='%s'/>\n",
          i->context.c_str(), i->action.c_str(), i->key.c_str());
      GIOStatus s = g_io_channel_write_chars(chan, buf2, -1, NULL, &err);
      g_free(buf2);

      if (s != G_IO_STATUS_NORMAL)
        ERROR();
    }

    buf = "</keyconfig>\n";
    if (g_io_channel_write_chars(chan, buf, -1, NULL, &err)
        != G_IO_STATUS_NORMAL)
      ERROR();

#undef ERROR

    g_io_channel_unref(chan);

    if (!g_file_get_contents(config, &contents, &length, &err)) {
      if (err) {
        g_warning(_("Error reading keybinding file '%s' (%s)."), config,
            err->message);
        g_error_free(err);
        err = NULL;
      }
      else
        g_warning(_("Error reading keybinding file '%s'."), config);
      return false;
    }
  }

  // parse the file
  bool res = true;
  GMarkupParser parser = {};
  parser.start_element = start_element_;
  GMarkupParseContext *context = g_markup_parse_context_new(&parser,
      G_MARKUP_PREFIX_ERROR_POSITION, this, NULL);
  if (!g_markup_parse_context_parse(context, contents, length, &err)
      || !g_markup_parse_context_end_parse(context, &err)) {
    if (err) {
      g_warning(_("Error parsing keybinding file '%s' (%s)."), config,
          err->message);
      g_error_free(err);
      err = NULL;
    }
    else
      g_warning(_("Error parsing keybinding file '%s'."), config);
    res = false;
  }
  g_markup_parse_context_free(context);
  g_free(contents);

  return res;
}
Ejemplo n.º 19
0
void
menu_open_activate_cb (GtkWidget *widget, gpointer data)
{
  queue_t *list;
  GtkWidget *fs;
  GIOChannel *channel;
  GError *error = NULL;
  GIOStatus status;
  gchar *filename, *buffer, *tmp, *tmp2, *title;

  fs = gtk_file_chooser_dialog_new ("Open File", 
                                    GTK_WINDOW (window_main->window),
                                    GTK_FILE_CHOOSER_ACTION_OPEN,
                                    GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                    GTK_STOCK_OPEN, GTK_RESPONSE_OK,
                                    NULL);

  if (gtk_dialog_run (GTK_DIALOG (fs)) != GTK_RESPONSE_OK)
    {
      gtk_widget_destroy (fs);
      return;
    }

  filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (fs));
  gtk_widget_destroy (fs);
  channel = g_io_channel_new_file (filename, "r", NULL);

  status = g_io_channel_read_to_end (channel, &buffer, NULL, &error);
  if (status != G_IO_STATUS_NORMAL)
    {
      tmp = g_path_get_basename (filename);
      fs = gtk_message_dialog_new (GTK_WINDOW (window_main->window),
                                   GTK_DIALOG_MODAL,
                                   GTK_MESSAGE_ERROR,
                                   GTK_BUTTONS_OK,
                                   "%s: %s", tmp, error->message);
      gtk_dialog_run (GTK_DIALOG (fs));
      gtk_widget_destroy (fs);
      g_free (tmp);
      g_error_free (error);
    }
  else
    {
      list = read_rbfsum2 (buffer);
      g_free (buffer);
      if (!list)
        {
          fs = gtk_message_dialog_new (GTK_WINDOW (window_main->window),
                                       GTK_DIALOG_MODAL,
                                       GTK_MESSAGE_ERROR,
                                       GTK_BUTTONS_OK,
                                       "Format file tidak valid");
          gtk_dialog_run (GTK_DIALOG (fs));
          gtk_widget_destroy (fs);
          return;
        }
           

      set_treeview_station (list);

      station_list = list;

      tmp = filename;
      if ((tmp2 = strrchr (filename, '/')))
        tmp = ++tmp2;

      title = g_strdup_printf ("%s - RBFSUM Utility", tmp);
      gtk_window_set_title (GTK_WINDOW (window_main->window), title);
      g_free (title);
    }

  g_free (filename);
  g_io_channel_shutdown (channel, FALSE, NULL);
  g_io_channel_unref (channel);
}
Ejemplo n.º 20
0
void
scrollback_load (session *sess)
{
	char *buf;
	char *text;
	time_t stamp;
	int lines;
	GIOChannel *io;
	GError *file_error = NULL;
	GError *io_err = NULL;

	if (sess->text_scrollback == SET_DEFAULT)
	{
		if (!prefs.pchat_text_replay)
			return;
	}
	else
	{
		if (sess->text_scrollback != SET_ON)
			return;
	}

	if ((buf = scrollback_get_filename (sess)) == NULL)
		return;

	io = g_io_channel_new_file (buf, "r", &file_error);
	g_free (buf);
	if (!io)
		return;

	lines = 0;

	while (1)
	{
		gsize n_bytes;
		GIOStatus io_status;

		io_status = g_io_channel_read_line (io, &buf, &n_bytes, NULL, &io_err);

		if (io_status == G_IO_STATUS_NORMAL)
		{
			char *buf_tmp;

			n_bytes--;
			buf_tmp = buf;
			buf = g_strndup (buf_tmp, n_bytes);
			g_free (buf_tmp);

			if (buf[0] == 'T')
			{
				if (sizeof (time_t) == 4)
					stamp = g_ascii_strtoul (buf + 2, NULL, 10);
				else
					stamp = g_ascii_strtoull (buf + 2, NULL, 10); /* in case time_t is 64 bits */
				text = strchr (buf + 3, ' ');
				if (text)
				{
					if (prefs.pchat_text_stripcolor_replay)
					{
						text = strip_color (text + 1, -1, STRIP_COLOR);
					}

					fe_print_text (sess, text, stamp, TRUE);

					if (prefs.pchat_text_stripcolor_replay)
					{
						g_free (text);
					}
				}
				lines++;
			}

			g_free (buf);
		}

		else
			break;
	}

	g_io_channel_unref (io);

	sess->scrollwritten = lines;

	if (lines)
	{
		text = ctime (&stamp);
		text[24] = 0;	/* get rid of the \n */
		buf = g_strdup_printf ("\n*\t%s %s\n\n", _("Loaded log from"), text);
		fe_print_text (sess, buf, 0, TRUE);
		g_free (buf);
		/*EMIT_SIGNAL (XP_TE_GENMSG, sess, "*", buf, NULL, NULL, NULL, 0);*/
	}
}
Ejemplo n.º 21
0
static int init(struct sr_input *in, const char *filename)
{
	int res;
	struct context *ctx;
	const char *param;
	GIOStatus status;
	gsize i, term_pos;
	char probe_name[SR_MAX_PROBENAME_LEN + 1];
	struct sr_probe *probe;
	char **columns;
	gsize num_columns;
	char *ptr;

	if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
		sr_err("Context malloc failed.");
		return SR_ERR_MALLOC;
	}

	/* Create a virtual device. */
	in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
	in->internal = ctx;

	/* Set default samplerate. */
	ctx->samplerate = 0;

	/*
	 * Enable auto-detection of the number of probes in multi column mode
	 * and enforce the specification of the number of probes in single
	 * column mode.
	 */
	ctx->num_probes = 0;

	/* Set default delimiter. */
	if (!(ctx->delimiter = g_string_new(","))) {
		sr_err("Delimiter malloc failed.");
		free_context(ctx);
		return SR_ERR_MALLOC;
	}

	/*
	 * Set default comment prefix. Note that an empty comment prefix
	 * disables removing of comments.
	 */
	if (!(ctx->comment = g_string_new(""))) {
		sr_err("Comment malloc failed.");
		free_context(ctx);
		return SR_ERR_MALLOC;
	}

	/* Enable multi column mode by default. */
	ctx->multi_column_mode = TRUE;

	/* Use first column as default single column number. */
	ctx->single_column = 0;

	/*
	 * In multi column mode start parsing sample data at the first column
	 * and in single column mode at the first bit.
	 */
	ctx->first_probe = 0;

	/* Start at the beginning of the file. */
	ctx->start_line = 1;

	/* Disable the usage of the first line as header by default. */
	ctx->header = FALSE;

	/* Set default format for single column mode. */
	ctx->format = FORMAT_BIN;

	if (!(ctx->buffer = g_string_new(""))) {
		sr_err("Line buffer malloc failed.");
		free_context(ctx);
		return SR_ERR_MALLOC;
	}

	if (in->param) {
		if ((param = g_hash_table_lookup(in->param, "samplerate"))) {
			res = sr_parse_sizestring(param, &ctx->samplerate);

			if (res != SR_OK) {
				sr_err("Invalid samplerate: %s.", param);
				free_context(ctx);
				return SR_ERR_ARG;
			}
		}

		if ((param = g_hash_table_lookup(in->param, "numprobes")))
			ctx->num_probes = g_ascii_strtoull(param, NULL, 10);

		if ((param = g_hash_table_lookup(in->param, "delimiter"))) {
			if (!strlen(param)) {
				sr_err("Delimiter must be at least one character.");
				free_context(ctx);
				return SR_ERR_ARG;
			}

			if (!g_ascii_strcasecmp(param, "\\t"))
				g_string_assign(ctx->delimiter, "\t");
			else
				g_string_assign(ctx->delimiter, param);
		}

		if ((param = g_hash_table_lookup(in->param, "comment")))
			g_string_assign(ctx->comment, param);

		if ((param = g_hash_table_lookup(in->param, "single-column"))) {
			ctx->single_column = g_ascii_strtoull(param, &ptr, 10);
			ctx->multi_column_mode = FALSE;

			if (param == ptr) {
				sr_err("Invalid single-colum number: %s.",
					param);
				free_context(ctx);
				return SR_ERR_ARG;
			}
		}

		if ((param = g_hash_table_lookup(in->param, "first-probe")))
			ctx->first_probe = g_ascii_strtoull(param, NULL, 10);

		if ((param = g_hash_table_lookup(in->param, "startline"))) {
			ctx->start_line = g_ascii_strtoull(param, NULL, 10);

			if (ctx->start_line < 1) {
				sr_err("Invalid start line: %s.", param);
				free_context(ctx);
				return SR_ERR_ARG;
			}
		}

		if ((param = g_hash_table_lookup(in->param, "header")))
			ctx->header = sr_parse_boolstring(param);

		if ((param = g_hash_table_lookup(in->param, "format"))) {
			if (!g_ascii_strncasecmp(param, "bin", 3)) {
				ctx->format = FORMAT_BIN;
			} else if (!g_ascii_strncasecmp(param, "hex", 3)) {
				ctx->format = FORMAT_HEX;
			} else if (!g_ascii_strncasecmp(param, "oct", 3)) {
				ctx->format = FORMAT_OCT;
			} else {
				sr_err("Invalid format: %s.", param);
				free_context(ctx);
				return SR_ERR;
			}
		}
	}

	if (ctx->multi_column_mode)
		ctx->first_column = ctx->first_probe;
	else
		ctx->first_column = ctx->single_column;

	if (!ctx->multi_column_mode && !ctx->num_probes) {
		sr_err("Number of probes needs to be specified in single column mode.");
		free_context(ctx);
		return SR_ERR;
	}

	if (!(ctx->channel = g_io_channel_new_file(filename, "r", NULL))) {
		sr_err("Input file '%s' could not be opened.", filename);
		free_context(ctx);
		return SR_ERR;
	}

	while (TRUE) {
		ctx->line_number++;
		status = g_io_channel_read_line_string(ctx->channel,
			ctx->buffer, &term_pos, NULL);

		if (status == G_IO_STATUS_EOF) {
			sr_err("Input file is empty.");
			free_context(ctx);
			return SR_ERR;
		}

		if (status != G_IO_STATUS_NORMAL) {
			sr_err("Error while reading line %zu.",
				ctx->line_number);
			free_context(ctx);
			return SR_ERR;
		}

		if (ctx->start_line > ctx->line_number) {
			sr_spew("Line %zu skipped.", ctx->line_number);
			continue;
		}

		/* Remove line termination character(s). */
		g_string_truncate(ctx->buffer, term_pos);

		if (!ctx->buffer->len) {
			sr_spew("Blank line %zu skipped.", ctx->line_number);
			continue;
		}

		/* Remove trailing comment. */
		strip_comment(ctx->buffer, ctx->comment);

		if (ctx->buffer->len)
			break;

		sr_spew("Comment-only line %zu skipped.", ctx->line_number);
	}

	/*
	 * In order to determine the number of columns parse the current line
	 * without limiting the number of columns.
	 */
	if (!(columns = parse_line(ctx, -1))) {
		sr_err("Error while parsing line %zu.", ctx->line_number);
		free_context(ctx);
		return SR_ERR;
	}

	num_columns = g_strv_length(columns);

	/* Ensure that the first column is not out of bounds. */
	if (!num_columns) {
		sr_err("Column %zu in line %zu is out of bounds.",
			ctx->first_column, ctx->line_number);
		g_strfreev(columns);
		free_context(ctx);
		return SR_ERR;
	}

	if (ctx->multi_column_mode) {
		/*
		 * Detect the number of probes in multi column mode
		 * automatically if not specified.
		 */
		if (!ctx->num_probes) {
			ctx->num_probes = num_columns;
			sr_info("Number of auto-detected probes: %zu.",
				ctx->num_probes);
		}

		/*
		 * Ensure that the number of probes does not exceed the number
		 * of columns in multi column mode.
		 */
		if (num_columns < ctx->num_probes) {
			sr_err("Not enough columns for desired number of probes in line %zu.",
				ctx->line_number);
			g_strfreev(columns);
			free_context(ctx);
			return SR_ERR;
		}
	}

	for (i = 0; i < ctx->num_probes; i++) {
		if (ctx->header && ctx->multi_column_mode && strlen(columns[i]))
			snprintf(probe_name, sizeof(probe_name), "%s",
				columns[i]);
		else
			snprintf(probe_name, sizeof(probe_name), "%zu", i);

		probe = sr_probe_new(i, SR_PROBE_LOGIC, TRUE, probe_name);

		if (!probe) {
			sr_err("Probe creation failed.");
			free_context(ctx);
			g_strfreev(columns);
			return SR_ERR;
		}

		in->sdi->probes = g_slist_append(in->sdi->probes, probe);
	}

	g_strfreev(columns);

	/*
	 * Calculate the minimum buffer size to store the sample data of the
	 * probes.
	 */
	ctx->sample_buffer_size = (ctx->num_probes + 7) >> 3;

	if (!(ctx->sample_buffer = g_try_malloc(ctx->sample_buffer_size))) {
		sr_err("Sample buffer malloc failed.");
		free_context(ctx);
		return SR_ERR_MALLOC;
	}

	return SR_OK;
}
Ejemplo n.º 22
0
static void
panel_place_menu_item_append_gtk_bookmarks (GtkWidget *menu)
{
	typedef struct {
		char *full_uri;
		char *label;
	} PanelBookmark;

	GtkWidget   *add_menu;
	char        *filename;
	GIOChannel  *io_channel;
	GHashTable  *table;
	int          i;
	GSList      *lines = NULL;
	GSList      *add_bookmarks, *l;
	PanelBookmark *bookmark;

	filename = g_build_filename (g_get_home_dir (),
				     BOOKMARKS_FILENAME, NULL);

	io_channel = g_io_channel_new_file (filename, "r", NULL);
	g_free (filename);

	if (!io_channel)
		return;

	/* We use a hard limit to avoid having users shooting their
	 * own feet, and to avoid crashing the system if a misbehaving
	 * application creates a big bookmars file.
	 */
	for (i = 0; i < MAX_BOOKMARK_ITEMS; i++) {
		char      *contents;
		gsize      length;
		gsize      terminator_pos;
		GIOStatus  status;

		status = g_io_channel_read_line (io_channel, &contents, &length, &terminator_pos, NULL);

		if (status != G_IO_STATUS_NORMAL)
			break;

		if (length == 0)
			break;

		/* Clear the line terminator (\n), if any */
		if (terminator_pos > 0)
			contents[terminator_pos] = '\0';

		lines = g_slist_prepend (lines, contents);
	}

	g_io_channel_shutdown (io_channel, FALSE, NULL);
	g_io_channel_unref (io_channel);

	if (!lines)
		return;

	lines = g_slist_reverse (lines);

	table = g_hash_table_new (g_str_hash, g_str_equal);
	add_bookmarks = NULL;

	for (l = lines; l; l = l->next) {
		char *line = (char*) l->data;

		if (line[0] && !g_hash_table_lookup (table, line)) {
			GFile    *file;
			char     *space;
			char     *label;
			gboolean  keep;

			g_hash_table_insert (table, line, line);

			space = strchr (line, ' ');
			if (space) {
				*space = '\0';
				label = g_strdup (space + 1);
			} else {
				label = NULL;
			}

			keep = FALSE;

			if (g_str_has_prefix (line, "x-caja-search:"))
				keep = TRUE;

			if (!keep) {
				file = g_file_new_for_uri (line);
				keep = !g_file_is_native (file) ||
				       g_file_query_exists (file, NULL);
				g_object_unref (file);
			}

			if (!keep) {
				if (label)
					g_free (label);
				continue;
			}

			bookmark = g_malloc (sizeof (PanelBookmark));
			bookmark->full_uri = g_strdup (line);
			bookmark->label = label;
			add_bookmarks = g_slist_prepend (add_bookmarks, bookmark);
		}
	}

	g_hash_table_destroy (table);
	g_slist_foreach (lines, (GFunc) g_free, NULL);
	g_slist_free (lines);

	add_bookmarks = g_slist_reverse (add_bookmarks);

	if (g_slist_length (add_bookmarks) <= MAX_ITEMS_OR_SUBMENU) {
		add_menu = menu;
	} else {
		GtkWidget *item;

		item = gtk_image_menu_item_new ();
		setup_menu_item_with_icon (item, panel_menu_icon_get_size (),
					   PANEL_ICON_BOOKMARKS, NULL, NULL,
					   _("Bookmarks"));

		gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
		gtk_widget_show (item);

		add_menu = create_empty_menu ();
		gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), add_menu);
	}

	for (l = add_bookmarks; l; l = l->next) {
		char *display_name;
		char *tooltip;
		char *label;
		char *icon;
		GFile *file;
		GIcon *gicon;

		bookmark = l->data;

		file = g_file_new_for_uri (bookmark->full_uri);
		display_name = g_file_get_parse_name (file);
		g_object_unref (file);
		/* Translators: %s is a URI */
		tooltip = g_strdup_printf (_("Open '%s'"), display_name);
		g_free (display_name);

		label = NULL;
		if (bookmark->label) {
			label = g_strdup (g_strstrip (bookmark->label));
			if (!label [0]) {
				g_free (label);
				label = NULL;
			}
		}

		if (!label) {
			label = panel_util_get_label_for_uri (bookmark->full_uri);

			if (!label) {
				g_free (tooltip);
				g_free (bookmark->full_uri);
				if (bookmark->label)
					g_free (bookmark->label);
				g_free (bookmark);
				continue;
			}
		}

		icon = panel_util_get_icon_for_uri (bookmark->full_uri);
		/*FIXME: we should probably get a GIcon if possible, so that we
		 * have customized icons for cd-rom, eg */
		if (!icon)
			icon = g_strdup (PANEL_ICON_FOLDER);

		gicon = g_themed_icon_new_with_default_fallbacks (icon);

		//FIXME: drag and drop will be broken for x-caja-search uris
		panel_menu_items_append_place_item (icon, gicon,
						    label,
						    tooltip,
						    add_menu,
						    G_CALLBACK (activate_uri),
						    bookmark->full_uri);

		g_free (icon);
		g_object_unref (gicon);
		g_free (tooltip);
		g_free (label);
		g_free (bookmark->full_uri);
		if (bookmark->label)
			g_free (bookmark->label);
		g_free (bookmark);
	}

	g_slist_free (add_bookmarks);
}
Ejemplo n.º 23
0
GHashTable *
nmn_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");
        nmn_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;
}
Ejemplo n.º 24
0
static gboolean handle_data(gconstpointer jingleft, const gchar *data, guint len)
{
  JingleFT *jft = (JingleFT *) jingleft;
  GError *err = NULL;
  GIOStatus status;
  gsize bytes_written = 0;

  if (jft->dir != JINGLE_FT_INCOMING)
    return FALSE;

  if (jft->md5 == NULL) {
    jft->md5 = g_checksum_new(G_CHECKSUM_MD5);
  }
  
  g_checksum_update(jft->md5, (guchar*)data, (gsize)len);
    
  // TODO: check if the file already exist or if it was created
  // during the call to jingle_ft_check and handle_data
  if (jft->outfile == NULL) {
    jft->outfile = g_io_channel_new_file(jft->name, "w", &err);
    if (jft->outfile == NULL || err != NULL) {
      scr_LogPrint(LPRINT_LOGNORM, "Jingle File Transfer: %s %s", err->message,
                   jft->name);
    //TODO: propagate the GError ?
      g_error_free(err);
      return FALSE;
    }
    jft->state = JINGLE_FT_STARTING;
    status = g_io_channel_set_encoding(jft->outfile, NULL, &err);
    if (status != G_IO_STATUS_NORMAL || err != NULL) {
     scr_LogPrint(LPRINT_LOGNORM, "Jingle File Transfer: %s %s", err->message,
                  jft->name);
     g_error_free(err);
     return FALSE;
   }
  }
  
  jft->state = JINGLE_FT_STARTING;

  status = g_io_channel_write_chars(jft->outfile, data, (gssize) len,
                                    &bytes_written, &err);
  if (status != G_IO_STATUS_NORMAL || err != NULL) {
     scr_LogPrint(LPRINT_LOGNORM, "Jingle File Transfer: %s %s", err->message,
                  jft->name);
    g_error_free(err);
    return FALSE;
  }
  status = g_io_channel_flush(jft->outfile, &err);
  if (status != G_IO_STATUS_NORMAL || err != NULL) {
    scr_LogPrint(LPRINT_LOGNORM, "Jingle File Transfer: %s %s", err->message,
                 jft->name);
    g_error_free(err);
    return FALSE;
  }

  if (bytes_written != len) {
    // not supposed to happen if status is normal, unless outfile is non-blocking
    return FALSE;
  }
  
  jft->transmit += len;
  return TRUE;
}
Ejemplo n.º 25
0
int
main (int argc, char *argv[])
{
    GOptionContext *context;
    UcaPluginManager *manager;
    GIOChannel *log_channel;
    GError *error = NULL;

    static Options options = {
        .n_frames = 1000,
        .n_runs = 3,
        .test_async = FALSE,
        .test_software = FALSE,
        .test_external = FALSE,
        .test_readout = FALSE,
    };

    static GOptionEntry entries[] = {
        { "num-frames", 'n', 0, G_OPTION_ARG_INT, &options.n_frames, "Number of frames per run", "N" },
        { "num-runs", 'r', 0, G_OPTION_ARG_INT, &options.n_runs, "Number of runs", "N" },
        { "async", 0, 0, G_OPTION_ARG_NONE, &options.test_async, "Test asynchronous mode", NULL },
        { "software", 0, 0, G_OPTION_ARG_NONE, &options.test_software, "Test software trigger mode", NULL },
        { "external", 0, 0, G_OPTION_ARG_NONE, &options.test_external, "Test external trigger mode", NULL },
        { "readout", 0, 0, G_OPTION_ARG_NONE, &options.test_readout, "Test readout from camRAM instead of sync acquisition", NULL},
        { NULL }
    };

    (void) signal (SIGINT, sigint_handler);

#if !(GLIB_CHECK_VERSION (2, 36, 0))
    g_type_init ();
#endif

    manager = uca_plugin_manager_new ();
    context = uca_common_context_new (manager);
    g_option_context_add_main_entries (context, entries, NULL);

    if (!g_option_context_parse (context, &argc, &argv, &error)) {
        g_print ("Failed parsing arguments: %s\n", error->message);
        goto cleanup_manager;
    }

    if (argc < 2) {
        g_print ("%s\n", g_option_context_get_help (context, TRUE, NULL));
        goto cleanup_manager;
    }

    log_channel = g_io_channel_new_file ("benchmark.log", "a+", &error);
    g_assert_no_error (error);
    g_log_set_handler (NULL, G_LOG_LEVEL_MASK, log_handler, log_channel);

    camera = uca_common_get_camera (manager, argv[argc - 1], &error);

    if (camera == NULL) {
        g_print ("Initialization: %s\n", error->message);
        goto cleanup_manager;
    }

    if (!uca_camera_parse_arg_props (camera, argv, argc - 1, &error)) {
        g_print ("Error setting properties: %s\n", error->message);
        goto cleanup_camera;
    }

    benchmark (camera, &options);

    g_io_channel_shutdown (log_channel, TRUE, &error);
    g_assert_no_error (error);

cleanup_camera:
    g_object_unref (camera);

cleanup_manager:
    g_object_unref (manager);

    return 0;
}
/*
  We have to save the whole set of indexes into a single file
  so it doesn't make sense to commit only a single writer.

  i suggest:

  gst_index_commit (index, -1);
*/
static void
gst_file_index_commit (GstIndex * _index, gint _writer_id)
{
  GstFileIndex *index = GST_FILE_INDEX (_index);
  xmlDocPtr doc;
  xmlNodePtr writers;
  GError *err = NULL;
  gchar *path;
  GIOChannel *tocfile;

  g_return_if_fail (index->location);
  g_return_if_fail (!index->is_loaded);

  GST_OBJECT_FLAG_UNSET (index, GST_INDEX_WRITABLE);

  doc = xmlNewDoc ((xmlChar *) "1.0");
  doc->xmlRootNode =
      xmlNewDocNode (doc, NULL, (xmlChar *) "gstfileindex", NULL);
  xmlSetProp (doc->xmlRootNode, (xmlChar *) "version", (xmlChar *) "1");

  writers = xmlNewChild (doc->xmlRootNode, NULL, (xmlChar *) "writers", NULL);
  g_hash_table_foreach (index->id_index,
      (GHFunc) _file_index_id_save_xml, writers);

  if (mkdir (index->location, 0777) && errno != EEXIST) {
    GST_ERROR_OBJECT (index, "mkdir %s: %s", index->location,
        g_strerror (errno));
    return;
  }

  path = g_strdup_printf ("%s/gstindex.xml", index->location);
  tocfile = g_io_channel_new_file (path, "w", &err);
  g_free (path);
  if (err) {
    GST_ERROR_OBJECT (index, "%s", err->message);
    return;
  }

  g_io_channel_set_encoding (tocfile, NULL, &err);
  if (err) {
    GST_ERROR_OBJECT (index, "%s", err->message);
    return;
  }

  {
    xmlChar *xmlmem;
    int xmlsize;

    xmlDocDumpMemory (doc, &xmlmem, &xmlsize);
    g_io_channel_write_chars (tocfile, (gchar *) xmlmem, xmlsize, NULL, &err);
    if (err) {
      GST_ERROR_OBJECT (index, "%s", err->message);
      return;
    }
    xmlFreeDoc (doc);
    free (xmlmem);
  }

  g_io_channel_shutdown (tocfile, TRUE, &err);
  if (err) {
    GST_ERROR_OBJECT (index, "%s", err->message);
    return;
  }

  g_io_channel_unref (tocfile);

  g_hash_table_foreach (index->id_index,
      (GHFunc) _file_index_id_save_entries, index->location);
}
Ejemplo n.º 27
0
int
main (int argc, char **argv)
{
    GIOChannel *channel;
    GIOStatus status;
    GError *error;
    gchar *line = NULL;
    gsize length, terminator_pos;
    FriBidiStrIndex *expected_ltor = NULL;
    FriBidiStrIndex expected_ltor_len = 0;
    FriBidiStrIndex *ltor = NULL;
    FriBidiStrIndex ltor_len = 0;
    FriBidiCharType *types = NULL;
    FriBidiStrIndex types_len = 0;
    FriBidiLevel *expected_levels = NULL;
    FriBidiLevel expected_levels_len = 0;
    FriBidiLevel *levels = NULL;
    FriBidiStrIndex levels_len = 0;
    int base_dir_flags, base_dir_mode;
    int numerrs = 0;
    int numtests = 0;
    int line_no = 0;
    gboolean debug = FALSE;
    const char *filename;
    int next_arg;

    if (argc < 2) {
	g_printerr ("usage: %s [--debug] test-file-name\n", argv[0]);
	exit (1);
    }

    next_arg = 1;
    if (!strcmp (argv[next_arg], "--debug")) {
	debug = TRUE;
	next_arg++;
    }

    filename = argv[next_arg++];

    error = NULL;
    channel = g_io_channel_new_file (filename, "r", &error);
    if (!channel) {
	g_printerr ("%s\n", error->message);
	exit (1);
    }

    while (TRUE) {
	error = NULL;
	g_free (line);
	status = g_io_channel_read_line (channel, &line, &length, &terminator_pos, &error);
	switch (status) {
        case G_IO_STATUS_ERROR:
            g_printerr ("%s\n", error->message);
            exit (1);

        case G_IO_STATUS_EOF:
	    goto done;

        case G_IO_STATUS_AGAIN:
            continue;

        case G_IO_STATUS_NORMAL:
            line[terminator_pos] = '\0';
            break;
	}

	line_no++;

	if (line[0] == '#' || line[0] == '\0')
	    continue;

	if (line[0] == '@')
	{
	    if (!strncmp (line, "@Reorder:", 9)) {
		g_free (expected_ltor);
		expected_ltor = parse_reorder_line (line, &expected_ltor_len);
		continue;
	    }
	    if (!strncmp (line, "@Levels:", 8)) {
		g_free (expected_levels);
		expected_levels = parse_levels_line (line, &expected_levels_len);
		continue;
	    }
	    continue;
	}

	/* Test line */
	g_free (types);
	types = parse_test_line (line, &types_len, &base_dir_flags);

	g_free (levels);
	levels = g_malloc (sizeof (FriBidiLevel) * types_len);
	levels_len = types_len;

	g_free (ltor);
	ltor = g_malloc (sizeof (FriBidiStrIndex) * types_len);

	/* Test it */
	for (base_dir_mode = 0; base_dir_mode < 3; base_dir_mode++) {
	    FriBidiParType base_dir;
	    int i, j;
	    gboolean matches;

	    if ((base_dir_flags & (1<<base_dir_mode)) == 0)
		continue;

            numtests++;

	    switch (base_dir_mode) {
	    case 0: base_dir = FRIBIDI_PAR_ON;  break;
	    case 1: base_dir = FRIBIDI_PAR_LTR; break;
	    case 2: base_dir = FRIBIDI_PAR_RTL; break;
	    }

	    fribidi_get_par_embedding_levels (types, types_len,
					      &base_dir,
					      levels);

	    for (i = 0; i < types_len; i++)
	        ltor[i] = i;

	    fribidi_reorder_line (0 /*FRIBIDI_FLAG_REORDER_NSM*/,
				  types, types_len,
				  0, base_dir,
				  levels,
				  NULL,
				  ltor);

	    j = 0;
	    for (i = 0; i < types_len; i++)
	    	if (!FRIBIDI_IS_EXPLICIT_OR_BN (types[ltor[i]]))
		    ltor[j++] = ltor[i];
	    ltor_len = j;

	    /* Compare */
	    matches = TRUE;
	    if (levels_len != expected_levels_len)
		matches = FALSE;
	    if (matches)
		for (i = 0; i < levels_len; i++)
		    if (levels[i] != expected_levels[i] &&
			expected_levels[i] != (FriBidiLevel) -1) {
			matches = FALSE;
			break;
		    }

	    if (ltor_len != expected_ltor_len)
		matches = FALSE;
	    if (matches)
		for (i = 0; i < ltor_len; i++)
		    if (ltor[i] != expected_ltor[i]) {
			matches = FALSE;
			break;
		    }

	    if (!matches)
	    {
		numerrs++;

		g_printerr ("failure on line %d\n", line_no);
		g_printerr ("input is: %s\n", line);
		g_printerr ("base dir: %s\n", base_dir_mode==0 ? "auto"
					    : base_dir_mode==1 ? "LTR" : "RTL");

		g_printerr ("expected levels:");
		for (i = 0; i < expected_levels_len; i++)
		    if (expected_levels[i] == (FriBidiLevel) -1)
			g_printerr (" x");
		    else
			g_printerr (" %d", expected_levels[i]);
		g_printerr ("\n");
		g_printerr ("returned levels:");
		for (i = 0; i < levels_len; i++)
		    g_printerr (" %d", levels[i]);
		g_printerr ("\n");

		g_printerr ("expected order:");
		for (i = 0; i < expected_ltor_len; i++)
		    g_printerr (" %d", expected_ltor[i]);
		g_printerr ("\n");
		g_printerr ("returned order:");
		for (i = 0; i < ltor_len; i++)
		    g_printerr (" %d", ltor[i]);
		g_printerr ("\n");

		if (debug) {
		    FriBidiParType base_dir;

		    fribidi_set_debug (1);

		    switch (base_dir_mode) {
		    case 0: base_dir = FRIBIDI_PAR_ON;  break;
		    case 1: base_dir = FRIBIDI_PAR_LTR; break;
		    case 2: base_dir = FRIBIDI_PAR_RTL; break;
		    }

		    fribidi_get_par_embedding_levels (types, types_len,
						      &base_dir,
						      levels);

		    fribidi_set_debug (0);
		}

		g_printerr ("\n");
	    }
	}
    }

done:
    g_free (ltor);
    g_free (levels);
    g_free (expected_ltor);
    g_free (types);
    g_free (line);
    g_io_channel_unref (channel);
    if (error)
	g_error_free (error);

    if (numerrs)
	g_printerr ("%d errors out of %d total tests\n", numerrs, numtests);
    return numerrs;
}
Ejemplo n.º 28
0
gchar * __pkey_retrieve_from_file (gchar **fn, gchar *cert_pem)
{
    gsize file_length = 0;
    GError *error = NULL;
    gboolean cancel = FALSE;

    gboolean save_new_filename = FALSE;
    gchar *file_name = g_strdup(* fn);

    gchar *file_contents = NULL;

    gchar *pem_pkey = NULL;

    gint tls_error = 0;
    gchar *password = NULL;

    TlsCert *cert = tls_parse_cert_pem (cert_pem);

    do {
        if (g_file_test(file_name, G_FILE_TEST_EXISTS)) {
            GIOChannel *gc = g_io_channel_new_file (file_name, "r", &error);
            if (gc) {
                g_io_channel_read_to_end (gc, &file_contents, &file_length, &error);
                g_io_channel_shutdown (gc, TRUE, NULL);

                do {
                    pem_pkey = tls_load_pkcs8_private_key (file_contents, password, cert->key_id, &tls_error);

                    if (tls_error == TLS_INVALID_PASSWORD) {
                        if (password)
                            dialog_error (_("The given password doesn't match with the one used while crypting the file."));

                        // We ask for a password
                        password = __pkey_manage_ask_external_file_password (cert->dn);

                        if (! password)
                            cancel = TRUE;
                    }

                } while (tls_error == TLS_INVALID_PASSWORD && ! cancel);

                g_free (password);

                if (! pem_pkey) {
                    if (tls_error == TLS_NON_MATCHING_PRIVATE_KEY) {
                        // The file could be opened, but it didn't contain any recognized private key
                        dialog_error (_("The file designated in database contains a private key, but it "
                                        "is not the private key corresponding to the certificate."));
                    } else {
                        // The file could be opened, but it didn't contain any recognized private key
                        dialog_error (_("The file designated in database doesn't contain any recognized private key."));
                    }
                }
            } else {
                // The file cannot be opened
                dialog_error (_("The file designated in database couldn't be opened."));

            }
        } else {
            // The file doesn't exist
            dialog_error (_("The file designated in database doesn't exist."));

        }

        if (! pem_pkey && ! cancel) {

#ifndef GNOMINTCLI
            // Show file open dialog

            GObject * widget = NULL, * filepath_widget = NULL, *remember_filepath_widget = NULL;
            GtkBuilder * dialog_gtkb = NULL;
            gint response = 0;

            dialog_gtkb = gtk_builder_new();
            gtk_builder_add_from_file (dialog_gtkb,
                                       g_build_filename (PACKAGE_DATA_DIR, "gnomint", "get_pkey_dialog.ui", NULL),
                                       NULL);
            gtk_builder_connect_signals (dialog_gtkb, NULL);

            filepath_widget = gtk_builder_get_object (dialog_gtkb, "pkey_filechooser");

            remember_filepath_widget = gtk_builder_get_object (dialog_gtkb, "save_filename_checkbutton");
            g_object_set (G_OBJECT(remember_filepath_widget), "visible", FALSE, NULL);

            gtk_widget_grab_focus (GTK_WIDGET(filepath_widget));
            gtk_file_chooser_set_filename (GTK_FILE_CHOOSER(filepath_widget), file_name);
            g_object_set_data (G_OBJECT(filepath_widget), "save_filename_checkbutton", remember_filepath_widget);

            widget = gtk_builder_get_object (dialog_gtkb, "cert_dn_label");
            gtk_label_set_text (GTK_LABEL(widget), cert->dn);

            widget = gtk_builder_get_object (dialog_gtkb, "get_pkey_dialog");
            response = gtk_dialog_run(GTK_DIALOG(widget));

            if (! response) {
                cancel = TRUE;
            } else {
                g_free (file_name);
                file_name = g_strdup ((gchar *) gtk_file_chooser_get_filename (GTK_FILE_CHOOSER(filepath_widget)));
                save_new_filename = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(remember_filepath_widget));
            }

            widget = gtk_builder_get_object (dialog_gtkb, "get_pkey_dialog");
            gtk_widget_destroy (GTK_WIDGET(widget));
            g_object_unref (G_OBJECT(dialog_gtkb));

#else
            cancel = TRUE;
#endif

        }
    } while (! pem_pkey && ! cancel);

    tls_cert_free (cert);
    g_free (file_contents);
    if (error)
        g_error_free (error);

    if (cancel) {
        g_free (file_name);
        return NULL;
    }

    if (save_new_filename) {
        g_free (*fn);
        (* fn) = file_name;
    }

    return pem_pkey;
}
Ejemplo n.º 29
0
gboolean
category_load_csv(gchar *filename, gchar **error)
{
gboolean retval;
GIOChannel *io;
gchar *tmpstr;
gint io_stat;
gchar **str_array;
gchar *lastcatname = NULL;
gchar *fullcatname;
GError *err = NULL;
Category *item;
gint type = 0;
const gchar *encoding;

	encoding = homebank_file_getencoding(filename);

			DB( g_print(" -> encoding should be %s\n", encoding) );


	retval = TRUE;
	*error = NULL;
	io = g_io_channel_new_file(filename, "r", NULL);
	if(io != NULL)
	{

		if( encoding != NULL )
		{
			g_io_channel_set_encoding(io, encoding, NULL);
		}

		for(;;)
		{
			if( *error != NULL )
				break;
			io_stat = g_io_channel_read_line(io, &tmpstr, NULL, NULL, &err);

			DB( g_print(" + iostat %d\n", io_stat) );

			if( io_stat == G_IO_STATUS_ERROR )
			{
				DB (g_print(" + ERROR %s\n",err->message));
				break;
			}
			if( io_stat == G_IO_STATUS_EOF)
				break;
			if( io_stat == G_IO_STATUS_NORMAL)
			{
				if( tmpstr != NULL )
				{
					DB( g_print(" + strip %s\n", tmpstr) );
					hb_string_strip_crlf(tmpstr);

					DB( g_print(" + split\n") );
					str_array = g_strsplit (tmpstr, ";", 3);
					// type; sign; name

					if( g_strv_length (str_array) != 3 )
					{
						*error = _("invalid CSV format");
						retval = FALSE;
						DB( g_print(" + error %s\n", *error) );
					}
					else
					{
						DB( g_print(" + read %s : %s : %s\n", str_array[0], str_array[1], str_array[2]) );

						fullcatname = NULL;
						if( g_str_has_prefix(str_array[0], "1") )
						{
							fullcatname = g_strdup(str_array[2]);
							g_free(lastcatname);
							lastcatname = g_strdup(str_array[2]);

							type = g_str_has_prefix(str_array[1], "+") ? GF_INCOME : 0;

							DB( g_print(" + type = %d\n", type) );

						}
						else
						if( g_str_has_prefix(str_array[0], "2") )
						{
							fullcatname = g_strdup_printf("%s:%s", lastcatname, str_array[2]);
						}

						DB( g_print(" + fullcatname %s\n", fullcatname) );

						item = da_cat_append_ifnew_by_fullname(fullcatname, FALSE);

						DB( g_print(" + item %p\n", item) );

						if( item != NULL)
						{
							DB( g_print(" + assign flags: '%c'\n", type) );

							item->flags |= type;

						}

						g_free(fullcatname);
						g_strfreev (str_array);
					}
				}

			}
			g_free(tmpstr);

		}
		g_io_channel_unref (io);


	}

	g_free(lastcatname);

	return retval;
}
Ejemplo n.º 30
0
int main (int argc, char **argv)
{
  GIOChannel *in;
  GError *error = NULL;
  GArray *line_array = g_array_new (FALSE, FALSE, sizeof(Line));
  guint i;
  gboolean do_key = FALSE;
  gboolean do_file = FALSE;
  gchar *locale;

  /* FIXME: need to modify environment here,
   * since g_utf8_collate_key calls setlocal (LC_COLLATE, "")
   */
  g_setenv ("LC_ALL", "en_US", TRUE);
  locale = setlocale (LC_ALL, "");
  if (locale == NULL || strcmp (locale, "en_US") != 0)
    {
      fprintf (stderr, "No suitable locale, skipping test\n"); 
      return 2;
    }

  if (argc != 1 && argc != 2 && argc != 3)
    {
      fprintf (stderr, "Usage: unicode-collate [--key|--file] [FILE]\n");
      return 1;
    }

  i = 1;
  if (argc > 1)
    {
      if (strcmp (argv[1], "--key") == 0)
        {
          do_key = TRUE;
	  i = 2;
        }
      else if (strcmp (argv[1], "--file") == 0)
        {
          do_key = TRUE;
          do_file = TRUE;
	  i = 2;
        }
    }

 if (argc > i)
    {
      in = g_io_channel_new_file (argv[i], "r", &error);
      if (!in)
	{
	  fprintf (stderr, "Cannot open %s: %s\n", argv[i], error->message);
	  return 1;
	}
    }
  else
    {
      in = g_io_channel_unix_new (fileno (stdin));
    }

  while (TRUE)
    {
      gsize term_pos;
      gchar *str;
      Line line;

      if (g_io_channel_read_line (in, &str, NULL, &term_pos, &error) != G_IO_STATUS_NORMAL)
	break;

      str[term_pos] = '\0';

      if (do_file)
	line.key = g_utf8_collate_key_for_filename (str, -1);
      else
	line.key = g_utf8_collate_key (str, -1);
      line.str = str;

      g_array_append_val (line_array, line);
    }

  if (error)
    {
      fprintf (stderr, "Error reading test file, %s\n", error->message);
      return 1;
    }

  qsort (line_array->data, line_array->len, sizeof (Line), do_key ? compare_key : compare_collate);
  for (i = 0; i < line_array->len; i++)
    printf ("%s\n", g_array_index (line_array, Line, i).str);

  g_io_channel_unref (in);

  return 0;
}