using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
///
/// 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 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 . 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.
///
public partial class WhyTooltip : PanelContainer
{
/// Tooltip della schermata di gioco (null fuori partita: gli agganci restano muti).
public static WhyTooltip? Instance { get; private set; }
/// Ritardo prima dell'apertura (secondi).
private const double OpenDelay = 0.45;
/// Intervallo minimo tra due richieste della stessa spiegazione (millisecondi).
private const ulong RequestIntervalMs = 1000;
/// Tempo per trovare il sostituto di un controllo ricostruito prima di chiudere (secondi).
private const double ReplaceGrace = 0.3;
private const float MaxWidth = 440;
/// Aggancio di un controllo: bersaglio, suggerimento e, se serve, il valore che il controllo mostra.
private sealed record Hook(Control Control, Func Target, string Hint, Func? Shown);
/// Agganci dei controlli nell'albero, per ritrovare il sostituto di un controllo ricostruito.
private static readonly List Hooks = [];
private readonly GameSession _session;
private readonly VBoxContainer _body = new();
private Hook? _hook;
/// Il controllo agganciato è stato tolto o sta per esserlo: si cerca il sostituto sotto il puntatore.
private bool _lost;
private double _lostFor;
private (byte Subject, int Target, int Arg) _key;
private bool _hasKey;
private double _wait;
/// Spiegazione in cache all'apertura: finché non ne arriva un'altra si mostra come in aggiornamento.
private ExplanationReport? _baseline;
private bool _fresh;
private ExplanationReport? _shown;
private bool _shownFresh;
private bool _dirty = true;
private bool _settling;
/// Per valore: istante dell'ultima richiesta e spiegazione in cache in quel momento.
private readonly Dictionary<(byte, int, int), (ulong At, ExplanationReport? Before)> _requests = [];
public WhyTooltip(GameSession session)
{
_session = session;
Visible = false;
MouseFilter = MouseFilterEnum.Ignore;
TopLevel = true;
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Amber, 8, 14));
_body.AddThemeConstantOverride("separation", 6);
_body.MouseFilter = MouseFilterEnum.Ignore;
AddChild(_body);
}
public override void _EnterTree() => Instance = this;
public override void _ExitTree()
{
if (Instance == this) Instance = null;
}
///
/// Aggancia il tooltip a un controllo: al passaggio del mouse chiede a quale valore
/// spiegare (null: nessuna spiegazione per ora). Il controllo riceve il mouse senza fermare i clic dei genitori.
/// (già tradotto) compare in fondo, per esempio che un clic apre un pannello.
/// 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.
///
public static void Attach(Control control, Func target, string hint = "", Func? shown = null)
{
var hook = new Hook(control, target, hint, shown);
if (control.MouseFilter == MouseFilterEnum.Ignore) control.MouseFilter = MouseFilterEnum.Pass;
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 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)
{
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;
_dirty = true;
Visible = false;
}
private void Leave(Hook hook)
{
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;
}
/// Il controllo non c'è più o sta per essere liberato (lui o un suo antenato).
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;
}
/// Il controllo agganciato, vivo e visibile, sotto il puntatore con la stessa spiegazione (il più piccolo).
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 (_hook is null) return;
var control = _hook.Control;
if (_lost || Doomed(control))
{
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;
if (_wait < OpenDelay) return;
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;
var e = w.Explanations.GetValueOrDefault(key);
ulong now = Time.GetTicksMsec();
_requests.TryGetValue(key, out var last);
bool recent = last.At > 0 && now - last.At < RequestIntervalMs;
if (!_hasKey || key != _key)
{
_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 (_dirty || !ReferenceEquals(e, _shown) || _fresh != _shownFresh)
{
_dirty = false;
_shown = e;
_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;
}
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);
}
/// Vicino al puntatore, in basso a destra, dentro la finestra.
private void Place()
{
var view = GetViewportRect().Size;
var mouse = GetViewport().GetMousePosition();
var size = GetCombinedMinimumSize();
Size = size;
float x = mouse.X + 18, y = mouse.Y + 22;
if (x + size.X > view.X - 8) x = Math.Max(8, mouse.X - size.X - 12);
if (y + size.Y > view.Y - 8) y = Math.Max(8, mouse.Y - size.Y - 12);
Position = new Vector2(x, y);
}
private void Rebuild(Protocol.Client.ClientWorld w, ExplanationReport? e, ExplainTarget t)
{
// 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 (_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)
{
if (e is null)
{
_body.AddChild(UiTheme.Text(T("Perché questo valore"), 13, Palette.TextSecondary, bold: true));
_body.AddChild(UiTheme.Text(T("in arrivo…"), 14, Palette.TextSecondary));
return;
}
var head = UiTheme.Text(e.Title.Length > 0 ? T(e.Title) : T("Perché questo valore"), 15, Palette.AmberLight, bold: true);
_body.AddChild(head);
string name = SubjectName(w, e, t);
if (name.Length > 0) _body.AddChild(Wrapped(name, 13, Palette.TextSecondary));
if (!e.Available)
{
foreach (var n in e.Notes) _body.AddChild(Wrapped(T(n), 13, Palette.TextSecondary));
return;
}
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)
{
var box = new PanelContainer { MouseFilter = MouseFilterEnum.Ignore };
box.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 6, 10));
box.AddChild(Wrapped(T(e.Formula), 13, Palette.Text));
_body.AddChild(box);
}
if (e.Terms.Count > 0)
{
var grid = new GridContainer { Columns = 3, MouseFilter = MouseFilterEnum.Ignore };
grid.AddThemeConstantOverride("h_separation", 10);
grid.AddThemeConstantOverride("v_separation", 3);
foreach (var term in e.Terms)
{
// i simboli che sono parole (soglia, quota, prezzo…) si traducono, le lettere restano come nella formula
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;
// 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);
grid.AddChild(label);
grid.AddChild(v);
}
_body.AddChild(grid);
}
foreach (var n in e.Notes) _body.AddChild(Wrapped(T(n), 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));
}
/// Nome dell'oggetto: i beni nella lingua dell'interfaccia, il resto com'è (nomi propri dal server).
private static string SubjectName(Protocol.Client.ClientWorld w, ExplanationReport e, ExplainTarget t)
{
bool en = TranslationServer.GetLocale().StartsWith("en");
string Good(int g) => g >= 0 && g < w.Data.Goods.Count ? (en ? w.Data.Goods[g].NameEn : w.Data.Goods[g].NameIt) : "";
return t.Subject switch
{
ExplainSubject.GlobalPrice => Good(t.A),
ExplainSubject.LocalPrice => w.Industries.TryGetValue(t.B, out var ind) ? $"{Good(t.A)} · {ind.Name}" : e.Name,
_ => e.Name,
};
}
/// Testi dei valori testuali: componenti dei veicoli tradotti, il resto (rating, nomi, anni) com'è.
private static string Translated(string text) => text switch
{
"engine" => T("motore"),
"brakes" => T("freni"),
"body" => T("cassa"),
_ => text,
};
///
/// Formato del valore secondo l'unità, con gli arrotondamenti dei pannelli: prezzi come la scheda
/// dell'industria (), 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).
///
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(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 => 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),
};
}
private static Label Wrapped(string text, int size, Color color)
{
var l = UiTheme.Text(text, size, color);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
l.CustomMinimumSize = new Vector2(MaxWidth - 40, 0);
l.MouseFilter = MouseFilterEnum.Ignore;
return l;
}
}