// SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® module; #include #include module Nostro.Ui.Shell:Window_impl; import std; import Crafter.Graphics; import Crafter.Event; import Nostro.Ui; import :Window; import :Loop; import :Canvas; using namespace Nostro::Ui; using namespace Nostro::Ui::Shell; namespace { // The window library repeats a held key only while its own frames run; with frames drawn on demand a timer asks // it to, this often while a key is down. constexpr std::int64_t repeatMs = 30; Key Letter(xkb_keysym_t symbol) noexcept { switch(xkb_keysym_to_lower(symbol)) { case XKB_KEY_a: return Key::A; case XKB_KEY_c: return Key::C; case XKB_KEY_f: return Key::F; case XKB_KEY_r: return Key::R; case XKB_KEY_v: return Key::V; case XKB_KEY_x: return Key::X; default: return Key::None; } } // The key by what it types on the user's layout, so that Ctrl+A is the key marked A wherever that is. Key Translate(Crafter::KeyCode code) noexcept { xkb_state* const state = Crafter::Device::xkb_state; if(state == nullptr) { return Key::None; } // The window library's code is the kernel's; xkb's is that and 8. const xkb_keycode_t keycode = code + 8; const xkb_keysym_t symbol = xkb_state_key_get_one_sym(state, keycode); switch(symbol) { case XKB_KEY_Return: case XKB_KEY_KP_Enter: return Key::Enter; case XKB_KEY_Escape: return Key::Escape; case XKB_KEY_Tab: case XKB_KEY_ISO_Left_Tab: return Key::Tab; case XKB_KEY_space: return Key::Space; case XKB_KEY_BackSpace: return Key::Backspace; case XKB_KEY_Delete: case XKB_KEY_KP_Delete: return Key::Delete; case XKB_KEY_Left: case XKB_KEY_KP_Left: return Key::Left; case XKB_KEY_Right: case XKB_KEY_KP_Right: return Key::Right; case XKB_KEY_Up: case XKB_KEY_KP_Up: return Key::Up; case XKB_KEY_Down: case XKB_KEY_KP_Down: return Key::Down; case XKB_KEY_Home: case XKB_KEY_KP_Home: return Key::Home; case XKB_KEY_End: case XKB_KEY_KP_End: return Key::End; case XKB_KEY_Page_Up: case XKB_KEY_KP_Page_Up: return Key::PageUp; case XKB_KEY_Page_Down: case XKB_KEY_KP_Page_Down: return Key::PageDown; case XKB_KEY_F5: return Key::F5; default: break; } if(const Key letter = Letter(symbol); letter != Key::None) { return letter; } // A layout without Latin letters (Greek, Cyrillic) has no key marked A: the shortcuts are then the keys of the // first of the user's layouts that has them, as other toolkits have it. xkb_keymap* const keymap = xkb_state_get_keymap(state); for(xkb_layout_index_t layout = 0; layout < xkb_keymap_num_layouts_for_key(keymap, keycode); layout++) { const xkb_keysym_t* symbols = nullptr; if(xkb_keymap_key_get_syms_by_level(keymap, keycode, layout, 0, &symbols) == 1) { if(const Key letter = Letter(symbols[0]); letter != Key::None) { return letter; } } } return Key::None; } Modifiers HeldModifiers() noexcept { xkb_state* const state = Crafter::Device::xkb_state; if(state == nullptr) { return {}; } return { .shift = xkb_state_mod_name_is_active(state, XKB_MOD_NAME_SHIFT, XKB_STATE_MODS_EFFECTIVE) > 0, .control = xkb_state_mod_name_is_active(state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_EFFECTIVE) > 0, }; } // The text a key types as the keyboard stands, as the window library reports it: nothing for a key that types a // control character. std::string Typed(Crafter::KeyCode code) { xkb_state* const state = Crafter::Device::xkb_state; if(state == nullptr) { return {}; } std::array buffer{}; const std::int32_t length = xkb_state_key_get_utf8(state, code + 8, buffer.data(), buffer.size()); if(length <= 0 || static_cast(buffer[0]) < 0x20 || buffer[0] == 0x7f) { return {}; } return std::string(buffer.data(), std::min(static_cast(length), buffer.size() - 1)); } constexpr Crafter::TextInputPurpose Purpose(TextPurpose purpose) noexcept { switch(purpose) { case TextPurpose::Digits: return Crafter::TextInputPurpose::Digits; case TextPurpose::Number: return Crafter::TextInputPurpose::Number; case TextPurpose::Phone: return Crafter::TextInputPurpose::Phone; case TextPurpose::Url: return Crafter::TextInputPurpose::Url; case TextPurpose::Email: return Crafter::TextInputPurpose::Email; case TextPurpose::Name: return Crafter::TextInputPurpose::Name; case TextPurpose::Password: return Crafter::TextInputPurpose::Password; default: return Crafter::TextInputPurpose::Normal; } } } Window::Window(Loop& loop, Context& context, Fonts& fonts, const CanvasOptions& options) : loop(loop), context(context), canvas(fonts, options), source(loop, Crafter::Device::display), frames(loop, canvas.Native().surface), wake(loop, [this] { // What the compositor has already sent comes first: a release waiting to be read happened before this time, // and the press it ends is not a long one. source.Pump(); Before(NowMs()); }), repeat(loop, [this] { if(canvas.Native().heldKeys.empty()) { return; } Crafter::Device::TickKeyRepeats(); repeat.After(repeatMs); }), paste(loop, [this] { Paste(); }) { Crafter::Window& window = canvas.Native(); source.onLost = [this] { Fail("the connection to the compositor is gone"); }; frames.onFrame = [this] { DrawFrame(); }; // The listeners run inside libwayland's dispatch, which nothing may be thrown through. const auto listen = [this](Crafter::Event& event, std::function body) { plain.emplace_back(&event, [this, body = std::move(body)] { this->loop.Guard("an event of the window", body); }); }; listen(window.onMouseLeftClick, [this] { Press(PointerPhase::Down); }); touchDown.emplace(&window.onTouchDown, [this](Crafter::TouchPoint point) { // Before the library makes it the pointer: the first finger. if(canvas.Native().primaryTouchId < 0) { touch = point.id; touchLifted = false; resting.reset(); } }); touchUp.emplace(&window.onTouchUp, [this](Crafter::TouchPoint point) { if(touch && point.id == *touch) { touchLifted = true; } }); listen(window.onMouseLeftRelease, [this] { const bool cancelled = touch && !touchLifted; touch.reset(); Press(cancelled ? PointerPhase::Cancel : PointerPhase::Up); // What the pointer is over once the release has acted, which may be another screen. Before(NowMs()); this->context.Hover(resting); }); listen(window.onTouchCancel, [this] { touch.reset(); if(down) { Press(PointerPhase::Cancel); } }); listen(window.onMouseMove, [this] { if(!touch) { resting = Pointer(); } if(down) { Press(PointerPhase::Move); } else { Before(EventTime()); this->context.Hover(resting); } }); listen(window.onMouseLeave, [this] { resting.reset(); Before(NowMs()); this->context.Hover(std::nullopt); }); listen(window.onMouseRightClick, [this] { Before(EventTime()); this->context.Secondary(Pointer()); }); scroll.emplace(&window.onMouseScroll, [this](std::uint32_t detents) { this->loop.Guard("the wheel", [this, detents] { Before(EventTime()); // Whole detents, signed, in an unsigned payload. this->context.Wheel(Pointer(), static_cast(static_cast(detents))); }); }); keyDown.emplace(&window.onRawKeyDown, [this](Crafter::KeyCode code) { this->loop.Guard("a key", [this, code] { OnKey(code); }); }); keyUp.emplace(&window.onRawKeyUp, [this](Crafter::KeyCode code) { if(spent && spent->code == code) { spent.reset(); } }); text.emplace(&window.onTextInput, [this](const std::string_view utf8) { this->loop.Guard("typed text", [this, utf8] { OnText(utf8); }); }); preedit.emplace(&window.onPreedit, [this](const std::string_view utf8) { this->loop.Guard("the input method", [this, utf8] { Before(NowMs()); this->context.Preedit(utf8); }); }); textDelete.emplace(&window.onTextInputDelete, [this](Crafter::TextDelete range) { this->loop.Guard("the input method", [this, range] { Before(NowMs()); this->context.DeleteAround(range.beforeBytes, range.afterBytes); }); }); listen(window.onResize, [this] { if(failed) { return; } // The screens at the new size at once, so that the next event finds them where they are. The frame is built // again and not thrown away: a resize is no change of screen, and a menu that is open stays open. An on-screen // keyboard resizes the window as it comes, which is when a field's own menu is up. Layout(); atlasWait.Reset(); frames.RequestRedraw(); }); listen(window.onClose, [this] { if(onClose) { onClose(); } }); } Window::~Window() { // The compositor's input method is told the field is gone, so that it carries no composition into whatever window // comes next. if(applied.active) { canvas.Native().SetTextInput(false); } } Canvas& Window::Surface() noexcept { return canvas; } bool Window::Failed() const noexcept { return failed; } void Window::Log(std::string_view line) const { if(onLog) { onLog(line); } } void Window::Layout() { Frame& frame = context.Begin(canvas.Bounds(), canvas.Scale(), NowMs()); if(onBuild) { onBuild(frame); } context.End(); // What is under the pointer now, unless it is pressing something: a press stays on what it went down on. if(!down) { context.Hover(resting); } } void Window::Before(std::int64_t atMs) { context.Tick(atMs); if(!context.Built()) { Layout(); } } void Window::Prepare() { Before(NowMs()); } // The time the event being handled happened at, on the host's clock: the compositor's own stamp of it, which an event // that waited in the queue keeps. By the host's clock at dispatch a backlog of a swipe would be a burst, read as a // fling at many times the finger's speed, and a tap that waited out a stall would be a long press. std::int64_t Window::EventTime() { return clock.At(canvas.Native().lastInputTime, NowMs()); } Point Window::Pointer() const noexcept { const Crafter::Window& window = canvas.Native(); return {window.currentMousePos.x, window.currentMousePos.y}; } void Window::Press(PointerPhase phase) { const std::int64_t at = EventTime(); Before(at); if(phase == PointerPhase::Down) { down = true; } else if(phase != PointerPhase::Move) { down = false; } context.Pointer(phase, Pointer(), at); } void Window::OnKey(Crafter::KeyCode code) { const Crafter::KeyRepeatState& repeating = Crafter::Device::keyRepeat; // The library sends a held key down again and again; only its first is a press. const bool repeated = repeating.active && repeating.key == code; if(!repeated && spent && spent->code == code) { spent.reset(); } if(!repeat.Armed()) { repeat.After(repeatMs); } const Key key = Translate(code); if(key == Key::None) { return; } Before(NowMs()); const std::string focus(context.Focused()); context.KeyDown(key, HeldModifiers(), repeated); if(!repeated && (!context.Built() || context.Focused() != focus)) { // The press changed the screen or moved the focus: what the key types, now and held down, was meant for // neither the new screen nor the field that has the focus now. Space on a button is the case. if(std::string typed = Typed(code); !typed.empty()) { spent = Spent{code, std::move(typed)}; } } } void Window::OnText(std::string_view utf8) { if(spent && utf8 == spent->text && canvas.Native().heldKeys.contains(spent->code)) { return; } Before(NowMs()); context.Text(utf8); } void Window::Start() { Layout(); Apply(context.Take(), false); canvas.Render(context.Shown().draw, context.theme.background); AfterFrame(); // And one when the compositor first shows the window: its size and its scale may only be known by then. frames.RequestRedraw(); } void Window::Settle() { if(failed) { return; } // The size the compositor asked for, where the library left it; the resize builds the frame anew by itself. canvas.Reconcile(); // A frame the events left stale is built now: the next event acts on the screens as they are. if(!context.Built()) { Layout(); } Apply(context.Take(), true); } void Window::Apply(const Context::Wants& wants, bool redraw) { if(wants.copy) { // Refused before the pointer or a finger has been in the window: the compositor takes a selection only from // whoever it has just sent input. if(!Crafter::Clipboard::SetText(*wants.copy)) { Log("the clipboard did not take the copy"); } } if(wants.paste) { pasteInto = std::string(context.Focused()); paste.Schedule(); } ApplyTextInput(wants.textInput); if(redraw && wants.redraw) { // What is drawn may have changed, so the wait for the atlas starts over. atlasWait.Reset(); frames.RequestRedraw(); } if(wants.animating != frames.Animating()) { frames.SetAnimating(wants.animating); } if(wants.wakeAtMs) { wake.At(*wants.wakeAtMs); } else { wake.Cancel(); } } void Window::ApplyTextInput(const TextInputRequest& want) { if(want == applied) { return; } Crafter::Window& window = canvas.Native(); // Another field, or none: the input method drops what it was composing and starts afresh, which turning the input // off does whatever the next field is. The Context took the composed word into its field before it asked. if(applied.active && (!want.active || want.field != applied.field)) { window.SetTextInput(false); } if(want.active) { window.SetTextInput(true, static_cast(want.caret.x), static_cast(want.caret.y), static_cast(want.caret.w), static_cast(want.caret.h), Purpose(want.purpose), want.hints); } applied = want; } void Window::DrawFrame() { if(failed) { return; } context.Tick(NowMs()); // Everything asked for so far but the frame, which this is. Apply(context.Take(), false); Layout(); try { canvas.Render(context.Shown().draw, context.theme.background); } catch(const std::exception& error) { Fail(error.what()); return; } AfterFrame(); } void Window::AfterFrame() { const Canvas::Stats& stats = canvas.Last(); if(stats.overflowed && !overflowSaid) { overflowSaid = true; Log("a frame had more to draw than the window's buffers hold; part of it was left out"); } // A glyph that found no cell in the font atlas drew blank and gets one when a later frame begins, and a frame // comes only when asked for. atlasWait.patience = Canvas::atlasPatience; if(atlasWait.Again(stats.glyphsWaiting)) { frames.RequestRedraw(); } if(onFrame) { onFrame(); } } void Window::Screenshot(const std::filesystem::path& png) { context.Tick(NowMs()); Layout(); canvas.Capture(png); canvas.Render(context.Shown().draw, context.theme.background); AfterFrame(); } // From the loop, never from inside a listener: the library waits for the clipboard's owner, for up to a second, and // serves the compositor meanwhile, so its events run the listeners here from inside the read. Asked for from the loop // that is all that happens; asked for from a listener they would run inside one another. void Window::Paste() { if(failed) { return; } std::optional clipboard = Crafter::Clipboard::GetText(); if(!clipboard) { return; } // Not into another field than the one that asked, if the focus moved on while the clipboard was read. if(!clipboard->empty() && context.Focused() == pasteInto) { Before(NowMs()); context.Paste(*clipboard); } // It may have been a key for a bank. explicit_bzero(clipboard->data(), clipboard->size()); } void Window::Fail(std::string_view why) { failed = true; wake.Cancel(); repeat.Cancel(); frames.SetAnimating(false); if(onFailed) { onFailed(why); } }