Imported Upstream version 2.60.4
[platform/upstream/glib.git] / gio / gfile.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2
3 /* GIO - GLib Input, Output and Streaming Library
4  * 
5  * Copyright (C) 2006-2007 Red Hat, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  *
20  * Author: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include "config.h"
24
25 #ifdef __linux__
26 #include <sys/ioctl.h>
27 #include <errno.h>
28 /* See linux.git/fs/btrfs/ioctl.h */
29 #define BTRFS_IOCTL_MAGIC 0x94
30 #define BTRFS_IOC_CLONE _IOW(BTRFS_IOCTL_MAGIC, 9, int)
31 #endif
32
33 #ifdef HAVE_SPLICE
34 #include <sys/stat.h>
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <errno.h>
38 #endif
39
40 #include <string.h>
41 #include <sys/types.h>
42
43 #include "gfile.h"
44 #include "glib/gstdio.h"
45 #ifdef G_OS_UNIX
46 #include "glib-unix.h"
47 #endif
48 #include "gvfs.h"
49 #include "gtask.h"
50 #include "gfileattribute-priv.h"
51 #include "gfiledescriptorbased.h"
52 #include "gpollfilemonitor.h"
53 #include "gappinfo.h"
54 #include "gfileinputstream.h"
55 #include "gfileoutputstream.h"
56 #include "glocalfileoutputstream.h"
57 #include "glocalfileiostream.h"
58 #include "glocalfile.h"
59 #include "gcancellable.h"
60 #include "gasyncresult.h"
61 #include "gioerror.h"
62 #include "glibintl.h"
63
64
65 /**
66  * SECTION:gfile
67  * @short_description: File and Directory Handling
68  * @include: gio/gio.h
69  * @see_also: #GFileInfo, #GFileEnumerator
70  *
71  * #GFile is a high level abstraction for manipulating files on a
72  * virtual file system. #GFiles are lightweight, immutable objects
73  * that do no I/O upon creation. It is necessary to understand that
74  * #GFile objects do not represent files, merely an identifier for a
75  * file. All file content I/O is implemented as streaming operations
76  * (see #GInputStream and #GOutputStream).
77  *
78  * To construct a #GFile, you can use:
79  * - g_file_new_for_path() if you have a path.
80  * - g_file_new_for_uri() if you have a URI.
81  * - g_file_new_for_commandline_arg() for a command line argument.
82  * - g_file_new_tmp() to create a temporary file from a template.
83  * - g_file_parse_name() from a UTF-8 string gotten from g_file_get_parse_name().
84  * - g_file_new_build_filename() to create a file from path elements.
85  *
86  * One way to think of a #GFile is as an abstraction of a pathname. For
87  * normal files the system pathname is what is stored internally, but as
88  * #GFiles are extensible it could also be something else that corresponds
89  * to a pathname in a userspace implementation of a filesystem.
90  *
91  * #GFiles make up hierarchies of directories and files that correspond to
92  * the files on a filesystem. You can move through the file system with
93  * #GFile using g_file_get_parent() to get an identifier for the parent
94  * directory, g_file_get_child() to get a child within a directory,
95  * g_file_resolve_relative_path() to resolve a relative path between two
96  * #GFiles. There can be multiple hierarchies, so you may not end up at
97  * the same root if you repeatedly call g_file_get_parent() on two different
98  * files.
99  *
100  * All #GFiles have a basename (get with g_file_get_basename()). These names
101  * are byte strings that are used to identify the file on the filesystem
102  * (relative to its parent directory) and there is no guarantees that they
103  * have any particular charset encoding or even make any sense at all. If
104  * you want to use filenames in a user interface you should use the display
105  * name that you can get by requesting the
106  * %G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME attribute with g_file_query_info().
107  * This is guaranteed to be in UTF-8 and can be used in a user interface.
108  * But always store the real basename or the #GFile to use to actually
109  * access the file, because there is no way to go from a display name to
110  * the actual name.
111  *
112  * Using #GFile as an identifier has the same weaknesses as using a path
113  * in that there may be multiple aliases for the same file. For instance,
114  * hard or soft links may cause two different #GFiles to refer to the same
115  * file. Other possible causes for aliases are: case insensitive filesystems,
116  * short and long names on FAT/NTFS, or bind mounts in Linux. If you want to
117  * check if two #GFiles point to the same file you can query for the
118  * %G_FILE_ATTRIBUTE_ID_FILE attribute. Note that #GFile does some trivial
119  * canonicalization of pathnames passed in, so that trivial differences in
120  * the path string used at creation (duplicated slashes, slash at end of
121  * path, "." or ".." path segments, etc) does not create different #GFiles.
122  *
123  * Many #GFile operations have both synchronous and asynchronous versions
124  * to suit your application. Asynchronous versions of synchronous functions
125  * simply have _async() appended to their function names. The asynchronous
126  * I/O functions call a #GAsyncReadyCallback which is then used to finalize
127  * the operation, producing a GAsyncResult which is then passed to the
128  * function's matching _finish() operation.
129  *
130  * It is highly recommended to use asynchronous calls when running within a
131  * shared main loop, such as in the main thread of an application. This avoids
132  * I/O operations blocking other sources on the main loop from being dispatched.
133  * Synchronous I/O operations should be performed from worker threads. See the
134  * [introduction to asynchronous programming section][async-programming] for
135  * more.
136  *
137  * Some #GFile operations almost always take a noticeable amount of time, and
138  * so do not have synchronous analogs. Notable cases include:
139  * - g_file_mount_mountable() to mount a mountable file.
140  * - g_file_unmount_mountable_with_operation() to unmount a mountable file.
141  * - g_file_eject_mountable_with_operation() to eject a mountable file.
142  *
143  * ## Entity Tags # {#gfile-etag}
144  *
145  * One notable feature of #GFiles are entity tags, or "etags" for
146  * short. Entity tags are somewhat like a more abstract version of the
147  * traditional mtime, and can be used to quickly determine if the file
148  * has been modified from the version on the file system. See the
149  * HTTP 1.1 
150  * [specification](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html)
151  * for HTTP Etag headers, which are a very similar concept.
152  */
153
154 static void               g_file_real_query_info_async            (GFile                  *file,
155                                                                    const char             *attributes,
156                                                                    GFileQueryInfoFlags     flags,
157                                                                    int                     io_priority,
158                                                                    GCancellable           *cancellable,
159                                                                    GAsyncReadyCallback     callback,
160                                                                    gpointer                user_data);
161 static GFileInfo *        g_file_real_query_info_finish           (GFile                  *file,
162                                                                    GAsyncResult           *res,
163                                                                    GError                **error);
164 static void               g_file_real_query_filesystem_info_async (GFile                  *file,
165                                                                    const char             *attributes,
166                                                                    int                     io_priority,
167                                                                    GCancellable           *cancellable,
168                                                                    GAsyncReadyCallback     callback,
169                                                                    gpointer                user_data);
170 static GFileInfo *        g_file_real_query_filesystem_info_finish (GFile                  *file,
171                                                                    GAsyncResult           *res,
172                                                                    GError                **error);
173 static void               g_file_real_enumerate_children_async    (GFile                  *file,
174                                                                    const char             *attributes,
175                                                                    GFileQueryInfoFlags     flags,
176                                                                    int                     io_priority,
177                                                                    GCancellable           *cancellable,
178                                                                    GAsyncReadyCallback     callback,
179                                                                    gpointer                user_data);
180 static GFileEnumerator *  g_file_real_enumerate_children_finish   (GFile                  *file,
181                                                                    GAsyncResult           *res,
182                                                                    GError                **error);
183 static void               g_file_real_read_async                  (GFile                  *file,
184                                                                    int                     io_priority,
185                                                                    GCancellable           *cancellable,
186                                                                    GAsyncReadyCallback     callback,
187                                                                    gpointer                user_data);
188 static GFileInputStream * g_file_real_read_finish                 (GFile                  *file,
189                                                                    GAsyncResult           *res,
190                                                                    GError                **error);
191 static void               g_file_real_append_to_async             (GFile                  *file,
192                                                                    GFileCreateFlags        flags,
193                                                                    int                     io_priority,
194                                                                    GCancellable           *cancellable,
195                                                                    GAsyncReadyCallback     callback,
196                                                                    gpointer                user_data);
197 static GFileOutputStream *g_file_real_append_to_finish            (GFile                  *file,
198                                                                    GAsyncResult           *res,
199                                                                    GError                **error);
200 static void               g_file_real_create_async                (GFile                  *file,
201                                                                    GFileCreateFlags        flags,
202                                                                    int                     io_priority,
203                                                                    GCancellable           *cancellable,
204                                                                    GAsyncReadyCallback     callback,
205                                                                    gpointer                user_data);
206 static GFileOutputStream *g_file_real_create_finish               (GFile                  *file,
207                                                                    GAsyncResult           *res,
208                                                                    GError                **error);
209 static void               g_file_real_replace_async               (GFile                  *file,
210                                                                    const char             *etag,
211                                                                    gboolean                make_backup,
212                                                                    GFileCreateFlags        flags,
213                                                                    int                     io_priority,
214                                                                    GCancellable           *cancellable,
215                                                                    GAsyncReadyCallback     callback,
216                                                                    gpointer                user_data);
217 static GFileOutputStream *g_file_real_replace_finish              (GFile                  *file,
218                                                                    GAsyncResult           *res,
219                                                                    GError                **error);
220 static void               g_file_real_delete_async                (GFile                  *file,
221                                                                    int                     io_priority,
222                                                                    GCancellable           *cancellable,
223                                                                    GAsyncReadyCallback     callback,
224                                                                    gpointer                user_data);
225 static gboolean           g_file_real_delete_finish               (GFile                  *file,
226                                                                    GAsyncResult           *res,
227                                                                    GError                **error);
228 static void               g_file_real_trash_async                 (GFile                  *file,
229                                                                    int                     io_priority,
230                                                                    GCancellable           *cancellable,
231                                                                    GAsyncReadyCallback     callback,
232                                                                    gpointer                user_data);
233 static gboolean           g_file_real_trash_finish                (GFile                  *file,
234                                                                    GAsyncResult           *res,
235                                                                    GError                **error);
236 static void               g_file_real_make_directory_async        (GFile                  *file,
237                                                                    int                     io_priority,
238                                                                    GCancellable           *cancellable,
239                                                                    GAsyncReadyCallback     callback,
240                                                                    gpointer                user_data);
241 static gboolean           g_file_real_make_directory_finish       (GFile                  *file,
242                                                                    GAsyncResult           *res,
243                                                                    GError                **error);
244 static void               g_file_real_open_readwrite_async        (GFile                  *file,
245                                                                    int                  io_priority,
246                                                                    GCancellable           *cancellable,
247                                                                    GAsyncReadyCallback     callback,
248                                                                    gpointer                user_data);
249 static GFileIOStream *    g_file_real_open_readwrite_finish       (GFile                  *file,
250                                                                    GAsyncResult           *res,
251                                                                    GError                **error);
252 static void               g_file_real_create_readwrite_async      (GFile                  *file,
253                                                                    GFileCreateFlags        flags,
254                                                                    int                     io_priority,
255                                                                    GCancellable           *cancellable,
256                                                                    GAsyncReadyCallback     callback,
257                                                                    gpointer                user_data);
258 static GFileIOStream *    g_file_real_create_readwrite_finish     (GFile                  *file,
259                                                                    GAsyncResult           *res,
260                                                                    GError                **error);
261 static void               g_file_real_replace_readwrite_async     (GFile                  *file,
262                                                                    const char             *etag,
263                                                                    gboolean                make_backup,
264                                                                    GFileCreateFlags        flags,
265                                                                    int                     io_priority,
266                                                                    GCancellable           *cancellable,
267                                                                    GAsyncReadyCallback     callback,
268                                                                    gpointer                user_data);
269 static GFileIOStream *    g_file_real_replace_readwrite_finish    (GFile                  *file,
270                                                                   GAsyncResult            *res,
271                                                                   GError                 **error);
272 static gboolean           g_file_real_set_attributes_from_info    (GFile                  *file,
273                                                                    GFileInfo              *info,
274                                                                    GFileQueryInfoFlags     flags,
275                                                                    GCancellable           *cancellable,
276                                                                    GError                **error);
277 static void               g_file_real_set_display_name_async      (GFile                  *file,
278                                                                    const char             *display_name,
279                                                                    int                     io_priority,
280                                                                    GCancellable           *cancellable,
281                                                                    GAsyncReadyCallback     callback,
282                                                                    gpointer                user_data);
283 static GFile *            g_file_real_set_display_name_finish     (GFile                  *file,
284                                                                    GAsyncResult           *res,
285                                                                    GError                **error);
286 static void               g_file_real_set_attributes_async        (GFile                  *file,
287                                                                    GFileInfo              *info,
288                                                                    GFileQueryInfoFlags     flags,
289                                                                    int                     io_priority,
290                                                                    GCancellable           *cancellable,
291                                                                    GAsyncReadyCallback     callback,
292                                                                    gpointer                user_data);
293 static gboolean           g_file_real_set_attributes_finish       (GFile                  *file,
294                                                                    GAsyncResult           *res,
295                                                                    GFileInfo             **info,
296                                                                    GError                **error);
297 static void               g_file_real_find_enclosing_mount_async  (GFile                  *file,
298                                                                    int                     io_priority,
299                                                                    GCancellable           *cancellable,
300                                                                    GAsyncReadyCallback     callback,
301                                                                    gpointer                user_data);
302 static GMount *           g_file_real_find_enclosing_mount_finish (GFile                  *file,
303                                                                    GAsyncResult           *res,
304                                                                    GError                **error);
305 static void               g_file_real_copy_async                  (GFile                  *source,
306                                                                    GFile                  *destination,
307                                                                    GFileCopyFlags          flags,
308                                                                    int                     io_priority,
309                                                                    GCancellable           *cancellable,
310                                                                    GFileProgressCallback   progress_callback,
311                                                                    gpointer                progress_callback_data,
312                                                                    GAsyncReadyCallback     callback,
313                                                                    gpointer                user_data);
314 static gboolean           g_file_real_copy_finish                 (GFile                  *file,
315                                                                    GAsyncResult           *res,
316                                                                    GError                **error);
317
318 static gboolean           g_file_real_measure_disk_usage          (GFile                         *file,
319                                                                    GFileMeasureFlags              flags,
320                                                                    GCancellable                  *cancellable,
321                                                                    GFileMeasureProgressCallback   progress_callback,
322                                                                    gpointer                       progress_data,
323                                                                    guint64                       *disk_usage,
324                                                                    guint64                       *num_dirs,
325                                                                    guint64                       *num_files,
326                                                                    GError                       **error);
327 static void               g_file_real_measure_disk_usage_async    (GFile                         *file,
328                                                                    GFileMeasureFlags              flags,
329                                                                    gint                           io_priority,
330                                                                    GCancellable                  *cancellable,
331                                                                    GFileMeasureProgressCallback   progress_callback,
332                                                                    gpointer                       progress_data,
333                                                                    GAsyncReadyCallback            callback,
334                                                                    gpointer                       user_data);
335 static gboolean           g_file_real_measure_disk_usage_finish   (GFile                         *file,
336                                                                    GAsyncResult                  *result,
337                                                                    guint64                       *disk_usage,
338                                                                    guint64                       *num_dirs,
339                                                                    guint64                       *num_files,
340                                                                    GError                       **error);
341
342 typedef GFileIface GFileInterface;
343 G_DEFINE_INTERFACE (GFile, g_file, G_TYPE_OBJECT)
344
345 static void
346 g_file_default_init (GFileIface *iface)
347 {
348   iface->enumerate_children_async = g_file_real_enumerate_children_async;
349   iface->enumerate_children_finish = g_file_real_enumerate_children_finish;
350   iface->set_display_name_async = g_file_real_set_display_name_async;
351   iface->set_display_name_finish = g_file_real_set_display_name_finish;
352   iface->query_info_async = g_file_real_query_info_async;
353   iface->query_info_finish = g_file_real_query_info_finish;
354   iface->query_filesystem_info_async = g_file_real_query_filesystem_info_async;
355   iface->query_filesystem_info_finish = g_file_real_query_filesystem_info_finish;
356   iface->set_attributes_async = g_file_real_set_attributes_async;
357   iface->set_attributes_finish = g_file_real_set_attributes_finish;
358   iface->read_async = g_file_real_read_async;
359   iface->read_finish = g_file_real_read_finish;
360   iface->append_to_async = g_file_real_append_to_async;
361   iface->append_to_finish = g_file_real_append_to_finish;
362   iface->create_async = g_file_real_create_async;
363   iface->create_finish = g_file_real_create_finish;
364   iface->replace_async = g_file_real_replace_async;
365   iface->replace_finish = g_file_real_replace_finish;
366   iface->delete_file_async = g_file_real_delete_async;
367   iface->delete_file_finish = g_file_real_delete_finish;
368   iface->trash_async = g_file_real_trash_async;
369   iface->trash_finish = g_file_real_trash_finish;
370   iface->make_directory_async = g_file_real_make_directory_async;
371   iface->make_directory_finish = g_file_real_make_directory_finish;
372   iface->open_readwrite_async = g_file_real_open_readwrite_async;
373   iface->open_readwrite_finish = g_file_real_open_readwrite_finish;
374   iface->create_readwrite_async = g_file_real_create_readwrite_async;
375   iface->create_readwrite_finish = g_file_real_create_readwrite_finish;
376   iface->replace_readwrite_async = g_file_real_replace_readwrite_async;
377   iface->replace_readwrite_finish = g_file_real_replace_readwrite_finish;
378   iface->find_enclosing_mount_async = g_file_real_find_enclosing_mount_async;
379   iface->find_enclosing_mount_finish = g_file_real_find_enclosing_mount_finish;
380   iface->set_attributes_from_info = g_file_real_set_attributes_from_info;
381   iface->copy_async = g_file_real_copy_async;
382   iface->copy_finish = g_file_real_copy_finish;
383   iface->measure_disk_usage = g_file_real_measure_disk_usage;
384   iface->measure_disk_usage_async = g_file_real_measure_disk_usage_async;
385   iface->measure_disk_usage_finish = g_file_real_measure_disk_usage_finish;
386 }
387
388
389 /**
390  * g_file_is_native:
391  * @file: input #GFile
392  *
393  * Checks to see if a file is native to the platform.
394  *
395  * A native file is one expressed in the platform-native filename format,
396  * e.g. "C:\Windows" or "/usr/bin/". This does not mean the file is local,
397  * as it might be on a locally mounted remote filesystem.
398  *
399  * On some systems non-native files may be available using the native
400  * filesystem via a userspace filesystem (FUSE), in these cases this call
401  * will return %FALSE, but g_file_get_path() will still return a native path.
402  *
403  * This call does no blocking I/O.
404  *
405  * Returns: %TRUE if @file is native
406  */
407 gboolean
408 g_file_is_native (GFile *file)
409 {
410   GFileIface *iface;
411
412   g_return_val_if_fail (G_IS_FILE (file), FALSE);
413
414   iface = G_FILE_GET_IFACE (file);
415
416   return (* iface->is_native) (file);
417 }
418
419
420 /**
421  * g_file_has_uri_scheme:
422  * @file: input #GFile
423  * @uri_scheme: a string containing a URI scheme
424  *
425  * Checks to see if a #GFile has a given URI scheme.
426  *
427  * This call does no blocking I/O.
428  *
429  * Returns: %TRUE if #GFile's backend supports the
430  *     given URI scheme, %FALSE if URI scheme is %NULL,
431  *     not supported, or #GFile is invalid.
432  */
433 gboolean
434 g_file_has_uri_scheme (GFile      *file,
435                        const char *uri_scheme)
436 {
437   GFileIface *iface;
438
439   g_return_val_if_fail (G_IS_FILE (file), FALSE);
440   g_return_val_if_fail (uri_scheme != NULL, FALSE);
441
442   iface = G_FILE_GET_IFACE (file);
443
444   return (* iface->has_uri_scheme) (file, uri_scheme);
445 }
446
447
448 /**
449  * g_file_get_uri_scheme:
450  * @file: input #GFile
451  *
452  * Gets the URI scheme for a #GFile.
453  * RFC 3986 decodes the scheme as:
454  * |[
455  * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
456  * ]|
457  * Common schemes include "file", "http", "ftp", etc.
458  *
459  * This call does no blocking I/O.
460  *
461  * Returns: a string containing the URI scheme for the given
462  *     #GFile. The returned string should be freed with g_free()
463  *     when no longer needed.
464  */
465 char *
466 g_file_get_uri_scheme (GFile *file)
467 {
468   GFileIface *iface;
469
470   g_return_val_if_fail (G_IS_FILE (file), NULL);
471
472   iface = G_FILE_GET_IFACE (file);
473
474   return (* iface->get_uri_scheme) (file);
475 }
476
477
478 /**
479  * g_file_get_basename:
480  * @file: input #GFile
481  *
482  * Gets the base name (the last component of the path) for a given #GFile.
483  *
484  * If called for the top level of a system (such as the filesystem root
485  * or a uri like sftp://host/) it will return a single directory separator
486  * (and on Windows, possibly a drive letter).
487  *
488  * The base name is a byte string (not UTF-8). It has no defined encoding
489  * or rules other than it may not contain zero bytes.  If you want to use
490  * filenames in a user interface you should use the display name that you
491  * can get by requesting the %G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME
492  * attribute with g_file_query_info().
493  *
494  * This call does no blocking I/O.
495  *
496  * Returns: (type filename) (nullable): string containing the #GFile's
497  *     base name, or %NULL if given #GFile is invalid. The returned string
498  *     should be freed with g_free() when no longer needed.
499  */
500 char *
501 g_file_get_basename (GFile *file)
502 {
503   GFileIface *iface;
504
505   g_return_val_if_fail (G_IS_FILE (file), NULL);
506
507   iface = G_FILE_GET_IFACE (file);
508
509   return (* iface->get_basename) (file);
510 }
511
512 /**
513  * g_file_get_path:
514  * @file: input #GFile
515  *
516  * Gets the local pathname for #GFile, if one exists. If non-%NULL, this is
517  * guaranteed to be an absolute, canonical path. It might contain symlinks.
518  *
519  * This call does no blocking I/O.
520  *
521  * Returns: (type filename) (nullable): string containing the #GFile's path,
522  *     or %NULL if no such path exists. The returned string should be freed
523  *     with g_free() when no longer needed.
524  */
525 char *
526 g_file_get_path (GFile *file)
527 {
528   GFileIface *iface;
529
530   g_return_val_if_fail (G_IS_FILE (file), NULL);
531
532   iface = G_FILE_GET_IFACE (file);
533
534   return (* iface->get_path) (file);
535 }
536
537 /* Original commit introducing this in libgsystem:
538  *
539  *  fileutil: Handle recent: and trash: URIs
540  *
541  *  The gs_file_get_path_cached() was rather brittle in its handling
542  *  of URIs. It would assert() when a GFile didn't have a backing path
543  *  (such as when handling trash: or recent: URIs), and didn't know
544  *  how to get the target URI for those items either.
545  *
546  *  Make sure that we do not assert() when a backing path cannot be
547  *  found, and handle recent: and trash: URIs.
548  *
549  *  https://bugzilla.gnome.org/show_bug.cgi?id=708435
550  */
551 static char *
552 file_get_target_path (GFile *file)
553 {
554   GFileInfo *info;
555   const char *target;
556   char *path;
557
558   info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_TARGET_URI, G_FILE_QUERY_INFO_NONE, NULL, NULL);
559   if (info == NULL)
560     return NULL;
561   target = g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_STANDARD_TARGET_URI);
562   path = g_filename_from_uri (target, NULL, NULL);
563   g_object_unref (info);
564
565   return path;
566 }
567
568 static const char *
569 file_peek_path_generic (GFile *file)
570 {
571   const char *path;
572   static GQuark _file_path_quark = 0;
573
574   if (G_UNLIKELY (_file_path_quark) == 0)
575     _file_path_quark = g_quark_from_static_string ("gio-file-path");
576
577   /* We need to be careful about threading, as two threads calling
578    * g_file_peek_path() on the same file could race: both would see
579    * (g_object_get_qdata(…) == NULL) to begin with, both would generate and add
580    * the path, but the second thread to add it would end up freeing the path
581    * set by the first thread. The first thread would still return the pointer
582    * to that freed path, though, resulting an a read-after-free. Handle that
583    * with a compare-and-swap loop. The g_object_*_qdata() functions are atomic. */
584
585   while (TRUE)
586     {
587       gchar *new_path = NULL;
588
589       path = g_object_get_qdata ((GObject*)file, _file_path_quark);
590
591       if (path != NULL)
592         break;
593
594       if (g_file_has_uri_scheme (file, "trash") ||
595           g_file_has_uri_scheme (file, "recent"))
596         new_path = file_get_target_path (file);
597       else
598         new_path = g_file_get_path (file);
599       if (new_path == NULL)
600         return NULL;
601
602       /* By passing NULL here, we ensure we never replace existing data: */
603       if (g_object_replace_qdata ((GObject *) file, _file_path_quark,
604                                   NULL, (gpointer) new_path,
605                                   (GDestroyNotify) g_free, NULL))
606         break;
607       else
608         g_free (new_path);
609     }
610
611   return path;
612 }
613
614 /**
615  * g_file_peek_path:
616  * @file: input #GFile
617  *
618  * Exactly like g_file_get_path(), but caches the result via
619  * g_object_set_qdata_full().  This is useful for example in C
620  * applications which mix `g_file_*` APIs with native ones.  It
621  * also avoids an extra duplicated string when possible, so will be
622  * generally more efficient.
623  *
624  * This call does no blocking I/O.
625  *
626  * Returns: (type filename) (nullable): string containing the #GFile's path,
627  *     or %NULL if no such path exists. The returned string is owned by @file.
628  * Since: 2.56
629  */
630 const char *
631 g_file_peek_path (GFile *file)
632 {
633   if (G_IS_LOCAL_FILE (file))
634     return _g_local_file_get_filename ((GLocalFile *) file);
635   return file_peek_path_generic (file);
636 }
637
638 /**
639  * g_file_get_uri:
640  * @file: input #GFile
641  *
642  * Gets the URI for the @file.
643  *
644  * This call does no blocking I/O.
645  *
646  * Returns: a string containing the #GFile's URI.
647  *     The returned string should be freed with g_free()
648  *     when no longer needed.
649  */
650 char *
651 g_file_get_uri (GFile *file)
652 {
653   GFileIface *iface;
654
655   g_return_val_if_fail (G_IS_FILE (file), NULL);
656
657   iface = G_FILE_GET_IFACE (file);
658
659   return (* iface->get_uri) (file);
660 }
661
662 /**
663  * g_file_get_parse_name:
664  * @file: input #GFile
665  *
666  * Gets the parse name of the @file.
667  * A parse name is a UTF-8 string that describes the
668  * file such that one can get the #GFile back using
669  * g_file_parse_name().
670  *
671  * This is generally used to show the #GFile as a nice
672  * full-pathname kind of string in a user interface,
673  * like in a location entry.
674  *
675  * For local files with names that can safely be converted
676  * to UTF-8 the pathname is used, otherwise the IRI is used
677  * (a form of URI that allows UTF-8 characters unescaped).
678  *
679  * This call does no blocking I/O.
680  *
681  * Returns: a string containing the #GFile's parse name.
682  *     The returned string should be freed with g_free()
683  *     when no longer needed.
684  */
685 char *
686 g_file_get_parse_name (GFile *file)
687 {
688   GFileIface *iface;
689
690   g_return_val_if_fail (G_IS_FILE (file), NULL);
691
692   iface = G_FILE_GET_IFACE (file);
693
694   return (* iface->get_parse_name) (file);
695 }
696
697 /**
698  * g_file_dup:
699  * @file: input #GFile
700  *
701  * Duplicates a #GFile handle. This operation does not duplicate
702  * the actual file or directory represented by the #GFile; see
703  * g_file_copy() if attempting to copy a file.
704  *
705  * g_file_dup() is useful when a second handle is needed to the same underlying
706  * file, for use in a separate thread (#GFile is not thread-safe). For use
707  * within the same thread, use g_object_ref() to increment the existing object’s
708  * reference count.
709  *
710  * This call does no blocking I/O.
711  *
712  * Returns: (transfer full): a new #GFile that is a duplicate
713  *     of the given #GFile.
714  */
715 GFile *
716 g_file_dup (GFile *file)
717 {
718   GFileIface *iface;
719
720   g_return_val_if_fail (G_IS_FILE (file), NULL);
721
722   iface = G_FILE_GET_IFACE (file);
723
724   return (* iface->dup) (file);
725 }
726
727 /**
728  * g_file_hash:
729  * @file: (type GFile): #gconstpointer to a #GFile
730  *
731  * Creates a hash value for a #GFile.
732  *
733  * This call does no blocking I/O.
734  *
735  * Virtual: hash
736  * Returns: 0 if @file is not a valid #GFile, otherwise an
737  *     integer that can be used as hash value for the #GFile.
738  *     This function is intended for easily hashing a #GFile to
739  *     add to a #GHashTable or similar data structure.
740  */
741 guint
742 g_file_hash (gconstpointer file)
743 {
744   GFileIface *iface;
745
746   g_return_val_if_fail (G_IS_FILE (file), 0);
747
748   iface = G_FILE_GET_IFACE (file);
749
750   return (* iface->hash) ((GFile *)file);
751 }
752
753 /**
754  * g_file_equal:
755  * @file1: the first #GFile
756  * @file2: the second #GFile
757  *
758  * Checks if the two given #GFiles refer to the same file.
759  *
760  * Note that two #GFiles that differ can still refer to the same
761  * file on the filesystem due to various forms of filename
762  * aliasing.
763  *
764  * This call does no blocking I/O.
765  *
766  * Returns: %TRUE if @file1 and @file2 are equal.
767  */
768 gboolean
769 g_file_equal (GFile *file1,
770               GFile *file2)
771 {
772   GFileIface *iface;
773
774   g_return_val_if_fail (G_IS_FILE (file1), FALSE);
775   g_return_val_if_fail (G_IS_FILE (file2), FALSE);
776
777   if (file1 == file2)
778     return TRUE;
779
780   if (G_TYPE_FROM_INSTANCE (file1) != G_TYPE_FROM_INSTANCE (file2))
781     return FALSE;
782
783   iface = G_FILE_GET_IFACE (file1);
784
785   return (* iface->equal) (file1, file2);
786 }
787
788
789 /**
790  * g_file_get_parent:
791  * @file: input #GFile
792  *
793  * Gets the parent directory for the @file.
794  * If the @file represents the root directory of the
795  * file system, then %NULL will be returned.
796  *
797  * This call does no blocking I/O.
798  *
799  * Returns: (nullable) (transfer full): a #GFile structure to the
800  *     parent of the given #GFile or %NULL if there is no parent. Free
801  *     the returned object with g_object_unref().
802  */
803 GFile *
804 g_file_get_parent (GFile *file)
805 {
806   GFileIface *iface;
807
808   g_return_val_if_fail (G_IS_FILE (file), NULL);
809
810   iface = G_FILE_GET_IFACE (file);
811
812   return (* iface->get_parent) (file);
813 }
814
815 /**
816  * g_file_has_parent:
817  * @file: input #GFile
818  * @parent: (nullable): the parent to check for, or %NULL
819  *
820  * Checks if @file has a parent, and optionally, if it is @parent.
821  *
822  * If @parent is %NULL then this function returns %TRUE if @file has any
823  * parent at all.  If @parent is non-%NULL then %TRUE is only returned
824  * if @file is an immediate child of @parent.
825  *
826  * Returns: %TRUE if @file is an immediate child of @parent (or any parent in
827  *          the case that @parent is %NULL).
828  *
829  * Since: 2.24
830  */
831 gboolean
832 g_file_has_parent (GFile *file,
833                    GFile *parent)
834 {
835   GFile *actual_parent;
836   gboolean result;
837
838   g_return_val_if_fail (G_IS_FILE (file), FALSE);
839   g_return_val_if_fail (parent == NULL || G_IS_FILE (parent), FALSE);
840
841   actual_parent = g_file_get_parent (file);
842
843   if (actual_parent != NULL)
844     {
845       if (parent != NULL)
846         result = g_file_equal (parent, actual_parent);
847       else
848         result = TRUE;
849
850       g_object_unref (actual_parent);
851     }
852   else
853     result = FALSE;
854
855   return result;
856 }
857
858 /**
859  * g_file_get_child:
860  * @file: input #GFile
861  * @name: (type filename): string containing the child's basename
862  *
863  * Gets a child of @file with basename equal to @name.
864  *
865  * Note that the file with that specific name might not exist, but
866  * you can still have a #GFile that points to it. You can use this
867  * for instance to create that file.
868  *
869  * This call does no blocking I/O.
870  *
871  * Returns: (transfer full): a #GFile to a child specified by @name.
872  *     Free the returned object with g_object_unref().
873  */
874 GFile *
875 g_file_get_child (GFile      *file,
876                   const char *name)
877 {
878   g_return_val_if_fail (G_IS_FILE (file), NULL);
879   g_return_val_if_fail (name != NULL, NULL);
880
881   return g_file_resolve_relative_path (file, name);
882 }
883
884 /**
885  * g_file_get_child_for_display_name:
886  * @file: input #GFile
887  * @display_name: string to a possible child
888  * @error: return location for an error
889  *
890  * Gets the child of @file for a given @display_name (i.e. a UTF-8
891  * version of the name). If this function fails, it returns %NULL
892  * and @error will be set. This is very useful when constructing a
893  * #GFile for a new file and the user entered the filename in the
894  * user interface, for instance when you select a directory and
895  * type a filename in the file selector.
896  *
897  * This call does no blocking I/O.
898  *
899  * Returns: (transfer full): a #GFile to the specified child, or
900  *     %NULL if the display name couldn't be converted.
901  *     Free the returned object with g_object_unref().
902  */
903 GFile *
904 g_file_get_child_for_display_name (GFile      *file,
905                                    const char *display_name,
906                                    GError **error)
907 {
908   GFileIface *iface;
909
910   g_return_val_if_fail (G_IS_FILE (file), NULL);
911   g_return_val_if_fail (display_name != NULL, NULL);
912
913   iface = G_FILE_GET_IFACE (file);
914
915   return (* iface->get_child_for_display_name) (file, display_name, error);
916 }
917
918 /**
919  * g_file_has_prefix:
920  * @file: input #GFile
921  * @prefix: input #GFile
922  *
923  * Checks whether @file has the prefix specified by @prefix.
924  *
925  * In other words, if the names of initial elements of @file's
926  * pathname match @prefix. Only full pathname elements are matched,
927  * so a path like /foo is not considered a prefix of /foobar, only
928  * of /foo/bar.
929  *
930  * A #GFile is not a prefix of itself. If you want to check for
931  * equality, use g_file_equal().
932  *
933  * This call does no I/O, as it works purely on names. As such it can
934  * sometimes return %FALSE even if @file is inside a @prefix (from a
935  * filesystem point of view), because the prefix of @file is an alias
936  * of @prefix.
937  *
938  * Virtual: prefix_matches
939  * Returns:  %TRUE if the @files's parent, grandparent, etc is @prefix,
940  *     %FALSE otherwise.
941  */
942 gboolean
943 g_file_has_prefix (GFile *file,
944                    GFile *prefix)
945 {
946   GFileIface *iface;
947
948   g_return_val_if_fail (G_IS_FILE (file), FALSE);
949   g_return_val_if_fail (G_IS_FILE (prefix), FALSE);
950
951   if (G_TYPE_FROM_INSTANCE (file) != G_TYPE_FROM_INSTANCE (prefix))
952     return FALSE;
953
954   iface = G_FILE_GET_IFACE (file);
955
956   /* The vtable function differs in arg order since
957    * we're using the old contains_file call
958    */
959   return (* iface->prefix_matches) (prefix, file);
960 }
961
962 /**
963  * g_file_get_relative_path:
964  * @parent: input #GFile
965  * @descendant: input #GFile
966  *
967  * Gets the path for @descendant relative to @parent.
968  *
969  * This call does no blocking I/O.
970  *
971  * Returns: (type filename) (nullable): string with the relative path from
972  *     @descendant to @parent, or %NULL if @descendant doesn't have @parent as
973  *     prefix. The returned string should be freed with g_free() when
974  *     no longer needed.
975  */
976 char *
977 g_file_get_relative_path (GFile *parent,
978                           GFile *descendant)
979 {
980   GFileIface *iface;
981
982   g_return_val_if_fail (G_IS_FILE (parent), NULL);
983   g_return_val_if_fail (G_IS_FILE (descendant), NULL);
984
985   if (G_TYPE_FROM_INSTANCE (parent) != G_TYPE_FROM_INSTANCE (descendant))
986     return NULL;
987
988   iface = G_FILE_GET_IFACE (parent);
989
990   return (* iface->get_relative_path) (parent, descendant);
991 }
992
993 /**
994  * g_file_resolve_relative_path:
995  * @file: input #GFile
996  * @relative_path: (type filename): a given relative path string
997  *
998  * Resolves a relative path for @file to an absolute path.
999  *
1000  * This call does no blocking I/O.
1001  *
1002  * Returns: (transfer full): #GFile to the resolved path.
1003  *     %NULL if @relative_path is %NULL or if @file is invalid.
1004  *     Free the returned object with g_object_unref().
1005  */
1006 GFile *
1007 g_file_resolve_relative_path (GFile      *file,
1008                               const char *relative_path)
1009 {
1010   GFileIface *iface;
1011
1012   g_return_val_if_fail (G_IS_FILE (file), NULL);
1013   g_return_val_if_fail (relative_path != NULL, NULL);
1014
1015   iface = G_FILE_GET_IFACE (file);
1016
1017   return (* iface->resolve_relative_path) (file, relative_path);
1018 }
1019
1020 /**
1021  * g_file_enumerate_children:
1022  * @file: input #GFile
1023  * @attributes: an attribute query string
1024  * @flags: a set of #GFileQueryInfoFlags
1025  * @cancellable: (nullable): optional #GCancellable object,
1026  *     %NULL to ignore
1027  * @error: #GError for error reporting
1028  *
1029  * Gets the requested information about the files in a directory.
1030  * The result is a #GFileEnumerator object that will give out
1031  * #GFileInfo objects for all the files in the directory.
1032  *
1033  * The @attributes value is a string that specifies the file
1034  * attributes that should be gathered. It is not an error if
1035  * it's not possible to read a particular requested attribute
1036  * from a file - it just won't be set. @attributes should
1037  * be a comma-separated list of attributes or attribute wildcards.
1038  * The wildcard "*" means all attributes, and a wildcard like
1039  * "standard::*" means all attributes in the standard namespace.
1040  * An example attribute query be "standard::*,owner::user".
1041  * The standard attributes are available as defines, like
1042  * #G_FILE_ATTRIBUTE_STANDARD_NAME.
1043  *
1044  * If @cancellable is not %NULL, then the operation can be cancelled
1045  * by triggering the cancellable object from another thread. If the
1046  * operation was cancelled, the error %G_IO_ERROR_CANCELLED will be
1047  * returned.
1048  *
1049  * If the file does not exist, the %G_IO_ERROR_NOT_FOUND error will
1050  * be returned. If the file is not a directory, the %G_IO_ERROR_NOT_DIRECTORY
1051  * error will be returned. Other errors are possible too.
1052  *
1053  * Returns: (transfer full): A #GFileEnumerator if successful,
1054  *     %NULL on error. Free the returned object with g_object_unref().
1055  */
1056 GFileEnumerator *
1057 g_file_enumerate_children (GFile                *file,
1058                            const char           *attributes,
1059                            GFileQueryInfoFlags   flags,
1060                            GCancellable         *cancellable,
1061                            GError              **error)
1062 {
1063   GFileIface *iface;
1064
1065   g_return_val_if_fail (G_IS_FILE (file), NULL);
1066
1067   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1068     return NULL;
1069
1070   iface = G_FILE_GET_IFACE (file);
1071
1072   if (iface->enumerate_children == NULL)
1073     {
1074       g_set_error_literal (error, G_IO_ERROR,
1075                            G_IO_ERROR_NOT_SUPPORTED,
1076                            _("Operation not supported"));
1077       return NULL;
1078     }
1079
1080   return (* iface->enumerate_children) (file, attributes, flags,
1081                                         cancellable, error);
1082 }
1083
1084 /**
1085  * g_file_enumerate_children_async:
1086  * @file: input #GFile
1087  * @attributes: an attribute query string
1088  * @flags: a set of #GFileQueryInfoFlags
1089  * @io_priority: the [I/O priority][io-priority] of the request
1090  * @cancellable: (nullable): optional #GCancellable object,
1091  *     %NULL to ignore
1092  * @callback: (scope async): a #GAsyncReadyCallback to call when the
1093  *     request is satisfied
1094  * @user_data: (closure): the data to pass to callback function
1095  *
1096  * Asynchronously gets the requested information about the files
1097  * in a directory. The result is a #GFileEnumerator object that will
1098  * give out #GFileInfo objects for all the files in the directory.
1099  *
1100  * For more details, see g_file_enumerate_children() which is
1101  * the synchronous version of this call.
1102  *
1103  * When the operation is finished, @callback will be called. You can
1104  * then call g_file_enumerate_children_finish() to get the result of
1105  * the operation.
1106  */
1107 void
1108 g_file_enumerate_children_async (GFile               *file,
1109                                  const char          *attributes,
1110                                  GFileQueryInfoFlags  flags,
1111                                  int                  io_priority,
1112                                  GCancellable        *cancellable,
1113                                  GAsyncReadyCallback  callback,
1114                                  gpointer             user_data)
1115 {
1116   GFileIface *iface;
1117
1118   g_return_if_fail (G_IS_FILE (file));
1119
1120   iface = G_FILE_GET_IFACE (file);
1121   (* iface->enumerate_children_async) (file,
1122                                        attributes,
1123                                        flags,
1124                                        io_priority,
1125                                        cancellable,
1126                                        callback,
1127                                        user_data);
1128 }
1129
1130 /**
1131  * g_file_enumerate_children_finish:
1132  * @file: input #GFile
1133  * @res: a #GAsyncResult
1134  * @error: a #GError
1135  *
1136  * Finishes an async enumerate children operation.
1137  * See g_file_enumerate_children_async().
1138  *
1139  * Returns: (transfer full): a #GFileEnumerator or %NULL
1140  *     if an error occurred.
1141  *     Free the returned object with g_object_unref().
1142  */
1143 GFileEnumerator *
1144 g_file_enumerate_children_finish (GFile         *file,
1145                                   GAsyncResult  *res,
1146                                   GError       **error)
1147 {
1148   GFileIface *iface;
1149
1150   g_return_val_if_fail (G_IS_FILE (file), NULL);
1151   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1152
1153   if (g_async_result_legacy_propagate_error (res, error))
1154     return NULL;
1155
1156   iface = G_FILE_GET_IFACE (file);
1157   return (* iface->enumerate_children_finish) (file, res, error);
1158 }
1159
1160 /**
1161  * g_file_query_exists:
1162  * @file: input #GFile
1163  * @cancellable: (nullable): optional #GCancellable object,
1164  *     %NULL to ignore
1165  *
1166  * Utility function to check if a particular file exists. This is
1167  * implemented using g_file_query_info() and as such does blocking I/O.
1168  *
1169  * Note that in many cases it is [racy to first check for file existence](https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use)
1170  * and then execute something based on the outcome of that, because the
1171  * file might have been created or removed in between the operations. The
1172  * general approach to handling that is to not check, but just do the
1173  * operation and handle the errors as they come.
1174  *
1175  * As an example of race-free checking, take the case of reading a file,
1176  * and if it doesn't exist, creating it. There are two racy versions: read
1177  * it, and on error create it; and: check if it exists, if not create it.
1178  * These can both result in two processes creating the file (with perhaps
1179  * a partially written file as the result). The correct approach is to
1180  * always try to create the file with g_file_create() which will either
1181  * atomically create the file or fail with a %G_IO_ERROR_EXISTS error.
1182  *
1183  * However, in many cases an existence check is useful in a user interface,
1184  * for instance to make a menu item sensitive/insensitive, so that you don't
1185  * have to fool users that something is possible and then just show an error
1186  * dialog. If you do this, you should make sure to also handle the errors
1187  * that can happen due to races when you execute the operation.
1188  *
1189  * Returns: %TRUE if the file exists (and can be detected without error),
1190  *     %FALSE otherwise (or if cancelled).
1191  */
1192 gboolean
1193 g_file_query_exists (GFile        *file,
1194                      GCancellable *cancellable)
1195 {
1196   GFileInfo *info;
1197
1198   g_return_val_if_fail (G_IS_FILE(file), FALSE);
1199
1200   info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_TYPE,
1201                             G_FILE_QUERY_INFO_NONE, cancellable, NULL);
1202   if (info != NULL)
1203     {
1204       g_object_unref (info);
1205       return TRUE;
1206     }
1207
1208   return FALSE;
1209 }
1210
1211 /**
1212  * g_file_query_file_type:
1213  * @file: input #GFile
1214  * @flags: a set of #GFileQueryInfoFlags passed to g_file_query_info()
1215  * @cancellable: (nullable): optional #GCancellable object,
1216  *     %NULL to ignore
1217  *
1218  * Utility function to inspect the #GFileType of a file. This is
1219  * implemented using g_file_query_info() and as such does blocking I/O.
1220  *
1221  * The primary use case of this method is to check if a file is
1222  * a regular file, directory, or symlink.
1223  *
1224  * Returns: The #GFileType of the file and #G_FILE_TYPE_UNKNOWN
1225  *     if the file does not exist
1226  *
1227  * Since: 2.18
1228  */
1229 GFileType
1230 g_file_query_file_type (GFile               *file,
1231                         GFileQueryInfoFlags  flags,
1232                         GCancellable        *cancellable)
1233 {
1234   GFileInfo *info;
1235   GFileType file_type;
1236
1237   g_return_val_if_fail (G_IS_FILE(file), G_FILE_TYPE_UNKNOWN);
1238   info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_TYPE, flags,
1239                             cancellable, NULL);
1240   if (info != NULL)
1241     {
1242       file_type = g_file_info_get_file_type (info);
1243       g_object_unref (info);
1244     }
1245   else
1246     file_type = G_FILE_TYPE_UNKNOWN;
1247
1248   return file_type;
1249 }
1250
1251 /**
1252  * g_file_query_info:
1253  * @file: input #GFile
1254  * @attributes: an attribute query string
1255  * @flags: a set of #GFileQueryInfoFlags
1256  * @cancellable: (nullable): optional #GCancellable object,
1257  *     %NULL to ignore
1258  * @error: a #GError
1259  *
1260  * Gets the requested information about specified @file.
1261  * The result is a #GFileInfo object that contains key-value
1262  * attributes (such as the type or size of the file).
1263  *
1264  * The @attributes value is a string that specifies the file
1265  * attributes that should be gathered. It is not an error if
1266  * it's not possible to read a particular requested attribute
1267  * from a file - it just won't be set. @attributes should be a
1268  * comma-separated list of attributes or attribute wildcards.
1269  * The wildcard "*" means all attributes, and a wildcard like
1270  * "standard::*" means all attributes in the standard namespace.
1271  * An example attribute query be "standard::*,owner::user".
1272  * The standard attributes are available as defines, like
1273  * #G_FILE_ATTRIBUTE_STANDARD_NAME.
1274  *
1275  * If @cancellable is not %NULL, then the operation can be cancelled
1276  * by triggering the cancellable object from another thread. If the
1277  * operation was cancelled, the error %G_IO_ERROR_CANCELLED will be
1278  * returned.
1279  *
1280  * For symlinks, normally the information about the target of the
1281  * symlink is returned, rather than information about the symlink
1282  * itself. However if you pass #G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS
1283  * in @flags the information about the symlink itself will be returned.
1284  * Also, for symlinks that point to non-existing files the information
1285  * about the symlink itself will be returned.
1286  *
1287  * If the file does not exist, the %G_IO_ERROR_NOT_FOUND error will be
1288  * returned. Other errors are possible too, and depend on what kind of
1289  * filesystem the file is on.
1290  *
1291  * Returns: (transfer full): a #GFileInfo for the given @file, or %NULL
1292  *     on error. Free the returned object with g_object_unref().
1293  */
1294 GFileInfo *
1295 g_file_query_info (GFile                *file,
1296                    const char           *attributes,
1297                    GFileQueryInfoFlags   flags,
1298                    GCancellable         *cancellable,
1299                    GError              **error)
1300 {
1301   GFileIface *iface;
1302
1303   g_return_val_if_fail (G_IS_FILE (file), NULL);
1304
1305   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1306     return NULL;
1307
1308   iface = G_FILE_GET_IFACE (file);
1309
1310   if (iface->query_info == NULL)
1311     {
1312       g_set_error_literal (error, G_IO_ERROR,
1313                            G_IO_ERROR_NOT_SUPPORTED,
1314                            _("Operation not supported"));
1315       return NULL;
1316     }
1317
1318   return (* iface->query_info) (file, attributes, flags, cancellable, error);
1319 }
1320
1321 /**
1322  * g_file_query_info_async:
1323  * @file: input #GFile
1324  * @attributes: an attribute query string
1325  * @flags: a set of #GFileQueryInfoFlags
1326  * @io_priority: the [I/O priority][io-priority] of the request
1327  * @cancellable: (nullable): optional #GCancellable object,
1328  *     %NULL to ignore
1329  * @callback: (scope async): a #GAsyncReadyCallback to call when the
1330  *     request is satisfied
1331  * @user_data: (closure): the data to pass to callback function
1332  *
1333  * Asynchronously gets the requested information about specified @file.
1334  * The result is a #GFileInfo object that contains key-value attributes
1335  * (such as type or size for the file).
1336  *
1337  * For more details, see g_file_query_info() which is the synchronous
1338  * version of this call.
1339  *
1340  * When the operation is finished, @callback will be called. You can
1341  * then call g_file_query_info_finish() to get the result of the operation.
1342  */
1343 void
1344 g_file_query_info_async (GFile               *file,
1345                          const char          *attributes,
1346                          GFileQueryInfoFlags  flags,
1347                          int                  io_priority,
1348                          GCancellable        *cancellable,
1349                          GAsyncReadyCallback  callback,
1350                          gpointer             user_data)
1351 {
1352   GFileIface *iface;
1353
1354   g_return_if_fail (G_IS_FILE (file));
1355
1356   iface = G_FILE_GET_IFACE (file);
1357   (* iface->query_info_async) (file,
1358                                attributes,
1359                                flags,
1360                                io_priority,
1361                                cancellable,
1362                                callback,
1363                                user_data);
1364 }
1365
1366 /**
1367  * g_file_query_info_finish:
1368  * @file: input #GFile
1369  * @res: a #GAsyncResult
1370  * @error: a #GError
1371  *
1372  * Finishes an asynchronous file info query.
1373  * See g_file_query_info_async().
1374  *
1375  * Returns: (transfer full): #GFileInfo for given @file
1376  *     or %NULL on error. Free the returned object with
1377  *     g_object_unref().
1378  */
1379 GFileInfo *
1380 g_file_query_info_finish (GFile         *file,
1381                           GAsyncResult  *res,
1382                           GError       **error)
1383 {
1384   GFileIface *iface;
1385
1386   g_return_val_if_fail (G_IS_FILE (file), NULL);
1387   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1388
1389   if (g_async_result_legacy_propagate_error (res, error))
1390     return NULL;
1391
1392   iface = G_FILE_GET_IFACE (file);
1393   return (* iface->query_info_finish) (file, res, error);
1394 }
1395
1396 /**
1397  * g_file_query_filesystem_info:
1398  * @file: input #GFile
1399  * @attributes:  an attribute query string
1400  * @cancellable: (nullable): optional #GCancellable object,
1401  *     %NULL to ignore
1402  * @error: a #GError
1403  *
1404  * Similar to g_file_query_info(), but obtains information
1405  * about the filesystem the @file is on, rather than the file itself.
1406  * For instance the amount of space available and the type of
1407  * the filesystem.
1408  *
1409  * The @attributes value is a string that specifies the attributes
1410  * that should be gathered. It is not an error if it's not possible
1411  * to read a particular requested attribute from a file - it just
1412  * won't be set. @attributes should be a comma-separated list of
1413  * attributes or attribute wildcards. The wildcard "*" means all
1414  * attributes, and a wildcard like "filesystem::*" means all attributes
1415  * in the filesystem namespace. The standard namespace for filesystem
1416  * attributes is "filesystem". Common attributes of interest are
1417  * #G_FILE_ATTRIBUTE_FILESYSTEM_SIZE (the total size of the filesystem
1418  * in bytes), #G_FILE_ATTRIBUTE_FILESYSTEM_FREE (number of bytes available),
1419  * and #G_FILE_ATTRIBUTE_FILESYSTEM_TYPE (type of the filesystem).
1420  *
1421  * If @cancellable is not %NULL, then the operation can be cancelled
1422  * by triggering the cancellable object from another thread. If the
1423  * operation was cancelled, the error %G_IO_ERROR_CANCELLED will be
1424  * returned.
1425  *
1426  * If the file does not exist, the %G_IO_ERROR_NOT_FOUND error will
1427  * be returned. Other errors are possible too, and depend on what
1428  * kind of filesystem the file is on.
1429  *
1430  * Returns: (transfer full): a #GFileInfo or %NULL if there was an error.
1431  *     Free the returned object with g_object_unref().
1432  */
1433 GFileInfo *
1434 g_file_query_filesystem_info (GFile         *file,
1435                               const char    *attributes,
1436                               GCancellable  *cancellable,
1437                               GError       **error)
1438 {
1439   GFileIface *iface;
1440
1441   g_return_val_if_fail (G_IS_FILE (file), NULL);
1442
1443   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1444     return NULL;
1445
1446   iface = G_FILE_GET_IFACE (file);
1447
1448   if (iface->query_filesystem_info == NULL)
1449     {
1450       g_set_error_literal (error, G_IO_ERROR,
1451                            G_IO_ERROR_NOT_SUPPORTED,
1452                            _("Operation not supported"));
1453       return NULL;
1454     }
1455
1456   return (* iface->query_filesystem_info) (file, attributes, cancellable, error);
1457 }
1458
1459 /**
1460  * g_file_query_filesystem_info_async:
1461  * @file: input #GFile
1462  * @attributes: an attribute query string
1463  * @io_priority: the [I/O priority][io-priority] of the request
1464  * @cancellable: (nullable): optional #GCancellable object,
1465  *     %NULL to ignore
1466  * @callback: (scope async): a #GAsyncReadyCallback to call
1467  *     when the request is satisfied
1468  * @user_data: (closure): the data to pass to callback function
1469  *
1470  * Asynchronously gets the requested information about the filesystem
1471  * that the specified @file is on. The result is a #GFileInfo object
1472  * that contains key-value attributes (such as type or size for the
1473  * file).
1474  *
1475  * For more details, see g_file_query_filesystem_info() which is the
1476  * synchronous version of this call.
1477  *
1478  * When the operation is finished, @callback will be called. You can
1479  * then call g_file_query_info_finish() to get the result of the
1480  * operation.
1481  */
1482 void
1483 g_file_query_filesystem_info_async (GFile               *file,
1484                                     const char          *attributes,
1485                                     int                  io_priority,
1486                                     GCancellable        *cancellable,
1487                                     GAsyncReadyCallback  callback,
1488                                     gpointer             user_data)
1489 {
1490   GFileIface *iface;
1491
1492   g_return_if_fail (G_IS_FILE (file));
1493
1494   iface = G_FILE_GET_IFACE (file);
1495   (* iface->query_filesystem_info_async) (file,
1496                                           attributes,
1497                                           io_priority,
1498                                           cancellable,
1499                                           callback,
1500                                           user_data);
1501 }
1502
1503 /**
1504  * g_file_query_filesystem_info_finish:
1505  * @file: input #GFile
1506  * @res: a #GAsyncResult
1507  * @error: a #GError
1508  *
1509  * Finishes an asynchronous filesystem info query.
1510  * See g_file_query_filesystem_info_async().
1511  *
1512  * Returns: (transfer full): #GFileInfo for given @file
1513  *     or %NULL on error.
1514  *     Free the returned object with g_object_unref().
1515  */
1516 GFileInfo *
1517 g_file_query_filesystem_info_finish (GFile         *file,
1518                                      GAsyncResult  *res,
1519                                      GError       **error)
1520 {
1521   GFileIface *iface;
1522
1523   g_return_val_if_fail (G_IS_FILE (file), NULL);
1524   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1525
1526   if (g_async_result_legacy_propagate_error (res, error))
1527     return NULL;
1528
1529   iface = G_FILE_GET_IFACE (file);
1530   return (* iface->query_filesystem_info_finish) (file, res, error);
1531 }
1532
1533 /**
1534  * g_file_find_enclosing_mount:
1535  * @file: input #GFile
1536  * @cancellable: (nullable): optional #GCancellable object,
1537  *     %NULL to ignore
1538  * @error: a #GError
1539  *
1540  * Gets a #GMount for the #GFile.
1541  *
1542  * If the #GFileIface for @file does not have a mount (e.g.
1543  * possibly a remote share), @error will be set to %G_IO_ERROR_NOT_FOUND
1544  * and %NULL will be returned.
1545  *
1546  * If @cancellable is not %NULL, then the operation can be cancelled by
1547  * triggering the cancellable object from another thread. If the operation
1548  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
1549  *
1550  * Returns: (transfer full): a #GMount where the @file is located
1551  *     or %NULL on error.
1552  *     Free the returned object with g_object_unref().
1553  */
1554 GMount *
1555 g_file_find_enclosing_mount (GFile         *file,
1556                              GCancellable  *cancellable,
1557                              GError       **error)
1558 {
1559   GFileIface *iface;
1560
1561   g_return_val_if_fail (G_IS_FILE (file), NULL);
1562
1563   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1564     return NULL;
1565
1566   iface = G_FILE_GET_IFACE (file);
1567   if (iface->find_enclosing_mount == NULL)
1568     {
1569
1570       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1571                            /* Translators: This is an error message when
1572                             * trying to find the enclosing (user visible)
1573                             * mount of a file, but none exists.
1574                             */
1575                            _("Containing mount does not exist"));
1576       return NULL;
1577     }
1578
1579   return (* iface->find_enclosing_mount) (file, cancellable, error);
1580 }
1581
1582 /**
1583  * g_file_find_enclosing_mount_async:
1584  * @file: a #GFile
1585  * @io_priority: the [I/O priority][io-priority] of the request
1586  * @cancellable: (nullable): optional #GCancellable object,
1587  *     %NULL to ignore
1588  * @callback: (scope async): a #GAsyncReadyCallback to call
1589  *     when the request is satisfied
1590  * @user_data: (closure): the data to pass to callback function
1591  *
1592  * Asynchronously gets the mount for the file.
1593  *
1594  * For more details, see g_file_find_enclosing_mount() which is
1595  * the synchronous version of this call.
1596  *
1597  * When the operation is finished, @callback will be called.
1598  * You can then call g_file_find_enclosing_mount_finish() to
1599  * get the result of the operation.
1600  */
1601 void
1602 g_file_find_enclosing_mount_async (GFile              *file,
1603                                    int                   io_priority,
1604                                    GCancellable         *cancellable,
1605                                    GAsyncReadyCallback   callback,
1606                                    gpointer              user_data)
1607 {
1608   GFileIface *iface;
1609
1610   g_return_if_fail (G_IS_FILE (file));
1611
1612   iface = G_FILE_GET_IFACE (file);
1613   (* iface->find_enclosing_mount_async) (file,
1614                                          io_priority,
1615                                          cancellable,
1616                                          callback,
1617                                          user_data);
1618 }
1619
1620 /**
1621  * g_file_find_enclosing_mount_finish:
1622  * @file: a #GFile
1623  * @res: a #GAsyncResult
1624  * @error: a #GError
1625  *
1626  * Finishes an asynchronous find mount request.
1627  * See g_file_find_enclosing_mount_async().
1628  *
1629  * Returns: (transfer full): #GMount for given @file or %NULL on error.
1630  *     Free the returned object with g_object_unref().
1631  */
1632 GMount *
1633 g_file_find_enclosing_mount_finish (GFile         *file,
1634                                     GAsyncResult  *res,
1635                                     GError       **error)
1636 {
1637   GFileIface *iface;
1638
1639   g_return_val_if_fail (G_IS_FILE (file), NULL);
1640   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1641
1642   if (g_async_result_legacy_propagate_error (res, error))
1643     return NULL;
1644
1645   iface = G_FILE_GET_IFACE (file);
1646   return (* iface->find_enclosing_mount_finish) (file, res, error);
1647 }
1648
1649
1650 /**
1651  * g_file_read:
1652  * @file: #GFile to read
1653  * @cancellable: (nullable): a #GCancellable
1654  * @error: a #GError, or %NULL
1655  *
1656  * Opens a file for reading. The result is a #GFileInputStream that
1657  * can be used to read the contents of the file.
1658  *
1659  * If @cancellable is not %NULL, then the operation can be cancelled by
1660  * triggering the cancellable object from another thread. If the operation
1661  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
1662  *
1663  * If the file does not exist, the %G_IO_ERROR_NOT_FOUND error will be
1664  * returned. If the file is a directory, the %G_IO_ERROR_IS_DIRECTORY
1665  * error will be returned. Other errors are possible too, and depend
1666  * on what kind of filesystem the file is on.
1667  *
1668  * Virtual: read_fn
1669  * Returns: (transfer full): #GFileInputStream or %NULL on error.
1670  *     Free the returned object with g_object_unref().
1671  */
1672 GFileInputStream *
1673 g_file_read (GFile         *file,
1674              GCancellable  *cancellable,
1675              GError       **error)
1676 {
1677   GFileIface *iface;
1678
1679   g_return_val_if_fail (G_IS_FILE (file), NULL);
1680
1681   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1682     return NULL;
1683
1684   iface = G_FILE_GET_IFACE (file);
1685
1686   if (iface->read_fn == NULL)
1687     {
1688       g_set_error_literal (error, G_IO_ERROR,
1689                            G_IO_ERROR_NOT_SUPPORTED,
1690                            _("Operation not supported"));
1691       return NULL;
1692     }
1693
1694   return (* iface->read_fn) (file, cancellable, error);
1695 }
1696
1697 /**
1698  * g_file_append_to:
1699  * @file: input #GFile
1700  * @flags: a set of #GFileCreateFlags
1701  * @cancellable: (nullable): optional #GCancellable object,
1702  *     %NULL to ignore
1703  * @error: a #GError, or %NULL
1704  *
1705  * Gets an output stream for appending data to the file.
1706  * If the file doesn't already exist it is created.
1707  *
1708  * By default files created are generally readable by everyone,
1709  * but if you pass #G_FILE_CREATE_PRIVATE in @flags the file
1710  * will be made readable only to the current user, to the level that
1711  * is supported on the target filesystem.
1712  *
1713  * If @cancellable is not %NULL, then the operation can be cancelled
1714  * by triggering the cancellable object from another thread. If the
1715  * operation was cancelled, the error %G_IO_ERROR_CANCELLED will be
1716  * returned.
1717  *
1718  * Some file systems don't allow all file names, and may return an
1719  * %G_IO_ERROR_INVALID_FILENAME error. If the file is a directory the
1720  * %G_IO_ERROR_IS_DIRECTORY error will be returned. Other errors are
1721  * possible too, and depend on what kind of filesystem the file is on.
1722  *
1723  * Returns: (transfer full): a #GFileOutputStream, or %NULL on error.
1724  *     Free the returned object with g_object_unref().
1725  */
1726 GFileOutputStream *
1727 g_file_append_to (GFile             *file,
1728                   GFileCreateFlags   flags,
1729                   GCancellable      *cancellable,
1730                   GError           **error)
1731 {
1732   GFileIface *iface;
1733
1734   g_return_val_if_fail (G_IS_FILE (file), NULL);
1735
1736   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1737     return NULL;
1738
1739   iface = G_FILE_GET_IFACE (file);
1740
1741   if (iface->append_to == NULL)
1742     {
1743       g_set_error_literal (error, G_IO_ERROR,
1744                            G_IO_ERROR_NOT_SUPPORTED,
1745                            _("Operation not supported"));
1746       return NULL;
1747     }
1748
1749   return (* iface->append_to) (file, flags, cancellable, error);
1750 }
1751
1752 /**
1753  * g_file_create:
1754  * @file: input #GFile
1755  * @flags: a set of #GFileCreateFlags
1756  * @cancellable: (nullable): optional #GCancellable object,
1757  *     %NULL to ignore
1758  * @error: a #GError, or %NULL
1759  *
1760  * Creates a new file and returns an output stream for writing to it.
1761  * The file must not already exist.
1762  *
1763  * By default files created are generally readable by everyone,
1764  * but if you pass #G_FILE_CREATE_PRIVATE in @flags the file
1765  * will be made readable only to the current user, to the level
1766  * that is supported on the target filesystem.
1767  *
1768  * If @cancellable is not %NULL, then the operation can be cancelled
1769  * by triggering the cancellable object from another thread. If the
1770  * operation was cancelled, the error %G_IO_ERROR_CANCELLED will be
1771  * returned.
1772  *
1773  * If a file or directory with this name already exists the
1774  * %G_IO_ERROR_EXISTS error will be returned. Some file systems don't
1775  * allow all file names, and may return an %G_IO_ERROR_INVALID_FILENAME
1776  * error, and if the name is to long %G_IO_ERROR_FILENAME_TOO_LONG will
1777  * be returned. Other errors are possible too, and depend on what kind
1778  * of filesystem the file is on.
1779  *
1780  * Returns: (transfer full): a #GFileOutputStream for the newly created
1781  *     file, or %NULL on error.
1782  *     Free the returned object with g_object_unref().
1783  */
1784 GFileOutputStream *
1785 g_file_create (GFile             *file,
1786                GFileCreateFlags   flags,
1787                GCancellable      *cancellable,
1788                GError           **error)
1789 {
1790   GFileIface *iface;
1791
1792   g_return_val_if_fail (G_IS_FILE (file), NULL);
1793
1794   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1795     return NULL;
1796
1797   iface = G_FILE_GET_IFACE (file);
1798
1799   if (iface->create == NULL)
1800     {
1801       g_set_error_literal (error, G_IO_ERROR,
1802                            G_IO_ERROR_NOT_SUPPORTED,
1803                            _("Operation not supported"));
1804       return NULL;
1805     }
1806
1807   return (* iface->create) (file, flags, cancellable, error);
1808 }
1809
1810 /**
1811  * g_file_replace:
1812  * @file: input #GFile
1813  * @etag: (nullable): an optional [entity tag][gfile-etag]
1814  *     for the current #GFile, or #NULL to ignore
1815  * @make_backup: %TRUE if a backup should be created
1816  * @flags: a set of #GFileCreateFlags
1817  * @cancellable: (nullable): optional #GCancellable object,
1818  *     %NULL to ignore
1819  * @error: a #GError, or %NULL
1820  *
1821  * Returns an output stream for overwriting the file, possibly
1822  * creating a backup copy of the file first. If the file doesn't exist,
1823  * it will be created.
1824  *
1825  * This will try to replace the file in the safest way possible so
1826  * that any errors during the writing will not affect an already
1827  * existing copy of the file. For instance, for local files it
1828  * may write to a temporary file and then atomically rename over
1829  * the destination when the stream is closed.
1830  *
1831  * By default files created are generally readable by everyone,
1832  * but if you pass #G_FILE_CREATE_PRIVATE in @flags the file
1833  * will be made readable only to the current user, to the level that
1834  * is supported on the target filesystem.
1835  *
1836  * If @cancellable is not %NULL, then the operation can be cancelled
1837  * by triggering the cancellable object from another thread. If the
1838  * operation was cancelled, the error %G_IO_ERROR_CANCELLED will be
1839  * returned.
1840  *
1841  * If you pass in a non-%NULL @etag value and @file already exists, then
1842  * this value is compared to the current entity tag of the file, and if
1843  * they differ an %G_IO_ERROR_WRONG_ETAG error is returned. This
1844  * generally means that the file has been changed since you last read
1845  * it. You can get the new etag from g_file_output_stream_get_etag()
1846  * after you've finished writing and closed the #GFileOutputStream. When
1847  * you load a new file you can use g_file_input_stream_query_info() to
1848  * get the etag of the file.
1849  *
1850  * If @make_backup is %TRUE, this function will attempt to make a
1851  * backup of the current file before overwriting it. If this fails
1852  * a %G_IO_ERROR_CANT_CREATE_BACKUP error will be returned. If you
1853  * want to replace anyway, try again with @make_backup set to %FALSE.
1854  *
1855  * If the file is a directory the %G_IO_ERROR_IS_DIRECTORY error will
1856  * be returned, and if the file is some other form of non-regular file
1857  * then a %G_IO_ERROR_NOT_REGULAR_FILE error will be returned. Some
1858  * file systems don't allow all file names, and may return an
1859  * %G_IO_ERROR_INVALID_FILENAME error, and if the name is to long
1860  * %G_IO_ERROR_FILENAME_TOO_LONG will be returned. Other errors are
1861  * possible too, and depend on what kind of filesystem the file is on.
1862  *
1863  * Returns: (transfer full): a #GFileOutputStream or %NULL on error.
1864  *     Free the returned object with g_object_unref().
1865  */
1866 GFileOutputStream *
1867 g_file_replace (GFile             *file,
1868                 const char        *etag,
1869                 gboolean           make_backup,
1870                 GFileCreateFlags   flags,
1871                 GCancellable      *cancellable,
1872                 GError           **error)
1873 {
1874   GFileIface *iface;
1875
1876   g_return_val_if_fail (G_IS_FILE (file), NULL);
1877
1878   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1879     return NULL;
1880
1881   iface = G_FILE_GET_IFACE (file);
1882
1883   if (iface->replace == NULL)
1884     {
1885       g_set_error_literal (error, G_IO_ERROR,
1886                            G_IO_ERROR_NOT_SUPPORTED,
1887                            _("Operation not supported"));
1888       return NULL;
1889     }
1890
1891   /* Handle empty tag string as NULL in consistent way. */
1892   if (etag && *etag == 0)
1893     etag = NULL;
1894
1895   return (* iface->replace) (file, etag, make_backup, flags, cancellable, error);
1896 }
1897
1898 /**
1899  * g_file_open_readwrite:
1900  * @file: #GFile to open
1901  * @cancellable: (nullable): a #GCancellable
1902  * @error: a #GError, or %NULL
1903  *
1904  * Opens an existing file for reading and writing. The result is
1905  * a #GFileIOStream that can be used to read and write the contents
1906  * of the file.
1907  *
1908  * If @cancellable is not %NULL, then the operation can be cancelled
1909  * by triggering the cancellable object from another thread. If the
1910  * operation was cancelled, the error %G_IO_ERROR_CANCELLED will be
1911  * returned.
1912  *
1913  * If the file does not exist, the %G_IO_ERROR_NOT_FOUND error will
1914  * be returned. If the file is a directory, the %G_IO_ERROR_IS_DIRECTORY
1915  * error will be returned. Other errors are possible too, and depend on
1916  * what kind of filesystem the file is on. Note that in many non-local
1917  * file cases read and write streams are not supported, so make sure you
1918  * really need to do read and write streaming, rather than just opening
1919  * for reading or writing.
1920  *
1921  * Returns: (transfer full): #GFileIOStream or %NULL on error.
1922  *     Free the returned object with g_object_unref().
1923  *
1924  * Since: 2.22
1925  */
1926 GFileIOStream *
1927 g_file_open_readwrite (GFile         *file,
1928                        GCancellable  *cancellable,
1929                        GError       **error)
1930 {
1931   GFileIface *iface;
1932
1933   g_return_val_if_fail (G_IS_FILE (file), NULL);
1934
1935   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1936     return NULL;
1937
1938   iface = G_FILE_GET_IFACE (file);
1939
1940   if (iface->open_readwrite == NULL)
1941     {
1942       g_set_error_literal (error, G_IO_ERROR,
1943                            G_IO_ERROR_NOT_SUPPORTED,
1944                            _("Operation not supported"));
1945       return NULL;
1946     }
1947
1948   return (* iface->open_readwrite) (file, cancellable, error);
1949 }
1950
1951 /**
1952  * g_file_create_readwrite:
1953  * @file: a #GFile
1954  * @flags: a set of #GFileCreateFlags
1955  * @cancellable: (nullable): optional #GCancellable object,
1956  *     %NULL to ignore
1957  * @error: return location for a #GError, or %NULL
1958  *
1959  * Creates a new file and returns a stream for reading and
1960  * writing to it. The file must not already exist.
1961  *
1962  * By default files created are generally readable by everyone,
1963  * but if you pass #G_FILE_CREATE_PRIVATE in @flags the file
1964  * will be made readable only to the current user, to the level
1965  * that is supported on the target filesystem.
1966  *
1967  * If @cancellable is not %NULL, then the operation can be cancelled
1968  * by triggering the cancellable object from another thread. If the
1969  * operation was cancelled, the error %G_IO_ERROR_CANCELLED will be
1970  * returned.
1971  *
1972  * If a file or directory with this name already exists, the
1973  * %G_IO_ERROR_EXISTS error will be returned. Some file systems don't
1974  * allow all file names, and may return an %G_IO_ERROR_INVALID_FILENAME
1975  * error, and if the name is too long, %G_IO_ERROR_FILENAME_TOO_LONG
1976  * will be returned. Other errors are possible too, and depend on what
1977  * kind of filesystem the file is on.
1978  *
1979  * Note that in many non-local file cases read and write streams are
1980  * not supported, so make sure you really need to do read and write
1981  * streaming, rather than just opening for reading or writing.
1982  *
1983  * Returns: (transfer full): a #GFileIOStream for the newly created
1984  *     file, or %NULL on error.
1985  *     Free the returned object with g_object_unref().
1986  *
1987  * Since: 2.22
1988  */
1989 GFileIOStream *
1990 g_file_create_readwrite (GFile             *file,
1991                          GFileCreateFlags   flags,
1992                          GCancellable      *cancellable,
1993                          GError           **error)
1994 {
1995   GFileIface *iface;
1996
1997   g_return_val_if_fail (G_IS_FILE (file), NULL);
1998
1999   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2000     return NULL;
2001
2002   iface = G_FILE_GET_IFACE (file);
2003
2004   if (iface->create_readwrite == NULL)
2005     {
2006       g_set_error_literal (error, G_IO_ERROR,
2007                            G_IO_ERROR_NOT_SUPPORTED,
2008                            _("Operation not supported"));
2009       return NULL;
2010     }
2011
2012   return (* iface->create_readwrite) (file, flags, cancellable, error);
2013 }
2014
2015 /**
2016  * g_file_replace_readwrite:
2017  * @file: a #GFile
2018  * @etag: (nullable): an optional [entity tag][gfile-etag]
2019  *     for the current #GFile, or #NULL to ignore
2020  * @make_backup: %TRUE if a backup should be created
2021  * @flags: a set of #GFileCreateFlags
2022  * @cancellable: (nullable): optional #GCancellable object,
2023  *     %NULL to ignore
2024  * @error: return location for a #GError, or %NULL
2025  *
2026  * Returns an output stream for overwriting the file in readwrite mode,
2027  * possibly creating a backup copy of the file first. If the file doesn't
2028  * exist, it will be created.
2029  *
2030  * For details about the behaviour, see g_file_replace() which does the
2031  * same thing but returns an output stream only.
2032  *
2033  * Note that in many non-local file cases read and write streams are not
2034  * supported, so make sure you really need to do read and write streaming,
2035  * rather than just opening for reading or writing.
2036  *
2037  * Returns: (transfer full): a #GFileIOStream or %NULL on error.
2038  *     Free the returned object with g_object_unref().
2039  *
2040  * Since: 2.22
2041  */
2042 GFileIOStream *
2043 g_file_replace_readwrite (GFile             *file,
2044                           const char        *etag,
2045                           gboolean           make_backup,
2046                           GFileCreateFlags   flags,
2047                           GCancellable      *cancellable,
2048                           GError           **error)
2049 {
2050   GFileIface *iface;
2051
2052   g_return_val_if_fail (G_IS_FILE (file), NULL);
2053
2054   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2055     return NULL;
2056
2057   iface = G_FILE_GET_IFACE (file);
2058
2059   if (iface->replace_readwrite == NULL)
2060     {
2061       g_set_error_literal (error, G_IO_ERROR,
2062                            G_IO_ERROR_NOT_SUPPORTED,
2063                            _("Operation not supported"));
2064       return NULL;
2065     }
2066
2067   return (* iface->replace_readwrite) (file, etag, make_backup, flags, cancellable, error);
2068 }
2069
2070 /**
2071  * g_file_read_async:
2072  * @file: input #GFile
2073  * @io_priority: the [I/O priority][io-priority] of the request
2074  * @cancellable: (nullable): optional #GCancellable object,
2075  *     %NULL to ignore
2076  * @callback: (scope async): a #GAsyncReadyCallback to call
2077  *     when the request is satisfied
2078  * @user_data: (closure): the data to pass to callback function
2079  *
2080  * Asynchronously opens @file for reading.
2081  *
2082  * For more details, see g_file_read() which is
2083  * the synchronous version of this call.
2084  *
2085  * When the operation is finished, @callback will be called.
2086  * You can then call g_file_read_finish() to get the result
2087  * of the operation.
2088  */
2089 void
2090 g_file_read_async (GFile               *file,
2091                    int                  io_priority,
2092                    GCancellable        *cancellable,
2093                    GAsyncReadyCallback  callback,
2094                    gpointer             user_data)
2095 {
2096   GFileIface *iface;
2097
2098   g_return_if_fail (G_IS_FILE (file));
2099
2100   iface = G_FILE_GET_IFACE (file);
2101   (* iface->read_async) (file,
2102                          io_priority,
2103                          cancellable,
2104                          callback,
2105                          user_data);
2106 }
2107
2108 /**
2109  * g_file_read_finish:
2110  * @file: input #GFile
2111  * @res: a #GAsyncResult
2112  * @error: a #GError, or %NULL
2113  *
2114  * Finishes an asynchronous file read operation started with
2115  * g_file_read_async().
2116  *
2117  * Returns: (transfer full): a #GFileInputStream or %NULL on error.
2118  *     Free the returned object with g_object_unref().
2119  */
2120 GFileInputStream *
2121 g_file_read_finish (GFile         *file,
2122                     GAsyncResult  *res,
2123                     GError       **error)
2124 {
2125   GFileIface *iface;
2126
2127   g_return_val_if_fail (G_IS_FILE (file), NULL);
2128   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2129
2130   if (g_async_result_legacy_propagate_error (res, error))
2131     return NULL;
2132
2133   iface = G_FILE_GET_IFACE (file);
2134   return (* iface->read_finish) (file, res, error);
2135 }
2136
2137 /**
2138  * g_file_append_to_async:
2139  * @file: input #GFile
2140  * @flags: a set of #GFileCreateFlags
2141  * @io_priority: the [I/O priority][io-priority] of the request
2142  * @cancellable: (nullable): optional #GCancellable object,
2143  *     %NULL to ignore
2144  * @callback: (scope async): a #GAsyncReadyCallback to call
2145  *     when the request is satisfied
2146  * @user_data: (closure): the data to pass to callback function
2147  *
2148  * Asynchronously opens @file for appending.
2149  *
2150  * For more details, see g_file_append_to() which is
2151  * the synchronous version of this call.
2152  *
2153  * When the operation is finished, @callback will be called.
2154  * You can then call g_file_append_to_finish() to get the result
2155  * of the operation.
2156  */
2157 void
2158 g_file_append_to_async (GFile               *file,
2159                         GFileCreateFlags     flags,
2160                         int                  io_priority,
2161                         GCancellable        *cancellable,
2162                         GAsyncReadyCallback  callback,
2163                         gpointer             user_data)
2164 {
2165   GFileIface *iface;
2166
2167   g_return_if_fail (G_IS_FILE (file));
2168
2169   iface = G_FILE_GET_IFACE (file);
2170   (* iface->append_to_async) (file,
2171                               flags,
2172                               io_priority,
2173                               cancellable,
2174                               callback,
2175                               user_data);
2176 }
2177
2178 /**
2179  * g_file_append_to_finish:
2180  * @file: input #GFile
2181  * @res: #GAsyncResult
2182  * @error: a #GError, or %NULL
2183  *
2184  * Finishes an asynchronous file append operation started with
2185  * g_file_append_to_async().
2186  *
2187  * Returns: (transfer full): a valid #GFileOutputStream
2188  *     or %NULL on error.
2189  *     Free the returned object with g_object_unref().
2190  */
2191 GFileOutputStream *
2192 g_file_append_to_finish (GFile         *file,
2193                          GAsyncResult  *res,
2194                          GError       **error)
2195 {
2196   GFileIface *iface;
2197
2198   g_return_val_if_fail (G_IS_FILE (file), NULL);
2199   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2200
2201   if (g_async_result_legacy_propagate_error (res, error))
2202     return NULL;
2203
2204   iface = G_FILE_GET_IFACE (file);
2205   return (* iface->append_to_finish) (file, res, error);
2206 }
2207
2208 /**
2209  * g_file_create_async:
2210  * @file: input #GFile
2211  * @flags: a set of #GFileCreateFlags
2212  * @io_priority: the [I/O priority][io-priority] of the request
2213  * @cancellable: (nullable): optional #GCancellable object,
2214  *     %NULL to ignore
2215  * @callback: (scope async): a #GAsyncReadyCallback to call
2216  *     when the request is satisfied
2217  * @user_data: (closure): the data to pass to callback function
2218  *
2219  * Asynchronously creates a new file and returns an output stream
2220  * for writing to it. The file must not already exist.
2221  *
2222  * For more details, see g_file_create() which is
2223  * the synchronous version of this call.
2224  *
2225  * When the operation is finished, @callback will be called.
2226  * You can then call g_file_create_finish() to get the result
2227  * of the operation.
2228  */
2229 void
2230 g_file_create_async (GFile               *file,
2231                      GFileCreateFlags     flags,
2232                      int                  io_priority,
2233                      GCancellable        *cancellable,
2234                      GAsyncReadyCallback  callback,
2235                      gpointer             user_data)
2236 {
2237   GFileIface *iface;
2238
2239   g_return_if_fail (G_IS_FILE (file));
2240
2241   iface = G_FILE_GET_IFACE (file);
2242   (* iface->create_async) (file,
2243                            flags,
2244                            io_priority,
2245                            cancellable,
2246                            callback,
2247                            user_data);
2248 }
2249
2250 /**
2251  * g_file_create_finish:
2252  * @file: input #GFile
2253  * @res: a #GAsyncResult
2254  * @error: a #GError, or %NULL
2255  *
2256  * Finishes an asynchronous file create operation started with
2257  * g_file_create_async().
2258  *
2259  * Returns: (transfer full): a #GFileOutputStream or %NULL on error.
2260  *     Free the returned object with g_object_unref().
2261  */
2262 GFileOutputStream *
2263 g_file_create_finish (GFile         *file,
2264                       GAsyncResult  *res,
2265                       GError       **error)
2266 {
2267   GFileIface *iface;
2268
2269   g_return_val_if_fail (G_IS_FILE (file), NULL);
2270   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2271
2272   if (g_async_result_legacy_propagate_error (res, error))
2273     return NULL;
2274
2275   iface = G_FILE_GET_IFACE (file);
2276   return (* iface->create_finish) (file, res, error);
2277 }
2278
2279 /**
2280  * g_file_replace_async:
2281  * @file: input #GFile
2282  * @etag: (nullable): an [entity tag][gfile-etag] for the current #GFile,
2283  *     or %NULL to ignore
2284  * @make_backup: %TRUE if a backup should be created
2285  * @flags: a set of #GFileCreateFlags
2286  * @io_priority: the [I/O priority][io-priority] of the request
2287  * @cancellable: (nullable): optional #GCancellable object,
2288  *     %NULL to ignore
2289  * @callback: (scope async): a #GAsyncReadyCallback to call
2290  *     when the request is satisfied
2291  * @user_data: (closure): the data to pass to callback function
2292  *
2293  * Asynchronously overwrites the file, replacing the contents,
2294  * possibly creating a backup copy of the file first.
2295  *
2296  * For more details, see g_file_replace() which is
2297  * the synchronous version of this call.
2298  *
2299  * When the operation is finished, @callback will be called.
2300  * You can then call g_file_replace_finish() to get the result
2301  * of the operation.
2302  */
2303 void
2304 g_file_replace_async (GFile               *file,
2305                       const char          *etag,
2306                       gboolean             make_backup,
2307                       GFileCreateFlags     flags,
2308                       int                  io_priority,
2309                       GCancellable        *cancellable,
2310                       GAsyncReadyCallback  callback,
2311                       gpointer             user_data)
2312 {
2313   GFileIface *iface;
2314
2315   g_return_if_fail (G_IS_FILE (file));
2316
2317   iface = G_FILE_GET_IFACE (file);
2318   (* iface->replace_async) (file,
2319                             etag,
2320                             make_backup,
2321                             flags,
2322                             io_priority,
2323                             cancellable,
2324                             callback,
2325                             user_data);
2326 }
2327
2328 /**
2329  * g_file_replace_finish:
2330  * @file: input #GFile
2331  * @res: a #GAsyncResult
2332  * @error: a #GError, or %NULL
2333  *
2334  * Finishes an asynchronous file replace operation started with
2335  * g_file_replace_async().
2336  *
2337  * Returns: (transfer full): a #GFileOutputStream, or %NULL on error.
2338  *     Free the returned object with g_object_unref().
2339  */
2340 GFileOutputStream *
2341 g_file_replace_finish (GFile         *file,
2342                        GAsyncResult  *res,
2343                        GError       **error)
2344 {
2345   GFileIface *iface;
2346
2347   g_return_val_if_fail (G_IS_FILE (file), NULL);
2348   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2349
2350   if (g_async_result_legacy_propagate_error (res, error))
2351     return NULL;
2352
2353   iface = G_FILE_GET_IFACE (file);
2354   return (* iface->replace_finish) (file, res, error);
2355 }
2356
2357 /**
2358  * g_file_open_readwrite_async
2359  * @file: input #GFile
2360  * @io_priority: the [I/O priority][io-priority] of the request
2361  * @cancellable: (nullable): optional #GCancellable object,
2362  *     %NULL to ignore
2363  * @callback: (scope async): a #GAsyncReadyCallback to call
2364  *     when the request is satisfied
2365  * @user_data: (closure): the data to pass to callback function
2366  *
2367  * Asynchronously opens @file for reading and writing.
2368  *
2369  * For more details, see g_file_open_readwrite() which is
2370  * the synchronous version of this call.
2371  *
2372  * When the operation is finished, @callback will be called.
2373  * You can then call g_file_open_readwrite_finish() to get
2374  * the result of the operation.
2375  *
2376  * Since: 2.22
2377  */
2378 void
2379 g_file_open_readwrite_async (GFile               *file,
2380                              int                  io_priority,
2381                              GCancellable        *cancellable,
2382                              GAsyncReadyCallback  callback,
2383                              gpointer             user_data)
2384 {
2385   GFileIface *iface;
2386
2387   g_return_if_fail (G_IS_FILE (file));
2388
2389   iface = G_FILE_GET_IFACE (file);
2390   (* iface->open_readwrite_async) (file,
2391                                    io_priority,
2392                                    cancellable,
2393                                    callback,
2394                                    user_data);
2395 }
2396
2397 /**
2398  * g_file_open_readwrite_finish:
2399  * @file: input #GFile
2400  * @res: a #GAsyncResult
2401  * @error: a #GError, or %NULL
2402  *
2403  * Finishes an asynchronous file read operation started with
2404  * g_file_open_readwrite_async().
2405  *
2406  * Returns: (transfer full): a #GFileIOStream or %NULL on error.
2407  *     Free the returned object with g_object_unref().
2408  *
2409  * Since: 2.22
2410  */
2411 GFileIOStream *
2412 g_file_open_readwrite_finish (GFile         *file,
2413                               GAsyncResult  *res,
2414                               GError       **error)
2415 {
2416   GFileIface *iface;
2417
2418   g_return_val_if_fail (G_IS_FILE (file), NULL);
2419   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2420
2421   if (g_async_result_legacy_propagate_error (res, error))
2422     return NULL;
2423
2424   iface = G_FILE_GET_IFACE (file);
2425   return (* iface->open_readwrite_finish) (file, res, error);
2426 }
2427
2428 /**
2429  * g_file_create_readwrite_async:
2430  * @file: input #GFile
2431  * @flags: a set of #GFileCreateFlags
2432  * @io_priority: the [I/O priority][io-priority] of the request
2433  * @cancellable: (nullable): optional #GCancellable object,
2434  *     %NULL to ignore
2435  * @callback: (scope async): a #GAsyncReadyCallback to call
2436  *     when the request is satisfied
2437  * @user_data: (closure): the data to pass to callback function
2438  *
2439  * Asynchronously creates a new file and returns a stream
2440  * for reading and writing to it. The file must not already exist.
2441  *
2442  * For more details, see g_file_create_readwrite() which is
2443  * the synchronous version of this call.
2444  *
2445  * When the operation is finished, @callback will be called.
2446  * You can then call g_file_create_readwrite_finish() to get
2447  * the result of the operation.
2448  *
2449  * Since: 2.22
2450  */
2451 void
2452 g_file_create_readwrite_async (GFile               *file,
2453                                GFileCreateFlags     flags,
2454                                int                  io_priority,
2455                                GCancellable        *cancellable,
2456                                GAsyncReadyCallback  callback,
2457                                gpointer             user_data)
2458 {
2459   GFileIface *iface;
2460
2461   g_return_if_fail (G_IS_FILE (file));
2462
2463   iface = G_FILE_GET_IFACE (file);
2464   (* iface->create_readwrite_async) (file,
2465                                      flags,
2466                                      io_priority,
2467                                      cancellable,
2468                                      callback,
2469                                      user_data);
2470 }
2471
2472 /**
2473  * g_file_create_readwrite_finish:
2474  * @file: input #GFile
2475  * @res: a #GAsyncResult
2476  * @error: a #GError, or %NULL
2477  *
2478  * Finishes an asynchronous file create operation started with
2479  * g_file_create_readwrite_async().
2480  *
2481  * Returns: (transfer full): a #GFileIOStream or %NULL on error.
2482  *     Free the returned object with g_object_unref().
2483  *
2484  * Since: 2.22
2485  */
2486 GFileIOStream *
2487 g_file_create_readwrite_finish (GFile         *file,
2488                                 GAsyncResult  *res,
2489                                 GError       **error)
2490 {
2491   GFileIface *iface;
2492
2493   g_return_val_if_fail (G_IS_FILE (file), NULL);
2494   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2495
2496   if (g_async_result_legacy_propagate_error (res, error))
2497     return NULL;
2498
2499   iface = G_FILE_GET_IFACE (file);
2500   return (* iface->create_readwrite_finish) (file, res, error);
2501 }
2502
2503 /**
2504  * g_file_replace_readwrite_async:
2505  * @file: input #GFile
2506  * @etag: (nullable): an [entity tag][gfile-etag] for the current #GFile,
2507  *     or %NULL to ignore
2508  * @make_backup: %TRUE if a backup should be created
2509  * @flags: a set of #GFileCreateFlags
2510  * @io_priority: the [I/O priority][io-priority] of the request
2511  * @cancellable: (nullable): optional #GCancellable object,
2512  *     %NULL to ignore
2513  * @callback: (scope async): a #GAsyncReadyCallback to call
2514  *     when the request is satisfied
2515  * @user_data: (closure): the data to pass to callback function
2516  *
2517  * Asynchronously overwrites the file in read-write mode,
2518  * replacing the contents, possibly creating a backup copy
2519  * of the file first.
2520  *
2521  * For more details, see g_file_replace_readwrite() which is
2522  * the synchronous version of this call.
2523  *
2524  * When the operation is finished, @callback will be called.
2525  * You can then call g_file_replace_readwrite_finish() to get
2526  * the result of the operation.
2527  *
2528  * Since: 2.22
2529  */
2530 void
2531 g_file_replace_readwrite_async (GFile               *file,
2532                                 const char          *etag,
2533                                 gboolean             make_backup,
2534                                 GFileCreateFlags     flags,
2535                                 int                  io_priority,
2536                                 GCancellable        *cancellable,
2537                                 GAsyncReadyCallback  callback,
2538                                 gpointer             user_data)
2539 {
2540   GFileIface *iface;
2541
2542   g_return_if_fail (G_IS_FILE (file));
2543
2544   iface = G_FILE_GET_IFACE (file);
2545   (* iface->replace_readwrite_async) (file,
2546                                       etag,
2547                                       make_backup,
2548                                       flags,
2549                                       io_priority,
2550                                       cancellable,
2551                                       callback,
2552                                       user_data);
2553 }
2554
2555 /**
2556  * g_file_replace_readwrite_finish:
2557  * @file: input #GFile
2558  * @res: a #GAsyncResult
2559  * @error: a #GError, or %NULL
2560  *
2561  * Finishes an asynchronous file replace operation started with
2562  * g_file_replace_readwrite_async().
2563  *
2564  * Returns: (transfer full): a #GFileIOStream, or %NULL on error.
2565  *     Free the returned object with g_object_unref().
2566  *
2567  * Since: 2.22
2568  */
2569 GFileIOStream *
2570 g_file_replace_readwrite_finish (GFile         *file,
2571                                  GAsyncResult  *res,
2572                                  GError       **error)
2573 {
2574   GFileIface *iface;
2575
2576   g_return_val_if_fail (G_IS_FILE (file), NULL);
2577   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2578
2579   if (g_async_result_legacy_propagate_error (res, error))
2580     return NULL;
2581
2582   iface = G_FILE_GET_IFACE (file);
2583   return (* iface->replace_readwrite_finish) (file, res, error);
2584 }
2585
2586 static gboolean
2587 copy_symlink (GFile           *destination,
2588               GFileCopyFlags   flags,
2589               GCancellable    *cancellable,
2590               const char      *target,
2591               GError         **error)
2592 {
2593   GError *my_error;
2594   gboolean tried_delete;
2595   GFileInfo *info;
2596   GFileType file_type;
2597
2598   tried_delete = FALSE;
2599
2600  retry:
2601   my_error = NULL;
2602   if (!g_file_make_symbolic_link (destination, target, cancellable, &my_error))
2603     {
2604       /* Maybe it already existed, and we want to overwrite? */
2605       if (!tried_delete && (flags & G_FILE_COPY_OVERWRITE) &&
2606           my_error->domain == G_IO_ERROR && my_error->code == G_IO_ERROR_EXISTS)
2607         {
2608           g_clear_error (&my_error);
2609
2610           /* Don't overwrite if the destination is a directory */
2611           info = g_file_query_info (destination, G_FILE_ATTRIBUTE_STANDARD_TYPE,
2612                                     G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
2613                                     cancellable, &my_error);
2614           if (info != NULL)
2615             {
2616               file_type = g_file_info_get_file_type (info);
2617               g_object_unref (info);
2618
2619               if (file_type == G_FILE_TYPE_DIRECTORY)
2620                 {
2621                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_IS_DIRECTORY,
2622                                        _("Can’t copy over directory"));
2623                   return FALSE;
2624                 }
2625             }
2626
2627           if (!g_file_delete (destination, cancellable, error))
2628             return FALSE;
2629
2630           tried_delete = TRUE;
2631           goto retry;
2632         }
2633             /* Nah, fail */
2634       g_propagate_error (error, my_error);
2635       return FALSE;
2636     }
2637
2638   return TRUE;
2639 }
2640
2641 static GFileInputStream *
2642 open_source_for_copy (GFile           *source,
2643                       GFile           *destination,
2644                       GFileCopyFlags   flags,
2645                       GCancellable    *cancellable,
2646                       GError         **error)
2647 {
2648   GError *my_error;
2649   GFileInputStream *ret;
2650   GFileInfo *info;
2651   GFileType file_type;
2652
2653   my_error = NULL;
2654   ret = g_file_read (source, cancellable, &my_error);
2655   if (ret != NULL)
2656     return ret;
2657
2658   /* There was an error opening the source, try to set a good error for it: */
2659   if (my_error->domain == G_IO_ERROR && my_error->code == G_IO_ERROR_IS_DIRECTORY)
2660     {
2661       /* The source is a directory, don't fail with WOULD_RECURSE immediately,
2662        * as that is less useful to the app. Better check for errors on the
2663        * target instead.
2664        */
2665       g_error_free (my_error);
2666       my_error = NULL;
2667
2668       info = g_file_query_info (destination, G_FILE_ATTRIBUTE_STANDARD_TYPE,
2669                                 G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
2670                                 cancellable, &my_error);
2671       if (info != NULL &&
2672           g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_STANDARD_TYPE))
2673         {
2674           file_type = g_file_info_get_file_type (info);
2675           g_object_unref (info);
2676
2677           if (flags & G_FILE_COPY_OVERWRITE)
2678             {
2679               if (file_type == G_FILE_TYPE_DIRECTORY)
2680                 {
2681                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_WOULD_MERGE,
2682                                        _("Can’t copy directory over directory"));
2683                   return NULL;
2684                 }
2685               /* continue to would_recurse error */
2686             }
2687           else
2688             {
2689               g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_EXISTS,
2690                                    _("Target file exists"));
2691               return NULL;
2692             }
2693         }
2694       else
2695         {
2696           /* Error getting info from target, return that error
2697            * (except for NOT_FOUND, which is no error here)
2698            */
2699           g_clear_object (&info);
2700           if (my_error != NULL && !g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
2701             {
2702               g_propagate_error (error, my_error);
2703               return NULL;
2704             }
2705           g_clear_error (&my_error);
2706         }
2707
2708       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_WOULD_RECURSE,
2709                            _("Can’t recursively copy directory"));
2710       return NULL;
2711     }
2712
2713   g_propagate_error (error, my_error);
2714   return NULL;
2715 }
2716
2717 static gboolean
2718 should_copy (GFileAttributeInfo *info,
2719              gboolean            copy_all_attributes,
2720              gboolean            skip_perms)
2721 {
2722   if (skip_perms && strcmp(info->name, "unix::mode") == 0)
2723         return FALSE;
2724
2725   if (copy_all_attributes)
2726     return info->flags & G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED;
2727   return info->flags & G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE;
2728 }
2729
2730 static gboolean
2731 build_attribute_list_for_copy (GFile                  *file,
2732                                GFileCopyFlags          flags,
2733                                char                  **out_attributes,
2734                                GCancellable           *cancellable,
2735                                GError                **error)
2736 {
2737   gboolean ret = FALSE;
2738   GFileAttributeInfoList *attributes = NULL, *namespaces = NULL;
2739   GString *s = NULL;
2740   gboolean first;
2741   int i;
2742   gboolean copy_all_attributes;
2743   gboolean skip_perms;
2744
2745   copy_all_attributes = flags & G_FILE_COPY_ALL_METADATA;
2746   skip_perms = (flags & G_FILE_COPY_TARGET_DEFAULT_PERMS) != 0;
2747
2748   /* Ignore errors here, if the target supports no attributes there is
2749    * nothing to copy.  We still honor the cancellable though.
2750    */
2751   attributes = g_file_query_settable_attributes (file, cancellable, NULL);
2752   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2753     goto out;
2754
2755   namespaces = g_file_query_writable_namespaces (file, cancellable, NULL);
2756   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2757     goto out;
2758
2759   if (attributes == NULL && namespaces == NULL)
2760     goto out;
2761
2762   first = TRUE;
2763   s = g_string_new ("");
2764
2765   if (attributes)
2766     {
2767       for (i = 0; i < attributes->n_infos; i++)
2768         {
2769           if (should_copy (&attributes->infos[i], copy_all_attributes, skip_perms))
2770             {
2771               if (first)
2772                 first = FALSE;
2773               else
2774                 g_string_append_c (s, ',');
2775
2776               g_string_append (s, attributes->infos[i].name);
2777             }
2778         }
2779     }
2780
2781   if (namespaces)
2782     {
2783       for (i = 0; i < namespaces->n_infos; i++)
2784         {
2785           if (should_copy (&namespaces->infos[i], copy_all_attributes, FALSE))
2786             {
2787               if (first)
2788                 first = FALSE;
2789               else
2790                 g_string_append_c (s, ',');
2791
2792               g_string_append (s, namespaces->infos[i].name);
2793               g_string_append (s, "::*");
2794             }
2795         }
2796     }
2797
2798   ret = TRUE;
2799   *out_attributes = g_string_free (s, FALSE);
2800   s = NULL;
2801  out:
2802   if (s)
2803     g_string_free (s, TRUE);
2804   if (attributes)
2805     g_file_attribute_info_list_unref (attributes);
2806   if (namespaces)
2807     g_file_attribute_info_list_unref (namespaces);
2808   
2809   return ret;
2810 }
2811
2812 /**
2813  * g_file_copy_attributes:
2814  * @source: a #GFile with attributes
2815  * @destination: a #GFile to copy attributes to
2816  * @flags: a set of #GFileCopyFlags
2817  * @cancellable: (nullable): optional #GCancellable object,
2818  *     %NULL to ignore
2819  * @error: a #GError, %NULL to ignore
2820  *
2821  * Copies the file attributes from @source to @destination.
2822  *
2823  * Normally only a subset of the file attributes are copied,
2824  * those that are copies in a normal file copy operation
2825  * (which for instance does not include e.g. owner). However
2826  * if #G_FILE_COPY_ALL_METADATA is specified in @flags, then
2827  * all the metadata that is possible to copy is copied. This
2828  * is useful when implementing move by copy + delete source.
2829  *
2830  * Returns: %TRUE if the attributes were copied successfully,
2831  *     %FALSE otherwise.
2832  */
2833 gboolean
2834 g_file_copy_attributes (GFile           *source,
2835                         GFile           *destination,
2836                         GFileCopyFlags   flags,
2837                         GCancellable    *cancellable,
2838                         GError         **error)
2839 {
2840   char *attrs_to_read;
2841   gboolean res;
2842   GFileInfo *info;
2843   gboolean source_nofollow_symlinks;
2844
2845   if (!build_attribute_list_for_copy (destination, flags, &attrs_to_read,
2846                                       cancellable, error))
2847     return FALSE;
2848
2849   source_nofollow_symlinks = flags & G_FILE_COPY_NOFOLLOW_SYMLINKS;
2850
2851   /* Ignore errors here, if we can't read some info (e.g. if it doesn't exist)
2852    * we just don't copy it.
2853    */
2854   info = g_file_query_info (source, attrs_to_read,
2855                             source_nofollow_symlinks ? G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS:0,
2856                             cancellable,
2857                             NULL);
2858
2859   g_free (attrs_to_read);
2860
2861   res = TRUE;
2862   if  (info)
2863     {
2864       res = g_file_set_attributes_from_info (destination,
2865                                              info,
2866                                              G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
2867                                              cancellable,
2868                                              error);
2869       g_object_unref (info);
2870     }
2871
2872   return res;
2873 }
2874
2875 /* 256k minus malloc overhead */
2876 #define STREAM_BUFFER_SIZE (1024*256 - 2 *sizeof(gpointer))
2877
2878 static gboolean
2879 copy_stream_with_progress (GInputStream           *in,
2880                            GOutputStream          *out,
2881                            GFile                  *source,
2882                            GCancellable           *cancellable,
2883                            GFileProgressCallback   progress_callback,
2884                            gpointer                progress_callback_data,
2885                            GError                **error)
2886 {
2887   gssize n_read;
2888   gsize n_written;
2889   goffset current_size;
2890   char *buffer;
2891   gboolean res;
2892   goffset total_size;
2893   GFileInfo *info;
2894
2895   total_size = -1;
2896   /* avoid performance impact of querying total size when it's not needed */
2897   if (progress_callback)
2898     {
2899       info = g_file_input_stream_query_info (G_FILE_INPUT_STREAM (in),
2900                                              G_FILE_ATTRIBUTE_STANDARD_SIZE,
2901                                              cancellable, NULL);
2902       if (info)
2903         {
2904           if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_STANDARD_SIZE))
2905             total_size = g_file_info_get_size (info);
2906           g_object_unref (info);
2907         }
2908
2909       if (total_size == -1)
2910         {
2911           info = g_file_query_info (source,
2912                                     G_FILE_ATTRIBUTE_STANDARD_SIZE,
2913                                     G_FILE_QUERY_INFO_NONE,
2914                                     cancellable, NULL);
2915           if (info)
2916             {
2917               if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_STANDARD_SIZE))
2918                 total_size = g_file_info_get_size (info);
2919               g_object_unref (info);
2920             }
2921         }
2922     }
2923
2924   if (total_size == -1)
2925     total_size = 0;
2926
2927   buffer = g_malloc0 (STREAM_BUFFER_SIZE);
2928   current_size = 0;
2929   res = TRUE;
2930   while (TRUE)
2931     {
2932       n_read = g_input_stream_read (in, buffer, STREAM_BUFFER_SIZE, cancellable, error);
2933       if (n_read == -1)
2934         {
2935           res = FALSE;
2936           break;
2937         }
2938
2939       if (n_read == 0)
2940         break;
2941
2942       current_size += n_read;
2943
2944       res = g_output_stream_write_all (out, buffer, n_read, &n_written, cancellable, error);
2945       if (!res)
2946         break;
2947
2948       if (progress_callback)
2949         progress_callback (current_size, total_size, progress_callback_data);
2950     }
2951   g_free (buffer);
2952
2953   /* Make sure we send full copied size */
2954   if (progress_callback)
2955     progress_callback (current_size, total_size, progress_callback_data);
2956
2957   return res;
2958 }
2959
2960 #ifdef HAVE_SPLICE
2961
2962 static gboolean
2963 do_splice (int     fd_in,
2964            loff_t *off_in,
2965            int     fd_out,
2966            loff_t *off_out,
2967            size_t  len,
2968            long   *bytes_transferd,
2969            GError **error)
2970 {
2971   long result;
2972
2973 retry:
2974   result = splice (fd_in, off_in, fd_out, off_out, len, SPLICE_F_MORE);
2975
2976   if (result == -1)
2977     {
2978       int errsv = errno;
2979
2980       if (errsv == EINTR)
2981         goto retry;
2982       else if (errsv == ENOSYS || errsv == EINVAL || errsv == EOPNOTSUPP)
2983         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2984                              _("Splice not supported"));
2985       else
2986         g_set_error (error, G_IO_ERROR,
2987                      g_io_error_from_errno (errsv),
2988                      _("Error splicing file: %s"),
2989                      g_strerror (errsv));
2990
2991       return FALSE;
2992     }
2993
2994   *bytes_transferd = result;
2995   return TRUE;
2996 }
2997
2998 static gboolean
2999 splice_stream_with_progress (GInputStream           *in,
3000                              GOutputStream          *out,
3001                              GCancellable           *cancellable,
3002                              GFileProgressCallback   progress_callback,
3003                              gpointer                progress_callback_data,
3004                              GError                **error)
3005 {
3006   int buffer[2] = { -1, -1 };
3007   int buffer_size;
3008   gboolean res;
3009   goffset total_size;
3010   loff_t offset_in;
3011   loff_t offset_out;
3012   int fd_in, fd_out;
3013
3014   fd_in = g_file_descriptor_based_get_fd (G_FILE_DESCRIPTOR_BASED (in));
3015   fd_out = g_file_descriptor_based_get_fd (G_FILE_DESCRIPTOR_BASED (out));
3016
3017   if (!g_unix_open_pipe (buffer, FD_CLOEXEC, error))
3018     return FALSE;
3019
3020 #if defined(F_SETPIPE_SZ) && defined(F_GETPIPE_SZ)
3021   /* Try a 1MiB buffer for improved throughput. If that fails, use the default
3022    * pipe size. See: https://bugzilla.gnome.org/791457 */
3023   buffer_size = fcntl (buffer[1], F_SETPIPE_SZ, 1024 * 1024);
3024   if (buffer_size <= 0)
3025     {
3026       int errsv;
3027       buffer_size = fcntl (buffer[1], F_GETPIPE_SZ);
3028       errsv = errno;
3029
3030       if (buffer_size <= 0)
3031         {
3032           g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
3033                        _("Error splicing file: %s"), g_strerror (errsv));
3034           res = FALSE;
3035           goto out;
3036         }
3037     }
3038 #else
3039   /* If #F_GETPIPE_SZ isn’t available, assume we’re on Linux < 2.6.35,
3040    * but ≥ 2.6.11, meaning the pipe capacity is 64KiB. Ignore the possibility of
3041    * running on Linux < 2.6.11 (where the capacity was the system page size,
3042    * typically 4KiB) because it’s ancient. See pipe(7). */
3043   buffer_size = 1024 * 64;
3044 #endif
3045
3046   g_assert (buffer_size > 0);
3047
3048   total_size = -1;
3049   /* avoid performance impact of querying total size when it's not needed */
3050   if (progress_callback)
3051     {
3052       struct stat sbuf;
3053
3054       if (fstat (fd_in, &sbuf) == 0)
3055         total_size = sbuf.st_size;
3056     }
3057
3058   if (total_size == -1)
3059     total_size = 0;
3060
3061   offset_in = offset_out = 0;
3062   res = FALSE;
3063   while (TRUE)
3064     {
3065       long n_read;
3066       long n_written;
3067
3068       if (g_cancellable_set_error_if_cancelled (cancellable, error))
3069         break;
3070
3071       if (!do_splice (fd_in, &offset_in, buffer[1], NULL, buffer_size, &n_read, error))
3072         break;
3073
3074       if (n_read == 0)
3075         {
3076           res = TRUE;
3077           break;
3078         }
3079
3080       while (n_read > 0)
3081         {
3082           if (g_cancellable_set_error_if_cancelled (cancellable, error))
3083             goto out;
3084
3085           if (!do_splice (buffer[0], NULL, fd_out, &offset_out, n_read, &n_written, error))
3086             goto out;
3087
3088           n_read -= n_written;
3089         }
3090
3091       if (progress_callback)
3092         progress_callback (offset_in, total_size, progress_callback_data);
3093     }
3094
3095   /* Make sure we send full copied size */
3096   if (progress_callback)
3097     progress_callback (offset_in, total_size, progress_callback_data);
3098
3099   if (!g_close (buffer[0], error))
3100     goto out;
3101   buffer[0] = -1;
3102   if (!g_close (buffer[1], error))
3103     goto out;
3104   buffer[1] = -1;
3105  out:
3106   if (buffer[0] != -1)
3107     (void) g_close (buffer[0], NULL);
3108   if (buffer[1] != -1)
3109     (void) g_close (buffer[1], NULL);
3110
3111   return res;
3112 }
3113 #endif
3114
3115 #ifdef __linux__
3116 static gboolean
3117 btrfs_reflink_with_progress (GInputStream           *in,
3118                              GOutputStream          *out,
3119                              GFileInfo              *info,
3120                              GCancellable           *cancellable,
3121                              GFileProgressCallback   progress_callback,
3122                              gpointer                progress_callback_data,
3123                              GError                **error)
3124 {
3125   goffset source_size;
3126   int fd_in, fd_out;
3127   int ret, errsv;
3128
3129   fd_in = g_file_descriptor_based_get_fd (G_FILE_DESCRIPTOR_BASED (in));
3130   fd_out = g_file_descriptor_based_get_fd (G_FILE_DESCRIPTOR_BASED (out));
3131
3132   if (progress_callback)
3133     source_size = g_file_info_get_size (info);
3134
3135   /* Btrfs clone ioctl properties:
3136    *  - Works at the inode level
3137    *  - Doesn't work with directories
3138    *  - Always follows symlinks (source and destination)
3139    *
3140    * By the time we get here, *in and *out are both regular files */
3141   ret = ioctl (fd_out, BTRFS_IOC_CLONE, fd_in);
3142   errsv = errno;
3143
3144   if (ret < 0)
3145     {
3146       if (errsv == EXDEV)
3147         g_set_error_literal (error, G_IO_ERROR,
3148                              G_IO_ERROR_NOT_SUPPORTED,
3149                              _("Copy (reflink/clone) between mounts is not supported"));
3150       else if (errsv == EINVAL)
3151         g_set_error_literal (error, G_IO_ERROR,
3152                              G_IO_ERROR_NOT_SUPPORTED,
3153                              _("Copy (reflink/clone) is not supported or invalid"));
3154       else
3155         /* Most probably something odd happened; retry with fallback */
3156         g_set_error_literal (error, G_IO_ERROR,
3157                              G_IO_ERROR_NOT_SUPPORTED,
3158                              _("Copy (reflink/clone) is not supported or didn’t work"));
3159       /* We retry with fallback for all error cases because Btrfs is currently
3160        * unstable, and so we can't trust it to do clone properly.
3161        * In addition, any hard errors here would cause the same failure in the
3162        * fallback manual copy as well. */
3163       return FALSE;
3164     }
3165
3166   /* Make sure we send full copied size */
3167   if (progress_callback)
3168     progress_callback (source_size, source_size, progress_callback_data);
3169
3170   return TRUE;
3171 }
3172 #endif
3173
3174 static gboolean
3175 file_copy_fallback (GFile                  *source,
3176                     GFile                  *destination,
3177                     GFileCopyFlags          flags,
3178                     GCancellable           *cancellable,
3179                     GFileProgressCallback   progress_callback,
3180                     gpointer                progress_callback_data,
3181                     GError                **error)
3182 {
3183   gboolean ret = FALSE;
3184   GFileInputStream *file_in = NULL;
3185   GInputStream *in = NULL;
3186   GOutputStream *out = NULL;
3187   GFileInfo *info = NULL;
3188   const char *target;
3189   char *attrs_to_read;
3190   gboolean do_set_attributes = FALSE;
3191
3192   /* need to know the file type */
3193   info = g_file_query_info (source,
3194                             G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
3195                             G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
3196                             cancellable,
3197                             error);
3198   if (!info)
3199     goto out;
3200
3201   /* Maybe copy the symlink? */
3202   if ((flags & G_FILE_COPY_NOFOLLOW_SYMLINKS) &&
3203       g_file_info_get_file_type (info) == G_FILE_TYPE_SYMBOLIC_LINK)
3204     {
3205       target = g_file_info_get_symlink_target (info);
3206       if (target)
3207         {
3208           if (!copy_symlink (destination, flags, cancellable, target, error))
3209             goto out;
3210
3211           ret = TRUE;
3212           goto out;
3213         }
3214         /* ... else fall back on a regular file copy */
3215     }
3216   /* Handle "special" files (pipes, device nodes, ...)? */
3217   else if (g_file_info_get_file_type (info) == G_FILE_TYPE_SPECIAL)
3218     {
3219       /* FIXME: could try to recreate device nodes and others? */
3220       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3221                            _("Can’t copy special file"));
3222       goto out;
3223     }
3224
3225   /* Everything else should just fall back on a regular copy. */
3226
3227   file_in = open_source_for_copy (source, destination, flags, cancellable, error);
3228   if (!file_in)
3229     goto out;
3230   in = G_INPUT_STREAM (file_in);
3231
3232   if (!build_attribute_list_for_copy (destination, flags, &attrs_to_read,
3233                                       cancellable, error))
3234     goto out;
3235
3236   if (attrs_to_read != NULL)
3237     {
3238       GError *tmp_error = NULL;
3239
3240       /* Ok, ditch the previous lightweight info (on Unix we just
3241        * called lstat()); at this point we gather all the information
3242        * we need about the source from the opened file descriptor.
3243        */
3244       g_object_unref (info);
3245
3246       info = g_file_input_stream_query_info (file_in, attrs_to_read,
3247                                              cancellable, &tmp_error);
3248       if (!info)
3249         {
3250           /* Not all gvfs backends implement query_info_on_read(), we
3251            * can just fall back to the pathname again.
3252            * https://bugzilla.gnome.org/706254
3253            */
3254           if (g_error_matches (tmp_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED))
3255             {
3256               g_clear_error (&tmp_error);
3257               info = g_file_query_info (source, attrs_to_read, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
3258                                         cancellable, error);
3259             }
3260           else
3261             {
3262               g_free (attrs_to_read);
3263               g_propagate_error (error, tmp_error);
3264               goto out;
3265             }
3266         }
3267       g_free (attrs_to_read);
3268       if (!info)
3269         goto out;
3270
3271       do_set_attributes = TRUE;
3272     }
3273
3274   /* In the local file path, we pass down the source info which
3275    * includes things like unix::mode, to ensure that the target file
3276    * is not created with different permissions from the source file.
3277    *
3278    * If a future API like g_file_replace_with_info() is added, switch
3279    * this code to use that.
3280    */
3281   if (G_IS_LOCAL_FILE (destination))
3282     {
3283       if (flags & G_FILE_COPY_OVERWRITE)
3284         out = (GOutputStream*)_g_local_file_output_stream_replace (_g_local_file_get_filename (G_LOCAL_FILE (destination)),
3285                                                                    FALSE, NULL,
3286                                                                    flags & G_FILE_COPY_BACKUP,
3287                                                                    G_FILE_CREATE_REPLACE_DESTINATION |
3288                                                                    G_FILE_CREATE_PRIVATE, info,
3289                                                                    cancellable, error);
3290       else
3291         out = (GOutputStream*)_g_local_file_output_stream_create (_g_local_file_get_filename (G_LOCAL_FILE (destination)),
3292                                                                   FALSE, G_FILE_CREATE_PRIVATE, info,
3293                                                                   cancellable, error);
3294     }
3295   else if (flags & G_FILE_COPY_OVERWRITE)
3296     {
3297       out = (GOutputStream *)g_file_replace (destination,
3298                                              NULL,
3299                                              flags & G_FILE_COPY_BACKUP,
3300                                              G_FILE_CREATE_REPLACE_DESTINATION |
3301                                              G_FILE_CREATE_PRIVATE,
3302                                              cancellable, error);
3303     }
3304   else
3305     {
3306       out = (GOutputStream *)g_file_create (destination, G_FILE_CREATE_PRIVATE, cancellable, error);
3307     }
3308
3309   if (!out)
3310     goto out;
3311
3312 #ifdef __linux__
3313   if (G_IS_FILE_DESCRIPTOR_BASED (in) && G_IS_FILE_DESCRIPTOR_BASED (out))
3314     {
3315       GError *reflink_err = NULL;
3316
3317       if (!btrfs_reflink_with_progress (in, out, info, cancellable,
3318                                         progress_callback, progress_callback_data,
3319                                         &reflink_err))
3320         {
3321           if (g_error_matches (reflink_err, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED))
3322             {
3323               g_clear_error (&reflink_err);
3324             }
3325           else
3326             {
3327               g_propagate_error (error, reflink_err);
3328               goto out;
3329             }
3330         }
3331       else
3332         {
3333           ret = TRUE;
3334           goto out;
3335         }
3336     }
3337 #endif
3338
3339 #ifdef HAVE_SPLICE
3340   if (G_IS_FILE_DESCRIPTOR_BASED (in) && G_IS_FILE_DESCRIPTOR_BASED (out))
3341     {
3342       GError *splice_err = NULL;
3343
3344       if (!splice_stream_with_progress (in, out, cancellable,
3345                                         progress_callback, progress_callback_data,
3346                                         &splice_err))
3347         {
3348           if (g_error_matches (splice_err, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED))
3349             {
3350               g_clear_error (&splice_err);
3351             }
3352           else
3353             {
3354               g_propagate_error (error, splice_err);
3355               goto out;
3356             }
3357         }
3358       else
3359         {
3360           ret = TRUE;
3361           goto out;
3362         }
3363     }
3364
3365 #endif
3366
3367   /* A plain read/write loop */
3368   if (!copy_stream_with_progress (in, out, source, cancellable,
3369                                   progress_callback, progress_callback_data,
3370                                   error))
3371     goto out;
3372
3373   ret = TRUE;
3374  out:
3375   if (in)
3376     {
3377       /* Don't care about errors in source here */
3378       (void) g_input_stream_close (in, cancellable, NULL);
3379       g_object_unref (in);
3380     }
3381
3382   if (out)
3383     {
3384       /* But write errors on close are bad! */
3385       if (!g_output_stream_close (out, cancellable, ret ? error : NULL))
3386         ret = FALSE;
3387       g_object_unref (out);
3388     }
3389
3390   /* Ignore errors here. Failure to copy metadata is not a hard error */
3391   /* TODO: set these attributes /before/ we do the rename() on Unix */
3392   if (ret && do_set_attributes)
3393     {
3394       g_file_set_attributes_from_info (destination,
3395                                        info,
3396                                        G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
3397                                        cancellable,
3398                                        NULL);
3399     }
3400
3401   g_clear_object (&info);
3402
3403   return ret;
3404 }
3405
3406 /**
3407  * g_file_copy:
3408  * @source: input #GFile
3409  * @destination: destination #GFile
3410  * @flags: set of #GFileCopyFlags
3411  * @cancellable: (nullable): optional #GCancellable object,
3412  *     %NULL to ignore
3413  * @progress_callback: (nullable) (scope call): function to callback with
3414  *     progress information, or %NULL if progress information is not needed
3415  * @progress_callback_data: (closure): user data to pass to @progress_callback
3416  * @error: #GError to set on error, or %NULL
3417  *
3418  * Copies the file @source to the location specified by @destination.
3419  * Can not handle recursive copies of directories.
3420  *
3421  * If the flag #G_FILE_COPY_OVERWRITE is specified an already
3422  * existing @destination file is overwritten.
3423  *
3424  * If the flag #G_FILE_COPY_NOFOLLOW_SYMLINKS is specified then symlinks
3425  * will be copied as symlinks, otherwise the target of the
3426  * @source symlink will be copied.
3427  *
3428  * If the flag #G_FILE_COPY_ALL_METADATA is specified then all the metadata
3429  * that is possible to copy is copied, not just the default subset (which,
3430  * for instance, does not include the owner, see #GFileInfo).
3431  *
3432  * If @cancellable is not %NULL, then the operation can be cancelled by
3433  * triggering the cancellable object from another thread. If the operation
3434  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
3435  *
3436  * If @progress_callback is not %NULL, then the operation can be monitored
3437  * by setting this to a #GFileProgressCallback function.
3438  * @progress_callback_data will be passed to this function. It is guaranteed
3439  * that this callback will be called after all data has been transferred with
3440  * the total number of bytes copied during the operation.
3441  *
3442  * If the @source file does not exist, then the %G_IO_ERROR_NOT_FOUND error
3443  * is returned, independent on the status of the @destination.
3444  *
3445  * If #G_FILE_COPY_OVERWRITE is not specified and the target exists, then
3446  * the error %G_IO_ERROR_EXISTS is returned.
3447  *
3448  * If trying to overwrite a file over a directory, the %G_IO_ERROR_IS_DIRECTORY
3449  * error is returned. If trying to overwrite a directory with a directory the
3450  * %G_IO_ERROR_WOULD_MERGE error is returned.
3451  *
3452  * If the source is a directory and the target does not exist, or
3453  * #G_FILE_COPY_OVERWRITE is specified and the target is a file, then the
3454  * %G_IO_ERROR_WOULD_RECURSE error is returned.
3455  *
3456  * If you are interested in copying the #GFile object itself (not the on-disk
3457  * file), see g_file_dup().
3458  *
3459  * Returns: %TRUE on success, %FALSE otherwise.
3460  */
3461 gboolean
3462 g_file_copy (GFile                  *source,
3463              GFile                  *destination,
3464              GFileCopyFlags          flags,
3465              GCancellable           *cancellable,
3466              GFileProgressCallback   progress_callback,
3467              gpointer                progress_callback_data,
3468              GError                **error)
3469 {
3470   GFileIface *iface;
3471   GError *my_error;
3472   gboolean res;
3473
3474   g_return_val_if_fail (G_IS_FILE (source), FALSE);
3475   g_return_val_if_fail (G_IS_FILE (destination), FALSE);
3476
3477   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3478     return FALSE;
3479
3480   iface = G_FILE_GET_IFACE (destination);
3481   if (iface->copy)
3482     {
3483       my_error = NULL;
3484       res = (* iface->copy) (source, destination,
3485                              flags, cancellable,
3486                              progress_callback, progress_callback_data,
3487                              &my_error);
3488
3489       if (res)
3490         return TRUE;
3491
3492       if (my_error->domain != G_IO_ERROR || my_error->code != G_IO_ERROR_NOT_SUPPORTED)
3493         {
3494           g_propagate_error (error, my_error);
3495               return FALSE;
3496         }
3497       else
3498         g_clear_error (&my_error);
3499     }
3500
3501   /* If the types are different, and the destination method failed
3502    * also try the source method
3503    */
3504   if (G_OBJECT_TYPE (source) != G_OBJECT_TYPE (destination))
3505     {
3506       iface = G_FILE_GET_IFACE (source);
3507
3508       if (iface->copy)
3509         {
3510           my_error = NULL;
3511           res = (* iface->copy) (source, destination,
3512                                  flags, cancellable,
3513                                  progress_callback, progress_callback_data,
3514                                  &my_error);
3515
3516           if (res)
3517             return TRUE;
3518
3519           if (my_error->domain != G_IO_ERROR || my_error->code != G_IO_ERROR_NOT_SUPPORTED)
3520             {
3521               g_propagate_error (error, my_error);
3522               return FALSE;
3523             }
3524           else
3525             g_clear_error (&my_error);
3526         }
3527     }
3528
3529   return file_copy_fallback (source, destination, flags, cancellable,
3530                              progress_callback, progress_callback_data,
3531                              error);
3532 }
3533
3534 /**
3535  * g_file_copy_async:
3536  * @source: input #GFile
3537  * @destination: destination #GFile
3538  * @flags: set of #GFileCopyFlags
3539  * @io_priority: the [I/O priority][io-priority] of the request
3540  * @cancellable: (nullable): optional #GCancellable object,
3541  *     %NULL to ignore
3542  * @progress_callback: (nullable) (scope notified): function to callback with progress
3543  *     information, or %NULL if progress information is not needed
3544  * @progress_callback_data: (closure progress_callback) (nullable): user data to pass to @progress_callback
3545  * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied
3546  * @user_data: (closure callback): the data to pass to callback function
3547  *
3548  * Copies the file @source to the location specified by @destination
3549  * asynchronously. For details of the behaviour, see g_file_copy().
3550  *
3551  * If @progress_callback is not %NULL, then that function that will be called
3552  * just like in g_file_copy(). The callback will run in the default main context
3553  * of the thread calling g_file_copy_async() — the same context as @callback is
3554  * run in.
3555  *
3556  * When the operation is finished, @callback will be called. You can then call
3557  * g_file_copy_finish() to get the result of the operation.
3558  */
3559 void
3560 g_file_copy_async (GFile                  *source,
3561                    GFile                  *destination,
3562                    GFileCopyFlags          flags,
3563                    int                     io_priority,
3564                    GCancellable           *cancellable,
3565                    GFileProgressCallback   progress_callback,
3566                    gpointer                progress_callback_data,
3567                    GAsyncReadyCallback     callback,
3568                    gpointer                user_data)
3569 {
3570   GFileIface *iface;
3571
3572   g_return_if_fail (G_IS_FILE (source));
3573   g_return_if_fail (G_IS_FILE (destination));
3574
3575   iface = G_FILE_GET_IFACE (source);
3576   (* iface->copy_async) (source,
3577                          destination,
3578                          flags,
3579                          io_priority,
3580                          cancellable,
3581                          progress_callback,
3582                          progress_callback_data,
3583                          callback,
3584                          user_data);
3585 }
3586
3587 /**
3588  * g_file_copy_finish:
3589  * @file: input #GFile
3590  * @res: a #GAsyncResult
3591  * @error: a #GError, or %NULL
3592  *
3593  * Finishes copying the file started with g_file_copy_async().
3594  *
3595  * Returns: a %TRUE on success, %FALSE on error.
3596  */
3597 gboolean
3598 g_file_copy_finish (GFile         *file,
3599                     GAsyncResult  *res,
3600                     GError       **error)
3601 {
3602   GFileIface *iface;
3603
3604   g_return_val_if_fail (G_IS_FILE (file), FALSE);
3605   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
3606
3607   if (g_async_result_legacy_propagate_error (res, error))
3608     return FALSE;
3609
3610   iface = G_FILE_GET_IFACE (file);
3611   return (* iface->copy_finish) (file, res, error);
3612 }
3613
3614 /**
3615  * g_file_move:
3616  * @source: #GFile pointing to the source location
3617  * @destination: #GFile pointing to the destination location
3618  * @flags: set of #GFileCopyFlags
3619  * @cancellable: (nullable): optional #GCancellable object,
3620  *     %NULL to ignore
3621  * @progress_callback: (nullable) (scope call): #GFileProgressCallback
3622  *     function for updates
3623  * @progress_callback_data: (closure): gpointer to user data for
3624  *     the callback function
3625  * @error: #GError for returning error conditions, or %NULL
3626  *
3627  * Tries to move the file or directory @source to the location specified
3628  * by @destination. If native move operations are supported then this is
3629  * used, otherwise a copy + delete fallback is used. The native
3630  * implementation may support moving directories (for instance on moves
3631  * inside the same filesystem), but the fallback code does not.
3632  *
3633  * If the flag #G_FILE_COPY_OVERWRITE is specified an already
3634  * existing @destination file is overwritten.
3635  *
3636  * If the flag #G_FILE_COPY_NOFOLLOW_SYMLINKS is specified then symlinks
3637  * will be copied as symlinks, otherwise the target of the
3638  * @source symlink will be copied.
3639  *
3640  * If @cancellable is not %NULL, then the operation can be cancelled by
3641  * triggering the cancellable object from another thread. If the operation
3642  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
3643  *
3644  * If @progress_callback is not %NULL, then the operation can be monitored
3645  * by setting this to a #GFileProgressCallback function.
3646  * @progress_callback_data will be passed to this function. It is
3647  * guaranteed that this callback will be called after all data has been
3648  * transferred with the total number of bytes copied during the operation.
3649  *
3650  * If the @source file does not exist, then the %G_IO_ERROR_NOT_FOUND
3651  * error is returned, independent on the status of the @destination.
3652  *
3653  * If #G_FILE_COPY_OVERWRITE is not specified and the target exists,
3654  * then the error %G_IO_ERROR_EXISTS is returned.
3655  *
3656  * If trying to overwrite a file over a directory, the %G_IO_ERROR_IS_DIRECTORY
3657  * error is returned. If trying to overwrite a directory with a directory the
3658  * %G_IO_ERROR_WOULD_MERGE error is returned.
3659  *
3660  * If the source is a directory and the target does not exist, or
3661  * #G_FILE_COPY_OVERWRITE is specified and the target is a file, then
3662  * the %G_IO_ERROR_WOULD_RECURSE error may be returned (if the native
3663  * move operation isn't available).
3664  *
3665  * Returns: %TRUE on successful move, %FALSE otherwise.
3666  */
3667 gboolean
3668 g_file_move (GFile                  *source,
3669              GFile                  *destination,
3670              GFileCopyFlags          flags,
3671              GCancellable           *cancellable,
3672              GFileProgressCallback   progress_callback,
3673              gpointer                progress_callback_data,
3674              GError                **error)
3675 {
3676   GFileIface *iface;
3677   GError *my_error;
3678   gboolean res;
3679
3680   g_return_val_if_fail (G_IS_FILE (source), FALSE);
3681   g_return_val_if_fail (G_IS_FILE (destination), FALSE);
3682
3683   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3684     return FALSE;
3685
3686   iface = G_FILE_GET_IFACE (destination);
3687   if (iface->move)
3688     {
3689       my_error = NULL;
3690       res = (* iface->move) (source, destination,
3691                              flags, cancellable,
3692                              progress_callback, progress_callback_data,
3693                              &my_error);
3694
3695       if (res)
3696         return TRUE;
3697
3698       if (my_error->domain != G_IO_ERROR || my_error->code != G_IO_ERROR_NOT_SUPPORTED)
3699         {
3700           g_propagate_error (error, my_error);
3701           return FALSE;
3702         }
3703       else
3704         g_clear_error (&my_error);
3705     }
3706
3707   /* If the types are different, and the destination method failed
3708    * also try the source method
3709    */
3710   if (G_OBJECT_TYPE (source) != G_OBJECT_TYPE (destination))
3711     {
3712       iface = G_FILE_GET_IFACE (source);
3713
3714       if (iface->move)
3715         {
3716           my_error = NULL;
3717           res = (* iface->move) (source, destination,
3718                                  flags, cancellable,
3719                                  progress_callback, progress_callback_data,
3720                                  &my_error);
3721
3722           if (res)
3723             return TRUE;
3724
3725           if (my_error->domain != G_IO_ERROR || my_error->code != G_IO_ERROR_NOT_SUPPORTED)
3726             {
3727               g_propagate_error (error, my_error);
3728               return FALSE;
3729             }
3730           else
3731             g_clear_error (&my_error);
3732         }
3733     }
3734
3735   if (flags & G_FILE_COPY_NO_FALLBACK_FOR_MOVE)
3736     {
3737       g_set_error_literal (error, G_IO_ERROR,
3738                            G_IO_ERROR_NOT_SUPPORTED,
3739                            _("Operation not supported"));
3740       return FALSE;
3741     }
3742
3743   flags |= G_FILE_COPY_ALL_METADATA;
3744   if (!g_file_copy (source, destination, flags, cancellable,
3745                     progress_callback, progress_callback_data,
3746                     error))
3747     return FALSE;
3748
3749   return g_file_delete (source, cancellable, error);
3750 }
3751
3752 /**
3753  * g_file_make_directory:
3754  * @file: input #GFile
3755  * @cancellable: (nullable): optional #GCancellable object,
3756  *     %NULL to ignore
3757  * @error: a #GError, or %NULL
3758  *
3759  * Creates a directory. Note that this will only create a child directory
3760  * of the immediate parent directory of the path or URI given by the #GFile.
3761  * To recursively create directories, see g_file_make_directory_with_parents().
3762  * This function will fail if the parent directory does not exist, setting
3763  * @error to %G_IO_ERROR_NOT_FOUND. If the file system doesn't support
3764  * creating directories, this function will fail, setting @error to
3765  * %G_IO_ERROR_NOT_SUPPORTED.
3766  *
3767  * For a local #GFile the newly created directory will have the default
3768  * (current) ownership and permissions of the current process.
3769  *
3770  * If @cancellable is not %NULL, then the operation can be cancelled by
3771  * triggering the cancellable object from another thread. If the operation
3772  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
3773  *
3774  * Returns: %TRUE on successful creation, %FALSE otherwise.
3775  */
3776 gboolean
3777 g_file_make_directory (GFile         *file,
3778                        GCancellable  *cancellable,
3779                        GError       **error)
3780 {
3781   GFileIface *iface;
3782
3783   g_return_val_if_fail (G_IS_FILE (file), FALSE);
3784
3785   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3786     return FALSE;
3787
3788   iface = G_FILE_GET_IFACE (file);
3789
3790   if (iface->make_directory == NULL)
3791     {
3792       g_set_error_literal (error, G_IO_ERROR,
3793                            G_IO_ERROR_NOT_SUPPORTED,
3794                            _("Operation not supported"));
3795       return FALSE;
3796     }
3797
3798   return (* iface->make_directory) (file, cancellable, error);
3799 }
3800
3801 /**
3802  * g_file_make_directory_async:
3803  * @file: input #GFile
3804  * @io_priority: the [I/O priority][io-priority] of the request
3805  * @cancellable: (nullable): optional #GCancellable object,
3806  *     %NULL to ignore
3807  * @callback: a #GAsyncReadyCallback to call
3808  *     when the request is satisfied
3809  * @user_data: the data to pass to callback function
3810  *
3811  * Asynchronously creates a directory.
3812  *
3813  * Virtual: make_directory_async
3814  * Since: 2.38
3815  */
3816 void
3817 g_file_make_directory_async (GFile               *file,
3818                              int                  io_priority,
3819                              GCancellable        *cancellable,
3820                              GAsyncReadyCallback  callback,
3821                              gpointer             user_data)
3822 {
3823   GFileIface *iface;
3824
3825   g_return_if_fail (G_IS_FILE (file));
3826
3827   iface = G_FILE_GET_IFACE (file);
3828   (* iface->make_directory_async) (file,
3829                                    io_priority,
3830                                    cancellable,
3831                                    callback,
3832                                    user_data);
3833 }
3834
3835 /**
3836  * g_file_make_directory_finish:
3837  * @file: input #GFile
3838  * @result: a #GAsyncResult
3839  * @error: a #GError, or %NULL
3840  *
3841  * Finishes an asynchronous directory creation, started with
3842  * g_file_make_directory_async().
3843  *
3844  * Virtual: make_directory_finish
3845  * Returns: %TRUE on successful directory creation, %FALSE otherwise.
3846  * Since: 2.38
3847  */
3848 gboolean
3849 g_file_make_directory_finish (GFile         *file,
3850                               GAsyncResult  *result,
3851                               GError       **error)
3852 {
3853   GFileIface *iface;
3854
3855   g_return_val_if_fail (G_IS_FILE (file), FALSE);
3856   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
3857
3858   iface = G_FILE_GET_IFACE (file);
3859   return (* iface->make_directory_finish) (file, result, error);
3860 }
3861
3862 /**
3863  * g_file_make_directory_with_parents:
3864  * @file: input #GFile
3865  * @cancellable: (nullable): optional #GCancellable object,
3866  *     %NULL to ignore
3867  * @error: a #GError, or %NULL
3868  *
3869  * Creates a directory and any parent directories that may not
3870  * exist similar to 'mkdir -p'. If the file system does not support
3871  * creating directories, this function will fail, setting @error to
3872  * %G_IO_ERROR_NOT_SUPPORTED. If the directory itself already exists,
3873  * this function will fail setting @error to %G_IO_ERROR_EXISTS, unlike
3874  * the similar g_mkdir_with_parents().
3875  *
3876  * For a local #GFile the newly created directories will have the default
3877  * (current) ownership and permissions of the current process.
3878  *
3879  * If @cancellable is not %NULL, then the operation can be cancelled by
3880  * triggering the cancellable object from another thread. If the operation
3881  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
3882  *
3883  * Returns: %TRUE if all directories have been successfully created, %FALSE
3884  * otherwise.
3885  *
3886  * Since: 2.18
3887  */
3888 gboolean
3889 g_file_make_directory_with_parents (GFile         *file,
3890                                     GCancellable  *cancellable,
3891                                     GError       **error)
3892 {
3893   GFile *work_file = NULL;
3894   GList *list = NULL, *l;
3895   GError *my_error = NULL;
3896
3897   g_return_val_if_fail (G_IS_FILE (file), FALSE);
3898
3899   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3900     return FALSE;
3901
3902   /* Try for the simple case of not having to create any parent
3903    * directories.  If any parent directory needs to be created, this
3904    * call will fail with NOT_FOUND. If that happens, then that value of
3905    * my_error persists into the while loop below.
3906    */
3907   g_file_make_directory (file, cancellable, &my_error);
3908   if (!g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
3909     {
3910       if (my_error)
3911         g_propagate_error (error, my_error);
3912       return my_error == NULL;
3913     }
3914
3915   work_file = g_object_ref (file);
3916
3917   /* Creates the parent directories as needed. In case any particular
3918    * creation operation fails for lack of other parent directories
3919    * (NOT_FOUND), the directory is added to a list of directories to
3920    * create later, and the value of my_error is retained until the next
3921    * iteration of the loop.  After the loop my_error should either be
3922    * empty or contain a real failure condition.
3923    */
3924   while (g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
3925     {
3926       GFile *parent_file;
3927
3928       parent_file = g_file_get_parent (work_file);
3929       if (parent_file == NULL)
3930         break;
3931
3932       g_clear_error (&my_error);
3933       g_file_make_directory (parent_file, cancellable, &my_error);
3934       /* Another process may have created the directory in between the
3935        * G_IO_ERROR_NOT_FOUND and now
3936        */
3937       if (g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_EXISTS))
3938         g_clear_error (&my_error);
3939
3940       g_object_unref (work_file);
3941       work_file = g_object_ref (parent_file);
3942
3943       if (g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
3944         list = g_list_prepend (list, parent_file);  /* Transfer ownership of ref */
3945       else
3946         g_object_unref (parent_file);
3947     }
3948
3949   /* All directories should be able to be created now, so an error at
3950    * this point means the whole operation must fail -- except an EXISTS
3951    * error, which means that another process already created the
3952    * directory in between the previous failure and now.
3953    */
3954   for (l = list; my_error == NULL && l; l = l->next)
3955     {
3956       g_file_make_directory ((GFile *) l->data, cancellable, &my_error);
3957       if (g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_EXISTS))
3958         g_clear_error (&my_error);
3959     }
3960
3961   if (work_file)
3962     g_object_unref (work_file);
3963
3964   /* Clean up */
3965   while (list != NULL)
3966     {
3967       g_object_unref ((GFile *) list->data);
3968       list = g_list_remove (list, list->data);
3969     }
3970
3971   /* At this point an error in my_error means a that something
3972    * unexpected failed in either of the loops above, so the whole
3973    * operation must fail.
3974    */
3975   if (my_error != NULL)
3976     {
3977       g_propagate_error (error, my_error);
3978       return FALSE;
3979     }
3980
3981   return g_file_make_directory (file, cancellable, error);
3982 }
3983
3984 /**
3985  * g_file_make_symbolic_link:
3986  * @file: a #GFile with the name of the symlink to create
3987  * @symlink_value: (type filename): a string with the path for the target
3988  *     of the new symlink
3989  * @cancellable: (nullable): optional #GCancellable object,
3990  *     %NULL to ignore
3991  * @error: a #GError
3992  *
3993  * Creates a symbolic link named @file which contains the string
3994  * @symlink_value.
3995  *
3996  * If @cancellable is not %NULL, then the operation can be cancelled by
3997  * triggering the cancellable object from another thread. If the operation
3998  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
3999  *
4000  * Returns: %TRUE on the creation of a new symlink, %FALSE otherwise.
4001  */
4002 gboolean
4003 g_file_make_symbolic_link (GFile         *file,
4004                            const char    *symlink_value,
4005                            GCancellable  *cancellable,
4006                            GError       **error)
4007 {
4008   GFileIface *iface;
4009
4010   g_return_val_if_fail (G_IS_FILE (file), FALSE);
4011   g_return_val_if_fail (symlink_value != NULL, FALSE);
4012
4013   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4014     return FALSE;
4015
4016   if (*symlink_value == '\0')
4017     {
4018       g_set_error_literal (error, G_IO_ERROR,
4019                            G_IO_ERROR_INVALID_ARGUMENT,
4020                            _("Invalid symlink value given"));
4021       return FALSE;
4022     }
4023
4024   iface = G_FILE_GET_IFACE (file);
4025
4026   if (iface->make_symbolic_link == NULL)
4027     {
4028       g_set_error_literal (error, G_IO_ERROR,
4029                            G_IO_ERROR_NOT_SUPPORTED,
4030                            _("Operation not supported"));
4031       return FALSE;
4032     }
4033
4034   return (* iface->make_symbolic_link) (file, symlink_value, cancellable, error);
4035 }
4036
4037 /**
4038  * g_file_delete:
4039  * @file: input #GFile
4040  * @cancellable: (nullable): optional #GCancellable object,
4041  *     %NULL to ignore
4042  * @error: a #GError, or %NULL
4043  *
4044  * Deletes a file. If the @file is a directory, it will only be
4045  * deleted if it is empty. This has the same semantics as g_unlink().
4046  *
4047  * If @cancellable is not %NULL, then the operation can be cancelled by
4048  * triggering the cancellable object from another thread. If the operation
4049  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4050  *
4051  * Virtual: delete_file
4052  * Returns: %TRUE if the file was deleted. %FALSE otherwise.
4053  */
4054 gboolean
4055 g_file_delete (GFile         *file,
4056                GCancellable  *cancellable,
4057                GError       **error)
4058 {
4059   GFileIface *iface;
4060
4061   g_return_val_if_fail (G_IS_FILE (file), FALSE);
4062
4063   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4064     return FALSE;
4065
4066   iface = G_FILE_GET_IFACE (file);
4067
4068   if (iface->delete_file == NULL)
4069     {
4070       g_set_error_literal (error, G_IO_ERROR,
4071                            G_IO_ERROR_NOT_SUPPORTED,
4072                            _("Operation not supported"));
4073       return FALSE;
4074     }
4075
4076   return (* iface->delete_file) (file, cancellable, error);
4077 }
4078
4079 /**
4080  * g_file_delete_async:
4081  * @file: input #GFile
4082  * @io_priority: the [I/O priority][io-priority] of the request
4083  * @cancellable: (nullable): optional #GCancellable object,
4084  *     %NULL to ignore
4085  * @callback: a #GAsyncReadyCallback to call
4086  *     when the request is satisfied
4087  * @user_data: the data to pass to callback function
4088  *
4089  * Asynchronously delete a file. If the @file is a directory, it will
4090  * only be deleted if it is empty.  This has the same semantics as
4091  * g_unlink().
4092  *
4093  * Virtual: delete_file_async
4094  * Since: 2.34
4095  */
4096 void
4097 g_file_delete_async (GFile               *file,
4098                      int                  io_priority,
4099                      GCancellable        *cancellable,
4100                      GAsyncReadyCallback  callback,
4101                      gpointer             user_data)
4102 {
4103   GFileIface *iface;
4104
4105   g_return_if_fail (G_IS_FILE (file));
4106
4107   iface = G_FILE_GET_IFACE (file);
4108   (* iface->delete_file_async) (file,
4109                                 io_priority,
4110                                 cancellable,
4111                                 callback,
4112                                 user_data);
4113 }
4114
4115 /**
4116  * g_file_delete_finish:
4117  * @file: input #GFile
4118  * @result: a #GAsyncResult
4119  * @error: a #GError, or %NULL
4120  *
4121  * Finishes deleting a file started with g_file_delete_async().
4122  *
4123  * Virtual: delete_file_finish
4124  * Returns: %TRUE if the file was deleted. %FALSE otherwise.
4125  * Since: 2.34
4126  **/
4127 gboolean
4128 g_file_delete_finish (GFile         *file,
4129                       GAsyncResult  *result,
4130                       GError       **error)
4131 {
4132   GFileIface *iface;
4133
4134   g_return_val_if_fail (G_IS_FILE (file), FALSE);
4135   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
4136
4137   if (g_async_result_legacy_propagate_error (result, error))
4138     return FALSE;
4139
4140   iface = G_FILE_GET_IFACE (file);
4141   return (* iface->delete_file_finish) (file, result, error);
4142 }
4143
4144 /**
4145  * g_file_trash:
4146  * @file: #GFile to send to trash
4147  * @cancellable: (nullable): optional #GCancellable object,
4148  *     %NULL to ignore
4149  * @error: a #GError, or %NULL
4150  *
4151  * Sends @file to the "Trashcan", if possible. This is similar to
4152  * deleting it, but the user can recover it before emptying the trashcan.
4153  * Not all file systems support trashing, so this call can return the
4154  * %G_IO_ERROR_NOT_SUPPORTED error.
4155  *
4156  * If @cancellable is not %NULL, then the operation can be cancelled by
4157  * triggering the cancellable object from another thread. If the operation
4158  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4159  *
4160  * Virtual: trash
4161  * Returns: %TRUE on successful trash, %FALSE otherwise.
4162  */
4163 gboolean
4164 g_file_trash (GFile         *file,
4165               GCancellable  *cancellable,
4166               GError       **error)
4167 {
4168   GFileIface *iface;
4169
4170   g_return_val_if_fail (G_IS_FILE (file), FALSE);
4171
4172   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4173     return FALSE;
4174
4175   iface = G_FILE_GET_IFACE (file);
4176
4177   if (iface->trash == NULL)
4178     {
4179       g_set_error_literal (error,
4180                            G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
4181                            _("Trash not supported"));
4182       return FALSE;
4183     }
4184
4185   return (* iface->trash) (file, cancellable, error);
4186 }
4187
4188 /**
4189  * g_file_trash_async:
4190  * @file: input #GFile
4191  * @io_priority: the [I/O priority][io-priority] of the request
4192  * @cancellable: (nullable): optional #GCancellable object,
4193  *     %NULL to ignore
4194  * @callback: a #GAsyncReadyCallback to call
4195  *     when the request is satisfied
4196  * @user_data: the data to pass to callback function
4197  *
4198  * Asynchronously sends @file to the Trash location, if possible.
4199  *
4200  * Virtual: trash_async
4201  * Since: 2.38
4202  */
4203 void
4204 g_file_trash_async (GFile               *file,
4205                     int                  io_priority,
4206                     GCancellable        *cancellable,
4207                     GAsyncReadyCallback  callback,
4208                     gpointer             user_data)
4209 {
4210   GFileIface *iface;
4211
4212   g_return_if_fail (G_IS_FILE (file));
4213
4214   iface = G_FILE_GET_IFACE (file);
4215   (* iface->trash_async) (file,
4216                           io_priority,
4217                           cancellable,
4218                           callback,
4219                           user_data);
4220 }
4221
4222 /**
4223  * g_file_trash_finish:
4224  * @file: input #GFile
4225  * @result: a #GAsyncResult
4226  * @error: a #GError, or %NULL
4227  *
4228  * Finishes an asynchronous file trashing operation, started with
4229  * g_file_trash_async().
4230  *
4231  * Virtual: trash_finish
4232  * Returns: %TRUE on successful trash, %FALSE otherwise.
4233  * Since: 2.38
4234  */
4235 gboolean
4236 g_file_trash_finish (GFile         *file,
4237                      GAsyncResult  *result,
4238                      GError       **error)
4239 {
4240   GFileIface *iface;
4241
4242   g_return_val_if_fail (G_IS_FILE (file), FALSE);
4243   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
4244
4245   iface = G_FILE_GET_IFACE (file);
4246   return (* iface->trash_finish) (file, result, error);
4247 }
4248
4249 /**
4250  * g_file_set_display_name:
4251  * @file: input #GFile
4252  * @display_name: a string
4253  * @cancellable: (nullable): optional #GCancellable object,
4254  *     %NULL to ignore
4255  * @error: a #GError, or %NULL
4256  *
4257  * Renames @file to the specified display name.
4258  *
4259  * The display name is converted from UTF-8 to the correct encoding
4260  * for the target filesystem if possible and the @file is renamed to this.
4261  *
4262  * If you want to implement a rename operation in the user interface the
4263  * edit name (#G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME) should be used as the
4264  * initial value in the rename widget, and then the result after editing
4265  * should be passed to g_file_set_display_name().
4266  *
4267  * On success the resulting converted filename is returned.
4268  *
4269  * If @cancellable is not %NULL, then the operation can be cancelled by
4270  * triggering the cancellable object from another thread. If the operation
4271  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4272  *
4273  * Returns: (transfer full): a #GFile specifying what @file was renamed to,
4274  *     or %NULL if there was an error.
4275  *     Free the returned object with g_object_unref().
4276  */
4277 GFile *
4278 g_file_set_display_name (GFile         *file,
4279                          const gchar   *display_name,
4280                          GCancellable  *cancellable,
4281                          GError       **error)
4282 {
4283   GFileIface *iface;
4284
4285   g_return_val_if_fail (G_IS_FILE (file), NULL);
4286   g_return_val_if_fail (display_name != NULL, NULL);
4287
4288   if (strchr (display_name, G_DIR_SEPARATOR) != NULL)
4289     {
4290       g_set_error (error,
4291                    G_IO_ERROR,
4292                    G_IO_ERROR_INVALID_ARGUMENT,
4293                    _("File names cannot contain “%c”"), G_DIR_SEPARATOR);
4294       return NULL;
4295     }
4296
4297   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4298     return NULL;
4299
4300   iface = G_FILE_GET_IFACE (file);
4301
4302   return (* iface->set_display_name) (file, display_name, cancellable, error);
4303 }
4304
4305 /**
4306  * g_file_set_display_name_async:
4307  * @file: input #GFile
4308  * @display_name: a string
4309  * @io_priority: the [I/O priority][io-priority] of the request
4310  * @cancellable: (nullable): optional #GCancellable object,
4311  *     %NULL to ignore
4312  * @callback: (scope async): a #GAsyncReadyCallback to call
4313  *     when the request is satisfied
4314  * @user_data: (closure): the data to pass to callback function
4315  *
4316  * Asynchronously sets the display name for a given #GFile.
4317  *
4318  * For more details, see g_file_set_display_name() which is
4319  * the synchronous version of this call.
4320  *
4321  * When the operation is finished, @callback will be called.
4322  * You can then call g_file_set_display_name_finish() to get
4323  * the result of the operation.
4324  */
4325 void
4326 g_file_set_display_name_async (GFile               *file,
4327                                const gchar         *display_name,
4328                                gint                 io_priority,
4329                                GCancellable        *cancellable,
4330                                GAsyncReadyCallback  callback,
4331                                gpointer             user_data)
4332 {
4333   GFileIface *iface;
4334
4335   g_return_if_fail (G_IS_FILE (file));
4336   g_return_if_fail (display_name != NULL);
4337
4338   iface = G_FILE_GET_IFACE (file);
4339   (* iface->set_display_name_async) (file,
4340                                      display_name,
4341                                      io_priority,
4342                                      cancellable,
4343                                      callback,
4344                                      user_data);
4345 }
4346
4347 /**
4348  * g_file_set_display_name_finish:
4349  * @file: input #GFile
4350  * @res: a #GAsyncResult
4351  * @error: a #GError, or %NULL
4352  *
4353  * Finishes setting a display name started with
4354  * g_file_set_display_name_async().
4355  *
4356  * Returns: (transfer full): a #GFile or %NULL on error.
4357  *     Free the returned object with g_object_unref().
4358  */
4359 GFile *
4360 g_file_set_display_name_finish (GFile         *file,
4361                                 GAsyncResult  *res,
4362                                 GError       **error)
4363 {
4364   GFileIface *iface;
4365
4366   g_return_val_if_fail (G_IS_FILE (file), NULL);
4367   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4368
4369   if (g_async_result_legacy_propagate_error (res, error))
4370     return NULL;
4371
4372   iface = G_FILE_GET_IFACE (file);
4373   return (* iface->set_display_name_finish) (file, res, error);
4374 }
4375
4376 /**
4377  * g_file_query_settable_attributes:
4378  * @file: input #GFile
4379  * @cancellable: (nullable): optional #GCancellable object,
4380  *     %NULL to ignore
4381  * @error: a #GError, or %NULL
4382  *
4383  * Obtain the list of settable attributes for the file.
4384  *
4385  * Returns the type and full attribute name of all the attributes
4386  * that can be set on this file. This doesn't mean setting it will
4387  * always succeed though, you might get an access failure, or some
4388  * specific file may not support a specific attribute.
4389  *
4390  * If @cancellable is not %NULL, then the operation can be cancelled by
4391  * triggering the cancellable object from another thread. If the operation
4392  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4393  *
4394  * Returns: a #GFileAttributeInfoList describing the settable attributes.
4395  *     When you are done with it, release it with
4396  *     g_file_attribute_info_list_unref()
4397  */
4398 GFileAttributeInfoList *
4399 g_file_query_settable_attributes (GFile         *file,
4400                                   GCancellable  *cancellable,
4401                                   GError       **error)
4402 {
4403   GFileIface *iface;
4404   GError *my_error;
4405   GFileAttributeInfoList *list;
4406
4407   g_return_val_if_fail (G_IS_FILE (file), NULL);
4408
4409   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4410     return NULL;
4411
4412   iface = G_FILE_GET_IFACE (file);
4413
4414   if (iface->query_settable_attributes == NULL)
4415     return g_file_attribute_info_list_new ();
4416
4417   my_error = NULL;
4418   list = (* iface->query_settable_attributes) (file, cancellable, &my_error);
4419
4420   if (list == NULL)
4421     {
4422       if (my_error->domain == G_IO_ERROR && my_error->code == G_IO_ERROR_NOT_SUPPORTED)
4423         {
4424           list = g_file_attribute_info_list_new ();
4425           g_error_free (my_error);
4426         }
4427       else
4428         g_propagate_error (error, my_error);
4429     }
4430
4431   return list;
4432 }
4433
4434 /**
4435  * g_file_query_writable_namespaces:
4436  * @file: input #GFile
4437  * @cancellable: (nullable): optional #GCancellable object,
4438  *     %NULL to ignore
4439  * @error: a #GError, or %NULL
4440  *
4441  * Obtain the list of attribute namespaces where new attributes
4442  * can be created by a user. An example of this is extended
4443  * attributes (in the "xattr" namespace).
4444  *
4445  * If @cancellable is not %NULL, then the operation can be cancelled by
4446  * triggering the cancellable object from another thread. If the operation
4447  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4448  *
4449  * Returns: a #GFileAttributeInfoList describing the writable namespaces.
4450  *     When you are done with it, release it with
4451  *     g_file_attribute_info_list_unref()
4452  */
4453 GFileAttributeInfoList *
4454 g_file_query_writable_namespaces (GFile         *file,
4455                                   GCancellable  *cancellable,
4456                                   GError       **error)
4457 {
4458   GFileIface *iface;
4459   GError *my_error;
4460   GFileAttributeInfoList *list;
4461
4462   g_return_val_if_fail (G_IS_FILE (file), NULL);
4463
4464   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4465     return NULL;
4466
4467   iface = G_FILE_GET_IFACE (file);
4468
4469   if (iface->query_writable_namespaces == NULL)
4470     return g_file_attribute_info_list_new ();
4471
4472   my_error = NULL;
4473   list = (* iface->query_writable_namespaces) (file, cancellable, &my_error);
4474
4475   if (list == NULL)
4476     {
4477       g_warn_if_reached();
4478       list = g_file_attribute_info_list_new ();
4479     }
4480
4481   if (my_error != NULL)
4482     {
4483       if (my_error->domain == G_IO_ERROR && my_error->code == G_IO_ERROR_NOT_SUPPORTED)
4484         {
4485           g_error_free (my_error);
4486         }
4487       else
4488         g_propagate_error (error, my_error);
4489     }
4490
4491   return list;
4492 }
4493
4494 /**
4495  * g_file_set_attribute:
4496  * @file: input #GFile
4497  * @attribute: a string containing the attribute's name
4498  * @type: The type of the attribute
4499  * @value_p: (nullable): a pointer to the value (or the pointer
4500  *     itself if the type is a pointer type)
4501  * @flags: a set of #GFileQueryInfoFlags
4502  * @cancellable: (nullable): optional #GCancellable object,
4503  *     %NULL to ignore
4504  * @error: a #GError, or %NULL
4505  *
4506  * Sets an attribute in the file with attribute name @attribute to @value.
4507  *
4508  * Some attributes can be unset by setting @type to
4509  * %G_FILE_ATTRIBUTE_TYPE_INVALID and @value_p to %NULL.
4510  *
4511  * If @cancellable is not %NULL, then the operation can be cancelled by
4512  * triggering the cancellable object from another thread. If the operation
4513  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4514  *
4515  * Returns: %TRUE if the attribute was set, %FALSE otherwise.
4516  */
4517 gboolean
4518 g_file_set_attribute (GFile                *file,
4519                       const gchar          *attribute,
4520                       GFileAttributeType    type,
4521                       gpointer              value_p,
4522                       GFileQueryInfoFlags   flags,
4523                       GCancellable         *cancellable,
4524                       GError              **error)
4525 {
4526   GFileIface *iface;
4527
4528   g_return_val_if_fail (G_IS_FILE (file), FALSE);
4529   g_return_val_if_fail (attribute != NULL && *attribute != '\0', FALSE);
4530
4531   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4532     return FALSE;
4533
4534   iface = G_FILE_GET_IFACE (file);
4535
4536   if (iface->set_attribute == NULL)
4537     {
4538       g_set_error_literal (error, G_IO_ERROR,
4539                            G_IO_ERROR_NOT_SUPPORTED,
4540                            _("Operation not supported"));
4541       return FALSE;
4542     }
4543
4544   return (* iface->set_attribute) (file, attribute, type, value_p, flags, cancellable, error);
4545 }
4546
4547 /**
4548  * g_file_set_attributes_from_info:
4549  * @file: input #GFile
4550  * @info: a #GFileInfo
4551  * @flags: #GFileQueryInfoFlags
4552  * @cancellable: (nullable): optional #GCancellable object,
4553  *     %NULL to ignore
4554  * @error: a #GError, or %NULL
4555  *
4556  * Tries to set all attributes in the #GFileInfo on the target
4557  * values, not stopping on the first error.
4558  *
4559  * If there is any error during this operation then @error will
4560  * be set to the first error. Error on particular fields are flagged
4561  * by setting the "status" field in the attribute value to
4562  * %G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING, which means you can
4563  * also detect further errors.
4564  *
4565  * If @cancellable is not %NULL, then the operation can be cancelled by
4566  * triggering the cancellable object from another thread. If the operation
4567  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4568  *
4569  * Returns: %FALSE if there was any error, %TRUE otherwise.
4570  */
4571 gboolean
4572 g_file_set_attributes_from_info (GFile                *file,
4573                                  GFileInfo            *info,
4574                                  GFileQueryInfoFlags   flags,
4575                                  GCancellable         *cancellable,
4576                                  GError              **error)
4577 {
4578   GFileIface *iface;
4579
4580   g_return_val_if_fail (G_IS_FILE (file), FALSE);
4581   g_return_val_if_fail (G_IS_FILE_INFO (info), FALSE);
4582
4583   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4584     return FALSE;
4585
4586   g_file_info_clear_status (info);
4587
4588   iface = G_FILE_GET_IFACE (file);
4589
4590   return (* iface->set_attributes_from_info) (file,
4591                                               info,
4592                                               flags,
4593                                               cancellable,
4594                                               error);
4595 }
4596
4597 static gboolean
4598 g_file_real_set_attributes_from_info (GFile                *file,
4599                                       GFileInfo            *info,
4600                                       GFileQueryInfoFlags   flags,
4601                                       GCancellable         *cancellable,
4602                                       GError              **error)
4603 {
4604   char **attributes;
4605   int i;
4606   gboolean res;
4607   GFileAttributeValue *value;
4608
4609   res = TRUE;
4610
4611   attributes = g_file_info_list_attributes (info, NULL);
4612
4613   for (i = 0; attributes[i] != NULL; i++)
4614     {
4615       value = _g_file_info_get_attribute_value (info, attributes[i]);
4616
4617       if (value->status != G_FILE_ATTRIBUTE_STATUS_UNSET)
4618         continue;
4619
4620       if (!g_file_set_attribute (file, attributes[i],
4621                                  value->type, _g_file_attribute_value_peek_as_pointer (value),
4622                                  flags, cancellable, error))
4623         {
4624           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
4625           res = FALSE;
4626           /* Don't set error multiple times */
4627           error = NULL;
4628         }
4629       else
4630         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
4631     }
4632
4633   g_strfreev (attributes);
4634
4635   return res;
4636 }
4637
4638 /**
4639  * g_file_set_attributes_async:
4640  * @file: input #GFile
4641  * @info: a #GFileInfo
4642  * @flags: a #GFileQueryInfoFlags
4643  * @io_priority: the [I/O priority][io-priority] of the request
4644  * @cancellable: (nullable): optional #GCancellable object,
4645  *     %NULL to ignore
4646  * @callback: (scope async): a #GAsyncReadyCallback
4647  * @user_data: (closure): a #gpointer
4648  *
4649  * Asynchronously sets the attributes of @file with @info.
4650  *
4651  * For more details, see g_file_set_attributes_from_info(),
4652  * which is the synchronous version of this call.
4653  *
4654  * When the operation is finished, @callback will be called.
4655  * You can then call g_file_set_attributes_finish() to get
4656  * the result of the operation.
4657  */
4658 void
4659 g_file_set_attributes_async (GFile               *file,
4660                              GFileInfo           *info,
4661                              GFileQueryInfoFlags  flags,
4662                              int                  io_priority,
4663                              GCancellable        *cancellable,
4664                              GAsyncReadyCallback  callback,
4665                              gpointer             user_data)
4666 {
4667   GFileIface *iface;
4668
4669   g_return_if_fail (G_IS_FILE (file));
4670   g_return_if_fail (G_IS_FILE_INFO (info));
4671
4672   iface = G_FILE_GET_IFACE (file);
4673   (* iface->set_attributes_async) (file,
4674                                    info,
4675                                    flags,
4676                                    io_priority,
4677                                    cancellable,
4678                                    callback,
4679                                    user_data);
4680 }
4681
4682 /**
4683  * g_file_set_attributes_finish:
4684  * @file: input #GFile
4685  * @result: a #GAsyncResult
4686  * @info: (out) (transfer full): a #GFileInfo
4687  * @error: a #GError, or %NULL
4688  *
4689  * Finishes setting an attribute started in g_file_set_attributes_async().
4690  *
4691  * Returns: %TRUE if the attributes were set correctly, %FALSE otherwise.
4692  */
4693 gboolean
4694 g_file_set_attributes_finish (GFile         *file,
4695                               GAsyncResult  *result,
4696                               GFileInfo    **info,
4697                               GError       **error)
4698 {
4699   GFileIface *iface;
4700
4701   g_return_val_if_fail (G_IS_FILE (file), FALSE);
4702   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
4703
4704   /* No standard handling of errors here, as we must set info even
4705    * on errors
4706    */
4707   iface = G_FILE_GET_IFACE (file);
4708   return (* iface->set_attributes_finish) (file, result, info, error);
4709 }
4710
4711 /**
4712  * g_file_set_attribute_string:
4713  * @file: input #GFile
4714  * @attribute: a string containing the attribute's name
4715  * @value: a string containing the attribute's value
4716  * @flags: #GFileQueryInfoFlags
4717  * @cancellable: (nullable): optional #GCancellable object,
4718  *     %NULL to ignore
4719  * @error: a #GError, or %NULL
4720  *
4721  * Sets @attribute of type %G_FILE_ATTRIBUTE_TYPE_STRING to @value.
4722  * If @attribute is of a different type, this operation will fail.
4723  *
4724  * If @cancellable is not %NULL, then the operation can be cancelled by
4725  * triggering the cancellable object from another thread. If the operation
4726  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4727  *
4728  * Returns: %TRUE if the @attribute was successfully set, %FALSE otherwise.
4729  */
4730 gboolean
4731 g_file_set_attribute_string (GFile                *file,
4732                              const char           *attribute,
4733                              const char           *value,
4734                              GFileQueryInfoFlags   flags,
4735                              GCancellable         *cancellable,
4736                              GError              **error)
4737 {
4738   return g_file_set_attribute (file, attribute,
4739                                G_FILE_ATTRIBUTE_TYPE_STRING, (gpointer)value,
4740                                flags, cancellable, error);
4741 }
4742
4743 /**
4744  * g_file_set_attribute_byte_string:
4745  * @file: input #GFile
4746  * @attribute: a string containing the attribute's name
4747  * @value: a string containing the attribute's new value
4748  * @flags: a #GFileQueryInfoFlags
4749  * @cancellable: (nullable): optional #GCancellable object,
4750  *     %NULL to ignore
4751  * @error: a #GError, or %NULL
4752  *
4753  * Sets @attribute of type %G_FILE_ATTRIBUTE_TYPE_BYTE_STRING to @value.
4754  * If @attribute is of a different type, this operation will fail,
4755  * returning %FALSE.
4756  *
4757  * If @cancellable is not %NULL, then the operation can be cancelled by
4758  * triggering the cancellable object from another thread. If the operation
4759  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4760  *
4761  * Returns: %TRUE if the @attribute was successfully set to @value
4762  *     in the @file, %FALSE otherwise.
4763  */
4764 gboolean
4765 g_file_set_attribute_byte_string  (GFile                *file,
4766                                    const gchar          *attribute,
4767                                    const gchar          *value,
4768                                    GFileQueryInfoFlags   flags,
4769                                    GCancellable         *cancellable,
4770                                    GError              **error)
4771 {
4772   return g_file_set_attribute (file, attribute,
4773                                G_FILE_ATTRIBUTE_TYPE_BYTE_STRING, (gpointer)value,
4774                                flags, cancellable, error);
4775 }
4776
4777 /**
4778  * g_file_set_attribute_uint32:
4779  * @file: input #GFile
4780  * @attribute: a string containing the attribute's name
4781  * @value: a #guint32 containing the attribute's new value
4782  * @flags: a #GFileQueryInfoFlags
4783  * @cancellable: (nullable): optional #GCancellable object,
4784  *     %NULL to ignore
4785  * @error: a #GError, or %NULL
4786  *
4787  * Sets @attribute of type %G_FILE_ATTRIBUTE_TYPE_UINT32 to @value.
4788  * If @attribute is of a different type, this operation will fail.
4789  *
4790  * If @cancellable is not %NULL, then the operation can be cancelled by
4791  * triggering the cancellable object from another thread. If the operation
4792  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4793  *
4794  * Returns: %TRUE if the @attribute was successfully set to @value
4795  *     in the @file, %FALSE otherwise.
4796  */
4797 gboolean
4798 g_file_set_attribute_uint32 (GFile                *file,
4799                              const gchar          *attribute,
4800                              guint32               value,
4801                              GFileQueryInfoFlags   flags,
4802                              GCancellable         *cancellable,
4803                              GError              **error)
4804 {
4805   return g_file_set_attribute (file, attribute,
4806                                G_FILE_ATTRIBUTE_TYPE_UINT32, &value,
4807                                flags, cancellable, error);
4808 }
4809
4810 /**
4811  * g_file_set_attribute_int32:
4812  * @file: input #GFile
4813  * @attribute: a string containing the attribute's name
4814  * @value: a #gint32 containing the attribute's new value
4815  * @flags: a #GFileQueryInfoFlags
4816  * @cancellable: (nullable): optional #GCancellable object,
4817  *     %NULL to ignore
4818  * @error: a #GError, or %NULL
4819  *
4820  * Sets @attribute of type %G_FILE_ATTRIBUTE_TYPE_INT32 to @value.
4821  * If @attribute is of a different type, this operation will fail.
4822  *
4823  * If @cancellable is not %NULL, then the operation can be cancelled by
4824  * triggering the cancellable object from another thread. If the operation
4825  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4826  *
4827  * Returns: %TRUE if the @attribute was successfully set to @value
4828  *     in the @file, %FALSE otherwise.
4829  */
4830 gboolean
4831 g_file_set_attribute_int32 (GFile                *file,
4832                             const gchar          *attribute,
4833                             gint32                value,
4834                             GFileQueryInfoFlags   flags,
4835                             GCancellable         *cancellable,
4836                             GError              **error)
4837 {
4838   return g_file_set_attribute (file, attribute,
4839                                G_FILE_ATTRIBUTE_TYPE_INT32, &value,
4840                                flags, cancellable, error);
4841 }
4842
4843 /**
4844  * g_file_set_attribute_uint64:
4845  * @file: input #GFile
4846  * @attribute: a string containing the attribute's name
4847  * @value: a #guint64 containing the attribute's new value
4848  * @flags: a #GFileQueryInfoFlags
4849  * @cancellable: (nullable): optional #GCancellable object,
4850  *     %NULL to ignore
4851  * @error: a #GError, or %NULL
4852  *
4853  * Sets @attribute of type %G_FILE_ATTRIBUTE_TYPE_UINT64 to @value.
4854  * If @attribute is of a different type, this operation will fail.
4855  *
4856  * If @cancellable is not %NULL, then the operation can be cancelled by
4857  * triggering the cancellable object from another thread. If the operation
4858  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4859  *
4860  * Returns: %TRUE if the @attribute was successfully set to @value
4861  *     in the @file, %FALSE otherwise.
4862  */
4863 gboolean
4864 g_file_set_attribute_uint64 (GFile                *file,
4865                              const gchar          *attribute,
4866                              guint64               value,
4867                              GFileQueryInfoFlags   flags,
4868                              GCancellable         *cancellable,
4869                              GError              **error)
4870  {
4871   return g_file_set_attribute (file, attribute,
4872                                G_FILE_ATTRIBUTE_TYPE_UINT64, &value,
4873                                flags, cancellable, error);
4874 }
4875
4876 /**
4877  * g_file_set_attribute_int64:
4878  * @file: input #GFile
4879  * @attribute: a string containing the attribute's name
4880  * @value: a #guint64 containing the attribute's new value
4881  * @flags: a #GFileQueryInfoFlags
4882  * @cancellable: (nullable): optional #GCancellable object,
4883  *     %NULL to ignore
4884  * @error: a #GError, or %NULL
4885  *
4886  * Sets @attribute of type %G_FILE_ATTRIBUTE_TYPE_INT64 to @value.
4887  * If @attribute is of a different type, this operation will fail.
4888  *
4889  * If @cancellable is not %NULL, then the operation can be cancelled by
4890  * triggering the cancellable object from another thread. If the operation
4891  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4892  *
4893  * Returns: %TRUE if the @attribute was successfully set, %FALSE otherwise.
4894  */
4895 gboolean
4896 g_file_set_attribute_int64 (GFile                *file,
4897                             const gchar          *attribute,
4898                             gint64                value,
4899                             GFileQueryInfoFlags   flags,
4900                             GCancellable         *cancellable,
4901                             GError              **error)
4902 {
4903   return g_file_set_attribute (file, attribute,
4904                                G_FILE_ATTRIBUTE_TYPE_INT64, &value,
4905                                flags, cancellable, error);
4906 }
4907
4908 /**
4909  * g_file_mount_mountable:
4910  * @file: input #GFile
4911  * @flags: flags affecting the operation
4912  * @mount_operation: (nullable): a #GMountOperation,
4913  *     or %NULL to avoid user interaction
4914  * @cancellable: (nullable): optional #GCancellable object,
4915  *     %NULL to ignore
4916  * @callback: (scope async) (nullable): a #GAsyncReadyCallback to call
4917  *     when the request is satisfied, or %NULL
4918  * @user_data: (closure): the data to pass to callback function
4919  *
4920  * Mounts a file of type G_FILE_TYPE_MOUNTABLE.
4921  * Using @mount_operation, you can request callbacks when, for instance,
4922  * passwords are needed during authentication.
4923  *
4924  * If @cancellable is not %NULL, then the operation can be cancelled by
4925  * triggering the cancellable object from another thread. If the operation
4926  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4927  *
4928  * When the operation is finished, @callback will be called.
4929  * You can then call g_file_mount_mountable_finish() to get
4930  * the result of the operation.
4931  */
4932 void
4933 g_file_mount_mountable (GFile               *file,
4934                         GMountMountFlags     flags,
4935                         GMountOperation     *mount_operation,
4936                         GCancellable        *cancellable,
4937                         GAsyncReadyCallback  callback,
4938                         gpointer             user_data)
4939 {
4940   GFileIface *iface;
4941
4942   g_return_if_fail (G_IS_FILE (file));
4943
4944   iface = G_FILE_GET_IFACE (file);
4945
4946   if (iface->mount_mountable == NULL)
4947     {
4948       g_task_report_new_error (file, callback, user_data,
4949                                g_file_mount_mountable,
4950                                G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
4951                                _("Operation not supported"));
4952       return;
4953     }
4954
4955   (* iface->mount_mountable) (file,
4956                               flags,
4957                               mount_operation,
4958                               cancellable,
4959                               callback,
4960                               user_data);
4961 }
4962
4963 /**
4964  * g_file_mount_mountable_finish:
4965  * @file: input #GFile
4966  * @result: a #GAsyncResult
4967  * @error: a #GError, or %NULL
4968  *
4969  * Finishes a mount operation. See g_file_mount_mountable() for details.
4970  *
4971  * Finish an asynchronous mount operation that was started
4972  * with g_file_mount_mountable().
4973  *
4974  * Returns: (transfer full): a #GFile or %NULL on error.
4975  *     Free the returned object with g_object_unref().
4976  */
4977 GFile *
4978 g_file_mount_mountable_finish (GFile         *file,
4979                                GAsyncResult  *result,
4980                                GError       **error)
4981 {
4982   GFileIface *iface;
4983
4984   g_return_val_if_fail (G_IS_FILE (file), NULL);
4985   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), NULL);
4986
4987   if (g_async_result_legacy_propagate_error (result, error))
4988     return NULL;
4989   else if (g_async_result_is_tagged (result, g_file_mount_mountable))
4990     return g_task_propagate_pointer (G_TASK (result), error);
4991
4992   iface = G_FILE_GET_IFACE (file);
4993   return (* iface->mount_mountable_finish) (file, result, error);
4994 }
4995
4996 /**
4997  * g_file_unmount_mountable:
4998  * @file: input #GFile
4999  * @flags: flags affecting the operation
5000  * @cancellable: (nullable): optional #GCancellable object,
5001  *     %NULL to ignore
5002  * @callback: (scope async) (nullable): a #GAsyncReadyCallback to call
5003  *     when the request is satisfied, or %NULL
5004  * @user_data: (closure): the data to pass to callback function
5005  *
5006  * Unmounts a file of type G_FILE_TYPE_MOUNTABLE.
5007  *
5008  * If @cancellable is not %NULL, then the operation can be cancelled by
5009  * triggering the cancellable object from another thread. If the operation
5010  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
5011  *
5012  * When the operation is finished, @callback will be called.
5013  * You can then call g_file_unmount_mountable_finish() to get
5014  * the result of the operation.
5015  *
5016  * Deprecated: 2.22: Use g_file_unmount_mountable_with_operation() instead.
5017  */
5018 void
5019 g_file_unmount_mountable (GFile               *file,
5020                           GMountUnmountFlags   flags,
5021                           GCancellable        *cancellable,
5022                           GAsyncReadyCallback  callback,
5023                           gpointer             user_data)
5024 {
5025   GFileIface *iface;
5026
5027   g_return_if_fail (G_IS_FILE (file));
5028
5029   iface = G_FILE_GET_IFACE (file);
5030
5031   if (iface->unmount_mountable == NULL)
5032     {
5033       g_task_report_new_error (file, callback, user_data,
5034                                g_file_unmount_mountable_with_operation,
5035                                G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
5036                                _("Operation not supported"));
5037       return;
5038     }
5039
5040   (* iface->unmount_mountable) (file,
5041                                 flags,
5042                                 cancellable,
5043                                 callback,
5044                                 user_data);
5045 }
5046
5047 /**
5048  * g_file_unmount_mountable_finish:
5049  * @file: input #GFile
5050  * @result: a #GAsyncResult
5051  * @error: a #GError, or %NULL
5052  *
5053  * Finishes an unmount operation, see g_file_unmount_mountable() for details.
5054  *
5055  * Finish an asynchronous unmount operation that was started
5056  * with g_file_unmount_mountable().
5057  *
5058  * Returns: %TRUE if the operation finished successfully.
5059  *     %FALSE otherwise.
5060  *
5061  * Deprecated: 2.22: Use g_file_unmount_mountable_with_operation_finish()
5062  *     instead.
5063  */
5064 gboolean
5065 g_file_unmount_mountable_finish (GFile         *file,
5066                                  GAsyncResult  *result,
5067                                  GError       **error)
5068 {
5069   GFileIface *iface;
5070
5071   g_return_val_if_fail (G_IS_FILE (file), FALSE);
5072   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
5073
5074   if (g_async_result_legacy_propagate_error (result, error))
5075     return FALSE;
5076   else if (g_async_result_is_tagged (result, g_file_unmount_mountable_with_operation))
5077     return g_task_propagate_boolean (G_TASK (result), error);
5078
5079   iface = G_FILE_GET_IFACE (file);
5080   return (* iface->unmount_mountable_finish) (file, result, error);
5081 }
5082
5083 /**
5084  * g_file_unmount_mountable_with_operation:
5085  * @file: input #GFile
5086  * @flags: flags affecting the operation
5087  * @mount_operation: (nullable): a #GMountOperation,
5088  *     or %NULL to avoid user interaction
5089  * @cancellable: (nullable): optional #GCancellable object,
5090  *     %NULL to ignore
5091  * @callback: (scope async) (nullable): a #GAsyncReadyCallback to call
5092  *     when the request is satisfied, or %NULL
5093  * @user_data: (closure): the data to pass to callback function
5094  *
5095  * Unmounts a file of type #G_FILE_TYPE_MOUNTABLE.
5096  *
5097  * If @cancellable is not %NULL, then the operation can be cancelled by
5098  * triggering the cancellable object from another thread. If the operation
5099  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
5100  *
5101  * When the operation is finished, @callback will be called.
5102  * You can then call g_file_unmount_mountable_finish() to get
5103  * the result of the operation.
5104  *
5105  * Since: 2.22
5106  */
5107 void
5108 g_file_unmount_mountable_with_operation (GFile               *file,
5109                                          GMountUnmountFlags   flags,
5110                                          GMountOperation     *mount_operation,
5111                                          GCancellable        *cancellable,
5112                                          GAsyncReadyCallback  callback,
5113                                          gpointer             user_data)
5114 {
5115   GFileIface *iface;
5116
5117   g_return_if_fail (G_IS_FILE (file));
5118
5119   iface = G_FILE_GET_IFACE (file);
5120
5121   if (iface->unmount_mountable == NULL && iface->unmount_mountable_with_operation == NULL)
5122     {
5123       g_task_report_new_error (file, callback, user_data,
5124                                g_file_unmount_mountable_with_operation,
5125                                G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
5126                                _("Operation not supported"));
5127       return;
5128     }
5129
5130   if (iface->unmount_mountable_with_operation != NULL)
5131     (* iface->unmount_mountable_with_operation) (file,
5132                                                  flags,
5133                                                  mount_operation,
5134                                                  cancellable,
5135                                                  callback,
5136                                                  user_data);
5137   else
5138     (* iface->unmount_mountable) (file,
5139                                   flags,
5140                                   cancellable,
5141                                   callback,
5142                                   user_data);
5143 }
5144
5145 /**
5146  * g_file_unmount_mountable_with_operation_finish:
5147  * @file: input #GFile
5148  * @result: a #GAsyncResult
5149  * @error: a #GError, or %NULL
5150  *
5151  * Finishes an unmount operation,
5152  * see g_file_unmount_mountable_with_operation() for details.
5153  *
5154  * Finish an asynchronous unmount operation that was started
5155  * with g_file_unmount_mountable_with_operation().
5156  *
5157  * Returns: %TRUE if the operation finished successfully.
5158  *     %FALSE otherwise.
5159  *
5160  * Since: 2.22
5161  */
5162 gboolean
5163 g_file_unmount_mountable_with_operation_finish (GFile         *file,
5164                                                 GAsyncResult  *result,
5165                                                 GError       **error)
5166 {
5167   GFileIface *iface;
5168
5169   g_return_val_if_fail (G_IS_FILE (file), FALSE);
5170   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
5171
5172   if (g_async_result_legacy_propagate_error (result, error))
5173     return FALSE;
5174   else if (g_async_result_is_tagged (result, g_file_unmount_mountable_with_operation))
5175     return g_task_propagate_boolean (G_TASK (result), error);
5176
5177   iface = G_FILE_GET_IFACE (file);
5178   if (iface->unmount_mountable_with_operation_finish != NULL)
5179     return (* iface->unmount_mountable_with_operation_finish) (file, result, error);
5180   else
5181     return (* iface->unmount_mountable_finish) (file, result, error);
5182 }
5183
5184 /**
5185  * g_file_eject_mountable:
5186  * @file: input #GFile
5187  * @flags: flags affecting the operation
5188  * @cancellable: (nullable): optional #GCancellable object,
5189  *     %NULL to ignore
5190  * @callback: (scope async) (nullable): a #GAsyncReadyCallback to call
5191  *     when the request is satisfied, or %NULL
5192  * @user_data: (closure): the data to pass to callback function
5193  *
5194  * Starts an asynchronous eject on a mountable.
5195  * When this operation has completed, @callback will be called with
5196  * @user_user data, and the operation can be finalized with
5197  * g_file_eject_mountable_finish().
5198  *
5199  * If @cancellable is not %NULL, then the operation can be cancelled by
5200  * triggering the cancellable object from another thread. If the operation
5201  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
5202  *
5203  * Deprecated: 2.22: Use g_file_eject_mountable_with_operation() instead.
5204  */
5205 void
5206 g_file_eject_mountable (GFile               *file,
5207                         GMountUnmountFlags   flags,
5208                         GCancellable        *cancellable,
5209                         GAsyncReadyCallback  callback,
5210                         gpointer             user_data)
5211 {
5212   GFileIface *iface;
5213
5214   g_return_if_fail (G_IS_FILE (file));
5215
5216   iface = G_FILE_GET_IFACE (file);
5217
5218   if (iface->eject_mountable == NULL)
5219     {
5220       g_task_report_new_error (file, callback, user_data,
5221                                g_file_eject_mountable_with_operation,
5222                                G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
5223                                _("Operation not supported"));
5224       return;
5225     }
5226
5227   (* iface->eject_mountable) (file,
5228                               flags,
5229                               cancellable,
5230                               callback,
5231                               user_data);
5232 }
5233
5234 /**
5235  * g_file_eject_mountable_finish:
5236  * @file: input #GFile
5237  * @result: a #GAsyncResult
5238  * @error: a #GError, or %NULL
5239  *
5240  * Finishes an asynchronous eject operation started by
5241  * g_file_eject_mountable().
5242  *
5243  * Returns: %TRUE if the @file was ejected successfully.
5244  *     %FALSE otherwise.
5245  *
5246  * Deprecated: 2.22: Use g_file_eject_mountable_with_operation_finish()
5247  *     instead.
5248  */
5249 gboolean
5250 g_file_eject_mountable_finish (GFile         *file,
5251                                GAsyncResult  *result,
5252                                GError       **error)
5253 {
5254   GFileIface *iface;
5255
5256   g_return_val_if_fail (G_IS_FILE (file), FALSE);
5257   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
5258
5259   if (g_async_result_legacy_propagate_error (result, error))
5260     return FALSE;
5261   else if (g_async_result_is_tagged (result, g_file_eject_mountable_with_operation))
5262     return g_task_propagate_boolean (G_TASK (result), error);
5263
5264   iface = G_FILE_GET_IFACE (file);
5265   return (* iface->eject_mountable_finish) (file, result, error);
5266 }
5267
5268 /**
5269  * g_file_eject_mountable_with_operation:
5270  * @file: input #GFile
5271  * @flags: flags affecting the operation
5272  * @mount_operation: (nullable): a #GMountOperation,
5273  *     or %NULL to avoid user interaction
5274  * @cancellable: (nullable): optional #GCancellable object,
5275  *     %NULL to ignore
5276  * @callback: (scope async) (nullable): a #GAsyncReadyCallback to call
5277  *     when the request is satisfied, or %NULL
5278  * @user_data: (closure): the data to pass to callback function
5279  *
5280  * Starts an asynchronous eject on a mountable.
5281  * When this operation has completed, @callback will be called with
5282  * @user_user data, and the operation can be finalized with
5283  * g_file_eject_mountable_with_operation_finish().
5284  *
5285  * If @cancellable is not %NULL, then the operation can be cancelled by
5286  * triggering the cancellable object from another thread. If the operation
5287  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
5288  *
5289  * Since: 2.22
5290  */
5291 void
5292 g_file_eject_mountable_with_operation (GFile               *file,
5293                                        GMountUnmountFlags   flags,
5294                                        GMountOperation     *mount_operation,
5295                                        GCancellable        *cancellable,
5296                                        GAsyncReadyCallback  callback,
5297                                        gpointer             user_data)
5298 {
5299   GFileIface *iface;
5300
5301   g_return_if_fail (G_IS_FILE (file));
5302
5303   iface = G_FILE_GET_IFACE (file);
5304
5305   if (iface->eject_mountable == NULL && iface->eject_mountable_with_operation == NULL)
5306     {
5307       g_task_report_new_error (file, callback, user_data,
5308                                g_file_eject_mountable_with_operation,
5309                                G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
5310                                _("Operation not supported"));
5311       return;
5312     }
5313
5314   if (iface->eject_mountable_with_operation != NULL)
5315     (* iface->eject_mountable_with_operation) (file,
5316                                                flags,
5317                                                mount_operation,
5318                                                cancellable,
5319                                                callback,
5320                                                user_data);
5321   else
5322     (* iface->eject_mountable) (file,
5323                                 flags,
5324                                 cancellable,
5325                                 callback,
5326                                 user_data);
5327 }
5328
5329 /**
5330  * g_file_eject_mountable_with_operation_finish:
5331  * @file: input #GFile
5332  * @result: a #GAsyncResult
5333  * @error: a #GError, or %NULL
5334  *
5335  * Finishes an asynchronous eject operation started by
5336  * g_file_eject_mountable_with_operation().
5337  *
5338  * Returns: %TRUE if the @file was ejected successfully.
5339  *     %FALSE otherwise.
5340  *
5341  * Since: 2.22
5342  */
5343 gboolean
5344 g_file_eject_mountable_with_operation_finish (GFile         *file,
5345                                               GAsyncResult  *result,
5346                                               GError       **error)
5347 {
5348   GFileIface *iface;
5349
5350   g_return_val_if_fail (G_IS_FILE (file), FALSE);
5351   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
5352
5353   if (g_async_result_legacy_propagate_error (result, error))
5354     return FALSE;
5355   else if (g_async_result_is_tagged (result, g_file_eject_mountable_with_operation))
5356     return g_task_propagate_boolean (G_TASK (result), error);
5357
5358   iface = G_FILE_GET_IFACE (file);
5359   if (iface->eject_mountable_with_operation_finish != NULL)
5360     return (* iface->eject_mountable_with_operation_finish) (file, result, error);
5361   else
5362     return (* iface->eject_mountable_finish) (file, result, error);
5363 }
5364
5365 /**
5366  * g_file_monitor_directory:
5367  * @file: input #GFile
5368  * @flags: a set of #GFileMonitorFlags
5369  * @cancellable: (nullable): optional #GCancellable object,
5370  *     %NULL to ignore
5371  * @error: a #GError, or %NULL
5372  *
5373  * Obtains a directory monitor for the given file.
5374  * This may fail if directory monitoring is not supported.
5375  *
5376  * If @cancellable is not %NULL, then the operation can be cancelled by
5377  * triggering the cancellable object from another thread. If the operation
5378  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
5379  *
5380  * It does not make sense for @flags to contain
5381  * %G_FILE_MONITOR_WATCH_HARD_LINKS, since hard links can not be made to
5382  * directories.  It is not possible to monitor all the files in a
5383  * directory for changes made via hard links; if you want to do this then
5384  * you must register individual watches with g_file_monitor().
5385  *
5386  * Virtual: monitor_dir
5387  * Returns: (transfer full): a #GFileMonitor for the given @file,
5388  *     or %NULL on error.
5389  *     Free the returned object with g_object_unref().
5390  */
5391 GFileMonitor *
5392 g_file_monitor_directory (GFile              *file,
5393                           GFileMonitorFlags   flags,
5394                           GCancellable       *cancellable,
5395                           GError            **error)
5396 {
5397   GFileIface *iface;
5398
5399   g_return_val_if_fail (G_IS_FILE (file), NULL);
5400   g_return_val_if_fail (~flags & G_FILE_MONITOR_WATCH_HARD_LINKS, NULL);
5401
5402   if (g_cancellable_set_error_if_cancelled (cancellable, error))
5403     return NULL;
5404
5405   iface = G_FILE_GET_IFACE (file);
5406
5407   if (iface->monitor_dir == NULL)
5408     {
5409       g_set_error_literal (error, G_IO_ERROR,
5410                            G_IO_ERROR_NOT_SUPPORTED,
5411                            _("Operation not supported"));
5412       return NULL;
5413     }
5414
5415   return (* iface->monitor_dir) (file, flags, cancellable, error);
5416 }
5417
5418 /**
5419  * g_file_monitor_file:
5420  * @file: input #GFile
5421  * @flags: a set of #GFileMonitorFlags
5422  * @cancellable: (nullable): optional #GCancellable object,
5423  *     %NULL to ignore
5424  * @error: a #GError, or %NULL
5425  *
5426  * Obtains a file monitor for the given file. If no file notification
5427  * mechanism exists, then regular polling of the file is used.
5428  *
5429  * If @cancellable is not %NULL, then the operation can be cancelled by
5430  * triggering the cancellable object from another thread. If the operation
5431  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
5432  *
5433  * If @flags contains %G_FILE_MONITOR_WATCH_HARD_LINKS then the monitor
5434  * will also attempt to report changes made to the file via another
5435  * filename (ie, a hard link). Without this flag, you can only rely on
5436  * changes made through the filename contained in @file to be
5437  * reported. Using this flag may result in an increase in resource
5438  * usage, and may not have any effect depending on the #GFileMonitor
5439  * backend and/or filesystem type.
5440  * 
5441  * Returns: (transfer full): a #GFileMonitor for the given @file,
5442  *     or %NULL on error.
5443  *     Free the returned object with g_object_unref().
5444  */
5445 GFileMonitor *
5446 g_file_monitor_file (GFile              *file,
5447                      GFileMonitorFlags   flags,
5448                      GCancellable       *cancellable,
5449                      GError            **error)
5450 {
5451   GFileIface *iface;
5452   GFileMonitor *monitor;
5453
5454   g_return_val_if_fail (G_IS_FILE (file), NULL);
5455
5456   if (g_cancellable_set_error_if_cancelled (cancellable, error))
5457     return NULL;
5458
5459   iface = G_FILE_GET_IFACE (file);
5460
5461   monitor = NULL;
5462
5463   if (iface->monitor_file)
5464     monitor = (* iface->monitor_file) (file, flags, cancellable, NULL);
5465
5466   /* Fallback to polling */
5467   if (monitor == NULL)
5468     monitor = _g_poll_file_monitor_new (file);
5469
5470   return monitor;
5471 }
5472
5473 /**
5474  * g_file_monitor:
5475  * @file: input #GFile
5476  * @flags: a set of #GFileMonitorFlags
5477  * @cancellable: (nullable): optional #GCancellable object,
5478  *     %NULL to ignore
5479  * @error: a #GError, or %NULL
5480  *
5481  * Obtains a file or directory monitor for the given file,
5482  * depending on the type of the file.
5483  *
5484  * If @cancellable is not %NULL, then the operation can be cancelled by
5485  * triggering the cancellable object from another thread. If the operation
5486  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
5487  *
5488  * Returns: (transfer full): a #GFileMonitor for the given @file,
5489  *     or %NULL on error.
5490  *     Free the returned object with g_object_unref().
5491  *
5492  * Since: 2.18
5493  */
5494 GFileMonitor *
5495 g_file_monitor (GFile              *file,
5496                 GFileMonitorFlags   flags,
5497                 GCancellable       *cancellable,
5498                 GError            **error)
5499 {
5500   if (g_file_query_file_type (file, 0, cancellable) == G_FILE_TYPE_DIRECTORY)
5501     return g_file_monitor_directory (file,
5502                                      flags & ~G_FILE_MONITOR_WATCH_HARD_LINKS,
5503                                      cancellable, error);
5504   else
5505     return g_file_monitor_file (file, flags, cancellable, error);
5506 }
5507
5508 /********************************************
5509  *   Default implementation of async ops    *
5510  ********************************************/
5511
5512 typedef struct {
5513   char *attributes;
5514   GFileQueryInfoFlags flags;
5515 } QueryInfoAsyncData;
5516
5517 static void
5518 query_info_data_free (QueryInfoAsyncData *data)
5519 {
5520   g_free (data->attributes);
5521   g_free (data);
5522 }
5523
5524 static void
5525 query_info_async_thread (GTask         *task,
5526                          gpointer       object,
5527                          gpointer       task_data,
5528                          GCancellable  *cancellable)
5529 {
5530   QueryInfoAsyncData *data = task_data;
5531   GFileInfo *info;
5532   GError *error = NULL;
5533
5534   info = g_file_query_info (G_FILE (object), data->attributes, data->flags, cancellable, &error);
5535   if (info)
5536     g_task_return_pointer (task, info, g_object_unref);
5537   else
5538     g_task_return_error (task, error);
5539 }
5540
5541 static void
5542 g_file_real_query_info_async (GFile               *file,
5543                               const char          *attributes,
5544                               GFileQueryInfoFlags  flags,
5545                               int                  io_priority,
5546                               GCancellable        *cancellable,
5547                               GAsyncReadyCallback  callback,
5548                               gpointer             user_data)
5549 {
5550   GTask *task;
5551   QueryInfoAsyncData *data;
5552
5553   data = g_new0 (QueryInfoAsyncData, 1);
5554   data->attributes = g_strdup (attributes);
5555   data->flags = flags;
5556
5557   task = g_task_new (file, cancellable, callback, user_data);
5558   g_task_set_source_tag (task, g_file_real_query_info_async);
5559   g_task_set_task_data (task, data, (GDestroyNotify)query_info_data_free);
5560   g_task_set_priority (task, io_priority);
5561   g_task_run_in_thread (task, query_info_async_thread);
5562   g_object_unref (task);
5563 }
5564
5565 static GFileInfo *
5566 g_file_real_query_info_finish (GFile         *file,
5567                                GAsyncResult  *res,
5568                                GError       **error)
5569 {
5570   g_return_val_if_fail (g_task_is_valid (res, file), NULL);
5571
5572   return g_task_propagate_pointer (G_TASK (res), error);
5573 }
5574
5575 static void
5576 query_filesystem_info_async_thread (GTask         *task,
5577                                     gpointer       object,
5578                                     gpointer       task_data,
5579                                     GCancellable  *cancellable)
5580 {
5581   const char *attributes = task_data;
5582   GFileInfo *info;
5583   GError *error = NULL;
5584
5585   info = g_file_query_filesystem_info (G_FILE (object), attributes, cancellable, &error);
5586   if (info)
5587     g_task_return_pointer (task, info, g_object_unref);
5588   else
5589     g_task_return_error (task, error);
5590 }
5591
5592 static void
5593 g_file_real_query_filesystem_info_async (GFile               *file,
5594                                          const char          *attributes,
5595                                          int                  io_priority,
5596                                          GCancellable        *cancellable,
5597                                          GAsyncReadyCallback  callback,
5598                                          gpointer             user_data)
5599 {
5600   GTask *task;
5601
5602   task = g_task_new (file, cancellable, callback, user_data);
5603   g_task_set_source_tag (task, g_file_real_query_filesystem_info_async);
5604   g_task_set_task_data (task, g_strdup (attributes), g_free);
5605   g_task_set_priority (task, io_priority);
5606   g_task_run_in_thread (task, query_filesystem_info_async_thread);
5607   g_object_unref (task);
5608 }
5609
5610 static GFileInfo *
5611 g_file_real_query_filesystem_info_finish (GFile         *file,
5612                                           GAsyncResult  *res,
5613                                           GError       **error)
5614 {
5615   g_return_val_if_fail (g_task_is_valid (res, file), NULL);
5616
5617   return g_task_propagate_pointer (G_TASK (res), error);
5618 }
5619
5620 static void
5621 enumerate_children_async_thread (GTask         *task,
5622                                  gpointer       object,
5623                                  gpointer       task_data,
5624                                  GCancellable  *cancellable)
5625 {
5626   QueryInfoAsyncData *data = task_data;
5627   GFileEnumerator *enumerator;
5628   GError *error = NULL;
5629
5630   enumerator = g_file_enumerate_children (G_FILE (object), data->attributes, data->flags, cancellable, &error);
5631   if (error)
5632     g_task_return_error (task, error);
5633   else
5634     g_task_return_pointer (task, enumerator, g_object_unref);
5635 }
5636
5637 static void
5638 g_file_real_enumerate_children_async (GFile               *file,
5639                                       const char          *attributes,
5640                                       GFileQueryInfoFlags  flags,
5641                                       int                  io_priority,
5642                                       GCancellable        *cancellable,
5643                                       GAsyncReadyCallback  callback,
5644                                       gpointer             user_data)
5645 {
5646   GTask *task;
5647   QueryInfoAsyncData *data;
5648
5649   data = g_new0 (QueryInfoAsyncData, 1);
5650   data->attributes = g_strdup (attributes);
5651   data->flags = flags;
5652
5653   task = g_task_new (file, cancellable, callback, user_data);
5654   g_task_set_source_tag (task, g_file_real_enumerate_children_async);
5655   g_task_set_task_data (task, data, (GDestroyNotify)query_info_data_free);
5656   g_task_set_priority (task, io_priority);
5657   g_task_run_in_thread (task, enumerate_children_async_thread);
5658   g_object_unref (task);
5659 }
5660
5661 static GFileEnumerator *
5662 g_file_real_enumerate_children_finish (GFile         *file,
5663                                        GAsyncResult  *res,
5664                                        GError       **error)
5665 {
5666   g_return_val_if_fail (g_task_is_valid (res, file), NULL);
5667
5668   return g_task_propagate_pointer (G_TASK (res), error);
5669 }
5670
5671 static void
5672 open_read_async_thread (GTask         *task,
5673                         gpointer       object,
5674                         gpointer       task_data,
5675                         GCancellable  *cancellable)
5676 {
5677   GFileInputStream *stream;
5678   GError *error = NULL;
5679
5680   stream = g_file_read (G_FILE (object), cancellable, &error);
5681   if (stream)
5682     g_task_return_pointer (task, stream, g_object_unref);
5683   else
5684     g_task_return_error (task, error);
5685 }
5686
5687 static void
5688 g_file_real_read_async (GFile               *file,
5689                         int                  io_priority,
5690                         GCancellable        *cancellable,
5691                         GAsyncReadyCallback  callback,
5692                         gpointer             user_data)
5693 {
5694   GTask *task;
5695
5696   task = g_task_new (file, cancellable, callback, user_data);
5697   g_task_set_source_tag (task, g_file_real_read_async);
5698   g_task_set_priority (task, io_priority);
5699   g_task_run_in_thread (task, open_read_async_thread);
5700   g_object_unref (task);
5701 }
5702
5703 static GFileInputStream *
5704 g_file_real_read_finish (GFile         *file,
5705                          GAsyncResult  *res,
5706                          GError       **error)
5707 {
5708   g_return_val_if_fail (g_task_is_valid (res, file), NULL);
5709
5710   return g_task_propagate_pointer (G_TASK (res), error);
5711 }
5712
5713 static void
5714 append_to_async_thread (GTask         *task,
5715                         gpointer       source_object,
5716                         gpointer       task_data,
5717                         GCancellable  *cancellable)
5718 {
5719   GFileCreateFlags *data = task_data;
5720   GFileOutputStream *stream;
5721   GError *error = NULL;
5722
5723   stream = g_file_append_to (G_FILE (source_object), *data, cancellable, &error);
5724   if (stream)
5725     g_task_return_pointer (task, stream, g_object_unref);
5726   else
5727     g_task_return_error (task, error);
5728 }
5729
5730 static void
5731 g_file_real_append_to_async (GFile               *file,
5732                              GFileCreateFlags     flags,
5733                              int                  io_priority,
5734                              GCancellable        *cancellable,
5735                              GAsyncReadyCallback  callback,
5736                              gpointer             user_data)
5737 {
5738   GFileCreateFlags *data;
5739   GTask *task;
5740
5741   data = g_new0 (GFileCreateFlags, 1);
5742   *data = flags;
5743
5744   task = g_task_new (file, cancellable, callback, user_data);
5745   g_task_set_source_tag (task, g_file_real_append_to_async);
5746   g_task_set_task_data (task, data, g_free);
5747   g_task_set_priority (task, io_priority);
5748
5749   g_task_run_in_thread (task, append_to_async_thread);
5750   g_object_unref (task);
5751 }
5752
5753 static GFileOutputStream *
5754 g_file_real_append_to_finish (GFile         *file,
5755                               GAsyncResult  *res,
5756                               GError       **error)
5757 {
5758   g_return_val_if_fail (g_task_is_valid (res, file), NULL);
5759
5760   return g_task_propagate_pointer (G_TASK (res), error);
5761 }
5762
5763 static void
5764 create_async_thread (GTask         *task,
5765                      gpointer       source_object,
5766                      gpointer       task_data,
5767                      GCancellable  *cancellable)
5768 {
5769   GFileCreateFlags *data = task_data;
5770   GFileOutputStream *stream;
5771   GError *error = NULL;
5772
5773   stream = g_file_create (G_FILE (source_object), *data, cancellable, &error);
5774   if (stream)
5775     g_task_return_pointer (task, stream, g_object_unref);
5776   else
5777     g_task_return_error (task, error);
5778 }
5779
5780 static void
5781 g_file_real_create_async (GFile               *file,
5782                           GFileCreateFlags     flags,
5783                           int                  io_priority,
5784                           GCancellable        *cancellable,
5785                           GAsyncReadyCallback  callback,
5786                           gpointer             user_data)
5787 {
5788   GFileCreateFlags *data;
5789   GTask *task;
5790
5791   data = g_new0 (GFileCreateFlags, 1);
5792   *data = flags;
5793
5794   task = g_task_new (file, cancellable, callback, user_data);
5795   g_task_set_source_tag (task, g_file_real_create_async);
5796   g_task_set_task_data (task, data, g_free);
5797   g_task_set_priority (task, io_priority);
5798
5799   g_task_run_in_thread (task, create_async_thread);
5800   g_object_unref (task);
5801 }
5802
5803 static GFileOutputStream *
5804 g_file_real_create_finish (GFile         *file,
5805                            GAsyncResult  *res,
5806                            GError       **error)
5807 {
5808   g_return_val_if_fail (g_task_is_valid (res, file), NULL);
5809
5810   return g_task_propagate_pointer (G_TASK (res), error);
5811 }
5812
5813 typedef struct {
5814   GFileOutputStream *stream;
5815   char *etag;
5816   gboolean make_backup;
5817   GFileCreateFlags flags;
5818 } ReplaceAsyncData;
5819
5820 static void
5821 replace_async_data_free (ReplaceAsyncData *data)
5822 {
5823   if (data->stream)
5824     g_object_unref (data->stream);
5825   g_free (data->etag);
5826   g_free (data);
5827 }
5828
5829 static void
5830 replace_async_thread (GTask         *task,
5831                       gpointer       source_object,
5832                       gpointer       task_data,
5833                       GCancellable  *cancellable)
5834 {
5835   GFileOutputStream *stream;
5836   ReplaceAsyncData *data = task_data;
5837   GError *error = NULL;
5838
5839   stream = g_file_replace (G_FILE (source_object),
5840                            data->etag,
5841                            data->make_backup,
5842                            data->flags,
5843                            cancellable,
5844                            &error);
5845
5846   if (stream)
5847     g_task_return_pointer (task, stream, g_object_unref);
5848   else
5849     g_task_return_error (task, error);
5850 }
5851
5852 static void
5853 g_file_real_replace_async (GFile               *file,
5854                            const char          *etag,
5855                            gboolean             make_backup,
5856                            GFileCreateFlags     flags,
5857                            int                  io_priority,
5858                            GCancellable        *cancellable,
5859                            GAsyncReadyCallback  callback,
5860                            gpointer             user_data)
5861 {
5862   GTask *task;
5863   ReplaceAsyncData *data;
5864
5865   data = g_new0 (ReplaceAsyncData, 1);
5866   data->etag = g_strdup (etag);
5867   data->make_backup = make_backup;
5868   data->flags = flags;
5869
5870   task = g_task_new (file, cancellable, callback, user_data);
5871   g_task_set_source_tag (task, g_file_real_replace_async);
5872   g_task_set_task_data (task, data, (GDestroyNotify)replace_async_data_free);
5873   g_task_set_priority (task, io_priority);
5874
5875   g_task_run_in_thread (task, replace_async_thread);
5876   g_object_unref (task);
5877 }
5878
5879 static GFileOutputStream *
5880 g_file_real_replace_finish (GFile         *file,
5881                             GAsyncResult  *res,
5882                             GError       **error)
5883 {
5884   g_return_val_if_fail (g_task_is_valid (res, file), NULL);
5885
5886   return g_task_propagate_pointer (G_TASK (res), error);
5887 }
5888
5889 static void
5890 delete_async_thread (GTask        *task,
5891                      gpointer      object,
5892                      gpointer      task_data,
5893                      GCancellable *cancellable)
5894 {
5895   GError *error = NULL;
5896
5897   if (g_file_delete (G_FILE (object), cancellable, &error))
5898     g_task_return_boolean (task, TRUE);
5899   else
5900     g_task_return_error (task, error);
5901 }
5902
5903 static void
5904 g_file_real_delete_async (GFile               *file,
5905                           int                  io_priority,
5906                           GCancellable        *cancellable,
5907                           GAsyncReadyCallback  callback,
5908                           gpointer             user_data)
5909 {
5910   GTask *task;
5911
5912   task = g_task_new (file, cancellable, callback, user_data);
5913   g_task_set_source_tag (task, g_file_real_delete_async);
5914   g_task_set_priority (task, io_priority);
5915   g_task_run_in_thread (task, delete_async_thread);
5916   g_object_unref (task);
5917 }
5918
5919 static gboolean
5920 g_file_real_delete_finish (GFile         *file,
5921                            GAsyncResult  *res,
5922                            GError       **error)
5923 {
5924   g_return_val_if_fail (g_task_is_valid (res, file), FALSE);
5925
5926   return g_task_propagate_boolean (G_TASK (res), error);
5927 }
5928
5929 static void
5930 trash_async_thread (GTask        *task,
5931                     gpointer      object,
5932                     gpointer      task_data,
5933                     GCancellable *cancellable)
5934 {
5935   GError *error = NULL;
5936
5937   if (g_file_trash (G_FILE (object), cancellable, &error))
5938     g_task_return_boolean (task, TRUE);
5939   else
5940     g_task_return_error (task, error);
5941 }
5942
5943 static void
5944 g_file_real_trash_async (GFile               *file,
5945                          int                  io_priority,
5946                          GCancellable        *cancellable,
5947                          GAsyncReadyCallback  callback,
5948                          gpointer             user_data)
5949 {
5950   GTask *task;
5951
5952   task = g_task_new (file, cancellable, callback, user_data);
5953   g_task_set_source_tag (task, g_file_real_trash_async);
5954   g_task_set_priority (task, io_priority);
5955   g_task_run_in_thread (task, trash_async_thread);
5956   g_object_unref (task);
5957 }
5958
5959 static gboolean
5960 g_file_real_trash_finish (GFile         *file,
5961                           GAsyncResult  *res,
5962                           GError       **error)
5963 {
5964   g_return_val_if_fail (g_task_is_valid (res, file), FALSE);
5965
5966   return g_task_propagate_boolean (G_TASK (res), error);
5967 }
5968
5969 static void
5970 make_directory_async_thread (GTask        *task,
5971                              gpointer      object,
5972                              gpointer      task_data,
5973                              GCancellable *cancellable)
5974 {
5975   GError *error = NULL;
5976
5977   if (g_file_make_directory (G_FILE (object), cancellable, &error))
5978     g_task_return_boolean (task, TRUE);
5979   else
5980     g_task_return_error (task, error);
5981 }
5982
5983 static void
5984 g_file_real_make_directory_async (GFile               *file,
5985                                   int                  io_priority,
5986                                   GCancellable        *cancellable,
5987                                   GAsyncReadyCallback  callback,
5988                                   gpointer             user_data)
5989 {
5990   GTask *task;
5991
5992   task = g_task_new (file, cancellable, callback, user_data);
5993   g_task_set_source_tag (task, g_file_real_make_directory_async);
5994   g_task_set_priority (task, io_priority);
5995   g_task_run_in_thread (task, make_directory_async_thread);
5996   g_object_unref (task);
5997 }
5998
5999 static gboolean
6000 g_file_real_make_directory_finish (GFile         *file,
6001                                    GAsyncResult  *res,
6002                                    GError       **error)
6003 {
6004   g_return_val_if_fail (g_task_is_valid (res, file), FALSE);
6005
6006   return g_task_propagate_boolean (G_TASK (res), error);
6007 }
6008
6009 static void
6010 open_readwrite_async_thread (GTask        *task,
6011                              gpointer      object,
6012                              gpointer      task_data,
6013                              GCancellable *cancellable)
6014 {
6015   GFileIOStream *stream;
6016   GError *error = NULL;
6017
6018   stream = g_file_open_readwrite (G_FILE (object), cancellable, &error);
6019
6020   if (stream == NULL)
6021     g_task_return_error (task, error);
6022   else
6023     g_task_return_pointer (task, stream, g_object_unref);
6024 }
6025
6026 static void
6027 g_file_real_open_readwrite_async (GFile               *file,
6028                                   int                  io_priority,
6029                                   GCancellable        *cancellable,
6030                                   GAsyncReadyCallback  callback,
6031                                   gpointer             user_data)
6032 {
6033   GTask *task;
6034
6035   task = g_task_new (file, cancellable, callback, user_data);
6036   g_task_set_source_tag (task, g_file_real_open_readwrite_async);
6037   g_task_set_priority (task, io_priority);
6038
6039   g_task_run_in_thread (task, open_readwrite_async_thread);
6040   g_object_unref (task);
6041 }
6042
6043 static GFileIOStream *
6044 g_file_real_open_readwrite_finish (GFile         *file,
6045                                    GAsyncResult  *res,
6046                                    GError       **error)
6047 {
6048   g_return_val_if_fail (g_task_is_valid (res, file), NULL);
6049
6050   return g_task_propagate_pointer (G_TASK (res), error);
6051 }
6052
6053 static void
6054 create_readwrite_async_thread (GTask        *task,
6055                                gpointer      object,
6056                                gpointer      task_data,
6057                                GCancellable *cancellable)
6058 {
6059   GFileCreateFlags *data = task_data;
6060   GFileIOStream *stream;
6061   GError *error = NULL;
6062
6063   stream = g_file_create_readwrite (G_FILE (object), *data, cancellable, &error);
6064
6065   if (stream == NULL)
6066     g_task_return_error (task, error);
6067   else
6068     g_task_return_pointer (task, stream, g_object_unref);
6069 }
6070
6071 static void
6072 g_file_real_create_readwrite_async (GFile               *file,
6073                                     GFileCreateFlags     flags,
6074                                     int                  io_priority,
6075                                     GCancellable        *cancellable,
6076                                     GAsyncReadyCallback  callback,
6077                                     gpointer             user_data)
6078 {
6079   GFileCreateFlags *data;
6080   GTask *task;
6081
6082   data = g_new0 (GFileCreateFlags, 1);
6083   *data = flags;
6084
6085   task = g_task_new (file, cancellable, callback, user_data);
6086   g_task_set_source_tag (task, g_file_real_create_readwrite_async);
6087   g_task_set_task_data (task, data, g_free);
6088   g_task_set_priority (task, io_priority);
6089
6090   g_task_run_in_thread (task, create_readwrite_async_thread);
6091   g_object_unref (task);
6092 }
6093
6094 static GFileIOStream *
6095 g_file_real_create_readwrite_finish (GFile         *file,
6096                                      GAsyncResult  *res,
6097                                      GError       **error)
6098 {
6099   g_return_val_if_fail (g_task_is_valid (res, file), NULL);
6100
6101   return g_task_propagate_pointer (G_TASK (res), error);
6102 }
6103
6104 typedef struct {
6105   char *etag;
6106   gboolean make_backup;
6107   GFileCreateFlags flags;
6108 } ReplaceRWAsyncData;
6109
6110 static void
6111 replace_rw_async_data_free (ReplaceRWAsyncData *data)
6112 {
6113   g_free (data->etag);
6114   g_free (data);
6115 }
6116
6117 static void
6118 replace_readwrite_async_thread (GTask        *task,
6119                                 gpointer      object,
6120                                 gpointer      task_data,
6121                                 GCancellable *cancellable)
6122 {
6123   GFileIOStream *stream;
6124   GError *error = NULL;
6125   ReplaceRWAsyncData *data = task_data;
6126
6127   stream = g_file_replace_readwrite (G_FILE (object),
6128                                      data->etag,
6129                                      data->make_backup,
6130                                      data->flags,
6131                                      cancellable,
6132                                      &error);
6133
6134   if (stream == NULL)
6135     g_task_return_error (task, error);
6136   else
6137     g_task_return_pointer (task, stream, g_object_unref);
6138 }
6139
6140 static void
6141 g_file_real_replace_readwrite_async (GFile               *file,
6142                                      const char          *etag,
6143                                      gboolean             make_backup,
6144                                      GFileCreateFlags     flags,
6145                                      int                  io_priority,
6146                                      GCancellable        *cancellable,
6147                                      GAsyncReadyCallback  callback,
6148                                      gpointer             user_data)
6149 {
6150   GTask *task;
6151   ReplaceRWAsyncData *data;
6152
6153   data = g_new0 (ReplaceRWAsyncData, 1);
6154   data->etag = g_strdup (etag);
6155   data->make_backup = make_backup;
6156   data->flags = flags;
6157
6158   task = g_task_new (file, cancellable, callback, user_data);
6159   g_task_set_source_tag (task, g_file_real_replace_readwrite_async);
6160   g_task_set_task_data (task, data, (GDestroyNotify)replace_rw_async_data_free);
6161   g_task_set_priority (task, io_priority);
6162
6163   g_task_run_in_thread (task, replace_readwrite_async_thread);
6164   g_object_unref (task);
6165 }
6166
6167 static GFileIOStream *
6168 g_file_real_replace_readwrite_finish (GFile         *file,
6169                                       GAsyncResult  *res,
6170                                       GError       **error)
6171 {
6172   g_return_val_if_fail (g_task_is_valid (res, file), NULL);
6173
6174   return g_task_propagate_pointer (G_TASK (res), error);
6175 }
6176
6177 static void
6178 set_display_name_async_thread (GTask        *task,
6179                                gpointer      object,
6180                                gpointer      task_data,
6181                                GCancellable *cancellable)
6182 {
6183   GError *error = NULL;
6184   char *name = task_data;
6185   GFile *file;
6186
6187   file = g_file_set_display_name (G_FILE (object), name, cancellable, &error);
6188
6189   if (file == NULL)
6190     g_task_return_error (task, error);
6191   else
6192     g_task_return_pointer (task, file, g_object_unref);
6193 }
6194
6195 static void
6196 g_file_real_set_display_name_async (GFile               *file,
6197                                     const char          *display_name,
6198                                     int                  io_priority,
6199                                     GCancellable        *cancellable,
6200                                     GAsyncReadyCallback  callback,
6201                                     gpointer             user_data)
6202 {
6203   GTask *task;
6204
6205   task = g_task_new (file, cancellable, callback, user_data);
6206   g_task_set_source_tag (task, g_file_real_set_display_name_async);
6207   g_task_set_task_data (task, g_strdup (display_name), g_free);
6208   g_task_set_priority (task, io_priority);
6209
6210   g_task_run_in_thread (task, set_display_name_async_thread);
6211   g_object_unref (task);
6212 }
6213
6214 static GFile *
6215 g_file_real_set_display_name_finish (GFile         *file,
6216                                      GAsyncResult  *res,
6217                                      GError       **error)
6218 {
6219   g_return_val_if_fail (g_task_is_valid (res, file), NULL);
6220
6221   return g_task_propagate_pointer (G_TASK (res), error);
6222 }
6223
6224 typedef struct {
6225   GFileQueryInfoFlags flags;
6226   GFileInfo *info;
6227   gboolean res;
6228   GError *error;
6229 } SetInfoAsyncData;
6230
6231 static void
6232 set_info_data_free (SetInfoAsyncData *data)
6233 {
6234   if (data->info)
6235     g_object_unref (data->info);
6236   if (data->error)
6237     g_error_free (data->error);
6238   g_free (data);
6239 }
6240
6241 static void
6242 set_info_async_thread (GTask        *task,
6243                        gpointer      object,
6244                        gpointer      task_data,
6245                        GCancellable *cancellable)
6246 {
6247   SetInfoAsyncData *data = task_data;
6248
6249   data->error = NULL;
6250   data->res = g_file_set_attributes_from_info (G_FILE (object),
6251                                                data->info,
6252                                                data->flags,
6253                                                cancellable,
6254                                                &data->error);
6255 }
6256
6257 static void
6258 g_file_real_set_attributes_async (GFile               *file,
6259                                   GFileInfo           *info,
6260                                   GFileQueryInfoFlags  flags,
6261                                   int                  io_priority,
6262                                   GCancellable        *cancellable,
6263                                   GAsyncReadyCallback  callback,
6264                                   gpointer             user_data)
6265 {
6266   GTask *task;
6267   SetInfoAsyncData *data;
6268
6269   data = g_new0 (SetInfoAsyncData, 1);
6270   data->info = g_file_info_dup (info);
6271   data->flags = flags;
6272
6273   task = g_task_new (file, cancellable, callback, user_data);
6274   g_task_set_source_tag (task, g_file_real_set_attributes_async);
6275   g_task_set_task_data (task, data, (GDestroyNotify)set_info_data_free);
6276   g_task_set_priority (task, io_priority);
6277
6278   g_task_run_in_thread (task, set_info_async_thread);
6279   g_object_unref (task);
6280 }
6281
6282 static gboolean
6283 g_file_real_set_attributes_finish (GFile         *file,
6284                                    GAsyncResult  *res,
6285                                    GFileInfo    **info,
6286                                    GError       **error)
6287 {
6288   SetInfoAsyncData *data;
6289
6290   g_return_val_if_fail (g_task_is_valid (res, file), FALSE);
6291
6292   data = g_task_get_task_data (G_TASK (res));
6293
6294   if (info)
6295     *info = g_object_ref (data->info);
6296
6297   if (error != NULL && data->error)
6298     *error = g_error_copy (data->error);
6299
6300   return data->res;
6301 }
6302
6303 static void
6304 find_enclosing_mount_async_thread (GTask        *task,
6305                                    gpointer      object,
6306                                    gpointer      task_data,
6307                                    GCancellable *cancellable)
6308 {
6309   GError *error = NULL;
6310   GMount *mount;
6311
6312   mount = g_file_find_enclosing_mount (G_FILE (object), cancellable, &error);
6313
6314   if (mount == NULL)
6315     g_task_return_error (task, error);
6316   else
6317     g_task_return_pointer (task, mount, g_object_unref);
6318 }
6319
6320 static void
6321 g_file_real_find_enclosing_mount_async (GFile               *file,
6322                                         int                  io_priority,
6323                                         GCancellable        *cancellable,
6324                                         GAsyncReadyCallback  callback,
6325                                         gpointer             user_data)
6326 {
6327   GTask *task;
6328
6329   task = g_task_new (file, cancellable, callback, user_data);
6330   g_task_set_source_tag (task, g_file_real_find_enclosing_mount_async);
6331   g_task_set_priority (task, io_priority);
6332
6333   g_task_run_in_thread (task, find_enclosing_mount_async_thread);
6334   g_object_unref (task);
6335 }
6336
6337 static GMount *
6338 g_file_real_find_enclosing_mount_finish (GFile         *file,
6339                                          GAsyncResult  *res,
6340                                          GError       **error)
6341 {
6342   g_return_val_if_fail (g_task_is_valid (res, file), NULL);
6343
6344   return g_task_propagate_pointer (G_TASK (res), error);
6345 }
6346
6347
6348 typedef struct {
6349   GFile *source;
6350   GFile *destination;
6351   GFileCopyFlags flags;
6352   GFileProgressCallback progress_cb;
6353   gpointer progress_cb_data;
6354 } CopyAsyncData;
6355
6356 static void
6357 copy_async_data_free (CopyAsyncData *data)
6358 {
6359   g_object_unref (data->source);
6360   g_object_unref (data->destination);
6361   g_slice_free (CopyAsyncData, data);
6362 }
6363
6364 typedef struct {
6365   CopyAsyncData *data;
6366   goffset current_num_bytes;
6367   goffset total_num_bytes;
6368 } ProgressData;
6369
6370 static gboolean
6371 copy_async_progress_in_main (gpointer user_data)
6372 {
6373   ProgressData *progress = user_data;
6374   CopyAsyncData *data = progress->data;
6375
6376   data->progress_cb (progress->current_num_bytes,
6377                      progress->total_num_bytes,
6378                      data->progress_cb_data);
6379
6380   return FALSE;
6381 }
6382
6383 static void
6384 copy_async_progress_callback (goffset  current_num_bytes,
6385                               goffset  total_num_bytes,
6386                               gpointer user_data)
6387 {
6388   GTask *task = user_data;
6389   CopyAsyncData *data = g_task_get_task_data (task);
6390   ProgressData *progress;
6391
6392   progress = g_new (ProgressData, 1);
6393   progress->data = data;
6394   progress->current_num_bytes = current_num_bytes;
6395   progress->total_num_bytes = total_num_bytes;
6396
6397   g_main_context_invoke_full (g_task_get_context (task),
6398                               g_task_get_priority (task),
6399                               copy_async_progress_in_main,
6400                               progress,
6401                               g_free);
6402 }
6403
6404 static void
6405 copy_async_thread (GTask        *task,
6406                    gpointer      source,
6407                    gpointer      task_data,
6408                    GCancellable *cancellable)
6409 {
6410   CopyAsyncData *data = task_data;
6411   gboolean result;
6412   GError *error = NULL;
6413
6414   result = g_file_copy (data->source,
6415                         data->destination,
6416                         data->flags,
6417                         cancellable,
6418                         (data->progress_cb != NULL) ? copy_async_progress_callback : NULL,
6419                         task,
6420                         &error);
6421   if (result)
6422     g_task_return_boolean (task, TRUE);
6423   else
6424     g_task_return_error (task, error);
6425 }
6426
6427 static void
6428 g_file_real_copy_async (GFile                  *source,
6429                         GFile                  *destination,
6430                         GFileCopyFlags          flags,
6431                         int                     io_priority,
6432                         GCancellable           *cancellable,
6433                         GFileProgressCallback   progress_callback,
6434                         gpointer                progress_callback_data,
6435                         GAsyncReadyCallback     callback,
6436                         gpointer                user_data)
6437 {
6438   GTask *task;
6439   CopyAsyncData *data;
6440
6441   data = g_slice_new (CopyAsyncData);
6442   data->source = g_object_ref (source);
6443   data->destination = g_object_ref (destination);
6444   data->flags = flags;
6445   data->progress_cb = progress_callback;
6446   data->progress_cb_data = progress_callback_data;
6447
6448   task = g_task_new (source, cancellable, callback, user_data);
6449   g_task_set_source_tag (task, g_file_real_copy_async);
6450   g_task_set_task_data (task, data, (GDestroyNotify)copy_async_data_free);
6451   g_task_set_priority (task, io_priority);
6452   g_task_run_in_thread (task, copy_async_thread);
6453   g_object_unref (task);
6454 }
6455
6456 static gboolean
6457 g_file_real_copy_finish (GFile        *file,
6458                          GAsyncResult *res,
6459                          GError      **error)
6460 {
6461   g_return_val_if_fail (g_task_is_valid (res, file), FALSE);
6462
6463   return g_task_propagate_boolean (G_TASK (res), error);
6464 }
6465
6466
6467 /********************************************
6468  *   Default VFS operations                 *
6469  ********************************************/
6470
6471 /**
6472  * g_file_new_for_path:
6473  * @path: (type filename): a string containing a relative or absolute path.
6474  *     The string must be encoded in the glib filename encoding.
6475  *
6476  * Constructs a #GFile for a given path. This operation never
6477  * fails, but the returned object might not support any I/O
6478  * operation if @path is malformed.
6479  *
6480  * Returns: (transfer full): a new #GFile for the given @path.
6481  *   Free the returned object with g_object_unref().
6482  */
6483 GFile *
6484 g_file_new_for_path (const char *path)
6485 {
6486   g_return_val_if_fail (path != NULL, NULL);
6487
6488   return g_vfs_get_file_for_path (g_vfs_get_default (), path);
6489 }
6490
6491 /**
6492  * g_file_new_for_uri:
6493  * @uri: a UTF-8 string containing a URI
6494  *
6495  * Constructs a #GFile for a given URI. This operation never
6496  * fails, but the returned object might not support any I/O
6497  * operation if @uri is malformed or if the uri type is
6498  * not supported.
6499  *
6500  * Returns: (transfer full): a new #GFile for the given @uri.
6501  *     Free the returned object with g_object_unref().
6502  */
6503 GFile *
6504 g_file_new_for_uri (const char *uri)
6505 {
6506   g_return_val_if_fail (uri != NULL, NULL);
6507
6508   return g_vfs_get_file_for_uri (g_vfs_get_default (), uri);
6509 }
6510
6511 /**
6512  * g_file_new_tmp:
6513  * @tmpl: (type filename) (nullable): Template for the file
6514  *   name, as in g_file_open_tmp(), or %NULL for a default template
6515  * @iostream: (out): on return, a #GFileIOStream for the created file
6516  * @error: a #GError, or %NULL
6517  *
6518  * Opens a file in the preferred directory for temporary files (as
6519  * returned by g_get_tmp_dir()) and returns a #GFile and
6520  * #GFileIOStream pointing to it.
6521  *
6522  * @tmpl should be a string in the GLib file name encoding
6523  * containing a sequence of six 'X' characters, and containing no
6524  * directory components. If it is %NULL, a default template is used.
6525  *
6526  * Unlike the other #GFile constructors, this will return %NULL if
6527  * a temporary file could not be created.
6528  *
6529  * Returns: (transfer full): a new #GFile.
6530  *     Free the returned object with g_object_unref().
6531  *
6532  * Since: 2.32
6533  */
6534 GFile *
6535 g_file_new_tmp (const char     *tmpl,
6536                 GFileIOStream **iostream,
6537                 GError        **error)
6538 {
6539   gint fd;
6540   gchar *path;
6541   GFile *file;
6542   GFileOutputStream *output;
6543
6544   g_return_val_if_fail (iostream != NULL, NULL);
6545
6546   fd = g_file_open_tmp (tmpl, &path, error);
6547   if (fd == -1)
6548     return NULL;
6549
6550   file = g_file_new_for_path (path);
6551
6552   output = _g_local_file_output_stream_new (fd);
6553   *iostream = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
6554
6555   g_object_unref (output);
6556   g_free (path);
6557
6558   return file;
6559 }
6560
6561 /**
6562  * g_file_parse_name:
6563  * @parse_name: a file name or path to be parsed
6564  *
6565  * Constructs a #GFile with the given @parse_name (i.e. something
6566  * given by g_file_get_parse_name()). This operation never fails,
6567  * but the returned object might not support any I/O operation if
6568  * the @parse_name cannot be parsed.
6569  *
6570  * Returns: (transfer full): a new #GFile.
6571  */
6572 GFile *
6573 g_file_parse_name (const char *parse_name)
6574 {
6575   g_return_val_if_fail (parse_name != NULL, NULL);
6576
6577   return g_vfs_parse_name (g_vfs_get_default (), parse_name);
6578 }
6579
6580 /**
6581  * g_file_new_build_filename:
6582  * @first_element: (type filename): the first element in the path
6583  * @...: remaining elements in path, terminated by %NULL
6584  *
6585  * Constructs a #GFile from a series of elements using the correct
6586  * separator for filenames.
6587  *
6588  * Using this function is equivalent to calling g_build_filename(),
6589  * followed by g_file_new_for_path() on the result.
6590  *
6591  * Returns: (transfer full): a new #GFile
6592  *
6593  * Since: 2.56
6594  */
6595 GFile *
6596 g_file_new_build_filename (const gchar *first_element,
6597                            ...)
6598 {
6599   gchar *str;
6600   GFile *file;
6601   va_list args;
6602
6603   g_return_val_if_fail (first_element != NULL, NULL);
6604
6605   va_start (args, first_element);
6606   str = g_build_filename_valist (first_element, &args);
6607   va_end (args);
6608
6609   file = g_file_new_for_path (str);
6610   g_free (str);
6611
6612   return file;
6613 }
6614
6615 static gboolean
6616 is_valid_scheme_character (char c)
6617 {
6618   return g_ascii_isalnum (c) || c == '+' || c == '-' || c == '.';
6619 }
6620
6621 /* Following RFC 2396, valid schemes are built like:
6622  *       scheme        = alpha *( alpha | digit | "+" | "-" | "." )
6623  */
6624 static gboolean
6625 has_valid_scheme (const char *uri)
6626 {
6627   const char *p;
6628
6629   p = uri;
6630
6631   if (!g_ascii_isalpha (*p))
6632     return FALSE;
6633
6634   do {
6635     p++;
6636   } while (is_valid_scheme_character (*p));
6637
6638   return *p == ':';
6639 }
6640
6641 static GFile *
6642 new_for_cmdline_arg (const gchar *arg,
6643                      const gchar *cwd)
6644 {
6645   GFile *file;
6646   char *filename;
6647
6648   if (g_path_is_absolute (arg))
6649     return g_file_new_for_path (arg);
6650
6651   if (has_valid_scheme (arg))
6652     return g_file_new_for_uri (arg);
6653
6654   if (cwd == NULL)
6655     {
6656       char *current_dir;
6657
6658       current_dir = g_get_current_dir ();
6659       filename = g_build_filename (current_dir, arg, NULL);
6660       g_free (current_dir);
6661     }
6662   else
6663     filename = g_build_filename (cwd, arg, NULL);
6664
6665   file = g_file_new_for_path (filename);
6666   g_free (filename);
6667
6668   return file;
6669 }
6670
6671 /**
6672  * g_file_new_for_commandline_arg:
6673  * @arg: (type filename): a command line string
6674  *
6675  * Creates a #GFile with the given argument from the command line.
6676  * The value of @arg can be either a URI, an absolute path or a
6677  * relative path resolved relative to the current working directory.
6678  * This operation never fails, but the returned object might not
6679  * support any I/O operation if @arg points to a malformed path.
6680  *
6681  * Note that on Windows, this function expects its argument to be in
6682  * UTF-8 -- not the system code page.  This means that you
6683  * should not use this function with string from argv as it is passed
6684  * to main().  g_win32_get_command_line() will return a UTF-8 version of
6685  * the commandline.  #GApplication also uses UTF-8 but
6686  * g_application_command_line_create_file_for_arg() may be more useful
6687  * for you there.  It is also always possible to use this function with
6688  * #GOptionContext arguments of type %G_OPTION_ARG_FILENAME.
6689  *
6690  * Returns: (transfer full): a new #GFile.
6691  *    Free the returned object with g_object_unref().
6692  */
6693 GFile *
6694 g_file_new_for_commandline_arg (const char *arg)
6695 {
6696   g_return_val_if_fail (arg != NULL, NULL);
6697
6698   return new_for_cmdline_arg (arg, NULL);
6699 }
6700
6701 /**
6702  * g_file_new_for_commandline_arg_and_cwd:
6703  * @arg: (type filename): a command line string
6704  * @cwd: (type filename): the current working directory of the commandline
6705  *
6706  * Creates a #GFile with the given argument from the command line.
6707  *
6708  * This function is similar to g_file_new_for_commandline_arg() except
6709  * that it allows for passing the current working directory as an
6710  * argument instead of using the current working directory of the
6711  * process.
6712  *
6713  * This is useful if the commandline argument was given in a context
6714  * other than the invocation of the current process.
6715  *
6716  * See also g_application_command_line_create_file_for_arg().
6717  *
6718  * Returns: (transfer full): a new #GFile
6719  *
6720  * Since: 2.36
6721  **/
6722 GFile *
6723 g_file_new_for_commandline_arg_and_cwd (const gchar *arg,
6724                                         const gchar *cwd)
6725 {
6726   g_return_val_if_fail (arg != NULL, NULL);
6727   g_return_val_if_fail (cwd != NULL, NULL);
6728
6729   return new_for_cmdline_arg (arg, cwd);
6730 }
6731
6732 /**
6733  * g_file_mount_enclosing_volume:
6734  * @location: input #GFile
6735  * @flags: flags affecting the operation
6736  * @mount_operation: (nullable): a #GMountOperation
6737  *     or %NULL to avoid user interaction
6738  * @cancellable: (nullable): optional #GCancellable object,
6739  *     %NULL to ignore
6740  * @callback: (nullable): a #GAsyncReadyCallback to call
6741  *     when the request is satisfied, or %NULL
6742  * @user_data: the data to pass to callback function
6743  *
6744  * Starts a @mount_operation, mounting the volume that contains
6745  * the file @location.
6746  *
6747  * When this operation has completed, @callback will be called with
6748  * @user_user data, and the operation can be finalized with
6749  * g_file_mount_enclosing_volume_finish().
6750  *
6751  * If @cancellable is not %NULL, then the operation can be cancelled by
6752  * triggering the cancellable object from another thread. If the operation
6753  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
6754  */
6755 void
6756 g_file_mount_enclosing_volume (GFile               *location,
6757                                GMountMountFlags     flags,
6758                                GMountOperation     *mount_operation,
6759                                GCancellable        *cancellable,
6760                                GAsyncReadyCallback  callback,
6761                                gpointer             user_data)
6762 {
6763   GFileIface *iface;
6764
6765   g_return_if_fail (G_IS_FILE (location));
6766
6767   iface = G_FILE_GET_IFACE (location);
6768
6769   if (iface->mount_enclosing_volume == NULL)
6770     {
6771       g_task_report_new_error (location, callback, user_data,
6772                                g_file_mount_enclosing_volume,
6773                                G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
6774                                _("volume doesn’t implement mount"));
6775       return;
6776     }
6777
6778   (* iface->mount_enclosing_volume) (location, flags, mount_operation, cancellable, callback, user_data);
6779
6780 }
6781
6782 /**
6783  * g_file_mount_enclosing_volume_finish:
6784  * @location: input #GFile
6785  * @result: a #GAsyncResult
6786  * @error: a #GError, or %NULL
6787  *
6788  * Finishes a mount operation started by g_file_mount_enclosing_volume().
6789  *
6790  * Returns: %TRUE if successful. If an error has occurred,
6791  *     this function will return %FALSE and set @error
6792  *     appropriately if present.
6793  */
6794 gboolean
6795 g_file_mount_enclosing_volume_finish (GFile         *location,
6796                                       GAsyncResult  *result,
6797                                       GError       **error)
6798 {
6799   GFileIface *iface;
6800
6801   g_return_val_if_fail (G_IS_FILE (location), FALSE);
6802   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
6803
6804   if (g_async_result_legacy_propagate_error (result, error))
6805     return FALSE;
6806   else if (g_async_result_is_tagged (result, g_file_mount_enclosing_volume))
6807     return g_task_propagate_boolean (G_TASK (result), error);
6808
6809   iface = G_FILE_GET_IFACE (location);
6810
6811   return (* iface->mount_enclosing_volume_finish) (location, result, error);
6812 }
6813
6814 /********************************************
6815  *   Utility functions                      *
6816  ********************************************/
6817
6818 /**
6819  * g_file_query_default_handler:
6820  * @file: a #GFile to open
6821  * @cancellable: optional #GCancellable object, %NULL to ignore
6822  * @error: a #GError, or %NULL
6823  *
6824  * Returns the #GAppInfo that is registered as the default
6825  * application to handle the file specified by @file.
6826  *
6827  * If @cancellable is not %NULL, then the operation can be cancelled by
6828  * triggering the cancellable object from another thread. If the operation
6829  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
6830  *
6831  * Returns: (transfer full): a #GAppInfo if the handle was found,
6832  *     %NULL if there were errors.
6833  *     When you are done with it, release it with g_object_unref()
6834  */
6835 GAppInfo *
6836 g_file_query_default_handler (GFile         *file,
6837                               GCancellable  *cancellable,
6838                               GError       **error)
6839 {
6840   char *uri_scheme;
6841   const char *content_type;
6842   GAppInfo *appinfo;
6843   GFileInfo *info;
6844   char *path;
6845
6846   uri_scheme = g_file_get_uri_scheme (file);
6847   if (uri_scheme && uri_scheme[0] != '\0')
6848     {
6849       appinfo = g_app_info_get_default_for_uri_scheme (uri_scheme);
6850       g_free (uri_scheme);
6851
6852       if (appinfo != NULL)
6853         return appinfo;
6854     }
6855   else
6856     g_free (uri_scheme);
6857
6858   info = g_file_query_info (file,
6859                             G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
6860                             0,
6861                             cancellable,
6862                             error);
6863   if (info == NULL)
6864     return NULL;
6865
6866   appinfo = NULL;
6867
6868   content_type = g_file_info_get_content_type (info);
6869   if (content_type)
6870     {
6871       /* Don't use is_native(), as we want to support fuse paths if available */
6872       path = g_file_get_path (file);
6873       appinfo = g_app_info_get_default_for_type (content_type,
6874                                                  path == NULL);
6875       g_free (path);
6876     }
6877
6878   g_object_unref (info);
6879
6880   if (appinfo != NULL)
6881     return appinfo;
6882
6883   g_set_error_literal (error, G_IO_ERROR,
6884                        G_IO_ERROR_NOT_SUPPORTED,
6885                        _("No application is registered as handling this file"));
6886   return NULL;
6887 }
6888
6889 static void
6890 query_default_handler_query_info_cb (GObject      *object,
6891                                      GAsyncResult *result,
6892                                      gpointer      user_data)
6893 {
6894   GFile *file = G_FILE (object);
6895   GTask *task = G_TASK (user_data);
6896   GError *error = NULL;
6897   GFileInfo *info;
6898   const char *content_type;
6899   GAppInfo *appinfo = NULL;
6900
6901   info = g_file_query_info_finish (file, result, &error);
6902   if (info == NULL)
6903     {
6904       g_task_return_error (task, g_steal_pointer (&error));
6905       g_object_unref (task);
6906       return;
6907     }
6908
6909   content_type = g_file_info_get_content_type (info);
6910   if (content_type)
6911     {
6912       char *path;
6913
6914       /* Don't use is_native(), as we want to support fuse paths if available */
6915       path = g_file_get_path (file);
6916
6917       /* FIXME: The following still uses blocking calls. */
6918       appinfo = g_app_info_get_default_for_type (content_type,
6919                                                  path == NULL);
6920       g_free (path);
6921     }
6922
6923   g_object_unref (info);
6924
6925   if (appinfo != NULL)
6926     g_task_return_pointer (task, g_steal_pointer (&appinfo), g_object_unref);
6927   else
6928     g_task_return_new_error (task,
6929                              G_IO_ERROR,
6930                              G_IO_ERROR_NOT_SUPPORTED,
6931                              _("No application is registered as handling this file"));
6932   g_object_unref (task);
6933 }
6934
6935 /**
6936  * g_file_query_default_handler_async:
6937  * @file: a #GFile to open
6938  * @cancellable: optional #GCancellable object, %NULL to ignore
6939  * @callback: (nullable): a #GAsyncReadyCallback to call when the request is done
6940  * @user_data: (nullable): data to pass to @callback
6941  *
6942  * Async version of g_file_query_default_handler().
6943  *
6944  * Since: 2.60
6945  */
6946 void
6947 g_file_query_default_handler_async (GFile              *file,
6948                                     int                 io_priority,
6949                                     GCancellable       *cancellable,
6950                                     GAsyncReadyCallback callback,
6951                                     gpointer            user_data)
6952 {
6953   GTask *task;
6954   char *uri_scheme;
6955
6956   task = g_task_new (file, cancellable, callback, user_data);
6957   g_task_set_source_tag (task, g_file_query_default_handler_async);
6958
6959   uri_scheme = g_file_get_uri_scheme (file);
6960   if (uri_scheme && uri_scheme[0] != '\0')
6961     {
6962       GAppInfo *appinfo;
6963
6964       /* FIXME: The following still uses blocking calls. */
6965       appinfo = g_app_info_get_default_for_uri_scheme (uri_scheme);
6966       g_free (uri_scheme);
6967
6968       if (appinfo != NULL)
6969         {
6970           g_task_return_pointer (task, g_steal_pointer (&appinfo), g_object_unref);
6971           g_object_unref (task);
6972           return;
6973         }
6974     }
6975   else
6976     g_free (uri_scheme);
6977
6978   g_file_query_info_async (file,
6979                            G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
6980                            0,
6981                            io_priority,
6982                            cancellable,
6983                            query_default_handler_query_info_cb,
6984                            g_steal_pointer (&task));
6985 }
6986
6987 /**
6988  * g_file_query_default_handler_finish:
6989  * @file: a #GFile to open
6990  * @result: a #GAsyncResult
6991  * @error: (nullable): a #GError
6992  *
6993  * Finishes a g_file_query_default_handler_async() operation.
6994  *
6995  * Returns: (transfer full): a #GAppInfo if the handle was found,
6996  *     %NULL if there were errors.
6997  *     When you are done with it, release it with g_object_unref()
6998  *
6999  * Since: 2.60
7000  */
7001 GAppInfo *
7002 g_file_query_default_handler_finish (GFile        *file,
7003                                      GAsyncResult *result,
7004                                      GError      **error)
7005 {
7006   g_return_val_if_fail (G_IS_FILE (file), NULL);
7007   g_return_val_if_fail (g_task_is_valid (result, file), NULL);
7008
7009   return g_task_propagate_pointer (G_TASK (result), error);
7010 }
7011
7012 #define GET_CONTENT_BLOCK_SIZE 8192
7013
7014 /**
7015  * g_file_load_contents:
7016  * @file: input #GFile
7017  * @cancellable: optional #GCancellable object, %NULL to ignore
7018  * @contents: (out) (transfer full) (element-type guint8) (array length=length): a location to place the contents of the file
7019  * @length: (out) (optional): a location to place the length of the contents of the file,
7020  *    or %NULL if the length is not needed
7021  * @etag_out: (out) (optional): a location to place the current entity tag for the file,
7022  *    or %NULL if the entity tag is not needed
7023  * @error: a #GError, or %NULL
7024  *
7025  * Loads the content of the file into memory. The data is always
7026  * zero-terminated, but this is not included in the resultant @length.
7027  * The returned @content should be freed with g_free() when no longer
7028  * needed.
7029  *
7030  * If @cancellable is not %NULL, then the operation can be cancelled by
7031  * triggering the cancellable object from another thread. If the operation
7032  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
7033  *
7034  * Returns: %TRUE if the @file's contents were successfully loaded.
7035  *     %FALSE if there were errors.
7036  */
7037 gboolean
7038 g_file_load_contents (GFile         *file,
7039                       GCancellable  *cancellable,
7040                       char         **contents,
7041                       gsize         *length,
7042                       char         **etag_out,
7043                       GError       **error)
7044 {
7045   GFileInputStream *in;
7046   GByteArray *content;
7047   gsize pos;
7048   gssize res;
7049   GFileInfo *info;
7050
7051   g_return_val_if_fail (G_IS_FILE (file), FALSE);
7052   g_return_val_if_fail (contents != NULL, FALSE);
7053
7054   in = g_file_read (file, cancellable, error);
7055   if (in == NULL)
7056     return FALSE;
7057
7058   content = g_byte_array_new ();
7059   pos = 0;
7060
7061   g_byte_array_set_size (content, pos + GET_CONTENT_BLOCK_SIZE + 1);
7062   while ((res = g_input_stream_read (G_INPUT_STREAM (in),
7063                                      content->data + pos,
7064                                      GET_CONTENT_BLOCK_SIZE,
7065                                      cancellable, error)) > 0)
7066     {
7067       pos += res;
7068       g_byte_array_set_size (content, pos + GET_CONTENT_BLOCK_SIZE + 1);
7069     }
7070
7071   if (etag_out)
7072     {
7073       *etag_out = NULL;
7074
7075       info = g_file_input_stream_query_info (in,
7076                                              G_FILE_ATTRIBUTE_ETAG_VALUE,
7077                                              cancellable,
7078                                              NULL);
7079       if (info)
7080         {
7081           *etag_out = g_strdup (g_file_info_get_etag (info));
7082           g_object_unref (info);
7083         }
7084     }
7085
7086   /* Ignore errors on close */
7087   g_input_stream_close (G_INPUT_STREAM (in), cancellable, NULL);
7088   g_object_unref (in);
7089
7090   if (res < 0)
7091     {
7092       /* error is set already */
7093       g_byte_array_free (content, TRUE);
7094       return FALSE;
7095     }
7096
7097   if (length)
7098     *length = pos;
7099
7100   /* Zero terminate (we got an extra byte allocated for this */
7101   content->data[pos] = 0;
7102
7103   *contents = (char *)g_byte_array_free (content, FALSE);
7104
7105   return TRUE;
7106 }
7107
7108 typedef struct {
7109   GTask *task;
7110   GFileReadMoreCallback read_more_callback;
7111   GByteArray *content;
7112   gsize pos;
7113   char *etag;
7114 } LoadContentsData;
7115
7116
7117 static void
7118 load_contents_data_free (LoadContentsData *data)
7119 {
7120   if (data->content)
7121     g_byte_array_free (data->content, TRUE);
7122   g_free (data->etag);
7123   g_free (data);
7124 }
7125
7126 static void
7127 load_contents_close_callback (GObject      *obj,
7128                               GAsyncResult *close_res,
7129                               gpointer      user_data)
7130 {
7131   GInputStream *stream = G_INPUT_STREAM (obj);
7132   LoadContentsData *data = user_data;
7133
7134   /* Ignore errors here, we're only reading anyway */
7135   g_input_stream_close_finish (stream, close_res, NULL);
7136   g_object_unref (stream);
7137
7138   g_task_return_boolean (data->task, TRUE);
7139   g_object_unref (data->task);
7140 }
7141
7142 static void
7143 load_contents_fstat_callback (GObject      *obj,
7144                               GAsyncResult *stat_res,
7145                               gpointer      user_data)
7146 {
7147   GInputStream *stream = G_INPUT_STREAM (obj);
7148   LoadContentsData *data = user_data;
7149   GFileInfo *info;
7150
7151   info = g_file_input_stream_query_info_finish (G_FILE_INPUT_STREAM (stream),
7152                                                 stat_res, NULL);
7153   if (info)
7154     {
7155       data->etag = g_strdup (g_file_info_get_etag (info));
7156       g_object_unref (info);
7157     }
7158
7159   g_input_stream_close_async (stream, 0,
7160                               g_task_get_cancellable (data->task),
7161                               load_contents_close_callback, data);
7162 }
7163
7164 static void
7165 load_contents_read_callback (GObject      *obj,
7166                              GAsyncResult *read_res,
7167                              gpointer      user_data)
7168 {
7169   GInputStream *stream = G_INPUT_STREAM (obj);
7170   LoadContentsData *data = user_data;
7171   GError *error = NULL;
7172   gssize read_size;
7173
7174   read_size = g_input_stream_read_finish (stream, read_res, &error);
7175
7176   if (read_size < 0)
7177     {
7178       g_task_return_error (data->task, error);
7179       g_object_unref (data->task);
7180
7181       /* Close the file ignoring any error */
7182       g_input_stream_close_async (stream, 0, NULL, NULL, NULL);
7183       g_object_unref (stream);
7184     }
7185   else if (read_size == 0)
7186     {
7187       g_file_input_stream_query_info_async (G_FILE_INPUT_STREAM (stream),
7188                                             G_FILE_ATTRIBUTE_ETAG_VALUE,
7189                                             0,
7190                                             g_task_get_cancellable (data->task),
7191                                             load_contents_fstat_callback,
7192                                             data);
7193     }
7194   else if (read_size > 0)
7195     {
7196       data->pos += read_size;
7197
7198       g_byte_array_set_size (data->content,
7199                              data->pos + GET_CONTENT_BLOCK_SIZE);
7200
7201
7202       if (data->read_more_callback &&
7203           !data->read_more_callback ((char *)data->content->data, data->pos,
7204                                      g_async_result_get_user_data (G_ASYNC_RESULT (data->task))))
7205         g_file_input_stream_query_info_async (G_FILE_INPUT_STREAM (stream),
7206                                               G_FILE_ATTRIBUTE_ETAG_VALUE,
7207                                               0,
7208                                               g_task_get_cancellable (data->task),
7209                                               load_contents_fstat_callback,
7210                                               data);
7211       else
7212         g_input_stream_read_async (stream,
7213                                    data->content->data + data->pos,
7214                                    GET_CONTENT_BLOCK_SIZE,
7215                                    0,
7216                                    g_task_get_cancellable (data->task),
7217                                    load_contents_read_callback,
7218                                    data);
7219     }
7220 }
7221
7222 static void
7223 load_contents_open_callback (GObject      *obj,
7224                              GAsyncResult *open_res,
7225                              gpointer      user_data)
7226 {
7227   GFile *file = G_FILE (obj);
7228   GFileInputStream *stream;
7229   LoadContentsData *data = user_data;
7230   GError *error = NULL;
7231
7232   stream = g_file_read_finish (file, open_res, &error);
7233
7234   if (stream)
7235     {
7236       g_byte_array_set_size (data->content,
7237                              data->pos + GET_CONTENT_BLOCK_SIZE);
7238       g_input_stream_read_async (G_INPUT_STREAM (stream),
7239                                  data->content->data + data->pos,
7240                                  GET_CONTENT_BLOCK_SIZE,
7241                                  0,
7242                                  g_task_get_cancellable (data->task),
7243                                  load_contents_read_callback,
7244                                  data);
7245     }
7246   else
7247     {
7248       g_task_return_error (data->task, error);
7249       g_object_unref (data->task);
7250     }
7251 }
7252
7253 /**
7254  * g_file_load_partial_contents_async: (skip)
7255  * @file: input #GFile
7256  * @cancellable: optional #GCancellable object, %NULL to ignore
7257  * @read_more_callback: (scope call) (closure user_data): a
7258  *     #GFileReadMoreCallback to receive partial data
7259  *     and to specify whether further data should be read
7260  * @callback: (scope async) (closure user_data): a #GAsyncReadyCallback to call
7261  *     when the request is satisfied
7262  * @user_data: the data to pass to the callback functions
7263  *
7264  * Reads the partial contents of a file. A #GFileReadMoreCallback should
7265  * be used to stop reading from the file when appropriate, else this
7266  * function will behave exactly as g_file_load_contents_async(). This
7267  * operation can be finished by g_file_load_partial_contents_finish().
7268  *
7269  * Users of this function should be aware that @user_data is passed to
7270  * both the @read_more_callback and the @callback.
7271  *
7272  * If @cancellable is not %NULL, then the operation can be cancelled by
7273  * triggering the cancellable object from another thread. If the operation
7274  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
7275  */
7276 void
7277 g_file_load_partial_contents_async (GFile                 *file,
7278                                     GCancellable          *cancellable,
7279                                     GFileReadMoreCallback  read_more_callback,
7280                                     GAsyncReadyCallback    callback,
7281                                     gpointer               user_data)
7282 {
7283   LoadContentsData *data;
7284
7285   g_return_if_fail (G_IS_FILE (file));
7286
7287   data = g_new0 (LoadContentsData, 1);
7288   data->read_more_callback = read_more_callback;
7289   data->content = g_byte_array_new ();
7290
7291   data->task = g_task_new (file, cancellable, callback, user_data);
7292   g_task_set_source_tag (data->task, g_file_load_partial_contents_async);
7293   g_task_set_task_data (data->task, data, (GDestroyNotify)load_contents_data_free);
7294
7295   g_file_read_async (file,
7296                      0,
7297                      g_task_get_cancellable (data->task),
7298                      load_contents_open_callback,
7299                      data);
7300 }
7301
7302 /**
7303  * g_file_load_partial_contents_finish:
7304  * @file: input #GFile
7305  * @res: a #GAsyncResult
7306  * @contents: (out) (transfer full) (element-type guint8) (array length=length): a location to place the contents of the file
7307  * @length: (out) (optional): a location to place the length of the contents of the file,
7308  *     or %NULL if the length is not needed
7309  * @etag_out: (out) (optional): a location to place the current entity tag for the file,
7310  *     or %NULL if the entity tag is not needed
7311  * @error: a #GError, or %NULL
7312  *
7313  * Finishes an asynchronous partial load operation that was started
7314  * with g_file_load_partial_contents_async(). The data is always
7315  * zero-terminated, but this is not included in the resultant @length.
7316  * The returned @content should be freed with g_free() when no longer
7317  * needed.
7318  *
7319  * Returns: %TRUE if the load was successful. If %FALSE and @error is
7320  *     present, it will be set appropriately.
7321  */
7322 gboolean
7323 g_file_load_partial_contents_finish (GFile         *file,
7324                                      GAsyncResult  *res,
7325                                      char         **contents,
7326                                      gsize         *length,
7327                                      char         **etag_out,
7328                                      GError       **error)
7329 {
7330   GTask *task;
7331   LoadContentsData *data;
7332
7333   g_return_val_if_fail (G_IS_FILE (file), FALSE);
7334   g_return_val_if_fail (g_task_is_valid (res, file), FALSE);
7335   g_return_val_if_fail (contents != NULL, FALSE);
7336
7337   task = G_TASK (res);
7338
7339   if (!g_task_propagate_boolean (task, error))
7340     {
7341       if (length)
7342         *length = 0;
7343       return FALSE;
7344     }
7345
7346   data = g_task_get_task_data (task);
7347
7348   if (length)
7349     *length = data->pos;
7350
7351   if (etag_out)
7352     {
7353       *etag_out = data->etag;
7354       data->etag = NULL;
7355     }
7356
7357   /* Zero terminate */
7358   g_byte_array_set_size (data->content, data->pos + 1);
7359   data->content->data[data->pos] = 0;
7360
7361   *contents = (char *)g_byte_array_free (data->content, FALSE);
7362   data->content = NULL;
7363
7364   return TRUE;
7365 }
7366
7367 /**
7368  * g_file_load_contents_async:
7369  * @file: input #GFile
7370  * @cancellable: optional #GCancellable object, %NULL to ignore
7371  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7372  * @user_data: the data to pass to callback function
7373  *
7374  * Starts an asynchronous load of the @file's contents.
7375  *
7376  * For more details, see g_file_load_contents() which is
7377  * the synchronous version of this call.
7378  *
7379  * When the load operation has completed, @callback will be called
7380  * with @user data. To finish the operation, call
7381  * g_file_load_contents_finish() with the #GAsyncResult returned by
7382  * the @callback.
7383  *
7384  * If @cancellable is not %NULL, then the operation can be cancelled by
7385  * triggering the cancellable object from another thread. If the operation
7386  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
7387  */
7388 void
7389 g_file_load_contents_async (GFile               *file,
7390                            GCancellable        *cancellable,
7391                            GAsyncReadyCallback  callback,
7392                            gpointer             user_data)
7393 {
7394   g_file_load_partial_contents_async (file,
7395                                       cancellable,
7396                                       NULL,
7397                                       callback, user_data);
7398 }
7399
7400 /**
7401  * g_file_load_contents_finish:
7402  * @file: input #GFile
7403  * @res: a #GAsyncResult
7404  * @contents: (out) (transfer full) (element-type guint8) (array length=length): a location to place the contents of the file
7405  * @length: (out) (optional): a location to place the length of the contents of the file,
7406  *     or %NULL if the length is not needed
7407  * @etag_out: (out) (optional): a location to place the current entity tag for the file,
7408  *     or %NULL if the entity tag is not needed
7409  * @error: a #GError, or %NULL
7410  *
7411  * Finishes an asynchronous load of the @file's contents.
7412  * The contents are placed in @contents, and @length is set to the
7413  * size of the @contents string. The @content should be freed with
7414  * g_free() when no longer needed. If @etag_out is present, it will be
7415  * set to the new entity tag for the @file.
7416  *
7417  * Returns: %TRUE if the load was successful. If %FALSE and @error is
7418  *     present, it will be set appropriately.
7419  */
7420 gboolean
7421 g_file_load_contents_finish (GFile         *file,
7422                              GAsyncResult  *res,
7423                              char         **contents,
7424                              gsize         *length,
7425                              char         **etag_out,
7426                              GError       **error)
7427 {
7428   return g_file_load_partial_contents_finish (file,
7429                                               res,
7430                                               contents,
7431                                               length,
7432                                               etag_out,
7433                                               error);
7434 }
7435
7436 /**
7437  * g_file_replace_contents:
7438  * @file: input #GFile
7439  * @contents: (element-type guint8) (array length=length): a string containing the new contents for @file
7440  * @length: the length of @contents in bytes
7441  * @etag: (nullable): the old [entity-tag][gfile-etag] for the document,
7442  *     or %NULL
7443  * @make_backup: %TRUE if a backup should be created
7444  * @flags: a set of #GFileCreateFlags
7445  * @new_etag: (out) (optional): a location to a new [entity tag][gfile-etag]
7446  *      for the document. This should be freed with g_free() when no longer
7447  *      needed, or %NULL
7448  * @cancellable: optional #GCancellable object, %NULL to ignore
7449  * @error: a #GError, or %NULL
7450  *
7451  * Replaces the contents of @file with @contents of @length bytes.
7452  *
7453  * If @etag is specified (not %NULL), any existing file must have that etag,
7454  * or the error %G_IO_ERROR_WRONG_ETAG will be returned.
7455  *
7456  * If @make_backup is %TRUE, this function will attempt to make a backup
7457  * of @file. Internally, it uses g_file_replace(), so will try to replace the
7458  * file contents in the safest way possible. For example, atomic renames are
7459  * used when replacing local files’ contents.
7460  *
7461  * If @cancellable is not %NULL, then the operation can be cancelled by
7462  * triggering the cancellable object from another thread. If the operation
7463  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
7464  *
7465  * The returned @new_etag can be used to verify that the file hasn't
7466  * changed the next time it is saved over.
7467  *
7468  * Returns: %TRUE if successful. If an error has occurred, this function
7469  *     will return %FALSE and set @error appropriately if present.
7470  */
7471 gboolean
7472 g_file_replace_contents (GFile             *file,
7473                          const char        *contents,
7474                          gsize              length,
7475                          const char        *etag,
7476                          gboolean           make_backup,
7477                          GFileCreateFlags   flags,
7478                          char             **new_etag,
7479                          GCancellable      *cancellable,
7480                          GError           **error)
7481 {
7482   GFileOutputStream *out;
7483   gsize pos, remainder;
7484   gssize res;
7485   gboolean ret;
7486
7487   g_return_val_if_fail (G_IS_FILE (file), FALSE);
7488   g_return_val_if_fail (contents != NULL, FALSE);
7489
7490   out = g_file_replace (file, etag, make_backup, flags, cancellable, error);
7491   if (out == NULL)
7492     return FALSE;
7493
7494   pos = 0;
7495   remainder = length;
7496   while (remainder > 0 &&
7497          (res = g_output_stream_write (G_OUTPUT_STREAM (out),
7498                                        contents + pos,
7499                                        MIN (remainder, GET_CONTENT_BLOCK_SIZE),
7500                                        cancellable,
7501                                        error)) > 0)
7502     {
7503       pos += res;
7504       remainder -= res;
7505     }
7506
7507   if (remainder > 0 && res < 0)
7508     {
7509       /* Ignore errors on close */
7510       g_output_stream_close (G_OUTPUT_STREAM (out), cancellable, NULL);
7511       g_object_unref (out);
7512
7513       /* error is set already */
7514       return FALSE;
7515     }
7516
7517   ret = g_output_stream_close (G_OUTPUT_STREAM (out), cancellable, error);
7518
7519   if (new_etag)
7520     *new_etag = g_file_output_stream_get_etag (out);
7521
7522   g_object_unref (out);
7523
7524   return ret;
7525 }
7526
7527 typedef struct {
7528   GTask *task;
7529   GBytes *content;
7530   gsize pos;
7531   char *etag;
7532   gboolean failed;
7533 } ReplaceContentsData;
7534
7535 static void
7536 replace_contents_data_free (ReplaceContentsData *data)
7537 {
7538   g_bytes_unref (data->content);
7539   g_free (data->etag);
7540   g_free (data);
7541 }
7542
7543 static void
7544 replace_contents_close_callback (GObject      *obj,
7545                                  GAsyncResult *close_res,
7546                                  gpointer      user_data)
7547 {
7548   GOutputStream *stream = G_OUTPUT_STREAM (obj);
7549   ReplaceContentsData *data = user_data;
7550
7551   /* Ignore errors here, we're only reading anyway */
7552   g_output_stream_close_finish (stream, close_res, NULL);
7553   g_object_unref (stream);
7554
7555   if (!data->failed)
7556     {
7557       data->etag = g_file_output_stream_get_etag (G_FILE_OUTPUT_STREAM (stream));
7558       g_task_return_boolean (data->task, TRUE);
7559     }
7560   g_object_unref (data->task);
7561 }
7562
7563 static void
7564 replace_contents_write_callback (GObject      *obj,
7565                                  GAsyncResult *read_res,
7566                                  gpointer      user_data)
7567 {
7568   GOutputStream *stream = G_OUTPUT_STREAM (obj);
7569   ReplaceContentsData *data = user_data;
7570   GError *error = NULL;
7571   gssize write_size;
7572
7573   write_size = g_output_stream_write_finish (stream, read_res, &error);
7574
7575   if (write_size <= 0)
7576     {
7577       /* Error or EOF, close the file */
7578       if (write_size < 0)
7579         {
7580           data->failed = TRUE;
7581           g_task_return_error (data->task, error);
7582         }
7583       g_output_stream_close_async (stream, 0,
7584                                    g_task_get_cancellable (data->task),
7585                                    replace_contents_close_callback, data);
7586     }
7587   else if (write_size > 0)
7588     {
7589       const gchar *content;
7590       gsize length;
7591
7592       content = g_bytes_get_data (data->content, &length);
7593       data->pos += write_size;
7594
7595       if (data->pos >= length)
7596         g_output_stream_close_async (stream, 0,
7597                                      g_task_get_cancellable (data->task),
7598                                      replace_contents_close_callback, data);
7599       else
7600         g_output_stream_write_async (stream,
7601                                      content + data->pos,
7602                                      length - data->pos,
7603                                      0,
7604                                      g_task_get_cancellable (data->task),
7605                                      replace_contents_write_callback,
7606                                      data);
7607     }
7608 }
7609
7610 static void
7611 replace_contents_open_callback (GObject      *obj,
7612                                 GAsyncResult *open_res,
7613                                 gpointer      user_data)
7614 {
7615   GFile *file = G_FILE (obj);
7616   GFileOutputStream *stream;
7617   ReplaceContentsData *data = user_data;
7618   GError *error = NULL;
7619
7620   stream = g_file_replace_finish (file, open_res, &error);
7621
7622   if (stream)
7623     {
7624       const gchar *content;
7625       gsize length;
7626
7627       content = g_bytes_get_data (data->content, &length);
7628       g_output_stream_write_async (G_OUTPUT_STREAM (stream),
7629                                    content + data->pos,
7630                                    length - data->pos,
7631                                    0,
7632                                    g_task_get_cancellable (data->task),
7633                                    replace_contents_write_callback,
7634                                    data);
7635     }
7636   else
7637     {
7638       g_task_return_error (data->task, error);
7639       g_object_unref (data->task);
7640     }
7641 }
7642
7643 /**
7644  * g_file_replace_contents_async:
7645  * @file: input #GFile
7646  * @contents: (element-type guint8) (array length=length): string of contents to replace the file with
7647  * @length: the length of @contents in bytes
7648  * @etag: (nullable): a new [entity tag][gfile-etag] for the @file, or %NULL
7649  * @make_backup: %TRUE if a backup should be created
7650  * @flags: a set of #GFileCreateFlags
7651  * @cancellable: optional #GCancellable object, %NULL to ignore
7652  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7653  * @user_data: the data to pass to callback function
7654  *
7655  * Starts an asynchronous replacement of @file with the given
7656  * @contents of @length bytes. @etag will replace the document's
7657  * current entity tag.
7658  *
7659  * When this operation has completed, @callback will be called with
7660  * @user_user data, and the operation can be finalized with
7661  * g_file_replace_contents_finish().
7662  *
7663  * If @cancellable is not %NULL, then the operation can be cancelled by
7664  * triggering the cancellable object from another thread. If the operation
7665  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
7666  *
7667  * If @make_backup is %TRUE, this function will attempt to
7668  * make a backup of @file.
7669  *
7670  * Note that no copy of @content will be made, so it must stay valid
7671  * until @callback is called. See g_file_replace_contents_bytes_async()
7672  * for a #GBytes version that will automatically hold a reference to the
7673  * contents (without copying) for the duration of the call.
7674  */
7675 void
7676 g_file_replace_contents_async  (GFile               *file,
7677                                 const char          *contents,
7678                                 gsize                length,
7679                                 const char          *etag,
7680                                 gboolean             make_backup,
7681                                 GFileCreateFlags     flags,
7682                                 GCancellable        *cancellable,
7683                                 GAsyncReadyCallback  callback,
7684                                 gpointer             user_data)
7685 {
7686   GBytes *bytes;
7687
7688   bytes = g_bytes_new_static (contents, length);
7689   g_file_replace_contents_bytes_async (file, bytes, etag, make_backup, flags,
7690       cancellable, callback, user_data);
7691   g_bytes_unref (bytes);
7692 }
7693
7694 /**
7695  * g_file_replace_contents_bytes_async:
7696  * @file: input #GFile
7697  * @contents: a #GBytes
7698  * @etag: (nullable): a new [entity tag][gfile-etag] for the @file, or %NULL
7699  * @make_backup: %TRUE if a backup should be created
7700  * @flags: a set of #GFileCreateFlags
7701  * @cancellable: optional #GCancellable object, %NULL to ignore
7702  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7703  * @user_data: the data to pass to callback function
7704  *
7705  * Same as g_file_replace_contents_async() but takes a #GBytes input instead.
7706  * This function will keep a ref on @contents until the operation is done.
7707  * Unlike g_file_replace_contents_async() this allows forgetting about the
7708  * content without waiting for the callback.
7709  *
7710  * When this operation has completed, @callback will be called with
7711  * @user_user data, and the operation can be finalized with
7712  * g_file_replace_contents_finish().
7713  *
7714  * Since: 2.40
7715  */
7716 void
7717 g_file_replace_contents_bytes_async  (GFile               *file,
7718                                       GBytes              *contents,
7719                                       const char          *etag,
7720                                       gboolean             make_backup,
7721                                       GFileCreateFlags     flags,
7722                                       GCancellable        *cancellable,
7723                                       GAsyncReadyCallback  callback,
7724                                       gpointer             user_data)
7725 {
7726   ReplaceContentsData *data;
7727
7728   g_return_if_fail (G_IS_FILE (file));
7729   g_return_if_fail (contents != NULL);
7730
7731   data = g_new0 (ReplaceContentsData, 1);
7732
7733   data->content = g_bytes_ref (contents);
7734
7735   data->task = g_task_new (file, cancellable, callback, user_data);
7736   g_task_set_source_tag (data->task, g_file_replace_contents_bytes_async);
7737   g_task_set_task_data (data->task, data, (GDestroyNotify)replace_contents_data_free);
7738
7739   g_file_replace_async (file,
7740                         etag,
7741                         make_backup,
7742                         flags,
7743                         0,
7744                         g_task_get_cancellable (data->task),
7745                         replace_contents_open_callback,
7746                         data);
7747 }
7748
7749 /**
7750  * g_file_replace_contents_finish:
7751  * @file: input #GFile
7752  * @res: a #GAsyncResult
7753  * @new_etag: (out) (optional): a location of a new [entity tag][gfile-etag]
7754  *     for the document. This should be freed with g_free() when it is no
7755  *     longer needed, or %NULL
7756  * @error: a #GError, or %NULL
7757  *
7758  * Finishes an asynchronous replace of the given @file. See
7759  * g_file_replace_contents_async(). Sets @new_etag to the new entity
7760  * tag for the document, if present.
7761  *
7762  * Returns: %TRUE on success, %FALSE on failure.
7763  */
7764 gboolean
7765 g_file_replace_contents_finish (GFile         *file,
7766                                 GAsyncResult  *res,
7767                                 char         **new_etag,
7768                                 GError       **error)
7769 {
7770   GTask *task;
7771   ReplaceContentsData *data;
7772
7773   g_return_val_if_fail (G_IS_FILE (file), FALSE);
7774   g_return_val_if_fail (g_task_is_valid (res, file), FALSE);
7775
7776   task = G_TASK (res);
7777
7778   if (!g_task_propagate_boolean (task, error))
7779     return FALSE;
7780
7781   data = g_task_get_task_data (task);
7782
7783   if (new_etag)
7784     {
7785       *new_etag = data->etag;
7786       data->etag = NULL; /* Take ownership */
7787     }
7788
7789   return TRUE;
7790 }
7791
7792 gboolean
7793 g_file_real_measure_disk_usage (GFile                         *file,
7794                                 GFileMeasureFlags              flags,
7795                                 GCancellable                  *cancellable,
7796                                 GFileMeasureProgressCallback   progress_callback,
7797                                 gpointer                       progress_data,
7798                                 guint64                       *disk_usage,
7799                                 guint64                       *num_dirs,
7800                                 guint64                       *num_files,
7801                                 GError                       **error)
7802 {
7803   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
7804                        "Operation not supported for the current backend.");
7805   return FALSE;
7806 }
7807
7808 typedef struct
7809 {
7810   GFileMeasureFlags             flags;
7811   GFileMeasureProgressCallback  progress_callback;
7812   gpointer                      progress_data;
7813 } MeasureTaskData;
7814
7815 typedef struct
7816 {
7817   guint64 disk_usage;
7818   guint64 num_dirs;
7819   guint64 num_files;
7820 } MeasureResult;
7821
7822 typedef struct
7823 {
7824   GFileMeasureProgressCallback callback;
7825   gpointer                     user_data;
7826   gboolean                     reporting;
7827   guint64                      current_size;
7828   guint64                      num_dirs;
7829   guint64                      num_files;
7830 } MeasureProgress;
7831
7832 static gboolean
7833 measure_disk_usage_invoke_progress (gpointer user_data)
7834 {
7835   MeasureProgress *progress = user_data;
7836
7837   (* progress->callback) (progress->reporting,
7838                           progress->current_size, progress->num_dirs, progress->num_files,
7839                           progress->user_data);
7840
7841   return FALSE;
7842 }
7843
7844 static void
7845 measure_disk_usage_progress (gboolean reporting,
7846                              guint64  current_size,
7847                              guint64  num_dirs,
7848                              guint64  num_files,
7849                              gpointer user_data)
7850 {
7851   MeasureProgress progress;
7852   GTask *task = user_data;
7853   MeasureTaskData *data;
7854
7855   data = g_task_get_task_data (task);
7856
7857   progress.callback = data->progress_callback;
7858   progress.user_data = data->progress_data;
7859   progress.reporting = reporting;
7860   progress.current_size = current_size;
7861   progress.num_dirs = num_dirs;
7862   progress.num_files = num_files;
7863
7864   g_main_context_invoke_full (g_task_get_context (task),
7865                               g_task_get_priority (task),
7866                               measure_disk_usage_invoke_progress,
7867                               g_memdup (&progress, sizeof progress),
7868                               g_free);
7869 }
7870
7871 static void
7872 measure_disk_usage_thread (GTask        *task,
7873                            gpointer      source_object,
7874                            gpointer      task_data,
7875                            GCancellable *cancellable)
7876 {
7877   MeasureTaskData *data = task_data;
7878   GError *error = NULL;
7879   MeasureResult result = { 0, };
7880
7881   if (g_file_measure_disk_usage (source_object, data->flags, cancellable,
7882                                  data->progress_callback ? measure_disk_usage_progress : NULL, task,
7883                                  &result.disk_usage, &result.num_dirs, &result.num_files,
7884                                  &error))
7885     g_task_return_pointer (task, g_memdup (&result, sizeof result), g_free);
7886   else
7887     g_task_return_error (task, error);
7888 }
7889
7890 static void
7891 g_file_real_measure_disk_usage_async (GFile                        *file,
7892                                       GFileMeasureFlags             flags,
7893                                       gint                          io_priority,
7894                                       GCancellable                 *cancellable,
7895                                       GFileMeasureProgressCallback  progress_callback,
7896                                       gpointer                      progress_data,
7897                                       GAsyncReadyCallback           callback,
7898                                       gpointer                      user_data)
7899 {
7900   MeasureTaskData data;
7901   GTask *task;
7902
7903   data.flags = flags;
7904   data.progress_callback = progress_callback;
7905   data.progress_data = progress_data;
7906
7907   task = g_task_new (file, cancellable, callback, user_data);
7908   g_task_set_source_tag (task, g_file_real_measure_disk_usage_async);
7909   g_task_set_task_data (task, g_memdup (&data, sizeof data), g_free);
7910   g_task_set_priority (task, io_priority);
7911
7912   g_task_run_in_thread (task, measure_disk_usage_thread);
7913   g_object_unref (task);
7914 }
7915
7916 static gboolean
7917 g_file_real_measure_disk_usage_finish (GFile         *file,
7918                                        GAsyncResult  *result,
7919                                        guint64       *disk_usage,
7920                                        guint64       *num_dirs,
7921                                        guint64       *num_files,
7922                                        GError       **error)
7923 {
7924   MeasureResult *measure_result;
7925
7926   g_return_val_if_fail (g_task_is_valid (result, file), FALSE);
7927
7928   measure_result = g_task_propagate_pointer (G_TASK (result), error);
7929
7930   if (measure_result == NULL)
7931     return FALSE;
7932
7933   if (disk_usage)
7934     *disk_usage = measure_result->disk_usage;
7935
7936   if (num_dirs)
7937     *num_dirs = measure_result->num_dirs;
7938
7939   if (num_files)
7940     *num_files = measure_result->num_files;
7941
7942   g_free (measure_result);
7943
7944   return TRUE;
7945 }
7946
7947 /**
7948  * g_file_measure_disk_usage:
7949  * @file: a #GFile
7950  * @flags: #GFileMeasureFlags
7951  * @cancellable: (nullable): optional #GCancellable
7952  * @progress_callback: (nullable): a #GFileMeasureProgressCallback
7953  * @progress_data: user_data for @progress_callback
7954  * @disk_usage: (out) (optional): the number of bytes of disk space used
7955  * @num_dirs: (out) (optional): the number of directories encountered
7956  * @num_files: (out) (optional): the number of non-directories encountered
7957  * @error: (nullable): %NULL, or a pointer to a %NULL #GError pointer
7958  *
7959  * Recursively measures the disk usage of @file.
7960  *
7961  * This is essentially an analog of the 'du' command, but it also
7962  * reports the number of directories and non-directory files encountered
7963  * (including things like symbolic links).
7964  *
7965  * By default, errors are only reported against the toplevel file
7966  * itself.  Errors found while recursing are silently ignored, unless
7967  * %G_FILE_DISK_USAGE_REPORT_ALL_ERRORS is given in @flags.
7968  *
7969  * The returned size, @disk_usage, is in bytes and should be formatted
7970  * with g_format_size() in order to get something reasonable for showing
7971  * in a user interface.
7972  *
7973  * @progress_callback and @progress_data can be given to request
7974  * periodic progress updates while scanning.  See the documentation for
7975  * #GFileMeasureProgressCallback for information about when and how the
7976  * callback will be invoked.
7977  *
7978  * Returns: %TRUE if successful, with the out parameters set.
7979  *          %FALSE otherwise, with @error set.
7980  *
7981  * Since: 2.38
7982  **/
7983 gboolean
7984 g_file_measure_disk_usage (GFile                         *file,
7985                            GFileMeasureFlags              flags,
7986                            GCancellable                  *cancellable,
7987                            GFileMeasureProgressCallback   progress_callback,
7988                            gpointer                       progress_data,
7989                            guint64                       *disk_usage,
7990                            guint64                       *num_dirs,
7991                            guint64                       *num_files,
7992                            GError                       **error)
7993 {
7994   g_return_val_if_fail (G_IS_FILE (file), FALSE);
7995   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
7996   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
7997
7998   return G_FILE_GET_IFACE (file)->measure_disk_usage (file, flags, cancellable,
7999                                                       progress_callback, progress_data,
8000                                                       disk_usage, num_dirs, num_files,
8001                                                       error);
8002 }
8003
8004 /**
8005  * g_file_measure_disk_usage_async:
8006  * @file: a #GFile
8007  * @flags: #GFileMeasureFlags
8008  * @io_priority: the [I/O priority][io-priority] of the request
8009  * @cancellable: (nullable): optional #GCancellable
8010  * @progress_callback: (nullable): a #GFileMeasureProgressCallback
8011  * @progress_data: user_data for @progress_callback
8012  * @callback: (nullable): a #GAsyncReadyCallback to call when complete
8013  * @user_data: the data to pass to callback function
8014  *
8015  * Recursively measures the disk usage of @file.
8016  *
8017  * This is the asynchronous version of g_file_measure_disk_usage().  See
8018  * there for more information.
8019  *
8020  * Since: 2.38
8021  **/
8022 void
8023 g_file_measure_disk_usage_async (GFile                        *file,
8024                                  GFileMeasureFlags             flags,
8025                                  gint                          io_priority,
8026                                  GCancellable                 *cancellable,
8027                                  GFileMeasureProgressCallback  progress_callback,
8028                                  gpointer                      progress_data,
8029                                  GAsyncReadyCallback           callback,
8030                                  gpointer                      user_data)
8031 {
8032   g_return_if_fail (G_IS_FILE (file));
8033   g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
8034
8035   G_FILE_GET_IFACE (file)->measure_disk_usage_async (file, flags, io_priority, cancellable,
8036                                                      progress_callback, progress_data,
8037                                                      callback, user_data);
8038 }
8039
8040 /**
8041  * g_file_measure_disk_usage_finish:
8042  * @file: a #GFile
8043  * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
8044  * @disk_usage: (out) (optional): the number of bytes of disk space used
8045  * @num_dirs: (out) (optional): the number of directories encountered
8046  * @num_files: (out) (optional): the number of non-directories encountered
8047  * @error: (nullable): %NULL, or a pointer to a %NULL #GError pointer
8048  *
8049  * Collects the results from an earlier call to
8050  * g_file_measure_disk_usage_async().  See g_file_measure_disk_usage() for
8051  * more information.
8052  *
8053  * Returns: %TRUE if successful, with the out parameters set.
8054  *          %FALSE otherwise, with @error set.
8055  *
8056  * Since: 2.38
8057  **/
8058 gboolean
8059 g_file_measure_disk_usage_finish (GFile         *file,
8060                                   GAsyncResult  *result,
8061                                   guint64       *disk_usage,
8062                                   guint64       *num_dirs,
8063                                   guint64       *num_files,
8064                                   GError       **error)
8065 {
8066   g_return_val_if_fail (G_IS_FILE (file), FALSE);
8067   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
8068
8069   return G_FILE_GET_IFACE (file)->measure_disk_usage_finish (file, result, disk_usage, num_dirs, num_files, error);
8070 }
8071
8072 /**
8073  * g_file_start_mountable:
8074  * @file: input #GFile
8075  * @flags: flags affecting the operation
8076  * @start_operation: (nullable): a #GMountOperation, or %NULL to avoid user interaction
8077  * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore
8078  * @callback: (nullable): a #GAsyncReadyCallback to call when the request is satisfied, or %NULL
8079  * @user_data: the data to pass to callback function
8080  *
8081  * Starts a file of type #G_FILE_TYPE_MOUNTABLE.
8082  * Using @start_operation, you can request callbacks when, for instance,
8083  * passwords are needed during authentication.
8084  *
8085  * If @cancellable is not %NULL, then the operation can be cancelled by
8086  * triggering the cancellable object from another thread. If the operation
8087  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
8088  *
8089  * When the operation is finished, @callback will be called.
8090  * You can then call g_file_mount_mountable_finish() to get
8091  * the result of the operation.
8092  *
8093  * Since: 2.22
8094  */
8095 void
8096 g_file_start_mountable (GFile               *file,
8097                         GDriveStartFlags     flags,
8098                         GMountOperation     *start_operation,
8099                         GCancellable        *cancellable,
8100                         GAsyncReadyCallback  callback,
8101                         gpointer             user_data)
8102 {
8103   GFileIface *iface;
8104
8105   g_return_if_fail (G_IS_FILE (file));
8106
8107   iface = G_FILE_GET_IFACE (file);
8108
8109   if (iface->start_mountable == NULL)
8110     {
8111       g_task_report_new_error (file, callback, user_data,
8112                                g_file_start_mountable,
8113                                G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
8114                                _("Operation not supported"));
8115       return;
8116     }
8117
8118   (* iface->start_mountable) (file,
8119                               flags,
8120                               start_operation,
8121                               cancellable,
8122                               callback,
8123                               user_data);
8124 }
8125
8126 /**
8127  * g_file_start_mountable_finish:
8128  * @file: input #GFile
8129  * @result: a #GAsyncResult
8130  * @error: a #GError, or %NULL
8131  *
8132  * Finishes a start operation. See g_file_start_mountable() for details.
8133  *
8134  * Finish an asynchronous start operation that was started
8135  * with g_file_start_mountable().
8136  *
8137  * Returns: %TRUE if the operation finished successfully. %FALSE
8138  * otherwise.
8139  *
8140  * Since: 2.22
8141  */
8142 gboolean
8143 g_file_start_mountable_finish (GFile         *file,
8144                                GAsyncResult  *result,
8145                                GError       **error)
8146 {
8147   GFileIface *iface;
8148
8149   g_return_val_if_fail (G_IS_FILE (file), FALSE);
8150   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
8151
8152   if (g_async_result_legacy_propagate_error (result, error))
8153     return FALSE;
8154   else if (g_async_result_is_tagged (result, g_file_start_mountable))
8155     return g_task_propagate_boolean (G_TASK (result), error);
8156
8157   iface = G_FILE_GET_IFACE (file);
8158   return (* iface->start_mountable_finish) (file, result, error);
8159 }
8160
8161 /**
8162  * g_file_stop_mountable:
8163  * @file: input #GFile
8164  * @flags: flags affecting the operation
8165  * @mount_operation: (nullable): a #GMountOperation,
8166  *     or %NULL to avoid user interaction.
8167  * @cancellable: (nullable): optional #GCancellable object,
8168  *     %NULL to ignore
8169  * @callback: (nullable): a #GAsyncReadyCallback to call
8170  *     when the request is satisfied, or %NULL
8171  * @user_data: the data to pass to callback function
8172  *
8173  * Stops a file of type #G_FILE_TYPE_MOUNTABLE.
8174  *
8175  * If @cancellable is not %NULL, then the operation can be cancelled by
8176  * triggering the cancellable object from another thread. If the operation
8177  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
8178  *
8179  * When the operation is finished, @callback will be called.
8180  * You can then call g_file_stop_mountable_finish() to get
8181  * the result of the operation.
8182  *
8183  * Since: 2.22
8184  */
8185 void
8186 g_file_stop_mountable (GFile               *file,
8187                        GMountUnmountFlags   flags,
8188                        GMountOperation     *mount_operation,
8189                        GCancellable        *cancellable,
8190                        GAsyncReadyCallback  callback,
8191                        gpointer             user_data)
8192 {
8193   GFileIface *iface;
8194
8195   g_return_if_fail (G_IS_FILE (file));
8196
8197   iface = G_FILE_GET_IFACE (file);
8198
8199   if (iface->stop_mountable == NULL)
8200     {
8201       g_task_report_new_error (file, callback, user_data,
8202                                g_file_stop_mountable,
8203                                G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
8204                                _("Operation not supported"));
8205       return;
8206     }
8207
8208   (* iface->stop_mountable) (file,
8209                              flags,
8210                              mount_operation,
8211                              cancellable,
8212                              callback,
8213                              user_data);
8214 }
8215
8216 /**
8217  * g_file_stop_mountable_finish:
8218  * @file: input #GFile
8219  * @result: a #GAsyncResult
8220  * @error: a #GError, or %NULL
8221  *
8222  * Finishes an stop operation, see g_file_stop_mountable() for details.
8223  *
8224  * Finish an asynchronous stop operation that was started
8225  * with g_file_stop_mountable().
8226  *
8227  * Returns: %TRUE if the operation finished successfully.
8228  *     %FALSE otherwise.
8229  *
8230  * Since: 2.22
8231  */
8232 gboolean
8233 g_file_stop_mountable_finish (GFile         *file,
8234                               GAsyncResult  *result,
8235                               GError       **error)
8236 {
8237   GFileIface *iface;
8238
8239   g_return_val_if_fail (G_IS_FILE (file), FALSE);
8240   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
8241
8242   if (g_async_result_legacy_propagate_error (result, error))
8243     return FALSE;
8244   else if (g_async_result_is_tagged (result, g_file_stop_mountable))
8245     return g_task_propagate_boolean (G_TASK (result), error);
8246
8247   iface = G_FILE_GET_IFACE (file);
8248   return (* iface->stop_mountable_finish) (file, result, error);
8249 }
8250
8251 /**
8252  * g_file_poll_mountable:
8253  * @file: input #GFile
8254  * @cancellable: optional #GCancellable object, %NULL to ignore
8255  * @callback: (nullable): a #GAsyncReadyCallback to call
8256  *     when the request is satisfied, or %NULL
8257  * @user_data: the data to pass to callback function
8258  *
8259  * Polls a file of type #G_FILE_TYPE_MOUNTABLE.
8260  *
8261  * If @cancellable is not %NULL, then the operation can be cancelled by
8262  * triggering the cancellable object from another thread. If the operation
8263  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
8264  *
8265  * When the operation is finished, @callback will be called.
8266  * You can then call g_file_mount_mountable_finish() to get
8267  * the result of the operation.
8268  *
8269  * Since: 2.22
8270  */
8271 void
8272 g_file_poll_mountable (GFile               *file,
8273                        GCancellable        *cancellable,
8274                        GAsyncReadyCallback  callback,
8275                        gpointer             user_data)
8276 {
8277   GFileIface *iface;
8278
8279   g_return_if_fail (G_IS_FILE (file));
8280
8281   iface = G_FILE_GET_IFACE (file);
8282
8283   if (iface->poll_mountable == NULL)
8284     {
8285       g_task_report_new_error (file, callback, user_data,
8286                                g_file_poll_mountable,
8287                                G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
8288                                _("Operation not supported"));
8289       return;
8290     }
8291
8292   (* iface->poll_mountable) (file,
8293                              cancellable,
8294                              callback,
8295                              user_data);
8296 }
8297
8298 /**
8299  * g_file_poll_mountable_finish:
8300  * @file: input #GFile
8301  * @result: a #GAsyncResult
8302  * @error: a #GError, or %NULL
8303  *
8304  * Finishes a poll operation. See g_file_poll_mountable() for details.
8305  *
8306  * Finish an asynchronous poll operation that was polled
8307  * with g_file_poll_mountable().
8308  *
8309  * Returns: %TRUE if the operation finished successfully. %FALSE
8310  * otherwise.
8311  *
8312  * Since: 2.22
8313  */
8314 gboolean
8315 g_file_poll_mountable_finish (GFile         *file,
8316                               GAsyncResult  *result,
8317                               GError       **error)
8318 {
8319   GFileIface *iface;
8320
8321   g_return_val_if_fail (G_IS_FILE (file), FALSE);
8322   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE);
8323
8324   if (g_async_result_legacy_propagate_error (result, error))
8325     return FALSE;
8326   else if (g_async_result_is_tagged (result, g_file_poll_mountable))
8327     return g_task_propagate_boolean (G_TASK (result), error);
8328
8329   iface = G_FILE_GET_IFACE (file);
8330   return (* iface->poll_mountable_finish) (file, result, error);
8331 }
8332
8333 /**
8334  * g_file_supports_thread_contexts:
8335  * @file: a #GFile
8336  *
8337  * Checks if @file supports
8338  * [thread-default contexts][g-main-context-push-thread-default-context].
8339  * If this returns %FALSE, you cannot perform asynchronous operations on
8340  * @file in a thread that has a thread-default context.
8341  *
8342  * Returns: Whether or not @file supports thread-default contexts.
8343  *
8344  * Since: 2.22
8345  */
8346 gboolean
8347 g_file_supports_thread_contexts (GFile *file)
8348 {
8349  GFileIface *iface;
8350
8351  g_return_val_if_fail (G_IS_FILE (file), FALSE);
8352
8353  iface = G_FILE_GET_IFACE (file);
8354  return iface->supports_thread_contexts;
8355 }
8356
8357 /**
8358  * g_file_load_bytes:
8359  * @file: a #GFile
8360  * @cancellable: (nullable): a #GCancellable or %NULL
8361  * @etag_out: (out) (nullable) (optional): a location to place the current
8362  *     entity tag for the file, or %NULL if the entity tag is not needed
8363  * @error: a location for a #GError or %NULL
8364  *
8365  * Loads the contents of @file and returns it as #GBytes.
8366  *
8367  * If @file is a resource:// based URI, the resulting bytes will reference the
8368  * embedded resource instead of a copy. Otherwise, this is equivalent to calling
8369  * g_file_load_contents() and g_bytes_new_take().
8370  *
8371  * For resources, @etag_out will be set to %NULL.
8372  *
8373  * The data contained in the resulting #GBytes is always zero-terminated, but
8374  * this is not included in the #GBytes length. The resulting #GBytes should be
8375  * freed with g_bytes_unref() when no longer in use.
8376  *
8377  * Returns: (transfer full): a #GBytes or %NULL and @error is set
8378  *
8379  * Since: 2.56
8380  */
8381 GBytes *
8382 g_file_load_bytes (GFile         *file,
8383                    GCancellable  *cancellable,
8384                    gchar        **etag_out,
8385                    GError       **error)
8386 {
8387   gchar *contents;
8388   gsize len;
8389
8390   g_return_val_if_fail (G_IS_FILE (file), NULL);
8391   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL);
8392   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
8393
8394   if (etag_out != NULL)
8395     *etag_out = NULL;
8396
8397   if (g_file_has_uri_scheme (file, "resource"))
8398     {
8399       GBytes *bytes;
8400       gchar *uri, *unescaped;
8401
8402       uri = g_file_get_uri (file);
8403       unescaped = g_uri_unescape_string (uri + strlen ("resource://"), NULL);
8404       g_free (uri);
8405
8406       bytes = g_resources_lookup_data (unescaped, G_RESOURCE_LOOKUP_FLAGS_NONE, error);
8407       g_free (unescaped);
8408
8409       return bytes;
8410     }
8411
8412   /* contents is guaranteed to be \0 terminated */
8413   if (g_file_load_contents (file, cancellable, &contents, &len, etag_out, error))
8414     return g_bytes_new_take (g_steal_pointer (&contents), len);
8415
8416   return NULL;
8417 }
8418
8419 static void
8420 g_file_load_bytes_cb (GObject      *object,
8421                       GAsyncResult *result,
8422                       gpointer      user_data)
8423 {
8424   GFile *file = G_FILE (object);
8425   GTask *task = user_data;
8426   GError *error = NULL;
8427   gchar *etag = NULL;
8428   gchar *contents = NULL;
8429   gsize len = 0;
8430
8431   g_file_load_contents_finish (file, result, &contents, &len, &etag, &error);
8432   g_task_set_task_data (task, g_steal_pointer (&etag), g_free);
8433
8434   if (error != NULL)
8435     g_task_return_error (task, g_steal_pointer (&error));
8436   else
8437     g_task_return_pointer (task,
8438                            g_bytes_new_take (g_steal_pointer (&contents), len),
8439                            (GDestroyNotify)g_bytes_unref);
8440
8441   g_object_unref (task);
8442 }
8443
8444 /**
8445  * g_file_load_bytes_async:
8446  * @file: a #GFile
8447  * @cancellable: (nullable): a #GCancellable or %NULL
8448  * @callback: (scope async): a #GAsyncReadyCallback to call when the
8449  *     request is satisfied
8450  * @user_data: (closure): the data to pass to callback function
8451  *
8452  * Asynchronously loads the contents of @file as #GBytes.
8453  *
8454  * If @file is a resource:// based URI, the resulting bytes will reference the
8455  * embedded resource instead of a copy. Otherwise, this is equivalent to calling
8456  * g_file_load_contents_async() and g_bytes_new_take().
8457  *
8458  * @callback should call g_file_load_bytes_finish() to get the result of this
8459  * asynchronous operation.
8460  *
8461  * See g_file_load_bytes() for more information.
8462  *
8463  * Since: 2.56
8464  */
8465 void
8466 g_file_load_bytes_async (GFile               *file,
8467                          GCancellable        *cancellable,
8468                          GAsyncReadyCallback  callback,
8469                          gpointer             user_data)
8470 {
8471   GError *error = NULL;
8472   GBytes *bytes;
8473   GTask *task;
8474
8475   g_return_if_fail (G_IS_FILE (file));
8476   g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
8477
8478   task = g_task_new (file, cancellable, callback, user_data);
8479   g_task_set_source_tag (task, g_file_load_bytes_async);
8480
8481   if (!g_file_has_uri_scheme (file, "resource"))
8482     {
8483       g_file_load_contents_async (file,
8484                                   cancellable,
8485                                   g_file_load_bytes_cb,
8486                                   g_steal_pointer (&task));
8487       return;
8488     }
8489
8490   bytes = g_file_load_bytes (file, cancellable, NULL, &error);
8491
8492   if (bytes == NULL)
8493     g_task_return_error (task, g_steal_pointer (&error));
8494   else
8495     g_task_return_pointer (task,
8496                            g_steal_pointer (&bytes),
8497                            (GDestroyNotify)g_bytes_unref);
8498
8499   g_object_unref (task);
8500 }
8501
8502 /**
8503  * g_file_load_bytes_finish:
8504  * @file: a #GFile
8505  * @result: a #GAsyncResult provided to the callback
8506  * @etag_out: (out) (nullable) (optional): a location to place the current
8507  *     entity tag for the file, or %NULL if the entity tag is not needed
8508  * @error: a location for a #GError, or %NULL
8509  *
8510  * Completes an asynchronous request to g_file_load_bytes_async().
8511  *
8512  * For resources, @etag_out will be set to %NULL.
8513  *
8514  * The data contained in the resulting #GBytes is always zero-terminated, but
8515  * this is not included in the #GBytes length. The resulting #GBytes should be
8516  * freed with g_bytes_unref() when no longer in use.
8517  *
8518  * See g_file_load_bytes() for more information.
8519  *
8520  * Returns: (transfer full): a #GBytes or %NULL and @error is set
8521  *
8522  * Since: 2.56
8523  */
8524 GBytes *
8525 g_file_load_bytes_finish (GFile         *file,
8526                           GAsyncResult  *result,
8527                           gchar        **etag_out,
8528                           GError       **error)
8529 {
8530   GBytes *bytes;
8531
8532   g_return_val_if_fail (G_IS_FILE (file), NULL);
8533   g_return_val_if_fail (G_IS_TASK (result), NULL);
8534   g_return_val_if_fail (g_task_is_valid (G_TASK (result), file), NULL);
8535   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
8536
8537   bytes = g_task_propagate_pointer (G_TASK (result), error);
8538
8539   if (etag_out != NULL)
8540     *etag_out = g_strdup (g_task_get_task_data (G_TASK (result)));
8541
8542   return bytes;
8543 }