F6: tooltip perché, correzioni della revisione
Le spiegazioni ora si ricompongono davvero dai termini mostrati e il tooltip resta coerente con il pannello su cui sta. Core: - prezzo globale: termini Dtot, Stot, η, rmin, rmax e formula del rapporto D/S = clamp(Dtot/Stot, rmin, rmax) con gli scambi con il mondo; - condizione del treno: la stima viene da Fleet.ConditionDue (estratta da Fleet.Dues senza cambiare l'aritmetica), con condizione e usura del componente che la dà, distinto dal più debole; - tariffe merci e passeggeri riservate alla compagnia della linea; - efficienza: la condizione mostrata è quella da cui viene mc (salvata in EfficiencyTerms prima della manutenzione), formula con «lavoro». Client: - WhyTooltip chiede la spiegazione a ogni apertura e poi al più una volta al secondo per valore (per chiave), mostrando la cache come in aggiornamento; passa al sostituto quando il pannello ricostruisce il controllo sotto il puntatore, invece di chiudersi e lampeggiare; - prezzi come la scheda dell'industria, importi piccoli con i centesimi, condizione per difetto in percentuale, componente accanto al numero; - misura del riquadro dopo l'impaginazione (niente salti di lato); - cassa della barra dalle entità e nota quando il numero mostrato non è quello spiegato; nel Mercato il suggerimento nativo della riga non copre più il tooltip del prezzo. Refs #44. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
19a3dd3af1
commit
4beedd2e75
14 files changed
+381
-112
No files matched your search
@@ -10,10 +10,13 @@ namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// Tooltip «perché» comune (F6, ADR 0024): sopra un valore dei pannelli, dopo un breve ritardo, mostra la
|
||||
/// spiegazione calcolata dal server (titolo, valore, formula, termini con i valori di oggi, note) nello stile
|
||||
/// della palette 05. Il client non calcola nulla: se la spiegazione manca o è di un giorno passato la chiede
|
||||
/// (RequestDetail con DetailKind.Explain) e intanto mostra «in arrivo…». Un solo tooltip per schermata, su
|
||||
/// un suo CanvasLayer sopra l'interfaccia; i pannelli lo agganciano con <see cref="Attach"/>.
|
||||
/// spiegazione calcolata dal server (titolo, valore, formula, termini con i valori di adesso, note) nello stile
|
||||
/// della palette 05. Il client non calcola nulla: a ogni apertura chiede la spiegazione (RequestDetail con
|
||||
/// DetailKind.Explain) e poi, finché il puntatore resta, al più una volta al secondo per valore; intanto mostra
|
||||
/// quella in cache con «aggiornamento in arrivo…» (o «in arrivo…» se manca). Un solo tooltip per schermata, su
|
||||
/// un suo CanvasLayer sopra l'interfaccia; i pannelli lo agganciano con <see cref="Attach"/>. Se il controllo
|
||||
/// sotto il puntatore viene ricostruito (i pannelli rifanno le righe a ogni scheda), il tooltip passa al
|
||||
/// sostituto con la stessa spiegazione senza chiudersi.
|
||||
/// </summary>
|
||||
public partial class WhyTooltip : PanelContainer
|
||||
{
|
||||
@@ -22,20 +25,36 @@ public partial class WhyTooltip : PanelContainer
|
||||
|
||||
/// <summary>Ritardo prima dell'apertura (secondi).</summary>
|
||||
private const double OpenDelay = 0.45;
|
||||
/// <summary>Intervallo minimo tra due richieste della stessa spiegazione (secondi).</summary>
|
||||
private const double RequestInterval = 1.0;
|
||||
/// <summary>Intervallo minimo tra due richieste della stessa spiegazione (millisecondi).</summary>
|
||||
private const ulong RequestIntervalMs = 1000;
|
||||
/// <summary>Tempo per trovare il sostituto di un controllo ricostruito prima di chiudere (secondi).</summary>
|
||||
private const double ReplaceGrace = 0.3;
|
||||
private const float MaxWidth = 440;
|
||||
|
||||
/// <summary>Aggancio di un controllo: bersaglio, suggerimento e, se serve, il valore che il controllo mostra.</summary>
|
||||
private sealed record Hook(Control Control, Func<ExplainTarget?> Target, string Hint, Func<double?>? Shown);
|
||||
|
||||
/// <summary>Agganci dei controlli nell'albero, per ritrovare il sostituto di un controllo ricostruito.</summary>
|
||||
private static readonly List<Hook> Hooks = [];
|
||||
|
||||
private readonly GameSession _session;
|
||||
private readonly VBoxContainer _body = new();
|
||||
private Control? _hover;
|
||||
private Func<ExplainTarget?>? _target;
|
||||
private string _hint = "";
|
||||
private Hook? _hook;
|
||||
/// <summary>Il controllo agganciato è stato tolto o sta per esserlo: si cerca il sostituto sotto il puntatore.</summary>
|
||||
private bool _lost;
|
||||
private double _lostFor;
|
||||
private (byte Subject, int Target, int Arg) _key;
|
||||
private bool _hasKey;
|
||||
private double _wait;
|
||||
private double _sinceRequest = double.MaxValue;
|
||||
private int _shownVersion = -1;
|
||||
/// <summary>Spiegazione in cache all'apertura: finché non ne arriva un'altra si mostra come in aggiornamento.</summary>
|
||||
private ExplanationReport? _baseline;
|
||||
private bool _fresh;
|
||||
private ExplanationReport? _shown;
|
||||
private bool _shownFresh;
|
||||
private bool _dirty = true;
|
||||
private bool _settling;
|
||||
/// <summary>Per valore: istante dell'ultima richiesta e spiegazione in cache in quel momento.</summary>
|
||||
private readonly Dictionary<(byte, int, int), (ulong At, ExplanationReport? Before)> _requests = [];
|
||||
|
||||
public WhyTooltip(GameSession session)
|
||||
{
|
||||
@@ -60,74 +79,177 @@ public partial class WhyTooltip : PanelContainer
|
||||
/// Aggancia il tooltip a un controllo: al passaggio del mouse chiede a <paramref name="target"/> quale valore
|
||||
/// spiegare (null: nessuna spiegazione per ora). Il controllo riceve il mouse senza fermare i clic dei genitori.
|
||||
/// <paramref name="hint"/> (già tradotto) compare in fondo, per esempio che un clic apre un pannello.
|
||||
/// <paramref name="shown"/> dà il numero che il controllo mostra (nell'unità della spiegazione), quando può
|
||||
/// essere di un altro momento della giornata: se differisce da quello spiegato il tooltip lo dice.
|
||||
/// </summary>
|
||||
public static void Attach(Control control, Func<ExplainTarget?> target, string hint = "")
|
||||
public static void Attach(Control control, Func<ExplainTarget?> target, string hint = "", Func<double?>? shown = null)
|
||||
{
|
||||
var hook = new Hook(control, target, hint, shown);
|
||||
if (control.MouseFilter == MouseFilterEnum.Ignore) control.MouseFilter = MouseFilterEnum.Pass;
|
||||
control.MouseEntered += () => Instance?.Enter(control, target, hint);
|
||||
control.MouseExited += () => Instance?.Leave(control);
|
||||
control.MouseEntered += () => Instance?.Enter(hook);
|
||||
control.MouseExited += () => Instance?.Leave(hook);
|
||||
control.TreeEntered += () =>
|
||||
{
|
||||
if (!Hooks.Contains(hook)) Hooks.Add(hook);
|
||||
};
|
||||
control.TreeExiting += () => Hooks.Remove(hook);
|
||||
if (control.IsInsideTree()) Hooks.Add(hook);
|
||||
}
|
||||
|
||||
private void Enter(Control control, Func<ExplainTarget?> target, string hint)
|
||||
private static (byte, int, int)? KeyOf(Hook hook) =>
|
||||
hook.Target() is { Subject: not ExplainSubject.None } t ? ((byte)t.Subject, t.A, t.B) : null;
|
||||
|
||||
private void Enter(Hook hook)
|
||||
{
|
||||
_hover = control;
|
||||
_target = target;
|
||||
_hint = hint;
|
||||
if (_hook == hook)
|
||||
{
|
||||
_lost = false;
|
||||
return;
|
||||
}
|
||||
// il sostituto di un controllo ricostruito, con la stessa spiegazione: il tooltip resta aperto
|
||||
if (_hook is not null && _hasKey && KeyOf(hook) == _key)
|
||||
{
|
||||
Adopt(hook);
|
||||
return;
|
||||
}
|
||||
_hook = hook;
|
||||
_lost = false;
|
||||
_lostFor = 0;
|
||||
_wait = 0;
|
||||
_hasKey = false;
|
||||
_shown = null;
|
||||
_shownVersion = -1;
|
||||
_dirty = true;
|
||||
Visible = false;
|
||||
}
|
||||
|
||||
private void Leave(Control control)
|
||||
private void Leave(Hook hook)
|
||||
{
|
||||
if (_hover != control) return;
|
||||
_hover = null;
|
||||
_target = null;
|
||||
if (_hook != hook) return;
|
||||
// tolto dall'albero o in via di liberazione: il pannello lo sta ricostruendo, si cerca il sostituto
|
||||
if (Doomed(hook.Control)) _lost = true;
|
||||
else Close();
|
||||
}
|
||||
|
||||
private void Adopt(Hook hook)
|
||||
{
|
||||
_hook = hook;
|
||||
_lost = false;
|
||||
_lostFor = 0;
|
||||
}
|
||||
|
||||
private void Close()
|
||||
{
|
||||
_hook = null;
|
||||
_lost = false;
|
||||
_hasKey = false;
|
||||
Visible = false;
|
||||
}
|
||||
|
||||
/// <summary>Il controllo non c'è più o sta per essere liberato (lui o un suo antenato).</summary>
|
||||
private static bool Doomed(Control c)
|
||||
{
|
||||
if (!IsInstanceValid(c) || !c.IsInsideTree()) return true;
|
||||
for (Node? n = c; n is not null; n = n.GetParent())
|
||||
{
|
||||
if (n.IsQueuedForDeletion()) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Il controllo agganciato, vivo e visibile, sotto il puntatore con la stessa spiegazione (il più piccolo).</summary>
|
||||
private Hook? Replacement()
|
||||
{
|
||||
Hook? best = null;
|
||||
float area = float.MaxValue;
|
||||
foreach (var h in Hooks)
|
||||
{
|
||||
var c = h.Control;
|
||||
if (Doomed(c) || !c.IsVisibleInTree()) continue;
|
||||
var rect = c.GetGlobalRect();
|
||||
if (!rect.HasPoint(c.GetGlobalMousePosition())) continue;
|
||||
if (_hasKey && KeyOf(h) != _key) continue;
|
||||
float a = rect.Size.X * rect.Size.Y;
|
||||
if (a >= area) continue;
|
||||
area = a;
|
||||
best = h;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (_hover is null || _target is null) return;
|
||||
if (!IsInstanceValid(_hover) || !_hover.IsVisibleInTree())
|
||||
if (_hook is null) return;
|
||||
var control = _hook.Control;
|
||||
if (_lost || Doomed(control))
|
||||
{
|
||||
Leave(_hover);
|
||||
if (Replacement() is { } next) Adopt(next);
|
||||
else
|
||||
{
|
||||
_lostFor += delta;
|
||||
if (_lostFor > ReplaceGrace) Close();
|
||||
return;
|
||||
}
|
||||
control = _hook.Control;
|
||||
}
|
||||
else if (!control.IsVisibleInTree() || !control.GetGlobalRect().HasPoint(control.GetGlobalMousePosition()))
|
||||
{
|
||||
// nascosto, oppure il puntatore è uscito senza che il controllo l'abbia mai saputo (sostituto adottato)
|
||||
Close();
|
||||
return;
|
||||
}
|
||||
_wait += delta;
|
||||
_sinceRequest += delta;
|
||||
if (_wait < OpenDelay) return;
|
||||
if (_target() is not { Subject: not ExplainSubject.None } t)
|
||||
if (_hook.Target() is not { Subject: not ExplainSubject.None } t)
|
||||
{
|
||||
Visible = false;
|
||||
return;
|
||||
}
|
||||
var key = ((byte)t.Subject, t.A, t.B);
|
||||
var w = _session.World;
|
||||
if (key != _key)
|
||||
{
|
||||
_key = key;
|
||||
_sinceRequest = double.MaxValue;
|
||||
_shown = null;
|
||||
_shownVersion = -1;
|
||||
}
|
||||
var e = w.Explanations.GetValueOrDefault(key);
|
||||
// una spiegazione di un giorno passato si mostra finché arriva quella di oggi
|
||||
bool stale = e is null || e.Day < Fmt.Today(w);
|
||||
if (stale && _sinceRequest >= RequestInterval && _session.IsOpen)
|
||||
ulong now = Time.GetTicksMsec();
|
||||
_requests.TryGetValue(key, out var last);
|
||||
bool recent = last.At > 0 && now - last.At < RequestIntervalMs;
|
||||
if (!_hasKey || key != _key)
|
||||
{
|
||||
_sinceRequest = 0;
|
||||
_hasKey = true;
|
||||
_key = key;
|
||||
// quella in cache vale solo se è la risposta a una richiesta di meno di un secondo fa
|
||||
_fresh = e is not null && recent && !ReferenceEquals(e, last.Before);
|
||||
_baseline = e;
|
||||
_shown = null;
|
||||
_dirty = true;
|
||||
}
|
||||
if (!_fresh && e is not null && !ReferenceEquals(e, _baseline)) _fresh = true;
|
||||
// a ogni apertura e poi al più una volta al secondo per valore, finché il puntatore resta
|
||||
if (!recent && _session.IsOpen)
|
||||
{
|
||||
if (_requests.Count > 64) Prune(now);
|
||||
_requests[key] = (now, e);
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Explain, Target = t.A, Subject = (byte)t.Subject, Arg = t.B });
|
||||
}
|
||||
if (!ReferenceEquals(e, _shown) || _shownVersion < 0)
|
||||
if (_dirty || !ReferenceEquals(e, _shown) || _fresh != _shownFresh)
|
||||
{
|
||||
_dirty = false;
|
||||
_shown = e;
|
||||
_shownVersion = w.ExplanationVersion;
|
||||
_shownFresh = _fresh;
|
||||
Rebuild(w, e, t);
|
||||
// il riquadro si misura al prossimo fotogramma, a impaginazione fatta: niente salti di lato
|
||||
_settling = true;
|
||||
return;
|
||||
}
|
||||
if (_settling)
|
||||
{
|
||||
_settling = false;
|
||||
Size = Vector2.Zero;
|
||||
}
|
||||
Visible = true;
|
||||
Place();
|
||||
Visible = true;
|
||||
}
|
||||
|
||||
private void Prune(ulong now)
|
||||
{
|
||||
foreach (var k in _requests.Where(r => now - r.Value.At >= RequestIntervalMs).Select(r => r.Key).ToList()) _requests.Remove(k);
|
||||
}
|
||||
|
||||
/// <summary>Vicino al puntatore, in basso a destra, dentro la finestra.</summary>
|
||||
@@ -145,9 +267,14 @@ public partial class WhyTooltip : PanelContainer
|
||||
|
||||
private void Rebuild(Protocol.Client.ClientWorld w, ExplanationReport? e, ExplainTarget t)
|
||||
{
|
||||
foreach (var child in _body.GetChildren()) child.QueueFree();
|
||||
// via subito dall'albero: la misura del riquadro non deve contare i figli vecchi
|
||||
foreach (var child in _body.GetChildren())
|
||||
{
|
||||
_body.RemoveChild(child);
|
||||
child.QueueFree();
|
||||
}
|
||||
Content(w, e, t);
|
||||
if (_hint.Length > 0) _body.AddChild(UiTheme.Text(_hint, 12, Palette.Amber));
|
||||
if (_hook?.Hint is { Length: > 0 } hint) _body.AddChild(UiTheme.Text(hint, 12, Palette.Amber));
|
||||
}
|
||||
|
||||
private void Content(Protocol.Client.ClientWorld w, ExplanationReport? e, ExplainTarget t)
|
||||
@@ -167,7 +294,8 @@ public partial class WhyTooltip : PanelContainer
|
||||
foreach (var n in e.Notes) _body.AddChild(Wrapped(T(n), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
string value = Format(e.Value, e.Unit, (ExplainSubject)e.Subject);
|
||||
var subject = (ExplainSubject)e.Subject;
|
||||
string value = Format(e.Value, e.Unit, subject, headline: true);
|
||||
_body.AddChild(UiTheme.TitleLabel(e.ValueText.Length > 0 ? $"{e.ValueText} ({value})" : value, 28, Palette.Text));
|
||||
if (e.Formula.Length > 0)
|
||||
{
|
||||
@@ -187,7 +315,11 @@ public partial class WhyTooltip : PanelContainer
|
||||
var symbol = UiTheme.Text(term.Symbol.Length >= 3 ? T(term.Symbol) : term.Symbol, 13, Palette.Amber, bold: true);
|
||||
var label = UiTheme.Text(T(term.Label), 13, Palette.TextSecondary);
|
||||
label.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
var v = UiTheme.Text(term.Unit == (byte)ExplainUnit.Text ? Translated(term.Text) : Format(term.Value, term.Unit, (ExplainSubject)e.Subject), 13, bold: true);
|
||||
// un termine numerico può portare anche un testo (il componente del veicolo): si mostrano entrambi
|
||||
string text = term.Unit == (byte)ExplainUnit.Text ? Translated(term.Text)
|
||||
: term.Text.Length > 0 ? $"{Format(term.Value, term.Unit, subject)} · {Translated(term.Text)}"
|
||||
: Format(term.Value, term.Unit, subject);
|
||||
var v = UiTheme.Text(text, 13, bold: true);
|
||||
v.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
foreach (var l in new[] { symbol, label, v }) l.MouseFilter = MouseFilterEnum.Ignore;
|
||||
grid.AddChild(symbol);
|
||||
@@ -197,7 +329,9 @@ public partial class WhyTooltip : PanelContainer
|
||||
_body.AddChild(grid);
|
||||
}
|
||||
foreach (var n in e.Notes) _body.AddChild(Wrapped(T(n), 12, Palette.TextSecondary));
|
||||
if (e.Day < Fmt.Today(w)) _body.AddChild(UiTheme.Text(T("aggiornamento in arrivo…"), 12, Palette.TextSecondary));
|
||||
if (_hook?.Shown?.Invoke() is { } shown && Format(shown, e.Unit, subject, headline: true) != value)
|
||||
_body.AddChild(Wrapped(T("Il numero sul pannello è di inizio giornata; qui c'è quello di adesso."), 12, Palette.TextSecondary));
|
||||
if (!_fresh) _body.AddChild(UiTheme.Text(T("aggiornamento in arrivo…"), 12, Palette.TextSecondary));
|
||||
}
|
||||
|
||||
/// <summary>Nome dell'oggetto: i beni nella lingua dell'interfaccia, il resto com'è (nomi propri dal server).</summary>
|
||||
@@ -222,23 +356,30 @@ public partial class WhyTooltip : PanelContainer
|
||||
_ => text,
|
||||
};
|
||||
|
||||
/// <summary>Formato del valore secondo l'unità, con gli arrotondamenti dei pannelli.</summary>
|
||||
public static string Format(double v, byte unit, ExplainSubject subject)
|
||||
/// <summary>
|
||||
/// Formato del valore secondo l'unità, con gli arrotondamenti dei pannelli: prezzi come la scheda
|
||||
/// dell'industria (<see cref="Fmt.PricePrecise"/>), importi sotto ₤ 1.000 con i centesimi (tariffe), la
|
||||
/// condizione per difetto con il segno di percentuale come le officine (intera nel valore principale, con
|
||||
/// un decimale nei termini).
|
||||
/// </summary>
|
||||
public static string Format(double v, byte unit, ExplainSubject subject, bool headline = false)
|
||||
{
|
||||
if (double.IsPositiveInfinity(v)) return "∞";
|
||||
if (double.IsNegativeInfinity(v)) return "−∞";
|
||||
if (double.IsNaN(v)) return "—";
|
||||
return (ExplainUnit)unit switch
|
||||
{
|
||||
ExplainUnit.Money => new Money((long)Math.Round(v)).ToString(),
|
||||
ExplainUnit.Price => Money.FromCentsRounded(v).ToString(),
|
||||
ExplainUnit.Money => new Money((long)Math.Round(v)).ToString(Math.Abs(v) < 100_000 ? "it2" : "it"),
|
||||
ExplainUnit.Price => Fmt.PricePrecise(v),
|
||||
// l'avanzamento si legge per difetto come nella barra superiore e nella scalata (ADR 0018)
|
||||
ExplainUnit.Percent => subject == ExplainSubject.TierProgress ? Fmt.Progress(v) : Fmt.Pct(v, Math.Abs(v) < 0.01 && v != 0 ? 3 : 1),
|
||||
ExplainUnit.Factor => "× " + Fmt.Number(v, 3),
|
||||
ExplainUnit.Km => Fmt.Number(v, 1) + " km",
|
||||
ExplainUnit.Days => Fmt.Number(v, 1) + " " + T("giorni"),
|
||||
ExplainUnit.Units => Fmt.Number(v, Math.Abs(v - Math.Round(v)) < 1e-9 ? 0 : 1),
|
||||
ExplainUnit.Condition => Fmt.Number(v, 1),
|
||||
ExplainUnit.Condition => headline
|
||||
? Fmt.Number(Math.Floor(v + 1e-9), 0) + "%"
|
||||
: Fmt.Number(Math.Floor(v * 10 + 1e-9) / 10, 1) + "%",
|
||||
ExplainUnit.Years => Fmt.Number(v, 1) + " " + T("anni"),
|
||||
_ => Fmt.Number(v, Math.Abs(v) < 0.01 && v != 0 ? 5 : 3),
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user