Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb40696d71
|
||
|
|
2a87046461
|
||
|
|
3eae21ef5a
|
||
|
|
6c60b86c78
|
||
|
|
ec79454d38
|
||
|
|
6e8694a68d
|
||
|
|
0fe4b12a0c
|
||
|
|
840c511618
|
||
|
|
74339a552c
|
No files matched your search
@@ -0,0 +1,17 @@
|
||||
<Project>
|
||||
|
||||
<!--
|
||||
Spike projects only. The spike/p0 branch is pushed but never merged (docs/spikes/README.md on
|
||||
main). This file deliberately does not import the repository's Directory.Build.props: throwaway
|
||||
proof-of-concept code skips the analyzer set and warnings-as-errors, but keeps NuGet Audit.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<NuGetAudit>true</NuGetAudit>
|
||||
<NuGetAuditMode>all</NuGetAuditMode>
|
||||
<Product>OmniDeck spikes</Product>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,15 @@
|
||||
<Application
|
||||
x:Class="MediaLab.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ui:ThemesDictionary Theme="Dark" />
|
||||
<ui:ControlsDictionary />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace MediaLab;
|
||||
|
||||
public partial class App : Application;
|
||||
@@ -0,0 +1,8 @@
|
||||
// The WPF SDK's implicit usings stop at System.* (and leave out System.IO because of Shapes.Path).
|
||||
global using System.IO;
|
||||
global using System.Windows;
|
||||
global using System.Windows.Controls;
|
||||
global using System.Windows.Media;
|
||||
global using LibVLCSharp.Shared;
|
||||
global using Path = System.IO.Path;
|
||||
global using MediaPlayer = LibVLCSharp.Shared.MediaPlayer;
|
||||
@@ -0,0 +1,69 @@
|
||||
<ui:FluentWindow
|
||||
x:Class="MediaLab.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||
xmlns:vlc="clr-namespace:LibVLCSharp.WPF;assembly=LibVLCSharp.WPF"
|
||||
Title="MediaLab — spike #6"
|
||||
Width="1280"
|
||||
Height="860"
|
||||
ExtendsContentIntoTitleBar="True"
|
||||
WindowBackdropType="Mica"
|
||||
WindowStartupLocation="CenterScreen">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition x:Name="LogRow" Height="170" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<ui:TitleBar x:Name="TitleBarControl" Title="MediaLab — spike #6: LibVLCSharp in a FluentWindow" Grid.Row="0" />
|
||||
|
||||
<Grid Grid.Row="1" Background="Black">
|
||||
<vlc:VideoView x:Name="Video">
|
||||
<!-- Overlay content: LibVLCSharp.WPF renders it in its own window above the video HWND. -->
|
||||
<Grid>
|
||||
<TextBlock
|
||||
Margin="12"
|
||||
Padding="8,4"
|
||||
HorizontalAlignment="Right"
|
||||
VerticalAlignment="Top"
|
||||
Background="#CCC42B1C"
|
||||
Foreground="White"
|
||||
Text="WPF overlay above the video" />
|
||||
<Border Padding="10,6" VerticalAlignment="Bottom" Background="#B0000000">
|
||||
<DockPanel LastChildFill="True">
|
||||
<ui:Button Margin="0,0,8,0" Click="OnPlayPause" Content="Play / Pause" DockPanel.Dock="Left" />
|
||||
<ui:Button Margin="8,0,0,0" Click="OnFullscreenInPlace" Content="Fullscreen" DockPanel.Dock="Right" />
|
||||
<TextBlock x:Name="TimeText" Margin="8,0,0,0" VerticalAlignment="Center" DockPanel.Dock="Right" Foreground="White" Text="0:00 / 0:00" />
|
||||
<Slider x:Name="SeekSlider" VerticalAlignment="Center" Maximum="1" Minimum="0" PreviewMouseDown="OnSeekPressed" PreviewMouseUp="OnSeekReleased" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</vlc:VideoView>
|
||||
</Grid>
|
||||
|
||||
<WrapPanel x:Name="LabBar" Grid.Row="2" Margin="8,6">
|
||||
<Button Margin="0,0,6,0" Padding="10,2" Click="OnOpenFile" Content="Open file…" />
|
||||
<Button Margin="0,0,6,0" Padding="10,2" Click="OnOpen1080" Content="Test 1080p30" />
|
||||
<Button Margin="0,0,6,0" Padding="10,2" Click="OnOpen2160" Content="Test 2160p60" />
|
||||
<Button Margin="0,0,12,0" Padding="10,2" Click="OnAddSubtitle" Content="Add .srt" />
|
||||
<Button Margin="0,0,6,0" Padding="10,2" Click="OnFullscreenInPlace" Content="Fullscreen: in place" />
|
||||
<Button Margin="0,0,6,0" Padding="10,2" Click="OnFullscreenWindow" Content="Fullscreen: own window" />
|
||||
<Button Margin="0,0,6,0" Padding="10,2" Click="OnPopOut" Content="Pop out" />
|
||||
<Button Margin="0,0,12,0" Padding="10,2" Click="OnHideShow" Content="Hide 3 s (tray)" />
|
||||
<Button Margin="0,0,6,0" Padding="10,2" Click="OnCapture" Content="Capture screen" />
|
||||
<Button Margin="0,0,6,0" Padding="10,2" Click="OnMemory" Content="Memory + stats" />
|
||||
</WrapPanel>
|
||||
|
||||
<TextBox
|
||||
x:Name="LogBox"
|
||||
Grid.Row="3"
|
||||
Margin="8,0,8,8"
|
||||
FontFamily="Cascadia Mono, Consolas"
|
||||
HorizontalScrollBarVisibility="Auto"
|
||||
IsReadOnly="True"
|
||||
VerticalScrollBarVisibility="Auto" />
|
||||
</Grid>
|
||||
</ui:FluentWindow>
|
||||
@@ -0,0 +1,476 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Windows.Threading;
|
||||
using LibVLCSharp.WPF;
|
||||
using Microsoft.Win32;
|
||||
using Wpf.Ui.Controls;
|
||||
|
||||
namespace MediaLab;
|
||||
|
||||
/// <summary>
|
||||
/// Spike #6 (issue #7). A FluentWindow (Mica, custom title bar) hosting LibVLCSharp's VideoView with
|
||||
/// WPF overlay controls, two fullscreen strategies, a pop-out, a tray-style hide, screen captures
|
||||
/// (the only way to see airspace problems) and memory/CPU readings. `--auto` runs it all unattended.
|
||||
/// </summary>
|
||||
public partial class MainWindow
|
||||
{
|
||||
private static readonly string DataRoot = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OmniDeck.Spikes");
|
||||
private static readonly string MediaDir = Path.Combine(DataRoot, "media");
|
||||
|
||||
private readonly string _outDir = Path.Combine(DataRoot, "medialab", DateTime.UtcNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture));
|
||||
private readonly DispatcherTimer _ui = new() { Interval = TimeSpan.FromMilliseconds(250) };
|
||||
private readonly StreamWriter _logFile;
|
||||
private LibVLC? _libVlc;
|
||||
private MediaPlayer? _player;
|
||||
private FullscreenState? _saved;
|
||||
private Window? _otherWindow;
|
||||
private VideoView? _otherView;
|
||||
private bool _seeking;
|
||||
private int _captures;
|
||||
private (TimeSpan Cpu, DateTime Wall) _cpuMark;
|
||||
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
Directory.CreateDirectory(_outDir);
|
||||
_logFile = new StreamWriter(Path.Combine(_outDir, "medialab.log")) { AutoFlush = true };
|
||||
Log($"MediaLab started; output in {_outDir}");
|
||||
LogMemory("before libVLC");
|
||||
Loaded += OnLoaded;
|
||||
Closed += (_, _) =>
|
||||
{
|
||||
_ui.Stop();
|
||||
_player?.Stop();
|
||||
_player?.Dispose();
|
||||
_libVlc?.Dispose();
|
||||
_logFile.Dispose();
|
||||
};
|
||||
DpiChanged += (_, e) => Log($"DpiChanged {e.OldDpi.PixelsPerDip:0.00} → {e.NewDpi.PixelsPerDip:0.00}");
|
||||
StateChanged += (_, _) => Log($"WindowState → {WindowState}");
|
||||
}
|
||||
|
||||
private sealed record FullscreenState(
|
||||
System.Windows.WindowState State, double Left, double Top, double Width, double Height, bool Topmost,
|
||||
ResizeMode Resize, GridLength LogHeight, WindowCornerPreference Corners);
|
||||
|
||||
private void OnLoaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
Core.Initialize();
|
||||
_libVlc = new LibVLC(enableDebugLogs: false);
|
||||
_libVlc.Log += (_, args) =>
|
||||
{
|
||||
if (args.Level >= LogLevel.Warning)
|
||||
{
|
||||
Dispatcher.InvokeAsync(() => Log($"libvlc {args.Level} [{args.Module}] {args.Message}"));
|
||||
}
|
||||
};
|
||||
_player = new MediaPlayer(_libVlc);
|
||||
_player.EncounteredError += (_, _) => Dispatcher.InvokeAsync(() => Log("MediaPlayer: EncounteredError"));
|
||||
Video.MediaPlayer = _player;
|
||||
Log($"libVLC {_libVlc.Version} ready in {sw.ElapsedMilliseconds} ms");
|
||||
LogMemory("libVLC idle");
|
||||
_ui.Tick += (_, _) => UpdateTime();
|
||||
_ui.Start();
|
||||
if (Environment.GetCommandLineArgs().Contains("--auto"))
|
||||
{
|
||||
Dispatcher.InvokeAsync(RunAutoAsync, DispatcherPriority.ContextIdle);
|
||||
}
|
||||
else if (Environment.GetCommandLineArgs().Contains("--auto-move"))
|
||||
{
|
||||
Dispatcher.InvokeAsync(RunMoveCheckAsync, DispatcherPriority.ContextIdle);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Playback ------------------------------------------------------------------------------
|
||||
|
||||
private void Play(string path)
|
||||
{
|
||||
using var media = new Media(_libVlc!, new Uri(path));
|
||||
_player!.Play(media);
|
||||
_cpuMark = (Process.GetCurrentProcess().TotalProcessorTime, DateTime.UtcNow);
|
||||
Log($"play {Path.GetFileName(path)}");
|
||||
}
|
||||
|
||||
private void UpdateTime()
|
||||
{
|
||||
if (_player is not { Length: > 0 })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TimeText.Text = $"{Fmt(_player.Time)} / {Fmt(_player.Length)}";
|
||||
if (!_seeking)
|
||||
{
|
||||
SeekSlider.Value = _player.Position;
|
||||
}
|
||||
|
||||
static string Fmt(long ms) => TimeSpan.FromMilliseconds(ms).ToString(@"m\:ss", CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private void LogPlayback(string label)
|
||||
{
|
||||
var stats = _player!.Media?.Statistics;
|
||||
var process = Process.GetCurrentProcess();
|
||||
var (cpu0, wall0) = _cpuMark;
|
||||
var cpuPercent = (process.TotalProcessorTime - cpu0).TotalMilliseconds / (DateTime.UtcNow - wall0).TotalMilliseconds / Environment.ProcessorCount * 100;
|
||||
_cpuMark = (process.TotalProcessorTime, DateTime.UtcNow);
|
||||
_player.Size(0, ref Unsafe.Width, ref Unsafe.Height);
|
||||
Log($"{label}: playing={_player.IsPlaying} time={_player.Time} ms state={_player.State} video={Unsafe.Width}x{Unsafe.Height} "
|
||||
+ $"displayed={stats?.DisplayedPictures} lost={stats?.LostPictures} cpu={cpuPercent:0.0}% of all cores");
|
||||
}
|
||||
|
||||
// libVLC's Size() takes refs; a tiny holder keeps the call site readable.
|
||||
private static class Unsafe
|
||||
{
|
||||
public static uint Width;
|
||||
public static uint Height;
|
||||
}
|
||||
|
||||
// ---- Fullscreen: in place (the shell window covers the monitor) -----------------------------
|
||||
|
||||
private void ToggleFullscreenInPlace()
|
||||
{
|
||||
if (_saved is { } s)
|
||||
{
|
||||
WindowCornerPreference = s.Corners;
|
||||
Topmost = s.Topmost;
|
||||
ResizeMode = s.Resize;
|
||||
Left = s.Left;
|
||||
Top = s.Top;
|
||||
Width = s.Width;
|
||||
Height = s.Height;
|
||||
WindowState = s.State;
|
||||
LogRow.Height = s.LogHeight;
|
||||
TitleBarControl.Visibility = Visibility.Visible;
|
||||
LabBar.Visibility = Visibility.Visible;
|
||||
LogBox.Visibility = Visibility.Visible;
|
||||
_saved = null;
|
||||
Log("fullscreen in place: off");
|
||||
return;
|
||||
}
|
||||
|
||||
_saved = new FullscreenState(WindowState, Left, Top, Width, Height, Topmost, ResizeMode, LogRow.Height, WindowCornerPreference);
|
||||
TitleBarControl.Visibility = Visibility.Collapsed;
|
||||
LabBar.Visibility = Visibility.Collapsed;
|
||||
LogBox.Visibility = Visibility.Collapsed;
|
||||
LogRow.Height = new GridLength(0);
|
||||
var px = Native.MonitorBounds(this);
|
||||
var dpi = VisualTreeHelper.GetDpi(this);
|
||||
WindowState = System.Windows.WindowState.Normal;
|
||||
WindowCornerPreference = WindowCornerPreference.DoNotRound;
|
||||
ResizeMode = ResizeMode.NoResize;
|
||||
Topmost = true;
|
||||
Left = px.X / dpi.DpiScaleX;
|
||||
Top = px.Y / dpi.DpiScaleY;
|
||||
Width = px.Width / dpi.DpiScaleX;
|
||||
Height = px.Height / dpi.DpiScaleY;
|
||||
Log($"fullscreen in place: on, monitor {px.Width}x{px.Height} px at ({px.X},{px.Y}), scale {dpi.DpiScaleX:0.00}");
|
||||
}
|
||||
|
||||
// ---- Fullscreen in its own window, and pop-out: the player moves to another VideoView -------
|
||||
|
||||
private void OpenOtherWindow(bool fullscreen, bool restartVout)
|
||||
{
|
||||
if (_otherWindow is not null)
|
||||
{
|
||||
CloseOtherWindow(restartVout);
|
||||
return;
|
||||
}
|
||||
|
||||
var view = new VideoView();
|
||||
var back = new Wpf.Ui.Controls.Button { Content = fullscreen ? "Exit fullscreen" : "Back to main window", Margin = new Thickness(16), HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top };
|
||||
back.Click += (_, _) => CloseOtherWindow(restartVout);
|
||||
view.Content = new Grid { Children = { back } };
|
||||
_otherView = view;
|
||||
|
||||
if (fullscreen)
|
||||
{
|
||||
var px = Native.MonitorBounds(this);
|
||||
var dpi = VisualTreeHelper.GetDpi(this);
|
||||
_otherWindow = new Window
|
||||
{
|
||||
WindowStyle = WindowStyle.None,
|
||||
ResizeMode = ResizeMode.NoResize,
|
||||
Topmost = true,
|
||||
ShowInTaskbar = false,
|
||||
Background = Brushes.Black,
|
||||
Left = px.X / dpi.DpiScaleX,
|
||||
Top = px.Y / dpi.DpiScaleY,
|
||||
Width = px.Width / dpi.DpiScaleX,
|
||||
Height = px.Height / dpi.DpiScaleY,
|
||||
Content = view,
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
_otherWindow = new FluentWindow
|
||||
{
|
||||
Title = "MediaLab pop-out",
|
||||
Width = 800,
|
||||
Height = 480,
|
||||
ExtendsContentIntoTitleBar = true,
|
||||
WindowBackdropType = WindowBackdropType.Mica,
|
||||
Content = new Grid
|
||||
{
|
||||
RowDefinitions = { new RowDefinition { Height = GridLength.Auto }, new RowDefinition() },
|
||||
Children = { new TitleBar { Title = "MediaLab pop-out" }, view },
|
||||
},
|
||||
};
|
||||
Grid.SetRow(view, 1);
|
||||
}
|
||||
|
||||
_otherWindow.KeyDown += (_, e) =>
|
||||
{
|
||||
if (e.Key == System.Windows.Input.Key.Escape)
|
||||
{
|
||||
CloseOtherWindow(restartVout);
|
||||
}
|
||||
};
|
||||
view.Loaded += (_, _) => MovePlayer(Video, view, restartVout);
|
||||
_otherWindow.Show();
|
||||
Log($"{(fullscreen ? "fullscreen window" : "pop-out")} opened (restart vout: {restartVout})");
|
||||
}
|
||||
|
||||
private void CloseOtherWindow(bool restartVout)
|
||||
{
|
||||
if (_otherWindow is null || _otherView is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
MovePlayer(_otherView, Video, restartVout);
|
||||
_otherWindow.Close();
|
||||
_otherWindow = null;
|
||||
_otherView = null;
|
||||
Log("other window closed; player back in the main window");
|
||||
}
|
||||
|
||||
private void MovePlayer(VideoView from, VideoView to, bool restartVout)
|
||||
{
|
||||
var time = _player!.Time;
|
||||
from.MediaPlayer = null;
|
||||
to.MediaPlayer = _player;
|
||||
if (restartVout && _player.VideoTrack is var track and >= 0)
|
||||
{
|
||||
// libVLC 3 keeps drawing into the window it started with; re-selecting the video track
|
||||
// makes it create a new video output on the new HWND. The decoder then restarts
|
||||
// mid-GOP, so seek to the current time to resume from a keyframe (with --seek-on-move).
|
||||
_player.SetVideoTrack(-1);
|
||||
_player.SetVideoTrack(track);
|
||||
if (Environment.GetCommandLineArgs().Contains("--seek-on-move"))
|
||||
{
|
||||
_player.Time = time;
|
||||
}
|
||||
}
|
||||
|
||||
Log($"player moved at {time} ms (restart vout: {restartVout}); playing={_player.IsPlaying}");
|
||||
}
|
||||
|
||||
// ---- Captures and readings -----------------------------------------------------------------
|
||||
|
||||
private string Capture(string label, Window? window = null)
|
||||
{
|
||||
var path = Path.Combine(_outDir, $"{++_captures:00}-{label}.png");
|
||||
Native.CaptureScreen(Native.WindowBounds(window ?? this), path);
|
||||
Log($"captured {Path.GetFileName(path)}");
|
||||
return path;
|
||||
}
|
||||
|
||||
private void LogMemory(string label)
|
||||
{
|
||||
using var p = Process.GetCurrentProcess();
|
||||
Log($"memory {label}: private commit {p.PrivateMemorySize64 / 1048576.0:F0} MB, working set {p.WorkingSet64 / 1048576.0:F0} MB");
|
||||
}
|
||||
|
||||
private void Log(string line)
|
||||
{
|
||||
var stamped = $"{DateTime.Now:HH:mm:ss.fff} {line}";
|
||||
_logFile.WriteLine(stamped);
|
||||
LogBox.AppendText(stamped + Environment.NewLine);
|
||||
LogBox.ScrollToEnd();
|
||||
}
|
||||
|
||||
// ---- Unattended run: `MediaLab.exe --auto` -----------------------------------------------------
|
||||
|
||||
// `--auto-move`: only the player hand-over to another window, captured at 0.5 s and 2 s.
|
||||
private async Task RunMoveCheckAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
Play(Path.Combine(MediaDir, "test-1080p30.mp4"));
|
||||
await Task.Delay(4500);
|
||||
OpenOtherWindow(fullscreen: true, restartVout: true);
|
||||
await Task.Delay(500);
|
||||
Capture("move-0.5s", _otherWindow);
|
||||
await Task.Delay(1500);
|
||||
Capture("move-2s", _otherWindow);
|
||||
LogPlayback("after the move");
|
||||
CloseOtherWindow(restartVout: true);
|
||||
await Task.Delay(500);
|
||||
Capture("move-back-0.5s");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"MOVE FAILED: {ex}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await Task.Delay(500);
|
||||
Close();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunAutoAsync()
|
||||
{
|
||||
var media1080 = Path.Combine(MediaDir, "test-1080p30.mp4");
|
||||
var media2160 = Path.Combine(MediaDir, "test-2160p60.mp4");
|
||||
try
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
Play(media1080);
|
||||
await Task.Delay(4000);
|
||||
LogPlayback("1080p30 in the window");
|
||||
LogMemory("1080p30 playing");
|
||||
Capture("1080p-window");
|
||||
|
||||
_player!.AddSlave(MediaSlaveType.Subtitle, new Uri(Path.ChangeExtension(media1080, ".srt")).AbsoluteUri, true);
|
||||
await Task.Delay(2500);
|
||||
Capture("1080p-subtitle");
|
||||
|
||||
ToggleFullscreenInPlace();
|
||||
await Task.Delay(2500);
|
||||
LogPlayback("fullscreen in place");
|
||||
Capture("fullscreen-in-place");
|
||||
ToggleFullscreenInPlace();
|
||||
await Task.Delay(2000);
|
||||
Capture("back-from-fullscreen");
|
||||
|
||||
foreach (var restart in new[] { false, true })
|
||||
{
|
||||
OpenOtherWindow(fullscreen: true, restartVout: restart);
|
||||
await Task.Delay(3000);
|
||||
LogPlayback($"own fullscreen window, restart={restart}");
|
||||
Capture($"own-window-restart-{restart}", _otherWindow);
|
||||
CloseOtherWindow(restart);
|
||||
await Task.Delay(2500);
|
||||
LogPlayback($"back in the main window, restart={restart}");
|
||||
Capture($"back-from-own-window-restart-{restart}");
|
||||
}
|
||||
|
||||
OpenOtherWindow(fullscreen: false, restartVout: true);
|
||||
await Task.Delay(3000);
|
||||
Capture("popout", _otherWindow);
|
||||
CloseOtherWindow(restartVout: true);
|
||||
await Task.Delay(2000);
|
||||
|
||||
Hide();
|
||||
await Task.Delay(2000);
|
||||
Show();
|
||||
Activate();
|
||||
await Task.Delay(2000);
|
||||
LogPlayback("after hide/show");
|
||||
Capture("after-hide-show");
|
||||
|
||||
Play(media2160);
|
||||
await Task.Delay(6000);
|
||||
LogPlayback("2160p60 in the window");
|
||||
LogMemory("2160p60 playing");
|
||||
Capture("2160p60-window");
|
||||
|
||||
_player.Stop();
|
||||
await Task.Delay(1500);
|
||||
LogMemory("stopped");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"AUTO FAILED: {ex}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await Task.Delay(500);
|
||||
Close();
|
||||
}
|
||||
}
|
||||
|
||||
// ---- UI handlers ---------------------------------------------------------------------------
|
||||
|
||||
private void OnPlayPause(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (_player is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_player.IsPlaying)
|
||||
{
|
||||
_player.Pause();
|
||||
}
|
||||
else
|
||||
{
|
||||
_player.Play();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSeekPressed(object sender, System.Windows.Input.MouseButtonEventArgs e) => _seeking = true;
|
||||
|
||||
private void OnSeekReleased(object sender, System.Windows.Input.MouseButtonEventArgs e)
|
||||
{
|
||||
_seeking = false;
|
||||
if (_player is not null)
|
||||
{
|
||||
_player.Position = (float)SeekSlider.Value;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnOpenFile(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dialog = new OpenFileDialog { Filter = "Media|*.mp4;*.mkv;*.webm;*.avi;*.mov;*.mp3;*.flac;*.m4a|All files|*.*" };
|
||||
if (dialog.ShowDialog(this) == true)
|
||||
{
|
||||
Play(dialog.FileName);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnOpen1080(object sender, RoutedEventArgs e) => Play(Path.Combine(MediaDir, "test-1080p30.mp4"));
|
||||
|
||||
private void OnOpen2160(object sender, RoutedEventArgs e) => Play(Path.Combine(MediaDir, "test-2160p60.mp4"));
|
||||
|
||||
private void OnAddSubtitle(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dialog = new OpenFileDialog { Filter = "Subtitles|*.srt;*.ass;*.ssa;*.vtt", InitialDirectory = MediaDir };
|
||||
if (dialog.ShowDialog(this) == true)
|
||||
{
|
||||
_player?.AddSlave(MediaSlaveType.Subtitle, new Uri(dialog.FileName).AbsoluteUri, true);
|
||||
Log($"subtitle {Path.GetFileName(dialog.FileName)}");
|
||||
}
|
||||
}
|
||||
|
||||
private void OnFullscreenInPlace(object sender, RoutedEventArgs e) => ToggleFullscreenInPlace();
|
||||
|
||||
private void OnFullscreenWindow(object sender, RoutedEventArgs e) => OpenOtherWindow(fullscreen: true, restartVout: true);
|
||||
|
||||
private void OnPopOut(object sender, RoutedEventArgs e) => OpenOtherWindow(fullscreen: false, restartVout: true);
|
||||
|
||||
private async void OnHideShow(object sender, RoutedEventArgs e)
|
||||
{
|
||||
Hide();
|
||||
await Task.Delay(3000);
|
||||
Show();
|
||||
Activate();
|
||||
LogPlayback("after hide/show");
|
||||
}
|
||||
|
||||
private void OnCapture(object sender, RoutedEventArgs e) => Capture("manual", _otherWindow);
|
||||
|
||||
private void OnMemory(object sender, RoutedEventArgs e)
|
||||
{
|
||||
LogMemory("now");
|
||||
if (_player is not null)
|
||||
{
|
||||
LogPlayback("now");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- Spike #6 (issue #7): LibVLCSharp's VideoView inside a WPF-UI FluentWindow: airspace, overlay
|
||||
controls, fullscreen, pop-out, and what libVLC adds to the install size. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<!-- x64 only, like OmniDeck: keeps the win-x86 libVLC copy out of the output. -->
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<!-- The libVLC package picks architectures from $(Platform); AnyCPU would copy all three. -->
|
||||
<VlcWindowsX86Enabled>false</VlcWindowsX86Enabled>
|
||||
<VlcWindowsArm64Enabled>false</VlcWindowsArm64Enabled>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="LibVLCSharp.WPF" Version="3.10.2" />
|
||||
<PackageReference Include="VideoLAN.LibVLC.Windows" Version="3.0.24" />
|
||||
<PackageReference Include="WPF-UI" Version="4.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- `-p:TrimVlc=true`: the plugin set SPEC §3.6 asks for (codecs, demux, audio/video output,
|
||||
subtitles), to measure the size the installer would really carry. -->
|
||||
<ItemGroup Condition="'$(TrimVlc)' == 'true'">
|
||||
<VlcWindowsX64IncludeFiles Include="libvlc.dll;libvlccore.dll" />
|
||||
<VlcWindowsX64IncludeFiles Include="plugins\access\%2A;plugins\audio_filter\%2A;plugins\audio_mixer\%2A;plugins\audio_output\%2A" />
|
||||
<VlcWindowsX64IncludeFiles Include="plugins\codec\%2A;plugins\demux\%2A;plugins\packetizer\%2A;plugins\stream_filter\%2A" />
|
||||
<VlcWindowsX64IncludeFiles Include="plugins\text_renderer\%2A;plugins\spu\%2A;plugins\video_chroma\%2A;plugins\video_filter\%2A;plugins\video_output\%2A;plugins\misc\%2A" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Media.Imaging;
|
||||
|
||||
namespace MediaLab;
|
||||
|
||||
/// <summary>Monitor bounds for fullscreen, and screen captures that show what the user really sees.</summary>
|
||||
internal static class Native
|
||||
{
|
||||
/// <summary>The bounds, in device pixels, of the monitor the window is mostly on.</summary>
|
||||
public static Int32Rect MonitorBounds(Window window)
|
||||
{
|
||||
var monitor = MonitorFromWindow(new WindowInteropHelper(window).Handle, MonitorDefaultToNearest);
|
||||
var info = new MonitorInfo { Size = Marshal.SizeOf<MonitorInfo>() };
|
||||
GetMonitorInfo(monitor, ref info);
|
||||
return new Int32Rect(info.Monitor.Left, info.Monitor.Top, info.Monitor.Right - info.Monitor.Left, info.Monitor.Bottom - info.Monitor.Top);
|
||||
}
|
||||
|
||||
/// <summary>The window's on-screen rectangle in device pixels (DWM extended frame bounds).</summary>
|
||||
public static Int32Rect WindowBounds(Window window)
|
||||
{
|
||||
var hwnd = new WindowInteropHelper(window).Handle;
|
||||
if (DwmGetWindowAttribute(hwnd, DwmwaExtendedFrameBounds, out var r, Marshal.SizeOf<Rect>()) != 0)
|
||||
{
|
||||
GetWindowRect(hwnd, out r);
|
||||
}
|
||||
|
||||
return new Int32Rect(r.Left, r.Top, r.Right - r.Left, r.Bottom - r.Top);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies a screen rectangle (composited by DWM, layered windows included) to a PNG. The video HWND
|
||||
/// and LibVLCSharp's overlay window are separate windows, so only a screen capture shows airspace.
|
||||
/// </summary>
|
||||
public static void CaptureScreen(Int32Rect area, string pngPath)
|
||||
{
|
||||
var screenDc = GetDC(IntPtr.Zero);
|
||||
var memDc = CreateCompatibleDC(screenDc);
|
||||
var bitmap = CreateCompatibleBitmap(screenDc, area.Width, area.Height);
|
||||
var old = SelectObject(memDc, bitmap);
|
||||
try
|
||||
{
|
||||
BitBlt(memDc, 0, 0, area.Width, area.Height, screenDc, area.X, area.Y, SrcCopy | CaptureBlt);
|
||||
var source = Imaging.CreateBitmapSourceFromHBitmap(bitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
|
||||
var encoder = new PngBitmapEncoder();
|
||||
encoder.Frames.Add(BitmapFrame.Create(source));
|
||||
using var file = File.Create(pngPath);
|
||||
encoder.Save(file);
|
||||
}
|
||||
finally
|
||||
{
|
||||
SelectObject(memDc, old);
|
||||
DeleteObject(bitmap);
|
||||
DeleteDC(memDc);
|
||||
_ = ReleaseDC(IntPtr.Zero, screenDc);
|
||||
}
|
||||
}
|
||||
|
||||
private const uint MonitorDefaultToNearest = 2;
|
||||
private const int DwmwaExtendedFrameBounds = 9;
|
||||
private const uint SrcCopy = 0x00CC0020;
|
||||
private const uint CaptureBlt = 0x40000000;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Rect
|
||||
{
|
||||
public int Left;
|
||||
public int Top;
|
||||
public int Right;
|
||||
public int Bottom;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct MonitorInfo
|
||||
{
|
||||
public int Size;
|
||||
public Rect Monitor;
|
||||
public Rect Work;
|
||||
public uint Flags;
|
||||
}
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint flags);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool GetMonitorInfo(IntPtr monitor, ref MonitorInfo info);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool GetWindowRect(IntPtr hwnd, out Rect rect);
|
||||
|
||||
[DllImport("dwmapi.dll")]
|
||||
private static extern int DwmGetWindowAttribute(IntPtr hwnd, int attribute, out Rect value, int size);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetDC(IntPtr hwnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
private static extern IntPtr CreateCompatibleDC(IntPtr dc);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
private static extern IntPtr CreateCompatibleBitmap(IntPtr dc, int width, int height);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
private static extern IntPtr SelectObject(IntPtr dc, IntPtr obj);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
private static extern bool BitBlt(IntPtr dest, int x, int y, int w, int h, IntPtr src, int sx, int sy, uint rop);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
private static extern bool DeleteObject(IntPtr obj);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
private static extern bool DeleteDC(IntPtr dc);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<Solution>
|
||||
<Project Path="MediaLab/MediaLab.csproj" />
|
||||
<Project Path="ProviderProbe/ProviderProbe.csproj" />
|
||||
<Project Path="ThemeLab/ThemeLab.csproj" />
|
||||
<Project Path="WebLab/WebLab.csproj" />
|
||||
</Solution>
|
||||
@@ -0,0 +1,280 @@
|
||||
// Spike #7 (issue #8): probe stock data providers and keep the raw responses for freezing models.
|
||||
//
|
||||
// dotnet run --project spikes/ProviderProbe -- stooq
|
||||
// dotnet run --project spikes/ProviderProbe -- twelvedata
|
||||
//
|
||||
// Output goes to %LocalAppData%\OmniDeck.Spikes\providers\. Rules (docs/spikes/README.md): single
|
||||
// plain requests, no bot-challenge solving. The Twelve Data key comes from OD_TWELVEDATA_KEY, is
|
||||
// sent in the Authorization header (never in a URL) and is never printed or written to disk.
|
||||
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
var outDir = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OmniDeck.Spikes", "providers");
|
||||
Directory.CreateDirectory(outDir);
|
||||
var stamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss");
|
||||
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
|
||||
http.DefaultRequestHeaders.UserAgent.ParseAdd("OmniDeck-Spike/0.1 (+https://github.com/poli0981/OmniDeck)");
|
||||
|
||||
var rows = new List<string>();
|
||||
|
||||
switch (args.FirstOrDefault())
|
||||
{
|
||||
case "stooq":
|
||||
await ProbeAsync("stooq-history", "https://stooq.com/q/d/l/?s=aapl.us&i=d", apiKey: null);
|
||||
await ProbeAsync("stooq-quote", "https://stooq.com/q/l/?s=aapl.us&f=sd2t2ohlcv&h&e=csv", apiKey: null);
|
||||
break;
|
||||
|
||||
case "twelvedata":
|
||||
var key = Environment.GetEnvironmentVariable("OD_TWELVEDATA_KEY");
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
Console.Error.WriteLine("Set OD_TWELVEDATA_KEY (a free key from https://twelvedata.com/pricing) first.");
|
||||
return 2;
|
||||
}
|
||||
|
||||
// Free plan: 8 credits per minute. Calls are paced 10 s apart so even the 3-symbol batch
|
||||
// (3 credits) never pushes a minute over the limit.
|
||||
(string Name, string Path)[] calls =
|
||||
[
|
||||
("quote-aapl", "quote?symbol=AAPL"),
|
||||
("quote-batch3", "quote?symbol=AAPL,MSFT,SPY"),
|
||||
("ts-1m-daily", "time_series?symbol=AAPL&interval=1day&outputsize=22"),
|
||||
("ts-6m-daily", "time_series?symbol=AAPL&interval=1day&outputsize=126"),
|
||||
("ts-1y-daily", "time_series?symbol=AAPL&interval=1day&outputsize=252"),
|
||||
("ts-5y-weekly", "time_series?symbol=AAPL&interval=1week&outputsize=261"),
|
||||
("search-sap", "symbol_search?symbol=SAP"),
|
||||
("quote-sap-xetr", "quote?symbol=SAP&exchange=XETR"),
|
||||
("quote-vod-lse", "quote?symbol=VOD&exchange=LSE"),
|
||||
("quote-asml-euronext", "quote?symbol=ASML&exchange=Euronext"),
|
||||
("quote-spx-index", "quote?symbol=SPX"),
|
||||
("api-usage", "api_usage"),
|
||||
];
|
||||
for (var i = 0; i < calls.Length; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(10));
|
||||
}
|
||||
|
||||
await ProbeAsync($"td-{calls[i].Name}", $"https://api.twelvedata.com/{calls[i].Path}", key);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case "shapes":
|
||||
// P3 addendum to docs/spikes/07-providers.md: the answers OmniDeck's parser has not seen from a
|
||||
// real key. Prints structure only (HTTP status, shape, field names, error codes and messages,
|
||||
// which credit headers came back), never a figure or the key, and saves nothing.
|
||||
// dotnet run --project spikes/ProviderProbe -- shapes [429]
|
||||
var shapesKey = Environment.GetEnvironmentVariable("OD_TWELVEDATA_KEY");
|
||||
if (string.IsNullOrWhiteSpace(shapesKey))
|
||||
{
|
||||
Console.Error.WriteLine("Set OD_TWELVEDATA_KEY first; the key is only sent to Twelve Data, never printed.");
|
||||
return 2;
|
||||
}
|
||||
|
||||
// About 10 credits, paced 10 s apart to stay under 8 per minute.
|
||||
(string Name, string Path)[] shapes =
|
||||
[
|
||||
("batch-with-unknown", "quote?symbol=AAPL,ZZZZQX"),
|
||||
("batch-with-plan-gated", "quote?symbol=AAPL,SAP:XETR"),
|
||||
("mic-code-form", "quote?symbol=SAP&mic_code=XETR"),
|
||||
("single-unknown", "quote?symbol=ZZZZQX"),
|
||||
("trailing-comma", "quote?symbol=AAPL,"),
|
||||
("dotted-symbol", "quote?symbol=BRK.B"),
|
||||
("series-unknown", "time_series?symbol=ZZZZQX&interval=1day&outputsize=5"),
|
||||
];
|
||||
for (var i = 0; i < shapes.Length; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(10));
|
||||
}
|
||||
|
||||
await ShapeAsync(shapes[i].Name, $"https://api.twelvedata.com/{shapes[i].Path}", shapesKey);
|
||||
}
|
||||
|
||||
if (args.Contains("429"))
|
||||
{
|
||||
// Nine more credits at once, to see what going over the minute's eight looks like.
|
||||
Console.WriteLine("Waiting a minute, then nine quotes at once...");
|
||||
await Task.Delay(TimeSpan.FromSeconds(61));
|
||||
for (var i = 0; i < 9; i++)
|
||||
{
|
||||
await ShapeAsync($"burst-{i + 1}", "https://api.twelvedata.com/quote?symbol=AAPL", shapesKey);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
case "verify-models":
|
||||
// Deserializes the newest saved Twelve Data responses with the frozen models.
|
||||
string Latest(string name) => Directory.GetFiles(outDir, $"*-td-{name}.json").Max()!;
|
||||
T Read<T>(string name) => JsonSerializer.Deserialize<T>(File.ReadAllText(Latest(name)), TwelveData.Json)!;
|
||||
var quote = Read<TdQuote>("quote-aapl");
|
||||
Console.WriteLine($"quote: {quote.Symbol} {quote.Close} {quote.Currency} ({quote.PercentChange:+0.00;-0.00}%), 52w {quote.FiftyTwoWeek?.Low}-{quote.FiftyTwoWeek?.High}, market open {quote.IsMarketOpen}");
|
||||
var batch = Read<Dictionary<string, TdQuote>>("quote-batch3");
|
||||
Console.WriteLine($"batch: {string.Join(", ", batch.Select(kv => $"{kv.Key} {kv.Value.Close}"))}");
|
||||
foreach (var range in new[] { "ts-1m-daily", "ts-6m-daily", "ts-1y-daily", "ts-5y-weekly" })
|
||||
{
|
||||
var series = Read<TdTimeSeries>(range);
|
||||
Console.WriteLine($"{range}: {series.Values.Count} bars {series.Meta.Interval}, {series.Values[^1].Datetime} -> {series.Values[0].Datetime}, last close {series.Values[0].Close}, tz {series.Meta.ExchangeTimezone}");
|
||||
}
|
||||
|
||||
var search = Read<TdSymbolSearch>("search-sap-showplan");
|
||||
Console.WriteLine($"search: {string.Join("; ", search.Data.Take(4).Select(l => $"{l.Symbol}@{l.MicCode} {l.InstrumentType} needs {l.Access?.Plan}"))}");
|
||||
var usage = Read<TdApiUsage>("api-usage");
|
||||
Console.WriteLine($"usage: {usage.DailyUsage}/{usage.PlanDailyLimit} today, {usage.CurrentUsage}/{usage.PlanLimit} this minute, plan {usage.PlanCategory}");
|
||||
var error = Read<TdError>("quote-sap-xetr");
|
||||
Console.WriteLine($"error: {error.Code} {error.Message[..60]}...");
|
||||
return 0;
|
||||
|
||||
default:
|
||||
Console.Error.WriteLine("usage: ProviderProbe stooq | twelvedata | shapes [429] | verify-models");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var summary = Path.Combine(outDir, $"{stamp}-{args[0]}-summary.md");
|
||||
await File.WriteAllLinesAsync(summary,
|
||||
[
|
||||
"| Call | HTTP | Content-Type | ms | Credits used/left | Verdict |",
|
||||
"|---|---|---|---|---|---|",
|
||||
.. rows,
|
||||
]);
|
||||
Console.WriteLine($"\nSummary: {summary}");
|
||||
return 0;
|
||||
|
||||
async Task ProbeAsync(string name, string url, string? apiKey)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
if (apiKey is not null)
|
||||
{
|
||||
request.Headers.TryAddWithoutValidation("Authorization", $"apikey {apiKey}");
|
||||
}
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
using var response = await http.SendAsync(request);
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
sw.Stop();
|
||||
|
||||
var contentType = response.Content.Headers.ContentType?.ToString() ?? "-";
|
||||
var credits = Header(response, "api-credits-used") is { } used ? $"{used}/{Header(response, "api-credits-left")}" : "-";
|
||||
var verdict = Classify(body);
|
||||
var ext = contentType.Contains("json", StringComparison.OrdinalIgnoreCase) ? "json"
|
||||
: contentType.Contains("csv", StringComparison.OrdinalIgnoreCase) ? "csv" : "txt";
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, $"{stamp}-{name}.{ext}"), body, Encoding.UTF8);
|
||||
|
||||
rows.Add($"| `{name}` | {(int)response.StatusCode} | {contentType} | {sw.ElapsedMilliseconds} | {credits} | {verdict} |");
|
||||
Console.WriteLine($"{name,-22} {(int)response.StatusCode} {sw.ElapsedMilliseconds,5} ms {credits,-9} {verdict}");
|
||||
}
|
||||
|
||||
async Task ShapeAsync(string name, string url, string apiKey)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
request.Headers.TryAddWithoutValidation("Authorization", $"apikey {apiKey}");
|
||||
using var response = await http.SendAsync(request);
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
var credits = string.Join(", ", new[] { "api-credits-used", "api-credits-left" }.Where(response.Headers.Contains));
|
||||
Console.WriteLine($"{name,-24} HTTP {(int)response.StatusCode} credit headers: {(credits.Length == 0 ? "none" : credits)}");
|
||||
Console.WriteLine(" " + Describe(body));
|
||||
}
|
||||
|
||||
static string Describe(string body)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(body);
|
||||
return Shape(document.RootElement);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return "not JSON";
|
||||
}
|
||||
}
|
||||
|
||||
static string Shape(JsonElement element)
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return element.ValueKind.ToString();
|
||||
}
|
||||
|
||||
if (ErrorOf(element) is { } error)
|
||||
{
|
||||
return error;
|
||||
}
|
||||
|
||||
static string Fields(JsonElement value) => string.Join(",", value.EnumerateObject().Select(p => p.Name).Order(StringComparer.Ordinal));
|
||||
if (element.TryGetProperty("symbol", out _))
|
||||
{
|
||||
return "flat quote; fields: " + Fields(element);
|
||||
}
|
||||
|
||||
if (element.TryGetProperty("values", out _))
|
||||
{
|
||||
return "series; fields: " + Fields(element);
|
||||
}
|
||||
|
||||
return "keyed by symbol: " + string.Join("; ", element.EnumerateObject().Select(p => $"{p.Name} => {(ErrorOf(p.Value) ?? (p.Value.ValueKind == JsonValueKind.Object ? "quote" : p.Value.ValueKind.ToString()))}"));
|
||||
}
|
||||
|
||||
static string? ErrorOf(JsonElement element) =>
|
||||
element.ValueKind == JsonValueKind.Object && element.TryGetProperty("status", out var status) && status.ValueKind == JsonValueKind.String && status.GetString() == "error"
|
||||
? $"error code={(element.TryGetProperty("code", out var code) ? code.ToString() : "?")} message=\"{(element.TryGetProperty("message", out var message) ? message.GetString() : "")}\""
|
||||
: null;
|
||||
|
||||
static string? Header(HttpResponseMessage response, string name) =>
|
||||
response.Headers.TryGetValues(name, out var values) ? values.FirstOrDefault() : null;
|
||||
|
||||
static string Classify(string body)
|
||||
{
|
||||
var head = body.Length > 600 ? body[..600] : body;
|
||||
if (head.StartsWith("Date,", StringComparison.Ordinal) || head.StartsWith("Symbol,", StringComparison.Ordinal))
|
||||
{
|
||||
return "CSV data";
|
||||
}
|
||||
|
||||
if (head.Contains("verify your browser", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "browser check (JavaScript proof of work)";
|
||||
}
|
||||
|
||||
if (head.Contains("apikey", StringComparison.OrdinalIgnoreCase) && !head.TrimStart().StartsWith('{'))
|
||||
{
|
||||
return "API key required";
|
||||
}
|
||||
|
||||
if (head.Contains("Exceeded the daily hits limit", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "daily limit";
|
||||
}
|
||||
|
||||
if (head.TrimStart().StartsWith('{') || head.TrimStart().StartsWith('['))
|
||||
{
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(body);
|
||||
if (doc.RootElement.ValueKind == JsonValueKind.Object
|
||||
&& doc.RootElement.TryGetProperty("status", out var status) && status.GetString() == "error")
|
||||
{
|
||||
var code = doc.RootElement.TryGetProperty("code", out var c) ? c.ToString() : "?";
|
||||
var message = doc.RootElement.TryGetProperty("message", out var m) ? m.GetString() : "";
|
||||
return $"error {code}: {Truncate(message, 90)}";
|
||||
}
|
||||
|
||||
return "JSON data";
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return "malformed JSON";
|
||||
}
|
||||
}
|
||||
|
||||
return $"other: {Truncate(head.ReplaceLineEndings(" "), 60)}";
|
||||
}
|
||||
|
||||
static string Truncate(string? text, int max) =>
|
||||
text is null ? "" : text.Length <= max ? text.Replace("|", "\\|") : text[..max].Replace("|", "\\|") + "…";
|
||||
@@ -0,0 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- Spike #7 (issue #8): stock data providers. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,44 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
// The Twelve Data response shapes frozen by spike #7 (docs/spikes/07-providers.md). Numbers arrive as
|
||||
// JSON strings, so the options read numbers from strings; names are snake_case.
|
||||
internal static class TwelveData
|
||||
{
|
||||
public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
|
||||
NumberHandling = JsonNumberHandling.AllowReadingFromString,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>GET /quote. The batch form (symbol=A,B,C) returns an object keyed by symbol.</summary>
|
||||
internal sealed record TdQuote(
|
||||
string Symbol, string Name, string Exchange, string MicCode, string Currency, string Datetime, long Timestamp,
|
||||
long? LastQuoteAt, decimal Open, decimal High, decimal Low, decimal Close, long? Volume, decimal PreviousClose,
|
||||
decimal Change, decimal PercentChange, bool IsMarketOpen, TdFiftyTwoWeek? FiftyTwoWeek);
|
||||
|
||||
internal sealed record TdFiftyTwoWeek(decimal Low, decimal High, string Range);
|
||||
|
||||
/// <summary>GET /time_series. Values are newest first; Datetime is a date for 1day/1week bars.</summary>
|
||||
internal sealed record TdTimeSeries(TdSeriesMeta Meta, IReadOnlyList<TdBar> Values, string Status);
|
||||
|
||||
internal sealed record TdSeriesMeta(
|
||||
string Symbol, string Interval, string Currency, string ExchangeTimezone, string Exchange, string MicCode, string Type);
|
||||
|
||||
internal sealed record TdBar(string Datetime, decimal Open, decimal High, decimal Low, decimal Close, long? Volume);
|
||||
|
||||
/// <summary>GET /symbol_search (free). With show_plan=true each listing carries the plan it needs.</summary>
|
||||
internal sealed record TdSymbolSearch(IReadOnlyList<TdListing> Data, string Status);
|
||||
|
||||
internal sealed record TdListing(
|
||||
string Symbol, string InstrumentName, string Exchange, string MicCode, string ExchangeTimezone,
|
||||
string InstrumentType, string Country, string Currency, TdAccess? Access);
|
||||
|
||||
internal sealed record TdAccess(string Global, string Plan);
|
||||
|
||||
/// <summary>GET /api_usage (1 credit).</summary>
|
||||
internal sealed record TdApiUsage(string Timestamp, int CurrentUsage, int PlanLimit, int DailyUsage, int PlanDailyLimit, string PlanCategory);
|
||||
|
||||
/// <summary>Any error; the HTTP status is mirrored in Code (401 no key, 404 symbol/plan, 429 credits).</summary>
|
||||
internal sealed record TdError(int Code, string Message, string Status);
|
||||
@@ -0,0 +1,33 @@
|
||||
# OmniDeck P0 spike harnesses
|
||||
|
||||
This is the `spike/p0` branch: throwaway proof-of-concept code for the P0 spikes. It is pushed but
|
||||
**never merged**. Notes and decisions live on `main` in `docs/spikes/`, and each note names the commit
|
||||
of this branch that it measured.
|
||||
|
||||
- Build: `dotnet build spikes/OmniDeck.Spikes.slnx`. The solution is separate from `OmniDeck.slnx`,
|
||||
and `spikes/Directory.Build.props` replaces the repository's analyzer set.
|
||||
- Data: `%LocalAppData%\OmniDeck.Spikes\` (WebView2 profiles, CSV samples, raw responses, logs). Never
|
||||
in the working tree.
|
||||
- Secrets: environment variables only.
|
||||
|
||||
| Harness | Spikes | Run |
|
||||
|---|---|---|
|
||||
| `ProviderProbe` | #7 providers | `dotnet run --project spikes/ProviderProbe -- stooq` · `-- twelvedata` (needs `OD_TWELVEDATA_KEY`) · `-- verify-models` (frozen models vs. saved responses) |
|
||||
| `ThemeLab` | #5 preset swap | `dotnet run --project spikes/ThemeLab` (interactive) · `-- --auto` (measurements → `theme\*.log`) |
|
||||
| `WebLab` | #1 DRM · #2 sign-in · #3 memory · #4 CDP | `dotnet run --project spikes/WebLab` (interactive) · `-- --auto` (EME, CDP and a short ladder) · `-- --wv2-args=...` (browser arguments) |
|
||||
|
||||
WebLab keeps WebView2 profiles in `%LocalAppData%\OmniDeck.Spikes\WebView2` (one profile per catalog
|
||||
`profile` group, so sign-ins persist across runs), memory samples in `memory\*.csv` (one row per process
|
||||
per 2 s sample, with the current phase) and its log in `weblab\*.log`. Sign-ins are done by hand in its
|
||||
window; the lab never touches the user agent.
|
||||
| `MediaLab` | #6 LibVLCSharp | `dotnet run --project spikes/MediaLab` (interactive) · `-- --auto` · `-- --auto-move --seek-on-move` · `dotnet build spikes/MediaLab -c Release -p:TrimVlc=true` (SPEC plugin set) |
|
||||
|
||||
MediaLab plays local test clips from `%LocalAppData%\OmniDeck.Spikes\media\`, generated with ffmpeg
|
||||
(nothing is downloaded):
|
||||
|
||||
```powershell
|
||||
ffmpeg -f lavfi -i "testsrc=size=1920x1080:rate=30" -f lavfi -i "sine=frequency=440" -t 60 -c:v libx264 -pix_fmt yuv420p -c:a aac -shortest test-1080p30.mp4
|
||||
ffmpeg -f lavfi -i "testsrc2=size=3840x2160:rate=60" -f lavfi -i "sine=frequency=660" -t 20 -c:v libx264 -preset ultrafast -pix_fmt yuv420p -c:a aac -shortest test-2160p60.mp4
|
||||
```
|
||||
|
||||
Screen captures and the log land in `medialab\<timestamp>\`.
|
||||
@@ -0,0 +1,38 @@
|
||||
<Application
|
||||
x:Class="ThemeLab.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ui:ThemesDictionary Theme="Dark" />
|
||||
<ui:ControlsDictionary />
|
||||
<!-- The preset layer is appended (and later replaced in place) by PresetEngine. -->
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<!--
|
||||
Od styles: BasedOn the WPF-UI defaults, but every size comes from an Od.* token through
|
||||
DynamicResource. WPF-UI 4.3 sets Padding from StaticResource ButtonPadding, which a preset
|
||||
swap cannot change; these setters can.
|
||||
-->
|
||||
<Style
|
||||
x:Key="OdButtonStyle"
|
||||
BasedOn="{StaticResource DefaultUiButtonStyle}"
|
||||
TargetType="{x:Type ui:Button}">
|
||||
<Setter Property="Padding" Value="{DynamicResource Od.Padding.Control}" />
|
||||
<Setter Property="MinHeight" Value="{DynamicResource Od.HitTarget.Min}" />
|
||||
<Setter Property="FontSize" Value="{DynamicResource Od.Font.Body}" />
|
||||
</Style>
|
||||
<Style
|
||||
x:Key="OdTextBoxStyle"
|
||||
BasedOn="{StaticResource DefaultUiTextBoxStyle}"
|
||||
TargetType="{x:Type ui:TextBox}">
|
||||
<Setter Property="Padding" Value="{DynamicResource Od.Padding.Control}" />
|
||||
<Setter Property="MinHeight" Value="{DynamicResource Od.HitTarget.Min}" />
|
||||
<Setter Property="FontSize" Value="{DynamicResource Od.Font.Body}" />
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace ThemeLab;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
protected override void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
// The preset layer must exist before the first window resolves its DynamicResource tokens.
|
||||
PresetEngine.Apply(PresetEngine.Build(Preset.Standard, textScale: 1.0));
|
||||
base.OnStartup(e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// The WPF SDK's implicit usings stop at System.*; the WPF namespaces this lab uses everywhere.
|
||||
global using System.Windows;
|
||||
global using System.Windows.Controls;
|
||||
global using System.Windows.Media;
|
||||
@@ -0,0 +1,124 @@
|
||||
<ui:FluentWindow
|
||||
x:Class="ThemeLab.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:ThemeLab"
|
||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||
Title="ThemeLab — spike #5"
|
||||
Width="1320"
|
||||
Height="900"
|
||||
ExtendsContentIntoTitleBar="True"
|
||||
WindowBackdropType="Mica"
|
||||
WindowStartupLocation="CenterScreen">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="230" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<ui:TitleBar Title="ThemeLab — spike #5: runtime preset swap" Grid.Row="0" />
|
||||
|
||||
<Grid Grid.Row="1" Margin="12,0,12,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="300" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Lab controls use fixed defaults on purpose: they must not move while presets swap. -->
|
||||
<StackPanel Grid.Column="0" Margin="0,0,12,0">
|
||||
<TextBlock FontWeight="SemiBold" Text="Preset" />
|
||||
<RadioButton Checked="OnPresetChecked" Content="Dynamic" GroupName="preset" Tag="Dynamic" />
|
||||
<RadioButton Checked="OnPresetChecked" Content="Standard" GroupName="preset" IsChecked="True" Tag="Standard" />
|
||||
<RadioButton Checked="OnPresetChecked" Content="Comfort" GroupName="preset" Tag="Comfort" />
|
||||
|
||||
<TextBlock Margin="0,12,0,0" FontWeight="SemiBold" Text="Theme (independent axis)" />
|
||||
<RadioButton Checked="OnThemeChecked" Content="Dark" GroupName="theme" IsChecked="True" Tag="Dark" />
|
||||
<RadioButton Checked="OnThemeChecked" Content="Light" GroupName="theme" Tag="Light" />
|
||||
<RadioButton Checked="OnThemeChecked" Content="Follow Windows" GroupName="theme" Tag="System" />
|
||||
|
||||
<CheckBox x:Name="ApplyTextScale" Margin="0,12,0,0" Checked="OnTextScaleToggled" Content="Apply Windows text size" Unchecked="OnTextScaleToggled" />
|
||||
<TextBlock x:Name="TextScaleInfo" TextWrapping="Wrap" />
|
||||
|
||||
<Button Margin="0,12,0,0" HorizontalAlignment="Stretch" Click="OnBenchmark" Content="Benchmark: swap presets ×30" />
|
||||
<Button Margin="0,6,0,0" HorizontalAlignment="Stretch" Click="OnStress" Content="Stress: add 300 controls" />
|
||||
<Button Margin="0,6,0,0" HorizontalAlignment="Stretch" Click="OnProbe" Content="Probe controls under each preset" />
|
||||
<Button Margin="0,6,0,0" HorizontalAlignment="Stretch" Click="OnFrozenStoryboardTest" Content="Test DynamicResource in a style storyboard" />
|
||||
<Button Margin="0,6,0,0" HorizontalAlignment="Stretch" Click="OnCopyLog" Content="Copy log" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Sample surface: everything here consumes Od.* tokens or WPF-UI defaults. -->
|
||||
<ScrollViewer Grid.Column="1" VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel>
|
||||
<TextBlock FontSize="{DynamicResource Od.Font.H1}" FontWeight="SemiBold" Text="Heading 1 (Od.Font.H1)" />
|
||||
<TextBlock FontSize="{DynamicResource Od.Font.H2}" FontWeight="SemiBold" Text="Heading 2 (Od.Font.H2)" />
|
||||
<TextBlock
|
||||
Margin="{DynamicResource Od.Margin.Item}"
|
||||
FontSize="{DynamicResource Od.Font.Body}"
|
||||
Text="Body text (Od.Font.Body). The quick brown fox jumps over the lazy dog; Đồng hồ, máy tính, thời tiết; 時計と電卓。"
|
||||
TextWrapping="Wrap" />
|
||||
|
||||
<ui:Card x:Name="ProbeCard" Margin="{DynamicResource Od.Margin.Item}">
|
||||
<StackPanel>
|
||||
<TextBlock FontSize="{DynamicResource Od.Font.Caption}" Text="WPF-UI defaults (no Od style): Padding comes from StaticResource ButtonPadding" />
|
||||
<WrapPanel Margin="0,8,0,0">
|
||||
<ui:Button x:Name="ProbeDefaultButton" Margin="0,0,8,8" Content="Default ui:Button" />
|
||||
<ui:Button Margin="0,0,8,8" Appearance="Primary" Content="Primary" />
|
||||
<ui:TextBox x:Name="ProbeDefaultTextBox" Width="220" Margin="0,0,8,8" PlaceholderText="Default ui:TextBox" />
|
||||
<ui:ToggleSwitch Margin="0,0,8,8" Content="Toggle" />
|
||||
<ComboBox Width="160" Margin="0,0,8,8" SelectedIndex="0">
|
||||
<ComboBoxItem Content="ComboBox" />
|
||||
<ComboBoxItem Content="Second" />
|
||||
</ComboBox>
|
||||
<ui:NumberBox Width="160" Margin="0,0,8,8" Value="5" />
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
</ui:Card>
|
||||
|
||||
<ui:Card Margin="{DynamicResource Od.Margin.Item}">
|
||||
<StackPanel>
|
||||
<TextBlock FontSize="{DynamicResource Od.Font.Caption}" Text="Od styles: BasedOn WPF-UI, sizes from Od.* via DynamicResource" />
|
||||
<WrapPanel Margin="0,8,0,0">
|
||||
<ui:Button x:Name="ProbeOdButton" Margin="0,0,8,8" Content="Od ui:Button" Style="{StaticResource OdButtonStyle}" />
|
||||
<ui:TextBox x:Name="ProbeOdTextBox" Width="220" Margin="0,0,8,8" PlaceholderText="Od ui:TextBox" Style="{StaticResource OdTextBoxStyle}" />
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
</ui:Card>
|
||||
|
||||
<Border
|
||||
Width="260"
|
||||
Margin="{DynamicResource Od.Margin.Item}"
|
||||
Padding="{DynamicResource Od.Padding.Card}"
|
||||
HorizontalAlignment="Left"
|
||||
local:OdMotion.HoverScale="True"
|
||||
Background="{DynamicResource CardBackground}"
|
||||
BorderBrush="{DynamicResource CardBorderBrush}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="{DynamicResource Od.Corner.Radius}">
|
||||
<TextBlock FontSize="{DynamicResource Od.Font.Body}" Text="Hover me (Od.Motion via code)" />
|
||||
</Border>
|
||||
|
||||
<ui:InfoBar
|
||||
Title="Stale data"
|
||||
Margin="{DynamicResource Od.Margin.Item}"
|
||||
IsClosable="False"
|
||||
IsOpen="True"
|
||||
Message="ui:InfoBar under the current preset."
|
||||
Severity="Warning" />
|
||||
|
||||
<WrapPanel x:Name="StressHost" />
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Grid>
|
||||
|
||||
<TextBox
|
||||
x:Name="LogBox"
|
||||
Grid.Row="2"
|
||||
Margin="12,0,12,12"
|
||||
AcceptsReturn="True"
|
||||
FontFamily="Cascadia Mono, Consolas"
|
||||
HorizontalScrollBarVisibility="Auto"
|
||||
IsReadOnly="True"
|
||||
VerticalScrollBarVisibility="Auto" />
|
||||
</Grid>
|
||||
</ui:FluentWindow>
|
||||
@@ -0,0 +1,280 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Markup;
|
||||
using System.Windows.Threading;
|
||||
using Microsoft.Win32;
|
||||
using Wpf.Ui.Appearance;
|
||||
using UiButton = Wpf.Ui.Controls.Button;
|
||||
using UiCard = Wpf.Ui.Controls.Card;
|
||||
using UiTextBox = Wpf.Ui.Controls.TextBox;
|
||||
|
||||
namespace ThemeLab;
|
||||
|
||||
public partial class MainWindow
|
||||
{
|
||||
private const int WmSettingChange = 0x001A;
|
||||
|
||||
// Kept alive for its TextScaleFactorChanged event.
|
||||
private readonly Windows.UI.ViewManagement.UISettings _uiSettings = new();
|
||||
private Preset _preset = Preset.Standard;
|
||||
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
Loaded += OnLoaded;
|
||||
}
|
||||
|
||||
private double CurrentTextScale => ApplyTextScale.IsChecked == true ? TextScale.FromWinRt(_uiSettings) : 1.0;
|
||||
|
||||
private void OnLoaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
HwndSource.FromHwnd(new WindowInteropHelper(this).Handle)?.AddHook(WndProc);
|
||||
_uiSettings.TextScaleFactorChanged += (_, _) => Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
Log($"UISettings.TextScaleFactorChanged -> {TextScale.FromWinRt(_uiSettings):0.00}");
|
||||
OnTextScaleChanged();
|
||||
});
|
||||
SystemEvents.UserPreferenceChanged += (_, args) => Dispatcher.InvokeAsync(() => Log($"SystemEvents.UserPreferenceChanged: {args.Category}"));
|
||||
|
||||
UpdateTextScaleInfo();
|
||||
Log($"Started. Elements: {CountElements(this)}; preset {_preset.Name}; theme {ApplicationThemeManager.GetAppTheme()}; "
|
||||
+ $"OS animations {(SystemParameters.ClientAreaAnimation ? "on" : "off")}; high contrast {(SystemParameters.HighContrast ? "on" : "off")}; "
|
||||
+ $"text scale registry {TextScale.FromRegistry():0.00} / WinRT {TextScale.FromWinRt(_uiSettings):0.00}");
|
||||
|
||||
if (Environment.GetCommandLineArgs().Contains("--auto"))
|
||||
{
|
||||
Dispatcher.InvokeAsync(RunAutomatedAsync, DispatcherPriority.ContextIdle);
|
||||
}
|
||||
}
|
||||
|
||||
// `ThemeLab.exe --auto`: every measurement the lab can take without a human, written to
|
||||
// %LocalAppData%\OmniDeck.Spikes\theme\. Flicker and Mica artifacts still need eyes on the window.
|
||||
private async Task RunAutomatedAsync()
|
||||
{
|
||||
await ProbeAsync();
|
||||
await BenchmarkAsync();
|
||||
OnStress(this, new RoutedEventArgs());
|
||||
await Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ContextIdle);
|
||||
await BenchmarkAsync();
|
||||
foreach (var theme in new[] { "Light", "Dark" })
|
||||
{
|
||||
OnThemeChecked(new FrameworkElement { Tag = theme }, new RoutedEventArgs());
|
||||
await Task.Delay(500);
|
||||
}
|
||||
|
||||
OnFrozenStoryboardTest(this, new RoutedEventArgs());
|
||||
await Task.Delay(500);
|
||||
|
||||
var dir = System.IO.Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OmniDeck.Spikes", "theme");
|
||||
System.IO.Directory.CreateDirectory(dir);
|
||||
var file = System.IO.Path.Combine(dir, $"{DateTime.UtcNow:yyyyMMdd-HHmmss}-auto.log");
|
||||
await System.IO.File.WriteAllTextAsync(file, LogBox.Text);
|
||||
Close();
|
||||
}
|
||||
|
||||
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
|
||||
{
|
||||
if (msg == WmSettingChange)
|
||||
{
|
||||
var area = lParam == IntPtr.Zero ? "(null)" : Marshal.PtrToStringUni(lParam);
|
||||
Log($"WM_SETTINGCHANGE wParam={wParam} lParam=\"{area}\"; registry text scale now {TextScale.FromRegistry():0.00}");
|
||||
}
|
||||
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
private async void OnPresetChecked(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (!IsLoaded || sender is not FrameworkElement { Tag: string name })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_preset = Preset.All.First(p => p.Name == name);
|
||||
var ms = await ApplyPresetAsync(_preset);
|
||||
Log($"Preset -> {_preset.Name}: {ms:F1} ms to layout/render ({CountElements(this)} elements)");
|
||||
}
|
||||
|
||||
private async Task<double> ApplyPresetAsync(Preset preset)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
PresetEngine.Apply(PresetEngine.Build(preset, CurrentTextScale));
|
||||
|
||||
// Loaded priority runs after the pending layout and render passes.
|
||||
await Dispatcher.InvokeAsync(() => { }, DispatcherPriority.Loaded);
|
||||
return sw.Elapsed.TotalMilliseconds;
|
||||
}
|
||||
|
||||
private void OnThemeChecked(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (!IsLoaded || sender is not FrameworkElement { Tag: string tag })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
if (tag == "System")
|
||||
{
|
||||
SystemThemeWatcher.Watch(this);
|
||||
ApplicationThemeManager.ApplySystemTheme();
|
||||
}
|
||||
else
|
||||
{
|
||||
SystemThemeWatcher.UnWatch(this);
|
||||
ApplicationThemeManager.Apply(tag == "Light" ? ApplicationTheme.Light : ApplicationTheme.Dark);
|
||||
}
|
||||
|
||||
var presetStillMerged = Application.Current.Resources.MergedDictionaries.Any(d => d.Contains("Od.Preset.Name"));
|
||||
Log($"Theme -> {tag} ({ApplicationThemeManager.GetAppTheme()}) in {sw.Elapsed.TotalMilliseconds:F1} ms; preset layer still merged: {presetStillMerged}");
|
||||
}
|
||||
|
||||
private async void OnTextScaleToggled(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (!IsLoaded)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await ApplyPresetAsync(_preset);
|
||||
UpdateTextScaleInfo();
|
||||
Log($"Text scale applied: {CurrentTextScale:0.00}");
|
||||
}
|
||||
|
||||
private async void OnTextScaleChanged()
|
||||
{
|
||||
UpdateTextScaleInfo();
|
||||
if (ApplyTextScale.IsChecked == true)
|
||||
{
|
||||
await ApplyPresetAsync(_preset);
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateTextScaleInfo() =>
|
||||
TextScaleInfo.Text = $"Registry: {TextScale.FromRegistry():0.00} · WinRT: {TextScale.FromWinRt(_uiSettings):0.00}";
|
||||
|
||||
private async void OnBenchmark(object sender, RoutedEventArgs e) => await BenchmarkAsync();
|
||||
|
||||
private async Task BenchmarkAsync()
|
||||
{
|
||||
var times = new List<double>();
|
||||
for (var i = 0; i < 30; i++)
|
||||
{
|
||||
times.Add(await ApplyPresetAsync(Preset.All[i % Preset.All.Length]));
|
||||
}
|
||||
|
||||
await ApplyPresetAsync(_preset);
|
||||
times.Sort();
|
||||
Log($"Benchmark x30 ({CountElements(this)} elements): min {times[0]:F1} ms, median {times[times.Count / 2]:F1} ms, "
|
||||
+ $"p90 {times[(int)(times.Count * 0.9)]:F1} ms, max {times[^1]:F1} ms");
|
||||
}
|
||||
|
||||
private void OnStress(object sender, RoutedEventArgs e)
|
||||
{
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
var panel = new StackPanel();
|
||||
panel.Children.Add(new TextBlock { Text = $"Card {i}" });
|
||||
panel.Children.Add(new UiButton { Content = "Od button", Style = (Style)FindResource("OdButtonStyle") });
|
||||
panel.Children.Add(new UiTextBox { PlaceholderText = "Od text box", Style = (Style)FindResource("OdTextBoxStyle") });
|
||||
var card = new UiCard { Width = 220, Content = panel };
|
||||
card.SetResourceReference(MarginProperty, "Od.Margin.Item");
|
||||
StressHost.Children.Add(card);
|
||||
}
|
||||
|
||||
Dispatcher.InvokeAsync(() => Log($"Stress: {StressHost.Children.Count} cards, {CountElements(this)} elements"), DispatcherPriority.Loaded);
|
||||
}
|
||||
|
||||
private async void OnProbe(object sender, RoutedEventArgs e) => await ProbeAsync();
|
||||
|
||||
private async Task ProbeAsync()
|
||||
{
|
||||
Log("Probe: preset | control | ActualHeight | Padding | FontSize | template CornerRadius");
|
||||
foreach (var preset in Preset.All)
|
||||
{
|
||||
await ApplyPresetAsync(preset);
|
||||
foreach (var (name, control) in new (string, Control)[]
|
||||
{
|
||||
("default ui:Button", ProbeDefaultButton), ("Od ui:Button", ProbeOdButton),
|
||||
("default ui:TextBox", ProbeDefaultTextBox), ("Od ui:TextBox", ProbeOdTextBox), ("ui:Card", ProbeCard),
|
||||
})
|
||||
{
|
||||
var border = FindFirst<Border>(control);
|
||||
Log($" {preset.Name,-8} | {name,-18} | {control.ActualHeight,6:F1} | {control.Padding} | {control.FontSize,5:F1} | {border?.CornerRadius.ToString() ?? "-"}");
|
||||
}
|
||||
}
|
||||
|
||||
await ApplyPresetAsync(_preset);
|
||||
}
|
||||
|
||||
private void OnFrozenStoryboardTest(object sender, RoutedEventArgs e)
|
||||
{
|
||||
const string xaml = """
|
||||
<Style xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" TargetType="Button">
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Trigger.EnterActions>
|
||||
<BeginStoryboard>
|
||||
<Storyboard>
|
||||
<DoubleAnimation Storyboard.TargetProperty="Opacity" To="0.5" Duration="{DynamicResource Od.Motion.Duration}" />
|
||||
</Storyboard>
|
||||
</BeginStoryboard>
|
||||
</Trigger.EnterActions>
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
""";
|
||||
try
|
||||
{
|
||||
var style = (Style)XamlReader.Parse(xaml);
|
||||
var button = new System.Windows.Controls.Button { Content = "Storyboard test", Style = style };
|
||||
StressHost.Children.Add(button);
|
||||
button.UpdateLayout();
|
||||
Log("Storyboard test: no exception (a DynamicResource in a style storyboard was accepted)");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Storyboard test: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void OnCopyLog(object sender, RoutedEventArgs e) => Clipboard.SetText(LogBox.Text);
|
||||
|
||||
private void Log(string line)
|
||||
{
|
||||
LogBox.AppendText($"{DateTime.Now:HH:mm:ss.fff} {line}{Environment.NewLine}");
|
||||
LogBox.ScrollToEnd();
|
||||
}
|
||||
|
||||
private static int CountElements(DependencyObject root)
|
||||
{
|
||||
var count = 1;
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
|
||||
{
|
||||
count += CountElements(VisualTreeHelper.GetChild(root, i));
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
private static T? FindFirst<T>(DependencyObject root)
|
||||
where T : DependencyObject
|
||||
{
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
|
||||
{
|
||||
var child = VisualTreeHelper.GetChild(root, i);
|
||||
if (child is T match)
|
||||
{
|
||||
return match;
|
||||
}
|
||||
|
||||
if (FindFirst<T>(child) is { } nested)
|
||||
{
|
||||
return nested;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System.Windows.Media.Animation;
|
||||
|
||||
namespace ThemeLab;
|
||||
|
||||
/// <summary>
|
||||
/// Code-driven motion: storyboards inside styles are frozen and cannot take DynamicResource, so the
|
||||
/// animation reads Od.Motion.Duration when it starts. A preset swap applies to the very next hover,
|
||||
/// and the OS "animation effects" switch (SystemParameters.ClientAreaAnimation) forces motion off.
|
||||
/// </summary>
|
||||
public static class OdMotion
|
||||
{
|
||||
public static readonly DependencyProperty HoverScaleProperty = DependencyProperty.RegisterAttached(
|
||||
"HoverScale", typeof(bool), typeof(OdMotion), new PropertyMetadata(false, OnHoverScaleChanged));
|
||||
|
||||
public static bool GetHoverScale(DependencyObject element) => (bool)element.GetValue(HoverScaleProperty);
|
||||
|
||||
public static void SetHoverScale(DependencyObject element, bool value) => element.SetValue(HoverScaleProperty, value);
|
||||
|
||||
private static void OnHoverScaleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is not FrameworkElement element || e.NewValue is not true)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
element.RenderTransformOrigin = new Point(0.5, 0.5);
|
||||
element.RenderTransform = new ScaleTransform(1, 1);
|
||||
element.MouseEnter += (_, _) => Animate(element, 1.04);
|
||||
element.MouseLeave += (_, _) => Animate(element, 1.0);
|
||||
}
|
||||
|
||||
private static void Animate(FrameworkElement element, double to)
|
||||
{
|
||||
var transform = (ScaleTransform)element.RenderTransform;
|
||||
var duration = element.TryFindResource("Od.Motion.Duration") is Duration d ? d : new Duration(TimeSpan.Zero);
|
||||
if (!SystemParameters.ClientAreaAnimation || duration.TimeSpan == TimeSpan.Zero)
|
||||
{
|
||||
transform.BeginAnimation(ScaleTransform.ScaleXProperty, null);
|
||||
transform.BeginAnimation(ScaleTransform.ScaleYProperty, null);
|
||||
transform.ScaleX = to;
|
||||
transform.ScaleY = to;
|
||||
return;
|
||||
}
|
||||
|
||||
var animation = new DoubleAnimation(to, duration) { EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut } };
|
||||
transform.BeginAnimation(ScaleTransform.ScaleXProperty, animation);
|
||||
transform.BeginAnimation(ScaleTransform.ScaleYProperty, animation);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
namespace ThemeLab;
|
||||
|
||||
/// <summary>One row set of the token table in docs/UI-MODES.md §2.</summary>
|
||||
public sealed record Preset(
|
||||
string Name, double FontBase, double FontScale, double Density, double HitTargetMin, double Corner, int MotionMs, double ChartLineWeight)
|
||||
{
|
||||
public static readonly Preset Dynamic = new("Dynamic", 13.5, 1.35, 4, 32, 8, 180, 1.5);
|
||||
public static readonly Preset Standard = new("Standard", 15.5, 1.30, 6, 36, 6, 100, 2);
|
||||
public static readonly Preset Comfort = new("Comfort", 19, 1.25, 10, 44, 6, 0, 3);
|
||||
|
||||
public static readonly Preset[] All = [Dynamic, Standard, Comfort];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the preset layer in code (derived tokens need the OS text scale and user overrides anyway)
|
||||
/// and swaps it in place inside Application.Resources.MergedDictionaries.
|
||||
/// </summary>
|
||||
public static class PresetEngine
|
||||
{
|
||||
private const string MarkerKey = "Od.Preset.Name";
|
||||
|
||||
public static ResourceDictionary Build(Preset p, double textScale)
|
||||
{
|
||||
var body = p.FontBase * textScale;
|
||||
var d = p.Density;
|
||||
return new ResourceDictionary
|
||||
{
|
||||
[MarkerKey] = p.Name,
|
||||
["Od.Font.Body"] = body,
|
||||
["Od.Font.H2"] = body * p.FontScale,
|
||||
["Od.Font.H1"] = body * p.FontScale * p.FontScale,
|
||||
["Od.Font.Caption"] = body * 0.85,
|
||||
["Od.Padding.Control"] = new Thickness(d * 2, d, d * 2, d),
|
||||
["Od.Padding.Card"] = new Thickness(d * 3),
|
||||
["Od.Margin.Item"] = new Thickness(0, 0, 0, d * 2),
|
||||
["Od.HitTarget.Min"] = p.HitTargetMin,
|
||||
["Od.Corner.Radius"] = new CornerRadius(p.Corner),
|
||||
["Od.Motion.Duration"] = new Duration(TimeSpan.FromMilliseconds(p.MotionMs)),
|
||||
["Od.Chart.LineWeight"] = p.ChartLineWeight,
|
||||
|
||||
// Deliberate WPF-UI overrides, to see which ones follow a runtime swap. In WPF-UI 4.3
|
||||
// templates ControlCornerRadius, ControlContentThemeFontSize and TextControlThemeMinHeight
|
||||
// are DynamicResource; ButtonPadding and CardPadding are StaticResource.
|
||||
["ControlCornerRadius"] = new CornerRadius(p.Corner),
|
||||
["ControlContentThemeFontSize"] = body,
|
||||
["TextControlThemeMinHeight"] = p.HitTargetMin,
|
||||
["ButtonPadding"] = new Thickness(d * 2, d, d * 2, d),
|
||||
["CardPadding"] = new Thickness(d * 3),
|
||||
};
|
||||
}
|
||||
|
||||
public static void Apply(ResourceDictionary preset)
|
||||
{
|
||||
var merged = Application.Current.Resources.MergedDictionaries;
|
||||
for (var i = 0; i < merged.Count; i++)
|
||||
{
|
||||
if (merged[i].Contains(MarkerKey))
|
||||
{
|
||||
merged[i] = preset;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
merged.Add(preset);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace ThemeLab;
|
||||
|
||||
/// <summary>
|
||||
/// Windows "Text size" (Settings → Accessibility). WPF ignores it, so OmniDeck has to read it and
|
||||
/// multiply Od.Font.* itself. Two sources are compared: the registry (no WinRT projection needed)
|
||||
/// and UISettings.TextScaleFactor (needs a Windows-versioned target framework).
|
||||
/// </summary>
|
||||
public static class TextScale
|
||||
{
|
||||
public static double FromRegistry()
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Accessibility");
|
||||
return key?.GetValue("TextScaleFactor") is int percent ? percent / 100.0 : 1.0;
|
||||
}
|
||||
|
||||
public static double FromWinRt(Windows.UI.ViewManagement.UISettings settings) => settings.TextScaleFactor;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- Spike #5 (issue #6): runtime preset swap on WPF-UI 4.3. The Windows-versioned TFM is only here
|
||||
to compare UISettings.TextScaleFactor (WinRT) with the registry value. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net10.0-windows10.0.26100.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="WPF-UI" Version="4.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,5 @@
|
||||
<Application
|
||||
x:Class="WebLab.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
StartupUri="MainWindow.xaml" />
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace WebLab;
|
||||
|
||||
public partial class App : Application;
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace WebLab;
|
||||
|
||||
public sealed record CatalogEntry(
|
||||
string Id, string Name, string StartUrl, string Profile, string[] NavAllow, string[] PopupAllow, bool Notifications, bool AudioPin);
|
||||
|
||||
public static class Catalog
|
||||
{
|
||||
/// <summary>Reads catalog/webapps.json from the repository this harness was built in.</summary>
|
||||
public static IReadOnlyList<CatalogEntry> Load()
|
||||
{
|
||||
for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
|
||||
{
|
||||
var file = Path.Combine(dir.FullName, "catalog", "webapps.json");
|
||||
if (File.Exists(file))
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file));
|
||||
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
||||
return doc.RootElement.GetProperty("apps").Deserialize<CatalogEntry[]>(options) ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/// <summary>docs/WEBAPP-CATALOG.md §1: equal to an entry, or a subdomain of it on whole labels.</summary>
|
||||
public static bool Matches(string host, IEnumerable<string> domains) =>
|
||||
domains.Any(d => host.Equals(d, StringComparison.OrdinalIgnoreCase)
|
||||
|| host.EndsWith("." + d, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>Scheme, host and path only: sign-in URLs carry tokens in their query strings.</summary>
|
||||
public static string Redact(string uri) =>
|
||||
Uri.TryCreate(uri, UriKind.Absolute, out var u) ? $"{u.Scheme}://{u.Host}{u.AbsolutePath}" : uri;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// The WPF SDK's implicit usings stop at System.* (and leave out System.IO because of Shapes.Path).
|
||||
global using System.IO;
|
||||
global using System.Windows;
|
||||
global using System.Windows.Controls;
|
||||
global using Microsoft.Web.WebView2.Core;
|
||||
global using Microsoft.Web.WebView2.Wpf;
|
||||
global using Path = System.IO.Path;
|
||||
@@ -0,0 +1,35 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>WebLab · CDP detection (spike #4)</title>
|
||||
<style>body { font: 14px/1.5 "Segoe UI", sans-serif; margin: 24px; } .big { font-size: 28px; font-weight: 600; }</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Can this page tell that the DevTools Protocol Runtime domain is on?</h1>
|
||||
<p>The widely used check: log an Error whose <code>stack</code> getter has a side effect. Only a
|
||||
DevTools client that serializes console arguments (Runtime.enable) reads it. Spike #4 (issue #5).</p>
|
||||
<p class="big" id="verdict">checking…</p>
|
||||
<button onclick="check()">Check again</button>
|
||||
<p>Console traffic for the ring buffer:
|
||||
<button onclick="console.log('log', {a: 1}, [1, 2])">console.log</button>
|
||||
<button onclick="console.warn('warn message')">console.warn</button>
|
||||
<button onclick="console.error(new Error('error object'))">console.error</button>
|
||||
<button onclick="setTimeout(() => { throw new Error('uncaught exception'); })">throw</button>
|
||||
<button onclick="fetch('https://weblab.example/missing.json').catch(() => {})">404 fetch</button>
|
||||
</p>
|
||||
<script>
|
||||
function check() {
|
||||
let read = false;
|
||||
const e = new Error('probe');
|
||||
Object.defineProperty(e, 'stack', { get() { read = true; return ''; } });
|
||||
console.debug(e);
|
||||
setTimeout(() => {
|
||||
document.getElementById('verdict').textContent = read ? 'DETECTED: Runtime domain is enabled' : 'not detected';
|
||||
window.chrome?.webview?.postMessage({ probe: 'cdp-detect', detected: read });
|
||||
}, 200);
|
||||
}
|
||||
check();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,23 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>WebLab · cookie persistence</title>
|
||||
</head>
|
||||
<body style="font: 14px/1.5 'Segoe UI', sans-serif; margin: 24px">
|
||||
<h1>Cookie persistence probe</h1>
|
||||
<p>Lists the cookies this origin already has, then (with <code>?set=NAME</code>) sets a one-year
|
||||
cookie named NAME. Used to tell which ways of closing the host keep cookies across restarts.</p>
|
||||
<pre id="out"></pre>
|
||||
<script>
|
||||
const before = document.cookie;
|
||||
const name = new URLSearchParams(location.search).get('set');
|
||||
if (name) {
|
||||
document.cookie = `${name}=${Date.now()}; max-age=31536000; path=/; secure; samesite=lax`;
|
||||
}
|
||||
const result = { probe: 'cookie', before, after: document.cookie, set: name };
|
||||
document.getElementById('out').textContent = JSON.stringify(result, null, 2);
|
||||
window.chrome?.webview?.postMessage(result);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,60 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>WebLab · EME probe (spike #1)</title>
|
||||
<style>
|
||||
body { font: 14px/1.5 "Segoe UI", sans-serif; margin: 24px; }
|
||||
table { border-collapse: collapse; } td, th { border: 1px solid #8884; padding: 4px 10px; text-align: left; }
|
||||
.yes { color: #0a7d32; font-weight: 600; } .no { color: #b3261e; font-weight: 600; }
|
||||
pre { background: #8881; padding: 8px; white-space: pre-wrap; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>EME probe</h1>
|
||||
<p>Spike #1 (issue #2): which key systems this WebView2 exposes. Results are also posted to the host log.</p>
|
||||
<table id="results"><tr><th>Key system</th><th>Robustness</th><th>Available</th><th>Detail</th></tr></table>
|
||||
<h2>User agent</h2>
|
||||
<pre id="ua"></pre>
|
||||
<script>
|
||||
const video = [{ contentType: 'video/mp4; codecs="avc1.42E01E"' }];
|
||||
const audio = [{ contentType: 'audio/mp4; codecs="mp4a.40.2"' }];
|
||||
const probes = [
|
||||
['com.widevine.alpha', ''], ['com.widevine.alpha', 'SW_SECURE_CRYPTO'], ['com.widevine.alpha', 'HW_SECURE_ALL'],
|
||||
['com.microsoft.playready.recommendation', ''], ['com.microsoft.playready.recommendation', '3000'],
|
||||
['com.microsoft.playready', ''], ['org.w3.clearkey', ''],
|
||||
];
|
||||
async function probe([keySystem, robustness]) {
|
||||
const withRobustness = caps => caps.map(c => robustness ? { ...c, robustness } : c);
|
||||
const config = [{ initDataTypes: ['cenc'], videoCapabilities: withRobustness(video), audioCapabilities: withRobustness(audio) }];
|
||||
try {
|
||||
const access = await navigator.requestMediaKeySystemAccess(keySystem, config);
|
||||
const keys = await access.createMediaKeys();
|
||||
return { keySystem, robustness, available: true, detail: `createMediaKeys ok (${keys.constructor.name})` };
|
||||
} catch (e) {
|
||||
return { keySystem, robustness, available: false, detail: `${e.name}: ${e.message}` };
|
||||
}
|
||||
}
|
||||
(async () => {
|
||||
const results = [];
|
||||
for (const p of probes) {
|
||||
const r = await probe(p);
|
||||
results.push(r);
|
||||
const row = document.getElementById('results').insertRow();
|
||||
row.insertCell().textContent = r.keySystem;
|
||||
row.insertCell().textContent = r.robustness || '(none)';
|
||||
const cell = row.insertCell(); cell.textContent = r.available ? 'yes' : 'no'; cell.className = r.available ? 'yes' : 'no';
|
||||
row.insertCell().textContent = r.detail;
|
||||
}
|
||||
let brands = null, high = null;
|
||||
if (navigator.userAgentData) {
|
||||
brands = navigator.userAgentData.brands;
|
||||
try { high = await navigator.userAgentData.getHighEntropyValues(['fullVersionList', 'platformVersion']); } catch {}
|
||||
}
|
||||
const ua = { userAgent: navigator.userAgent, brands, fullVersionList: high?.fullVersionList, platformVersion: high?.platformVersion };
|
||||
document.getElementById('ua').textContent = JSON.stringify(ua, null, 2);
|
||||
window.chrome?.webview?.postMessage({ probe: 'eme', results, ua });
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,98 @@
|
||||
namespace WebLab;
|
||||
|
||||
/// <summary>
|
||||
/// `--check-signed-in`: reopen the catalog apps on their saved profiles and ask each page whether it
|
||||
/// is signed in, to tell whether sign-ins survived the last shutdown (spike #2). Gmail then reloads
|
||||
/// with CDP capture on, to check that a signed-in app still loads with Runtime.enable (spike #4).
|
||||
/// `--ladder=gmail,...`: only the governor ladder, for the listed apps.
|
||||
/// </summary>
|
||||
public partial class MainWindow
|
||||
{
|
||||
// Each expression returns "in" or "out". It only reads the page's own state.
|
||||
private static readonly Dictionary<string, string> SignedInProbes = new()
|
||||
{
|
||||
["gmail"] = "location.host === 'mail.google.com' ? 'in' : 'out'",
|
||||
["youtube"] = "document.querySelector('#avatar-btn') ? 'in' : 'out'",
|
||||
["spotify"] = "document.querySelector('[data-testid=\"login-button\"]') ? 'out' : 'in'",
|
||||
["facebook"] = "document.querySelector('input[name=\"email\"]') ? 'out' : 'in'",
|
||||
["discord"] = "location.pathname.startsWith('/channels') ? 'in' : 'out'",
|
||||
};
|
||||
|
||||
private async Task RunSignedInCheckAsync()
|
||||
{
|
||||
var targets = ((List<Target>)Targets.ItemsSource).Where(t => t.Entry is not null && SignedInProbes.ContainsKey(t.Entry.Id)).ToList();
|
||||
try
|
||||
{
|
||||
foreach (var target in targets)
|
||||
{
|
||||
var slot = await OpenAsync(target);
|
||||
await Task.Delay(TimeSpan.FromSeconds(12));
|
||||
await LogSignedInAsync(slot);
|
||||
}
|
||||
|
||||
var gmail = _slots.First(s => s.Id == "gmail");
|
||||
ShowOnly(gmail);
|
||||
await SetCaptureAsync(gmail, runtime: true, log: true);
|
||||
var done = new TaskCompletionSource<bool>();
|
||||
gmail.View!.CoreWebView2.NavigationCompleted += (_, e) => done.TrySetResult(e.IsSuccess);
|
||||
gmail.View.CoreWebView2.Reload();
|
||||
await done.Task.WaitAsync(TimeSpan.FromSeconds(60));
|
||||
await Task.Delay(TimeSpan.FromSeconds(10));
|
||||
Log("[gmail] after a reload with capture on:");
|
||||
await LogSignedInAsync(gmail);
|
||||
Log($"[gmail] ring buffer holds {gmail.ConsoleRing.Count} entries");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"CHECK FAILED: {ex}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var slot in _slots.ToList())
|
||||
{
|
||||
Hibernate(slot);
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
Close();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LogSignedInAsync(Slot slot)
|
||||
{
|
||||
var id = slot.Entry!.Id;
|
||||
var result = await slot.View!.CoreWebView2.ExecuteScriptAsync(SignedInProbes[id]);
|
||||
Log($"SIGNED-IN {id}: {result.Trim('"')} at {Catalog.Redact(slot.View.CoreWebView2.Source)}");
|
||||
}
|
||||
|
||||
private async Task RunLaddersOnlyAsync(string ids)
|
||||
{
|
||||
var targets = (List<Target>)Targets.ItemsSource;
|
||||
var phase = TimeSpan.FromSeconds(int.TryParse(Arg("--phase"), out var s) && s > 0 ? s : 60);
|
||||
try
|
||||
{
|
||||
StartCsv();
|
||||
foreach (var id in ids.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
var slot = await OpenAsync(targets.First(t => t.Entry?.Id == id));
|
||||
await Task.Delay(TimeSpan.FromSeconds(12));
|
||||
await LogSignedInAsync(slot);
|
||||
await RunLadderAsync(slot, phase);
|
||||
await LogSignedInAsync(slot);
|
||||
Hibernate(slot);
|
||||
_slots.Remove(slot);
|
||||
await Task.Delay(TimeSpan.FromSeconds(10));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"LADDER FAILED: {ex}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
StopCsv();
|
||||
await Task.Delay(500);
|
||||
Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
namespace WebLab;
|
||||
|
||||
/// <summary>
|
||||
/// Cookie persistence across host shutdowns (spike #2 follow-up): sign-ins made in an interactive
|
||||
/// session were gone after the host was closed, while cookies from a run that disposed every view
|
||||
/// first survived.
|
||||
/// `--cookie-set=NAME [--exit=clean]`: set a one-year cookie, wait past the cookie store's commit
|
||||
/// interval, then either dispose every view and exit (clean) or wait to be closed from outside.
|
||||
/// `--cookie-check`: list the cookies the probe page can see, then exit cleanly.
|
||||
/// </summary>
|
||||
public partial class MainWindow
|
||||
{
|
||||
private async Task RunCookieProbeAsync()
|
||||
{
|
||||
var page = new Target("lab · cookie probe", $"https://{LabHost}/cookie.html", "lab", null);
|
||||
try
|
||||
{
|
||||
if (Arg("--cookie-set") is { } name)
|
||||
{
|
||||
var wait = WaitForMessageAsync("cookie");
|
||||
await OpenAsync(page with { Url = page.Url + "?set=" + Uri.EscapeDataString(name) });
|
||||
var result = await wait;
|
||||
Log($"COOKIE set '{name}'; before: \"{result.GetProperty("before").GetString()}\"");
|
||||
await Task.Delay(TimeSpan.FromSeconds(45)); // past the 30 s commit interval
|
||||
if (Arg("--exit") == "clean")
|
||||
{
|
||||
foreach (var slot in _slots.ToList())
|
||||
{
|
||||
Hibernate(slot);
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
Log("COOKIE exit: clean (views disposed first)");
|
||||
Close();
|
||||
}
|
||||
else
|
||||
{
|
||||
Log("COOKIE ready to be closed from outside");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var wait = WaitForMessageAsync("cookie");
|
||||
await OpenAsync(page);
|
||||
var result = await wait;
|
||||
Log($"COOKIE check: \"{result.GetProperty("before").GetString()}\"");
|
||||
foreach (var slot in _slots.ToList())
|
||||
{
|
||||
Hibernate(slot);
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
Close();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"COOKIE FAILED: {ex}");
|
||||
Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace WebLab;
|
||||
|
||||
/// <summary>
|
||||
/// `WebLab.exe --measure [--phase=60]`: spikes #3 and #4 on the profiles signed in by hand earlier.
|
||||
/// A governor ladder per app (Discord, YouTube, Gmail), every catalog app open at once, then CDP
|
||||
/// capture overhead and whether signed-in apps still load with Runtime.enable on.
|
||||
/// </summary>
|
||||
public partial class MainWindow
|
||||
{
|
||||
private static readonly string[] LadderApps = ["discord", "youtube", "gmail"];
|
||||
|
||||
private async Task RunMeasureAsync()
|
||||
{
|
||||
// Messenger is left out: messenger.com closed in April 2026.
|
||||
var targets = ((List<Target>)Targets.ItemsSource).Where(t => t.Entry is { Id: not "messenger" }).ToList();
|
||||
var phase = TimeSpan.FromSeconds(int.TryParse(Arg("--phase"), out var s) && s > 0 ? s : 60);
|
||||
Target App(string id) => targets.First(t => t.Entry!.Id == id);
|
||||
try
|
||||
{
|
||||
StartCsv();
|
||||
Mark("measure:shell-only");
|
||||
await Task.Delay(TimeSpan.FromSeconds(10));
|
||||
|
||||
foreach (var id in LadderApps)
|
||||
{
|
||||
var slot = await OpenAsync(App(id));
|
||||
await RunLadderAsync(slot, phase);
|
||||
LogTitle(slot);
|
||||
Hibernate(slot);
|
||||
_slots.Remove(slot);
|
||||
Mark("measure:gap");
|
||||
await Task.Delay(TimeSpan.FromSeconds(10));
|
||||
}
|
||||
|
||||
// Every catalog app at once; the last one opened stays visible, the others are hidden.
|
||||
var all = new List<Slot>();
|
||||
foreach (var target in targets)
|
||||
{
|
||||
all.Add(await OpenAsync(target));
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
}
|
||||
|
||||
Mark("all:open");
|
||||
await Task.Delay(phase * 1.5);
|
||||
all.ForEach(LogTitle);
|
||||
foreach (var slot in all.Take(all.Count - 1))
|
||||
{
|
||||
await SuspendAsync(slot);
|
||||
}
|
||||
|
||||
Mark("all:suspended");
|
||||
await Task.Delay(phase);
|
||||
all.ForEach(Hibernate);
|
||||
Mark("all:hibernated");
|
||||
await Task.Delay(phase / 2);
|
||||
all.ForEach(slot => _slots.Remove(slot));
|
||||
|
||||
// CDP capture on signed-in apps: cost, and whether they still load with Runtime.enable on.
|
||||
var cdp = new List<Slot>();
|
||||
foreach (var id in new[] { "gmail", "discord", "spotify" })
|
||||
{
|
||||
cdp.Add(await OpenAsync(App(id)));
|
||||
}
|
||||
|
||||
Mark("cdp:off");
|
||||
await Task.Delay(phase);
|
||||
foreach (var slot in cdp)
|
||||
{
|
||||
await SetCaptureAsync(slot, runtime: true, log: true);
|
||||
}
|
||||
|
||||
Mark("cdp:on");
|
||||
await Task.Delay(phase);
|
||||
foreach (var slot in cdp)
|
||||
{
|
||||
var done = new TaskCompletionSource<bool>();
|
||||
slot.View!.CoreWebView2.NavigationCompleted += (_, e) => done.TrySetResult(e.IsSuccess);
|
||||
slot.View.CoreWebView2.Reload();
|
||||
Log($"[{slot.Id}] reload with capture on: {(await done.Task.WaitAsync(TimeSpan.FromSeconds(60)) ? "ok" : "failed")}");
|
||||
}
|
||||
|
||||
Mark("cdp:on-reloaded");
|
||||
await Task.Delay(phase);
|
||||
foreach (var slot in cdp)
|
||||
{
|
||||
LogTitle(slot);
|
||||
Log($"[{slot.Id}] ring buffer holds {slot.ConsoleRing.Count} entries; last 10:");
|
||||
foreach (var line in slot.ConsoleRing.TakeLast(10))
|
||||
{
|
||||
Log($"[{slot.Id}] {RedactEmails(line)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"MEASURE FAILED: {ex}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
StopCsv();
|
||||
await Task.Delay(500);
|
||||
Close();
|
||||
}
|
||||
}
|
||||
|
||||
// Titles show whether an app is still signed in; addresses in them stay out of the log.
|
||||
private void LogTitle(Slot slot)
|
||||
{
|
||||
try
|
||||
{
|
||||
Log($"[{slot.Id}] title \"{RedactEmails(slot.View?.CoreWebView2?.DocumentTitle ?? "")}\" at {Catalog.Redact(slot.View?.CoreWebView2?.Source ?? "")}");
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// The view is being torn down.
|
||||
}
|
||||
}
|
||||
|
||||
private static string RedactEmails(string text) => Regex.Replace(text, @"[^\s@""']+@[^\s@""']+", "<email>");
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<Window
|
||||
x:Class="WebLab.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="WebLab — spikes #1–#4 (WebView2)"
|
||||
Width="1560"
|
||||
Height="960"
|
||||
WindowStartupLocation="CenterScreen">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="210" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<WrapPanel Grid.Row="0" Margin="6">
|
||||
<ComboBox x:Name="Targets" Width="280" Margin="0,0,6,0" DisplayMemberPath="Label" />
|
||||
<Button Margin="0,0,12,0" Padding="10,2" Click="OnOpen" Content="Open" />
|
||||
<CheckBox x:Name="EnforcePolicy" Margin="0,4,12,0" Content="Enforce navAllow / popupAllow" IsChecked="True" />
|
||||
<CheckBox x:Name="DevToolsEnabled" Margin="0,4,12,0" Content="DevTools UI enabled (new slots)" />
|
||||
<TextBlock Margin="0,4,4,0" Text="Ladder phase (s):" />
|
||||
<TextBox x:Name="PhaseSeconds" Width="40" Margin="0,0,12,0" Text="60" />
|
||||
<Button x:Name="RecordButton" Margin="0,0,6,0" Padding="10,2" Click="OnRecord" Content="Start CSV" />
|
||||
<TextBox x:Name="MarkText" Width="160" Margin="0,0,4,0" />
|
||||
<Button Margin="0,0,12,0" Padding="10,2" Click="OnMark" Content="Mark phase" />
|
||||
<TextBlock x:Name="EnvInfo" Margin="0,4,0,0" />
|
||||
</WrapPanel>
|
||||
|
||||
<Grid Grid.Row="1">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="280" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="470" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<DockPanel Grid.Column="0" Margin="6,0,6,0">
|
||||
<UniformGrid DockPanel.Dock="Bottom" Columns="2">
|
||||
<Button Margin="2" Click="OnShow" Content="Show" />
|
||||
<Button Margin="2" Click="OnHide" Content="Hide" />
|
||||
<Button Margin="2" Click="OnSuspend" Content="Suspend (+Low)" />
|
||||
<Button Margin="2" Click="OnResume" Content="Resume" />
|
||||
<Button Margin="2" Click="OnHibernate" Content="Dispose (hibernate)" />
|
||||
<Button Margin="2" Click="OnReopen" Content="Reopen" />
|
||||
<Button Margin="2" Click="OnCaptureFull" Content="Console: Runtime+Log" />
|
||||
<Button Margin="2" Click="OnCaptureLogOnly" Content="Console: Log only" />
|
||||
<Button Margin="2" Click="OnCaptureOff" Content="Console off" />
|
||||
<Button Margin="2" Click="OnCloseSlot" Content="Close slot" />
|
||||
<Button Margin="2" Click="OnLadder" Content="Run ladder" />
|
||||
<Button Margin="2" Click="OnHibernateAll" Content="Dispose all" />
|
||||
</UniformGrid>
|
||||
<ListBox x:Name="SlotList" SelectionChanged="OnSlotSelected" />
|
||||
</DockPanel>
|
||||
|
||||
<Grid x:Name="Host" Grid.Column="1" />
|
||||
|
||||
<DockPanel Grid.Column="2" Margin="6,0,6,0">
|
||||
<TextBlock x:Name="Totals" Margin="0,0,0,4" DockPanel.Dock="Top" TextWrapping="Wrap" />
|
||||
<DataGrid x:Name="MemGrid" AutoGenerateColumns="True" HeadersVisibility="Column" IsReadOnly="True" />
|
||||
</DockPanel>
|
||||
</Grid>
|
||||
|
||||
<Grid Grid.Row="2" Margin="6">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="3*" />
|
||||
<ColumnDefinition Width="2*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBox x:Name="LogBox" Grid.Column="0" Margin="0,0,6,0" FontFamily="Cascadia Mono, Consolas" HorizontalScrollBarVisibility="Auto" IsReadOnly="True" VerticalScrollBarVisibility="Auto" />
|
||||
<TextBox x:Name="ConsoleBox" Grid.Column="1" FontFamily="Cascadia Mono, Consolas" HorizontalScrollBarVisibility="Auto" IsReadOnly="True" VerticalScrollBarVisibility="Auto" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -0,0 +1,749 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Windows.Threading;
|
||||
|
||||
namespace WebLab;
|
||||
|
||||
public sealed record Target(string Label, string Url, string Profile, CatalogEntry? Entry);
|
||||
|
||||
/// <summary>
|
||||
/// The WebView2 lab for spikes #1–#4. One shared environment, one profile per catalog profile group,
|
||||
/// the catalog's navigation policy, the governor's lifecycle steps, a per-process memory sampler and
|
||||
/// CDP console capture. `--auto` runs the unattended checks; `--wv2-args=...` passes browser arguments.
|
||||
/// </summary>
|
||||
public partial class MainWindow
|
||||
{
|
||||
private const string LabHost = "weblab.example";
|
||||
private static readonly string DataRoot = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OmniDeck.Spikes");
|
||||
private static readonly string LabPages = Path.Combine(AppContext.BaseDirectory, "LabPages");
|
||||
|
||||
private readonly ObservableCollection<Slot> _slots = [];
|
||||
private readonly DispatcherTimer _sampler = new() { Interval = TimeSpan.FromSeconds(2) };
|
||||
private readonly string _stamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
|
||||
private readonly StreamWriter _logFile;
|
||||
private readonly Dictionary<string, TaskCompletionSource<JsonElement>> _waiters = [];
|
||||
private CoreWebView2Environment? _env;
|
||||
private StreamWriter? _csv;
|
||||
private string _phase = "-";
|
||||
private bool _sampling;
|
||||
private bool _browserGone;
|
||||
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
Directory.CreateDirectory(Path.Combine(DataRoot, "weblab"));
|
||||
_logFile = new StreamWriter(Path.Combine(DataRoot, "weblab", $"{_stamp}.log")) { AutoFlush = true };
|
||||
SlotList.ItemsSource = _slots;
|
||||
Targets.ItemsSource = BuildTargets();
|
||||
Targets.SelectedIndex = 0;
|
||||
_sampler.Tick += async (_, _) => await SampleAsync();
|
||||
_sampler.Start();
|
||||
Closed += (_, _) =>
|
||||
{
|
||||
_csv?.Dispose();
|
||||
_logFile.Dispose();
|
||||
};
|
||||
|
||||
Log($"WebLab started. Windows {Environment.OSVersion.Version}, {Environment.ProcessorCount} logical CPUs, "
|
||||
+ $"{GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / (1024.0 * 1024 * 1024):F1} GiB RAM. Data under {DataRoot}");
|
||||
if (Environment.GetCommandLineArgs().Contains("--auto"))
|
||||
{
|
||||
Loaded += async (_, _) => await RunAutoAsync();
|
||||
}
|
||||
else if (Environment.GetCommandLineArgs().Contains("--measure"))
|
||||
{
|
||||
Loaded += async (_, _) => await RunMeasureAsync();
|
||||
}
|
||||
else if (Arg("--cookie-set") is not null || Environment.GetCommandLineArgs().Contains("--cookie-check"))
|
||||
{
|
||||
Loaded += async (_, _) => await RunCookieProbeAsync();
|
||||
}
|
||||
else if (Environment.GetCommandLineArgs().Contains("--check-signed-in"))
|
||||
{
|
||||
Loaded += async (_, _) => await RunSignedInCheckAsync();
|
||||
}
|
||||
else if (Arg("--ladder") is { } ladderApps)
|
||||
{
|
||||
Loaded += async (_, _) => await RunLaddersOnlyAsync(ladderApps);
|
||||
}
|
||||
}
|
||||
|
||||
private Slot? Selected => SlotList.SelectedItem as Slot;
|
||||
|
||||
private static List<Target> BuildTargets()
|
||||
{
|
||||
var targets = new List<Target>
|
||||
{
|
||||
new("lab · EME probe (#1)", $"https://{LabHost}/eme.html", "lab", null),
|
||||
new("lab · Shaka support page (#1)", "https://shaka-player-demo.appspot.com/support.html", "lab", null),
|
||||
new("lab · CDP detection (#4)", $"https://{LabHost}/cdp-detect.html", "lab", null),
|
||||
};
|
||||
targets.AddRange(Catalog.Load().Select(e => new Target($"{e.Id} · {e.Name} [{e.Profile}]", e.StartUrl, e.Profile, e)));
|
||||
return targets;
|
||||
}
|
||||
|
||||
private static string? Arg(string name) =>
|
||||
Environment.GetCommandLineArgs().FirstOrDefault(a => a.StartsWith(name + "=", StringComparison.Ordinal))?[(name.Length + 1)..];
|
||||
|
||||
// ---- Environment and views -------------------------------------------------------------------
|
||||
|
||||
private async Task<CoreWebView2Environment> EnsureEnvironmentAsync()
|
||||
{
|
||||
if (_env is not null)
|
||||
{
|
||||
return _env;
|
||||
}
|
||||
|
||||
var args = Arg("--wv2-args");
|
||||
var options = new CoreWebView2EnvironmentOptions(additionalBrowserArguments: args);
|
||||
_env = await CoreWebView2Environment.CreateAsync(null, Path.Combine(DataRoot, "WebView2"), options);
|
||||
Log($"Environment: WebView2 Runtime {_env.BrowserVersionString}; user data {_env.UserDataFolder}; browser args '{args ?? ""}'");
|
||||
EnvInfo.Text = $"WebView2 Runtime {_env.BrowserVersionString}";
|
||||
return _env;
|
||||
}
|
||||
|
||||
private async Task<WebView2> CreateViewAsync(Slot slot, string url, Action<CoreWebView2>? beforeNavigate = null)
|
||||
{
|
||||
var env = await EnsureEnvironmentAsync();
|
||||
var view = new WebView2();
|
||||
Host.Children.Add(view);
|
||||
var options = env.CreateCoreWebView2ControllerOptions();
|
||||
options.ProfileName = slot.Profile;
|
||||
await view.EnsureCoreWebView2Async(env, options);
|
||||
Configure(view.CoreWebView2, slot);
|
||||
beforeNavigate?.Invoke(view.CoreWebView2);
|
||||
view.CoreWebView2.Navigate(url);
|
||||
return view;
|
||||
}
|
||||
|
||||
private void Configure(CoreWebView2 core, Slot slot)
|
||||
{
|
||||
// docs/ARCHITECTURE.md §3 per-app pipeline. The user agent is never touched.
|
||||
core.Settings.AreDevToolsEnabled = DevToolsEnabled.IsChecked == true;
|
||||
core.Settings.IsPasswordAutosaveEnabled = false;
|
||||
core.Settings.IsGeneralAutofillEnabled = false;
|
||||
core.SetVirtualHostNameToFolderMapping(LabHost, LabPages, CoreWebView2HostResourceAccessKind.Allow);
|
||||
|
||||
core.NavigationStarting += (_, e) =>
|
||||
{
|
||||
var host = Uri.TryCreate(e.Uri, UriKind.Absolute, out var u) ? u.Host : "";
|
||||
var allowed = slot.Entry is null || Catalog.Matches(host, slot.Entry.NavAllow);
|
||||
Log($"[{slot.Id}] {(e.IsRedirected ? "redirect" : "navigate")} {Catalog.Redact(e.Uri)}"
|
||||
+ $"{(e.IsUserInitiated ? " (user)" : "")}{(allowed ? "" : " — OUTSIDE navAllow")}");
|
||||
if (!allowed && EnforcePolicy.IsChecked == true)
|
||||
{
|
||||
e.Cancel = true;
|
||||
Log($"[{slot.Id}] cancelled: the product would open this in the default browser");
|
||||
}
|
||||
};
|
||||
core.NavigationCompleted += (_, e) =>
|
||||
Log($"[{slot.Id}] completed {(e.IsSuccess ? "ok" : e.WebErrorStatus.ToString())} {Catalog.Redact(core.Source)}");
|
||||
core.NewWindowRequested += (_, e) => OnNewWindowRequested(slot, e);
|
||||
core.IsDocumentPlayingAudioChanged += (_, _) => Log($"[{slot.Id}] playing audio: {core.IsDocumentPlayingAudio}");
|
||||
core.ProcessFailed += (_, e) => Log($"[{slot.Id}] ProcessFailed {e.ProcessFailedKind}, reason {e.Reason}, exit {e.ExitCode}");
|
||||
core.PermissionRequested += (_, e) => Log($"[{slot.Id}] permission {e.PermissionKind} for {Catalog.Redact(e.Uri)} (default handling)");
|
||||
core.WebMessageReceived += (_, e) => OnWebMessage(slot, e.WebMessageAsJson);
|
||||
}
|
||||
|
||||
private async void OnNewWindowRequested(Slot slot, CoreWebView2NewWindowRequestedEventArgs e)
|
||||
{
|
||||
var host = Uri.TryCreate(e.Uri, UriKind.Absolute, out var u) ? u.Host : "";
|
||||
var inApp = slot.Entry is null || EnforcePolicy.IsChecked != true || Catalog.Matches(host, slot.Entry.PopupAllow);
|
||||
Log($"[{slot.Id}] popup {Catalog.Redact(e.Uri)} → "
|
||||
+ (inApp ? "in-app popup on the same profile" : "blocked: the product would open it in the default browser"));
|
||||
if (!inApp)
|
||||
{
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
var deferral = e.GetDeferral();
|
||||
try
|
||||
{
|
||||
var view = new WebView2();
|
||||
var features = e.WindowFeatures;
|
||||
var window = new Window
|
||||
{
|
||||
Title = $"{slot.Id} · popup",
|
||||
Owner = this,
|
||||
Content = view,
|
||||
Width = features.HasSize ? features.Width : 520,
|
||||
Height = features.HasSize ? features.Height : 700,
|
||||
};
|
||||
window.Show();
|
||||
var options = _env!.CreateCoreWebView2ControllerOptions();
|
||||
options.ProfileName = slot.Profile;
|
||||
await view.EnsureCoreWebView2Async(_env, options);
|
||||
Configure(view.CoreWebView2, new Slot { Id = slot.Id + ":popup", Profile = slot.Profile, StartUrl = e.Uri, Entry = slot.Entry });
|
||||
view.CoreWebView2.WindowCloseRequested += (_, _) => window.Close();
|
||||
window.Closed += (_, _) => view.Dispose();
|
||||
e.NewWindow = view.CoreWebView2;
|
||||
e.Handled = true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
deferral.Complete();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnWebMessage(Slot slot, string json)
|
||||
{
|
||||
Log($"[{slot.Id}] page says: {json}");
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
if (doc.RootElement.ValueKind == JsonValueKind.Object
|
||||
&& doc.RootElement.TryGetProperty("probe", out var probe)
|
||||
&& _waiters.Remove(probe.GetString() ?? "", out var waiter))
|
||||
{
|
||||
waiter.TrySetResult(doc.RootElement.Clone());
|
||||
}
|
||||
}
|
||||
|
||||
private Task<JsonElement> WaitForMessageAsync(string probe)
|
||||
{
|
||||
var tcs = new TaskCompletionSource<JsonElement>();
|
||||
_waiters[probe] = tcs;
|
||||
return tcs.Task.WaitAsync(TimeSpan.FromSeconds(45));
|
||||
}
|
||||
|
||||
// ---- Governor lifecycle steps ----------------------------------------------------------------
|
||||
|
||||
private async Task<Slot> OpenAsync(Target target)
|
||||
{
|
||||
var baseId = target.Entry?.Id ?? "lab";
|
||||
var n = _slots.Count(s => s.Id == baseId || s.Id.StartsWith(baseId + "#", StringComparison.Ordinal));
|
||||
var slot = new Slot { Id = n == 0 ? baseId : $"{baseId}#{n + 1}", Profile = target.Profile, StartUrl = target.Url, Entry = target.Entry };
|
||||
_slots.Add(slot);
|
||||
var sw = Stopwatch.StartNew();
|
||||
slot.View = await CreateViewAsync(slot, target.Url);
|
||||
slot.State = "Active";
|
||||
SlotList.SelectedItem = slot;
|
||||
ShowOnly(slot);
|
||||
Log($"[{slot.Id}] opened on profile '{slot.Profile}', controller ready in {sw.ElapsedMilliseconds} ms");
|
||||
return slot;
|
||||
}
|
||||
|
||||
private void ShowOnly(Slot slot)
|
||||
{
|
||||
foreach (var s in _slots.Where(s => s.View is not null))
|
||||
{
|
||||
var visible = ReferenceEquals(s, slot);
|
||||
s.View!.Visibility = visible ? Visibility.Visible : Visibility.Collapsed;
|
||||
if (visible)
|
||||
{
|
||||
s.State = "Active";
|
||||
}
|
||||
else if (s.State == "Active")
|
||||
{
|
||||
s.State = "Hidden";
|
||||
}
|
||||
}
|
||||
|
||||
SlotList.Items.Refresh();
|
||||
}
|
||||
|
||||
private void Hide(Slot slot)
|
||||
{
|
||||
slot.View!.Visibility = Visibility.Collapsed;
|
||||
slot.State = "Hidden";
|
||||
SlotList.Items.Refresh();
|
||||
}
|
||||
|
||||
private async Task SuspendAsync(Slot slot)
|
||||
{
|
||||
var core = slot.View!.CoreWebView2;
|
||||
Hide(slot);
|
||||
await Dispatcher.InvokeAsync(() => { }, DispatcherPriority.Background); // let IsVisible reach the controller
|
||||
var sw = Stopwatch.StartNew();
|
||||
var ok = await core.TrySuspendAsync();
|
||||
core.MemoryUsageTargetLevel = CoreWebView2MemoryUsageTargetLevel.Low;
|
||||
slot.State = ok ? "Suspended" : "Hidden (suspend refused)";
|
||||
SlotList.Items.Refresh();
|
||||
Log($"[{slot.Id}] TrySuspendAsync → {ok} in {sw.ElapsedMilliseconds} ms; MemoryUsageTargetLevel = Low");
|
||||
}
|
||||
|
||||
private void Resume(Slot slot)
|
||||
{
|
||||
var core = slot.View!.CoreWebView2;
|
||||
var sw = Stopwatch.StartNew();
|
||||
core.MemoryUsageTargetLevel = CoreWebView2MemoryUsageTargetLevel.Normal;
|
||||
core.Resume();
|
||||
ShowOnly(slot);
|
||||
Log($"[{slot.Id}] resumed (Normal + Resume + show) in {sw.Elapsed.TotalMilliseconds:F1} ms");
|
||||
}
|
||||
|
||||
private void Hibernate(Slot slot)
|
||||
{
|
||||
if (slot.View is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
slot.SavedUrl = slot.View.CoreWebView2?.Source ?? slot.StartUrl;
|
||||
Host.Children.Remove(slot.View);
|
||||
slot.View.Dispose();
|
||||
slot.View = null;
|
||||
slot.ConsoleReceiver = null;
|
||||
slot.LogReceiver = null;
|
||||
slot.Capturing = false;
|
||||
slot.State = "Hibernated";
|
||||
SlotList.Items.Refresh();
|
||||
Log($"[{slot.Id}] disposed; kept {{url}} = {Catalog.Redact(slot.SavedUrl)}");
|
||||
}
|
||||
|
||||
private async Task ReopenAsync(Slot slot)
|
||||
{
|
||||
if (slot.View is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
var first = new TaskCompletionSource<bool>();
|
||||
slot.View = await CreateViewAsync(slot, slot.SavedUrl ?? slot.StartUrl,
|
||||
core => core.NavigationCompleted += (_, e) => first.TrySetResult(e.IsSuccess));
|
||||
var controllerMs = sw.ElapsedMilliseconds;
|
||||
ShowOnly(slot);
|
||||
var ok = await first.Task.WaitAsync(TimeSpan.FromSeconds(60));
|
||||
Log($"[{slot.Id}] reopened: controller {controllerMs} ms, first NavigationCompleted ({(ok ? "ok" : "failed")}) {sw.ElapsedMilliseconds} ms");
|
||||
}
|
||||
|
||||
// ---- CDP console capture (spike #4) ----------------------------------------------------------
|
||||
|
||||
private async Task SetCaptureAsync(Slot slot, bool runtime, bool log)
|
||||
{
|
||||
if (slot.View?.CoreWebView2 is not { } core)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (slot.ConsoleReceiver is null)
|
||||
{
|
||||
slot.ConsoleReceiver = core.GetDevToolsProtocolEventReceiver("Runtime.consoleAPICalled");
|
||||
slot.ConsoleReceiver.DevToolsProtocolEventReceived += (_, e) => AddConsole(slot, "console", e.ParameterObjectAsJson);
|
||||
slot.LogReceiver = core.GetDevToolsProtocolEventReceiver("Log.entryAdded");
|
||||
slot.LogReceiver.DevToolsProtocolEventReceived += (_, e) => AddConsole(slot, "log", e.ParameterObjectAsJson);
|
||||
core.GetDevToolsProtocolEventReceiver("Runtime.exceptionThrown").DevToolsProtocolEventReceived +=
|
||||
(_, e) => AddConsole(slot, "exception", e.ParameterObjectAsJson);
|
||||
}
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
await core.CallDevToolsProtocolMethodAsync(runtime ? "Runtime.enable" : "Runtime.disable", "{}");
|
||||
await core.CallDevToolsProtocolMethodAsync(log ? "Log.enable" : "Log.disable", "{}");
|
||||
slot.Capturing = runtime || log;
|
||||
Log($"[{slot.Id}] console capture: Runtime {(runtime ? "on" : "off")}, Log {(log ? "on" : "off")} in {sw.ElapsedMilliseconds} ms "
|
||||
+ $"(DevTools UI {(core.Settings.AreDevToolsEnabled ? "enabled" : "disabled")})");
|
||||
}
|
||||
|
||||
private void AddConsole(Slot slot, string source, string json)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
var text = source switch
|
||||
{
|
||||
"console" => $"{Str(root, "type")}: " + string.Join(" ", root.GetProperty("args").EnumerateArray()
|
||||
.Select(a => a.TryGetProperty("value", out var v) ? v.ToString() : Str(a, "description"))),
|
||||
"log" => $"[{Str(root.GetProperty("entry"), "source")}/{Str(root.GetProperty("entry"), "level")}] {Str(root.GetProperty("entry"), "text")}",
|
||||
_ => $"uncaught: {Str(root.GetProperty("exceptionDetails"), "text")} "
|
||||
+ (root.GetProperty("exceptionDetails").TryGetProperty("exception", out var ex) ? Str(ex, "description") : ""),
|
||||
};
|
||||
slot.AddConsole($"{DateTime.Now:HH:mm:ss.fff} {source,-9} {text}");
|
||||
if (ReferenceEquals(slot, Selected))
|
||||
{
|
||||
ConsoleBox.Text = string.Join(Environment.NewLine, slot.ConsoleRing);
|
||||
ConsoleBox.ScrollToEnd();
|
||||
}
|
||||
|
||||
static string Str(JsonElement e, string name) => e.TryGetProperty(name, out var v) ? v.ToString() : "";
|
||||
}
|
||||
|
||||
// ---- Memory sampling (spike #3) --------------------------------------------------------------
|
||||
|
||||
private async Task SampleAsync()
|
||||
{
|
||||
if (_sampling)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_sampling = true;
|
||||
try
|
||||
{
|
||||
var rows = new List<ProcessSample>();
|
||||
if (MemorySampler.Sample(Environment.ProcessId, "Shell", "shell") is { } shell)
|
||||
{
|
||||
rows.Add(shell);
|
||||
}
|
||||
|
||||
if (_env is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var owners = await AttributeAsync();
|
||||
foreach (var info in _env.GetProcessInfos())
|
||||
{
|
||||
if (MemorySampler.Sample(info.ProcessId, info.Kind.ToString(), owners.GetValueOrDefault(info.ProcessId, "shared")) is { } row)
|
||||
{
|
||||
rows.Add(row);
|
||||
}
|
||||
}
|
||||
|
||||
_browserGone = false;
|
||||
}
|
||||
catch (Exception ex) when (ex is FileNotFoundException or System.Runtime.InteropServices.COMException or InvalidOperationException)
|
||||
{
|
||||
// With every controller closed the browser process exits; the environment object stays.
|
||||
if (!_browserGone)
|
||||
{
|
||||
Log($"No WebView2 browser process ({ex.GetType().Name}: {ex.Message.Trim()})");
|
||||
_browserGone = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var slot in _slots)
|
||||
{
|
||||
slot.AttributedMb = rows.Where(r => r.Attributed.Split('+').Contains(slot.Id)).Sum(r => r.PrivateCommitMb);
|
||||
}
|
||||
|
||||
MemGrid.ItemsSource = rows;
|
||||
Totals.Text = $"{rows.Count} processes · Σ private commit {rows.Sum(r => r.PrivateCommitMb):F0} MB · "
|
||||
+ $"Σ private WS {rows.Sum(r => r.PrivateWsMb):F0} MB · Σ WS {rows.Sum(r => r.WsMb):F0} MB · phase '{_phase}'";
|
||||
if (_csv is not null)
|
||||
{
|
||||
var time = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
|
||||
foreach (var r in rows)
|
||||
{
|
||||
_csv.WriteLine(string.Join(',', time, _phase, r.Pid, r.Kind, r.Attributed.Replace(',', ';'),
|
||||
F(r.PrivateCommitMb), F(r.PrivateWsMb), F(r.WsMb), F(r.SharedCommitMb), F(r.CpuMs)));
|
||||
}
|
||||
}
|
||||
|
||||
SlotList.Items.Refresh();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_sampling = false;
|
||||
}
|
||||
|
||||
static string F(double v) => v.ToString("F1", CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>Renderer and OOPIF processes → slot, by each frame's root (main frame) id, then by host.</summary>
|
||||
private async Task<Dictionary<int, string>> AttributeAsync()
|
||||
{
|
||||
var owners = new Dictionary<int, string>();
|
||||
foreach (var info in await _env!.GetProcessExtendedInfosAsync())
|
||||
{
|
||||
var names = new SortedSet<string>(StringComparer.Ordinal);
|
||||
foreach (var frame in info.AssociatedFrameInfos)
|
||||
{
|
||||
var root = frame;
|
||||
while (root.ParentFrameInfo is not null)
|
||||
{
|
||||
root = root.ParentFrameInfo;
|
||||
}
|
||||
|
||||
names.Add(OwnerOf(root));
|
||||
}
|
||||
|
||||
if (names.Count > 0)
|
||||
{
|
||||
owners[info.ProcessInfo.ProcessId] = string.Join('+', names);
|
||||
}
|
||||
else if (info.ProcessInfo.Kind == CoreWebView2ProcessKind.Renderer)
|
||||
{
|
||||
owners[info.ProcessInfo.ProcessId] = "renderer (no frames)";
|
||||
}
|
||||
}
|
||||
|
||||
return owners;
|
||||
}
|
||||
|
||||
private string OwnerOf(CoreWebView2FrameInfo root)
|
||||
{
|
||||
var rootHost = Uri.TryCreate(root.Source, UriKind.Absolute, out var u) ? u.Host : "";
|
||||
Slot? byHost = null;
|
||||
foreach (var slot in _slots)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (slot.View?.CoreWebView2 is not { } core)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var sameHost = Uri.TryCreate(core.Source, UriKind.Absolute, out var s) && s.Host == rootHost;
|
||||
if (sameHost && core.FrameId == root.FrameId)
|
||||
{
|
||||
return slot.Id;
|
||||
}
|
||||
|
||||
byHost ??= sameHost ? slot : null;
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// The view is being torn down.
|
||||
}
|
||||
}
|
||||
|
||||
return byHost?.Id ?? $"?{rootHost}";
|
||||
}
|
||||
|
||||
private void Mark(string phase)
|
||||
{
|
||||
_phase = phase;
|
||||
Log($"PHASE → {phase}");
|
||||
}
|
||||
|
||||
private void StartCsv()
|
||||
{
|
||||
if (_csv is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(Path.Combine(DataRoot, "memory"));
|
||||
var file = Path.Combine(DataRoot, "memory", $"{DateTime.UtcNow:yyyyMMdd-HHmmss}-samples.csv");
|
||||
_csv = new StreamWriter(file) { AutoFlush = true };
|
||||
_csv.WriteLine("time,phase,pid,kind,attributed,private_commit_mb,private_ws_mb,ws_mb,shared_commit_mb,cpu_ms");
|
||||
RecordButton.Content = "Stop CSV";
|
||||
Log($"CSV → {file}");
|
||||
}
|
||||
|
||||
private void StopCsv()
|
||||
{
|
||||
_csv?.Dispose();
|
||||
_csv = null;
|
||||
RecordButton.Content = "Start CSV";
|
||||
Log("CSV stopped");
|
||||
}
|
||||
|
||||
private async Task RunLadderAsync(Slot slot, TimeSpan phase)
|
||||
{
|
||||
StartCsv();
|
||||
Mark($"{slot.Id}:active");
|
||||
ShowOnly(slot);
|
||||
await Task.Delay(phase);
|
||||
Mark($"{slot.Id}:hidden");
|
||||
Hide(slot);
|
||||
await Task.Delay(phase / 2);
|
||||
Mark($"{slot.Id}:suspended");
|
||||
await SuspendAsync(slot);
|
||||
await Task.Delay(phase);
|
||||
Mark($"{slot.Id}:resumed");
|
||||
Resume(slot);
|
||||
await Task.Delay(phase / 2);
|
||||
Mark($"{slot.Id}:hibernated");
|
||||
Hibernate(slot);
|
||||
await Task.Delay(phase / 2);
|
||||
Mark($"{slot.Id}:reopened");
|
||||
await ReopenAsync(slot);
|
||||
await Task.Delay(phase);
|
||||
Mark("-");
|
||||
Log($"[{slot.Id}] ladder done");
|
||||
}
|
||||
|
||||
// ---- Unattended checks: `WebLab.exe --auto` ---------------------------------------------------
|
||||
|
||||
private async Task RunAutoAsync()
|
||||
{
|
||||
var targets = (List<Target>)Targets.ItemsSource;
|
||||
try
|
||||
{
|
||||
StartCsv();
|
||||
Mark("auto:shell-only");
|
||||
await Task.Delay(TimeSpan.FromSeconds(6));
|
||||
|
||||
// Spike #1: which key systems the runtime exposes.
|
||||
Mark("auto:eme");
|
||||
var emeWait = WaitForMessageAsync("eme");
|
||||
var eme = await OpenAsync(targets[0]);
|
||||
var emeResult = await emeWait;
|
||||
foreach (var r in emeResult.GetProperty("results").EnumerateArray())
|
||||
{
|
||||
Log($"EME {r.GetProperty("keySystem").GetString()} [{r.GetProperty("robustness").GetString()}]: "
|
||||
+ $"{(r.GetProperty("available").GetBoolean() ? "AVAILABLE" : "no")} — {r.GetProperty("detail").GetString()}");
|
||||
}
|
||||
|
||||
// Spike #4: detection and capture with DevTools UI disabled (the release setting).
|
||||
Mark("auto:cdp");
|
||||
var cdpWait = WaitForMessageAsync("cdp-detect");
|
||||
var cdp = await OpenAsync(targets[2]);
|
||||
Log($"CDP detect, capture off: {(await cdpWait).GetProperty("detected")}");
|
||||
foreach (var (runtime, log, label) in new[] { (true, true, "Runtime+Log"), (false, true, "Log only"), (false, false, "off") })
|
||||
{
|
||||
await SetCaptureAsync(cdp, runtime, log);
|
||||
var before = cdp.ConsoleRing.Count;
|
||||
var wait = WaitForMessageAsync("cdp-detect");
|
||||
await cdp.View!.CoreWebView2.ExecuteScriptAsync(
|
||||
"check(); console.log('ring-test', 42); console.warn('ring-warn'); setTimeout(() => { throw new Error('ring-throw'); });"
|
||||
+ "fetch('https://weblab.example/missing.json').catch(() => {});");
|
||||
var detected = (await wait).GetProperty("detected");
|
||||
await Task.Delay(1000);
|
||||
Log($"CDP detect, capture {label}: {detected}; ring buffer +{cdp.ConsoleRing.Count - before} entries");
|
||||
}
|
||||
|
||||
Log("Ring buffer contents:" + Environment.NewLine + string.Join(Environment.NewLine, cdp.ConsoleRing));
|
||||
|
||||
// Spike #3 dry run: environment baseline and a short ladder on a public page (not signed in).
|
||||
Hibernate(eme);
|
||||
Hibernate(cdp);
|
||||
Mark("auto:env-only");
|
||||
await Task.Delay(TimeSpan.FromSeconds(10));
|
||||
var youtube = targets.FirstOrDefault(t => t.Entry?.Id == "youtube");
|
||||
if (youtube is not null)
|
||||
{
|
||||
await RunLadderAsync(await OpenAsync(youtube), TimeSpan.FromSeconds(20));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"AUTO FAILED: {ex}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
StopCsv();
|
||||
await Task.Delay(500);
|
||||
Close();
|
||||
}
|
||||
}
|
||||
|
||||
// ---- UI handlers -----------------------------------------------------------------------------
|
||||
|
||||
private async void OnOpen(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Targets.SelectedItem is Target target)
|
||||
{
|
||||
await OpenAsync(target);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnShow(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Selected is { View: not null } slot)
|
||||
{
|
||||
ShowOnly(slot);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnHide(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Selected is { View: not null } slot)
|
||||
{
|
||||
Hide(slot);
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnSuspend(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Selected is { View: not null } slot)
|
||||
{
|
||||
await SuspendAsync(slot);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnResume(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Selected is { View: not null } slot)
|
||||
{
|
||||
Resume(slot);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnHibernate(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Selected is { } slot)
|
||||
{
|
||||
Hibernate(slot);
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnReopen(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Selected is { View: null } slot)
|
||||
{
|
||||
await ReopenAsync(slot);
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnCaptureFull(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Selected is { } slot)
|
||||
{
|
||||
await SetCaptureAsync(slot, runtime: true, log: true);
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnCaptureLogOnly(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Selected is { } slot)
|
||||
{
|
||||
await SetCaptureAsync(slot, runtime: false, log: true);
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnCaptureOff(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Selected is { } slot)
|
||||
{
|
||||
await SetCaptureAsync(slot, runtime: false, log: false);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnCloseSlot(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Selected is { } slot)
|
||||
{
|
||||
Hibernate(slot);
|
||||
_slots.Remove(slot);
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnLadder(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Selected is not { View: not null } slot)
|
||||
{
|
||||
Log("Select an open slot first.");
|
||||
return;
|
||||
}
|
||||
|
||||
var seconds = int.TryParse(PhaseSeconds.Text, out var s) && s > 0 ? s : 60;
|
||||
await RunLadderAsync(slot, TimeSpan.FromSeconds(seconds));
|
||||
}
|
||||
|
||||
private void OnHibernateAll(object sender, RoutedEventArgs e)
|
||||
{
|
||||
foreach (var slot in _slots)
|
||||
{
|
||||
Hibernate(slot);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnRecord(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (_csv is null)
|
||||
{
|
||||
StartCsv();
|
||||
}
|
||||
else
|
||||
{
|
||||
StopCsv();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnMark(object sender, RoutedEventArgs e) => Mark(string.IsNullOrWhiteSpace(MarkText.Text) ? "-" : MarkText.Text.Trim());
|
||||
|
||||
private void OnSlotSelected(object sender, SelectionChangedEventArgs e) =>
|
||||
ConsoleBox.Text = Selected is { } slot ? string.Join(Environment.NewLine, slot.ConsoleRing) : "";
|
||||
|
||||
private void Log(string line)
|
||||
{
|
||||
var stamped = $"{DateTime.Now:HH:mm:ss.fff} {line}";
|
||||
_logFile.WriteLine(stamped);
|
||||
LogBox.AppendText(stamped + Environment.NewLine);
|
||||
LogBox.ScrollToEnd();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace WebLab;
|
||||
|
||||
/// <summary>One process in one sample. All sizes in MiB.</summary>
|
||||
public sealed record ProcessSample(
|
||||
int Pid, string Kind, string Attributed, double PrivateCommitMb, double PrivateWsMb, double WsMb, double SharedCommitMb, double CpuMs);
|
||||
|
||||
/// <summary>
|
||||
/// The three candidate governor metrics side by side (docs/RAM-GOVERNOR.md §4): private commit
|
||||
/// (Process.PrivateMemorySize64), private working set (PROCESS_MEMORY_COUNTERS_EX2) and working set.
|
||||
/// </summary>
|
||||
public static class MemorySampler
|
||||
{
|
||||
private const uint ProcessQueryLimitedInformation = 0x1000;
|
||||
private const uint ProcessVmRead = 0x0010;
|
||||
private const double MiB = 1024 * 1024;
|
||||
|
||||
public static ProcessSample? Sample(int pid, string kind, string attributed)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var process = Process.GetProcessById(pid);
|
||||
var privateCommit = process.PrivateMemorySize64 / MiB;
|
||||
var ws = process.WorkingSet64 / MiB;
|
||||
|
||||
double privateWs = double.NaN, sharedCommit = double.NaN, cpuMs = double.NaN;
|
||||
using var handle = OpenProcess(ProcessQueryLimitedInformation | ProcessVmRead, false, pid) is { IsInvalid: false } h
|
||||
? h
|
||||
: OpenProcess(ProcessQueryLimitedInformation, false, pid);
|
||||
if (!handle.IsInvalid)
|
||||
{
|
||||
var counters = new ProcessMemoryCountersEx2 { Cb = (uint)Marshal.SizeOf<ProcessMemoryCountersEx2>() };
|
||||
if (GetProcessMemoryInfo(handle, ref counters, counters.Cb))
|
||||
{
|
||||
privateWs = counters.PrivateWorkingSetSize / MiB;
|
||||
sharedCommit = counters.SharedCommitUsage / MiB;
|
||||
}
|
||||
|
||||
if (GetProcessTimes(handle, out _, out _, out var kernel, out var user))
|
||||
{
|
||||
cpuMs = (kernel + user) / 10_000.0;
|
||||
}
|
||||
}
|
||||
|
||||
return new ProcessSample(pid, kind, attributed, privateCommit, privateWs, ws, sharedCommit, cpuMs);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or System.ComponentModel.Win32Exception)
|
||||
{
|
||||
return null; // exited between enumeration and sampling
|
||||
}
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct ProcessMemoryCountersEx2
|
||||
{
|
||||
public uint Cb;
|
||||
public uint PageFaultCount;
|
||||
public nuint PeakWorkingSetSize;
|
||||
public nuint WorkingSetSize;
|
||||
public nuint QuotaPeakPagedPoolUsage;
|
||||
public nuint QuotaPagedPoolUsage;
|
||||
public nuint QuotaPeakNonPagedPoolUsage;
|
||||
public nuint QuotaNonPagedPoolUsage;
|
||||
public nuint PagefileUsage;
|
||||
public nuint PeakPagefileUsage;
|
||||
public nuint PrivateUsage;
|
||||
public nuint PrivateWorkingSetSize;
|
||||
public ulong SharedCommitUsage;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern SafeProcessHandle OpenProcess(uint desiredAccess, bool inheritHandle, int processId);
|
||||
|
||||
[DllImport("psapi.dll", SetLastError = true)]
|
||||
private static extern bool GetProcessMemoryInfo(SafeProcessHandle process, ref ProcessMemoryCountersEx2 counters, uint size);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool GetProcessTimes(SafeProcessHandle process, out long creation, out long exit, out long kernel, out long user);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
namespace WebLab;
|
||||
|
||||
/// <summary>One open web app: the lab's stand-in for a governed web module.</summary>
|
||||
public sealed class Slot
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
|
||||
public required string Profile { get; init; }
|
||||
|
||||
public required string StartUrl { get; init; }
|
||||
|
||||
public CatalogEntry? Entry { get; init; }
|
||||
|
||||
public WebView2? View { get; set; }
|
||||
|
||||
public string State { get; set; } = "Created";
|
||||
|
||||
/// <summary>The only thing kept across hibernation (docs/RAM-GOVERNOR.md §1).</summary>
|
||||
public string? SavedUrl { get; set; }
|
||||
|
||||
public bool Capturing { get; set; }
|
||||
|
||||
public CoreWebView2DevToolsProtocolEventReceiver? ConsoleReceiver { get; set; }
|
||||
|
||||
public CoreWebView2DevToolsProtocolEventReceiver? LogReceiver { get; set; }
|
||||
|
||||
public Queue<string> ConsoleRing { get; } = new();
|
||||
|
||||
public double AttributedMb { get; set; }
|
||||
|
||||
public void AddConsole(string line)
|
||||
{
|
||||
// The SPEC's 200-entry ring buffer per app.
|
||||
if (ConsoleRing.Count == 200)
|
||||
{
|
||||
ConsoleRing.Dequeue();
|
||||
}
|
||||
|
||||
ConsoleRing.Enqueue(line);
|
||||
}
|
||||
|
||||
public override string ToString() => $"{Id} [{Profile}] {State} · {AttributedMb:F0} MB";
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- Spikes #1–#4 (issues #2–#5): DRM, sign-in, memory ladder, CDP console capture in WebView2. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4314.35" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="LabPages\**\*" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in new issue
Block a user