// SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® module; #include #include #include #include #include #include module Nostro.Ui.Shell:Loop_impl; import std; import :Loop; using namespace Nostro::Ui::Shell; namespace { // sd-event's answer, or what it could not do. std::int32_t Checked(std::int32_t result, std::string_view what) { if(result < 0) { throw std::system_error(-result, std::generic_category(), std::format("cannot {}", what)); } return result; } } std::int64_t Nostro::Ui::Shell::NowMs() noexcept { timespec now{}; clock_gettime(CLOCK_MONOTONIC, &now); return static_cast(now.tv_sec) * 1000 + now.tv_nsec / 1000000; } Loop::Loop() { Checked(sd_event_new(&event), "make an event loop"); try { // A signal is a source like the rest once it is blocked, and a thread started later inherits the mask. sigset_t ending{}; sigemptyset(&ending); sigaddset(&ending, SIGINT); sigaddset(&ending, SIGTERM); sigprocmask(SIG_BLOCK, &ending, nullptr); Checked(sd_event_add_signal(event, nullptr, SIGINT, nullptr, nullptr), "watch for SIGINT"); Checked(sd_event_add_signal(event, nullptr, SIGTERM, nullptr, nullptr), "watch for SIGTERM"); Checked(sd_event_add_post(event, &post, OnPost, this), "follow the event loop"); } catch(...) { sd_event_unref(event); throw; } } Loop::~Loop() { sd_event_source_unref(post); sd_event_unref(event); } sd_event* Loop::Event() const noexcept { return event; } std::int32_t Loop::Run() { return Checked(sd_event_loop(event), "run the event loop"); } void Loop::Exit(std::int32_t status) noexcept { sd_event_exit(event, status); } void Loop::Guard(std::string_view what, const std::function& body) noexcept { try { body(); } catch(const std::exception& error) { Failed(std::format("{} failed: {}", what, error.what())); } catch(...) { Failed(std::format("{} failed", what)); } } void Loop::Failed(std::string_view line) noexcept { if(onError) { onError(line); } else { std::println(std::cerr, "{}", line); } Exit(1); } std::int32_t Loop::OnPost(sd_event_source*, void* data) { Loop& self = *static_cast(data); if(self.onSettle) { self.Guard("settling after an event", self.onSettle); } return 0; } Timer::Timer(Loop& loop, std::function fire) : loop(loop), fire(std::move(fire)) { // Accurate to a millisecond: left to itself sd-event lets a timer slip by up to a quarter of a second, to wake less // often, which a caret's blink and a held key's repeat would show. Checked(sd_event_add_time(loop.Event(), &source, CLOCK_MONOTONIC, 0, 1000, OnTime, this), "make a timer"); sd_event_source_set_enabled(source, SD_EVENT_OFF); } Timer::~Timer() { sd_event_source_disable_unref(source); } void Timer::At(std::int64_t ms) { Checked(sd_event_source_set_time(source, static_cast(std::max(ms, 0)) * 1000), "set a timer"); Checked(sd_event_source_set_enabled(source, SD_EVENT_ONESHOT), "set a timer"); armed = true; } void Timer::After(std::int64_t ms) { At(NowMs() + ms); } void Timer::Cancel() noexcept { sd_event_source_set_enabled(source, SD_EVENT_OFF); armed = false; } bool Timer::Armed() const noexcept { return armed; } std::int32_t Timer::OnTime(sd_event_source*, std::uint64_t, void* data) { Timer& self = *static_cast(data); // Before the callback, which may set the timer again. self.armed = false; self.loop.Guard("a timer", self.fire); return 0; } Defer::Defer(Loop& loop, std::function run) : loop(loop), run(std::move(run)) { Checked(sd_event_add_defer(loop.Event(), &source, OnDefer, this), "make a deferred call"); sd_event_source_set_enabled(source, SD_EVENT_OFF); } Defer::~Defer() { sd_event_source_disable_unref(source); } void Defer::Schedule() noexcept { sd_event_source_set_enabled(source, SD_EVENT_ONESHOT); } void Defer::Cancel() noexcept { sd_event_source_set_enabled(source, SD_EVENT_OFF); } std::int32_t Defer::OnDefer(sd_event_source*, void* data) { Defer& self = *static_cast(data); self.loop.Guard("a deferred call", self.run); return 0; } WaylandSource::WaylandSource(Loop& loop, wl_display* display) : loop(loop), display(display) { Checked(sd_event_add_io(loop.Event(), &source, wl_display_get_fd(display), EPOLLIN, OnReady, this), "watch the compositor's connection"); Checked(sd_event_source_set_prepare(source, OnPrepare), "watch the compositor's connection"); Checked(sd_event_add_defer(loop.Event(), &nudge, OnNudge, this), "watch the compositor's connection"); sd_event_source_set_enabled(nudge, SD_EVENT_OFF); } WaylandSource::~WaylandSource() { sd_event_source_disable_unref(nudge); sd_event_source_disable_unref(source); } std::int32_t WaylandSource::OnPrepare(sd_event_source*, void* data) { WaylandSource& self = *static_cast(data); self.loop.Guard("the compositor's events", [&self] { if(self.lost) { return; } // What a read by someone else on this thread left queued for it. Their listeners ran outside any source, so one // is made to run: the loop then settles after them as after any other, and goes round once more before it // waits, which every other source's own preparation needs after what the listeners may have asked of it. const std::int32_t dispatched = wl_display_dispatch_pending(self.display); if(dispatched < 0) { self.Lost(); return; } if(dispatched > 0) { sd_event_source_set_enabled(self.nudge, SD_EVENT_ONESHOT); } self.Flush(); }); return 0; } std::int32_t WaylandSource::OnNudge(sd_event_source*, void*) { return 0; } std::int32_t WaylandSource::OnReady(sd_event_source*, std::int32_t, std::uint32_t revents, void* data) { WaylandSource& self = *static_cast(data); self.loop.Guard("the compositor's events", [&self, revents] { // Room to write alone is the next preparation's to use. if((revents & (EPOLLIN | EPOLLHUP | EPOLLERR)) != 0) { self.Pump(); } }); return 0; } void WaylandSource::Pump() { if(lost) { return; } // Announce, read and dispatch, all here. The announcement is refused while events are queued, which are dispatched // first; the read itself never waits, and fails once the connection is gone. while(wl_display_prepare_read(display) != 0) { if(wl_display_dispatch_pending(display) < 0) { Lost(); return; } } if(wl_display_read_events(display) < 0 || wl_display_dispatch_pending(display) < 0) { Lost(); } } void WaylandSource::Flush() { // What does not fit in the socket goes when it has room again. A connection that broke is found by the next read. const bool full = wl_display_flush(display) < 0 && errno == EAGAIN; if(full != writing) { writing = full; Checked(sd_event_source_set_io_events(source, full ? EPOLLIN | EPOLLOUT : EPOLLIN), "watch the compositor's connection"); } } void WaylandSource::Lost() { lost = true; sd_event_source_set_enabled(source, SD_EVENT_OFF); if(onLost) { onLost(); } } FrameDriver::FrameDriver(Loop& loop, wl_surface* surface) : loop(loop), surface(surface) { } FrameDriver::~FrameDriver() { if(pending != nullptr) { wl_callback_destroy(pending); } } void FrameDriver::RequestRedraw() { dirty = true; if(pending != nullptr) { return; } pending = wl_surface_frame(surface); wl_callback_add_listener(pending, &listener, this); wl_surface_commit(surface); } void FrameDriver::SetAnimating(bool on) { animating = on; if(on) { RequestRedraw(); } } bool FrameDriver::Animating() const noexcept { return animating; } bool FrameDriver::Waiting() const noexcept { return pending != nullptr; } void FrameDriver::OnDone(void* data, wl_callback* callback, std::uint32_t) { FrameDriver& self = *static_cast(data); wl_callback_destroy(callback); self.pending = nullptr; self.dirty = false; if(self.onFrame) { self.loop.Guard("a frame", self.onFrame); } // What the frame itself asked for, or what is still moving. if(self.animating || self.dirty) { self.RequestRedraw(); } }