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