Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
ui_async.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/background.hpp>
6#include <portals/ui_scene_pipeline.hpp>
7
8#include <chrono>
9#include <tuple>
10
11namespace portals::ui {
12class AsyncContext;
13
14namespace detail {
16struct AsyncSite {
17 ManagedScene *scene{};
18 Application *application{};
19 Node<Widget> node;
20 std::weak_ptr<const void> lifetime;
21 std::weak_ptr<SceneAnchor> anchor;
22 std::source_location origin;
23};
24
25ManagedError asyncFailure(const AsyncSite &site, AsyncError error,
26 std::optional<BackgroundError> background = {}) noexcept;
27AsyncError backgroundAsyncError(BackgroundError error) noexcept;
28
29struct AsyncAccess {
30 static std::expected<AsyncSite, ManagedError> site(ManagedScene &, Node<Widget>, std::source_location);
31 static std::expected<Node<Button>, ManagedError> node(ManagedScene &, const Ref<Button> &);
32 static std::expected<void, AsyncError> start(UiAsync &, UiTask &&, UiTaskRestart, portals::detail::AsyncHooks);
33 static EditorCommandResult result(const AsyncSite &, std::expected<void, ManagedError>);
34 static AsyncTimer rejectedTimer(AsyncError error) noexcept;
35};
36
37class AsyncInvocation : public SceneActivity, public std::enable_shared_from_this<AsyncInvocation> {
38public:
39 AsyncInvocation(AsyncSite site, UiAsyncContext context) : site_(std::move(site)), context_(std::move(context)) {
40 }
41
42 ~AsyncInvocation() override;
43 bool active() const noexcept override;
44 void service() noexcept override;
45 void cancel() noexcept override;
46 bool live() const noexcept;
47 bool entered() const noexcept;
48 portals::detail::AsyncHooks hooks();
49 AsyncContext context();
50 AsyncTimer after(std::chrono::milliseconds delay) const noexcept;
51 void submit(std::unique_ptr<BackgroundJob> job, std::function<std::expected<void, AsyncError>(AsyncError)> fail);
52 void fail(BackgroundError error, std::function<std::expected<void, AsyncError>(AsyncError)> publish);
53
54private:
55 struct OperationFailure {
56 AsyncError error;
57 std::optional<BackgroundError> background;
58 };
59
60 static bool resume(void *, std::coroutine_handle<>) noexcept;
61 static void complete(void *, const UiTaskOutcome &) noexcept;
62 void fail(AsyncError, std::optional<BackgroundError>) noexcept;
63 void publishFailure() noexcept;
64
65 AsyncSite site_;
66 UiAsyncContext context_;
67 std::unique_ptr<BackgroundLatest> background_;
68 std::function<std::expected<void, AsyncError>(AsyncError)> failurePublisher_;
69 std::optional<AsyncError> pendingFailure_;
70 std::optional<OperationFailure> operationFailure_;
71 bool active_{true};
72 bool entered_{};
73};
74
76} // namespace detail
77
83public:
85 AsyncContext() = default;
86
90 AsyncTimer until(SchedulerTime deadline) const {
91 return context_.until(deadline);
92 }
93
98 AsyncTimer after(std::chrono::milliseconds delay) const noexcept;
99
104 template <class T> AsyncReceive<T> receive(std::function<void(AsyncReply<T>)> start) const {
105 return context_.receive<T>(std::move(start));
106 }
107
120 template <class Output, class Input, class Work>
121 requires(std::copy_constructible<Work> && std::is_nothrow_move_constructible_v<Work>)
122 AsyncReceive<Output> background(std::shared_ptr<const Input> input, Work work) const {
123 return context_.receive<Output>(
124 [weak = invocation_, input = std::move(input), work = std::move(work)](AsyncReply<Output> reply) mutable {
125 auto invocation = weak.lock();
126
127 if (!invocation || !invocation->live()) {
128 (void)reply.fail(AsyncError::CLOSED);
129
130 return;
131 }
132
133 auto job = makeBackgroundJob<Input, Output>(std::move(input), reply, std::move(work));
134 auto fail = [reply](AsyncError error) -> std::expected<void, AsyncError> {
135 auto result = reply.fail(error);
136
137 return result ? std::expected<void, AsyncError>{} : std::unexpected(result.error());
138 };
139
140 if (!job) {
141 invocation->fail(job.error(), std::move(fail));
142
143 return;
144 }
145
146 invocation->submit(std::move(*job), std::move(fail));
147 });
148 }
149
150private:
151 friend class detail::AsyncInvocation;
152
153 AsyncContext(UiAsyncContext context, std::weak_ptr<detail::AsyncInvocation> invocation)
154 : context_(std::move(context)), invocation_(std::move(invocation)), owner_(std::this_thread::get_id()) {
155 }
156
157 UiAsyncContext context_;
158 std::weak_ptr<detail::AsyncInvocation> invocation_;
159 std::thread::id owner_{};
160};
161
162namespace detail {
164template <class Function, class... Args> struct AsyncHandler {
165 Function function;
166 std::tuple<Args...> arguments;
167 UiTaskRestart restart{UiTaskRestart::REJECT_RUNNING};
168};
169
170template <class Function, class... Args> class OwnedAsyncInvocation final : public AsyncInvocation {
171public:
172 OwnedAsyncInvocation(AsyncSite site, UiAsyncContext context, const AsyncHandler<Function, Args...> &prototype)
173 : AsyncInvocation(std::move(site), std::move(context)), function_(prototype.function),
174 arguments_(prototype.arguments) {
175 }
176
177 ~OwnedAsyncInvocation() override {
178 // Arbitrary capture/argument destructors must not inherit a caller's unrelated UI attribution.
179 SetupFailureScope setup({}, nullptr, nullptr);
180 CurrentSceneScope mask;
181
182 arguments_.reset();
183 function_.reset();
184 }
185
186 UiTask task() {
187 return std::apply(
188 [this](auto &...arguments) {
189 return std::invoke(*function_, context(), arguments...);
190 },
191 *arguments_);
192 }
193
194private:
195 std::optional<Function> function_;
196 std::optional<std::tuple<Args...>> arguments_;
197};
198
199template <class Function, class... Args> class AsyncBinding {
200public:
201 AsyncBinding(AsyncSite site, std::unique_ptr<UiAsync> owner, AsyncHandler<Function, Args...> prototype)
202 : site_(std::move(site)), prototype_(std::move(prototype)), owner_(std::move(owner)) {
203 }
204
205 EditorCommandResult invoke() {
206 try {
207 return AsyncAccess::result(site_, invokeChecked());
208 } catch (const std::bad_alloc &) {
209 return AsyncAccess::result(site_, std::unexpected(asyncFailure(site_, AsyncError::NO_MEMORY)));
210 } catch (...) {
211 return AsyncAccess::result(site_, std::unexpected(asyncFailure(site_, AsyncError::CALLBACK_FAILED)));
212 }
213 }
214
215private:
216 std::expected<void, ManagedError> invokeChecked() {
217 if (starting_) {
218 return std::unexpected(asyncFailure(site_, AsyncError::WOULD_BLOCK));
219 }
220
221 struct Starting {
222 bool &value;
223
224 explicit Starting(bool &flag) : value(flag) {
225 value = true;
226 }
227
228 ~Starting() {
229 value = false;
230 }
231 } starting(starting_);
232
233 auto outcome = owner_->outcome();
234
235 if (!outcome) {
236 return std::unexpected(asyncFailure(site_, outcome.error()));
237 }
238
239 if (outcome->status == UiTaskStatus::RUNNING && prototype_.restart == UiTaskRestart::REJECT_RUNNING) {
240 return std::unexpected(asyncFailure(site_, AsyncError::WOULD_BLOCK));
241 }
242
243 auto invocation = std::make_shared<OwnedAsyncInvocation<Function, Args...>>(site_, owner_->context(), prototype_);
244 auto admitted = SceneAccess::admitActivity(*site_.scene, invocation);
245
246 if (!admitted) {
247 if (const auto *cause = std::get_if<TreeError>(&admitted.error().cause)) {
248 admitted.error().async = portals::detail::asyncError(*cause);
249 }
250
251 return admitted;
252 }
253
254 // Declaration order also protects an unadopted/rejected task: its frame retires before invocation storage.
255 auto task = invocation->task();
256 auto started = AsyncAccess::start(*owner_, std::move(task), prototype_.restart, invocation->hooks());
257
258 if (!started && !(invocation->entered() &&
259 (started.error() == AsyncError::CLOSED || started.error() == AsyncError::CANCELLED))) {
260 invocation->cancel();
261
262 return std::unexpected(asyncFailure(site_, started.error()));
263 }
264
265 return {};
266 }
267
268 AsyncSite site_;
269 AsyncHandler<Function, Args...> prototype_;
270 // Reverse member destruction closes the frame before releasing the callable prototype.
271 std::unique_ptr<UiAsync> owner_;
272 bool starting_{};
273};
274
275template <class Function, class... Args>
276auto asyncBinding(ManagedScene &scene, Node<Widget> node, AsyncHandler<Function, Args...> handler,
277 std::source_location origin)
278 -> std::expected<std::shared_ptr<AsyncBinding<Function, Args...>>, ManagedError> {
279 auto site = AsyncAccess::site(scene, node, origin);
280
281 if (!site) {
282 return std::unexpected(site.error());
283 }
284
285 if (handler.restart != UiTaskRestart::REJECT_RUNNING && handler.restart != UiTaskRestart::CANCEL_PREVIOUS) {
286 return std::unexpected(asyncFailure(*site, AsyncError::INVALID_ARGUMENT));
287 }
288
289 try {
290 auto owner = UiAsync::create(site->application->scheduler(), site->application->tree(), node);
291
292 if (!owner) {
293 return std::unexpected(asyncFailure(*site, owner.error()));
294 }
295
296 return std::make_shared<AsyncBinding<Function, Args...>>(*site, std::move(*owner), std::move(handler));
297 } catch (const std::bad_alloc &) {
298 return std::unexpected(asyncFailure(*site, AsyncError::NO_MEMORY));
299 } catch (...) {
300 return std::unexpected(asyncFailure(*site, AsyncError::CALLBACK_FAILED));
301 }
302}
303
305} // namespace detail
306
315template <class Function, class... Args>
316 requires(std::copy_constructible<Function> && (std::copy_constructible<Args> && ...) &&
317 std::same_as<std::invoke_result_t<Function &, AsyncContext, Args & ...>, UiTask>)
318auto async(UiTaskRestart restart, Function function, Args... args) {
319 return detail::AsyncHandler<Function, Args...>{std::move(function), {std::move(args)...}, restart};
320}
321
328template <class Function, class... Args>
329 requires(std::copy_constructible<Function> && (std::copy_constructible<Args> && ...) &&
330 std::same_as<std::invoke_result_t<Function &, AsyncContext, Args & ...>, UiTask>)
331auto async(Function function, Args... args) {
332 return async(UiTaskRestart::REJECT_RUNNING, std::move(function), std::move(args)...);
333}
334
341template <class Function, class... Args>
342auto onClick(Ref<Button> reference, detail::AsyncHandler<Function, Args...> handler,
343 std::source_location origin = std::source_location::current()) {
344 return detail::SceneStage{[registration = [reference = std::move(reference), handler = std::move(handler),
345 origin](ManagedScene &scene) mutable -> std::expected<void, ManagedError> {
346 auto node = detail::AsyncAccess::node(scene, reference);
347
348 if (!node) {
349 return std::unexpected(node.error());
350 }
351
352 auto binding = detail::asyncBinding(scene, *node, std::move(handler), origin);
353
354 if (!binding) {
355 return std::unexpected(binding.error());
356 }
357
359 scene, reference,
360 [binding = std::move(*binding)] {
361 return binding->invoke();
362 },
363 origin);
364 },
365 origin](Scene &owner) mutable {
366 detail::SceneAccess::onClick(owner, registration, origin);
367 }};
368}
369
378template <portals::detail::ShortcutSource Source, class Function, class... Args>
379auto onKey(Source &&source, detail::AsyncHandler<Function, Args...> handler, ShortcutBehavior behavior,
380 ShortcutOptions options = {}, std::source_location origin = std::source_location::current()) {
381 auto shortcut =
382 portals::detail::retainShortcut(portals::detail::prepareShortcut(std::forward<Source>(source), options));
383
384 return detail::SceneStage{
385 [registration = [shortcut = std::move(shortcut), handler = std::move(handler), behavior, options,
386 origin](ManagedScene &scene) mutable -> std::expected<void, ManagedError> {
387 if (!shortcut) {
388 ManagedError failure{ManagedPhase::BIND, scene.root().id(), TreeError::INVALID_ARGUMENT, {}, {}};
389
390 failure.shortcut = shortcut.error();
391
392 return std::unexpected(failure);
393 }
394
395 auto binding = detail::asyncBinding(scene, scene.root(), std::move(handler), origin);
396
397 if (!binding) {
398 return std::unexpected(binding.error());
399 }
400
401 return scene.onKey(
402 std::move(**shortcut),
403 [binding = std::move(*binding)] {
404 return binding->invoke();
405 },
406 behavior, options, origin);
407 },
408 origin](Scene &owner) mutable {
409 detail::SceneAccess::onClick(owner, registration, origin);
410 }};
411}
412
418template <portals::detail::ShortcutSource Source, class Function, class... Args>
419auto onKey(Source &&source, detail::AsyncHandler<Function, Args...> handler,
420 std::source_location origin = std::source_location::current()) {
421 return onKey(std::forward<Source>(source), std::move(handler), ShortcutBehavior{}, ShortcutOptions{}, origin);
422}
423
428template <class Function, class... Args>
429auto onKey(KeyEvent chord, detail::AsyncHandler<Function, Args...> handler,
430 std::source_location origin = std::source_location::current()) {
431 return detail::SceneStage{[registration = [chord, handler = std::move(handler),
432 origin](ManagedScene &scene) mutable -> std::expected<void, ManagedError> {
433 auto binding = detail::asyncBinding(scene, scene.root(), std::move(handler), origin);
434
435 if (!binding) {
436 return std::unexpected(binding.error());
437 }
438
439 return scene.onKey(chord, [binding = std::move(*binding)] {
440 return binding->invoke();
441 });
442 },
443 origin](Scene &owner) mutable {
444 detail::SceneAccess::onClick(owner, registration, origin);
445 }};
446}
447} // namespace portals::ui
Owning typed data awaiter; normally obtained through UiAsyncContext::receive.
Definition async.hpp:290
Copyable producer endpoint owning no UI state, callbacks or coroutine frame. T and its deleter must s...
Definition async.hpp:213
One-shot absolute millisecond wait on the existing scheduler.
Definition async.hpp:428
Weak context copied into owning coroutine parameters; never extends the UI owner's life.
Definition async.hpp:462
static std::expected< std::unique_ptr< UiAsync >, AsyncError > create(Scheduler &scheduler, WidgetTree &tree, Node< Widget > context)
Weak UI invocation context using the existing UiTask awaiters and scheduler. Copies never retain a sc...
Definition ui_async.hpp:82
AsyncReceive< Output > background(std::shared_ptr< const Input > input, Work work) const
Definition ui_async.hpp:122
AsyncReceive< T > receive(std::function< void(AsyncReply< T >)> start) const
Definition ui_async.hpp:104
AsyncTimer until(SchedulerTime deadline) const
Definition ui_async.hpp:90
AsyncContext()=default
Construct an unavailable invocation context.
AsyncTimer after(std::chrono::milliseconds delay) const noexcept
Typed Widget observation; explicit composite specializations reuse their existing weak facades.
Definition ui_ref.hpp:761
Single-use lazy owner of one Application and ManagedScene; no second runtime. Construct and operate o...
Definition ui_scene.hpp:253
consteval auto background(E expression)
Definition style_static.hpp:906
auto reference(ui::Ref< T > value)
Definition ui_static.hpp:572
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
@ 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
BackgroundError
Executor admission and startup failures; domain errors stay in the result value.
Definition background_options.hpp:11
@ BIND
Register a managed callback, binding or presentation adapter.
Definition managed_diagnostics.hpp:51
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
std::expected< std::unique_ptr< BackgroundJob >, BackgroundError > makeBackgroundJob(std::shared_ptr< const Input > input, AsyncReply< Output > reply, Work work)
Prepare owning immutable work without running it on the caller's UI thread.
Definition background.hpp:220
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
static std::expected< void, ManagedError > attach(ManagedScene &scene, const Ref< Button > &reference, Callback callback, std::source_location origin)
Definition ui_event_access.hpp:45
static void onClick(Scene &owner, Callback &callback, std::source_location origin)
Definition ui_scene.hpp:1279
Owning minimal pipe adapter forwarding to the same facade method.
Definition ui_scene_pipeline.hpp:29