1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT

use crate::AsyncResult;
use crate::Cancellable;
use glib::object::IsA;
use glib::object::ObjectType as ObjectType_;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;

glib::wrapper! {
    /// A [`Task`][crate::Task] represents and manages a cancellable "task".
    ///
    /// ## Asynchronous operations
    ///
    /// The most common usage of [`Task`][crate::Task] is as a [`AsyncResult`][crate::AsyncResult], to
    /// manage data during an asynchronous operation. You call
    /// [`new()`][Self::new()] in the "start" method, followed by
    /// `g_task_set_task_data()` and the like if you need to keep some
    /// additional data associated with the task, and then pass the
    /// task object around through your asynchronous operation.
    /// Eventually, you will call a method such as
    /// `g_task_return_pointer()` or [`return_error()`][Self::return_error()], which will
    /// save the value you give it and then invoke the task's callback
    /// function in the
    /// [thread-default main context][g-main-context-push-thread-default]
    /// where it was created (waiting until the next iteration of the main
    /// loop first, if necessary). The caller will pass the [`Task`][crate::Task] back to
    /// the operation's finish function (as a [`AsyncResult`][crate::AsyncResult]), and you can
    /// use `g_task_propagate_pointer()` or the like to extract the
    /// return value.
    ///
    /// Here is an example for using GTask as a GAsyncResult:
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    ///     typedef struct {
    ///       CakeFrostingType frosting;
    ///       char *message;
    ///     } DecorationData;
    ///
    ///     static void
    ///     decoration_data_free (DecorationData *decoration)
    ///     {
    ///       g_free (decoration->message);
    ///       g_slice_free (DecorationData, decoration);
    ///     }
    ///
    ///     static void
    ///     baked_cb (Cake     *cake,
    ///               gpointer  user_data)
    ///     {
    ///       GTask *task = user_data;
    ///       DecorationData *decoration = g_task_get_task_data (task);
    ///       GError *error = NULL;
    ///
    ///       if (cake == NULL)
    ///         {
    ///           g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
    ///                                    "Go to the supermarket");
    ///           g_object_unref (task);
    ///           return;
    ///         }
    ///
    ///       if (!cake_decorate (cake, decoration->frosting, decoration->message, &error))
    ///         {
    ///           g_object_unref (cake);
    ///           // g_task_return_error() takes ownership of error
    ///           g_task_return_error (task, error);
    ///           g_object_unref (task);
    ///           return;
    ///         }
    ///
    ///       g_task_return_pointer (task, cake, g_object_unref);
    ///       g_object_unref (task);
    ///     }
    ///
    ///     void
    ///     baker_bake_cake_async (Baker               *self,
    ///                            guint                radius,
    ///                            CakeFlavor           flavor,
    ///                            CakeFrostingType     frosting,
    ///                            const char          *message,
    ///                            GCancellable        *cancellable,
    ///                            GAsyncReadyCallback  callback,
    ///                            gpointer             user_data)
    ///     {
    ///       GTask *task;
    ///       DecorationData *decoration;
    ///       Cake  *cake;
    ///
    ///       task = g_task_new (self, cancellable, callback, user_data);
    ///       if (radius < 3)
    ///         {
    ///           g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_TOO_SMALL,
    ///                                    "%ucm radius cakes are silly",
    ///                                    radius);
    ///           g_object_unref (task);
    ///           return;
    ///         }
    ///
    ///       cake = _baker_get_cached_cake (self, radius, flavor, frosting, message);
    ///       if (cake != NULL)
    ///         {
    ///           // _baker_get_cached_cake() returns a reffed cake
    ///           g_task_return_pointer (task, cake, g_object_unref);
    ///           g_object_unref (task);
    ///           return;
    ///         }
    ///
    ///       decoration = g_slice_new (DecorationData);
    ///       decoration->frosting = frosting;
    ///       decoration->message = g_strdup (message);
    ///       g_task_set_task_data (task, decoration, (GDestroyNotify) decoration_data_free);
    ///
    ///       _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
    ///     }
    ///
    ///     Cake *
    ///     baker_bake_cake_finish (Baker         *self,
    ///                             GAsyncResult  *result,
    ///                             GError       **error)
    ///     {
    ///       g_return_val_if_fail (g_task_is_valid (result, self), NULL);
    ///
    ///       return g_task_propagate_pointer (G_TASK (result), error);
    ///     }
    /// ```
    ///
    /// ## Chained asynchronous operations
    ///
    /// [`Task`][crate::Task] also tries to simplify asynchronous operations that
    /// internally chain together several smaller asynchronous
    /// operations. [`cancellable()`][Self::cancellable()], [`context()`][Self::context()],
    /// and [`priority()`][Self::priority()] allow you to get back the task's
    /// [`Cancellable`][crate::Cancellable], [`glib::MainContext`][crate::glib::MainContext], and [I/O priority][io-priority]
    /// when starting a new subtask, so you don't have to keep track
    /// of them yourself. `g_task_attach_source()` simplifies the case
    /// of waiting for a source to fire (automatically using the correct
    /// [`glib::MainContext`][crate::glib::MainContext] and priority).
    ///
    /// Here is an example for chained asynchronous operations:
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    ///     typedef struct {
    ///       Cake *cake;
    ///       CakeFrostingType frosting;
    ///       char *message;
    ///     } BakingData;
    ///
    ///     static void
    ///     decoration_data_free (BakingData *bd)
    ///     {
    ///       if (bd->cake)
    ///         g_object_unref (bd->cake);
    ///       g_free (bd->message);
    ///       g_slice_free (BakingData, bd);
    ///     }
    ///
    ///     static void
    ///     decorated_cb (Cake         *cake,
    ///                   GAsyncResult *result,
    ///                   gpointer      user_data)
    ///     {
    ///       GTask *task = user_data;
    ///       GError *error = NULL;
    ///
    ///       if (!cake_decorate_finish (cake, result, &error))
    ///         {
    ///           g_object_unref (cake);
    ///           g_task_return_error (task, error);
    ///           g_object_unref (task);
    ///           return;
    ///         }
    ///
    ///       // baking_data_free() will drop its ref on the cake, so we have to
    ///       // take another here to give to the caller.
    ///       g_task_return_pointer (task, g_object_ref (cake), g_object_unref);
    ///       g_object_unref (task);
    ///     }
    ///
    ///     static gboolean
    ///     decorator_ready (gpointer user_data)
    ///     {
    ///       GTask *task = user_data;
    ///       BakingData *bd = g_task_get_task_data (task);
    ///
    ///       cake_decorate_async (bd->cake, bd->frosting, bd->message,
    ///                            g_task_get_cancellable (task),
    ///                            decorated_cb, task);
    ///
    ///       return G_SOURCE_REMOVE;
    ///     }
    ///
    ///     static void
    ///     baked_cb (Cake     *cake,
    ///               gpointer  user_data)
    ///     {
    ///       GTask *task = user_data;
    ///       BakingData *bd = g_task_get_task_data (task);
    ///       GError *error = NULL;
    ///
    ///       if (cake == NULL)
    ///         {
    ///           g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
    ///                                    "Go to the supermarket");
    ///           g_object_unref (task);
    ///           return;
    ///         }
    ///
    ///       bd->cake = cake;
    ///
    ///       // Bail out now if the user has already cancelled
    ///       if (g_task_return_error_if_cancelled (task))
    ///         {
    ///           g_object_unref (task);
    ///           return;
    ///         }
    ///
    ///       if (cake_decorator_available (cake))
    ///         decorator_ready (task);
    ///       else
    ///         {
    ///           GSource *source;
    ///
    ///           source = cake_decorator_wait_source_new (cake);
    ///           // Attach @source to @task's GMainContext and have it call
    ///           // decorator_ready() when it is ready.
    ///           g_task_attach_source (task, source, decorator_ready);
    ///           g_source_unref (source);
    ///         }
    ///     }
    ///
    ///     void
    ///     baker_bake_cake_async (Baker               *self,
    ///                            guint                radius,
    ///                            CakeFlavor           flavor,
    ///                            CakeFrostingType     frosting,
    ///                            const char          *message,
    ///                            gint                 priority,
    ///                            GCancellable        *cancellable,
    ///                            GAsyncReadyCallback  callback,
    ///                            gpointer             user_data)
    ///     {
    ///       GTask *task;
    ///       BakingData *bd;
    ///
    ///       task = g_task_new (self, cancellable, callback, user_data);
    ///       g_task_set_priority (task, priority);
    ///
    ///       bd = g_slice_new0 (BakingData);
    ///       bd->frosting = frosting;
    ///       bd->message = g_strdup (message);
    ///       g_task_set_task_data (task, bd, (GDestroyNotify) baking_data_free);
    ///
    ///       _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
    ///     }
    ///
    ///     Cake *
    ///     baker_bake_cake_finish (Baker         *self,
    ///                             GAsyncResult  *result,
    ///                             GError       **error)
    ///     {
    ///       g_return_val_if_fail (g_task_is_valid (result, self), NULL);
    ///
    ///       return g_task_propagate_pointer (G_TASK (result), error);
    ///     }
    /// ```
    ///
    /// ## Asynchronous operations from synchronous ones
    ///
    /// You can use `g_task_run_in_thread()` to turn a synchronous
    /// operation into an asynchronous one, by running it in a thread.
    /// When it completes, the result will be dispatched to the
    /// [thread-default main context][g-main-context-push-thread-default]
    /// where the [`Task`][crate::Task] was created.
    ///
    /// Running a task in a thread:
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    ///     typedef struct {
    ///       guint radius;
    ///       CakeFlavor flavor;
    ///       CakeFrostingType frosting;
    ///       char *message;
    ///     } CakeData;
    ///
    ///     static void
    ///     cake_data_free (CakeData *cake_data)
    ///     {
    ///       g_free (cake_data->message);
    ///       g_slice_free (CakeData, cake_data);
    ///     }
    ///
    ///     static void
    ///     bake_cake_thread (GTask         *task,
    ///                       gpointer       source_object,
    ///                       gpointer       task_data,
    ///                       GCancellable  *cancellable)
    ///     {
    ///       Baker *self = source_object;
    ///       CakeData *cake_data = task_data;
    ///       Cake *cake;
    ///       GError *error = NULL;
    ///
    ///       cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
    ///                         cake_data->frosting, cake_data->message,
    ///                         cancellable, &error);
    ///       if (cake)
    ///         g_task_return_pointer (task, cake, g_object_unref);
    ///       else
    ///         g_task_return_error (task, error);
    ///     }
    ///
    ///     void
    ///     baker_bake_cake_async (Baker               *self,
    ///                            guint                radius,
    ///                            CakeFlavor           flavor,
    ///                            CakeFrostingType     frosting,
    ///                            const char          *message,
    ///                            GCancellable        *cancellable,
    ///                            GAsyncReadyCallback  callback,
    ///                            gpointer             user_data)
    ///     {
    ///       CakeData *cake_data;
    ///       GTask *task;
    ///
    ///       cake_data = g_slice_new (CakeData);
    ///       cake_data->radius = radius;
    ///       cake_data->flavor = flavor;
    ///       cake_data->frosting = frosting;
    ///       cake_data->message = g_strdup (message);
    ///       task = g_task_new (self, cancellable, callback, user_data);
    ///       g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
    ///       g_task_run_in_thread (task, bake_cake_thread);
    ///       g_object_unref (task);
    ///     }
    ///
    ///     Cake *
    ///     baker_bake_cake_finish (Baker         *self,
    ///                             GAsyncResult  *result,
    ///                             GError       **error)
    ///     {
    ///       g_return_val_if_fail (g_task_is_valid (result, self), NULL);
    ///
    ///       return g_task_propagate_pointer (G_TASK (result), error);
    ///     }
    /// ```
    ///
    /// ## Adding cancellability to uncancellable tasks
    ///
    /// Finally, `g_task_run_in_thread()` and `g_task_run_in_thread_sync()`
    /// can be used to turn an uncancellable operation into a
    /// cancellable one. If you call [`set_return_on_cancel()`][Self::set_return_on_cancel()],
    /// passing [`true`], then if the task's [`Cancellable`][crate::Cancellable] is cancelled,
    /// it will return control back to the caller immediately, while
    /// allowing the task thread to continue running in the background
    /// (and simply discarding its result when it finally does finish).
    /// Provided that the task thread is careful about how it uses
    /// locks and other externally-visible resources, this allows you
    /// to make "GLib-friendly" asynchronous and cancellable
    /// synchronous variants of blocking APIs.
    ///
    /// Cancelling a task:
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    ///     static void
    ///     bake_cake_thread (GTask         *task,
    ///                       gpointer       source_object,
    ///                       gpointer       task_data,
    ///                       GCancellable  *cancellable)
    ///     {
    ///       Baker *self = source_object;
    ///       CakeData *cake_data = task_data;
    ///       Cake *cake;
    ///       GError *error = NULL;
    ///
    ///       cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
    ///                         cake_data->frosting, cake_data->message,
    ///                         &error);
    ///       if (error)
    ///         {
    ///           g_task_return_error (task, error);
    ///           return;
    ///         }
    ///
    ///       // If the task has already been cancelled, then we don't want to add
    ///       // the cake to the cake cache. Likewise, we don't  want to have the
    ///       // task get cancelled in the middle of updating the cache.
    ///       // g_task_set_return_on_cancel() will return %TRUE here if it managed
    ///       // to disable return-on-cancel, or %FALSE if the task was cancelled
    ///       // before it could.
    ///       if (g_task_set_return_on_cancel (task, FALSE))
    ///         {
    ///           // If the caller cancels at this point, their
    ///           // GAsyncReadyCallback won't be invoked until we return,
    ///           // so we don't have to worry that this code will run at
    ///           // the same time as that code does. But if there were
    ///           // other functions that might look at the cake cache,
    ///           // then we'd probably need a GMutex here as well.
    ///           baker_add_cake_to_cache (baker, cake);
    ///           g_task_return_pointer (task, cake, g_object_unref);
    ///         }
    ///     }
    ///
    ///     void
    ///     baker_bake_cake_async (Baker               *self,
    ///                            guint                radius,
    ///                            CakeFlavor           flavor,
    ///                            CakeFrostingType     frosting,
    ///                            const char          *message,
    ///                            GCancellable        *cancellable,
    ///                            GAsyncReadyCallback  callback,
    ///                            gpointer             user_data)
    ///     {
    ///       CakeData *cake_data;
    ///       GTask *task;
    ///
    ///       cake_data = g_slice_new (CakeData);
    ///
    ///       ...
    ///
    ///       task = g_task_new (self, cancellable, callback, user_data);
    ///       g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
    ///       g_task_set_return_on_cancel (task, TRUE);
    ///       g_task_run_in_thread (task, bake_cake_thread);
    ///     }
    ///
    ///     Cake *
    ///     baker_bake_cake_sync (Baker               *self,
    ///                           guint                radius,
    ///                           CakeFlavor           flavor,
    ///                           CakeFrostingType     frosting,
    ///                           const char          *message,
    ///                           GCancellable        *cancellable,
    ///                           GError             **error)
    ///     {
    ///       CakeData *cake_data;
    ///       GTask *task;
    ///       Cake *cake;
    ///
    ///       cake_data = g_slice_new (CakeData);
    ///
    ///       ...
    ///
    ///       task = g_task_new (self, cancellable, NULL, NULL);
    ///       g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
    ///       g_task_set_return_on_cancel (task, TRUE);
    ///       g_task_run_in_thread_sync (task, bake_cake_thread);
    ///
    ///       cake = g_task_propagate_pointer (task, error);
    ///       g_object_unref (task);
    ///       return cake;
    ///     }
    /// ```
    ///
    /// ## Porting from GSimpleAsyncResult
    ///
    /// [`Task`][crate::Task]'s API attempts to be simpler than `GSimpleAsyncResult`'s
    /// in several ways:
    /// - You can save task-specific data with `g_task_set_task_data()`, and
    ///  retrieve it later with `g_task_get_task_data()`. This replaces the
    ///  abuse of `g_simple_async_result_set_op_res_gpointer()` for the same
    ///  purpose with `GSimpleAsyncResult`.
    /// - In addition to the task data, [`Task`][crate::Task] also keeps track of the
    ///  [priority][io-priority], [`Cancellable`][crate::Cancellable], and
    ///  [`glib::MainContext`][crate::glib::MainContext] associated with the task, so tasks that consist of
    ///  a chain of simpler asynchronous operations will have easy access
    ///  to those values when starting each sub-task.
    /// - [`return_error_if_cancelled()`][Self::return_error_if_cancelled()] provides simplified
    ///  handling for cancellation. In addition, cancellation
    ///  overrides any other [`Task`][crate::Task] return value by default, like
    ///  `GSimpleAsyncResult` does when
    ///  `g_simple_async_result_set_check_cancellable()` is called.
    ///  (You can use [`set_check_cancellable()`][Self::set_check_cancellable()] to turn off that
    ///  behavior.) On the other hand, `g_task_run_in_thread()`
    ///  guarantees that it will always run your
    ///  `task_func`, even if the task's [`Cancellable`][crate::Cancellable]
    ///  is already cancelled before the task gets a chance to run;
    ///  you can start your `task_func` with a
    ///  [`return_error_if_cancelled()`][Self::return_error_if_cancelled()] check if you need the
    ///  old behavior.
    /// - The "return" methods (eg, `g_task_return_pointer()`)
    ///  automatically cause the task to be "completed" as well, and
    ///  there is no need to worry about the "complete" vs "complete
    ///  in idle" distinction. ([`Task`][crate::Task] automatically figures out
    ///  whether the task's callback can be invoked directly, or
    ///  if it needs to be sent to another [`glib::MainContext`][crate::glib::MainContext], or delayed
    ///  until the next iteration of the current [`glib::MainContext`][crate::glib::MainContext].)
    /// - The "finish" functions for [`Task`][crate::Task] based operations are generally
    ///  much simpler than `GSimpleAsyncResult` ones, normally consisting
    ///  of only a single call to `g_task_propagate_pointer()` or the like.
    ///  Since `g_task_propagate_pointer()` "steals" the return value from
    ///  the [`Task`][crate::Task], it is not necessary to juggle pointers around to
    ///  prevent it from being freed twice.
    /// - With `GSimpleAsyncResult`, it was common to call
    ///  `g_simple_async_result_propagate_error()` from the
    ///  ``_finish()`` wrapper function, and have
    ///  virtual method implementations only deal with successful
    ///  returns. This behavior is deprecated, because it makes it
    ///  difficult for a subclass to chain to a parent class's async
    ///  methods. Instead, the wrapper function should just be a
    ///  simple wrapper, and the virtual method should call an
    ///  appropriate `g_task_propagate_` function.
    ///  Note that wrapper methods can now use
    ///  [`AsyncResultExt::legacy_propagate_error()`][crate::prelude::AsyncResultExt::legacy_propagate_error()] to do old-style
    ///  `GSimpleAsyncResult` error-returning behavior, and
    ///  `g_async_result_is_tagged()` to check if a result is tagged as
    ///  having come from the ``_async()`` wrapper
    ///  function (for "short-circuit" results, such as when passing
    ///  0 to [`InputStreamExtManual::read_async()`][crate::prelude::InputStreamExtManual::read_async()]).
    ///
    /// # Implements
    ///
    /// [`trait@glib::ObjectExt`], [`AsyncResultExt`][trait@crate::prelude::AsyncResultExt]
    #[doc(alias = "GTask")]
    pub struct Task(Object<ffi::GTask, ffi::GTaskClass>) @implements AsyncResult;

    match fn {
        type_ => || ffi::g_task_get_type(),
    }
}

impl Task {
    //#[doc(alias = "g_task_attach_source")]
    //pub fn attach_source<P: Fn() -> bool + 'static>(&self, source: &glib::Source, callback: P) {
    //    unsafe { TODO: call ffi:g_task_attach_source() }
    //}

    /// Gets `self`'s [`Cancellable`][crate::Cancellable]
    ///
    /// # Returns
    ///
    /// `self`'s [`Cancellable`][crate::Cancellable]
    #[doc(alias = "g_task_get_cancellable")]
    #[doc(alias = "get_cancellable")]
    pub fn cancellable(&self) -> Cancellable {
        unsafe { from_glib_none(ffi::g_task_get_cancellable(self.to_glib_none().0)) }
    }

    /// Gets `self`'s check-cancellable flag. See
    /// [`set_check_cancellable()`][Self::set_check_cancellable()] for more details.
    #[doc(alias = "g_task_get_check_cancellable")]
    #[doc(alias = "get_check_cancellable")]
    pub fn is_check_cancellable(&self) -> bool {
        unsafe { from_glib(ffi::g_task_get_check_cancellable(self.to_glib_none().0)) }
    }

    /// Gets the value of `property::Task::completed`. This changes from [`false`] to [`true`] after
    /// the task’s callback is invoked, and will return [`false`] if called from inside
    /// the callback.
    ///
    /// # Returns
    ///
    /// [`true`] if the task has completed, [`false`] otherwise.
    #[doc(alias = "g_task_get_completed")]
    #[doc(alias = "get_completed")]
    pub fn is_completed(&self) -> bool {
        unsafe { from_glib(ffi::g_task_get_completed(self.to_glib_none().0)) }
    }

    /// Gets the [`glib::MainContext`][crate::glib::MainContext] that `self` will return its result in (that
    /// is, the context that was the
    /// [thread-default main context][g-main-context-push-thread-default]
    /// at the point when `self` was created).
    ///
    /// This will always return a non-[`None`] value, even if the task's
    /// context is the default [`glib::MainContext`][crate::glib::MainContext].
    ///
    /// # Returns
    ///
    /// `self`'s [`glib::MainContext`][crate::glib::MainContext]
    #[doc(alias = "g_task_get_context")]
    #[doc(alias = "get_context")]
    pub fn context(&self) -> glib::MainContext {
        unsafe { from_glib_none(ffi::g_task_get_context(self.to_glib_none().0)) }
    }

    /// Gets `self`’s name. See [`set_name()`][Self::set_name()].
    ///
    /// # Returns
    ///
    /// `self`’s name, or [`None`]
    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    #[doc(alias = "g_task_get_name")]
    #[doc(alias = "get_name")]
    pub fn name(&self) -> Option<glib::GString> {
        unsafe { from_glib_none(ffi::g_task_get_name(self.to_glib_none().0)) }
    }

    /// Gets `self`'s return-on-cancel flag. See
    /// [`set_return_on_cancel()`][Self::set_return_on_cancel()] for more details.
    #[doc(alias = "g_task_get_return_on_cancel")]
    #[doc(alias = "get_return_on_cancel")]
    pub fn is_return_on_cancel(&self) -> bool {
        unsafe { from_glib(ffi::g_task_get_return_on_cancel(self.to_glib_none().0)) }
    }

    //#[doc(alias = "g_task_get_source_tag")]
    //#[doc(alias = "get_source_tag")]
    //pub fn source_tag(&self) -> /*Unimplemented*/Option<Fundamental: Pointer> {
    //    unsafe { TODO: call ffi:g_task_get_source_tag() }
    //}

    //#[doc(alias = "g_task_get_task_data")]
    //#[doc(alias = "get_task_data")]
    //pub fn task_data(&self) -> /*Unimplemented*/Option<Fundamental: Pointer> {
    //    unsafe { TODO: call ffi:g_task_get_task_data() }
    //}

    /// Tests if `self` resulted in an error.
    ///
    /// # Returns
    ///
    /// [`true`] if the task resulted in an error, [`false`] otherwise.
    #[doc(alias = "g_task_had_error")]
    pub fn had_error(&self) -> bool {
        unsafe { from_glib(ffi::g_task_had_error(self.to_glib_none().0)) }
    }

    /// Checks if `self`'s [`Cancellable`][crate::Cancellable] has been cancelled, and if so, sets
    /// `self`'s error accordingly and completes the task (see
    /// `g_task_return_pointer()` for more discussion of exactly what this
    /// means).
    ///
    /// # Returns
    ///
    /// [`true`] if `self` has been cancelled, [`false`] if not
    #[doc(alias = "g_task_return_error_if_cancelled")]
    pub fn return_error_if_cancelled(&self) -> bool {
        unsafe { from_glib(ffi::g_task_return_error_if_cancelled(self.to_glib_none().0)) }
    }

    //#[doc(alias = "g_task_return_new_error")]
    //pub fn return_new_error(&self, domain: glib::Quark, code: i32, format: &str, : /*Unknown conversion*//*Unimplemented*/Fundamental: VarArgs) {
    //    unsafe { TODO: call ffi:g_task_return_new_error() }
    //}

    //#[doc(alias = "g_task_run_in_thread")]
    //pub fn run_in_thread(&self, task_func: /*Unimplemented*/FnOnce(&Task, &glib::Object, /*Unimplemented*/Option<Fundamental: Pointer>, Option<&Cancellable>)) {
    //    unsafe { TODO: call ffi:g_task_run_in_thread() }
    //}

    //#[doc(alias = "g_task_run_in_thread_sync")]
    //pub fn run_in_thread_sync(&self, task_func: /*Unimplemented*/FnOnce(&Task, &glib::Object, /*Unimplemented*/Option<Fundamental: Pointer>, Option<&Cancellable>)) {
    //    unsafe { TODO: call ffi:g_task_run_in_thread_sync() }
    //}

    /// Sets or clears `self`'s check-cancellable flag. If this is [`true`]
    /// (the default), then `g_task_propagate_pointer()`, etc, and
    /// [`had_error()`][Self::had_error()] will check the task's [`Cancellable`][crate::Cancellable] first, and
    /// if it has been cancelled, then they will consider the task to have
    /// returned an "Operation was cancelled" error
    /// ([`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled]), regardless of any other error or return
    /// value the task may have had.
    ///
    /// If `check_cancellable` is [`false`], then the [`Task`][crate::Task] will not check the
    /// cancellable itself, and it is up to `self`'s owner to do this (eg,
    /// via [`return_error_if_cancelled()`][Self::return_error_if_cancelled()]).
    ///
    /// If you are using [`set_return_on_cancel()`][Self::set_return_on_cancel()] as well, then
    /// you must leave check-cancellable set [`true`].
    /// ## `check_cancellable`
    /// whether [`Task`][crate::Task] will check the state of
    ///  its [`Cancellable`][crate::Cancellable] for you.
    #[doc(alias = "g_task_set_check_cancellable")]
    pub fn set_check_cancellable(&self, check_cancellable: bool) {
        unsafe {
            ffi::g_task_set_check_cancellable(self.to_glib_none().0, check_cancellable.into_glib());
        }
    }

    /// Sets `self`’s name, used in debugging and profiling. The name defaults to
    /// [`None`].
    ///
    /// The task name should describe in a human readable way what the task does.
    /// For example, ‘Open file’ or ‘Connect to network host’. It is used to set the
    /// name of the [`glib::Source`][crate::glib::Source] used for idle completion of the task.
    ///
    /// This function may only be called before the `self` is first used in a thread
    /// other than the one it was constructed in.
    /// ## `name`
    /// a human readable name for the task, or [`None`] to unset it
    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    #[doc(alias = "g_task_set_name")]
    pub fn set_name(&self, name: Option<&str>) {
        unsafe {
            ffi::g_task_set_name(self.to_glib_none().0, name.to_glib_none().0);
        }
    }

    /// Sets or clears `self`'s return-on-cancel flag. This is only
    /// meaningful for tasks run via `g_task_run_in_thread()` or
    /// `g_task_run_in_thread_sync()`.
    ///
    /// If `return_on_cancel` is [`true`], then cancelling `self`'s
    /// [`Cancellable`][crate::Cancellable] will immediately cause it to return, as though the
    /// task's `GTaskThreadFunc` had called
    /// [`return_error_if_cancelled()`][Self::return_error_if_cancelled()] and then returned.
    ///
    /// This allows you to create a cancellable wrapper around an
    /// uninterruptible function. The `GTaskThreadFunc` just needs to be
    /// careful that it does not modify any externally-visible state after
    /// it has been cancelled. To do that, the thread should call
    /// [`set_return_on_cancel()`][Self::set_return_on_cancel()] again to (atomically) set
    /// return-on-cancel [`false`] before making externally-visible changes;
    /// if the task gets cancelled before the return-on-cancel flag could
    /// be changed, [`set_return_on_cancel()`][Self::set_return_on_cancel()] will indicate this by
    /// returning [`false`].
    ///
    /// You can disable and re-enable this flag multiple times if you wish.
    /// If the task's [`Cancellable`][crate::Cancellable] is cancelled while return-on-cancel is
    /// [`false`], then calling [`set_return_on_cancel()`][Self::set_return_on_cancel()] to set it [`true`]
    /// again will cause the task to be cancelled at that point.
    ///
    /// If the task's [`Cancellable`][crate::Cancellable] is already cancelled before you call
    /// `g_task_run_in_thread()`/`g_task_run_in_thread_sync()`, then the
    /// `GTaskThreadFunc` will still be run (for consistency), but the task
    /// will also be completed right away.
    /// ## `return_on_cancel`
    /// whether the task returns automatically when
    ///  it is cancelled.
    ///
    /// # Returns
    ///
    /// [`true`] if `self`'s return-on-cancel flag was changed to
    ///  match `return_on_cancel`. [`false`] if `self` has already been
    ///  cancelled.
    #[doc(alias = "g_task_set_return_on_cancel")]
    pub fn set_return_on_cancel(&self, return_on_cancel: bool) -> bool {
        unsafe {
            from_glib(ffi::g_task_set_return_on_cancel(
                self.to_glib_none().0,
                return_on_cancel.into_glib(),
            ))
        }
    }

    //#[doc(alias = "g_task_set_source_tag")]
    //pub fn set_source_tag(&self, source_tag: /*Unimplemented*/Option<Fundamental: Pointer>) {
    //    unsafe { TODO: call ffi:g_task_set_source_tag() }
    //}

    //#[doc(alias = "g_task_set_task_data")]
    //pub fn set_task_data(&self, task_data: /*Unimplemented*/Option<Fundamental: Pointer>) {
    //    unsafe { TODO: call ffi:g_task_set_task_data() }
    //}

    /// Checks that `result` is a [`Task`][crate::Task], and that `source_object` is its
    /// source object (or that `source_object` is [`None`] and `result` has no
    /// source object). This can be used in `g_return_if_fail()` checks.
    /// ## `result`
    /// A [`AsyncResult`][crate::AsyncResult]
    /// ## `source_object`
    /// the source object
    ///  expected to be associated with the task
    ///
    /// # Returns
    ///
    /// [`true`] if `result` and `source_object` are valid, [`false`]
    /// if not
    #[doc(alias = "g_task_is_valid")]
    pub fn is_valid<P: IsA<AsyncResult>, Q: IsA<glib::Object>>(
        result: &P,
        source_object: Option<&Q>,
    ) -> bool {
        unsafe {
            from_glib(ffi::g_task_is_valid(
                result.as_ref().to_glib_none().0,
                source_object.map(|p| p.as_ref()).to_glib_none().0,
            ))
        }
    }

    //#[doc(alias = "g_task_report_error")]
    //pub fn report_error<P: FnOnce(Result<(), glib::Error>) + 'static>(source_object: Option<&glib::Object>, callback: P, source_tag: /*Unimplemented*/Option<Fundamental: Pointer>, error: &mut glib::Error) {
    //    unsafe { TODO: call ffi:g_task_report_error() }
    //}

    //#[doc(alias = "g_task_report_new_error")]
    //pub fn report_new_error<P: FnOnce(Result<(), glib::Error>) + 'static>(source_object: Option<&glib::Object>, callback: P, source_tag: /*Unimplemented*/Option<Fundamental: Pointer>, domain: glib::Quark, code: i32, format: &str, : /*Unknown conversion*//*Unimplemented*/Fundamental: VarArgs) {
    //    unsafe { TODO: call ffi:g_task_report_new_error() }
    //}

    #[doc(alias = "completed")]
    pub fn connect_completed_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_completed_trampoline<F: Fn(&Task) + 'static>(
            this: *mut ffi::GTask,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this))
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::completed\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_completed_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

impl fmt::Display for Task {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("Task")
    }
}