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.

thinkterm-web: hold the tab, claim pane by pane, park the rest

RoversXbd580620bf05
diff --git a/thinkterm-session/src/pane.rs b/thinkterm-session/src/pane.rs
index 731875f4..4b903df5 100644
--- a/thinkterm-session/src/pane.rs
+++ b/thinkterm-session/src/pane.rs
@@ -15,6 +15,7 @@ use codec::{GetLines, GetPaneRenderChanges, GetPaneRenderChangesResponse, InputS
use rangeset::RangeSet;
use std::ops::Range;
use std::sync::atomic::{AtomicUsize, Ordering};
+use thinkterm_proto::TabId;
use std::sync::{Arc, Weak};
use std::time::Duration;
use termwiz::cell::CellAttributes;
@@ -87,6 +88,11 @@ impl<H: SessionHost> PaneSession<H> {
self.remote_pane_id
}
+ /// The tab the server files the pane under, as last told.
+ pub fn remote_tab_id(&self) -> TabId {
+ self.remote_tab_id.load(Ordering::Relaxed)
+ }
+
pub fn host_pane_id(&self) -> HostPaneId {
self.host_pane_id
}
@@ -101,6 +107,12 @@ impl<H: SessionHost> PaneSession<H> {
self.state().cursor_position
}
+ /// Whether a render delta has arrived: until then the pane has no
+ /// picture of its own, only placeholders.
+ pub fn has_received(&self) -> bool {
+ self.state().received
+ }
+
pub fn current_seqno(&self) -> SequenceNo {
self.state().seqno
}
@@ -595,6 +607,7 @@ impl<H: SessionHost> PaneSession<H> {
let now = self.now();
st.poll_interval = BASE_POLL_INTERVAL;
st.last_recv_time = now;
+ st.received = true;
if delta.alt_screen != st.alt_screen {
st.alt_screen = delta.alt_screen;
diff --git a/thinkterm-session/src/pane_state.rs b/thinkterm-session/src/pane_state.rs
index a8f0fc9e..a66d5664 100644
--- a/thinkterm-session/src/pane_state.rs
+++ b/thinkterm-session/src/pane_state.rs
@@ -68,6 +68,9 @@ pub struct PaneState {
pub(crate) last_send_time: Timestamp,
pub(crate) last_recv_time: Timestamp,
+ /// Whether the server has said anything about this pane yet: before
+ /// that its cursor and rows are placeholders, not a picture.
+ pub(crate) received: bool,
pub(crate) last_late_dirty: Timestamp,
pub(crate) last_input_rtt: u64,
@@ -107,6 +110,7 @@ impl PaneState {
fetch_limiter: RateLimiter::new(fetch_rate_per_second, now),
last_send_time: now,
last_recv_time: now,
+ received: false,
last_late_dirty: now,
last_input_rtt: 0,
input_serial: InputSerial::empty(),
diff --git a/thinkterm-web/src/agents.rs b/thinkterm-web/src/agents.rs
index 8904d1df..826820f1 100644
--- a/thinkterm-web/src/agents.rs
+++ b/thinkterm-web/src/agents.rs
@@ -24,10 +24,51 @@ pub struct AgentRow {
pub icon: &'static str,
}
+/// One tab of the right panel's selector, as the desktop lists them
+/// (`RightSidebarMode::ALL`: Files, Notes, Code, Agents). Which exist and
+/// which the browser can open is decided here, not in the display layer.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct PanelTab {
+ pub id: &'static str,
+ /// A lucide name, as the menus name theirs.
+ pub icon: &'static str,
+ pub label: String,
+ /// Off for the panels whose APIs the browser has not got; the tip
+ /// says so, and a press does nothing.
+ pub available: bool,
+ pub tip: String,
+}
+
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AgentsView {
pub rows: Vec<AgentRow>,
pub summary: String,
+ /// The selector above the panel, and which of its tabs is showing.
+ pub tabs: Vec<PanelTab>,
+ pub active: &'static str,
+}
+
+/// The panel's sections, in the desktop's order, but only those the page
+/// can open: a button for a feature the browser lacks is noise. Files,
+/// Notes and Code join here when they get a wire.
+pub fn panel_tabs() -> Vec<PanelTab> {
+ [("agents", "bot", "right-mode-agents")]
+ .into_iter()
+ .map(|(id, icon, key)| {
+ let label = tr(key);
+ PanelTab { id, icon, label: label.clone(), available: true, tip: label }
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod panel_tests {
+ #[test]
+ fn only_agents_is_available_in_a_browser() {
+ let tabs = super::panel_tabs();
+ assert!(tabs.iter().map(|t| t.id).eq(["agents"]));
+ assert!(tabs.iter().all(|t| t.available));
+ }
}
/// The curated names the desktop uses; anything else is its id, title-cased.
diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rs
index 0c07142d..39219d16 100644
--- a/thinkterm-web/src/app.rs
+++ b/thinkterm-web/src/app.rs
@@ -122,17 +122,29 @@ pub struct PaneCell {
pub session: Arc<PaneSession<WebHost>>,
pub scroll_from_bottom: usize,
pub selection: Option<Selection>,
- /// The pane's own colours (OSC 4/10/11), pushed as `SetApplicationPalette`.
+ /// The pane's own colours (OSC 4/10/11), pushed as `SetApplicationPalette`,
+ /// exactly as they arrived. `None` means the base palette shows through.
+ pub application: Option<ColorPalette>,
+ /// What is drawn: the base palette under `application`, if any.
pub palette: ColorPalette,
pub title: String,
+ /// A live-resize preview in force: its epoch, size, and when it
+ /// began, so one the server never confirms is not kept for good.
+ pub preview: Option<(u64, TerminalSize, f64)>,
+ /// Parked through a reconnect: its rows may have moved on without
+ /// this page hearing, so it is polled afresh when next shown.
+ pub reconnect_stale: bool,
}
impl PaneCell {
pub fn new(session: Arc<PaneSession<WebHost>>, title: &str) -> Self {
Self {
+ preview: None,
+ reconnect_stale: false,
session,
scroll_from_bottom: 0,
selection: None,
+ application: None,
palette: ColorPalette::default(),
title: title.to_string(),
}
@@ -145,6 +157,10 @@ pub struct Inner {
/// focused pane's cell stays (dead, if need be) until a listing puts
/// something else in its place.
panes: std::collections::BTreeMap<PaneId, PaneCell>,
+ /// Cells of tabs the page has shown and left: kept, and kept current
+ /// by the server's pushes, so switching back shows them at once with
+ /// their lines, cursor and colours rather than a blank round trip.
+ parked: std::collections::BTreeMap<PaneId, PaneCell>,
focused_pane: PaneId,
host: Arc<WebHost>,
/// One per connection, shared by every session: a picture one pane
@@ -168,11 +184,24 @@ pub struct Inner {
cols: usize,
rows: usize,
font_pinned: bool,
+ /// The page's own size: what it shows while it holds the tab, and
+ /// what the settings pin. Following the desktop's cell is for a
+ /// follower only.
+ base_size_pt: f64,
+ /// The size the page started with: what "follow" goes back to.
+ boot_size_pt: f64,
languages: Vec<String>,
/// Palette picks, most recent first; the page keeps them across loads.
recent: Vec<String>,
/// The page's preferences, as it handed them over.
settings: crate::settings::WebSettings,
+ /// The palette the server's own configuration resolves to, pushed as
+ /// `DefaultPalette` right after the handshake.
+ server_palette: Option<ColorPalette>,
+ /// A scheme this browser picked, which outranks the server's.
+ chosen_palette: Option<ColorPalette>,
+ /// The background last published on the canvas as `data-bg`.
+ published_bg: Option<String>,
/// Word/line selection extends by units; the pointer is down.
selecting: bool,
/// The pane a drag started in; it keeps the drag until the release.
@@ -180,6 +209,23 @@ pub struct Inner {
/// A divider being dragged: which, where the press was along its
/// axis (device px), and the cells already sent to the server.
drag_divider: Option<(usize, f64, isize)>,
+ /// The layout as the divider drag began: every step is measured
+ /// from it, not from the last step's result.
+ drag_layout: Option<crate::layout::TabLayout>,
+ /// A divider claim on the wire, and the step that arrived meanwhile
+ /// to send when it answers: one round trip at a time, the newest
+ /// position wins.
+ divider_claim_busy: bool,
+ divider_claim_next: Option<(usize, isize)>,
+ /// Counts live-resize previews, so a late answer cannot end a newer one.
+ preview_epoch: u64,
+ /// A sidebar or panel edge is being dragged: the canvas follows it,
+ /// the tab is reshaped once when it is let go.
+ panel_drag: bool,
+ /// Every pane's application palette the server has pushed, on the page
+ /// or not: it is sent once per connection, so a pane drawn again after
+ /// a tab switch takes its colours from here.
+ overrides: std::collections::HashMap<PaneId, Option<ColorPalette>>,
click_count: u8,
last_click_ms: f64,
focused: bool,
@@ -219,6 +265,9 @@ pub struct Inner {
/// default: a page opened to "see my terminal" wants the one being
/// used. Choosing a pane here turns it off.
following: bool,
+ /// The tab the page last claimed on its own, on showing it; see
+ /// `show`. A tab is claimed once per showing, not on every listing.
+ auto_claimed: Option<TabId>,
/// The page's display layer, told once per animation frame that
/// something it shows changed; it reads the views it wants.
on_change: Option<js_sys::Function>,
@@ -232,6 +281,8 @@ pub struct Inner {
/// A thread's delete button was pressed once, and when.
deleting: Option<(String, f64)>,
editing: crate::sidebar::Editing,
+ /// Why the last path typed into "Add workspace" was refused.
+ new_project_error: Option<String>,
/// A tab's close button was pressed once, and when.
closing_tab: Option<(TabId, f64)>,
layout_refresh_pending: bool,
@@ -244,6 +295,8 @@ pub struct Inner {
/// What the interaction that asked for the terminal wanted done once
/// the server hands it over.
after_take_over: Option<AfterTakeOver>,
+ /// How the last ask for the terminal went, for the card to say.
+ claim: Claim,
}
/// One pane's own font: its scale over the page's size, and what draws it.
@@ -255,6 +308,18 @@ struct PaneFont {
}
/// Continuation of a take-over that an interaction started.
+/// How many tabs' cells are kept parked when the page leaves them.
+const PARKED_TABS: usize = 12;
+
+/// The page's last ask for the terminal (Handoff mode): none, on the
+/// wire, or turned down by the server.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Claim {
+ Idle,
+ Taking,
+ Refused,
+}
+
enum AfterTakeOver {
Focus(PaneId),
Key(KeyCode, Modifiers, bool),
@@ -338,6 +403,33 @@ pub fn build_session(
}
impl Inner {
+ /// The base palette every pane draws from: this browser's pick, else
+ /// the server's configured scheme, else the stock palette.
+ pub fn configured(&self) -> ColorPalette {
+ crate::settings::configured_palette(
+ self.chosen_palette.as_ref(),
+ self.server_palette.as_ref(),
+ )
+ }
+
+ /// Fold the base palette and each pane's application override back into
+ /// what is drawn. Returns the panes whose palette moved.
+ fn recompute_palettes(&mut self) -> Vec<PaneId> {
+ let configured = self.configured();
+ let mut changed = Vec::new();
+ for (pane_id, cell) in self.panes.iter_mut() {
+ if let Some(palette) = crate::settings::recomputed_palette(
+ &cell.palette,
+ &configured,
+ cell.application.as_ref(),
+ ) {
+ cell.palette = palette;
+ changed.push(*pane_id);
+ }
+ }
+ changed
+ }
+
fn focused(&self) -> &PaneCell {
self.panes
.get(&self.focused_pane)
@@ -369,11 +461,14 @@ impl App {
let inner = Inner {
link: setup.link,
panes,
+ parked: std::collections::BTreeMap::new(),
focused_pane: setup.pane_id,
host: setup.host,
images: setup.images,
remote_tab_id: setup.remote_tab_id,
gpu: setup.gpu,
+ base_size_pt: setup.glyphs.size_pt,
+ boot_size_pt: setup.glyphs.size_pt,
glyphs: setup.glyphs,
fonts: setup.fonts,
canvas: setup.canvas,
@@ -388,6 +483,12 @@ impl App {
selecting: false,
drag_pane: None,
drag_divider: None,
+ drag_layout: None,
+ divider_claim_busy: false,
+ divider_claim_next: None,
+ preview_epoch: 0,
+ panel_drag: false,
+ overrides: std::collections::HashMap::new(),
click_count: 0,
last_click_ms: 0.0,
focused: true,
@@ -406,12 +507,16 @@ impl App {
languages: setup.languages,
recent: Vec::new(),
settings: crate::settings::WebSettings::default(),
+ server_palette: None,
+ chosen_palette: None,
+ published_bg: None,
quads: HeapQuadAllocator::default(),
vertices: Vec::new(),
pane_fonts: Default::default(),
layout: None,
tab_layout: None,
following: true,
+ auto_claimed: None,
on_change: None,
notify_pending: Rc::new(Cell::new(false)),
toast: RefCell::new(None),
@@ -420,11 +525,13 @@ impl App {
session_refresh_pending: false,
deleting: None,
editing: crate::sidebar::Editing::None,
+ new_project_error: None,
closing_tab: None,
layout_refresh_pending: false,
switching: false,
closing_since: None,
after_take_over: None,
+ claim: Claim::Idle,
};
let app = Rc::new(Self {
inner: RefCell::new(inner),
@@ -527,18 +634,49 @@ impl App {
Self::notify(&inner);
}
- /// The desktop's words over a terminal another device holds, or none
- /// when this page may type.
+ /// The desktop's surface over a terminal another device holds, or
+ /// none when this page may type. It says who holds it, and after a
+ /// press, whether the server let go.
fn card(inner: &Inner) -> Option<crate::views::Card> {
+ use crate::views::Card;
let lease = inner.link.lease();
- match lease.mode {
- Some(codec::FrontendAccessMode::Handoff) if !lease.owns_viewport() => Some(if lease.owner.is_some() {
- crate::views::Card { title: tr("web-card-busy-title"), hint: tr("web-card-busy-hint") }
- } else {
- crate::views::Card { title: tr("web-card-free-title"), hint: tr("web-card-free-hint") }
- }),
- _ => None,
+ if !matches!(lease.mode, Some(codec::FrontendAccessMode::Handoff)) || lease.owns_viewport() {
+ return None;
}
+ let host = lease.owner.as_ref().map(|o| o.hostname.trim().to_string()).unwrap_or_default();
+ let taking = tr("web-card-take-over");
+ Some(match (inner.claim, lease.owner.is_some()) {
+ (Claim::Taking, _) => Card {
+ title: tr("web-card-taking-title"),
+ hint: tr("web-card-taking-hint"),
+ state: "taking",
+ action: taking,
+ },
+ (Claim::Refused, true) => Card {
+ title: tr("web-card-refused-title"),
+ hint: tr("web-card-refused-hint"),
+ state: "refused",
+ action: tr("web-card-try-again"),
+ },
+ (_, true) => Card {
+ title: if host.is_empty() {
+ tr("web-card-busy-title")
+ } else {
+ let mut args = thinkterm_i18n::FluentArgs::new();
+ args.set("host", host);
+ thinkterm_i18n::tr_args("web-card-busy-on", &args)
+ },
+ hint: tr("web-card-busy-hint"),
+ state: "busy",
+ action: taking,
+ },
+ (_, false) => Card {
+ title: tr("web-card-free-title"),
+ hint: tr("web-card-free-hint"),
+ state: "free",
+ action: tr("web-card-take-control"),
+ },
+ })
}
/// Tell the display layer that a view changed: once per task, so a
@@ -586,9 +724,41 @@ impl App {
rows: Self::side_rows(&inner),
editing: inner.editing.clone(),
space: inner.tree.current_space().map(|s| s.id.clone()),
+ new_project_error: inner.new_project_error.clone(),
+ reveal: crate::sidebar::REVEAL,
+ footer: Self::side_footer(),
+ footer_label_min_width: crate::sidebar::FOOTER_LABEL_MIN_WIDTH,
}
}
+ /// The footer the desktop's sidebar ends with: the gear and its label,
+ /// then Live Overview, Remote Hosts and the thread search. The first
+ /// two need windows the browser has not got, so they are shown and
+ /// refused rather than hidden -- the panel is the shape the desktop's
+ /// is either way.
+ fn side_footer() -> Vec<crate::sidebar::FooterAction> {
+ // Only what the page can do: the desktop's Live Overview and
+ // Remote Hosts have no browser counterpart, so no button for them.
+ vec![
+ crate::sidebar::FooterAction {
+ id: "settings".into(),
+ icon: "settings".into(),
+ label: Some(thinkterm_i18n::tr("sidebar-settings")),
+ tip: thinkterm_i18n::tr("tooltip-sidebar-settings"),
+ enabled: true,
+ trailing: false,
+ },
+ crate::sidebar::FooterAction {
+ id: "search".into(),
+ icon: "search".into(),
+ label: None,
+ tip: thinkterm_i18n::tr("tooltip-sidebar-thread-search"),
+ enabled: true,
+ trailing: true,
+ },
+ ]
+ }
+
pub fn tabs_view(&self) -> crate::views::TabsView {
let inner = self.inner.borrow();
let (tabs, controls) = Self::strip_model(&inner).unwrap_or_default();
@@ -618,10 +788,17 @@ impl App {
// ones on this page are wanted, and the rest are simply not
// ours (never a reason to re-list: there are many).
Pdu::GetPaneRenderChangesResponse(delta) => {
- if let Some(cell) = inner.panes.get(&delta.pane_id) {
+ if let Some(cell) = inner.panes.get(&delta.pane_id).or_else(|| inner.parked.get(&delta.pane_id)) {
cell.session.queue_render_delta(delta);
}
}
+ Pdu::PaneRemoved(removed) if inner.parked.contains_key(&removed.pane_id) => {
+ drop(inner);
+ self.inner.borrow_mut().parked.remove(&removed.pane_id);
+ // The strip and the sidebar list it still.
+ self.refresh_layout_soon();
+ self.refresh_session_soon();
+ }
Pdu::PaneRemoved(removed) if inner.panes.contains_key(&removed.pane_id) => {
let cell = &inner.panes[&removed.pane_id];
cell.session.set_dead(true);
@@ -654,19 +831,29 @@ impl App {
// Sent once per connection, before the first line change: a
// program's OSC 4/10/11 colours. Dropping it would leave the
// page on the stock palette for good.
- Pdu::SetApplicationPalette(codec::SetApplicationPalette { pane_id, palette })
- if inner.panes.contains_key(&pane_id) =>
- {
+ Pdu::SetApplicationPalette(codec::SetApplicationPalette { pane_id, palette }) => {
drop(inner);
let mut inner = self.inner.borrow_mut();
- let palette = palette.unwrap_or_default();
- let cell = inner.panes.get_mut(&pane_id).expect("checked above");
- if palette != cell.palette {
- cell.palette = palette;
- cell.session.make_all_stale();
+ inner.overrides.insert(pane_id, palette.clone());
+ if let Some(cell) = inner.panes.get_mut(&pane_id) {
+ cell.application = palette;
+ let changed = inner.recompute_palettes();
drop(inner);
- self.request_frame();
+ self.repaint_palettes(&changed);
+ }
+ }
+ // The server's own `color_scheme`: the base under any override,
+ // unless this browser picked a scheme of its own.
+ Pdu::DefaultPalette(codec::DefaultPalette { palette }) => {
+ drop(inner);
+ let mut inner = self.inner.borrow_mut();
+ if inner.server_palette.as_ref() == Some(&palette) {
+ return;
}
+ inner.server_palette = Some(palette);
+ let changed = inner.recompute_palettes();
+ drop(inner);
+ self.repaint_palettes(&changed);
}
Pdu::ThinkTermTreeState(state) => {
drop(inner);
@@ -726,9 +913,15 @@ impl App {
// Nothing more will arrive on this socket: the watchdog must
// stop asking, or the page keeps requesting lines that never
// come. `reconnected` turns it back on.
- for cell in inner.panes.values() {
+ for cell in inner.panes.values().chain(inner.parked.values()) {
cell.session.set_dead(true);
}
+ // An ask on this socket will not be answered; the card must
+ // not sit at "taking" with its button disabled.
+ if inner.claim == Claim::Taking {
+ inner.claim = Claim::Idle;
+ Self::notify(&inner);
+ }
log::warn!("connection lost: {reason}");
}
self.show_reconnect_status();
@@ -874,6 +1067,13 @@ impl App {
cell.session.set_dead(false);
cell.session.make_all_stale();
}
+ // A parked pane's rows may have moved while the socket was
+ // down; it is polled again when it comes back on show.
+ for cell in inner.parked.values_mut() {
+ cell.session.set_dead(false);
+ cell.session.make_all_stale();
+ cell.reconnect_stale = true;
+ }
log::info!("reconnected to pane {}", inner.focused_pane);
}
self.refresh_status();
@@ -908,9 +1108,6 @@ impl App {
} else {
format!("{} · {}x{} · mirroring the desktop", inner.title(), cols, rows)
};
- if lease.fit {
- text.push_str(" · fitted to this window (Ctrl+Shift+F again to let go)");
- }
drop(lease);
if cols > inner.cols || rows > inner.rows {
text.push_str(&format!(" · this window fits {}x{}", inner.cols, inner.rows));
@@ -1123,6 +1320,7 @@ impl App {
let mut inner = self.inner.borrow_mut();
if let Some((idx, at)) = Self::divider_under(&inner, x, y) {
inner.drag_divider = Some((idx, at, 0));
+ inner.drag_layout = inner.tab_layout.clone();
}
}
Pointer::Move => {
@@ -1157,12 +1355,20 @@ impl App {
return;
}
inner.drag_divider = Some((idx, start, cells));
- (idx, cells - sent)
+ (idx, cells - sent, cells)
};
- self.adjust_divider(step.0, step.1);
+ // The page's own claim, pane by pane, keeps every bar's rows
+ // as the divider moves; a page that does not hold the tab
+ // can only ask the server to grow a pane.
+ if self.inner.borrow().link.lease().owns_viewport() {
+ self.drag_divider_to(step.0, step.2);
+ } else {
+ self.adjust_divider(step.0, step.1);
+ }
}
Pointer::Up => {
let was = self.inner.borrow_mut().drag_divider.take();
+ self.inner.borrow_mut().drag_layout = None;
if was.is_some() {
// The held-back report goes out with a fresh listing,
// and not deduplicated: the drag put every pane at its
@@ -1175,6 +1381,208 @@ impl App {
}
}
+ /// Keep every drawn pane's rows on screen across a resize the server
+ /// has yet to answer: a live-resize preview at the size each pane is
+ /// expected to get. Rows are normalised to that width and refetched,
+ /// never dropped, until a listing settles the sizes (`settle_previews`).
+ fn preview_panes(inner: &mut Inner, sizes: &[(PaneId, TerminalSize)]) {
+ use thinkterm_session::lines::FrontendPreviewPolicy;
+ inner.preview_epoch += 1;
+ let epoch = inner.preview_epoch;
+ for (pane, size) in sizes {
+ if let Some(cell) = inner.panes.get_mut(pane) {
+ cell.session.begin_frontend_preview(epoch, *size, FrontendPreviewPolicy::LiveResize);
+ cell.preview = Some((epoch, *size, monotonic_ms()));
+ }
+ }
+ }
+
+ /// The layout with every frame scaled to a `cols` x `rows` grid, edges
+ /// rounded so the frames still tile: what the tab looks like once it
+ /// takes this window's grid, near enough to claim pane by pane.
+ fn scaled_layout(inner: &Inner, cols: usize, rows: usize) -> Option<crate::layout::TabLayout> {
+ let layout = inner.tab_layout.as_ref()?;
+ if layout.cols == 0 || layout.rows == 0 {
+ return None;
+ }
+ let (cw, ch) = (
+ inner.glyphs.metrics.cell_size.width as usize,
+ inner.glyphs.metrics.cell_size.height as usize,
+ );
+ crate::layout::scaled(
+ layout,
+ TerminalSize {
+ cols,
+ rows,
+ pixel_width: cols * cw,
+ pixel_height: rows * ch,
+ dpi: (96.0 * inner.dpr) as u32,
+ },
+ )
+ }
+
+ /// The sizes the panes would have if the tab took this grid, scaled
+ /// from their frames: near enough for a preview, which only has to
+ /// keep rows on screen until the server says the exact size.
+ #[allow(dead_code)]
+ fn scaled_pane_sizes(inner: &Inner, cols: usize, rows: usize) -> Vec<(PaneId, TerminalSize)> {
+ let Some(layout) = inner.tab_layout.as_ref() else {
+ return vec![];
+ };
+ if layout.cols == 0 || layout.rows == 0 {
+ return vec![];
+ }
+ let nav_rows = Self::nav_rows(inner);
+ let (cw, ch) = (
+ inner.glyphs.metrics.cell_size.width as usize,
+ inner.glyphs.metrics.cell_size.height as usize,
+ );
+ let dpi = (96.0 * inner.dpr) as u32;
+ layout
+ .panes
+ .iter()
+ .map(|p| {
+ let c = (p.frame.cols * cols + layout.cols / 2) / layout.cols;
+ let r = (p.frame.rows * rows + layout.rows / 2) / layout.rows;
+ let r = r.saturating_sub(nav_rows).max(1);
+ let c = c.max(1);
+ (p.pane_id, TerminalSize { cols: c, rows: r, pixel_width: c * cw, pixel_height: r * ch, dpi })
+ })
+ .collect()
+ }
+
+ /// A listing is the server's word on every pane's size: a preview it
+ /// confirms ends; one it contradicts is moved to the listed size, rows
+ /// kept, so the change never shows as a blank pane.
+ /// How long a preview may wait for the server to confirm its size
+ /// before the page gives it up and shows what the server has: a
+ /// preview holds the pane's rows at a guess and turns away pushes
+ /// at any other size, so one the server never meets would leave
+ /// the pane painted wrong until something else redrew it.
+ const PREVIEW_PATIENCE_MS: f64 = 1_500.0;
+
+ fn settle_previews(inner: &mut Inner) {
+ use thinkterm_session::lines::FrontendPreviewPolicy;
+ let Some(layout) = inner.tab_layout.clone() else {
+ return;
+ };
+ let now = monotonic_ms();
+ for place in &layout.panes {
+ let Some(cell) = inner.panes.get_mut(&place.pane_id) else {
+ continue;
+ };
+ let listed = place.size;
+ match cell.preview {
+ Some((epoch, size, _)) if cell.session.server_geometry_matches(size) => {
+ cell.session.end_frontend_preview(epoch, true);
+ cell.preview = None;
+ }
+ Some((epoch, _, at)) if now - at > Self::PREVIEW_PATIENCE_MS => {
+ log::info!("pane {}: the server never met the previewed size; showing its own", place.pane_id);
+ cell.session.end_frontend_preview(epoch, false);
+ cell.preview = None;
+ }
+ Some((_, size, at)) if size != listed => {
+ inner.preview_epoch += 1;
+ let epoch = inner.preview_epoch;
+ cell.session.begin_frontend_preview(epoch, listed, FrontendPreviewPolicy::LiveResize);
+ cell.preview = Some((epoch, listed, at));
+ if cell.session.server_geometry_matches(listed) {
+ cell.session.end_frontend_preview(epoch, true);
+ cell.preview = None;
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+
+ /// See `Client::panel_drag`. Letting go reshapes the tab to the grid
+ /// the canvas ended at, in one claim.
+ pub fn set_panel_drag(&self, on: bool) {
+ {
+ let mut inner = self.inner.borrow_mut();
+ if inner.panel_drag == on {
+ return;
+ }
+ inner.panel_drag = on;
+ if !on {
+ inner.cols = 0;
+ }
+ }
+ if !on {
+ self.resize();
+ }
+ }
+
+ /// Another pane in `pane`'s stack, as the desktop's bar `+` makes;
+ /// it is shown and focused.
+ pub fn new_in_stack(self: &Rc<Self>, pane: PaneId) {
+ self.act(
+ "web-act-new-tab",
+ Pdu::SpawnPaneInStack(codec::SpawnPaneInStack {
+ pane_id: pane,
+ command: None,
+ command_dir: None,
+ domain: thinkterm_proto::SpawnTabDomain::CurrentPaneDomain,
+ }),
+ |app, answer| {
+ if let Pdu::SpawnResponse(spawned) = answer {
+ app.switch_to_pane(spawned.pane_id, false);
+ }
+ },
+ );
+ }
+
+ /// Claim the tab with divider `idx` moved `cells` from where the drag
+ /// began (right/down positive): every pane touching the divider along
+ /// its extent gives or takes the cells, none below one content row.
+ fn drag_divider_to(self: &Rc<Self>, idx: usize, cells: isize) {
+ let (link, tab_id) = {
+ let inner = self.inner.borrow();
+ let Some(layout) = inner.drag_layout.as_ref() else {
+ return;
+ };
+ let Some(moved) = crate::layout::with_divider_moved(layout, idx, cells, Self::nav_rows(&inner)) else {
+ return;
+ };
+ let panes = Self::native_panes(&inner, &moved);
+ let sizes: Vec<(PaneId, TerminalSize)> = panes.iter().map(|p| (p.pane_id, p.size)).collect();
+ let mut lease = inner.link.lease_mut();
+ lease.native = panes;
+ lease.native_root = Some(moved.size);
+ drop(lease);
+ let tab_id = layout.tab_id;
+ let link = inner.link.clone();
+ drop(inner);
+ let mut inner = self.inner.borrow_mut();
+ Self::preview_panes(&mut inner, &sizes);
+ // The picture follows every step; the wire takes one step at
+ // a time, and the latest when it is free again.
+ if inner.divider_claim_busy {
+ inner.divider_claim_next = Some((idx, cells));
+ return;
+ }
+ inner.divider_claim_busy = true;
+ (link, tab_id)
+ };
+ let app = Rc::clone(self);
+ wasm_bindgen_futures::spawn_local(async move {
+ if let Err(err) = link.report_viewport(tab_id).await {
+ log::warn!("moving the divider: {err:#}");
+ }
+ let next = {
+ let mut inner = app.inner.borrow_mut();
+ inner.divider_claim_busy = false;
+ inner.divider_claim_next.take().filter(|_| inner.drag_divider.is_some())
+ };
+ match next {
+ Some((idx, cells)) => app.drag_divider_to(idx, cells),
+ None => app.refresh_layout(),
+ }
+ });
+ }
+
/// Move divider `idx` by `delta` cells (right/down positive): the
/// server grows the pane on one side of it in that direction, so the
/// pane next to the divider is focused first. Nested splits are
@@ -1182,7 +1590,7 @@ impl App {
/// orientation above the pane.
fn adjust_divider(self: &Rc<Self>, idx: usize, delta: isize) {
use thinkterm_proto::keyassignment::PaneDirection;
- let (pane, direction, link) = {
+ let (pane, direction, link, palette) = {
let inner = self.inner.borrow();
let Some(layout) = inner.tab_layout.as_ref() else {
return;
@@ -1215,7 +1623,7 @@ impl App {
let Some(pane) = pane else {
return;
};
- (pane, direction, inner.link.clone())
+ (pane, direction, inner.link.clone(), inner.configured())
};
let amount = delta.unsigned_abs();
let app = Rc::clone(self);
@@ -1223,7 +1631,7 @@ impl App {
// The server resizes the tab's active pane: make it this one.
let _ = thinkterm_session::host::request(
&link,
- Pdu::SetFocusedPane(codec::SetFocusedPane { pane_id: pane, configured_palette: None }),
+ Pdu::SetFocusedPane(codec::SetFocusedPane { pane_id: pane, configured_palette: Some(palette) }),
|p| match p {
Pdu::UnitResponse(_) => Ok(()),
other => Err(other),
@@ -1318,12 +1726,12 @@ impl App {
doc.set_title(&format!("{} — ThinkTerm", inner.title()));
}
Self::render_strip(&inner);
- inner.link.clone()
+ (inner.link.clone(), inner.configured())
};
self.refresh_status();
self.request_frame();
if advise {
- Self::advise_focus(link, pane_id);
+ Self::advise_focus(link.0, pane_id, link.1);
}
}
@@ -1331,11 +1739,14 @@ impl App {
/// Sent and forgotten: the desktop may ignore it for a few seconds
/// after a focus move of its own, and the echo is the pane already
/// focused here.
- fn advise_focus(link: crate::link::WsLink, pane_id: PaneId) {
+ /// The page's base palette goes with it: the server paints a pane
+ /// with the colours of whoever focused it last, as it does for the
+ /// desktop, so a pane the page uses shows the page's scheme.
+ fn advise_focus(link: crate::link::WsLink, pane_id: PaneId, palette: ColorPalette) {
wasm_bindgen_futures::spawn_local(async move {
let pdu = Pdu::SetFocusedPane(codec::SetFocusedPane {
pane_id,
- configured_palette: None,
+ configured_palette: Some(palette),
});
if let Err(err) = thinkterm_session::host::request(&link, pdu, |p| match p {
Pdu::UnitResponse(_) => Ok(()),
@@ -1924,7 +2335,9 @@ impl App {
if !matches!(click, SideClick::RenameThread(_) | SideClick::RenameProject(_) | SideClick::NewProject)
&& self.inner.borrow().editing != crate::sidebar::Editing::None
{
- self.inner.borrow_mut().editing = crate::sidebar::Editing::None;
+ let inner = &mut *self.inner.borrow_mut();
+ inner.editing = crate::sidebar::Editing::None;
+ inner.new_project_error = None;
}
match click {
SideClick::Thread(id) => self.activate_thread(id),
@@ -1981,6 +2394,17 @@ impl App {
/// against it (a refusal is a remark, never an error), then ask for
/// the session view the server does not push, and go on.
fn mutate(self: &Rc<Self>, intent: crate::tree::Intent, then: impl FnOnce(&Rc<Self>) + 'static) {
+ self.mutate_or(intent, then, |app, why| Self::set_status(&app.inner.borrow(), &why));
+ }
+
+ /// `mutate`, with the refusal handed to a caller that shows it itself
+ /// rather than letting it pass by as a remark.
+ fn mutate_or(
+ self: &Rc<Self>,
+ intent: crate::tree::Intent,
+ then: impl FnOnce(&Rc<Self>) + 'static,
+ refused: impl FnOnce(&Rc<Self>, String) + 'static,
+ ) {
let link = self.inner.borrow().link.clone();
let app = Rc::clone(self);
wasm_bindgen_futures::spawn_local(async move {
@@ -1996,7 +2420,7 @@ impl App {
let tree = match tree {
Ok(tree) => tree,
Err(err) => {
- Self::set_status(&app.inner.borrow(), &format!("the server refused: {err:#}"));
+ refused(&app, format!("the server refused: {err:#}"));
return;
}
};
@@ -2005,7 +2429,7 @@ impl App {
app.fetch_session().await;
match verdict {
Ok(()) => then(&app),
- Err(why) => Self::set_status(&app.inner.borrow(), &why),
+ Err(why) => refused(&app, why),
}
});
}
@@ -2029,7 +2453,9 @@ impl App {
fn on_side_write(self: &Rc<Self>, click: crate::sidebar::SideClick) {
use crate::sidebar::{Editing, SideClick};
if !matches!(click, SideClick::RenameThread(_) | SideClick::RenameProject(_) | SideClick::NewProject) {
- self.inner.borrow_mut().editing = Editing::None;
+ let inner = &mut *self.inner.borrow_mut();
+ inner.editing = Editing::None;
+ inner.new_project_error = None;
}
match click {
SideClick::NewThread(project) => {
@@ -2074,6 +2500,7 @@ impl App {
SideClick::NewProject => {
let inner = &mut *self.inner.borrow_mut();
inner.editing = Editing::NewProject;
+ inner.new_project_error = None;
Self::notify(inner);
}
SideClick::RenameThread(id) => {
@@ -2090,20 +2517,11 @@ impl App {
self.mutate(crate::tree::set_pinned(&id, on, Self::now_secs()), |_| {});
}
SideClick::Delete(id) => {
+ // On the first press, as the desktop's menu item is: no
+ // second press to confirm.
let confirmed = {
- let mut inner = self.inner.borrow_mut();
- let now = monotonic_ms();
- match &inner.deleting {
- Some((pending, since)) if *pending == id && now - since < CLOSE_CONFIRM_MS => {
- inner.deleting = None;
- true
- }
- _ => {
- inner.deleting = Some((id.clone(), now));
- Self::notify(&inner);
- false
- }
- }
+ self.inner.borrow_mut().deleting = None;
+ true
};
if confirmed {
let panes = Self::thread_panes(&self.inner.borrow(), &id);
@@ -2142,9 +2560,11 @@ impl App {
"Escape" => {
let inner = &mut *self.inner.borrow_mut();
inner.editing = Editing::None;
+ inner.new_project_error = None;
Self::notify(inner);
let _ = inner.textarea.focus();
}
+ "Enter" if editing == Editing::NewProject => self.add_workspace(value.trim()),
"Enter" => {
{
let inner = &mut *self.inner.borrow_mut();
@@ -2160,25 +2580,70 @@ impl App {
Editing::Thread(id) => self.mutate(crate::tree::rename_thread(&id, &value, Self::now_secs()), |_| {}),
Editing::Project(id) => self.mutate(crate::tree::rename_project(&id, &value), |_| {}),
Editing::Space(id) => self.mutate(crate::tree::rename_space(&id, &value), |_| {}),
- Editing::NewProject => {
- if !(value.starts_with('/') || value.starts_with('~')) {
- Self::set_status(&self.inner.borrow(), "a project is a directory: ~/dir or /dir");
- return;
- }
- // The new project lands in the Space on show.
- let space = self.inner.borrow().tree.current_space().map(|s| s.id.clone());
- let project = Self::new_id("project");
- let thread = Self::new_id("thread");
- let intent = crate::tree::create_project(space.as_deref(), project, thread.clone(), &value, Self::now_secs());
- self.mutate(intent, move |app| app.activate_thread(thread));
- }
- Editing::None => {}
+ Editing::NewProject | Editing::None => {}
}
}
_ => {}
}
}
+ /// Keep the "Add workspace" field open with `why` beside it, so the
+ /// path that was refused can be corrected rather than retyped.
+ fn refuse_workspace(self: &Rc<Self>, why: String) {
+ let inner = &mut *self.inner.borrow_mut();
+ inner.editing = crate::sidebar::Editing::NewProject;
+ inner.new_project_error = Some(why);
+ Self::notify(inner);
+ }
+
+ /// A path typed into "Add workspace". An empty or relative one is
+ /// refused here; a directory the tree already has is opened rather
+ /// than added twice, as the desktop's `create_project_from_path`
+ /// does; anything else is a project and its `main` thread.
+ fn add_workspace(self: &Rc<Self>, path: &str) {
+ if path.is_empty() {
+ self.refuse_workspace(thinkterm_i18n::tr("web-add-workspace-empty"));
+ return;
+ }
+ if !(path.starts_with('/') || path.starts_with('~')) {
+ self.refuse_workspace(thinkterm_i18n::tr("web-add-workspace-relative"));
+ return;
+ }
+ let trimmed = path.trim_end_matches('/');
+ let (space, existing) = {
+ let inner = self.inner.borrow();
+ let space = inner.tree.current_space().map(|s| s.id.clone());
+ let existing = inner.tree.session.as_ref().and_then(|s| {
+ s.projects
+ .iter()
+ .filter(|p| space.as_deref().is_none_or(|id| p.space_id == id))
+ .find(|p| p.path.trim_end_matches('/') == trimmed && !trimmed.is_empty())
+ .and_then(|p| p.threads.first())
+ .map(|t| t.id.clone())
+ });
+ (space, existing)
+ };
+ {
+ let inner = &mut *self.inner.borrow_mut();
+ inner.editing = crate::sidebar::Editing::None;
+ inner.new_project_error = None;
+ Self::notify(inner);
+ let _ = inner.textarea.focus();
+ }
+ if let Some(thread) = existing {
+ self.activate_thread(thread);
+ return;
+ }
+ let project = Self::new_id("project");
+ let thread = Self::new_id("thread");
+ let intent = crate::tree::create_project(space.as_deref(), project, thread.clone(), path, Self::now_secs());
+ self.mutate_or(
+ intent,
+ move |app| app.activate_thread(thread),
+ |app, why| app.refuse_workspace(why),
+ );
+ }
+
/// Show a thread: its active tab when it has terminals, else have the
/// server make them (`EnsureThinkTermThread`) and show what it made.
/// Either way the thread is touched and read, as the desktop does.
@@ -2412,6 +2877,9 @@ impl App {
if tab_changed {
inner.selecting = false;
inner.ime_anchor = None;
+ // Every showing claims afresh: the desktop may have taken
+ // this tab since the page last had it.
+ inner.auto_claimed = None;
// Forces `resize` to see a change: the tab is reflowed to
// this grid if the page owns it, or reported against it.
inner.cols = 0;
@@ -2459,6 +2927,27 @@ impl App {
self.refresh_status();
self.request_frame();
}
+ // The page holds the terminal it shows: taken at this window's
+ // shape as soon as a tab is on screen, and taken back by the
+ // desktop only when someone interacts there.
+ // A showing the page already owns (the report took an ownerless
+ // tab) is handled too: the desktop taking it later is not undone
+ // by the next listing.
+ let claim = {
+ let mut inner = self.inner.borrow_mut();
+ let showing = inner.auto_claimed != Some(tab_id) && inner.disconnected.is_none();
+ if showing {
+ inner.auto_claimed = Some(tab_id);
+ }
+ let lease = inner.link.lease();
+ // Handoff is exclusive: a terminal someone holds is taken by a
+ // press on the card, never by a page merely opening.
+ let held_exclusively = lease.needs_claim() && lease.owner.is_some();
+ showing && !lease.owns_viewport() && !held_exclusively
+ };
+ if claim {
+ self.take_over_with(true);
+ }
}
/// Make `inner.panes` match `layout`, focusing `want` if it is drawn
@@ -2469,8 +2958,20 @@ impl App {
// Another tab is another lease and another tab id for every
// session under it.
inner.remote_tab_id = Arc::new(std::sync::atomic::AtomicUsize::new(layout.tab_id));
- inner.panes.clear();
+ let mut leaving = std::mem::take(&mut inner.panes);
+ // A preview in force would turn away every push while the
+ // tab is parked; it is over now, the server's size stands.
+ for cell in leaving.values_mut() {
+ if let Some((epoch, _, _)) = cell.preview.take() {
+ cell.session.end_frontend_preview(epoch, false);
+ }
+ }
+ inner.parked.extend(leaving);
inner.tab_id = layout.tab_id;
+ // Kept for the tabs recently shown; the rest are built again
+ // when next shown, as they were the first time.
+ let kept: Vec<TabId> = inner.recent_tabs.iter().take(PARKED_TABS).copied().collect();
+ inner.parked.retain(|_, cell| kept.contains(&cell.session.remote_tab_id()));
}
inner.recent_tabs.retain(|t| *t != layout.tab_id);
inner.recent_tabs.insert(0, layout.tab_id);
@@ -2485,6 +2986,21 @@ impl App {
if inner.panes.contains_key(&place.pane_id) {
continue;
}
+ // A parked pane comes back with what it had, unless it has
+ // moved to another tab meanwhile: its session is bound to the
+ // old tab's lease, so it is built afresh, as a stranger is.
+ if let Some(mut cell) = inner.parked.remove(&place.pane_id) {
+ if cell.session.remote_tab_id() == layout.tab_id {
+ // Its program may have set or reset its colours while
+ // the tab was away; only `overrides` heard.
+ cell.application = inner.overrides.get(&place.pane_id).cloned().flatten();
+ if std::mem::take(&mut cell.reconnect_stale) {
+ fresh.push(place.pane_id);
+ }
+ inner.panes.insert(place.pane_id, cell);
+ continue;
+ }
+ }
let rows = place.size.rows;
let dims = thinkterm_proto::RenderableDimensions {
cols: place.size.cols,
@@ -2506,11 +3022,14 @@ impl App {
&place.title,
place.alt_screen,
);
- inner
- .panes
- .insert(place.pane_id, PaneCell::new(session, &place.title));
+ let mut cell = PaneCell::new(session, &place.title);
+ cell.application = inner.overrides.get(&place.pane_id).cloned().flatten();
+ inner.panes.insert(place.pane_id, cell);
fresh.push(place.pane_id);
}
+ // A fresh cell starts on the stock palette; the base and any
+ // override it has are folded in before it is first drawn.
+ inner.recompute_palettes();
inner.focused_pane = if drawn.contains(&want) {
want
} else {
@@ -2523,6 +3042,7 @@ impl App {
.unwrap_or(want)
};
inner.tab_layout = Some(layout);
+ Self::settle_previews(inner);
fresh
}
@@ -2594,31 +3114,21 @@ impl App {
}
Click::CloseTab(tab_id) => {
let panes: Vec<PaneId> = {
+ // On the first press, as the desktop's × is.
let mut inner = self.inner.borrow_mut();
- let now = monotonic_ms();
- match inner.closing_tab {
- Some((tab, since)) if tab == tab_id && now - since < CLOSE_CONFIRM_MS => {
- inner.closing_tab = None;
- inner
- .layout
- .as_ref()
- .map(|l| {
- l.tabs
- .iter()
- .flat_map(crate::layout::leaves)
- .filter(|e| e.tab_id == tab_id)
- .map(|e| e.pane_id)
- .collect()
- })
- .unwrap_or_default()
- }
- _ => {
- inner.closing_tab = Some((tab_id, now));
- Self::render_strip(&inner);
- let _ = inner.textarea.focus();
- vec![]
- }
- }
+ inner.closing_tab = None;
+ inner
+ .layout
+ .as_ref()
+ .map(|l| {
+ l.tabs
+ .iter()
+ .flat_map(crate::layout::leaves)
+ .filter(|e| e.tab_id == tab_id)
+ .map(|e| e.pane_id)
+ .collect()
+ })
+ .unwrap_or_default()
};
for pane_id in panes {
self.act(
@@ -2646,25 +3156,15 @@ impl App {
let _ = inner.textarea.focus();
}
Click::NewTab => self.new_tab(),
+ Click::NewInStack(pane) => self.new_in_stack(pane),
Click::SplitRight(pane) => self.split(pane, thinkterm_proto::SplitDirection::Horizontal),
Click::SplitBelow(pane) => self.split(pane, thinkterm_proto::SplitDirection::Vertical),
Click::Zoom(pane) => self.toggle_zoom(pane),
Click::Close => {
+ // On the first press, as the desktop's × is.
let confirmed = {
- let mut inner = self.inner.borrow_mut();
- let now = monotonic_ms();
- match inner.closing_since {
- Some(since) if now - since < CLOSE_CONFIRM_MS => {
- inner.closing_since = None;
- true
- }
- _ => {
- inner.closing_since = Some(now);
- Self::render_strip(&inner);
- let _ = inner.textarea.focus();
- false
- }
- }
+ self.inner.borrow_mut().closing_since = None;
+ true
};
if confirmed {
self.close_pane();
@@ -2773,6 +3273,101 @@ impl App {
);
}
+ /// A dropped tab: put it at `index` among its window's tabs. The
+ /// listing that follows redraws the strip; the drop is refused for a
+ /// tab the page does not know.
+ pub fn move_tab(self: &Rc<Self>, tab: TabId, index: usize) -> bool {
+ let window_id = {
+ let inner = self.inner.borrow();
+ let Some((tabs, _)) = Self::strip_model(&inner) else {
+ return false;
+ };
+ let Some(view) = tabs.iter().find(|t| t.tab_id == tab) else {
+ return false;
+ };
+ if tabs.iter().position(|t| t.tab_id == tab) == Some(index) {
+ return true;
+ }
+ view.window_id
+ };
+ self.act("web-act-move-tab", Pdu::MoveTab(codec::MoveTab { window_id, tab_id: tab, index }), |_, _| {});
+ true
+ }
+
+ /// A pane dropped on another: it leaves its place and becomes the
+ /// target's neighbour in `direction`, after it (`second`) or before.
+ /// Dropping a pane on itself is nothing.
+ pub fn move_pane(
+ self: &Rc<Self>,
+ pane: PaneId,
+ target: PaneId,
+ direction: thinkterm_proto::SplitDirection,
+ second: bool,
+ ) -> bool {
+ if pane == target {
+ return false;
+ }
+ self.act(
+ "web-act-move-pane",
+ Pdu::SplitPane(codec::SplitPane {
+ pane_id: target,
+ split_request: thinkterm_proto::SplitRequest {
+ direction,
+ target_is_second: second,
+ top_level: false,
+ size: thinkterm_proto::SplitSize::Percent(50),
+ },
+ command: None,
+ command_dir: None,
+ domain: thinkterm_proto::SpawnTabDomain::CurrentPaneDomain,
+ move_pane_id: Some(pane),
+ }),
+ move |app, _| app.switch_to_pane(pane, false),
+ );
+ true
+ }
+
+ /// A thread dropped among its project's unpinned threads, before
+ /// `before` (None: last); refused across projects and for pinned rows.
+ pub fn move_thread(self: &Rc<Self>, id: &str, before: Option<&str>) -> bool {
+ let intent = {
+ let inner = self.inner.borrow();
+ let Some(project) = inner.tree.project_of(id) else {
+ return false;
+ };
+ let unpinned: Vec<String> =
+ project.threads.iter().filter(|t| !t.is_pinned).map(|t| t.id.clone()).collect();
+ if !unpinned.iter().any(|t| t == id) || before.is_some_and(|b| !unpinned.iter().any(|t| t == b)) {
+ return false;
+ }
+ crate::tree::move_thread_before(&project.id, id, before, &unpinned)
+ };
+ self.mutate(intent, |_| {});
+ true
+ }
+
+ /// A project dropped among its Space's projects, before `before`
+ /// (None: last); refused across Spaces.
+ pub fn move_project(self: &Rc<Self>, id: &str, before: Option<&str>) -> bool {
+ let intent = {
+ let inner = self.inner.borrow();
+ let Some(session) = inner.tree.session.as_ref() else {
+ return false;
+ };
+ let Some(space) = session.projects.iter().find(|p| p.id == id).map(|p| p.space_id.clone()) else {
+ return false;
+ };
+ let order: Vec<String> =
+ session.projects.iter().filter(|p| p.space_id == space).map(|p| p.id.clone()).collect();
+ if before.is_some_and(|b| !order.iter().any(|p| p == b)) {
+ return false;
+ }
+ crate::tree::move_project_before(&space, id, before, &order)
+ };
+ self.mutate(intent, |_| {});
+ true
+ }
+
/// A context menu for something on the page: `kind` names what was
/// clicked, `id` which one. Empty when there is nothing to offer.
pub fn context_menu(&self, kind: &str, id: &str) -> Vec<crate::menu::MenuItem> {
@@ -2806,7 +3401,8 @@ impl App {
inner.panes.get(&pane).map(|c| crate::navbar::display_title(&c.title).0)
});
let summary = crate::agents::summary(&rows);
- crate::agents::AgentsView { rows, summary }
+ let tabs = crate::agents::panel_tabs();
+ crate::agents::AgentsView { rows, summary, tabs, active: "agents" }
}
/// Bring an agent's pane on show: switch to it here, or open the
@@ -2847,6 +3443,44 @@ impl App {
}
}
+ /// Re-upload and repaint the panes whose palette moved: every glyph and
+ /// the ground behind it are coloured from it.
+ fn repaint_palettes(self: &Rc<Self>, changed: &[PaneId]) {
+ if changed.is_empty() {
+ return;
+ }
+ {
+ let inner = self.inner.borrow();
+ for pane_id in changed {
+ if let Some(cell) = inner.panes.get(pane_id) {
+ cell.session.make_all_stale();
+ }
+ }
+ }
+ self.request_frame();
+ }
+
+ /// The colours of the scheme this browser picked, as the page read them
+ /// out of `schemes.json`; `None` follows the server's configuration.
+ pub fn set_terminal_palette(self: &Rc<Self>, palette: Option<ColorPalette>) {
+ let changed = {
+ let mut inner = self.inner.borrow_mut();
+ if inner.chosen_palette == palette {
+ return;
+ }
+ inner.chosen_palette = palette;
+ inner.recompute_palettes()
+ };
+ self.repaint_palettes(&changed);
+ // The pane in use takes the new scheme on the server too.
+ let (link, pane, palette) = {
+ let inner = self.inner.borrow();
+ (inner.link.clone(), inner.focused_pane, inner.configured())
+ };
+ Self::advise_focus(link, pane, palette);
+ Self::notify(&self.inner.borrow());
+ }
+
/// The page's preferences, as the model holds them.
pub fn settings_view(&self) -> crate::settings::WebSettings {
self.inner.borrow().settings.clone()
@@ -2858,19 +3492,31 @@ impl App {
self.inner.borrow_mut().settings = settings.clone();
self.apply_language(&settings.language);
self.set_font_mode(settings.font);
+ if settings.terminal_scheme == crate::settings::FOLLOW_DESKTOP {
+ self.set_terminal_palette(None);
+ }
Ok(())
}
/// One preference changed on the page.
pub fn set_setting(self: &Rc<Self>, key: &str, value: &str) -> Result<(), String> {
- let (language, font) = {
+ let (language, font, scheme) = {
let mut inner = self.inner.borrow_mut();
inner.settings.set(key, value)?;
- (inner.settings.language.clone(), inner.settings.font)
+ (
+ inner.settings.language.clone(),
+ inner.settings.font,
+ inner.settings.terminal_scheme.clone(),
+ )
};
match key {
"language" => self.apply_language(&language),
"font" => self.set_font_mode(font),
+ // Back to the desktop's scheme: the colours the page sends with
+ // a named pick are simply dropped.
+ "terminal-scheme" if scheme == crate::settings::FOLLOW_DESKTOP => {
+ self.set_terminal_palette(None)
+ }
_ => Self::notify(&self.inner.borrow()),
}
Ok(())
@@ -2891,6 +3537,7 @@ impl App {
let pt = pt.clamp(6.0, 72.0);
let mut inner = self.inner.borrow_mut();
inner.font_pinned = true;
+ inner.base_size_pt = pt;
if (inner.glyphs.size_pt - pt).abs() >= 0.125 {
let dpi = (96.0 * inner.dpr) as u32;
Self::rerasterise(&mut inner, pt, dpi);
@@ -2901,7 +3548,10 @@ impl App {
self.request_frame();
}
FontMode::Follow => {
- self.inner.borrow_mut().font_pinned = false;
+ let mut inner = self.inner.borrow_mut();
+ inner.font_pinned = false;
+ inner.base_size_pt = inner.boot_size_pt;
+ drop(inner);
self.match_desktop_cell();
self.request_frame();
}
@@ -3046,6 +3696,7 @@ impl App {
let known = inner.tree.set_space(id);
if known {
inner.editing = crate::sidebar::Editing::None;
+ inner.new_project_error = None;
Self::notify(inner);
}
known
@@ -3283,9 +3934,20 @@ impl App {
/// Take the terminal from whichever device holds it (Handoff mode).
/// There is no giving it back: the desktop takes it by interacting.
pub fn take_over(self: &Rc<Self>) {
+ self.take_over_with(false);
+ }
+
+ /// `quiet`: the page's own claim on showing a tab, not a person's
+ /// action, so a refusal is logged rather than remarked on.
+ fn take_over_with(self: &Rc<Self>, quiet: bool) {
let (link, tab_id) = {
- let inner = self.inner.borrow();
- Self::set_status(&inner, &tr("web-toast-taking-over"));
+ let mut inner = self.inner.borrow_mut();
+ if !quiet {
+ // The card says it is on the wire; a toast would sit under
+ // the card.
+ inner.claim = Claim::Taking;
+ Self::notify(&inner);
+ }
// Taken by an interaction here: at this page's own shape.
inner.link.lease_mut().fit = true;
(inner.link.clone(), inner.tab_id)
@@ -3294,27 +3956,46 @@ impl App {
wasm_bindgen_futures::spawn_local(async move {
let after = match link.claim(tab_id).await {
Ok(true) => {
+ // Back to the page's own size, and the grid with it.
+ app.match_desktop_cell();
app.refresh_status();
app.request_frame();
- app.inner.borrow_mut().after_take_over.take()
+ let mut inner = app.inner.borrow_mut();
+ inner.claim = Claim::Idle;
+ Self::notify(&inner);
+ inner.after_take_over.take()
}
Ok(false) => {
let mut inner = app.inner.borrow_mut();
inner.after_take_over = None;
- Self::set_status(&inner, &tr("web-toast-not-handed-over"));
+ if quiet {
+ log::info!("the server did not hand the terminal over on showing the tab");
+ } else {
+ inner.claim = Claim::Refused;
+ Self::notify(&inner);
+ }
None
}
Err(err) => {
let mut inner = app.inner.borrow_mut();
inner.after_take_over = None;
- Self::set_status(&inner, &failed("web-act-take-over", &err));
+ if quiet {
+ log::warn!("claiming the tab on showing it: {err:#}");
+ } else {
+ inner.claim = Claim::Refused;
+ Self::notify(&inner);
+ Self::set_status(&inner, &failed("web-act-take-over", &err));
+ }
None
}
};
match after {
Some(AfterTakeOver::Focus(pane_id)) => {
- let link = app.inner.borrow().link.clone();
- Self::advise_focus(link, pane_id);
+ let (link, palette) = {
+ let inner = app.inner.borrow();
+ (inner.link.clone(), inner.configured())
+ };
+ Self::advise_focus(link, pane_id, palette);
}
Some(AfterTakeOver::Key(key, mods, shift)) => {
app.key_down(key, mods, shift);
@@ -3529,6 +4210,12 @@ impl App {
if inner.font_pinned {
return None;
}
+ // Holding the tab, the page shows its own size; the desktop is
+ // the one following now.
+ if inner.link.lease().owns_viewport() {
+ let base = inner.base_size_pt;
+ return ((inner.glyphs.size_pt - base).abs() >= 0.125).then_some(base);
+ }
let (desktop, fit) = {
let lease = inner.link.lease();
(lease.canonical_size, lease.fit)
@@ -3620,10 +4307,10 @@ impl App {
// The bars are placed from the cell size, which may just have moved.
Self::notify(&inner);
if changed {
- // The page's grid is its own business: the tab keeps the
- // desktop's size and this canvas letterboxes it. Only a page
- // that asked to fit the tab to itself sends its grid, and then
- // as a claim, because that is what changing the tab's size is.
+ // The holder shapes the tab: a page that has the tab claims
+ // its new grid, as a claim, because that is what changing the
+ // tab's size is. A follower keeps the desktop's size and
+ // letterboxes it.
let size = TerminalSize {
rows,
cols,
@@ -3634,9 +4321,21 @@ impl App {
let fitting = {
let mut lease = inner.link.lease_mut();
lease.reported = Some(size);
- lease.fit && lease.owns_viewport()
+ lease.owns_viewport() && !inner.panel_drag
};
if fitting {
+ // Pane by pane, at frames scaled to the new grid: one
+ // claim that reserves every bar's rows, rather than a bare
+ // grid the listing then corrects (two reflows on screen).
+ if let Some(scaled) = Self::scaled_layout(&inner, cols, rows) {
+ let panes = Self::native_panes(&inner, &scaled);
+ let sizes: Vec<(PaneId, TerminalSize)> = panes.iter().map(|p| (p.pane_id, p.size)).collect();
+ let mut lease = inner.link.lease_mut();
+ lease.native = panes;
+ lease.native_root = Some(size);
+ drop(lease);
+ Self::preview_panes(&mut inner, &sizes);
+ }
let link = inner.link.clone();
let tab_id = inner.tab_id;
wasm_bindgen_futures::spawn_local(async move {
@@ -3669,7 +4368,12 @@ impl App {
inner.connected_since = None;
inner.reconnect_delay = RECONNECT_MIN_MS;
}
- let _ = inner.host.events.take_dirty();
+ // Output in a parked tab keeps its cell current but changes
+ // nothing on screen: no paint for it alone.
+ let dirty = inner.host.events.take_dirty();
+ if !dirty.is_empty() && dirty.iter().all(|pane| !inner.panes.contains_key(pane)) {
+ return;
+ }
let title = inner.focused().session.title();
if title != inner.focused().title {
inner.focused_mut().title = title;
@@ -3915,6 +4619,7 @@ impl App {
let placements = Self::placements(inner);
let focused_palette = inner.focused().palette.clone();
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();
for place in &placements {
let (cols_shown, rows_shown) = Self::shown_in(inner, place);
@@ -3930,7 +4635,12 @@ impl App {
}
let visible = visible_rows(&dims, rows_shown, cell.scroll_from_bottom);
let (first, lines) = session.get_lines(visible);
- let cursor = session.cursor_position();
+ // No cursor before the server has placed one: a fresh cell's
+ // sits at the origin, which is nowhere real.
+ let mut cursor = session.cursor_position();
+ if !session.has_received() {
+ cursor.y = StableRowIndex::MIN;
+ }
let palette = cell.palette.clone();
let selection = cell.selection;
let is_focused = place.pane_id == inner.focused_pane;
@@ -3951,16 +4661,30 @@ impl App {
// The content sits below the pane's bar, as on the desktop.
let origin = (frame_origin.0, frame_origin.1 + offset);
let clip = (cols_shown as f32 * cell_w, rows_shown as f32 * cell_h);
- // The pane's own ground, over its whole frame: it carries the
- // pane's colours, and covers the rows of a frame the desktop
- // reserved below its bar.
+ // 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
+ // canvas and an inactive pane's dimming shows no rim.
+ let (tab_cols, tab_rows) = (tab.0, tab.1);
+ let x0 = if place.frame.left == 0 { 0.0 } else { frame_origin.0 - root_w / 2.0 };
+ let y0 = if place.frame.top == 0 { 0.0 } else { frame_origin.1 - root_h / 2.0 };
+ let x1 = if place.frame.left + place.frame.cols >= tab_cols {
+ surface.0
+ } else {
+ frame_origin.0 + place.frame.cols as f32 * root_w + root_w / 2.0
+ };
+ let y1 = if place.frame.top + place.frame.rows >= tab_rows {
+ surface.1
+ } else {
+ frame_origin.1 + place.frame.rows as f32 * root_h + root_h / 2.0
+ };
crate::emit::fill_rect(
glyphs,
quads,
0,
surface,
- frame_origin,
- (place.frame.cols as f32 * root_w, place.frame.rows as f32 * root_h),
+ (x0, y0),
+ (x1 - x0, y1 - y0),
palette.background.to_linear(),
hsv,
)?;
@@ -4014,22 +4738,25 @@ impl App {
if let Some(layout) = &inner.tab_layout {
let t = (inner.glyphs.metrics.underline_height.max(1)) as f32;
let colour = focused_palette.split.to_linear();
+ // Centred in the gap cell, and as long as the desktop's: half a
+ // cell into the neighbouring gaps, to the canvas edge where the
+ // gap reaches the tab's edge (`paint_split`).
for divider in &layout.dividers {
- let (x, y, dw, dh) = match *divider {
- crate::layout::Divider::Col { col, top, rows } => (
- col as f32 * cell_w + (cell_w - t) / 2.0,
- top as f32 * cell_h,
- t,
- rows as f32 * cell_h,
- ),
- crate::layout::Divider::Row { row, left, cols } => (
- left as f32 * cell_w,
- row as f32 * cell_h + (cell_h - t) / 2.0,
- cols as f32 * cell_w,
- t,
- ),
+ let (x0, y0, x1, y1) = match *divider {
+ crate::layout::Divider::Col { col, top, rows } => {
+ let x = pad.0 + col as f32 * cell_w + (cell_w - t) / 2.0;
+ let y0 = if top == 0 { 0.0 } else { pad.1 + top as f32 * cell_h - cell_h / 2.0 };
+ let y1 = if top + rows >= layout.rows { surface.1 } else { pad.1 + (top + rows) as f32 * cell_h + cell_h / 2.0 };
+ (x, y0, x + t, y1)
+ }
+ crate::layout::Divider::Row { row, left, cols } => {
+ let y = pad.1 + row as f32 * cell_h + (cell_h - t) / 2.0;
+ let x0 = if left == 0 { 0.0 } else { pad.0 + left as f32 * cell_w - cell_w / 2.0 };
+ let x1 = if left + cols >= layout.cols { surface.0 } else { pad.0 + (left + cols) as f32 * cell_w + cell_w / 2.0 };
+ (x0, y, x1, y + t)
+ }
};
- crate::emit::fill_rect(&inner.glyphs, &mut inner.quads, 0, surface, (pad.0 + x, pad.1 + y), (dw, dh), colour, None)?;
+ crate::emit::fill_rect(&inner.glyphs, &mut inner.quads, 0, surface, (x0, y0), (x1 - x0, y1 - y0), colour, None)?;
}
// A follower larger than the tab sees the desktop's faint
// grid over what the tab does not reach.
@@ -4065,6 +4792,13 @@ impl App {
font.quads.extract_vertices(&mut font.vertices);
declined += font.glyphs.declined();
}
+ // The cleared ground, for anyone reading the canvas from the page:
+ // the pixels themselves are behind WebGPU.
+ let hex = focused_palette.background.to_rgb_string();
+ if inner.published_bg.as_deref() != Some(hex.as_str()) {
+ let _ = inner.canvas.set_attribute("data-bg", &hex);
+ inner.published_bg = Some(hex);
+ }
let bg = focused_palette.background.to_linear().tuple();
let millis = (js_sys::Date::now() % (u32::MAX as f64)) as u32;
let mut batches: Vec<(&[Vertex], &GpuTexture)> = vec![(&inner.vertices, inner.glyphs.texture())];
diff --git a/thinkterm-web/src/bridge.rs b/thinkterm-web/src/bridge.rs
index 3a164b8d..995dd459 100644
--- a/thinkterm-web/src/bridge.rs
+++ b/thinkterm-web/src/bridge.rs
@@ -62,6 +62,25 @@ impl Client {
code.to_string()
}
+ /// A panel's edge is being dragged (`on`) or was let go: while it is,
+ /// the canvas follows but the tab is not reshaped on the server; the
+ /// one reshape comes at the end.
+ pub fn panel_drag(&self, on: bool) {
+ self.app.set_panel_drag(on);
+ }
+
+ /// Refit the canvas to its box now, in the same task as the layout
+ /// change that moved it, so no frame shows the old bitmap stretched.
+ pub fn resize(&self) {
+ self.app.resize();
+ }
+
+ /// The card's button, or a press on the card: ask for the terminal
+ /// another device holds. What comes of it is the card's next state.
+ pub fn take_over(&self) {
+ self.app.take_over();
+ }
+
/// A click in the sidebar: `kind` names the row or button, `id` the
/// thread, project or window it is about, `flag` the pin state.
/// Returns false for a kind the model does not know.
@@ -137,6 +156,23 @@ impl Client {
self.app.set_setting(&key, &value).err().unwrap_or_default()
}
+ /// The colours of the scheme named by `terminal-scheme`, as the page
+ /// read them out of `schemes.json`; `None` follows the server's
+ /// configuration. Returns an error text or "".
+ pub fn set_terminal_palette(&self, json: Option<String>) -> String {
+ let palette = match json.as_deref() {
+ None => None,
+ Some(text) => match crate::settings::SchemeColors::parse(text)
+ .and_then(|colors| colors.to_palette())
+ {
+ Ok(palette) => Some(palette),
+ Err(err) => return err,
+ },
+ };
+ self.app.set_terminal_palette(palette);
+ String::new()
+ }
+
/// The search palette's entries for `query`, ranked: JSON `Results`.
pub fn palette(&self, query: String) -> String {
json(&self.app.palette(&query))
@@ -180,6 +216,38 @@ impl Client {
/// A click on the tab row or a pane's bar. Returns false for an
/// action the model does not know.
+ /// A drop, decided here: `kind` is "tab" (id = tab id, `at` = the
+ /// index it lands on), "pane" (id = pane id, `target` = the pane it
+ /// was dropped on, `edge` = "left"|"right"|"top"|"bottom"), "thread"
+ /// or "project" (`target` = the row it lands before, None for last).
+ /// False when the model refuses; the listing or tree that follows
+ /// redraws the page.
+ pub fn drop(&self, kind: String, id: String, target: Option<String>, edge: Option<String>, at: Option<u32>) -> bool {
+ use thinkterm_proto::SplitDirection;
+ match kind.as_str() {
+ "tab" => match (id.parse(), at) {
+ (Ok(tab), Some(at)) => self.app.move_tab(tab, at as usize),
+ _ => false,
+ },
+ "pane" => {
+ let (Ok(pane), Some(Ok(target))) = (id.parse(), target.map(|t| t.parse())) else {
+ return false;
+ };
+ let (direction, second) = match edge.as_deref() {
+ Some("left") => (SplitDirection::Horizontal, false),
+ Some("right") => (SplitDirection::Horizontal, true),
+ Some("top") => (SplitDirection::Vertical, false),
+ Some("bottom") => (SplitDirection::Vertical, true),
+ _ => return false,
+ };
+ self.app.move_pane(pane, target, direction, second)
+ }
+ "thread" => self.app.move_thread(&id, target.as_deref()),
+ "project" => self.app.move_project(&id, target.as_deref()),
+ _ => false,
+ }
+ }
+
pub fn chrome_click(&self, action: String, pane: Option<u32>, tab: Option<u32>) -> bool {
use crate::chrome::Click;
let pane = pane.map(|p| p as usize);
@@ -187,6 +255,7 @@ impl Client {
("pane", Some(p), _) => Click::Pane(p),
("follow", _, _) => Click::Follow,
("new-tab", _, _) => Click::NewTab,
+ ("new-pane", Some(p), _) => Click::NewInStack(p),
("split-right", p, _) => Click::SplitRight(p),
("split-below", p, _) => Click::SplitBelow(p),
("zoom", p, _) => Click::Zoom(p),
diff --git a/thinkterm-web/src/chrome.rs b/thinkterm-web/src/chrome.rs
index 2f8cd82a..6bdf1127 100644
--- a/thinkterm-web/src/chrome.rs
+++ b/thinkterm-web/src/chrome.rs
@@ -157,6 +157,8 @@ pub enum Click {
Pane(PaneId),
Follow,
NewTab,
+ /// A bar's `+`: another pane in that pane's stack, as the desktop's.
+ NewInStack(PaneId),
/// The bar's pane, or the focused one from a chord.
SplitRight(Option<PaneId>),
SplitBelow(Option<PaneId>),
diff --git a/thinkterm-web/src/input.rs b/thinkterm-web/src/input.rs
index 32531a33..5eb524d5 100644
--- a/thinkterm-web/src/input.rs
+++ b/thinkterm-web/src/input.rs
@@ -45,7 +45,13 @@ pub fn install(app: Rc<App>, canvas: &HtmlCanvasElement, textarea: &HtmlTextArea
alt: ev.alt_key(),
shift: ev.shift_key(),
meta: ev.meta_key(),
- composing: ev.is_composing(),
+ // Chrome on macOS names the key the IME took (`h`, not
+ // `Process`) and only marks it by keyCode 229; a Pinyin
+ // `htop` would otherwise send `h` and then `htop`.
+ // Only a printable key: an IME that is on but idle (an
+ // Android keyboard, a CJK IME in ASCII mode) marks every
+ // key 229, and Backspace or Enter must still get through.
+ composing: ev.is_composing() || (ev.key_code() == 229 && key.chars().count() == 1),
};
match map_key(&dom) {
Some((key, mods)) => {
diff --git a/thinkterm-web/src/layout.rs b/thinkterm-web/src/layout.rs
index 84aaadd3..1eb620b5 100644
--- a/thinkterm-web/src/layout.rs
+++ b/thinkterm-web/src/layout.rs
@@ -123,6 +123,127 @@ impl TabLayout {
}
}
+/// The layout with divider `idx` moved `cells` (right/down positive):
+/// the panes ending at it along its extent grow, the ones starting past
+/// it shrink, and the move is clamped so each keeps `nav_rows` + 1 rows
+/// (or one column). `cells` is a displacement from `layout`, so zero
+/// (asked, or clamped to) is `layout` itself: a drag back to where it
+/// started has to restore what it started from. `None` for a divider
+/// that is not there or has nothing on one side.
+pub fn with_divider_moved(layout: &TabLayout, idx: usize, cells: isize, nav_rows: usize) -> Option<TabLayout> {
+ let divider = *layout.dividers.get(idx)?;
+ let mut moved = layout.clone();
+ let (before, after): (Vec<usize>, Vec<usize>) = match divider {
+ Divider::Col { col, top, rows } => {
+ let spans = |p: &PanePlacement| p.frame.top < top + rows && p.frame.top + p.frame.rows > top;
+ let b = moved.panes.iter().enumerate().filter(|(_, p)| spans(p) && p.frame.left + p.frame.cols == col).map(|(i, _)| i).collect();
+ let a = moved.panes.iter().enumerate().filter(|(_, p)| spans(p) && p.frame.left == col + 1).map(|(i, _)| i).collect();
+ (b, a)
+ }
+ Divider::Row { row, left, cols } => {
+ let spans = |p: &PanePlacement| p.frame.left < left + cols && p.frame.left + p.frame.cols > left;
+ let b = moved.panes.iter().enumerate().filter(|(_, p)| spans(p) && p.frame.top + p.frame.rows == row).map(|(i, _)| i).collect();
+ let a = moved.panes.iter().enumerate().filter(|(_, p)| spans(p) && p.frame.top == row + 1).map(|(i, _)| i).collect();
+ (b, a)
+ }
+ };
+ if before.is_empty() || after.is_empty() {
+ return None;
+ }
+ let horizontal = matches!(divider, Divider::Col { .. });
+ let min = if horizontal { 1 } else { nav_rows + 1 };
+ let extent = |p: &PanePlacement| if horizontal { p.frame.cols } else { p.frame.rows } as isize;
+ // Room to shrink on whichever side loses cells.
+ let room = |side: &[usize]| side.iter().map(|&i| extent(&moved.panes[i]) - min as isize).min().unwrap_or(0).max(0);
+ let cells = if cells > 0 { cells.min(room(&after)) } else { cells.max(-room(&before)) };
+ if cells == 0 {
+ return Some(moved);
+ }
+ for &i in &before {
+ let f = &mut moved.panes[i].frame;
+ if horizontal { f.cols = (f.cols as isize + cells) as usize } else { f.rows = (f.rows as isize + cells) as usize }
+ }
+ for &i in &after {
+ let f = &mut moved.panes[i].frame;
+ if horizontal {
+ f.left = (f.left as isize + cells) as usize;
+ f.cols = (f.cols as isize - cells) as usize;
+ } else {
+ f.top = (f.top as isize + cells) as usize;
+ f.rows = (f.rows as isize - cells) as usize;
+ }
+ }
+ match &mut moved.dividers[idx] {
+ Divider::Col { col, .. } => *col = (*col as isize + cells) as usize,
+ Divider::Row { row, .. } => *row = (*row as isize + cells) as usize,
+ }
+ Some(moved)
+}
+
+/// The layout with every frame scaled to `size`'s grid, the dividers
+/// kept to one cell: pane edges next to a divider are put at the
+/// divider's new place, so the frames still compose to the grid as the
+/// server requires. Near enough to claim pane by pane. `None` when a
+/// pane would be left without a cell: padding one out would break the
+/// composition, and the server would refuse the lot.
+pub fn scaled(layout: &TabLayout, size: TerminalSize) -> Option<TabLayout> {
+ let (cols, rows) = (size.cols, size.rows);
+ let sx = |c: usize| (c * cols + layout.cols / 2) / layout.cols;
+ let sy = |r: usize| (r * rows + layout.rows / 2) / layout.rows;
+ let mut scaled = layout.clone();
+ scaled.cols = cols;
+ scaled.rows = rows;
+ scaled.size = size;
+ for p in scaled.panes.iter_mut() {
+ let old = p.frame;
+ let (mut l, mut t) = (sx(old.left), sy(old.top));
+ let (mut r, mut b) = (sx(old.left + old.cols), sy(old.top + old.rows));
+ // Edges on a divider follow it: the gap stays one cell.
+ for d in &layout.dividers {
+ match *d {
+ Divider::Col { col, top, rows: n } if old.top < top + n && old.top + old.rows > top => {
+ if old.left + old.cols == col {
+ r = sx(col);
+ }
+ if old.left == col + 1 {
+ l = sx(col) + 1;
+ }
+ }
+ Divider::Row { row, left, cols: n } if old.left < left + n && old.left + old.cols > left => {
+ if old.top + old.rows == row {
+ b = sy(row);
+ }
+ if old.top == row + 1 {
+ t = sy(row) + 1;
+ }
+ }
+ _ => {}
+ }
+ }
+ if r <= l || b <= t {
+ return None;
+ }
+ p.frame = Rect { left: l, top: t, cols: r - l, rows: b - t };
+ }
+ for d in scaled.dividers.iter_mut() {
+ match d {
+ Divider::Col { col, top, rows: n } => {
+ let (t, b) = (sy(*top), sy(*top + *n));
+ *col = sx(*col);
+ *top = t;
+ *n = b.saturating_sub(t).max(1);
+ }
+ Divider::Row { row, left, cols: n } => {
+ let (l, r) = (sx(*left), sx(*left + *n));
+ *row = sy(*row);
+ *left = l;
+ *n = r.saturating_sub(l).max(1);
+ }
+ }
+ }
+ Some(scaled)
+}
+
/// Every pane in a tab, left to right, top to bottom, stacks included.
pub fn leaves(node: &PaneNode) -> Vec<&PaneEntry> {
match node {
@@ -232,16 +353,24 @@ pub fn layout(node: &PaneNode) -> Option<TabLayout> {
/// size of the pane would shrink the pane by the bar's rows each time.
pub fn layout_in(node: &PaneNode, tab_size: Option<TerminalSize>, nav_rows: usize) -> Option<TabLayout> {
let listed = node.root_size()?;
- let size = match node {
- PaneNode::Split { .. } => listed,
- _ => tab_size.unwrap_or_else(|| {
- let rows = listed.rows + nav_rows;
+ let framed = |grid: TerminalSize| {
+ tab_size.unwrap_or_else(|| {
+ let rows = grid.rows + nav_rows;
TerminalSize {
rows,
- pixel_height: listed.pixel_height.checked_div(listed.rows).unwrap_or(0) * rows,
- ..listed
+ pixel_height: grid.pixel_height.checked_div(grid.rows).unwrap_or(0) * rows,
+ ..grid
}
- }),
+ })
+ };
+ // A zoomed pane's own size is the tab's: the split tree it hides is
+ // not resized while it is zoomed, so the root the server lists is
+ // wherever the tab stood at the zoom.
+ let zoomed_grid = leaves(node).into_iter().find(|e| e.is_zoomed_pane).map(|e| e.size);
+ let size = match (node, zoomed_grid) {
+ (PaneNode::Split { .. }, None) => listed,
+ (_, Some(grid)) => framed(grid),
+ _ => framed(listed),
};
let (window_id, tab_id) = node.window_and_tab_ids()?;
let root = Rect {
@@ -295,6 +424,35 @@ pub fn hit(layout: &TabLayout, col: usize, row: usize) -> Option<&PanePlacement>
#[cfg(test)]
mod tests {
+ #[test]
+ fn moving_a_divider_shifts_the_panes_on_both_sides_within_bounds() {
+ let place = |id: usize, top: usize, rows: usize| PanePlacement {
+ pane_id: id, tab_id: 1, window_id: 1,
+ frame: Rect { left: 0, top, cols: 80, rows },
+ content: (80, rows.saturating_sub(2)), is_active: id == 1, is_zoomed: false,
+ title: String::new(), alt_screen: false, physical_top: 0,
+ size: TerminalSize { rows: rows.saturating_sub(2), cols: 80, pixel_width: 800, pixel_height: 0, dpi: 96 },
+ workspace: "w".into(), stack: vec![],
+ };
+ let layout = TabLayout {
+ tab_id: 1, window_id: 1, workspace: "w".into(), cols: 80, rows: 41,
+ size: TerminalSize { rows: 41, cols: 80, pixel_width: 800, pixel_height: 820, dpi: 96 },
+ panes: vec![place(1, 0, 20), place(2, 21, 20)],
+ dividers: vec![Divider::Row { row: 20, left: 0, cols: 80 }],
+ zoomed: None, hidden: vec![],
+ };
+ let moved = with_divider_moved(&layout, 0, 5, 2).unwrap();
+ assert_eq!((moved.panes[0].frame.rows, moved.panes[1].frame.top, moved.panes[1].frame.rows), (25, 26, 15));
+ assert!(matches!(moved.dividers[0], Divider::Row { row: 25, .. }));
+ // Clamped: the lower pane keeps its bar and one row.
+ let moved = with_divider_moved(&layout, 0, 30, 2).unwrap();
+ assert_eq!(moved.panes[1].frame.rows, 3);
+ // Back at the origin, or pushed against the clamp from the other
+ // side: the starting layout, not nothing.
+ assert_eq!(with_divider_moved(&layout, 0, 0, 2).unwrap(), layout);
+ assert_eq!(with_divider_moved(&layout, 0, -40, 2).unwrap().panes[0].frame.rows, 3);
+ assert!(with_divider_moved(&layout, 1, 3, 2).is_none());
+ }
use super::*;
use thinkterm_proto::layout::PaneStackEntry;
use thinkterm_proto::split::SplitDirectionAndSize;
@@ -490,6 +648,56 @@ mod tests {
assert_eq!(l.hidden, vec![1]);
}
+ /// The server's tree keeps the pre-zoom sizes while a pane is zoomed;
+ /// the zoomed pane's own size, resized since, is the tab's.
+ #[test]
+ fn a_zoomed_pane_resized_since_the_zoom_sizes_the_tab() {
+ let mut zoomed = pane(2, 165, 22, 41, 0, true);
+ zoomed.is_zoomed_pane = true;
+ let node = split(
+ SplitDirection::Horizontal,
+ size(70, 36),
+ size(39, 36),
+ PaneNode::Leaf(pane(1, 70, 36, 0, 0, false)),
+ PaneNode::Leaf(zoomed),
+ );
+ let l = layout_in(&node, None, 3).unwrap();
+ assert_eq!((l.cols, l.rows), (165, 25));
+ assert_eq!(l.panes[0].frame, Rect { left: 0, top: 0, cols: 165, rows: 25 });
+ // With the server's word for the tab, that.
+ let l = layout_in(&node, Some(size(165, 25)), 3).unwrap();
+ assert_eq!((l.cols, l.rows), (165, 25));
+ }
+
+ /// Doubling an 80-column tab split 40 | 39 gives 80 | 79 with the
+ /// divider still one cell, not 80 | 78 with a two-cell gap the
+ /// server would refuse.
+ #[test]
+ fn scaling_keeps_dividers_one_cell_wide() {
+ let mut zoomed = pane(2, 39, 24, 41, 0, true);
+ zoomed.is_zoomed_pane = false;
+ let node = split(
+ SplitDirection::Horizontal,
+ size(40, 24),
+ size(39, 24),
+ PaneNode::Leaf(pane(1, 40, 24, 0, 0, false)),
+ PaneNode::Leaf(zoomed),
+ );
+ let l = layout(&node).unwrap();
+ let big = scaled(&l, size(160, 24)).unwrap();
+ let frames: Vec<(usize, usize)> = big.panes.iter().map(|p| (p.frame.left, p.frame.cols)).collect();
+ assert_eq!(frames, vec![(0, 80), (81, 79)]);
+ assert!(matches!(big.dividers[0], Divider::Col { col: 80, .. }));
+ // And back down, still composing.
+ let small = scaled(&big, size(60, 24)).unwrap();
+ let frames: Vec<(usize, usize)> = small.panes.iter().map(|p| (p.frame.left, p.frame.cols)).collect();
+ assert_eq!(frames[0].0 + frames[0].1 + 1, frames[1].0);
+ assert_eq!(frames[1].0 + frames[1].1, 60);
+ // A one-column pane has nowhere to go at 3 columns: no layout,
+ // rather than one a column too wide.
+ assert!(scaled(&l, size(3, 24)).is_none());
+ }
+
#[test]
fn content_can_be_smaller_than_the_frame() {
// The desktop reserves a nav bar row: the pane's grid is 23 rows in
diff --git a/thinkterm-web/src/lease.rs b/thinkterm-web/src/lease.rs
index 8f5949df..ad3c6107 100644
--- a/thinkterm-web/src/lease.rs
+++ b/thinkterm-web/src/lease.rs
@@ -128,7 +128,9 @@ impl Lease {
/// pane keeps the rows above it for its bar -- and as a bare grid
/// otherwise (the size just changed; the next listing catches up).
pub fn claim_viewport(&self) -> Option<codec::ClientViewport> {
- let size = if self.fit || (self.ownerless() && self.canonical_size.is_none()) {
+ // The holder shapes the tab to its own grid: this page while it
+ // owns the tab, whatever `fit` says (a push can clear it mid-claim).
+ let size = if self.fit || self.owns_viewport() || (self.ownerless() && self.canonical_size.is_none()) {
self.reported.or(self.canonical_size)?
} else {
self.canonical_size.or(self.reported)?
@@ -276,10 +278,11 @@ mod claim_tests {
}
#[test]
- fn a_tab_this_page_holds_keeps_the_size_it_was_claimed_at() {
+ fn a_tab_this_page_holds_takes_the_page_s_own_grid() {
let mut l = lease(codec::FrontendAccessMode::TmuxLatest);
l.tab_owner = Some(id(1));
- assert_eq!(grid(&l), Some(size(120, 40)));
+ // The holder shapes the tab, whether or not a push cleared `fit`.
+ assert_eq!(grid(&l), Some(size(96, 30)));
}
#[test]
diff --git a/thinkterm-web/src/navbar.rs b/thinkterm-web/src/navbar.rs
index 8e382f7a..a78db93b 100644
--- a/thinkterm-web/src/navbar.rs
+++ b/thinkterm-web/src/navbar.rs
@@ -78,7 +78,9 @@ pub fn rects(
};
// A pane on the tab's top row starts at the window's edge,
// over the padding, like one at its left edge.
- let top = if p.frame.top == 0 { 0.0 } else { pad_css.1 + p.frame.top as f64 * ch };
+ // Below a divider the bar starts right under the line, which
+ // sits in the middle of the gap row, as the desktop's does.
+ let top = if p.frame.top == 0 { 0.0 } else { pad_css.1 + p.frame.top as f64 * ch - ch / 2.0 + 1.0 };
NavRect {
pane_id: p.pane_id,
left,
diff --git a/thinkterm-web/src/settings.rs b/thinkterm-web/src/settings.rs
index 00c586d5..2144e9ec 100644
--- a/thinkterm-web/src/settings.rs
+++ b/thinkterm-web/src/settings.rs
@@ -4,6 +4,34 @@
use serde::{Deserialize, Serialize};
+/// The `terminal-scheme` value that means "whatever the server is set to".
+pub const FOLLOW_DESKTOP: &str = "desktop";
+
+/// The base palette every pane draws from: this browser's pick, else the
+/// server's configured scheme, else the stock palette.
+pub fn configured_palette(
+ chosen: Option<&wezterm_term::color::ColorPalette>,
+ server: Option<&wezterm_term::color::ColorPalette>,
+) -> wezterm_term::color::ColorPalette {
+ chosen.or(server).cloned().unwrap_or_default()
+}
+
+/// What a pane should draw now, given the base palette and the pane's own
+/// application override; `None` when nothing moved.
+pub fn recomputed_palette(
+ current: &wezterm_term::color::ColorPalette,
+ configured: &wezterm_term::color::ColorPalette,
+ application: Option<&wezterm_term::color::ColorPalette>,
+) -> Option<wezterm_term::color::ColorPalette> {
+ let transition = thinkterm_session::decide::application_palette_transition(
+ current,
+ configured,
+ application.is_some(),
+ application.cloned(),
+ );
+ transition.palette_changed.then_some(transition.palette)
+}
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct WebSettings {
@@ -15,6 +43,55 @@ pub struct WebSettings {
pub agents_panel: bool,
pub palette_hotkey: Hotkey,
pub sidebar_width: f64,
+ /// `"desktop"` follows the server's configured scheme; anything else
+ /// names a scheme this browser picked.
+ pub terminal_scheme: String,
+}
+
+/// A colour scheme as the page hands it over, straight out of
+/// `schemes.json`: every colour a CSS hex string.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct SchemeColors {
+ pub foreground: String,
+ pub background: String,
+ pub cursor_bg: String,
+ pub cursor_fg: String,
+ pub cursor_border: String,
+ pub selection_bg: String,
+ pub selection_fg: String,
+ pub ansi: [String; 8],
+ pub brights: [String; 8],
+}
+
+impl SchemeColors {
+ pub fn parse(json: &str) -> Result<Self, String> {
+ serde_json::from_str(json).map_err(|e| e.to_string())
+ }
+
+ /// The scheme as a palette to draw with. Every other entry (the indexed
+ /// colours, the split line) keeps the stock value.
+ pub fn to_palette(&self) -> Result<wezterm_term::color::ColorPalette, String> {
+ use std::str::FromStr;
+ use wezterm_term::color::SrgbaTuple;
+ fn colour(s: &str) -> Result<SrgbaTuple, String> {
+ SrgbaTuple::from_str(s).map_err(|_| format!("not a colour: {s:?}"))
+ }
+ let mut p = wezterm_term::color::ColorPalette::default();
+ p.foreground = colour(&self.foreground)?.into();
+ p.background = colour(&self.background)?.into();
+ p.cursor_bg = colour(&self.cursor_bg)?.into();
+ p.cursor_fg = colour(&self.cursor_fg)?.into();
+ p.cursor_border = colour(&self.cursor_border)?.into();
+ p.selection_bg = colour(&self.selection_bg)?.into();
+ p.selection_fg = colour(&self.selection_fg)?.into();
+ for (idx, hex) in self.ansi.iter().enumerate() {
+ p.colors.0[idx] = colour(hex)?.into();
+ }
+ for (idx, hex) in self.brights.iter().enumerate() {
+ p.colors.0[idx + 8] = colour(hex)?.into();
+ }
+ Ok(p)
+ }
}
impl Default for WebSettings {
@@ -27,6 +104,7 @@ impl Default for WebSettings {
agents_panel: false,
palette_hotkey: Hotkey::CmdK,
sidebar_width: 220.0,
+ terminal_scheme: FOLLOW_DESKTOP.to_string(),
}
}
}
@@ -78,6 +156,55 @@ impl WebSettings {
mod tests {
use super::*;
+ fn tinted(v: f32) -> wezterm_term::color::ColorPalette {
+ let mut p = wezterm_term::color::ColorPalette::default();
+ p.background = (v, v, v, 1.0).into();
+ p
+ }
+
+ #[test]
+ fn the_browsers_pick_outranks_the_servers_scheme() {
+ let chosen = tinted(0.25);
+ let server = tinted(0.5);
+ assert_eq!(configured_palette(Some(&chosen), Some(&server)), chosen);
+ assert_eq!(configured_palette(None, Some(&server)), server);
+ assert_eq!(
+ configured_palette(None, None),
+ wezterm_term::color::ColorPalette::default()
+ );
+ }
+
+ #[test]
+ fn an_application_override_outranks_the_base_and_survives_a_base_change() {
+ let base = tinted(0.5);
+ let app = tinted(0.75);
+ let current = wezterm_term::color::ColorPalette::default();
+ // No override: the base shows through, once.
+ assert_eq!(recomputed_palette(&current, &base, None), Some(base.clone()));
+ assert_eq!(recomputed_palette(&base, &base, None), None);
+ // With one, the base is invisible: changing it moves nothing.
+ assert_eq!(recomputed_palette(&base, &base, Some(&app)), Some(app.clone()));
+ assert_eq!(recomputed_palette(&app, &tinted(0.1), Some(&app)), None);
+ // Cleared, the (new) base comes back.
+ let other = tinted(0.1);
+ assert_eq!(recomputed_palette(&app, &other, None), Some(other));
+ }
+
+ #[test]
+ fn scheme_colours_parse_into_a_palette() {
+ let json = r##"{"foreground":"#f8f8f2","background":"#282a36",
+ "cursor_bg":"#f8f8f2","cursor_fg":"#282a36","cursor_border":"#f8f8f2",
+ "selection_bg":"#44475a","selection_fg":"#f8f8f2",
+ "ansi":["#000000","#ff5555","#50fa7b","#f1fa8c","#bd93f9","#ff79c6","#8be9fd","#bfbfbf"],
+ "brights":["#4d4d4d","#ff6e67","#5af78e","#f4f99d","#caa9fa","#ff92d0","#9aedfe","#e6e6e6"]}"##;
+ let palette = SchemeColors::parse(json).unwrap().to_palette().unwrap();
+ assert_eq!(palette.background.to_rgb_string(), "#282a36");
+ assert_eq!(palette.colors.0[1].to_rgb_string(), "#ff5555");
+ assert_eq!(palette.colors.0[15].to_rgb_string(), "#e6e6e6");
+ let bad = SchemeColors::parse(&json.replace("#282a36", "not-a-colour")).unwrap();
+ assert!(bad.to_palette().is_err());
+ }
+
#[test]
fn missing_fields_take_defaults_and_keys_are_checked() {
let s = WebSettings::parse(r#"{"theme":"light","font":{"mode":"pinned","pt":14}}"#).unwrap();
@@ -89,6 +216,8 @@ mod tests {
s.set("language", "\"de-DE\"").unwrap();
s.set("palette-hotkey", "\"ctrl-shift-p\"").unwrap();
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!(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/sidebar.rs b/thinkterm-web/src/sidebar.rs
index 2ec7f8f0..f7a3015b 100644
--- a/thinkterm-web/src/sidebar.rs
+++ b/thinkterm-web/src/sidebar.rs
@@ -33,6 +33,48 @@ pub enum SideClick {
SpaceMenu,
}
+/// The hover reveal's rules, held here rather than in the display layer:
+/// a native shell reads them from the same JSON. Lengths are CSS pixels
+/// (the desktop's design pixels are a 2x grid).
+#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize)]
+pub struct Reveal {
+ /// How far into the window the left-edge trigger reaches
+ /// (`SIDEBAR_HOVER_HOT_ZONE_WIDTH` 12 design px).
+ pub edge: f64,
+ /// How long the pointer rests there before the panel comes back.
+ pub dwell_ms: u32,
+ /// How long a departed pointer has to come back before it leaves.
+ pub retreat_ms: u32,
+}
+
+/// The desktop dwells 180ms and waits 400ms (`SIDEBAR_HOVER_DWELL_MS`,
+/// `SIDEBAR_HOVER_GRACE_MS`); a pointer over a page is quicker to place,
+/// so the reveal is quicker in both directions.
+pub const REVEAL: Reveal = Reveal { edge: 6.0, dwell_ms: 150, retreat_ms: 250 };
+
+/// One action in the panel's footer. `label` is drawn beside the icon
+/// while the panel is wide enough for it; `min_label_width` is that width.
+#[derive(Debug, Clone, PartialEq, serde::Serialize)]
+pub struct FooterAction {
+ /// What a press means, as `SideClick`/the page's own panels read it.
+ pub id: String,
+ /// A lucide name, as the menus name theirs.
+ pub icon: String,
+ pub label: Option<String>,
+ pub tip: String,
+ /// Off for what the desktop has and the browser has not; the tip says
+ /// so, and a press does nothing.
+ pub enabled: bool,
+ /// The desktop keeps its settings row at the left inset and its other
+ /// actions against the right one.
+ pub trailing: bool,
+}
+
+/// Below this the label cannot sit beside the gear and the trailing
+/// actions, and the footer shows the gear alone -- what `sidebar.rs`'s
+/// `settings_label_fits` decides on the desktop.
+pub const FOOTER_LABEL_MIN_WIDTH: f64 = 168.0;
+
pub const MIN_WIDTH: f64 = 127.0;
pub const MAX_WIDTH: f64 = 260.0;
pub const DEFAULT_WIDTH: f64 = 220.0;
diff --git a/thinkterm-web/src/tree.rs b/thinkterm-web/src/tree.rs
index ac8c8e0e..0fcc08de 100644
--- a/thinkterm-web/src/tree.rs
+++ b/thinkterm-web/src/tree.rs
@@ -467,6 +467,10 @@ pub enum Expect {
SpaceExists(String),
SpaceNamed(String, String),
SpaceGone(String),
+ /// The unpinned threads of a project, in order.
+ ThreadOrder(String, Vec<String>),
+ /// The projects of a Space, in order.
+ ProjectOrder(String, Vec<String>),
}
impl Expect {
@@ -513,6 +517,27 @@ impl Expect {
Some(_) => Err("the server did not change the unread mark".into()),
None => Err("the thread is gone".into()),
},
+ Expect::ThreadOrder(project_id, order) => match project(project_id) {
+ Some(p) => {
+ let now: Vec<&str> = p.threads.iter().filter(|t| !t.is_pinned).map(|t| t.id.as_str()).collect();
+ (now == order.iter().map(String::as_str).collect::<Vec<_>>())
+ .then_some(())
+ .ok_or_else(|| "the server did not move the thread".into())
+ }
+ None => Err("the project is gone".into()),
+ },
+ Expect::ProjectOrder(space_id, order) => {
+ // Archived projects are not in the session view the
+ // wanted order was built from; they hold no place in it.
+ let now: Vec<&str> = tree
+ .projects_in_space(space_id)
+ .filter(|p| p.archived_at.is_none())
+ .map(|p| p.id.as_str())
+ .collect();
+ (now == order.iter().map(String::as_str).collect::<Vec<_>>())
+ .then_some(())
+ .ok_or_else(|| "the server did not move the project".into())
+ }
Expect::ProjectGone(id) => match project(id) {
None => Ok(()),
Some(_) => Err("the server did not remove the project".into()),
@@ -594,6 +619,37 @@ pub fn rename_thread(id: &str, name: &str, now: i64) -> Intent {
}
}
+/// Put an unpinned thread before `before` (None: last) among its
+/// project's unpinned threads; `order` is that list as it stands.
+pub fn move_thread_before(project_id: &str, id: &str, before: Option<&str>, order: &[String]) -> Intent {
+ let mut want: Vec<String> = order.iter().filter(|t| t.as_str() != id).cloned().collect();
+ let at = before.and_then(|b| want.iter().position(|t| t == b)).unwrap_or(want.len());
+ want.insert(at, id.to_string());
+ Intent {
+ ops: vec![TreeOp::MoveThreadBefore {
+ project_id: project_id.to_string(),
+ thread_id: id.to_string(),
+ before: before.map(str::to_string),
+ }],
+ expect: Expect::ThreadOrder(project_id.to_string(), want),
+ }
+}
+
+/// Put a project before `before` (None: last) among its Space's projects.
+pub fn move_project_before(space_id: &str, id: &str, before: Option<&str>, order: &[String]) -> Intent {
+ let mut want: Vec<String> = order.iter().filter(|p| p.as_str() != id).cloned().collect();
+ let at = before.and_then(|b| want.iter().position(|p| p == b)).unwrap_or(want.len());
+ want.insert(at, id.to_string());
+ Intent {
+ ops: vec![TreeOp::MoveProjectBefore {
+ space_id: space_id.to_string(),
+ project_id: id.to_string(),
+ before: before.map(str::to_string),
+ }],
+ expect: Expect::ProjectOrder(space_id.to_string(), want),
+ }
+}
+
pub fn rename_project(id: &str, name: &str) -> Intent {
Intent {
ops: vec![TreeOp::RenameProject { project_id: id.to_string(), name: name.to_string() }],
@@ -687,6 +743,33 @@ mod tests {
assert!(new_id("thread", || 0xabcd).starts_with("thread-0000abcd"));
}
+ #[test]
+ fn reorder_intents_expect_the_order_they_asked_for() {
+ let mut tree = ThinkTermTree::default();
+ for op in create_project(None, "p1".into(), "t1".into(), "~/a", 1).ops {
+ assert!(codec::apply_op(&mut tree, &op));
+ }
+ for id in ["t2", "t3"] {
+ assert!(codec::apply_op(&mut tree, &TreeOp::CreateThread {
+ thread_id: id.into(), project_id: "p1".into(), name: id.into(), workspace: None, created_at: 2,
+ }));
+ }
+ let order = ["t1", "t2", "t3"].map(String::from);
+ let intent = move_thread_before("p1", "t3", Some("t1"), &order);
+ assert!(codec::apply_op(&mut tree, &intent.ops[0]));
+ assert!(intent.expect.check(&tree).is_ok());
+ assert_eq!(intent.expect, Expect::ThreadOrder("p1".into(), ["t3", "t1", "t2"].map(String::from).to_vec()));
+ // A move the server did not apply is a refusal.
+ assert!(move_thread_before("p1", "t2", None, &order).expect.check(&tree).is_err());
+ let space = tree.spaces[0].id.clone();
+ assert!(codec::apply_op(&mut tree, &TreeOp::CreateProject {
+ project_id: "p2".into(), space_id: space.clone(), name: "b".into(), path: "~/b".into(),
+ }));
+ let intent = move_project_before(&space, "p2", Some("p1"), &["p1".to_string(), "p2".to_string()]);
+ assert!(codec::apply_op(&mut tree, &intent.ops[0]));
+ assert!(intent.expect.check(&tree).is_ok());
+ }
+
fn thread(id: &str, ws: Option<&str>, tabs: Vec<(TabId, Vec<PaneId>)>) -> ThinkTermSessionThread {
ThinkTermSessionThread {
id: id.into(),
diff --git a/thinkterm-web/src/views.rs b/thinkterm-web/src/views.rs
index 97c0d992..52af22a8 100644
--- a/thinkterm-web/src/views.rs
+++ b/thinkterm-web/src/views.rs
@@ -5,7 +5,7 @@
use crate::chrome::{Controls, TabView};
use crate::navbar::NavView;
-use crate::sidebar::Editing;
+use crate::sidebar::{Editing, FooterAction, Reveal};
use crate::tree::Row;
use serde::Serialize;
@@ -15,6 +15,15 @@ pub struct SidebarView {
pub editing: Editing,
/// The Space on show, for the page to remember.
pub space: Option<String>,
+ /// Why the last "add workspace" path was refused, shown next to the
+ /// field it was typed into rather than as a passing remark.
+ pub new_project_error: Option<String>,
+ /// What a hover over the window's left edge does with the panel put
+ /// away, and the footer the panel ends with. Rules, not drawing: a
+ /// native shell reads the same values.
+ pub reveal: Reveal,
+ pub footer: Vec<FooterAction>,
+ pub footer_label_min_width: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
@@ -66,6 +75,11 @@ pub struct Toast {
pub struct Card {
pub title: String,
pub hint: String,
+ /// `busy` (another device holds it), `free` (nobody does), `taking`
+ /// (this page asked), `refused` (the server kept it there).
+ pub state: &'static str,
+ /// The button's words; a press asks for the terminal.
+ pub action: String,
}
/// The static labels the page draws itself (tooltips, headers, the
@@ -76,6 +90,8 @@ pub const STRING_KEYS: &[&str] = &[
"sidebar-workspaces",
"web-sidebar-other-windows",
"web-path-placeholder",
+ "web-add-workspace",
+ "web-add-workspace-hint",
"web-tip-space",
"web-tip-new-thread",
"web-tip-new-thread-here",
@@ -95,17 +111,12 @@ pub const STRING_KEYS: &[&str] = &[
"web-tip-zoom",
"web-tip-unzoom",
"web-tip-sidebar",
- "web-fitted",
- "web-tip-fitted",
"web-tip-sidebar-options",
"tooltip-sidebar-notifications",
- "tooltip-sidebar-thread-search",
- "tooltip-sidebar-settings",
"web-tip-search",
"web-tip-agents",
"web-tip-settings",
"web-agents-title",
- "sidebar-settings",
"settings-language",
"web-settings-theme",
"web-theme-dark",
@@ -132,11 +143,18 @@ pub const STRING_KEYS: &[&str] = &[
"web-settings-hotkey-description",
"web-settings-theme-description",
"web-settings-font-description",
+ "web-settings-scheme",
+ "web-settings-scheme-description",
+ "web-scheme-desktop",
+ "web-scheme-search",
+ "web-scheme-preview",
"web-settings-hover-reveal-description",
"web-settings-agents-panel-description",
"web-settings-sidebar-reset-description",
"web-cmd-font-reset",
"common-reset",
+ "web-tip-new-pane",
+ "command-palette-empty",
];
pub fn strings() -> std::collections::BTreeMap<&'static str, String> {
@@ -168,7 +186,16 @@ mod tests {
}),
Row::Window { window_id: 3, title: "Terminal".into(), selected: false },
];
- let v = to_value(SidebarView { rows, editing: Editing::Thread("thread-1".into()), space: Some("space-1".into()) }).unwrap();
+ let v = to_value(SidebarView {
+ rows,
+ editing: Editing::Thread("thread-1".into()),
+ space: Some("space-1".into()),
+ new_project_error: None,
+ reveal: crate::sidebar::REVEAL,
+ footer: vec![],
+ footer_label_min_width: crate::sidebar::FOOTER_LABEL_MIN_WIDTH,
+ })
+ .unwrap();
assert_eq!(v["rows"][0], json!({"kind": "space", "id": "space-1", "name": "Default"}));
assert_eq!(v["space"], "space-1");
assert_eq!(v["rows"][1], json!({"kind": "new-thread"}));
@@ -181,6 +208,9 @@ mod tests {
assert_eq!(v["rows"][3], json!({"kind": "window", "id": 3, "title": "Terminal", "selected": false}));
assert_eq!(v["editing"], json!({"kind": "thread", "id": "thread-1"}));
assert_eq!(to_value(Editing::None).unwrap(), json!({"kind": "none"}));
+ // The rules the display layer reads rather than decides.
+ assert_eq!(v["reveal"], json!({"edge": 6.0, "dwell_ms": 150, "retreat_ms": 250}));
+ assert_eq!(v["footer_label_min_width"], 168.0);
}
#[test]
@@ -188,7 +218,7 @@ mod tests {
for key in STRING_KEYS {
assert!(thinkterm_i18n::has_key(key), "{key}");
}
- assert_eq!(strings()["web-fitted"], "fitted");
+ assert_eq!(strings()["web-tip-sidebar"].is_empty(), false);
}
#[test]
@@ -212,7 +242,7 @@ mod tests {
assert_eq!(v["controls"], json!({"following": true, "fit": false, "closing": 7, "clipped": [80, 24]}));
let s = to_value(StatusView {
toast: Some(Toast { text: "hi".into(), sticky: false, at: 12.5 }),
- card: Some(Card { title: "Terminal is available".into(), hint: "Click or scroll to take control".into() }),
+ card: Some(Card { title: "Terminal is available".into(), hint: "Click or scroll to take control".into(), state: "free", action: "Take control".into() }),
summary: "zsh".into(),
})
.unwrap();