Esempio n. 1
0
/**
 * pk_get_distro_id:
 *
 * Return value: the distro-id, typically "distro;version;arch"
 **/
gchar *
pk_get_distro_id (void)
{
	guint i;
	gboolean ret;
	gchar *contents = NULL;
	gchar *arch = NULL;
	gchar *version = NULL;
	gchar **split = NULL;
	gchar *distro = NULL;
	gchar *distro_id = NULL;

	/* The distro id property should have the
	   format "distro;version;arch" as this is
	   used to determine if a specific package
	   can be installed on a certain machine.
	   For instance, x86_64 packages cannot be
	   installed on a i386 machine.
	*/

	/* we can't get arch from /etc */
	arch = pk_get_distro_id_machine_type ();

	/* check for fedora */
	ret = g_file_get_contents ("/etc/fedora-release", &contents, NULL, NULL);
	if (ret) {
		/* Fedora release 8.92 (Rawhide) */
		split = g_strsplit (contents, " ", 0);
		if (split == NULL)
			goto out;

		/* complete! */
		distro_id = g_strdup_printf ("fedora;%s;%s", split[2], arch);
		goto out;
	}

	/* check for suse */
	ret = g_file_get_contents ("/etc/SuSE-release", &contents, NULL, NULL);
	if (ret) {
		/* replace with spaces: openSUSE 11.0 (i586) Alpha3\nVERSION = 11.0 */
		g_strdelimit (contents, "()\n", ' ');

		/* openSUSE 11.0  i586  Alpha3 VERSION = 11.0 */
		split = g_strsplit (contents, " ", 0);
		if (split == NULL)
			goto out;

		/* complete! */
		distro_id = g_strdup_printf ("suse;%s-%s;%s", split[1], split[3], arch);
		goto out;
	}

	/* check for meego */
	ret = g_file_get_contents ("/etc/meego-release", &contents, NULL, NULL);
	if (ret) {
		/* Meego release 1.0 (MeeGo) */
		split = g_strsplit (contents, " ", 0);
		if (split == NULL)
			goto out;

		/* complete! */
		distro_id = g_strdup_printf ("meego;%s;%s", split[2], arch);
		goto out;
	}

	/* check for foresight or foresight derivatives */
	ret = g_file_get_contents ("/etc/distro-release", &contents, NULL, NULL);
	if (ret) {
		/* Foresight Linux 2 */
		split = g_strsplit (contents, " ", 0);
		if (split == NULL)
			goto out;

		/* complete! */
		distro_id = g_strdup_printf ("foresight;%s;%s", split[2], arch);
		goto out;
	}

	/* check for PLD */
	ret = g_file_get_contents ("/etc/pld-release", &contents, NULL, NULL);
	if (ret) {
		/* 2.99 PLD Linux (Th) */
		split = g_strsplit (contents, " ", 0);
		if (split == NULL)
			goto out;

		/* complete! */
		distro_id = g_strdup_printf ("pld;%s;%s", split[0], arch);
		goto out;
	}

	/* check for Arch */
	ret = g_file_test ("/etc/arch-release", G_FILE_TEST_EXISTS);
	if (ret) {
		/* complete! */
		distro_id = g_strdup_printf ("arch;current;%s", arch);
		goto out;
	}

	/* check for LSB */
	ret = g_file_get_contents ("/etc/lsb-release", &contents, NULL, NULL);
	if (ret) {
		/* split by lines */
		split = g_strsplit (contents, "\n", -1);
		for (i=0; split[i] != NULL; i++) {
			if (g_str_has_prefix (split[i], "DISTRIB_ID="))
				distro = g_ascii_strdown (&split[i][11], -1);
			if (g_str_has_prefix (split[i], "DISTRIB_RELEASE="))
				version = g_ascii_strdown (&split[i][16], -1);
		}

		/* complete! */
		distro_id = g_strdup_printf ("%s;%s;%s", distro, version, arch);
		goto out;
	}

	/* check for Debian or Debian derivatives */
	ret = g_file_get_contents ("/etc/debian_version", &contents, NULL, NULL);
	if (ret) {
		/* remove "\n": "squeeze/sid\n" */
		g_strdelimit (contents, "\n", '\0');
		/* removes leading and trailing whitespace */
		g_strstrip (contents);

		/* complete! */
		distro_id = g_strdup_printf ("debian;%s;%s", contents, arch);
		goto out;
	}

#ifdef __FreeBSD__
	ret = TRUE;
#endif
	/* FreeBSD */
	if (ret) {
		/* we can't get version from /etc */
		version = pk_get_distro_id_os_release ();
		if (version == NULL)
			goto out;

		/* 7.2-RELEASE */
		split = g_strsplit (version, "-", 0);
		if (split == NULL)
			goto out;

		/* complete! */
		distro_id = g_strdup_printf ("freebsd;%s;%s", split[0], arch);
		goto out;
	}
out:
	g_strfreev (split);
	g_free (version);
	g_free (distro);
	g_free (arch);
	g_free (contents);
	return distro_id;
}
Esempio n. 2
0
static void
cload(GwyContainer *data, GwyRunType run)
{
    GwyDataField *dfield;
    CLoadArgs args;
    gboolean ok;
    gint oldid, i, n;
    GwyCalibration *calibration;
    GwyCalData *caldata = NULL;
    gchar *filename;
    gchar *contents;
    gsize len;
    GError *err = NULL;
    gsize pos = 0;
    GString *str;
    GByteArray *barray;
    FILE *fh;


    g_return_if_fail(run & CNEW_RUN_MODES);
    gwy_app_data_browser_get_current(GWY_APP_DATA_FIELD, &dfield,
                                     GWY_APP_DATA_FIELD_ID, &oldid,
                                     0);
    g_return_if_fail(dfield);

    //cload_load_args(gwy_app_settings_get(), &args);
    if (run == GWY_RUN_INTERACTIVE) {
        ok = cload_dialog(&args, dfield);
        //cload_save_args(gwy_app_settings_get(), &args);
        if (!ok)
            return;
    }

    /*if append requested, copy newly created calibration into old one*/
    if (args.duplicate == DUPLICATE_APPEND && (calibration = gwy_inventory_get_item(gwy_calibrations(), args.name)))
    {
        
        filename = g_build_filename(gwy_get_user_dir(), "caldata", calibration->filename, NULL);
        if (!g_file_get_contents(filename,
                                 &contents, &len, &err))
        {
             g_warning("Error loading file: %s\n", err->message);
             g_clear_error(&err);
             return;
        }
        else {
            if (len)
              caldata = GWY_CALDATA(gwy_serializable_deserialize(contents, len, &pos));
            g_free(contents);
        }
        n = caldata->ndata + args.caldata->ndata;

        //add to args->caldata
        args.caldata->x = g_realloc(args.caldata->x, n*sizeof(gdouble));
        args.caldata->y = g_realloc(args.caldata->y, n*sizeof(gdouble));
        args.caldata->z = g_realloc(args.caldata->z, n*sizeof(gdouble));
        args.caldata->xerr = g_realloc(args.caldata->xerr, n*sizeof(gdouble));
        args.caldata->yerr = g_realloc(args.caldata->yerr, n*sizeof(gdouble));
        args.caldata->zerr = g_realloc(args.caldata->zerr, n*sizeof(gdouble));
        args.caldata->xunc = g_realloc(args.caldata->xunc, n*sizeof(gdouble));
        args.caldata->yunc = g_realloc(args.caldata->yunc, n*sizeof(gdouble));
        args.caldata->zunc = g_realloc(args.caldata->zunc, n*sizeof(gdouble));

        for (i=args.caldata->ndata; i<n; i++)
        {
           args.caldata->x[i] = caldata->x[i-caldata->ndata];
           args.caldata->y[i] = caldata->y[i-caldata->ndata];
           args.caldata->z[i] = caldata->z[i-caldata->ndata];
           args.caldata->xerr[i] = caldata->xerr[i-caldata->ndata];
           args.caldata->yerr[i] = caldata->yerr[i-caldata->ndata];
           args.caldata->zerr[i] = caldata->zerr[i-caldata->ndata];
           args.caldata->xunc[i] = caldata->xunc[i-caldata->ndata];
           args.caldata->yunc[i] = caldata->yunc[i-caldata->ndata];
           args.caldata->zunc[i] = caldata->zunc[i-caldata->ndata];
        }
        args.caldata->ndata = n; 
    }

    /*now create and save the resource*/
    if ((calibration = GWY_CALIBRATION(gwy_inventory_get_item(gwy_calibrations(), args.name)))==NULL)
    {
        calibration = gwy_calibration_new(args.name, 8, g_strconcat(args.name, ".dat", NULL));
        gwy_inventory_insert_item(gwy_calibrations(), calibration);
        g_object_unref(calibration);
    }

    filename = gwy_resource_build_filename(GWY_RESOURCE(calibration));
    fh = g_fopen(filename, "w");
    if (!fh) {
        g_warning("Cannot save preset: %s", filename);
        g_free(filename);
        return;
    }
    g_free(filename);

    str = gwy_resource_dump(GWY_RESOURCE(calibration));
    fwrite(str->str, 1, str->len, fh);
    fclose(fh);
    g_string_free(str, TRUE);

    gwy_resource_data_saved(GWY_RESOURCE(calibration));

    //debugcal(args.caldata);

    /*now save the calibration data*/
    if (!g_file_test(g_build_filename(gwy_get_user_dir(), "caldata", NULL), G_FILE_TEST_EXISTS)) {
        g_mkdir(g_build_filename(gwy_get_user_dir(), "caldata", NULL), 0700);
    }
    fh = g_fopen(g_build_filename(gwy_get_user_dir(), "caldata", calibration->filename, NULL), "w");
    if (!fh) {
        g_warning("Cannot save caldata\n");
        return;
    }
    barray = gwy_serializable_serialize(G_OBJECT(args.caldata), NULL);
    //g_file_set_contents(fh, barray->data, sizeof(guint8)*barray->len, NULL);
    fwrite(barray->data, sizeof(guint8), barray->len, fh);
    fclose(fh);

}
Esempio n. 3
0
gboolean lock_port(gchar * name)
#endif
{
#ifndef __WIN32__
	gchar *tmpbuf = NULL;
	gchar *lock = NULL;
	gchar **vector = NULL;
	gchar *contents = NULL;
	GError *err = NULL;
	guint i = 0;
	gint pid = 0;

	/* If no /proc (i.e. os-X), just fake it and return */
	if (!g_file_test("/proc",G_FILE_TEST_IS_DIR))
		return TRUE;

	lock = g_strdup_printf("/var/lock/LCK..");
	vector = g_strsplit(name,PSEP,-1);
	for (i=0;i<g_strv_length(vector);i++)
	{
		if ((g_ascii_strcasecmp(vector[i],"") == 0) || (g_ascii_strcasecmp(vector[i],"dev") == 0))
			continue;
		lock = g_strconcat(lock,vector[i],NULL);
	}
	g_strfreev(vector);
	if (g_file_test(lock,G_FILE_TEST_IS_REGULAR))
	{
/*		printf("found existing lock!\n");*/
		if(g_file_get_contents(lock,&contents,NULL,&err))
		{
/*			printf("read existing lock\n");*/
			vector = g_strsplit(g_strchug(contents)," ", -1);
/*			printf("lock had %i fields\n",g_strv_length(vector));*/
			pid = (gint)g_ascii_strtoull(vector[0],NULL,10);
/*			printf("pid in lock \"%i\"\n",pid);*/
			g_free(contents);
			g_strfreev(vector);
			tmpbuf = g_strdup_printf("/proc/%i",pid);
			if (g_file_test(tmpbuf,G_FILE_TEST_IS_DIR))
			{
/*				printf("process active\n");*/
				g_free(tmpbuf);
				g_free(lock);
				return FALSE;
			}
			else
				g_remove(lock);
			g_free(tmpbuf);
		}
		
	}
	contents = g_strdup_printf("     %i",getpid());
	if(g_file_set_contents(lock,contents,-1,&err))
	{
		serial_lockfile = g_strdup(lock);
		g_free(contents);
		g_free(lock);
		return TRUE;
	}
	else
		printf("Error setting serial lock %s\n",(gchar *)strerror(errno));
	g_free(contents);
#endif	
	return TRUE;
}
Esempio n. 4
0
static JSObject *
load_module_init(JSContext  *context,
                 JSObject   *in_object,
                 const char *full_path)
{
    char *script;
    gsize script_len;
    jsval script_retval;
    JSObject *module_obj;

    /* First we check if js module has already been loaded  */
    if (gjs_object_has_property(context, in_object, MODULE_INIT_PROPERTY)) {
        jsval module_obj_val;

        if (gjs_object_get_property(context,
                                    in_object,
                                    MODULE_INIT_PROPERTY,
                                    &module_obj_val)) {
            return JSVAL_TO_OBJECT(module_obj_val);
        }
    }

    module_obj = JS_NewObject(context, NULL, NULL, NULL);
    if (module_obj == NULL) {
        return JS_FALSE;
    }

    /* https://bugzilla.mozilla.org/show_bug.cgi?id=599651 means we
     * can't just pass in the global as the parent */
    JS_SetParent(context, module_obj,
                 gjs_get_import_global (context));

    /* Define module in importer for future use and to avoid module_obj
     * object to be garbage collected during the evaluation of the script */
    JS_DefineProperty(context, in_object,
                      MODULE_INIT_PROPERTY, OBJECT_TO_JSVAL(module_obj),
                      NULL, NULL,
                      GJS_MODULE_PROP_FLAGS & ~JSPROP_PERMANENT);

    script = NULL;
    script_len = 0;

    if (!g_file_get_contents(full_path, &script, &script_len, NULL)) {
        return NULL;
    }

    g_assert(script != NULL);

    gjs_debug(GJS_DEBUG_IMPORTER, "Importing %s", full_path);

    if (!JS_EvaluateScript(context,
                           module_obj,
                           script,
                           script_len,
                           full_path,
                           1, /* line number */
                           &script_retval)) {
        g_free(script);

        /* If JSOPTION_DONT_REPORT_UNCAUGHT is set then the exception
         * would be left set after the evaluate and not go to the error
         * reporter function.
         */
        if (JS_IsExceptionPending(context)) {
            gjs_debug(GJS_DEBUG_IMPORTER,
                      "Module " MODULE_INIT_FILENAME " left an exception set");
            gjs_log_and_keep_exception(context, NULL);
        } else {
            gjs_throw(context,
                      "JS_EvaluateScript() returned FALSE but did not set exception");
        }

        return NULL;
    }

    g_free(script);

    return module_obj;
}
Esempio n. 5
0
void
open_pdf_cb (GtkWidget *widget, gpointer data)
{
	GtkWidget *dialog, * window;
	GtkTextView * text_view;
	GtkFileFilter *pdffilter, *txtfilter;
	Ebook * ebook;

	ebook = (Ebook *)data;
	window = GTK_WIDGET(gtk_builder_get_object (ebook->builder, "gpdfwindow"));
	text_view = GTK_TEXT_VIEW(gtk_builder_get_object (ebook->builder, "textview"));
	dialog = gtk_file_chooser_dialog_new (_("Open file"),
		GTK_WINDOW (window), GTK_FILE_CHOOSER_ACTION_OPEN,
		GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN,
		GTK_RESPONSE_ACCEPT, NULL);
	gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_ACCEPT);

	pdffilter = gtk_file_filter_new ();
	gtk_file_filter_set_name (pdffilter, _("All PDF Files (*.pdf)"));
	gtk_file_filter_add_mime_type (pdffilter, "application/pdf");
	gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), pdffilter);
	gtk_file_chooser_set_filter (GTK_FILE_CHOOSER (dialog), pdffilter);
	txtfilter = gtk_file_filter_new ();
	gtk_file_filter_set_name (txtfilter, _("ASCII text files (*.txt)"));
	gtk_file_filter_add_mime_type (txtfilter, "text/plain");
	gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), txtfilter);
	if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
	{
		gchar *filename;
		GtkFileFilter * f;

		filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
		// read the filter property.
		g_object_get (G_OBJECT(GTK_FILE_CHOOSER (dialog)), "filter", &f, NULL);
		if (f == pdffilter)
		{
			/* get the dialog out of the way before the work starts. */
			gtk_widget_destroy (dialog);
			open_file (ebook, filename);
		}
		else
		{
			gchar * contents, * msg;
			GtkTextBuffer * buffer;
			GtkStatusbar * statusbar;
			GtkProgressBar * progressbar;
			guint id;

			/* get the dialog out of the way before the work starts. */
			gtk_widget_destroy (dialog);
			progressbar = GTK_PROGRESS_BAR(gtk_builder_get_object (ebook->builder, "progressbar"));
			statusbar = GTK_STATUSBAR(gtk_builder_get_object (ebook->builder, "statusbar"));
			id = gtk_statusbar_get_context_id (statusbar, PACKAGE);
			/* typical text files are v.large and this can block. FIXME. */
			g_file_get_contents (filename, &contents, NULL, NULL);
			buffer = gtk_text_view_get_buffer (text_view);
			gtk_text_buffer_set_text (buffer, contents, -1);
			msg = g_strconcat (PACKAGE, " - ", g_filename_display_basename (filename), NULL);
			gtk_window_set_title (GTK_WINDOW(window), msg);
			gtk_progress_bar_set_text (progressbar, "");
			gtk_progress_bar_set_fraction (progressbar, 0.0);
			gtk_statusbar_push (statusbar, id, _("Done"));
		}
		/* this is the PDF filename, so free it. */
		g_free (filename);
		filename = NULL;
		return;
	}
	gtk_widget_destroy (dialog);
}
Esempio n. 6
0
static gchar * _watermark_get_svgdoc( dt_iop_module_t *self, dt_iop_watermark_data_t *data, const dt_image_t *image)
{
  gsize length;

  gchar *svgdoc=NULL;
  gchar configdir[DT_MAX_PATH_LEN];
  gchar datadir[DT_MAX_PATH_LEN];
  gchar *filename;
  dt_loc_get_datadir(datadir, DT_MAX_PATH_LEN);
  dt_loc_get_user_config_dir(configdir, DT_MAX_PATH_LEN);
  g_strlcat(datadir,"/watermarks/", DT_MAX_PATH_LEN);
  g_strlcat(configdir,"/watermarks/", DT_MAX_PATH_LEN);
  g_strlcat(datadir,data->filename, DT_MAX_PATH_LEN);
  g_strlcat(configdir,data->filename, DT_MAX_PATH_LEN);

  if (g_file_test(configdir,G_FILE_TEST_EXISTS))
    filename=configdir;
  else if (g_file_test(datadir,G_FILE_TEST_EXISTS))
    filename=datadir;
  else return NULL;

  gchar *svgdata=NULL;
  char datetime[200];

  // EXIF datetime
  struct tm tt_exif = {0};
  if(sscanf(image->exif_datetime_taken,"%d:%d:%d %d:%d:%d",
            &tt_exif.tm_year,
            &tt_exif.tm_mon,
            &tt_exif.tm_mday,
            &tt_exif.tm_hour,
            &tt_exif.tm_min,
            &tt_exif.tm_sec
           ) == 6
    )
  {
    tt_exif.tm_year-=1900;
    tt_exif.tm_mon--;
  }

  // Current datetime
  struct tm tt_cur = {0};
  time_t t = time(NULL);
  (void)localtime_r(&t, &tt_cur);

  if( g_file_get_contents( filename, &svgdata, &length, NULL) )
  {
    // File is loaded lets substitute strings if found...

    // Darktable internal
    svgdoc = _string_substitute(svgdata,"$(DARKTABLE.NAME)",PACKAGE_NAME);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    svgdoc = _string_substitute(svgdata,"$(DARKTABLE.VERSION)",PACKAGE_VERSION);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }

    // Current image ID
    gchar buffer[1024];
    g_snprintf(buffer,sizeof(buffer),"%d",image->id);
    svgdoc = _string_substitute(svgdata,"$(IMAGE.ID)",buffer);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }

    // Current image
    dt_image_print_exif(image,buffer,sizeof(buffer));
    svgdoc = _string_substitute(svgdata,"$(IMAGE.EXIF)",buffer);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }

    // Image exif
    // EXIF date
    svgdoc = _string_substitute(svgdata,"$(EXIF.DATE)",image->exif_datetime_taken);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(EXIF.DATE.SECOND) -- 00..60
    strftime(datetime, sizeof(datetime), "%S", &tt_exif);
    svgdoc = _string_substitute(svgdata,"$(EXIF.DATE.SECOND)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(EXIF.DATE.MINUTE) -- 00..59
    strftime(datetime, sizeof(datetime), "%M", &tt_exif);
    svgdoc = _string_substitute(svgdata,"$(EXIF.DATE.MINUTE)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(EXIF.DATE.HOUR) -- 00..23
    strftime(datetime, sizeof(datetime), "%H", &tt_exif);
    svgdoc = _string_substitute(svgdata,"$(EXIF.DATE.HOUR)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(EXIF.DATE.HOUR_AMPM) -- 01..12
    strftime(datetime, sizeof(datetime), "%I %p", &tt_exif);
    svgdoc = _string_substitute(svgdata,"$(EXIF.DATE.HOUR_AMPM)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(EXIF.DATE.DAY) -- 01..31
    strftime(datetime, sizeof(datetime), "%d", &tt_exif);
    svgdoc = _string_substitute(svgdata,"$(EXIF.DATE.DAY)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(EXIF.DATE.MONTH) -- 01..12
    strftime(datetime, sizeof(datetime), "%m", &tt_exif);
    svgdoc = _string_substitute(svgdata,"$(EXIF.DATE.MONTH)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(EXIF.DATE.SHORT_MONTH) -- Jan, Feb, .., Dec, localized
    strftime(datetime, sizeof(datetime), "%b", &tt_exif);
    svgdoc = _string_substitute(svgdata,"$(EXIF.DATE.SHORT_MONTH)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(EXIF.DATE.LONG_MONTH) -- January, February, .., December, localized
    strftime(datetime, sizeof(datetime), "%B", &tt_exif);
    svgdoc = _string_substitute(svgdata,"$(EXIF.DATE.LONG_MONTH)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(EXIF.DATE.SHORT_YEAR) -- 12
    strftime(datetime, sizeof(datetime), "%y", &tt_exif);
    svgdoc = _string_substitute(svgdata,"$(EXIF.DATE.SHORT_YEAR)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(EXIF.DATE.LONG_YEAR) -- 2012
    strftime(datetime, sizeof(datetime), "%Y", &tt_exif);
    svgdoc = _string_substitute(svgdata,"$(EXIF.DATE.LONG_YEAR)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }

    // Current date
    // $(DATE) -- YYYY:
    dt_gettime_t(datetime, sizeof(datetime), t);
    svgdoc = _string_substitute(svgdata,"$(DATE)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(DATE.SECOND) -- 00..60
    strftime(datetime, sizeof(datetime), "%S", &tt_cur);
    svgdoc = _string_substitute(svgdata,"$(DATE.SECOND)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(DATE.MINUTE) -- 00..59
    strftime(datetime, sizeof(datetime), "%M", &tt_cur);
    svgdoc = _string_substitute(svgdata,"$(DATE.MINUTE)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(DATE.HOUR) -- 00..23
    strftime(datetime, sizeof(datetime), "%H", &tt_cur);
    svgdoc = _string_substitute(svgdata,"$(DATE.HOUR)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(DATE.HOUR_AMPM) -- 01..12
    strftime(datetime, sizeof(datetime), "%I %p", &tt_cur);
    svgdoc = _string_substitute(svgdata,"$(DATE.HOUR_AMPM)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(DATE.DAY) -- 01..31
    strftime(datetime, sizeof(datetime), "%d", &tt_cur);
    svgdoc = _string_substitute(svgdata,"$(DATE.DAY)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(DATE.MONTH) -- 01..12
    strftime(datetime, sizeof(datetime), "%m", &tt_cur);
    svgdoc = _string_substitute(svgdata,"$(DATE.MONTH)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(DATE.SHORT_MONTH) -- Jan, Feb, .., Dec, localized
    strftime(datetime, sizeof(datetime), "%b", &tt_cur);
    svgdoc = _string_substitute(svgdata,"$(DATE.SHORT_MONTH)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(DATE.LONG_MONTH) -- January, February, .., December, localized
    strftime(datetime, sizeof(datetime), "%B", &tt_cur);
    svgdoc = _string_substitute(svgdata,"$(DATE.LONG_MONTH)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(DATE.SHORT_YEAR) -- 12
    strftime(datetime, sizeof(datetime), "%y", &tt_cur);
    svgdoc = _string_substitute(svgdata,"$(DATE.SHORT_YEAR)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    // $(DATE.LONG_YEAR) -- 2012
    strftime(datetime, sizeof(datetime), "%Y", &tt_cur);
    svgdoc = _string_substitute(svgdata,"$(DATE.LONG_YEAR)",datetime);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }

    svgdoc = _string_substitute(svgdata,"$(EXIF.MAKER)",image->exif_maker);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    svgdoc = _string_substitute(svgdata,"$(EXIF.MODEL)",image->exif_model);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    svgdoc = _string_substitute(svgdata,"$(EXIF.LENS)",image->exif_lens);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }

    svgdoc = _string_substitute(svgdata,"$(IMAGE.FILENAME)",image->filename);
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }

    // TODO: auto generate that code?
    GList * res;
    res = dt_metadata_get(image->id, "Xmp.dc.creator", NULL);
    svgdoc = _string_substitute(svgdata,"$(Xmp.dc.creator)",(res?res->data:""));
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    if( res )
    {
      g_list_free_full(res, &g_free);
    }

    res = dt_metadata_get(image->id, "Xmp.dc.publisher", NULL);
    svgdoc = _string_substitute(svgdata,"$(Xmp.dc.publisher)",(res?res->data:""));
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    if( res )
    {
      g_list_free_full(res, &g_free);
    }

    res = dt_metadata_get(image->id, "Xmp.dc.title", NULL);
    svgdoc = _string_substitute(svgdata,"$(Xmp.dc.title)",(res?res->data:""));
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    if( res )
    {
      g_list_free_full(res, &g_free);
    }

    res = dt_metadata_get(image->id, "Xmp.dc.description", NULL);
    svgdoc = _string_substitute(svgdata,"$(Xmp.dc.description)",(res?res->data:""));
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    if( res )
    {
      g_list_free_full(res, &g_free);
    }

    res = dt_metadata_get(image->id, "Xmp.dc.rights", NULL);
    svgdoc = _string_substitute(svgdata,"$(Xmp.dc.rights)",(res?res->data:""));
    if( svgdoc != svgdata )
    {
      g_free(svgdata);
      svgdata = svgdoc;
    }
    if( res )
    {
      g_list_free_full(res, &g_free);
    }

  }
  return svgdoc;
}
Esempio n. 7
0
static GwyContainer*
nanoscope_load(const gchar *filename,
               G_GNUC_UNUSED GwyRunType mode,
               GError **error)
{
    GwyContainer *meta, *container = NULL;
    GError *err = NULL;
    gchar *buffer = NULL;
    gchar *p;
    const gchar *self;
    gsize size = 0;
    NanoscopeFileType file_type;
    NanoscopeData *ndata;
    NanoscopeValue *val;
    GHashTable *hash, *scannerlist = NULL, *scanlist = NULL;
    GList *l, *list = NULL;
    gint i, xres = 0, yres = 0;
    gboolean ok, has_version = FALSE;

    if (!g_file_get_contents(filename, &buffer, &size, &err)) {
        err_GET_FILE_CONTENTS(error, &err);
        return NULL;
    }
    file_type = NANOSCOPE_FILE_TYPE_NONE;
    if (size > MAGIC_SIZE) {
        if (!memcmp(buffer, MAGIC_TXT, MAGIC_SIZE))
            file_type = NANOSCOPE_FILE_TYPE_TXT;
        else if (!memcmp(buffer, MAGIC_BIN, MAGIC_SIZE))
            file_type = NANOSCOPE_FILE_TYPE_BIN;
    }
    if (!file_type) {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                    _("File is not a Nanoscope file, "
                      "or it is a unknown subtype."));
        g_free(buffer);
        return NULL;
    }
    gwy_debug("File type: %d", file_type);
    /* as already know file_type, fix the first char for hash reading */
    *buffer = '\\';

    p = buffer;
    while ((hash = read_hash(&p, &err))) {
        ndata = g_new0(NanoscopeData, 1);
        ndata->hash = hash;
        list = g_list_append(list, ndata);
    }
    if (err) {
        g_propagate_error(error, err);
        ok = FALSE;
    }
    else
        ok = TRUE;

    for (l = list; ok && l; l = g_list_next(l)) {
        ndata = (NanoscopeData*)l->data;
        hash = ndata->hash;
        self = g_hash_table_lookup(hash, "#self");
        /* The alternate names were found in files written by some beast
         * called Nanoscope E software */
        if (gwy_strequal(self, "Scanner list")
            || gwy_strequal(self, "Microscope list")) {
            scannerlist = hash;
            continue;
        }
        if (gwy_strequal(self, "File list")) {
            has_version = !!g_hash_table_lookup(hash, "Version");
            gwy_debug("has Version: %d", has_version);
            continue;
        }
        if (gwy_strequal(self, "Ciao scan list")
            || gwy_strequal(self, "Afm list")
            || gwy_strequal(self, "NC Afm list")) {
            get_scan_list_res(hash, &xres, &yres);
            scanlist = hash;
        }
        if (!gwy_strequal(self, "Ciao image list")
            && !gwy_strequal(self, "AFM image list")
            && !gwy_strequal(self, "NCAFM image list"))
            continue;

        ndata->data_field = hash_to_data_field(hash, scannerlist, scanlist,
                                               file_type, has_version,
                                               size, buffer,
                                               xres, yres,
                                               &p, error);
        ok = ok && ndata->data_field;
    }

    if (ok) {
        gchar key[40];

        i = 0;
        container = gwy_container_new();
        for (l = list; l; l = g_list_next(l)) {
            ndata = (NanoscopeData*)l->data;
            if (ndata->data_field) {
                g_snprintf(key, sizeof(key), "/%d/data", i);
                gwy_container_set_object_by_name(container, key,
                                                 ndata->data_field);
                if ((val = g_hash_table_lookup(ndata->hash, "@2:Image Data"))
                    && val->soft_scale) {
                    g_snprintf(key, sizeof(key), "/%d/data/title", i);
                    gwy_container_set_string_by_name(container, key,
                                                     g_strdup(val->soft_scale));
                }

                meta = nanoscope_get_metadata(ndata->hash, list);
                g_snprintf(key, sizeof(key), "/%d/meta", i);
                gwy_container_set_object_by_name(container, key, meta);
                g_object_unref(meta);

                gwy_app_channel_check_nonsquare(container, i);
                i++;
            }
        }
        if (!i)
            gwy_object_unref(container);
    }

    for (l = list; l; l = g_list_next(l)) {
        ndata = (NanoscopeData*)l->data;
        gwy_object_unref(ndata->data_field);
        if (ndata->hash)
            g_hash_table_destroy(ndata->hash);
        g_free(ndata);
    }
    g_free(buffer);
    g_list_free(list);

    if (!container && ok)
        err_NO_DATA(error);

    return container;
}
Esempio n. 8
0
static GtkWidget *create_dialog(void)
{
	GtkWidget *dialog;
	GtkWidget *header_image;
	GtkWidget *header_label;
	GtkWidget *label_info;
	GtkWidget *codename_label;
	GtkWidget *builddate_label;
	GtkWidget *url_button;
	GtkWidget *cop_label;
	GtkWidget *label;
	GtkWidget *license_textview;
	GtkWidget *notebook;
	GtkWidget *box;
	GtkWidget *credits_scrollwin;
	GtkWidget *table;
	GtkWidget *license_scrollwin;
	GtkWidget *info_box;
	GtkWidget *header_hbox;
	GtkWidget *header_eventbox;
	GdkPixbuf *icon;
	GtkTextBuffer* tb;
	gchar *license_text = NULL;
	gchar buffer[512];
	gchar buffer2[128];
	guint i, row = 0;

	dialog = gtk_dialog_new();

	/* configure dialog */
	gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(main_widgets.window));
	gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER_ON_PARENT);
	gtk_window_set_title(GTK_WINDOW(dialog), _("About Geany"));
	gtk_widget_set_name(dialog, "GeanyDialog");
	gtk_dialog_add_button(GTK_DIALOG(dialog), GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE);
	gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CLOSE);
	gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE);
	g_signal_connect(dialog, "key-press-event", G_CALLBACK(gb_on_key_pressed), NULL);

	/* create header */
	header_eventbox = gtk_event_box_new();
	gtk_widget_show(header_eventbox);
	header_hbox = gtk_hbox_new(FALSE, 12);
	gtk_container_set_border_width(GTK_CONTAINER(header_hbox), 4);
	gtk_widget_show(header_hbox);
	gtk_container_add(GTK_CONTAINER(header_eventbox), header_hbox);
	header_image = gtk_image_new();
	gtk_box_pack_start(GTK_BOX(header_hbox), header_image, FALSE, FALSE, 0);
	header_label = gtk_label_new(NULL);
	gtk_label_set_use_markup(GTK_LABEL(header_label), TRUE);
	/* print the subversion revision generated by ./configure if it is available */
	g_snprintf(buffer, sizeof(buffer), HEADER, main_get_version_string());
	gtk_label_set_markup(GTK_LABEL(header_label), buffer);
	gtk_widget_show(header_label);
	gtk_box_pack_start(GTK_BOX(header_hbox), header_label, FALSE, FALSE, 0);
	header_eventbox_style_set(header_eventbox);
	header_label_style_set(header_label);
	g_signal_connect_after(header_eventbox, "style-set", G_CALLBACK(header_eventbox_style_set), NULL);
	g_signal_connect_after(header_label, "style-set", G_CALLBACK(header_label_style_set), NULL);
	gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), header_eventbox, FALSE, FALSE, 0);

	/* set image */
	icon = ui_new_pixbuf_from_inline(GEANY_IMAGE_LOGO);
	gtk_image_set_from_pixbuf(GTK_IMAGE(header_image), icon);
	gtk_window_set_icon(GTK_WINDOW(dialog), icon);
	g_object_unref(icon);	/* free our reference */

	/* create notebook */
	notebook = gtk_notebook_new();
	gtk_widget_show(notebook);
	gtk_container_set_border_width(GTK_CONTAINER(notebook), 2);
	gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), notebook, TRUE, TRUE, 0);

	/* create "Info" tab */
	info_box = gtk_vbox_new(FALSE, 0);
	gtk_container_set_border_width(GTK_CONTAINER(info_box), 6);
	gtk_widget_show(info_box);

	label_info = gtk_label_new(NULL);
	gtk_label_set_justify(GTK_LABEL(label_info), GTK_JUSTIFY_CENTER);
	gtk_label_set_selectable(GTK_LABEL(label_info), TRUE);
	gtk_label_set_use_markup(GTK_LABEL(label_info), TRUE);
	g_snprintf(buffer, sizeof(buffer), INFO, _("A fast and lightweight IDE"));
	gtk_label_set_markup(GTK_LABEL(label_info), buffer);
	gtk_misc_set_padding(GTK_MISC(label_info), 2, 11);
	gtk_widget_show(label_info);
	gtk_box_pack_start(GTK_BOX(info_box), label_info, FALSE, FALSE, 0);

	/* Codename label */
	codename_label = gtk_label_new(NULL);
	gtk_label_set_justify(GTK_LABEL(codename_label), GTK_JUSTIFY_CENTER);
	gtk_label_set_selectable(GTK_LABEL(codename_label), TRUE);
	gtk_label_set_use_markup(GTK_LABEL(codename_label), TRUE);
	gtk_label_set_markup(GTK_LABEL(codename_label), CODENAME);
	gtk_misc_set_padding(GTK_MISC(codename_label), 2, 8);
	gtk_widget_show(codename_label);
	gtk_box_pack_start(GTK_BOX(info_box), codename_label, FALSE, FALSE, 0);

	/* build date label */
	builddate_label = gtk_label_new(NULL);
	gtk_label_set_justify(GTK_LABEL(builddate_label), GTK_JUSTIFY_CENTER);
	gtk_label_set_selectable(GTK_LABEL(builddate_label), TRUE);
	gtk_label_set_use_markup(GTK_LABEL(builddate_label), TRUE);
	g_snprintf(buffer2, sizeof(buffer2), _("(built on or after %s)"), __DATE__);
	g_snprintf(buffer, sizeof(buffer), BUILDDATE, buffer2);
	gtk_label_set_markup(GTK_LABEL(builddate_label), buffer);
	gtk_misc_set_padding(GTK_MISC(builddate_label), 2, 2);
	gtk_widget_show(builddate_label);
	gtk_box_pack_start(GTK_BOX(info_box), builddate_label, FALSE, FALSE, 0);

	box = gtk_hbutton_box_new();
	url_button = gtk_button_new();
	gtk_button_set_relief(GTK_BUTTON(url_button), GTK_RELIEF_NONE);
	g_signal_connect(url_button, "clicked", G_CALLBACK(homepage_clicked), (gpointer)GEANY_HOMEPAGE);
	label = gtk_label_new(NULL);
	gtk_label_set_text(GTK_LABEL(label), GEANY_HOMEPAGE);
	gtk_widget_show(label);
	gtk_container_add(GTK_CONTAINER(url_button), label);
	gtk_widget_show(url_button);
	gtk_box_pack_start(GTK_BOX(box), url_button, FALSE, FALSE, 0);
	gtk_widget_show(box);
	gtk_box_pack_start(GTK_BOX(info_box), box, FALSE, FALSE, 10);

	/* copyright label */
	cop_label = gtk_label_new(NULL);
	gtk_label_set_justify(GTK_LABEL(cop_label), GTK_JUSTIFY_CENTER);
	gtk_label_set_selectable(GTK_LABEL(cop_label), FALSE);
	gtk_label_set_use_markup(GTK_LABEL(cop_label), TRUE);
	gtk_label_set_markup(GTK_LABEL(cop_label), COPYRIGHT);
	gtk_misc_set_padding(GTK_MISC(cop_label), 2, 10);
	gtk_widget_show(cop_label);
	gtk_box_pack_start(GTK_BOX(info_box), cop_label, FALSE, FALSE, 0);
	/*gtk_container_add(GTK_CONTAINER(info_box), cop_label); */

	label = gtk_label_new(_("Info"));
	gtk_widget_show(label);
	gtk_widget_show_all(info_box);
	gtk_notebook_append_page(GTK_NOTEBOOK(notebook), info_box, label);

	/* create "Credits" tab */
	credits_scrollwin = gtk_scrolled_window_new(NULL, NULL);
	gtk_container_set_border_width(GTK_CONTAINER(credits_scrollwin), 6);
	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(credits_scrollwin),
		GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);

	table = gtk_table_new(23 + translators_len + prev_translators_len, 3, FALSE);
	gtk_table_set_col_spacings(GTK_TABLE(table), 10);

	row = 0;
	g_snprintf(buffer, sizeof(buffer),
		"<span size=\"larger\" weight=\"bold\">%s</span>", _("Developers"));
	label = gtk_label_new(buffer);
	gtk_table_attach(GTK_TABLE(table), label, 0, 2, row, row + 1, GTK_FILL, 0, 0, 5);
	gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
	gtk_misc_set_alignment(GTK_MISC(label), 0, 0);
	row++;

	g_snprintf(buffer, sizeof(buffer), "Colomban Wendling - %s", _("maintainer"));
	ROW(buffer, row, 0, 0, 0, 1);
	row++;
	ROW("&lt;[email protected]&gt;", row, 0, 0, 0, 1);
	row++;
	ROW("", row, 0, 0, 0, 0);
	row++;

	g_snprintf(buffer, sizeof(buffer), "Nick Treleaven - %s", _("developer"));
	ROW(buffer, row, 0, 0, 0, 1);
	row++;
	ROW("&lt;[email protected]&gt;", row, 0, 0, 0, 1);
	row++;
	ROW("", row, 0, 0, 0, 0);
	row++;

	g_snprintf(buffer, sizeof(buffer), "Enrico Tröger - %s", _("developer"));
	ROW(buffer, row, 0, 0, 0, 1);
	row++;
	ROW("&lt;[email protected]&gt;", row, 0, 0, 0, 1);
	row++;
	ROW("", row, 0, 0, 0, 0);
	row++;

	g_snprintf(buffer, sizeof(buffer), "Matthew Brush - %s", _("developer"));
	ROW(buffer, row, 0, 0, 0, 1);
	row++;
	ROW("&lt;[email protected]&gt;", row, 0, 0, 0, 1);
	row++;
	ROW("", row, 0, 0, 0, 0);
	row++;

	g_snprintf(buffer, sizeof(buffer), "Frank Lanitz - %s", _("translation maintainer"));
	ROW(buffer, row, 0, 0, 0, 1);
	row++;
	ROW("&lt;[email protected]&gt;", row, 0, 0, 0, 1);
	row++;
	ROW("", row, 0, 0, 0, 0);
	row++;

	g_snprintf(buffer, sizeof(buffer),
		"<span size=\"larger\" weight=\"bold\">%s</span>", _("Translators"));
	label = gtk_label_new(buffer);
	gtk_table_attach(GTK_TABLE(table), label, 0, 2, row, row + 1,
					(GtkAttachOptions) (GTK_FILL),
					(GtkAttachOptions) (0), 0, 5);
	gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
	gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
	row++;

	for (i = 0; i < translators_len; i++)
	{
		ROW(translators[i][0], row, 0, 1, 4, 0);
		ROW(translators[i][1], row, 1, 0, 4, 0);
		row++;
	}

	ROW("", row, 0, 0, 0, 0);
	row++;

	g_snprintf(buffer, sizeof(buffer),
		"<span size=\"larger\" weight=\"bold\">%s</span>", _("Previous Translators"));
	label = gtk_label_new(buffer);
	gtk_table_attach(GTK_TABLE(table), label, 0, 2, row, row + 1,
					(GtkAttachOptions) (GTK_FILL),
					(GtkAttachOptions) (0), 0, 5);
	gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
	gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
	row++;

	for (i = 0; i < prev_translators_len; i++)
	{
		ROW(prev_translators[i][0], row, 0, 1, 4, 0);
		ROW(prev_translators[i][1], row, 1, 0, 4, 0);
		row++;
	}


	ROW("", row, 0, 0, 0, 0);
	row++;

	g_snprintf(buffer, sizeof(buffer),
		"<span size=\"larger\" weight=\"bold\">%s</span>", _("Contributors"));
	label = gtk_label_new(buffer);
	gtk_table_attach(GTK_TABLE(table), label, 0, 2, row, row + 1,
					(GtkAttachOptions) (GTK_FILL),
					(GtkAttachOptions) (0), 0, 5);
	gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
	gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
	row++;

	g_snprintf(buffer, sizeof(buffer),
		_("Some of the many contributors (for a more detailed list, see the file %s):"),
#ifdef G_OS_WIN32
			"Thanks.txt"
#else
			"THANKS"
#endif
		);
	label = geany_wrap_label_new(buffer);
	gtk_table_attach(GTK_TABLE(table), label, 0, 2, row, row + 1,
					(GtkAttachOptions) (GTK_FILL),
					(GtkAttachOptions) (0), 0, 5);
	gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
	gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
	row++;

	label = geany_wrap_label_new(contributors);
	gtk_table_attach(GTK_TABLE(table), label, 0, 2, row, row + 1,
					(GtkAttachOptions) (GTK_FILL | GTK_EXPAND),
					(GtkAttachOptions) (0), 0, 5);
	gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
	gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
	row++;

	gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(credits_scrollwin), table);
	gtk_viewport_set_shadow_type(GTK_VIEWPORT(gtk_widget_get_parent(table)), GTK_SHADOW_NONE);
	gtk_widget_show_all(table);
	label = gtk_label_new(_("Credits"));
	gtk_widget_show(label);
	gtk_notebook_append_page(GTK_NOTEBOOK(notebook), credits_scrollwin, label);

	/* create "License" tab */
	license_scrollwin = gtk_scrolled_window_new(NULL, NULL);
	gtk_container_set_border_width(GTK_CONTAINER(license_scrollwin), 6);
	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(license_scrollwin),
		GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
	gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(license_scrollwin), GTK_SHADOW_IN);
	license_textview = gtk_text_view_new();
	gtk_text_view_set_left_margin(GTK_TEXT_VIEW(license_textview), 2);
	gtk_text_view_set_right_margin(GTK_TEXT_VIEW(license_textview), 2);
	gtk_text_view_set_editable(GTK_TEXT_VIEW(license_textview), FALSE);
	gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(license_textview), FALSE);
	gtk_widget_show(license_textview);
	gtk_container_add(GTK_CONTAINER(license_scrollwin), license_textview);
	label = gtk_label_new(_("License"));
	gtk_widget_show(label);

	g_snprintf(buffer, sizeof(buffer), "%s" G_DIR_SEPARATOR_S "GPL-2", app->datadir);

	g_file_get_contents(buffer, &license_text, NULL, NULL);
	if (license_text == NULL)
	{
		license_text = g_strdup(
			_("License text could not be found, please visit http://www.gnu.org/licenses/gpl-2.0.txt to view it online."));
	}
	tb = gtk_text_view_get_buffer(GTK_TEXT_VIEW(license_textview));
	gtk_text_buffer_set_text(tb, license_text, -1);

	g_free(license_text);

	gtk_notebook_append_page(GTK_NOTEBOOK(notebook), license_scrollwin, label);

	gtk_widget_show_all(dialog);
	return dialog;
}
Esempio n. 9
0
/*
 * Arguments:
 *   1) .node file to compare
 *   2) .png file to compare the rendered .node file to
 */
int
main (int argc, char **argv)
{
  cairo_surface_t *reference_surface = NULL;
  cairo_surface_t *rendered_surface = NULL;
  cairo_surface_t *diff_surface = NULL;
  GdkTexture *texture;
  GskRenderer *renderer;
  GdkSurface *window;
  GskRenderNode *node;
  const char *node_file;
  const char *png_file;

  g_assert (argc == 3);

  gtk_init ();

  node_file = argv[1];
  png_file = argv[2];

  window = gdk_surface_new_toplevel (gdk_display_get_default(), 10 , 10);
  renderer = gsk_renderer_new_for_surface (window);

  g_test_message ("Node file: '%s'\n", node_file);
  g_test_message ("PNG file: '%s'\n", png_file);

  /* Load the render node from the given .node file */
  {
    GBytes *bytes;
    GError *error = NULL;
    gsize len;
    char *contents;

    if (!g_file_get_contents (node_file, &contents, &len, &error))
      {
        g_test_message ("Could not open node file: %s\n", error->message);
        g_clear_error (&error);
        g_test_fail ();
        return -1;
      }

    bytes = g_bytes_new_take (contents, len);
    node = gsk_render_node_deserialize (bytes, &error);
    g_bytes_unref (bytes);

    g_assert (node != NULL);
  }

  /* Render the .node file and download to cairo surface */
  texture = gsk_renderer_render_texture (renderer, node, NULL);
  g_assert (texture != NULL);

  rendered_surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
                                                 gdk_texture_get_width (texture),
                                                 gdk_texture_get_height (texture));
  gdk_texture_download (texture,
                        cairo_image_surface_get_data (rendered_surface),
                        cairo_image_surface_get_stride (rendered_surface));
  cairo_surface_mark_dirty (rendered_surface);

  /* Load the given reference png file */
  reference_surface = cairo_image_surface_create_from_png (png_file);
  g_assert (reference_surface != NULL);

  /* Now compare the two */
  diff_surface = reftest_compare_surfaces (rendered_surface, reference_surface);

  save_image (rendered_surface, node_file, ".out.png");

  if (diff_surface)
    save_image (diff_surface, node_file, ".diff.png");

  g_assert (diff_surface == NULL);

  return 0;
}
Esempio n. 10
0
int main(int argc, char *argv[])
{
	int ret;
	const char *cid;
	char cmd[CMD_SIZE];
	GError *err = NULL;
	_cleanup_free_ char *contents;
	int cpid = -1;
	int status;
	pid_t pid;
	_cleanup_close_ int mfd = -1;
	_cleanup_close_ int epfd = -1;
	char slname[BUF_SIZE];
	char buf[BUF_SIZE];
	int num_read;
	struct termios t;
	struct epoll_event ev;
	struct epoll_event evlist[MAX_EVENTS];

	if (argc < 2) {
		nexit("Run as: conmon <id>");
	}

	/* Get the container id */
	cid = argv[1];

	/*
	 * Set self as subreaper so we can wait for container process
	 * and return its exit code.
	 */
	ret = prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0);
	if (ret != 0) {
		pexit("Failed to set as subreaper");
	}

	/* Open the master pty */
	mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
	if (mfd < 0)
		pexit("Failed to open console master pty");

	/* Grant access to the slave pty */
	if (grantpt(mfd) == -1)
		pexit("Failed to grant access to slave pty");

	/* Unlock the slave pty */
	if (unlockpt(mfd) == -1) {             /* Unlock slave pty */
		pexit("Failed to unlock the slave pty");
	}

	/* Get the slave pty name */
	ret = ptsname_r(mfd, slname, BUF_SIZE);
	if (ret != 0) {
		pexit("Failed to get the slave pty name");
	}

	/* Create the container */
	snprintf(cmd, CMD_SIZE, "runc create %s --pid-file pidfile --console %s", cid, slname);
	ret = system(cmd);
	if (ret != 0) {
		nexit("Failed to create container");
	}

	/* Read the pid so we can wait for the process to exit */
	g_file_get_contents("pidfile", &contents, NULL, &err);
	if (err) {
		fprintf(stderr, "Failed to read pidfile: %s\n", err->message);
		g_error_free(err);
		exit(1);
	}

	cpid = atoi(contents);
	printf("container PID: %d\n", cpid);

	/* Save exiting termios settings */
	if (tcgetattr(STDIN_FILENO, &tty_orig) == -1)
		pexit("tcegetattr");

	/* Settings for raw mode */
	t.c_lflag &= ~(ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHONL | IEXTEN);
	t.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR | INPCK |
		       ISTRIP | IXON | IXOFF | IGNPAR | PARMRK);
	t.c_oflag &= ~OPOST;
	t.c_cc[VMIN] = 1;
	t.c_cc[VTIME] = 0;

	/* Set terminal to raw mode */
	if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &t) == -1)
		pexit("tcsetattr");

	/* Setup terminal restore on exit */
	if (atexit(tty_restore) != 0)
		pexit("atexit");

	epfd = epoll_create(5);
	if (epfd < 0)
		pexit("epoll_create");
	ev.events = EPOLLIN;
	ev.data.fd = STDIN_FILENO;
	if (epoll_ctl(epfd, EPOLL_CTL_ADD, STDIN_FILENO, &ev) < 0) {
		pexit("Failed to add stdin to epoll");
	}
	ev.data.fd = mfd;
	if (epoll_ctl(epfd, EPOLL_CTL_ADD, mfd, &ev) < 0) {
		pexit("Failed to add console master fd to epoll");
	}

	/* Copy data back and forth between STDIN and master fd */
	while (true) {
		int ready = epoll_wait(epfd, evlist, MAX_EVENTS, -1);
		for (int i = 0; i < ready; i++) {
			if (evlist[i].events & EPOLLIN) {
				if (evlist[i].data.fd == STDIN_FILENO) {
					num_read = read(STDIN_FILENO, buf, BUF_SIZE);
					if (num_read <= 0)
						goto out;

					if (write(mfd, buf, num_read) != num_read) {
						nwarn("partial/failed write (masterFd)");
						goto out;
					}
				} else if (evlist[i].data.fd == mfd) {
					num_read = read(mfd, buf, BUF_SIZE);
					if (num_read <= 0)
						goto out;

					if (write(STDOUT_FILENO, buf, num_read) != num_read) {
						nwarn("partial/failed write (STDOUT_FILENO)");
						goto out;
					}
				}
			} else if (evlist[i].events & (EPOLLHUP | EPOLLERR)) {
				printf("closing fd %d\n", evlist[i].data.fd);
				if (close(evlist[i].data.fd) < 0)
					pexit("close");
				goto out;
			}
		}
	}
out:
	tty_restore();

	/* Wait for the container process and record its exit code */
	while ((pid = waitpid(-1, &status, 0)) > 0) {
		printf("PID %d exited\n", pid);
		if (pid == cpid) {
			_cleanup_free_ char *status_str = NULL;
			ret = asprintf(&status_str, "%d", status);
			if (ret < 0) {
				pexit("Failed to allocate memory for status");
			}
			g_file_set_contents("exit", status_str, strlen(status_str), &err);
			if (err) {
				fprintf(stderr, "Failed to write %s to exit file: %s\n", status_str, err->message);
				g_error_free(err);
				exit(1);
			}
			break;
		}
	}

	return EXIT_SUCCESS;
}
/* Parse /proc/net/route to get default gateway address and then parse
 * /proc/net/arp to find matching mac address.
 *
 * There are some problems with this. First, it's IPv4 only.
 * Second, there must be a way to do this with ioctl, but that seemed really
 * complicated... even /usr/sbin/arp parses /proc/net/arp
 *
 * returns:
 *   1 : on success
 *   0 : no success, no errors
 *  <0 : error
 */
int
get_mac_address (char **mac)
{
	char *content;
	char **lines, **entry;
	GError *error = NULL;
	char *route_gateway = NULL;

	g_assert (*mac == NULL);

	if (!g_file_get_contents ("/proc/net/route", &content, NULL, &error)) {
		g_warning ("Failed to read /proc/net/route: %s", error->message);
		g_error_free (error);
		return -1;
	}

	lines = g_strsplit (content, "\n", 0);
	g_free (content);
	entry = lines + 1;

	while (*entry && strlen (*entry) > 0) {
		char dest[9];
		char gateway[9];
		if (sscanf (*entry,
			        "%*s %8[0-9A-Fa-f] %8[0-9A-Fa-f] %*s",
			        dest, gateway) != 2) {
			g_warning ("Failed to parse /proc/net/route entry '%s'", *entry);
		} else if (strcmp (dest, "00000000") == 0) {
			route_gateway = g_strdup (gateway);
			break;
		}
		entry++;
	}
	g_strfreev (lines);

	if (!route_gateway) {
		g_warning ("Failed to find default route in /proc/net/route");
		return -1;
	}

	if (!g_file_get_contents ("/proc/net/arp", &content, NULL, &error)) {
		g_warning ("Failed to read /proc/net/arp: %s", error->message);
		g_error_free (error);
		return -1;
	}

	lines = g_strsplit (content, "\n", 0);
	g_free (content);
	entry = lines+1;
	while (*entry && strlen (*entry) > 0) {
		char hwa[100];
		char *arp_gateway;
		int ip[4];

		if (sscanf(*entry,
		           "%d.%d.%d.%d 0x%*x 0x%*x %100s %*s %*s\n",
		           &ip[0], &ip[1], &ip[2], &ip[3], hwa) != 5) {
			g_warning ("Failed to parse /proc/net/arp entry '%s'", *entry);
		} else {
			arp_gateway = g_strdup_printf ("%02X%02X%02X%02X", ip[3], ip[2], ip[1], ip[0]);
			if (strcmp (arp_gateway, route_gateway) == 0) {
				g_free (arp_gateway);
				*mac = g_strdup (hwa);
				break;
			}
			g_free (arp_gateway);

		}
		entry++;
	}
	g_free (route_gateway);
	g_strfreev (lines);

	return *mac ? 1 : 0;
}
Esempio n. 12
0
int
qcrypto_tls_creds_get_dh_params_file(QCryptoTLSCreds *creds,
                                     const char *filename,
                                     gnutls_dh_params_t *dh_params,
                                     Error **errp)
{
    int ret;

    trace_qcrypto_tls_creds_load_dh(creds, filename ? filename : "<generated>");

    if (filename == NULL) {
        ret = gnutls_dh_params_init(dh_params);
        if (ret < 0) {
            error_setg(errp, "Unable to initialize DH parameters: %s",
                       gnutls_strerror(ret));
            return -1;
        }
        ret = gnutls_dh_params_generate2(*dh_params, DH_BITS);
        if (ret < 0) {
            gnutls_dh_params_deinit(*dh_params);
            *dh_params = NULL;
            error_setg(errp, "Unable to generate DH parameters: %s",
                       gnutls_strerror(ret));
            return -1;
        }
    } else {
        GError *gerr = NULL;
        gchar *contents;
        gsize len;
        gnutls_datum_t data;
        if (!g_file_get_contents(filename,
                                 &contents,
                                 &len,
                                 &gerr)) {

            error_setg(errp, "%s", gerr->message);
            g_error_free(gerr);
            return -1;
        }
        data.data = (unsigned char *)contents;
        data.size = len;
        ret = gnutls_dh_params_init(dh_params);
        if (ret < 0) {
            g_free(contents);
            error_setg(errp, "Unable to initialize DH parameters: %s",
                       gnutls_strerror(ret));
            return -1;
        }
        ret = gnutls_dh_params_import_pkcs3(*dh_params,
                                            &data,
                                            GNUTLS_X509_FMT_PEM);
        g_free(contents);
        if (ret < 0) {
            gnutls_dh_params_deinit(*dh_params);
            *dh_params = NULL;
            error_setg(errp, "Unable to load DH parameters from %s: %s",
                       filename, gnutls_strerror(ret));
            return -1;
        }
    }

    return 0;
}
static gboolean
tls_default_filter (const GtkFileFilterInfo *filter_info, gpointer data)
{
	char *contents = NULL, *p, *ext;
	gsize bytes_read = 0;
	gboolean show = FALSE;
	struct stat statbuf;

	if (!filter_info->filename)
		return FALSE;

	p = strrchr (filter_info->filename, '.');
	if (!p)
		return FALSE;

	ext = g_ascii_strdown (p, -1);
	if (!ext)
		return FALSE;
	if (strcmp (ext, ".pem") && strcmp (ext, ".crt") && strcmp (ext, ".key")) {
		g_free (ext);
		return FALSE;
	}
	g_free (ext);

	/* Ignore files that are really large */
	if (!stat (filter_info->filename, &statbuf)) {
		if (statbuf.st_size > 500000)
			return FALSE;
	}

	if (!g_file_get_contents (filter_info->filename, &contents, &bytes_read, NULL))
		return FALSE;

	if (bytes_read < 400)  /* needs to be lower? */
		goto out;

	/* Check for PEM signatures */
	if (find_tag (pem_rsa_key_begin, (const char *) contents, bytes_read)) {
		show = TRUE;
		goto out;
	}

	if (find_tag (pem_dsa_key_begin, (const char *) contents, bytes_read)) {
		show = TRUE;
		goto out;
	}

	if (find_tag (pem_key_begin, (const char *) contents, bytes_read)) {
		show = TRUE;
		goto out;
	}

	if (find_tag (pem_enc_key_begin, (const char *) contents, bytes_read)) {
		show = TRUE;
		goto out;
	}

	if (find_tag (pem_tss_keyblob_begin, (const char *) contents, bytes_read)) {
		show = TRUE;
		goto out;
	}

	if (find_tag (pem_cert_begin, (const char *) contents, bytes_read)) {
		show = TRUE;
		goto out;
	}

out:
	g_free (contents);
	return show;
}
Esempio n. 14
0
/* Creates a list of global tags. Ideally, this should be created once during
 installations so that all users can use the same file. Thsi is because a full
 scale global tag list can occupy several megabytes of disk space.
 @param pre_process The pre-processing command. This is executed via system(),
 so you can pass stuff like 'gcc -E -dD -P `gnome-config --cflags gnome`'.
 @param includes Include files to process. Wildcards such as '/usr/include/a*.h'
 are allowed.
 @param tags_file The file where the tags will be stored.
 @param lang The language to use for the tags file.
 @return TRUE on success, FALSE on failure.
*/
gboolean tm_workspace_create_global_tags(const char *pre_process, const char **includes,
	int includes_count, const char *tags_file, int lang)
{
#ifdef HAVE_GLOB_H
	glob_t globbuf;
	size_t idx_glob;
#endif
	int idx_inc;
	char *command;
	guint i;
	FILE *fp;
	TMSourceFile *source_file;
	GPtrArray *tags_array;
	GHashTable *includes_files_hash;
	GList *includes_files = NULL;
	gchar *temp_file = create_temp_file("tmp_XXXXXX.cpp");
	gchar *temp_file2 = create_temp_file("tmp_XXXXXX.cpp");

	if (NULL == temp_file || NULL == temp_file2 ||
		NULL == (fp = g_fopen(temp_file, "w")))
	{
		g_free(temp_file);
		g_free(temp_file2);
		return FALSE;
	}

	includes_files_hash = g_hash_table_new_full (tm_file_inode_hash,
												 g_direct_equal,
												 NULL, g_free);

#ifdef HAVE_GLOB_H
	globbuf.gl_offs = 0;

	if (includes[0][0] == '"')	/* leading \" char for glob matching */
	for(idx_inc = 0; idx_inc < includes_count; idx_inc++)
	{
		size_t dirty_len = strlen(includes[idx_inc]);
		char *clean_path = g_malloc(dirty_len - 1);

		strncpy(clean_path, includes[idx_inc] + 1, dirty_len - 1);
		clean_path[dirty_len - 2] = 0;

#ifdef TM_DEBUG
		g_message ("[o][%s]\n", clean_path);
#endif
		glob(clean_path, 0, NULL, &globbuf);

#ifdef TM_DEBUG
		g_message ("matches: %d\n", globbuf.gl_pathc);
#endif

		for(idx_glob = 0; idx_glob < globbuf.gl_pathc; idx_glob++)
		{
#ifdef TM_DEBUG
			g_message (">>> %s\n", globbuf.gl_pathv[idx_glob]);
#endif
			if (!g_hash_table_lookup(includes_files_hash,
									globbuf.gl_pathv[idx_glob]))
			{
				char* file_name_copy = strdup(globbuf.gl_pathv[idx_glob]);
				g_hash_table_insert(includes_files_hash, file_name_copy,
									file_name_copy);
#ifdef TM_DEBUG
				g_message ("Added ...\n");
#endif
			}
		}
		globfree(&globbuf);
		g_free(clean_path);
  	}
  	else
#endif
	/* no glob support or globbing not wanted */
	for(idx_inc = 0; idx_inc < includes_count; idx_inc++)
	{
		if (!g_hash_table_lookup(includes_files_hash,
									includes[idx_inc]))
		{
			char* file_name_copy = strdup(includes[idx_inc]);
			g_hash_table_insert(includes_files_hash, file_name_copy,
								file_name_copy);
		}
  	}

	/* Checks for duplicate file entries which would case trouble */
	g_hash_table_foreach(includes_files_hash, tm_move_entries_to_g_list,
						 &includes_files);

	includes_files = g_list_reverse (includes_files);

#ifdef TM_DEBUG
	g_message ("writing out files to %s\n", temp_file);
#endif
	if (pre_process != NULL)
		write_includes_file(fp, includes_files);
	else
		append_to_temp_file(fp, includes_files);

	g_list_free (includes_files);
	g_hash_table_destroy(includes_files_hash);
	includes_files_hash = NULL;
	includes_files = NULL;
	fclose(fp);

	if (pre_process != NULL)
	{
		gint ret;
		gchar *tmp_errfile = create_temp_file("tmp_XXXXXX");
		gchar *errors = NULL;
		command = g_strdup_printf("%s %s >%s 2>%s",
								pre_process, temp_file, temp_file2, tmp_errfile);
#ifdef TM_DEBUG
		g_message("Executing: %s", command);
#endif
		ret = system(command);
		g_free(command);
		g_unlink(temp_file);
		g_free(temp_file);
		g_file_get_contents(tmp_errfile, &errors, NULL, NULL);
		if (errors && *errors)
			g_printerr("%s", errors);
		g_free(errors);
		g_unlink(tmp_errfile);
		g_free(tmp_errfile);
		if (ret == -1)
		{
			g_unlink(temp_file2);
			return FALSE;
		}
	}
	else
	{
		/* no pre-processing needed, so temp_file2 = temp_file */
		g_unlink(temp_file2);
		g_free(temp_file2);
		temp_file2 = temp_file;
		temp_file = NULL;
	}
	source_file = tm_source_file_new(temp_file2, tm_source_file_get_lang_name(lang));
	update_source_file(source_file, NULL, 0, FALSE, FALSE);
	if (NULL == source_file)
	{
		g_unlink(temp_file2);
		return FALSE;
	}
	g_unlink(temp_file2);
	g_free(temp_file2);
	if (0 == source_file->tags_array->len)
	{
		tm_source_file_free(source_file);
		return FALSE;
	}
	tags_array = tm_tags_extract(source_file->tags_array, tm_tag_max_t);
	if ((NULL == tags_array) || (0 == tags_array->len))
	{
		if (tags_array)
			g_ptr_array_free(tags_array, TRUE);
		tm_source_file_free(source_file);
		return FALSE;
	}
	if (FALSE == tm_tags_sort(tags_array, global_tags_sort_attrs, TRUE, FALSE))
	{
		tm_source_file_free(source_file);
		return FALSE;
	}
	if (NULL == (fp = g_fopen(tags_file, "w")))
	{
		tm_source_file_free(source_file);
		return FALSE;
	}
	fprintf(fp, "# format=tagmanager\n");
	for (i = 0; i < tags_array->len; ++i)
	{
		tm_tag_write(TM_TAG(tags_array->pdata[i]), fp, tm_tag_attr_type_t
		  | tm_tag_attr_scope_t | tm_tag_attr_arglist_t | tm_tag_attr_vartype_t
		  | tm_tag_attr_pointer_t);
	}
	fclose(fp);
	tm_source_file_free(source_file);
	g_ptr_array_free(tags_array, TRUE);
	return TRUE;
}
Esempio n. 15
0
/**
 * ephy_web_application_get_application_list:
 *
 * Gets a list of the currently installed web applications.
 * Free the returned GList with
 * ephy_web_application_free_application_list.
 *
 * Returns: (transfer-full): a #GList of #EphyWebApplication objects
 **/
GList *
ephy_web_application_get_application_list ()
{
  GFileEnumerator *children = NULL;
  GFileInfo *info;
  GList *applications = NULL;
  GFile *dot_dir;

  dot_dir = g_file_new_for_path (ephy_dot_dir ());
  children = g_file_enumerate_children (dot_dir,
                                        "standard::name",
                                        0, NULL, NULL);
  g_object_unref (dot_dir);

  info = g_file_enumerator_next_file (children, NULL, NULL);
  while (info) {
    EphyWebApplication *app;
    const char *name;
    glong prefix_length = g_utf8_strlen (EPHY_WEB_APP_PREFIX, -1);

    name = g_file_info_get_name (info);
    if (g_str_has_prefix (name, EPHY_WEB_APP_PREFIX)) {
      char *profile_dir;
      guint64 created;
      GDate *date;
      char *desktop_file, *desktop_file_path;
      char *contents;
      GFileInfo *desktop_info;

      app = g_slice_new0 (EphyWebApplication);

      profile_dir = g_build_filename (ephy_dot_dir (), name, NULL);
      app->icon_url = g_build_filename (profile_dir, EPHY_WEB_APP_ICON_NAME, NULL);

      desktop_file = g_strconcat (name + prefix_length, ".desktop", NULL);
      desktop_file_path = g_build_filename (profile_dir, desktop_file, NULL);
      app->desktop_file = g_strdup (desktop_file);

      if (g_file_get_contents (desktop_file_path, &contents, NULL, NULL)) {
        char *exec;
        char **strings;
        GKeyFile *key;
        int i;
        GFile *file;

        key = g_key_file_new ();
        g_key_file_load_from_data (key, contents, -1, 0, NULL);
        app->name = g_key_file_get_string (key, "Desktop Entry", "Name", NULL);
        exec = g_key_file_get_string (key, "Desktop Entry", "Exec", NULL);
        strings = g_strsplit (exec, " ", -1);

        for (i = 0; strings[i]; i++);
        app->url = g_strdup (strings[i - 1]);

        g_strfreev (strings);
        g_free (exec);
        g_key_file_free (key);

        file = g_file_new_for_path (desktop_file_path);

        /* FIXME: this should use TIME_CREATED but it does not seem to be working. */
        desktop_info = g_file_query_info (file, G_FILE_ATTRIBUTE_TIME_MODIFIED, 0, NULL, NULL);
        created = g_file_info_get_attribute_uint64 (desktop_info, G_FILE_ATTRIBUTE_TIME_MODIFIED);

        date = g_date_new ();
        g_date_set_time_t (date, (time_t)created);
        g_date_strftime (app->install_date, 127, "%x", date);

        g_date_free (date);
        g_object_unref (file);
        g_object_unref (desktop_info);

        applications = g_list_append (applications, app);
      }

      g_free (contents);
      g_free (desktop_file);
      g_free (profile_dir);
      g_free (desktop_file_path);
    }

    g_object_unref (info);

    info = g_file_enumerator_next_file (children, NULL, NULL);
  }

  g_object_unref (children);

  return applications;
}
Esempio n. 16
0
guint rc_cue_read_data(const gchar *input, RCCueInputType type,
    RCCueData *data)
{
    const gchar *locale = NULL;
    gchar *path = NULL;
    gchar *ex_encoding = NULL;
    gchar *buf = NULL, *line = NULL;
    gchar *dir = NULL;
    gchar *tmp = NULL;
    gchar *cue_raw_data = NULL, *cue_tmp_data = NULL, *cue_new_data = NULL;
    gsize cue_raw_length = 0, cue_tmp_length = 0, cue_new_length = 0;
    gint track_index, track_sm, track_ss, track_sd;
    guint64 track_time;
    gchar **line_data_array = NULL;
    gboolean flag;
    guint i = 0;
    gchar chr;
    guint track_num = 0;
    GSList *track_list = NULL, *list_foreach = NULL;
    GRegex *music_filename_regex;
    GRegex *data_regex;
    GMatchInfo *match_info;
    RCCueTrack *cue_track_data = NULL, *cue_track_array = NULL;
    if(input==NULL) return 0;
    if(data==NULL) return 0;
    switch(type)
    {
        case RC_CUE_INPUT_URI:
            path = g_filename_from_uri(input, NULL, NULL);
            if(path==NULL) return 0;
        case RC_CUE_INPUT_PATH:
            if(path==NULL) path = g_strdup(input);
            if(path==NULL) return 0;
            flag = g_file_get_contents(path, &cue_raw_data,
                &cue_raw_length, NULL);
            dir = g_path_get_dirname(path);
            g_free(path);
            if(!flag)
            {
                g_free(dir);
                return 0;
            }
        case RC_CUE_INPUT_EMBEDED:
            break;
        default:
            return 0;
    }
    if(rc_set_get_boolean("Metadata", "AutoEncodingDetect", NULL))
    {
        locale = rc_player_get_locale();
        if(strncmp(locale, "zh_CN", 5)==0)
            ex_encoding = g_strdup("GB18030");
        else if(strncmp(locale, "zh_TW", 5)==0)
            ex_encoding = g_strdup("BIG5");
        else if(strncmp(locale, "ja_JP", 5)==0)
            ex_encoding = g_strdup("ShiftJIS");
        else
            ex_encoding = rc_set_get_string("Metadata",
                "TagExEncoding", NULL);
    } 
    else
        ex_encoding = rc_set_get_string("Metadata", "TagExEncoding", NULL);
    if(ex_encoding==NULL) ex_encoding = g_strdup("GBK");
    if(cue_raw_data==NULL)
    {
        if(!g_utf8_validate(input, -1, NULL))
            cue_tmp_data = g_convert(input, -1, "UTF-8", ex_encoding,
                NULL, NULL, NULL);
        else
            cue_tmp_data = g_strdup(input);
    }
    else
    {
        if(!g_utf8_validate(cue_raw_data, -1, NULL))
            cue_tmp_data = g_convert(cue_raw_data, -1, "UTF-8",
                ex_encoding, NULL, NULL, NULL);
        else
            cue_tmp_data = g_strdup(cue_raw_data);
        g_free(cue_raw_data);
    }
    if(ex_encoding!=NULL) g_free(ex_encoding);
    if(cue_tmp_data==NULL)
    {
        if(dir!=NULL) g_free(dir);
        return 0;
    }
    cue_tmp_length = strlen(cue_tmp_data);
    cue_new_data = g_new0(gchar, cue_tmp_length);
    for(i=0;i<cue_tmp_length;i++)
    {
        chr = cue_tmp_data[i];
        if(chr!='\r')
        {
            cue_new_data[cue_new_length] = chr;
            cue_new_length++;
        }
        else if(i+1<cue_tmp_length && cue_new_data[i+1]!='\n')
        {
            cue_new_data[cue_new_length] = '\n';
            cue_new_length++;
        }
    }
    g_free(cue_tmp_data);
    bzero(data, sizeof(RCCueData));
    data->type = type;
    if(type!=RC_CUE_INPUT_EMBEDED)
    {
        music_filename_regex = g_regex_new("(FILE \").*[\"]",
            G_REGEX_CASELESS, 0, NULL);
        g_regex_match(music_filename_regex, cue_new_data, 0, &match_info);
        if(g_match_info_matches(match_info))
        {
            buf = g_match_info_fetch(match_info, 0);
            if(dir!=NULL)
            {
                path = g_strndup(buf+6, strlen(buf)-7);
                tmp = g_build_filename(dir, path, NULL);
                data->file = g_filename_to_uri(tmp, NULL, NULL);
                g_free(tmp);
                g_free(path);
            }
            else
                data->file = g_strndup(buf+6, strlen(buf)-7);
            g_free(buf);
        }
        g_match_info_free(match_info);
        g_regex_unref(music_filename_regex);
        if(dir!=NULL) g_free(dir);
        if(data->file==NULL)
        {
            g_free(cue_new_data);
            return 0;
        }
    }
    else
        data->file = NULL;
    data_regex = g_regex_new("\".*[^\"]", G_REGEX_CASELESS, 0, NULL);
    line_data_array = g_strsplit(cue_new_data, "\n", 0);
    for(i=0;line_data_array[i]!=NULL;i++)
    {
        line = line_data_array[i];
        if(g_regex_match_simple("(TRACK )[0-9]+( AUDIO)", line,
            G_REGEX_CASELESS, 0))
        {
            track_num++;
            cue_track_data = g_new0(RCCueTrack, 1);
            sscanf(line, "%*s%d", &(cue_track_data->index));
            track_list = g_slist_append(track_list, cue_track_data);
        }
        else if(cue_track_data!=NULL && g_regex_match_simple("(INDEX )[0-9]+ "
            "[0-9]+:[0-9]{2}:[0-9]{2}", line, G_REGEX_CASELESS, 0))
        {
            sscanf(line, "%*s%d %d:%d:%d", &track_index, &track_sm,
                &track_ss, &track_sd);
            track_time = (track_sm * 60 + track_ss) * 1000 + 10 * track_sd;
            track_time *= GST_MSECOND;
            if(track_index==0)
                cue_track_data->time0 = track_time;
            else if(track_index==1)
                cue_track_data->time1 = track_time;
        }
        else if(g_regex_match_simple("(TITLE \").*[\"]", line,
            G_REGEX_CASELESS, 0))
        {
            g_regex_match(data_regex, line, 0, &match_info);
            if(g_match_info_matches(match_info))
            {
                buf = g_match_info_fetch(match_info, 0);
                if(buf!=NULL && strlen(buf)>1)
                {
                    if(cue_track_data!=NULL)
                    {
                        if(cue_track_data->title!=NULL)
                            g_free(cue_track_data->title);
                        cue_track_data->title = g_strdup(buf+1);
                    }
                    else
                    {
                        if(data->title!=NULL) g_free(data->title);
                        data->title = g_strdup(buf+1);
                    }
                }
                if(buf!=NULL) g_free(buf);
            }
            g_match_info_free(match_info);
        }
        else if(g_regex_match_simple("(PERFORMER \").*[\"]", line,
            G_REGEX_CASELESS, 0))
        {
            g_regex_match(data_regex, line, 0, &match_info);
            if(g_match_info_matches(match_info))
            {
                buf = g_match_info_fetch(match_info, 0);
                if(buf!=NULL && strlen(buf)>1)
                {
                    if(cue_track_data!=NULL)
                    {
                        if(cue_track_data->performer!=NULL)
                            g_free(cue_track_data->performer);
                        cue_track_data->performer = g_strdup(buf+1);
                    }
                    else
                    {
                        if(data->performer!=NULL) g_free(data->performer);
                        data->performer = g_strdup(buf+1);
                    }
                }
                if(buf!=NULL) g_free(buf);
            }
            g_match_info_free(match_info);
        }
    }
    g_strfreev(line_data_array);
    g_free(cue_new_data);
    g_regex_unref(data_regex);
    i = 0;
    cue_track_array = g_new0(RCCueTrack, track_num);
    for(list_foreach=track_list;list_foreach!=NULL;
        list_foreach=g_slist_next(list_foreach))
    {
        memcpy(cue_track_array+i, list_foreach->data, sizeof(RCCueTrack));
        g_free(list_foreach->data);
        i++;
    }
    g_slist_free(track_list);
    data->track = cue_track_array;
    data->length = track_num;
    return track_num;
}
Esempio n. 17
0
/* This function is taken from libhif
 * Original author: Richard Hughes <richard at hughsie dot com>
 */
static GKeyFile *
lr_load_multiline_key_file(const char *filename,
                           GError **err)
{
    GKeyFile *file = NULL;
    gboolean ret;
    gsize len;
    guint i;
    _cleanup_error_free_ GError *tmp_err = NULL;
    _cleanup_free_ gchar *data = NULL;
    _cleanup_string_free_ GString *string = NULL;
    _cleanup_strv_free_ gchar **lines = NULL;

    // load file
    if (!g_file_get_contents (filename, &data, &len, &tmp_err)) {
        g_set_error(err, LR_REPOCONF_ERROR, LRE_FILE,
                    "Cannot load content of %s: %s",
                    filename, tmp_err->message);
        return NULL;
    }

    // split into lines
    string = g_string_new ("");
    lines = g_strsplit (data, "\n", -1);
    for (i = 0; lines[i] != NULL; i++) {

        // convert tabs to spaces
        g_strdelimit (lines[i], "\t", ' ');

        // if a line starts with whitespace, then append it on
        // the previous line
        if (lines[i][0] == ' ' && string->len > 0) {

            // remove old newline from previous line
            g_string_set_size (string, string->len - 1);

            // whitespace strip this new line
            g_strchug (lines[i]);

            // only add a ';' if we have anything after the '='
            if (string->str[string->len - 1] == '=') {
                g_string_append_printf (string, "%s\n", lines[i]);
            } else {
                g_string_append_printf (string, ";%s\n", lines[i]);
            }
        } else {
            g_string_append_printf (string, "%s\n", lines[i]);
        }
    }

    // remove final newline
    if (string->len > 0)
        g_string_set_size (string, string->len - 1);

    // load modified lines
    file = g_key_file_new ();
    ret = g_key_file_load_from_data (file,
                                     string->str,
                                     -1,
                                     G_KEY_FILE_KEEP_COMMENTS,
                                     &tmp_err);
    if (!ret) {
        g_key_file_free (file);
        g_set_error(err, LR_REPOCONF_ERROR, LRE_KEYFILE,
                    "Cannot parse key file %s: %s", filename, tmp_err->message);
        return NULL;
    }
    return file;
}
//Fonction de lecture du tuyau.
void cd_xmms_read_pipe (CairoDockModuleInstance *myApplet)
{
	//\________________________ On determine le pipe.
	gchar *cPipeCommand = NULL;
	switch (myConfig.iPlayer) {  // On emule un pipe pour les lecteurs qui n'en ont pas.
		case MY_XMMS :
		break ;
		case MY_AUDACIOUS :  //Il faut émuler le pipe d'audacious par AUDTOOL
			cPipeCommand = g_strdup_printf ("bash %s/infoaudacious.sh", MY_APPLET_SHARE_DATA_DIR);
		break ;
		case MY_BANSHEE :  //Le pipe est trop lent et cause des freezes... // Il faut émuler le pipe de banshee par le script
			cPipeCommand = g_strdup_printf ("bash %s/infobanshee.sh", MY_APPLET_SHARE_DATA_DIR);
		break ;
		case MY_EXAILE :  //Le pipe est trop lent, récupération des infos une fois sur deux avec un pique du cpu lors de l'éxécution du script // Il faut émuler le pipe d'audacious par Exaile -q
			cPipeCommand = g_strdup_printf ("bash %s/infoexaile.sh", MY_APPLET_SHARE_DATA_DIR);
		break ;
		default :
		break ;
	}
	
	//\________________________ On lit le pipe.
	gchar *cResult = NULL;
	if (cPipeCommand != NULL)  // c'est un lecteur avec un pipe emule.
	{
		cResult = cairo_dock_launch_command_sync (cPipeCommand);
		g_free (cPipeCommand);
	}
	else if (myConfig.iPlayer == MY_XMMS)  // c'est XMMS, il a deja son propre pipe.
	{
		gchar *cPipe = g_strdup_printf ("/tmp/xmms-info_%s.0",g_getenv ("USER"));
		gsize length=0;
		GError *erreur = NULL;
		g_file_get_contents (cPipe, &cResult, &length, &erreur);
		
		if (erreur != NULL) {
			cd_warning("xmms : %s", erreur->message);
			g_error_free(erreur);
		}
		
		g_free (cPipe);
	}
	
	if (cResult == NULL)  // erreur lors de la leture du pipe, on sort.
	{
		myData.playingStatus = PLAYER_NONE;
		cd_xmms_player_none (myApplet);
		return;
	}
	
	//\________________________ On recupere les donnees.
	gchar **cInfopipesList = g_strsplit(cResult, "\n", -1);
	g_free(cResult);
	
	gchar *cQuickInfo = NULL;
	gchar *cOneInfopipe;
	myData.iTrackNumber = -1;
	myData.iCurrentTime = -1;
	myData.iSongLength = -1;
	int *pLineNumber = s_pLineNumber[myConfig.iPlayer];
	int i;
	for (i = 0; cInfopipesList[i] != NULL; i ++) {
		cOneInfopipe = cInfopipesList[i];
		if (i == pLineNumber[INFO_STATUS]) {
			gchar *str = strchr (cOneInfopipe, ' ');
			if (str != NULL) {
				str ++;
				while (*str == ' ')
					str ++;
				if ((strcmp (str, "Playing") == 0) || (strcmp (str, "playing") == 0))
					myData.playingStatus = PLAYER_PLAYING;
				else if ((strcmp (str, "Paused") == 0) || (strcmp (str, "paused") == 0))
					myData.playingStatus = PLAYER_PAUSED;
				else if ((strcmp (str, "Stopped") == 0) || (strcmp (str, "stopped") == 0))
					myData.playingStatus = PLAYER_STOPPED;
				else
					myData.playingStatus = PLAYER_BROKEN;
			}
			else
				myData.playingStatus = PLAYER_BROKEN;
		}
		else if (i == pLineNumber[INFO_TRACK_IN_PLAYLIST]) {
			if (myConfig.quickInfoType == MY_APPLET_TRACK) {
				gchar *str = strchr (cOneInfopipe, ':');
				if (str != NULL) {
					str ++;
					while (*str == ' ')
						str ++;
					myData.iTrackNumber = atoi (str);
				}
			}
		}
		else if (i == pLineNumber[INFO_TIME_ELAPSED_IN_SEC]) {
			if (myConfig.quickInfoType == MY_APPLET_TIME_ELAPSED || myConfig.quickInfoType == MY_APPLET_TIME_LEFT) {
				gchar *str = strchr (cOneInfopipe, ' ');
				if (str != NULL) {
					str ++;
					while (*str == ' ')
						str ++;
					if (*str != 'N')
						myData.iCurrentTime = atoi(str) * 1e-3;
				}
			}
		}
		else if (i == pLineNumber[INFO_TIME_ELAPSED]) {
			if ((myConfig.quickInfoType == MY_APPLET_TIME_ELAPSED || myConfig.quickInfoType == MY_APPLET_TIME_LEFT) && myData.iCurrentTime == -1) {
				gchar *str = strchr (cOneInfopipe, ' ');
				if (str != NULL) {
					str ++;
					while (*str == ' ')
						str ++;
					gchar *str2 = strchr (str, ':');
					if (str2 == NULL) { // pas de minutes.
						myData.iCurrentTime = atoi(str);
					}
					else {
						*str2 = '\0';
						myData.iCurrentTime = atoi(str2+1) + 60*atoi (str);  // prions pour qu'ils n'ecrivent jamais les heures ... xD
					}
				}
			}
		}
		else if (i == pLineNumber[INFO_TOTAL_TIME_IN_SEC]) {
			if (myConfig.quickInfoType == MY_APPLET_TIME_LEFT) {
				gchar *str = strchr (cOneInfopipe, ' ');
				if (str != NULL) {
					str ++;
					while (*str == ' ')
						str ++;
					if (*str != 'N')
						myData.iSongLength = atoi(str) * 1e-3;
				}
			}
		}
		else if (i == pLineNumber[INFO_TOTAL_TIME]) {
			if (myConfig.quickInfoType == MY_APPLET_TIME_LEFT && myData.iSongLength == -1) {
				gchar *str = strchr (cOneInfopipe, ' ');
				if (str != NULL) {
					str ++;
					while (*str == ' ')
						str ++;
					gchar *str2 = strchr (str, ':');
					if (str2 == NULL) { // pas de minutes.
						myData.iSongLength = atoi(str);
					}
					else {
						*str2 = '\0';
						myData.iSongLength = atoi(str2+1) + 60*atoi (str);  // prions pour qu'ils n'ecrivent jamais les heures ...
					}
				}
			}
		}
		else if (i == pLineNumber[INFO_NOW_TITLE]) {
			gchar *str = strchr (cOneInfopipe, ':');
			if (str != NULL) {
				str ++;
				while (*str == ' ')
					str ++;
				if ((strcmp(str," (null)") != 0) && (myData.playingTitle == NULL || strcmp(str, myData.playingTitle) != 0)) {
					g_free (myData.playingTitle);
					myData.playingTitle = g_strdup (str);
					cd_message("On a changé de son! (%s)", myData.playingTitle);
					cd_xmms_change_desklet_data(myApplet);
				}
			}
		}
	}  // fin de parcours des lignes.
	g_strfreev (cInfopipesList);
	
	if (myConfig.iPlayer != MY_XMMS) {
		g_remove (s_cTmpFile);
	}
	g_free (s_cTmpFile);
	s_cTmpFile = NULL;
}
Esempio n. 19
0
void OtNtParallels::read(const gchar * filename)
{
  // Get contents of the data file. Bail out if not there.
  ustring xmlfilename = gw_build_filename(Directories->get_package_data(), filename);
  if (!g_file_test(xmlfilename.c_str(), G_FILE_TEST_IS_REGULAR))
    return;
  gchar *contents;
  g_file_get_contents(xmlfilename.c_str(), &contents, NULL, NULL);

  /*
     Read the xml data. Example:
     <section title="The Descendants of Noah's Sons">
     <set>
     <reference book="Genesis" chapter="10" verse="2-4"/>
     <reference book="1 Chronicles" chapter="1" verse="5-7"/>
     </set>
     <set>
     <reference book="Genesis" chapter="10" verse="6-8"/>
     <reference book="1 Chronicles" chapter="1" verse="8-10"/>
     </set>
     <set>
     <reference book="Genesis" chapter="10" verse="13-18"/>
     <reference book="1 Chronicles" chapter="1" verse="11-16"/>
     </set>
     </section>
   */
  xmlParserInputBufferPtr inputbuffer;
  inputbuffer = xmlParserInputBufferCreateMem(contents, strlen(contents), XML_CHAR_ENCODING_NONE);
  xmlTextReaderPtr reader = xmlNewTextReader(inputbuffer, NULL);
  if (reader) {
    char *opening_element = NULL;
    OtNtParallelSection parallelsection(0);
    OtNtParallelSet parallelset(0);
    while ((xmlTextReaderRead(reader) == 1)) {
      switch (xmlTextReaderNodeType(reader)) {
      case XML_READER_TYPE_ELEMENT:
        {
          opening_element = (char *)xmlTextReaderName(reader);
          if (!strcmp(opening_element, "section")) {
            parallelsection.sets.clear();
            parallelsection.title.clear();
            char *attribute;
            attribute = (char *)xmlTextReaderGetAttribute(reader, BAD_CAST "title");
            if (attribute) {
              parallelsection.title = attribute;
              free(attribute);
            }
          }
          if (!strcmp(opening_element, "set")) {
            parallelset.references.clear();
          }
          if (!strcmp(opening_element, "reference")) {
            Reference ref(0);
            char *attribute;
            attribute = (char *)xmlTextReaderGetAttribute(reader, BAD_CAST "book");
            if (attribute) {
              ref.book = books_english_to_id(attribute);
              free(attribute);
            }
            attribute = (char *)xmlTextReaderGetAttribute(reader, BAD_CAST "chapter");
            if (attribute) {
              ref.chapter = convert_to_int(attribute);
              free(attribute);
            }
            attribute = (char *)xmlTextReaderGetAttribute(reader, BAD_CAST "verse");
            if (attribute) {
              ref.verse = attribute;
              free(attribute);
            }
            parallelset.references.push_back(ref);
          }
          break;
        }
      case XML_READER_TYPE_TEXT:
        {
          char *text = (char *)xmlTextReaderValue(reader);
          if (text) {
            free(text);
          }
          break;
        }
      case XML_READER_TYPE_END_ELEMENT:
        {
          char *closing_element = (char *)xmlTextReaderName(reader);
          if (!strcmp(closing_element, "set")) {
            parallelsection.sets.push_back(parallelset);
          }
          if (!strcmp(closing_element, "section")) {
            sections.push_back(parallelsection);
          }
          break;
        }
      }
    }
  }
  // Free memory.
  if (reader)
    xmlFreeTextReader(reader);
  if (inputbuffer)
    xmlFreeParserInputBuffer(inputbuffer);
  if (contents)
    g_free(contents);
}
Esempio n. 20
0
static BOOL
load_skindata_from_file (const char* skinfile, SKINDATA* skind)
{
    gchar *cwd;
    gchar *skinpath;
    void *txt = 0;
    int txt_len;

    if (!skind) {
	return FALSE;
    }

    /* This is only for debugging */
    cwd = g_get_current_dir ();
    debug_printf ("CWD = %s\n", cwd);
    g_free (cwd);

    skinpath = g_build_filename (SKIN_PATH, skinfile, 0);
    debug_printf ("loading skindata from file: %s\n", skinpath);

    skind->bmdc.bm = (HBITMAP) LoadImage(0, skinpath, IMAGE_BITMAP, 
				   BIG_IMAGE_WIDTH, BIG_IMAGE_HEIGHT, 
				   LR_CREATEDIBSECTION | LR_LOADFROMFILE);

    /* LoadImage succeeded.  Try to load the associated txt file. */
    if (skind->bmdc.bm) {
	if (g_str_has_suffix (skinpath, ".bmp")) {
	    gchar* contents = 0;
	    gsize length;
	    gboolean rc;

	    strcpy (&skinpath[strlen(skinpath)-4], ".txt");
	    //debug_box ("Trying to load txt %s", skinpath);
	    rc = g_file_get_contents (skinpath, &contents, &length, NULL);
	    if (rc) {
		parse_skin_txt (skind, contents, length);
		g_free (contents);
	    }
	}
	g_free (skinpath);
    }
    
    /* LoadImage failed.  Try to load zipfile. */
    else {
	debug_printf ("Error.  LoadImage returned NULL\n");
	render2_load_skin (&skind->bmdc.bm, &txt, &txt_len, skinpath);
	g_free (skinpath);
	if (skind->bmdc.bm == NULL) {
	    return FALSE;
	}
	if (txt) {
	    parse_skin_txt (skind, txt, txt_len);
	    free (txt);
	}
    }

    skind->bmdc.hdc = CreateCompatibleDC(NULL);
    SelectObject(skind->bmdc.hdc, skind->bmdc.bm);

    skind->textcolor = GetPixel (skind->bmdc.hdc, m_pt_color.x, m_pt_color.y);
    skind->hbrush = CreateSolidBrush (skind->textcolor);
    return skind->hbrush ? TRUE : FALSE;
}
Esempio n. 21
0
void WindowMerge::merge_edited_into_master(bool approve)
// This merges the edited data into the master data, and does error checking.
{
  // Bail out if there's nothing to merge.
  if (main_project_data == edited_project_data) {
    gtkw_dialog_info(NULL, _("Both the chapters already are the same"));
    return;
  }

  // Get the available snapshots of the master and edited projects.
  vector <unsigned int> masterseconds = snapshots_get_seconds (current_master_project, book, chapter);
  vector <unsigned int> editedseconds = snapshots_get_seconds (current_edited_project, book, chapter);

  // We need to look for the common ancestor.
  // It needs a fast routine that goes through the history as little as possible.

  // Make a combined set of the times and flags.
  vector <bool> combinedflags;
  vector <unsigned int> combinedseconds;
  for (unsigned int i = 0; i < masterseconds.size(); i++) {
    combinedflags.push_back (true);
    combinedseconds.push_back (masterseconds[i]);    
  }
  for (unsigned int i = 0; i < editedseconds.size(); i++) {
    combinedflags.push_back (false);
    combinedseconds.push_back (editedseconds[i]);    
  }
  // Sort the combined set on the time, most recent ones first.
  quick_sort (combinedseconds, combinedflags, 0, combinedseconds.size());
  {
    vector <bool> flags = combinedflags;
    vector <unsigned int> seconds = combinedseconds;
    combinedflags.clear();
    combinedseconds.clear();
    for (int i = flags.size() - 1; i >= 0; i--) {
      combinedflags.push_back (flags[i]);
      combinedseconds.push_back (seconds[i]);
    }
  }

  // Go through the history of both projects, extract the state in history,
  // and compare them in order to find the common ancestor.
  vector <ustring> mastertexts;
  vector <ustring> editedtexts;
  ustring common_ancestor;
  for (unsigned int i = 0; i < combinedseconds.size(); i++) {
    unsigned int second = combinedseconds[i];
    bool master = combinedflags[i];
    if (master) {
      mastertexts.push_back(snapshots_get_chapter(current_master_project, book, chapter, second));
    } else {
      editedtexts.push_back(snapshots_get_chapter(current_edited_project, book, chapter, second));
    }
    for (unsigned int m = 0; m < mastertexts.size(); m++) {
      for (unsigned int e = 0; e < editedtexts.size(); e++) {
        if (common_ancestor.empty()) {
          if (mastertexts[m] == editedtexts[e]) {
            common_ancestor = mastertexts[m];
          }
        }
      }
    }
    if (!common_ancestor.empty()) {
      break;
    }
  }  

  // If no common ancestor was found, give message and bail out.
  if (common_ancestor.empty()) {
    gtkw_dialog_error(NULL, _("Can't merge because a common ancestor was not found"));
    return;
  }
  // Do the merge in a temporal directory.
  workingdirectory = gw_build_filename(Directories->get_temp(), "merge");
  unix_rmdir(workingdirectory);
  gw_mkdir_with_parents(workingdirectory);

  /*
     Merge works with file1, file2 and file3.

     merge [ options ] file1 file2 file3

     merge incorporates all changes that lead from file2 to file3 into file1.
     The result ordinarily goes into file1.
     merge is useful for combining separate changes to an original. 
     Suppose file2 is the original, and both file1 and file3 are modifications of file2. 
     Then merge combines both changes.
   */
  ustring file1 = gw_build_filename(workingdirectory, "file1");
  ustring file2 = gw_build_filename(workingdirectory, "file2");
  ustring file3 = gw_build_filename(workingdirectory, "file3");

  /*
     merge has problems when two consecutive lines are changed, 
     one line in one file and the other line in the other file. 
     Therefore data is going to be cut on the spaces, 
     so that there is one word per line. 
     Each new line is indicated too so as to facilitate joining the loose bits again.
     Another advantage of this is that the merge operation becomes finer grained.
   */

  // Write the data for the common ancestor.
  g_file_set_contents(file2.c_str(), merge_split_data(common_ancestor).c_str(), -1, NULL);

  // Write the data for the main project.
  g_file_set_contents(file1.c_str(), merge_split_data(main_project_data).c_str(), -1, NULL);

  // Write the data for the edited project.
  g_file_set_contents(file3.c_str(), merge_split_data(edited_project_data).c_str(), -1, NULL);

  // Do the three-way merge.
  {
    GwSpawn spawn("merge");
    spawn.workingdirectory(workingdirectory);
    spawn.arg(file1);
    spawn.arg(file2);
    spawn.arg(file3);
    spawn.run();
  }

  // Read the result of the merge.
  ustring merge_result;
  {
    gchar *contents;
    g_file_get_contents(file1.c_str(), &contents, NULL, NULL);
    if (contents) {
      merge_result = contents;
      g_free(contents);
    }
  }

  // Make conflicts human readable.
  merge_result = merge_conflicts_2_human_readable_text(merge_result);

  // Join the bits again.
  merge_result = merge_join_data(merge_result);

  // If there are conflicts, resolve them.
  if (merge_result.find(merge_conflict_markup(1)) != string::npos) {
    MergeDialog dialog(merge_result);
    if (dialog.run() == GTK_RESPONSE_OK) {
      merge_result = dialog.reconciled_text;
    }
  }
  // If there are still conflicts, give a message and bail out.
  if (merge_result.find(merge_conflict_markup(1)) != string::npos) {
    gtkw_dialog_error(NULL, _("The chapters were not merged"));
    return;
  }

  if (approve) {

    // Setup the approval system.
    approval_setup(main_project_data, merge_result);

  } else {

    // Store the merge result in both chapters.  
    ParseLine parseline(merge_result);
    CategorizeChapterVerse ccv(parseline.lines);
    project_store_chapter(current_master_project, book, ccv);
    project_store_chapter(current_edited_project, book, ccv);
    // A normal snapshot may be removed over time, so we need a persistent one to enable future merges.
    snapshots_shoot_chapter (current_master_project, book, chapter, 0, true);
    snapshots_shoot_chapter (current_edited_project, book, chapter, 0, true);

    // Message ok.
    gtkw_dialog_info(NULL, _("The chapters were successfully merged"));

  }
}
Esempio n. 22
0
static gboolean
grab_port (MMModem *modem,
           const char *subsys,
           const char *name,
           MMPortType suggested_type,
           gpointer user_data,
           GError **error)
{
    MMGenericGsm *gsm = MM_GENERIC_GSM (modem);
    MMPortType ptype = MM_PORT_TYPE_IGNORED;
    const char *sys[] = { "tty", "net", NULL };
    GUdevClient *client;
    GUdevDevice *device = NULL;
    MMPort *port = NULL;
    const char *sysfs_path;

    client = g_udev_client_new (sys);
    if (!client) {
        g_set_error (error, 0, 0, "Could not get udev client.");
        return FALSE;
    }

    device = g_udev_client_query_by_subsystem_and_name (client, subsys, name);
    if (!device) {
        g_set_error (error, 0, 0, "Could not get udev device.");
        goto out;
    }

    sysfs_path = g_udev_device_get_sysfs_path (device);
    if (!sysfs_path) {
        g_set_error (error, 0, 0, "Could not get udev device sysfs path.");
        goto out;
    }

    if (!strcmp (subsys, "tty")) {
        char *hsotype_path;
        char *contents = NULL;

        hsotype_path = g_build_filename (sysfs_path, "hsotype", NULL);
        if (g_file_get_contents (hsotype_path, &contents, NULL, NULL)) {
            if (g_str_has_prefix (contents, "Control"))
                ptype = MM_PORT_TYPE_PRIMARY;
            else if (g_str_has_prefix (contents, "Application") || g_str_has_prefix (contents, "Application2"))
                ptype = MM_PORT_TYPE_SECONDARY;
            g_free (contents);
        }
        g_free (hsotype_path);
    }

    port = mm_generic_gsm_grab_port (gsm, subsys, name, ptype, error);
    if (!port)
        goto out;

    if (MM_IS_AT_SERIAL_PORT (port)) {
        g_object_set (G_OBJECT (port), MM_SERIAL_PORT_SEND_DELAY, (guint64) 10000, NULL);
        if (ptype == MM_PORT_TYPE_PRIMARY) {
            GRegex *regex;

            regex = g_regex_new ("_OWANCALL: (\\d),\\s*(\\d)\\r\\n", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
            mm_at_serial_port_add_unsolicited_msg_handler (MM_AT_SERIAL_PORT (port), regex, connection_enabled, modem, NULL);
            g_regex_unref (regex);

            regex = g_regex_new ("\\r\\n\\+PACSP0\\r\\n", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
            mm_at_serial_port_add_unsolicited_msg_handler (MM_AT_SERIAL_PORT (port), regex, NULL, NULL, NULL);
            g_regex_unref (regex);
        }
        option_register_unsolicted_handlers (gsm, MM_AT_SERIAL_PORT (port));
    }

out:
    if (device)
        g_object_unref (device);
    g_object_unref (client);
    return !!port;
}
Esempio n. 23
0
static JSBool
import_file(JSContext  *context,
            JSObject   *obj,
            const char *name,
            const char *full_path)
{
    char *script;
    gsize script_len;
    JSObject *module_obj;
    GError *error;
    jsval script_retval;
    JSBool retval = JS_FALSE;

    gjs_debug(GJS_DEBUG_IMPORTER,
              "Importing '%s'", full_path);

    module_obj = JS_ConstructObject(context, NULL, NULL, NULL);
    if (module_obj == NULL) {
        return JS_FALSE;
    }

    if (!define_import(context, obj, module_obj, name))
        return JS_FALSE;

    if (!define_meta_properties(context, module_obj, name, obj))
        goto out;

    script = NULL;
    script_len = 0;

    error = NULL;
    if (!g_file_get_contents(full_path, &script, &script_len, &error)) {
        gjs_throw(context, "Could not open %s: %s", full_path, error->message);
        g_error_free(error);
        goto out;
    }

    g_assert(script != NULL);

    if (!JS_EvaluateScript(context,
                           module_obj,
                           script,
                           script_len,
                           full_path,
                           1, /* line number */
                           &script_retval)) {
        g_free(script);

        /* If JSOPTION_DONT_REPORT_UNCAUGHT is set then the exception
         * would be left set after the evaluate and not go to the error
         * reporter function.
         */
        if (JS_IsExceptionPending(context)) {
            gjs_debug(GJS_DEBUG_IMPORTER,
                      "Module '%s' left an exception set",
                      name);
            gjs_log_and_keep_exception(context, NULL);
        } else {
            gjs_throw(context,
                      "JS_EvaluateScript() returned FALSE but did not set exception");
        }

        goto out;
    }

    g_free(script);

    if (!finish_import(context, name))
        goto out;

    if (!seal_import(context, obj, name))
        goto out;

    retval = JS_TRUE;

out:
    if (!retval)
        cancel_import(context, obj, name);

    return retval;
}
static GstFlowReturn
gst_multi_file_src_create (GstPushSrc * src, GstBuffer ** buffer)
{
  GstMultiFileSrc *multifilesrc;
  gsize size;
  gchar *data;
  gchar *filename;
  GstBuffer *buf;
  gboolean ret;
  GError *error = NULL;

  multifilesrc = GST_MULTI_FILE_SRC (src);

  if (multifilesrc->index < multifilesrc->start_index) {
    multifilesrc->index = multifilesrc->start_index;
  }
  filename = gst_multi_file_src_get_filename (multifilesrc);

  GST_DEBUG_OBJECT (multifilesrc, "reading from file \"%s\".", filename);

  ret = g_file_get_contents (filename, &data, &size, &error);
  if (!ret) {
    if (multifilesrc->successful_read) {
      /* If we've read at least one buffer successfully, not finding the
       * next file is EOS. */
      g_free (filename);
      if (error != NULL)
        g_error_free (error);

      if (multifilesrc->loop) {
        error = NULL;
        multifilesrc->index = multifilesrc->start_index;

        filename = gst_multi_file_src_get_filename (multifilesrc);
        ret = g_file_get_contents (filename, &data, &size, &error);
        if (!ret) {
          g_free (filename);
          if (error != NULL)
            g_error_free (error);

          return GST_FLOW_EOS;
        }
      } else {
        return GST_FLOW_EOS;
      }
    } else {
      goto handle_error;
    }
  }

  multifilesrc->successful_read = TRUE;
  multifilesrc->index++;
  if (multifilesrc->stop_index != -1 &&
      multifilesrc->index >= multifilesrc->stop_index) {
    multifilesrc->index = multifilesrc->start_index;
  }

  buf = gst_buffer_new ();
  gst_buffer_append_memory (buf,
      gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
  GST_BUFFER_OFFSET (buf) = multifilesrc->offset;
  GST_BUFFER_OFFSET_END (buf) = multifilesrc->offset + size;
  multifilesrc->offset += size;

  GST_DEBUG_OBJECT (multifilesrc, "read file \"%s\".", filename);

  g_free (filename);
  *buffer = buf;
  return GST_FLOW_OK;

handle_error:
  {
    if (error != NULL) {
      GST_ELEMENT_ERROR (multifilesrc, RESOURCE, READ,
          ("Error while reading from file \"%s\".", filename),
          ("%s", error->message));
      g_error_free (error);
    } else {
      GST_ELEMENT_ERROR (multifilesrc, RESOURCE, READ,
          ("Error while reading from file \"%s\".", filename),
          ("%s", g_strerror (errno)));
    }
    g_free (filename);
    return GST_FLOW_ERROR;
  }
}
Esempio n. 25
0
/**
 * main:
 **/
gint
main (gint argc, gchar *argv[])
{
	gboolean ret;
	gchar *data = NULL;
	gchar **split = NULL;
	gchar **sections = NULL;
	GString *output = NULL;
	GError *error = NULL;
	guint i;
	CdParseEntry entry;
	gchar *part;
	gint retval = 1;
	CdSensorKind kind;

	if (argc != 4) {
		g_print ("need to specify [huey|colormunki] input output\n");
		goto out;
	}
	kind = cd_sensor_kind_from_string (argv[1]);
	if (kind != CD_SENSOR_KIND_HUEY &&
	    kind != CD_SENSOR_KIND_DTP94 &&
	    kind != CD_SENSOR_KIND_COLOR_MUNKI_PHOTO) {
		g_print ("only huey and colormunki device kinds supported\n");
		goto out;
	}

	/* read file */
	ret = g_file_get_contents (argv[2], &data, NULL, &error);
	if (!ret) {
		g_print ("failed to read: %s\n", error->message);
		g_error_free (error);
		goto out;
	}

	/* parse string */
	output = g_string_new ("// automatically generated, do not edit\n");

	/* parse string */
	split = g_strsplit (data, "\n", -1);
	for (i = 0; split[i] != NULL; i++) {

		/* comment or blank line */
		if (split[i][0] == '#' ||
		    split[i][0] == '\0')
			continue;

		g_print ("@@%i:%s\n", i, split[i]);

		/* populate a CdParseEntry */
		sections = g_strsplit (split[i], ",", -1);
		entry.record = sections[CD_PARSE_SECTION_RECORD];
		entry.summary = sections[CD_PARSE_SECTION_SUMMARY];
		entry.dev = atoi (sections[CD_PARSE_SECTION_DEV]);
		entry.ep = atoi (sections[CD_PARSE_SECTION_EP]);
		entry.direction = CD_PARSE_ENTRY_DIRECTION_UNKNOWN;
		entry.summary_pretty = NULL;
		entry.ep_description = NULL;
		part = cd_parse_beagle_process_entry (kind, &entry);
		if (part != NULL) {
			g_string_append (output, part);
//			g_print ("%s\n", part);
		}
		g_free (part);
		g_strfreev (sections);
	}

	/* write file */
	ret = g_file_set_contents (argv[3], output->str, -1, &error);
	if (!ret) {
		g_print ("failed to read: %s\n", error->message);
		g_error_free (error);
		goto out;
	}

	g_print ("done!\n");
	retval = 0;
out:
	if (output != NULL)
		g_string_free (output, TRUE);
	g_free (data);
	g_strfreev (split);
	return retval;
}
Esempio n. 26
0
/**
 * @brief Load the user's customized preferences
 *
 * Tries to load the user's preferences.xml file. If there is none, creates it.
 * Displays dialog boxes on any errors.
 */
void Preferences::load(bool use_gui, bool quiet)
{   
    Glib::ustring const not_saved = _("Inkscape will run with default settings, "
                                "and new settings will not be saved. ");
    _use_gui = use_gui;
    _quiet = quiet;
    _loaded = true;
    
    // NOTE: After we upgrade to Glib 2.16, use Glib::ustring::compose
    
    // 1. Does the file exist?
    if (!g_file_test(_prefs_filename.data(), G_FILE_TEST_EXISTS)) {
        // No - we need to create one.
        // Does the profile directory exist?
        if (!g_file_test(_prefs_dir.data(), G_FILE_TEST_EXISTS)) {
            // No - create the profile directory
            if (g_mkdir(_prefs_dir.data(), 0755)) {
                // the creation failed
                //_errorDialog(Glib::ustring::compose(_("Cannot create profile directory %1."),
                //    Glib::filename_to_utf8(_prefs_dir)), not_saved);
                gchar *msg = g_strdup_printf(_("Cannot create profile directory %s."),
                    Glib::filename_to_utf8(_prefs_dir).data());
                _errorDialog(msg, not_saved);
                g_free(msg);
                return;
            }
            // create some subdirectories for user stuff
            char const *user_dirs[] = {"keys", "templates", "icons", "extensions", "palettes", NULL};
            for(int i=0; user_dirs[i]; ++i) {
                char *dir = profile_path(user_dirs[i]);
                g_mkdir(dir, 0755);
                g_free(dir);
            }
            
        } else if (!g_file_test(_prefs_dir.data(), G_FILE_TEST_IS_DIR)) {
            // The profile dir is not actually a directory
            //_errorDialog(Glib::ustring::compose(_("%1 is not a valid directory."),
            //    Glib::filename_to_utf8(_prefs_dir)), not_saved);
            gchar *msg = g_strdup_printf(_("%s is not a valid directory."),
                Glib::filename_to_utf8(_prefs_dir).data());
            _errorDialog(msg, not_saved);
            g_free(msg);
            return;
        }
        // The profile dir exists and is valid.
        if (!g_file_set_contents(_prefs_filename.data(), preferences_skeleton, PREFERENCES_SKELETON_SIZE, NULL)) {
            // The write failed.
            //_errorDialog(Glib::ustring::compose(_("Failed to create the preferences file %1."),
            //    Glib::filename_to_utf8(_prefs_filename)), not_saved);
            gchar *msg = g_strdup_printf(_("Failed to create the preferences file %s."),
                Glib::filename_to_utf8(_prefs_filename).data());
            _errorDialog(msg, not_saved);
            g_free(msg);
            return;
        }
        
        // The prefs file was just created.
        // We can return now and skip the rest of the load process.
        _writable = true;
        return;
    }
    
    // Yes, the pref file exists.
    // 2. Is it a regular file?
    if (!g_file_test(_prefs_filename.data(), G_FILE_TEST_IS_REGULAR)) {
        //_errorDialog(Glib::ustring::compose(_("The preferences file %1 is not a regular file."),
        //    Glib::filename_to_utf8(_prefs_filename)), not_saved);
        gchar *msg = g_strdup_printf(_("The preferences file %s is not a regular file."),
            Glib::filename_to_utf8(_prefs_filename).data());
        _errorDialog(msg, not_saved);
        g_free(msg);
        return;
    }
    
    // 3. Is the file readable?
    gchar *prefs_xml = NULL; gsize len = 0;
    if (!g_file_get_contents(_prefs_filename.data(), &prefs_xml, &len, NULL)) {
        //_errorDialog(Glib::ustring::compose(_("The preferences file %1 could not be read."),
        //    Glib::filename_to_utf8(_prefs_filename)), not_saved);
        gchar *msg = g_strdup_printf(_("The preferences file %s could not be read."),
            Glib::filename_to_utf8(_prefs_filename).data());
        _errorDialog(msg, not_saved);
        g_free(msg);
        return;
    }
    // 4. Is it valid XML?
    Inkscape::XML::Document *prefs_read = sp_repr_read_mem(prefs_xml, len, NULL);
    g_free(prefs_xml);
    if (!prefs_read) {
        //_errorDialog(Glib::ustring::compose(_("The preferences file %1 is not a valid XML document."),
        //    Glib::filename_to_utf8(_prefs_filename)), not_saved);
        gchar *msg = g_strdup_printf(_("The preferences file %s is not a valid XML document."),
            Glib::filename_to_utf8(_prefs_filename).data());
        _errorDialog(msg, not_saved);
        g_free(msg);
        return;
    }
    // 5. Basic sanity check: does the root element have a correct name?
    if (strcmp(prefs_read->root()->name(), "inkscape")) {
        //_errorDialog(Glib::ustring::compose(_("The file %1 is not a valid Inkscape preferences file."),
        //    Glib::filename_to_utf8(_prefs_filename)), not_saved);
        gchar *msg = g_strdup_printf(_("The file %s is not a valid Inkscape preferences file."),
            Glib::filename_to_utf8(_prefs_filename).data());
        _errorDialog(msg, not_saved);
        g_free(msg);
        Inkscape::GC::release(prefs_read);
        return;
    }
    
    // Merge the loaded prefs with defaults.
    _prefs_doc->root()->mergeFrom(prefs_read->root(), "id");
    Inkscape::GC::release(prefs_read);
    _writable = true;
}
Esempio n. 27
0
static gboolean
gnc_totd_initialize (void)
{
    gchar *filename, *contents, *new_str;
    gsize length;
    GError *error;

    /* Find the file */
    filename = gnc_filepath_locate_data_file("tip_of_the_day.list");
    if (!filename)
        return FALSE;

    /* Read it */
    if (!g_file_get_contents(filename, &contents, &length, &error))
    {
        printf("Unable to read file: %s\n", error->message);
        g_error_free(error);
        g_free(filename);
        return FALSE;
    }
    g_free(filename);

    /* Split into multiple strings. Due to the nature of the
     * tip list file, this can contain empty strings */
    tip_list = g_strsplit(contents, "\n", 0);
    g_free(contents);
    contents = NULL;

    /* Remove the empty strings */
    for (tip_count = 0; tip_list[tip_count] != NULL; tip_count++)
    {
        if (*tip_list[tip_count]!='\0')
        {
            g_strstrip(tip_list[tip_count]);
            if (!contents)
                contents = g_strdup (tip_list[tip_count]);
            else
            {
                new_str = g_strjoin ("\n", contents, tip_list[tip_count], NULL);
                g_free (contents);
                contents = new_str;
            }
        }
    }

    /* Split cleaned up contents into multiple strings again */
    g_strfreev (tip_list);
    tip_list = g_strsplit(contents, "\n", 0);

    /* Convert any escaped characters while counting the strings */
    for (tip_count = 0; tip_list[tip_count] != NULL; tip_count++)
    {
        new_str = g_strcompress(tip_list[tip_count]);
        g_free(tip_list[tip_count]);
        tip_list[tip_count] = new_str;
    }


    /* Don't continue when no tips were found, to prevent
     * gnc_new_tip_number doesn't handle that case (it would try to
     * display the terminating NULL). There's nothing to show
     * anyway...*/
    if (tip_count == 0)
    {
        PWARN("No tips found - Tips of the day window won't be displayed.");
        return FALSE;
    }

    return TRUE;
}
Esempio n. 28
0
/**
 * main:
 **/
int
main (int argc, char *argv[])
{
	gboolean ret;
	gchar **package_ids = NULL;
	gchar *packages_data = NULL;
	GError *error = NULL;
	GFile *file = NULL;
	gint retval;
	GMainLoop *loop = NULL;
	PkResults *results;
	PkTask *task = NULL;
	PkProgressBar *progressbar = NULL;

#if (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION < 35)
	g_type_init ();
#endif

	/* ensure root user */
	if (getuid () != 0 || geteuid () != 0) {
		retval = EXIT_FAILURE;
		g_warning ("This program can only be used using root");
		goto out;
	}

	/* always do this first to avoid a loop if this tool segfaults */
	g_unlink (PK_OFFLINE_UPDATE_TRIGGER_FILENAME);

	/* get the list of packages to update */
	ret = g_file_get_contents (PK_OFFLINE_PREPARED_UPDATE_FILENAME,
				   &packages_data,
				   NULL,
				   &error);
	if (!ret) {
		retval = EXIT_FAILURE;
		g_warning ("failed to read: %s", error->message);
		g_error_free (error);
		goto out;
	}

	/* use a progress bar when the user presses <esc> in plymouth */
	progressbar = pk_progress_bar_new ();
	pk_progress_bar_set_size (progressbar, 25);
	pk_progress_bar_set_padding (progressbar, 30);

	/* just update the system */
	task = pk_task_new ();
	pk_task_set_interactive (task, FALSE);
	pk_offline_update_set_plymouth_mode ("updates");
	package_ids = g_strsplit (packages_data, "\n", -1);
	pk_offline_update_write_dummy_results (package_ids);
	results = pk_client_update_packages (PK_CLIENT (task),
					     0,
					     package_ids,
					     NULL, /* GCancellable */
					     pk_offline_update_progress_cb,
					     progressbar, /* user_data */
					     &error);
	if (results == NULL) {
		retval = EXIT_FAILURE;
		pk_offline_update_write_error (error);
		g_warning ("failed to update system: %s", error->message);
		g_error_free (error);
		goto out;
	}
	pk_progress_bar_end (progressbar);
	pk_offline_update_write_results (results);

	/* delete prepared-update file */
	file = g_file_new_for_path (PK_OFFLINE_PREPARED_UPDATE_FILENAME);
	ret = g_file_delete (file, NULL, &error);
	if (!ret) {
		retval = EXIT_FAILURE;
		g_warning ("failed to delete %s: %s",
			   PK_OFFLINE_PREPARED_UPDATE_FILENAME,
			   error->message);
		g_error_free (error);
		goto out;
	}

	retval = EXIT_SUCCESS;
out:
	/* if we failed, we pause to show any error on the screen */
	if (retval != EXIT_SUCCESS) {
		loop = g_main_loop_new (NULL, FALSE);
		g_timeout_add_seconds (10, pk_offline_update_loop_quit_cb, loop);
		g_main_loop_run (loop);
	}
	pk_offline_update_reboot ();
	g_free (packages_data);
	g_strfreev (package_ids);
	if (progressbar != NULL)
		g_object_unref (progressbar);
	if (file != NULL)
		g_object_unref (file);
	if (task != NULL)
		g_object_unref (task);
	if (loop != NULL)
		g_main_loop_unref (loop);
	return retval;
}
static void scrobble_cached_queue() {

    gchar *queuepath = g_build_filename(aud_get_path(AUD_PATH_USER_DIR),"scrobbler.log", NULL);
    gchar *contents = NULL;
    gboolean success;
    gchar **lines = NULL;
    gchar **line;
    gchar *scrobblemsg;
    GSList *lines_to_remove = NULL;
    gchar *error_code = NULL;
    gchar *error_detail = NULL;
    pthread_mutex_lock(&log_access_mutex);
    success = g_file_get_contents(queuepath, &contents, NULL, NULL);
    pthread_mutex_unlock(&log_access_mutex);
    if (!success) {
        AUDDBG("Couldn't access the queue file.\n");
    } else {

        lines = g_strsplit(contents, "\n", 0);

        for (int i = 0; lines[i] != NULL && strlen(lines[i]) > 0 && scrobbling_enabled; i++) {
            line = g_strsplit(lines[i], "\t", 0);

            //line[0] line[1] line[2] line[3] line[4] line[5] line[6]   line[7]
            //artist  album   title   number  length  "L"     timestamp NULL

            if (line[0] && line[2] && (strcmp(line[5], "L") == 0) && line[6] && (line[7] == NULL)) {
                scrobblemsg = create_message_to_lastfm("track.scrobble",
                                                       8,
                                                       "artist", line[0],
                                                       "album", line[1],
                                                       "track", line[2],
                                                       "trackNumber", line[3],
                                                       "duration", line[4],
                                                       "timestamp", line[6],
                                                       "api_key", SCROBBLER_API_KEY,
                                                       "sk", session_key);
                if (send_message_to_lastfm(scrobblemsg) == TRUE) {
                    error_code = NULL;
                    error_detail = NULL;
                    if (read_scrobble_result(&error_code, &error_detail) == TRUE) {
                        //TODO: a track might not be scrobbled due to "daily scrobble limit exeeded".
                        //This message comes on the ignoredMessage attribute, inside the XML of the response.
                        //We are not dealing with this case currently and are losing that scrobble.
                        AUDDBG("SCROBBLE OK.\n");
                        save_line_to_remove(&lines_to_remove, i);
                    } else {
                        AUDDBG("SCROBBLE NOT OK. Error code: %s. Error detail: %s.\n", error_code, error_detail);

                        if (error_code == NULL) { //net error(?) or the answer from last.fm was not well read
                            //scrobble to be retried
                        }
                        else if (g_strcmp0(error_code, "11") == 0 ||
                                 g_strcmp0(error_code, "16") == 0){
                            //error code 11: Service Offline - This service is temporarily offline. Try again later.
                            //error code 16: The service is temporarily unavailable, please try again.
                            //scrobble to be retried
                        }
                        else if (g_strcmp0(error_code,  "9") == 0) {
                            //Bad Session. Reauth.
                            scrobbling_enabled = FALSE;
                            g_free(session_key);
                            session_key = NULL;
                            aud_set_string("scrobbler", "session_key", "");
                        }
                        else {
                            save_line_to_remove(&lines_to_remove, i);
                        }
                    }

                    g_free(error_code);
                    g_free(error_detail);

                } else {
                    AUDDBG("Could not scrobble a track on the queue. Network problem?\n");
                    //scrobble to be retried
                    scrobbling_enabled = FALSE;
                }

                g_free(scrobblemsg);
            } else {
                AUDDBG("Unscrobbable line.\n");
                //leave entry on the cache file
            }
            g_strfreev(line);
        }//for

        if (lines_to_remove != NULL) {
            delete_lines_from_scrobble_log(&lines_to_remove, queuepath);
            g_slist_free_full(lines_to_remove, g_free);
        }
        g_strfreev(lines);
    }

    g_free(contents);
    g_free(queuepath);
}
Esempio n. 30
0
/* this will do zap style channels.conf only for the moment */
static GHashTable *
parse_channels_conf_from_file (GstElement * dvbbasebin, const gchar * filename,
    GError ** error)
{
  gchar *contents;
  gchar **lines;
  gchar *line;
  gchar **fields;
  const gchar *terrestrial[] = { "inversion", "bandwidth",
    "code-rate-hp", "code-rate-lp", "modulation", "transmission-mode",
    "guard", "hierarchy"
  };
  const gchar *satellite[] = { "polarity", "diseqc-source",
    "symbol-rate"
  };
  const gchar *cable[] = { "inversion", "symbol-rate", "code-rate-hp",
    "modulation"
  };
  int i, parsedchannels = 0;
  GHashTable *res;
  GError *err = NULL;

  GST_INFO_OBJECT (dvbbasebin, "parsing '%s'", filename);

  if (!g_file_get_contents (filename, &contents, NULL, &err))
    goto open_fail;

  lines = g_strsplit (contents, "\n", 0);
  res = g_hash_table_new (g_str_hash, g_str_equal);

  i = 0;
  line = lines[0];
  while (line != NULL) {
    if (line[0] != '#') {
      int numfields;
      gboolean parsed = FALSE;
      GHashTable *params = g_hash_table_new_full (g_str_hash, g_str_equal,
          g_free, g_free);

      fields = g_strsplit (line, ":", 0);
      numfields = g_strv_length (fields);
      if (numfields == 8) {
        /* satellite */
        int j;

        g_hash_table_insert (params, g_strdup ("type"), g_strdup ("satellite"));
        for (j = 2; j <= 4; j++) {
          g_hash_table_insert (params, g_strdup (satellite[j - 2]),
              g_strdup (fields[j]));
        }
        /**
         * Some ZAP format variations store freqs in MHz
         * but we internally use kHz for DVB-S/S2.
         */
        if (strlen (fields[1]) < 6) {
          g_hash_table_insert (params, g_strdup ("frequency"),
              g_strdup_printf ("%d", atoi (fields[1]) * 1000));
        } else {
          g_hash_table_insert (params, g_strdup ("frequency"),
              g_strdup_printf ("%d", atoi (fields[1])));
        }
        parsed = TRUE;
      } else if (numfields == 13) {
        /* terrestrial */
        int j;

        g_hash_table_insert (params, g_strdup ("type"),
            g_strdup ("terrestrial"));
        for (j = 2; j <= 9; j++) {
          g_hash_table_insert (params, g_strdup (terrestrial[j - 2]),
              g_strdup (fields[j]));
        }
        g_hash_table_insert (params, g_strdup ("frequency"),
            g_strdup (fields[1]));
        parsed = TRUE;
      } else if (numfields == 9) {
        /* cable */
        int j;

        g_hash_table_insert (params, g_strdup ("type"), g_strdup ("cable"));
        for (j = 2; j <= 5; j++) {
          g_hash_table_insert (params, g_strdup (cable[j - 2]),
              g_strdup (fields[j]));
        }
        g_hash_table_insert (params, g_strdup ("frequency"),
            g_strdup (fields[1]));
        parsed = TRUE;
      } else if (numfields == 6) {
        /* atsc (vsb/qam) */
        g_hash_table_insert (params, g_strdup ("type"), g_strdup ("atsc"));
        g_hash_table_insert (params, g_strdup ("modulation"),
            g_strdup (fields[2]));

        g_hash_table_insert (params, g_strdup ("frequency"),
            g_strdup (fields[1]));
        parsed = TRUE;
      }
      if (parsed) {
        g_hash_table_insert (params, g_strdup ("sid"),
            g_strdup (fields[numfields - 1]));
        g_hash_table_insert (res, g_strdup (fields[0]), params);
        parsedchannels++;
      }
      g_strfreev (fields);
    }
    line = lines[++i];
  }
  g_strfreev (lines);
  g_free (contents);

  if (parsedchannels == 0)
    goto no_channels;

  return res;

open_fail:
  {
    if (err->code == G_FILE_ERROR_NOENT) {
      g_set_error (error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_NOT_FOUND,
          _("Couldn't find DVB channel configuration file"));
    } else {
      g_set_error (error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_READ,
          _("Couldn't load DVB channel configuration file: %s"), err->message);
    }
    g_clear_error (&err);
    return NULL;
  }

no_channels:
  {
    g_set_error (error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_FAILED,
        _("DVB channel configuration file doesn't contain any channels"));
    g_hash_table_unref (res);
    return NULL;
  }
}