Exemplo n.º 1
0
/* Load an iwb file and create the list of save-point. */
GSList *
load_iwb (gchar *iwbfile)
{
    const gchar *tmpdir = g_get_tmp_dir ();
    GSList *savepoint_list = (GSList *) NULL;
    gchar  *ardesia_tmp_dir = g_build_filename (tmpdir, PACKAGE_NAME, (gchar *) 0);
    gchar  *project_name = get_project_name ();
    gchar  *project_tmp_dir = g_build_filename (ardesia_tmp_dir, project_name, (gchar *) 0);
    gchar  *content_filename = "content.xml";
    gchar  *content_filepath = g_build_filename (project_tmp_dir, content_filename, (gchar *) 0);
    xmlDocPtr doc = (xmlDocPtr) NULL; // the resulting document tree
    xmlXPathContextPtr context = (xmlXPathContextPtr) NULL;

    decompress_iwb (iwbfile, project_tmp_dir);

    /* Initialize libxml. */
    xmlInitParser ();

    /*
     * This initialize the library and check potential ABI mismatches
     * between the version it was compiled for and the actual shared
     * library used.
     */
    LIBXML_TEST_VERSION

    /*
     * Build an XML tree from a the file.
     */
    doc = xmlParseFile (content_filepath);

    if (doc == NULL)
    {
        printf ("Failed to parse %s\n", content_filepath);
        exit (EXIT_FAILURE);
    }

    context = xmlXPathNewContext (doc);

    if (context == NULL)
    {
        xmlFreeDoc (doc);
        printf ("Error: unable to create new XPath context\n");
        exit (EXIT_FAILURE);
    }

    context = register_namespaces (context);

    savepoint_list = load_savepoints_by_iwb (savepoint_list, project_tmp_dir, context);

    g_remove (content_filepath);

    xmlXPathFreeContext (context);

    xmlFreeDoc (doc);
    doc = NULL;

    /*
     * Cleanup function for the XML library.
     */
    xmlCleanupParser ();

    g_free (ardesia_tmp_dir);
    ardesia_tmp_dir = NULL;

    g_free (project_tmp_dir);
    project_tmp_dir = NULL;

    g_free (content_filepath);
    content_filepath = NULL;

    return savepoint_list;
}
Exemplo n.º 2
0
static gboolean
openssl_make_dummy_cert (const gchar *key_file,
                         const gchar *out_file,
                         GError **error)
{
  gboolean ret = FALSE;
  gint exit_status;
  gchar *stderr_str = NULL;
  gchar *command_line = NULL;
  gchar *ssl_config = NULL;
  gchar *subject = generate_subject ();

  /* make config file with subjectAltName for localhost and our tests */
  ssl_config = create_temp_file (g_get_tmp_dir (), "ssl.conf.XXXXXX", error);
  if (!ssl_config)
      return FALSE;
  if (!g_file_set_contents (ssl_config,
              "[ req ]\n"
              "req_extensions = v3_req\n"
              "extensions = v3_req\n"
              "distinguished_name = req_distinguished_name\n"
              "[ req_distinguished_name ]\n"
              "[ v3_req ]\n"
              "subjectAltName=IP:127.0.0.1,DNS:localhost\n",
              -1, error))
      return FALSE;

  const gchar *argv[] = {
    "openssl",
    "req", "-x509",
    "-days", "36500",
    "-newkey", "rsa:2048",
    "-keyout", key_file,
    "-keyform", "PEM",
    "-nodes",
    "-out", out_file,
    "-outform", "PEM",
    "-subj", subject,
    "-config", ssl_config,
    "-extensions", "v3_req",
    NULL
  };

  command_line = g_strjoinv (" ", (gchar **)argv);
  g_info ("Generating temporary certificate using: %s", command_line);

  if (!g_spawn_sync (NULL, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
                     NULL, &stderr_str, &exit_status, error) ||
      !g_spawn_check_exit_status (exit_status, error))
    {
      g_warning ("%s", stderr_str);
      g_prefix_error (error, "Error generating temporary self-signed dummy cert using openssl: ");
      goto out;
    }

  ret = TRUE;

out:
  if (ssl_config)
    g_unlink (ssl_config);
  g_free (ssl_config);
  g_free (stderr_str);
  g_free (command_line);
  g_free (subject);
  return ret;
}
Exemplo n.º 3
0
} END_TEST

/*
 * TODO:
 *
 * We should really explore maximum paths values:
 *
 * - absolute maximum: PATH_MAX
 * - relative maximum: _POSIX_PATH_MAX
 * - pathconf(3)
 */
START_TEST(test_cc_oci_resolve_path) {
	gchar *tmpdir;
	gchar *file;
	gchar *slink;
	gchar *path;
	const char *d = NULL;

	tmpdir = g_dir_make_tmp (NULL, NULL);
	ck_assert (tmpdir);

	file = g_build_path ("/", tmpdir, "foo", NULL);
	ck_assert (file);

	slink = g_build_path ("/", tmpdir, "symlink", NULL);
	ck_assert (slink);

	/* create a symlink */
	ck_assert (! symlink (file, slink));

	ck_assert (! cc_oci_resolve_path (NULL));
	ck_assert (! cc_oci_resolve_path (""));
	ck_assert (! cc_oci_resolve_path ("not a path"));
	ck_assert (! cc_oci_resolve_path ("/does/not/exist"));

	/*******************************/
	/* check a known valid path */

	d = g_get_tmp_dir ();
	ck_assert (d);

	path = cc_oci_resolve_path (d);
	ck_assert (path);
	ck_assert (! g_strcmp0 (path, d));
	g_free (path);

	/*******************************/
	/* file doesn't exist */

	path = cc_oci_resolve_path (file);
	ck_assert (! path);

	/*******************************/
	/* create valid file */

	ck_assert (g_file_set_contents (file, "", -1, NULL));

	path = cc_oci_resolve_path (file);
	ck_assert (path);
	ck_assert (! g_strcmp0 (path, file));
	g_free (path);

	/*******************************/
	/* check a broken symlink */

	/* break the symlink by removing the file it points to */
	ck_assert (! g_remove (file));

	path = cc_oci_resolve_path (slink);
	ck_assert (! path);

	/*******************************/
	/* check a valid symlink */

	/* re create the file */
	ck_assert (g_file_set_contents (file, "", -1, NULL));

	path = cc_oci_resolve_path (slink);
	ck_assert (path);

	ck_assert (! g_strcmp0 (path, file));
	g_free (path);

	/* clean up */
	ck_assert (! g_remove (file));
	ck_assert (! g_remove (slink));
	ck_assert (! g_remove (tmpdir));
	g_free (tmpdir);
	g_free (file);
	g_free (slink);

} END_TEST
Exemplo n.º 4
0
/**
 * g_file_open_tmp:
 * @tmpl: Template for file name, as in g_mkstemp(), basename only
 * @name_used: location to store actual name used
 * @error: return location for a #GError
 *
 * Opens a file for writing in the preferred directory for temporary
 * files (as returned by g_get_tmp_dir()). 
 *
 * @tmpl should be a string in the GLib file name encoding ending with
 * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
 * However, unlike these functions, the template should only be a
 * basename, no directory components are allowed. If template is
 * %NULL, a default template is used.
 *
 * Note that in contrast to g_mkstemp() (and mkstemp()) 
 * @tmpl is not modified, and might thus be a read-only literal string.
 *
 * The actual name used is returned in @name_used if non-%NULL. This
 * string should be freed with g_free() when not needed any longer.
 * The returned name is in the GLib file name encoding.
 *
 * Return value: A file handle (as from open()) to 
 * the file opened for reading and writing. The file is opened in binary 
 * mode on platforms where there is a difference. The file handle should be
 * closed with close(). In case of errors, -1 is returned 
 * and @error will be set.
 **/
gint
g_file_open_tmp (const gchar *tmpl,
		 gchar      **name_used,
		 GError     **error)
{
  int retval;
  const char *tmpdir;
  char *sep;
  char *fulltemplate;
  const char *slash;

  if (tmpl == NULL)
    tmpl = ".XXXXXX";

  if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
#ifdef G_OS_WIN32
      || (strchr (tmpl, '/') != NULL && (slash = "/"))
#endif
      )
    {
      gchar *display_tmpl = g_filename_display_name (tmpl);
      char c[2];
      c[0] = *slash;
      c[1] = '\0';

      g_set_error (error,
		   G_FILE_ERROR,
		   G_FILE_ERROR_FAILED,
		   _("Template '%s' invalid, should not contain a '%s'"),
		   display_tmpl, c);
      g_free (display_tmpl);

      return -1;
    }
  
  if (strlen (tmpl) < 6 ||
      strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
    {
      gchar *display_tmpl = g_filename_display_name (tmpl);
      g_set_error (error,
		   G_FILE_ERROR,
		   G_FILE_ERROR_FAILED,
		   _("Template '%s' doesn't end with XXXXXX"),
		   display_tmpl);
      g_free (display_tmpl);
      return -1;
    }

  tmpdir = g_get_tmp_dir ();

  if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
    sep = "";
  else
    sep = G_DIR_SEPARATOR_S;

  fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);

  retval = g_mkstemp (fulltemplate);

  if (retval == -1)
    {
      gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
      g_set_error (error,
		   G_FILE_ERROR,
		   g_file_error_from_errno (errno),
		   _("Failed to create file '%s': %s"),
		   display_fulltemplate, g_strerror (errno));
      g_free (display_fulltemplate);
      g_free (fulltemplate);
      return -1;
    }

  if (name_used)
    *name_used = fulltemplate;
  else
    g_free (fulltemplate);

  return retval;
}
Exemplo n.º 5
0
int main(int argc, char **argv)
{
	XmrApp *app;
	GOptionContext *context;
	GError *error = NULL;
	PlayerAction player_action = ActionNone;
	gchar *tmp_dir = NULL;

#if !GLIB_CHECK_VERSION(2, 32, 0)
	g_thread_init(NULL);
#endif

	gdk_threads_init();

	g_type_init();

	setlocale(LC_ALL, NULL);

#ifdef ENABLE_NLS
	/* initialize i18n */
	bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
	bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");

	textdomain(GETTEXT_PACKAGE);
#endif
	
	context = g_option_context_new(NULL);

	g_option_context_add_main_entries(context, options, GETTEXT_PACKAGE);

	g_option_context_add_group(context, gtk_get_option_group(TRUE));
	g_option_context_add_group(context, gst_init_get_option_group());

	if (g_option_context_parse(context, &argc, &argv, &error) == FALSE)
	{
		g_print(_("%s\nRun '%s --help' to see a full list of available command line options.\n"),
			 error->message, argv[0]);
		g_error_free(error);
		g_option_context_free(context);
		exit(1);
	}

	g_option_context_free(context);

	if (action_play){
		player_action = ActionPlay;
	}else if (action_pause){
		player_action = ActionPause;
	}else if(action_next){
		player_action = ActionNext;
	}else if(action_love){
		player_action = ActionLove;
	}else if(action_hate){
		player_action = ActionHate;
	}

	if (player_action != ActionNone)
	{
		DBusConnection *bus;
		DBusError dbus_error;
		dbus_error_init(&dbus_error);
		bus = dbus_bus_get(DBUS_BUS_SESSION, &dbus_error);
		if (!bus)
		{
			g_warning ("Failed to connect to the D-BUS daemon: %s", dbus_error.message);
			dbus_error_free(&dbus_error);
			exit(1);
		}
		
		dbus_connection_setup_with_g_main(bus, NULL);

		send_action(bus, player_action);

		// exit directly
		return 0;
	}

	xmr_debug_enable(debug);

	gst_init(&argc, &argv);

	gdk_threads_init();
	curl_global_init(CURL_GLOBAL_ALL);

	// this make our XmrRadio always works
	g_object_set(gtk_settings_get_default(),
				"gtk-button-images", TRUE,
				NULL);

	// ensure folder exists
	tmp_dir = g_strdup_printf("%s/%s", g_get_tmp_dir(), PACKAGE);
	g_mkdir_with_parents(tmp_dir, 0755);

	app = xmr_app_new();

	g_application_run(G_APPLICATION(app), argc, argv);

	// remove ...
	list_file(tmp_dir, FALSE, remove_file, NULL);

	g_free(tmp_dir);
	g_object_unref(app);

	curl_global_cleanup();

	return 0;
}
Exemplo n.º 6
0
void FV_UnixFrameEdit::mouseDrag(UT_sint32 x, UT_sint32 y)
{
    UT_DEBUGMSG(("Mouse drag x=%d y=%d \n",x,y));
    bool bYOK = ( (y > 0) && (y < getView()->getWindowHeight()));
    if(!bYOK || (x> 0 && x < getView()->getWindowWidth()))
     {
         m_bDragOut = false;
	 _mouseDrag(x,y);
	 return;
     }
     if(FV_DragWhole != getDragWhat())
     {
         m_bDragOut = false;
	 _mouseDrag(x,y);
	 return;
     }
     if(FV_FrameEdit_DRAG_EXISTING != getFrameEditMode())
     {
         m_bDragOut = false;
	 _mouseDrag(x,y);
	 return;
     }
     if(!isImageWrapper())
     {
         m_bDragOut = false;
	 _mouseDrag(x,y);
	 return;
     }
     if(!m_bDragOut)
     {
	 const UT_ByteBuf * pBuf = NULL;
	 const char * pszData = getPNGImage(&pBuf);
	 UT_DEBUGMSG(("Got image buffer %p pszData %p \n",pBuf,pszData));
	 if(pBuf)
	 {
       //
       // write the image to a temperary file
       //
	     XAP_UnixApp * pXApp = static_cast<XAP_UnixApp *>(XAP_App::getApp());
	     pXApp->removeTmpFile();
	     char ** pszTmpName = pXApp->getTmpFile();
	     UT_UTF8String sTmpF = g_get_tmp_dir();
	     sTmpF += "/";
	     sTmpF += pszData;
	     sTmpF += ".png";
	     //
	     // Now write the contents of the buffer to a temp file.
	     //
	     FILE * fd = fopen(sTmpF.utf8_str(),"w");
	     fwrite(pBuf->getPointer(0),sizeof(UT_Byte),pBuf->getLength(),fd);
	     fclose(fd);

       //
       // OK set up the gtk drag and drop code to andle this
       //
	     XAP_Frame * pFrame = static_cast<XAP_Frame*>(getView()->getParentData());
	     XAP_UnixFrameImpl * pFrameImpl =static_cast<XAP_UnixFrameImpl *>( pFrame->getFrameImpl());
	     GtkWidget * pWindow = pFrameImpl->getTopLevelWindow();
	     GtkTargetList *target_list = gtk_target_list_new(targets, G_N_ELEMENTS(targets));
	     GdkDragContext *context = gtk_drag_begin(pWindow, target_list,
						(GdkDragAction)(GDK_ACTION_COPY ), 1, NULL);

	     gdk_drag_status(context, GDK_ACTION_COPY, 0);
	     gtk_target_list_unref(target_list);
	     *pszTmpName = g_strdup(sTmpF.utf8_str());  
	     UT_DEBUGMSG(("Created Tmp File %s XApp %s \n",sTmpF.utf8_str(),*pXApp->getTmpFile()));

	 }
	 //
	 // OK quit dragging the image and return to the previous state
	 //
	 m_bDragOut = true;
	 abortDrag();
     }
     m_bDragOut = true;
}
Exemplo n.º 7
0
int main (int argc, char *argv[])
{
	int i;
	char *pluginname = NULL;
	char *plugindir = NULL;
	char *configfile = NULL;
	char *objtype = NULL;
	OSyncError *error = NULL;

	if (argc < 2)
		usage (argv[0], 1);

	pluginname = argv[1];
	for (i = 2; i < argc; i++) {
		char *arg = argv[i];
		if (!strcmp (arg, "--config")) {
			configfile = argv[i + 1];
			i++;
			if (!configfile)
				usage (argv[0], 1);
		} else if (!strcmp (arg, "--type")) {
			objtype = argv[i + 1];
			i++;
			if (!objtype)
				usage (argv[0], 1);
		} else if (!strcmp (arg, "--plugindir")) {
			printf("plugindir %s\n", argv[i + 1]);
			plugindir = argv[i + 1];
			i++;
			if (!plugindir)
				usage (argv[0], 1);
		} else if (!strcmp (arg, "--random")) {
			only_random = TRUE;
		} else if (!strcmp (arg, "--help")) {
			usage (argv[0], 0);
		} else {
			usage (argv[0], 1);
		}
	}

	OSyncEnv *env = osync_env_new(NULL);
	osync_env_set_option(env, "LOAD_GROUPS", "FALSE");

	if (plugindir)
		osync_env_set_option(env, "PLUGINS_DIRECTORY", plugindir);

	if (!osync_env_initialize(env, &error)) {
		printf("Unable to initialize environment: %s\n", osync_error_print(&error));
		osync_error_unref(&error);
		return 1;
	}

	char *testdir = g_strdup_printf("%s/plgtest.XXXXXX", g_get_tmp_dir());
	char *result = mkdtemp(testdir);

	if (result == NULL)
	{
		osync_trace(TRACE_EXIT_ERROR, "unable to create temporary dir: %s", g_strerror(errno));
		return 1;
	}

	OSyncGroup *group = osync_group_new(env);
	osync_group_set_name(group, osync_rand_str(8));
	osync_group_set_configdir(group, testdir);
	OSyncMember *member = osync_member_new(group);

	char *config = NULL;
	int size = 0;
	if (configfile) {
		if (!osync_file_read(configfile, &config, &size, &error)) {
			fprintf(stderr, "Unable to read config: %s\n", osync_error_print(&error));
			osync_error_unref(&error);
			return 1;
		}
		osync_member_set_config(member, config, size);
	}

	osync_member_set_pluginname(member, pluginname);

	OSyncMember *file = osync_member_new(group);

	localdir = g_strdup_printf("%s/plgtest.XXXXXX", g_get_tmp_dir());
	result = mkdtemp(localdir);

	if (result == NULL)
	{
		osync_trace(TRACE_EXIT_ERROR, "unable to create temporary dir: %s", g_strerror(errno));
		return 1;
	}

	config = g_strdup_printf("<config><path>%s</path><recursive>0</recursive></config>", localdir);
	osync_member_set_config(file, config, strlen(config) + 1);
	osync_member_set_pluginname(file, "file-sync");

	if (!osync_group_save(group, &error)) {
		printf("Error while creating syncengine: %s\n", osync_error_print(&error));
		osync_error_unref(&error);
		goto error_free_env;
	}

	if (!g_thread_supported ()) g_thread_init (NULL);

	OSyncEngine *engine = osengine_new(group, &error);
	if (!engine) {
		printf("Error while creating syncengine: %s\n", osync_error_print(&error));
		osync_error_unref(&error);
		goto error_free_env;
	}

	if (!osengine_init(engine, &error)) {
		printf("Error while initializing syncengine: %s\n", osync_error_print(&error));
		osync_error_unref(&error);
		goto error_free_engine;
	}

	int count = 0;
	if (only_random) {
		do {
			count++;
			printf("++++++++++++++++++++++++++++++\n");
			printf("Initializing new round #%i!\n", count);

			if (g_random_int_range(0, 5) == 0) {
				int i;
				OSyncFormatEnv *env = osync_group_get_format_env(group);
				for (i = 0; i < osync_conv_num_objtypes(env); i++) {
					if (g_random_int_range(0, 5) == 0) {
						OSyncObjType *type = osync_conv_nth_objtype(env, i);
						osync_group_set_slow_sync(group, osync_objtype_get_name(type), TRUE);
						printf("Requesting slow-sync for: %s\n", osync_objtype_get_name(type));
					}
				}
				osync_conv_env_free(env);
			}

			change_content();

			check_sync(engine, "Random", 1);
		} while (g_random_int_range(0, 3) != 0);

		printf("Finalizing engine\n");
		osengine_finalize(engine);
		osengine_free(engine);

		engine = osengine_new(group, &error);
		if (!engine) {
			printf("Error while creating syncengine: %s\n", osync_error_print(&error));
			osync_error_unref(&error);
			goto error_free_env;
		}

		if (!osengine_init(engine, &error)) {
			printf("Error while initializing syncengine: %s\n", osync_error_print(&error));
			osync_error_unref(&error);
			goto error_free_engine;
		}
	} else {
		register_tests();
		run_all_tests(engine, file, member, objtype);
	}

	printf("\nCompleted successfully\n");
	return 0;

error_free_engine:
	osengine_free(engine);
error_free_env:
	osync_group_free(group);
	osync_env_free(env);
	return 1;
}
Exemplo n.º 8
0
 g_assert(!strcmp(s,"C:\\Private\\e000002c") && "Wrong value for g_get_home_dir()");
 s = g_get_user_data_dir ();
 g_assert(!strcmp(s,"C:\\Private\\e000002c"));
 s = g_get_user_config_dir ();
 g_assert(!strcmp(s,"C:\\Private\\e000002c"));
 s = g_get_user_cache_dir ();
 g_assert(!strcmp(s,"C:\\Private\\e000002c"));
 sv = (gchar **) g_get_system_data_dirs ();
 g_assert(!strcmp(sv[0],"C:\\Private\\e000002c"));
 g_assert(sv[1] == NULL);
 
 sv = (gchar **) g_get_system_config_dirs ();
 g_assert(!strcmp(sv[0],"C:\\Private\\e000002c"));
 g_assert(sv[1] == NULL);
 
 string = (char *)g_get_tmp_dir ();
 g_assert(!strcmp(string,"C:\\Private\\e000002c\\tmp") && "Wrong value for g_get_tmp_dir()");
     
 sv = (gchar **) g_get_language_names ();
 g_assert(!strcmp(sv[0],"C"));
 g_assert(!strcmp(sv[1],"C"));
 g_assert(sv[2] == NULL);
 
 /* type sizes */
 TEST (NULL, sizeof (gint8) == 1);
 
 TEST (NULL, sizeof (gint16) == 2);
 
 TEST (NULL, sizeof (gint32) == 4);
 
 TEST (NULL, sizeof (gint64) == 8);
Exemplo n.º 9
0
gchar *
glide_dirs_make_temp_dir ()
{
  const gchar *temp_dir = g_get_tmp_dir();
  gchar *template = g_strdup_printf ("%s/glide-XXXXXX", temp_dir);
Exemplo n.º 10
0
int tgp_msg_send (struct tgl_state *TLS, const char *message, tgl_peer_id_t to) {
  // search for outgoing embedded image tags and send them
  gchar *img = NULL;
  gchar *stripped = NULL;
  
  if ((img = g_strrstr (message, "<IMG")) || (img = g_strrstr (message, "<img"))) {
    if (tgl_get_peer_type(to) == TGL_PEER_ENCR_CHAT) {
      tgp_msg_err_out (TLS, _("Sorry, sending documents to encrypted chats not yet supported."), to);
      return 0;
    }
    debug ("img found: %s", img);
    gchar *id;
    if ((id = g_strrstr (img, "ID=\"")) || (id = g_strrstr (img, "id=\""))) {
      id += 4;
      int imgid = atoi (id);
      if (imgid > 0) {
        PurpleStoredImage *psi = purple_imgstore_find_by_id (imgid);
        gchar *tmp = g_build_filename (g_get_tmp_dir(), purple_imgstore_get_filename (psi), NULL) ;
        GError *err = NULL;
        gconstpointer data = purple_imgstore_get_data (psi);
        g_file_set_contents (tmp, data, purple_imgstore_get_size (psi), &err);
        if (! err) {
          stripped = g_strstrip(purple_markup_strip_html (message));
          tgl_do_send_document (TLS, to, tmp, stripped, (int)strlen (stripped),
                                TGL_SEND_MSG_FLAG_DOCUMENT_AUTO, send_inline_picture_done, NULL);
          g_free (stripped);
          
          // return 0 to assure that the picture is not echoed, since
          // it will already be echoed with the outgoing message
          return 0;
        } else {
          failure ("Storing %s in imagestore failed: %s\n", tmp, err->message);
          g_error_free (err);
          return -1;
        }
      }
    }
    // no image id found in image
    return -1;
  }
  
#ifndef __ADIUM_
  /*
    Adium won't escape any HTML markup and just pass any user-input through,
    while Pidgin will replace special chars with the escape chars and also add 
    additional markup for RTL languages and such.

    First, we remove any HTML markup added by Pidgin, since Telegram won't handle it properly.
    User-entered HTML is still escaped and therefore won't be harmed.
   */
  stripped = purple_markup_strip_html (message);
  
  /* 
    now unescape the markup, so that html special chars will still show
    up properly in Telegram
   */
  gchar *unescaped = purple_unescape_text (stripped);
  int ret = tgp_msg_send_split (TLS, stripped, to);
  
  g_free (unescaped);
  g_free (stripped);
  return ret;
#endif
  
  return tgp_msg_send_split (TLS, message, to);
}
Exemplo n.º 11
0
/**
 * gimp_thumb_init:
 * @creator: an ASCII string that identifies the thumbnail creator
 * @thumb_basedir: an absolute path or %NULL to use the default
 *
 * This function initializes the thumbnail system. It must be called
 * before any other functions from libgimpthumb are used. You may call
 * it more than once if you want to change the @thumb_basedir but if
 * you do that, you should make sure that no thread is still using the
 * library. Apart from this function, libgimpthumb is multi-thread
 * safe.
 *
 * The @creator string must be 7bit ASCII and should contain the name
 * of the software that creates the thumbnails. It is used to handle
 * thumbnail creation failures. See the spec for more details.
 *
 * Usually you will pass %NULL for @thumb_basedir. Thumbnails will
 * then be stored in the user's personal thumbnail directory as
 * defined in the spec. If you wish to use libgimpthumb to store
 * application-specific thumbnails, you can specify a different base
 * directory here.
 *
 * Return value: %TRUE if the library was successfully initialized.
 **/
gboolean
gimp_thumb_init (const gchar *creator,
                 const gchar *thumb_basedir)
{
  GEnumClass *enum_class;
  GEnumValue *enum_value;
  gint        i;

  g_return_val_if_fail (creator != NULL, FALSE);
  g_return_val_if_fail (thumb_basedir == NULL ||
                        g_path_is_absolute (thumb_basedir), FALSE);

  if (gimp_thumb_initialized)
    gimp_thumb_exit ();

  if (thumb_basedir)
    {
      thumb_dir = g_strdup (thumb_basedir);
    }
  else
    {
      const gchar *home_dir = g_get_home_dir ();

      if (home_dir && g_file_test (home_dir, G_FILE_TEST_IS_DIR))
        {
          thumb_dir = g_build_filename (home_dir, ".thumbnails", NULL);
        }
      else
        {
          gchar *name = g_filename_display_name (g_get_tmp_dir ());

          g_message (_("Cannot determine a valid home directory.\n"
                       "Thumbnails will be stored in the folder for "
                       "temporary files (%s) instead."), name);
          g_free (name);

          thumb_dir = g_build_filename (g_get_tmp_dir (), ".thumbnails", NULL);
        }
    }

  enum_class = g_type_class_ref (GIMP_TYPE_THUMB_SIZE);

  thumb_num_sizes = enum_class->n_values;
  thumb_sizes     = g_new (gint, thumb_num_sizes);
  thumb_sizenames = g_new (const gchar *, thumb_num_sizes);
  thumb_subdirs   = g_new (gchar *, thumb_num_sizes);

  for (i = 0, enum_value = enum_class->values;
       i < enum_class->n_values;
       i++, enum_value++)
    {
      thumb_sizes[i]     = enum_value->value;
      thumb_sizenames[i] = enum_value->value_nick;
      thumb_subdirs[i]   = g_build_filename (thumb_dir,
                                             enum_value->value_nick, NULL);
    }

  thumb_fail_subdir = thumb_subdirs[0];
  thumb_subdirs[0]  = g_build_filename (thumb_fail_subdir, creator, NULL);

  g_type_class_unref (enum_class);

  gimp_thumb_initialized = TRUE;

  return gimp_thumb_initialized;
}
Exemplo n.º 12
0
/**
 * Create a tempfile with the given prefix (e.g. "wireshark").
 *
 * @param namebuf If not NULL, receives the full path of the temp file.
 *                Should NOT be freed.
 * @param pfx A prefix for the temporary file.
 * @param sfx [in] A file extension for the temporary file. NULL can be passed
 *                 if no file extension is needed
 * @return The file descriptor of the new tempfile, from mkstemps().
 */
int
create_tempfile(char **namebuf, const char *pfx, const char *sfx)
{
  static struct _tf {
    char *path;
    size_t len;
  } tf[MAX_TEMPFILES];
  static int idx;

  const char *tmp_dir;
  int old_umask;
  int fd;
  time_t current_time;
  char timestr[14 + 1];
  gchar *tmp_file;
  gchar *safe_pfx;
  gchar sep[2] = {0, 0};

  /* The characters in "delimiters" come from:
   * http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx.
   * Add to the list as necessary for other OS's.
   */
  const gchar *delimiters = "<>:\"/\\|?*"
    "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a"
    "\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14"
    "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f";

  /* Sanitize the pfx to resolve bug 7877 */
  safe_pfx = g_strdup(pfx);
  safe_pfx = g_strdelimit(safe_pfx, delimiters, '-');

  idx = (idx + 1) % MAX_TEMPFILES;

  /*
   * Allocate the buffer if it's not already allocated.
   */
  if (tf[idx].path == NULL) {
    tf[idx].len = INITIAL_PATH_SIZE;
    tf[idx].path = (char *)g_malloc(tf[idx].len);
  }

  tmp_dir = g_get_tmp_dir();

#ifdef _WIN32
  _tzset();
#endif
  current_time = time(NULL);
  strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&current_time));
  sep[0] = G_DIR_SEPARATOR;
  tmp_file = g_strconcat(tmp_dir, sep, safe_pfx, "_", timestr, "_", TMP_FILE_SUFFIX, sfx, NULL);
  g_free(safe_pfx);
  if (strlen(tmp_file) > tf[idx].len) {
    tf[idx].len = strlen(tmp_file) + 1;
    tf[idx].path = (char *)g_realloc(tf[idx].path, tf[idx].len);
  }
  g_strlcpy(tf[idx].path, tmp_file, tf[idx].len);
  g_free(tmp_file);

  if (namebuf) {
    *namebuf = tf[idx].path;
  }
  /* The Single UNIX Specification doesn't say that "mkstemps()"
     creates the temporary file with mode rw-------, so we
     won't assume that all UNIXes will do so; instead, we set
     the umask to 0077 to take away all group and other
     permissions, attempt to create the file, and then put
     the umask back. */
  old_umask = ws_umask(0077);
  fd = mkstemps(tf[idx].path, sfx ? (int) strlen(sfx) : 0);
  ws_umask(old_umask);
  return fd;
}
Exemplo n.º 13
0
/*
 * Construct and return the path name of a file in the
 * appropriate temporary file directory.
 */
char *get_tempfile_path(const char *filename)
{
  return g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s", g_get_tmp_dir(), filename);
}
Exemplo n.º 14
0
static void
create_channel_cb (GObject *acr,
    GAsyncResult *res,
    gpointer user_data)
{
  GSimpleAsyncResult *simple = user_data;
  CreateTubeData *data;
  GSocketListener *listener = NULL;
  gchar *dir;
  GSocket *socket = NULL;
  GSocketAddress *socket_address = NULL;
  GValue *address;
  GHashTable *parameters;
  GError *error = NULL;

  data = g_simple_async_result_get_op_res_gpointer (simple);

  if (g_cancellable_is_cancelled (data->op_cancellable))
    {
      g_object_unref (simple);
      return;
    }

  data->channel = tp_account_channel_request_create_and_handle_channel_finish (
      TP_ACCOUNT_CHANNEL_REQUEST (acr), res, NULL, &error);
   if (data->channel == NULL)
    goto OUT;

  data->invalidated_id = g_signal_connect (data->channel, "invalidated",
      G_CALLBACK (create_tube_channel_invalidated_cb), simple);

  /* We are client side, but we have to offer a socket... So we offer an unix
   * socket on which the service side can connect. We also create an IPv4 socket
   * on which the ssh client can connect. When both sockets are connected,
   * we can forward all communications between them. */

  listener = g_socket_listener_new ();

  /* Create temporary file for our unix socket */
  dir = g_build_filename (g_get_tmp_dir (), "telepathy-ssh-XXXXXX", NULL);
  dir = mkdtemp (dir);
  data->unix_path = g_build_filename (dir, "unix-socket", NULL);
  g_free (dir);

  /* Create the unix socket, and listen for connection on it */
  socket = g_socket_new (G_SOCKET_FAMILY_UNIX, G_SOCKET_TYPE_STREAM,
      G_SOCKET_PROTOCOL_DEFAULT, &error);
  if (socket == NULL)
    goto OUT;
  socket_address = g_unix_socket_address_new (data->unix_path);
  if (!g_socket_bind (socket, socket_address, FALSE, &error))
    goto OUT; 
  if (!g_socket_listen (socket, &error))
    goto OUT;
  if (!g_socket_listener_add_socket (listener, socket, NULL, &error))
    goto OUT;

  g_socket_listener_accept_async (listener, data->op_cancellable,
    create_tube_socket_connected_cb, g_object_ref (simple));

  /* Offer the socket */
  address = tp_address_variant_from_g_socket_address (socket_address,
      TP_SOCKET_ADDRESS_TYPE_UNIX, &error);
  if (address == NULL)
    goto OUT;
  parameters = g_hash_table_new (NULL, NULL);
  data->offer_call = tp_cli_channel_type_stream_tube_call_offer (data->channel,
      -1,
      TP_SOCKET_ADDRESS_TYPE_UNIX, address,
      TP_SOCKET_ACCESS_CONTROL_LOCALHOST, parameters,
      create_tube_offer_cb, g_object_ref (simple), g_object_unref, NULL);
  tp_g_value_slice_free (address);
  g_hash_table_unref (parameters);

OUT:

  if (error != NULL)
    create_tube_complete (simple, error);

  tp_clear_object (&listener);
  tp_clear_object (&socket);
  tp_clear_object (&socket_address);
  g_clear_error (&error);
  g_object_unref (simple);
}
Exemplo n.º 15
0
gboolean ipc_init_check(int argc, char **argv){
	GDir *dir;
	const char *entry, *user_name, *tmp_path;
	char *prefix;
	guint prefix_len;
	char *cur_dir_tmp;
	char *cur_dir;
	char *to_open;
	
	g_return_val_if_fail(input == NULL, FALSE);
	
	tmp_path=g_get_tmp_dir();
	dir=g_dir_open(tmp_path, 0, NULL);
	g_return_val_if_fail(dir != NULL, FALSE);
	
	user_name=g_get_user_name();
	prefix=g_strdup_printf(IPC_PIPE_PREFIX, user_name, GETTEXT_PACKAGE);
	prefix_len=strlen(prefix);

	cur_dir_tmp=g_get_current_dir();
	cur_dir=g_strdup_printf("%s/", cur_dir_tmp);
	uber_free(cur_dir_tmp);
	
	/* if another process creates a pipe while we are doing this,
	 * we may not get that pipe here. dunno if it's a problem */
	while((entry=g_dir_read_name(dir)) ){
		if(strncmp( entry, prefix, prefix_len ))
			continue;
		
		const char *pid_string;
		pid_t pid;
		char *filename;
		
		errno=0;
		pid_string=entry+prefix_len;
		/* this is not right, but should not cause real problems */
		pid=strtol(pid_string, NULL, 10);
		filename=g_build_filename(tmp_path, entry, NULL);
		
		if(errno && pid <= 0 && kill(pid, 0)){
			unlink(filename);
			uber_free(filename);
			continue;
		}
		/* it would be cool to check that the file is indeed a fifo,
		 * but again, who cares? */
		int fd;
		if((fd=open(filename, O_WRONLY | O_NONBLOCK)) == -1 ){
			perror("open");
			unlink(filename);
			uber_free(filename);
			continue;
		}
		
		/* TODO: validate argumants. */
		gboolean write_check=FALSE;
		if(!(write_check=write(fd, "", 1) )){
			close(fd);
			uber_free(filename);
			g_dir_close(dir);
			uber_free(prefix);
			return FALSE;
		}
		
		for(int i=0; i < argc; ++i) {
			to_open=NULL;
			if(!g_path_is_absolute(argv[i]))
				to_open=g_build_filename(cur_dir, argv[1], NULL);
			else
				to_open=g_build_filename(argv[i], NULL);
			if(!(write_check=write(fd, to_open, strlen(to_open) + 1)) )
				debug("**WARNING:** Failed to write: %s to %s", to_open, filename);
			uber_free(to_open);
		}
		close(fd);
		uber_free(filename);
		g_dir_close(dir);
		uber_free(prefix);
		return TRUE;
	}
	
	g_dir_close(dir);
	uber_free(prefix);
	ipc_main();
	return FALSE;
}
Exemplo n.º 16
0
Arquivo: socket.c Projeto: AR-H/geany
static gint socket_fd_open_unix(const gchar *path)
{
	gint sock;
	struct sockaddr_un addr;
	gint val;
	gchar *real_path;

	sock = socket(PF_UNIX, SOCK_STREAM, 0);

	if (sock < 0)
	{
		perror("sock_open_unix(): socket");
		return -1;
	}

	val = 1;
	if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
	{
		perror("setsockopt");
		socket_fd_close(sock);
		return -1;
	}

	/* fix for #1888561:
	 * in case the configuration directory is located on a network file system or any other
	 * file system which doesn't support sockets, we just link the socket there and create the
	 * real socket in the system's tmp directory assuming it supports sockets */
	real_path = g_strdup_printf("%s%cgeany_socket.%08x",
		g_get_tmp_dir(), G_DIR_SEPARATOR, g_random_int());

	if (utils_is_file_writable(real_path) != 0)
	{	/* if real_path is not writable for us, fall back to ~/.config/geany/geany_socket_*_* */
		/* instead of creating a symlink and print a warning */
		g_warning("Socket %s could not be written, using %s as fallback.", real_path, path);
		SETPTR(real_path, g_strdup(path));
	}
	/* create a symlink in e.g. ~/.config/geany/geany_socket_hostname__0 to /tmp/geany_socket.499602d2 */
	else if (symlink(real_path, path) != 0)
	{
		perror("symlink");
		socket_fd_close(sock);
		return -1;
	}

	memset(&addr, 0, sizeof(addr));
	addr.sun_family = AF_UNIX;
	strncpy(addr.sun_path, real_path, sizeof(addr.sun_path) - 1);

	if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
	{
		perror("bind");
		socket_fd_close(sock);
		return -1;
	}

	if (listen(sock, 1) < 0)
	{
		perror("listen");
		socket_fd_close(sock);
		return -1;
	}

	g_chmod(real_path, 0600);

	g_free(real_path);

	return sock;
}
/* The hierarchy looks like this:
 * /tmp/first_dir/first_dir_dir1/dir1_child
 * /tmp/first_dir/first_dir_dir2/dir2_child
 * /tmp/second_dir
 * We're copying first_dir to second_dir.
 */
static void
test_copy_third_hierarchy (void)
{
    g_autoptr (GFile) root = NULL;
    g_autoptr (GFile) first_dir = NULL;
    g_autoptr (GFile) second_dir = NULL;
    g_autoptr (GFile) file = NULL;
    g_autoptr (GFile) result_file = NULL;
    g_autolist (GFile) files = NULL;

    create_third_hierarchy ("copy");

    root = g_file_new_for_path (g_get_tmp_dir ());
    g_assert_true (root != NULL);

    first_dir = g_file_get_child (root, "copy_first_dir");
    files = g_list_prepend (files, g_object_ref (first_dir));
    g_assert_true (first_dir != NULL);

    file = g_file_get_child (first_dir, "copy_first_dir_dir1");
    g_assert_true (file != NULL);

    file = g_file_get_child (file, "copy_dir1_child");
    g_assert_true (file != NULL);

    file = g_file_get_child (first_dir, "copy_first_dir_dir2");
    g_assert_true (file != NULL);

    file = g_file_get_child (file, "copy_dir2_child");
    g_assert_true (file != NULL);

    second_dir = g_file_get_child (root, "copy_second_dir");
    g_assert_true (second_dir != NULL);

    nautilus_file_operations_copy_sync (files,
                                        second_dir);

    result_file = g_file_get_child (second_dir, "copy_first_dir");

    g_assert_true (g_file_query_exists (result_file, NULL));
    file = g_file_get_child (result_file, "copy_first_dir_dir1");
    g_assert_true (g_file_query_exists (file, NULL));
    file = g_file_get_child (file, "copy_dir1_child");
    g_assert_true (g_file_query_exists (file, NULL));
    file = g_file_get_child (result_file, "copy_first_dir_dir1");

    file = g_file_get_child (result_file, "copy_first_dir_dir2");
    g_assert_true (g_file_query_exists (file, NULL));
    file = g_file_get_child (file, "copy_dir2_child");
    g_assert_true (g_file_query_exists (file, NULL));
    file = g_file_get_child (result_file, "copy_first_dir_dir2");

    file = g_file_get_child (first_dir, "copy_first_dir_dir1");
    g_assert_true (g_file_query_exists (file, NULL));
    file = g_file_get_child (file, "copy_dir1_child");
    g_assert_true (g_file_query_exists (file, NULL));
    file = g_file_get_child (first_dir, "copy_first_dir_dir1");

    file = g_file_get_child (first_dir, "copy_first_dir_dir2");
    g_assert_true (g_file_query_exists (file, NULL));
    file = g_file_get_child (file, "copy_dir2_child");
    g_assert_true (g_file_query_exists (file, NULL));
    file = g_file_get_child (first_dir, "copy_first_dir_dir2");
    g_assert_true (g_file_query_exists (file, NULL));

    g_assert_true (g_file_query_exists (first_dir, NULL));

    empty_directory_by_prefix (root, "copy");
}
Exemplo n.º 18
0
static void
download_track (RBMtpThread *thread, RBMtpThreadTask *task)
{
	LIBMTP_file_t *fileinfo;
	LIBMTP_error_t *stack;
	GError *error = NULL;
	GFile *dir;
	RBMtpDownloadCallback cb = (RBMtpDownloadCallback) task->callback;

	/* first, check there's enough space to copy it */
	fileinfo = LIBMTP_Get_Filemetadata (thread->device, task->track_id);
	if (fileinfo == NULL) {
		stack = LIBMTP_Get_Errorstack (thread->device);
		rb_debug ("unable to get track metadata for %u: %s", task->track_id, stack->error_text);
		error = g_error_new (RB_MTP_THREAD_ERROR,
				     RB_MTP_THREAD_ERROR_GET_TRACK,
				     _("Unable to copy file from MTP device: %s"),
				     stack->error_text);
		LIBMTP_Clear_Errorstack (thread->device);

		cb (task->track_id, NULL, error, task->user_data);
		g_error_free (error);
		return;
	}

	if (task->filename[0] == '\0') {
		dir = g_file_new_for_path (g_get_tmp_dir ());
	} else {
		GFile *file = g_file_new_for_path (task->filename);
		dir = g_file_get_parent (file);
		g_object_unref (file);
	}
	rb_debug ("checking for %" G_GINT64_FORMAT " bytes available", fileinfo->filesize);
	if (rb_check_dir_has_space (dir, fileinfo->filesize) == FALSE) {
		char *dpath = g_file_get_path (dir);
		rb_debug ("not enough space in %s", dpath);
		error = g_error_new (RB_MTP_THREAD_ERROR, RB_MTP_THREAD_ERROR_NO_SPACE,
				     _("Not enough space in %s"), dpath);
		g_free (dpath);
	}
	LIBMTP_destroy_file_t (fileinfo);
	g_object_unref (dir);

	if (error != NULL) {
		rb_debug ("bailing out due to error: %s", error->message);
		cb (task->track_id, NULL, error, task->user_data);
		g_error_free (error);
		return;
	}

	if (task->filename[0] == '\0') {
		/* download to a temporary file */
		int fd;
		GError *tmperror = NULL;

		g_free (task->filename);
		fd = g_file_open_tmp ("rb-mtp-temp-XXXXXX", &task->filename, &tmperror);
		if (fd == -1) {
			rb_debug ("unable to open temporary file: %s", tmperror->message);
			error = g_error_new (RB_MTP_THREAD_ERROR,
					     RB_MTP_THREAD_ERROR_TEMPFILE,
					     _("Unable to open temporary file: %s"),
					     tmperror->message);
			g_error_free (tmperror);

			cb (task->track_id, NULL, error, task->user_data);
			g_error_free (error);
			return;
		} else {
			rb_debug ("downloading track %u to file descriptor %d", task->track_id, fd);
			if (LIBMTP_Get_Track_To_File_Descriptor (thread->device, task->track_id, fd, NULL, NULL)) {
				stack = LIBMTP_Get_Errorstack (thread->device);
				rb_debug ("unable to retrieve track %u: %s", task->track_id, stack->error_text);
				error = g_error_new (RB_MTP_THREAD_ERROR, RB_MTP_THREAD_ERROR_GET_TRACK,
						     _("Unable to copy file from MTP device: %s"),
						     stack->error_text);
				LIBMTP_Clear_Errorstack (thread->device);

				cb (task->track_id, NULL, error, task->user_data);
				g_error_free (error);
				close (fd);
				remove (task->filename);
				return;
			}
			rb_debug ("done downloading track");

			close (fd);
		}
	} else {
		if (LIBMTP_Get_Track_To_File (thread->device, task->track_id, task->filename, NULL, NULL)) {
			stack = LIBMTP_Get_Errorstack (thread->device);
			error = g_error_new (RB_MTP_THREAD_ERROR, RB_MTP_THREAD_ERROR_GET_TRACK,
					     _("Unable to copy file from MTP device: %s"),
					     stack->error_text);
			LIBMTP_Clear_Errorstack (thread->device);

			cb (task->track_id, NULL, error, task->user_data);
			g_error_free (error);
			return;
		}
	}

	cb (task->track_id, task->filename, NULL, task->user_data);
}
static gchar*
rb_disc_recorder_plugin_write_audio_project (const gchar 	*name,
					     GtkTreeModel       *model,
					     GError		**error)
{
        GtkTreeIter iter;
	xmlTextWriter *project;
	xmlDocPtr doc = NULL;
	xmlSaveCtxt *save;
	gint success;
    	gchar *path;
	int fd;
	int use_errno = 0;

        if (! gtk_tree_model_get_iter_first (model, &iter)) {
                g_set_error (error,
                             RB_RECORDER_ERROR,
                             RB_RECORDER_ERROR_GENERAL,
                             _("Unable to build an audio track list"));
                return NULL;
        }

	/* get a temporary path */
	path = g_build_filename (g_get_tmp_dir (), "brasero-tmp-project-XXXXXX",  NULL);
	fd = g_mkstemp (path);
	if (fd == -1) {
		g_set_error (error,
                 	     RB_RECORDER_ERROR,
                     	     RB_RECORDER_ERROR_GENERAL,
                    	     _("Unable to write audio project file %s: %s"),
			     path,
			     g_strerror (errno));
		rb_debug ("g_mkstemp failed");

		g_free (path);
		return NULL;
	}

	project = xmlNewTextWriterDoc (&doc, 0);
	if (!project) {
		g_remove (path);
		g_free (path);
		close (fd);

		g_set_error (error,
                 	     RB_RECORDER_ERROR,
                     	     RB_RECORDER_ERROR_GENERAL,
                    	     _("Unable to write audio project"));

		return NULL;
	}

	xmlTextWriterSetIndent (project, 1);
	xmlTextWriterSetIndentString (project, (xmlChar *) "\t");

	success = xmlTextWriterStartDocument (project,
					      NULL,
					      "UTF8",
					      NULL);
	if (success < 0)
		goto error;

	success = xmlTextWriterStartElement (project, (xmlChar *) "braseroproject");
	if (success < 0)
		goto error;

	/* write the name of the version */
	success = xmlTextWriterWriteElement (project,
					     (xmlChar *) "version",
					     (xmlChar *) "0.2");
	if (success < 0)
		goto error;

	if (name) {
		success = xmlTextWriterWriteElement (project,
						     (xmlChar *) "label",
						     (xmlChar *) name);
		if (success < 0)
			goto error;
	}

	success = xmlTextWriterStartElement (project, (xmlChar *) "track");
	if (success < 0)
		goto error;

	success = xmlTextWriterStartElement (project, (xmlChar *) "audio");
	if (success < 0)
		goto error;

        do {
		RhythmDBEntry  *entry;
		const char *str;
		xmlChar *escaped;

		gtk_tree_model_get (model, &iter, 0, &entry, -1);

		str = rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_LOCATION);
		escaped = (xmlChar *) g_uri_escape_string (str, NULL, FALSE);
		success = xmlTextWriterWriteElement (project,
						    (xmlChar *) "uri",
						     escaped);
		g_free (escaped);

		if (success == -1)
			goto error;

		/* start of the song always 0 */
		success = xmlTextWriterWriteElement (project,
						     (xmlChar *) "start",
						     (xmlChar *) "0");
		if (success == -1)
			goto error;

		/* end of the song = duration (in seconds while brasero likes it
		 * in nanoseconds =( ) */
		/* Disable this for the moment and let brasero check the size
		 * itself. In case the user chooses on the fly burning we need
		 * a more precise duration or we'd end up burning the track
		 * incompletely or with a big padding */
		/*
		end = g_strdup_printf ("%"G_GINT64_FORMAT, (gint64) (song->duration * 1000000000LL));
		success = xmlTextWriterWriteElement (project,
						     (xmlChar *) "end",
						     (xmlChar *) end);

		g_free (end);
		if (success == -1)
			goto error;
		*/

		str = rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_TITLE);
		if (str) {
			escaped = (xmlChar *) g_uri_escape_string (str, NULL, FALSE);
			success = xmlTextWriterWriteElement (project,
							    (xmlChar *) "title",
							     escaped);
			g_free (escaped);

			if (success == -1)
				goto error;
		}

		str = rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_ARTIST);
		if (str) {
			escaped = (xmlChar *) g_uri_escape_string (str, NULL, FALSE);
			success = xmlTextWriterWriteElement (project,
							    (xmlChar *) "artist",
							     escaped);
			g_free (escaped);

			if (success == -1)
				goto error;
		}

		/*
		if (song->composer) {
			escaped = (unsigned char *) g_uri_escape_string (song->composer, NULL, FALSE);
			success = xmlTextWriterWriteElement (project,
							    (xmlChar *) "composer",
							     escaped);
			g_free (escaped);

			if (success == -1)
				goto error;
		}
		*/
        } while (gtk_tree_model_iter_next (model, &iter));

	success = xmlTextWriterEndElement (project); /* audio */
	if (success < 0)
		goto error;

	success = xmlTextWriterEndElement (project); /* track */
	if (success < 0)
		goto error;

	success = xmlTextWriterEndElement (project); /* braseroproject */
	if (success < 0)
		goto error;

	success = xmlTextWriterEndDocument (project);
	if (success < 0)
		goto end_error;

	xmlFreeTextWriter (project);

	save = xmlSaveToFd (fd, "UTF8", XML_SAVE_FORMAT);
	if (save == NULL)
		goto save_error;

	if (xmlSaveDoc (save, doc) == -1)
		goto save_error;

	if (xmlSaveClose (save) == -1) {
		use_errno = errno;
		rb_debug ("xmlSaveClose failed");
		goto save_error;
	}

	xmlFreeDoc (doc);

	if (close (fd) == -1) {
		use_errno = errno;
		rb_debug ("close() failed");
		goto save_error;
	}

	return path;

error:
	/* cleanup */
	xmlTextWriterEndDocument (project);

end_error:
	xmlFreeTextWriter (project);

save_error:
	if (use_errno != 0) {
		g_set_error (error,
			     RB_RECORDER_ERROR,
			     RB_RECORDER_ERROR_GENERAL,
			     _("Unable to write audio project file %s: %s"),
			     path,
			     g_strerror (use_errno));
	} else {
		g_set_error (error,
			     RB_RECORDER_ERROR,
			     RB_RECORDER_ERROR_GENERAL,
			     _("Unable to write audio project"));
	}

	g_remove (path);
	g_free (path);
	close (fd);

	return NULL;
}
Exemplo n.º 20
0
gboolean Distro_WindowsCreate( const gchar * project_title, const gchar * game_path )
{
	gchar * blank_buffer = g_new(gchar, 512);
	gchar * game_buffer = NULL;
	gchar * binary_buffer = NULL;
	gsize game_buffer_length = 0;
	gsize binary_buffer_length = 0;
	gsize bytes_read = 0;



	gzFile binary_original;
	FILE * binary_temporary;

	gchar * shared_directory = Meg_Directory_Share("binaries");
	gchar * binary_original_path;
	gchar * binary_temporary_path;
	gchar * target_name;
	gchar * zip_original_path;
	gchar * zip_target_path;


	if ( g_file_get_contents( game_path, &game_buffer, &game_buffer_length, NULL ) )
	{
		target_name = g_strdup_printf("%s.exe", project_title );

		binary_original_path = g_build_filename( shared_directory, "windows-exe.gz", NULL);
		binary_temporary_path = g_build_filename( g_get_tmp_dir(), target_name, NULL);

		zip_original_path = g_build_filename( shared_directory, "windows-dll.zip", NULL);
		zip_target_path = g_strdup_printf( "%s"G_DIR_SEPARATOR_S"%s-windows.zip", Meg_Directory_Document(), project_title );


		binary_original = gzopen( binary_original_path, "rb" );
		binary_temporary = g_fopen( binary_temporary_path, "wb" );

		g_print( "binary_original: %p\n", binary_original );
		g_print( "binary_temporary: %p\n", binary_temporary );
		g_print( "binary_original_path: %s\n", binary_original_path );
		g_print( "binary_temporary_path: %s\n", binary_temporary_path );
		g_print( "zip_original_path: %s\n", zip_original_path );
		g_print( "zip_target_path: %s\n", zip_target_path );


		if ( binary_original && binary_temporary )
		{
			while ( TRUE ) // Read gzip
			{
				bytes_read = gzread( binary_original, blank_buffer, 512);
				if ( bytes_read > 0 )
				{
					fwrite( blank_buffer, bytes_read, 1, binary_temporary );
				}
				else
				{
					break;
				}

			}
			fwrite( game_buffer, game_buffer_length, 1, binary_temporary );

			if ( g_file_get_contents( binary_temporary_path, &binary_buffer, &binary_buffer_length, NULL ) )
			{
				Meg_FileCopy( zip_original_path, zip_target_path );
				mz_zip_add_mem_to_archive_file_in_place( zip_target_path, target_name, binary_buffer, binary_buffer_length, NULL, 0, 0 );
			}
			g_free(binary_buffer);
		}
		else
		{
			g_warning("Distro_WindowsCreate Failed");
		}




		gzclose(binary_original);
		fclose(binary_temporary);

		g_free(game_buffer);

		g_free(zip_original_path);
		g_free(zip_target_path);

		g_free(binary_temporary_path);
		g_free(binary_original_path);

		return TRUE;
	}

	return FALSE;
}
static char*
idol_disc_recorder_plugin_write_video_project (IdolDiscRecorderPlugin *pi,
						char **error)
{
	xmlTextWriter *project;
	xmlDocPtr doc = NULL;
	xmlSaveCtxt *save;
	xmlChar *escaped;
	gint success;
	char *title, *path, *uri;
	int fd;

	/* get a temporary path */
	path = g_build_filename (g_get_tmp_dir (), "brasero-tmp-project-XXXXXX",  NULL);
	fd = g_mkstemp (path);
	if (!fd) {
		g_free (path);

		*error = g_strdup (_("Unable to write a project."));
		return NULL;
	}

	project = xmlNewTextWriterDoc (&doc, 0);
	if (!project) {
		g_remove (path);
		g_free (path);
		close (fd);

		*error = g_strdup (_("Unable to write a project."));
		return NULL;
	}

	xmlTextWriterSetIndent (project, 1);
	xmlTextWriterSetIndentString (project, (xmlChar *) "\t");

	success = xmlTextWriterStartDocument (project,
					      NULL,
					      "UTF8",
					      NULL);
	if (success < 0)
		goto error;

	success = xmlTextWriterStartElement (project, (xmlChar *) "braseroproject");
	if (success < 0)
		goto error;

	/* write the name of the version */
	success = xmlTextWriterWriteElement (project,
					     (xmlChar *) "version",
					     (xmlChar *) "0.2");
	if (success < 0)
		goto error;

	title = idol_get_short_title (pi->idol);
	if (title) {
		success = xmlTextWriterWriteElement (project,
						     (xmlChar *) "label",
						     (xmlChar *) title);
		g_free (title);

		if (success < 0)
			goto error;
	}

	success = xmlTextWriterStartElement (project, (xmlChar *) "track");
	if (success < 0)
		goto error;

	success = xmlTextWriterStartElement (project, (xmlChar *) "video");
	if (success < 0)
		goto error;

	uri = idol_get_current_mrl (pi->idol);
	escaped = (unsigned char *) g_uri_escape_string (uri, NULL, FALSE);
	g_free (uri);

	success = xmlTextWriterWriteElement (project,
					     (xmlChar *) "uri",
					     escaped);
	g_free (escaped);
	if (success == -1)
		goto error;

	/* start of the song always 0 */
	success = xmlTextWriterWriteElement (project,
					     (xmlChar *) "start",
					     (xmlChar *) "0");
	if (success == -1)
		goto error;

	success = xmlTextWriterEndElement (project); /* video */
	if (success < 0)
		goto error;

	success = xmlTextWriterEndElement (project); /* track */
	if (success < 0)
		goto error;

	success = xmlTextWriterEndElement (project); /* braseroproject */
	if (success < 0)
		goto error;

	xmlTextWriterEndDocument (project);
	xmlFreeTextWriter (project);

	save = xmlSaveToFd (fd, "UTF8", XML_SAVE_FORMAT);
	xmlSaveDoc (save, doc);
	xmlSaveClose (save);

	xmlFreeDoc (doc);
	close (fd);

	return path;

error:

	/* cleanup */
	xmlTextWriterEndDocument (project);
	xmlFreeTextWriter (project);

	g_remove (path);
	g_free (path);
	close (fd);

	*error = g_strdup (_("Unable to write a project."));
	return NULL;
}
Exemplo n.º 22
0
gchar *
get_user_xml_file (const gchar *filename)
{
  return g_build_filename (g_get_tmp_dir (), filename, NULL);
}
gchar *cairo_dock_edit_themes (GHashTable **hThemeTable, gboolean bSafeMode)
{
	//\___________________ On recupere la liste des themes existant (pre-installes et utilisateur).
	GError *erreur = NULL;
	gchar *cThemesDir = CAIRO_DOCK_SHARE_THEMES_DIR;
	*hThemeTable = cairo_dock_list_themes (cThemesDir, NULL, &erreur);
	if (erreur != NULL)
	{
		cd_warning ("Attention : %s", erreur->message);
		g_error_free (erreur);
		erreur = NULL;
	}
	g_hash_table_insert (*hThemeTable, g_strdup (""), g_strdup (""));

	cThemesDir = g_strdup_printf ("%s/%s", g_cCairoDockDataDir, CAIRO_DOCK_THEMES_DIR);
	*hThemeTable = cairo_dock_list_themes (cThemesDir, *hThemeTable, &erreur);
	if (erreur != NULL)
	{
		cd_warning ("Attention : %s", erreur->message);
		g_error_free (erreur);
		erreur = NULL;
	}

	GHashTable *hUserThemeTable = cairo_dock_list_themes (cThemesDir, NULL, NULL);
	g_free (cThemesDir);

	gchar *cUserThemeNames = cairo_dock_write_table_content (hUserThemeTable, (GHFunc) cairo_dock_write_one_name, TRUE, FALSE);

	//\___________________ On cree un fichier de conf temporaire.
	const gchar *cTmpDir = g_get_tmp_dir ();
	gchar *cTmpConfFile = g_strdup_printf ("%s/cairo-dock-init", cTmpDir);

	gchar *cCommand = g_strdup_printf ("cp %s/%s %s", CAIRO_DOCK_SHARE_DATA_DIR, CAIRO_DOCK_THEME_CONF_FILE, cTmpConfFile);
	system (cCommand);
	g_free (cCommand);

	//\___________________ On met a jour ce fichier de conf.
	GKeyFile *pKeyFile = g_key_file_new ();
	g_key_file_load_from_file (pKeyFile, cTmpConfFile, G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS, &erreur);
	if (erreur != NULL)
	{
		cd_warning ("Attention : %s", erreur->message);
		g_error_free (erreur);
		return NULL;
	}
	
	cairo_dock_update_conf_file_with_themes (pKeyFile, cTmpConfFile, *hThemeTable, "Themes", "chosen theme");
	cairo_dock_update_conf_file_with_hash_table (pKeyFile, cTmpConfFile, hUserThemeTable, "Delete", "wanted themes", NULL, (GHFunc) cairo_dock_write_one_name, TRUE, FALSE);
	cairo_dock_update_conf_file_with_hash_table (pKeyFile, cTmpConfFile, hUserThemeTable, "Save", "theme name", NULL, (GHFunc) cairo_dock_write_one_name, TRUE, FALSE);
	g_hash_table_destroy (hUserThemeTable);
	
	g_key_file_set_string (pKeyFile, "Delete", "wanted themes", cUserThemeNames);  // sThemeNames
	g_free (cUserThemeNames);

	cairo_dock_write_keys_to_file (pKeyFile, cTmpConfFile);
	g_key_file_free (pKeyFile);

	//\___________________ On laisse l'utilisateur l'editer.
	gchar *cPresentedGroup = (cairo_dock_theme_need_save () ? "Save" : NULL);
	const gchar *cTitle = (bSafeMode ? _("< Safe Mode >") : _("Manage Themes"));
	
	CairoDialog *pDialog = NULL;
	if (bSafeMode)
	{
		pDialog = cairo_dock_show_general_message (_("You are running Cairo-Dock in safe mode.\nWhy ? Probably because a plug-in has messed into your dock,\n or maybe your theme has got corrupted.\nSo, no plug-in will be available, and you can now save your current theme if you want\n before you start using the dock.\nTry with your current theme, if it works, it means a plug-in is wrong.\nOtherwise, try with another theme.\nSave a config that is working, and restart the dock in normal mode.\nThen, activate plug-ins one by one to guess which one is wrong."), 0.);
	}
	
	gboolean bChoiceOK = cairo_dock_edit_conf_file (NULL, cTmpConfFile, cTitle, CAIRO_DOCK_THEME_PANEL_WIDTH, CAIRO_DOCK_THEME_PANEL_HEIGHT, 0, cPresentedGroup, NULL, NULL, NULL, NULL);
	if (! bChoiceOK)
	{
		g_remove (cTmpConfFile);
		g_free (cTmpConfFile);
		cTmpConfFile = NULL;
	}
	if (bSafeMode)
		cairo_dock_dialog_unreference (pDialog);
	
	return cTmpConfFile;
}