diff --git a/CHANGELOG.md b/CHANGELOG.md index 80f515f7..ea0cd4f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,19 +13,34 @@ and a release's notes are its section. The procedure is in [`docs/RELEASING.md`] own, as the Roleplay layout puts it, had no tab to close it by. The draft is kept, and *Dock the composer* brings it back. +### Changed + +- The mouse wheel and PgUp/PgDn now scroll the output 10 lines at a time, in the window and the terminal alike. F7 ▸ + Scrollback has *lines per wheel notch* and *lines per page key* to change that; 0 page-key lines scrolls a whole page, + as PgUp used to. + ### Fixed +- In the window, scrolled-back or frozen text no longer drops a row when the pane splits. A blank row used to appear + above the history, so the text jumped down as the band opened. +- Dragging a pane's scrollbar in the window no longer opens the scrolled-back band under the pointer. The band used to + appear mid-drag, which moved the scrollbar away from the pointer and redrew the pane on every movement. The pane now + splits when the scrollbar is let go, and the scrollbar stays exactly where it was when it does. +- A pane's scrollbar in the window now runs the whole height of the pane while it is scrolled back. It used to stop at + the scrolled-back band, which was drawn over it, so the bar looked shorter than the pane it scrolls. +- The scrolled-back band in the window is the same height at every text size. It used to be two rows of text tall, so it + was thin with a small font and thick with a large one. +- Reading a few lines back from the newest output no longer jumps further back when a busy pane drops its oldest + lines. A reader closer to the bottom than the lines dropped was moved up by the difference. - Esc in the docked composer goes back to the tab you came from. It used to leave the keyboard on the composer's own pane, so the command line was your character's main window's even when you had been reading Chat. - Closing the docked composer (Ctrl+W or the new button) puts the keyboard focus straight back on the command line, so a paste lands there. - - A character whose name has a space, connected as `"first last"` on a MUSH, gets a session log again. The quotes went into the log's file name, which Windows refuses, so no log was written. World and character names are now made safe for Windows, Linux and macOS before they name a file: quotes and control characters are dropped, `< > : / \ | ? *` become `_`, and a name like `CON` is changed so Windows will take it. A name that needed none of this names the same file as before. - - A world connected with no character (`/connect host`, a `telnet://` link, Browse worlds) can be closed again. Its tab was the client's main window, which only closed once a character was deleted, so ⌃W, ⌃B x and the tab's × did nothing. Closing it now ends that connection. Its world's row in the sidebar reads *no character* and opens it again, diff --git a/CLAUDE.md b/CLAUDE.md index 230b7574..09a0f976 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -687,11 +687,25 @@ fallbacks) for inline images/maps. passed (`TheHistoryIsAVisibleStepOffEveryPaneAndNeverPastTheReadingPlane`, all three themes). The history viewport is wrapped in a grid wearing it (`_scrollHistorySurfaces`, re-coloured in `RefreshPaneFocus`); the tail keeps the pane's plane. Where the host keeps a gutter, `PaintScrollHistoryGutters` paints the blank gutter and - pad-row cells beside it after the frame, and the window's overlay scrollbar runs beside the history alone. - - **The window's band is two rows** (`ScrollBandRows`: 2 under `HostChrome.Tabs`, else 1; the second row is blank band), - published across the gutter with `ScrollBandOverlay.Inset`, so `ScrollBandView` lines its words up with the output - and keeps its button as far from the right edge — the mockup's 40 px band with a real button. Still `rows`, not the - mockup's `lines`: a buffer index is not a viewport row. + pad-row cells beside it after the frame. + - **The window's scrollbar measures a split pane as if it were whole** (`ScrollbarViewportRows`: the track is the pane, + the viewport the rows it had before it split), so the split opening or closing moves the thumb not at all; the history + cannot scroll further down than that before `MeetsTail` closes the split. **A held thumb holds the split** + (`PaneScrollbar.Held`, `HoldScrollbar`, `_scrollbarHeld`): while the window's thumb is dragged `SyncScrollSplit` opens + and closes nothing, and catches up on release. A split opened mid-drag rebuilt the pane under the pointer and moved + the track (reported). + **The bars are drawn over the native views** (`ScrollbarLayer`, in `DesktopLayer` above the pane views; `TerminalView` + draws them itself only with no layer), so the band does not hide the track's foot, and the band's button keeps clear of + the bar's press zone (`ScrollBandView.ClearRight`, from `TerminalView.ScrollbarZones`). Once a split's history viewport + is arranged its height is read live (`SplitHistoryRows`), so a resize while split keeps the bar and `MeetsTail` agreed. + - **The window's band is 40 px at every text size** (`ScrollBandView.BandHeight`): the client gives it whole rows + (`ScrollBandRows` reads `IPointerPresenter.ScrollBandRows`, the window's `ScrollBandView.RowsFor(cell, interface + scale)`; 2 where nothing measured, 1 in the cells), and the view draws the band at the foot of them with what is left + above in the history's plane, read off the cell over it. Published across the gutter with `ScrollBandOverlay.Inset`, + so `ScrollBandView` lines its words up with the output and keeps its button as far from the right edge. Still `rows`, + not the mockup's `lines`: a buffer index is not a viewport row. + - **The wheel and the page keys move F7's lines** (`TextSettings.WheelLines`/`PageLines`, 10 each; `PageLines` 0 is a + page less two rows of overlap), in both hosts: the window's wheel arrives as notches through the same driver path. - **Inside the pane rectangle, so NAWS never moves**: the band and the tail are rows of the tab's content; `PaneOutputRects` is unchanged (`ScrollingBackSplitsThePane…` pins it). - **A split pane is not "scrolled back" for the workspace** (`SetScrolledBack(…, !AutoScroll && !split)`): diff --git a/src/SharpMUTerm.Avalonia/DesktopLayer.cs b/src/SharpMUTerm.Avalonia/DesktopLayer.cs index 23a9a1c1..74280b0b 100644 --- a/src/SharpMUTerm.Avalonia/DesktopLayer.cs +++ b/src/SharpMUTerm.Avalonia/DesktopLayer.cs @@ -54,6 +54,7 @@ internal sealed partial class DesktopLayer : Canvas private readonly Dictionary _strips = new(StringComparer.Ordinal); private readonly Dictionary _bands = new(StringComparer.Ordinal); private readonly SeamRules _seams = new(); + private readonly ScrollbarLayer _scrollbars; private (SharpMUTerm.Core.Theming.Theme Theme, NativeTokens Tokens)? _paneTokens; private int _noticeAboveRow; @@ -85,6 +86,11 @@ public DesktopLayer(TerminalView view, HostChrome chrome) // The runs of the native views' rules into the divider cells beside them: over the cells, under nothing it touches. Children.Add(_seams); + + // The panes' overlay scrollbars over every native view laid on a pane (a scrolled-back band lies over its foot). + _scrollbars = new ScrollbarLayer(view); + view.ScrollbarLayer = _scrollbars; + Children.Add(_scrollbars); _pointer.StatusChanged += () => Dispatcher.UIThread.Post(Sync); // A dragged tab's hint over the panels; the toasts still over it. @@ -266,6 +272,9 @@ private void SyncCovered() /// The native views' rules carried on to the pane dividers' hairlines beside them. Internal for tests. internal SeamRules Seams => _seams; + /// Where the panes' scrollbars are drawn. Internal for tests. + internal ScrollbarLayer Scrollbars => _scrollbars; + /// /// Runs each full-width rule a native view over a pane draws () on through the half divider /// cell between the view's edge and the divider's hairline (), so a tab @@ -273,6 +282,12 @@ private void SyncCovered() /// private void SyncSeams(Size cell) { + var at = CellOrigin; + SetLeft(_scrollbars, at.X); + SetTop(_scrollbars, at.Y); + _scrollbars.Width = Math.Max(0, _view.Bounds.Width); + _scrollbars.Height = Math.Max(0, _view.Bounds.Height); + SetLeft(_seams, 0); SetTop(_seams, 0); _seams.Width = Math.Max(0, Bounds.Width); @@ -323,9 +338,22 @@ private void SyncPaneChrome(Size cell) } Sync(_bands, bands.Select(b => (b.Model.WindowId, b.Row)), () => new ScrollBandView(), origin, cell); + var frame = _view.Driver.Frame; + var zones = _view.ScrollbarZones(); foreach (var band in bands) { - _bands[band.Model.WindowId].Show(band, tokens, said!.Interactive); + // What of its rows the band leaves is the history's: read the plane off the cell just above it. + var view = _bands[band.Model.WindowId]; + var x = Math.Clamp(band.Row.X, 0, Math.Max(0, frame.Width - 1)); + view.Above = band.Row.Y > 0 && band.Row.Y - 1 < frame.Height && frame.Width > 0 + ? Colour(_view.Renderer.Background(frame[x, band.Row.Y - 1])) + : null; + // The pane's scrollbar runs on under the band, at its right edge: the button keeps clear of where a press is the bar's. + var outerRight = GetLeft(view) + NativeScale.Extent(view).Width; + view.ClearRight = zones.TryGetValue(band.Model.WindowId, out var zone) + ? Math.Max(0, outerRight - (origin.X + zone.Left)) / Math.Max(0.1, NativeScale.Of(view)) + : 0; + view.Show(band, tokens, said!.Interactive); } } diff --git a/src/SharpMUTerm.Avalonia/MainWindow.cs b/src/SharpMUTerm.Avalonia/MainWindow.cs index 0b51ae36..1e175072 100644 --- a/src/SharpMUTerm.Avalonia/MainWindow.cs +++ b/src/SharpMUTerm.Avalonia/MainWindow.cs @@ -128,6 +128,7 @@ public MainWindow(WindowOptions options, IClassicDesktopStyleApplicationLifetime _driver.Settings.Scales = scales; _driver.Floating.Scales = scales; _driver.Pointer.PanelScale = () => scales().Panels; + _driver.Pointer.InterfaceScale = () => scales().Interface; // The edge Avalonia would have drawn round a BorderOnly window on X11, drawn here (DecorationsFor): a hairline, // only while the window is an ordinary window with no frame of its own. diff --git a/src/SharpMUTerm.Avalonia/PaneChromeViews.cs b/src/SharpMUTerm.Avalonia/PaneChromeViews.cs index 5639e42a..497f843f 100644 --- a/src/SharpMUTerm.Avalonia/PaneChromeViews.cs +++ b/src/SharpMUTerm.Avalonia/PaneChromeViews.cs @@ -513,10 +513,47 @@ public IEnumerable EdgeRules(Size size) yield break; } - yield return new EdgeRule(NativeTokens.HorizontalRule(this, 0, 0, size.Width), Tokens.Rule); + var top = BandTop(size.Height); + yield return new EdgeRule(NativeTokens.HorizontalRule(this, top, 0, size.Width), Tokens.Rule); yield return new EdgeRule(NativeTokens.HorizontalRule(this, size.Height - NativeTokens.DevicePixel(this), 0, size.Width), Tokens.Rule); } + /// + /// The band's height in logical pixels: the mockups' 40, at every font size. The client gives it whole rows + /// (); the part of a row it does not need is drawn above it in the history's plane. + /// + internal const double BandHeight = 40; + + /// The rows a band of needs at a cell tall, drawn at . + internal static int RowsFor(double cellHeight, double scale) => + cellHeight <= 0 ? 2 : Math.Max(1, (int)Math.Ceiling((BandHeight * Math.Max(0.1, scale) / cellHeight) - 0.001)); + + /// Where the band begins in a view tall: at its foot, under what of the rows it leaves. + private static double BandTop(double height) => Math.Max(0, Math.Round(height - BandHeight)); + + /// + /// How much of the band's right end, in its own pixels, the pane's scrollbar takes: the button stays left of it, so a + /// press there is the bar's (the band passes every press but the button's on to the cells). + /// + internal double ClearRight + { + get => _clearRight; + set + { + if (Math.Abs(_clearRight - value) > 0.01) + { + _clearRight = value; + Lay(); + InvalidateVisual(); + } + } + } + + private double _clearRight; + + /// The plane the rows above the band are drawn in: the history's, read off the cells above. Internal for tests. + internal Color? Above { get; set; } + private Rect _button; private bool _hover; private bool _pressed; @@ -538,7 +575,7 @@ public ScrollBandView() internal Rect Button => _button; /// The band's words and button: the mockups' 12 px over the output's 13. - private double Size => (double.IsNaN(Height) ? Bounds.Height : Height) >= 20 ? NativeTokens.Caption : NativeTokens.Small; + private double Size => Math.Min(BandHeight, double.IsNaN(Height) ? Bounds.Height : Height) >= 20 ? NativeTokens.Caption : NativeTokens.Small; private string ButtonText => $"{ScrollBandModel.Action} {NativeKeys.Words(ScrollBandModel.ReturnKey)}"; @@ -577,9 +614,11 @@ private void Lay() { var width = double.IsNaN(Width) ? Bounds.Width : Width; var height = double.IsNaN(Height) ? Bounds.Height : Height; + var top = BandTop(height); + var band = height - top; var w = PanelText.Measure(ButtonText, Size, bold: true) + 20; - var h = Math.Max(4, Math.Min(height - 4, 24)); - _button = new Rect(Math.Max(0, width - w - TextInset), Math.Round((height - h) / 2), w, h); + var h = Math.Max(4, Math.Min(band - 4, 24)); + _button = new Rect(Math.Max(0, width - w - Math.Max(TextInset, ClearRight + 4)), top + Math.Round((band - h) / 2), w, h); } public bool HitTest(Point point) => Interactive && _button.Contains(point); @@ -637,15 +676,21 @@ public override void Render(DrawingContext context) return; } - var bounds = new Rect(Bounds.Size); + var top = BandTop(Bounds.Height); + if (top > 0 && Above is { } above) + { + context.FillRectangle(new SolidColorBrush(above), new Rect(0, 0, Bounds.Width, top)); + } + + var bounds = new Rect(0, top, Bounds.Width, Bounds.Height - top); var plane = Tokens.Raised; context.FillRectangle(new SolidColorBrush(plane), bounds); var rule = new SolidColorBrush(Tokens.Rule); - context.FillRectangle(rule, NativeTokens.HorizontalRule(this, 0, 0, bounds.Width)); - context.FillRectangle(rule, NativeTokens.HorizontalRule(this, bounds.Height - NativeTokens.DevicePixel(this), 0, bounds.Width)); + context.FillRectangle(rule, NativeTokens.HorizontalRule(this, top, 0, bounds.Width)); + context.FillRectangle(rule, NativeTokens.HorizontalRule(this, Bounds.Height - NativeTokens.DevicePixel(this), 0, bounds.Width)); var size = Size; - var middle = bounds.Height / 2; + var middle = bounds.Y + (bounds.Height / 2); var x = TextInset; var room = _button.X - 12; x += PanelText.Draw(context, band.Model.Lead(band.Count), x, middle, size, NativeTabStrip.Held(Tokens.Text, plane), true, room - x); diff --git a/src/SharpMUTerm.Avalonia/ScrollbarLayer.cs b/src/SharpMUTerm.Avalonia/ScrollbarLayer.cs new file mode 100644 index 00000000..be350b5b --- /dev/null +++ b/src/SharpMUTerm.Avalonia/ScrollbarLayer.cs @@ -0,0 +1,24 @@ +using Avalonia.Controls; +using Avalonia.Media; + +namespace SharpMUTerm.Avalonia; + +/// +/// The panes' overlay scrollbars, drawn over the native views the window lays on a pane rather than under them. A pane +/// split by scrolling back has a native band over its foot (); drawn in the cells' view, the +/// track stopped at the band, so the bar read as shorter than the pane it scrolls. It lies over the cells at the cells' +/// origin and takes no input: a press on a bar is still 's, which the band lets through. +/// +internal sealed class ScrollbarLayer : Control +{ + private readonly TerminalView _view; + + public ScrollbarLayer(TerminalView view) + { + _view = view; + IsHitTestVisible = false; + Focusable = false; + } + + public override void Render(DrawingContext context) => _view.DrawScrollbars(context); +} diff --git a/src/SharpMUTerm.Avalonia/TerminalView.cs b/src/SharpMUTerm.Avalonia/TerminalView.cs index 9420aadd..a7307cdc 100644 --- a/src/SharpMUTerm.Avalonia/TerminalView.cs +++ b/src/SharpMUTerm.Avalonia/TerminalView.cs @@ -178,7 +178,7 @@ public TerminalView(AvaloniaConsoleDriver driver, SKColor foreground, SKColor ba pointer.ScrollbarsChanged += _ => Dispatcher.UIThread.Post(() => { _bars = pointer.Bars; - InvalidateVisual(); + InvalidateBars(); }); pointer.MenuRequested += (_, items) => Dispatcher.UIThread.Post(() => OpenMenu(items)); pointer.ModelMenuRequested += (_, menu, dispatch) => Dispatcher.UIThread.Post(() => OpenMenu(NativeMenu.Build(menu, dispatch, PlacementMode.Pointer, this))); @@ -363,9 +363,23 @@ public override void Render(DrawingContext context) } DrawHover(context); - DrawScrollbars(context); + if (ScrollbarLayer is { } layer) + { + // Drawn over the native views instead (a band lies over a pane's foot): repaint it with this frame. + Dispatcher.UIThread.Post(layer.InvalidateVisual, DispatcherPriority.Render); + } + else + { + DrawScrollbars(context); + } } + /// + /// Where the scrollbars are drawn when the window lays native views over the cells (): + /// over them, so a pane's native scrolled-back band does not hide the foot of its track. Null draws them here. + /// + internal Control? ScrollbarLayer { get; set; } + /// A bar caret's width in logical units, which the placeholder's plate leaves uncovered. private double CaretWidth => _renderer.CaretThickness / _scale; @@ -696,12 +710,18 @@ protected override void OnPointerMoved(PointerEventArgs e) } } + protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e) + { + base.OnPointerCaptureLost(e); + LetGoOfScrollbar(); + } + protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (_scrollDrag is not null) { - _scrollDrag = null; + LetGoOfScrollbar(); e.Pointer.Capture(null); HoverScrollbar(e.GetPosition(this)); UpdateCursor(e.GetPosition(this)); @@ -886,7 +906,7 @@ protected override void OnPointerExited(PointerEventArgs e) if (_barHovered is not null && _scrollDrag is null) { _barHovered = null; - InvalidateVisual(); + InvalidateBars(); } } @@ -956,9 +976,22 @@ private void OpenMenu(ContextMenu menu) /// The scrollbars are drawn over the pane's right edge rather than in a column of it: a column would make /// the pane narrower in this host than in a terminal, and every connected world is told the pane's width. /// - private const double BarWidth = 4, BarWidthHovered = 8, BarZone = 12, MinimumThumb = 18; + private const double BarWidth = 4, BarWidthHovered = 8, MinimumThumb = 18; + + /// How far in from a pane's right edge a press is its scrollbar's. + internal const double BarZone = 12; - private sealed record ScrollDrag(string WindowId, double Grab); + private sealed record ScrollDrag(string WindowId, double Grab, Action? Held); + + /// Ends a thumb drag and tells the client the thumb is let go, so a split held off while it was dragged catches up. + private void LetGoOfScrollbar() + { + if (_scrollDrag is { } drag) + { + _scrollDrag = null; + drag.Held?.Invoke(false); + } + } /// A bar's track and thumb in logical pixels, or null when the pane has nothing to scroll. /// The windows a native view lies over (): their panes draw no overlay scrollbar. @@ -970,7 +1003,7 @@ internal IReadOnlySet CoveredWindows if (!_covered.SetEquals(value)) { _covered = value; - InvalidateVisual(); + InvalidateBars(); } } } @@ -996,6 +1029,12 @@ internal IReadOnlySet CoveredWindows return (new Rect(right - BarZone, top, BarZone, height), new Rect(right - width - 2, y, width, thumb), travel); } + /// Each drawn bar's press zone (its whole track) by window, in this view's pixels. Internal for tests. + internal IReadOnlyDictionary ScrollbarZones() => + _bars.Select(bar => (bar.WindowId, Geometry: BarGeometry(bar))) + .Where(b => b.Geometry is not null) + .ToDictionary(b => b.WindowId, b => b.Geometry!.Value.Zone, StringComparer.Ordinal); + private PaneScrollbar? BarAt(Point position) => _bars.FirstOrDefault(bar => BarGeometry(bar) is { } g && g.Zone.Contains(position)); @@ -1005,7 +1044,7 @@ private void HoverScrollbar(Point position) if (hovered != _barHovered) { _barHovered = hovered; - InvalidateVisual(); + InvalidateBars(); } } @@ -1018,8 +1057,9 @@ private bool TryGrabScrollbar(PointerPressedEventArgs e, Point position) } var grab = g.Thumb.Top <= position.Y && position.Y < g.Thumb.Bottom ? position.Y - g.Thumb.Top : g.Thumb.Height / 2; - _scrollDrag = new ScrollDrag(bar.WindowId, grab); + _scrollDrag = new ScrollDrag(bar.WindowId, grab, bar.Held); _barHovered = bar.WindowId; + bar.Held?.Invoke(true); e.Pointer.Capture(this); DragScrollbar(_scrollDrag, position.Y); return true; @@ -1037,7 +1077,14 @@ private void DragScrollbar(ScrollDrag drag, double y) bar.ScrollTo((int)Math.Round(fraction * hidden)); } - private void DrawScrollbars(DrawingContext context) + /// Repaints the scrollbars wherever they are drawn. + private void InvalidateBars() + { + InvalidateVisual(); + ScrollbarLayer?.InvalidateVisual(); + } + + internal void DrawScrollbars(DrawingContext context) { var colour = _renderer.DefaultForeground; foreach (var bar in _bars) diff --git a/src/SharpMUTerm.Avalonia/WindowPointer.cs b/src/SharpMUTerm.Avalonia/WindowPointer.cs index 555d2089..febb0e85 100644 --- a/src/SharpMUTerm.Avalonia/WindowPointer.cs +++ b/src/SharpMUTerm.Avalonia/WindowPointer.cs @@ -122,6 +122,15 @@ internal double CellHeightMeasured int? IPointerPresenter.VitalsCardRows(int meters, bool target) => CellsOnly ? null : CellHeightMeasured is > 0 and var cell ? VitalsGauges.CardRows(meters, target, cell, PanelScale()) : null; + /// + /// The Text size page's interface scale the pane chrome is drawn at (the scrolled-back band among it), read when the + /// client asks; 1 until the main window says how to read it. + /// + internal Func InterfaceScale { get; set; } = () => 1; + + int? IPointerPresenter.ScrollBandRows => + CellsOnly ? null : CellHeightMeasured is > 0 and var cell ? ScrollBandView.RowsFor(cell, InterfaceScale()) : null; + public void Scrollbars(IReadOnlyList bars) { Volatile.Write(ref _bars, bars); diff --git a/src/SharpMUTerm.Client/Help/HelpTopics.cs b/src/SharpMUTerm.Client/Help/HelpTopics.cs index 4a4d8eec..21c75081 100644 --- a/src/SharpMUTerm.Client/Help/HelpTopics.cs +++ b/src/SharpMUTerm.Client/Help/HelpTopics.cs @@ -28,8 +28,9 @@ public static IReadOnlyList For(string newline) => "⌃Q quits and says first what a quit would end.", ]), new("reading", "Reading output", "scroll back, search, freeze, join a server's wraps", [ - "Scroll: PgUp/PgDn a page, ⇧↑/⇧↓ a line, the wheel. Scrolled back, the pane splits: history on", - "top, the live tail below. End or ⌃End goes back to live output.", + "Scroll: PgUp/PgDn and the wheel, 10 lines unless F7 ▸ Scrollback says otherwise; ⇧↑/⇧↓ a line.", + "Scrolled back, the pane splits: history on top, the live tail below. End or ⌃End goes back", + "to live output.", "", "Search: ⌃F finds text in what the panes hold. ⌥E reads the query as a pattern, ⌥A widens it", "to every window, ⏎ goes to the line, ⌥G to the next one.", diff --git a/src/SharpMUTerm.Client/Settings/BuiltInSettings.cs b/src/SharpMUTerm.Client/Settings/BuiltInSettings.cs index eedd26d7..99270bd5 100644 --- a/src/SharpMUTerm.Client/Settings/BuiltInSettings.cs +++ b/src/SharpMUTerm.Client/Settings/BuiltInSettings.cs @@ -147,6 +147,12 @@ public static partial class BuiltInSettings c => c.Text.ScrollTail, (c, v) => c.Text.ScrollTail = v ?? ScrollTail.Default), }, + Number("wheel-lines", "lines per wheel notch", 1, TextSettings.MaxWheelLines, ScrollbackGroup, + c => c.Text.WheelLines, (c, v) => c.Text.WheelLines = v, + "how far one notch of the mouse wheel scrolls the output", "mouse scroll speed step"), + Number("page-lines", "lines per page key", 0, TextSettings.MaxPageLines, ScrollbackGroup, + c => c.Text.PageLines, (c, v) => c.Text.PageLines = v, + "how far PgUp and PgDn scroll the output; 0 scrolls a whole page", "pgup pgdn page up down scroll step"), Flag("sound", "game sound", SoundGroup, c => c.Sound.Enabled, (c, v) => c.Sound.Enabled = v, diff --git a/src/SharpMUTerm.Core/Configuration/PreferenceSettings.cs b/src/SharpMUTerm.Core/Configuration/PreferenceSettings.cs index 0d8e0f8e..b0d2a427 100644 --- a/src/SharpMUTerm.Core/Configuration/PreferenceSettings.cs +++ b/src/SharpMUTerm.Core/Configuration/PreferenceSettings.cs @@ -170,6 +170,27 @@ public sealed class TextSettings /// public string ScrollTail { get; set; } = Configuration.ScrollTail.Default; + /// + /// How many lines one notch of the mouse wheel moves a pane's scrollback (F7 ▸ SCROLLBACK, 10 by default). One + /// notch, in both hosts: the window counts a touchpad's fractions into whole notches first. + /// + public int WheelLines { get; set; } = DefaultScrollLines; + + /// + /// How many lines PgUp and PgDn move a pane's scrollback (F7 ▸ SCROLLBACK, 10 by default); 0 is a page, the pane's + /// height less two rows of overlap. + /// + public int PageLines { get; set; } = DefaultScrollLines; + + /// What and start at. + public const int DefaultScrollLines = 10; + + /// The most lines a wheel notch may move. + public const int MaxWheelLines = 100; + + /// The most lines a page key may move. + public const int MaxPageLines = 500; + /// /// Whether a trigger marked alert, or a world's name-and-pages alert, may tell the desktop while the /// player is in another window (F7 ▸ ALERTS, on by default). Nothing alerts until a trigger or a world asks for diff --git a/src/SharpMUTerm.Tui/Pointer/PointerTarget.cs b/src/SharpMUTerm.Tui/Pointer/PointerTarget.cs index 50589abb..2f83b2e2 100644 --- a/src/SharpMUTerm.Tui/Pointer/PointerTarget.cs +++ b/src/SharpMUTerm.Tui/Pointer/PointerTarget.cs @@ -93,8 +93,13 @@ internal sealed record PointerMenuItem(string Label, string? Hint, Action Run, b /// Rows it shows at once. /// Rows hidden above what it shows. /// Scrolls the pane so that many rows are above it; safe to call from any thread. +/// +/// Told true when the host's thumb is picked up and false when it is let go; safe to call from any thread. While it is +/// held the pane neither splits nor closes its split (SharpMUTermApp.ScrollSplit): a layout that changed under a +/// dragged thumb moved the thumb away from the pointer and redrew the pane on every move. +/// internal sealed record PaneScrollbar( - string WindowId, PaneRect Track, int ContentRows, int ViewportRows, int Offset, Action ScrollTo) + string WindowId, PaneRect Track, int ContentRows, int ViewportRows, int Offset, Action ScrollTo, Action? Held = null) { /// Same position, ignoring the callback, which is a fresh closure each time. public bool SameAs(PaneScrollbar other) => @@ -188,6 +193,13 @@ void PaneChrome(PaneChromeOverlay chrome) /// int? VitalsCardRows(int meters, bool target) => null; + /// + /// The rows a split pane's band takes where this host draws the band natively (HostChrome.Tabs): its fixed + /// pixel height rounded up to whole rows, so the band is one height at every font size. Null when the host does not + /// know (no view measured yet, the terminal, the default), and the band takes two rows. Asked on the client's thread. + /// + int? ScrollBandRows => null; + /// /// A notice was said, as it is drawn on the status row. The status row's cells carry it in every host; a host that /// draws notices natively (the window's toasts) shows this over the cells and ignores nothing else. It must never diff --git a/src/SharpMUTerm.Tui/Pointer/SharpMUTermApp.Pointer.cs b/src/SharpMUTerm.Tui/Pointer/SharpMUTermApp.Pointer.cs index d775794b..61e15f2a 100644 --- a/src/SharpMUTerm.Tui/Pointer/SharpMUTermApp.Pointer.cs +++ b/src/SharpMUTerm.Tui/Pointer/SharpMUTermApp.Pointer.cs @@ -858,12 +858,13 @@ private void PublishScrollbars() continue; } - // A pane split by scrolling back scrolls only its history, so its bar runs beside the history alone. - var span = _scrollHistorySurfaces.GetValueOrDefault(windowId) is { } history && BoundsOf(history) is { Height: > 0 } h - ? new PaneRect(rect.X, h.Y, rect.Width, h.Height) - : rect; + // A pane split by scrolling back is measured as if it were whole: the track is the pane and the viewport the + // rows the pane had before it split. The history can scroll no further down than that before the split closes + // (MeetsTail), so the bar maps the same offsets either way, and opening or closing the split under a thumb + // moves the thumb not at all. + var viewport = ScrollbarViewportRows(windowId, panel); bars.Add(new PaneScrollbar( - windowId, span, panel.TotalContentHeight, panel.ViewportHeight, panel.VerticalScrollOffset, + windowId, rect, panel.TotalContentHeight, viewport, panel.VerticalScrollOffset, offset => OnUiThread(() => { if (_paneScrolls.GetValueOrDefault(windowId) is { } live && live.VerticalScrollOffset != offset) @@ -871,7 +872,8 @@ private void PublishScrollbars() live.ScrollVerticalBy(offset - live.VerticalScrollOffset); SyncScrollbackState(windowId); } - }))); + }), + held => OnUiThread(() => HoldScrollbar(windowId, held)))); } if (bars.Count == _scrollbars.Count && bars.Zip(_scrollbars).All(pair => pair.First.SameAs(pair.Second))) diff --git a/src/SharpMUTerm.Tui/SharpMUTermApp.ScrollSplit.cs b/src/SharpMUTerm.Tui/SharpMUTermApp.ScrollSplit.cs index 00e95cbe..19ed5f96 100644 --- a/src/SharpMUTerm.Tui/SharpMUTermApp.ScrollSplit.cs +++ b/src/SharpMUTerm.Tui/SharpMUTermApp.ScrollSplit.cs @@ -52,11 +52,74 @@ internal sealed partial class SharpMUTermApp internal const int TailLines = 64; /// - /// How many rows the band takes: two where the host draws the pane chrome natively (, - /// the window), so its band has the mockup's height with a real button in it; one in the cells. Inside the pane - /// either way, so the pane rectangle — and NAWS — never moves. + /// How many rows the band takes: where the host draws the pane chrome natively (, the + /// window), as many as its band's fixed pixel height needs at the cells' size (), + /// so the band is one height at every font size; two when the host has not measured, one in the cells. Inside the + /// pane either way, so the pane rectangle — and NAWS — never moves. /// - internal int ScrollBandRows => Host.Chrome.Tabs ? 2 : 1; + internal int ScrollBandRows => Host.Chrome.Tabs ? Math.Max(1, _pointer?.ScrollBandRows ?? 2) : 1; + + /// + /// The window whose scrollbar thumb the host is holding, or null. While it is held, + /// leaves the pane as it is: a split that opened under a dragged thumb rebuilt the pane area and moved the thumb's + /// track away from the pointer, and one that closed and opened again as the thumb crossed the tail did so on every + /// move. The split catches up when the thumb is let go (). + /// + private string? _scrollbarHeld; + + /// The host picked a pane's scrollbar thumb up () or let it go. + internal void HoldScrollbar(string windowId, bool held) + { + if (held) + { + _scrollbarHeld = windowId; + return; + } + + if (!string.Equals(_scrollbarHeld, windowId, StringComparison.Ordinal)) + { + return; + } + + _scrollbarHeld = null; + SyncScrollbackState(windowId); + } + + /// + /// The viewport a pane's scrollbar is measured against: the rows it shows, or while split the rows it showed before + /// it split (history, band and tail), so the bar reads the same offsets either way. + /// + private int ScrollbarViewportRows(string windowId, ScrollablePanelControl panel) => + _scrollSplits.TryGetValue(windowId, out var tail) && SplitHistoryRows(windowId, panel) is { } history + ? history + ScrollBandRows + tail + : panel.ViewportHeight; + + /// + /// The height of a split window's history viewport. On the frame that opens a split the viewport still reports + /// the whole pane, so the height recorded at opening stands in for it; once the viewport has been arranged at + /// its split height it is read live, so a resize while split moves the bar and together. + /// Null for a window that is not split. + /// + private int? SplitHistoryRows(string windowId, ScrollablePanelControl live) + { + if (!_scrollSplitHistoryRows.TryGetValue(windowId, out var recorded)) + { + return null; + } + + var arranged = live.ViewportHeight; + if (arranged > 0 && (_scrollSplitSettled.Contains(windowId) || arranged <= recorded)) + { + _scrollSplitSettled.Add(windowId); + _scrollSplitHistoryRows[windowId] = arranged; + return arranged; + } + + return recorded; + } + + /// The split windows whose history viewport has been arranged at its split height at least once. + private readonly HashSet _scrollSplitSettled = new(StringComparer.Ordinal); /// /// The rows a live tail gets in a pane whose viewport is tall, or zero when the @@ -107,6 +170,17 @@ private void SyncScrollSplit(string windowId) && live is not null; var wanted = eligible && !live!.AutoScroll && Scrollable(live); + // A thumb being dragged keeps the pane as it is until it is let go. + if (string.Equals(_scrollbarHeld, windowId, StringComparison.Ordinal) && eligible) + { + if (open) + { + RefreshScrollSplitBar(windowId); + } + + return; + } + // Scrolled down to where the tail begins, the history has nothing left to show that the tail does not, so the // pane goes back to following its output. Waiting for the history's own end made the reader scroll on through // every row the tail was already showing, which read as having to reach the newest line before the rest came. @@ -151,8 +225,8 @@ private void SyncScrollSplit(string windowId) private bool MeetsTail(string windowId, ScrollablePanelControl live) { if (!_scrollSplits.TryGetValue(windowId, out var tail) - || !_scrollSplitHistoryRows.TryGetValue(windowId, out var history) - || live.ViewportHeight <= 0 || live.ViewportHeight > history) + || SplitHistoryRows(windowId, live) is null + || !_scrollSplitSettled.Contains(windowId)) { return false; } @@ -166,6 +240,7 @@ private void CloseScrollSplit(string windowId) { _scrollSplits.Remove(windowId); _scrollSplitHistoryRows.Remove(windowId); + _scrollSplitSettled.Remove(windowId); if (_scrollTails.TryGetValue(windowId, out var tail)) { tail.ClearSelection(); @@ -178,6 +253,7 @@ private void ForgetScrollSplit(string windowId) { _scrollSplits.Remove(windowId); _scrollSplitHistoryRows.Remove(windowId); + _scrollSplitSettled.Remove(windowId); _scrollHistorySurfaces.Remove(windowId); _scrollTails.Remove(windowId); _scrollSplitBars.Remove(windowId); @@ -209,7 +285,7 @@ private IWindowControl BuildScrollSplitContent(string windowId, string title) .WithAlignment(HorizontalAlignment.Stretch) .WithVerticalAlignment(VerticalAlignment.Fill); history.Rows(GridLength.Star(1)).Columns(GridLength.Star(1)); - history.Place(ScrollViewFor(windowId, live), 0, 0, 1, 1); + history.Place(InnerView(ScrollViewFor(windowId, live)), 0, 0, 1, 1); var surface = history.Build(); surface.BackgroundColor = HistoryPlaneColor(windowId); _scrollHistorySurfaces[windowId] = surface; @@ -219,6 +295,22 @@ private IWindowControl BuildScrollSplitContent(string windowId, string title) return grid.Build(); } + /// + /// A window's own viewport placed inside a split (scrolled back or frozen). Outside one it is the tab's content and + /// carries the gutter's top row (); inside one the split's grid is the tab's content + /// and carries that row, so the kept viewport must give it up, or the history starts a row lower than the pane did + /// and the text jumps down as the split opens. + /// + private static ScrollablePanelControl InnerView(ScrollablePanelControl view) + { + if (view.Margin.Top != 0) + { + view.Margin = new Margin(view.Margin.Left, 0, view.Margin.Right, view.Margin.Bottom); + } + + return view; + } + private MarkupControl ScrollTailFor(string windowId) { if (_scrollTails.TryGetValue(windowId, out var existing)) diff --git a/src/SharpMUTerm.Tui/SharpMUTermApp.cs b/src/SharpMUTerm.Tui/SharpMUTermApp.cs index c3145229..78d76bb5 100644 --- a/src/SharpMUTerm.Tui/SharpMUTermApp.cs +++ b/src/SharpMUTerm.Tui/SharpMUTermApp.cs @@ -4042,7 +4042,7 @@ private void AppendWindowLine( /// buffer, split at the freeze point, so the lines above it come off the pinned half and any beyond /// it off the live tail. /// - private List<(ScrollablePanelControl Panel, int Rows)> RowsToKeepReadingPosition( + private List<(ScrollablePanelControl Panel, int Target)> RowsToKeepReadingPosition( string windowId, List buffer, int excess) { var result = new List<(ScrollablePanelControl, int)>(); @@ -4071,7 +4071,10 @@ void Measure(ScrollablePanelControl? panel, int from, int count, MarkupControl? var rows = MeasureRows(buffer, from, panel.ViewportWidth, like, count); if (rows > 0) { - result.Add((panel, rows)); + // Where the viewport is to end up, not how far to move it: the re-feed can clamp the offset against the + // shorter content first, and a move by the trimmed rows from there lands short by the clamp — which is + // every reader within a trim's worth of rows of the live tail. + result.Add((panel, Math.Max(0, panel.VerticalScrollOffset - rows))); } } } @@ -4081,12 +4084,17 @@ void Measure(ScrollablePanelControl? panel, int from, int count, MarkupControl? /// re-pins a following one: a whole-buffer re-feed leaves its offset a frame behind (the same /// pairing makes after an insert). /// - private void KeepReadingPosition(string windowId, List<(ScrollablePanelControl Panel, int Rows)> keep) + private void KeepReadingPosition(string windowId, List<(ScrollablePanelControl Panel, int Target)> keep) { - foreach (var (panel, rows) in keep) + foreach (var (panel, target) in keep) { - // Upwards only, so the clamp against a viewport not yet re-arranged cannot bite. - panel.ScrollVerticalBy(-rows); + // Settle the offset against the content as it now is, then move up to the target. Upwards only, so the + // clamp against a viewport not yet re-arranged cannot bite. + panel.ScrollVerticalBy(0); + if (target < panel.VerticalScrollOffset) + { + panel.ScrollVerticalBy(target - panel.VerticalScrollOffset); + } } if (_paneScrolls.GetValueOrDefault(windowId) is { AutoScroll: true } following) @@ -7210,8 +7218,8 @@ private bool TryScrollKey(KeyPressedEventArgs e) Action? scroll = (key, ctrl, shift) switch { - (ConsoleKey.PageUp, false, _) => panel => panel.ScrollVerticalBy(-PageRows(panel)), - (ConsoleKey.PageDown, false, _) => panel => panel.ScrollVerticalBy(PageRows(panel)), + (ConsoleKey.PageUp, false, _) => panel => panel.ScrollVerticalBy(-PageRows(panel, _config.Text.PageLines)), + (ConsoleKey.PageDown, false, _) => panel => panel.ScrollVerticalBy(PageRows(panel, _config.Text.PageLines)), (ConsoleKey.UpArrow, false, true) => panel => panel.ScrollVerticalBy(-1), (ConsoleKey.DownArrow, false, true) => panel => panel.ScrollVerticalBy(1), @@ -7242,12 +7250,13 @@ private bool TryScrollKey(KeyPressedEventArgs e) } /// - /// Rows one page key moves. Read off the viewport the last frame arranged the panel at — the panel - /// is the only thing that knows how tall its content box came out after the pane's chrome, and the - /// figure it reports is the one it will clamp the scroll against. + /// Rows one page key moves: F7's lines per page key (, 10 by default), + /// or with 0 a page — read off the viewport the last frame arranged the panel at, since the panel is the only + /// thing that knows how tall its content box came out after the pane's chrome, and the figure it reports is the + /// one it will clamp the scroll against. /// - private static int PageRows(ScrollablePanelControl panel) => - Math.Max(1, panel.ViewportHeight - PageOverlapRows); + internal static int PageRows(ScrollablePanelControl panel, int lines) => + lines > 0 ? lines : Math.Max(1, panel.ViewportHeight - PageOverlapRows); /// /// Returns a viewport to the newest line and re-arms auto-scroll, so it stays there as @@ -12398,7 +12407,7 @@ private IWindowControl BuildFrozenContent(string windowId, string title) grid.Rows(GridLength.Star(3), GridLength.Cells(1), GridLength.Star(1)).Columns(GridLength.Star(1)); grid.Place(ScrollViewFor(FrozenRegionKey(windowId), frozen), 0, 0, 1, 1); grid.Place(bar, 1, 0, 1, 1); - grid.Place(ScrollViewFor(windowId, live), 2, 0, 1, 1); + grid.Place(InnerView(ScrollViewFor(windowId, live)), 2, 0, 1, 1); return grid.Build(); } @@ -13679,7 +13688,7 @@ private void RouteDriverMouseEvent(List flags, System.Drawing.Point return; } - if (WheelLines(flags) is { } lines) + if (WheelLines(flags, _config.Text.WheelLines) is { } lines) { OnUiThread(() => ScrollPaneUnderPointer(point, lines)); return; @@ -13695,23 +13704,20 @@ private void RouteDriverMouseEvent(List flags, System.Drawing.Point } /// - /// How many lines a mouse frame asks the scrollback to move, or null when it is not a wheel frame. - /// Three, the customary notch: one line makes a wheel useless on a transcript and a whole page makes - /// it unusable for reading one. + /// How many lines a mouse frame asks the scrollback to move, or null when it is not a wheel frame: F7's + /// lines per wheel notch (, 10 by default), held to at least one. /// - private static int? WheelLines(List flags) + private static int? WheelLines(List flags, int notch) { + notch = Math.Max(1, notch); if (flags.Contains(MouseFlags.WheeledUp)) { - return -WheelNotchRows; + return -notch; } - return flags.Contains(MouseFlags.WheeledDown) ? WheelNotchRows : null; + return flags.Contains(MouseFlags.WheeledDown) ? notch : null; } - /// Lines one wheel notch moves the scrollback. - private const int WheelNotchRows = 3; - /// /// Scrolls whichever pane the pointer is over. /// diff --git a/tests/SharpMUTerm.Avalonia.Tests/ScrollbarLayerTests.cs b/tests/SharpMUTerm.Avalonia.Tests/ScrollbarLayerTests.cs new file mode 100644 index 00000000..02393019 --- /dev/null +++ b/tests/SharpMUTerm.Avalonia.Tests/ScrollbarLayerTests.cs @@ -0,0 +1,76 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Headless; +using Avalonia.Input; +using Avalonia.VisualTree; +using SharpMUTerm.Tui; +using SkiaSharp; +using Window = Avalonia.Controls.Window; + +namespace SharpMUTerm.Avalonia.Tests; + +/// +/// A pane split by scrolling back keeps a scrollbar the whole height of the pane. The track already spans the pane +/// (the client measures a split pane as if it were whole); the window draws the bars over its native views, so the +/// scrolled-back band laid over the pane's foot no longer hides the bottom of it, and a press there is still the bar's. +/// +[NotInParallel] +public class ScrollbarLayerTests +{ + [Test] + public async Task ASplitPanesScrollbarRunsUnderTheBandAndIsDrawnOverIt() + { + (double zoneBottom, double bandTop, double bandBottom, bool layerAbove, bool pressReachesCells) = await TerminalViewTests.Session.Dispatch(() => + { + var driver = new AvaloniaConsoleDriver(120, 34); + var terminal = new TerminalView(driver, SKColors.White, new SKColor(0x1e, 0x1e, 0x24), 10f, null, 1.12f); + var root = new Panel(); + root.Children.Add(terminal); + var layer = new DesktopLayer(terminal, HostChrome.Desktop); + root.Children.Add(layer); + var window = new Window { Content = root, Width = 1400, Height = 900 }; + window.Show(); + var app = new SharpMUTermApp(DemoScene.Build(), WindowHost.Create(driver, clipboard: null) with + { + Capabilities = WindowOptions.Capabilities, + Audio = null, + Presence = null, + Announcer = null, + RunsInline = true, + }); + try + { + app.RenderSnapshot("scrollback-up"); + app.RenderNextFrame(); + DesktopLayerTests.Drain(); + window.UpdateLayout(); + layer.Sync(); + window.UpdateLayout(); + + var (windowId, band) = layer.Bands.Single(b => b.Value.IsVisible); + var zone = terminal.ScrollbarZones()[windowId]; + var origin = layer.CellOrigin; + var top = Canvas.GetTop(band); + var bottom = top + band.Bounds.Height; + var above = layer.Children.IndexOf(layer.Scrollbars) > layer.Children.IndexOf(band) + && ReferenceEquals(terminal.ScrollbarLayer, layer.Scrollbars); + + // A press on the track where the band lies goes to the cells' view, which owns the bar. + var point = new Point(origin.X + zone.Center.X, (top + bottom) / 2); + var reaches = window.InputHitTest(point) is Visual hit + && (ReferenceEquals(hit, terminal) || hit.GetVisualAncestors().Contains(terminal)); + return (ZoneBottom: origin.Y + zone.Bottom, Top: top, Bottom: bottom, Above: above, Reaches: reaches); + } + finally + { + app.DisposeAsync().AsTask().GetAwaiter().GetResult(); + window.Close(); + driver.Dispose(); + } + }, CancellationToken.None); + + await Assert.That(zoneBottom).IsGreaterThanOrEqualTo(bandBottom).Because($"the track runs past the band ({bandTop}..{bandBottom}) to the pane's foot"); + await Assert.That(layerAbove).IsTrue().Because("the bars are drawn over the band, not under it"); + await Assert.That(pressReachesCells).IsTrue(); + } +} diff --git a/tests/SharpMUTerm.Avalonia.Tests/SurfaceParityTests.cs b/tests/SharpMUTerm.Avalonia.Tests/SurfaceParityTests.cs index c83d15bc..301c0961 100644 --- a/tests/SharpMUTerm.Avalonia.Tests/SurfaceParityTests.cs +++ b/tests/SharpMUTerm.Avalonia.Tests/SurfaceParityTests.cs @@ -31,7 +31,8 @@ public class SurfaceParityTests // The focus ring is an adorner drawing one rule round whatever control has the keyboard: it carries no model and says nothing. // FittedText is a TextBlock part the composer's footer is built from: it draws the words its view hands it. // SeamRules carries the declared views' own rules on to a divider's hairline: no model, no input, nothing said. - private static readonly HashSet Infrastructure = [typeof(TerminalView), typeof(DesktopLayer), typeof(MainWindow), typeof(FocusRing), typeof(FittedText), typeof(SeamRules)]; + // ScrollbarLayer is where TerminalView draws its own overlay scrollbars, over the native views: no model, no input. + private static readonly HashSet Infrastructure = [typeof(TerminalView), typeof(DesktopLayer), typeof(MainWindow), typeof(FocusRing), typeof(FittedText), typeof(SeamRules), typeof(ScrollbarLayer)]; private static readonly Assembly Window = typeof(DesktopLayer).Assembly; diff --git a/tests/SharpMUTerm.Avalonia.Tests/TerminalViewTests.cs b/tests/SharpMUTerm.Avalonia.Tests/TerminalViewTests.cs index 999e54a5..17d81c85 100644 --- a/tests/SharpMUTerm.Avalonia.Tests/TerminalViewTests.cs +++ b/tests/SharpMUTerm.Avalonia.Tests/TerminalViewTests.cs @@ -7,6 +7,7 @@ using Window = Avalonia.Controls.Window; using SharpConsoleUI.Drivers; using SkiaSharp; +using SharpMUTerm.Core.Workspaces; using SharpMUTerm.Tui; namespace SharpMUTerm.Avalonia.Tests; @@ -244,13 +245,14 @@ public async Task TheClientsMenuOpensAndAnEntryRunsItsAction() [Test] public async Task APanesScrollbarIsPaintedOnItsRightEdgeAndDraggingItScrollsInsteadOfSelecting() { + var held = new List(); var (thumb, empty, scrolledTo, clientSaw) = await Run(window => { var (view, driver) = ((TerminalView, AvaloniaConsoleDriver))window.Tag!; var scrolledTo = new List(); var clientSaw = 0; driver.MouseEvent += (_, _, _) => clientSaw++; - driver.Pointer.Scrollbars([new PaneScrollbar("main", new(0, 0, 10, 4), 40, 4, 0, scrolledTo.Add)]); + driver.Pointer.Scrollbars([new PaneScrollbar("main", new(0, 0, 10, 4), 40, 4, 0, scrolledTo.Add, held.Add)]); Dispatch.Drain(); using var frame = window.CaptureRenderedFrame()!; var cell = view.SizeFor(1, 1); @@ -271,6 +273,46 @@ public async Task APanesScrollbarIsPaintedOnItsRightEdgeAndDraggingItScrollsInst await Assert.That(scrolledTo.Count).IsGreaterThan(0); await Assert.That(scrolledTo[^1]).IsGreaterThan(0); await Assert.That(clientSaw).IsEqualTo(0).Because("a press on the bar is the window's, not a selection"); + await Assert.That(held).IsEquivalentTo(new[] { true, false }, TUnit.Assertions.Enums.CollectionOrdering.Matching) + .Because("the client is told the thumb is held, so the pane does not split under it, and when it is let go"); + } + + /// The band is 40 px at every font size: the rows it is given are that rounded up, and what they leave is above it. + [Test] + [Arguments(20.0, 1.0, 2)] + [Arguments(14.0, 1.0, 3)] + [Arguments(16.0, 1.0, 3)] + [Arguments(30.0, 1.0, 2)] + [Arguments(40.0, 1.0, 1)] + [Arguments(48.0, 1.0, 1)] + [Arguments(20.0, 1.5, 3)] + public async Task TheScrolledBackBandTakesTheRowsItsFixedHeightNeeds(double cell, double scale, int rows) + { + await Assert.That(ScrollBandView.RowsFor(cell, scale)).IsEqualTo(rows); + } + + [Test] + [Arguments(42.0)] + [Arguments(48.0)] + [Arguments(60.0)] + public async Task TheBandIsDrawnAtItsFixedHeightAtTheFootOfItsRows(double rowsHeight) + { + (Rect Button, double[] Rules) drawn = await Session.Dispatch(() => + { + var band = new ScrollBandView { Width = 400, Height = rowsHeight }; + band.Show( + new ScrollBandOverlay(new PaneRect(0, 0, 40, 3), new SharpMUTerm.Client.Chrome.ScrollBandModel("main", 12), "12", _ => { }), + NativeTokens.Dark, + interactive: true); + band.Measure(new Size(400, rowsHeight)); + band.Arrange(new Rect(0, 0, 400, rowsHeight)); + return (band.Button, band.EdgeRules(new Size(400, rowsHeight)).Select(r => r.Rect.Y).ToArray()); + }, CancellationToken.None); + + var top = rowsHeight - ScrollBandView.BandHeight; + var (button, rules) = drawn; + await Assert.That(rules[0]).IsEqualTo(top).Because("the band's top rule is 40 px above its foot, whatever the rows"); + await Assert.That(Math.Abs(button.Center.Y - (top + (ScrollBandView.BandHeight / 2)))).IsLessThanOrEqualTo(1.0); } private static global::Avalonia.Media.Color Pixel(global::Avalonia.Media.Imaging.WriteableBitmap bitmap, double x, double y) diff --git a/tests/SharpMUTerm.Core.Tests/Telnet/TerminalCellQueryTests.cs b/tests/SharpMUTerm.Core.Tests/Telnet/TerminalCellQueryTests.cs index 13939a1e..acbbca41 100644 --- a/tests/SharpMUTerm.Core.Tests/Telnet/TerminalCellQueryTests.cs +++ b/tests/SharpMUTerm.Core.Tests/Telnet/TerminalCellQueryTests.cs @@ -168,7 +168,7 @@ private static async Task DeliverLine(TelnetSession session, ScriptedTransport t try { transport.SendToClient(Encoding.ASCII.GetBytes(text + "\r\n")); - await completion.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await completion.Task.WaitAsync(TimeSpan.FromSeconds(10)); } finally { @@ -176,9 +176,13 @@ private static async Task DeliverLine(TelnetSession session, ScriptedTransport t } } + // A reply is written by the library's read loop, one fragmented byte per read. On a loaded CI runner + // that loop can be starved for seconds while the rest of the suite runs in parallel, so the wait is a + // deadline rather than a count: 2.5 s was once not enough on ubuntu-latest. private static async Task Until(Func predicate) { - for (var i = 0; i < 250 && !predicate(); i++) + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); + while (!predicate() && DateTime.UtcNow < deadline) { await Task.Delay(10); } diff --git a/tests/SharpMUTerm.Tui.Tests/OutputScrollbackTests.cs b/tests/SharpMUTerm.Tui.Tests/OutputScrollbackTests.cs index 6cd15ac5..87caed01 100644 --- a/tests/SharpMUTerm.Tui.Tests/OutputScrollbackTests.cs +++ b/tests/SharpMUTerm.Tui.Tests/OutputScrollbackTests.cs @@ -264,9 +264,9 @@ public async Task PageUpShowsAnEarlierRegionAndPageDownComesBack() await Assert.That(up.CanScrollDown).IsTrue(); await Assert.That(Shows(upRows, SharpMUTermApp.ScrollbackSceneLines)).IsFalse(); - // A page keeps a couple of rows of overlap, so the jump is a page less that. + // F7's lines per page key, ten by default. var moved = bottom.Offset - up.Offset; - await Assert.That(moved).IsEqualTo(up.ViewportRows - 2); + await Assert.That(moved).IsEqualTo(TextSettings.DefaultScrollLines); app.SimulateKey(Chord(ConsoleKey.PageDown)); var back = app.ScrollbackOf(Main)!.Value; @@ -310,11 +310,12 @@ public async Task CtrlHomeReachesTheOldestLine() } /// The demo app with a pane cap small enough for a test to cross it. - private static SharpMUTermApp CappedApp(int paneLines) + private static SharpMUTermApp CappedApp(int paneLines, int? pageLines = null) { Console.SetIn(TextReader.Null); var config = WholePane(); config.PaneLines = paneLines; + if (pageLines is { } lines) config.Text.PageLines = lines; return new SharpMUTermApp(config, Headless, new HeadlessConsoleDriver(Width, Height)); } @@ -358,6 +359,26 @@ public async Task AReaderInTheirScrollbackStaysOnTheSameLinesThroughATrim() await Assert.That(after).IsEquivalentTo(before); } + /// + /// A reader a few rows from the live tail, closer to it than a trim takes: the re-feed clamped the offset against + /// the shorter content before the trimmed rows were taken off it, so they landed that many rows too far up. + /// + [Test] + public async Task AReaderCloseToTheLiveTailStaysOnTheSameLinesThroughATrim() + { + var app = CappedApp(200, pageLines: 5); + app.LoadLongScene(Main, 240); + SettledRows(app); + app.SimulateKey(Chord(ConsoleKey.PageUp)); + var before = VisibleLines(Rows(app.RenderWholeFrame())); + + app.LoadLongScene(Main, 60, first: 5001); + var after = VisibleLines(SettledRows(app)); + + await Assert.That(before.Count).IsGreaterThan(0); + await Assert.That(after).IsEquivalentTo(before); + } + /// /// A frozen pane is two viewports over one buffer, and a trim comes off the pinned half. What the /// reader froze stays where they froze it while the live tail below it carries on. @@ -537,7 +558,7 @@ public async Task TheWheelScrollsThePaneUnderThePointer() driver.SimulateMouseEvent(new List { MouseFlags.WheeledUp }, pointer); var up = app.ScrollbackOf(Main)!.Value; - await Assert.That(up.Offset).IsEqualTo(bottom.Offset - 3); + await Assert.That(up.Offset).IsEqualTo(bottom.Offset - TextSettings.DefaultScrollLines); await Assert.That(up.AutoScroll).IsFalse(); await Assert.That(Shows(SettledRows(app), SharpMUTermApp.ScrollbackSceneLines)).IsFalse(); diff --git a/tests/SharpMUTerm.Tui.Tests/PointerTests.cs b/tests/SharpMUTerm.Tui.Tests/PointerTests.cs index 836839f2..aca247ea 100644 --- a/tests/SharpMUTerm.Tui.Tests/PointerTests.cs +++ b/tests/SharpMUTerm.Tui.Tests/PointerTests.cs @@ -344,4 +344,94 @@ public async Task APaneWithMoreOutputThanItShowsReportsAScrollbarThatScrollsIt() await Assert.That(top.Offset).IsEqualTo(0); await Assert.That(bar.Offset).IsGreaterThan(0); } + + /// + /// The reported defect: dragging the window's scrollbar opened the split under the thumb, which rebuilt the pane and + /// moved the bar's track away from the pointer. The pane stays whole while the thumb is held, splits once it is let go, + /// and the bar reads the same track, viewport and offset before and after, so the thumb does not move. + /// + [Test] + public async Task AHeldThumbSplitsThePaneOnlyWhenLetGoAndTheBarDoesNotMove() + { + var (app, pointer) = App("scrollback"); + var bar = pointer.Bars.Single(b => b.ContentRows > b.ViewportRows); + + bar.Held!(true); + bar.ScrollTo(bar.Offset - 40); + app.RenderNextFrame(); + app.RenderNextFrame(); + var held = pointer.Bars.Single(b => b.WindowId == bar.WindowId); + held.ScrollTo(held.Offset - 10); + app.RenderNextFrame(); + app.RenderNextFrame(); + var dragged = pointer.Bars.Single(b => b.WindowId == bar.WindowId); + + await Assert.That(app.IsScrollSplit(bar.WindowId)).IsFalse().Because("nothing moves under a held thumb"); + await Assert.That(dragged.Offset).IsEqualTo(bar.Offset - 50); + + dragged.Held!(false); + app.RenderNextFrame(); + app.RenderNextFrame(); + var after = pointer.Bars.Single(b => b.WindowId == bar.WindowId); + + await Assert.That(app.IsScrollSplit(bar.WindowId)).IsTrue(); + await Assert.That(after.Track).IsEqualTo(dragged.Track); + await Assert.That(after.ViewportRows).IsEqualTo(dragged.ViewportRows); + await Assert.That(after.ContentRows).IsEqualTo(dragged.ContentRows); + await Assert.That(after.Offset).IsEqualTo(dragged.Offset); + } + + /// A split pane's thumb dragged to the foot of its track takes the pane back to its live tail when let go. + [Test] + public async Task AThumbLetGoAtTheFootOfASplitPanesTrackReturnsToTheLiveTail() + { + var (app, pointer) = App("scrollback"); + var bar = pointer.Bars.Single(b => b.ContentRows > b.ViewportRows); + bar.ScrollTo(bar.Offset - 40); + app.RenderNextFrame(); + app.RenderNextFrame(); + await Assert.That(app.IsScrollSplit(bar.WindowId)).IsTrue(); + + var split = pointer.Bars.Single(b => b.WindowId == bar.WindowId); + split.Held!(true); + split.ScrollTo(split.ContentRows - split.ViewportRows); + app.RenderNextFrame(); + app.RenderNextFrame(); + await Assert.That(app.IsScrollSplit(bar.WindowId)).IsTrue().Because("still held"); + + split.Held(false); + app.RenderNextFrame(); + app.RenderNextFrame(); + await Assert.That(app.IsScrollSplit(bar.WindowId)).IsFalse(); + } + /// + /// The pane shrinks while split (here the second command line comes up, taking rows from the panes): the bar is + /// measured on the history's new height, so the foot of its track is still the live tail. + /// + [Test] + public async Task AThumbLetGoAtTheFootAfterTheSplitPaneShrankStillReturnsToTheLiveTail() + { + var (app, pointer) = App("scrollback"); + var bar = pointer.Bars.Single(b => b.ContentRows > b.ViewportRows); + bar.ScrollTo(bar.Offset - 40); + app.RenderNextFrame(); + app.RenderNextFrame(); + await Assert.That(app.IsScrollSplit(bar.WindowId)).IsTrue(); + var before = pointer.Bars.Single(b => b.WindowId == bar.WindowId).ViewportRows; + + await Assert.That(app.DispatchCommand("term:input2-on")).IsTrue(); + app.RenderNextFrame(); + app.RenderNextFrame(); + await Assert.That(app.IsScrollSplit(bar.WindowId)).IsTrue(); + + var split = pointer.Bars.Single(b => b.WindowId == bar.WindowId); + await Assert.That(split.ViewportRows).IsLessThan(before).Because("the pane is shorter now"); + split.Held!(true); + split.ScrollTo(split.ContentRows - split.ViewportRows); + app.RenderNextFrame(); + split.Held(false); + app.RenderNextFrame(); + app.RenderNextFrame(); + await Assert.That(app.IsScrollSplit(bar.WindowId)).IsFalse(); + } } diff --git a/tests/SharpMUTerm.Tui.Tests/ScreenModelTests.cs b/tests/SharpMUTerm.Tui.Tests/ScreenModelTests.cs index 31476219..014c9954 100644 --- a/tests/SharpMUTerm.Tui.Tests/ScreenModelTests.cs +++ b/tests/SharpMUTerm.Tui.Tests/ScreenModelTests.cs @@ -376,10 +376,10 @@ public async Task Options_NavigableRowsSkipSectionHeadersAndSpacers() // ALERTS adds three rows and one stop: its heading, its spacer and `alert when away`. // SCENE LOG adds four rows and two stops: its heading, its spacer, the format and what is recorded. // UPDATES adds four rows and two stops: its heading, its spacer, `check for updates` and `include prereleases`. - // SCROLLBACK's `live tail rows when split` adds one row and one stop. - await Assert.That(screen.Rows.Count).IsEqualTo(51); + // SCROLLBACK's `live tail rows when split` adds one row and one stop, and its wheel and page-key lines two more. + await Assert.That(screen.Rows.Count).IsEqualTo(53); await Assert.That(model.PaneCount).IsEqualTo(1); - await Assert.That(model.Sizes[0]).IsEqualTo(23); + await Assert.That(model.Sizes[0]).IsEqualTo(25); } /// diff --git a/tests/SharpMUTerm.Tui.Tests/ScrollSplitTests.cs b/tests/SharpMUTerm.Tui.Tests/ScrollSplitTests.cs index c2993784..571e0eb2 100644 --- a/tests/SharpMUTerm.Tui.Tests/ScrollSplitTests.cs +++ b/tests/SharpMUTerm.Tui.Tests/ScrollSplitTests.cs @@ -1,5 +1,6 @@ using System.Text.RegularExpressions; using SharpConsoleUI.Drivers; +using SharpMUTerm.Core.Configuration; using SharpMUTerm.Core.Workspaces; using SharpMUTerm.Graphics; using SharpMUTerm.Tui; @@ -18,11 +19,12 @@ public class ScrollSplitTests private static readonly TerminalCapabilities Headless = new(GraphicsProtocol.None, supportsTrueColor: true, supportsKittyGraphics: false, supportsSixel: false); - private static SharpMUTermApp App(bool split = true, string? tail = null) + private static SharpMUTermApp App(bool split = true, string? tail = null, int? page = null) { Console.SetIn(TextReader.Null); var config = DemoScene.Build(); config.Text.SplitScrollback = split; + if (page is { } lines) config.Text.PageLines = lines; if (tail is not null) config.Text.ScrollTail = tail; var app = new SharpMUTermApp(config, Headless, new HeadlessConsoleDriver(120, 32)); app.RenderSnapshot("scrollback"); @@ -54,11 +56,13 @@ private static void Wheel(SharpMUTermApp app, HeadlessConsoleDriver driver, bool Settled(app); } - private static (SharpMUTermApp App, HeadlessConsoleDriver Driver, PaneRect Pane) WheelApp() + private static (SharpMUTermApp App, HeadlessConsoleDriver Driver, PaneRect Pane) WheelApp(int? wheel = null) { Console.SetIn(TextReader.Null); var driver = new HeadlessConsoleDriver(120, 32); - var app = new SharpMUTermApp(DemoScene.Build(), Headless, driver); + var config = DemoScene.Build(); + if (wheel is { } lines) config.Text.WheelLines = lines; + var app = new SharpMUTermApp(config, Headless, driver); app.RenderSnapshot("scrollback"); Settled(app); var paneId = app.PaneWindows().First(p => p.Value == Main).Key; @@ -83,7 +87,7 @@ public async Task TheWheelOverTheLiveTailScrollsTheHistoryAndNotTheTail() var tailAt = app.ScrollTailOf(Main)!.Value; Wheel(app, driver, up: true, tail); - await Assert.That(app.ScrollbackOf(Main)!.Value.Offset).IsEqualTo(opened - 3); + await Assert.That(app.ScrollbackOf(Main)!.Value.Offset).IsEqualTo(opened - TextSettings.DefaultScrollLines); await Assert.That(app.ScrollTailOf(Main)!.Value.Offset).IsEqualTo(tailAt.Offset); await Assert.That(app.ScrollTailOf(Main)!.Value.AutoScroll).IsTrue(); @@ -92,9 +96,9 @@ public async Task TheWheelOverTheLiveTailScrollsTheHistoryAndNotTheTail() await Assert.That(app.ScrollTailOf(Main)!.Value.Offset).IsEqualTo(tailAt.Offset); } - /// A notch is three rows wherever the pointer is, never three plus the framework's own one. + /// A notch is F7's lines per notch (10 by default) wherever the pointer is, never that plus the framework's own one. [Test] - public async Task AWheelNotchOverTheHistoryMovesItThreeRows() + public async Task AWheelNotchOverTheHistoryMovesItTheSettingsLines() { var (app, driver, pane) = WheelApp(); var history = new System.Drawing.Point(pane.X + 5, pane.Y + 2); @@ -103,7 +107,56 @@ public async Task AWheelNotchOverTheHistoryMovesItThreeRows() var opened = app.ScrollbackOf(Main)!.Value.Offset; Wheel(app, driver, up: true, history); - await Assert.That(app.ScrollbackOf(Main)!.Value.Offset).IsEqualTo(opened - 3); + await Assert.That(app.ScrollbackOf(Main)!.Value.Offset).IsEqualTo(opened - TextSettings.DefaultScrollLines); + } + + [Test] + public async Task AWheelNotchMovesAsManyLinesAsTheSettingSays() + { + var (app, driver, pane) = WheelApp(wheel: 4); + var history = new System.Drawing.Point(pane.X + 5, pane.Y + 2); + + Wheel(app, driver, up: true, history); + var opened = app.ScrollbackOf(Main)!.Value.Offset; + Wheel(app, driver, up: true, history); + Wheel(app, driver, up: false, history); + Wheel(app, driver, up: true, history); + + await Assert.That(app.ScrollbackOf(Main)!.Value.Offset).IsEqualTo(opened - 4); + } + + [Test] + public async Task PageUpMovesTenLinesByDefaultAndTheSettingsCountOtherwise() + { + var app = App(); + app.SimulateKey(Key(ConsoleKey.PageUp)); + Settled(app); + var first = app.ScrollbackOf(Main)!.Value.Offset; + app.SimulateKey(Key(ConsoleKey.PageUp)); + Settled(app); + await Assert.That(app.ScrollbackOf(Main)!.Value.Offset).IsEqualTo(first - TextSettings.DefaultScrollLines); + + var custom = App(page: 25); + custom.SimulateKey(Key(ConsoleKey.PageUp)); + Settled(custom); + var at = custom.ScrollbackOf(Main)!.Value.Offset; + custom.SimulateKey(Key(ConsoleKey.PageUp)); + Settled(custom); + await Assert.That(custom.ScrollbackOf(Main)!.Value.Offset).IsEqualTo(at - 25); + } + + /// Zero is a page: the viewport less two rows of overlap, as PgUp always was. + [Test] + public async Task PageLinesOfZeroPagesByTheViewport() + { + var app = App(page: 0); + app.SimulateKey(Key(ConsoleKey.PageUp)); + Settled(app); + var view = app.ScrollbackOf(Main)!.Value; + app.SimulateKey(Key(ConsoleKey.PageUp)); + Settled(app); + + await Assert.That(view.Offset - app.ScrollbackOf(Main)!.Value.Offset).IsEqualTo(view.ViewportRows - 2); } [Test] @@ -125,6 +178,28 @@ public async Task ScrollingBackSplitsThePaneAndKeepsTheNewestLineInView() await Assert.That(app.PaneOutputRects()).IsEquivalentTo(before); } + [Test] + public async Task WhereTheHostKeepsAGutterTheHistoryDoesNotDropARowWhenThePaneSplits() + { + // The window keeps a blank row above output (HostChrome.PaneGutter). Split, that row is the split's; the kept + // viewport used to keep its own too, so the history started a row lower and the text jumped down as it opened. + Console.SetIn(TextReader.Null); + var config = DemoScene.Build(); + config.Text.SplitScrollback = true; + var host = ClientHost.Headless(new HeadlessConsoleDriver(120, 32), Headless) with { Chrome = HostChrome.Desktop }; + await using var app = new SharpMUTermApp(config, host); + app.RenderSnapshot("scrollback"); + var top = app.PaneOutputRects().Values.Single().Y; + app.SimulateKey(Key(ConsoleKey.PageUp)); + app.SimulateKey(Key(ConsoleKey.PageUp)); + app.RenderWholeFrame(); + var rows = FrameGrid.Decode(app.RenderWholeFrame(), 120, 32); + + await Assert.That(app.IsScrollSplit(Main)).IsTrue(); + await Assert.That(rows[top]).Contains("line 0"); + await Assert.That(rows[top - 1]).DoesNotContain("line 0"); + } + [Test] public async Task OutputArrivingWhileSplitLandsInTheTailAndLeavesTheHistoryWhereItWas() {