#! /bin/sh /usr/share/dpatch/dpatch-run
## 40_gio_file_saving.dpatch by Alexey Antipov (1a_antipov@mail.ru)
##
## All lines beginning with `## DP:' are a description of the patch.
## DP: Use GIO API (GFile) for saving files, if possible
@DPATCH@
--- ./src/document.c	(revision 4788)
+++ ./src/document.c	(working copy)
@@ -1686,14 +1686,22 @@
 static gchar *write_data_to_disk(GeanyDocument *doc, const gchar *locale_filename,
 								 const gchar *data, gint len)
 {
-	FILE *fp;
-	gint bytes_written;
-	gint err = 0;
 	GError *error = NULL;
 
 	g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
 	g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
 
+#ifdef HAVE_GIO
+	//Use GIO API to save file (GVFS-safe)
+	GFile *fp = g_file_new_for_path(locale_filename);  
+	g_file_replace_contents(fp, data, len, NULL, (file_prefs.use_safe_file_saving!=FALSE), G_FILE_CREATE_NONE, NULL, NULL, &error);
+#else
+	//Use POSIX API for unsafe saving (GVFS-unsafe)
+	//Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons)
+	gint err = 0;
+	FILE *fp;
+	gint bytes_written;
+
 	if (! file_prefs.use_safe_file_saving)
 	{
 		fp = g_fopen(locale_filename, "wb");
@@ -1713,14 +1721,14 @@
 	else
 	{
 		g_file_set_contents(locale_filename, data, len, &error);
-		if (error != NULL)
-		{
-			gchar *msg = g_strdup(error->message);
-			g_error_free(error);
-			return msg;
-		}
 	}
-
+#endif
+	if (error != NULL)
+	{
+		gchar *msg = g_strdup(error->message);
+		g_error_free(error);
+		return msg;
+	}
 	/* now the file is on disk, set real_path */
 	if (doc->real_path == NULL)
 	{
