Snapshot for release 2026.10.31.3 (internal 136d99a)
This commit is contained in:
parent
2546497f37
commit
057bb66426
13 changed files with 3674 additions and 0 deletions
221
src/RynthCore.App.Avalonia/HeadlessWindow.axaml
Normal file
221
src/RynthCore.App.Avalonia/HeadlessWindow.axaml
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="RynthCore.App.Avalonia.HeadlessWindow"
|
||||
Width="1100"
|
||||
Height="760"
|
||||
MinWidth="900"
|
||||
MinHeight="620"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
Title="RynthCore - Headless clients"
|
||||
Background="#0B1218"
|
||||
Icon="avares://RynthCore.App.Avalonia/LogoCore.ico">
|
||||
<!-- What the headless characters (rynth-headless.exe) are doing, from their status files and logs
|
||||
(HeadlessWindow.axaml.cs; the file rules are in RynthCore.App\HeadlessMonitor.cs). -->
|
||||
<Window.Styles>
|
||||
<Style Selector="TextBlock">
|
||||
<Setter Property="FontSize" Value="12.5" />
|
||||
<Setter Property="Foreground" Value="#EAF0F4" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.label">
|
||||
<Setter Property="Foreground" Value="#9AA8B3" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.title">
|
||||
<Setter Property="FontSize" Value="16" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Foreground" Value="#26C1A6" />
|
||||
</Style>
|
||||
<Style Selector="Button">
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="Padding" Value="12,8" />
|
||||
</Style>
|
||||
<Style Selector="TextBox">
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
</Style>
|
||||
<Style Selector="ListBox">
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
</Style>
|
||||
<Style Selector="Border.card">
|
||||
<Setter Property="Background" Value="#132028" />
|
||||
<Setter Property="CornerRadius" Value="16" />
|
||||
<Setter Property="Padding" Value="14" />
|
||||
</Style>
|
||||
<Style Selector="ProgressBar.vital">
|
||||
<Setter Property="Height" Value="10" />
|
||||
<Setter Property="MinHeight" Value="10" />
|
||||
<Setter Property="MinWidth" Value="0" />
|
||||
<Setter Property="Minimum" Value="0" />
|
||||
<Setter Property="Maximum" Value="1" />
|
||||
<Setter Property="Background" Value="#0F161D" />
|
||||
</Style>
|
||||
</Window.Styles>
|
||||
|
||||
<Grid ColumnDefinitions="280,Auto,*" Margin="14">
|
||||
<!-- Left: one row per headless character. -->
|
||||
<Border Grid.Column="0" Classes="card">
|
||||
<Grid RowDefinitions="Auto,Auto,*,Auto">
|
||||
<TextBlock Grid.Row="0" Classes="title" Text="Headless clients" />
|
||||
<TextBlock Grid.Row="1" Classes="label" TextWrapping="Wrap" Margin="0,4,0,8"
|
||||
Text="Green botting, blue idle, red dead, grey not in the world, amber not answering (no status for 10 s)." />
|
||||
<ListBox Grid.Row="2" x:Name="CharacterList"
|
||||
Background="#0F161D"
|
||||
BorderBrush="#243742"
|
||||
Foreground="#EAF0F4" />
|
||||
<TextBlock Grid.Row="3" x:Name="ListHintText" Classes="label" TextWrapping="Wrap" Margin="0,8,0,0" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<GridSplitter Grid.Column="1" Width="12" ResizeDirection="Columns" Background="Transparent" />
|
||||
|
||||
<!-- Right: the selected character. -->
|
||||
<Grid Grid.Column="2">
|
||||
<Border x:Name="EmptyPanel" Classes="card" IsVisible="True">
|
||||
<StackPanel Spacing="8" VerticalAlignment="Center" HorizontalAlignment="Center" MaxWidth="460">
|
||||
<TextBlock Classes="title" Text="No headless character selected" HorizontalAlignment="Center" />
|
||||
<TextBlock x:Name="EmptyText" Classes="label" TextWrapping="Wrap" TextAlignment="Center"
|
||||
Text="Accounts set to Headless (experimental) show up here while they run." />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Grid x:Name="DetailPanel" RowDefinitions="Auto,Auto,Auto,*" IsVisible="False">
|
||||
<!-- Header: who, where, and the actions. -->
|
||||
<Border Grid.Row="0" Classes="card" Margin="0,0,0,10">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
<Ellipse Grid.Column="0" x:Name="DetailDot" Width="14" Height="14" Margin="0,0,10,0"
|
||||
VerticalAlignment="Center" Fill="#6F7F8A" />
|
||||
<StackPanel Grid.Column="1" Spacing="2" VerticalAlignment="Center">
|
||||
<TextBlock x:Name="DetailNameText" FontSize="19" FontWeight="Bold" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock x:Name="DetailStateText" Classes="label" TextWrapping="Wrap" />
|
||||
<TextBlock x:Name="WhereText" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<WrapPanel Grid.Column="2" Orientation="Horizontal" VerticalAlignment="Center" Margin="10,0,0,0">
|
||||
<Button x:Name="MacroButton" Content="Start macro" Margin="0,0,8,0"
|
||||
ToolTip.Tip="Turns RynthAi's macro on or off for this character (the same command the phone sends)." />
|
||||
<Button x:Name="LogOutButton" Content="Log out" Margin="0,0,8,0"
|
||||
ToolTip.Tip="Asks this character's rynth-headless.exe to log out and exit (closed after 20 s if it doesn't). The stop request is per process: a process running several characters logs them all out. With AutoLaunch on, uncheck the account first or it is started again." />
|
||||
<Button x:Name="OpenLogFolderButton" Content="Open log folder"
|
||||
ToolTip.Tip="Opens the folder with this character's headless log." />
|
||||
</WrapPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Vitals, what it is doing and how the session is going. -->
|
||||
<Grid Grid.Row="1" ColumnDefinitions="*,10,*,10,1.3*" Margin="0,0,0,10">
|
||||
<Border Grid.Column="0" Classes="card">
|
||||
<StackPanel Spacing="6">
|
||||
<TextBlock Classes="title" Text="Vitals" />
|
||||
<Grid ColumnDefinitions="Auto,*" RowDefinitions="Auto,Auto,Auto,Auto,Auto,Auto">
|
||||
<TextBlock Grid.Row="0" Grid.Column="0" Classes="label" Text="Health" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="1" x:Name="HealthText" HorizontalAlignment="Right" />
|
||||
<ProgressBar Grid.Row="1" Grid.ColumnSpan="2" x:Name="HealthBar" Classes="vital" Foreground="#E05A5A" Margin="0,2,0,6" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="0" Classes="label" Text="Stamina" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="1" x:Name="StaminaText" HorizontalAlignment="Right" />
|
||||
<ProgressBar Grid.Row="3" Grid.ColumnSpan="2" x:Name="StaminaBar" Classes="vital" Foreground="#F2C14E" Margin="0,2,0,6" />
|
||||
<TextBlock Grid.Row="4" Grid.Column="0" Classes="label" Text="Mana" />
|
||||
<TextBlock Grid.Row="4" Grid.Column="1" x:Name="ManaText" HorizontalAlignment="Right" />
|
||||
<ProgressBar Grid.Row="5" Grid.ColumnSpan="2" x:Name="ManaBar" Classes="vital" Foreground="#4A90E2" Margin="0,2,0,0" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Border Grid.Column="2" Classes="card">
|
||||
<StackPanel Spacing="6">
|
||||
<TextBlock Classes="title" Text="Doing" />
|
||||
<Grid ColumnDefinitions="Auto,*" RowDefinitions="Auto,Auto,Auto,Auto,Auto">
|
||||
<TextBlock Grid.Row="0" Grid.Column="0" Classes="label" Text="Action" Margin="0,0,10,4" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="1" x:Name="ActionText" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="0" Classes="label" Text="Macro" Margin="0,0,10,4" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="1" x:Name="MacroText" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="0" Classes="label" Text="Meta" Margin="0,0,10,4" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="1" x:Name="MetaText" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Grid.Row="3" Grid.Column="0" Classes="label" Text="Target" Margin="0,0,10,4" />
|
||||
<TextBlock Grid.Row="3" Grid.Column="1" x:Name="TargetText" TextTrimming="CharacterEllipsis" />
|
||||
<ProgressBar Grid.Row="4" Grid.ColumnSpan="2" x:Name="TargetBar" Classes="vital" Foreground="#E05A5A" Margin="0,2,0,0" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Border Grid.Column="4" Classes="card">
|
||||
<StackPanel Spacing="6">
|
||||
<TextBlock Classes="title" Text="Session" />
|
||||
<!-- Wraps to one pair a row when the window is narrow. -->
|
||||
<WrapPanel Orientation="Horizontal" ItemWidth="134">
|
||||
<Grid ColumnDefinitions="68,*" Margin="0,0,0,4">
|
||||
<TextBlock Grid.Column="0" Classes="label" Text="XP/hour" />
|
||||
<TextBlock Grid.Column="1" x:Name="XpHourText" TextTrimming="CharacterEllipsis" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="68,*" Margin="0,0,0,4">
|
||||
<TextBlock Grid.Column="0" Classes="label" Text="XP session" />
|
||||
<TextBlock Grid.Column="1" x:Name="XpSessionText" TextTrimming="CharacterEllipsis" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="68,*" Margin="0,0,0,4">
|
||||
<TextBlock Grid.Column="0" Classes="label" Text="Kills" />
|
||||
<TextBlock Grid.Column="1" x:Name="KillsText" TextTrimming="CharacterEllipsis" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="68,*" Margin="0,0,0,4">
|
||||
<TextBlock Grid.Column="0" Classes="label" Text="Deaths" />
|
||||
<TextBlock Grid.Column="1" x:Name="DeathsText" TextTrimming="CharacterEllipsis" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="68,*" Margin="0,0,0,4">
|
||||
<TextBlock Grid.Column="0" Classes="label" Text="Vitae" />
|
||||
<TextBlock Grid.Column="1" x:Name="VitaeText" TextTrimming="CharacterEllipsis" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="68,*" Margin="0,0,0,4">
|
||||
<TextBlock Grid.Column="0" Classes="label" Text="Burden" />
|
||||
<TextBlock Grid.Column="1" x:Name="BurdenText" TextTrimming="CharacterEllipsis" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="68,*" Margin="0,0,0,4">
|
||||
<TextBlock Grid.Column="0" Classes="label" Text="Uptime" />
|
||||
<TextBlock Grid.Column="1" x:Name="UptimeText" TextTrimming="CharacterEllipsis" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="68,*" Margin="0,0,0,4">
|
||||
<TextBlock Grid.Column="0" Classes="label" Text="Process" />
|
||||
<TextBlock Grid.Column="1" x:Name="ProcessText" TextTrimming="CharacterEllipsis" />
|
||||
</Grid>
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
|
||||
<!-- Command box: /ra, /rnav, /mt, /rn through the character's command file. -->
|
||||
<Border Grid.Row="2" Classes="card" Margin="0,0,0,10">
|
||||
<Grid ColumnDefinitions="*,Auto" RowDefinitions="Auto,Auto">
|
||||
<TextBox Grid.Row="0" Grid.Column="0" x:Name="CommandBox"
|
||||
Watermark="/ra pause, /ra start, /rnav ..., /mt ..., /rn ... (Enter sends)"
|
||||
AcceptsReturn="False" Margin="0,0,8,0" />
|
||||
<Button Grid.Row="0" Grid.Column="1" x:Name="SendButton" Content="Send"
|
||||
Background="#26C1A6" Foreground="#0B1218" FontWeight="SemiBold" />
|
||||
<TextBlock Grid.Row="1" Grid.ColumnSpan="2" x:Name="CommandStatusText" Classes="label"
|
||||
TextWrapping="Wrap" Margin="2,6,0,0" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Chat and log. -->
|
||||
<Grid Grid.Row="3" ColumnDefinitions="*,Auto,*">
|
||||
<Border Grid.Column="0" Classes="card">
|
||||
<Grid RowDefinitions="Auto,*">
|
||||
<TextBlock Grid.Row="0" Classes="title" Text="Chat" Margin="0,0,0,6"
|
||||
ToolTip.Tip="The last 30 lines the character saw; combat damage lines are hidden." />
|
||||
<TextBox Grid.Row="1" x:Name="ChatBox" IsReadOnly="True" TextWrapping="Wrap"
|
||||
AcceptsReturn="True" FontFamily="Consolas,Menlo,monospace" FontSize="11.5"
|
||||
Background="#0F161D" BorderBrush="#243742" Foreground="#EAF0F4"
|
||||
ScrollViewer.VerticalScrollBarVisibility="Auto" />
|
||||
</Grid>
|
||||
</Border>
|
||||
<GridSplitter Grid.Column="1" Width="10" ResizeDirection="Columns" Background="Transparent" />
|
||||
<Border Grid.Column="2" Classes="card">
|
||||
<Grid RowDefinitions="Auto,Auto,*">
|
||||
<TextBlock Grid.Row="0" Classes="title" Text="Log" Margin="0,0,0,2" />
|
||||
<TextBlock Grid.Row="1" x:Name="LogPathText" Classes="label" FontSize="11"
|
||||
TextTrimming="CharacterEllipsis" Margin="0,0,0,6" />
|
||||
<TextBox Grid.Row="2" x:Name="LogBox" IsReadOnly="True" TextWrapping="NoWrap"
|
||||
AcceptsReturn="True" FontFamily="Consolas,Menlo,monospace" FontSize="11"
|
||||
Background="#0F161D" BorderBrush="#243742" Foreground="#EAF0F4"
|
||||
ScrollViewer.VerticalScrollBarVisibility="Auto"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Auto" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Window>
|
||||
722
src/RynthCore.App.Avalonia/HeadlessWindow.axaml.cs
Normal file
722
src/RynthCore.App.Avalonia/HeadlessWindow.axaml.cs
Normal file
|
|
@ -0,0 +1,722 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Shapes;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using RynthCore.App;
|
||||
using Path = System.IO.Path;
|
||||
|
||||
namespace RynthCore.App.Avalonia;
|
||||
|
||||
/// <summary>What the Headless window needs from the launcher.</summary>
|
||||
internal sealed class HeadlessWindowHost
|
||||
{
|
||||
/// <summary>The launcher's settings (the window keeps its size and place in them).</summary>
|
||||
public required AppSettings Settings { get; init; }
|
||||
public required Action SaveSettings { get; init; }
|
||||
/// <summary>The status folder rynth-headless writes (AppSettings.HeadlessStatusDir or its default).</summary>
|
||||
public required Func<string> StatusDir { get; init; }
|
||||
/// <summary>AppSettings.HeadlessSuiteDir ("" = the default).</summary>
|
||||
public required Func<string> ConfiguredSuiteDir { get; init; }
|
||||
/// <summary>%APPDATA%\RynthCore\headless, where the launcher writes the run configs.</summary>
|
||||
public required string LaunchConfigDir { get; init; }
|
||||
/// <summary>Asks rynth-headless process <pid> to log out and exit; returns what happened.</summary>
|
||||
public required Func<int, string> LogOutProcess { get; init; }
|
||||
/// <summary>Whether AutoLaunch is on (a logged-out account is started again).</summary>
|
||||
public required Func<bool> AutoLaunch { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The launcher's Headless window: what each headless character (rynth-headless.exe, no game window)
|
||||
/// is doing, from its status file, its chat and its log, with a command box, macro on/off and log out.
|
||||
/// Reads files once a second off the UI thread and writes only command files
|
||||
/// (RynthCore.App\HeadlessMonitor.cs has the rules and the tests in tools\HeadlessWindowTests).
|
||||
/// Never shows a password or a config file; no account names (characters and servers only).
|
||||
/// </summary>
|
||||
internal partial class HeadlessWindow : Window
|
||||
{
|
||||
private static readonly IBrush BottingBrush = Brush("#26C1A6");
|
||||
private static readonly IBrush IdleBrush = Brush("#4A90E2");
|
||||
private static readonly IBrush DeadBrush = Brush("#E05A5A");
|
||||
private static readonly IBrush LoadingBrush = Brush("#6F7F8A");
|
||||
private static readonly IBrush StaleBrush = Brush("#F2C14E");
|
||||
private static readonly IBrush TextBrush = Brush("#EAF0F4");
|
||||
private static readonly IBrush MutedBrush = Brush("#9AA8B3");
|
||||
private static readonly IBrush WarnBrush = Brush("#F2C14E");
|
||||
|
||||
/// <summary>How long the window waits for a chat line after a command.</summary>
|
||||
private static readonly TimeSpan ReplyWait = TimeSpan.FromSeconds(20);
|
||||
/// <summary>A command file nobody took in this long is removed (the StatusAgent prunes at 60 s too).</summary>
|
||||
private static readonly TimeSpan UntakenLimit = TimeSpan.FromSeconds(60);
|
||||
/// <summary>How long a found log path is trusted before it is looked up again.</summary>
|
||||
private static readonly TimeSpan LogLookupEvery = TimeSpan.FromSeconds(15);
|
||||
|
||||
private readonly HeadlessWindowHost? _host;
|
||||
private readonly DispatcherTimer _timer = new() { Interval = TimeSpan.FromSeconds(1) };
|
||||
private readonly HeadlessRoster _roster = new();
|
||||
private readonly ObservableCollection<Control> _items = new();
|
||||
private readonly Dictionary<int, Row> _rows = new();
|
||||
private int? _selectedId;
|
||||
private bool _suppressSelection;
|
||||
private bool _refreshing;
|
||||
private bool _closed;
|
||||
private bool _autoSelected;
|
||||
|
||||
// The log of the selected character (touched by the background read only while _refreshing).
|
||||
private string? _logAccount;
|
||||
private string? _logPath;
|
||||
private List<string> _logDirs = new();
|
||||
private DateTime _logLookedUpUtc;
|
||||
private (long Length, DateTime Written)? _logStamp;
|
||||
private int _logForId;
|
||||
|
||||
// The last command sent from the box, until its reply shows or the wait is over.
|
||||
private PendingCommand? _pending;
|
||||
// Command files written here and not taken yet (path, written).
|
||||
private readonly List<(string Path, DateTime WrittenUtc)> _untaken = new();
|
||||
|
||||
private sealed class Row
|
||||
{
|
||||
public required Border Root { get; init; }
|
||||
public required Ellipse Dot { get; init; }
|
||||
public required TextBlock Name { get; init; }
|
||||
public required TextBlock Server { get; init; }
|
||||
public required ProgressBar Health { get; init; }
|
||||
}
|
||||
|
||||
private sealed class PendingCommand
|
||||
{
|
||||
public required int Id { get; init; }
|
||||
public required string Text { get; init; }
|
||||
public required string Path { get; init; }
|
||||
public required DateTime SentUtc { get; init; }
|
||||
public required IReadOnlyList<HeadlessChatLine> ChatAtSend { get; init; }
|
||||
public bool Taken { get; set; }
|
||||
}
|
||||
|
||||
private sealed class ReadResult
|
||||
{
|
||||
public List<HeadlessCharacterStatus> Found { get; init; } = new();
|
||||
public List<int> Unreadable { get; init; } = new();
|
||||
public int LogForId { get; init; }
|
||||
public string? LogPath { get; init; }
|
||||
/// <summary>Null = unchanged since the last read (or no log).</summary>
|
||||
public List<string>? LogLines { get; init; }
|
||||
public bool LogMissing { get; init; }
|
||||
public string? PendingPath { get; init; }
|
||||
public bool PendingFileExists { get; init; }
|
||||
public int RemovedUntaken { get; init; }
|
||||
public string? Error { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>For the XAML designer only.</summary>
|
||||
public HeadlessWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public HeadlessWindow(HeadlessWindowHost host)
|
||||
{
|
||||
_host = host;
|
||||
InitializeComponent();
|
||||
RestoreLayout();
|
||||
CharacterList.ItemsSource = _items;
|
||||
CharacterList.SelectionChanged += (_, _) => OnSelectionChanged();
|
||||
SendButton.Click += async (_, _) => await SendCommandAsync();
|
||||
// Tunnel: Enter reaches us before the text box can take it.
|
||||
CommandBox.AddHandler(KeyDownEvent, async (_, e) =>
|
||||
{
|
||||
if (e.Key == Key.Enter)
|
||||
{
|
||||
e.Handled = true;
|
||||
await SendCommandAsync();
|
||||
}
|
||||
}, RoutingStrategies.Tunnel);
|
||||
MacroButton.Click += async (_, _) => await ToggleMacroAsync();
|
||||
LogOutButton.Click += async (_, _) => await LogOutAsync();
|
||||
OpenLogFolderButton.Click += (_, _) => OpenLogFolder();
|
||||
_timer.Tick += async (_, _) => await RefreshAsync();
|
||||
Opened += async (_, _) =>
|
||||
{
|
||||
_timer.Start();
|
||||
await RefreshAsync();
|
||||
};
|
||||
Closing += (_, _) => SaveLayout();
|
||||
Closed += (_, _) =>
|
||||
{
|
||||
_closed = true;
|
||||
_timer.Stop();
|
||||
};
|
||||
}
|
||||
|
||||
private static IBrush Brush(string hex) => new SolidColorBrush(Color.Parse(hex));
|
||||
|
||||
// ── size and place ──────────────────────────────────────────────────────
|
||||
|
||||
private void RestoreLayout()
|
||||
{
|
||||
AppSettings s = _host!.Settings;
|
||||
if (s.HeadlessWindowWidth is double w && w >= MinWidth) Width = w;
|
||||
if (s.HeadlessWindowHeight is double h && h >= MinHeight) Height = h;
|
||||
// The launcher's own rule (MainWindow.LoadSettings): never restore a minimized (-32000) or
|
||||
// far off-screen point, which would open the window where nobody can see it.
|
||||
if (s.HeadlessWindowX is double x && s.HeadlessWindowY is double y &&
|
||||
x > -2000 && y > -2000 && x < 30000 && y < 30000)
|
||||
{
|
||||
Position = new PixelPoint((int)x, (int)y);
|
||||
WindowStartupLocation = WindowStartupLocation.Manual;
|
||||
}
|
||||
}
|
||||
|
||||
private void SaveLayout()
|
||||
{
|
||||
if (_host == null || WindowState == WindowState.Minimized || Position.X <= -2000 || Position.Y <= -2000)
|
||||
return;
|
||||
_host.Settings.HeadlessWindowWidth = Width;
|
||||
_host.Settings.HeadlessWindowHeight = Height;
|
||||
_host.Settings.HeadlessWindowX = Position.X;
|
||||
_host.Settings.HeadlessWindowY = Position.Y;
|
||||
_host.SaveSettings();
|
||||
}
|
||||
|
||||
// ── refresh: files off the UI thread, then the controls ─────────────────
|
||||
|
||||
private async Task RefreshAsync()
|
||||
{
|
||||
if (_host == null || _refreshing || _closed)
|
||||
return;
|
||||
_refreshing = true;
|
||||
try
|
||||
{
|
||||
string statusDir = _host.StatusDir();
|
||||
string configuredSuite = _host.ConfiguredSuiteDir();
|
||||
HeadlessCharacterStatus? selected = _selectedId is int sid && _roster.TryGet(sid, out var st) ? st : null;
|
||||
PendingCommand? pending = _pending;
|
||||
DateTime nowUtc = DateTime.UtcNow;
|
||||
ReadResult result = await Task.Run(() => Read(statusDir, configuredSuite, selected, pending, nowUtc));
|
||||
if (!_closed)
|
||||
Apply(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ListHintText.Text = "Couldn't read the status files: " + ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs on a pool thread: every file the window needs, read once.</summary>
|
||||
private ReadResult Read(string statusDir, string configuredSuite, HeadlessCharacterStatus? selected, PendingCommand? pending, DateTime nowUtc)
|
||||
{
|
||||
try
|
||||
{
|
||||
List<HeadlessCharacterStatus> found = HeadlessStatusScanner.Scan(statusDir, nowUtc, out List<int> unreadable);
|
||||
|
||||
// Command files nobody took within a minute: the character isn't reading its inbox.
|
||||
int removed = 0;
|
||||
lock (_untaken)
|
||||
{
|
||||
for (int i = _untaken.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var (path, written) = _untaken[i];
|
||||
bool exists = File.Exists(path);
|
||||
if (exists && nowUtc - written > UntakenLimit)
|
||||
{
|
||||
try { File.Delete(path); removed++; } catch (IOException) { } catch (UnauthorizedAccessException) { }
|
||||
exists = File.Exists(path);
|
||||
}
|
||||
if (!exists)
|
||||
_untaken.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
|
||||
// The selected character's log.
|
||||
int logFor = selected?.Id ?? 0;
|
||||
string? logPath = null;
|
||||
List<string>? lines = null;
|
||||
bool missing = false;
|
||||
if (selected != null && selected.Account.Length > 0)
|
||||
{
|
||||
if (_logForId != selected.Id || _logAccount != selected.Account)
|
||||
{
|
||||
_logForId = selected.Id;
|
||||
_logAccount = selected.Account;
|
||||
_logPath = null;
|
||||
_logStamp = null;
|
||||
_logLookedUpUtc = DateTime.MinValue;
|
||||
}
|
||||
if (_logPath == null || !File.Exists(_logPath) || nowUtc - _logLookedUpUtc > LogLookupEvery)
|
||||
{
|
||||
_logDirs = HeadlessLogs.CandidateSuiteDirs(selected.Account, _host!.LaunchConfigDir, configuredSuite, HeadlessLogs.DefaultSuiteDir);
|
||||
string? path = HeadlessLogs.Find(selected.Account, _logDirs);
|
||||
if (path != _logPath) _logStamp = null;
|
||||
_logPath = path;
|
||||
_logLookedUpUtc = nowUtc;
|
||||
}
|
||||
logPath = _logPath;
|
||||
if (logPath == null)
|
||||
{
|
||||
missing = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
var info = new FileInfo(logPath);
|
||||
var stamp = (info.Length, info.LastWriteTimeUtc);
|
||||
if (_logStamp != stamp)
|
||||
{
|
||||
lines = HeadlessLogs.Tail(logPath);
|
||||
if (lines != null) _logStamp = stamp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new ReadResult
|
||||
{
|
||||
Found = found,
|
||||
Unreadable = unreadable,
|
||||
LogForId = logFor,
|
||||
LogPath = logPath,
|
||||
LogLines = lines,
|
||||
LogMissing = missing,
|
||||
PendingPath = pending?.Path,
|
||||
PendingFileExists = pending != null && File.Exists(pending.Path),
|
||||
RemovedUntaken = removed,
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ReadResult { Error = ex.Message };
|
||||
}
|
||||
}
|
||||
|
||||
private void Apply(ReadResult r)
|
||||
{
|
||||
DateTime nowUtc = DateTime.UtcNow;
|
||||
if (r.Error != null)
|
||||
{
|
||||
ListHintText.Text = "Couldn't read the status files: " + r.Error;
|
||||
return;
|
||||
}
|
||||
|
||||
List<HeadlessCharacterStatus> list = _roster.Update(r.Found, r.Unreadable, nowUtc);
|
||||
SyncRows(list, nowUtc);
|
||||
string folder = _host!.StatusDir();
|
||||
ListHintText.Text = list.Count == 0
|
||||
? $"No headless character is running. Status folder: {folder}"
|
||||
: list.Count == 1 ? "1 headless character." : $"{list.Count} headless characters.";
|
||||
ToolTip.SetTip(ListHintText, "Status folder: " + folder);
|
||||
|
||||
if (_selectedId is int id && !_roster.TryGet(id, out _))
|
||||
{
|
||||
_selectedId = null;
|
||||
EmptyText.Text = "That character left: no status for 30 s (logged out, or its process ended).";
|
||||
}
|
||||
// The first character is picked once, when the window opens; after that the player picks.
|
||||
if (!_autoSelected && _selectedId == null && list.Count > 0)
|
||||
{
|
||||
_autoSelected = true;
|
||||
HeadlessCharacterStatus first = list.FirstOrDefault(c => HeadlessStatusRules.Activity(c, nowUtc) is
|
||||
HeadlessActivity.Botting or HeadlessActivity.Idle or HeadlessActivity.Dead) ?? list[0];
|
||||
Select(first.Id);
|
||||
}
|
||||
|
||||
if (_selectedId is int sel && _roster.TryGet(sel, out HeadlessCharacterStatus? s))
|
||||
{
|
||||
ShowDetail(s, nowUtc);
|
||||
if (r.LogForId == sel)
|
||||
ShowLog(r);
|
||||
}
|
||||
else
|
||||
{
|
||||
DetailPanel.IsVisible = false;
|
||||
EmptyPanel.IsVisible = true;
|
||||
if (list.Count == 0)
|
||||
EmptyText.Text = "Accounts set to Headless (experimental) show up here while they run.";
|
||||
}
|
||||
|
||||
UpdatePending(r, nowUtc);
|
||||
}
|
||||
|
||||
// ── the list ────────────────────────────────────────────────────────────
|
||||
|
||||
private void SyncRows(List<HeadlessCharacterStatus> list, DateTime nowUtc)
|
||||
{
|
||||
_suppressSelection = true;
|
||||
try
|
||||
{
|
||||
var ids = list.Select(s => s.Id).ToHashSet();
|
||||
foreach (int gone in _rows.Keys.Where(k => !ids.Contains(k)).ToList())
|
||||
{
|
||||
_items.Remove(_rows[gone].Root);
|
||||
_rows.Remove(gone);
|
||||
}
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
HeadlessCharacterStatus s = list[i];
|
||||
if (!_rows.TryGetValue(s.Id, out Row? row))
|
||||
{
|
||||
row = NewRow(s.Id);
|
||||
_rows[s.Id] = row;
|
||||
}
|
||||
int at = _items.IndexOf(row.Root);
|
||||
if (at != i)
|
||||
{
|
||||
if (at >= 0) _items.RemoveAt(at);
|
||||
_items.Insert(i, row.Root);
|
||||
}
|
||||
HeadlessActivity a = HeadlessStatusRules.Activity(s, nowUtc);
|
||||
row.Dot.Fill = DotBrush(a);
|
||||
ToolTip.SetTip(row.Root, HeadlessStatusRules.ActivityText(a));
|
||||
row.Name.Text = s.Character.Length > 0 ? s.Character : "(character not known yet)";
|
||||
row.Server.Text = s.Server;
|
||||
row.Health.Value = s.HasVitals ? HeadlessFormat.Fraction(s.Health, s.MaxHealth) : 0;
|
||||
row.Health.Opacity = s.HasVitals ? 1 : 0.3;
|
||||
}
|
||||
if (_selectedId is int sel && _rows.TryGetValue(sel, out Row? selRow) && !ReferenceEquals(CharacterList.SelectedItem, selRow.Root))
|
||||
CharacterList.SelectedItem = selRow.Root;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_suppressSelection = false;
|
||||
}
|
||||
}
|
||||
|
||||
private Row NewRow(int id)
|
||||
{
|
||||
var dot = new Ellipse { Width = 10, Height = 10, Fill = LoadingBrush, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 8, 0) };
|
||||
var name = new TextBlock { FontWeight = FontWeight.SemiBold, Foreground = TextBrush, TextTrimming = TextTrimming.CharacterEllipsis };
|
||||
var server = new TextBlock { FontSize = 11, Foreground = MutedBrush, TextTrimming = TextTrimming.CharacterEllipsis };
|
||||
var hp = new ProgressBar
|
||||
{
|
||||
Minimum = 0, Maximum = 1, Height = 4, MinHeight = 4, MinWidth = 0, Margin = new Thickness(0, 4, 0, 0),
|
||||
Foreground = DeadBrush, Background = Brush("#0B1218"),
|
||||
};
|
||||
var text = new StackPanel { Spacing = 1, Children = { name, server, hp } };
|
||||
Grid.SetColumn(text, 1);
|
||||
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Children = { dot, text } };
|
||||
var root = new Border { Padding = new Thickness(4, 4), Tag = id, Child = grid };
|
||||
return new Row { Root = root, Dot = dot, Name = name, Server = server, Health = hp };
|
||||
}
|
||||
|
||||
private static IBrush DotBrush(HeadlessActivity a) => a switch
|
||||
{
|
||||
HeadlessActivity.Botting => BottingBrush,
|
||||
HeadlessActivity.Idle => IdleBrush,
|
||||
HeadlessActivity.Dead => DeadBrush,
|
||||
HeadlessActivity.Stale => StaleBrush,
|
||||
_ => LoadingBrush,
|
||||
};
|
||||
|
||||
private void Select(int id)
|
||||
{
|
||||
_selectedId = id;
|
||||
if (_rows.TryGetValue(id, out Row? row))
|
||||
{
|
||||
_suppressSelection = true;
|
||||
try { CharacterList.SelectedItem = row.Root; }
|
||||
finally { _suppressSelection = false; }
|
||||
}
|
||||
ResetDetailViews();
|
||||
}
|
||||
|
||||
private void OnSelectionChanged()
|
||||
{
|
||||
if (_suppressSelection)
|
||||
return;
|
||||
int? id = (CharacterList.SelectedItem as Control)?.Tag as int?;
|
||||
if (id == _selectedId)
|
||||
return;
|
||||
_selectedId = id;
|
||||
ResetDetailViews();
|
||||
_ = RefreshAsync();
|
||||
}
|
||||
|
||||
private void ResetDetailViews()
|
||||
{
|
||||
ChatBox.Text = string.Empty;
|
||||
LogBox.Text = string.Empty;
|
||||
LogPathText.Text = "Looking for the log...";
|
||||
CommandStatusText.Text = string.Empty;
|
||||
_pending = null;
|
||||
_logForId = 0; // the next read looks the log up again and shows it whole
|
||||
}
|
||||
|
||||
// ── details ─────────────────────────────────────────────────────────────
|
||||
|
||||
private void ShowDetail(HeadlessCharacterStatus s, DateTime nowUtc)
|
||||
{
|
||||
EmptyPanel.IsVisible = false;
|
||||
DetailPanel.IsVisible = true;
|
||||
|
||||
TimeSpan age = HeadlessStatusRules.Age(s, nowUtc);
|
||||
HeadlessActivity a = HeadlessStatusRules.Activity(s, nowUtc);
|
||||
DetailDot.Fill = DotBrush(a);
|
||||
DetailNameText.Text = s.Character.Length > 0 ? s.Character : "(character not known yet)";
|
||||
string state = HeadlessStatusRules.ActivityText(a);
|
||||
if (a == HeadlessActivity.Stale)
|
||||
state += $" (no status for {age.TotalSeconds:0} s)";
|
||||
DetailStateText.Text = s.Server.Length > 0 ? $"{s.Server} - {state}" : state;
|
||||
|
||||
if (s.HasVitals)
|
||||
{
|
||||
HealthText.Text = HeadlessFormat.Vital(s.Health, s.MaxHealth);
|
||||
StaminaText.Text = HeadlessFormat.Vital(s.Stamina, s.MaxStamina);
|
||||
ManaText.Text = HeadlessFormat.Vital(s.Mana, s.MaxMana);
|
||||
}
|
||||
else
|
||||
{
|
||||
HealthText.Text = StaminaText.Text = ManaText.Text = "-";
|
||||
}
|
||||
HealthBar.Value = s.HasVitals ? HeadlessFormat.Fraction(s.Health, s.MaxHealth) : 0;
|
||||
StaminaBar.Value = s.HasVitals ? HeadlessFormat.Fraction(s.Stamina, s.MaxStamina) : 0;
|
||||
ManaBar.Value = s.HasVitals ? HeadlessFormat.Fraction(s.Mana, s.MaxMana) : 0;
|
||||
|
||||
if (!s.HasBot)
|
||||
{
|
||||
string why = s.InWorld ? "no RynthAi status (is RynthAi loaded?)" : "not in the world";
|
||||
ActionText.Text = why;
|
||||
MacroText.Text = MetaText.Text = TargetText.Text = "-";
|
||||
TargetBar.Value = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
ActionText.Text = s.BotAction.Length > 0 ? s.BotAction : "-";
|
||||
MacroText.Text = s.MacroRunning ? "on" : "off";
|
||||
MacroText.Foreground = s.MacroRunning ? BottingBrush : TextBrush;
|
||||
string meta = s.MetaName.Length > 0 && !s.MetaName.Equals("None", StringComparison.OrdinalIgnoreCase) ? s.MetaName : "none";
|
||||
MetaText.Text = s.CurrentState.Length > 0 && meta != "none" ? $"{meta} (state {s.CurrentState})" : meta;
|
||||
TargetText.Text = s.HasTarget
|
||||
? $"{s.TargetLabel} ({s.TargetHealthPercent:0}%)"
|
||||
: "none";
|
||||
TargetBar.Value = s.HasTarget ? Math.Clamp(s.TargetHealthPercent / 100.0, 0, 1) : 0;
|
||||
}
|
||||
|
||||
WhereText.Text = s.InWorld ? HeadlessCoords.Where(s) : "Not in the world";
|
||||
XpHourText.Text = HeadlessFormat.Number(s.XpPerHour);
|
||||
XpSessionText.Text = HeadlessFormat.Number(s.XpSession);
|
||||
KillsText.Text = s.HasBot
|
||||
? (s.KillsPerHour > 0 ? $"{s.SessionKills}, {HeadlessFormat.Number(s.KillsPerHour)}/h" : s.SessionKills.ToString())
|
||||
: "-";
|
||||
DeathsText.Text = s.DeathsSession.ToString();
|
||||
VitaeText.Text = s.VitaePct > 0 ? $"{s.VitaePct:0.#}%" : "none";
|
||||
VitaeText.Foreground = s.VitaePct > 0 ? WarnBrush : TextBrush;
|
||||
BurdenText.Text = $"{s.BurdenPct:0.#}%";
|
||||
BurdenText.Foreground = s.BurdenPct > 100 ? WarnBrush : TextBrush;
|
||||
UptimeText.Text = HeadlessFormat.Duration(s.UptimeSec);
|
||||
ProcessText.Text = s.HostPid > 0 ? $"PID {s.HostPid}" : "-";
|
||||
|
||||
bool fresh = a != HeadlessActivity.Stale;
|
||||
MacroButton.Content = s.MacroRunning ? "Stop macro" : "Start macro";
|
||||
MacroButton.IsEnabled = s.HasBot && s.InWorld && fresh;
|
||||
LogOutButton.IsEnabled = s.HostPid > 0;
|
||||
SendButton.IsEnabled = true;
|
||||
|
||||
string chat = string.Join(Environment.NewLine, HeadlessChat.Visible(s.RecentChat).Select(l => l.Text));
|
||||
if (s.RecentChat.Count == 0)
|
||||
chat = s.HasBot ? "(no chat yet)" : "(no chat: RynthAi's status isn't there)";
|
||||
SetLiveText(ChatBox, chat);
|
||||
}
|
||||
|
||||
private void ShowLog(ReadResult r)
|
||||
{
|
||||
if (r.LogMissing)
|
||||
{
|
||||
LogPathText.Text = "No log found. Looked in: " + string.Join("; ", _logDirs);
|
||||
if (LogBox.Text?.Length > 0) LogBox.Text = string.Empty;
|
||||
return;
|
||||
}
|
||||
if (r.LogPath != null)
|
||||
LogPathText.Text = r.LogPath;
|
||||
if (r.LogLines != null)
|
||||
SetLiveText(LogBox, string.Join(Environment.NewLine, r.LogLines));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replaces a read-only box's text when it changed. It follows the newest line unless the player
|
||||
/// has scrolled up to read (then it stays where it is).
|
||||
/// </summary>
|
||||
private static void SetLiveText(TextBox box, string text)
|
||||
{
|
||||
if (box.Text == text)
|
||||
return;
|
||||
ScrollViewer? scroll = box.GetVisualDescendants().OfType<ScrollViewer>().FirstOrDefault();
|
||||
bool follow = string.IsNullOrEmpty(box.Text) || scroll == null ||
|
||||
scroll.Offset.Y >= scroll.Extent.Height - scroll.Viewport.Height - 4;
|
||||
box.Text = text;
|
||||
if (!follow)
|
||||
return;
|
||||
// The start of the last line: the box shows the newest line from its left edge (a long log
|
||||
// line would otherwise scroll the box sideways).
|
||||
box.CaretIndex = text.LastIndexOf('\n') + 1;
|
||||
if (scroll == null)
|
||||
return;
|
||||
// The new text's height is known only after the next layout pass.
|
||||
EventHandler? once = null;
|
||||
once = (_, _) =>
|
||||
{
|
||||
box.LayoutUpdated -= once;
|
||||
scroll.ScrollToEnd();
|
||||
scroll.Offset = new Vector(0, scroll.Offset.Y);
|
||||
};
|
||||
box.LayoutUpdated += once;
|
||||
}
|
||||
|
||||
// ── commands ────────────────────────────────────────────────────────────
|
||||
|
||||
private bool TrySelected(out HeadlessCharacterStatus s)
|
||||
{
|
||||
s = null!;
|
||||
return _selectedId is int id && _roster.TryGet(id, out s!);
|
||||
}
|
||||
|
||||
private async Task SendCommandAsync()
|
||||
{
|
||||
if (!TrySelected(out HeadlessCharacterStatus s))
|
||||
return;
|
||||
string text = (CommandBox.Text ?? string.Empty).Trim();
|
||||
if (HeadlessCommandFile.ChatCommandProblem(text) is string problem)
|
||||
{
|
||||
ShowCommandStatus(problem, warn: true);
|
||||
return;
|
||||
}
|
||||
string? path = await WriteCommandAsync(s, HeadlessCommandFile.SendChatAction, text);
|
||||
if (path == null)
|
||||
return;
|
||||
_pending = new PendingCommand
|
||||
{
|
||||
Id = s.Id, Text = text, Path = path, SentUtc = DateTime.UtcNow, ChatAtSend = s.RecentChat,
|
||||
};
|
||||
CommandBox.Text = string.Empty;
|
||||
TimeSpan age = HeadlessStatusRules.Age(s, DateTime.UtcNow);
|
||||
ShowCommandStatus(HeadlessStatusRules.Freshness(age) == HeadlessFreshness.Fresh
|
||||
? $"Sent: {text}"
|
||||
: $"Sent: {text}, but this character isn't answering (no status for {age.TotalSeconds:0} s).", warn: false);
|
||||
}
|
||||
|
||||
private async Task ToggleMacroAsync()
|
||||
{
|
||||
if (!TrySelected(out HeadlessCharacterStatus s))
|
||||
return;
|
||||
bool turnOn = !s.MacroRunning;
|
||||
if (await WriteCommandAsync(s, HeadlessCommandFile.MacroAction, turnOn ? "on" : "off") != null)
|
||||
ShowCommandStatus(turnOn ? "Asked to start the macro." : "Asked to stop the macro.", warn: false);
|
||||
}
|
||||
|
||||
/// <summary>Writes one command file for <paramref name="s"/> (off the UI thread); null when it failed.</summary>
|
||||
private async Task<string?> WriteCommandAsync(HeadlessCharacterStatus s, string action, string value)
|
||||
{
|
||||
string commandsDir = Path.Combine(_host!.StatusDir(), HeadlessCommandFile.CommandsFolderName);
|
||||
int id = s.Id;
|
||||
try
|
||||
{
|
||||
string path = await Task.Run(() => HeadlessCommandFile.Write(commandsDir, id, action, value, DateTime.UtcNow));
|
||||
lock (_untaken)
|
||||
_untaken.Add((path, DateTime.UtcNow));
|
||||
return path;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ShowCommandStatus($"Couldn't write the command: {ex.Message}", warn: true);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdatePending(ReadResult r, DateTime nowUtc)
|
||||
{
|
||||
if (r.RemovedUntaken > 0)
|
||||
ShowCommandStatus("The character didn't take the command within a minute (not reading its commands?): it was removed.", warn: true);
|
||||
|
||||
PendingCommand? p = _pending;
|
||||
if (p == null)
|
||||
return;
|
||||
if (!p.Taken && r.PendingPath == p.Path && !r.PendingFileExists)
|
||||
{
|
||||
p.Taken = true;
|
||||
ShowCommandStatus($"Taken: {p.Text}. Waiting for a reply...", warn: false);
|
||||
}
|
||||
if (_roster.TryGet(p.Id, out HeadlessCharacterStatus? s))
|
||||
{
|
||||
HeadlessChatLine? reply = HeadlessChat.FirstReply(HeadlessChat.NewLines(p.ChatAtSend, s.RecentChat));
|
||||
if (reply is HeadlessChatLine line)
|
||||
{
|
||||
ShowCommandStatus($"{p.Text} -> {line.Text}", warn: false);
|
||||
_pending = null;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (nowUtc - p.SentUtc > ReplyWait)
|
||||
{
|
||||
ShowCommandStatus(p.Taken
|
||||
? $"{p.Text}: taken, no chat reply in {ReplyWait.TotalSeconds:0} s (see the log)."
|
||||
: $"{p.Text}: not taken yet after {ReplyWait.TotalSeconds:0} s.", warn: true);
|
||||
_pending = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void ShowCommandStatus(string text, bool warn)
|
||||
{
|
||||
CommandStatusText.Text = text;
|
||||
CommandStatusText.Foreground = warn ? WarnBrush : MutedBrush;
|
||||
}
|
||||
|
||||
// ── log out, log folder ─────────────────────────────────────────────────
|
||||
|
||||
private async Task LogOutAsync()
|
||||
{
|
||||
if (!TrySelected(out HeadlessCharacterStatus s) || s.HostPid <= 0)
|
||||
return;
|
||||
string name = s.Character.Length > 0 ? s.Character : "this character";
|
||||
var others = _roster.All.Where(o => o.HostPid == s.HostPid && o.Id != s.Id).Select(o => o.Character).ToList();
|
||||
string message =
|
||||
$"Log {name} out? This asks its rynth-headless.exe (PID {s.HostPid}) to log out and exit; it is closed after " +
|
||||
$"{HeadlessLaunch.StopGrace.TotalSeconds:0} s if it doesn't.";
|
||||
if (others.Count > 0)
|
||||
message += $"\n\nThe stop request is per process, and this process also runs {others.Count} other character(s) " +
|
||||
$"({string.Join(", ", others)}): they log out too.";
|
||||
if (_host!.AutoLaunch())
|
||||
message += "\n\nAutoLaunch is on: a checked account is started again. Uncheck it first to keep it out.";
|
||||
if (!await DecalBridgeDialog.AskAsync(this, "Log out headless character", message, "Log out", "Cancel"))
|
||||
return;
|
||||
string result;
|
||||
try { result = _host.LogOutProcess(s.HostPid); }
|
||||
catch (Exception ex) { result = "Couldn't stop it: " + ex.Message; }
|
||||
ShowCommandStatus(result, warn: false);
|
||||
}
|
||||
|
||||
private void OpenLogFolder()
|
||||
{
|
||||
try
|
||||
{
|
||||
string? log = _logPath;
|
||||
if (log != null && File.Exists(log))
|
||||
{
|
||||
Process.Start(new ProcessStartInfo("explorer.exe", "/select,\"" + log + "\"") { UseShellExecute = false });
|
||||
return;
|
||||
}
|
||||
string? dir = _logDirs.FirstOrDefault(Directory.Exists);
|
||||
if (dir != null)
|
||||
{
|
||||
Process.Start(new ProcessStartInfo("explorer.exe") { ArgumentList = { dir }, UseShellExecute = false });
|
||||
return;
|
||||
}
|
||||
ShowCommandStatus("No log folder found yet. Looked in: " + string.Join("; ", _logDirs), warn: true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ShowCommandStatus("Couldn't open the folder: " + ex.Message, warn: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -404,6 +404,10 @@
|
|||
AcceptsReturn="True"
|
||||
TextWrapping="NoWrap"
|
||||
MinHeight="56" />
|
||||
<Button x:Name="ShowHeadlessWindowButton"
|
||||
Content="Show headless clients"
|
||||
ToolTip.Tip="Opens the Headless window: what each headless character is doing (vitals, target, place, XP, chat and its log), with a command box, macro on/off and log out."
|
||||
HorizontalAlignment="Left" />
|
||||
<Button x:Name="StopHeadlessButton"
|
||||
Content="Log out headless clients"
|
||||
ToolTip.Tip="A headless client has no window to close: this asks every running rynth-headless.exe to log its character out and exit (closed after 20 s if it doesn't). With AutoLaunch on, uncheck the account first or it is started again."
|
||||
|
|
@ -614,6 +618,10 @@
|
|||
Background="#0F161D"
|
||||
BorderBrush="#243742"
|
||||
Foreground="#EAF0F4" />
|
||||
<Button x:Name="SessionsHeadlessButton"
|
||||
Content="Headless clients"
|
||||
ToolTip.Tip="Headless characters have no game window: this window shows what they are doing, their chat and log, and takes commands."
|
||||
HorizontalAlignment="Left" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
|
|
|||
|
|
@ -167,6 +167,7 @@ internal partial class MainWindow : Window
|
|||
_serverStatusTimer.Tick += async (_, _) => await RefreshServerStatusesAsync();
|
||||
_serverStatusTimer.Start();
|
||||
Closing += (_, _) => SaveWindowLayout();
|
||||
Closed += (_, _) => _headlessWindow?.Close();
|
||||
ShowVersion();
|
||||
AppendActivity("Avalonia launcher preview ready.");
|
||||
// One-line host/runtime sidecar check (full detail in Desktop RynthCore-Launcher.log).
|
||||
|
|
@ -263,6 +264,8 @@ internal partial class MainWindow : Window
|
|||
AutoLaunchHeaderCheckBox.IsCheckedChanged += (_, _) => SaveAutoLaunchPreference();
|
||||
SavePathsButton.Click += (_, _) => SaveRuntimePaths();
|
||||
StopHeadlessButton.Click += (_, _) => StopHeadlessClients();
|
||||
ShowHeadlessWindowButton.Click += (_, _) => ShowHeadlessWindow();
|
||||
SessionsHeadlessButton.Click += (_, _) => ShowHeadlessWindow();
|
||||
SaveBehaviorButton.Click += (_, _) => SaveLaunchBehavior();
|
||||
InjectRunningAcButton.Click += async (_, _) => await InjectRunningAcAsync();
|
||||
RefreshSessionsButton.Click += (_, _) => RefreshSessionState();
|
||||
|
|
@ -2498,6 +2501,68 @@ internal partial class MainWindow : Window
|
|||
(_settings.AutoLaunch ? " AutoLaunch is on: checked accounts are started again." : ""));
|
||||
}
|
||||
|
||||
// ── The Headless window (HeadlessWindow): what headless characters are doing ──
|
||||
private HeadlessWindow? _headlessWindow;
|
||||
|
||||
/// <summary>Runtime > Headless client > Show headless clients, and the button under Live Sessions.</summary>
|
||||
private void ShowHeadlessWindow()
|
||||
{
|
||||
if (_headlessWindow != null)
|
||||
{
|
||||
if (_headlessWindow.WindowState == WindowState.Minimized)
|
||||
_headlessWindow.WindowState = WindowState.Normal;
|
||||
_headlessWindow.Activate();
|
||||
return;
|
||||
}
|
||||
var host = new HeadlessWindowHost
|
||||
{
|
||||
Settings = _settings,
|
||||
SaveSettings = SaveSettings,
|
||||
// The folders rynth-headless uses: the launcher's settings, else the CLI's defaults (HeadlessDefaults.cs).
|
||||
StatusDir = () => string.IsNullOrWhiteSpace(_settings.HeadlessStatusDir)
|
||||
? Path.Combine(RynthInstallPaths.CoreLogsDir, "status")
|
||||
: Environment.ExpandEnvironmentVariables(_settings.HeadlessStatusDir.Trim().Trim('"')),
|
||||
ConfiguredSuiteDir = () => _settings.HeadlessSuiteDir ?? string.Empty,
|
||||
LaunchConfigDir = Path.Combine(AppSettingsStore.SettingsDirectoryPath, HeadlessLaunch.ConfigFolderName),
|
||||
LogOutProcess = LogOutHeadlessProcess,
|
||||
AutoLaunch = () => _settings.AutoLaunch,
|
||||
};
|
||||
_headlessWindow = new HeadlessWindow(host);
|
||||
_headlessWindow.Closed += (_, _) => _headlessWindow = null;
|
||||
_headlessWindow.Show();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Headless window's "Log out": the stop request of one rynth-headless process
|
||||
/// (<see cref="EndClientProcess"/>: log out, exit, killed after the grace time). The stop event is
|
||||
/// per process; the launcher starts one process per Headless account, so that is one character.
|
||||
/// Only a pid the enumeration just saw as rynth-headless is touched.
|
||||
/// </summary>
|
||||
private string LogOutHeadlessProcess(int pid)
|
||||
{
|
||||
Process[] clients = FindClientProcesses();
|
||||
try
|
||||
{
|
||||
if (!_headlessClientPids.Contains(pid))
|
||||
return $"PID {pid} isn't a running rynth-headless.exe any more; nothing to do.";
|
||||
foreach (Process p in clients)
|
||||
{
|
||||
int id;
|
||||
try { id = p.Id; } catch { continue; }
|
||||
if (id != pid)
|
||||
continue;
|
||||
EndClientProcess(p, pid);
|
||||
return $"Asked PID {pid} to log out and exit (closed after {HeadlessLaunch.StopGrace.TotalSeconds:0} s if it doesn't)." +
|
||||
(_settings.AutoLaunch ? " AutoLaunch is on: a checked account is started again." : "");
|
||||
}
|
||||
return $"PID {pid} isn't running any more.";
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (Process p in clients) p.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private Process[] AcClientsOnly(Process[] targets) =>
|
||||
_headlessClientPids.Count == 0 && _launchedHeadlessPids.Count == 0
|
||||
? targets
|
||||
|
|
|
|||
|
|
@ -71,6 +71,7 @@
|
|||
<Compile Include="..\RynthCore.App\DecalAccountModes.cs" Link="Shared\DecalAccountModes.cs" />
|
||||
<Compile Include="..\RynthCore.App\HeadlessAccountModes.cs" Link="Shared\HeadlessAccountModes.cs" />
|
||||
<Compile Include="..\RynthCore.App\HeadlessLaunch.cs" Link="Shared\HeadlessLaunch.cs" />
|
||||
<Compile Include="..\RynthCore.App\HeadlessMonitor.cs" Link="Shared\HeadlessMonitor.cs" />
|
||||
<Compile Include="..\RynthCore.App\PluginDefinition.cs" Link="Shared\PluginDefinition.cs" />
|
||||
<!-- The plugin API of the engine installed with this launcher (RynthUpdater.InstalledEngineApi). -->
|
||||
<Compile Include="..\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Shared\PluginContractVersion.cs" />
|
||||
|
|
|
|||
|
|
@ -108,4 +108,10 @@ internal sealed class AppSettings
|
|||
public double? WindowY { get; set; }
|
||||
public double? WindowWidth { get; set; }
|
||||
public double? WindowHeight { get; set; }
|
||||
|
||||
/// The Headless window's last size and place (HeadlessWindow; null = default, centred).
|
||||
public double? HeadlessWindowX { get; set; }
|
||||
public double? HeadlessWindowY { get; set; }
|
||||
public double? HeadlessWindowWidth { get; set; }
|
||||
public double? HeadlessWindowHeight { get; set; }
|
||||
}
|
||||
|
|
|
|||
723
src/RynthCore.App/HeadlessMonitor.cs
Normal file
723
src/RynthCore.App/HeadlessMonitor.cs
Normal file
|
|
@ -0,0 +1,723 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.App;
|
||||
|
||||
// ============================================================================
|
||||
// The launcher's Headless window (RynthCore.App.Avalonia\HeadlessWindow), without the UI.
|
||||
// BCL only, so tools\HeadlessWindowTests compiles it as it is.
|
||||
//
|
||||
// What a headless character tells the world is in files (src\RynthCore.Headless\Host\Status\
|
||||
// StatusExporter.cs is the writer and the authority on the schema):
|
||||
// <statusDir>\RynthCore.<id>.status.json every 1 s: the engine's "rynthcore.client-status/1"
|
||||
// fields, RynthAi's snapshot in "bot", "opos", and headless: true, hostPid, hostProcess.
|
||||
// <id> is a synthetic per-character id (odd, above a billion), not a process id.
|
||||
// <statusDir>\commands\RynthCore.<id>.<ticks>-<guid>.cmd.json the inbox, drained every
|
||||
// 200 ms, oldest first, each file deleted before it runs (the StatusAgent's format).
|
||||
// <suiteDir>\headless-<account>.log the character's own log (Bot.cs).
|
||||
// The window only reads these and writes command files; it never opens a socket or a process.
|
||||
// ============================================================================
|
||||
|
||||
/// <summary>A status dot: what one headless character is doing, as the status file says.</summary>
|
||||
internal enum HeadlessActivity
|
||||
{
|
||||
/// <summary>In the world with the macro running.</summary>
|
||||
Botting,
|
||||
/// <summary>In the world, macro off.</summary>
|
||||
Idle,
|
||||
/// <summary>In the world with no health left.</summary>
|
||||
Dead,
|
||||
/// <summary>Connecting, at the character list, or waiting to reconnect (inWorld false).</summary>
|
||||
Loading,
|
||||
/// <summary>The status file stopped changing (over <see cref="HeadlessStatusRules.StaleAfter"/>).</summary>
|
||||
Stale,
|
||||
}
|
||||
|
||||
internal enum HeadlessFreshness { Fresh, Stale, Gone }
|
||||
|
||||
internal enum HeadlessParseResult { Ok, NotHeadless, Broken }
|
||||
|
||||
/// <summary>One line of bot.recentChat: {"t": text, "c": AC chat type}.</summary>
|
||||
internal readonly record struct HeadlessChatLine(string Text, int Type);
|
||||
|
||||
/// <summary>What the window shows of one headless character, read from its status file.</summary>
|
||||
internal sealed class HeadlessCharacterStatus
|
||||
{
|
||||
public int Id { get; init; }
|
||||
public string Character { get; init; } = string.Empty;
|
||||
public string Server { get; init; } = string.Empty;
|
||||
/// <summary>Used only to find the character's log file (headless-<account>.log); never shown.</summary>
|
||||
public string Account { get; init; } = string.Empty;
|
||||
/// <summary>The file's "ts" (UTC); the file's write time when "ts" is missing or unreadable.</summary>
|
||||
public DateTime TimestampUtc { get; init; }
|
||||
public bool InWorld { get; init; }
|
||||
public int HostPid { get; init; }
|
||||
public string HostProcess { get; init; } = string.Empty;
|
||||
public long UptimeSec { get; init; }
|
||||
|
||||
public double VitaePct { get; init; }
|
||||
public double XpPerHour { get; init; }
|
||||
public long XpSession { get; init; }
|
||||
public int DeathsSession { get; init; }
|
||||
public double BurdenPct { get; init; }
|
||||
|
||||
public string Landblock { get; init; } = string.Empty;
|
||||
public bool Indoor { get; init; }
|
||||
public string Cell { get; init; } = string.Empty;
|
||||
/// <summary>World position from "opos" (192 units a landblock); null without one.</summary>
|
||||
public double? WorldX { get; init; }
|
||||
public double? WorldY { get; init; }
|
||||
public double? Z { get; init; }
|
||||
public double? Heading { get; init; }
|
||||
|
||||
/// <summary>False when "bot" is null (not in the world, or no RynthAi loaded).</summary>
|
||||
public bool HasBot { get; init; }
|
||||
public bool MacroRunning { get; init; }
|
||||
public string BotAction { get; init; } = string.Empty;
|
||||
public string CurrentState { get; init; } = string.Empty;
|
||||
public string MetaName { get; init; } = string.Empty;
|
||||
public string NavName { get; init; } = string.Empty;
|
||||
public long TargetId { get; init; }
|
||||
public string TargetLabel { get; init; } = string.Empty;
|
||||
public double TargetHealthPercent { get; init; }
|
||||
public long Health { get; init; }
|
||||
public long MaxHealth { get; init; }
|
||||
public long Stamina { get; init; }
|
||||
public long MaxStamina { get; init; }
|
||||
public long Mana { get; init; }
|
||||
public long MaxMana { get; init; }
|
||||
public long SessionKills { get; init; }
|
||||
public double KillsPerHour { get; init; }
|
||||
public IReadOnlyList<HeadlessChatLine> RecentChat { get; init; } = Array.Empty<HeadlessChatLine>();
|
||||
|
||||
public bool HasTarget => TargetId != 0;
|
||||
public bool HasVitals => HasBot && MaxHealth > 0;
|
||||
}
|
||||
|
||||
/// <summary>Parses a status file into <see cref="HeadlessCharacterStatus"/>.</summary>
|
||||
internal static class HeadlessStatusParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Parses <paramref name="json"/> (one status file). False for anything that isn't a headless
|
||||
/// character's status (a game client's own status file, a half-written or empty file).
|
||||
/// <paramref name="fileWriteUtc"/> stands in for a missing "ts".
|
||||
/// </summary>
|
||||
public static bool TryParse(string json, DateTime fileWriteUtc, out HeadlessCharacterStatus status) =>
|
||||
Parse(json, fileWriteUtc, out status) == HeadlessParseResult.Ok;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="TryParse"/> telling a complete file that isn't a headless character's
|
||||
/// (<see cref="HeadlessParseResult.NotHeadless"/>) from one that can't be read as JSON now: empty,
|
||||
/// truncated, caught mid-replace (<see cref="HeadlessParseResult.Broken"/>).
|
||||
/// </summary>
|
||||
public static HeadlessParseResult Parse(string json, DateTime fileWriteUtc, out HeadlessCharacterStatus status)
|
||||
{
|
||||
status = null!;
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
return HeadlessParseResult.Broken;
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement r = doc.RootElement;
|
||||
if (r.ValueKind != JsonValueKind.Object || !Bool(r, "headless"))
|
||||
return HeadlessParseResult.NotHeadless;
|
||||
int id = (int)Long(r, "pid");
|
||||
if (id <= 0)
|
||||
return HeadlessParseResult.NotHeadless;
|
||||
|
||||
DateTime ts = DateTime.TryParse(Str(r, "ts"), CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t)
|
||||
? DateTime.SpecifyKind(t, DateTimeKind.Utc)
|
||||
: fileWriteUtc;
|
||||
|
||||
r.TryGetProperty("opos", out JsonElement opos);
|
||||
bool hasOpos = opos.ValueKind == JsonValueKind.Object;
|
||||
r.TryGetProperty("bot", out JsonElement bot);
|
||||
bool hasBot = bot.ValueKind == JsonValueKind.Object;
|
||||
|
||||
status = new HeadlessCharacterStatus
|
||||
{
|
||||
Id = id,
|
||||
Character = Str(r, "character"),
|
||||
Server = Str(r, "server"),
|
||||
Account = Str(r, "account"),
|
||||
TimestampUtc = ts,
|
||||
InWorld = Bool(r, "inWorld"),
|
||||
HostPid = (int)Long(r, "hostPid"),
|
||||
HostProcess = Str(r, "hostProcess"),
|
||||
UptimeSec = Long(r, "uptimeSec"),
|
||||
VitaePct = Dbl(r, "vitaePct"),
|
||||
XpPerHour = Dbl(r, "xpPerHour"),
|
||||
XpSession = Long(r, "xpSession"),
|
||||
DeathsSession = (int)Long(r, "deathsSession"),
|
||||
BurdenPct = Dbl(r, "burdenPct"),
|
||||
Landblock = Str(r, "landblock"),
|
||||
Indoor = hasOpos && opos.TryGetProperty("indoor", out _) ? Bool(opos, "indoor") : Bool(r, "indoor"),
|
||||
Cell = hasOpos ? Str(opos, "cell") : string.Empty,
|
||||
WorldX = hasOpos ? NDbl(opos, "wx") : null,
|
||||
WorldY = hasOpos ? NDbl(opos, "wy") : null,
|
||||
Z = hasOpos ? NDbl(opos, "z") : null,
|
||||
Heading = hasOpos ? NDbl(opos, "heading") : null,
|
||||
HasBot = hasBot,
|
||||
MacroRunning = hasBot && Bool(bot, "macroRunning"),
|
||||
BotAction = hasBot ? Str(bot, "botAction") : string.Empty,
|
||||
CurrentState = hasBot ? Str(bot, "currentState") : string.Empty,
|
||||
MetaName = hasBot ? Str(bot, "currentMetaName") : string.Empty,
|
||||
NavName = hasBot ? Str(bot, "currentNavName") : string.Empty,
|
||||
TargetId = hasBot ? Long(bot, "currentTargetId") : 0,
|
||||
TargetLabel = hasBot ? Str(bot, "targetLabel") : string.Empty,
|
||||
TargetHealthPercent = hasBot ? Dbl(bot, "targetHealthPercent") : 0,
|
||||
Health = hasBot ? Long(bot, "playerHealth") : 0,
|
||||
MaxHealth = hasBot ? Long(bot, "playerMaxHealth") : 0,
|
||||
Stamina = hasBot ? Long(bot, "playerStamina") : 0,
|
||||
MaxStamina = hasBot ? Long(bot, "playerMaxStamina") : 0,
|
||||
Mana = hasBot ? Long(bot, "playerMana") : 0,
|
||||
MaxMana = hasBot ? Long(bot, "playerMaxMana") : 0,
|
||||
SessionKills = hasBot ? Long(bot, "sessionKills") : 0,
|
||||
KillsPerHour = hasBot ? Dbl(bot, "killsPerHour") : 0,
|
||||
RecentChat = hasBot ? Chat(bot) : Array.Empty<HeadlessChatLine>(),
|
||||
};
|
||||
return HeadlessParseResult.Ok;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return HeadlessParseResult.Broken; // mid-replace or truncated: the caller keeps what it had
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
return HeadlessParseResult.NotHeadless; // a field of an unexpected kind at the top
|
||||
}
|
||||
}
|
||||
|
||||
private static List<HeadlessChatLine> Chat(JsonElement bot)
|
||||
{
|
||||
var lines = new List<HeadlessChatLine>();
|
||||
if (!bot.TryGetProperty("recentChat", out JsonElement chat) || chat.ValueKind != JsonValueKind.Array)
|
||||
return lines;
|
||||
foreach (JsonElement e in chat.EnumerateArray())
|
||||
{
|
||||
if (e.ValueKind == JsonValueKind.Object)
|
||||
lines.Add(new HeadlessChatLine(Str(e, "t"), (int)Long(e, "c")));
|
||||
else if (e.ValueKind == JsonValueKind.String)
|
||||
lines.Add(new HeadlessChatLine(e.GetString() ?? string.Empty, 0));
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static string Str(JsonElement o, string name) =>
|
||||
o.TryGetProperty(name, out JsonElement v)
|
||||
? v.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => v.GetString() ?? string.Empty,
|
||||
JsonValueKind.Number => v.GetRawText(),
|
||||
_ => string.Empty,
|
||||
}
|
||||
: string.Empty;
|
||||
|
||||
private static bool Bool(JsonElement o, string name) =>
|
||||
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True;
|
||||
|
||||
private static double? NDbl(JsonElement o, string name) =>
|
||||
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out double d) ? d : null;
|
||||
|
||||
private static double Dbl(JsonElement o, string name) => NDbl(o, name) ?? 0;
|
||||
|
||||
private static long Long(JsonElement o, string name)
|
||||
{
|
||||
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number)
|
||||
return 0;
|
||||
if (v.TryGetInt64(out long l))
|
||||
return l;
|
||||
return v.TryGetDouble(out double d) && !double.IsNaN(d) ? (long)Math.Clamp(d, long.MinValue, long.MaxValue) : 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The stale and gone rules, and the status dot.</summary>
|
||||
internal static class HeadlessStatusRules
|
||||
{
|
||||
/// <summary>The exporter writes every second: older than this, the character isn't ticking.</summary>
|
||||
public static readonly TimeSpan StaleAfter = TimeSpan.FromSeconds(10);
|
||||
/// <summary>Older than this, the character is gone (the process ended without removing its files).</summary>
|
||||
public static readonly TimeSpan GoneAfter = TimeSpan.FromSeconds(30);
|
||||
|
||||
public static TimeSpan Age(HeadlessCharacterStatus s, DateTime nowUtc)
|
||||
{
|
||||
TimeSpan age = nowUtc - s.TimestampUtc;
|
||||
return age < TimeSpan.Zero ? TimeSpan.Zero : age;
|
||||
}
|
||||
|
||||
public static HeadlessFreshness Freshness(TimeSpan age) =>
|
||||
age > GoneAfter ? HeadlessFreshness.Gone : age > StaleAfter ? HeadlessFreshness.Stale : HeadlessFreshness.Fresh;
|
||||
|
||||
public static HeadlessActivity Activity(HeadlessCharacterStatus s, DateTime nowUtc)
|
||||
{
|
||||
if (Freshness(Age(s, nowUtc)) != HeadlessFreshness.Fresh)
|
||||
return HeadlessActivity.Stale;
|
||||
if (!s.InWorld)
|
||||
return HeadlessActivity.Loading;
|
||||
if (s.HasVitals && s.Health <= 0)
|
||||
return HeadlessActivity.Dead;
|
||||
return s.MacroRunning ? HeadlessActivity.Botting : HeadlessActivity.Idle;
|
||||
}
|
||||
|
||||
public static string ActivityText(HeadlessActivity a) => a switch
|
||||
{
|
||||
HeadlessActivity.Botting => "botting",
|
||||
HeadlessActivity.Idle => "idle",
|
||||
HeadlessActivity.Dead => "dead",
|
||||
HeadlessActivity.Loading => "not in the world",
|
||||
_ => "not answering",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the window's list: the last good status per character. A file that couldn't be read this
|
||||
/// time (being replaced) keeps its last status; a character whose file is gone, or whose status is
|
||||
/// older than <see cref="HeadlessStatusRules.GoneAfter"/>, leaves the list.
|
||||
/// </summary>
|
||||
internal sealed class HeadlessRoster
|
||||
{
|
||||
private readonly Dictionary<int, HeadlessCharacterStatus> _byId = new();
|
||||
|
||||
public IReadOnlyCollection<HeadlessCharacterStatus> All => _byId.Values;
|
||||
|
||||
public bool TryGet(int id, out HeadlessCharacterStatus status) => _byId.TryGetValue(id, out status!);
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="parsed"/>: the files read this time. <paramref name="unreadable"/>: ids whose
|
||||
/// file exists but didn't parse. Returns the list sorted by character name, then id.
|
||||
/// </summary>
|
||||
public List<HeadlessCharacterStatus> Update(IEnumerable<HeadlessCharacterStatus> parsed, IEnumerable<int> unreadable, DateTime nowUtc)
|
||||
{
|
||||
var seen = new HashSet<int>();
|
||||
foreach (HeadlessCharacterStatus s in parsed)
|
||||
{
|
||||
seen.Add(s.Id);
|
||||
// A file mid-replace can't go back in time: keep the newer status.
|
||||
if (!_byId.TryGetValue(s.Id, out HeadlessCharacterStatus? old) || s.TimestampUtc >= old.TimestampUtc)
|
||||
_byId[s.Id] = s;
|
||||
}
|
||||
foreach (int id in unreadable)
|
||||
seen.Add(id);
|
||||
foreach (int id in _byId.Keys.ToList())
|
||||
{
|
||||
if (!seen.Contains(id) ||
|
||||
HeadlessStatusRules.Freshness(HeadlessStatusRules.Age(_byId[id], nowUtc)) == HeadlessFreshness.Gone)
|
||||
_byId.Remove(id);
|
||||
}
|
||||
return _byId.Values
|
||||
.OrderBy(s => s.Character, StringComparer.OrdinalIgnoreCase)
|
||||
.ThenBy(s => s.Id)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>bot.recentChat: the combat spam filter and the lines new since an earlier snapshot.</summary>
|
||||
internal static class HeadlessChat
|
||||
{
|
||||
/// <summary>How many chat lines the window shows.</summary>
|
||||
public const int ShownLines = 30;
|
||||
|
||||
/// <summary>
|
||||
/// AC chat types that are pure combat spam (our hits, their hits, evades): hidden (21 and 22).
|
||||
/// </summary>
|
||||
public static bool IsCombatSpam(int type) => type is 21 or 22;
|
||||
|
||||
/// <summary>The last <paramref name="max"/> lines that aren't combat spam, oldest first.</summary>
|
||||
public static List<HeadlessChatLine> Visible(IReadOnlyList<HeadlessChatLine> lines, int max = ShownLines)
|
||||
{
|
||||
var shown = lines.Where(l => !IsCombatSpam(l.Type)).ToList();
|
||||
return shown.Count > max ? shown.GetRange(shown.Count - max, max) : shown;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The lines of <paramref name="current"/> after its overlap with the end of
|
||||
/// <paramref name="previous"/>. The export keeps the last 60 lines, so a newer list is the older
|
||||
/// one shifted left with new lines at the end (observe.py's new_chat). No overlap at all = every
|
||||
/// line is new.
|
||||
/// </summary>
|
||||
public static List<HeadlessChatLine> NewLines(IReadOnlyList<HeadlessChatLine> previous, IReadOnlyList<HeadlessChatLine> current)
|
||||
{
|
||||
if (previous.Count == 0)
|
||||
return current.ToList();
|
||||
for (int k = Math.Min(previous.Count, current.Count); k > 0; k--)
|
||||
{
|
||||
bool match = true;
|
||||
for (int i = 0; i < k && match; i++)
|
||||
match = previous[previous.Count - k + i] == current[i];
|
||||
if (match)
|
||||
return current.Skip(k).ToList();
|
||||
}
|
||||
return current.ToList();
|
||||
}
|
||||
|
||||
/// <summary>The first line in <paramref name="lines"/> that isn't combat spam, or null.</summary>
|
||||
public static HeadlessChatLine? FirstReply(IEnumerable<HeadlessChatLine> lines)
|
||||
{
|
||||
foreach (HeadlessChatLine l in lines)
|
||||
if (!IsCombatSpam(l.Type) && l.Text.Length > 0)
|
||||
return l;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map coordinates from a status file's opos world position.</summary>
|
||||
internal static class HeadlessCoords
|
||||
{
|
||||
/// <summary>
|
||||
/// (north/south, east/west) from world units (192 a landblock), north and east positive: the
|
||||
/// conversion of the StatusAgent's NavAtlasService.FromWorld and observe.py's map_of.
|
||||
/// </summary>
|
||||
public static (double Ns, double Ew) FromWorld(double wx, double wy) =>
|
||||
((wy / 24.0 - 1019.5) / 10.0, (wx / 24.0 - 1019.5) / 10.0);
|
||||
|
||||
/// <summary>"42.1N 33.6E" (RynthNet's CharactersModel.CoordsText).</summary>
|
||||
public static string Text(double ns, double ew) =>
|
||||
Math.Abs(ns).ToString("0.0", CultureInfo.InvariantCulture) + (ns >= 0 ? "N " : "S ") +
|
||||
Math.Abs(ew).ToString("0.0", CultureInfo.InvariantCulture) + (ew >= 0 ? "E" : "W");
|
||||
|
||||
/// <summary>
|
||||
/// Where the character is: "Outdoors 42.1N 33.6E (landblock A9B3)", "Indoors (landblock 01F5,
|
||||
/// cell 01F501BE)", or "unknown".
|
||||
/// </summary>
|
||||
public static string Where(HeadlessCharacterStatus s)
|
||||
{
|
||||
string lb = s.Landblock.Length >= 4 ? s.Landblock[^4..] : s.Landblock;
|
||||
if (s.Indoor)
|
||||
{
|
||||
if (lb.Length == 0) return "Indoors";
|
||||
return s.Cell.Length > 0 ? $"Indoors (landblock {lb}, cell {s.Cell})" : $"Indoors (landblock {lb})";
|
||||
}
|
||||
if (s.WorldX is double wx && s.WorldY is double wy)
|
||||
{
|
||||
var (ns, ew) = FromWorld(wx, wy);
|
||||
return lb.Length > 0 ? $"Outdoors {Text(ns, ew)} (landblock {lb})" : $"Outdoors {Text(ns, ew)}";
|
||||
}
|
||||
return lb.Length > 0 ? $"Outdoors (landblock {lb})" : "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Short numbers and durations for the details panel.</summary>
|
||||
internal static class HeadlessFormat
|
||||
{
|
||||
/// <summary>"950", "12.3k", "36.8M", "2.4B".</summary>
|
||||
public static string Number(double n)
|
||||
{
|
||||
double a = Math.Abs(n);
|
||||
string s = a >= 1e9 ? (n / 1e9).ToString("0.0", CultureInfo.InvariantCulture) + "B"
|
||||
: a >= 1e6 ? (n / 1e6).ToString("0.0", CultureInfo.InvariantCulture) + "M"
|
||||
: a >= 1e4 ? (n / 1e3).ToString("0.0", CultureInfo.InvariantCulture) + "k"
|
||||
: Math.Round(n).ToString("0", CultureInfo.InvariantCulture);
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>"45s", "12m 05s", "3h 12m", "2d 18h".</summary>
|
||||
public static string Duration(long seconds)
|
||||
{
|
||||
if (seconds < 0) seconds = 0;
|
||||
long d = seconds / 86400, h = seconds / 3600 % 24, m = seconds / 60 % 60, s = seconds % 60;
|
||||
if (d > 0) return $"{d}d {h}h";
|
||||
if (h > 0) return $"{h}h {m:00}m";
|
||||
if (m > 0) return $"{m}m {s:00}s";
|
||||
return $"{s}s";
|
||||
}
|
||||
|
||||
/// <summary>"165 / 230" (no maximum = "-").</summary>
|
||||
public static string Vital(long cur, long max) =>
|
||||
max <= 0 ? "-" : $"{cur.ToString(CultureInfo.InvariantCulture)} / {max.ToString(CultureInfo.InvariantCulture)}";
|
||||
|
||||
public static double Fraction(long cur, long max) => max <= 0 ? 0 : Math.Clamp((double)cur / max, 0, 1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The command inbox: the file the StatusAgent writes for the phone (LocalStatusServer.HandleCommand,
|
||||
/// Models.CommandFile), so a headless character takes it the same way (StatusExporter.DrainCommands).
|
||||
/// </summary>
|
||||
internal static class HeadlessCommandFile
|
||||
{
|
||||
public const string CommandsFolderName = "commands";
|
||||
public const string SendChatAction = "sendChat";
|
||||
public const string MacroAction = "macro";
|
||||
|
||||
/// <summary>Chat commands the window's command box sends (RynthAi, RynthNav, meta tools, RynthNet).</summary>
|
||||
public static readonly IReadOnlyList<string> AllowedPrefixes = new[] { "/ra", "/rnav", "/mt", "/rn" };
|
||||
|
||||
public const int MaxCommandLength = 400;
|
||||
|
||||
/// <summary>Why <paramref name="text"/> can't be sent (null = it can): one line starting with an allowed prefix.</summary>
|
||||
public static string? ChatCommandProblem(string? text)
|
||||
{
|
||||
string t = (text ?? string.Empty).Trim();
|
||||
if (t.Length == 0)
|
||||
return "Type a command first, for example /ra pause.";
|
||||
if (t.IndexOfAny(new[] { '\r', '\n' }) >= 0)
|
||||
return "One command per line.";
|
||||
if (t.Length > MaxCommandLength)
|
||||
return $"That command is longer than {MaxCommandLength} characters.";
|
||||
foreach (string p in AllowedPrefixes)
|
||||
{
|
||||
if (t.Length == p.Length && t.Equals(p, StringComparison.OrdinalIgnoreCase))
|
||||
return null;
|
||||
if (t.Length > p.Length && t.StartsWith(p, StringComparison.OrdinalIgnoreCase) && t[p.Length] == ' ')
|
||||
return null;
|
||||
}
|
||||
return "Only " + string.Join(", ", AllowedPrefixes) + " commands can be sent from here.";
|
||||
}
|
||||
|
||||
/// <summary>RynthCore.<id>.<ticks, 19 digits>-<guid>.cmd.json: sorts in submit order.</summary>
|
||||
public static string FileName(int id, DateTime nowUtc, Guid guid) =>
|
||||
$"RynthCore.{id.ToString(CultureInfo.InvariantCulture)}.{nowUtc.Ticks.ToString("D19", CultureInfo.InvariantCulture)}-{guid:N}.cmd.json";
|
||||
|
||||
/// <summary>{"schema":"rynthcore.command/1","pid":id,"action":..,"value":..,"ts":..}.</summary>
|
||||
public static string Json(int id, string action, string value, DateTime nowUtc)
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(stream))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("schema", "rynthcore.command/1");
|
||||
w.WriteNumber("pid", id);
|
||||
w.WriteString("action", action);
|
||||
w.WriteString("value", value);
|
||||
w.WriteString("ts", new DateTimeOffset(DateTime.SpecifyKind(nowUtc, DateTimeKind.Utc)));
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(stream.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes one command for character <paramref name="id"/> into <paramref name="commandsDir"/>:
|
||||
/// a temp file (".tmp", which the drain's *.cmd.json pattern never matches), then a rename, so
|
||||
/// the character never reads half a command. Returns the command file's path.
|
||||
/// </summary>
|
||||
public static string Write(string commandsDir, int id, string action, string value, DateTime nowUtc)
|
||||
{
|
||||
if (id <= 0) throw new ArgumentOutOfRangeException(nameof(id));
|
||||
if (string.IsNullOrWhiteSpace(action)) throw new ArgumentException("No action.", nameof(action));
|
||||
Directory.CreateDirectory(commandsDir);
|
||||
string dest = Path.Combine(commandsDir, FileName(id, nowUtc, Guid.NewGuid()));
|
||||
string tmp = dest + ".tmp";
|
||||
File.WriteAllText(tmp, Json(id, action, value ?? string.Empty, nowUtc), new UTF8Encoding(false));
|
||||
File.Move(tmp, dest, overwrite: false);
|
||||
return dest;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Finds and reads the status files.</summary>
|
||||
internal static class HeadlessStatusScanner
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads every headless status file in <paramref name="statusDir"/>. Files not written for a
|
||||
/// minute are skipped without being opened (the game clients' old ones stay in the folder).
|
||||
/// <paramref name="unreadable"/> gets the ids whose file couldn't be read or parsed this time.
|
||||
/// </summary>
|
||||
public static List<HeadlessCharacterStatus> Scan(string statusDir, DateTime nowUtc, out List<int> unreadable)
|
||||
{
|
||||
unreadable = new List<int>();
|
||||
var found = new List<HeadlessCharacterStatus>();
|
||||
string[] files;
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(statusDir))
|
||||
return found;
|
||||
files = Directory.GetFiles(statusDir, "RynthCore.*.status.json");
|
||||
}
|
||||
catch (IOException) { return found; }
|
||||
catch (UnauthorizedAccessException) { return found; }
|
||||
|
||||
foreach (string path in files)
|
||||
{
|
||||
if (!TryIdOf(path, out int id))
|
||||
continue;
|
||||
DateTime written;
|
||||
try { written = File.GetLastWriteTimeUtc(path); }
|
||||
catch (IOException) { continue; }
|
||||
catch (UnauthorizedAccessException) { continue; }
|
||||
if (nowUtc - written > HeadlessStatusRules.GoneAfter + TimeSpan.FromSeconds(30))
|
||||
continue;
|
||||
string? text = ReadShared(path);
|
||||
if (text == null)
|
||||
{
|
||||
unreadable.Add(id);
|
||||
continue;
|
||||
}
|
||||
switch (HeadlessStatusParser.Parse(text, written, out HeadlessCharacterStatus s))
|
||||
{
|
||||
case HeadlessParseResult.Ok:
|
||||
found.Add(s);
|
||||
break;
|
||||
case HeadlessParseResult.Broken:
|
||||
// Caught mid-write. The list keeps the character's last status if it had one
|
||||
// (HeadlessRoster); a game client's file in this state is simply not listed.
|
||||
unreadable.Add(id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>The <id> of RynthCore.<id>.status.json.</summary>
|
||||
public static bool TryIdOf(string path, out int id)
|
||||
{
|
||||
id = 0;
|
||||
string name = Path.GetFileName(path);
|
||||
const string prefix = "RynthCore.", suffix = ".status.json";
|
||||
if (!name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) || !name.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
string mid = name.Substring(prefix.Length, name.Length - prefix.Length - suffix.Length);
|
||||
return int.TryParse(mid, NumberStyles.None, CultureInfo.InvariantCulture, out id) && id > 0;
|
||||
}
|
||||
|
||||
/// <summary>The whole file, read while others may write or replace it; null when it can't be read now.</summary>
|
||||
public static string? ReadShared(string path)
|
||||
{
|
||||
for (int attempt = 0; attempt < 2; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
using var reader = new StreamReader(fs, Encoding.UTF8);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
catch (FileNotFoundException) { return null; }
|
||||
catch (IOException) { }
|
||||
catch (UnauthorizedAccessException) { }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A headless character's own log: where it is and its last lines.</summary>
|
||||
internal static class HeadlessLogs
|
||||
{
|
||||
public const int ShownLines = 50;
|
||||
|
||||
/// <summary>
|
||||
/// The suite folder rynth-headless 2026.10.31.1 and later use when the run config names none
|
||||
/// (HeadlessDefaults.SuiteDir in the CLI).
|
||||
/// </summary>
|
||||
public static string DefaultSuiteDir =>
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "headless");
|
||||
|
||||
/// <summary>The builds before 2026.10.31.1 used the development sandbox (docs\HEADLESS.md, P3).</summary>
|
||||
public const string LegacySuiteDir = @"C:\Projects\headless\sandbox\suite";
|
||||
|
||||
/// <summary>headless-<account>.log, the account's letters and digits kept (Bot.cs's Safe).</summary>
|
||||
public static string LogFileName(string account) =>
|
||||
"headless-" + string.Concat((account ?? string.Empty).Select(c => char.IsLetterOrDigit(c) ? c : '_')) + ".log";
|
||||
|
||||
/// <summary>
|
||||
/// The folders a log of <paramref name="account"/> may be in, most likely first: the suiteDir of
|
||||
/// every launcher run config (%APPDATA%\RynthCore\headless\launch_*.json) with a session for the
|
||||
/// account (no suiteDir = the default), then <paramref name="configuredSuiteDir"/>
|
||||
/// (AppSettings.HeadlessSuiteDir), the default and the legacy folder.
|
||||
/// </summary>
|
||||
public static List<string> CandidateSuiteDirs(string account, string? launchConfigDir, string? configuredSuiteDir,
|
||||
string defaultSuiteDir, string? legacySuiteDir = LegacySuiteDir)
|
||||
{
|
||||
var dirs = new List<string>();
|
||||
void Add(string? d)
|
||||
{
|
||||
d = (d ?? string.Empty).Trim().Trim('"');
|
||||
if (d.Length > 0 && !dirs.Contains(d, StringComparer.OrdinalIgnoreCase))
|
||||
dirs.Add(Environment.ExpandEnvironmentVariables(d));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(launchConfigDir) && Directory.Exists(launchConfigDir) && account.Length > 0)
|
||||
{
|
||||
foreach (string file in Directory.GetFiles(launchConfigDir, "launch_*.json").OrderBy(f => f, StringComparer.Ordinal))
|
||||
{
|
||||
string? text = HeadlessStatusScanner.ReadShared(file);
|
||||
if (text == null) continue;
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(text);
|
||||
JsonElement r = doc.RootElement;
|
||||
if (!r.TryGetProperty("sessions", out JsonElement sessions) || sessions.ValueKind != JsonValueKind.Array)
|
||||
continue;
|
||||
bool mine = sessions.EnumerateArray().Any(s =>
|
||||
s.ValueKind == JsonValueKind.Object &&
|
||||
(Matches(s, "account", account) || Matches(s, "launcherAccount", account)));
|
||||
if (!mine) continue;
|
||||
Add(r.TryGetProperty("suiteDir", out JsonElement sd) && sd.ValueKind == JsonValueKind.String
|
||||
? sd.GetString()
|
||||
: defaultSuiteDir);
|
||||
}
|
||||
catch (JsonException) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IOException) { }
|
||||
catch (UnauthorizedAccessException) { }
|
||||
|
||||
Add(configuredSuiteDir);
|
||||
Add(defaultSuiteDir);
|
||||
Add(legacySuiteDir);
|
||||
return dirs;
|
||||
}
|
||||
|
||||
private static bool Matches(JsonElement o, string name, string account) =>
|
||||
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String &&
|
||||
string.Equals(v.GetString(), account, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The first existing log of <paramref name="account"/> in <paramref name="dirs"/>, or null.</summary>
|
||||
public static string? Find(string account, IEnumerable<string> dirs)
|
||||
{
|
||||
string name = LogFileName(account);
|
||||
foreach (string d in dirs)
|
||||
{
|
||||
try
|
||||
{
|
||||
string p = Path.Combine(d, name);
|
||||
if (File.Exists(p)) return p;
|
||||
}
|
||||
catch (ArgumentException) { }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The last <paramref name="maxLines"/> lines of <paramref name="path"/>, reading at most the
|
||||
/// last <paramref name="maxBytes"/> (the logs grow to 100 MB and more). Opened shared, so the
|
||||
/// writing process is never disturbed. Null when it can't be read.
|
||||
/// </summary>
|
||||
public static List<string>? Tail(string path, int maxLines = ShownLines, int maxBytes = 128 * 1024)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
long start = Math.Max(0, fs.Length - maxBytes);
|
||||
fs.Seek(start, SeekOrigin.Begin);
|
||||
var buffer = new byte[fs.Length - start];
|
||||
int read = 0;
|
||||
while (read < buffer.Length)
|
||||
{
|
||||
int n = fs.Read(buffer, read, buffer.Length - read);
|
||||
if (n <= 0) break;
|
||||
read += n;
|
||||
}
|
||||
return LastLines(Encoding.UTF8.GetString(buffer, 0, read), maxLines, startsMidFile: start > 0);
|
||||
}
|
||||
catch (IOException) { return null; }
|
||||
catch (UnauthorizedAccessException) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The last <paramref name="maxLines"/> lines of <paramref name="text"/>. With
|
||||
/// <paramref name="startsMidFile"/> the first (partial) line is dropped; an unfinished last line is kept.
|
||||
/// </summary>
|
||||
public static List<string> LastLines(string text, int maxLines, bool startsMidFile)
|
||||
{
|
||||
var lines = text.Split('\n').Select(l => l.TrimEnd('\r')).ToList();
|
||||
if (startsMidFile && lines.Count > 0) lines.RemoveAt(0);
|
||||
if (lines.Count > 0 && lines[^1].Length == 0) lines.RemoveAt(lines.Count - 1);
|
||||
return lines.Count > maxLines ? lines.GetRange(lines.Count - maxLines, maxLines) : lines;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue