5#include <portals/background.hpp>
6#include <portals/ui_scene_pipeline.hpp>
11namespace portals::ui {
17 ManagedScene *scene{};
18 Application *application{};
20 std::weak_ptr<const void> lifetime;
21 std::weak_ptr<SceneAnchor> anchor;
22 std::source_location origin;
25ManagedError asyncFailure(
const AsyncSite &site,
AsyncError error,
26 std::optional<BackgroundError> background = {})
noexcept;
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;
37class AsyncInvocation :
public SceneActivity,
public std::enable_shared_from_this<AsyncInvocation> {
39 AsyncInvocation(AsyncSite site, UiAsyncContext context) : site_(std::move(site)), context_(std::move(context)) {
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);
55 struct OperationFailure {
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;
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_;
91 return context_.until(deadline);
105 return context_.receive<T>(std::move(start));
120 template <
class Output,
class Input,
class Work>
121 requires(std::copy_constructible<Work> && std::is_nothrow_move_constructible_v<Work>)
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();
127 if (!invocation || !invocation->live()) {
134 auto fail = [reply](
AsyncError error) -> std::expected<void, AsyncError> {
135 auto result = reply.fail(error);
137 return result ? std::expected<void, AsyncError>{} : std::unexpected(result.error());
141 invocation->fail(job.error(), std::move(fail));
146 invocation->submit(std::move(*job), std::move(fail));
151 friend class detail::AsyncInvocation;
154 : context_(std::move(context)), invocation_(std::move(invocation)), owner_(std::this_thread::get_id()) {
158 std::weak_ptr<detail::AsyncInvocation> invocation_;
159 std::thread::id owner_{};
164template <
class Function,
class... Args>
struct AsyncHandler {
166 std::tuple<Args...> arguments;
170template <
class Function,
class... Args>
class OwnedAsyncInvocation final :
public AsyncInvocation {
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) {
177 ~OwnedAsyncInvocation()
override {
179 SetupFailureScope setup({},
nullptr,
nullptr);
180 CurrentSceneScope mask;
188 [
this](
auto &...arguments) {
189 return std::invoke(*function_, context(), arguments...);
195 std::optional<Function> function_;
196 std::optional<std::tuple<Args...>> arguments_;
199template <
class Function,
class... Args>
class AsyncBinding {
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)) {
205 EditorCommandResult invoke() {
207 return AsyncAccess::result(site_, invokeChecked());
208 }
catch (
const std::bad_alloc &) {
209 return AsyncAccess::result(site_, std::unexpected(asyncFailure(site_, AsyncError::NO_MEMORY)));
211 return AsyncAccess::result(site_, std::unexpected(asyncFailure(site_, AsyncError::CALLBACK_FAILED)));
216 std::expected<void, ManagedError> invokeChecked() {
218 return std::unexpected(asyncFailure(site_, AsyncError::WOULD_BLOCK));
224 explicit Starting(
bool &flag) : value(flag) {
231 } starting(starting_);
233 auto outcome = owner_->outcome();
236 return std::unexpected(asyncFailure(site_, outcome.error()));
239 if (outcome->status == UiTaskStatus::RUNNING && prototype_.restart == UiTaskRestart::REJECT_RUNNING) {
240 return std::unexpected(asyncFailure(site_, AsyncError::WOULD_BLOCK));
243 auto invocation = std::make_shared<OwnedAsyncInvocation<Function, Args...>>(site_, owner_->context(), prototype_);
244 auto admitted = SceneAccess::admitActivity(*site_.scene, invocation);
247 if (
const auto *cause = std::get_if<TreeError>(&admitted.error().cause)) {
248 admitted.error().async = portals::detail::asyncError(*cause);
255 auto task = invocation->task();
256 auto started = AsyncAccess::start(*owner_, std::move(task), prototype_.restart, invocation->hooks());
258 if (!started && !(invocation->entered() &&
259 (started.error() == AsyncError::CLOSED || started.error() == AsyncError::CANCELLED))) {
260 invocation->cancel();
262 return std::unexpected(asyncFailure(site_, started.error()));
269 AsyncHandler<Function, Args...> prototype_;
271 std::unique_ptr<UiAsync> owner_;
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);
282 return std::unexpected(site.error());
290 auto owner =
UiAsync::create(site->application->scheduler(), site->application->tree(), node);
293 return std::unexpected(asyncFailure(*site, owner.error()));
296 return std::make_shared<AsyncBinding<Function, Args...>>(*site, std::move(*owner), std::move(handler));
297 }
catch (
const std::bad_alloc &) {
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};
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) {
341template <
class Function,
class... Args>
342auto onClick(
Ref<Button> reference, detail::AsyncHandler<Function, Args...> handler,
343 std::source_location origin = std::source_location::current()) {
345 origin](ManagedScene &scene)
mutable -> std::expected<void, ManagedError> {
346 auto node = detail::AsyncAccess::node(scene, reference);
349 return std::unexpected(node.error());
352 auto binding = detail::asyncBinding(scene, *node, std::move(handler), origin);
355 return std::unexpected(binding.error());
360 [binding = std::move(*binding)] {
361 return binding->invoke();
365 origin](
Scene &owner)
mutable {
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()) {
382 portals::detail::retainShortcut(portals::detail::prepareShortcut(std::forward<Source>(source), options));
385 [registration = [shortcut = std::move(shortcut), handler = std::move(handler), behavior, options,
386 origin](ManagedScene &scene)
mutable -> std::expected<void, ManagedError> {
390 failure.shortcut = shortcut.error();
392 return std::unexpected(failure);
395 auto binding = detail::asyncBinding(scene, scene.root(), std::move(handler), origin);
398 return std::unexpected(binding.error());
402 std::move(**shortcut),
403 [binding = std::move(*binding)] {
404 return binding->invoke();
406 behavior, options, origin);
408 origin](
Scene &owner)
mutable {
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);
428template <
class Function,
class... Args>
429auto onKey(KeyEvent chord, detail::AsyncHandler<Function, Args...> handler,
430 std::source_location origin = std::source_location::current()) {
432 origin](ManagedScene &scene)
mutable -> std::expected<void, ManagedError> {
433 auto binding = detail::asyncBinding(scene, scene.root(), std::move(handler), origin);
436 return std::unexpected(binding.error());
439 return scene.onKey(chord, [binding = std::move(*binding)] {
440 return binding->invoke();
443 origin](
Scene &owner)
mutable {
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