ide-task.c 53.9 KB
Newer Older
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 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
/* ide-task.c
 *
 * Copyright 2018 Christian Hergert
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#define G_LOG_DOMAIN "ide-task"

#include <dazzle.h>

#include "threading/ide-task.h"
#include "threading/ide-thread-pool.h"

/**
 * SECTION:ide-task
 * @title: IdeTask
 * @short_description: asynchronous task management
 *
 * #IdeTask is meant to be an improved form of #GTask. There are a few
 * deficiencies in #GTask that have made it unsuitable for certain use cases.
 *
 * #GTask does not provide a way to guarnatee that the source object,
 * task data, and unused results are freed with in a given #GMainContext.
 * #IdeTask addresses this by having a more flexible result and object
 * ownership control.
 *
 * Furthermore, #IdeTask allows consumers to force disposal from a given
 * thread so that the data is released there.
 *
 * #IdeTask also supports chaining tasks together which makes it simpler
 * to avoid doing duplicate work by instead simply chaining the tasks.
 *
 * There are some costs to this design. It uses the main context a bit
 * more than #GTask may use it. Also, an equivalent to
 * g_task_get_source_object() cannot be provided because we do not control
 * the exact lifecycle of that object. g_async_result_get_source_object()
 * may be used which provides a full reference instead of a borrowed
 * reference.
 *
 * #IdeTask uses it's own #GThreadPool, however the threads are not exclusive
 * to increase the chances of thread sharing with other pools.
 *
 * The number of threads in the pool is equivalent to N_CPU*2+1.
 *
 * Because #IdeTask needs more control over result life-cycles (for chaining
 * results), additional return methods have been provided. Consumers should
 * use ide_task_return_boxed() when working with boxed types as it allows us
 * to copy the result to another task. Additionally, ide_task_return_object()
 * provides a simplified API over ide_task_return_pointer() which also allows
 * copying the result to chained tasks.
 *
 * Since: 3.28
 */

typedef struct
{
  /*
   * The pointer we were provided.
   */
  gpointer data;

  /*
   * The destroy notify for @data. We should only call this from the
   * main context associated with the task.
   */
  GDestroyNotify data_destroy;
} IdeTaskData;

typedef enum
{
  IDE_TASK_RESULT_NONE,
  IDE_TASK_RESULT_CANCELLED,
  IDE_TASK_RESULT_BOOLEAN,
  IDE_TASK_RESULT_INT,
  IDE_TASK_RESULT_ERROR,
  IDE_TASK_RESULT_OBJECT,
  IDE_TASK_RESULT_BOXED,
  IDE_TASK_RESULT_POINTER,
} IdeTaskResultType;

typedef struct
{
  /*
   * The type of result stored in our union @u.
   */
  IdeTaskResultType type;

  /*
   * To ensure that we can pass ownership back to the main context
   * from our worker thread, we need to be able to stash the reference
   * here in our result. It is also convenient as we need access to it
   * from the main context callback anyway.
   */
  IdeTask *task;

  /*
   * Additionally, we need to allow passing our main context reference
   * back so that it cannot be finalized in our thread.
   */
  GMainContext *main_context;

  /*
   * Priority for our GSource attached to @main_context.
   */
  gint priority;

  /*
   * The actual result information, broken down by result @type.
   */
  union {
    gboolean  v_bool;
    gssize    v_int;
    GError   *v_error;
    GObject  *v_object;
    struct {
      GType    type;
      gpointer pointer;
    } v_boxed;
    struct {
      gpointer       pointer;
      GDestroyNotify destroy;
    } v_pointer;
  } u;
} IdeTaskResult;

typedef struct
{
  IdeTask      *task;
  GMainContext *main_context;
  gint          priority;
} IdeTaskCancel;

typedef struct
{
  /*
   * Controls access to our private data. We only access structure
   * data while holding this mutex to ensure that we have consistency
   * between threads which could be accessing internals.
   */
  GMutex mutex;

  /*
   * The source object for the GAsyncResult interface. If we have set
   * release_on_propagate, this will be released when the task propagate
   * function is called.
   */
  gpointer source_object;

  /*
   * The cancellable that we're monitoring for task cancellation.
   */
  GCancellable *cancellable;

  /*
   * If ide_task_set_return_on_cancel() has been set, then we might be
   * listening for changes. Handling this will queue a completion
   */
  gulong cancel_handler;

  /*
   * The callback to execute upon completion of the operation. It will
   * be called from @main_contect after the operation completes.
   */
  GAsyncReadyCallback callback;
  gpointer user_data;

  /*
   * The name for the task. This string is interned so you should not
   * use dynamic names. They are meant to simplify the process of
   * debugging what task failed.
   */
  const gchar *name;

  /*
   * The GMainContext that was the thread default when the task was
   * created. Most operations are proxied back to this context so that
   * the consumer does not need to worry about thread safety.
   */
  GMainContext *main_context;

  /*
   * The task data that has been set for the task. Task data is released
   * from a callback in the #GMainContext if changed outside the main
   * context.
   */
  IdeTaskData *task_data;

  /*
   * The result for the task. If release_on_propagate as set to %FALSE,
   * then this may be kept around so that ide_task_chain() can be used to
   * duplicate the result to another task. This is convenient when multiple
   * async funcs race to do some work, allowing just a single winner with all
   * the callers getting the same result.
   */
  IdeTaskResult *result;

  /*
   * ide_task_chain() allows us to propagate the result of this task to
   * another task (for a limited number of result types). This is the
   * list of those tasks.
   */
  GPtrArray *chained;

  /*
   * If ide_task_run_in_thread() is called, this will be set to the func
   * that should be called from within the thread.
   */
  IdeTaskThreadFunc thread_func;

  /*
   * If we're running in a thread, we'll stash the value here until we
   * can complete things cleanly and pass ownership back as one operation.
   */
  IdeTaskResult *thread_result;

  /*
   * The source tag for the task, which can be used to determine what
   * the task is from a debugger as well as to verify correctness
   * in async finish functions.
   */
  gpointer source_tag;

  /*
   * Our priority for scheduling tasks in the particular workqueue.
   */
  gint priority;

  /*
   * While we're waiting for our return callback, this is set to our
   * source id. We use that to know we need to block on the main loop
   * in case the user calls ide_task_propagate_*() synchronously without
   * round-triping to the main loop.
   */
  guint return_source;

  /*
   * Our kind of task, which is used to determine what thread pool we
   * can use when running threaded work. This can be used to help choke
   * lots of work down to a relatively small number of threads.
   */
  IdeTaskKind kind : 8;

  /*
   * If the task has been completed, which is to say that the callback
   * dispatch has occurred in @main_context.
   */
  guint completed : 1;

  /*
   * If we should check @cancellable before returning the result. If set
   * to true, and the cancellable was cancelled, an error will be returned
   * even if the task completed successfully.
   */
  guint check_cancellable : 1;

  /*
   * If we should synthesize completion from a GCancellable::cancelled
   * event instead of waiting for the task to complete normally.
   */
  guint return_on_cancel : 1;

  /*
   * If we should release the source object and task data after we've
   * dispatched the callback (or the callback was NULL). This allows us
   * to ensure that various dependent data are released in the main
   * context. This is the default and helps ensure thread-safety.
   */
  guint release_on_propagate : 1;

  /*
   * Protect against multiple return calls, and given the developer a good
   * warning so they catch this early.
   */
  guint return_called : 1;

  /*
   * If we got a result that was a cancellation, then we mark it here so
   * that we can deal with it cleanly later.
   */
  guint got_cancel : 1;

  /*
   * If we have dispatched to a thread already.
   */
  guint thread_called : 1;

} IdeTaskPrivate;

static void     async_result_init_iface (GAsyncResultIface *iface);
static void     ide_task_data_free      (IdeTaskData       *task_data);
static void     ide_task_result_free    (IdeTaskResult     *result);
static gboolean ide_task_return_cb      (gpointer           user_data);
static void     ide_task_release        (IdeTask           *self,
                                         gboolean           force);

G_DEFINE_AUTOPTR_CLEANUP_FUNC (IdeTaskData, ide_task_data_free);
G_DEFINE_AUTOPTR_CLEANUP_FUNC (IdeTaskResult, ide_task_result_free);

DZL_DEFINE_COUNTER (instances, "Tasks", "Instances", "Number of active tasks")

G_DEFINE_TYPE_WITH_CODE (IdeTask, ide_task, G_TYPE_OBJECT,
                         G_ADD_PRIVATE (IdeTask)
                         G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_RESULT, async_result_init_iface))

enum {
  PROP_0,
  PROP_COMPLETED,
  N_PROPS
};

static GParamSpec *properties [N_PROPS];

static void
ide_task_cancel_free (IdeTaskCancel *cancel)
{
  g_clear_pointer (&cancel->main_context, g_main_context_unref);
  g_clear_object (&cancel->task);
  g_slice_free (IdeTaskCancel, cancel);
}

static const gchar *
result_type_name (IdeTaskResultType type)
{
  switch (type)
    {
    case IDE_TASK_RESULT_NONE:
      return "none";

    case IDE_TASK_RESULT_CANCELLED:
      return "cancelled";

    case IDE_TASK_RESULT_INT:
      return "int";

    case IDE_TASK_RESULT_POINTER:
      return "pointer";

    case IDE_TASK_RESULT_OBJECT:
      return "object";

    case IDE_TASK_RESULT_BOXED:
      return "boxed";

    case IDE_TASK_RESULT_BOOLEAN:
      return "boolean";

    case IDE_TASK_RESULT_ERROR:
      return "error";

    default:
      return NULL;
    }
}

static void
ide_task_data_free (IdeTaskData *task_data)
{
  if (task_data->data_destroy != NULL)
    task_data->data_destroy (task_data->data);
  g_slice_free (IdeTaskData, task_data);
}

static IdeTaskResult *
ide_task_result_copy (const IdeTaskResult *src)
{
  IdeTaskResult *dst;

  dst = g_slice_new0 (IdeTaskResult);
  dst->type = src->type;

  switch (src->type)
    {
    case IDE_TASK_RESULT_INT:
      dst->u.v_int = src->u.v_int;
      break;

    case IDE_TASK_RESULT_BOOLEAN:
      dst->u.v_bool = src->u.v_bool;
      break;

    case IDE_TASK_RESULT_ERROR:
      dst->u.v_error = g_error_copy (src->u.v_error);
      break;

    case IDE_TASK_RESULT_OBJECT:
      dst->u.v_object = src->u.v_object ? g_object_ref (src->u.v_object) : NULL;
      break;

    case IDE_TASK_RESULT_BOXED:
      dst->u.v_boxed.type = src->u.v_boxed.type;
      dst->u.v_boxed.pointer = g_boxed_copy (src->u.v_boxed.type, src->u.v_boxed.pointer);
      break;

    case IDE_TASK_RESULT_POINTER:
      g_critical ("Cannot proxy raw pointers for task results");
      break;

    case IDE_TASK_RESULT_CANCELLED:
    case IDE_TASK_RESULT_NONE:
    default:
      break;
    }

  return g_steal_pointer (&dst);
}

static void
ide_task_result_free (IdeTaskResult *result)
{
  if (result == NULL)
    return;

  switch (result->type)
    {
    case IDE_TASK_RESULT_POINTER:
      if (result->u.v_pointer.destroy)
        result->u.v_pointer.destroy (result->u.v_pointer.pointer);
      break;

    case IDE_TASK_RESULT_ERROR:
      g_error_free (result->u.v_error);
      break;

    case IDE_TASK_RESULT_BOXED:
      if (result->u.v_boxed.pointer)
        g_boxed_free (result->u.v_boxed.type, result->u.v_boxed.pointer);
      break;

    case IDE_TASK_RESULT_OBJECT:
      g_clear_object (&result->u.v_object);
      break;

    case IDE_TASK_RESULT_BOOLEAN:
    case IDE_TASK_RESULT_INT:
    case IDE_TASK_RESULT_NONE:
    case IDE_TASK_RESULT_CANCELLED:
    default:
      break;
    }

  g_clear_object (&result->task);
  g_clear_pointer (&result->main_context, g_main_context_unref);
  g_slice_free (IdeTaskResult, result);
}

/*
 * ide_task_complete:
 * @result: (transfer full): the result to complete
 *
 * queues the completion for the task. make sure that you've
 * set the result->task, main_context, and priority first.
 *
 * This is designed to allow stealing the last reference from
 * a worker thread and pass it back to the main context.
 *
 * Returns: a gsource identifier
 */
static guint
ide_task_complete (IdeTaskResult *result)
{
  GSource *source;
  guint ret;

  g_assert (result != NULL);
  g_assert (IDE_IS_TASK (result->task));
  g_assert (result->main_context);

  source = g_idle_source_new ();
  g_source_set_name (source, "[ide-task] complete result");
  g_source_set_ready_time (source, -1);
  g_source_set_callback (source, ide_task_return_cb, result, NULL);
  g_source_set_priority (source, result->priority);
  ret = g_source_attach (source, result->main_context);
  g_source_unref (source);

  return ret;
}

static void
ide_task_thread_func (gpointer data)
{
  g_autoptr(GObject) source_object = NULL;
  g_autoptr(GCancellable) cancellable = NULL;
  g_autoptr(IdeTask) task = data;
  IdeTaskPrivate *priv = ide_task_get_instance_private (task);
  gpointer task_data = NULL;
  IdeTaskThreadFunc thread_func;

  g_assert (IDE_IS_TASK (task));

  g_mutex_lock (&priv->mutex);
  source_object = priv->source_object ? g_object_ref (priv->source_object) : NULL;
  cancellable = priv->cancellable ? g_object_ref (priv->cancellable) : NULL;
  if (priv->task_data)
    task_data = priv->task_data->data;
  thread_func = priv->thread_func;
  priv->thread_func = NULL;
  g_mutex_unlock (&priv->mutex);

  g_assert (thread_func != NULL);

  thread_func (task, source_object, task_data, cancellable);

  g_clear_object (&source_object);
  g_clear_object (&cancellable);

  g_mutex_lock (&priv->mutex);

  /*
   * We've delayed our ide_task_return() until we reach here, so now
   * we can steal our object instance and complete the task along with
   * ensuring the object wont be finalized from this thread.
   */
  if (priv->thread_result)
    {
      IdeTaskResult *result = g_steal_pointer (&priv->thread_result);

      g_assert (result->task == task);
      g_clear_object (&result->task);
      result->task = g_steal_pointer (&task);

      priv->return_source = ide_task_complete (g_steal_pointer (&result));

      g_assert (source_object == NULL);
      g_assert (cancellable == NULL);
      g_assert (task == NULL);
    }
  else
    {
      /* The task did not return a value while in the thread func!  GTask
       * doesn't support this, but its useful to us in a number of ways, so
       * we'll begrudgingly support it but the best we can do is drop our
       * reference from the thread.
       */
    }

  g_mutex_unlock (&priv->mutex);

  g_assert (source_object == NULL);
  g_assert (cancellable == NULL);
  g_assert (task == NULL);
}

static void
ide_task_dispose (GObject *object)
{
  IdeTask *self = (IdeTask *)object;
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  g_assert (IDE_IS_TASK (self));

  ide_task_release (self, TRUE);

  g_mutex_lock (&priv->mutex);
  g_clear_pointer (&priv->result, ide_task_result_free);
  g_mutex_unlock (&priv->mutex);

  G_OBJECT_CLASS (ide_task_parent_class)->dispose (object);
}

static void
ide_task_finalize (GObject *object)
{
  IdeTask *self = (IdeTask *)object;
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  if (!priv->return_called)
    g_critical ("%s [%s] finalized before completing",
                G_OBJECT_TYPE_NAME (self),
                priv->name ?: "unnamed");
  else if (priv->chained && priv->chained->len)
    g_critical ("%s [%s] finalized before dependents were notified",
                G_OBJECT_TYPE_NAME (self),
                priv->name ?: "unnamed");
  else if (priv->thread_func)
    g_critical ("%s [%s] finalized while thread_func is active",
                G_OBJECT_TYPE_NAME (self),
                priv->name ?: "unnamed");
  else if (!priv->completed)
    g_critical ("%s [%s] finalized before completion",
                G_OBJECT_TYPE_NAME (self),
                priv->name ?: "unnamed");

  g_assert (priv->return_source == 0);
  g_assert (priv->result == NULL);
  g_assert (priv->task_data == NULL);
  g_assert (priv->source_object == NULL);
  g_assert (priv->chained == NULL);
  g_assert (priv->thread_result == NULL);

  g_clear_pointer (&priv->main_context, g_main_context_unref);
  g_clear_object (&priv->cancellable);
  g_mutex_clear (&priv->mutex);

  G_OBJECT_CLASS (ide_task_parent_class)->finalize (object);

  DZL_COUNTER_DEC (instances);
}

static void
ide_task_get_property (GObject    *object,
                       guint       prop_id,
                       GValue     *value,
                       GParamSpec *pspec)
{
  IdeTask *self = IDE_TASK (object);

  switch (prop_id)
    {
    case PROP_COMPLETED:
      g_value_set_boolean (value, ide_task_get_completed (self));
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
    }
}

static void
ide_task_class_init (IdeTaskClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->dispose = ide_task_dispose;
  object_class->finalize = ide_task_finalize;
  object_class->get_property = ide_task_get_property;

  properties [PROP_COMPLETED] =
    g_param_spec_boolean ("completed",
                          "Completed",
                          "If the task has completed",
                          FALSE,
                          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

  g_object_class_install_properties (object_class, N_PROPS, properties);
}

static void
ide_task_init (IdeTask *self)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  DZL_COUNTER_INC (instances);

  g_mutex_init (&priv->mutex);

  priv->check_cancellable = TRUE;
  priv->release_on_propagate = TRUE;
  priv->priority = G_PRIORITY_DEFAULT;
  priv->main_context = g_main_context_ref_thread_default ();
}

/**
 * ide_task_get_source_object: (skip)
 * @self: a #IdeTask
 *
 * Gets the #GObject used when creating the source object.
 *
 * As this does not provide ownership transfer of the #GObject, it is a
 * programmer error to call this function outside of a thread worker called
 * from ide_task_run_in_thread() or outside the #GMainContext that is
 * associated with the task.
 *
 * If you need to access the object in other scenarios, you must use the
 * g_async_result_get_source_object() which provides a full reference to the
 * source object, safely. You are responsible for ensuring that you do not
 * release the object in a manner that is unsafe for the source object.
 *
 * Returns: (transfer none) (nullable) (type GObject.Object): a #GObject or %NULL
 *
 * Since: 3.28
 */
gpointer
ide_task_get_source_object (IdeTask *self)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  gpointer ret;

  g_return_val_if_fail (IDE_IS_TASK (self), NULL);

  g_mutex_lock (&priv->mutex);
  ret = priv->source_object;
  g_mutex_unlock (&priv->mutex);

  return ret;
}

/**
 * ide_task_new:
 * @source_object: (type GObject.Object) (nullable): a #GObject or %NULL
 * @cancellable: (nullable): a #GCancellable or %NULL
 * @callback: (scope async) (nullable): a #GAsyncReadyCallback or %NULL
 * @user_data: closure data for @callback
 *
 * Creates a new #IdeTask.
 *
 * #IdeTask is similar to #GTask but provides some additional guarantees
 * such that by default, the source object, task data, and unused results
 * are guaranteed to be finalized in the #GMainContext associated with
 * the task itself.
 *
 * Returns: (transfer full): an #IdeTask
 *
 * Since: 3.28
 */
IdeTask *
(ide_task_new) (gpointer             source_object,
                GCancellable        *cancellable,
                GAsyncReadyCallback  callback,
                gpointer             user_data)
{
  g_autoptr(IdeTask) self = NULL;
  IdeTaskPrivate *priv;

  g_return_val_if_fail (!source_object || G_IS_OBJECT (source_object), NULL);
  g_return_val_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable), NULL);

  self = g_object_new (IDE_TYPE_TASK, NULL);
  priv = ide_task_get_instance_private (self);

  priv->source_object = source_object ? g_object_ref (source_object) : NULL;
  priv->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
  priv->callback = callback;
  priv->user_data = user_data;

  return g_steal_pointer (&self);
}

/**
 * ide_task_is_valid:
 * @self: (nullable) (type Ide.Task): a #IdeTask
 * @source_object: (nullable): a #GObject or %NULL
 *
 * Checks if @source_object matches the object the task was created with.
 *
 * Returns: %TRUE is source_object matches
 *
 * Since: 3.28
 */
gboolean
ide_task_is_valid (gpointer self,
                   gpointer source_object)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  return IDE_IS_TASK (self) && priv->source_object == source_object;
}

/**
 * ide_task_get_completed:
 * @self: a #IdeTask
 *
 * Gets the "completed" property. This is %TRUE after the callback used when
 * creating the task has been executed.
 *
 * The property will be notified using g_object_notify() exactly once in the
 * same #GMainContext as the callback.
 *
 * Returns: %TRUE if the task has completed
 *
 * Since: 3.28
 */
gboolean
ide_task_get_completed (IdeTask *self)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  gboolean ret;

  g_return_val_if_fail (IDE_IS_TASK (self), FALSE);

  g_mutex_lock (&priv->mutex);
  ret = priv->completed;
  g_mutex_unlock (&priv->mutex);

  return ret;
}

gint
ide_task_get_priority (IdeTask *self)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  gint ret;

  g_return_val_if_fail (IDE_IS_TASK (self), 0);

  g_mutex_lock (&priv->mutex);
  ret = priv->priority;
  g_mutex_unlock (&priv->mutex);

  return ret;
}

void
ide_task_set_priority (IdeTask *self,
                       gint     priority)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  g_return_if_fail (IDE_IS_TASK (self));

  g_mutex_lock (&priv->mutex);
  priv->priority = priority;
  g_mutex_unlock (&priv->mutex);
}

/**
 * ide_task_get_cancellable:
 * @self: a #IdeTask
 *
 * Gets the #GCancellable for the task.
 *
 * Returns: (transfer none) (nullable): a #GCancellable or %NULL
 *
 * Since: 3.28
 */
GCancellable *
ide_task_get_cancellable (IdeTask *self)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  g_return_val_if_fail (IDE_IS_TASK (self), NULL);

  return priv->cancellable;
}

static void
ide_task_deliver_result (IdeTask       *self,
                         IdeTaskResult *result)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  g_assert (IDE_IS_TASK (self));
  g_assert (result != NULL);
  g_assert (result->task == NULL);
  g_assert (result->main_context == NULL);

  /* This task was chained from another task. This completes the result
   * and we should dispatch the callback. To simplify the dispatching and
   * help prevent any re-entrancy issues, we defer back to the main context
   * to complete the operation.
   */

  result->task = g_object_ref (self);
  result->main_context = g_main_context_ref (priv->main_context);
  result->priority = priv->priority;

  g_mutex_lock (&priv->mutex);

  priv->return_called = TRUE;
  priv->return_source = ide_task_complete (g_steal_pointer (&result));

  g_mutex_unlock (&priv->mutex);
}

static void
ide_task_release (IdeTask  *self,
                  gboolean  force)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  g_autoptr(IdeTaskData) task_data = NULL;
  g_autoptr(GObject) source_object = NULL;
  g_autoptr(GPtrArray) chained = NULL;

  g_assert (IDE_IS_TASK (self));

  g_mutex_lock (&priv->mutex);
  if (force || priv->release_on_propagate)
    {
      source_object = g_steal_pointer (&priv->source_object);
      task_data = g_steal_pointer (&priv->task_data);
      chained = g_steal_pointer (&priv->chained);
    }
  g_mutex_unlock (&priv->mutex);

  if (chained)
    {
      for (guint i = 0; i < chained->len; i++)
        {
          IdeTask *task = g_ptr_array_index (chained, i);

          ide_task_return_new_error (task,
                                     G_IO_ERROR,
                                     G_IO_ERROR_FAILED,
                                     "Error synthesized for task, parent task disposed");
        }
    }
}

static gboolean
ide_task_return_cb (gpointer user_data)
{
  g_autoptr(IdeTask) self = NULL;
  g_autoptr(IdeTaskResult) result = user_data;
  g_autoptr(IdeTaskResult) result_copy = NULL;
  g_autoptr(GCancellable) cancellable = NULL;
  g_autoptr(GObject) source_object = NULL;
  g_autoptr(GPtrArray) chained = NULL;
  GAsyncReadyCallback callback = NULL;
  gpointer callback_data = NULL;
  IdeTaskPrivate *priv;

  g_assert (result != NULL);
  g_assert (IDE_IS_TASK (result->task));

  /* We steal the task object, because we only stash it in the result
   * structure to get it here. And if we held onto it, we would have
   * a reference cycle.
   */
  self = g_steal_pointer (&result->task);
  priv = ide_task_get_instance_private (self);

  g_mutex_lock (&priv->mutex);

  g_assert (priv->return_source != 0);

  priv->return_source = 0;

  if (priv->got_cancel && priv->result != NULL)
    {
      /* We can discard this since we already handled a result for the
       * task. We delivered this here just so that we could finalize
       * any objects back inside them main context.
       */
      g_mutex_unlock (&priv->mutex);
      return G_SOURCE_REMOVE;
    }

  g_assert (priv->result == NULL);
  g_assert (priv->return_called == TRUE);

  priv->result = g_steal_pointer (&result);

  callback = priv->callback;
  callback_data = priv->user_data;

  priv->callback = NULL;
  priv->user_data = NULL;

  source_object = priv->source_object ? g_object_ref (priv->source_object) : NULL;
  cancellable = priv->cancellable ? g_object_ref (priv->cancellable) : NULL;

  chained = g_steal_pointer (&priv->chained);

  /* Make a private copy of the result data if we're going to need to notify
   * other tasks of our result. We can't guarantee the result in @task will
   * stay alive during our dispatch callbacks, so we need to have a copy.
   */
  if (chained != NULL && chained->len > 0)
    result_copy = ide_task_result_copy (priv->result);

  g_mutex_unlock (&priv->mutex);

  if (callback)
    callback (source_object, G_ASYNC_RESULT (self), callback_data);

  if (chained)
    {
      for (guint i = 0; i < chained->len; i++)
        {
          IdeTask *other = g_ptr_array_index (chained, i);
          g_autoptr(IdeTaskResult) other_result = ide_task_result_copy (result_copy);

          ide_task_deliver_result (other, g_steal_pointer (&other_result));
        }
    }

  g_mutex_lock (&priv->mutex);
  priv->completed = TRUE;
  g_mutex_unlock (&priv->mutex);

  g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_COMPLETED]);

  ide_task_release (self, FALSE);

  return G_SOURCE_REMOVE;
}

static void
ide_task_return (IdeTask       *self,
                 IdeTaskResult *result)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  g_autoptr(GMutexLocker) locker = NULL;

  g_assert (IDE_IS_TASK (self));
  g_assert (result != NULL);
  g_assert (result->task == NULL);

  locker = g_mutex_locker_new (&priv->mutex);

  if (priv->cancel_handler && priv->cancellable)
    {
      g_cancellable_disconnect (priv->cancellable, priv->cancel_handler);
      priv->cancel_handler = 0;
    }

  if (priv->return_called)
    {
      if (result->type == IDE_TASK_RESULT_CANCELLED)
        {
1014 1015 1016
          /* We already had a result, and now raced to be notified of
           * cancellation. We can safely free this result even if we're
           * currently in a worker thread.
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
           */
          ide_task_result_free (result);
          return;
        }

      /*
       * We already failed this task, but we need to ensure that the data
       * is released from the main context rather than potentially on a
       * thread (as we could be now).
       *
       * Since this can only happen when return_on_cancel is set, we can
       * be assured the main context is alive because that is our contract
       * with the API consumer.
       */
      if (!priv->got_cancel)
        {
          /* leak result to ensure we don't free anything in the wrong context */
          g_critical ("Attempted to set task result multiple times, leaking result");
          return;
        }
    }

  priv->return_called = TRUE;

  if (result->type == IDE_TASK_RESULT_CANCELLED)
    priv->got_cancel = TRUE;

  result->task = g_object_ref (self);
  result->main_context = g_main_context_ref (priv->main_context);
  result->priority = priv->priority;

  /* We can queue the result immediately if we're not being called
   * while we're inside of a ide_task_run_in_thread() callback. Otherwise,
   * that thread cleanup must complete this to ensure objects cannot
   * be finalized in that thread.
   */
  if (!priv->thread_called)
    priv->return_source = ide_task_complete (result);
  else if (priv->return_on_cancel && result->type == IDE_TASK_RESULT_CANCELLED)
    priv->return_source = ide_task_complete (result);
  else
    priv->thread_result = result;
}

/**
 * ide_task_return_int:
 * @self: a #IdeTask
 * @result: the result for the task
 *
 * Sets the result of the task to @result.
 *
 * Other tasks depending on the result will be notified after returning
 * to the #GMainContext of the task.
 *
 * Since: 3.28
 */
void
ide_task_return_int (IdeTask *self,
                     gssize   result)
{
  IdeTaskResult *ret;

  g_return_if_fail (IDE_IS_TASK (self));

  ret = g_slice_new0 (IdeTaskResult);
  ret->type = IDE_TASK_RESULT_INT;
  ret->u.v_int = result;

  ide_task_return (self, g_steal_pointer (&ret));
}

/**
 * ide_task_return_boolean:
 * @self: a #IdeTask
 * @result: the result for the task
 *
 * Sets the result of the task to @result.
 *
 * Other tasks depending on the result will be notified after returning
 * to the #GMainContext of the task.
 *
 * Since: 3.28
 */
void
ide_task_return_boolean (IdeTask  *self,
                         gboolean  result)
{
  IdeTaskResult *ret;

  g_return_if_fail (IDE_IS_TASK (self));

  ret = g_slice_new0 (IdeTaskResult);
  ret->type = IDE_TASK_RESULT_BOOLEAN;
  ret->u.v_bool = !!result;

  ide_task_return (self, g_steal_pointer (&ret));
}

void
ide_task_return_boxed (IdeTask  *self,
                       GType     result_type,
                       gpointer  result)
{
  IdeTaskResult *ret;

  g_return_if_fail (IDE_IS_TASK (self));
  g_return_if_fail (result_type != G_TYPE_INVALID);
  g_return_if_fail (G_TYPE_IS_BOXED (result_type));

  ret = g_slice_new0 (IdeTaskResult);
  ret->type = IDE_TASK_RESULT_BOXED;
  ret->u.v_boxed.type = result_type;
  ret->u.v_boxed.pointer = result;

  ide_task_return (self, g_steal_pointer (&ret));
}

/**
 * ide_task_return_object:
 * @self: a #IdeTask
 * @instance: (transfer full): a #GObject instance
 *
 * Returns a new object instance.
 *
 * Takes ownership of @instance to allow saving a reference increment and
 * decrement by the caller.
 *
 * Since: 3.28
 */
void
ide_task_return_object (IdeTask  *self,
                        gpointer  instance)
{
  IdeTaskResult *ret;

  g_return_if_fail (IDE_IS_TASK (self));
  g_return_if_fail (!instance || G_IS_OBJECT (instance));

  ret = g_slice_new0 (IdeTaskResult);
  ret->type = IDE_TASK_RESULT_OBJECT;
  ret->u.v_object = instance;

  ide_task_return (self, g_steal_pointer (&ret));
}

/**
 * ide_task_return_pointer: (skip)
 * @self: a #IdeTask
 * @data: the data to return
 * @destroy: an optional #GDestroyNotify to cleanup data if no handler
 *   propagates the result
 *
 * Returns a new raw pointer.
 *
 * Note that pointers cannot be chained to other tasks, so you may not
 * use ide_task_chain() in conjunction with a task returning a pointer
 * using ide_task_return_pointer().
 *
 * If you need task chaining with pointers, see ide_task_return_boxed()
 * or ide_task_return_object().
 *
 * Since: 3.28
 */
void
ide_task_return_pointer (IdeTask        *self,
                         gpointer        data,
                         GDestroyNotify  destroy)
{
  IdeTaskResult *ret;

  g_return_if_fail (IDE_IS_TASK (self));

  ret = g_slice_new0 (IdeTaskResult);
  ret->type = IDE_TASK_RESULT_POINTER;
  ret->u.v_pointer.pointer = data;
  ret->u.v_pointer.destroy = destroy;

  ide_task_return (self, g_steal_pointer (&ret));
}

/**
 * ide_task_return_error:
 * @self: a #IdeTask
 * @error: (transfer full): a #GError
 *
 * Sets @error as the result of the #IdeTask
 *
 * Since: 3.28
 */
void
ide_task_return_error (IdeTask *self,
                       GError  *error)
{
  IdeTaskResult *ret;

  g_return_if_fail (IDE_IS_TASK (self));

  ret = g_slice_new0 (IdeTaskResult);
  ret->type = IDE_TASK_RESULT_ERROR;
  ret->u.v_error = error;

  ide_task_return (self, g_steal_pointer (&ret));
}

/**
 * ide_task_return_new_error:
 * @self: a #IdeTask
 * @error_domain: the error domain of the #GError
 * @error_code: the error code for the #GError
 * @format: the printf-style format string
 *
 * Creates a new #GError and sets it as the result for the task.
 *
 * Since: 3.28
 */
void
ide_task_return_new_error (IdeTask     *self,
                           GQuark       error_domain,
                           gint         error_code,
                           const gchar *format,
                           ...)
{
  GError *error;
  va_list args;

  g_return_if_fail (IDE_IS_TASK (self));

  va_start (args, format);
  error = g_error_new_valist (error_domain, error_code, format, args);
  va_end (args);

  ide_task_return_error (self, g_steal_pointer (&error));
}

/**
 * ide_task_return_error_if_cancelled:
 * @self: a #IdeTask
 *
 * Returns a new #GError if the cancellable associated with the task
 * has been cancelled. If so, %TRUE is returned, otherwise %FALSE.
 *
 * Returns: %TRUE if the task was cancelled and error returned.
 *
 * Since: 3.28
 */
gboolean
ide_task_return_error_if_cancelled (IdeTask *self)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  gboolean failed;

  g_return_val_if_fail (IDE_IS_TASK (self), FALSE);

  g_mutex_lock (&priv->mutex);
  failed = g_cancellable_is_cancelled (priv->cancellable);
  g_mutex_unlock (&priv->mutex);

  if (failed)
    ide_task_return_new_error (self,
                               G_IO_ERROR,
                               G_IO_ERROR_CANCELLED,
                               "The task was cancelled");

  return failed;
}

/**
 * ide_task_set_release_on_propagate:
 * @self: a #IdeTask
 * @release_on_propagate: if data should be released on propagate
 *
 * Setting this to %TRUE (the default) ensures that the task will release all
 * task data and source_object references after executing the configured
 * callback. This is useful to ensure that dependent objects are finalized
 * in the thread-default #GMainContext the task was created in.
 *
 * Generally, you want to leave this as %TRUE to ensure thread-safety on the
 * dependent objects and task data.
 *
 * Since: 3.28
 */
void
ide_task_set_release_on_propagate (IdeTask  *self,
                                   gboolean  release_on_propagate)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  g_return_if_fail (IDE_IS_TASK (self));

  release_on_propagate = !!release_on_propagate;

  g_mutex_lock (&priv->mutex);
  priv->release_on_propagate = release_on_propagate;
  g_mutex_unlock (&priv->mutex);
}

/**
 * ide_task_set_source_tag:
 * @self: a #IdeTask
 * @source_tag: a tag to identify the task, usual a function pointer
 *
 * Sets the source tag for the task. Generally this is a function pointer
 * of the function that created the task.
 *
 * Since: 3.28
 */
void
ide_task_set_source_tag (IdeTask  *self,
                         gpointer  source_tag)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  g_return_if_fail (IDE_IS_TASK (self));

  g_mutex_lock (&priv->mutex);
  priv->source_tag = source_tag;
  g_mutex_unlock (&priv->mutex);
}

/**
 * ide_task_set_check_cancellable:
 * @self: a #IdeTask
 * @check_cancellable: %TRUE if the cancellable should be checked
 *
 * Setting @check_cancellable to %TRUE (the default) ensures that the
 * #GCancellable used when creating the #IdeTask is checked for cancellation
 * before propagating a result. If cancelled, an error will be returned
 * instead of the result.
 *
 * Since: 3.28
 */
void
ide_task_set_check_cancellable (IdeTask  *self,
                                gboolean  check_cancellable)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  g_return_if_fail (IDE_IS_TASK (self));

  check_cancellable = !!check_cancellable;

  g_mutex_lock (&priv->mutex);
  priv->check_cancellable = check_cancellable;
  g_mutex_unlock (&priv->mutex);
}

/**
 * ide_task_run_in_thread: (skip)
 * @self: a #IdeTask
 * @thread_func: a function to execute on a worker thread
 *
 * Scheules @thread_func to be executed on a worker thread.
 *
 * @thread_func must complete the task from the worker thread using one of
 * ide_task_return_boolean(), ide_task_return_int(), or
 * ide_task_return_pointer().
 *
 * Since: 3.28
 */
void
ide_task_run_in_thread (IdeTask           *self,
                        IdeTaskThreadFunc  thread_func)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  g_autoptr(GError) error = NULL;

  g_return_if_fail (IDE_IS_TASK (self));
  g_return_if_fail (thread_func != NULL);

  g_mutex_lock (&priv->mutex);

  if (priv->completed == TRUE)
    {
      g_critical ("Task already completed, cannot run in thread");
      goto unlock;
    }

  if (priv->thread_called)
    {
      g_critical ("Run in thread already called, cannot run again");
      goto unlock;
    }

  priv->thread_called = TRUE;
  priv->thread_func = thread_func;

  ide_thread_pool_push ((IdeThreadPoolKind)priv->kind,
                        ide_task_thread_func,
                        g_object_ref (self));

unlock:
  g_mutex_unlock (&priv->mutex);

  if (error != NULL)
    ide_task_return_error (self, g_steal_pointer (&error));
}

static IdeTaskResult *
ide_task_propagate_locked (IdeTask            *self,
                           IdeTaskResultType   expected_type,
                           GError            **error)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  IdeTaskResult *ret = NULL;

  g_assert (IDE_IS_TASK (self));
  g_assert (expected_type > IDE_TASK_RESULT_NONE);

  if (priv->result == NULL)
    {
      g_autoptr(GMainContext) context = g_main_context_ref (priv->main_context);

      while (priv->return_source)
        {
          g_mutex_unlock (&priv->mutex);
          g_main_context_iteration (context, FALSE);
          g_mutex_lock (&priv->mutex);
        }
    }

  if (priv->result == NULL)
    {
      g_set_error_literal (error,
                           G_IO_ERROR,
                           G_IO_ERROR_FAILED,
                           "No result available for task");
    }
  else if (priv->result->type == IDE_TASK_RESULT_ERROR)
    {
      if (error != NULL)
        *error = g_error_copy (priv->result->u.v_error);
    }
  else if ((priv->check_cancellable && g_cancellable_is_cancelled (priv->cancellable)) ||
           priv->result->type == IDE_TASK_RESULT_CANCELLED)
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_CANCELLED,
                   "The operation was cancelled");
    }
  else if (priv->result->type != expected_type)
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_FAILED,
                   "Task expected result of %s got %s",
                   result_type_name (expected_type),
                   result_type_name (priv->result->type));
    }
  else
    {
      g_assert (priv->result != NULL);
      g_assert (priv->result->type == expected_type);

      if (priv->release_on_propagate)
        ret = g_steal_pointer (&priv->result);
      else
        ret = ide_task_result_copy (priv->result);

      g_assert (ret != NULL);
    }

  return ret;
}

gboolean
ide_task_propagate_boolean (IdeTask  *self,
                            GError  **error)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  g_autoptr(GMutexLocker) locker = NULL;
  g_autoptr(IdeTaskResult) res = NULL;

  g_return_val_if_fail (IDE_IS_TASK (self), FALSE);

  locker = g_mutex_locker_new (&priv->mutex);

  if (!(res = ide_task_propagate_locked (self, IDE_TASK_RESULT_BOOLEAN, error)))
    return FALSE;

  return res->u.v_bool;
}

gpointer
ide_task_propagate_boxed (IdeTask  *self,
                          GError  **error)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  g_autoptr(GMutexLocker) locker = NULL;
  g_autoptr(IdeTaskResult) res = NULL;

  g_return_val_if_fail (IDE_IS_TASK (self), NULL);

  locker = g_mutex_locker_new (&priv->mutex);

  if (!(res = ide_task_propagate_locked (self, IDE_TASK_RESULT_BOXED, error)))
    return NULL;

  return g_boxed_copy (res->u.v_boxed.type, res->u.v_boxed.pointer);
}

gssize
ide_task_propagate_int (IdeTask  *self,
                        GError  **error)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  g_autoptr(GMutexLocker) locker = NULL;
  g_autoptr(IdeTaskResult) res = NULL;

  g_return_val_if_fail (IDE_IS_TASK (self), 0);

  locker = g_mutex_locker_new (&priv->mutex);

  if (!(res = ide_task_propagate_locked (self, IDE_TASK_RESULT_INT, error)))
    return 0;

  return res->u.v_int;
}

gpointer
ide_task_propagate_object (IdeTask  *self,
                           GError  **error)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  g_autoptr(GMutexLocker) locker = NULL;
  g_autoptr(IdeTaskResult) res = NULL;

  g_return_val_if_fail (IDE_IS_TASK (self), NULL);

  locker = g_mutex_locker_new (&priv->mutex);

  if (!(res = ide_task_propagate_locked (self, IDE_TASK_RESULT_OBJECT, error)))
    return NULL;

  return g_steal_pointer (&res->u.v_object);
}

gpointer
ide_task_propagate_pointer (IdeTask  *self,
                            GError  **error)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  g_autoptr(GMutexLocker) locker = NULL;
  g_autoptr(IdeTaskResult) res = NULL;
  gpointer ret;

  g_return_val_if_fail (IDE_IS_TASK (self), NULL);

  locker = g_mutex_locker_new (&priv->mutex);

  if (!(res = ide_task_propagate_locked (self, IDE_TASK_RESULT_POINTER, error)))
    return NULL;

  ret = g_steal_pointer (&res->u.v_pointer.pointer);
  res->u.v_pointer.destroy = NULL;

  return ret;
}

/**
 * ide_task_chain:
 * @self: a #IdeTask
 * @other_task: a #IdeTask
 *
 * Causes the result of @self to also be delivered to @other_task.
 *
 * This API is useful in situations when you want to avoid doing the same
 * work multiple times, and can share the result between mutliple async
 * operations requesting the same work.
 *
 * Users of this API must make sure one of two things is true. Either they
 * have called ide_task_set_release_on_propagate() with @self and set
 * release_on_propagate to %FALSE, or @self has not yet completed.
 *
 * Since: 3.28
 */
void
ide_task_chain (IdeTask *self,
                IdeTask *other_task)
{
  IdeTaskPrivate *self_priv = ide_task_get_instance_private (self);

  g_return_if_fail (IDE_IS_TASK (self));
  g_return_if_fail (IDE_IS_TASK (other_task));
  g_return_if_fail (self != other_task);

  g_mutex_lock (&self_priv->mutex);

  if (self_priv->result)
    {
      IdeTaskResult *copy = ide_task_result_copy (self_priv->result);

      if (copy != NULL)
        ide_task_deliver_result (other_task, g_steal_pointer (&copy));
      else
        ide_task_return_new_error (other_task,
                                   G_IO_ERROR,
                                   G_IO_ERROR_FAILED,
                                   "Result could not be copied to task");
    }
  else
    {
      if (self_priv->chained == NULL)
        self_priv->chained = g_ptr_array_new_with_free_func (g_object_unref);
      g_ptr_array_add (self_priv->chained, g_object_ref (other_task));
    }

  g_mutex_unlock (&self_priv->mutex);
}

gpointer
ide_task_get_source_tag (IdeTask *self)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  gpointer ret;

  g_return_val_if_fail (IDE_IS_TASK (self), NULL);

  g_mutex_lock (&priv->mutex);
  ret = priv->source_tag;
  g_mutex_unlock (&priv->mutex);

  return ret;
}

IdeTaskKind
ide_task_get_kind (IdeTask *self)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  IdeTaskKind kind;

  g_return_val_if_fail (IDE_IS_TASK (self), 0);

  g_mutex_lock (&priv->mutex);
  kind = priv->kind;
  g_mutex_unlock (&priv->mutex);

  return kind;
}

void
ide_task_set_kind (IdeTask     *self,
                   IdeTaskKind  kind)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  g_return_if_fail (IDE_IS_TASK (self));
  g_return_if_fail (kind >= IDE_TASK_KIND_DEFAULT);
  g_return_if_fail (kind < IDE_TASK_KIND_LAST);

  g_mutex_lock (&priv->mutex);
  priv->kind = kind;
  g_mutex_unlock (&priv->mutex);
}

/**
 * ide_task_get_task_data: (skip)
 * @self: a #IdeTask
 *
 * Gets the task data previously set with ide_task_set_task_data().
 *
 * Returns: (transfer none): previously registered task data or %NULL
 *
 * Since: 3.28
 */
gpointer
ide_task_get_task_data (IdeTask *self)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  gpointer task_data = NULL;

  g_assert (IDE_IS_TASK (self));

  g_mutex_lock (&priv->mutex);
  if (priv->task_data)
    task_data = priv->task_data->data;
  g_mutex_unlock (&priv->mutex);

  return task_data;
}

static gboolean
ide_task_set_task_data_cb (gpointer data)
{
  IdeTaskData *task_data = data;
  ide_task_data_free (task_data);
  return G_SOURCE_REMOVE;
}

void
ide_task_set_task_data (IdeTask        *self,
                        gpointer        task_data,
                        GDestroyNotify  task_data_destroy)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  g_autoptr(IdeTaskData) old_task_data = NULL;
  g_autoptr(IdeTaskData) new_task_data = NULL;

  g_return_if_fail (IDE_IS_TASK (self));

  new_task_data = g_slice_new0 (IdeTaskData);
  new_task_data->data = task_data;
  new_task_data->data_destroy = task_data_destroy;

  g_mutex_lock (&priv->mutex);

  if (priv->return_called)
    {
      g_critical ("Cannot set task data after returning value");
      goto unlock;
    }

  old_task_data = g_steal_pointer (&priv->task_data);
  priv->task_data = g_steal_pointer (&new_task_data);

  if (priv->thread_called && old_task_data)
    {
      GSource *source;

      source = g_idle_source_new ();
      g_source_set_name (source, "[ide-task] finalize task data");
      g_source_set_ready_time (source, -1);
      g_source_set_callback (source,
                             ide_task_set_task_data_cb,
                             NULL, NULL);
      g_source_set_priority (source, priv->priority);
      g_source_attach (source, priv->main_context);
      g_source_unref (source);
    }

unlock:
  g_mutex_unlock (&priv->mutex);
}

static gboolean
ide_task_cancel_cb (gpointer user_data)
{
  IdeTask *self = user_data;
  IdeTaskResult *ret;

  g_assert (IDE_IS_TASK (self));

  ret = g_slice_new0 (IdeTaskResult);
  ret->type = IDE_TASK_RESULT_CANCELLED;

  ide_task_return (self, g_steal_pointer (&ret));

  return G_SOURCE_REMOVE;
}

static void
ide_task_cancellable_cancelled_cb (GCancellable  *cancellable,
                                   IdeTaskCancel *cancel)
{
  GSource *source;

  g_assert (G_IS_CANCELLABLE (cancellable));
  g_assert (cancel != NULL);
  g_assert (IDE_IS_TASK (cancel->task));
  g_assert (cancel->main_context != NULL);

  /*
   * This can be called synchronously from g_cancellable_connect(), which
   * could still be holding priv->mutex. So we need to queue the cancellation
   * request back through the main context.
   */

  source = g_idle_source_new ();
  g_source_set_name (source, "[ide-task] cancel task");
  g_source_set_ready_time (source, -1);
  g_source_set_callback (source, ide_task_cancel_cb, g_object_ref (cancel->task), g_object_unref);
  g_source_set_priority (source, cancel->priority);
  g_source_attach (source, cancel->main_context);
  g_source_unref (source);
}

1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
/**
 * ide_task_get_return_on_cancel:
 * @self: a #IdeTask
 *
 * Gets the return_on_cancel value, which means the task will return
 * immediately when the #GCancellable is cancelled.
 */
gboolean
ide_task_get_return_on_cancel (IdeTask *self)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  gboolean ret;

  g_return_val_if_fail (IDE_IS_TASK (self), FALSE);

  g_mutex_lock (&priv->mutex);
  ret = priv->return_on_cancel;
  g_mutex_unlock (&priv->mutex);

  return ret;
}

1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
/**
 * ide_task_set_return_on_cancel:
 * @self: a #IdeTask
 * @return_on_cancel: if the task should return immediately when the
 *   #GCancellable has been cancelled.
 *
 * Setting @return_on_cancel to %TRUE ensures that the task will cancel
 * immediately when #GCancellable::cancelled is emitted by the configured
 * cancellable.
 *
 * Setting this requires that the caller can ensure the configured #GMainContext
 * will outlive the threaded worker so that task state can be freed in a delayed
 * fashion.
 *
 * Since: 3.28
 */
void
ide_task_set_return_on_cancel (IdeTask  *self,
                               gboolean  return_on_cancel)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  g_autoptr(GMutexLocker) locker = NULL;

  g_return_if_fail (IDE_IS_TASK (self));

  locker = g_mutex_locker_new (&priv->mutex);

  if (priv->cancellable == NULL)
    return;

  return_on_cancel = !!return_on_cancel;

  if (priv->return_on_cancel != return_on_cancel)
    {
      priv->return_on_cancel = return_on_cancel;

      if (return_on_cancel)
        {
          IdeTaskCancel *cancel;

          /* This creates a reference cycle, but it gets destroyed when the
           * appropriate ide_task_return() API is called.
           */
          cancel = g_slice_new0 (IdeTaskCancel);
          cancel->main_context = g_main_context_ref (priv->main_context);
          cancel->task = g_object_ref (self);
          cancel->priority = priv->priority;

          priv->cancel_handler =
            g_cancellable_connect (priv->cancellable,
                                   G_CALLBACK (ide_task_cancellable_cancelled_cb),
                                   g_steal_pointer (&cancel),
                                   (GDestroyNotify)ide_task_cancel_free);

        }
      else
        {
          if (priv->cancel_handler)
            {
              g_cancellable_disconnect (priv->cancellable, priv->cancel_handler);
              priv->cancel_handler = 0;
            }
        }
    }
}

void
ide_task_report_new_error (gpointer              source_object,
                           GAsyncReadyCallback   callback,
                           gpointer              callback_data,
                           gpointer              source_tag,
                           GQuark                domain,
                           gint                  code,
                           const gchar          *format,
                           ...)
{
  g_autoptr(IdeTask) task = NULL;
  GError *error;
  va_list args;

  va_start (args, format);
  error = g_error_new_valist (domain, code, format, args);
  va_end (args);

  task = ide_task_new (source_object, NULL, callback, callback_data);
  ide_task_set_source_tag (task, source_tag);
  ide_task_return_error (task, g_steal_pointer (&error));
}

/**
 * ide_task_get_name:
 * @self: a #IdeTask
 *
 * Gets the name assigned for the task.
 *
 * Returns: (nullable): a string or %NULL
 *
 * Since: 3.28
 */
const gchar *
ide_task_get_name (IdeTask *self)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  const gchar *ret;

  g_return_val_if_fail (IDE_IS_TASK (self), NULL);

  g_mutex_lock (&priv->mutex);
  ret = priv->name;
  g_mutex_unlock (&priv->mutex);

  return ret;
}

/**
 * ide_task_set_name:
 * @self: a #IdeTask
 *
 * Sets a useful name for the task.
 *
 * This string is interned, so it is best to avoid dynamic names as
 * that can result in lots of unnecessary strings being interned for
 * the lifetime of the process.
 *
 * This name may be used in various g_critical() messages which can
 * be useful in troubleshooting.
 *
 * If using #IdeTask from C, a default name is set using the source
 * file name and line number.
 *
 * Since: 3.28
 */
void
ide_task_set_name (IdeTask *self,
                   const gchar *name)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  g_return_if_fail (IDE_IS_TASK (self));

  name = g_intern_string (name);

  g_mutex_lock (&priv->mutex);
  priv->name = name;
  g_mutex_unlock (&priv->mutex);
}

1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
gboolean
ide_task_had_error (IdeTask *self)
{
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);
  gboolean ret;

  g_return_val_if_fail (IDE_IS_TASK (self), FALSE);

  g_mutex_lock (&priv->mutex);
  ret = (priv->result != NULL && priv->result->type == IDE_TASK_RESULT_ERROR) ||
        (priv->thread_result != NULL && priv->thread_result->type == IDE_TASK_RESULT_ERROR);
  g_mutex_unlock (&priv->mutex);

  return ret;
}

1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
static gpointer
ide_task_get_user_data (GAsyncResult *result)
{
  IdeTask *self = (IdeTask *)result;
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  g_assert (IDE_IS_TASK (self));

  return priv->user_data;
}

static GObject *
ide_task_get_source_object_full (GAsyncResult *result)
{
  IdeTask *self = (IdeTask *)result;
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  g_assert (IDE_IS_TASK (self));

  return priv->source_object ? g_object_ref (priv->source_object) : NULL;
}

static gboolean
ide_task_is_tagged (GAsyncResult *result,
                    gpointer      source_tag)
{
  IdeTask *self = (IdeTask *)result;
  IdeTaskPrivate *priv = ide_task_get_instance_private (self);

  g_assert (IDE_IS_TASK (self));

  return source_tag == priv->source_tag;
}

static void
async_result_init_iface (GAsyncResultIface *iface)
{
  iface->get_user_data = ide_task_get_user_data;
  iface->get_source_object = ide_task_get_source_object_full;
  iface->is_tagged = ide_task_is_tagged;
}