Example #1
0
static void
rip_one_track(gpointer data, gpointer user_data)
{
    track_info_t *track = (track_info_t*)data;
    char *cdrom_device = (char*)user_data;
    GstBus *bus;
    GstElement *pipeline, *source, *encoder, *sink;
    GMainLoop *loop;
    char *tmp_file, *final_file;


    loop = g_main_loop_new(NULL, FALSE);

    pipeline = gst_pipeline_new("rip-flac");
    source = gst_element_factory_make("cdparanoiasrc", "rip");
    encoder = gst_element_factory_make("flacenc", "flac");
    sink = gst_element_factory_make("filesink", "output");

    if (!(pipeline && source && encoder && sink)) {
        fprintf(stderr, "unable to make all necessary gstreamer elements\n");
        return;
    }

    g_object_set(G_OBJECT(source), "device", cdrom_device, NULL);
    g_object_set(G_OBJECT(source), "track", track->track_num, NULL);

    g_object_set(G_OBJECT(encoder), "quality", 8, NULL);

    final_file = track_filename(track);
    {
        char *tmp_dir = g_path_get_dirname(final_file);
        char *tmp_base = g_path_get_basename(final_file);

        tmp_file = g_strconcat(tmp_dir, "/.", tmp_base, NULL);

        g_mkdir_with_parents(tmp_dir, 0755);

        g_free(tmp_dir);
        g_free(tmp_base);
    }
    g_object_set(G_OBJECT(sink), "location", tmp_file, NULL);

    bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
    gst_bus_add_watch(bus, bus_call, loop);
    gst_object_unref(bus);

    gst_bin_add_many(GST_BIN(pipeline), source, encoder, sink, NULL);

    gst_element_link_many(source, encoder, sink, NULL);

    set_tags(pipeline, track);

    gst_element_set_state(pipeline, GST_STATE_PLAYING);

    printf("ripping track: %d\n", track->track_num);
    g_main_loop_run(loop);

    gst_element_set_state(pipeline, GST_STATE_NULL);
    gst_object_unref(GST_OBJECT(pipeline));

    g_rename(tmp_file, final_file);

    g_free(tmp_file);
    g_free(final_file);
}
Example #2
0
void
dt_styles_update (const char *name, const char *newname, const char *newdescription, GList *filter, int imgid, GList *update)
{
  sqlite3_stmt *stmt;
  int id=0;
  gchar *desc = NULL;

  id = dt_styles_get_id_by_name(name);
  if(id == 0) return;

  desc = dt_styles_get_description (name);

  if ((g_strcmp0(name, newname)) || (g_strcmp0(desc, newdescription)))
  {
    DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "update styles set name=?1, description=?2 where rowid=?3", -1, &stmt, NULL);
    DT_DEBUG_SQLITE3_BIND_TEXT(stmt, 1, newname, strlen (newname), SQLITE_STATIC);
    DT_DEBUG_SQLITE3_BIND_TEXT(stmt, 2, newdescription, strlen (newdescription), SQLITE_STATIC);
    DT_DEBUG_SQLITE3_BIND_INT(stmt, 3, id);
    sqlite3_step(stmt);
    sqlite3_finalize(stmt);
  }

  if (filter)
  {
    GList *list=filter;
    char tmp[64];
    char include[2048] = {0};
    g_strlcat(include,"num not in (", 2048);
    do
    {
      if(list!=g_list_first(list))
        g_strlcat(include, ",", 2048);
      sprintf(tmp, "%ld", (glong)list->data);
      g_strlcat(include, tmp, 2048);
    }
    while ((list=g_list_next(list)));
    g_strlcat(include,")", 2048);

    char query[4096]= {0};
    sprintf(query,"delete from style_items where styleid=?1 and %s", include);
    DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), query, -1, &stmt, NULL);
    DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, id);
    sqlite3_step(stmt);
    sqlite3_finalize(stmt);
  }

  _dt_style_update_from_image(id,imgid,filter,update);

  _dt_style_cleanup_multi_instance(id);

  /* backup style to disk */
  char stylesdir[1024];
  dt_loc_get_user_config_dir(stylesdir, 1024);
  g_strlcat(stylesdir,"/styles",1024);
  g_mkdir_with_parents(stylesdir,00755);

  dt_styles_save_to_file(newname,stylesdir,TRUE);

  /* delete old accelerator and create a new one */
  //TODO: should better use dt_accel_rename_global() to keep the old accel_key untouched, but it seems to be buggy
  if (g_strcmp0(name, newname))
  {
    char tmp_accel[1024];
    snprintf(tmp_accel, 1024, C_("accel", "styles/apply %s"), name);
    dt_accel_deregister_global(tmp_accel);

    gchar* tmp_name = g_strdup(newname); // freed by _destroy_style_shortcut_callback
    snprintf(tmp_accel, 1024, C_("accel", "styles/apply %s"), newname);
    dt_accel_register_global( tmp_accel, 0, 0);
    GClosure *closure;
    closure = g_cclosure_new(
                G_CALLBACK(_apply_style_shortcut_callback),
                tmp_name, _destroy_style_shortcut_callback);
    dt_accel_connect_global(tmp_accel, closure);
  }

  g_free(desc);
}
Example #3
0
static char *
define_destination_uri (EphyDownload *download, const char *suggested_filename)
{
  char *dest_dir;
  char *dest_name;
  char *destination_filename;
  char *destination_uri;

  dest_dir = ephy_file_get_downloads_dir ();

  /* Make sure the download directory exists */
  if (g_mkdir_with_parents (dest_dir, 0700) == -1) {
    g_critical ("Could not create downloads directory \"%s\": %s",
                dest_dir, strerror (errno));
    g_free (dest_dir);
    return NULL;
  }

  if (suggested_filename != NULL) {
    dest_name = g_strdup (suggested_filename);
  } else {
    dest_name = ephy_file_tmp_filename ("ephy-download-XXXXXX", NULL);
  }

  destination_filename = g_build_filename (dest_dir, dest_name, NULL);
  g_free (dest_dir);
  g_free (dest_name);

  /* Append (n) as needed. */
  if (g_file_test (destination_filename, G_FILE_TEST_EXISTS)) {
    int i = 1;
    const char *dot_pos;
    gssize position;
    char *serial = NULL;
    GString *tmp_filename;

    dot_pos = parse_extension (destination_filename);
    if (dot_pos)
      position = dot_pos - destination_filename;
    else
      position = strlen (destination_filename);

    tmp_filename = g_string_new (NULL);

    do {
      serial = g_strdup_printf ("(%d)", i++);

      g_string_assign (tmp_filename, destination_filename);
      g_string_insert (tmp_filename, position, serial);

      g_free (serial);
    } while (g_file_test (tmp_filename->str, G_FILE_TEST_EXISTS));

    destination_filename = g_strdup (tmp_filename->str);
    g_string_free (tmp_filename, TRUE);
  }

  destination_uri = g_filename_to_uri (destination_filename, NULL, NULL);
  g_free (destination_filename);

  g_assert (destination_uri);

  return destination_uri;
}
static void
load_libreoffice (NemoPreviewPdfLoader *self)
{
  gchar *libreoffice_path;
  GFile *file;
  gchar *doc_path, *doc_name, *tmp_name, *pdf_dir;
  gboolean res;
  GPid pid;
  GError *error = NULL;
  const gchar *libreoffice_argv[] = {
    NULL /* to be replaced with binary */,
    "--convert-to", "pdf",
    "--outdir", NULL /* to be replaced with output dir */,
    NULL /* to be replaced with input file */,
    NULL
  };

  libreoffice_path = g_find_program_in_path ("libreoffice");
  if (libreoffice_path == NULL) {
    libreoffice_missing (self);
    return;
  }

  file = g_file_new_for_uri (self->priv->uri);
  doc_path = g_file_get_path (file);
  doc_name = g_file_get_basename (file);
  g_object_unref (file);

  /* libreoffice --convert-to replaces the extension with .pdf */
  tmp_name = g_strrstr (doc_name, ".");
  if (tmp_name)
    *tmp_name = '\0';
  tmp_name = g_strdup_printf ("%s.pdf", doc_name);
  g_free (doc_name);

  pdf_dir = g_build_filename (g_get_user_cache_dir (), "sushi", NULL);
  self->priv->pdf_path = g_build_filename (pdf_dir, tmp_name, NULL);
  g_mkdir_with_parents (pdf_dir, 0700);

  g_free (tmp_name);
  libreoffice_argv[0] = libreoffice_path;
  libreoffice_argv[4] = pdf_dir;
  libreoffice_argv[5] = doc_path;

  tmp_name = g_strjoinv (" ", (gchar **) libreoffice_argv);
  g_debug ("Executing LibreOffice command: %s", tmp_name);
  g_free (tmp_name);

  res = g_spawn_async (NULL, (gchar **) libreoffice_argv, NULL,
                       G_SPAWN_DO_NOT_REAP_CHILD,
                       NULL, NULL,
                       &pid, &error);

  g_free (pdf_dir);
  g_free (doc_path);
  g_free (libreoffice_path);

  if (!res) {
    g_warning ("Error while spawning libreoffice: %s",
               error->message);
    g_error_free (error);

    return;
  }

  g_child_watch_add (pid, libreoffice_child_watch_cb, self);
  self->priv->libreoffice_pid = pid;
}
static GObject *
empathy_chatroom_manager_constructor (GType type,
    guint n_props,
    GObjectConstructParam *props)
{
  GObject *obj;
  EmpathyChatroomManager *self;
  EmpathyChatroomManagerPriv *priv;
  GError *error = NULL;

  if (chatroom_manager_singleton != NULL)
    return g_object_ref (chatroom_manager_singleton);

  /* Parent constructor chain */
  obj = G_OBJECT_CLASS (empathy_chatroom_manager_parent_class)->
        constructor (type, n_props, props);

  self = EMPATHY_CHATROOM_MANAGER (obj);
  priv = GET_PRIV (self);

  priv->ready = FALSE;

  chatroom_manager_singleton = self;
  g_object_add_weak_pointer (obj, (gpointer) &chatroom_manager_singleton);

  priv->account_manager = tp_account_manager_dup ();

  tp_proxy_prepare_async (priv->account_manager, NULL,
      account_manager_ready_cb, g_object_ref (self));

  if (priv->file == NULL)
    {
      /* Set the default file path */
      gchar *dir;

      dir = g_build_filename (g_get_user_config_dir (), PACKAGE_NAME, NULL);
      if (!g_file_test (dir, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))
        g_mkdir_with_parents (dir, S_IRUSR | S_IWUSR | S_IXUSR);

      priv->file = g_build_filename (dir, CHATROOMS_XML_FILENAME, NULL);
      g_free (dir);
    }

  /* Setup a room observer */
  priv->observer = tp_simple_observer_new_with_am (priv->account_manager, TRUE,
      "Empathy.ChatroomManager", TRUE, observe_channels_cb, self, NULL);

  tp_base_client_take_observer_filter (priv->observer, tp_asv_new (
      TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING,
        TP_IFACE_CHANNEL_TYPE_TEXT,
      TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT,
        TP_HANDLE_TYPE_ROOM,
      NULL));

  if (!tp_base_client_register (priv->observer, &error))
    {
      g_critical ("Failed to register Observer: %s", error->message);

      g_error_free (error);
    }

  return obj;
}
static gboolean
status_presets_file_save (void)
{
    xmlDocPtr   doc;
    xmlNodePtr  root;
    GList      *l;
    gchar      *dir;
    gchar      *file;
    gint        count[TP_NUM_CONNECTION_PRESENCE_TYPES];
    gint        i;

    for (i = 0; i < TP_NUM_CONNECTION_PRESENCE_TYPES; i++) {
        count[i] = 0;
    }

    dir = g_build_filename (g_get_user_config_dir (), PACKAGE_NAME, NULL);
    g_mkdir_with_parents (dir, S_IRUSR | S_IWUSR | S_IXUSR);
    file = g_build_filename (dir, STATUS_PRESETS_XML_FILENAME, NULL);
    g_free (dir);

    doc = xmlNewDoc ((const xmlChar *) "1.0");
    root = xmlNewNode (NULL, (const xmlChar *) "presets");
    xmlDocSetRootElement (doc, root);

    if (default_preset) {
        xmlNodePtr  subnode;
        xmlChar    *state;

        state = (xmlChar *) empathy_presence_to_str (default_preset->state);

        subnode = xmlNewTextChild (root, NULL, (const xmlChar *) "default",
                                   (const xmlChar *) default_preset->status);
        xmlNewProp (subnode, (const xmlChar *) "presence", state);
    }

    for (l = presets; l; l = l->next) {
        StatusPreset *sp;
        xmlNodePtr    subnode;
        xmlChar      *state;

        sp = l->data;
        state = (xmlChar *) empathy_presence_to_str (sp->state);

        count[sp->state]++;
        if (count[sp->state] > STATUS_PRESETS_MAX_EACH) {
            continue;
        }

        subnode = xmlNewTextChild (root, NULL,
                                   (const xmlChar *) "status", (const xmlChar *) sp->status);
        xmlNewProp (subnode, (const xmlChar *) "presence", state);
    }

    /* Make sure the XML is indented properly */
    xmlIndentTreeOutput = 1;

    DEBUG ("Saving file:'%s'", file);
    xmlSaveFormatFileEnc (file, doc, "utf-8", 1);
    xmlFreeDoc (doc);

    g_free (file);

    return TRUE;
}
Example #7
0
void _capture_view_set_jobcode(const dt_view_t *view, const char *name)
{
  g_assert( view != NULL );
  dt_capture_t *cv=(dt_capture_t *)view->data;

  /* take care of previous capture filmroll */
  if( cv->film )
  {
    if( dt_film_is_empty(cv->film->id) )
      dt_film_remove(cv->film->id );
    else
      dt_film_cleanup( cv->film );
  }

  /* lets initialize a new filmroll for the capture... */
  cv->film = (dt_film_t*)malloc(sizeof(dt_film_t));
  if(!cv->film) return;
  dt_film_init(cv->film);

  int current_filmroll = dt_conf_get_int("plugins/capture/current_filmroll");
  if(current_filmroll >= 0)
  {
    /* open existing filmroll and import captured images into this roll */
    cv->film->id = current_filmroll;
    if (dt_film_open2 (cv->film) !=0)
    {
      /* failed to open the current filmroll, let's reset and create a new one */
      dt_conf_set_int ("plugins/capture/current_filmroll",-1);
    }
    else
      cv->path = g_strdup(cv->film->dirname);

  }

  if (dt_conf_get_int ("plugins/capture/current_filmroll") == -1)
  {
    if(cv->jobcode)
      g_free(cv->jobcode);
    cv->jobcode = g_strdup(name);

    // Setup variables jobcode...
    cv->vp->jobcode = cv->jobcode;

    /* reset session sequence number */
    dt_variables_reset_sequence (cv->vp);

    // Construct the directory for filmroll...
    gchar* path = g_build_path(G_DIR_SEPARATOR_S,cv->basedirectory,cv->subdirectory, (char *)NULL);
    cv->path = dt_util_fix_path(path);
    g_free(path);

    dt_variables_expand( cv->vp, cv->path, FALSE );
    sprintf(cv->film->dirname,"%s",dt_variables_get_result(cv->vp));

    // Create recursive directories, abort if no access
    if( g_mkdir_with_parents(cv->film->dirname,0755) == -1 )
    {
      dt_control_log(_("failed to create session path %s."), cv->film->dirname);
      if(cv->film)
      {
        free( cv->film );
        cv->film = NULL;
      }
      return;
    }

    if(dt_film_new(cv->film,cv->film->dirname) > 0)
    {
      // Switch to new filmroll
      dt_film_open(cv->film->id);

      /* store current filmroll */
      dt_conf_set_int("plugins/capture/current_filmroll",cv->film->id);
    }

    dt_control_log(_("new session initiated '%s'"),cv->jobcode,cv->film->id);
  }


}
Example #8
0
static void kkc_user_rule_write_files (KkcRuleMetadata* parent, const gchar* path, const gchar* name, GError** error) {
	JsonGenerator* generator = NULL;
	JsonGenerator* _tmp0_ = NULL;
	JsonGenerator* _tmp1_ = NULL;
	const gchar* _tmp2_ = NULL;
	JsonBuilder* metadata_builder = NULL;
	KkcRuleMetadata* _tmp3_ = NULL;
	const gchar* _tmp4_ = NULL;
	JsonBuilder* _tmp5_ = NULL;
	JsonGenerator* _tmp6_ = NULL;
	JsonBuilder* _tmp7_ = NULL;
	JsonNode* _tmp8_ = NULL;
	JsonNode* _tmp9_ = NULL;
	gchar* metadata_filename = NULL;
	const gchar* _tmp10_ = NULL;
	gchar* _tmp11_ = NULL;
	JsonGenerator* _tmp12_ = NULL;
	const gchar* _tmp13_ = NULL;
	gchar* keymap_path = NULL;
	const gchar* _tmp14_ = NULL;
	gchar* _tmp15_ = NULL;
	const gchar* _tmp16_ = NULL;
	GEnumClass* enum_class = NULL;
	GTypeClass* _tmp17_ = NULL;
	gchar* rom_kana_path = NULL;
	const gchar* _tmp46_ = NULL;
	gchar* _tmp47_ = NULL;
	const gchar* _tmp48_ = NULL;
	JsonBuilder* rom_kana_builder = NULL;
	KkcRuleMetadata* _tmp49_ = NULL;
	JsonBuilder* _tmp50_ = NULL;
	JsonGenerator* _tmp51_ = NULL;
	JsonBuilder* _tmp52_ = NULL;
	JsonNode* _tmp53_ = NULL;
	JsonNode* _tmp54_ = NULL;
	gchar* rom_kana_filename = NULL;
	const gchar* _tmp55_ = NULL;
	gchar* _tmp56_ = NULL;
	JsonGenerator* _tmp57_ = NULL;
	const gchar* _tmp58_ = NULL;
	GError * _inner_error_ = NULL;
	g_return_if_fail (parent != NULL);
	g_return_if_fail (path != NULL);
	g_return_if_fail (name != NULL);
	_tmp0_ = json_generator_new ();
	generator = _tmp0_;
	_tmp1_ = generator;
	json_generator_set_pretty (_tmp1_, TRUE);
	_tmp2_ = path;
	g_mkdir_with_parents (_tmp2_, 448);
	_tmp3_ = parent;
	_tmp4_ = name;
	_tmp5_ = kkc_user_rule_create_metadata (_tmp3_, _tmp4_);
	metadata_builder = _tmp5_;
	_tmp6_ = generator;
	_tmp7_ = metadata_builder;
	_tmp8_ = json_builder_get_root (_tmp7_);
	_tmp9_ = _tmp8_;
	json_generator_set_root (_tmp6_, _tmp9_);
	__vala_JsonNode_free0 (_tmp9_);
	_tmp10_ = path;
	_tmp11_ = g_build_filename (_tmp10_, "metadata.json", NULL);
	metadata_filename = _tmp11_;
	_tmp12_ = generator;
	_tmp13_ = metadata_filename;
	json_generator_to_file (_tmp12_, _tmp13_, &_inner_error_);
	if (G_UNLIKELY (_inner_error_ != NULL)) {
		g_propagate_error (error, _inner_error_);
		_g_free0 (metadata_filename);
		_g_object_unref0 (metadata_builder);
		_g_object_unref0 (generator);
		return;
	}
	_tmp14_ = path;
	_tmp15_ = g_build_filename (_tmp14_, "keymap", NULL);
	keymap_path = _tmp15_;
	_tmp16_ = keymap_path;
	g_mkdir_with_parents (_tmp16_, 448);
	_tmp17_ = g_type_class_ref (KKC_TYPE_INPUT_MODE);
	enum_class = (GEnumClass*) _tmp17_;
	{
		gint i = 0;
		GEnumClass* _tmp18_ = NULL;
		gint _tmp19_ = 0;
		_tmp18_ = enum_class;
		_tmp19_ = _tmp18_->minimum;
		i = _tmp19_;
		{
			gboolean _tmp20_ = FALSE;
			_tmp20_ = TRUE;
			while (TRUE) {
				gint _tmp22_ = 0;
				GEnumClass* _tmp23_ = NULL;
				gint _tmp24_ = 0;
				GEnumValue* enum_value = NULL;
				GEnumClass* _tmp25_ = NULL;
				gint _tmp26_ = 0;
				GEnumValue* _tmp27_ = NULL;
				GEnumValue* _tmp28_ = NULL;
				JsonBuilder* keymap_builder = NULL;
				KkcRuleMetadata* _tmp29_ = NULL;
				GEnumValue* _tmp30_ = NULL;
				const gchar* _tmp31_ = NULL;
				JsonBuilder* _tmp32_ = NULL;
				JsonGenerator* _tmp33_ = NULL;
				JsonBuilder* _tmp34_ = NULL;
				JsonNode* _tmp35_ = NULL;
				JsonNode* _tmp36_ = NULL;
				gchar* keymap_filename = NULL;
				const gchar* _tmp37_ = NULL;
				GEnumValue* _tmp38_ = NULL;
				const gchar* _tmp39_ = NULL;
				gchar* _tmp40_ = NULL;
				gchar* _tmp41_ = NULL;
				gchar* _tmp42_ = NULL;
				gchar* _tmp43_ = NULL;
				JsonGenerator* _tmp44_ = NULL;
				const gchar* _tmp45_ = NULL;
				if (!_tmp20_) {
					gint _tmp21_ = 0;
					_tmp21_ = i;
					i = _tmp21_ + 1;
				}
				_tmp20_ = FALSE;
				_tmp22_ = i;
				_tmp23_ = enum_class;
				_tmp24_ = _tmp23_->maximum;
				if (!(_tmp22_ <= _tmp24_)) {
					break;
				}
				_tmp25_ = enum_class;
				_tmp26_ = i;
				_tmp27_ = g_enum_get_value (_tmp25_, _tmp26_);
				_tmp28_ = __g_enum_value_dup0 (_tmp27_);
				enum_value = _tmp28_;
				_tmp29_ = parent;
				_tmp30_ = enum_value;
				_tmp31_ = (*_tmp30_).value_nick;
				_tmp32_ = kkc_user_rule_create_keymap (_tmp29_, _tmp31_, NULL);
				keymap_builder = _tmp32_;
				_tmp33_ = generator;
				_tmp34_ = keymap_builder;
				_tmp35_ = json_builder_get_root (_tmp34_);
				_tmp36_ = _tmp35_;
				json_generator_set_root (_tmp33_, _tmp36_);
				__vala_JsonNode_free0 (_tmp36_);
				_tmp37_ = keymap_path;
				_tmp38_ = enum_value;
				_tmp39_ = (*_tmp38_).value_nick;
				_tmp40_ = g_strdup_printf ("%s.json", _tmp39_);
				_tmp41_ = _tmp40_;
				_tmp42_ = g_build_filename (_tmp37_, _tmp41_, NULL);
				_tmp43_ = _tmp42_;
				_g_free0 (_tmp41_);
				keymap_filename = _tmp43_;
				_tmp44_ = generator;
				_tmp45_ = keymap_filename;
				json_generator_to_file (_tmp44_, _tmp45_, &_inner_error_);
				if (G_UNLIKELY (_inner_error_ != NULL)) {
					g_propagate_error (error, _inner_error_);
					_g_free0 (keymap_filename);
					_g_object_unref0 (keymap_builder);
					_g_free0 (enum_value);
					_g_type_class_unref0 (enum_class);
					_g_free0 (keymap_path);
					_g_free0 (metadata_filename);
					_g_object_unref0 (metadata_builder);
					_g_object_unref0 (generator);
					return;
				}
				_g_free0 (keymap_filename);
				_g_object_unref0 (keymap_builder);
				_g_free0 (enum_value);
			}
		}
	}
	_tmp46_ = path;
	_tmp47_ = g_build_filename (_tmp46_, "rom-kana", NULL);
	rom_kana_path = _tmp47_;
	_tmp48_ = rom_kana_path;
	g_mkdir_with_parents (_tmp48_, 448);
	_tmp49_ = parent;
	_tmp50_ = kkc_user_rule_create_rom_kana (_tmp49_, "default");
	rom_kana_builder = _tmp50_;
	_tmp51_ = generator;
	_tmp52_ = rom_kana_builder;
	_tmp53_ = json_builder_get_root (_tmp52_);
	_tmp54_ = _tmp53_;
	json_generator_set_root (_tmp51_, _tmp54_);
	__vala_JsonNode_free0 (_tmp54_);
	_tmp55_ = rom_kana_path;
	_tmp56_ = g_build_filename (_tmp55_, "default.json", NULL);
	rom_kana_filename = _tmp56_;
	_tmp57_ = generator;
	_tmp58_ = rom_kana_filename;
	json_generator_to_file (_tmp57_, _tmp58_, &_inner_error_);
	if (G_UNLIKELY (_inner_error_ != NULL)) {
		g_propagate_error (error, _inner_error_);
		_g_free0 (rom_kana_filename);
		_g_object_unref0 (rom_kana_builder);
		_g_free0 (rom_kana_path);
		_g_type_class_unref0 (enum_class);
		_g_free0 (keymap_path);
		_g_free0 (metadata_filename);
		_g_object_unref0 (metadata_builder);
		_g_object_unref0 (generator);
		return;
	}
	_g_free0 (rom_kana_filename);
	_g_object_unref0 (rom_kana_builder);
	_g_free0 (rom_kana_path);
	_g_type_class_unref0 (enum_class);
	_g_free0 (keymap_path);
	_g_free0 (metadata_filename);
	_g_object_unref0 (metadata_builder);
	_g_object_unref0 (generator);
}
Example #9
0
/**
         * Save keymap for given input mode.
         *
         * @param input_mode input mode
         */
void kkc_user_rule_write (KkcUserRule* self, KkcInputMode input_mode, GError** error) {
	GEnumClass* enum_class = NULL;
	GTypeClass* _tmp0_ = NULL;
	gchar* keymap_name = NULL;
	KkcInputMode _tmp1_ = 0;
	GEnumValue* _tmp2_ = NULL;
	const gchar* _tmp3_ = NULL;
	gchar* _tmp4_ = NULL;
	gchar* keymap_path = NULL;
	const gchar* _tmp5_ = NULL;
	gchar* _tmp6_ = NULL;
	JsonGenerator* generator = NULL;
	JsonGenerator* _tmp7_ = NULL;
	JsonBuilder* builder = NULL;
	KkcRuleMetadata* _tmp8_ = NULL;
	KkcInputMode _tmp9_ = 0;
	KkcKeymap* _tmp10_ = NULL;
	KkcKeymap* _tmp11_ = NULL;
	JsonBuilder* _tmp12_ = NULL;
	JsonBuilder* _tmp13_ = NULL;
	JsonNode* _tmp14_ = NULL;
	JsonNode* _tmp15_ = NULL;
	gchar* filename = NULL;
	gchar* _tmp16_ = NULL;
	gchar* _tmp17_ = NULL;
	gchar* _tmp18_ = NULL;
	gchar* _tmp19_ = NULL;
	GError * _inner_error_ = NULL;
	g_return_if_fail (self != NULL);
	_tmp0_ = g_type_class_ref (KKC_TYPE_INPUT_MODE);
	enum_class = (GEnumClass*) _tmp0_;
	_tmp1_ = input_mode;
	_tmp2_ = g_enum_get_value (enum_class, (gint) _tmp1_);
	_tmp3_ = (*_tmp2_).value_nick;
	_tmp4_ = g_strdup (_tmp3_);
	keymap_name = _tmp4_;
	_tmp5_ = self->priv->path;
	_tmp6_ = g_build_filename (_tmp5_, "keymap", NULL);
	keymap_path = _tmp6_;
	g_mkdir_with_parents (keymap_path, 448);
	_tmp7_ = json_generator_new ();
	generator = _tmp7_;
	json_generator_set_pretty (generator, TRUE);
	_tmp8_ = self->priv->parent;
	_tmp9_ = input_mode;
	_tmp10_ = kkc_rule_get_keymap ((KkcRule*) self, _tmp9_);
	_tmp11_ = _tmp10_;
	_tmp12_ = kkc_user_rule_create_keymap (_tmp8_, keymap_name, _tmp11_);
	_tmp13_ = _tmp12_;
	_g_object_unref0 (_tmp11_);
	builder = _tmp13_;
	_tmp14_ = json_builder_get_root (builder);
	_tmp15_ = _tmp14_;
	json_generator_set_root (generator, _tmp15_);
	__vala_JsonNode_free0 (_tmp15_);
	_tmp16_ = g_strdup_printf ("%s.json", keymap_name);
	_tmp17_ = _tmp16_;
	_tmp18_ = g_build_filename (keymap_path, _tmp17_, NULL);
	_tmp19_ = _tmp18_;
	_g_free0 (_tmp17_);
	filename = _tmp19_;
	json_generator_to_file (generator, filename, &_inner_error_);
	if (G_UNLIKELY (_inner_error_ != NULL)) {
		g_propagate_error (error, _inner_error_);
		_g_free0 (filename);
		_g_object_unref0 (builder);
		_g_object_unref0 (generator);
		_g_free0 (keymap_path);
		_g_free0 (keymap_name);
		_g_type_class_unref0 (enum_class);
		return;
	}
	_g_free0 (filename);
	_g_object_unref0 (builder);
	_g_object_unref0 (generator);
	_g_free0 (keymap_path);
	_g_free0 (keymap_name);
	_g_type_class_unref0 (enum_class);
}
Example #10
0
/**
 * main:
 **/
int
main (int argc, char *argv[])
{
	GError *error = NULL;
	GOptionContext *context;
	gchar *options_help;
	gboolean ret;
	gchar *filename = NULL;
	PkClient *client = NULL;
	PkControl *control = NULL;
	PkBitfield roles;
	gchar *tempdir = NULL;
	gboolean exists;
	gboolean overwrite;
	gchar **excludes = NULL;
	gchar *package_id = NULL;
	PkServicePack *pack = NULL;
	gchar *directory = NULL;
	gchar *package_list = NULL;
	gchar *package = NULL;
	gboolean updates = FALSE;
	gint retval = 1;

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

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

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

	g_type_init ();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	g_object_unref (cancellable);
	if (progressbar != NULL)
		g_object_unref (progressbar);
	if (pack != NULL)
		g_object_unref (pack);
	if (client != NULL)
		g_object_unref (client);
	if (control != NULL)
		g_object_unref (control);
	g_free (tempdir);
	g_free (filename);
	g_free (package_id);
	g_free (directory);
	g_free (package_list);
	g_free (options_help);
	g_strfreev (excludes);
	return retval;
}
Example #11
0
static void
pragha_preferences_load_from_file(PraghaPreferences *preferences)
{
	gboolean approximate_search, instant_search;
	gboolean shuffle, repeat, use_hint, restore_playlist, software_mixer;
	gboolean lateral_panel, show_album_art, show_status_bar;
	gboolean add_recursively, timer_remaining_mode;
	gchar *audio_sink, *audio_device, *audio_cd_device;
	gint library_style, sidebar_size;
	gboolean fuse_folders, sort_by_year;
	const gchar *user_config_dir;
	gchar *pragha_config_dir = NULL;
	GError *error = NULL;
	PraghaPreferencesPrivate *priv = preferences->priv;

	/* First check preferences folder or create it */

	user_config_dir = g_get_user_config_dir();
	pragha_config_dir = g_build_path(G_DIR_SEPARATOR_S, user_config_dir, "/pragha", NULL);

	if (g_file_test(pragha_config_dir, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) == FALSE) {
		if (g_mkdir_with_parents (pragha_config_dir, S_IRWXU) == -1) {
			g_free(pragha_config_dir);
			g_critical("Unable to create preferences directory, err: %s", strerror(errno));
			return;
		}
		CDEBUG(DBG_INFO, "Created .config/pragha folder");
	}
	g_free(pragha_config_dir);

	/* Does /pragha/config exist ? */

	priv->rc_filepath = g_build_path(G_DIR_SEPARATOR_S, user_config_dir, "/pragha/config", NULL);

	if (g_file_test(priv->rc_filepath, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR) == FALSE) {
		if (g_creat(priv->rc_filepath, S_IRWXU) == -1) {
			g_free(priv->rc_filepath);
			priv->rc_filepath = NULL;
			g_critical("Unable to create config file, err: %s", strerror(errno));
			return;
		}
		CDEBUG(DBG_INFO, "Created .config/pragha/config file");
	}

	/* Open the preferences storage file */

	priv->rc_keyfile = g_key_file_new();

	if (!g_key_file_load_from_file(priv->rc_keyfile,
	                               priv->rc_filepath,
	                               G_KEY_FILE_NONE,
	                               &error)) {
		g_critical("Unable to load config file (Possible first start), err: %s", error->message);
		g_error_free(error);
		return;
	}

	/* Open last preferences */

	approximate_search = g_key_file_get_boolean(priv->rc_keyfile,
	                                            GROUP_GENERAL,
	                                            KEY_APPROXIMATE_SEARCH,
	                                            &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_approximate_search(preferences, approximate_search);
	}

	instant_search = g_key_file_get_boolean(priv->rc_keyfile,
	                                        GROUP_GENERAL,
	                                        KEY_INSTANT_SEARCH,
	                                        &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_instant_search(preferences, instant_search);
	}

	shuffle = g_key_file_get_boolean(priv->rc_keyfile,
	                                 GROUP_PLAYLIST,
	                                 KEY_SHUFFLE,
	                                 &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_shuffle(preferences, shuffle);
	}

	repeat = g_key_file_get_boolean(priv->rc_keyfile,
	                                GROUP_PLAYLIST,
	                                KEY_REPEAT,
	                                &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_repeat(preferences, repeat);
	}

	use_hint = g_key_file_get_boolean(priv->rc_keyfile,
	                                  GROUP_GENERAL,
	                                  KEY_USE_HINT,
	                                  &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_use_hint(preferences, use_hint);
	}

	library_style = g_key_file_get_integer(priv->rc_keyfile,
	                                       GROUP_LIBRARY,
	                                       KEY_LIBRARY_VIEW_ORDER,
	                                       &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_library_style(preferences, library_style);
	}

	sort_by_year = g_key_file_get_boolean(priv->rc_keyfile,
	                                      GROUP_LIBRARY,
	                                      KEY_SORT_BY_YEAR,
	                                      &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_sort_by_year(preferences, sort_by_year);
	}

	fuse_folders = g_key_file_get_boolean(priv->rc_keyfile,
	                                      GROUP_LIBRARY,
	                                      KEY_FUSE_FOLDERS,
	                                      &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_fuse_folders(preferences, fuse_folders);
	}

	restore_playlist = g_key_file_get_boolean(priv->rc_keyfile,
	                                          GROUP_PLAYLIST,
	                                          KEY_SAVE_PLAYLIST,
	                                          &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_restore_playlist(preferences, restore_playlist);
	}

	audio_sink = g_key_file_get_string(priv->rc_keyfile,
	                                   GROUP_AUDIO,
	                                   KEY_AUDIO_SINK,
	                                   &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_audio_sink(preferences, audio_sink);
	}

	audio_device = g_key_file_get_string(priv->rc_keyfile,
	                                     GROUP_AUDIO,
	                                     KEY_AUDIO_DEVICE,
	                                     &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_audio_device(preferences, audio_device);
	}

	software_mixer = g_key_file_get_boolean(priv->rc_keyfile,
	                                        GROUP_AUDIO,
	                                        KEY_SOFTWARE_MIXER,
	                                        &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_software_mixer(preferences, software_mixer);
	}

	audio_cd_device = g_key_file_get_string(priv->rc_keyfile,
	                                        GROUP_AUDIO,
	                                        KEY_AUDIO_CD_DEVICE,
	                                        &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_audio_cd_device(preferences, audio_cd_device);
	}

	lateral_panel = g_key_file_get_boolean(priv->rc_keyfile,
	                                       GROUP_WINDOW,
	                                       KEY_SIDEBAR,
	                                       &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_lateral_panel(preferences, lateral_panel);
	}

	sidebar_size = g_key_file_get_integer(priv->rc_keyfile,
	                                      GROUP_WINDOW,
	                                      KEY_SIDEBAR_SIZE,
	                                      &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_sidebar_size(preferences, sidebar_size);
	}

	show_album_art = g_key_file_get_boolean(priv->rc_keyfile,
	                                        GROUP_WINDOW,
	                                        KEY_SHOW_ALBUM_ART,
	                                        &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_show_album_art(preferences, show_album_art);
	}

	show_status_bar = g_key_file_get_boolean(priv->rc_keyfile,
	                                         GROUP_WINDOW,
	                                         KEY_STATUS_BAR,
	                                         &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_show_status_bar(preferences, show_status_bar);
	}

	add_recursively = g_key_file_get_boolean(priv->rc_keyfile,
	                                         GROUP_GENERAL,
	                                         KEY_ADD_RECURSIVELY_FILES,
	                                         &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_add_recursively(preferences, add_recursively);
	}

	timer_remaining_mode = g_key_file_get_boolean(priv->rc_keyfile,
	                                              GROUP_GENERAL,
	                                              KEY_TIMER_REMAINING_MODE,
	                                              &error);
	if (error) {
		g_error_free(error);
		error = NULL;
	}
	else {
		pragha_preferences_set_timer_remaining_mode(preferences, timer_remaining_mode);
	}

	g_free(audio_sink);
	g_free(audio_device);
	g_free(audio_cd_device);
}
Example #12
0
static void
restore (const gchar *filename,
         GCancellable *cancellable)
{
	gchar *command;
	gchar *quotedfname;
	gboolean is_new_format = FALSE;

	g_return_if_fail (filename && *filename);

	if (!check (filename, &is_new_format)) {
		g_message ("Cannot restore from an incorrect archive '%s'.", filename);
		goto end;
	}

	quotedfname = g_shell_quote (filename);

	if (g_cancellable_is_cancelled (cancellable))
		return;

	/* FIXME Will the versioned setting always work? */
	txt = _("Shutting down Evolution");
	run_cmd (EVOLUTION " --quit");

	if (g_cancellable_is_cancelled (cancellable))
		return;

	txt = _("Back up current Evolution data");
	run_cmd ("mv $DATADIR $DATADIR_old");
	run_cmd ("mv $CONFIGDIR $CONFIGDIR_old");
	run_cmd ("mv $HOME/.camel_certs $HOME/.camel_certs_old");

	if (g_cancellable_is_cancelled (cancellable))
		return;

	txt = _("Extracting files from back up");

	if (is_new_format) {
		GString *dir_fn;
		gchar *data_dir = NULL, *config_dir = NULL;

		command = g_strdup_printf (
			"cd $TMP && tar xzf %s "
			EVOLUTION_DIR_FILE, quotedfname);
		run_cmd (command);
		g_free (command);

		dir_fn = replace_variables ("$TMP" G_DIR_SEPARATOR_S EVOLUTION_DIR_FILE);
		if (!dir_fn) {
			g_warning ("Failed to create evolution's dir filename");
			goto end;
		}

		/* data_dir and config_dir are quoted inside extract_backup_dirs */
		extract_backup_dirs (dir_fn->str, &data_dir, &config_dir);

		g_unlink (dir_fn->str);
		g_string_free (dir_fn, TRUE);

		if (!data_dir || !config_dir) {
			g_warning ("Failed to get old data_dir (%p)/config_dir (%p)", data_dir, config_dir);
			g_free (data_dir);
			g_free (config_dir);
			goto end;
		}

		g_mkdir_with_parents (e_get_user_data_dir (), 0700);
		g_mkdir_with_parents (e_get_user_config_dir (), 0700);

		command = g_strdup_printf (
			"cd $DATADIR && tar xzf %s %s --strip-components=%d",
			quotedfname, data_dir, get_dir_level (data_dir));
		run_cmd (command);
		g_free (command);

		command = g_strdup_printf (
			"cd $CONFIGDIR && tar xzf %s %s --strip-components=%d",
			quotedfname, config_dir, get_dir_level (config_dir));
		run_cmd (command);
		g_free (command);

		command = g_strdup_printf (
			"cd $HOME && tar xzf %s .camel_certs", quotedfname);
		run_cmd (command);
		g_free (command);

		g_free (data_dir);
		g_free (config_dir);
	} else {
		run_cmd ("mv $HOME/.evolution $HOME/.evolution_old");

		command = g_strdup_printf (
			"cd $HOME && gzip -cd %s | tar xf -", quotedfname);
		run_cmd (command);
		g_free (command);
	}

	g_free (quotedfname);

	if (g_cancellable_is_cancelled (cancellable))
		return;

	txt = _("Loading Evolution settings");

	if (is_new_format) {
		/* new format has it in DATADIR... */
		replace_in_file (
			EVOLUTION_DIR GCONF_DUMP_FILE,
			EVOUSERDATADIR_MAGIC, e_get_user_data_dir ());
		run_cmd ("gconftool-2 --load " EVOLUTION_DIR GCONF_DUMP_FILE);
		run_cmd ("rm " EVOLUTION_DIR GCONF_DUMP_FILE);
	} else {
		gchar *gconf_dump_file;

		/* ... old format in ~/.evolution */
		gconf_dump_file = g_build_filename (
			"$HOME", ".evolution", GCONF_DUMP_FILE, NULL);

		replace_in_file (
			gconf_dump_file,
			EVOUSERDATADIR_MAGIC,
			e_get_user_data_dir ());

		command = g_strconcat (
			"gconftool-2 --load ", gconf_dump_file, NULL);
		run_cmd (command);
		g_free (command);

		command = g_strconcat ("rm ", gconf_dump_file, NULL);
		run_cmd (command);
		g_free (command);

		g_free (gconf_dump_file);
	}

	if (g_cancellable_is_cancelled (cancellable))
		return;

	txt = _("Removing temporary back up files");
	run_cmd ("rm -rf $DATADIR_old");
	run_cmd ("rm -rf $CONFIGDIR_old");
	run_cmd ("rm -rf $HOME/.camel_certs_old");
	run_cmd ("rm $DATADIR/.running");

	if (!is_new_format)
		run_cmd ("rm -rf $HOME/.evolution_old");

	if (g_cancellable_is_cancelled (cancellable))
		return;

	txt = _("Ensuring local sources");

end:
	if (restart_arg) {
		if (g_cancellable_is_cancelled (cancellable))
			return;

		txt = _("Restarting Evolution");
		run_evolution_no_wait ();
	}
}
Example #13
0
bool
ExtractAll (unzFile zip, const char *dir, CanonMode mode)
{
	char *filename, *dirname, *path, *altpath;
	char *canonicalized_filename;
	unz_file_info info;
	int fd;
	
	if (unzGoToFirstFile (zip) != UNZ_OK)
		return false;
	
	do {
		unzGetCurrentFileInfo (zip, &info, NULL, 0, NULL, 0, NULL, 0);
		if (info.external_fa & (1 << 4))
			continue;
		
		if (!(filename = (char *) g_malloc (info.size_filename + 1)))
			return false;
		
		unzGetCurrentFileInfo (zip, NULL, filename, info.size_filename + 1, NULL, 0, NULL, 0);
		
		canonicalized_filename = Deployment::GetCurrent ()->CanonicalizeFileName (filename, mode == CanonModeXap);
		
		path = g_build_filename (dir, canonicalized_filename, NULL);
		
		dirname = g_path_get_dirname (path);
		if (g_mkdir_with_parents (dirname, 0700) == -1 && errno != EEXIST) {
			g_free (filename);
			g_free (dirname);
			g_free (canonicalized_filename);
			g_free (path);
			return false;
		}
		
		g_free (dirname);
		
		if ((fd = g_open (path, O_CREAT | O_WRONLY | O_TRUNC, 0600)) == -1) {
			g_free (filename);
			g_free (canonicalized_filename);
			g_free (path);
			return false;
		}
		
		if (unzOpenCurrentFile (zip) != UNZ_OK) {
			g_free (filename);
			g_free (canonicalized_filename);
			g_free (path);
			close (fd);
			return false;
		}
		
		if (!ExtractFile (zip, fd)) {
			unzCloseCurrentFile (zip);
			g_free (filename);
			g_free (canonicalized_filename);
			g_free (path);
			return false;
		}
		
		unzCloseCurrentFile (zip);
		
		if (mode == CanonModeXap && is_dll_exe_or_mdb (filename, info.size_filename)) {
			g_free (canonicalized_filename);
			canonicalized_filename = Deployment::GetCurrent ()->CanonicalizeFileName (filename, false);
			altpath = g_build_filename (dir, canonicalized_filename, NULL);
			if (strcmp (path, altpath) != 0)
				symlink (path, altpath);
			g_free (altpath);
		}
		
		g_free (filename);
		g_free (canonicalized_filename);
		g_free (path);
	} while (unzGoToNextFile (zip) == UNZ_OK);
	
	return true;
}
Example #14
0
File: tls.c Project: GNOME/libepc
/**
 * epc_tls_private_key_save:
 * @key: a private X.509 key
 * @filename: name of a file to write the private key to, in the GLib file name encoding
 * @error: return location for a #GError, or %NULL
 *
 * Writes a PEM encoded private X.509 key.
 *
 * If the call was successful, it returns %TRUE. If the call was not
 * successful, it returns %FALSE and sets @error. The error domain is
 * #EPC_TLS_ERROR. Error codes are taken from the <citetitle>GNU
 * TLS</citetitle> library.
 *
 * Returns: %TRUE on successful, %FALSE if an error occured
 */
gboolean
epc_tls_private_key_save (gnutls_x509_privkey_t  key,
                          const gchar           *filename,
                          GError               **error)
{
  gint rc = GNUTLS_E_SUCCESS;
  gchar *display_name = NULL;
  guchar *contents = NULL;
  gchar *dirname = NULL;
  gsize length = 0;
  gint fd = -1;

  g_return_val_if_fail (NULL != key, FALSE);
  g_return_val_if_fail (NULL != filename, FALSE);

  if (EPC_DEBUG_LEVEL (1))
    g_debug ("%s: Writing server key `%s'", G_STRLOC, filename);

  rc = gnutls_x509_privkey_export (key, GNUTLS_X509_FMT_PEM, NULL, &length);
  g_assert (GNUTLS_E_SHORT_MEMORY_BUFFER == rc);

  contents = g_malloc (length);

  if (GNUTLS_E_SUCCESS != (rc =
      gnutls_x509_privkey_export (key, GNUTLS_X509_FMT_PEM, contents, &length)))
    {
      g_set_error (error, EPC_TLS_ERROR, rc,
                   _("Cannot export private key to PEM format: %s"),
                   gnutls_strerror (rc));

      goto out;
    }

  if (g_mkdir_with_parents (dirname = g_path_get_dirname (filename), 0700))
    {
      display_name = g_filename_display_name (dirname);
      rc = GNUTLS_E_FILE_ERROR;

      g_set_error (error,
                   G_FILE_ERROR,
                   g_file_error_from_errno (errno),
                   _("Failed to create private key folder '%s': %s"),
                   display_name, g_strerror (errno));

      goto out;
    }

  fd = g_open (filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);

  if (-1 == fd)
    {
      display_name = g_filename_display_name (filename);
      rc = GNUTLS_E_FILE_ERROR;

      g_set_error (error,
                   G_FILE_ERROR,
                   g_file_error_from_errno (errno),
                   _("Failed to create private key file '%s': %s"),
                   display_name, g_strerror (errno));

      goto out;
    }

  if (write (fd, contents, length) < (gssize)length)
    {
      display_name = g_filename_display_name (filename);
      rc = GNUTLS_E_FILE_ERROR;

      g_set_error (error,
                   G_FILE_ERROR,
                   g_file_error_from_errno (errno),
                   _("Failed to write private key file '%s': %s"),
                   display_name, g_strerror (errno));

      goto out;
    }

out:
  if (-1 != fd)
    close (fd);

  if (GNUTLS_E_SUCCESS != rc)
    g_unlink (filename);

  g_free (display_name);
  g_free (contents);
  g_free (dirname);

  return (GNUTLS_E_SUCCESS == rc);
}
Example #15
0
void
finalize_store(dt_imageio_module_storage_t *self, void *dd)
{
  dt_imageio_gallery_t *d = (dt_imageio_gallery_t *)dd;
  char filename[1024];
  snprintf(filename, 1024, "%s", d->cached_dirname);
  char *c = filename + strlen(filename);

  // also create style/ subdir:
  sprintf(c, "/style");
  g_mkdir_with_parents(filename, 0755);
  sprintf(c, "/style/style.css");
  copy_res("/style/style.css", filename);
  sprintf(c, "/style/favicon.ico");
  copy_res("/style/favicon.ico", filename);
  sprintf(c, "/style/bullet.gif");
  copy_res("/style/bullet.gif", filename);
  sprintf(c, "/style/close.gif");
  copy_res("/style/close.gif", filename);
  sprintf(c, "/style/closelabel.gif");
  copy_res("/style/closelabel.gif", filename);
  sprintf(c, "/style/donate-button.gif");
  copy_res("/style/donate-button.gif", filename);
  sprintf(c, "/style/download-icon.gif");
  copy_res("/style/download-icon.gif", filename);
  sprintf(c, "/style/image-1.jpg");
  copy_res("/style/image-1.jpg", filename);
  sprintf(c, "/style/lightbox.css");
  copy_res("/style/lightbox.css", filename);
  sprintf(c, "/style/loading.gif");
  copy_res("/style/loading.gif", filename);
  sprintf(c, "/style/nextlabel.gif");
  copy_res("/style/nextlabel.gif", filename);
  sprintf(c, "/style/prevlabel.gif");
  copy_res("/style/prevlabel.gif", filename);
  sprintf(c, "/style/thumb-1.jpg");
  copy_res("/style/thumb-1.jpg", filename);
  
  // create subdir   js for lightbox2 viewer scripts
  sprintf(c, "/js");
  g_mkdir_with_parents(filename, 0755);
  sprintf(c, "/js/builder.js");
  copy_res("/js/builder.js", filename);
  sprintf(c, "/js/effects.js");
  copy_res("/js/effects.js", filename);
  sprintf(c, "/js/lightbox.js");
  copy_res("/js/lightbox.js", filename);
  sprintf(c, "/js/lightbox-web.js");
  copy_res("/js/lightbox-web.js", filename);
  sprintf(c, "/js/prototype.js");
  copy_res("/js/prototype.js", filename);
  sprintf(c, "/js/scriptaculous.js");
  copy_res("/js/scriptaculous.js", filename);
  
  sprintf(c, "/index.html");

  const char *title = d->title;

  FILE *f = fopen(filename, "wb");
  if(!f) return;
  fprintf(f,
          "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
          "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
          "  <head>\n"
          "    <meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n"
          "    <link rel=\"shortcut icon\" href=\"style/favicon.ico\" />\n"
          "    <link rel=\"stylesheet\" href=\"style/style.css\" type=\"text/css\" />\n"
          "    <link rel=\"stylesheet\" href=\"style/lightbox.css\" type=\"text/css\" media=\"screen\" />"
          "    <script type=\"text/javascript\" src=\"js/prototype.js\"></script>\n"
          "    <script type=\"text/javascript\" src=\"js/scriptaculous.js?load=effects,builder\"></script>\n"
          "    <script type=\"text/javascript\" src=\"js/lightbox.js\"></script>\n"
          "    <title>%s</title>\n"
          "  </head>\n"
          "  <body>\n"
          "    <div class=\"title\">%s</div>\n"
          "    <div class=\"page\">\n",
          title, title);

  while(d->l)
  {
    pair_t *p = (pair_t *)d->l->data;
    fprintf(f, "%s", p->line);
    free(p);
    d->l = g_list_delete_link(d->l, d->l);
  }

  fprintf(f,
          "        <p style=\"clear:both;\"></p>\n"
          "    </div>\n"
          "    <div class=\"footer\">\n"
          "      <script language=\"JavaScript\" type=\"text/javascript\">\n"
          "      document.write(\"download all: <em>wget -r -np -nc -k \" + document.documentURI + \"</em>\")\n"
          "      </script><br />\n"
          "      created with darktable "PACKAGE_VERSION"\n"
          "    </div>\n"
          "  </body>\n"
          "</html>\n"
         );
  fclose(f);
}
static gboolean
shell_xdg_migrate_rename_files (const gchar *src_directory,
                                const gchar *dst_directory)
{
	GDir *dir;
	GHashTable *corrections;
	const gchar *basename;
	const gchar *home_dir;
	gchar *old_base_dir;
	gchar *new_base_dir;

	dir = g_dir_open (src_directory, 0, NULL);
	if (dir == NULL)
		return FALSE;

	/* This is to avoid renaming files which we're iterating over the
	 * directory.  POSIX says the outcome of that is unspecified. */
	corrections = g_hash_table_new_full (
		g_str_hash, g_str_equal,
		(GDestroyNotify) g_free,
		(GDestroyNotify) g_free);

	g_mkdir_with_parents (dst_directory, 0700);

	home_dir = g_get_home_dir ();
	old_base_dir = g_build_filename (home_dir, ".evolution", NULL);
	e_filename_make_safe (old_base_dir);
	new_base_dir = g_strdup (e_get_user_data_dir ());
	e_filename_make_safe (new_base_dir);

	while ((basename = g_dir_read_name (dir)) != NULL) {
		GString *buffer;
		gchar *old_filename;
		gchar *new_filename;
		gchar *cp;

		buffer = g_string_new (basename);

		if ((cp = strstr (basename, old_base_dir)) != NULL) {
			g_string_erase (
				buffer, cp - basename,
				strlen (old_base_dir));
			g_string_insert (
				buffer, cp - basename, new_base_dir);
		}

		old_filename = g_build_filename (
			src_directory, basename, NULL);
		new_filename = g_build_filename (
			dst_directory, buffer->str, NULL);

		g_string_free (buffer, TRUE);

		g_hash_table_insert (corrections, old_filename, new_filename);
	}

	g_free (old_base_dir);
	g_free (new_base_dir);

	g_dir_close (dir);

	shell_xdg_migrate_process_corrections (corrections);
	g_hash_table_destroy (corrections);

	/* It's tempting to want to remove the source directory here.
	 * Don't.  We might be iterating over the source directory's
	 * parent directory, and removing the source directory would
	 * screw up the iteration. */

	return TRUE;
}
Example #17
0
/*
 * main
 *
 */
int
main (int argc, char *argv[])
{
	gboolean wifi_enabled = TRUE, net_enabled = TRUE, wwan_enabled = TRUE;
	gboolean success = FALSE;
	NMConfig *config;
	GError *error = NULL;
	gboolean wrote_pidfile = FALSE;
	char *bad_domains = NULL;
	NMConfigCmdLineOptions *config_cli;

	nm_g_type_init ();

	/* Known to cause a possible deadlock upon GDBus initialization:
	 * https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
	g_type_ensure (G_TYPE_SOCKET);
	g_type_ensure (G_TYPE_DBUS_CONNECTION);
	g_type_ensure (NM_TYPE_BUS_MANAGER);

	_nm_utils_is_manager_process = TRUE;

	main_loop = g_main_loop_new (NULL, FALSE);

	config_cli = nm_config_cmd_line_options_new ();
	do_early_setup (&argc, &argv, config_cli);

	if (global_opt.g_fatal_warnings)
		_set_g_fatal_warnings ();

	if (global_opt.show_version) {
		fprintf (stdout, NM_DIST_VERSION "\n");
		exit (0);
	}

	nm_main_utils_ensure_root ();

	nm_main_utils_ensure_not_running_pidfile (global_opt.pidfile);

	/* Ensure state directory exists */
	if (g_mkdir_with_parents (NMSTATEDIR, 0755) != 0) {
		fprintf (stderr, "Cannot create '%s': %s", NMSTATEDIR, strerror (errno));
		exit (1);
	}

	nm_main_utils_ensure_rundir ();

	/* When running from the build directory, determine our build directory
	 * base and set helper paths in the build tree */
	if (global_opt.run_from_build_dir) {
		char *path, *slash;
		int g;

		/* exe is <basedir>/src/.libs/lt-NetworkManager, so chop off
		 * the last three components */
		path = realpath ("/proc/self/exe", NULL);
		g_assert (path != NULL);
		for (g = 0; g < 3; ++g) {
			slash = strrchr (path, '/');
			g_assert (slash != NULL);
			*slash = '\0';
		}

		/* don't free these strings, we need them for the entire
		 * process lifetime */
		nm_dhcp_helper_path = g_strdup_printf ("%s/src/dhcp-manager/nm-dhcp-helper", path);

		g_free (path);
	}

	if (!nm_logging_setup (global_opt.opt_log_level,
	                       global_opt.opt_log_domains,
	                       &bad_domains,
	                       &error)) {
		fprintf (stderr,
		         _("%s.  Please use --help to see a list of valid options.\n"),
		         error->message);
		exit (1);
	} else if (bad_domains) {
		fprintf (stderr,
		         _("Ignoring unrecognized log domain(s) '%s' passed on command line.\n"),
		         bad_domains);
		g_clear_pointer (&bad_domains, g_free);
	}

	/* Read the config file and CLI overrides */
	config = nm_config_setup (config_cli, NULL, &error);
	nm_config_cmd_line_options_free (config_cli);
	config_cli = NULL;
	if (config == NULL) {
		fprintf (stderr, _("Failed to read configuration: (%d) %s\n"),
		         error ? error->code : -1,
		         (error && error->message) ? error->message : _("unknown"));
		exit (1);
	}

	_init_nm_debug (nm_config_get_debug (config));

	/* Initialize logging from config file *only* if not explicitly
	 * specified by commandline.
	 */
	if (global_opt.opt_log_level == NULL && global_opt.opt_log_domains == NULL) {
		if (!nm_logging_setup (nm_config_get_log_level (config),
		                       nm_config_get_log_domains (config),
		                       &bad_domains,
		                       &error)) {
			fprintf (stderr, _("Error in configuration file: %s.\n"),
			         error->message);
			exit (1);
		} else if (bad_domains) {
			fprintf (stderr,
			         _("Ignoring unrecognized log domain(s) '%s' from config files.\n"),
			         bad_domains);
			g_clear_pointer (&bad_domains, g_free);
		}
	}

	if (global_opt.become_daemon && !nm_config_get_is_debug (config)) {
		if (daemon (0, 0) < 0) {
			int saved_errno;

			saved_errno = errno;
			fprintf (stderr, _("Could not daemonize: %s [error %u]\n"),
			         g_strerror (saved_errno),
			         saved_errno);
			exit (1);
		}
		wrote_pidfile = nm_main_utils_write_pidfile (global_opt.pidfile);
	}

	/* Set up unix signal handling - before creating threads, but after daemonizing! */
	nm_main_utils_setup_signals (main_loop);

	nm_logging_syslog_openlog (nm_config_get_is_debug (config)
	                           ? "debug"
	                           : nm_config_data_get_value_cached (NM_CONFIG_GET_DATA_ORIG,
	                                                              NM_CONFIG_KEYFILE_GROUP_LOGGING,
	                                                              NM_CONFIG_KEYFILE_KEY_LOGGING_BACKEND,
	                                                              NM_CONFIG_GET_VALUE_STRIP | NM_CONFIG_GET_VALUE_NO_EMPTY));

	nm_log_info (LOGD_CORE, "NetworkManager (version " NM_DIST_VERSION ") is starting...");

	/* Parse the state file */
	if (!parse_state_file (global_opt.state_file, &net_enabled, &wifi_enabled, &wwan_enabled, &error)) {
		nm_log_err (LOGD_CORE, "State file %s parsing failed: (%d) %s",
		            global_opt.state_file,
		            error ? error->code : -1,
		            (error && error->message) ? error->message : _("unknown"));
		/* Not a hard failure */
	}
	g_clear_error (&error);

	nm_log_info (LOGD_CORE, "Read config: %s", nm_config_data_get_config_description (nm_config_get_data (config)));
	nm_config_data_log (nm_config_get_data (config), "CONFIG: ");
	nm_log_dbg (LOGD_CORE, "WEXT support is %s",
#if HAVE_WEXT
	             "enabled"
#else
	             "disabled"
#endif
	             );

	nm_auth_manager_setup (nm_config_get_auth_polkit (config));

	nm_manager_setup (global_opt.state_file,
	                  net_enabled,
	                  wifi_enabled,
	                  wwan_enabled);

	if (!nm_bus_manager_get_connection (nm_bus_manager_get ())) {
		nm_log_warn (LOGD_CORE, "Failed to connect to D-Bus; only private bus is available");
	} else {
		/* Start our DBus service */
		if (!nm_bus_manager_start_service (nm_bus_manager_get ())) {
			nm_log_err (LOGD_CORE, "failed to start the dbus service.");
			goto done;
		}
	}

	/* Set up platform interaction layer */
	nm_linux_platform_setup ();

	NM_UTILS_KEEP_ALIVE (config, NM_PLATFORM_GET, "NMConfig-depends-on-NMPlatform");

	nm_dispatcher_init ();

	g_signal_connect (nm_manager_get (), NM_MANAGER_CONFIGURE_QUIT, G_CALLBACK (manager_configure_quit), config);

	if (!nm_manager_start (nm_manager_get (), &error)) {
		nm_log_err (LOGD_CORE, "failed to initialize: %s", error->message);
		goto done;
	}

	/* Make sure the loopback interface is up. If interface is down, we bring
	 * it up and kernel will assign it link-local IPv4 and IPv6 addresses. If
	 * it was already up, we assume is in clean state.
	 *
	 * TODO: it might be desirable to check the list of addresses and compare
	 * it with a list of expected addresses (one of the protocol families
	 * could be disabled). The 'lo' interface is sometimes used for assigning
	 * global addresses so their availability doesn't depend on the state of
	 * physical interfaces.
	 */
	nm_log_dbg (LOGD_CORE, "setting up local loopback");
	nm_platform_link_set_up (NM_PLATFORM_GET, 1, NULL);

	success = TRUE;

	if (configure_and_quit == FALSE)
		g_main_loop_run (main_loop);

	nm_manager_stop (nm_manager_get ());

done:
	if (global_opt.pidfile && wrote_pidfile)
		unlink (global_opt.pidfile);

	nm_log_info (LOGD_CORE, "exiting (%s)", success ? "success" : "error");
	exit (success ? 0 : 1);
}
static void
shell_xdg_migrate_config_dir_common (EShell *shell,
                                     const gchar *old_base_dir,
                                     const gchar *backend_name)
{
	GDir *dir;
	const gchar *user_config_dir;
	gchar *old_config_dir;
	gchar *new_config_dir;
	gchar *old_filename;
	gchar *new_filename;
	gchar *dirname;

	user_config_dir = e_get_user_config_dir ();

	old_config_dir = g_build_filename (old_base_dir, backend_name, NULL);
	new_config_dir = g_build_filename (user_config_dir, backend_name, NULL);

	g_mkdir_with_parents (new_config_dir, 0700);

	old_filename = g_build_filename (old_config_dir, "views", NULL);
	new_filename = g_build_filename (new_config_dir, "views", NULL);
	shell_xdg_migrate_rename_files (old_filename, new_filename);
	g_free (old_filename);
	g_free (new_filename);

	old_filename = g_build_filename (old_config_dir, "searches.xml", NULL);
	new_filename = g_build_filename (new_config_dir, "searches.xml", NULL);
	shell_xdg_migrate_rename (old_filename, new_filename);
	g_free (old_filename);
	g_free (new_filename);

	/* This one only occurs in calendar and memos.
	 * For other backends this will just be a no-op. */
	old_filename = g_build_filename (
		old_config_dir, "config", "MemoPad", NULL);
	new_filename = g_build_filename (new_config_dir, "MemoPad", NULL);
	shell_xdg_migrate_rename (old_filename, new_filename);
	g_free (old_filename);
	g_free (new_filename);

	/* This one only occurs in calendar and tasks.
	 * For other backends this will just be a no-op. */
	old_filename = g_build_filename (
		old_config_dir, "config", "TaskPad", NULL);
	new_filename = g_build_filename (new_config_dir, "TaskPad", NULL);
	shell_xdg_migrate_rename (old_filename, new_filename);
	g_free (old_filename);
	g_free (new_filename);

	/* Subtle name change: config/state --> state.ini */
	old_filename = g_build_filename (old_config_dir, "config", "state", NULL);
	new_filename = g_build_filename (new_config_dir, "state.ini", NULL);
	shell_xdg_migrate_rename (old_filename, new_filename);
	g_free (old_filename);
	g_free (new_filename);

	/* GIO had a bug for awhile where it would leave behind an empty
	 * temp file with the pattern .goutputstream-XXXXXX if an output
	 * stream operation was cancelled.  We've had several reports of
	 * these files in config directories, so remove any we find. */
	dirname = g_build_filename (old_config_dir, "config", NULL);
	dir = g_dir_open (dirname, 0, NULL);
	if (dir != NULL) {
		const gchar *basename;

		while ((basename = g_dir_read_name (dir)) != NULL) {
			gchar *filename;
			struct stat st;

			if (!g_str_has_prefix (basename, ".goutputstream"))
				continue;

			filename = g_build_filename (dirname, basename, NULL);

			/* Verify the file is indeed empty. */
			if (g_stat (filename, &st) == 0 && st.st_size == 0)
				g_unlink (filename);

			g_free (filename);
		}

		g_dir_close (dir);
	}
	g_free (dirname);

	g_free (old_config_dir);
	g_free (new_config_dir);
}
Example #19
0
/********************************
* EntityCompiler_PawnScript
* compiles entity file
@ string_inputfile
- returns XML error handling
*/
gchar * EntityCompiler_PawnScript( gchar * input_file, gchar * temporary_filepath  )
{
	GError * err = NULL;
	gint exit_status;

	gchar * entity_file = NULL, * compiled_entity_file = NULL;
	gchar * working_directory = NULL;
	gchar * full_output_directory = NULL;

	gchar * args[6] = { NULL, NULL, NULL, NULL, NULL, NULL };
	gchar * output = NULL;
	gchar * output_error = NULL;

	full_output_directory = g_build_path( "/", AL_ProjectPath(), "c", g_path_get_dirname(input_file), NULL);

	g_mkdir_with_parents( full_output_directory, 0755 );

	#ifdef apple
	working_directory = Meg_Directory();
	#endif

	args[0] = g_build_filename( Meg_Directory(), PAWN_COMPILER, NULL );
	args[1] = g_strconcat( AL_ProjectPath(), input_file, NULL );
	args[2] = g_strdup( "--xmloutput");
	args[3] = g_strconcat( "--project=", AL_ProjectPath(), NULL );

	if ( temporary_filepath )
		args[4] = g_strconcat( "--temporary=", temporary_filepath,  NULL );
	else
		args[4] = g_strdup( "--notemporary" );

	if ( !g_spawn_sync( working_directory, //working_directory
		args, //gchar **argv,
		NULL, //gchar **envp,
		G_SPAWN_SEARCH_PATH, //GSpawnFlags flags,
		NULL, //GSpawnChildSetupFunc child_setup,
		NULL, //gpointer user_data,
		&output, //gchar **standard_output,
		&output_error, //gchar **standard_error,
		&exit_status, //gint *exit_status,
		&err //GError **error
	))
	{
		output = g_strdup_printf("<results><fatalerror message=\"%s\" file=\"%s\" /></results>", g_markup_escape_text(err->message, -1), args[0] );
		g_clear_error(&err);
	}

	if ( exit_status && !output )
	{
		output = g_strdup_printf("<results><fatalerror message=\"Possible Compiler Crash.\" file=\"%s\" /></results>", args[0] );
	}

	g_free(full_output_directory);

	g_free(args[0]);
	g_free(args[1]);
	g_free(args[2]);
	g_free(args[3]);
	g_free(args[4]);

	/* Check if compiler left an empty file */
	entity_file = g_build_filename( AL_ProjectPath(), "c", input_file, NULL);
	compiled_entity_file = Meg_String_ReplaceFileExtension( entity_file, ".mps", ".amx" );
	if ( file_get_size( compiled_entity_file ) == 0 )
	{
		g_unlink(compiled_entity_file);
	}
	g_free(compiled_entity_file);
	g_free(entity_file);



	return output;
}
Example #20
0
// main function
int main(int argc, char *argv[]) {
	gboolean show_version = FALSE;
	gboolean log_info = FALSE;
	gboolean log_debug = FALSE;
	gboolean no_daemon = FALSE;
	gboolean test_mode = FALSE;
	gint poll_interval = -1;
	gboolean success;
	GOptionContext *opt_ctx;

	thd_daemonize = TRUE;
	dbus_enable = FALSE;

	GOptionEntry options[] = { { "version", 0, 0, G_OPTION_ARG_NONE,
			&show_version, N_("Print thermald version and exit"), NULL }, {
			"no-daemon", 0, 0, G_OPTION_ARG_NONE, &no_daemon, N_(
					"Don't become a daemon: Default is daemon mode"), NULL }, {
			"loglevel=info", 0, 0, G_OPTION_ARG_NONE, &log_info, N_(
					"log severity: info level and up"), NULL }, {
			"loglevel=debug", 0, 0, G_OPTION_ARG_NONE, &log_debug, N_(
					"log severity: debug level and up: Max logging"), NULL }, {
			"test-mode", 0, 0, G_OPTION_ARG_NONE, &test_mode, N_(
					"Test Mode only: Allow non root user"), NULL }, {
			"poll-interval", 0, 0, G_OPTION_ARG_INT, &poll_interval,
			N_("Poll interval in seconds: Poll for zone temperature changes. "
					"If want to disable polling set to zero."), NULL }, {
			"dbus-enable", 0, 0, G_OPTION_ARG_NONE, &dbus_enable, N_(
					"Enable Dbus."), NULL }, { "exclusive-control", 0, 0,
			G_OPTION_ARG_NONE, &exclusive_control, N_(
					"Take over thermal control from kernel thermal driver."),
			NULL }, { "ingore-cpuid-check", 0, 0, G_OPTION_ARG_NONE,
			&ignore_cpuid_check, N_("Ignore CPU ID check."), NULL },

	{ NULL } };

	if (!g_module_supported()) {
		fprintf(stderr, _("GModules are not supported on your platform!\n"));
		exit(1);
	}

	/* Set locale to be able to use environment variables */
	setlocale(LC_ALL, "");

	bindtextdomain(GETTEXT_PACKAGE, TDLOCALEDIR);
	bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
	textdomain(GETTEXT_PACKAGE);
	/* Parse options */
	opt_ctx = g_option_context_new(NULL);
	g_option_context_set_translation_domain(opt_ctx, GETTEXT_PACKAGE);
	g_option_context_set_ignore_unknown_options(opt_ctx, FALSE);
	g_option_context_set_help_enabled(opt_ctx, TRUE);
	g_option_context_add_main_entries(opt_ctx, options, NULL);

	g_option_context_set_summary(opt_ctx,
			_(
					"Thermal daemon monitors temperature sensors and decides the best action "
							"based on the temperature readings and user preferences."));

	success = g_option_context_parse(opt_ctx, &argc, &argv, NULL);
	g_option_context_free(opt_ctx);

	if (!success) {
		fprintf(stderr,
				_(
						"Invalid option.  Please use --help to see a list of valid options.\n"));
		exit(1);
	}

	if (show_version) {
		fprintf(stdout, TD_DIST_VERSION "\n");
		exit(0);
	}

	if (getuid() != 0 && !test_mode) {
		fprintf(stderr, _("You must be root to run thermald!\n"));
		exit(1);
	}
	if (g_mkdir_with_parents(TDRUNDIR, 0755) != 0) {
		fprintf(stderr, "Cannot create '%s': %s", TDRUNDIR, strerror(errno));
		exit(1);
	}
	g_mkdir_with_parents(TDCONFDIR, 0755); // Don't care return value as directory
	// may already exist
	if (log_info) {
		thd_log_level |= G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO;
	}
	if (log_debug) {
		thd_log_level |= G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO
				| G_LOG_LEVEL_DEBUG;
	}
	if (poll_interval >= 0) {
		fprintf(stdout, "Polling enabled: %d\n", poll_interval);
		thd_poll_interval = poll_interval;
	}

	openlog("thermald", LOG_PID, LOG_USER | LOG_DAEMON | LOG_SYSLOG);
	// Don't care return val
	//setlogmask(LOG_CRIT | LOG_ERR | LOG_WARNING | LOG_NOTICE | LOG_DEBUG | LOG_INFO);
	thd_daemonize = !no_daemon;
	g_log_set_handler(NULL, G_LOG_LEVEL_MASK, thd_logger, NULL);

	if (no_daemon)
		signal(SIGINT, sig_int_handler);

	// dbus glib processing begin
	thd_dbus_server_proc(no_daemon);

	fprintf(stdout, "Exiting ..\n");
	closelog();
}
static void
test_ontology_change (void)
{
    gchar *ontology_file;
    GFile *file2;
    gchar *prefix, *build_prefix;
    gchar *ontology_dir;
    guint i;
    GError *error = NULL;
    gchar *test_schemas[5] = { NULL, NULL, NULL, NULL, NULL };

    delete_db (TRUE);

    prefix = g_build_path (G_DIR_SEPARATOR_S, TOP_SRCDIR, "tests", "libtracker-data", NULL);
    build_prefix = g_build_path (G_DIR_SEPARATOR_S, TOP_BUILDDIR, "tests", "libtracker-data", NULL);

    test_schemas[0] = g_build_path (G_DIR_SEPARATOR_S, prefix, "ontologies", "20-dc", NULL);
    test_schemas[1] = g_build_path (G_DIR_SEPARATOR_S, prefix, "ontologies", "31-nao", NULL);
    test_schemas[2] = g_build_path (G_DIR_SEPARATOR_S, prefix, "ontologies", "90-tracker", NULL);
    test_schemas[3] = g_build_path (G_DIR_SEPARATOR_S, build_prefix, "change", "ontologies", "99-example", NULL);

    ontology_file = g_build_path (G_DIR_SEPARATOR_S, build_prefix, "change", "ontologies", "99-example.ontology", NULL);

    file2 = g_file_new_for_path (ontology_file);

    g_file_delete (file2, NULL, NULL);

    ontology_dir = g_build_path (G_DIR_SEPARATOR_S, build_prefix, "change", "ontologies", NULL);
    g_mkdir_with_parents (ontology_dir, 0777);
    g_free (ontology_dir);

    for (i = 0; changes[i].ontology; i++) {
        GFile *file1;
        gchar *queries = NULL;
        gchar *source = g_build_path (G_DIR_SEPARATOR_S, prefix, "change", "source", changes[i].ontology, NULL);
        gchar *update = g_build_path (G_DIR_SEPARATOR_S, prefix, "change", "updates", changes[i].update, NULL);
        gchar *from, *to;

        file1 = g_file_new_for_path (source);

        from = g_file_get_path (file1);
        to = g_file_get_path (file2);
        g_debug ("copy %s to %s", from, to);
        g_free (from);
        g_free (to);

        g_file_copy (file1, file2, G_FILE_COPY_OVERWRITE, NULL, NULL, NULL, &error);

        g_assert_no_error (error);
        g_chmod (ontology_file, 0666);

        tracker_data_manager_init (0, (const gchar **) test_schemas,
                                   NULL, FALSE, FALSE,
                                   100, 100, NULL, NULL, NULL, &error);

        g_assert_no_error (error);

        if (g_file_get_contents (update, &queries, NULL, NULL)) {
            gchar *query = strtok (queries, "\n");
            while (query) {

                tracker_data_update_sparql (query, &error);

                g_assert_no_error (error);
                query = strtok (NULL, "\n");
            }
            g_free (queries);
        }

        g_free (update);
        g_free (source);
        g_object_unref (file1);


        if (changes[i].test_name) {
            gchar *query_filename;
            gchar *results_filename;
            gchar *test_prefix;

            test_prefix = g_build_filename (prefix, changes[i].test_name, NULL);
            query_filename = g_strconcat (test_prefix, ".rq", NULL);
            results_filename = g_strconcat (test_prefix, ".out", NULL);

            query_helper (query_filename, results_filename);

            g_free (test_prefix);
            g_free (query_filename);
            g_free (results_filename);
        }

        tracker_data_manager_shutdown ();
    }

    delete_db (FALSE);

    tracker_data_manager_init (0, (const gchar **) test_schemas,
                               NULL, TRUE, FALSE,
                               100, 100, NULL, NULL, NULL, &error);

    g_assert_no_error (error);

    for (i = 0; change_tests[i].test_name != NULL; i++) {
        gchar *query_filename;
        gchar *results_filename;
        gchar *test_prefix;

        test_prefix = g_build_filename (prefix, change_tests[i].test_name, NULL);
        query_filename = g_strconcat (test_prefix, ".rq", NULL);
        results_filename = g_strconcat (test_prefix, ".out", NULL);

        query_helper (query_filename, results_filename);

        g_free (test_prefix);
        g_free (query_filename);
        g_free (results_filename);
    }

    tracker_data_manager_shutdown ();

    g_file_delete (file2, NULL, NULL);

    g_object_unref (file2);
    g_free (test_schemas[0]);
    g_free (test_schemas[1]);
    g_free (test_schemas[2]);
    g_free (build_prefix);
    g_free (prefix);
}
Example #22
0
AppDirs::AppDirs(const std::string& dirs_config_file)
{
#ifdef _WIN32
	std::string t_path;
#endif
	std::string l_dirs_config_file = get_dirs_config_file(dirs_config_file);
#ifdef _WIN32
	if(abs_path_to_app_dir(l_dirs_config_file, t_path)) {
		g_error(_("Unable to resolve StarDict directories config file: %s."), 
			l_dirs_config_file.c_str());
	}
	l_dirs_config_file = t_path;
#endif
	AppDirsConf app_conf;
	app_conf.load(l_dirs_config_file);

	std::string path;

	path = app_conf.get_string_at("user_config_dir");
	user_config_dir = path.empty() ? get_default_user_config_dir() : path;
#ifdef _WIN32
	if(abs_path_to_app_dir(user_config_dir, t_path)) {
		g_error(_("Unable to resolve user config directory: %s."), 
			user_config_dir.c_str());
	}
	user_config_dir = t_path;
#endif
	if (!g_file_test(user_config_dir.c_str(), G_FILE_TEST_IS_DIR)) {
		if (-1 == g_mkdir_with_parents(user_config_dir.c_str(), S_IRWXU))
			g_warning(_("Cannot create user config directory %s."), 
				user_config_dir.c_str());
	}

	path = app_conf.get_string_at("user_cache_dir");
	user_cache_dir = path.empty() ? get_default_user_cache_dir() : path;
#ifdef _WIN32
	if(abs_path_to_app_dir(user_cache_dir, t_path)) {
		g_error(_("Unable to resolve user cache directory: %s."), 
			user_cache_dir.c_str());
	}
	user_cache_dir = t_path;
#endif

	path = app_conf.get_string_at("data_dir");
	data_dir = path.empty() ? get_default_data_dir() : path;
#ifdef _WIN32
	if(abs_path_to_app_dir(data_dir, t_path)) {
		g_error(_("Unable to resolve data directory: %s."), 
			data_dir.c_str());
	}
	data_dir = t_path;
#endif

	path = app_conf.get_string_at("log_dir");
	log_dir = path.empty() ? get_default_log_dir() : path;
#ifdef _WIN32
	if(abs_path_to_app_dir(log_dir, t_path)) {
		g_error(_("Unable to resolve log directory: %s."), 
			log_dir.c_str());
	}
	log_dir = t_path;
#endif
	if(!g_file_test(log_dir.c_str(), G_FILE_TEST_IS_DIR))
		if(-1 == g_mkdir_with_parents(log_dir.c_str(), S_IRWXU))
			g_warning(_("Cannot create log directory %s."), log_dir.c_str());

#ifdef _WIN32
	path = app_conf.get_string_at("dll_dir");
	dll_dir = path.empty() ? data_dir : path;
	if(abs_path_to_app_dir(dll_dir, t_path)) {
		g_error(_("Unable to resolve DLL directory: %s."), 
			dll_dir.c_str());
	}
	dll_dir = t_path;
#endif
	path = app_conf.get_string_at("plugin_dir");
	plugin_dir = path.empty() ? get_default_plugin_dir() : path;
#ifdef _WIN32
	if(abs_path_to_app_dir(plugin_dir, t_path)) {
		g_error(_("Unable to resolve plugin directory: %s."), 
			plugin_dir.c_str());
	}
	plugin_dir = t_path;
#endif
#ifndef CONFIG_GNOME
	path = app_conf.get_string_at("help_dir");
	help_dir = path.empty() ? get_default_help_dir() : path;
#endif
	locale_dir = get_default_locale_dir();
#ifdef _WIN32
	if(abs_path_to_app_dir(locale_dir, t_path)) {
		g_error(_("Unable to resolve locale directory: %s."), 
			locale_dir.c_str());
	}
	locale_dir = t_path;
#endif
}
static void
backgrounds_changed_cb (GtkIconView       *icon_view,
                        CcBackgroundPanel *panel)
{
  GtkTreeIter iter;
  GtkTreeModel *model;
  CcBackgroundItem *item;
  CcBackgroundPanelPrivate *priv = panel->priv;
  char *pcolor, *scolor;
  gboolean draw_preview = TRUE;
  const char *uri;
  CcBackgroundItemFlags flags;
  char *filename;

  item = get_selected_item (panel);

  if (item == NULL)
    return;

  /* Update current source */
  model = gtk_combo_box_get_model (GTK_COMBO_BOX (WID ("sources-combobox")));
  gtk_combo_box_get_active_iter (GTK_COMBO_BOX (WID ("sources-combobox")),
                                 &iter);
  gtk_tree_model_get (model, &iter,
		      COL_SOURCE_TYPE, &priv->current_source, -1);

  uri = cc_background_item_get_uri (item);
  flags = cc_background_item_get_flags (item);

  if ((flags & CC_BACKGROUND_ITEM_HAS_URI) && uri == NULL)
    {
      g_settings_set_enum (priv->settings, WP_OPTIONS_KEY, G_DESKTOP_BACKGROUND_STYLE_NONE);
      g_settings_set_string (priv->settings, WP_URI_KEY, "");
    }
  else if (cc_background_item_get_source_url (item) != NULL &&
	   cc_background_item_get_needs_download (item))
    {
      GFile *source, *dest;
      gchar *cache_path, *basename, *dest_path, *display_name, *dest_uri;
      GdkPixbuf *pixbuf;

      cache_path = bg_pictures_source_get_cache_path ();
      if (g_mkdir_with_parents (cache_path, 0755) < 0)
        {
          g_warning ("Failed to create directory '%s'", cache_path);
          g_free (cache_path);
          return;
	}
      g_free (cache_path);

      dest_path = bg_pictures_source_get_unique_path (cc_background_item_get_source_url (item));
      dest = g_file_new_for_path (dest_path);
      g_free (dest_path);
      source = g_file_new_for_uri (cc_background_item_get_source_url (item));
      basename = g_file_get_basename (source);
      display_name = g_filename_display_name (basename);
      dest_path = g_file_get_path (dest);
      g_free (basename);

      /* create a blank image to use until the source image is ready */
      pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, 1, 1);
      gdk_pixbuf_fill (pixbuf, 0x00000000);
      gdk_pixbuf_save (pixbuf, dest_path, "png", NULL, NULL);
      g_object_unref (pixbuf);
      g_free (dest_path);

      if (priv->copy_cancellable)
        {
          g_cancellable_cancel (priv->copy_cancellable);
          g_cancellable_reset (priv->copy_cancellable);
        }

      if (priv->spinner)
        {
          gtk_widget_destroy (GTK_WIDGET (priv->spinner));
          priv->spinner = NULL;
        }

      /* create a spinner while the file downloads */
      priv->spinner = gtk_spinner_new ();
      gtk_spinner_start (GTK_SPINNER (priv->spinner));
      gtk_box_pack_start (GTK_BOX (WID ("bottom-hbox")), priv->spinner, FALSE,
                          FALSE, 6);
      gtk_widget_show (priv->spinner);

      /* reference the panel in case it is removed before the copy is
       * finished */
      g_object_ref (panel);
      g_object_set_data_full (G_OBJECT (source), "item", g_object_ref (item), g_object_unref);
      g_file_copy_async (source, dest, G_FILE_COPY_OVERWRITE,
                         G_PRIORITY_DEFAULT, priv->copy_cancellable,
                         NULL, NULL,
                         copy_finished_cb, panel);
      g_object_unref (source);
      dest_uri = g_file_get_uri (dest);
      g_object_unref (dest);

      g_settings_set_string (priv->settings, WP_URI_KEY, dest_uri);
      g_object_set (G_OBJECT (item),
		    "uri", dest_uri,
		    "needs-download", FALSE,
		    "name", display_name,
		    NULL);
      g_free (display_name);
      g_free (dest_uri);

      /* delay the updated drawing of the preview until the copy finishes */
      draw_preview = FALSE;
    }
  else
    {
      g_settings_set_string (priv->settings, WP_URI_KEY, uri);
    }

  /* Also set the placement if we have a URI and the previous value was none */
  if (flags & CC_BACKGROUND_ITEM_HAS_PLACEMENT)
    {
      g_settings_set_enum (priv->settings, WP_OPTIONS_KEY, cc_background_item_get_placement (item));
    }
  else if (uri != NULL)
    {
      GDesktopBackgroundStyle style;
      style = g_settings_get_enum (priv->settings, WP_OPTIONS_KEY);
      if (style == G_DESKTOP_BACKGROUND_STYLE_NONE)
        g_settings_set_enum (priv->settings, WP_OPTIONS_KEY, cc_background_item_get_placement (item));
    }

  if (flags & CC_BACKGROUND_ITEM_HAS_SHADING)
    g_settings_set_enum (priv->settings, WP_SHADING_KEY, cc_background_item_get_shading (item));

  /* When changing to a background with colours set,
   * don't overwrite what's in GSettings, but read
   * from it instead.
   * We have a hack for the colors source though */
  if (flags & CC_BACKGROUND_ITEM_HAS_PCOLOR &&
      priv->current_source != SOURCE_COLORS)
    {
      g_settings_set_string (priv->settings, WP_PCOLOR_KEY, cc_background_item_get_pcolor (item));
    }
  else
    {
      pcolor = g_settings_get_string (priv->settings, WP_PCOLOR_KEY);
      g_object_set (G_OBJECT (item), "primary-color", pcolor, NULL);
    }

  if (flags & CC_BACKGROUND_ITEM_HAS_SCOLOR &&
      priv->current_source != SOURCE_COLORS)
    {
      g_settings_set_string (priv->settings, WP_SCOLOR_KEY, cc_background_item_get_scolor (item));
    }
  else
    {
      scolor = g_settings_get_string (priv->settings, WP_SCOLOR_KEY);
      g_object_set (G_OBJECT (item), "secondary-color", scolor, NULL);
    }

  /* Apply all changes */
  g_settings_apply (priv->settings);

  update_remove_button (panel, item);

  /* update the preview information */
  if (draw_preview != FALSE)
    {
      update_preview (priv, item);

      /* Save the source XML if there is one */
      filename = get_save_path ();
      if (create_save_dir ())
        cc_background_xml_save (priv->current_background, filename);
    }
}
Example #24
0
/**
 * cheese_fileutil_get_new_media_filename:
 * @fileutil: a #CheeseFileUtil
 * @mode: the type of media to create a filename for
 *
 * Creates a filename for one of the three media types: photo, photo burst or
 * video. If a filename for a photo burst image was previously created, this
 * function increments the burst count automatically. To start a new burst,
 * first call cheese_fileutil_reset_burst().
 *
 * Returns: (transfer full) (type filename): a new filename
 */
gchar *
cheese_fileutil_get_new_media_filename (CheeseFileUtil *fileutil, CheeseMediaMode mode)
{
  GDateTime *datetime;
  gchar       *time_string;
  const gchar *path;
  gchar       *filename;
  GFile       *file;
  guint        num;
  CheeseFileUtilPrivate *priv;

  g_return_val_if_fail (CHEESE_IS_FILEUTIL (fileutil), NULL);

  priv = fileutil->priv;

  datetime = g_date_time_new_now_local ();

  g_assert (datetime != NULL);

  time_string = g_date_time_format (datetime, "%F-%H%M%S");
  g_date_time_unref (datetime);

  g_assert (time_string != NULL);

  switch (mode)
  {
    case CHEESE_MEDIA_MODE_PHOTO:
    case CHEESE_MEDIA_MODE_BURST:
      path = cheese_fileutil_get_photo_path (fileutil);
      break;
    case CHEESE_MEDIA_MODE_VIDEO:
      path = cheese_fileutil_get_video_path (fileutil);
      break;
    default:
      g_assert_not_reached ();
  }

  g_mkdir_with_parents (path, 0775);

  switch (mode)
  {
    case CHEESE_MEDIA_MODE_PHOTO:
      filename = g_strdup_printf ("%s%s%s%s", path, G_DIR_SEPARATOR_S, time_string, CHEESE_PHOTO_NAME_SUFFIX);
      break;
    case CHEESE_MEDIA_MODE_BURST:
      priv->burst_count++;
      if (strlen (priv->burst_raw_name) == 0)
        priv->burst_raw_name = g_strdup_printf ("%s%s%s", path, G_DIR_SEPARATOR_S, time_string);

      filename = g_strdup_printf ("%s_%d%s", priv->burst_raw_name, priv->burst_count, CHEESE_PHOTO_NAME_SUFFIX);
      break;
    case CHEESE_MEDIA_MODE_VIDEO:
      filename = g_strdup_printf ("%s%s%s%s", path, G_DIR_SEPARATOR_S, time_string, CHEESE_VIDEO_NAME_SUFFIX);
      break;
    default:
      g_assert_not_reached ();
  }

  file = g_file_new_for_path (filename);
  num = 0;

  while (g_file_query_exists (file, NULL))
  {
    num++;

    g_object_unref (file);
    g_free (filename);

    switch (mode)
    {
      case CHEESE_MEDIA_MODE_PHOTO:
        filename = g_strdup_printf ("%s%s%s (%d)%s", path, G_DIR_SEPARATOR_S, time_string, num, CHEESE_PHOTO_NAME_SUFFIX);
        break;
      case CHEESE_MEDIA_MODE_BURST:
        filename = g_strdup_printf ("%s_%d (%d)%s", priv->burst_raw_name, priv->burst_count, num, CHEESE_PHOTO_NAME_SUFFIX);
        break;
      case CHEESE_MEDIA_MODE_VIDEO:
        filename = g_strdup_printf ("%s%s%s (%d)%s", path, G_DIR_SEPARATOR_S, time_string, num, CHEESE_VIDEO_NAME_SUFFIX);
        break;
      default:
        g_assert_not_reached ();
    }

    file = g_file_new_for_path (filename);
  }

  g_free (time_string);
  g_object_unref (file);

  return filename;
}
Example #25
0
/**
 * pkgen_make_template:
 */
static gint
pkgen_make_template (const gchar *dir)
{
	gint res = 0;
	gchar *res_dir = NULL;
	gchar *tmp;
	gchar *fname;
	gboolean appstream_linked = FALSE;
	GError *error = NULL;

	if (dir == NULL) {
		tmp = g_get_current_dir ();
		res_dir = g_build_filename (tmp, "pkginstall", NULL);
		g_free (tmp);
	} else {
		res_dir = g_strdup (dir);
	}

	g_mkdir_with_parents (res_dir, 0755);

	g_print (_("Do you have an AppStream XML file for your software? [y/N]"));
	tmp = li_get_stdin ();
	if (tmp != NULL) {
		gchar *str;
		str = g_utf8_strdown (tmp, -1);
		g_free (tmp);
		g_strstrip (str);

		if (g_strcmp0 (str, "y") == 0) {
			g_print ("%s ", _("Please specify a path to the AppStream XML data:"));
			tmp = li_get_stdin ();
			if (tmp != NULL) {
				gchar *asfile;
				asfile = g_build_filename (res_dir, "metainfo.xml", NULL);
				/* TODO: create relative symlink */
				symlink (tmp, asfile);
				g_free (tmp);
				appstream_linked = TRUE;
			} else {
				res = 1;
				g_print ("%s\n", _("No path given. Exiting."));
				g_free (str);
				goto out;
			}
		}
		g_free (str);
    }

    if (!appstream_linked) {
		AsComponent *cpt;
		gchar *asfile;
		cpt = as_component_new ();

		while (TRUE) {
			g_print ("%s ", _("Your software needs a unique name.\nIn case of a GUI application, this is its .desktop filename.\nUnique software name:"));
			tmp = li_get_stdin ();
			if (tmp != NULL) {
				as_component_set_id (cpt, tmp);
				g_free (tmp);
				break;
			}
		}

		while (TRUE) {
			g_print ("%s ", _("Define a software name (human readable):"));
			tmp = li_get_stdin ();
			if (tmp != NULL) {
				as_component_set_name (cpt, tmp);
				g_free (tmp);
				break;
			}
		}

		while (TRUE) {
			g_print ("%s ", _("Define a software version:"));
			tmp = li_get_stdin ();
			if (tmp != NULL) {
				AsRelease *rel;
				rel = as_release_new ();
				as_release_set_version (rel, tmp);
				as_component_add_release (cpt, rel);
				g_object_unref (rel);
				g_free (tmp);
				break;
			}
		}

		while (TRUE) {
			g_print ("%s ", _("Write a short summary (one sentence) about your software:"));
			tmp = li_get_stdin ();
			if (tmp != NULL) {
				as_component_set_summary (cpt, tmp);
				g_free (tmp);
				break;
			}
		}

		asfile = g_build_filename (res_dir, "metainfo.xml", NULL);
		tmp = as_component_to_xml (cpt);
		g_file_set_contents (asfile, tmp, -1, &error);
		g_free (tmp);
		if (error != NULL) {
			li_print_stderr (_("Unable to write AppStream data. %s"), error->message);
			g_error_free (error);
			res = 2;
			g_free (asfile);
			goto out;
		}

		if (g_file_test ("/usr/bin/xmllint", G_FILE_TEST_EXISTS)) {
			gchar *cmd;
			/* we can try to pretty-print our XML file. Using xmllint from the environment should
			 * not be a security risk here */
			cmd = g_strdup_printf ("xmllint --format %s -o %s", asfile, asfile);

			/* any error / exit-code isn't relevant here - a failed attempt to format the XML will do no harm */
			g_spawn_command_line_sync (cmd, NULL, NULL, NULL, NULL);
			g_free (cmd);
		}
		g_free (asfile);
    }

    fname = g_build_filename (res_dir, "control", NULL);
	g_file_set_contents (fname, "Format-Version: 1.0\n\nRequires:\n", -1, &error);
	g_free (fname);
	if (error != NULL) {
		li_print_stderr (_("Unable to write 'control' file. %s"), error->message);
		g_error_free (error);
		res = 2;
		goto out;
	}

	li_print_stdout ("\n========");\
	li_print_stdout (_("Created project template in '%s'.\n\n" \
"Please edit the files in that directory, e.g. add a long description to your\n" \
"application and specify its run-time dependencies.\n" \
"When you are done with this, build your software with --prefix=%s\n" \
"and install it into the inst_target subdirectory of your 'pkginstall' directory.\n" \
"Then run 'lipkgen build pkginstall/' to create your package. \n" \
"If you want to embed dependencies, place their IPK packages in the 'repo/'\n" \
"subdirectory of 'pkginstall/'"), res_dir, LI_SW_ROOT_PREFIX);
	li_print_stdout ("========\n");

out:
	g_free (res_dir);
	return res;
}
Example #26
0
/* This function connects using curl to the tftp server.  It grabs needed
 * files from there */
void *
get_tftp_file (tclient_c *tclient, gchar *filename)
{
    CURL *curl = 0;
    FILE *config_file = 0;
    GError *error = 0;
    gchar *local_filename = 0;
    gchar *uri = 0;
    gchar *dirs = 0;
    gchar *itr = 0;

    /* Make the directory structure for the file being fetched */
    itr = g_strrstr(filename, "/");
    if (itr != NULL)
    {
        dirs = g_strndup(filename, (strlen(filename) - strlen(itr)));
        itr = g_strdup_printf("/tmp/%s", dirs);
        g_mkdir_with_parents(itr, 0777);
        g_free(dirs);
        g_free(itr);
    }

    local_filename = g_strdup_printf("/tmp/%s", filename);
    uri = g_strdup_printf("tftp://%s/tclient/%s", tftp_server, filename);

    curl = curl_easy_init();
    config_file = fopen (local_filename, "w+b");
    if (config_file != NULL)
    {
        CURLcode result;

        curl_easy_setopt (curl, CURLOPT_WRITEDATA, config_file);
        curl_easy_setopt (curl, CURLOPT_URL, uri);
        curl_easy_setopt (curl, CURLOPT_TIMEOUT, 5);
        result = curl_easy_perform(curl);

        curl_easy_cleanup(curl);

		/* If there is an error code, and it isn't 
		 * CURLE_TFTP_NOTFOUND
		 * CURLE_TFTP_ILLEGAL
		 * Both of these can originate on missing or null files which
		 * are not to be considered errors */
        if (result != 0 && result != CURLE_TFTP_NOTFOUND && result != CURLE_TFTP_ILLEGAL)
        {
            start_error_dialog(tclient, __FUNCTION__, (gchar *)curl_easy_strerror(result));

            return NULL;
        }
    }
    else
    {
        if (error != NULL)
        {
            start_error_dialog(tclient, __FUNCTION__, error->message);
        }
    }

    /* Cleanup */
    g_free(uri);

    if (config_file != NULL)
    {
        fclose(config_file);
        return local_filename;
    }

    return NULL;
}
Example #27
0
gboolean
dt_styles_create_from_image (const char *name,const char *description,int32_t imgid,GList *filter)
{
  int id=0;
  sqlite3_stmt *stmt;

  /* first create the style header */
  if (!dt_styles_create_style_header(name,description) ) return FALSE;

  if ((id=dt_styles_get_id_by_name(name)) != 0)
  {
    /* create the style_items from source image history stack */
    if (filter)
    {
      GList *list=filter;
      char tmp[64];
      char include[2048]= {0};
      g_strlcat(include,"num in (", 2048);
      do
      {
        if(list!=g_list_first(list))
          g_strlcat(include,",", 2048);
        sprintf(tmp,"%ld",(glong)list->data);
        g_strlcat(include,tmp, 2048);
      }
      while ((list=g_list_next(list)));
      g_strlcat(include,")", 2048);
      char query[4096]= {0};
      sprintf(query,"insert into style_items (styleid,num,module,operation,op_params,enabled,blendop_params,blendop_version,multi_priority,multi_name) select ?1, num,module,operation,op_params,enabled,blendop_params,blendop_version,multi_priority,multi_name from history where imgid=?2 and %s",include);
      DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), query, -1, &stmt, NULL);
    }
    else
      DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "insert into style_items (styleid,num,module,operation,op_params,enabled,blendop_params,blendop_version,multi_priority,multi_name) select ?1, num,module,operation,op_params,enabled,blendop_params,blendop_version,multi_priority,multi_name from history where imgid=?2", -1, &stmt, NULL);
    DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, id);
    DT_DEBUG_SQLITE3_BIND_INT(stmt, 2, imgid);
    sqlite3_step (stmt);
    sqlite3_finalize (stmt);

    _dt_style_cleanup_multi_instance(id);

    /* backup style to disk */
    char stylesdir[1024];
    dt_loc_get_user_config_dir(stylesdir, 1024);
    g_strlcat(stylesdir,"/styles",1024);
    g_mkdir_with_parents(stylesdir,00755);

    dt_styles_save_to_file(name,stylesdir,FALSE);

    char tmp_accel[1024];
    gchar* tmp_name = g_strdup(name); // freed by _destroy_style_shortcut_callback
    snprintf(tmp_accel,1024,C_("accel", "styles/apply %s"),name);
    dt_accel_register_global( tmp_accel, 0, 0);
    GClosure *closure;
    closure = g_cclosure_new(
                G_CALLBACK(_apply_style_shortcut_callback),
                tmp_name, _destroy_style_shortcut_callback);
    dt_accel_connect_global(tmp_accel, closure);
    return TRUE;
  }
  return FALSE;
}
Example #28
0
int
store (dt_imageio_module_data_t *sdata, const int imgid, dt_imageio_module_format_t *format, dt_imageio_module_data_t *fdata, const int num, const int total)
{
  dt_imageio_gallery_t *d = (dt_imageio_gallery_t *)sdata;

  char filename[1024]= {0};
  char dirname[1024]= {0};
  dt_image_full_path(imgid, dirname, 1024);
  // we're potentially called in parallel. have sequence number synchronized:
  dt_pthread_mutex_lock(&darktable.plugin_threadsafe);
  {

    char tmp_dir[1024];
    dt_variables_expand(d->vp, d->filename, TRUE);
    g_strlcpy(tmp_dir, dt_variables_get_result(d->vp), 1024);

    // if filenamepattern is a directory just let att ${FILE_NAME} as default..
    if ( g_file_test(tmp_dir, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) || ((d->filename+strlen(d->filename)-1)[0]=='/' || (d->filename+strlen(d->filename)-1)[0]=='\\') )
      snprintf (d->filename+strlen(d->filename), 1024-strlen(d->filename), "/$(FILE_NAME)");

    // avoid braindead export which is bound to overwrite at random:
    if(total > 1 && !g_strrstr(d->filename, "$"))
    {
      snprintf(d->filename+strlen(d->filename), 1024-strlen(d->filename), "_$(SEQUENCE)");
    }

    gchar* fixed_path = dt_util_fix_path(d->filename);
    g_strlcpy(d->filename, fixed_path, 1024);
    g_free(fixed_path);

    d->vp->filename = dirname;
    d->vp->jobcode = "export";
    d->vp->imgid = imgid;
    d->vp->sequence = num;
    dt_variables_expand(d->vp, d->filename, TRUE);
    g_strlcpy(filename, dt_variables_get_result(d->vp), 1024);
    g_strlcpy(dirname, filename, 1024);

    const char *ext = format->extension(fdata);
    char *c = dirname + strlen(dirname);
    for(; c>dirname && *c != '/'; c--);
    if(*c == '/') *c = '\0';
    if(g_mkdir_with_parents(dirname, 0755))
    {
      fprintf(stderr, "[imageio_storage_gallery] could not create directory: `%s'!\n", dirname);
      dt_control_log(_("could not create directory `%s'!"), dirname);
      dt_pthread_mutex_unlock(&darktable.plugin_threadsafe);
      return 1;
    }

    // store away dir.
    snprintf(d->cached_dirname, 1024, "%s", dirname);

    c = filename + strlen(filename);
    for(; c>filename && *c != '.' && *c != '/' ; c--);
    if(c <= filename || *c=='/') c = filename + strlen(filename);

    sprintf(c,".%s",ext);

    // save image to list, in order:
    pair_t *pair = malloc(sizeof(pair_t));

    char *title = NULL, *description = NULL, *tags = NULL;
    GList *res;

    res = dt_metadata_get(imgid, "Xmp.dc.title", NULL);
    if(res)
    {
      title = res->data;
      g_list_free(res);
    }

    res = dt_metadata_get(imgid, "Xmp.dc.description", NULL);
    if(res)
    {
      description = res->data;
      g_list_free(res);
    }

    unsigned int count = 0;
    res = dt_metadata_get(imgid, "Xmp.dc.subject", &count);
    if(res)
    {
      // don't show the internal tags (darktable|...)
      res = g_list_first(res);
      GList *iter = res;
      while(iter)
      {
        GList *next = g_list_next(iter);
        if(g_str_has_prefix(iter->data, "darktable|"))
        {
          g_free(iter->data);
          res = g_list_delete_link(res, iter);
          count--;
        }
        iter = next;
      }
      tags = dt_util_glist_to_str(", ", res, count);
    }

    char relfilename[256], relthumbfilename[256];
    c = filename + strlen(filename);
    for(; c>filename && *c != '/' ; c--);
    if(*c == '/') c++;
    if(c <= filename) c = filename;
    snprintf(relfilename, 256, "%s", c);
    snprintf(relthumbfilename, 256, "%s", relfilename);
    c = relthumbfilename + strlen(relthumbfilename);
    for(; c>relthumbfilename && *c != '.'; c--);
    if(c <= relthumbfilename) c = relthumbfilename + strlen(relthumbfilename);
    sprintf(c, "-thumb.%s", ext);

    char subfilename[1024], relsubfilename[256];
    snprintf(subfilename, 1024, "%s", d->cached_dirname);
    char* sc = subfilename + strlen(subfilename);
    sprintf(sc, "/img_%d.html", num);
    sprintf(relsubfilename, "img_%d.html", num);

    snprintf(pair->line, 4096,
             "\n"
             "      <div><a class=\"dia\" rel=\"lightbox[viewer]\" title=\"%s - %s\" href=\"%s\"><span></span><img src=\"%s\" alt=\"img%d\" class=\"img\"/></a>\n"
             "      <h1>%s</h1>\n"
             "      %s<br/><span class=\"tags\">%s</span></div>\n", title?title:relfilename, description?description:"&nbsp;", relfilename, relthumbfilename, num, title?title:"&nbsp;", description?description:"&nbsp;", tags?tags:"&nbsp;");

    char next[256];
    sprintf(next, "img_%d.html", (num)%total+1);

    char prev[256];
    sprintf(prev, "img_%d.html", (num==1)?total:num-1);

/* Becomes unecessary with the Lightbox image viewer overlay

    FILE* subfile = fopen(subfilename, "wb");
    fprintf(subfile,
          "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
          "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
          "  <head>\n"
          "    <meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n"
          "    <link rel=\"shortcut icon\" href=\"style/favicon.ico\" />\n"
          "    <link rel=\"stylesheet\" href=\"style/style.css\" type=\"text/css\" />\n"
          "    <title>%s</title>\n"
          "  </head>\n"
          "  <body>\n"
          "    <div class=\"title\"><a href=\"index.html\">%s</a></div>\n"
          "    <div class=\"page\">\n"
          "      <div style=\"width: 692px; max-width: 692px; height: 10px;\">\n"
          "        <a style=\"float: left;\" href=\"%s\"><h1>prev</h1></a>\n" 
          "        <a style=\"float: right;\"href=\"%s\"><h1>next</h1></a>\n"
          "      </div>\n"
          "      <a href=\"%s\"><img src=\"%s\" width=\"692\" class=\"img\"/></a>\n"
          "      %s<br/><span class=\"tags\">%s</span></div>\n"
          "      <p style=\"clear:both;\"></p>\n"
          "    </div>\n"
          "    <div class=\"footer\">\n"
          "      created with darktable "PACKAGE_VERSION"\n"
          "    </div>\n"
          "  </body>\n"
          "</html>\n",
          relfilename, title?title:relfilename, prev, next, relfilename, relfilename, description?description:"&nbsp;", tags?tags:"&nbsp;");
    fclose(subfile);
*/
    pair->pos = num;
    g_free(title);
    g_free(description);
    g_free(tags);
    d->l = g_list_insert_sorted(d->l, pair, (GCompareFunc)sort_pos);
  } // end of critical block
  dt_pthread_mutex_unlock(&darktable.plugin_threadsafe);

  /* export image to file */
  if(dt_imageio_export(imgid, filename, format, fdata) != 0)
  {
    fprintf(stderr, "[imageio_storage_gallery] could not export to file: `%s'!\n", filename);
    dt_control_log(_("could not export to file `%s'!"), filename);
    return 1;
  }

  /* also export thumbnail: */
  // write with reduced resolution:
  const int max_width  = fdata->max_width;
  const int max_height = fdata->max_height;
  fdata->max_width  = 200;
  fdata->max_height = 200;
  // alter filename with -thumb:
  char *c = filename + strlen(filename);
  for(; c>filename && *c != '.' && *c != '/' ; c--);
  if(c <= filename || *c=='/') c = filename + strlen(filename);
  const char *ext = format->extension(fdata);
  sprintf(c,"-thumb.%s",ext);
  if(dt_imageio_export(imgid, filename, format, fdata) != 0)
  {
    fprintf(stderr, "[imageio_storage_gallery] could not export to file: `%s'!\n", filename);
    dt_control_log(_("could not export to file `%s'!"), filename);
    return 1;
  }
  // restore for next image:
  fdata->max_width = max_width;
  fdata->max_height = max_height;

  printf("[export_job] exported to `%s'\n", filename);
  char *trunc = filename + strlen(filename) - 32;
  if(trunc < filename) trunc = filename;
  dt_control_log(_("%d/%d exported to `%s%s'"), num, total, trunc != filename ? ".." : "", trunc);
  return 0;
}
Example #29
0
int
store (dt_imageio_module_storage_t *self, dt_imageio_module_data_t *sdata, const int imgid, dt_imageio_module_format_t *format, dt_imageio_module_data_t *fdata,
       const int num, const int total, const gboolean high_quality)
{
  disk_t *g = (disk_t *)self->gui_data;
  dt_imageio_disk_t *d = (dt_imageio_disk_t *)sdata;

  // since we're potentially called in parallel, we should uncheck button as early as possible
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g->overwrite_btn), FALSE);

  char filename[DT_MAX_PATH_LEN]= {0};
  char dirname[DT_MAX_PATH_LEN]= {0};
  gboolean from_cache = FALSE;
  dt_image_full_path(imgid, dirname, DT_MAX_PATH_LEN, &from_cache);
  int fail = 0;
  // we're potentially called in parallel. have sequence number synchronized:
  dt_pthread_mutex_lock(&darktable.plugin_threadsafe);
  {

    // if filenamepattern is a directory just let att ${FILE_NAME} as default..
    if ( g_file_test(d->filename, G_FILE_TEST_IS_DIR) || ((d->filename+strlen(d->filename))[0]=='/' || (d->filename+strlen(d->filename))[0]=='\\') )
      snprintf (d->filename+strlen(d->filename), DT_MAX_PATH_LEN-strlen(d->filename), "$(FILE_NAME)");

    // avoid braindead export which is bound to overwrite at random:
    if(total > 1 && !g_strrstr(d->filename, "$"))
    {
      snprintf(d->filename+strlen(d->filename), DT_MAX_PATH_LEN-strlen(d->filename), "_$(SEQUENCE)");
    }

    gchar* fixed_path = dt_util_fix_path(d->filename);
    g_strlcpy(d->filename, fixed_path, DT_MAX_PATH_LEN);
    g_free(fixed_path);

    d->vp->filename = dirname;
    d->vp->jobcode = "export";
    d->vp->imgid = imgid;
    d->vp->sequence = num;
    dt_variables_expand(d->vp, d->filename, TRUE);
    g_strlcpy(filename, dt_variables_get_result(d->vp), DT_MAX_PATH_LEN);
    g_strlcpy(dirname, filename, DT_MAX_PATH_LEN);

    const char *ext = format->extension(fdata);
    char *c = dirname + strlen(dirname);
    for(; c>dirname && *c != '/'; c--);
    if(*c == '/')
    {
      if(c > dirname) // /.../.../foo
        c[0] = '\0';
      else // /foo
        c[1] = '\0';
    }
    else if(c == dirname) // foo
    {
      c[0] = '.';
      c[1] = '\0';
    }

    if(g_mkdir_with_parents(dirname, 0755))
    {
      fprintf(stderr, "[imageio_storage_disk] could not create directory: `%s'!\n", dirname);
      dt_control_log(_("could not create directory `%s'!"), dirname);
      fail = 1;
      goto failed;
    }
    if(g_access(dirname, W_OK) != 0)
    {
      fprintf(stderr, "[imageio_storage_disk] could not write to directory: `%s'!\n", dirname);
      dt_control_log(_("could not write to directory `%s'!"), dirname);
      fail = 1;
      goto failed;
    }

    c = filename + strlen(filename);
    // remove everything after the last '.'. this destroys any file name with dots in it since $(FILE_NAME) already comes without the original extension.
//     for(; c>filename && *c != '.' && *c != '/' ; c--);
//     if(c <= filename || *c=='/') c = filename + strlen(filename);

    sprintf(c,".%s",ext);

    /* prevent overwrite of files */
failed:
    if (!d->overwrite) {
        int seq=1;
        if (!fail && g_file_test (filename,G_FILE_TEST_EXISTS))
        {
          do
          {
            sprintf(c,"_%.2d.%s",seq,ext);
            seq++;
          }
          while (g_file_test (filename,G_FILE_TEST_EXISTS));
        }
    }
  } // end of critical block
  dt_pthread_mutex_unlock(&darktable.plugin_threadsafe);
  if(fail) return 1;

  /* export image to file */
  if(dt_imageio_export(imgid, filename, format, fdata, high_quality) != 0)
  {
    fprintf(stderr, "[imageio_storage_disk] could not export to file: `%s'!\n", filename);
    dt_control_log(_("could not export to file `%s'!"), filename);
    return 1;
  }

  /* now write xmp into that container, if possible */
  if((format->flags(fdata) & FORMAT_FLAGS_SUPPORT_XMP) && dt_exif_xmp_attach(imgid, filename) != 0)
  {
    fprintf(stderr, "[imageio_storage_disk] could not attach xmp data to file: `%s'!\n", filename);
    // don't report that one to gui, as some formats (pfm, ppm, exr) just don't support
    // writing xmp via exiv2, so it might not be to worry.
    return 1;
  }

  printf("[export_job] exported to `%s'\n", filename);
  char *trunc = filename + strlen(filename) - 32;
  if(trunc < filename) trunc = filename;
  dt_control_log(_("%d/%d exported to `%s%s'"), num, total, trunc != filename ? ".." : "", trunc);
  return 0;
}
Example #30
0
bool makeAllDirectories(const String& path)
{
    GUniquePtr<gchar> filename = unescapedFilename(path);
    return filename ? g_mkdir_with_parents(filename.get(), S_IRWXU) != -1 : false;
}