5#include <portals/widget.hpp>
52 std::optional<AsyncError>
error;
63 std::shared_ptr<void> owner;
64 bool (*resume)(
void *, std::coroutine_handle<>)
noexcept {};
65 void (*cancel)(
void *)
noexcept {};
66 void (*complete)(
void *,
const UiTaskOutcome &)
noexcept {};
71struct AsyncInvocation {
72 std::weak_ptr<AsyncControl> control;
73 std::uint64_t generation{};
74 std::weak_ptr<AsyncWait> wait;
78AsyncInvocation asyncInvocation(
const std::weak_ptr<AsyncControl> &control)
noexcept;
79bool asyncInvocationCurrent(
const AsyncInvocation &identity)
noexcept;
80void asyncCancelInvocation(
const AsyncInvocation &identity)
noexcept;
83struct AsyncReceiveAdmission {
84 std::weak_ptr<const void> lifetime;
85 std::weak_ptr<const void> request;
86 const void *context{};
87 bool (*allows)(
const void *,
const std::shared_ptr<const void> &)
noexcept {};
95template <
class T>
inline constexpr bool IS_ASYNC_AWAITER =
false;
96template <
class T>
inline constexpr bool IS_ASYNC_AWAITER<AsyncReceive<T>> =
true;
97template <>
inline constexpr bool IS_ASYNC_AWAITER<AsyncTimer> =
true;
109std::expected<void, AsyncError> asyncCheck(
const std::shared_ptr<AsyncControl> &state);
110std::expected<void, AsyncError> asyncInstallWait(
const std::shared_ptr<AsyncControl> &state, std::uint64_t generation,
111 std::shared_ptr<AsyncWait> wait);
112void asyncResume(
const std::shared_ptr<AsyncControl> &state, std::uint64_t generation);
113void asyncFinishWait(
const std::shared_ptr<AsyncControl> &state,
const AsyncWait *wait)
noexcept;
114Scheduler &asyncScheduler(
const std::shared_ptr<AsyncControl> &state)
noexcept;
115WidgetTree &asyncTree(
const std::shared_ptr<AsyncControl> &state)
noexcept;
116Node<Widget> asyncNode(
const std::shared_ptr<AsyncControl> &state)
noexcept;
120 static constexpr unsigned OPEN = 0;
146 const std::thread::id
owner = std::this_thread::get_id();
176 template <class Awaiter>
177 requires detail::IS_ASYNC_AWAITER<std::remove_cvref_t<Awaiter>>
179 return std::forward<Awaiter>(awaiter);
197 friend class UiAsync;
198 using Handle = std::coroutine_handle<promise_type>;
200 explicit UiTask(Handle frame) : frame_(frame) {
222 std::expected<PublishResult, AsyncError>
complete(std::shared_ptr<const T> value)
const {
227 return publish(std::move(value));
234 return publish(std::unexpected(error));
241 : publisher_(std::move(publisher)), admission_(std::move(admission)) {
244 std::expected<PublishResult, AsyncError> publish(std::expected<std::shared_ptr<const T>,
AsyncError> result)
const {
247 auto admission = admission_;
248 auto publisher = publisher_;
254 auto phase = admission->phase.load();
261 auto event = std::make_shared<const detail::AsyncCompletion<T>>(std::move(result));
268 auto sent = publisher.publish(std::move(event));
270 admission->phase.compare_exchange_strong(phase,
274 return std::unexpected(detail::asyncError(sent.error()));
278 }
catch (
const std::bad_alloc &) {
283 Publisher<detail::AsyncCompletion<T>> publisher_;
284 std::shared_ptr<detail::AsyncAdmission> admission_;
290template <
class T>
class AsyncReceive {
293 std::shared_ptr<detail::AsyncAdmission> admission = std::make_shared<detail::AsyncAdmission>();
297 void cancel(
AsyncError error)
noexcept override {
299 result = std::unexpected(error);
304 (void)subscription.disconnect();
318 auto state = control_.lock();
319 auto checked = detail::asyncCheck(state);
322 fallback_ = checked.error();
326 if (frame.promise().control.lock() != state) {
337 wait_ = std::make_shared<Wait>();
338 auto installed = detail::asyncInstallWait(state, frame.promise().generation, wait_);
341 wait_->cancel(installed.error());
345 std::expected<SchedulerConnection<detail::AsyncCompletion<T>>,
SchedulerError> connection =
347 auto allowed = detail::asyncTree(state).withScope(detail::asyncNode(state), [&](
const UiScope &scope) {
348 connection = detail::asyncScheduler(state).template connect<detail::AsyncCompletion<T>>(
349 scope, [weak = std::weak_ptr(wait_), control = std::weak_ptr(state), generation = frame.promise().generation,
350 admission = admission_](std::shared_ptr<const detail::AsyncCompletion<T>> event) {
351 auto wait = weak.lock();
352 auto retained = control.lock();
354 if (!wait || !retained || wait->settled) {
358 if (admission.allows) {
359 const auto request = admission.request.lock();
362 if (admission.lifetime.expired() || !request || !admission.allows(admission.context, request)) {
363 detail::asyncCancelInvocation({retained, generation, wait, {}});
368 wait->result =
event->result;
369 wait->settled =
true;
371 detail::asyncResume(retained, generation);
375 if (!allowed || !connection) {
376 wait_->cancel(!allowed ? detail::asyncError(allowed.error()) : detail::asyncError(connection.error()));
381 wait_->subscription = std::move(connection->subscription);
382 start_(
AsyncReply<T>(std::move(connection->publisher), wait_->admission));
383 checked = detail::asyncCheck(state);
386 wait_->cancel(checked.error());
389 return !wait_->settled;
390 }
catch (
const std::bad_alloc &) {
397 wait_->cancel(fallback_);
405 if (
auto state = control_.lock()) {
406 detail::asyncFinishWait(state, wait_.get());
409 return wait_ ? wait_->result : std::expected<std::shared_ptr<const T>,
AsyncError>(std::unexpected(fallback_));
414 friend struct ui::detail::MessageAccess;
417 : control_(std::move(control)), start_(std::move(start)) {
420 std::weak_ptr<detail::AsyncControl> control_;
421 std::function<void(AsyncReply<T>)> start_;
422 std::shared_ptr<Wait> wait_;
423 detail::AsyncReceiveAdmission admission_;
443 friend class UiAsyncContext;
444 friend struct ui::detail::AsyncAccess;
447 AsyncTimer(std::weak_ptr<detail::AsyncControl> control,
SchedulerTime deadline)
448 : control_(std::move(control)), deadline_(deadline) {
454 std::weak_ptr<detail::AsyncControl> control_;
455 std::shared_ptr<Wait> wait_;
486 friend struct ui::detail::MessageAccess;
488 explicit UiAsyncContext(std::weak_ptr<detail::AsyncControl> control) : control_(std::move(control)) {
491 std::weak_ptr<detail::AsyncControl> control_;
511 UiAsync(
const UiAsync &) =
delete;
512 UiAsync &operator=(
const UiAsync &) =
delete;
528 std::expected<void, AsyncError>
cancel();
532 std::expected<void, AsyncError>
close();
534 std::expected<UiTaskOutcome, AsyncError>
outcome()
const;
537 friend struct ui::detail::AsyncAccess;
539 std::expected<void, AsyncError> startOwned(
UiTask &&task,
UiTaskRestart restart, detail::AsyncHooks hooks);
541 explicit UiAsync(std::shared_ptr<detail::AsyncControl> state) : state_(std::move(state)) {
544 std::shared_ptr<detail::AsyncControl> state_;
Owning typed data awaiter; normally obtained through UiAsyncContext::receive.
Definition async.hpp:290
std::expected< std::shared_ptr< const T >, AsyncError > await_resume() noexcept
Definition async.hpp:404
bool await_suspend(std::coroutine_handle< UiTask::promise_type > frame)
Definition async.hpp:317
constexpr bool await_ready() const noexcept
Definition async.hpp:310
Copyable producer endpoint owning no UI state, callbacks or coroutine frame. T and its deleter must s...
Definition async.hpp:213
std::expected< PublishResult, AsyncError > fail(AsyncError error) const
Definition async.hpp:233
std::expected< PublishResult, AsyncError > complete(std::shared_ptr< const T > value) const
Definition async.hpp:222
AsyncReply()=default
Empty closed endpoint.
One-shot absolute millisecond wait on the existing scheduler.
Definition async.hpp:428
bool await_suspend(std::coroutine_handle< UiTask::promise_type > frame)
constexpr bool await_ready() const noexcept
Definition async.hpp:431
std::expected< void, AsyncError > await_resume() noexcept
Copyable typed observer; never owns or exposes an unchecked widget pointer.
Definition widget.hpp:92
Copyable, worker-safe endpoint. It owns the closed channel state, never UI captures....
Definition scheduler.hpp:189
One UI executor; call dispatch only between frames, never during layout/paint. create captures its ca...
Definition scheduler.hpp:238
UI-owned move-only cancellation token. Release before Scheduler. Disconnect is immediate logically; a...
Definition scheduler.hpp:121
Weak context copied into owning coroutine parameters; never extends the UI owner's life.
Definition async.hpp:462
AsyncReceive< T > receive(std::function< void(AsyncReply< T >)> start) const
Register one completion before calling the owning UI provider-start callback.
Definition async.hpp:480
AsyncTimer until(SchedulerTime deadline) const
Definition async.hpp:470
UiAsyncContext()=default
Empty closed context.
Optional UI owner of at most one coroutine frame and one wait, with no separate runtime....
Definition async.hpp:500
UiAsyncContext context() const
~UiAsync()
Close on UI; foreign-thread destruction terminates.
std::expected< void, AsyncError > close()
Permanently close on UI without joining; idempotent.
std::expected< UiTaskOutcome, AsyncError > outcome() const
static std::expected< std::unique_ptr< UiAsync >, AsyncError > create(Scheduler &scheduler, WidgetTree &tree, Node< Widget > context)
std::expected< void, AsyncError > start(UiTask &&task, UiTaskRestart restart=UiTaskRestart::REJECT_RUNNING)
Adopt and initially resume on UI; subsequent waits resume through scheduler dispatch.
std::expected< void, AsyncError > cancel()
Cancel on UI; suspended frame is released now, executing frame after resume returns.
UI-owned scope disconnecting all its subscriptions and timers, in any token order....
Definition scheduler.hpp:154
Lazy move-only coroutine frame, created and released on its creating UI thread. The task owns its fun...
Definition async.hpp:142
~UiTask()
Destroy an unadopted frame on its creating thread; foreign destruction terminates.
UiTask(UiTask &&other) noexcept
UiTask()=default
Empty task.
UiTask & operator=(UiTask &&other) noexcept
Public Portals API.
Definition action.hpp:8
SchedulerError
Observable operation failures; no callback is started on rejection.
Definition scheduler.hpp:20
@ CLOSED
Scheduler, scope, registration or endpoint is closed.
Definition scheduler.hpp:24
UiTaskStatus
Retained business outcome, independent of scheduler queue acceptance.
Definition async.hpp:41
@ RUNNING
One frame is executing or waiting.
Definition async.hpp:43
@ IDLE
No invocation has been adopted.
Definition async.hpp:42
@ FAILED
The coroutine returned an error or threw.
Definition async.hpp:46
@ SUCCEEDED
The coroutine returned success.
Definition async.hpp:44
@ CALLBACK_FAILED
A non-allocation exception escaped into a runner callback boundary.
Definition application.hpp:34
@ NO_MEMORY
Allocation failed at a runner exception boundary.
Definition application.hpp:33
AsyncError
Failures of the optional single-frame UI coroutine adapter.
Definition async.hpp:25
@ CLOSED
Owner, node scope, scheduler or completion endpoint is closed.
Definition async.hpp:28
@ CALLBACK_FAILED
Provider or coroutine body threw an exception other than bad_alloc.
Definition async.hpp:32
@ WRONG_THREAD
The operation or coroutine frame belongs to another thread.
Definition async.hpp:27
@ CANCELLED
Explicit cancellation or replacement stopped the invocation.
Definition async.hpp:29
@ WOULD_BLOCK
Active resume, invocation, registration or queue capacity rejects the operation.
Definition async.hpp:30
@ IDENTITY_EXHAUSTED
Invocation identity cannot advance without reuse.
Definition async.hpp:33
@ INVALID_ARGUMENT
Empty task, callback or immutable data owner, or invalid policy.
Definition async.hpp:26
@ NO_MEMORY
Allocation failed inside an adapter or coroutine boundary.
Definition async.hpp:31
UiTaskRestart
Explicit policy for repeated actions on one owner.
Definition async.hpp:36
@ REJECT_RUNNING
Default: preserve the active invocation and reject the new task.
Definition async.hpp:37
@ CANCEL_PREVIOUS
Cancel a suspended invocation before adopting the new task; active resume still rejects.
Definition async.hpp:38
std::uint64_t SchedulerTime
Monotonic milliseconds; the clock must not move backwards.
Definition scheduler.hpp:18
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
UI-readable outcome remains available after context removal.
Definition async.hpp:50
UiTaskStatus status
Current or most recently completed invocation.
Definition async.hpp:51
std::optional< AsyncError > error
Empty for idle, running or successful completion.
Definition async.hpp:52
std::uint64_t generation
Monotonic adopted invocation identity; zero before the first task.
Definition async.hpp:53
Compiler-facing coroutine promise; not an independent execution API.
Definition async.hpp:145
std::uint64_t generation
Invocation to which this frame belongs.
Definition async.hpp:148
const std::thread::id owner
Frame creation affinity.
Definition async.hpp:146
void return_value(std::expected< void, AsyncError > value) noexcept
Definition async.hpp:164
std::expected< void, AsyncError > result
Returned or exception-translated outcome.
Definition async.hpp:149
constexpr std::suspend_always final_suspend() const noexcept
Definition async.hpp:159
Awaiter && await_transform(Awaiter &&awaiter) noexcept
Permit only waits whose resume and destruction belong to this UI adapter.
Definition async.hpp:178
void unhandled_exception() noexcept
Translate body exceptions to NO_MEMORY or CALLBACK_FAILED.
UiTask get_return_object() noexcept
constexpr std::suspend_always initial_suspend() const noexcept
Definition async.hpp:154
std::weak_ptr< detail::AsyncControl > control
Observes the adopting UI owner.
Definition async.hpp:147
std::atomic< unsigned > phase
Only shared mutable producer state; never retains UI storage.
Definition async.hpp:124
static constexpr unsigned CLOSED
UI cancellation or delivery permanently closes admission.
Definition async.hpp:123
static constexpr unsigned OPEN
A producer can attempt one publication.
Definition async.hpp:120
static constexpr unsigned ACCEPTED
One completion was accepted; further admission rejects.
Definition async.hpp:122
static constexpr unsigned PUBLISHING
One producer holds the admission attempt.
Definition async.hpp:121
Single immutable scheduler payload carrying the owning await result.
Definition async.hpp:130
std::expected< std::shared_ptr< const T >, AsyncError > result
Owning data or exact provider error.
Definition async.hpp:131
UI-owned wait registration; workers never retain this cancellation interface.
Definition async.hpp:100
virtual void cancel(AsyncError error) noexcept=0
virtual ~AsyncWait()=default
Destroy on UI after registration detachment.