// SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® // lint-disable-file no-char-pointer /* ImsdMessages.Ui:App — the window as a whole: created on the first Show and again after a Hide, fed by Sync through the shell, drawn from the store on demand. Mouse events become gestures (the library's first finger drives the pointer; a touch the compositor cancels is a cancel), a tap is resolved against the regions the last frame recorded, scrolling is by wheel, drag or fling, and nothing is drawn while nothing changes. */ module; #include #include #include "vulkan/vulkan.h" export module ImsdMessages.Ui:App; import std; import Crafter.Graphics; import Crafter.Event; import ImsdMessages; import :Loop; import :Canvas; import :Compose; import :Screens; export namespace ImsdMessages::Ui { class App { public: App(MessageStore& store, std::filesystem::path assetDir, std::filesystem::path cacheDir) : store(store), assetDir(std::move(assetDir)), cacheDir(std::move(cacheDir)) {} ~App() { Shutdown(); if (longPressTimer) g_source_remove(longPressTimer); if (repeatTimer) g_source_remove(repeatTimer); if (hideIdle) g_source_remove(hideIdle); } // Tears the window down in order: the GPU first finishes the frame // it may still be drawing from the item buffers, then the listeners // let go of the window, then the frame driver and the canvas go, and // the display source last. void Shutdown() { Teardown(); source.reset(); } private: void Teardown() { if (!canvas) return; StopFling(); // The composition ends with the window: committed into the field, // and the input method told (the disable Send's reset sends), so // neither it nor the library carries the word into the next window. EndComposition(); vkDeviceWaitIdle(Crafter::Device::device); if (blinkTimer) g_source_remove(blinkTimer); blinkTimer = 0; downSub.reset(); upSub.reset(); touchDownSub.reset(); touchUpSub.reset(); touchCancelSub.reset(); touch.reset(); moveSub.reset(); scrollSub.reset(); keySub.reset(); keyUpSub.reset(); textSub.reset(); preeditSub.reset(); deleteSub.reset(); resizeSub.reset(); closeSub.reset(); seenSub.reset(); day.reset(); frames.reset(); canvas.reset(); // The library queues a window's buffers, shaders and pipelines // for deletion; with no window left no frame frees them, and // the device is idle here. Crafter::Device::DrainDeletions(); gestures = GestureDetector{}; hits.clear(); hitKeys.clear(); hitMessages.clear(); textSinceFrame.clear(); } static gboolean OnHideIdle(gpointer data) { App& self = *static_cast(data); self.hideIdle = 0; self.Hide(); return G_SOURCE_REMOVE; } static gboolean OnScreenshot(gpointer data) { App& self = *static_cast(data); if (self.canvas) { try { self.canvas->Window().CaptureNextFrame(self.screenshotPath); self.canvas->Window().Update(); self.Log(std::format("screenshot written to {} ({}x{} px)", self.screenshotPath.string(), self.canvas->Window().width, self.canvas->Window().height)); self.exitCode = 0; // a failure until written (main) } catch (const std::exception& e) { // The library throws when the capture fails (a Vulkan call, // the PNG's write): the bench learns it from the log and the // exit status. self.Log(std::format("screenshot not written to {}: {}", self.screenshotPath.string(), e.what())); self.exitCode = 1; } } else { // No window to render it — none could be made, or it went // between the request and the capture: logged, and the run // ends with exit 1, so a bench learns it from both. self.Log(std::format("screenshot not written to {}: no window", self.screenshotPath.string())); self.exitCode = 1; } if (self.onQuit) self.onQuit(); return G_SOURCE_REMOVE; } public: App(const App&) = delete; App& operator=(const App&) = delete; Sync* sync = nullptr; bool closeQuits = false; // no session bus: a close ends the process, since nothing could show the window again bool verbose = false; // --headless: log lines may name a correspondent std::string appId = "net.catcrafts.ImsdMessages"; // the xdg app id; main sets it from the bus layer's constant std::function onQuit; // the screenshot's run is over, or the window closed with no bus to come back on std::function onConversationOpened; // the notification goes std::function onConversationDeleted; // so does the notification std::function onLog; std::function onDisplayLost; // the compositor's connection broke std::int32_t exitCode = 0; // what main returns when nothing else decided: 1 for a screenshot not written bool Visible() const noexcept { return canvas.has_value(); } // The system's appearance: dark or light, and its accent colour. // Applied to the window at once and kept for the next one. void SetTheme(bool dark, std::optional> accent) { theme = dark ? Theme::Dark() : Theme::Light(); if (accent) theme.Accent(*accent); if (canvas) canvas->theme = theme; Dirty(); } // Cancels a close's deferred Hide: a Show or an Open before it runs // keeps the window. True when there was one. bool KeepWindow() { if (!hideIdle) return false; g_source_remove(hideIdle); hideIdle = 0; return true; } // Whether the screens count as seen: the window is up, no close is // waiting for its Hide, and the compositor counts it the active // window and has not suspended it (the library's Window::activated // and suspended, xdg_toplevel's states). A window behind a lock // screen or another application, minimised or with the display // off, is up all the same. bool OnScreen() const noexcept { return canvas.has_value() && hideIdle == 0 && canvas->Window().activated && !canvas->Window().suspended; } // The compositor's word on the window changed. Out of sight, no // conversation is on screen: a text for the open one is stored // unread and notified, as after a close. In sight again, the open // conversation is read, as at a Show. void SeenChanged() { if (verbose) Log(std::format("window {}{}", canvas->Window().activated ? "active" : "not active", canvas->Window().suspended ? ", suspended" : "")); if (OnScreen()) Opened(); else if (sync) sync->SetOpenConversation(std::nullopt); } // Creates the window; shows it again after a Hide. void Show() { const bool kept = KeepWindow(); if (canvas) { if (kept) Opened(); // a close taken back: the kept conversation is on screen again, if the window is seen return; } canvas.emplace(); try { canvas->Create(400, 800, "Messages", appId, assetDir, cacheDir); } catch (const std::exception& e) { // No display, a compositor without a global the library // needs, no Vulkan device: the library throws, and the app // has no window. It says so and runs on without one — a // resident instance keeps importing. A later Show fails at // once with the same reason when the device's set-up failed // (it runs only once), and tries again past it (an asset // missing): what the failed Create queued is drained here, // as Teardown drains, since no frame will. canvas.reset(); Crafter::Device::DrainDeletions(); Log(std::format("no window: {}", e.what())); return; } canvas->theme = theme; if (!source) { source.emplace(Crafter::Device::display); source->onLost = [this] { if (onDisplayLost) onDisplayLost(); }; Log(std::format("vulkan: {}, descriptors by {}; window scale {}", Crafter::Device::deviceProperties.deviceName, Crafter::Device::descriptorHeapSupported ? "heap" : "sets", canvas->Window().scale)); } frames.emplace(canvas->Window()); frames->onFrame = [this] { canvas->Window().Update(); }; day.emplace(); // The captions name the day ("Today", a clock time for today's // text): drawn again when it changes. day->onDay = [this] { Log("the day changed"); Dirty(); }; canvas->onDraw = [this](VkCommandBuffer cmd) { Build(cmd); }; Crafter::Window& w = canvas->Window(); downSub.emplace(&w.onMouseLeftClick, [this] { Pointer(PointerPhase::Down); }); // The first finger drives the pointer. A touch the compositor // cancels (a gesture of its own) arrives as a release without the // finger's touch-up: a cancel, which taps nothing. touchDownSub.emplace(&w.onTouchDown, [this](Crafter::TouchPoint t) { if (canvas->Window().primaryTouchId < 0) { touch = t.id; touchUp = false; } }); touchUpSub.emplace(&w.onTouchUp, [this](Crafter::TouchPoint t) { if (touch && t.id == *touch) touchUp = true; }); upSub.emplace(&w.onMouseLeftRelease, [this] { const bool cancelled = touch && !touchUp; touch.reset(); Pointer(cancelled ? PointerPhase::Cancel : PointerPhase::Up); }); touchCancelSub.emplace(&w.onTouchCancel, [this] { touch.reset(); if (gestures.Pressed()) Pointer(PointerPhase::Cancel); }); moveSub.emplace(&w.onMouseMove, [this] { if (gestures.Pressed()) Pointer(PointerPhase::Move); }); scrollSub.emplace(&w.onMouseScroll, [this](std::uint32_t raw) { if (sheet || fresh) return; // a sheet takes the wheel as it takes the taps; the new-conversation screen scrolls nothing const std::int32_t detents = static_cast(raw); ActiveScroll().ScrollBy(static_cast(detents) * canvas->Dp(48)); if (view) view->stickToBottom = false; Dirty(); }); keySub.emplace(&w.onRawKeyDown, [this](Crafter::KeyCode code) { Key(code); }); keyUpSub.emplace(&w.onRawKeyUp, [this](Crafter::KeyCode) { if (canvas->Window().heldKeys.empty() && repeatTimer) { g_source_remove(repeatTimer); repeatTimer = 0; } }); textSub.emplace(&w.onTextInput, [this](const std::string_view text) { if (sheet) return; if (fresh) { // One line: a pasted number's line breaks are dropped, the rest kept. std::string oneLine(text); std::erase_if(oneLine, [](char c) { return c == '\n' || c == '\r'; }); fresh->field.preedit.clear(); ComposeInsert(fresh->field, oneLine); fresh->error.clear(); ShowCaret(); } else if (view) { view->compose.preedit.clear(); view->compose.focused = true; ComposeInsert(view->compose, text); ShowCaret(); } }); // The input method's composing text and its deletions; what it // commits arrives as text input above. preeditSub.emplace(&w.onPreedit, [this](const std::string_view text) { if (sheet) return; if (ComposeState* field = FocusedField()) { field->preedit = std::string(text); ShowCaret(); } }); deleteSub.emplace(&w.onTextInputDelete, [this](Crafter::TextDelete d) { if (sheet) return; if (ComposeState* field = FocusedField()) { ComposeDeleteAround(*field, d.beforeBytes, d.afterBytes); ShowCaret(); } }); resizeSub.emplace(&w.onResize, [this] { if (verbose) Log(std::format("window {}x{} px", canvas->Window().width, canvas->Window().height)); Dirty(); }); closeSub.emplace(&w.onClose, [this] { Close(); }); seenSub.emplace(&w.onToplevelState, [this] { SeenChanged(); }); Reload(); Opened(); // read once the new window counts as seen: now, or at the call that finds it so if (fresh || (view && view->compose.focused)) ShowCaret(); // the blink a hide stopped w.Render(); frames->RequestRedraw(); } // The window's close, the compositor's or the bench's (--hide-after, // --hide-every). Closing hides: the process stays for the next text // (the resident model); --quit or a signal ends it. The library runs // onClose from inside its own listener, so the teardown is deferred // to the loop; a Show before it runs keeps the window. The // conversation is off the screen from here, not from the Hide: a // text for it meanwhile is unread, and notified. Without a session // bus nothing could show the window again, so there a close ends // the process. void Close() { if (!canvas) return; if (closeQuits) { Log("window closed; no session bus to come back on: quitting"); if (onQuit) onQuit(); return; } if (hideIdle) return; if (sync) sync->SetOpenConversation(std::nullopt); hideIdle = g_idle_add(OnHideIdle, this); } // Tears the window down and keeps everything else: the store, the // screens (a conversation left open comes back on Show; its texts // stay unread meanwhile), the bus. void Hide() { if (!canvas) return; Teardown(); Log("window hidden; still running"); } // Shows the window on a conversation. Without a window (Show says // why) nothing is on screen, so nothing is read or opened. `dialled` // is the address as the user typed or a link gave it, what a text // from here is sent to and what the status re-keys the conversation // from (Status); "" from the list or a notification, where the // latest message's address is (Destination). void Open(std::string_view key, std::string_view dialled = "") { // The view may point into what opening replaces (a row's key in // `hitKeys`, the notifier's record of the tapped notification): // owned before anything runs. const std::string opening(key); key = opening; // Over the number screen, or over another conversation: the // field that goes ends its composition first. if (fresh || (view && view->key != key)) EndComposition(); StopFling(); CancelGesture(); KeepWindow(); fresh.reset(); sheet.reset(); if (!view || view->key != key) { KeepDraft(); view.emplace(); view->key = std::string(key); view->compose = drafts.Take(key); } view->dialled = std::string(dialled); view->dialledPlan = sync ? sync->Plan() : SimPlan{}; // for an address typed or linked now: the SIM's as known now view->stickToBottom = true; view->messages = store.Conversation(key); if (verbose) Log(std::format("opened {}", key)); else Log("opened a conversation"); if (canvas) Opened(); else Show(); ShowCaret(); } // The conversation the window shows, while the screens count as // seen (OnScreen): read, its notification gone, Sync told (a text // for it is stored read). Until then nothing: SeenChanged or the // next Show calls again. void Opened() { if (!view || !OnScreen()) return; if (store.MarkRead(view->key) > 0) Reload(); if (sync) sync->SetOpenConversation(view->key); if (onConversationOpened) onConversationOpened(view->key); } void Back() { // Every exit is a screen change: a press held across it (Escape // on a keyboard while a finger or a button is down) is cancelled, // not resolved against what the next frame draws there. if (sheet) { CancelGesture(); sheet.reset(); Dirty(); return; } if (fresh) { CancelGesture(); EndComposition(); fresh.reset(); Dirty(); return; } if (!view) return; StopFling(); CancelGesture(); EndComposition(); KeepDraft(); view.reset(); if (blinkTimer) { g_source_remove(blinkTimer); blinkTimer = 0; } if (sync) sync->SetOpenConversation(std::nullopt); Dirty(); } // The screen behind the +. void NewConversation() { StopFling(); CancelGesture(); EndComposition(); KeepDraft(); view.reset(); sheet.reset(); fresh.emplace(); fresh->field.focused = true; Show(); if (sync) sync->SetOpenConversation(std::nullopt); ShowCaret(); } // Start, from the new-conversation screen: a number becomes a key. void Start() { if (!fresh) return; // One reading of the field, the composing text included: the key // and the address dialled come from the same digits. const std::string shown = ComposeShown(fresh->field); const std::string key = ConversationKey(shown, sync ? sync->CountryCode() : ""); if (key.empty()) { fresh->error = "Enter a phone number"; Dirty(); return; } const std::string dialled = DialledNumber(shown); ResetTextInput(); // the composing text is used up: told before the screen changes, as Send does fresh.reset(); Open(key, dialled); } // The bench's hands: types into the field of the open screen, and // opens a sheet as a long press would. void Prefill(std::string_view text) { if (fresh) { ComposeInsert(fresh->field, text); } else if (view) { view->compose.focused = true; ComposeInsert(view->compose, text); } ShowCaret(); } void BenchSheet(std::string_view which) { // As a long press opens them: a conversation's sheet over the // list, a message's over its conversation — and a line when the // screen has nothing of the kind to press. if (which == "conversation" && !view && !fresh && !convs.empty()) sheet = Sheet{ Sheet::Kind::DeleteConversation, convs.front().key, 0, "" }; else if (which == "message" && view && !view->messages.empty()) sheet = Sheet{ Sheet::Kind::MessageActions, view->key, view->messages.front().id, view->messages.front().text }; else Log(std::format("--bench-sheet {}: nothing on this screen to press", which)); if (sheet) EndComposition(); Dirty(); } // The address a text from the open conversation is sent to (Model's // SendAddress: as the user typed or a link gave it, else the latest // message's, never the key); "" when none is known or it belongs to // another SIM's plan, and Send is off. std::string Destination() const { return SendAddress(view->dialled, view->dialledPlan, view->messages, sync ? sync->Plan() : SimPlan{}); } // Sends what the field shows, a word the input method is still // composing included, to the open conversation. The field keeps the // focus for the next text, and the input method starts afresh. void SendDraft() { if (!view || !sync || !CanSend(status) || Destination().empty()) return; // One reading of the shown text, the composing word included, as // Start takes it: a store that refuses the text (its disk full) // leaves the field and the composing word as they are; taken, the // field is cleared and the input method told its text is used up. std::string text = ComposeShown(view->compose); if (text.empty()) return; while (!text.empty() && (text.back() == '\n' || text.back() == ' ')) text.pop_back(); if (!text.empty() && sync->Send(view->key, Destination(), text) == Sync::kNotStored) return; view->compose = ComposeState{ .focused = true }; ResetTextInput(); view->stickToBottom = true; Dirty(); } // Renders one frame now, outside the compositor's pacing, saves it as // a PNG and asks to quit: the verification path for a machine without // eyes, which must not depend on a desktop that repaints. A window // created here first gets a moment for the compositor's configure, // which sizes it (to the screen, on a phone) before the frame. void ScreenshotThenQuit(const std::filesystem::path& path) { const bool created = !canvas; Show(); screenshotPath = path; if (created && canvas) g_timeout_add(600, OnScreenshot, this); else OnScreenshot(this); // a window already up, or none to come: now } // ---- fed by the shell from Sync's events ------------------------------ void Status(const AppStatus& s) { status = s; // The open conversation's key and its typed address's plan follow // the status of the SIM the address was typed under (Number's // AfterStatus): one opened from a link or a typed number before // imsd's status brought the code was keyed as its digits, and a // text sent meanwhile (CanSend needs no code — a status without // one, a registration before the re-read) keeps the conversation // on the key its rows carry. if (view && s.statusKnown && sync && !view->dialled.empty()) { TypedKey typed = AfterStatus(view->dialled, { view->key, view->dialledPlan }, sync->Plan(), sync->CountryCode(), store.Conversation(view->key).empty()); view->dialledPlan = std::move(typed.plan); if (typed.key != view->key) { view->key = std::move(typed.key); view->messages = store.Conversation(view->key); // Shown as Open shows a conversation: at its latest message, // whatever a turn of the wheel did over the empty one. view->scroll = ScrollState{}; view->stickToBottom = true; if (OnScreen()) Opened(); // not on screen, the kept conversation stays unread and keeps its notification: Show or SeenChanged opens it } } // The drafts of the typed addresses that were left follow it too. if (s.statusKnown && sync) drafts.Status(sync->Plan(), sync->CountryCode(), [this](std::string_view key) { return store.Conversation(key).empty(); }); Dirty(); } void Changed() { Reload(); } // A text arrived. A sheet that asks to delete its conversation goes: // the question was about the texts the list showed, and a yes to it // would delete this one unread. A press on its row opens no such // sheet either while the row it aimed at had not shown the text — // the regions are a frame's: the press that is down now, and one // that comes down before the next frame is drawn (Pointer), have no // long press. A release before the long-press time is still the // row's tap, while the row stays under the finger. void Imported(const Message& m) { if (sheet && sheet->kind == Sheet::Kind::DeleteConversation && sheet->key == m.conversation) { CancelGesture(); sheet.reset(); } textSinceFrame.insert(m.conversation); if (gestures.Pressed() && pressedOn && pressedOn->id == Hit::rowBase && pressedOn->key == m.conversation) pressGotText = true; Reload(); } private: void Log(std::string_view line) { if (onLog) onLog(line); } // A redraw asked for: whatever changed may have changed what is // drawn, so the atlas wait starts over (Build's own request does not // come through here; a fling's frames, which do not either, restart // it in Build). void Dirty() { frameWait.Reset(); if (frames) frames->RequestRedraw(); } // Leaving a conversation keeps what its field holds, by its key // (Edit's Drafts); Open takes it up again. void KeepDraft() { if (view) drafts.Keep(view->key, view->compose, view->dialled, view->dialledPlan); } void Reload() { convs = GroupConversations(store.All()); if (view) { const std::size_t before = view->messages.size(); view->messages = store.Conversation(view->key); if (view->messages.size() > before) view->stickToBottom = true; // Texts on screen are read; a conversation kept across a hide // or in a window that is not seen is not on screen, and its // new texts stay unread until it is. if (OnScreen() && sync && store.MarkRead(view->key) > 0) convs = GroupConversations(store.All()); } Dirty(); } static std::int64_t NowEpoch() { return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); } static std::int64_t NowMs() { return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); } static std::int32_t OffsetAt(std::int64_t epoch) { std::tm tm{}; const time_t t = static_cast(epoch); localtime_r(&t, &tm); return static_cast(tm.tm_gmtoff / 60); } ScrollState& ActiveScroll() { return view ? view->scroll : list.scroll; } // A screen change stops a fling: the scroll left behind keeps no // velocity for a return to revive, and the frames stop asking. void StopFling() { list.scroll.velocity = 0; if (view) view->scroll.velocity = 0; if (frames) frames->SetAnimating(false); } // A screen change under a finger cancels the press: its release is no // tap on what the new screen drew where the finger went down (a // forwarded link's or a notification's Open by the other thumb, Back // from a key), and its long press does not fire. void CancelGesture() { if (gestures.Pressed()) gestures.Feed(PointerPhase::Cancel, Point{}, eventClock); if (longPressTimer) { g_source_remove(longPressTimer); longPressTimer = 0; } } void Build(VkCommandBuffer) { tzset(); // the zone may have changed since the last frame: the captions read it Canvas& c = *canvas; hits.clear(); const std::int64_t now = NowEpoch(); const ZoneFn zone = OffsetAt; const auto frameTime = std::chrono::steady_clock::now(); const float dt = lastFrame.time_since_epoch().count() == 0 ? 0.0f : std::chrono::duration(frameTime - lastFrame).count(); lastFrame = frameTime; if (frames->Animating()) { frameWait.Reset(); // a fling's frame changes what is drawn, as a request through Dirty does: the atlas wait starts over if (!ActiveScroll().Tick(std::min(dt, 0.05f))) frames->SetAnimating(false); } if (fresh) { Box area = DrawHeader(c, "New message", true, hits); area = DrawBanner(c, area, status); fresh->Draw(c, area, hits); } else if (view) { Box area = DrawHeader(c, DisplayNumber(view->key), true, hits); area = DrawBanner(c, area, status); area = view->DrawComposeBar(c, area, CanSend(status) && !Destination().empty(), hits); view->Draw(c, area, now, zone, hits); } else { Box area = DrawHeader(c, "Messages", false, hits); area = DrawBanner(c, area, status); list.Draw(c, area, convs, now, zone, hits); } if (sheet) DrawSheet(c, *sheet, hits); UpdateTextInput(); // What the regions name, as drawn: a reload before the next frame // re-sorts the vectors, so a gesture resolves against these. hitKeys.clear(); for (const auto& conv : convs) hitKeys.push_back(conv.key); hitMessages.clear(); if (view) for (const Message& m : view->messages) hitMessages.push_back(m.id); textSinceFrame.clear(); // this frame's regions are of the texts as they are now if (c.Overflowed() && !overflowLogged) { overflowLogged = true; Log("a layer ran out of items this frame; the buffers are too small for this screen"); } // A glyph that found no room in the atlas drew blank and gets a // cell when a later frame begins — from glyphs not drawn in the // last framesInFlight + 1 frames — and only a request brings a // frame, frames being drawn on demand: FrameWait's rule (Gesture), // the request not through Dirty, which would start the wait over. if (frameWait.Again(c.GlyphsWaiting())) frames->RequestRedraw(); } ComposeState* FocusedField() { if (fresh) return &fresh->field; if (view && view->compose.focused) return &view->compose; return nullptr; } struct TextInputState { bool active = false; Box caret{}; Crafter::TextInputPurpose purpose = Crafter::TextInputPurpose::Normal; }; // The word the input method is composing goes into its field, as a // tap elsewhere does: once the text input is off, the input method // starts afresh and would replace or drop it. void CommitComposition() { if (fresh) ComposeCommitPreedit(fresh->field); if (view) ComposeCommitPreedit(view->compose); } // Tells the compositor which field has the focus and where its caret // is, after every frame, when that changed: the number field at once, // the message field after a tap or a key; a sheet or leaving the // screen takes it back. void UpdateTextInput() { TextInputState want; if (!sheet) { if (fresh) want = { true, fresh->fieldLayout.caret, Crafter::TextInputPurpose::Phone }; else if (view && view->compose.focused) want = { true, view->composeLayout.caret, Crafter::TextInputPurpose::Normal }; } const bool sameCaret = want.caret.x == lastTextInput.caret.x && want.caret.y == lastTextInput.caret.y && want.caret.w == lastTextInput.caret.w && want.caret.h == lastTextInput.caret.h; if (want.active == lastTextInput.active && want.purpose == lastTextInput.purpose && (!want.active || sameCaret)) return; if (want.active != lastTextInput.active) Log(want.active ? (want.purpose == Crafter::TextInputPurpose::Phone ? "text input on (a number)" : "text input on") : "text input off"); // Turning the input off ends the composition on the input // method's side; the field keeps the word it showed. if (!want.active && lastTextInput.active) CommitComposition(); lastTextInput = want; canvas->Window().SetTextInput(want.active, static_cast(want.caret.x), static_cast(want.caret.y), static_cast(want.caret.w), static_cast(want.caret.h), want.purpose); } // The event's own time: the compositor's stamp of the pointer or touch // event the listener is being invoked for (Window::lastInputTime, ms // from an undefined base, wrapping at 2^32), unwrapped into one // running clock. Events queued while the loop was busy keep the // times they happened at, so a backlog is not read as a burst: a // swipe's as a fling at many times the finger's speed, a held press // as a tap. The host's clock where the stamp is 0: the one // millisecond in 2^32 that the compositor's time reads 0, and before // the first event that has a time. std::int64_t EventTimeMs() { const std::uint32_t raw = canvas->Window().lastInputTime; if (raw == 0) return NowMs(); if (lastRawEventMs != 0) eventClock += static_cast(raw - lastRawEventMs); else eventClock = raw; lastRawEventMs = raw; return eventClock; } void Pointer(PointerPhase phase) { const Point p{ canvas->Window().currentMousePos.x, canvas->Window().currentMousePos.y }; // Buffer pixels: the slop and the fling threshold follow the // window's scale like every other distance, set at the point of use, // so a fresh detector after a teardown has them too. gestures.slopPx = canvas->Dp(8); gestures.flingMinPxPerS = canvas->Dp(60); if (phase == PointerPhase::Down) ActiveScroll().velocity = 0; // a finger down stops the fling under it if (phase == PointerPhase::Down) { pressedOn = Target(p); pressGotText = pressedOn && pressedOn->id == Hit::rowBase && textSinceFrame.contains(pressedOn->key); // Only a row and a message have a long press. A press on // anything else — a button, a field, a sheet's row — stays // that control's tap at its release, however long it was // held: a slow finger presses the button all the same. gestures.longPress = pressedOn && pressedOn->id >= Hit::rowBase; } const std::int64_t at = EventTimeMs(); Handle(gestures.Feed(phase, p, at)); if (phase == PointerPhase::Down) { downEventMs = at; downHostMs = NowMs(); if (longPressTimer) g_source_remove(longPressTimer); longPressTimer = gestures.longPress ? g_timeout_add(static_cast(gestures.longPressMs), OnLongPress, this) : 0; } else if (phase != PointerPhase::Move && longPressTimer) { g_source_remove(longPressTimer); longPressTimer = 0; } } static gboolean OnLongPress(gpointer data) { App& self = *static_cast(data); self.longPressTimer = 0; self.Handle(self.gestures.Timeout(self.downEventMs + (NowMs() - self.downHostMs))); // the host's elapsed since the press, on the events' clock return G_SOURCE_REMOVE; } void Handle(const GestureEvent& e) { if (sheet && e.kind != GestureEvent::Kind::Tap) return; // A tap or a long press acts on what the press went down on: a // frame drawn meanwhile (a new text snapped the conversation, the // list re-sorted) that moved another bubble or row under the // finger names something else, and the release acts on nothing. if ((e.kind == GestureEvent::Kind::Tap || e.kind == GestureEvent::Kind::LongPress) && Target(e.at) != pressedOn) return; if (e.kind == GestureEvent::Kind::LongPress && pressGotText) return; // the pressed row had not shown a text of its conversation (Imported) switch (e.kind) { case GestureEvent::Kind::None: return; case GestureEvent::Kind::Tap: Tap(e.at); return; case GestureEvent::Kind::LongPress: LongPress(e.at); return; case GestureEvent::Kind::DragStart: case GestureEvent::Kind::Drag: if (fresh) return; // the new-conversation screen scrolls nothing frames->SetAnimating(false); ActiveScroll().ScrollBy(-e.delta.y); if (view) view->stickToBottom = false; Dirty(); return; case GestureEvent::Kind::Fling: if (fresh) return; ActiveScroll().Fling(-e.velocity.y); frames->SetAnimating(true); return; case GestureEvent::Kind::Release: return; } } // What a frame's regions name at a point (Gesture's TargetAt). std::optional Target(Point p) const { return TargetAt(hits, p, Hit::rowBase, hitKeys, Hit::messageBase, hitMessages); } // The message a frame's region named, if the conversation still // holds it. const Message* HitMessage(std::size_t i) const { if (!view || i >= hitMessages.size()) return nullptr; for (const Message& m : view->messages) { if (m.id == hitMessages[i]) return &m; } return nullptr; } // A key: Escape goes back; Enter on the number screen starts the // conversation; Ctrl+Enter sends; the rest edits the field. void Key(Crafter::KeyCode code) { using Crafter::CrafterKeys; // A key whose press changed the screen acts once: held, the // library sends it again (its repeat is that key's while it // runs), and those are the old screen's — Enter's, which // started the conversation, would type line breaks into its // field, and Escape's would go on back, from a sheet through // the conversation and its draft. A new press acts again. if (spentKey == code) { if (Crafter::Device::keyRepeat.active && Crafter::Device::keyRepeat.key == code) return; spentKey.reset(); } if (code == Crafter::Key(CrafterKeys::Escape)) { spentKey = code; Back(); return; } if (sheet) return; if (fresh) { if (code == Crafter::Key(CrafterKeys::Enter) || code == Crafter::Key(CrafterKeys::keypad_enter)) { Start(); if (!fresh) spentKey = code; // started: the conversation's screen is up } else if (ComposeKey(fresh->field, code)) ShowCaret(); if (!repeatTimer) repeatTimer = g_timeout_add(30, OnRepeat, this); return; } if (!view) return; const std::unordered_set& held = canvas->Window().heldKeys; const bool ctrl = held.contains(Crafter::Key(CrafterKeys::LeftCtrl)) || held.contains(Crafter::Key(CrafterKeys::RightCtrl)); if (ctrl && (code == Crafter::Key(CrafterKeys::Enter) || code == Crafter::Key(CrafterKeys::keypad_enter))) { SendDraft(); return; } if (ComposeKey(view->compose, code)) { view->compose.focused = true; ShowCaret(); } // The library repeats a held key only while frames run; with frames // on demand a timer ticks the repeat instead. if (!repeatTimer) repeatTimer = g_timeout_add(30, OnRepeat, this); } static gboolean OnRepeat(gpointer data) { App& self = *static_cast(data); if (!self.canvas || self.canvas->Window().heldKeys.empty()) { self.repeatTimer = 0; return G_SOURCE_REMOVE; } Crafter::Device::TickKeyRepeats(); return G_SOURCE_CONTINUE; } // A tap places the cursor. Inside the composing text it stays where it // is (that span is the input method's); outside, the word is committed // where it was typed and the input method reset, as Send does, so the // half-typed word does not move to the tap. void TapField(ComposeState& s, const ComposeLayout& layout, Point at) { const std::size_t shown = ComposeHit(*canvas, s, layout, at); if (!s.preedit.empty()) { if (shown > s.cursor && shown < s.cursor + s.preedit.size()) return; ComposeCommitPreedit(s); ResetTextInput(); } s.cursor = shown; } // Disables the text input now and lets the next frame enable it // again: an enable resets the input method, the word it was composing // included. void ResetTextInput() { if (!canvas || !lastTextInput.active) return; canvas->Window().SetTextInput(false, 0, 0, 0, 0, lastTextInput.purpose); lastTextInput = {}; } // The caret shows at once after an edit and blinks from there while a // field has the focus and the window is up (without one nothing // draws it; Show starts the blink again). void ShowCaret() { if (blinkTimer) { g_source_remove(blinkTimer); blinkTimer = 0; } if (view) view->caretVisible = true; if (fresh) fresh->caretVisible = true; if (canvas && FocusedField()) blinkTimer = g_timeout_add(500, OnBlink, this); Dirty(); } static gboolean OnBlink(gpointer data) { App& self = *static_cast(data); if (!self.FocusedField()) { self.blinkTimer = 0; return G_SOURCE_REMOVE; } if (self.view) self.view->caretVisible = !self.view->caretVisible; if (self.fresh) self.fresh->caretVisible = !self.fresh->caretVisible; self.Dirty(); return G_SOURCE_CONTINUE; } void LongPress(Point at) { const std::optional id = HitTest(hits, at); if (!id) return; if (*id >= Hit::messageBase && view) { if (const Message* m = HitMessage(*id - Hit::messageBase)) sheet = Sheet{ Sheet::Kind::MessageActions, view->key, m->id, m->text }; } else if (*id >= Hit::rowBase && !view && !fresh) { const std::size_t i = *id - Hit::rowBase; if (i < hitKeys.size()) sheet = Sheet{ Sheet::Kind::DeleteConversation, hitKeys[i], 0, "" }; } if (sheet) EndComposition(); Dirty(); } // Leaving a screen with its field (Open, Back, the +), or a sheet // over the screen, ends the composition of the field that had the // text input, now and not at the next frame's UpdateTextInput: the // word goes into the field as shown and the input method is told. // Left on for that frame, it would send its next commit to the // screen that opens — into another conversation's field — or have // it dropped on a sheet. void EndComposition() { if (!lastTextInput.active) return; CommitComposition(); ResetTextInput(); } // A conversation that no longer exists: its notification goes, and // the view on it closes, its field's text kept as at any leave (a // view closes when its last message is deleted; a conversation // deleted whole takes its draft with it, SheetAction). void ConversationGone(const std::string& key) { if (onConversationDeleted) onConversationDeleted(key); if (view && view->key == key) { StopFling(); CancelGesture(); KeepDraft(); view.reset(); if (sync) sync->SetOpenConversation(std::nullopt); } } void SheetAction(std::uint32_t id) { if (!sheet) return; const Sheet s = *sheet; sheet.reset(); if (id == Hit::sheetDelete) { if (s.kind == Sheet::Kind::DeleteConversation) { if (sync) sync->EraseConversation(s.key); else store.EraseConversation(s.key); } else { if (sync) sync->Erase(s.messageId); else store.Erase(s.messageId); } // Gone once no message is left (the list groups messages) — // not on a delete the store refused: the rows stay, their // notification with them, and the banner says why. if (store.Conversation(s.key).empty()) { ConversationGone(s.key); if (s.kind == Sheet::Kind::DeleteConversation) drafts.Drop(s.key); } Reload(); } else if (id == Hit::sheetCopy) { if (!Crafter::Clipboard::SetText(s.text)) Log("the clipboard did not take the text"); } Dirty(); } void Tap(Point at) { const std::optional id = HitTest(hits, at); if (!id) return; if (*id == Hit::sheetScrim || *id == Hit::sheetCancel || *id == Hit::sheetDelete || *id == Hit::sheetCopy) { SheetAction(*id); } else if (*id == Hit::back) { Back(); } else if (*id == Hit::start) { Start(); } else if (*id == Hit::newField) { if (!fresh) return; TapField(fresh->field, fresh->fieldLayout, at); ShowCaret(); } else if (*id == Hit::compose) { if (!view) return; view->compose.focused = true; TapField(view->compose, view->composeLayout, at); ShowCaret(); } else if (*id == Hit::send) { SendDraft(); } else if (*id == Hit::fab) { NewConversation(); } else if (*id >= Hit::messageBase) { if (!view || !sync) return; const Message* m = HitMessage(*id - Hit::messageBase); if (m && m->state == MessageState::Failed) sync->Retry(m->id); } else if (*id >= Hit::rowBase) { const std::size_t i = *id - Hit::rowBase; if (i < hitKeys.size()) Open(hitKeys[i]); } } MessageStore& store; std::filesystem::path assetDir; std::filesystem::path cacheDir; AppStatus status; Theme theme; std::vector convs; std::optional canvas; std::vector hitKeys; // the conversation each row region named, as drawn std::vector hitMessages; // the message each bubble region named, as drawn std::optional pressedOn; // what the press went down on, as drawn then bool pressGotText = false; // the pressed row had not shown a text of its conversation: no long press (Imported) std::unordered_set textSinceFrame; // the conversations a text arrived for since the regions were recorded std::optional source; std::optional frames; std::optional day; // while the window is up ListScreen list; std::optional view; Drafts drafts; // what was typed in the conversations left and not sent std::optional fresh; // the new-conversation screen std::optional sheet; GestureDetector gestures; std::vector hits; guint longPressTimer = 0; std::int64_t eventClock = 0; // the events' own clock (EventTimeMs), unwrapped std::uint32_t lastRawEventMs = 0; std::int64_t downEventMs = 0; // the press on both clocks: the long-press timer's expiry is mapped from the host's std::int64_t downHostMs = 0; guint repeatTimer = 0; std::optional spentKey; // the key whose press changed the screen (Key) guint blinkTimer = 0; guint hideIdle = 0; // a close's Hide, deferred to the loop std::chrono::steady_clock::time_point lastFrame{}; bool overflowLogged = false; FrameWait frameWait{ .patience = Canvas::framesInFlight + 1 }; // the frames owed to the atlas while glyphs wait for a cell std::filesystem::path screenshotPath; std::optional> downSub; std::optional> upSub; std::optional> touchDownSub; std::optional> touchUpSub; std::optional> touchCancelSub; std::optional touch; // the finger that drives the pointer bool touchUp = false; // its touch-up came before the release std::optional> moveSub; std::optional> scrollSub; std::optional> keySub; std::optional> keyUpSub; std::optional> textSub; std::optional> preeditSub; std::optional> deleteSub; TextInputState lastTextInput; std::optional> resizeSub; std::optional> closeSub; std::optional> seenSub; }; }