diff --git a/implementations/main.cpp b/implementations/main.cpp index 63f93bd..a8c18c6 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -394,11 +394,13 @@ int main(int argc, char** argv) { app.emplace(*store, AssetDir(), CacheDir()); if (o.screenshot) app->exitCode = 1; // an asked-for screenshot is a failure until the PNG is written: a run that ends first says so app->closeQuits = session == nullptr; + app->appId = std::string(Bus::appId); app->sync = &sync; app->onQuit = [loop] { g_main_loop_quit(loop); }; app->onConversationOpened = [¬ifier](const std::string& conversation) { notifier.Close(conversation); }; app->onConversationDeleted = [¬ifier](const std::string& conversation) { notifier.Close(conversation); }; app->onLog = Log; + app->verbose = o.headless; // a log line that names a correspondent is the smoke test's alone // The compositor's connection broke, and the process cannot connect its // display again: it ends (the store flushed, the name freed), so the next // launch starts afresh. diff --git a/interfaces/ImsdMessages-Edit.cppm b/interfaces/ImsdMessages-Edit.cppm index a234f90..33d3fa5 100644 --- a/interfaces/ImsdMessages-Edit.cppm +++ b/interfaces/ImsdMessages-Edit.cppm @@ -18,9 +18,19 @@ export namespace ImsdMessages { struct ComposeState { std::string value; std::size_t cursor = 0; // a byte offset on a code point boundary - bool focused = true; + std::string preedit; // the input method's composing text: shown at the cursor, not yet in the value + bool focused = false; }; + // The text as shown: the value with the composing text at the cursor. + std::string ComposeShown(const ComposeState& s) { + std::string shown = s.value; + shown.insert(s.cursor, s.preedit); + return shown; + } + + std::size_t ShownCursor(const ComposeState& s) { return s.cursor + s.preedit.size(); } + // The byte offset of the code point before `at`. std::size_t PreviousCodepoint(std::string_view s, std::size_t at) { if (at == 0) return 0; @@ -41,6 +51,18 @@ export namespace ImsdMessages { c.cursor += utf8.size(); } + // The input method's deletion: so many bytes before and after the cursor, + // rounded out to code points. The composing text stays; the input method + // replaces it when it changes. + void ComposeDeleteAround(ComposeState& c, std::size_t beforeBytes, std::size_t afterBytes) { + std::size_t from = c.cursor; + while (from > 0 && c.cursor - from < beforeBytes) from = PreviousCodepoint(c.value, from); + std::size_t to = c.cursor; + while (to < c.value.size() && to - c.cursor < afterBytes) to = NextCodepoint(c.value, to); + c.value.erase(from, to - from); + c.cursor = from; + } + enum class EditKey : std::uint8_t { Backspace, Delete, Left, Right, Home, End, Newline }; // Applies one key. False when Backspace or Delete has nothing to delete; @@ -103,6 +125,15 @@ export namespace ImsdMessages { return caretLine + 1 > shown ? caretLine + 1 - shown : 0; } + // Takes the composing text into the value at the cursor, as the input + // method would commit it: what Send and Start read is what the field shows. + void ComposeCommitPreedit(ComposeState& c) { + if (c.preedit.empty()) return; + const std::string preedit = std::move(c.preedit); + c.preedit.clear(); + ComposeInsert(c, preedit); + } + // What was typed in the conversations that were left, and not sent, by // conversation key, for this run. A draft is its conversation's, not // the view's: leaving the conversation keeps it, opening it again @@ -110,15 +141,17 @@ export namespace ImsdMessages { // deleted. class Drafts { public: - // A conversation is left: what its field holds is kept and comes - // back as a field is opened; an empty field keeps nothing and drops - // nothing. `dialled` and `plan` are the view's: the address as typed - // or linked — "" for a conversation opened from the list, whose - // draft Status leaves where it is — and the plan of the SIM it was - // opened under. A second text kept under one key (two keys that - // became one: Status, and the open conversation's own move) goes - // after the first on a line of its own, so nothing typed is dropped. + // A conversation is left: what its field holds is kept — a word + // still being composed as text — and comes back as a field is + // opened; an empty field keeps nothing and drops nothing. `dialled` + // and `plan` are the view's: the address as typed or linked — "" + // for a conversation opened from the list, whose draft Status + // leaves where it is — and the plan of the SIM it was opened + // under. A second text kept under one key (two keys that became + // one: Status, and the open conversation's own move) goes after + // the first on a line of its own, so nothing typed is dropped. void Keep(std::string_view key, ComposeState field, std::string_view dialled = {}, SimPlan plan = {}) { + ComposeCommitPreedit(field); if (field.value.empty()) return; field.focused = ComposeState{}.focused; const auto kept = byKey.find(key); diff --git a/interfaces/ImsdMessages.Ui-App.cppm b/interfaces/ImsdMessages.Ui-App.cppm index 5c31758..e751b49 100644 --- a/interfaces/ImsdMessages.Ui-App.cppm +++ b/interfaces/ImsdMessages.Ui-App.cppm @@ -6,9 +6,10 @@ 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 (touch joins them once Crafter.Graphics delivers it), 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. +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 @@ -48,16 +49,26 @@ export namespace ImsdMessages::Ui { 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 + // it does not carry 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(); day.reset(); @@ -101,6 +112,8 @@ export namespace ImsdMessages::Ui { 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 @@ -132,7 +145,7 @@ export namespace ImsdMessages::Ui { } canvas.emplace(); try { - canvas->Create(400, 800, "Messages", assetDir, cacheDir); + 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 @@ -163,7 +176,27 @@ export namespace ImsdMessages::Ui { canvas->onDraw = [this](VkCommandBuffer cmd) { Build(cmd); }; Crafter::Window& w = canvas->Window(); downSub.emplace(&w.onMouseLeftClick, [this] { Pointer(PointerPhase::Down); }); - upSub.emplace(&w.onMouseLeftRelease, [this] { Pointer(PointerPhase::Up); }); + // 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); }); @@ -187,15 +220,37 @@ export namespace ImsdMessages::Ui { // 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(); } }); - resizeSub.emplace(&w.onResize, [this] { Dirty(); }); + // 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(); }); Reload(); Opened(); @@ -246,6 +301,9 @@ export namespace ImsdMessages::Ui { // 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(); @@ -261,6 +319,8 @@ export namespace ImsdMessages::Ui { 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(); @@ -287,6 +347,7 @@ export namespace ImsdMessages::Ui { } if (fresh) { CancelGesture(); + EndComposition(); fresh.reset(); Dirty(); return; @@ -294,6 +355,7 @@ export namespace ImsdMessages::Ui { if (!view) return; StopFling(); CancelGesture(); + EndComposition(); KeepDraft(); view.reset(); if (blinkTimer) { @@ -308,10 +370,12 @@ export namespace ImsdMessages::Ui { void NewConversation() { StopFling(); CancelGesture(); + EndComposition(); KeepDraft(); view.reset(); sheet.reset(); fresh.emplace(); + fresh->field.focused = true; Show(); if (sync) sync->SetOpenConversation(std::nullopt); ShowCaret(); @@ -320,13 +384,17 @@ export namespace ImsdMessages::Ui { // Start, from the new-conversation screen: a number becomes a key. void Start() { if (!fresh) return; - const std::string key = ConversationKey(fresh->field.value, sync ? sync->CountryCode() : ""); + // 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(fresh->field.value); + 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); } @@ -334,9 +402,13 @@ export namespace ImsdMessages::Ui { // 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) ComposeInsert(view->compose, text); - Dirty(); + if (fresh) { + ComposeInsert(fresh->field, text); + } else if (view) { + view->compose.focused = true; + ComposeInsert(view->compose, text); + } + ShowCaret(); } void BenchSheet(std::string_view which) { @@ -346,6 +418,7 @@ export namespace ImsdMessages::Ui { 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(); } @@ -355,14 +428,21 @@ export namespace ImsdMessages::Ui { // 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 the field's text to the open conversation. + // 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 || view->compose.value.empty() || !CanSend(status) || Destination().empty()) return; - std::string text = view->compose.value; + 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(); - // A store that refuses the text (its disk full) keeps the draft. if (!text.empty() && sync->Send(view->key, Destination(), text) == Sync::kNotStored) return; - view->compose = ComposeState{}; + view->compose = ComposeState{ .focused = true }; + ResetTextInput(); view->stickToBottom = true; Dirty(); } @@ -520,6 +600,7 @@ export namespace ImsdMessages::Ui { 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(); @@ -533,6 +614,46 @@ export namespace ImsdMessages::Ui { } } + 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); + } + 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 @@ -644,7 +765,10 @@ export namespace ImsdMessages::Ui { SendDraft(); return; } - if (ComposeKey(view->compose, code)) ShowCaret(); + 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); @@ -660,21 +784,46 @@ export namespace ImsdMessages::Ui { return G_SOURCE_CONTINUE; } - // The caret shows at once after an edit and blinks from there while - // the window is up (without one nothing draws it; Show starts the - // blink again). + // 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 (!view && !fresh) return; + if (blinkTimer) { + g_source_remove(blinkTimer); + blinkTimer = 0; + } if (view) view->caretVisible = true; if (fresh) fresh->caretVisible = true; - if (blinkTimer) g_source_remove(blinkTimer); - blinkTimer = canvas ? g_timeout_add(500, OnBlink, this) : 0; + if (canvas && FocusedField()) blinkTimer = g_timeout_add(500, OnBlink, this); Dirty(); } static gboolean OnBlink(gpointer data) { App& self = *static_cast(data); - if (!self.view && !self.fresh) { + if (!self.FocusedField()) { self.blinkTimer = 0; return G_SOURCE_REMOVE; } @@ -693,9 +842,23 @@ export namespace ImsdMessages::Ui { 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 @@ -748,12 +911,12 @@ export namespace ImsdMessages::Ui { Start(); } else if (*id == Hit::newField) { if (!fresh) return; - fresh->field.cursor = ComposeHit(*canvas, fresh->field, fresh->fieldLayout, at); + TapField(fresh->field, fresh->fieldLayout, at); ShowCaret(); } else if (*id == Hit::compose) { if (!view) return; view->compose.focused = true; - view->compose.cursor = ComposeHit(*canvas, view->compose, view->composeLayout, at); + TapField(view->compose, view->composeLayout, at); ShowCaret(); } else if (*id == Hit::send) { SendDraft(); @@ -800,11 +963,19 @@ export namespace ImsdMessages::Ui { 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; }; diff --git a/interfaces/ImsdMessages.Ui-Canvas.cppm b/interfaces/ImsdMessages.Ui-Canvas.cppm index 198b520..9ae0958 100644 --- a/interfaces/ImsdMessages.Ui-Canvas.cppm +++ b/interfaces/ImsdMessages.Ui-Canvas.cppm @@ -153,7 +153,7 @@ export namespace ImsdMessages::Ui { // The device once per process, then the window, the heap, the font, // the atlas, the renderer and the layers. Sizes in dp; the // compositor decides the real size on a phone anyway. - void Create(std::uint32_t widthDp, std::uint32_t heightDp, std::string_view title, const std::filesystem::path& assetDir, const std::filesystem::path& cacheDir) { + void Create(std::uint32_t widthDp, std::uint32_t heightDp, std::string_view title, std::string_view appId, const std::filesystem::path& assetDir, const std::filesystem::path& cacheDir) { static bool deviceReady = false; static std::string deviceError; // the library's set-up cannot run twice: a failure is final if (!deviceError.empty()) throw std::runtime_error(deviceError); @@ -170,6 +170,7 @@ export namespace ImsdMessages::Ui { deviceReady = true; } window.emplace(widthDp, heightDp, title); + window->SetAppId(appId); VkCommandBuffer init = window->StartInit(); heap.Initialize(16, 32, 4); window->descriptorHeap = &heap; diff --git a/interfaces/ImsdMessages.Ui-Compose.cppm b/interfaces/ImsdMessages.Ui-Compose.cppm index ae6736c..08b51fe 100644 --- a/interfaces/ImsdMessages.Ui-Compose.cppm +++ b/interfaces/ImsdMessages.Ui-Compose.cppm @@ -7,7 +7,8 @@ InputField is one line and erases single bytes, which breaks UTF-8; a text message needs neither limit, so the field's state and its editing are the core's (ImsdMessages:Edit). Here the keys become its EditKeys, and the draw function lays the field out with the canvas's word wrapper and -reports where the text sits, so a tap can place the cursor. +reports where the text sits, so a tap can place the cursor, and where the +caret is, for the input method. */ module; #include "vulkan/vulkan.h" @@ -44,6 +45,7 @@ export namespace ImsdMessages::Ui { float lineHeight = 0; float px = 0; std::size_t first = 0; // the first line drawn: a longer text shows the lines around the caret + Box caret; // where the caret is, drawn or not: the input method's cursor rectangle }; // The lines the field's box shows: as many as it is tall, at least one. @@ -51,9 +53,9 @@ export namespace ImsdMessages::Ui { return std::max(1, static_cast(std::lround(layout.text.h / layout.lineHeight))); } - // The field's text: one to five lines tall, a placeholder when empty, the - // caret at the cursor; the box itself is the caller's, whose screen - // decides its fill and outline. Returns the layout the app needs for taps. + // Draws the field's text and lays it out; the box itself is the caller's, + // whose screen decides its fill and outline. The layout reports where the + // text sits (for a tap) and the caret (for the input method), drawn or not. ComposeLayout DrawCompose(Canvas& c, const ComposeState& s, Box field, bool caretVisible, std::string_view placeholder = "Message") { const float px = c.Dp(16); const float padX = c.Dp(12); @@ -62,17 +64,21 @@ export namespace ImsdMessages::Ui { layout.px = px; layout.lineHeight = c.LineHeight(px); layout.text = { field.x + padX, field.y + padY, field.w - 2 * padX, field.h - 2 * padY }; - if (s.value.empty()) { + const std::string shown = ComposeShown(s); + const std::size_t cursor = ShownCursor(s); + const std::size_t preeditBegin = s.cursor; + const std::size_t preeditEnd = s.cursor + s.preedit.size(); + if (shown.empty()) { c.chrome.Text(placeholder, layout.text.x, layout.text.y + c.Ascent(px), c.Font(), px, c.theme.muted); layout.lines = { { 0, 0, 0 } }; } else { - layout.lines = c.Wrapper().Wrap(s.value, px, layout.text.w); + layout.lines = c.Wrapper().Wrap(shown, px, layout.text.w); } // The caret's line: the last line that starts at or before the // cursor; a cursor right after a break belongs to the next line. std::size_t li = 0; for (std::size_t i = 0; i < layout.lines.size(); ++i) { - if (layout.lines[i].begin <= s.cursor) li = i; + if (layout.lines[i].begin <= cursor) li = i; } // The field holds as many lines as its box is tall (the bar grows it // to composeMaxLines; a one-line box shows one): a longer text shows @@ -83,43 +89,51 @@ export namespace ImsdMessages::Ui { float baseline = layout.text.y + c.Ascent(px); for (std::size_t i = layout.first; i < last; ++i) { const WrappedLine& l = layout.lines[i]; - if (!s.value.empty()) c.chrome.Text(std::string_view(s.value).substr(l.begin, l.end - l.begin), layout.text.x, baseline, c.Font(), px, c.theme.text); + // Up to three runs: before, inside and after the composing text, + // which shows in the accent colour until the input method commits it. + float x = layout.text.x; + const std::size_t bounds[4] = { l.begin, std::clamp(preeditBegin, l.begin, l.end), std::clamp(preeditEnd, l.begin, l.end), l.end }; + for (std::int32_t run = 0; run < 3; ++run) { + if (bounds[run + 1] <= bounds[run]) continue; + const std::string_view part = std::string_view(shown).substr(bounds[run], bounds[run + 1] - bounds[run]); + x += c.chrome.Text(part, x, baseline, c.Font(), px, run == 1 ? c.theme.accent : c.theme.text); + } baseline += layout.lineHeight; } - if (s.focused && caretVisible) { - const WrappedLine& l = layout.lines[li]; - const std::size_t end = std::min(s.cursor, l.end); - const float x = layout.text.x + (end > l.begin ? c.TextWidth(std::string_view(s.value).substr(l.begin, end - l.begin), px) : 0.0f); - const float y = layout.text.y + layout.lineHeight * static_cast(li - layout.first); - c.chrome.Quad({ x, y + c.Dp(2), c.Dp(2), layout.lineHeight - c.Dp(4) }, c.theme.accent); - } + const WrappedLine& l = layout.lines[li]; + const std::size_t end = std::min(cursor, l.end); + const float cx = layout.text.x + (end > l.begin ? c.TextWidth(std::string_view(shown).substr(l.begin, end - l.begin), px) : 0.0f); + const float cy = layout.text.y + layout.lineHeight * static_cast(li - layout.first); + layout.caret = { cx, cy + c.Dp(2), c.Dp(2), layout.lineHeight - c.Dp(4) }; + if (s.focused && caretVisible) c.chrome.Quad(layout.caret, c.theme.accent); return layout; } - // The number of lines the field needs for its text, one to five. + // How many lines the field needs for its text, one to five. std::size_t ComposeLines(Canvas& c, const ComposeState& s, float textWidth) { - if (s.value.empty()) return 1; - return std::clamp(c.Wrapper().Wrap(s.value, c.Dp(16), textWidth).size(), 1, composeMaxLines); + if (s.value.empty() && s.preedit.empty()) return 1; + return std::clamp(c.Wrapper().Wrap(ComposeShown(s), c.Dp(16), textWidth).size(), 1, composeMaxLines); } - // The byte offset in the text a tap at p asks for (App's Tap makes it - // the cursor). The lines are the text's as it is now: an edit since the - // frame that laid the field out only asked for a frame, so the layout's - // lines may describe text that is gone. + // The byte offset in the shown text a tap at p asks for (App::TapField + // makes it the cursor). The lines are the text's as it is now: an edit + // since the frame that laid the field out only asked for a frame, so the + // layout's lines may describe text that is gone. std::size_t ComposeHit(Canvas& c, const ComposeState& s, const ComposeLayout& layout, Point p) { - if (s.value.empty()) return 0; - if (layout.lineHeight <= 0) return s.value.size(); // no frame has laid the field out (a view just opened): the text's end - const std::vector& lines = c.Wrapper().Wrap(s.value, layout.px, layout.text.w); + const std::string shown = ComposeShown(s); + if (shown.empty()) return 0; + if (layout.lineHeight <= 0) return shown.size(); // no frame has laid the field out (a view just opened): the text's end + const std::vector& lines = c.Wrapper().Wrap(shown, layout.px, layout.text.w); if (lines.empty()) return 0; std::size_t li = layout.first + static_cast(std::max(0.0f, (p.y - layout.text.y) / layout.lineHeight)); li = std::min(li, layout.first + ComposeShownLines(layout) - 1); // the drawn lines only: the padding below belongs to the last li = std::min(li, lines.size() - 1); const WrappedLine& l = lines[li]; - const std::string_view line = std::string_view(s.value).substr(l.begin, l.end - l.begin); + const std::string_view line = std::string_view(shown).substr(l.begin, l.end - l.begin); const std::size_t byte = c.NearestByte(line, layout.px, p.x - layout.text.x); // At or past the line's end: the text's end on the last line, the // newline after a hung space before a hard break (Edit's ComposeLineEnd). - if (byte == line.size()) return ComposeLineEnd(lines, li, s.value); + if (byte == line.size()) return ComposeLineEnd(lines, li, shown); return l.begin + byte; } } diff --git a/interfaces/ImsdMessages.Ui-Screens.cppm b/interfaces/ImsdMessages.Ui-Screens.cppm index 5550a37..118f296 100644 --- a/interfaces/ImsdMessages.Ui-Screens.cppm +++ b/interfaces/ImsdMessages.Ui-Screens.cppm @@ -170,7 +170,7 @@ export namespace ImsdMessages::Ui { c.chrome.Quad(field, c.theme.bg, c.Dp(18)); // the field's box on the surface bar composeLayout = DrawCompose(c, compose, field, caretVisible); hits.push_back({ field, Hit::compose }); - const bool enabled = canSend && !compose.value.empty(); + const bool enabled = canSend && !(compose.value.empty() && compose.preedit.empty()); const Box button{ field.Right() + c.Dp(8), bar.Bottom() - c.Dp(10) - c.Dp(40), sendW, c.Dp(40) }; c.chrome.Quad(button, enabled ? c.theme.accent : c.theme.divider, c.Dp(20)); c.chrome.Text("Send", button.x + button.w / 2, c.CenteredBaseline(button, c.Dp(15)), c.Font(), c.Dp(15), enabled ? c.theme.onAccent : c.theme.muted, Crafter::TextAlign::Center); @@ -278,7 +278,7 @@ export namespace ImsdMessages::Ui { const std::string hint = error.empty() ? "Like +31 6 1234 5678 or 06 1234 5678" : error; c.chrome.Text(c.Wrapper().Ellipsize(hint, c.Dp(13), w), x, y + c.Ascent(c.Dp(13)), c.Font(), c.Dp(13), error.empty() ? c.theme.muted : c.theme.danger); y += c.LineHeight(c.Dp(13)) + c.Dp(20); - const bool enabled = !field.value.empty(); + const bool enabled = !(field.value.empty() && field.preedit.empty()); const Box button{ x, y, w, c.Dp(44) }; c.chrome.Quad(button, enabled ? c.theme.accent : c.theme.divider, c.Dp(22)); c.chrome.Text("Start", button.x + button.w / 2, c.CenteredBaseline(button, c.Dp(16)), c.Font(), c.Dp(16), enabled ? c.theme.onAccent : c.theme.muted, Crafter::TextAlign::Center); diff --git a/tests/Edit/main.cpp b/tests/Edit/main.cpp index 6237c8a..a91ed06 100644 --- a/tests/Edit/main.cpp +++ b/tests/Edit/main.cpp @@ -2,7 +2,8 @@ // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® // The message field's editing by code point: one to four bytes of UTF-8, -// and the lines of a text with newlines. +// the lines of a text with newlines, and the input method's composing +// text and deletions. import std; import ImsdMessages; using namespace ImsdMessages; @@ -89,6 +90,37 @@ int main() { Check(s.cursor == 3, "an insert moves the cursor past its bytes"); CheckEqual(s.value, "aéb", "the text after an insert"); + // The input method's composing text: shown at the cursor, not in the value. + s = At("hello", 2); + s.preedit = "XY"; + CheckEqual(ComposeShown(s), "heXYllo", "the composing text shows at the cursor"); + Check(ShownCursor(s) == 4, "the shown cursor follows the composing text"); + + // Its deletions: byte counts around the cursor, rounded out to code points. + s = At(mixed, 6); + s.preedit = "z"; + ComposeDeleteAround(s, 1, 1); + Check(s.cursor == 3 && s.preedit == "z", "one byte each side takes the € before and the 😀 after; the composing text stays"); + CheckEqual(s.value, "a\u00e9", "what is left after the deletion"); + s = At("abc", 1); + ComposeDeleteAround(s, 5, 0); + Check(s.cursor == 0, "a deletion past the start stops at the start"); + CheckEqual(s.value, "bc", "what is left after it"); + s = At("abc", 2); + ComposeDeleteAround(s, 0, 0); + Check(s.cursor == 2 && s.value == "abc", "a deletion of nothing leaves the text"); + + // The composition ends into the field when the text input goes off + // (a sheet, a tap elsewhere): the word as shown. + s = At("hello wor", 9); + s.preedit = "ld"; + ComposeCommitPreedit(s); + Check(s.cursor == 11 && s.preedit.empty(), "committing the composing text moves the cursor past it"); + CheckEqual(s.value, "hello world", "and puts it into the value"); + s = At("a", 0); + ComposeCommitPreedit(s); + Check(s.value == "a" && s.cursor == 0, "with no composing text nothing changes"); + // A tap at or past a line's end: the text's end on the last line, the // newline after a hung space before a hard break, the line's end at a // soft wrap (the lines as tests/Wrap pins them, 10 px a glyph, 50 px wide). @@ -140,6 +172,12 @@ int main() { drafts.Drop("+31612345678"); drafts.Drop("no such conversation"); Check(drafts.Size() == 0, "a deleted conversation's draft goes with it"); + ComposeState composing; + ComposeInsert(composing, "hello "); + composing.preedit = "wor"; + drafts.Keep("1234", composing); + const ComposeState kept = drafts.Take("1234"); + Check(kept.value == "hello wor" && kept.preedit.empty() && kept.cursor == 9, "a word still being composed is kept as text"); } // A kept typed address follows imsd's status as an open conversation's // key does: typed before the country code was known, found after.