Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

web: scroll the scrollback by the pixel, with a Scrolling setting

RoversXb23c5c59b6fb
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftl
index 357646d3..234f9642 100644
--- a/thinkterm-i18n/i18n/de-DE.ftl
+++ b/thinkterm-i18n/i18n/de-DE.ftl
@@ -830,6 +830,9 @@ web-settings-theme = Design
web-theme-dark = Dunkel
web-theme-light = Hell
web-theme-system = Systemeinstellung folgen
+web-settings-scroll-mode = Scrollen
+web-scroll-mode-stepped = Zeilenweise
+web-scroll-mode-smooth = Weich
web-settings-font = Schriftgröße
web-font-follow = Dem Desktop folgen
web-font-pinned = Feste Größe
@@ -844,6 +847,7 @@ web-settings-build = Build
web-settings-language-description = Die Sprache der Seite. „Systemeinstellung folgen“ nimmt die des Browsers.
web-settings-hotkey-description = Öffnet die Suche von überall auf der Seite.
web-settings-theme-description = Dunkel, hell oder wie das System eingestellt ist.
+web-settings-scroll-mode-description = „Weich“ folgt Finger und Trackpad pixelgenau; „Zeilenweise“ springt jeweils eine ganze Zeile.
web-settings-font-description = Der Zelle des Desktops folgen, damit beide dasselbe Raster zeigen, oder eine eigene Größe für diese Seite behalten.
web-settings-scheme = Farbschema
web-settings-scheme-description = Dem im Server eingestellten Farbschema folgen oder eines nur für diesen Browser wählen.
diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftl
index b1da2926..4134567e 100644
--- a/thinkterm-i18n/i18n/en-US.ftl
+++ b/thinkterm-i18n/i18n/en-US.ftl
@@ -822,6 +822,9 @@ web-settings-theme = Theme
web-theme-dark = Dark
web-theme-light = Light
web-theme-system = Follow System
+web-settings-scroll-mode = Scrolling
+web-scroll-mode-stepped = Stepped
+web-scroll-mode-smooth = Smooth
web-settings-font = Font size
web-font-follow = Follow the desktop
web-font-pinned = Fixed size
@@ -844,6 +847,7 @@ web-settings-build = Build
web-settings-language-description = The language of the page. "Follow System" takes the browser's.
web-settings-hotkey-description = Opens the search from anywhere on the page.
web-settings-theme-description = Dark, light, or whatever the system is set to.
+web-settings-scroll-mode-description = Smooth follows a finger or a trackpad by the pixel; stepped moves a whole row at a time.
web-settings-font-description = Follow the desktop's cell so both show the same grid, or keep a size of this page's own.
web-settings-scheme = Color scheme
web-settings-scheme-description = Follow the color scheme the server is configured with, or pick one for this browser alone.
diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftl
index b0209b63..112738f9 100644
--- a/thinkterm-i18n/i18n/fr-FR.ftl
+++ b/thinkterm-i18n/i18n/fr-FR.ftl
@@ -827,6 +827,9 @@ web-settings-theme = Thème
web-theme-dark = Sombre
web-theme-light = Clair
web-theme-system = Suivre le système
+web-settings-scroll-mode = Défilement
+web-scroll-mode-stepped = Par ligne
+web-scroll-mode-smooth = Fluide
web-settings-font = Taille de police
web-font-follow = Suivre le bureau
web-font-pinned = Taille fixe
@@ -841,6 +844,7 @@ web-settings-build = Version
web-settings-language-description = La langue de la page. « Suivre le système » prend celle du navigateur.
web-settings-hotkey-description = Ouvre la recherche depuis n’importe où sur la page.
web-settings-theme-description = Sombre, clair, ou ce que le système a choisi.
+web-settings-scroll-mode-description = « Fluide » suit le doigt ou le pavé tactile au pixel près ; « Par ligne » avance d’une ligne entière à la fois.
web-settings-font-description = Suivre la cellule du bureau pour afficher la même grille des deux côtés, ou garder une taille propre à cette page.
web-settings-scheme = Palette de couleurs
web-settings-scheme-description = Suivre la palette configurée sur le serveur, ou en choisir une pour ce navigateur seulement.
diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftl
index be113cb4..06ef70ec 100644
--- a/thinkterm-i18n/i18n/ja-JP.ftl
+++ b/thinkterm-i18n/i18n/ja-JP.ftl
@@ -808,6 +808,9 @@ web-settings-theme = テーマ
web-theme-dark = ダーク
web-theme-light = ライト
web-theme-system = システム設定に従う
+web-settings-scroll-mode = スクロール
+web-scroll-mode-stepped = 行単位
+web-scroll-mode-smooth = スムーズ
web-settings-font = フォントサイズ
web-font-follow = デスクトップに従う
web-font-pinned = サイズを固定
@@ -822,6 +825,7 @@ web-settings-build = ビルド
web-settings-language-description = ページの言語。「システム設定に従う」はブラウザの言語を使います。
web-settings-hotkey-description = ページのどこからでも検索を開きます。
web-settings-theme-description = ダーク、ライト、またはシステムの設定に従います。
+web-settings-scroll-mode-description = 「スムーズ」は指やトラックパッドにピクセル単位で追従し、「行単位」は 1 行ずつ動きます。
web-settings-font-description = デスクトップのセルに合わせて同じグリッドを表示するか、このページ独自のサイズを保ちます。
web-settings-scheme = カラースキーム
web-settings-scheme-description = サーバーに設定されたカラースキームに従うか、このブラウザーだけのものを選びます。
diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftl
index c90f1222..f088b69e 100644
--- a/thinkterm-i18n/i18n/zh-CN.ftl
+++ b/thinkterm-i18n/i18n/zh-CN.ftl
@@ -808,6 +808,9 @@ web-settings-theme = 主题
web-theme-dark = 深色
web-theme-light = 浅色
web-theme-system = 跟随系统
+web-settings-scroll-mode = 滚动方式
+web-scroll-mode-stepped = 逐行
+web-scroll-mode-smooth = 平滑
web-settings-font = 字号
web-font-follow = 跟随桌面端
web-font-pinned = 固定字号
@@ -822,6 +825,7 @@ web-settings-build = 构建
web-settings-language-description = 页面的语言。“跟随系统”使用浏览器的语言。
web-settings-hotkey-description = 在页面任意位置打开搜索。
web-settings-theme-description = 深色、浅色,或跟随系统设置。
+web-settings-scroll-mode-description = “平滑”按像素跟随手指或触控板;“逐行”每次移动一整行。
web-settings-font-description = 跟随桌面端的单元格,让两边显示同样的网格;或使用本页面自己的固定字号。
web-settings-scheme = 配色方案
web-settings-scheme-description = 跟随服务端配置的配色方案,或只为这个浏览器单独选一套。
diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rs
index 02d14282..55cb4105 100644
--- a/thinkterm-web/src/app.rs
+++ b/thinkterm-web/src/app.rs
@@ -6,7 +6,7 @@ use crate::glyphs::GlyphCache;
use crate::gpu::Gpu;
use crate::host::WebHost;
use crate::link::WsLink;
-use crate::viewport::{cell_at, max_scroll, visible_rows};
+use crate::viewport::{cell_at, max_scroll, visible_rows, visible_rows_px};
use anyhow::Result;
use codec::Pdu;
use std::cell::{Cell, RefCell};
@@ -121,6 +121,12 @@ struct Hit {
pub struct PaneCell {
pub session: Arc<PaneSession<WebHost>>,
pub scroll_from_bottom: usize,
+ /// How far the top visible row is cut off at its top, in device px,
+ /// always inside `[0, cell_h)`: the part of a row that smooth
+ /// scrolling is through. Zero means the view sits on a row boundary,
+ /// which is the only position stepped mode ever holds and the only
+ /// one either end of the scrollback allows.
+ pub scroll_px: f32,
pub selection: Option<Selection>,
/// The pane's own colours (OSC 4/10/11), pushed as `SetApplicationPalette`,
/// exactly as they arrived. `None` means the base palette shows through.
@@ -143,6 +149,7 @@ impl PaneCell {
reconnect_stale: false,
session,
scroll_from_bottom: 0,
+ scroll_px: 0.0,
selection: None,
application: None,
palette: ColorPalette::default(),
@@ -250,6 +257,11 @@ pub struct Inner {
connected_since: Option<f64>,
quads: HeapQuadAllocator,
vertices: Vec<Vertex>,
+ /// Where a row that hangs over the edge of its pane's content box is
+ /// recorded before being replayed cropped. One row at a time, emptied
+ /// and refilled: at most two rows per pane per frame go through it,
+ /// and it is never allocated inside the paint.
+ scratch: HeapQuadAllocator,
/// Panes at their own font size (Cmd+= / Cmd+-), as on the desktop:
/// each has its own glyph cache and atlas, and is drawn as its own
/// batch. Absent means the page's size.
@@ -512,6 +524,7 @@ impl App {
published_bg: None,
quads: HeapQuadAllocator::default(),
vertices: Vec::new(),
+ scratch: HeapQuadAllocator::default(),
pane_fonts: Default::default(),
layout: None,
tab_layout: None,
@@ -1232,6 +1245,7 @@ impl App {
// Typing goes back to following the output.
let cell = inner.focused_mut();
cell.scroll_from_bottom = 0;
+ cell.scroll_px = 0.0;
cell.selection = None;
let start = cell.session.key_down(serial, key, mods);
Self::spawn_drain(&cell.session, start);
@@ -1266,6 +1280,7 @@ impl App {
}
let cell = inner.focused_mut();
cell.scroll_from_bottom = 0;
+ cell.scroll_px = 0.0;
let start = cell.session.write_bytes(text.as_bytes());
Self::spawn_drain(&cell.session, start);
drop(inner);
@@ -1279,6 +1294,7 @@ impl App {
}
let cell = inner.focused_mut();
cell.scroll_from_bottom = 0;
+ cell.scroll_px = 0.0;
let start = cell.session.paste(text);
Self::spawn_drain(&cell.session, start);
drop(inner);
@@ -1679,10 +1695,22 @@ impl App {
let root = inner.glyphs.metrics.cell_size;
let nav = Self::content_offset(inner, place) as f64;
let origin = (place.frame.left as f64 * root.width as f64, place.frame.top as f64 * root.height as f64 + nav);
+ // Smooth scrolling draws the rows shifted up by `scroll_px`, with
+ // one more row filling the strip that leaves at the bottom; the
+ // row under a pixel moves with them, and the extra row is one the
+ // pointer can reach. `row` stays an offset from the first row
+ // drawn, which is what every caller adds to `visible_rows`'s start.
+ let scroll_px = inner
+ .panes
+ .get(&place.pane_id)
+ .map(|cell| (cell.scroll_px as f64).clamp(0.0, ch))
+ .unwrap_or(0.0);
+ let last = if scroll_px > 0.0 && rows > 0 { rows } else { rows.saturating_sub(1) };
let local_col = (((px - origin.0) / cw).floor().max(0.0) as usize).min(cols.saturating_sub(1));
- let local_row = (((py - origin.1) / ch).floor().max(0.0) as usize).min(rows.saturating_sub(1));
+ let local_y = py - origin.1 + scroll_px;
+ let local_row = ((local_y / ch).floor().max(0.0) as usize).min(last);
let x_off = (px - origin.0 - local_col as f64 * cw).clamp(0.0, cw) as isize;
- let y_off = (py - origin.1 - local_row as f64 * ch).clamp(0.0, ch) as isize;
+ let y_off = (local_y - local_row as f64 * ch).clamp(0.0, ch) as isize;
Hit {
pane_id: place.pane_id,
col: local_col,
@@ -2041,6 +2069,7 @@ impl App {
if notches == 0 {
return false;
}
+ let smooth = inner.settings.scroll_mode.is_smooth();
let Some(cell) = inner.panes.get_mut(&hit.pane_id) else {
return false;
};
@@ -2078,11 +2107,28 @@ impl App {
return true;
}
let max = max_scroll(&session.dimensions());
- cell.scroll_from_bottom = if lines < 0.0 {
- (cell.scroll_from_bottom + notches).min(max)
+ if smooth {
+ // Down the page (a positive delta) is towards the newest row,
+ // which is the way `normalize_scroll_px` counts. A trackpad or
+ // a finger hands over a fraction of a row at a time and keeps
+ // it: nothing is rounded up to a notch.
+ let (scroll, px) = crate::viewport::normalize_scroll_px(
+ cell.scroll_from_bottom,
+ cell.scroll_px,
+ (lines * cell_h) as f32,
+ cell_h as f32,
+ max,
+ );
+ cell.scroll_from_bottom = scroll;
+ cell.scroll_px = px;
} else {
- cell.scroll_from_bottom.saturating_sub(notches)
- };
+ cell.scroll_from_bottom = if lines < 0.0 {
+ (cell.scroll_from_bottom + notches).min(max)
+ } else {
+ cell.scroll_from_bottom.saturating_sub(notches)
+ };
+ cell.scroll_px = 0.0;
+ }
drop(inner);
self.request_frame();
true
@@ -3529,6 +3575,15 @@ impl App {
"terminal-scheme" if scheme == crate::settings::FOLLOW_DESKTOP => {
self.set_terminal_palette(None)
}
+ // Stepped mode holds no part of a row: whatever a pane was
+ // through goes, rather than staying frozen until it is scrolled.
+ "scroll-mode" => {
+ for cell in self.inner.borrow_mut().panes.values_mut() {
+ cell.scroll_px = 0.0;
+ }
+ Self::notify(&self.inner.borrow());
+ self.request_frame();
+ }
_ => Self::notify(&self.inner.borrow()),
}
Ok(())
@@ -4482,7 +4537,11 @@ impl App {
continue;
};
let dims = cell.session.dimensions();
- let visible = visible_rows(&dims, Self::shown(&place).1, cell.scroll_from_bottom);
+ // The extra row a fractional scroll draws is one whose fetch can
+ // stall like any other; asking about the range that was painted
+ // is what keeps a dropped `GetLines` for it being retried.
+ let visible =
+ visible_rows_px(&dims, Self::shown(&place).1, cell.scroll_from_bottom, cell.scroll_px);
stalled |= cell.session.render_looks_stalled_in(visible);
}
let mut again = owed > 0 || stalled;
@@ -4633,9 +4692,13 @@ impl App {
let pad = Self::pad(inner);
let tab = inner.tab_layout.as_ref().map(|l| (l.cols, l.rows)).unwrap_or((usize::MAX, usize::MAX));
inner.quads.recycle();
+ let smooth = inner.settings.scroll_mode.is_smooth();
for place in &placements {
let (cols_shown, rows_shown) = Self::shown_in(inner, place);
let offset = Self::content_offset(inner, place);
+ // The pane's own cell height, before its glyph cache is borrowed
+ // to draw with: what a fractional scroll offset is measured in.
+ let pane_cell_h = Self::pane_cell(inner, place).1 as f32;
let Some(cell) = inner.panes.get_mut(&place.pane_id) else {
continue;
};
@@ -4644,8 +4707,21 @@ impl App {
let max = max_scroll(&dims);
if cell.scroll_from_bottom > max {
cell.scroll_from_bottom = max;
+ cell.scroll_px = 0.0;
+ }
+ // The offset only means anything inside the row it is measured
+ // against, and only above the tail: a font change, a switch to
+ // stepped mode or a scroll back to the newest row all leave it
+ // behind, and a whole row is what each of those wants.
+ if !smooth
+ || cell.scroll_from_bottom == 0
+ || !(cell.scroll_px > 0.0)
+ || cell.scroll_px >= pane_cell_h
+ {
+ cell.scroll_px = 0.0;
}
- let visible = visible_rows(&dims, rows_shown, cell.scroll_from_bottom);
+ let px = cell.scroll_px;
+ let visible = visible_rows_px(&dims, rows_shown, cell.scroll_from_bottom, px);
let (first, lines) = session.get_lines(visible);
// No cursor before the server has placed one: a fresh cell's
// sits at the origin, which is nowhere real.
@@ -4664,15 +4740,33 @@ impl App {
Some(font) if own_font => (&mut font.glyphs, &mut font.quads),
_ => (&mut inner.glyphs, &mut inner.quads),
};
+ let scratch = &mut inner.scratch;
let cell_w = glyphs.metrics.cell_size.width as f32;
let cell_h = glyphs.metrics.cell_size.height as f32;
let frame_origin = (
pad.0 + place.frame.left as f32 * root_w,
pad.1 + place.frame.top as f32 * root_h,
);
- // The content sits below the pane's bar, as on the desktop.
- let origin = (frame_origin.0, frame_origin.1 + offset);
+ // The content sits below the pane's bar, as on the desktop, and
+ // a fractional scroll lifts the rows by the part of the top one
+ // that is cut off; the extra row fetched above fills the strip
+ // that leaves at the bottom.
+ let content_top = frame_origin.1 + offset;
+ let origin = (frame_origin.0, content_top - px);
let clip = (cols_shown as f32 * cell_w, rows_shown as f32 * cell_h);
+ // The content box, in the quads' own centre-relative space: what
+ // the two rows hanging over its edges are cropped to.
+ let content_clip = thinkterm_render::quad::QuadClipRect::from_top_left_pixels(
+ frame_origin.0,
+ content_top,
+ frame_origin.0 + clip.0,
+ content_top + clip.1,
+ &thinkterm_render::geom::Dimensions {
+ pixel_width: w as usize,
+ pixel_height: h as usize,
+ dpi: dims.dpi as usize,
+ },
+ );
// The pane's own ground: its frame, plus the padding out to the
// canvas edge where it touches the tab's edge and half a cell
// into the divider where it does not, so the panes tile the
@@ -4721,6 +4815,7 @@ impl App {
crate::ime::update_field(&inner.textarea, &mut inner.ime_anchor, anchor)
.map_err(|e| anyhow::anyhow!("IME anchor: {e:?}"))?;
}
+ let last = lines.len().saturating_sub(1);
for (i, line) in lines.iter().enumerate() {
let row = first + i as StableRowIndex;
let sel_range = match &selection {
@@ -4742,7 +4837,18 @@ impl App {
hsv,
draw_cursor: is_focused,
};
- crate::emit::emit_line(glyphs, quads, budget, &params)?;
+ if px > 0.0 && (i == 0 || i == last) {
+ // Only the two rows that hang over the content box are
+ // worth cropping quad by quad: the clip does a bilerp
+ // and a box per quad, which no interior row needs. The
+ // scratch buffer is the one kept on `Inner`, emptied
+ // rather than allocated.
+ scratch.recycle();
+ crate::emit::emit_line(glyphs, scratch, budget, &params)?;
+ scratch.apply_to_clipped_at(&mut *quads, 0.0, 0.0, content_clip, 1.0)?;
+ } else {
+ crate::emit::emit_line(glyphs, quads, budget, &params)?;
+ }
}
}
let (cell_w, cell_h) = (root_w, root_h);
diff --git a/thinkterm-web/src/settings.rs b/thinkterm-web/src/settings.rs
index 2144e9ec..712bb283 100644
--- a/thinkterm-web/src/settings.rs
+++ b/thinkterm-web/src/settings.rs
@@ -43,6 +43,7 @@ pub struct WebSettings {
pub agents_panel: bool,
pub palette_hotkey: Hotkey,
pub sidebar_width: f64,
+ pub scroll_mode: ScrollMode,
/// `"desktop"` follows the server's configured scheme; anything else
/// names a scheme this browser picked.
pub terminal_scheme: String,
@@ -104,6 +105,7 @@ impl Default for WebSettings {
agents_panel: false,
palette_hotkey: Hotkey::CmdK,
sidebar_width: 220.0,
+ scroll_mode: ScrollMode::Smooth,
terminal_scheme: FOLLOW_DESKTOP.to_string(),
}
}
@@ -117,6 +119,22 @@ pub enum Theme {
System,
}
+/// How the scrollback follows a finger, a trackpad or a wheel: by the
+/// pixel, so the rows move with the hand, or a whole row at a time as a
+/// wheel's notch always has.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum ScrollMode {
+ Stepped,
+ Smooth,
+}
+
+impl ScrollMode {
+ pub fn is_smooth(self) -> bool {
+ matches!(self, Self::Smooth)
+ }
+}
+
/// The base font size: the desktop's cell, or a size of the page's own.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "kebab-case")]
@@ -218,6 +236,15 @@ mod tests {
assert_eq!((s.language.as_str(), s.palette_hotkey), ("de-DE", Hotkey::CtrlShiftP));
s.set("terminal-scheme", "\"Dracula\"").unwrap();
assert_eq!(s.terminal_scheme, "Dracula");
+ assert_eq!(WebSettings::default().scroll_mode, ScrollMode::Smooth, "pixels by default");
+ s.set("scroll-mode", "\"stepped\"").unwrap();
+ assert_eq!(s.scroll_mode, ScrollMode::Stepped);
+ assert!(!s.scroll_mode.is_smooth());
+ assert_eq!(serde_json::to_value(&s).unwrap()["scroll-mode"], serde_json::json!("stepped"));
+ s.set("scroll-mode", "\"smooth\"").unwrap();
+ assert!(s.scroll_mode.is_smooth());
+ assert!(s.set("scroll-mode", "\"glide\"").is_err());
+ assert_eq!(s.scroll_mode, ScrollMode::Smooth, "a refused value changes nothing");
assert!(s.set("colour", "1").is_err());
assert!(s.set("theme", "\"blue\"").is_err());
let json = serde_json::to_value(&s).unwrap();
diff --git a/thinkterm-web/src/viewport.rs b/thinkterm-web/src/viewport.rs
index 10941dde..81ef78fa 100644
--- a/thinkterm-web/src/viewport.rs
+++ b/thinkterm-web/src/viewport.rs
@@ -61,6 +61,79 @@ pub fn max_scroll(dims: &RenderableDimensions) -> usize {
(dims.physical_top - dims.scrollback_top).max(0) as usize
}
+/// The rows a fractionally scrolled view draws: `visible_rows` with one
+/// more row at the bottom, to fill what shifting the rows up by `px`
+/// leaves empty -- but never past the newest row the server has.
+pub fn visible_rows_px(
+ dims: &RenderableDimensions,
+ rows: usize,
+ scroll_from_bottom: usize,
+ px: f32,
+) -> Range<StableRowIndex> {
+ let range = visible_rows(dims, rows, scroll_from_bottom);
+ let bottom = dims.physical_top + dims.viewport_rows as StableRowIndex;
+ if px > 0.0 && range.end < bottom {
+ range.start..range.end + 1
+ } else {
+ range
+ }
+}
+
+/// Where a scroll of `delta_px` device pixels lands, keeping the part of a
+/// row the view is through.
+///
+/// `scroll_from_bottom` counts whole rows up into the scrollback and `px`,
+/// in `[0, cell_h)`, is how far the top visible row is cut off at its top:
+/// the view sits `px` pixels *below* the row `scroll_from_bottom` names, so
+/// it is `scroll_from_bottom - px / cell_h` rows above the tail. A positive
+/// `delta_px` scrolls down, towards the newest row, as a wheel pushed away
+/// from the hand does.
+///
+/// The floor keeps the two directions symmetric: the same distance back and
+/// forth returns to the same pixel. Both ends clamp onto a whole row -- the
+/// tail cannot show half a row that has not been written yet, and neither
+/// can the oldest row the server kept.
+pub fn normalize_scroll_px(
+ scroll_from_bottom: usize,
+ px: f32,
+ delta_px: f32,
+ cell_h: f32,
+ max: usize,
+) -> (usize, f32) {
+ if !(cell_h > 0.0) || !px.is_finite() || !delta_px.is_finite() {
+ return (scroll_from_bottom.min(max), 0.0);
+ }
+ let total = px + delta_px;
+ let mut rows = (total / cell_h).floor();
+ let mut px = total - rows * cell_h;
+ // The division rounds; a remainder that landed outside the row it
+ // belongs to is on a boundary, so put it on the boundary rather than
+ // carrying a negative offset or a whole extra row of one.
+ if px >= cell_h {
+ rows += 1.0;
+ px = 0.0;
+ } else if px < 0.0 {
+ px = 0.0;
+ }
+ // A delta wider than the whole scrollback can still only reach an end,
+ // and `as isize` on a large float saturates rather than wrapping;
+ // holding the row count inside the reachable range says the same thing
+ // in numbers the arithmetic below can carry.
+ let reach = (max as f32) + (scroll_from_bottom as f32) + 1.0;
+ let rows = rows.clamp(-reach, reach) as isize;
+ let scroll = scroll_from_bottom as isize - rows;
+ if scroll <= 0 {
+ // The tail: there is nothing below the last row to show.
+ return (0, 0.0);
+ }
+ let scroll = scroll as usize;
+ if scroll > max {
+ // The oldest row the server kept, whole.
+ return (max, 0.0);
+ }
+ (scroll, px)
+}
+
/// The cell under a canvas pixel (device pixels, origin top-left).
pub fn cell_at(px: f64, py: f64, cell_width: f64, cell_height: f64) -> (usize, usize) {
let col = (px / cell_width).floor().max(0.0) as usize;
@@ -102,6 +175,90 @@ mod tests {
fn a_shorter_page_still_shows_the_bottom_of_the_screen() {
assert_eq!(visible_rows(&dims(100, 0, 24), 10, 0), 114..124);
}
+
+ #[test]
+ fn a_fractional_view_draws_one_more_row_but_never_past_the_newest() {
+ let d = dims(100, 0, 24);
+ assert_eq!(visible_rows_px(&d, 24, 10, 0.0), 90..114, "a whole row draws what it always did");
+ assert_eq!(visible_rows_px(&d, 24, 10, 4.0), 90..115);
+ // At the tail there is no row below to borrow, and the convention
+ // forbids a fraction there anyway.
+ assert_eq!(visible_rows_px(&d, 24, 0, 4.0), 100..124);
+ // Clamped at the oldest row, the extra one is still inside the screen.
+ let d = dims(100, 95, 24);
+ let range = visible_rows_px(&d, 24, 10, 4.0);
+ assert_eq!(range, 95..120);
+ assert!(range.end <= d.physical_top + d.viewport_rows as StableRowIndex);
+ }
+}
+
+#[cfg(test)]
+mod scroll_px_tests {
+ use super::*;
+
+ const CELL: f32 = 20.0;
+
+ #[test]
+ fn a_delta_short_of_a_row_moves_only_the_offset() {
+ // Up (negative) from the tail: a quarter of a row back.
+ assert_eq!(normalize_scroll_px(0, 0.0, -5.0, CELL, 100), (1, 15.0));
+ // And down again lands exactly where it started.
+ assert_eq!(normalize_scroll_px(1, 15.0, 5.0, CELL, 100), (0, 0.0));
+ }
+
+ #[test]
+ fn whole_rows_leave_no_offset_behind() {
+ assert_eq!(normalize_scroll_px(0, 0.0, -CELL, CELL, 100), (1, 0.0));
+ assert_eq!(normalize_scroll_px(3, 0.0, -3.0 * CELL, CELL, 100), (6, 0.0));
+ assert_eq!(normalize_scroll_px(6, 0.0, 2.0 * CELL, CELL, 100), (4, 0.0));
+ // A whole row on top of an offset keeps the offset.
+ assert_eq!(normalize_scroll_px(4, 7.0, -CELL, CELL, 100), (5, 7.0));
+ }
+
+ #[test]
+ fn the_same_distance_back_and_forth_returns_to_the_same_pixel() {
+ for delta in [1.0f32, 3.5, 19.0, 20.0, 47.25, 137.0] {
+ let start = (7usize, 11.0f32);
+ let up = normalize_scroll_px(start.0, start.1, -delta, CELL, 100);
+ let back = normalize_scroll_px(up.0, up.1, delta, CELL, 100);
+ assert_eq!(back, start, "{delta} px up and down again");
+ }
+ }
+
+ #[test]
+ fn the_offset_stays_inside_one_row() {
+ let mut at = (10usize, 0.0f32);
+ for step in 0..200 {
+ let delta = if step % 3 == 0 { 7.5 } else { -3.25 };
+ at = normalize_scroll_px(at.0, at.1, delta, CELL, 40);
+ assert!((0.0..CELL).contains(&at.1), "{at:?} after {delta}");
+ assert!(at.0 <= 40, "{at:?}");
+ assert!(at.0 > 0 || at.1 == 0.0, "the tail is always a whole row: {at:?}");
+ }
+ }
+
+ #[test]
+ fn both_ends_land_on_a_whole_row() {
+ // Past the tail.
+ assert_eq!(normalize_scroll_px(1, 4.0, 5.0 * CELL, CELL, 100), (0, 0.0));
+ assert_eq!(normalize_scroll_px(0, 0.0, 3.0, CELL, 100), (0, 0.0));
+ // Past the oldest row the server kept.
+ assert_eq!(normalize_scroll_px(9, 4.0, -5.0 * CELL, CELL, 10), (10, 0.0));
+ // Stopping exactly on it keeps the offset: the oldest row may be cut.
+ assert_eq!(normalize_scroll_px(8, 0.0, -CELL - 6.0, CELL, 10), (10, 14.0));
+ // Nothing to scroll at all.
+ assert_eq!(normalize_scroll_px(0, 0.0, -100.0, CELL, 0), (0, 0.0));
+ }
+
+ #[test]
+ fn nonsense_input_falls_back_to_a_whole_row() {
+ assert_eq!(normalize_scroll_px(5, 3.0, -10.0, 0.0, 100), (5, 0.0));
+ assert_eq!(normalize_scroll_px(5, 3.0, f32::NAN, CELL, 100), (5, 0.0));
+ assert_eq!(normalize_scroll_px(5, f32::INFINITY, -1.0, CELL, 100), (5, 0.0));
+ assert_eq!(normalize_scroll_px(5, 3.0, -1e30, CELL, 10), (10, 0.0));
+ assert_eq!(normalize_scroll_px(5, 3.0, 1e30, CELL, 10), (0, 0.0));
+ assert_eq!(normalize_scroll_px(50, 0.0, 0.0, CELL, 10), (10, 0.0), "a stale row is clamped");
+ }
}
#[cfg(test)]
diff --git a/thinkterm-web/src/views.rs b/thinkterm-web/src/views.rs
index 52af22a8..19730a14 100644
--- a/thinkterm-web/src/views.rs
+++ b/thinkterm-web/src/views.rs
@@ -122,6 +122,10 @@ pub const STRING_KEYS: &[&str] = &[
"web-theme-dark",
"web-theme-light",
"web-theme-system",
+ "web-settings-scroll-mode",
+ "web-settings-scroll-mode-description",
+ "web-scroll-mode-stepped",
+ "web-scroll-mode-smooth",
"web-settings-font",
"web-font-follow",
"web-font-pinned",
diff --git a/thinkterm-web/ui/src/SettingsPanel.svelte b/thinkterm-web/ui/src/SettingsPanel.svelte
index 8955a4e0..c39145cd 100644
--- a/thinkterm-web/ui/src/SettingsPanel.svelte
+++ b/thinkterm-web/ui/src/SettingsPanel.svelte
@@ -6,7 +6,7 @@
import { s, views } from './client.svelte';
import { bot, info, minus, palette, panelLeft, plus, rotateCcw, search, slidersHorizontal, x } from './icons';
import { applyTheme, closeSettings, FOLLOW_DESKTOP, loadSchemes, panel, pickScheme, previewScheme, schemes, setSetting, storedScheme } from './settings.svelte';
- import type { Hotkey, Scheme, Theme } from './model';
+ import type { Hotkey, Scheme, ScrollMode, Theme } from './model';
import { POP, WINDOW, ms } from './motion';
import { fade, scale } from 'svelte/transition';
import { cubicOut } from 'svelte/easing';
@@ -58,6 +58,10 @@
['light', 'web-theme-light'],
['system', 'web-theme-system'],
];
+ const SCROLL_MODES: [ScrollMode, string][] = [
+ ['smooth', 'web-scroll-mode-smooth'],
+ ['stepped', 'web-scroll-mode-stepped'],
+ ];
// The shortcuts as they are pressed, not as they are stored.
const HOTKEYS: [Hotkey, string][] = [
['cmd-k', '⌘K'],
@@ -243,7 +247,7 @@
<div class="body">
<div class="title">{query.trim() === '' ? s(SECTIONS.find(([id]) => id === section)?.[1] ?? '') : s('web-settings-search')}</div>
- {#if shows('general', s('settings-language')) || shows('general', s('web-settings-palette-hotkey'))}
+ {#if shows('general', s('settings-language')) || shows('general', s('web-settings-palette-hotkey')) || shows('general', s('web-settings-scroll-mode'))}
<div class="card">
{#if shows('general', s('settings-language'))}
<div class="srow">
@@ -257,6 +261,16 @@
</select>
</div>
{/if}
+ {#if shows('general', s('web-settings-scroll-mode'))}
+ <div class="srow">
+ <div class="tx"><div class="lab">{s('web-settings-scroll-mode')}</div><div class="desc">{d('web-settings-scroll-mode-description')}</div></div>
+ <select class="pillsel" data-setting="scroll-mode" value={settings['scroll-mode']} onchange={(ev) => setSetting('scroll-mode', (ev.currentTarget as HTMLSelectElement).value)}>
+ {#each SCROLL_MODES as [value, label] (value)}
+ <option value={value}>{s(label)}</option>
+ {/each}
+ </select>
+ </div>
+ {/if}
{#if shows('general', s('web-settings-palette-hotkey'))}
<div class="srow">
<div class="tx"><div class="lab">{s('web-settings-palette-hotkey')}</div><div class="desc">{d('web-settings-hotkey-description')}</div></div>
diff --git a/thinkterm-web/ui/src/client.svelte.ts b/thinkterm-web/ui/src/client.svelte.ts
index 2e7eff6c..7768eb52 100644
--- a/thinkterm-web/ui/src/client.svelte.ts
+++ b/thinkterm-web/ui/src/client.svelte.ts
@@ -25,6 +25,7 @@ export const views = $state({
'agents-panel': false,
'palette-hotkey': 'cmd-k',
'sidebar-width': 220,
+ 'scroll-mode': 'smooth',
} as WebSettings,
layout: '',
/** The page's own labels in the active language; empty until attached. */
diff --git a/thinkterm-web/ui/src/model.ts b/thinkterm-web/ui/src/model.ts
index f05b4f26..bdae9e3f 100644
--- a/thinkterm-web/ui/src/model.ts
+++ b/thinkterm-web/ui/src/model.ts
@@ -209,6 +209,8 @@ export type AgentsView = { rows: AgentRow[]; summary: string; tabs: PanelTab[];
export type Theme = 'dark' | 'light' | 'system';
export type FontMode = { mode: 'follow' } | { mode: 'pinned'; pt: number };
export type Hotkey = 'cmd-k' | 'cmd-shift-p' | 'ctrl-shift-p';
+/** By the pixel, so the rows follow the hand, or a whole row at a time. */
+export type ScrollMode = 'stepped' | 'smooth';
export type WebSettings = {
/** `"system"` or a locale tag. */
@@ -219,6 +221,7 @@ export type WebSettings = {
'agents-panel': boolean;
'palette-hotkey': Hotkey;
'sidebar-width': number;
+ 'scroll-mode': ScrollMode;
/** `"desktop"` follows the server's configuration; else a scheme's name. */
'terminal-scheme': string;
};
diff --git a/thinkterm-web/ui/src/settings.svelte.ts b/thinkterm-web/ui/src/settings.svelte.ts
index 10d1f2d1..a855cb5a 100644
--- a/thinkterm-web/ui/src/settings.svelte.ts
+++ b/thinkterm-web/ui/src/settings.svelte.ts
@@ -90,6 +90,13 @@ export function setSetting(key: string, value: unknown) {
persist();
}
+/** Whether the scrollback follows a finger by the pixel (`scroll-mode`).
+ Read on every touch move, so it is a plain read of what the wasm last
+ handed back rather than anything the gesture has to be told about. */
+export function smoothScroll(): boolean {
+ return views.settings['scroll-mode'] !== 'stepped';
+}
+
export function storedSpace(): string {
try {
return localStorage.getItem(SPACE) ?? '';
diff --git a/thinkterm-web/ui/src/touch.ts b/thinkterm-web/ui/src/touch.ts
index e9ac7aee..aad31d17 100644
--- a/thinkterm-web/ui/src/touch.ts
+++ b/thinkterm-web/ui/src/touch.ts
@@ -17,6 +17,7 @@
import { openMenu } from './menu.svelte';
import { mobile, openSide } from './mobile.svelte';
import { cellHeight, paneAt } from './pane';
+import { smoothScroll } from './settings.svelte';
/** How far a finger may wander and still be a tap. */
const SLOP = 8;
@@ -149,19 +150,27 @@ export function installTouch(canvas: HTMLCanvasElement): () => void {
);
};
- /** Scroll by what the fingers moved, a whole cell at a time: the wasm
- rounds any wheel up to one notch, so a few pixels handed over one
- event at a time would run away from the finger. */
+ /** Scroll by what the fingers moved. In smooth mode every move goes over
+ as it is, so the rows follow the finger; in stepped mode the wasm
+ rounds any wheel up to a whole notch, so a few pixels handed over one
+ event at a time would run away from the finger and the pixels are
+ held back here until they are worth a cell. */
const scrollBy = (dy: number, at: Finger) => {
- pending += dy;
- const cell = cellHeight(canvas, CELL);
- const cells = Math.trunc(pending / cell);
- if (cells === 0) return;
- pending -= cells * cell;
+ let by = dy;
+ if (!smoothScroll()) {
+ pending += dy;
+ const cell = cellHeight(canvas, CELL);
+ const cells = Math.trunc(pending / cell);
+ if (cells === 0) return;
+ pending -= cells * cell;
+ by = cells * cell;
+ } else if (by === 0) {
+ return;
+ }
// Down the screen is back through the scrollback, as a wheel's is.
canvas.dispatchEvent(
new WheelEvent('wheel', {
- deltaY: -cells * cell,
+ deltaY: -by,
deltaMode: 0,
bubbles: true,
cancelable: true,