LayoutImporter.ReadState now reads Properties 0x1B (ColorBaseProperty, ARGB bytes) and stores the normalized Vector4 in ElementInfo.FontColor (nullable). ElementReader.Merge propagates it with the same non-null-derived-wins rule as FontDid and HJustify. DatWidgetFactory.BuildText seeds UiText.DefaultColor from FontColor when present. Diagnosis for LayoutDesc 0x2100002E: ALL 12 header and footer text elements carry NO dat color. Every color is runtime set by CharacterStatController. Comments added at each callsite. No hardcoded colors deleted. Tests added: 3 ElementReader FontColor Merge + 3 DatWidgetFactory DefaultColor. 702 passed, 0 failed. Screenshots: character window, vitals, toolbar all unchanged. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
525 lines
23 KiB
C#
525 lines
23 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Numerics;
|
|
using System.Text;
|
|
using AcDream.App.Rendering;
|
|
using AcDream.App.UI.Layout;
|
|
|
|
namespace AcDream.App.UI;
|
|
|
|
/// <summary>
|
|
/// Scrollable text view for retail UIElement_Text elements
|
|
/// (<c>RegisterElementClass(0xc) @ acclient_2013_pseudo_c.txt:115655</c>).
|
|
/// Renders the lines from <see cref="LinesProvider"/> bottom-pinned (newest at the bottom,
|
|
/// like retail) with mouse-wheel scrollback. Whole-line vertical clipping keeps
|
|
/// text inside the window.
|
|
///
|
|
/// <para>
|
|
/// Supports Windows-like text selection: a left-click-drag inside the transcript
|
|
/// selects characters (the <see cref="UiElement.CapturesPointerDrag"/> opt-out
|
|
/// stops that interior drag from moving the host window), and Ctrl+C copies the
|
|
/// selected span to the clipboard. Ctrl+A selects everything.
|
|
/// </para>
|
|
/// </summary>
|
|
public sealed class UiText : UiElement
|
|
{
|
|
/// <summary>One display line: pre-formatted text + its colour.</summary>
|
|
public readonly record struct Line(string Text, Vector4 Color);
|
|
|
|
/// <summary>A caret position: a line index into the cached line list plus a
|
|
/// character index (0..line.Text.Length, i.e. a caret slot between glyphs).</summary>
|
|
public readonly record struct Pos(int Line, int Col);
|
|
|
|
/// <summary>Provider of the lines to show, oldest-first. Polled each frame.</summary>
|
|
public Func<IReadOnlyList<Line>> LinesProvider { get; set; } = static () => Array.Empty<Line>();
|
|
|
|
/// <summary>Font for the transcript; falls back to the context default.</summary>
|
|
public BitmapFont? Font { get; set; }
|
|
|
|
/// <summary>Retail dat font (0x40000000) for the transcript. When set, glyphs
|
|
/// render via the two-pass dat-font blit and measure/hit-test use the dat glyph
|
|
/// advance; when null, the debug BitmapFont path is used. Set by the controller.</summary>
|
|
public UiDatFont? DatFont { get; set; }
|
|
|
|
/// <summary>Keyboard device for clipboard (Ctrl+C) + modifier state. Wired by
|
|
/// the host from <see cref="UiHost.Keyboard"/>.</summary>
|
|
public Silk.NET.Input.IKeyboard? Keyboard { get; set; }
|
|
|
|
/// <summary>
|
|
/// Default line color used by controllers when they do not supply a per-line
|
|
/// <see cref="Vector4"/> color explicitly. Set by <c>DatWidgetFactory.BuildText</c>
|
|
/// from <c>ElementInfo.FontColor</c> when the dat carries a 0x1B ColorBaseProperty;
|
|
/// otherwise white (<see cref="Vector4.One"/>).
|
|
///
|
|
/// <para>Controllers that supply a per-line color via <see cref="LinesProvider"/>
|
|
/// (e.g. <c>new UiText.Line(text, explicitColor)</c>) are unaffected — they always
|
|
/// win over this default. This property is only a convenience starting point for
|
|
/// controllers that want to read the dat color rather than hard-code it.</para>
|
|
/// </summary>
|
|
public Vector4 DefaultColor { get; set; } = Vector4.One;
|
|
|
|
/// <summary>Backing fill behind the text. Defaults to transparent so an unbound
|
|
/// UiText (no controller) draws nothing. Set to the retail translucent value by
|
|
/// the controller (e.g. <c>ChatWindowController</c>).</summary>
|
|
public Vector4 BackgroundColor { get; set; } = new(0f, 0f, 0f, 0f);
|
|
|
|
/// <summary>Optional dat state-sprite background (the element's own media), drawn
|
|
/// UNDER the text. Set by DatWidgetFactory.BuildText from the ElementInfo. 0 = none.</summary>
|
|
public uint BackgroundSprite { get; set; }
|
|
|
|
/// <summary>Resolves a dat RenderSurface id to (GL tex handle, pixel width, pixel height).
|
|
/// Required when <see cref="BackgroundSprite"/> is non-zero.</summary>
|
|
public Func<uint, (uint tex, int w, int h)>? SpriteResolve { get; set; }
|
|
|
|
/// <summary>Highlight colour painted behind a selected character span.</summary>
|
|
public Vector4 SelectionColor { get; set; } = new(0.25f, 0.45f, 0.85f, 0.5f);
|
|
|
|
/// <summary>Inner text inset from the view edges, px.</summary>
|
|
public float Padding { get; set; } = 4f;
|
|
|
|
/// <summary>Static centered single-line mode (retail <c>UIElement_Text</c> center
|
|
/// justification): draws the FIRST line centered horizontally AND vertically in the
|
|
/// element rect, with NO scroll/selection machinery. Used for static labels such as
|
|
/// the vitals cur/max numbers. The centering formula is IDENTICAL to
|
|
/// <see cref="UiMeter"/>'s former number overlay so those numbers stay pixel-identical
|
|
/// after the rewire. Pair with <c>ClickThrough = true</c> for non-interactive labels.</summary>
|
|
public bool Centered { get; set; }
|
|
|
|
/// <summary>Static right-aligned single-line mode: draws the FIRST line right-justified
|
|
/// within the element rect, vertically centered, with NO scroll/selection machinery.
|
|
/// Used for value labels in attribute/skill rows where the number must hug the right edge.
|
|
/// Mutually exclusive with <see cref="Centered"/> — if both are true, Centered takes
|
|
/// precedence. Pair with <c>ClickThrough = true</c> for non-interactive labels.</summary>
|
|
public bool RightAligned { get; set; }
|
|
|
|
/// <summary>
|
|
/// Vertical position of the text within the element rect in single-line mode
|
|
/// (<see cref="Centered"/> or <see cref="RightAligned"/>).
|
|
/// <list type="bullet">
|
|
/// <item><description><b>Center</b> (default) — vertically centered, matching the original
|
|
/// behavior of the centered/right-aligned paths.</description></item>
|
|
/// <item><description><b>Top</b> — text is placed at <c>y = Padding</c> (top of the content
|
|
/// area), so the text sits at the top of the element rather than centering in it.
|
|
/// Used for footer title elements whose dat box is the full footer height (55 px) but
|
|
/// the text should render near the top.</description></item>
|
|
/// <item><description><b>Bottom</b> — text is placed at <c>y = Height - lineHeight - Padding</c>.</description></item>
|
|
/// </list>
|
|
/// Only meaningful when <see cref="Centered"/> or <see cref="RightAligned"/> is true.
|
|
/// Has no effect on the scrollable multi-line path.
|
|
/// </summary>
|
|
public VJustify VerticalJustify { get; set; } = VJustify.Center;
|
|
|
|
/// <summary>The scroll model — also read by the linked UiScrollbar.</summary>
|
|
public UiScrollable Scroll { get; } = new();
|
|
|
|
/// <summary>True while the view is pinned to the newest line (auto-scrolls as content grows).</summary>
|
|
private bool _pinBottom = true;
|
|
|
|
private const float WheelLines = 1f; // lines advanced per wheel notch (retail = 1 line per notch)
|
|
|
|
// ── Cached layout from the last OnDraw, so OnEvent hit-tests the SAME geometry ──
|
|
private IReadOnlyList<Line> _lastLines = Array.Empty<Line>();
|
|
private BitmapFont? _lastFont;
|
|
private UiDatFont? _lastDatFont;
|
|
private float _lastLineHeight = 16f;
|
|
private float _lastBaseY; // top Y of line 0 in local space
|
|
private float _lastPadding = 4f;
|
|
|
|
// ── Selection state ──────────────────────────────────────────────────
|
|
private Pos? _selAnchor; // where the drag started
|
|
private Pos? _selCaret; // where the drag currently is
|
|
private bool _selecting;
|
|
|
|
public UiText()
|
|
{
|
|
AcceptsFocus = true;
|
|
IsEditControl = true; // absorb keys (Ctrl+C) while focused
|
|
CapturesPointerDrag = true; // interior drag selects, doesn't move the window
|
|
}
|
|
|
|
/// <summary>The text view draws its own lines + background; any dat sub-elements
|
|
/// (scroll indicators, caps) are not built as separate widgets by the importer.</summary>
|
|
public override bool ConsumesDatChildren => true;
|
|
|
|
/// <summary>
|
|
/// Clamp a scroll offset to [0, max] where max = content-height - view-height
|
|
/// (never negative — when everything fits, scroll is pinned to 0). Exposed for tests.
|
|
/// </summary>
|
|
public static float ClampScroll(float scroll, float contentHeight, float viewHeight)
|
|
{
|
|
float max = Math.Max(0f, contentHeight - viewHeight);
|
|
if (scroll < 0f) return 0f;
|
|
return scroll > max ? max : scroll;
|
|
}
|
|
|
|
protected override void OnDraw(UiRenderContext ctx)
|
|
{
|
|
// Optional dat state-sprite background drawn UNDER everything else.
|
|
if (BackgroundSprite != 0 && SpriteResolve is { } sr)
|
|
{
|
|
var (tex, tw, th) = sr(BackgroundSprite);
|
|
if (tex != 0 && tw != 0 && th != 0)
|
|
ctx.DrawSprite(tex, 0, 0, Width, Height, 0, 0, Width / tw, Height / th, Vector4.One);
|
|
}
|
|
|
|
// Background must draw UNDER the transcript text. DrawStringDat emits into the
|
|
// sprite bucket which flushes BEFORE rects, so a DrawRect background would wash
|
|
// over the text. DrawFill routes the background through the sprite bucket too,
|
|
// submitted first → text on top.
|
|
ctx.DrawFill(0, 0, Width, Height, BackgroundColor);
|
|
|
|
// Static centered single-line mode (vitals cur/max numbers etc.): draw the first
|
|
// line centered H+V (or H+Top/Bottom per VerticalJustify) with the SAME formula
|
|
// UIElement_Meter used for its label, then skip the scroll/selection machinery entirely.
|
|
if (Centered)
|
|
{
|
|
var cLines = LinesProvider();
|
|
if (cLines.Count == 0) return;
|
|
var line0 = cLines[0];
|
|
if (DatFont is { } cdf)
|
|
{
|
|
float cx = (Width - cdf.MeasureWidth(line0.Text)) * 0.5f;
|
|
float cy = VOffset(Height, cdf.LineHeight, Padding, VerticalJustify);
|
|
ctx.DrawStringDat(cdf, line0.Text, cx, cy, line0.Color);
|
|
}
|
|
else if ((Font ?? ctx.DefaultFont) is { } cbf)
|
|
{
|
|
float cx = (Width - cbf.MeasureWidth(line0.Text)) * 0.5f;
|
|
float cy = VOffset(Height, cbf.LineHeight, Padding, VerticalJustify);
|
|
ctx.DrawString(line0.Text, cx, cy, line0.Color, cbf);
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Static right-aligned single-line mode: draw the first line flush with the right
|
|
// edge, vertical position per VerticalJustify, then skip the scroll/selection machinery.
|
|
if (RightAligned)
|
|
{
|
|
var rLines = LinesProvider();
|
|
if (rLines.Count == 0) return;
|
|
var line0 = rLines[0];
|
|
if (DatFont is { } rdf)
|
|
{
|
|
float rx = Width - rdf.MeasureWidth(line0.Text) - Padding;
|
|
float ry = VOffset(Height, rdf.LineHeight, Padding, VerticalJustify);
|
|
ctx.DrawStringDat(rdf, line0.Text, rx, ry, line0.Color);
|
|
}
|
|
else if ((Font ?? ctx.DefaultFont) is { } rbf)
|
|
{
|
|
float rx = Width - rbf.MeasureWidth(line0.Text) - Padding;
|
|
float ry = VOffset(Height, rbf.LineHeight, Padding, VerticalJustify);
|
|
ctx.DrawString(line0.Text, rx, ry, line0.Color, rbf);
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Prefer the retail dat font when set; fall back to BitmapFont.
|
|
var datFont = DatFont;
|
|
var bitmapFont = datFont is null ? (Font ?? ctx.DefaultFont) : null;
|
|
if (datFont is null && bitmapFont is null) return;
|
|
|
|
var lines = LinesProvider();
|
|
|
|
// Cache the geometry OnEvent will hit-test against. Even when there are no
|
|
// lines we record the font/padding so a stray hit-test is harmless.
|
|
_lastLines = lines;
|
|
_lastDatFont = datFont;
|
|
_lastFont = bitmapFont;
|
|
_lastLineHeight = datFont is not null ? datFont.LineHeight : bitmapFont!.LineHeight;
|
|
_lastPadding = Padding;
|
|
|
|
if (lines.Count == 0) return;
|
|
|
|
float lh = _lastLineHeight;
|
|
float top = Padding, bottom = Height - Padding;
|
|
float innerH = bottom - top;
|
|
float contentH = lines.Count * lh;
|
|
|
|
// Drive the shared scroll model with the current geometry.
|
|
Scroll.LineHeight = (int)MathF.Round(lh);
|
|
Scroll.ContentHeight = (int)MathF.Ceiling(contentH);
|
|
Scroll.ViewHeight = (int)MathF.Floor(innerH);
|
|
if (_pinBottom) Scroll.ScrollToEnd();
|
|
|
|
// UiScrollable: ScrollY=0 is TOP/oldest, ScrollY=MaxScroll is BOTTOM/newest.
|
|
// Visual layout: newest at bottom → baseY = bottom - contentH (ScrollY at max).
|
|
// Invert: baseY = bottom - contentH + (MaxScroll - ScrollY).
|
|
// With _pinBottom: ScrollY=MaxScroll → baseY=bottom-contentH → last line ends at bottom. ✓
|
|
// Scrolled to top: ScrollY=0 → baseY=bottom-contentH+MaxScroll=bottom-innerH=top. ✓
|
|
float baseY = bottom - contentH + (Scroll.MaxScroll - Scroll.ScrollY);
|
|
_lastBaseY = baseY;
|
|
|
|
// Normalised selection span (start <= end), if any.
|
|
bool hasSel = TryGetOrderedSelection(out Pos selStart, out Pos selEnd);
|
|
|
|
for (int i = 0; i < lines.Count; i++)
|
|
{
|
|
float y = baseY + i * lh;
|
|
if (y < top || y + lh > bottom) continue; // whole-line vertical clip (no scissor yet)
|
|
|
|
string text = lines[i].Text;
|
|
|
|
// Selection highlight behind this line's selected character span.
|
|
if (hasSel && i >= selStart.Line && i <= selEnd.Line)
|
|
{
|
|
int c0 = i == selStart.Line ? selStart.Col : 0;
|
|
int c1 = i == selEnd.Line ? selEnd.Col : text.Length;
|
|
c0 = Math.Clamp(c0, 0, text.Length);
|
|
c1 = Math.Clamp(c1, 0, text.Length);
|
|
if (c1 > c0)
|
|
{
|
|
float hx, hw;
|
|
if (datFont is not null)
|
|
{
|
|
hx = Padding + datFont.MeasureWidth(text.Substring(0, c0));
|
|
hw = datFont.MeasureWidth(text.Substring(c0, c1 - c0));
|
|
}
|
|
else
|
|
{
|
|
hx = Padding + bitmapFont!.MeasureWidth(text.Substring(0, c0));
|
|
hw = bitmapFont.MeasureWidth(text.Substring(c0, c1 - c0));
|
|
}
|
|
// Highlight sits BEHIND the line's text → sprite bucket, submitted
|
|
// before this line's DrawStringDat.
|
|
ctx.DrawFill(hx, y, hw, lh, SelectionColor);
|
|
}
|
|
}
|
|
|
|
if (datFont is not null)
|
|
ctx.DrawStringDat(datFont, text, Padding, y, lines[i].Color);
|
|
else
|
|
ctx.DrawString(text, Padding, y, lines[i].Color, bitmapFont);
|
|
}
|
|
}
|
|
|
|
public override bool OnEvent(in UiEvent e)
|
|
{
|
|
switch (e.Type)
|
|
{
|
|
case UiEventType.Scroll:
|
|
{
|
|
// Silk wheel +Y = scroll up = reveal older = toward the TOP = decrease ScrollY.
|
|
// ScrollByLines sign: +down/newer, -up/older.
|
|
// e.Data0 > 0 → wheel up → want older → ScrollByLines with negative lines.
|
|
Scroll.ScrollByLines((int)(-e.Data0 * WheelLines));
|
|
_pinBottom = Scroll.AtEnd;
|
|
return true;
|
|
}
|
|
|
|
case UiEventType.MouseDown:
|
|
{
|
|
// Data1/Data2 = local-to-target coords (UiRoot.OnMouseDown).
|
|
var p = HitChar(e.Data1, e.Data2);
|
|
_selAnchor = p;
|
|
_selCaret = p;
|
|
_selecting = true;
|
|
return true;
|
|
}
|
|
|
|
case UiEventType.MouseMove:
|
|
{
|
|
if (_selecting)
|
|
{
|
|
// Data1/Data2 = local-to-target coords (DispatchMouseMove).
|
|
_selCaret = HitChar(e.Data1, e.Data2);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
case UiEventType.MouseUp:
|
|
{
|
|
_selecting = false;
|
|
return true;
|
|
}
|
|
|
|
case UiEventType.KeyDown:
|
|
{
|
|
var key = (Silk.NET.Input.Key)e.Data0;
|
|
bool ctrl = Keyboard is not null
|
|
&& (Keyboard.IsKeyPressed(Silk.NET.Input.Key.ControlLeft)
|
|
|| Keyboard.IsKeyPressed(Silk.NET.Input.Key.ControlRight));
|
|
if (ctrl && key == Silk.NET.Input.Key.C)
|
|
{
|
|
// Only touch the clipboard when there's a selection — an empty
|
|
// copy must NOT clobber what the user previously copied.
|
|
if (Keyboard is not null)
|
|
{
|
|
string sel = SelectedText();
|
|
if (sel.Length > 0) Keyboard.ClipboardText = sel;
|
|
}
|
|
return true;
|
|
}
|
|
if (ctrl && key == Silk.NET.Input.Key.A)
|
|
{
|
|
SelectAll();
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// ── Selection helpers ────────────────────────────────────────────────
|
|
|
|
/// <summary>Select the entire cached transcript (Ctrl+A).</summary>
|
|
private void SelectAll()
|
|
{
|
|
var lines = _lastLines;
|
|
if (lines.Count == 0)
|
|
{
|
|
_selAnchor = _selCaret = null;
|
|
return;
|
|
}
|
|
int last = lines.Count - 1;
|
|
_selAnchor = new Pos(0, 0);
|
|
_selCaret = new Pos(last, lines[last].Text.Length);
|
|
}
|
|
|
|
/// <summary>Normalise (anchor, caret) into ordered (start, end). False if no
|
|
/// selection or it is empty (anchor == caret).</summary>
|
|
private bool TryGetOrderedSelection(out Pos start, out Pos end)
|
|
{
|
|
start = default; end = default;
|
|
if (_selAnchor is not { } a || _selCaret is not { } c) return false;
|
|
(start, end) = Order(a, c);
|
|
return !(start.Line == end.Line && start.Col == end.Col);
|
|
}
|
|
|
|
/// <summary>The currently-selected text against the cached lines. Empty when
|
|
/// nothing is selected.</summary>
|
|
public string SelectedText()
|
|
{
|
|
if (!TryGetOrderedSelection(out var start, out var end)) return string.Empty;
|
|
return SelectedText(_lastLines, start, end);
|
|
}
|
|
|
|
// ── Pure, testable logic (no GL / no font texture) ───────────────────
|
|
|
|
/// <summary>
|
|
/// Compute the Y offset (local space) for a single line in the Centered/RightAligned
|
|
/// single-line path, given the element height, font line-height, padding, and
|
|
/// vertical justification.
|
|
/// </summary>
|
|
/// <param name="height">Element height in pixels.</param>
|
|
/// <param name="lineHeight">Font line height in pixels.</param>
|
|
/// <param name="padding">Content padding.</param>
|
|
/// <param name="vj">Vertical justification.</param>
|
|
public static float VOffset(float height, float lineHeight, float padding, VJustify vj)
|
|
=> vj switch
|
|
{
|
|
VJustify.Top => padding,
|
|
VJustify.Bottom => height - lineHeight - padding,
|
|
_ => (height - lineHeight) * 0.5f, // Center (default)
|
|
};
|
|
|
|
/// <summary>Order two caret positions so the first is <= the second (by line,
|
|
/// then column).</summary>
|
|
public static (Pos start, Pos end) Order(Pos a, Pos b)
|
|
{
|
|
if (a.Line < b.Line || (a.Line == b.Line && a.Col <= b.Col)) return (a, b);
|
|
return (b, a);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Assemble the selected substring spanning <paramref name="start"/> ..
|
|
/// <paramref name="end"/> (inclusive of start.Col, exclusive of end.Col) from
|
|
/// <paramref name="lines"/>. Multi-line selections are joined with "\n":
|
|
/// the first line from start.Col to its end, whole middle lines, and the last
|
|
/// line up to end.Col. Pure — unit-testable without GL.
|
|
/// </summary>
|
|
public static string SelectedText(IReadOnlyList<Line> lines, Pos start, Pos end)
|
|
{
|
|
if (lines.Count == 0) return string.Empty;
|
|
(start, end) = Order(start, end);
|
|
|
|
int sl = Math.Clamp(start.Line, 0, lines.Count - 1);
|
|
int el = Math.Clamp(end.Line, 0, lines.Count - 1);
|
|
|
|
if (sl == el)
|
|
{
|
|
string t = lines[sl].Text;
|
|
int c0 = Math.Clamp(start.Col, 0, t.Length);
|
|
int c1 = Math.Clamp(end.Col, 0, t.Length);
|
|
if (c1 <= c0) return string.Empty;
|
|
return t.Substring(c0, c1 - c0);
|
|
}
|
|
|
|
var sb = new StringBuilder();
|
|
|
|
// First line: from start.Col to its end.
|
|
{
|
|
string t = lines[sl].Text;
|
|
int c0 = Math.Clamp(start.Col, 0, t.Length);
|
|
sb.Append(t.AsSpan(c0));
|
|
}
|
|
|
|
// Whole middle lines.
|
|
for (int i = sl + 1; i < el; i++)
|
|
{
|
|
sb.Append('\n');
|
|
sb.Append(lines[i].Text);
|
|
}
|
|
|
|
// Last line: up to end.Col.
|
|
{
|
|
sb.Append('\n');
|
|
string t = lines[el].Text;
|
|
int c1 = Math.Clamp(end.Col, 0, t.Length);
|
|
sb.Append(t.AsSpan(0, c1));
|
|
}
|
|
|
|
return sb.ToString();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Convert a local-space point to a caret <see cref="Pos"/> against the cached
|
|
/// layout from the last draw. line = floor((localY - baseY)/lineHeight) clamped
|
|
/// to the line range; col via <see cref="CharIndexAt"/>.
|
|
/// </summary>
|
|
private Pos HitChar(float localX, float localY)
|
|
{
|
|
var lines = _lastLines;
|
|
if (lines.Count == 0) return new Pos(0, 0);
|
|
|
|
float lh = _lastLineHeight <= 0f ? 16f : _lastLineHeight;
|
|
int line = (int)MathF.Floor((localY - _lastBaseY) / lh);
|
|
line = Math.Clamp(line, 0, lines.Count - 1);
|
|
|
|
string text = lines[line].Text;
|
|
int col = _lastDatFont is { } df
|
|
? CharIndexAt(text, ch => df.TryGetGlyph(ch, out var g) ? UiDatFont.GlyphAdvance(g) : 0f,
|
|
localX - _lastPadding)
|
|
: (_lastFont is { } bf
|
|
? CharIndexAt(text, ch => bf.TryGetGlyph(ch, out var bg) ? bg.Advance : 0f,
|
|
localX - _lastPadding)
|
|
: 0);
|
|
return new Pos(line, col);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The caret column for a horizontal position <paramref name="x"/> (already
|
|
/// adjusted for the left padding, so x=0 is the start of the text). Walks the
|
|
/// string accumulating each glyph's advance and snaps the caret to whichever
|
|
/// side of the glyph midpoint <paramref name="x"/> falls on — natural
|
|
/// Windows-like caret placement. Pure — unit-testable with a synthetic advance.
|
|
/// </summary>
|
|
/// <param name="text">The line text.</param>
|
|
/// <param name="advanceOf">Per-character advance (pixels) lookup.</param>
|
|
/// <param name="x">Horizontal position relative to the text's left edge.</param>
|
|
public static int CharIndexAt(string text, Func<char, float> advanceOf, float x)
|
|
{
|
|
if (string.IsNullOrEmpty(text) || x <= 0f) return 0;
|
|
|
|
float cursor = 0f;
|
|
for (int i = 0; i < text.Length; i++)
|
|
{
|
|
float adv = advanceOf(text[i]);
|
|
float mid = cursor + adv * 0.5f;
|
|
if (x < mid) return i; // caret sits before this glyph
|
|
cursor += adv;
|
|
}
|
|
return text.Length; // past the last glyph → end caret
|
|
}
|
|
}
|