using CommunityToolkit.Mvvm.ComponentModel;
using XFEEDToolBox.Core.Galaxy;
using XFEEDToolBox.Core.Navigation;
namespace XFEEDToolBox.ViewModels;
public partial class ToolboxViewModel
{
[ObservableProperty] public partial IReadOnlyList<GalaxyHistoricalTradeFlow> GalaxyHistoricalTradeFlows { get; set; }=[];
[ObservableProperty] public partial IReadOnlyList<GalaxyFilterChoice> GalaxyHistoricalTradeChoices { get; set; }=[];
[ObservableProperty] public partial string GalaxyHistoricalTradeStatus { get; set; }="历史贸易流默认关闭;只读取账号原缓存,不代表实时流量。";
private CancellationTokenSource? galaxyHistoricalTradeStop;
private Task? galaxyHistoricalTradeTask;
private string galaxyHistoricalTradeBinding="";
private readonly Dictionary<long,DateTimeOffset> galaxyHistoricalTradeAttempts=[];
private IReadOnlyDictionary<long,OriginalTradeDataSnapshot>? historicalChoicesSource,historicalEdgesSource;
private IReadOnlySet<string>? historicalEdgesCommodities;
private GalaxyTradeFlowSource historicalEdgesKind;
private ulong historicalEdgesCommander;
private bool historicalEdgesShown;
private IReadOnlyList<GalaxyHistoricalTradeEdge> historicalEdges=[];
private string HistoricalTradeBinding()=>GalaxyFilter.ShowHistoricalTradeFlows
?$"{CurrentPlayer.CommanderId}|{CurrentPlayer.LoadGameAt:O}|{(runtime.FlightDriver as NativeFlightControlDriver)?.ProcessId}|{GalaxyFilter.HistoricalTradeSource}|{(GalaxyFilter.HistoricalTradeCommodities is {} selected?string.Join(',',selected.Order(StringComparer.Ordinal)):"*")}":"";
private GalaxyHistoricalTradeProjection RefreshHistoricalTradeProjection()
{
var accountReady=galaxyMetadataAccount==CurrentPlayer.CommanderId&&galaxyOriginalVisited is not null;
var source=accountReady?galaxyOriginalTrades:null;var commander=accountReady?galaxyOriginalVisited!.CommanderId:0;
if(!ReferenceEquals(historicalChoicesSource,source))
{
historicalChoicesSource=source;
var choices=(source?.Values??[]).SelectMany(s=>s.Routes).Select(r=>new GalaxyFilterChoice(GalaxyMapFilter.Normalize(r.Commodity),r.Commodity)).DistinctBy(c=>c.Key).OrderBy(c=>c.Label,StringComparer.OrdinalIgnoreCase).ToArray();
if(!GalaxyHistoricalTradeChoices.SequenceEqual(choices))GalaxyHistoricalTradeChoices=choices;
}
if(!ReferenceEquals(historicalEdgesSource,source)||!ReferenceEquals(historicalEdgesCommodities,GalaxyFilter.HistoricalTradeCommodities)||historicalEdgesCommander!=commander||historicalEdgesShown!=GalaxyFilter.ShowHistoricalTradeFlows||historicalEdgesKind!=GalaxyFilter.HistoricalTradeSource)
{
historicalEdgesSource=source;historicalEdgesCommodities=GalaxyFilter.HistoricalTradeCommodities;historicalEdgesCommander=commander;historicalEdgesShown=GalaxyFilter.ShowHistoricalTradeFlows;historicalEdgesKind=GalaxyFilter.HistoricalTradeSource;
historicalEdges=historicalEdgesShown&&source is not null?GalaxyHistoricalTrade.Select(source.Values,commander,historicalEdgesKind,historicalEdgesCommodities):[];
}
var edges=historicalEdges;
GalaxyHistoricalTradeProjection projection;
if(edges.Count==0)projection=new(edges,[],[]);
else
{
var required=edges.SelectMany(e=>new[]{e.FromSystemAddress,e.ToSystemAddress}).ToHashSet();
var systems=galaxyCache.Values.Where(s=>s.SystemAddress is {} id&&required.Contains(id)&&s.Position.IsValid).GroupBy(s=>s.SystemAddress!.Value)
.ToDictionary(g=>g.Key,g=>g.OrderByDescending(s=>s.Source=="游戏银河目录").First());
projection=GalaxyHistoricalTrade.Project(edges,systems);
}
if(!GalaxyHistoricalTradeFlows.SequenceEqual(projection.Flows))GalaxyHistoricalTradeFlows=projection.Flows;
if(!GalaxyFilter.ShowHistoricalTradeFlows)GalaxyHistoricalTradeStatus="历史贸易流已关闭;名称/数量仅来自账号缓存,未查询实时流量。";
else if(!accountReady)GalaxyHistoricalTradeStatus="尚无当前账号原CommanderId证明;历史贸易流保持未知。";
else
{
var dates=projection.OldestCache is {} oldest&&projection.NewestCache is {} newest?$"缓存 {oldest.ToLocalTime():yyyy-MM-dd HH:mm}"+(oldest!=newest?$" — {newest.ToLocalTime():yyyy-MM-dd HH:mm}":""):"暂无所选历史缓存记录";
GalaxyHistoricalTradeStatus=$"历史贸易流 · {projection.Flows.Count:N0} / {edges.Count:N0} 条已解析 · {projection.MissingSystemAddresses.Count:N0} 个端点待确认。\n{dates};非实时流量,不证明完整覆盖。";
}
return projection;
}
private void QueueGalaxyHistoricalTradeFlows()
{
var binding=HistoricalTradeBinding();
if(binding!=galaxyHistoricalTradeBinding)
{galaxyHistoricalTradeBinding=binding;galaxyHistoricalTradeStop?.Cancel();galaxyHistoricalTradeStop?.Dispose();galaxyHistoricalTradeStop=null;galaxyHistoricalTradeAttempts.Clear();}
var projection=RefreshHistoricalTradeProjection();
if(binding.Length==0||projection.MissingSystemAddresses.Count==0||galaxyHistoricalTradeTask is {IsCompleted:false}&&galaxyHistoricalTradeStop?.IsCancellationRequested==false)return;
if(NavigationActive||!CurrentPlayer.InGame||runtime.FlightDriver is not NativeFlightControlDriver{SupportsGalaxyResolveAddress:true} driver||NativeGalaxy() is not {} catalog)
{if(projection.MissingSystemAddresses.Count>0)GalaxyHistoricalTradeStatus+="\n原游戏地址解析尚未连接;不会猜测端点坐标。";return;}
galaxyHistoricalTradeStop=CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);
galaxyHistoricalTradeTask=ResolveHistoricalTradeEndpointsAsync(binding,driver.ProcessId,catalog,galaxyHistoricalTradeStop.Token);
}
private async Task ResolveHistoricalTradeEndpointsAsync(string binding,int processId,NativeGalaxyCatalog catalog,CancellationToken token)
{
bool Latest()=>!token.IsCancellationRequested&&HistoricalTradeBinding()==binding&&runtime.FlightDriver is NativeFlightControlDriver current&¤t.ProcessId==processId;
try
{
while(Latest())
{
if(NavigationActive||!CurrentPlayer.InGame)return;
var projection=RefreshHistoricalTradeProjection();if(projection.MissingSystemAddresses.Count==0)return;
var now=DateTimeOffset.UtcNow;
var pending=projection.MissingSystemAddresses.Where(a=>!galaxyHistoricalTradeAttempts.TryGetValue(a,out var at)||now-at>=TimeSpan.FromSeconds(30))
.OrderBy(a=>galaxyHistoricalTradeAttempts.GetValueOrDefault(a)).Take(8).ToArray();
if(pending.Length==0){await Task.Delay(1000,token);continue;}
foreach(var address in pending)
{
if(!Latest())return;galaxyHistoricalTradeAttempts[address]=DateTimeOffset.UtcNow;
try
{var resolved=await catalog.ResolveAddressAsync(address,token);if(!Latest())return;RememberGalaxy(resolved);}
catch(Exception error)when(error is KeyNotFoundException or InvalidDataException or IOException or TimeoutException)
{if(!Latest())return;GalaxyHistoricalTradeStatus="历史贸易流端点解析待确认:"+error.Message+";不会猜测坐标。";}
}
if(!Latest())return;RefreshHistoricalTradeProjection();await Task.Delay(250,token);
}
}
catch(OperationCanceledException){ }
catch(Exception error)when(error is InvalidOperationException or System.Text.Json.JsonException)
{if(Latest())GalaxyHistoricalTradeStatus="历史贸易流地址来源尚未确认:"+error.Message;}
}
}
using CommunityToolkit.Mvvm.ComponentModel;
using XFEEDToolBox.Core.Galaxy;
using XFEEDToolBox.Core.Navigation;
namespace XFEEDToolBox.ViewModels;
public partial class ToolboxViewModel
{
[ObservableProperty] public partial IReadOnlyList<GalaxyHistoricalTradeFlow> GalaxyHistoricalTradeFlows { get; set; }=[];
[ObservableProperty] public partial IReadOnlyList<GalaxyFilterChoice> GalaxyHistoricalTradeChoices { get; set; }=[];
[ObservableProperty] public partial string GalaxyHistoricalTradeStatus { get; set; }="历史贸易流默认关闭;只读取账号原缓存,不代表实时流量。";
private CancellationTokenSource? galaxyHistoricalTradeStop;
private Task? galaxyHistoricalTradeTask;
private string galaxyHistoricalTradeBinding="";
private readonly Dictionary<long,DateTimeOffset> galaxyHistoricalTradeAttempts=[];
private IReadOnlyDictionary<long,OriginalTradeDataSnapshot>? historicalChoicesSource,historicalEdgesSource;
private IReadOnlySet<string>? historicalEdgesCommodities;
private GalaxyTradeFlowSource historicalEdgesKind;
private ulong historicalEdgesCommander;
private bool historicalEdgesShown;
private IReadOnlyList<GalaxyHistoricalTradeEdge> historicalEdges=[];
private string HistoricalTradeBinding()=>GalaxyFilter.ShowHistoricalTradeFlows
?$"{CurrentPlayer.CommanderId}|{CurrentPlayer.LoadGameAt:O}|{(runtime.FlightDriver as NativeFlightControlDriver)?.ProcessId}|{GalaxyFilter.HistoricalTradeSource}|{(GalaxyFilter.HistoricalTradeCommodities is {} selected?string.Join(',',selected.Order(StringComparer.Ordinal)):"*")}":"";
private GalaxyHistoricalTradeProjection RefreshHistoricalTradeProjection()
{
var accountReady=galaxyMetadataAccount==CurrentPlayer.CommanderId&&galaxyOriginalVisited is not null;
var source=accountReady?galaxyOriginalTrades:null;var commander=accountReady?galaxyOriginalVisited!.CommanderId:0;
if(!ReferenceEquals(historicalChoicesSource,source))
{
historicalChoicesSource=source;
var choices=(source?.Values??[]).SelectMany(s=>s.Routes).Select(r=>new GalaxyFilterChoice(GalaxyMapFilter.Normalize(r.Commodity),r.Commodity)).DistinctBy(c=>c.Key).OrderBy(c=>c.Label,StringComparer.OrdinalIgnoreCase).ToArray();
if(!GalaxyHistoricalTradeChoices.SequenceEqual(choices))GalaxyHistoricalTradeChoices=choices;
}
if(!ReferenceEquals(historicalEdgesSource,source)||!ReferenceEquals(historicalEdgesCommodities,GalaxyFilter.HistoricalTradeCommodities)||historicalEdgesCommander!=commander||historicalEdgesShown!=GalaxyFilter.ShowHistoricalTradeFlows||historicalEdgesKind!=GalaxyFilter.HistoricalTradeSource)
{
historicalEdgesSource=source;historicalEdgesCommodities=GalaxyFilter.HistoricalTradeCommodities;historicalEdgesCommander=commander;historicalEdgesShown=GalaxyFilter.ShowHistoricalTradeFlows;historicalEdgesKind=GalaxyFilter.HistoricalTradeSource;
historicalEdges=historicalEdgesShown&&source is not null?GalaxyHistoricalTrade.Select(source.Values,commander,historicalEdgesKind,historicalEdgesCommodities):[];
}
var edges=historicalEdges;
GalaxyHistoricalTradeProjection projection;
if(edges.Count==0)projection=new(edges,[],[]);
else
{
var required=edges.SelectMany(e=>new[]{e.FromSystemAddress,e.ToSystemAddress}).ToHashSet();
var systems=galaxyCache.Values.Where(s=>s.SystemAddress is {} id&&required.Contains(id)&&s.Position.IsValid).GroupBy(s=>s.SystemAddress!.Value)
.ToDictionary(g=>g.Key,g=>g.OrderByDescending(s=>s.Source=="游戏银河目录").First());
projection=GalaxyHistoricalTrade.Project(edges,systems);
}
if(!GalaxyHistoricalTradeFlows.SequenceEqual(projection.Flows))GalaxyHistoricalTradeFlows=projection.Flows;
if(!GalaxyFilter.ShowHistoricalTradeFlows)GalaxyHistoricalTradeStatus="历史贸易流已关闭;名称/数量仅来自账号缓存,未查询实时流量。";
else if(!accountReady)GalaxyHistoricalTradeStatus="尚无当前账号原CommanderId证明;历史贸易流保持未知。";
else
{
var dates=projection.OldestCache is {} oldest&&projection.NewestCache is {} newest?$"缓存 {oldest.ToLocalTime():yyyy-MM-dd HH:mm}"+(oldest!=newest?$" — {newest.ToLocalTime():yyyy-MM-dd HH:mm}":""):"暂无所选历史缓存记录";
GalaxyHistoricalTradeStatus=$"历史贸易流 · {projection.Flows.Count:N0} / {edges.Count:N0} 条已解析 · {projection.MissingSystemAddresses.Count:N0} 个端点待确认。\n{dates};非实时流量,不证明完整覆盖。";
}
return projection;
}
private void QueueGalaxyHistoricalTradeFlows()
{
var binding=HistoricalTradeBinding();
if(binding!=galaxyHistoricalTradeBinding)
{galaxyHistoricalTradeBinding=binding;galaxyHistoricalTradeStop?.Cancel();galaxyHistoricalTradeStop?.Dispose();galaxyHistoricalTradeStop=null;galaxyHistoricalTradeAttempts.Clear();}
var projection=RefreshHistoricalTradeProjection();
if(binding.Length==0||projection.MissingSystemAddresses.Count==0||galaxyHistoricalTradeTask is {IsCompleted:false}&&galaxyHistoricalTradeStop?.IsCancellationRequested==false)return;
if(NavigationActive||!CurrentPlayer.InGame||runtime.FlightDriver is not NativeFlightControlDriver{SupportsGalaxyResolveAddress:true} driver||NativeGalaxy() is not {} catalog)
{if(projection.MissingSystemAddresses.Count>0)GalaxyHistoricalTradeStatus+="\n原游戏地址解析尚未连接;不会猜测端点坐标。";return;}
galaxyHistoricalTradeStop=CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);
galaxyHistoricalTradeTask=ResolveHistoricalTradeEndpointsAsync(binding,driver.ProcessId,catalog,galaxyHistoricalTradeStop.Token);
}
private async Task ResolveHistoricalTradeEndpointsAsync(string binding,int processId,NativeGalaxyCatalog catalog,CancellationToken token)
{
bool Latest()=>!token.IsCancellationRequested&&HistoricalTradeBinding()==binding&&runtime.FlightDriver is NativeFlightControlDriver current&¤t.ProcessId==processId;
try
{
while(Latest())
{
if(NavigationActive||!CurrentPlayer.InGame)return;
var projection=RefreshHistoricalTradeProjection();if(projection.MissingSystemAddresses.Count==0)return;
var now=DateTimeOffset.UtcNow;
var pending=projection.MissingSystemAddresses.Where(a=>!galaxyHistoricalTradeAttempts.TryGetValue(a,out var at)||now-at>=TimeSpan.FromSeconds(30))
.OrderBy(a=>galaxyHistoricalTradeAttempts.GetValueOrDefault(a)).Take(8).ToArray();
if(pending.Length==0){await Task.Delay(1000,token);continue;}
foreach(var address in pending)
{
if(!Latest())return;galaxyHistoricalTradeAttempts[address]=DateTimeOffset.UtcNow;
try
{var resolved=await catalog.ResolveAddressAsync(address,token);if(!Latest())return;RememberGalaxy(resolved);}
catch(Exception error)when(error is KeyNotFoundException or InvalidDataException or IOException or TimeoutException)
{if(!Latest())return;GalaxyHistoricalTradeStatus="历史贸易流端点解析待确认:"+error.Message+";不会猜测坐标。";}
}
if(!Latest())return;RefreshHistoricalTradeProjection();await Task.Delay(250,token);
}
}
catch(OperationCanceledException){ }
catch(Exception error)when(error is InvalidOperationException or System.Text.Json.JsonException)
{if(Latest())GalaxyHistoricalTradeStatus="历史贸易流地址来源尚未确认:"+error.Message;}
}
}