F6: scheda industria e connessione, correzioni della revisione

Correzioni dalla revisione della scheda industria e della schermata di
connessione.

- Dati di altre compagnie: la forza lavoro della scheda mostra solo i
  contratti a piedi, quelli della compagnia della sessione e, se
  l'industria è sua, quelli di tutti i vettori, come il Registro degli
  impieghi. Lo stesso filtro vale per provenienze, conteggio e viaggio
  medio.
- Prezzo: «prezzo medio realizzato» mescolava una media mobile dei
  ricavi con i totali del trimestre in corso. Al suo posto c'è il prezzo
  di vendita, cioè il prezzo globale del giorno (SalePrice).
- Avvisi del server: hanno il giorno −1, così il rifiuto di Load o
  NewGame non si confonde più con gli eventi del mondo che arrivano
  mentre si aspetta il Welcome.
- Schermata di connessione:
  - all'apertura avvia la strada scelta l'ultima volta;
  - cambiando strada chiude la sessione dell'altra;
  - senza sessione «Connetti e riprendi» la apre;
  - il cambio di lingua passa la sessione alla schermata nuova;
  - la scelta del salvataggio si tiene per id;
  - Load e nuova partita chiedono conferma;
  - stato del server su 3×2 con la versione del protocollo, salvataggi
    su tre colonne, «Attivo da» che avanza.
- Scheda dell'industria:
  - collegamenti e nodi non collegati sono leggibili;
  - testo per l'industria inattiva;
  - revisione e ammodernamento disabilitati, con il motivo, quando il
    server li rifiuterebbe;
  - l'esito dell'acquisto compare accanto al pulsante;
  - le righe lunghe vanno a capo;
  - «in sede» al posto di «al lavoro ora».
- Gli avvisi dei comandi compaiono anche sulle schermate a tutto
  schermo.
- Pilota automatico:
  - la schermata 20 sta su un suo CanvasLayer sopra l'interfaccia;
  - 12 e 12b sono ora la scheda a tutto schermo.
- Test: pendolari di altri vettori nascosti, Load rifiutato via
  WebSocket, Welcome senza ServerInfo. 202 test, 183 senza i lenti.

Refs #42.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-08 14:29:14 +01:00
1 parent 45462bf9ec
commit 0667a4a544
17 files changed
+514 -156

No files matched your search

@@ -13,19 +13,24 @@ namespace RailEnterprise.Client.Screens;
/// <summary>
/// Schermata iniziale e di connessione (immagine di riferimento 09): a sinistra la mappa decorativa
/// con il titolo, a destra «Dove gira il motore di gioco?» con le due strade (server locale figlio
/// del gioco o server in rete), indirizzo e token, lo stato del server (versione, sistema, tempo di
/// attività, tick al secondo, latenza, client collegati), le partite salvate sul server e i
/// pulsanti per riprendere o iniziare. La schermata apre una sessione di prova per leggere lo stato
/// e l'elenco dei salvataggi; «Connetti e riprendi» la passa alla partita. Nessuna logica di gioco:
/// carica, nuova partita ed elenco sono richieste al server (Load, NewGame, ListSaves).
/// del gioco o server in rete), indirizzo e token, lo stato del server (versione e protocollo,
/// sistema, tempo di attività, tick al secondo, latenza, client collegati), le partite salvate sul
/// server e i pulsanti per riprendere o iniziare. All'apertura la schermata avvia il server locale o
/// verifica il server in rete ricordato, con una sessione di prova che legge lo stato e l'elenco dei
/// salvataggi; «Connetti e riprendi» la passa alla partita (e se non c'è ancora la apre). Nessuna
/// logica di gioco: carica, nuova partita ed elenco sono richieste al server (Load, NewGame,
/// ListSaves). Caricare o creare una partita sostituisce il mondo per tutti: si chiede conferma.
/// </summary>
public partial class ConnectScreen : Control
{
private const string SettingsPath = "user://settings.cfg";
private const double SavesRefreshS = 5;
private const double WelcomeTimeoutS = 30;
/// <summary>Metadato della riga «Partita in corso» nell'elenco dei salvataggi.</summary>
private const string CurrentGame = "";
private readonly GameData _data;
private readonly bool _remember;
private readonly bool _remember, _autoStart;
private GameSession? _handover;
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400", SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly CheckBox _rememberBox = new() { Text = T("Ricorda questo server"), ButtonPressed = true };
@@ -35,28 +40,44 @@ public partial class ConnectScreen : Control
private readonly Button _remoteCard = new() { ToggleMode = true, CustomMinimumSize = new Vector2(0, 112), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly ColorRect _dot = new() { CustomMinimumSize = new Vector2(12, 12), SizeFlagsVertical = SizeFlags.ShrinkCenter };
private readonly Label _stateTitle = UiTheme.Text("", 16, bold: true);
private readonly GridContainer _stateRows = new() { Columns = 2 };
private readonly ItemList _saves = new() { CustomMinimumSize = new Vector2(0, 150), SizeFlagsVertical = SizeFlags.ExpandFill };
private readonly List<string> _saveIds = [];
/// <summary>Stato del server in tre colonne per due righe, didascalia sopra il valore (immagine 09).</summary>
private readonly GridContainer _stateGrid = new() { Columns = 3 };
private readonly List<(Label Caption, Label Value)> _stateCells = [];
/// <summary>Partite salvate in tre colonne: nome, data di gioco, quanto tempo fa.</summary>
private readonly Tree _saves = new()
{
Columns = 3, HideRoot = true, SelectMode = Tree.SelectModeEnum.Row, CustomMinimumSize = new Vector2(0, 150), SizeFlagsVertical = SizeFlags.ExpandFill,
};
private readonly Button _resume = UiTheme.Primary(T("Connetti e riprendi"));
private readonly Button _newGame = new() { Text = T("Nuova partita sul server") };
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly ConfirmationDialog _confirm = new() { Title = T("Sostituire la partita?"), DialogAutowrap = true, MinSize = new Vector2I(520, 0) };
private Action? _onConfirm;
private GameSession? _session;
private bool _busy, _local;
private bool _busy, _local, _closed, _resumeAfterConnect;
private double _sinceSaves = double.MaxValue;
private SaveList? _shownSaves;
/// <summary>Riga scelta nell'elenco, per id del salvataggio (CurrentGame per la partita in corso): l'elenco si riordina a ogni aggiornamento.</summary>
private string _selectedSave = CurrentGame;
private Action<IMessage>? _awaitingWelcome;
private double _waiting;
/// <summary>Stato del server mostrato e istante in cui è arrivato: il tempo di attività avanza da lì.</summary>
private ServerInfo? _infoSeen;
private double _infoAt;
/// <summary>La sessione di prova diventa la partita: la schermata non la chiude più.</summary>
public event Action<GameSession>? PlayRequested;
public event Action<string>? LanguageChanged;
/// <param name="remember">Falso per l'anteprima del collaudo: non legge né scrive le impostazioni.</param>
public ConnectScreen(GameData data, bool remember = true)
/// <param name="autoStart">Avvia subito il server locale o verifica il server ricordato (falso nel collaudo).</param>
/// <param name="handover">Sessione di prova di una schermata precedente (cambio di lingua): la si riprende così com'è.</param>
public ConnectScreen(GameData data, bool remember = true, bool autoStart = true, GameSession? handover = null)
{
_data = data;
_remember = remember;
_autoStart = autoStart;
_handover = handover;
}
/// <summary>Stato e salvataggi sono arrivati dal server (serve al collaudo).</summary>
@@ -117,7 +138,7 @@ public partial class ConnectScreen : Control
ModeCard(_localCard, group, T("Gioca in locale"), T("Server su questo computer, avviato e chiuso con il gioco. Le partite restano qui."));
ModeCard(_remoteCard, group, T("Connetti a un server"), T("Server dedicato in rete, per esempio in Docker su un NAS. Più giocatori, partita sempre accesa."));
_localCard.Pressed += () => SetMode(local: true, start: true);
_remoteCard.Pressed += () => SetMode(local: false, start: false);
_remoteCard.Pressed += () => SetMode(local: false, start: true);
modes.AddChild(_localCard);
modes.AddChild(_remoteCard);
col.AddChild(modes);
@@ -148,20 +169,42 @@ public partial class ConnectScreen : Control
// stato del server
var state = new PanelContainer();
state.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 10, 18));
var stateCol = PanelKit.Column(10);
var stateCol = PanelKit.Column(12);
var stateHead = PanelKit.Row(10);
stateHead.AddChild(_dot);
stateHead.AddChild(_stateTitle);
stateCol.AddChild(stateHead);
_stateRows.AddThemeConstantOverride("h_separation", 24);
_stateRows.AddThemeConstantOverride("v_separation", 6);
stateCol.AddChild(_stateRows);
_stateGrid.AddThemeConstantOverride("h_separation", 24);
_stateGrid.AddThemeConstantOverride("v_separation", 12);
for (int i = 0; i < 6; i++)
{
var cell = PanelKit.Column(2);
cell.SizeFlagsHorizontal = SizeFlags.ExpandFill;
var caption = UiTheme.Text("", 12, Palette.TextSecondary);
var value = UiTheme.Text("", 14, bold: true);
value.AutowrapMode = TextServer.AutowrapMode.WordSmart;
cell.AddChild(caption);
cell.AddChild(value);
_stateGrid.AddChild(cell);
_stateCells.Add((caption, value));
}
stateCol.AddChild(_stateGrid);
state.AddChild(stateCol);
col.AddChild(state);
// partite salvate sul server
// partite salvate sul server: nome, data di gioco, quanto tempo fa
col.AddChild(UiTheme.Text(T("Partite salvate sul server"), 17, bold: true));
_saves.ItemActivated += _ => Resume();
_saves.SetColumnExpand(0, true);
_saves.SetColumnExpandRatio(0, 3);
_saves.SetColumnExpand(1, true);
_saves.SetColumnExpandRatio(1, 2);
_saves.SetColumnExpand(2, true);
_saves.SetColumnExpandRatio(2, 1);
_saves.ItemSelected += () =>
{
if (_saves.GetSelected() is { } item) _selectedSave = item.GetMetadata(0).AsString();
};
_saves.ItemActivated += Resume;
col.AddChild(_saves);
var actions = PanelKit.Row(10);
_resume.CustomMinimumSize = new Vector2(0, 48);
@@ -193,6 +236,18 @@ public partial class ConnectScreen : Control
notice.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(notice);
// conferma prima di sostituire la partita sul server
_confirm.OkButtonText = T("Sostituisci la partita");
_confirm.CancelButtonText = T("Annulla");
_confirm.Confirmed += () =>
{
var action = _onConfirm;
_onConfirm = null;
action?.Invoke();
};
_confirm.Canceled += () => _onConfirm = null;
AddChild(_confirm);
bool remote = false;
if (_remember)
{
@@ -204,7 +259,19 @@ public partial class ConnectScreen : Control
remote = (string)cfg.GetValue("server", "mode", "local") == "remote";
}
}
SetMode(local: !remote, start: false);
if (_handover is not null)
{
// cambio di lingua: la sessione di prova (e il suo server locale) passa a questa schermata
var session = _handover;
_handover = null;
SetMode(local: session.LocalServer is not null, start: false);
Attach(session);
}
else
{
// all'apertura si avvia la strada scelta l'ultima volta, come nell'immagine 09
SetMode(local: !remote, start: _autoStart);
}
ShowState();
}
@@ -215,6 +282,7 @@ public partial class ConnectScreen : Control
card.AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.AmberDark, 10, 0));
card.AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
card.AddThemeStyleboxOverride("hover_pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
card.AddThemeStyleboxOverride("disabled", UiTheme.Box(Palette.Inner, Palette.Border, 10, 0));
var margin = new MarginContainer { MouseFilter = MouseFilterEnum.Ignore };
margin.SetAnchorsPreset(LayoutPreset.FullRect);
foreach (var side in new[] { "left", "right", "top", "bottom" }) margin.AddThemeConstantOverride("margin_" + side, 16);
@@ -235,13 +303,25 @@ public partial class ConnectScreen : Control
// ------------------------------------------------------------------ modalità e sessione di prova
/// <summary>La sessione di prova è della strada scelta: server locale figlio del gioco o server in rete.</summary>
private bool SessionMatchesMode => _session is not null && (_session.LocalServer is not null) == _local;
/// <summary>
/// Cambia strada. La sessione dell'altra strada si chiude (e con lei il server locale), così
/// «Connetti e riprendi» non apre mai la partita della strada non scelta. Con start si avvia il
/// server locale o si verifica il server in rete indicato.
/// </summary>
private void SetMode(bool local, bool start)
{
_local = local;
_localCard.SetPressedNoSignal(local);
_remoteCard.SetPressedNoSignal(!local);
_remoteFields.Visible = !local;
if (start && local && (_session is null || _session.LocalServer is null)) _ = StartLocal();
if (_session is not null && !SessionMatchesMode)
{
_ = Release();
SetStatus("");
}
if (_remember)
{
var cfg = new ConfigFile();
@@ -249,6 +329,11 @@ public partial class ConnectScreen : Control
cfg.SetValue("server", "mode", local ? "local" : "remote");
cfg.Save(SettingsPath);
}
if (start && _session is null && !_busy)
{
if (local) _ = StartLocal();
else if (_address.Text.Trim().Length > 0) SubmitRemote();
}
ShowState();
}
@@ -259,6 +344,7 @@ public partial class ConnectScreen : Control
string? server = LocalServerLauncher.FindServer();
if (server is null)
{
_resumeAfterConnect = false;
SetStatus(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), error: true);
return;
}
@@ -272,15 +358,18 @@ public partial class ConnectScreen : Control
int port = await launcher.StartAsync(server, ProjectSettings.GlobalizePath("user://server"), TimeSpan.FromSeconds(60));
var session = await GameSession.ConnectAsync(_data, new Uri($"ws://127.0.0.1:{port}/ws"), launcher.Token, T("Partita locale"));
session.LocalServer = launcher;
Attach(session);
_busy = false;
if (!Adopt(session, local: true)) return;
SetStatus("");
}
catch (Exception e)
{
launcher.Dispose();
SetStatus($"{T("Partita locale non avviata")}: {e.Message}", error: true);
_busy = false;
_resumeAfterConnect = false;
if (!_closed) SetStatus($"{T("Partita locale non avviata")}: {e.Message}", error: true);
}
_busy = false;
ShowState();
if (!_closed) ShowState();
}
private void SubmitRemote()
@@ -288,6 +377,7 @@ public partial class ConnectScreen : Control
string address = _address.Text.Trim();
if (address.Length == 0)
{
_resumeAfterConnect = false;
SetStatus(T("Indica l'indirizzo del server"), error: true);
return;
}
@@ -295,6 +385,7 @@ public partial class ConnectScreen : Control
if (!url.EndsWith("/ws", StringComparison.Ordinal)) url = url.TrimEnd('/') + "/ws";
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
_resumeAfterConnect = false;
SetStatus(T("Indirizzo non valido"), error: true);
return;
}
@@ -321,15 +412,41 @@ public partial class ConnectScreen : Control
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
Attach(await GameSession.ConnectAsync(_data, uri, token, uri.Host, cts.Token));
var session = await GameSession.ConnectAsync(_data, uri, token, uri.Host, cts.Token);
_busy = false;
if (!Adopt(session, local: false)) return;
SetStatus("");
}
catch (Exception e)
{
SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", error: true);
_busy = false;
_resumeAfterConnect = false;
if (!_closed) SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", error: true);
}
_busy = false;
ShowState();
if (!_closed) ShowState();
}
/// <summary>
/// Prende la sessione appena aperta, se la schermata è ancora aperta e sulla stessa strada;
/// altrimenti la chiude (con il suo server locale). Con «Connetti e riprendi» in attesa si entra
/// subito in partita.
/// </summary>
private bool Adopt(GameSession session, bool local)
{
if (_closed || _local != local)
{
_resumeAfterConnect = false;
_ = session.DisposeAsync();
return false;
}
Attach(session);
if (_resumeAfterConnect)
{
_resumeAfterConnect = false;
Play();
return false;
}
return true;
}
private void Attach(GameSession session)
@@ -352,17 +469,20 @@ public partial class ConnectScreen : Control
await s.DisposeAsync();
}
/// <summary>Consegna la sessione di prova a chi la chiede (Main, alla chiusura del gioco).</summary>
/// <summary>Consegna la sessione di prova a chi la chiede (Main: partita, cambio di lingua, chiusura del gioco).</summary>
public GameSession? TakeSession()
{
var s = _session;
if (s is not null) s.MessageApplied -= OnMessage;
_session = null;
_awaitingWelcome = null;
return s;
}
public override void _ExitTree()
{
// una connessione ancora in corso si chiude da sola quando arriva (Adopt)
_closed = true;
if (_session is not null) _ = Release();
}
@@ -372,6 +492,7 @@ public partial class ConnectScreen : Control
{
if (_session is null) return;
_session.Poll();
if (_session is null) return; // Play durante Poll: la sessione è passata alla partita
if (!_session.IsOpen)
{
SetStatus(T("Il server ha chiuso la connessione"), error: true);
@@ -398,27 +519,65 @@ public partial class ConnectScreen : Control
private void Resume()
{
if (_session is null || _awaitingWelcome is not null) return;
int index = _saves.GetSelectedItems() is { Length: > 0 } sel ? sel[0] : 0;
if (index <= 0 || index > _saveIds.Count)
if (_busy || _awaitingWelcome is not null) return;
if (_session is null)
{
// nessuna sessione ancora: «Connetti e riprendi» apre la strada scelta ed entra in partita
_resumeAfterConnect = true;
if (_local) _ = StartLocal();
else SubmitRemote();
return;
}
if (!SessionMatchesMode) return;
string id = _selectedSave;
var save = _shownSaves?.Saves.FirstOrDefault(s => s.SaveId == id);
if (id == CurrentGame || save is null)
{
Play();
return;
}
string id = _saveIds[index - 1];
SetStatus($"{T("Caricamento di")} {_saves.GetItemText(index)}…");
AwaitWelcome();
_session.Send(new Load { SaveId = id });
Confirm(string.Format(T("Il server sostituirà la partita in corso ({0}) con il salvataggio «{1}» per tutti i client collegati ({2}). Quello che non è stato salvato andrà perso."),
CurrentGameText(), save.Name, ConnectedText()), () =>
{
if (_session is null || _awaitingWelcome is not null) return;
SetStatus($"{T("Caricamento di")} {save.Name}…");
AwaitWelcome();
_session.Send(new Load { SaveId = id });
});
}
private void NewGameOnServer()
{
if (_session is null || _awaitingWelcome is not null) return;
var summary = _session.World.Summary;
SetStatus(T("Creazione della nuova partita sul server…"));
AwaitWelcome();
// il seme lo sceglie il client: la generazione resta deterministica sul server
_session.Send(new NewGame { Seed = (ulong)Time.GetUnixTimeFromSystem() ^ (summary?.Seed ?? 0), SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = _session.Difficulty });
if (_session is null || _awaitingWelcome is not null || !SessionMatchesMode) return;
Confirm(string.Format(T("Il server sostituirà la partita in corso ({0}) con una partita nuova per tutti i client collegati ({1}). Quello che non è stato salvato andrà perso."),
CurrentGameText(), ConnectedText()), () =>
{
if (_session is null || _awaitingWelcome is not null) return;
var summary = _session.World.Summary;
SetStatus(T("Creazione della nuova partita sul server…"));
AwaitWelcome();
// il seme lo sceglie il client: la generazione resta deterministica sul server
_session.Send(new NewGame { Seed = (ulong)Time.GetUnixTimeFromSystem() ^ (summary?.Seed ?? 0), SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = _session.Difficulty });
});
}
private void Confirm(string text, Action action)
{
_onConfirm = action;
_confirm.DialogText = text;
_confirm.PopupCentered();
}
private string CurrentGameText()
{
var summary = _session?.World.Summary;
return summary is null ? "—" : $"{summary.CompanyName}, {summary.Date}";
}
private string ConnectedText()
{
var info = _session?.World.Server;
return info is null ? "?" : info.Sessions.ToString();
}
/// <summary>Dopo Load o NewGame il server rimanda il Welcome a tutti: allora si entra in partita.</summary>
@@ -431,9 +590,10 @@ public partial class ConnectScreen : Control
_awaitingWelcome = null;
Play();
}
else if (m is Notification { Event.Severity: >= (byte)EventSeverity.Warning } note)
else if (m is Notification { Event.Day: < 0 } note)
{
// caricamento o creazione rifiutati: il server risponde con un avviso
// caricamento o creazione rifiutati: l'avviso del server ha il giorno −1; gli eventi
// del mondo (giorno della partita) arrivano anche qui e non interrompono l'attesa
_awaitingWelcome = null;
SetStatus(note.Event.Text, error: true);
}
@@ -459,6 +619,12 @@ public partial class ConnectScreen : Control
{
var info = _session?.World.Server;
var summary = _session?.World.Summary;
double now = Time.GetTicksMsec() / 1000.0;
if (!ReferenceEquals(info, _infoSeen))
{
_infoSeen = info;
_infoAt = now;
}
string title;
Color dot;
if (_busy)
@@ -468,62 +634,67 @@ public partial class ConnectScreen : Control
}
else if (_session is not null)
{
title = $"{T("Collegato a")} {_session.ServerLabel}";
title = $"{T("Server raggiungibile")} · {_session.ServerLabel}";
dot = Palette.Ok;
}
else
{
title = _local ? T("Server locale spento: scegli «Gioca in locale» per avviarlo") : T("Non collegato");
title = _local ? T("Server locale spento: «Connetti e riprendi» lo avvia") : T("Non collegato");
dot = Palette.TextSecondary;
}
_stateTitle.Text = title;
_dot.Color = dot;
var rows = new List<(string, string)>
var cells = new (string, string)[]
{
(T("Versione"), info is null ? "—" : $"{info.Version} · {T("dati compatibili")}"),
(T("Versione"), info is null ? "—" : $"{info.Version}, {T("protocollo")} {Frame.ProtocolVersion}"),
(T("Sistema"), info is null ? "—" : info.Os + (info.Container ? " · Docker" : "") + (info.Local ? " · " + T("locale") : "")),
(T("Attivo da"), info is null ? "—" : Uptime(info.UptimeSeconds)),
(T("Attivo da"), info is null ? "—" : Uptime(info.UptimeSeconds + (long)(now - _infoAt))),
(T("Simulazione"), info is null || info.TickMs <= 0 ? "—" : $"{Fmt.Number(1000 / info.TickMs, 0)} {T("tick al secondo")}" + (summary is null ? "" : $" · {summary.Date}")),
(T("Latenza"), _session is null || _session.LatencyMs <= 0 ? "—" : $"{Fmt.Number(_session.LatencyMs, 0)} ms"),
(T("Client collegati"), info is null ? "—" : $"{info.Sessions} / {info.MaxSessions}"),
};
if (_stateRows.GetChildCount() != rows.Count * 2)
for (int i = 0; i < cells.Length && i < _stateCells.Count; i++)
{
foreach (var c in _stateRows.GetChildren()) c.QueueFree();
foreach (var (caption, _) in rows)
{
_stateRows.AddChild(UiTheme.Text(caption, 13, Palette.TextSecondary));
_stateRows.AddChild(UiTheme.Text("", 13, bold: true));
}
_stateCells[i].Caption.Text = cells[i].Item1;
_stateCells[i].Value.Text = cells[i].Item2;
}
for (int i = 0; i < rows.Count; i++)
{
((Label)_stateRows.GetChild(i * 2)).Text = rows[i].Item1;
((Label)_stateRows.GetChild(i * 2 + 1)).Text = rows[i].Item2;
}
bool ready = _session is not null && !_busy && _awaitingWelcome is null;
_resume.Disabled = !ready;
bool ready = SessionMatchesMode && !_busy && _awaitingWelcome is null;
// senza sessione «Connetti e riprendi» apre la connessione; «Nuova partita» vuole il server collegato
_resume.Disabled = _busy || _awaitingWelcome is not null || (_session is not null && !ready);
_newGame.Disabled = !ready;
_probe.Disabled = _busy;
_localCard.Disabled = _busy;
_remoteCard.Disabled = _busy;
}
/// <summary>Elenco ricostruito a ogni aggiornamento: la riga scelta si ritrova per id, non per posizione.</summary>
private void ShowSaves()
{
var w = _session!.World;
_shownSaves = w.Saves;
int selected = _saves.GetSelectedItems() is { Length: > 0 } sel ? sel[0] : 0;
_saves.Clear();
_saveIds.Clear();
string company = w.Summary?.CompanyName ?? "";
_saves.AddItem($"{T("Partita in corso")} · {company} · {w.Summary?.Date ?? ""}");
var root = _saves.CreateItem();
var current = _saves.CreateItem(root);
current.SetText(0, $"{T("Partita in corso")} · {w.Summary?.CompanyName ?? ""}");
current.SetText(1, w.Summary?.Date ?? "");
current.SetText(2, T("in corso"));
current.SetMetadata(0, CurrentGame);
current.SetCustomColor(2, Palette.Ok);
TreeItem selected = current;
double now = Time.GetUnixTimeFromSystem();
foreach (var s in (_shownSaves?.Saves ?? []).OrderByDescending(s => s.SavedUnixMs))
foreach (var s in (_shownSaves?.Saves ?? []).OrderByDescending(s => s.SavedUnixMs).ThenBy(s => s.SaveId, StringComparer.Ordinal))
{
_saveIds.Add(s.SaveId);
string kind = s.Autosave ? $" ({T("automatico")})" : "";
_saves.AddItem($"{s.Name}{kind} · {s.GameDate} · {Ago(now - s.SavedUnixMs / 1000.0)}");
var item = _saves.CreateItem(root);
item.SetText(0, s.Autosave ? $"{s.Name} ({T("automatico")})" : s.Name);
item.SetText(1, s.GameDate);
item.SetText(2, Ago(now - s.SavedUnixMs / 1000.0));
item.SetMetadata(0, s.SaveId);
for (int c = 1; c < 3; c++) item.SetCustomColor(c, Palette.TextSecondary);
if (s.SaveId == _selectedSave) selected = item;
}
_saves.Select(Math.Clamp(selected, 0, _saves.ItemCount - 1));
// salvataggio scelto sparito dall'elenco: si torna alla partita in corso
_selectedSave = selected.GetMetadata(0).AsString();
selected.Select(0);
}
private static string Uptime(long seconds)