Gesture: taps, long presses, drags and flings from pointer phases

What a finger or a mouse did, decided from raw Down/Move/Up/Cancel
phases over the app's own point type: a short press within the slop is a
tap at the press position, a press held past the long-press time (the
host's timer) a long press, movement past the slop a drag with its
deltas, a fast release a fling with a velocity (the last 100 ms of
movement before it: a finger held still before letting go flings
nothing). With it the scroll physics of a list (clamped offset, a
decaying fling that stops at the edges) and the topmost hit region under
a point.

Tested: tests/Gesture.
This commit is contained in:
Jorijn van der Graaf 2026-10-18 00:08:34 +02:00
commit f360a746c2
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
5 changed files with 348 additions and 9 deletions

View file

@ -27,7 +27,7 @@ and §7.9 (Messaging) and §8.1 (the frozen one).
| Path | What it is |
|---|---|
| `project.cpp` | The build description for Crafter.Build: three products (below) and the tests. |
| `interfaces/ImsdMessages*.cppm` | `imsd-messages-core`: std + Crafter.DB, no GLib, no window — numbers, time, the model, word wrap, the store, the sync logic. |
| `interfaces/ImsdMessages*.cppm` | `imsd-messages-core`: std + Crafter.DB, no GLib, no window — numbers, time, the model, word wrap, gestures, the store, the sync logic. |
| `interfaces/ImsdMessages.Bus*.cppm` | `imsd-messages-bus`: GLib/GDBus — imsd's dictionaries, the client, notifications, the app's own bus name. |
| `implementations/main.cpp` | The executable `imsd-messages`. |
| `tests/<Name>/main.cpp` | One test per directory, declared in `project.cpp`. |

View file

@ -0,0 +1,233 @@
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
ImsdMessages:Gesture — what a finger or a mouse did, decided from raw
pointer phases, and the scroll physics of a list. Pure arithmetic over the
app's own point and box types, so the tests feed it by hand.
*/
export module ImsdMessages:Gesture;
import std;
export namespace ImsdMessages {
struct Point {
float x = 0;
float y = 0;
friend bool operator==(const Point&, const Point&) = default;
};
struct Box {
float x = 0;
float y = 0;
float w = 0;
float h = 0;
bool Contains(Point p) const noexcept { return p.x >= x && p.x < x + w && p.y >= y && p.y < y + h; }
float Right() const noexcept { return x + w; }
float Bottom() const noexcept { return y + h; }
friend bool operator==(const Box&, const Box&) = default;
};
enum class PointerPhase : std::uint8_t { Down, Move, Up, Cancel };
struct GestureEvent {
enum class Kind : std::uint8_t { None, Tap, LongPress, DragStart, Drag, Fling, Release };
Kind kind = Kind::None;
Point at; // the press for Tap, LongPress and DragStart; the current position for Drag
Point delta; // Drag: the movement since the previous event
Point velocity; // Fling: pixels per second
};
// One pointer at a time: a press that ends within the slop and before
// the long-press time is a tap; a press held past that time without
// moving is a long press (the host runs the timer and calls Timeout);
// movement past the slop starts a drag whose release is a fling when it
// was fast enough.
class GestureDetector {
public:
float slopPx = 8;
std::int64_t longPressMs = 500;
float flingMinPxPerS = 60;
GestureEvent Feed(PointerPhase phase, Point p, std::int64_t tMs) {
GestureEvent e;
switch (phase) {
case PointerPhase::Down:
pressed = true;
dragging = false;
longPressed = false;
down = p;
downAt = tMs;
last = p;
samples.clear();
samples.push_back({ p, tMs });
break;
case PointerPhase::Move: {
if (!pressed) break;
if (!dragging && !longPressed && (std::abs(p.x - down.x) > slopPx || std::abs(p.y - down.y) > slopPx)) {
dragging = true;
e.kind = GestureEvent::Kind::DragStart;
e.at = down;
last = down;
}
if (dragging) {
if (e.kind == GestureEvent::Kind::DragStart) {
e.delta = { p.x - down.x, p.y - down.y };
} else {
e.kind = GestureEvent::Kind::Drag;
e.delta = { p.x - last.x, p.y - last.y };
e.at = p;
}
}
last = p;
samples.push_back({ p, tMs });
while (samples.size() > 1 && tMs - samples.front().tMs > 100) samples.erase(samples.begin());
break;
}
case PointerPhase::Up: {
if (!pressed) break;
pressed = false;
if (dragging) {
// The velocity is the last 100 ms of movement before
// the release: a finger held still before letting go
// has none, whatever it did before (no event comes
// while it is still).
while (samples.size() > 1 && tMs - samples.front().tMs > 100) samples.erase(samples.begin());
const Point v = Velocity(p, tMs);
if (std::hypot(v.x, v.y) >= flingMinPxPerS) {
e.kind = GestureEvent::Kind::Fling;
e.velocity = v;
} else {
e.kind = GestureEvent::Kind::Release;
}
e.at = p;
} else if (!longPressed && tMs - downAt < longPressMs) {
e.kind = GestureEvent::Kind::Tap;
e.at = down;
} else {
e.kind = GestureEvent::Kind::Release;
e.at = p;
}
dragging = false;
break;
}
case PointerPhase::Cancel:
pressed = false;
dragging = false;
longPressed = false;
break;
}
return e;
}
// The host's timer at Down + longPressMs.
GestureEvent Timeout(std::int64_t tMs) {
GestureEvent e;
if (!pressed || dragging || longPressed || tMs - downAt < longPressMs) return e;
longPressed = true;
e.kind = GestureEvent::Kind::LongPress;
e.at = down;
return e;
}
bool Pressed() const noexcept { return pressed; }
bool Dragging() const noexcept { return dragging; }
private:
struct Sample {
Point p;
std::int64_t tMs;
};
Point Velocity(Point p, std::int64_t tMs) const {
if (samples.empty()) return {};
const Sample& oldest = samples.front();
const std::int64_t dt = tMs - oldest.tMs;
if (dt <= 0) return {};
return { (p.x - oldest.p.x) * 1000.0f / static_cast<float>(dt), (p.y - oldest.p.y) * 1000.0f / static_cast<float>(dt) };
}
bool pressed = false;
bool dragging = false;
bool longPressed = false;
Point down;
Point last;
std::int64_t downAt = 0;
std::vector<Sample> samples;
};
// A scrollable extent: the offset is how far the content moved up.
struct ScrollState {
float offset = 0;
float velocity = 0; // px/s, positive scrolls further down
float content = 0;
float viewport = 0;
float Max() const noexcept { return std::max(0.0f, content - viewport); }
void Clamp() noexcept { offset = std::clamp(offset, 0.0f, Max()); }
void ScrollBy(float dy) noexcept {
offset += dy;
velocity = 0;
Clamp();
}
void Fling(float pxPerS) noexcept { velocity = pxPerS; }
// Advances the fling by dt seconds; true while still moving.
bool Tick(float dt) noexcept {
if (std::abs(velocity) < 20.0f) {
velocity = 0;
return false;
}
const float before = offset;
offset += velocity * dt;
Clamp();
if (offset == before || offset == 0.0f || offset == Max()) {
velocity = 0;
return false;
}
velocity *= std::exp(-4.0f * dt);
return true;
}
};
struct HitRegion {
Box box;
std::uint32_t id = 0;
};
// The topmost region (the last drawn) under a point.
std::optional<std::uint32_t> HitTest(std::span<const HitRegion> regions, Point p) {
for (auto it = regions.rbegin(); it != regions.rend(); ++it) {
if (it->box.Contains(p)) return it->id;
}
return std::nullopt;
}
// What a point names on a drawn frame, by what the region stood for
// rather than its index: a control's id, or — for the regions of a
// list (`rowBase` + the row's index into `keys`) and of a conversation
// (`messageBase` + the bubble's index into `messages`) — the
// conversation or the message. A press is bound to this: a frame
// drawn while the finger is down (a new text snaps the conversation,
// the list re-sorts) that moves another row or bubble under it names
// something else at the release, which then acts on nothing.
struct HitTarget {
std::uint32_t id = 0;
std::string key;
std::uint64_t message = 0;
friend bool operator==(const HitTarget&, const HitTarget&) = default;
};
std::optional<HitTarget> TargetAt(std::span<const HitRegion> regions, Point p, std::uint32_t rowBase, std::span<const std::string> keys, std::uint32_t messageBase, std::span<const std::uint64_t> messages) {
const std::optional<std::uint32_t> id = HitTest(regions, p);
if (!id) return std::nullopt;
if (*id >= messageBase) {
if (const std::size_t i = *id - messageBase; i < messages.size()) return HitTarget{ messageBase, "", messages[i] };
} else if (*id >= rowBase) {
if (const std::size_t i = *id - rowBase; i < keys.size()) return HitTarget{ rowBase, keys[i] };
}
return HitTarget{ *id };
}
}

View file

@ -3,10 +3,10 @@
/*
ImsdMessages — the core of imsd-messages: the parts that need neither the
bus nor a window (numbers, time, the message model, word wrap, the store and
the sync logic), so each of them is unit-testable on a dev box with no phone,
no imsd and no GPU. The bus layer is ImsdMessages.Bus, the window is the
executable.
bus nor a window (numbers, time, the message model, word wrap, gestures,
the store and the sync logic), so each of them is unit-testable on a dev box
with no phone, no imsd and no GPU. The bus layer is ImsdMessages.Bus, the
window is the executable.
*/
export module ImsdMessages;
export import :Number;
@ -15,3 +15,4 @@ export import :Model;
export import :Wrap;
export import :Store;
export import :Sync;
export import :Gesture;

View file

@ -78,9 +78,9 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
? LocalProject({ .projectFile = "../Crafter/Crafter.DB/project.cpp", .args = depArgs })
: GitProject({ .source = { .url = "https://forgejo.catcrafts.net/Catcrafts/Crafter.DB.git" }, .args = depArgs });
// imsd-messages-core — numbers, time, the model, word wrap, the store and
// the sync logic: std + Crafter.DB, no GLib, so every test runs with no
// bus, no phone and no GPU.
// imsd-messages-core — numbers, time, the model, word wrap, gestures,
// the store and the sync logic: std + Crafter.DB, no GLib, so every
// test runs with no bus, no phone and no GPU.
static auto Core = std::make_unique<Configuration>();
Core->path = "./";
Core->name = "imsd-messages-core";
@ -89,7 +89,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
Core->type = ConfigurationType::LibraryStatic;
Core->dependencies = { db };
{
std::array<fs::path, 7> ifaces = {
std::array<fs::path, 8> ifaces = {
"interfaces/ImsdMessages",
"interfaces/ImsdMessages-Number",
"interfaces/ImsdMessages-Time",
@ -97,6 +97,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
"interfaces/ImsdMessages-Wrap",
"interfaces/ImsdMessages-Store",
"interfaces/ImsdMessages-Sync",
"interfaces/ImsdMessages-Gesture",
};
std::array<fs::path, 0> impls = {};
Core->GetInterfacesAndImplementations(ifaces, impls);
@ -148,6 +149,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
cfg.AddTest("Model").Dependencies({ Core.get() });
cfg.AddTest("Store").Dependencies({ Core.get(), db });
cfg.AddTest("Sync").Dependencies({ Core.get() });
cfg.AddTest("Gesture").Dependencies({ Core.get() });
// The bus library's decoding test includes GLib's headers: the library's
// compile flags (its link flags come with the library).
TestBuilder decode = cfg.AddTest("Decode");

103
tests/Gesture/main.cpp Normal file
View file

@ -0,0 +1,103 @@
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Gestures from raw pointer phases: tap, long press by the host's timer,
// drag with its deltas, fling by velocity, cancel; the scroll physics; the
// topmost hit region.
import std;
import ImsdMessages;
using namespace ImsdMessages;
using Kind = GestureEvent::Kind;
namespace {
std::int32_t failures = 0;
void Check(bool ok, std::string_view what) {
std::println("{} {}", ok ? "PASS" : "FAIL", what);
if (!ok) ++failures;
}
}
int main() {
GestureDetector g;
Check(g.Feed(PointerPhase::Down, { 10, 10 }, 0).kind == Kind::None, "a press decides nothing yet");
Check(g.Feed(PointerPhase::Move, { 13, 12 }, 50).kind == Kind::None, "movement within the slop is not a drag");
const GestureEvent tap = g.Feed(PointerPhase::Up, { 13, 12 }, 120);
Check(tap.kind == Kind::Tap && tap.at == Point{ 10, 10 }, "a short press is a tap at the press position");
g.Feed(PointerPhase::Down, { 10, 10 }, 1000);
Check(g.Timeout(1400).kind == Kind::None, "the timer before the long-press time decides nothing");
const GestureEvent lp = g.Timeout(1500);
Check(lp.kind == Kind::LongPress && lp.at == Point{ 10, 10 }, "the timer at the long-press time is a long press");
Check(g.Feed(PointerPhase::Move, { 40, 40 }, 1600).kind == Kind::None, "movement after a long press is not a drag");
Check(g.Feed(PointerPhase::Up, { 40, 40 }, 1700).kind == Kind::Release, "the release after a long press is a plain release");
g.Feed(PointerPhase::Down, { 100, 100 }, 2000);
const GestureEvent start = g.Feed(PointerPhase::Move, { 100, 120 }, 2016);
Check(start.kind == Kind::DragStart && start.at == Point{ 100, 100 } && start.delta == Point{ 0, 20 }, "movement past the slop starts a drag with the whole movement as delta");
const GestureEvent drag = g.Feed(PointerPhase::Move, { 100, 150 }, 2032);
Check(drag.kind == Kind::Drag && drag.delta == Point{ 0, 30 } && drag.at == Point{ 100, 150 }, "a drag reports the delta since the previous event");
Check(g.Dragging(), "dragging");
const GestureEvent fling = g.Feed(PointerPhase::Up, { 100, 200 }, 2048);
Check(fling.kind == Kind::Fling && fling.velocity.y > 1000 && fling.velocity.x == 0, "a fast release is a fling with a velocity in px/s");
Check(g.Timeout(2500).kind == Kind::None, "the timer after a drag decides nothing");
g.Feed(PointerPhase::Down, { 100, 100 }, 3000);
g.Feed(PointerPhase::Move, { 100, 150 }, 3016);
g.Feed(PointerPhase::Move, { 100, 200 }, 3032);
const GestureEvent held = g.Feed(PointerPhase::Up, { 100, 200 }, 3500);
Check(held.kind == Kind::Release, "a release after the finger was held still is not a fling, however fast it moved before");
g.Feed(PointerPhase::Down, { 0, 0 }, 3000);
g.Feed(PointerPhase::Move, { 0, 30 }, 3100);
g.Feed(PointerPhase::Move, { 0, 31 }, 3900);
Check(g.Feed(PointerPhase::Up, { 0, 31 }, 4000).kind == Kind::Release, "a slow release after a drag is a release, not a fling");
g.Feed(PointerPhase::Down, { 0, 0 }, 5000);
g.Feed(PointerPhase::Cancel, { 0, 0 }, 5010);
Check(!g.Pressed() && g.Feed(PointerPhase::Up, { 0, 0 }, 5020).kind == Kind::None, "a cancel forgets the press");
Check(g.Feed(PointerPhase::Down, { 5, 5 }, 6000).kind == Kind::None && g.Feed(PointerPhase::Up, { 5, 5 }, 6600).kind == Kind::Release, "a long press released without the timer is a release");
ScrollState s;
s.content = 1000;
s.viewport = 400;
s.ScrollBy(100);
Check(s.offset == 100 && s.Max() == 600, "scroll by and the maximum");
s.ScrollBy(5000);
Check(s.offset == 600, "the offset clamps at the end");
s.ScrollBy(-5000);
Check(s.offset == 0, "and at the start");
s.Fling(1000);
Check(s.Tick(0.1f) && s.offset > 0 && s.velocity < 1000, "a fling moves the content and slows down");
while (s.Tick(0.1f)) {}
Check(s.velocity == 0 && s.offset > 0 && s.offset <= 600, "a fling comes to rest within the extent");
s.offset = 0;
s.Fling(-500);
Check(!s.Tick(0.1f) && s.offset == 0, "a fling against the edge stops at once");
s.content = 300;
s.offset = 250;
s.Clamp();
Check(s.offset == 0, "content shorter than the viewport has no scroll");
const std::vector<HitRegion> regions = { { { 0, 0, 100, 100 }, 1 }, { { 50, 50, 100, 100 }, 2 } };
Check(HitTest(regions, { 75, 75 }) == std::optional<std::uint32_t>(2), "the last drawn region wins where they overlap");
Check(HitTest(regions, { 10, 10 }) == std::optional<std::uint32_t>(1), "the lower region where only it is");
Check(!HitTest(regions, { 500, 500 }), "nothing outside");
// What a point names, by identity: a bubble that another frame moved
// under the finger names another message, and nothing matches.
const std::vector<HitRegion> frame = { { { 0, 0, 100, 20 }, 7 }, { { 0, 20, 100, 20 }, 1000 }, { { 0, 40, 100, 20 }, 1001 }, { { 0, 60, 100, 20 }, 100000 }, { { 0, 80, 100, 20 }, 100001 } };
const std::vector<std::string> keys = { "+31611111111", "+31622222222" };
const std::vector<std::uint64_t> drawn = { 40, 41 };
const std::vector<std::uint64_t> snapped = { 41, 42 }; // a new text at the bottom: every bubble one slot up
Check(TargetAt(frame, { 5, 5 }, 1000, keys, 100000, drawn) == HitTarget{ 7 }, "a control names its id");
Check(TargetAt(frame, { 5, 45 }, 1000, keys, 100000, drawn) == HitTarget{ 1000, "+31622222222" }, "a row names its conversation");
Check(TargetAt(frame, { 5, 85 }, 1000, keys, 100000, drawn) == HitTarget{ 100000, "", 41 }, "a bubble names its message");
Check(!TargetAt(frame, { 5, 150 }, 1000, keys, 100000, drawn), "nothing under the point names nothing");
Check(TargetAt(frame, { 5, 85 }, 1000, keys, 100000, snapped) != TargetAt(frame, { 5, 85 }, 1000, keys, 100000, drawn), "the frame that moved another bubble under the point names it: the release matches no press");
Check(TargetAt(frame, { 5, 65 }, 1000, keys, 100000, snapped) == TargetAt(frame, { 5, 85 }, 1000, keys, 100000, drawn), "the same message, moved, still names itself");
return failures == 0 ? 0 : 1;
}