diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 930c0bba..1f7b1525 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -199,6 +199,9 @@ jobs: runs-on: windows-latest timeout-minutes: 15 environment: update-signing + permissions: + contents: read + actions: read steps: # Keep the signing secret in the protected update-signing environment. - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -211,6 +214,14 @@ jobs: with: global-json-file: global.json + - name: Download native artifact from successful CI run + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + name: tested-native + path: artifacts/native + github-token: ${{ secrets.GITHUB_TOKEN }} + run-id: ${{ github.event.workflow_run.id }} + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 with: path: signed-assets diff --git a/.gitleaks.toml b/.gitleaks.toml index 6dd6c35e..dd317e6a 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -23,18 +23,10 @@ regexes = ['^LEGACY-KEY-12345$'] [[allowlists]] description = "Exact built-in YouTube client identifier, one service only" condition = "AND" -paths = ['(^|[\\/])Services[\\/]YouTubeSubtitleService\.cs$', '(^|[\\/])Assets[\\/]MediaProtocols\.json$'] +paths = ['(^|[\\/])Services[\\/]YouTubeSubtitleService\.cs$'] regexTarget = "secret" regexes = ['^(?:AIza)SyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8$'] -# This exact public Spotify Web Player TOTP version-61 seed is not a tenant key. -[[allowlists]] -description = "Exact built-in Spotify Web Player TOTP seed in MediaProtocols.json" -condition = "AND" -paths = ['(^|[\\/])Assets[\\/]MediaProtocols\.json$'] -regexTarget = "secret" -regexes = ['^Mzc2MTM2Mzg3NTM4NDU5ODkzODgzMzEyMzEwOTExOTkyODQ3MTEyNDQ4ODk0NDEwMjEwNTExMjk3MTA4$'] - [[allowlists]] description = "Synthetic clipboard benchmark tokens" condition = "AND" diff --git a/.gitleaksignore b/.gitleaksignore index ee4bdfb7..3a224c28 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -5,4 +5,6 @@ 176edcfcb8628d6af9d719f9d14a7905e4e51f25:Services/YouTubeSubtitleService.cs:gcp-api-key:34 4a886045b2ffda4b7f5914fff22683871c4cd5f0:Assets/MediaProtocols.json:gcp-api-key:7 4a886045b2ffda4b7f5914fff22683871c4cd5f0:Assets/MediaProtocols.json:generic-api-key:4 +bd171fc91536901017c12afac0c59b2a45e19c16:Assets/MediaProtocols.json:gcp-api-key:7 +bd171fc91536901017c12afac0c59b2a45e19c16:Assets/MediaProtocols.json:generic-api-key:4 3ca5c3d3319460b24db9f01a6732050d9bf19ab5:Tests/SettingsActionsAndBaselineTests.cs:generic-api-key:39 diff --git a/Assets/MediaProtocols.json b/Assets/MediaProtocols.json deleted file mode 100644 index 1144e184..00000000 --- a/Assets/MediaProtocols.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "SchemaVersion": 1, - "SpotifyTotpVersion": "61", - "SpotifyTotpSecretBase64": "Mzc2MTM2Mzg3NTM4NDU5ODkzODgzMzEyMzEwOTExOTkyODQ3MTEyNDQ4ODk0NDEwMjEwNTExMjk3MTA4", - "SpotifyFindTracksHash": "903df2a65d8121e27d73a2be03c01e88ebe6021bb6d4eb82a389e35d87e51d27", - "SpotifyCanvasHash": "575138ab27cd5c1b3e54da54d0a7cc8d85485402de26340c2145f0f6bb5e7a9f", - "YouTubeInnertubeApiKey": "AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8", - "PipedInstances": [ - "pipedapi.kavin.rocks", - "pipedapi.adminforge.de" - ], - "InvidiousInstances": [ - "invidious.fdn.fr", - "invidious.nerdvpn.de" - ], - "YouTubeAndroidClientVersion": "20.10.38" -} diff --git a/Controllers/D3DImageFramePresenter.Webcam.cs b/Controllers/D3DImageFramePresenter.Webcam.cs index 699dcae9..d62e5e1a 100644 --- a/Controllers/D3DImageFramePresenter.Webcam.cs +++ b/Controllers/D3DImageFramePresenter.Webcam.cs @@ -19,9 +19,6 @@ internal sealed partial class D3DImageFramePresenter internal event Action? WebcamFallbackRequested; - internal bool FitsWebcam(int width, int height, int token) => - width == _surfaceWidth && height == _surfaceHeight && token == _sessionGeneration; - internal void RequestWebcamAcquire(WebcamCaptureController capture, int token) { ArgumentNullException.ThrowIfNull(capture); diff --git a/Controllers/DedicatedKeyboardHook.cs b/Controllers/DedicatedKeyboardHook.cs deleted file mode 100644 index b970b15b..00000000 --- a/Controllers/DedicatedKeyboardHook.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System.Windows.Threading; -using VNotch.Services; -using static VNotch.Services.Win32Interop; - -namespace VNotch.Controllers; - -/// Shares a single reference-counted low-level keyboard hook thread across all listeners. -internal sealed class DedicatedKeyboardHook : IDisposable -{ - private static readonly object Gate = new(); - private static SharedHookHost? s_current; - - private readonly SharedHookHost _host; - private readonly Func _callback; - private int _disposed; - - internal int InstallationError { get; } - internal int ManagedThreadId => _host.ManagedThreadId; - internal Dispatcher? Dispatcher => _host.Dispatcher; - internal bool IsInstalled => Volatile.Read(ref _disposed) == 0 && _host.IsInstalled; - - internal DedicatedKeyboardHook(Func handleKey) - { - ArgumentNullException.ThrowIfNull(handleKey); - _callback = (key, message) => Volatile.Read(ref _disposed) == 0 && handleKey(key, message); - - lock (Gate) - { - if (s_current == null || !s_current.IsActive) - { - s_current = new SharedHookHost(); - } - - _host = s_current; - if (!_host.IsInstalled) - { - InstallationError = _host.InstallationError; - s_current = null; - return; - } - - _host.AddListener(_callback); - } - } - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) return; - - bool shouldShutdown = false; - lock (Gate) - { - if (_host.RemoveListener(_callback) == 0 && ReferenceEquals(s_current, _host)) - { - s_current = null; - shouldShutdown = true; - } - } - - if (shouldShutdown) - { - _host.Shutdown(); - } - } - - private sealed class SharedHookHost - { - private static readonly TimeSpan WorkerStartupTimeout = TimeSpan.FromSeconds(2); - private readonly Thread _thread; - private readonly LowLevelKeyboardHook _hook; - private Func[] _listeners = []; - private int _stopped; - - internal Dispatcher? Dispatcher { get; private set; } - internal int InstallationError { get; private set; } - internal int ManagedThreadId => _thread.ManagedThreadId; - internal bool IsInstalled => Volatile.Read(ref _stopped) == 0 && _hook.IsInstalled; - internal bool IsActive => Volatile.Read(ref _stopped) == 0 && _hook.IsInstalled && Dispatcher is { HasShutdownStarted: false }; - - internal SharedHookHost() - { - _hook = new LowLevelKeyboardHook(DispatchKey); - var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - _thread = new Thread(() => Run(ready)) { IsBackground = true, Name = "VNotch keyboard hook" }; - _thread.SetApartmentState(ApartmentState.STA); - _thread.Start(); - // Startup only installs the native hook; bound the wait so a stalled worker cannot wedge the UI thread. - if (!ready.Task.Wait(WorkerStartupTimeout)) - RuntimeLog.Warn("KEYBOARD-HOOK", "Timed out waiting for shared keyboard hook startup."); - } - - private bool DispatchKey(KBDLLHOOKSTRUCT key, int message) - { - var snapshot = Volatile.Read(ref _listeners); - bool swallow = false; - for (int i = 0; i < snapshot.Length; i++) - { - if (snapshot[i](key, message)) - swallow = true; - } - return swallow; - } - - internal void AddListener(Func listener) - { - var current = _listeners; - var next = new Func[current.Length + 1]; - Array.Copy(current, next, current.Length); - next[current.Length] = listener; - Volatile.Write(ref _listeners, next); - } - - internal int RemoveListener(Func listener) - { - var current = _listeners; - int idx = Array.IndexOf(current, listener); - if (idx < 0) return current.Length; - if (current.Length == 1) - { - Volatile.Write(ref _listeners, []); - return 0; - } - var next = new Func[current.Length - 1]; - if (idx > 0) Array.Copy(current, 0, next, 0, idx); - if (idx < current.Length - 1) Array.Copy(current, idx + 1, next, idx, current.Length - idx - 1); - Volatile.Write(ref _listeners, next); - return next.Length; - } - - private void Run(TaskCompletionSource ready) - { - try - { - Dispatcher = Dispatcher.CurrentDispatcher; - bool installed = _hook.Install(); - if (!installed) InstallationError = _hook.InstallationError; - ready.TrySetResult(); - if (installed) Dispatcher.Run(); - } - catch (Exception ex) - { - InstallationError = ex.HResult; - } - finally - { - Interlocked.Exchange(ref _stopped, 1); - ready.TrySetResult(); - _hook.Dispose(); - } - } - - internal void Shutdown() - { - if (Interlocked.Exchange(ref _stopped, 1) != 0) return; - // No synchronous UI call is made from the hook thread, so shutdown cannot - // deadlock with activation/layout work on the UI dispatcher. - var dispatcher = Dispatcher; - if (dispatcher == null || dispatcher.HasShutdownStarted) return; - if (Thread.CurrentThread == _thread) - { - _hook.Dispose(); - dispatcher.InvokeShutdown(); - return; - } - try - { - dispatcher.Invoke(() => - { - _hook.Dispose(); - dispatcher.InvokeShutdown(); - }, DispatcherPriority.Send); - } - catch - { - try { dispatcher.BeginInvokeShutdown(DispatcherPriority.Send); } - catch { /* already shutting down */ } - } - } - } -} diff --git a/Controllers/OverlayWindowController.cs b/Controllers/OverlayWindowController.cs index 2fed1f9f..e992033b 100644 --- a/Controllers/OverlayWindowController.cs +++ b/Controllers/OverlayWindowController.cs @@ -163,11 +163,6 @@ public void MoveFixedPosition(int newX, int newY) ApplyFixedBounds(); } - public void ResetToCenteredTop(double widthDip, double heightDip) - { - PositionAtTop(Math.Max(600, widthDip - HorizontalPadding), Math.Max(200, heightDip - VerticalPadding)); - } - public void ReassertBounds() { if (!_state.HasFixedBounds || _state.WindowWidth <= 0 || _state.WindowHeight <= 0) diff --git a/Interop/CountdownHandle.cs b/Interop/CountdownHandle.cs index 464f6e4a..ea18585d 100644 --- a/Interop/CountdownHandle.cs +++ b/Interop/CountdownHandle.cs @@ -29,9 +29,6 @@ private static partial int vn_countdown_command( long arg, M05Native.VnCountdownSnapshotPod* outSnapshot); - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_calendar_set_day_tick_enabled(long countdownHandle, byte enabled); - internal static int DestroyRaw(long handle) => vn_countdown_destroy(handle); internal static CountdownHandle Create(long session = 0) @@ -64,26 +61,6 @@ internal M05Native.VnCountdownSnapshotPod Command(uint op, long arg = 0) } } - internal void SetCalendarDayTickEnabled(bool enabled) - { - ObjectDisposedException.ThrowIf(IsClosed || IsInvalid, this); - bool addedRef = false; - try - { - DangerousAddRef(ref addedRef); - NativeResult.RequireSuccess( - vn_calendar_set_day_tick_enabled((long)DangerousGetHandle(), enabled ? (byte)1 : (byte)0), - nameof(vn_calendar_set_day_tick_enabled)); - } - finally - { - if (addedRef) - { - DangerousRelease(); - } - } - } - protected override bool ReleaseHandle() => vn_countdown_destroy((long)handle) == (int)NativeStatus.Ok; } diff --git a/Interop/GlassPresenterSafeHandle.cs b/Interop/GlassPresenterSafeHandle.cs index 647c8025..384af876 100644 --- a/Interop/GlassPresenterSafeHandle.cs +++ b/Interop/GlassPresenterSafeHandle.cs @@ -6,7 +6,7 @@ namespace VNotch.Interop; /// /// SafeHandle owning a native M12 D3D9Presenter handle in vnotch_rust.dll. -/// Borrowed COM pointers (, ) remain valid only +/// Borrowed COM pointers () remain valid only /// until or . /// internal sealed unsafe partial class GlassPresenterSafeHandle : VNotchSafeHandle @@ -47,9 +47,6 @@ private static partial int vn_glass_presenter_recreate( [LibraryImport(NativeAbi.RustLibraryName)] private static partial int vn_glass_presenter_set_interval(long handle, double intervalMs); - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_glass_presenter_get_d3d9_device(long handle, nint* outDevice9Ptr); - [LibraryImport(NativeAbi.RustLibraryName)] private static partial int vn_glass_gpu_render_v2( long handle, @@ -216,23 +213,6 @@ internal void SetInterval(double intervalMs) } } - internal nint GetD3D9Device() - { - long rawHandle = AcquireRawHandle(out bool addedRef); - try - { - nint devicePtr = 0; - NativeResult.RequireSuccess( - vn_glass_presenter_get_d3d9_device(rawHandle, &devicePtr), - nameof(vn_glass_presenter_get_d3d9_device)); - return devicePtr; - } - finally - { - ReleaseRawHandle(addedRef); - } - } - internal int RenderDesktop(in M12Native.VnGpuFrame frame) { long rawHandle = AcquireRawHandle(out bool addedRef); diff --git a/Interop/ImagingNative.cs b/Interop/ImagingNative.cs index 3a000633..005027af 100644 --- a/Interop/ImagingNative.cs +++ b/Interop/ImagingNative.cs @@ -293,12 +293,6 @@ internal static partial int vn_dicolor_extract_palette_v2( VnColorRequest* req, VnPaletteResult* outRes); - [LibraryImport(NativeAbi.RustLibraryName)] - internal static partial int vn_dicolor_clamp_crop_v2( - VnColorRequest* req, - VnCoreRect* outRect, - byte* outValid); - [LibraryImport(NativeAbi.RustLibraryName)] internal static partial int vn_dicolor_ensure_contrast_v2( VnColorRequest* req, diff --git a/Interop/InputHookSafeHandle.cs b/Interop/InputHookSafeHandle.cs index 46f37cb7..6b7da669 100644 --- a/Interop/InputHookSafeHandle.cs +++ b/Interop/InputHookSafeHandle.cs @@ -49,17 +49,6 @@ private static partial int vn_input_hook_set_raw_mouse_excluded_hwnd( internal static int DestroyRaw(long hookHandle) => vn_input_hook_destroy(hookHandle); - internal static InputHookSafeHandle CreateKeyboard(long session, bool captureSpotlight, out int win32Error) - { - int rc = vn_input_hook_create_keyboard( - session, - captureSpotlight ? (byte)1 : (byte)0, - out long rawHandle, - out win32Error); - NativeResult.RequireSuccess(rc, nameof(vn_input_hook_create_keyboard)); - return new InputHookSafeHandle(checked((nint)rawHandle)); - } - internal static bool TryCreateKeyboard( long session, bool captureSpotlight, @@ -81,13 +70,6 @@ internal static bool TryCreateKeyboard( return false; } - internal static InputHookSafeHandle CreateRawMouse(long session, out int win32Error) - { - int rc = vn_input_hook_create_raw_mouse(session, out long rawHandle, out win32Error); - NativeResult.RequireSuccess(rc, nameof(vn_input_hook_create_raw_mouse)); - return new InputHookSafeHandle(checked((nint)rawHandle)); - } - internal static bool TryCreateRawMouse( long session, out InputHookSafeHandle? handle, @@ -104,13 +86,6 @@ internal static bool TryCreateRawMouse( return false; } - internal static InputHookSafeHandle CreateForeground(long session, nint notchHwnd, uint hideFlags) - { - int rc = vn_input_hook_create_foreground(session, notchHwnd, hideFlags, out long rawHandle); - NativeResult.RequireSuccess(rc, nameof(vn_input_hook_create_foreground)); - return new InputHookSafeHandle(checked((nint)rawHandle)); - } - internal static bool TryCreateForeground( long session, nint notchHwnd, @@ -147,9 +122,6 @@ internal void SetSpotlightConfig(uint flags) } } - internal static int SetRawMouseExcludedHwndRaw(long hookHandle, nint excludedHwnd) => - vn_input_hook_set_raw_mouse_excluded_hwnd(hookHandle, excludedHwnd); - internal void SetRawMouseExcludedHwnd(nint excludedHwnd) { ObjectDisposedException.ThrowIf(IsClosed || IsInvalid, this); diff --git a/Interop/M05Native.cs b/Interop/M05Native.cs index c26f83c1..a891ad9d 100644 --- a/Interop/M05Native.cs +++ b/Interop/M05Native.cs @@ -240,9 +240,6 @@ internal struct VnWeatherModuleDecisionPod [LibraryImport(NativeAbi.RustLibraryName)] internal static partial int vn_power_bt_extract_name_from_id(byte* idUtf8, uint idLen, VnOwnedBytes* outNameUtf8); - [LibraryImport(NativeAbi.RustLibraryName)] - internal static partial int vn_power_bt_parse_percentage(byte* buf, uint len, int* outPercentage); - [LibraryImport(NativeAbi.RustLibraryName)] internal static partial int vn_power_apply_system_power_status_v2( VnSystemPowerStatusPod* input, @@ -481,19 +478,6 @@ internal static string ExtractBtNameFromId(string? id) => return CopyOwnedUtf8AndFree(ref owned); }); - internal static int ParseBtBatteryPercentage(ReadOnlySpan value) - { - int pct = -1; - fixed (byte* p = value) - { - NativeResult.RequireSuccess( - vn_power_bt_parse_percentage(p, (uint)value.Length, &pct), - nameof(vn_power_bt_parse_percentage)); - } - - return pct; - } - internal static void ApplySystemPowerStatus(in VnSystemPowerStatusPod status, ref VnBatterySnapshotPod snap) { VnSystemPowerStatusPod copy = status; diff --git a/Interop/M08Native.cs b/Interop/M08Native.cs index 97d2400e..1f2e774c 100644 --- a/Interop/M08Native.cs +++ b/Interop/M08Native.cs @@ -36,21 +36,6 @@ internal struct VnClipboardPolicyPod public long ApprovalThresholdBytes; public long MaxArchiveExtractBytes; public long MaxDropImageBytes; - - public static VnClipboardPolicyPod CreateDefault() => new() - { - MaxUnpinnedEntries = DefaultMaxUnpinnedEntries, - RetentionDays = DefaultRetentionDays, - SensitiveTtlSeconds = DefaultSensitiveTtlSeconds, - MaxImportItems = DefaultMaxImportItems, - MaxImportContents = DefaultMaxImportContents, - AutoDeleteSensitive = 1, - AllowNetworkArtwork = 0, - MaxUnpinnedBytes = DefaultMaxUnpinnedBytes, - ApprovalThresholdBytes = DefaultApprovalThresholdBytes, - MaxArchiveExtractBytes = DefaultMaxArchiveExtractBytes, - MaxDropImageBytes = DefaultMaxDropImageBytes, - }; } [StructLayout(LayoutKind.Sequential)] diff --git a/Interop/M08Postcard.cs b/Interop/M08Postcard.cs index 402e321b..0166554e 100644 --- a/Interop/M08Postcard.cs +++ b/Interop/M08Postcard.cs @@ -300,9 +300,6 @@ public void WriteVarint64(ulong value) _buffer.Advance(i); } - public void WriteZigZagInt32(int value) - => WriteVarint32((uint)((value << 1) ^ (value >> 31))); - public void WriteZigZagInt64(long value) => WriteVarint64((ulong)((value << 1) ^ (value >> 63))); diff --git a/Interop/M10Native.cs b/Interop/M10Native.cs index 01c5ec31..fbe4db83 100644 --- a/Interop/M10Native.cs +++ b/Interop/M10Native.cs @@ -22,7 +22,6 @@ internal static unsafe partial class M10Native internal const int LyricKindNetEaseJson = 7; internal const int LyricKindKugouKrcRaw = 8; - internal const int LyricEncodingUtf8 = 0; internal const int LyricEncodingUtf16Le = 1; internal const int TransportToggle = 0; @@ -34,7 +33,6 @@ internal static unsafe partial class M10Native internal const uint BrowserTabNavigateBack = 1; private const int Utf8StackThreshold = 256; - private const int TotpBufferCapacity = 8; private const int TimeBufferCapacity = 32; [StructLayout(LayoutKind.Sequential)] @@ -112,25 +110,6 @@ internal struct VnSubtitleFetchRequest public byte Reserved2; } - [StructLayout(LayoutKind.Sequential)] - internal struct VnLyricsParseRequest - { - public byte* Bytes; - public uint Len; - public int Kind; - public int Encoding; - public uint Reserved; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct VnTotpRequest - { - public byte* Secret; - public long TimestampMs; - public uint SecretLen; - public uint Reserved; - } - [StructLayout(LayoutKind.Sequential)] internal struct VnVolumeSessionScoreReq { @@ -156,38 +135,11 @@ internal struct VnVolumeSessionMatchReq public uint SourceLen; } - [StructLayout(LayoutKind.Sequential)] - internal struct VnVolumeUtf8PairReq - { - public byte* FirstUtf8; - public byte* SecondUtf8; - public uint FirstLen; - public uint SecondLen; - } - [LibraryImport(NativeAbi.RustLibraryName)] private static partial int vn_media_artwork_detect_bounds( VnArtworkBoundsRequest* req, VnArtworkBoundsResult* outBounds); - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_lyrics_parse_blob( - VnLyricsParseRequest* req, - VnOwnedBytes* outPostcard); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_lyrics_decode_krc( - byte* krcBytes, - uint krcLen, - VnOwnedBytes* outUtf8Text); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_spotify_totp_generate( - VnTotpRequest* req, - byte* outDigits6, - uint cap, - uint* outLen); - [LibraryImport(NativeAbi.RustLibraryName)] private static partial int vn_progress_format_time_utf8( long timeTicks, @@ -202,10 +154,6 @@ private static partial int vn_media_try_get_youtube_video_id_v2( int mode, VnOwnedBytes* outUtf8); - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_media_session_volume_process_aliases_v2( - VnOwnedBytes* outJsonUtf8); - [LibraryImport(NativeAbi.RustLibraryName)] private static partial int vn_media_session_volume_compute_score_v2( VnVolumeSessionScoreReq* req, @@ -222,16 +170,6 @@ private static partial int vn_media_session_volume_matches_source_v2( VnVolumeSessionMatchReq* req, byte* outMatches); - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_media_session_volume_contains_source_token_v2( - VnVolumeUtf8PairReq* req, - byte* outContains); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_media_session_volume_matches_executable_v2( - VnVolumeUtf8PairReq* req, - byte* outMatches); - [LibraryImport(NativeAbi.RustLibraryName)] private static partial int vn_media_session_volume_get_process_ids_v2( byte* sourceAppIdUtf8, @@ -323,107 +261,6 @@ internal static bool TryDetectArtworkBounds( } } - internal static VnArtworkBoundsResult DetectArtworkBoundsRaw( - byte* bgraPixels, - int pixelsLen, - int stride, - int sw, - int sh, - int width, - int height, - double scaleX, - double scaleY) - { - var req = new VnArtworkBoundsRequest - { - BgraPixels = bgraPixels, - ScaleX = scaleX, - ScaleY = scaleY, - PixelsLen = pixelsLen, - Stride = stride, - Sw = sw, - Sh = sh, - Width = width, - Height = height, - }; - VnArtworkBoundsResult res = default; - NativeResult.RequireSuccess( - vn_media_artwork_detect_bounds(&req, &res), - nameof(vn_media_artwork_detect_bounds)); - return res; - } - - internal static List ParseLyricsBlob( - ReadOnlySpan bytes, - int kind, - int encoding = LyricEncodingUtf8) - { - if (bytes.IsEmpty) - { - return []; - } - - VnOwnedBytes owned = default; - try - { - fixed (byte* pBytes = bytes) - { - var req = new VnLyricsParseRequest - { - Bytes = pBytes, - Len = (uint)bytes.Length, - Kind = kind, - Encoding = encoding, - }; - NativeResult.RequireSuccess( - vn_lyrics_parse_blob(&req, &owned), - nameof(vn_lyrics_parse_blob)); - } - - return DecodeParsedLyricsPostcard(owned.AsSpan()); - } - finally - { - owned.Free(); - } - } - - internal static List ParseLyricsText(string? text, int kind) => - WithUtf8(text, utf8 => ParseLyricsBlob(utf8, kind, LyricEncodingUtf8)); - - internal static string DecodeKrc(ReadOnlySpan krcBytes) - { - VnOwnedBytes owned = default; - fixed (byte* pBytes = krcBytes) - { - NativeResult.RequireSuccess( - vn_lyrics_decode_krc(pBytes, (uint)krcBytes.Length, &owned), - nameof(vn_lyrics_decode_krc)); - } - - return CopyOwnedUtf8AndFree(ref owned); - } - - internal static string GenerateSpotifyTotp(ReadOnlySpan secret, long timestampMs) - { - byte* buf = stackalloc byte[TotpBufferCapacity]; - uint outLen = 0; - fixed (byte* pSecret = secret) - { - var req = new VnTotpRequest - { - Secret = pSecret, - TimestampMs = timestampMs, - SecretLen = (uint)secret.Length, - }; - NativeResult.RequireSuccess( - vn_spotify_totp_generate(&req, buf, TotpBufferCapacity, &outLen), - nameof(vn_spotify_totp_generate)); - } - - return Encoding.ASCII.GetString(new ReadOnlySpan(buf, (int)outLen)); - } - internal static string FormatProgressTime(TimeSpan time) { byte* buf = stackalloc byte[TimeBufferCapacity]; @@ -499,46 +336,6 @@ private static VnLyricWordPod[] ReadWordPodsFromJson(JsonElement root) return words; } - private static List DecodeParsedLyricsPostcard(ReadOnlySpan payload) - { - if (payload.IsEmpty) - { - return []; - } - - int pos = 0; - int lineCount = checked((int)ReadVarUInt64(payload, ref pos)); - var lines = new VnLyricLinePod[lineCount]; - for (int i = 0; i < lineCount; i++) - { - lines[i] = new VnLyricLinePod - { - StartTicks = ReadZigZag64(payload, ref pos), - Utf8Offset = ReadZigZag32(payload, ref pos), - Utf8Len = ReadZigZag32(payload, ref pos), - WordOffset = ReadZigZag32(payload, ref pos), - WordCount = ReadZigZag32(payload, ref pos), - }; - } - - int wordCount = checked((int)ReadVarUInt64(payload, ref pos)); - var words = new VnLyricWordPod[wordCount]; - for (int i = 0; i < wordCount; i++) - { - words[i] = new VnLyricWordPod - { - StartTicks = ReadZigZag64(payload, ref pos), - EndTicks = ReadZigZag64(payload, ref pos), - Utf8Offset = ReadZigZag32(payload, ref pos), - Utf8Len = ReadZigZag32(payload, ref pos), - }; - } - - int textLen = checked((int)ReadVarUInt64(payload, ref pos)); - ReadOnlySpan textUtf8 = payload.Slice(pos, textLen); - return BuildLyricLines(lines, words, textUtf8); - } - private static List BuildLyricLines( VnLyricLinePod[] lines, VnLyricWordPod[] words, @@ -595,37 +392,6 @@ private static List BuildLyricLines( return result; } - private static ulong ReadVarUInt64(ReadOnlySpan data, ref int pos) - { - ulong value = 0; - int shift = 0; - while (pos < data.Length) - { - byte b = data[pos++]; - value |= (ulong)(b & 0x7F) << shift; - if ((b & 0x80) == 0) - { - return value; - } - - shift += 7; - } - - throw new InvalidDataException("Truncated postcard varint payload."); - } - - private static long ReadZigZag64(ReadOnlySpan data, ref int pos) - { - ulong raw = ReadVarUInt64(data, ref pos); - return (long)(raw >> 1) ^ -(long)(raw & 1UL); - } - - private static int ReadZigZag32(ReadOnlySpan data, ref int pos) - { - uint raw = unchecked((uint)ReadVarUInt64(data, ref pos)); - return (int)(raw >> 1) ^ -(int)(raw & 1U); - } - internal static string? ExtractYouTubeVideoId(string? input, int mode = 2) { if (string.IsNullOrWhiteSpace(input)) @@ -648,42 +414,6 @@ private static int ReadZigZag32(ReadOnlySpan data, ref int pos) return string.IsNullOrEmpty(id) ? null : id; } - internal static List<(string Token, string ProcessName)> GetVolumeProcessAliases() - { - VnOwnedBytes owned = default; - try - { - NativeResult.RequireSuccess( - vn_media_session_volume_process_aliases_v2(&owned), - nameof(vn_media_session_volume_process_aliases_v2)); - ReadOnlySpan span = owned.AsSpan(); - if (span.IsEmpty) - { - return []; - } - - using JsonDocument doc = JsonDocument.Parse(span.ToArray()); - if (doc.RootElement.ValueKind != JsonValueKind.Array) - { - return []; - } - - var result = new List<(string Token, string ProcessName)>(doc.RootElement.GetArrayLength()); - foreach (JsonElement item in doc.RootElement.EnumerateArray()) - { - string token = item.TryGetProperty("token", out JsonElement tok) ? tok.GetString() ?? string.Empty : string.Empty; - string proc = item.TryGetProperty("processName", out JsonElement prc) ? prc.GetString() ?? string.Empty : string.Empty; - result.Add((token, proc)); - } - - return result; - } - finally - { - owned.Free(); - } - } - internal static double ComputeVolumeSessionScore(in VnVolumeSessionScoreReq req) { double score = 0; @@ -783,45 +513,6 @@ private static bool MatchVolumeSourceNative( return matches != 0; } - internal static bool VolumeContainsSourceToken(string? first, string? second) => - EvalVolumePair(first, second, &vn_media_session_volume_contains_source_token_v2, nameof(vn_media_session_volume_contains_source_token_v2)); - - internal static bool VolumeMatchesExecutable(string? metadata, string? candidates) => - EvalVolumePair(metadata, candidates, &vn_media_session_volume_matches_executable_v2, nameof(vn_media_session_volume_matches_executable_v2)); - - private static bool EvalVolumePair( - string? first, - string? second, - delegate* managed fn, - string opName) - { - byte[]? r1 = null, r2 = null; - try - { - Span u1 = AllocateUtf8Buf(first, ref r1, stackalloc byte[Utf8StackThreshold]); - Span u2 = AllocateUtf8Buf(second, ref r2, stackalloc byte[Utf8StackThreshold]); - byte outBool = 0; - fixed (byte* p1 = u1, p2 = u2) - { - var req = new VnVolumeUtf8PairReq - { - FirstUtf8 = p1, - SecondUtf8 = p2, - FirstLen = (uint)u1.Length, - SecondLen = (uint)u2.Length, - }; - NativeResult.RequireSuccess(fn(&req, &outBool), opName); - } - - return outBool != 0; - } - finally - { - ReturnRented(r1); - ReturnRented(r2); - } - } - private static void ReturnRented(byte[]? rented) { if (rented is not null) diff --git a/Interop/M11Native.cs b/Interop/M11Native.cs index df8d50ae..42747a00 100644 --- a/Interop/M11Native.cs +++ b/Interop/M11Native.cs @@ -67,15 +67,6 @@ internal struct VnTranslationOptionsV2 internal fixed byte Reserved[3]; } - [StructLayout(LayoutKind.Sequential)] - internal struct VnUtf8PairReq - { - internal nint FirstUtf8; - internal nint SecondUtf8; - internal uint FirstLen; - internal uint SecondLen; - } - [StructLayout(LayoutKind.Sequential)] internal struct VnUtf8QuadReq { @@ -291,12 +282,6 @@ internal static partial int vn_transhardware_recommended_id_v2( VnHardwareRecommendReq* req, VnOwnedBytes* outUtf8); - [LibraryImport(NativeAbi.RustLibraryName)] - internal static partial int vn_transoptions_can_reuse_cached_v2( - VnTranslationOptionsV2* current, - VnTranslationOptionsV2* previous, - byte* outCanReuse); - [LibraryImport(NativeAbi.RustLibraryName)] internal static partial int vn_custom_translation_models_is_valid_id_v2( byte* idUtf8, @@ -386,12 +371,6 @@ internal static partial int vn_translation_lang_analyze_v2( uint textLen, VnOwnedBytes* outJsonUtf8); - [LibraryImport(NativeAbi.RustLibraryName)] - internal static partial int vn_translation_lang_detect_unambiguous_script_v2( - byte* textUtf8, - uint textLen, - VnOwnedBytes* outUtf8); - internal delegate T Utf8Func(ReadOnlySpan utf8); internal delegate T Utf8PairFunc(ReadOnlySpan firstUtf8, ReadOnlySpan secondUtf8); diff --git a/Interop/M12Native.cs b/Interop/M12Native.cs index 0a4039f3..5216bbcc 100644 --- a/Interop/M12Native.cs +++ b/Interop/M12Native.cs @@ -433,13 +433,6 @@ internal struct VnLiquidGlassScalarsV2 internal byte Reserved; } - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_glass_score_d3d9_adapter_utf8( - byte* description, - int len, - uint vendorId, - long* outScore); - [LibraryImport(NativeAbi.RustLibraryName)] private static partial int vn_glass_should_submit_frame_v2( VnGlassSubmitFrameReq* req, @@ -580,9 +573,6 @@ private static partial int vn_glass_compute_sampling_margin_v2( VnGlassSamplingMarginReq* req, int* outMargin); - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_glass_prepare_gpu_frame_v2(VnGpuFrame* inoutFrame); - [LibraryImport(NativeAbi.RustLibraryName)] private static partial int vn_magcap_is_complete_frame_v2( VnMagcapCompleteFrameReq* req, @@ -602,38 +592,6 @@ private static partial int vn_liquid_glass_config_equals_v2( VnLiquidGlassScalarsV2* b, byte* outEqual); - internal static bool TryScoreD3D9Adapter(string? description, uint vendorId, out long score) - { - long localScore = 0; - if (string.IsNullOrEmpty(description)) - { - bool ok = vn_glass_score_d3d9_adapter_utf8(null, 0, vendorId, &localScore) == (int)NativeStatus.Ok; - score = localScore; - return ok; - } - - int maxBytes = Encoding.UTF8.GetMaxByteCount(description.Length); - byte[]? rented = maxBytes > Utf8StackThreshold ? ArrayPool.Shared.Rent(maxBytes) : null; - Span buf = rented ?? stackalloc byte[Utf8StackThreshold]; - try - { - int written = Encoding.UTF8.GetBytes(description, buf); - fixed (byte* p = buf) - { - bool ok = vn_glass_score_d3d9_adapter_utf8(p, written, vendorId, &localScore) == (int)NativeStatus.Ok; - score = localScore; - return ok; - } - } - finally - { - if (rented is not null) - { - ArrayPool.Shared.Return(rented); - } - } - } - internal static bool ShouldSubmitFrame( long nowTicks, long lastSubmitTicks, @@ -878,16 +836,6 @@ internal static int ComputeSamplingMargin( return margin; } - internal static void PrepareGpuFrame(ref VnGpuFrame frame) - { - fixed (VnGpuFrame* pFrame = &frame) - { - NativeResult.RequireSuccess( - vn_glass_prepare_gpu_frame_v2(pFrame), - nameof(vn_glass_prepare_gpu_frame_v2)); - } - } - internal static bool TryAnalyzeBackdropSamples( int* rgbSamples, int sampleLen, diff --git a/Interop/M13Native.cs b/Interop/M13Native.cs index 1c1b85c7..01b5552c 100644 --- a/Interop/M13Native.cs +++ b/Interop/M13Native.cs @@ -97,58 +97,9 @@ internal struct VnWebcamGpuCreateRequest internal int Height; } - [StructLayout(LayoutKind.Sequential)] - internal struct VnWebcamPlaneCopyRequest - { - internal byte* Src; - internal VnWebcamPlaneDesc Desc; - internal uint SrcCap; - internal uint Format; - internal int AlphaMode; - internal byte* Dst; - internal int DstPitch; - internal uint Reserved; - } - [LibraryImport(NativeAbi.RustLibraryName)] private static partial int vn_webcam_enumerate_devices(VnOwnedBytes* outJson); - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_webcam_validate_and_copy_plane(VnWebcamPlaneCopyRequest* req); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_webcam_convert_rgb_in_place( - byte* pixels, - int length, - byte isRgba, - int alphaMode); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_webcam_convert_gray8_to_bgra8( - byte* src, - int pixelCount, - byte* dst); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_webcam_convert_nv12_to_bgra8( - byte* src, - int width, - int height, - byte* dst); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_webcam_convert_yuy2_to_bgra8( - byte* src, - int pixelCount, - byte* dst); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_webcam_convert_rgb24_to_bgra8( - byte* src, - int pixelCount, - byte isBgr, - byte* dst); - internal static IReadOnlyList EnumerateColorDevices() { VnOwnedBytes owned = default; @@ -170,58 +121,4 @@ internal static IReadOnlyList EnumerateColorDevices() owned.Free(); } } - - internal static int ValidateAndCopyPlane(in VnWebcamPlaneCopyRequest req) - { - VnWebcamPlaneCopyRequest local = req; - return vn_webcam_validate_and_copy_plane(&local); - } - - internal static int ConvertRgbInPlace(Span pixels, bool isRgba, int alphaMode) - { - fixed (byte* pPixels = pixels) - { - return vn_webcam_convert_rgb_in_place( - pPixels, - pixels.Length, - isRgba ? (byte)1 : (byte)0, - alphaMode); - } - } - - internal static int ConvertGray8ToBgra8(ReadOnlySpan src, int pixelCount, Span dst) - { - fixed (byte* pSrc = src) - fixed (byte* pDst = dst) - { - return vn_webcam_convert_gray8_to_bgra8(pSrc, pixelCount, pDst); - } - } - - internal static int ConvertNv12ToBgra8(ReadOnlySpan src, int width, int height, Span dst) - { - fixed (byte* pSrc = src) - fixed (byte* pDst = dst) - { - return vn_webcam_convert_nv12_to_bgra8(pSrc, width, height, pDst); - } - } - - internal static int ConvertYuy2ToBgra8(ReadOnlySpan src, int pixelCount, Span dst) - { - fixed (byte* pSrc = src) - fixed (byte* pDst = dst) - { - return vn_webcam_convert_yuy2_to_bgra8(pSrc, pixelCount, pDst); - } - } - - internal static int ConvertRgb24ToBgra8(ReadOnlySpan src, int pixelCount, bool isBgr, Span dst) - { - fixed (byte* pSrc = src) - fixed (byte* pDst = dst) - { - return vn_webcam_convert_rgb24_to_bgra8(pSrc, pixelCount, isBgr ? (byte)1 : (byte)0, pDst); - } - } } diff --git a/Interop/M14Native.cs b/Interop/M14Native.cs index 13e66e82..d9865e66 100644 --- a/Interop/M14Native.cs +++ b/Interop/M14Native.cs @@ -26,10 +26,6 @@ internal static unsafe partial class M14Native internal const uint DialogKindSetupWizard = 0; - internal const int MessageModeYesNoWarning = 0; - internal const int MessageModeOkInfo = 1; - internal const int MessageModeOkWarning = 2; - private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { PropertyNameCaseInsensitive = true @@ -57,16 +53,6 @@ internal struct VnCliDecision internal byte Reserved; } - [StructLayout(LayoutKind.Sequential)] - internal struct VnSetupProgressPod - { - internal uint CurrentStep; - internal uint TotalSteps; - internal byte IsIndeterminate; - internal byte StageCode; - internal ushort Reserved; - } - [StructLayout(LayoutKind.Sequential)] internal struct VnCliParseRequest { @@ -93,17 +79,6 @@ internal struct VnDialogModelRequest internal uint DialogKind; } - [StructLayout(LayoutKind.Sequential)] - internal struct VnShowMessageRequest - { - internal byte* TextUtf8; - internal byte* TitleUtf8; - internal uint TextLen; - internal uint TitleLen; - internal int Mode; - internal uint Reserved; - } - internal sealed record CliParsedArgsDto( [property: JsonPropertyName("mode")] string Mode, [property: JsonPropertyName("isSetupOrUninstall")] bool IsSetupOrUninstall, @@ -218,11 +193,6 @@ internal static partial int vn_setup_build_dialog_model( VnDialogModelRequest* req, VnOwnedBytes* outModelJson); - [LibraryImport(NativeAbi.RustLibraryName)] - internal static partial int vn_setup_show_message_utf8( - VnShowMessageRequest* req, - int* outResult); - internal static CliParseOutcome ParseCli(string[] args, string? processPath) { string argvJson = JsonSerializer.Serialize(args ?? []); @@ -449,34 +419,6 @@ internal static SetupWizardModelDto BuildSetupWizardModel(long session, bool isU ?? throw new InvalidOperationException("Invalid setup wizard model response."); } - internal static int ShowMessageUtf8(string text, string title, int mode) - { - ArgumentNullException.ThrowIfNull(text); - ArgumentNullException.ThrowIfNull(title); - return WithUtf8Pair(text, title, (textUtf8, titleUtf8) => - { - int result = 0; - byte dummy = 0; - fixed (byte* pText = textUtf8) - fixed (byte* pTitle = titleUtf8) - { - var req = new VnShowMessageRequest - { - TextUtf8 = textUtf8.IsEmpty ? &dummy : pText, - TitleUtf8 = titleUtf8.IsEmpty ? &dummy : pTitle, - TextLen = (uint)textUtf8.Length, - TitleLen = (uint)titleUtf8.Length, - Mode = mode, - }; - NativeResult.RequireSuccess( - vn_setup_show_message_utf8(&req, &result), - nameof(vn_setup_show_message_utf8)); - } - - return result; - }); - } - internal static string CopyOwnedUtf8AndFree(ref VnOwnedBytes owned) { try diff --git a/Interop/PerfMonitorSafeHandle.cs b/Interop/PerfMonitorSafeHandle.cs index 64245b67..8aafcf43 100644 --- a/Interop/PerfMonitorSafeHandle.cs +++ b/Interop/PerfMonitorSafeHandle.cs @@ -101,45 +101,6 @@ internal struct VnPerfLogPushRequest internal uint Pad0; } - [StructLayout(LayoutKind.Sequential)] - internal struct VnPerformancePresetStateV2 - { - internal byte AutoAnimationFps; - internal byte Pad0; - internal byte Pad1; - internal byte Pad2; - internal int AnimationFps; - internal byte EnableBlurEffects; - internal byte EnableSubjectBlur; - internal byte EnableSmartCrop; - internal byte ShowMediaArtBackground; - internal byte EnableShadow; - internal byte IsLiquidGlass; - internal byte UseGpuRefraction; - internal byte UseUltimateGpu; - internal int GlassTargetFps; - internal int GpuPreference; - internal int ProcessPriority; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct VnPresetSelectionRequest - { - internal nint Current; - internal int PreferredSelection; - internal uint Flags; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct VnPresetSelectionOut - { - internal int ActiveItem; - internal byte ShouldBackup; - internal byte Reserved0; - internal byte Reserved1; - internal byte Reserved2; - } - private PerfMonitorSafeHandle() { } @@ -204,22 +165,6 @@ private static partial int vn_gpu_monitor_find_best_adapter_utf8( out VnOwnedBytes outNameUtf8, out ulong outDedicatedVram); - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_perf_preset_apply_v2( - int presetId, - VnPerformancePresetStateV2* current, - VnPerformancePresetStateV2* outNext); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_perf_preset_match_v2( - VnPerformancePresetStateV2* state, - out int outPresetId); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_perf_preset_decide_selection_v2( - VnPresetSelectionRequest* req, - VnPresetSelectionOut* outResult); - [LibraryImport(NativeAbi.RustLibraryName)] private static partial int vn_perf_preset_recommend_hardware_tier(out int outPresetId); @@ -452,42 +397,6 @@ internal static (string Name, ulong DedicatedVramBytes) FindBestGpuAdapter() } } - internal static unsafe int ApplyPresetV2(int presetId, in VnPerformancePresetStateV2 current, out VnPerformancePresetStateV2 next) - { - VnPerformancePresetStateV2 cur = current; - VnPerformancePresetStateV2 dst = default; - int rc = vn_perf_preset_apply_v2(presetId, &cur, &dst); - next = dst; - return rc; - } - - internal static unsafe int MatchPresetV2(in VnPerformancePresetStateV2 state, out int presetId) - { - VnPerformancePresetStateV2 copy = state; - return vn_perf_preset_match_v2(©, out presetId); - } - - internal static unsafe int DecideSelectionV2( - in VnPerformancePresetStateV2 current, - uint flags, - int preferredSelection, - out int activeItem, - out bool shouldBackup) - { - VnPerformancePresetStateV2 cur = current; - var req = new VnPresetSelectionRequest - { - Current = (nint)(&cur), - PreferredSelection = preferredSelection, - Flags = flags - }; - VnPresetSelectionOut output = default; - int rc = vn_perf_preset_decide_selection_v2(&req, &output); - activeItem = output.ActiveItem; - shouldBackup = output.ShouldBackup != 0; - return rc; - } - internal static int RecommendHardwareTier(out int presetId) => vn_perf_preset_recommend_hardware_tier(out presetId); diff --git a/Interop/PlatformShellNative.cs b/Interop/PlatformShellNative.cs index 13552f91..a9d9c515 100644 --- a/Interop/PlatformShellNative.cs +++ b/Interop/PlatformShellNative.cs @@ -843,13 +843,6 @@ internal static partial int vn_shell_get_icon_or_thumbnail_utf8( VnShellIconHeader* outHeader, VnOwnedBytes* outBgra8); - [LibraryImport(NativeAbi.RustLibraryName)] - internal static partial int vn_win32_send_unicode_text_utf8( - byte* textUtf8, - uint textLen, - out int outSent, - out int outExpected); - internal static string? GetMonitorDeviceId(string deviceName) { if (string.IsNullOrEmpty(deviceName)) diff --git a/Interop/RepoAnnouncementsNative.cs b/Interop/RepoAnnouncementsNative.cs index 3b1a206e..ced69280 100644 --- a/Interop/RepoAnnouncementsNative.cs +++ b/Interop/RepoAnnouncementsNative.cs @@ -42,12 +42,6 @@ private static unsafe partial int vn_announcements_mark_seen_utf8( uint reqLen, out uint outCount); - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_announcements_parse_pinned_utf8( - byte* htmlUtf8, - uint htmlLen, - out VnOwnedBytes outJson); - internal static unsafe FetchAnnouncementsResponseDto FetchUnseen( string cachePath, string? url = null, @@ -108,31 +102,4 @@ internal static unsafe uint MarkSeen(string cachePath, IReadOnlyList ids NativeResult.RequireSuccess(status, nameof(vn_announcements_mark_seen_utf8)); return count; } - - internal static unsafe IReadOnlyList ParsePinnedHtml(string html) - { - byte[] htmlBytes = Encoding.UTF8.GetBytes(html ?? string.Empty); - VnOwnedBytes owned = default; - try - { - int status; - fixed (byte* ptr = htmlBytes) - { - status = vn_announcements_parse_pinned_utf8(ptr, checked((uint)htmlBytes.Length), out owned); - } - - NativeResult.RequireSuccess(status, nameof(vn_announcements_parse_pinned_utf8)); - ReadOnlySpan span = owned.AsSpan(); - if (span.IsEmpty) - { - return []; - } - - return JsonSerializer.Deserialize>(span, JsonOptions) ?? []; - } - finally - { - owned.Free(); - } - } } diff --git a/Interop/ShellCoordinatorSafeHandle.cs b/Interop/ShellCoordinatorSafeHandle.cs index 11ef2cd5..805dc285 100644 --- a/Interop/ShellCoordinatorSafeHandle.cs +++ b/Interop/ShellCoordinatorSafeHandle.cs @@ -65,9 +65,6 @@ private static partial int vn_shell_eval_fullscreen( internal static int DestroyRaw(long coord) => vn_shell_coordinator_destroy(coord); - internal static int ConfigureHoverRaw(long coord, PlatformShellNative.VnHoverConfigureRequest req) => - vn_shell_hover_configure(coord, &req); - internal static ShellCoordinatorSafeHandle Create(long session = 0) { NativeResult.RequireSuccess( diff --git a/Interop/SmartCropSessionSafeHandle.cs b/Interop/SmartCropSessionSafeHandle.cs deleted file mode 100644 index 39d8b183..00000000 --- a/Interop/SmartCropSessionSafeHandle.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System.Runtime.InteropServices; - -namespace VNotch.Interop; - -/// -/// SafeHandle owning a native M06 ONNX Runtime SmartCropSession in vnotch_rust.dll. -/// -internal sealed unsafe partial class SmartCropSessionSafeHandle : VNotchSafeHandle -{ - private const int PathStackThreshold = 256; - internal const int MinDetectionCapacity = 3549; - - private SmartCropSessionSafeHandle() - { - } - - internal SmartCropSessionSafeHandle(nint handle) - : base(handle) - { - } - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_smartcrop_session_create_req( - ImagingNative.VnSmartCropSessionCreateReq* req, - out long outHandle, - out byte outDml); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_smartcrop_session_destroy(long handle); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_smartcrop_session_cancel(long handle); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_smartcrop_session_infer_req( - long handle, - ImagingNative.VnSmartCropInferReq* req, - out int outCount, - out byte outDml); - - internal static int DestroyRaw(long handle) => vn_smartcrop_session_destroy(handle); - - internal static (SmartCropSessionSafeHandle Handle, bool UsedDml) Create( - string modelPath, - string directory, - bool preferDml = false) - { - ArgumentException.ThrowIfNullOrEmpty(modelPath); - ArgumentException.ThrowIfNullOrEmpty(directory); - byte[]? rentedModel = null; - byte[]? rentedDir = null; - try - { - ReadOnlySpan modelUtf8 = ImagingNative.EncodeUtf8(modelPath, stackalloc byte[PathStackThreshold], out rentedModel); - ReadOnlySpan dirUtf8 = ImagingNative.EncodeUtf8(directory, stackalloc byte[PathStackThreshold], out rentedDir); - fixed (byte* pModel = modelUtf8) - fixed (byte* pDir = dirUtf8) - { - ImagingNative.VnSmartCropSessionCreateReq req = new() - { - ModelUtf8 = (nint)pModel, - ModelLen = checked((uint)modelUtf8.Length), - DirectoryUtf8 = (nint)pDir, - DirectoryLen = checked((uint)dirUtf8.Length), - PreferDml = preferDml ? (byte)1 : (byte)0, - }; - int rc = vn_smartcrop_session_create_req(&req, out long rawHandle, out byte usedDml); - NativeResult.RequireSuccess(rc, nameof(vn_smartcrop_session_create_req)); - return (new SmartCropSessionSafeHandle(checked((nint)rawHandle)), usedDml != 0); - } - } - finally - { - ImagingNative.ReturnBuffer(rentedModel); - ImagingNative.ReturnBuffer(rentedDir); - } - } - - internal void Cancel() - { - ObjectDisposedException.ThrowIf(IsClosed || IsInvalid, this); - bool addedRef = false; - try - { - DangerousAddRef(ref addedRef); - int rc = vn_smartcrop_session_cancel((long)DangerousGetHandle()); - NativeResult.RequireSuccess(rc, nameof(vn_smartcrop_session_cancel)); - } - finally - { - if (addedRef) - { - DangerousRelease(); - } - } - } - - internal int Infer( - ReadOnlySpan pixels, - int width, - int height, - int stride, - Span detections, - out bool usedDml) - { - ObjectDisposedException.ThrowIf(IsClosed || IsInvalid, this); - bool addedRef = false; - try - { - DangerousAddRef(ref addedRef); - fixed (byte* pPixels = pixels) - fixed (ImagingNative.VnCoreDetection* pDet = detections) - { - ImagingNative.VnSmartCropInferReq req = new() - { - Pixels = pixels.IsEmpty ? 0 : (nint)pPixels, - Length = pixels.Length, - Width = width, - Height = height, - Stride = stride, - Detections = detections.IsEmpty ? 0 : (nint)pDet, - Capacity = detections.Length, - }; - int rc = vn_smartcrop_session_infer_req( - (long)DangerousGetHandle(), - &req, - out int count, - out byte dml); - NativeResult.RequireSuccess(rc, nameof(vn_smartcrop_session_infer_req)); - usedDml = dml != 0; - return count; - } - } - finally - { - if (addedRef) - { - DangerousRelease(); - } - } - } - - protected override bool ReleaseHandle() => - vn_smartcrop_session_destroy((long)handle) == (int)NativeStatus.Ok; -} diff --git a/Interop/UpdaterSafeHandle.cs b/Interop/UpdaterSafeHandle.cs index 24456069..248dd055 100644 --- a/Interop/UpdaterSafeHandle.cs +++ b/Interop/UpdaterSafeHandle.cs @@ -279,33 +279,12 @@ private static partial int vn_updater_get_latest_cached( long updater, out VnOwnedBytes outJson); - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_updater_reset_changelog(long updater); - [LibraryImport(NativeAbi.RustLibraryName)] private static unsafe partial int vn_updater_normalize_thumbprint_utf8( byte* thumbprintUtf8, uint len, out VnOwnedBytes outUtf8); - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_updater_parse_atom_releases_utf8( - byte* xmlUtf8, - uint xmlLen, - out VnOwnedBytes outReleasesJson); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_updater_parse_github_releases_utf8( - byte* jsonUtf8, - uint jsonLen, - out VnOwnedBytes outReleasesJson); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_updater_html_to_markdown_utf8( - byte* htmlUtf8, - uint htmlLen, - out VnOwnedBytes outMdUtf8); - [LibraryImport(NativeAbi.RustLibraryName)] private static unsafe partial int vn_updater_try_parse_version_utf8( byte* verUtf8, @@ -580,26 +559,6 @@ internal string PollEventsJson(uint maxEvents = 64) } } - internal void ResetChangelog() - { - ObjectDisposedException.ThrowIf(IsClosed || IsInvalid, this); - bool addedRef = false; - try - { - DangerousAddRef(ref addedRef); - NativeResult.RequireSuccess( - vn_updater_reset_changelog((long)DangerousGetHandle()), - nameof(vn_updater_reset_changelog)); - } - finally - { - if (addedRef) - { - DangerousRelease(); - } - } - } - internal unsafe ulong StartDownloadAndVerifyAsync( UpdateInfo updateInfo, string destinationPath, @@ -673,83 +632,6 @@ internal static unsafe string NormalizeThumbprint(string? value) } } - internal static unsafe List ParseAtomReleases(ReadOnlySpan xmlUtf8) - { - VnOwnedBytes owned = default; - try - { - fixed (byte* pXml = xmlUtf8) - { - int rc = vn_updater_parse_atom_releases_utf8( - xmlUtf8.IsEmpty ? null : pXml, - (uint)xmlUtf8.Length, - out owned); - if (rc != (int)NativeStatus.Ok) - { - throw new InvalidDataException("Invalid release feed."); - } - - List dtos = JsonSerializer.Deserialize>(owned.AsSpan(), JsonOptions) ?? []; - return MapReleaseDtos(dtos); - } - } - finally - { - owned.Free(); - } - } - - internal static unsafe List ParseGitHubReleases(ReadOnlySpan jsonUtf8) - { - VnOwnedBytes owned = default; - try - { - fixed (byte* pJson = jsonUtf8) - { - int rc = vn_updater_parse_github_releases_utf8( - jsonUtf8.IsEmpty ? null : pJson, - (uint)jsonUtf8.Length, - out owned); - if (rc != (int)NativeStatus.Ok) - { - throw new InvalidDataException("Invalid release list JSON."); - } - - List dtos = JsonSerializer.Deserialize>(owned.AsSpan(), JsonOptions) ?? []; - return MapReleaseDtos(dtos); - } - } - finally - { - owned.Free(); - } - } - - internal static unsafe string HtmlToMarkdown(string? html) - { - if (string.IsNullOrEmpty(html)) - { - return string.Empty; - } - - byte[] utf8 = Encoding.UTF8.GetBytes(html); - VnOwnedBytes owned = default; - try - { - fixed (byte* pHtml = utf8) - { - int rc = vn_updater_html_to_markdown_utf8(pHtml, (uint)utf8.Length, out owned); - return rc == (int)NativeStatus.Ok && owned.Len > 0 - ? Encoding.UTF8.GetString(owned.AsSpan()) - : string.Empty; - } - } - finally - { - owned.Free(); - } - } - internal static unsafe bool TryParseVersion(string? value, out Version version, out string[] prerelease) { version = new Version(0, 0, 0, 0); diff --git a/Interop/VnOwnedBytes.cs b/Interop/VnOwnedBytes.cs index 2289c7d0..88fcac07 100644 --- a/Interop/VnOwnedBytes.cs +++ b/Interop/VnOwnedBytes.cs @@ -15,8 +15,6 @@ internal partial struct VnOwnedBytes [LibraryImport(NativeAbi.RustLibraryName, EntryPoint = "vn_free_bytes")] private static partial int FreeBytesNative(nint ptr, uint len); - internal static int FreeRaw(nint ptr, uint len) => FreeBytesNative(ptr, len); - internal readonly unsafe ReadOnlySpan AsSpan() { if (Ptr == 0 || Len == 0) diff --git a/Models/MediaPlatform.cs b/Models/MediaPlatform.cs index 1ffa490b..54b2cf4d 100644 --- a/Models/MediaPlatform.cs +++ b/Models/MediaPlatform.cs @@ -22,26 +22,6 @@ public enum MediaPlatform public static class MediaPlatformExtensions { - public static string ToDisplayString(this MediaPlatform platform) => platform switch - { - MediaPlatform.Spotify => "Spotify", - MediaPlatform.YouTube => "YouTube", - MediaPlatform.SoundCloud => "SoundCloud", - MediaPlatform.AppleMusic => "Apple Music", - MediaPlatform.Browser => "Browser", - MediaPlatform.Instagram => "Instagram", - MediaPlatform.Twitter => "Twitter", - MediaPlatform.Twitch => "Twitch", - MediaPlatform.Discord => "Discord", - MediaPlatform.Netflix => "Netflix", - MediaPlatform.Tidal => "TIDAL", - MediaPlatform.Deezer => "Deezer", - MediaPlatform.Bandcamp => "Bandcamp", - MediaPlatform.Bilibili => "Bilibili", - MediaPlatform.Vimeo => "Vimeo", - _ => string.Empty, - }; - public static MediaPlatform ParsePlatform(string? value) { if (string.IsNullOrEmpty(value)) diff --git a/Services/Clipboard/NativeBufferStream.cs b/Services/Clipboard/NativeBufferStream.cs deleted file mode 100644 index 3cef3cd4..00000000 --- a/Services/Clipboard/NativeBufferStream.cs +++ /dev/null @@ -1,251 +0,0 @@ -using System.IO; -using System.Runtime.InteropServices; -using System.Security.Cryptography; - -namespace VNotch.Services.Clipboard; - -// Seekable, zero-filled plaintext scratch storage outside the managed heap. -// SafeBuffer owns and wipes the allocation even if a serializer throws. -internal sealed unsafe class NativeBufferStream : Stream -{ - private sealed class Buffer : SafeBuffer - { - internal int Capacity { get; } - - internal Buffer(int capacity) : base(true) - { - Capacity = capacity; - SetHandle((nint)NativeMemory.AllocZeroed((nuint)capacity)); - if (IsInvalid) - { - throw new OutOfMemoryException(); - } - - Initialize((ulong)capacity); - } - - protected override bool ReleaseHandle() - { - CryptographicOperations.ZeroMemory(new Span((void*)handle, Capacity)); - NativeMemory.Free((void*)handle); - return true; - } - } - - private Buffer? _buffer; - private long _length; - private long _position; - private bool _disposed; - - public override bool CanRead => !_disposed; - public override bool CanSeek => !_disposed; - public override bool CanWrite => !_disposed; - - public override long Length - { - get - { - ThrowIfDisposed(); - return _length; - } - } - - public override long Position - { - get - { - ThrowIfDisposed(); - return _position; - } - set - { - ThrowIfDisposed(); - ArgumentOutOfRangeException.ThrowIfNegative(value); - _position = value; - } - } - - private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); - - private void EnsureCapacity(long length) - { - ThrowIfDisposed(); - if (length > int.MaxValue) - { - throw new IOException("Clipboard scratch buffer exceeds its size limit."); - } - - if (length <= (_buffer?.Capacity ?? 0)) - { - return; - } - - int capacity = (int)Math.Max(length, Math.Min(int.MaxValue, Math.Max(65536L, (_buffer?.Capacity ?? 0) * 2L))); - var next = new Buffer(capacity); - if (_buffer != null) - { - byte* source = null; - byte* destination = null; - try - { - _buffer.AcquirePointer(ref source); - next.AcquirePointer(ref destination); - new ReadOnlySpan(source, (int)_length).CopyTo(new Span(destination, capacity)); - } - catch - { - next.Dispose(); - throw; - } - finally - { - if (source != null) - { - _buffer.ReleasePointer(); - } - - if (destination != null) - { - next.ReleasePointer(); - } - } - - _buffer.Dispose(); - } - - _buffer = next; - } - - public override void Flush() => ThrowIfDisposed(); - - internal delegate T BufferReader(ReadOnlySpan bytes); - - internal T ReadBuffered(BufferReader read) - { - ThrowIfDisposed(); - if (_length == 0) - { - return read(default); - } - - byte* data = null; - try - { - _buffer!.AcquirePointer(ref data); - return read(new ReadOnlySpan(data, (int)_length)); - } - finally - { - if (data != null) - { - _buffer!.ReleasePointer(); - } - } - } - - public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); - - public override int Read(Span buffer) - { - ThrowIfDisposed(); - int count = (int)Math.Min(buffer.Length, Math.Max(0, _length - _position)); - if (count == 0) - { - return 0; - } - - byte* source = null; - try - { - _buffer!.AcquirePointer(ref source); - new ReadOnlySpan(source + _position, count).CopyTo(buffer); - _position += count; - return count; - } - finally - { - if (source != null) - { - _buffer!.ReleasePointer(); - } - } - } - - public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); - - public override void Write(ReadOnlySpan buffer) - { - ThrowIfDisposed(); - if (buffer.IsEmpty) - { - return; - } - - long end = checked(_position + buffer.Length); - EnsureCapacity(end); - byte* destination = null; - try - { - _buffer!.AcquirePointer(ref destination); - buffer.CopyTo(new Span(destination + _position, buffer.Length)); - _position = end; - _length = Math.Max(_length, end); - } - finally - { - if (destination != null) - { - _buffer!.ReleasePointer(); - } - } - } - - public override long Seek(long offset, SeekOrigin origin) - { - Position = origin switch - { - SeekOrigin.Begin => offset, - SeekOrigin.Current => checked(_position + offset), - SeekOrigin.End => checked(_length + offset), - _ => throw new ArgumentOutOfRangeException(nameof(origin)) - }; - return _position; - } - - public override void SetLength(long value) - { - ArgumentOutOfRangeException.ThrowIfNegative(value); - EnsureCapacity(value); - if (value < _length) - { - byte* data = null; - try - { - _buffer!.AcquirePointer(ref data); - CryptographicOperations.ZeroMemory(new Span(data + value, (int)(_length - value))); - } - finally - { - if (data != null) - { - _buffer!.ReleasePointer(); - } - } - } - - _length = value; - _position = Math.Min(_position, value); - } - - protected override void Dispose(bool disposing) - { - if (disposing && !_disposed) - { - _disposed = true; - _buffer?.Dispose(); - _buffer = null; - } - - base.Dispose(disposing); - } -} diff --git a/Services/DiagnosticLogCapturePolicy.cs b/Services/DiagnosticLogCapturePolicy.cs deleted file mode 100644 index 0f4f88e8..00000000 --- a/Services/DiagnosticLogCapturePolicy.cs +++ /dev/null @@ -1,12 +0,0 @@ -using VNotch.Interop; - -namespace VNotch.Services; - -internal sealed class DiagnosticLogCapturePolicy -{ - internal const int MaxEntriesPerSecond = 32; - private long _windowAndCount = -1; - - internal bool TryCapture(long tickCountMs) => - RuntimeLogSafeHandle.TryCaptureDiagnosticLog(ref _windowAndCount, tickCountMs); -} diff --git a/Services/ISettingsApplicationService.cs b/Services/ISettingsApplicationService.cs index 910a4bfe..4fc805da 100644 --- a/Services/ISettingsApplicationService.cs +++ b/Services/ISettingsApplicationService.cs @@ -16,6 +16,4 @@ public interface ISettingsApplicationService void Export(string filePath, NotchSettings settings); bool IsAutoStartEnabled(); - - event EventHandler? SettingsApplied; } diff --git a/Services/LyricsProviderOrder.cs b/Services/LyricsProviderOrder.cs index 3a83ef4f..638bd84b 100644 --- a/Services/LyricsProviderOrder.cs +++ b/Services/LyricsProviderOrder.cs @@ -12,7 +12,6 @@ internal static class LyricsProviderOrder internal const string Lrclib = "LRCLIB"; internal const string LrcMux = "lrc mux"; internal const string Default = "AMLL TTML DB,NetEase,Kugou,QQ Music,LRCLIB,lrc mux"; - internal const string Legacy = "LRCLIB,lrc mux"; private static readonly string[] CanonicalNames = [ diff --git a/Services/NotchManager.cs b/Services/NotchManager.cs index 337b5eb7..140d1864 100644 --- a/Services/NotchManager.cs +++ b/Services/NotchManager.cs @@ -24,10 +24,6 @@ public sealed unsafe class NotchManager : IDisposable public Rect SafeArea => _safeArea; - public event EventHandler? SafeAreaChanged; - - public event EventHandler? PositionUpdated; - public NotchManager(Window window, NotchSettings settings) { _settings = settings; @@ -58,7 +54,6 @@ public void UpdatePosition() AnimationConfig.Refresh(_currentScreen.DeviceName); ComputeGeometry(_currentScreen, out _geometry); RefreshAnchor(); - PositionUpdated?.Invoke(this, EventArgs.Empty); } internal void RefreshAnchor() @@ -113,7 +108,6 @@ private void ComputeGeometry(Screen screen, out PlatformShellNative.VnNotchGeome private void ApplySafeArea(in PlatformShellNative.VnNotchGeometryV2 geom) { _safeArea = new Rect(geom.SafeLeft, geom.SafeTop, geom.SafeWidth, geom.SafeHeight); - SafeAreaChanged?.Invoke(this, _safeArea); } private Screen GetTargetScreen() => MonitorSelection.Resolve(_settings); diff --git a/Services/RuntimeLog.cs b/Services/RuntimeLog.cs index 658c1e20..3069bc22 100644 --- a/Services/RuntimeLog.cs +++ b/Services/RuntimeLog.cs @@ -353,61 +353,4 @@ private static void WriteEntry(LogLevel level, string category, string message) } } } - - internal sealed class AsyncLogWriter : IDisposable - { - private const uint FlushTimeoutMs = 5000; - private readonly RuntimeLogSafeHandle _handle; - private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously); - private int _stopRequested; - - public AsyncLogWriter(string path) - { - _handle = RuntimeLogSafeHandle.Create(path, LogLevel.Trace, forceRotate: false); - } - - public Task Completion => _completion.Task; - - public bool TryEnqueue(string line, LogLevel level = LogLevel.Info) - { - if (Volatile.Read(ref _stopRequested) != 0) - { - return false; - } - - return _handle.Write(level, "ASYNC", line, returnScrubbed: false, out _); - } - - public Task EnqueueFlush() - { - if (Volatile.Read(ref _stopRequested) != 0) - { - return Task.CompletedTask; - } - - return Task.Run(() => _handle.Flush(FlushTimeoutMs)); - } - - public void RequestStop() - { - if (Interlocked.Exchange(ref _stopRequested, 1) != 0) - { - return; - } - - _ = Task.Run(() => - { - try - { - _handle.ShutdownAndDispose(DefaultShutdownTimeoutMs); - } - finally - { - _completion.TrySetResult(); - } - }); - } - - public void Dispose() => RequestStop(); - } } diff --git a/Services/SensitiveDataScrubber.cs b/Services/SensitiveDataScrubber.cs deleted file mode 100644 index c429057b..00000000 --- a/Services/SensitiveDataScrubber.cs +++ /dev/null @@ -1,8 +0,0 @@ -using VNotch.Interop; - -namespace VNotch.Services; - -public static class SensitiveDataScrubber -{ - public static string Scrub(string? input) => SecurityNative.ScrubSensitiveText(input); -} diff --git a/Services/SettingsApplicationService.cs b/Services/SettingsApplicationService.cs index 862986df..9b977c80 100644 --- a/Services/SettingsApplicationService.cs +++ b/Services/SettingsApplicationService.cs @@ -19,8 +19,6 @@ private static bool IsValidFilePath(string? filePath) => ? System.IO.Path.Combine(appFolder, "Presets") : null; - public event EventHandler? SettingsApplied; - public SettingsApplicationService(ISettingsService settingsService, IStartupManager? startupManager = null) { _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); @@ -48,7 +46,6 @@ public async Task ApplyAsync(NotchSettings settings, CancellationToken ct = defa catch (Exception rollbackError) { throw new AggregateException(saveError, rollbackError); } throw; } - SettingsApplied?.Invoke(this, snapshot); } finally { _applyGate.Release(); } } diff --git a/Services/SettingsService.cs b/Services/SettingsService.cs index 221d353f..19d6d6e3 100644 --- a/Services/SettingsService.cs +++ b/Services/SettingsService.cs @@ -30,7 +30,6 @@ private sealed record ImportPayloadDto( [property: JsonPropertyName("rawJson")] string RawJson, [property: JsonPropertyName("current")] NotchSettings? Current); private sealed record ImportResponseDto(NotchSettings Settings, bool RequiresRestart); - private sealed record NormalizeResponseDto(NotchSettings Settings, bool Changed); private readonly string _settingsPath; private readonly string _appFolder; @@ -338,56 +337,6 @@ public static bool CheckRequiresRestart(NotchSettings imported, NotchSettings? c internal static bool IsGeneratedSettingsBackup(string path) => SettingsStoreSafeHandle.IsGeneratedBackupName(path); - private static bool NormalizeSettings(NotchSettings settings) - { - NotchSettings before = settings.Clone(); - SettingsStoreSafeHandle.SanitizeNonFiniteOptionals(settings); - byte[] payloadUtf8 = JsonSerializer.SerializeToUtf8Bytes(settings, SettingsStoreSafeHandle.FfiJsonOptions); - int rc = SettingsStoreSafeHandle.TryExecuteStatelessCommand( - SettingsStoreSafeHandle.OpNormalize, - payloadUtf8, - out string respJson); - NativeResult.RequireSuccess(rc, nameof(SettingsStoreSafeHandle.OpNormalize)); - NormalizeResponseDto resp = JsonSerializer.Deserialize( - respJson, - SettingsStoreSafeHandle.FfiJsonOptions) - ?? throw new InvalidOperationException("Normalize returned null response."); - ApplyNormalizedFields(settings, resp.Settings); - return resp.Changed || !before.ValueEquals(settings); - } - - private static void ApplyNormalizedFields(NotchSettings target, NotchSettings source) - { - target.Width = source.Width; - target.Height = source.Height; - target.CornerRadius = source.CornerRadius; - target.DynamicIslandWidth = source.DynamicIslandWidth; - target.DynamicIslandHeight = source.DynamicIslandHeight; - target.NotificationDuration = source.NotificationDuration; - target.AnimationFps = source.AnimationFps; - target.SpotifyCanvasBrightness = source.SpotifyCanvasBrightness; - target.Opacity = source.Opacity; - target.AnimationSpeed = source.AnimationSpeed; - target.HoverExpandDelay = source.HoverExpandDelay; - target.HoverCollapseDelay = source.HoverCollapseDelay; - target.HoverZoneMargin = source.HoverZoneMargin; - target.IdleAutoHideDelay = source.IdleAutoHideDelay; - target.MediaBlurBrightnessBoost = source.MediaBlurBrightnessBoost; - target.MediaBlurDarkOverlay = source.MediaBlurDarkOverlay; - target.CompactExpandMultiplier = source.CompactExpandMultiplier; - target.MediumExpandMultiplier = source.MediumExpandMultiplier; - target.LargeExpandMultiplier = source.LargeExpandMultiplier; - target.SpotlightAiWordsPerSecond = source.SpotlightAiWordsPerSecond; - target.GpuPreference = source.GpuPreference; - target.ProcessPriority = source.ProcessPriority; - target.Language = source.Language; - target.ManualCity = source.ManualCity; - target.DebugWindowX = source.DebugWindowX; - target.DebugWindowY = source.DebugWindowY; - target.LiquidGlass = source.LiquidGlass; - target.LiquidGlassCustom = source.LiquidGlassCustom; - } - private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); diff --git a/Services/SetupDialogs.cs b/Services/SetupDialogs.cs deleted file mode 100644 index 4b2e4a2d..00000000 --- a/Services/SetupDialogs.cs +++ /dev/null @@ -1,20 +0,0 @@ -using VNotch.Interop; - -namespace VNotch.Services; - -/// -/// Thin native UI dialog facade backed by Rust ABI 2.2 vn_setup_show_message_utf8. -/// -internal static class SetupDialogs -{ - private const int DialogResultYes = 6; - - internal static bool ConfirmUninstall(string text, string title) => - M14Native.ShowMessageUtf8(text, title, M14Native.MessageModeYesNoWarning) == DialogResultYes; - - internal static void ShowUninstallResult(string text, string title, bool hasErrors) => - _ = M14Native.ShowMessageUtf8( - text, - title, - hasErrors ? M14Native.MessageModeOkWarning : M14Native.MessageModeOkInfo); -} diff --git a/Services/Spotlight/SpotlightSearchService.cs b/Services/Spotlight/SpotlightSearchService.cs index 1cb5f6ef..503ce78f 100644 --- a/Services/Spotlight/SpotlightSearchService.cs +++ b/Services/Spotlight/SpotlightSearchService.cs @@ -158,8 +158,6 @@ public void UpdateLocale() engine?.UpdatePrefs(BuildLocaleJson()); } - internal Task WarmupAsync() => EnsureWarmedUpAsync(CancellationToken.None); - public void Dispose() { SpotlightEngineHandle? engine; diff --git a/Services/ThumbnailHeuristics.cs b/Services/ThumbnailHeuristics.cs deleted file mode 100644 index 600f3020..00000000 --- a/Services/ThumbnailHeuristics.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System; -using System.Buffers; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using VNotch.Interop; - -namespace VNotch.Services; - -internal static class ThumbnailHeuristics -{ - private const int SampleSize = 24; - private const int SmallSquareThreshold = 320; - private const int MinArtworkCandidateDimension = 120; - - public static bool IsLikelyPlaceholderThumbnail(BitmapSource? thumbnail) - { - if (thumbnail == null || thumbnail.PixelWidth <= 0 || thumbnail.PixelHeight <= 0) - { - return true; - } - - double aspect = (double)thumbnail.PixelWidth / thumbnail.PixelHeight; - bool isSquare = Math.Abs(aspect - 1.0) < 0.06; - if (!isSquare) - { - return false; - } - - if (thumbnail.PixelWidth <= SmallSquareThreshold || thumbnail.PixelHeight <= SmallSquareThreshold) - { - return !IsLikelyArtworkCandidate(thumbnail); - } - - return HasLowEntropyMonochromeProfile(thumbnail); - } - - public static bool IsLikelyArtworkCandidate(BitmapSource? thumbnail) - { - if (thumbnail == null || thumbnail.PixelWidth <= 0 || thumbnail.PixelHeight <= 0) - { - return false; - } - - double aspect = (double)thumbnail.PixelWidth / thumbnail.PixelHeight; - bool isSquare = Math.Abs(aspect - 1.0) < 0.08; - if (!isSquare) - { - return false; - } - - return thumbnail.PixelWidth >= MinArtworkCandidateDimension && - thumbnail.PixelHeight >= MinArtworkCandidateDimension && - !HasPlaceholderProfile( - thumbnail, - rejectSimpleColorIcons: thumbnail.PixelWidth <= SmallSquareThreshold || thumbnail.PixelHeight <= SmallSquareThreshold); - } - - public static bool HasLowEntropyMonochromeProfile(BitmapSource thumbnail) => - HasPlaceholderProfile(thumbnail, rejectSimpleColorIcons: false); - - private static bool HasPlaceholderProfile(BitmapSource thumbnail, bool rejectSimpleColorIcons) - { - try - { - double scale = Math.Min( - 1.0, - (double)SampleSize / Math.Max(thumbnail.PixelWidth, thumbnail.PixelHeight)); - - BitmapSource source = thumbnail; - if (scale < 1.0) - { - var transformed = new TransformedBitmap(thumbnail, new ScaleTransform(scale, scale)); - transformed.Freeze(); - source = transformed; - } - - var formatted = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0); - formatted.Freeze(); - - int width = Math.Max(1, formatted.PixelWidth); - int height = Math.Max(1, formatted.PixelHeight); - int stride = width * 4; - int bufLen = stride * height; - byte[] pixels = ArrayPool.Shared.Rent(bufLen); - try - { - formatted.CopyPixels(pixels, stride, 0); - return ImagingNative.HasPlaceholderProfile(pixels.AsSpan(0, bufLen), width * height, rejectSimpleColorIcons); - } - finally - { - ArrayPool.Shared.Return(pixels); - } - } - catch (Exception) - { - return false; - } - } - - public enum SmtcThumbnailDecision - { - Reject, - Accept, - Skip, - } - - public readonly struct SmtcThumbnailInputs - { - public bool IsYouTubeLikeSource { get; init; } - public bool IsSoundCloudSource { get; init; } - public bool IsBrowserOrYouTubePlatform { get; init; } - public bool IsBrowserSession { get; init; } - public bool TrackChanged { get; init; } - public bool BrowserSessionChanged { get; init; } - public bool HasVerifiedYouTubeThumb { get; init; } - public bool HasVerifiedSoundCloudThumb { get; init; } - public bool LikelySoundCloudArtwork { get; init; } - public bool RecentTrackChange { get; init; } - public bool CachedThumbnailIsNull { get; init; } - public int PixelWidth { get; init; } - public int PixelHeight { get; init; } - } - - public static SmtcThumbnailDecision DecideSmtcThumbnail(in SmtcThumbnailInputs x) - { - ImagingNative.VnSmtcThumbnailInputs nInputs = new() - { - IsYouTubeLikeSource = x.IsYouTubeLikeSource ? (byte)1 : (byte)0, - IsSoundCloudSource = x.IsSoundCloudSource ? (byte)1 : (byte)0, - IsBrowserOrYouTubePlatform = x.IsBrowserOrYouTubePlatform ? (byte)1 : (byte)0, - IsBrowserSession = x.IsBrowserSession ? (byte)1 : (byte)0, - TrackChanged = x.TrackChanged ? (byte)1 : (byte)0, - BrowserSessionChanged = x.BrowserSessionChanged ? (byte)1 : (byte)0, - HasVerifiedYouTubeThumb = x.HasVerifiedYouTubeThumb ? (byte)1 : (byte)0, - HasVerifiedSoundCloudThumb = x.HasVerifiedSoundCloudThumb ? (byte)1 : (byte)0, - LikelySoundCloudArtwork = x.LikelySoundCloudArtwork ? (byte)1 : (byte)0, - RecentTrackChange = x.RecentTrackChange ? (byte)1 : (byte)0, - CachedThumbnailIsNull = x.CachedThumbnailIsNull ? (byte)1 : (byte)0, - PixelWidth = x.PixelWidth, - PixelHeight = x.PixelHeight, - }; - return (SmtcThumbnailDecision)ImagingNative.DecideSmtcThumbnail(in nInputs); - } -} diff --git a/Services/Translation/TranslationLanguages.cs b/Services/Translation/TranslationLanguages.cs index 3c38fc76..f2e9bf38 100644 --- a/Services/Translation/TranslationLanguages.cs +++ b/Services/Translation/TranslationLanguages.cs @@ -143,31 +143,6 @@ internal static Task AnalyzeAsync(string text, Canc return detected.Length > 0 ? detected : null; } - internal static string? DetectUnambiguousScript(string text) - { - if (string.IsNullOrEmpty(text)) - { - return null; - } - - string detected = M11Native.WithUtf8(text, static utf8 => - { - VnOwnedBytes owned = default; - fixed (byte* p = utf8) - { - if (M11Native.vn_translation_lang_detect_unambiguous_script_v2(p, (uint)utf8.Length, &owned) != 0) - { - owned.Free(); - return string.Empty; - } - } - - return M11Native.CopyOwnedUtf8AndFree(ref owned); - }); - - return detected.Length > 0 ? detected : null; - } - private static string FormatName(string code) { try diff --git a/Services/Translation/TranslationModelStore.cs b/Services/Translation/TranslationModelStore.cs index 4f1112f6..8fec360e 100644 --- a/Services/Translation/TranslationModelStore.cs +++ b/Services/Translation/TranslationModelStore.cs @@ -34,8 +34,6 @@ internal static TranslationModelStore For(TranslationModelProfile profile, strin internal SemaphoreSlim Gate { get; } = new(1, 1); internal string Root { get; } internal event Action? Changed; - // Called under Gate before removing files; engine releases its file handles synchronously. - internal event Action? Replacing; private string AssetPath(Asset asset) => Path.IsPathFullyQualified(asset.Name) ? asset.Name @@ -106,7 +104,6 @@ internal async Task DownloadAsync(IProgress? progress, CancellationToken Directory.CreateDirectory(Root); using var _ = AppFileCleanupService.Protect(Root); _verifiedState = null; - Replacing?.Invoke(); File.Delete(Path.Combine(Root, "verified.txt")); if (ReferenceEquals(_client, Client) && RustTranslationEngine.SupportsBuiltinDownload(Profile.Id)) { @@ -321,7 +318,6 @@ private async Task ImportPinnedAssetsAsync(string folder, CancellationToken ct) await File.WriteAllTextAsync(stagedMarker, Profile.Revision, ct).ConfigureAwait(false); ct.ThrowIfCancellationRequested(); - Replacing?.Invoke(); _verifiedState = null; File.Delete(marker); foreach (var file in staged) @@ -371,7 +367,6 @@ internal async Task RemoveAsync(CancellationToken ct = default) try { _verifiedState = null; - Replacing?.Invoke(); if (Directory.Exists(Root)) { File.Delete(Path.Combine(Root, "verified.txt")); diff --git a/Services/Translation/TranslationOptions.cs b/Services/Translation/TranslationOptions.cs index e16abf5a..0dec1adf 100644 --- a/Services/Translation/TranslationOptions.cs +++ b/Services/Translation/TranslationOptions.cs @@ -20,14 +20,6 @@ internal sealed record TranslationOptions internal int TimeoutSeconds { get; init; } = 90; internal bool EnableHumanizer { get; init; } = true; - internal unsafe bool CanReuseCachedResults(TranslationOptions previous) - { - M11Native.VnTranslationOptionsV2 cur = ToNative(); - M11Native.VnTranslationOptionsV2 prev = previous.ToNative(); - byte canReuse = 0; - return M11Native.vn_transoptions_can_reuse_cached_v2(&cur, &prev, &canReuse) == 0 && canReuse != 0; - } - internal static TranslationOptions From(NotchSettings settings) => new() { ModelIdleMinutes = settings.TranslationModelIdleMinutes, diff --git a/Services/Translation/TranslationSelectionService.cs b/Services/Translation/TranslationSelectionService.cs index af28f99d..41eb82d5 100644 --- a/Services/Translation/TranslationSelectionService.cs +++ b/Services/Translation/TranslationSelectionService.cs @@ -60,19 +60,6 @@ internal TranslationSelectionService( internal bool IsManualRequestCurrent(long version) => !_disposed && version == Interlocked.Read(ref _manualRequestVersion); - internal void RequestManualTranslation() - { - if (_disposed) - { - return; - } - - SelectionReaderSafeHandle handle = EnsureReaderCreated(); - ulong version = handle.RequestManual(); - Interlocked.Exchange(ref _manualRequestVersion, checked((long)version)); - EnsureDrainLoopLocked(handle); - } - internal void SetAutomaticWatching(bool enabled) { if (_disposed || _automaticWatching == enabled) diff --git a/Services/Win32Interop.Input.cs b/Services/Win32Interop.Input.cs deleted file mode 100644 index 84500587..00000000 --- a/Services/Win32Interop.Input.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System.Buffers; -using System.Runtime.InteropServices; -using System.Text; -using VNotch.Interop; - -namespace VNotch.Services; - -// Focus, child-window and message helpers used by the selection readers. Native side: Native/Services/Win32Interop.cpp. -internal static unsafe partial class Win32Interop -{ - private const int ChildWindowCapacity = 1024; - private const int UnicodeTextStackThreshold = 512; - - [LibraryImport(NativeDll, EntryPoint = "vn_win32_get_gui_thread_focus")] - private static partial int NativeGetGuiThreadFocus(uint threadId, out long focus); - - [LibraryImport(NativeDll, EntryPoint = "vn_win32_is_child")] - private static partial int NativeIsChild(long parent, long child, out byte isChild); - - [LibraryImport(NativeDll, EntryPoint = "vn_win32_get_ancestor")] - private static partial int NativeGetAncestor(long hwnd, uint flags, out long ancestor); - - [LibraryImport(NativeDll, EntryPoint = "vn_win32_enum_child_windows")] - private static partial int NativeEnumChildWindows(long parent, long* buffer, int capacity, out int written); - - /// Focused control of the foreground GUI thread that owns , or zero. - public static IntPtr GetFocusedControl(IntPtr window) - { - uint thread = GetWindowThreadProcessId(window, out _); - return thread != 0 && NativeGetGuiThreadFocus(thread, out long focus) == 0 ? (IntPtr)focus : IntPtr.Zero; - } - - public static bool IsChild(IntPtr parent, IntPtr child) => - NativeIsChild(parent, child, out byte isChild) == 0 && isChild != 0; - - public static IntPtr GetAncestor(IntPtr hwnd, uint flags) => - NativeGetAncestor(hwnd, flags, out long ancestor) == 0 ? (IntPtr)ancestor : IntPtr.Zero; - - /// Walks a native snapshot of the child windows until returns false. - public static bool EnumChildWindows(IntPtr parent, EnumWindowsProc enumProc, IntPtr lParam) - { - long* windows = stackalloc long[ChildWindowCapacity]; - if (NativeEnumChildWindows(parent, windows, ChildWindowCapacity, out int count) != 0) return false; - for (int i = 0; i < count; i++) - { - if (!enumProc((IntPtr)windows[i], lParam)) break; - } - - return true; - } - - /// - /// Sends a message whose WPARAM and LPARAM are written by the target (EM_GETSEL style). - /// - public static IntPtr SendMessageSelectionTimeout( - IntPtr hwnd, uint message, out int wParam, out int lParam, uint flags, uint timeout, out IntPtr result) - { - int start = 0, end = 0; - IntPtr sent = SendMessageTimeout(hwnd, message, (IntPtr)(&start), (IntPtr)(&end), flags, timeout, out result); - wParam = start; - lParam = end; - return sent; - } - - /// - /// Sends a text-retrieval message (WM_GETTEXT, LB_GETTEXT, ...) with a UTF-16 buffer sized from - /// .Capacity and appends the null-terminated reply to it. - /// - public static IntPtr SendMessageTextTimeout( - IntPtr hwnd, uint message, IntPtr wParam, StringBuilder text, uint flags, uint timeout, out IntPtr result) - { - // WM_GETTEXT takes a capacity. Index/selection messages do not, so - // their two-step callers must own the target thread through the copy. - if (message == 0x000D) wParam = (IntPtr)Math.Clamp(wParam.ToInt64(), 0, text.Capacity); - else if (message is not (0x0148 or 0x0189 or 0x043E) || - GetWindowThreadProcessId(hwnd, out _) != GetCurrentThreadId()) - throw new ArgumentException("This text retrieval requires the owning thread.", nameof(message)); - int capacity = Math.Max(2, checked(text.Capacity + 1)); - char[] rented = ArrayPool.Shared.Rent(capacity); - try - { - rented.AsSpan(0, capacity).Clear(); - fixed (char* buffer = rented) - { - IntPtr sent = SendMessageTimeout(hwnd, message, wParam, (IntPtr)buffer, flags, timeout, out result); - if (sent != IntPtr.Zero) - { - int length = Array.IndexOf(rented, '\0', 0, capacity); - text.Clear(); - text.Append(rented, 0, length < 0 ? capacity : length); - } - - return sent; - } - } - finally - { - ArrayPool.Shared.Return(rented); - } - } - - /// Types the text as Unicode keystrokes; true when every key event was accepted. - public static bool SendUnicodeText(string text) - { - if (string.IsNullOrEmpty(text)) - { - return false; - } - - byte[]? rented = null; - try - { - ReadOnlySpan utf8 = PlatformShellNative.EncodeUtf8( - text, - stackalloc byte[UnicodeTextStackThreshold], - out rented); - fixed (byte* pUtf8 = utf8) - { - return PlatformShellNative.vn_win32_send_unicode_text_utf8( - pUtf8, - (uint)utf8.Length, - out _, - out _) == (int)NativeStatus.Ok; - } - } - finally - { - PlatformShellNative.ReturnBuffer(rented); - } - } -} diff --git a/Services/Win32Interop.Process.cs b/Services/Win32Interop.Process.cs index 613bb3b7..0025b871 100644 --- a/Services/Win32Interop.Process.cs +++ b/Services/Win32Interop.Process.cs @@ -35,13 +35,6 @@ private static partial int NativeProcessImagePathEquals( uint expectedLen, out byte equal); - [LibraryImport(NativeDll, EntryPoint = "vn_process_app_user_model_id_equals_utf8")] - private static partial int NativeProcessAppUserModelIdEquals( - long processHandle, - ReadOnlySpan expectedUtf8, - uint expectedLen, - out byte equal); - [LibraryImport(NativeDll, EntryPoint = "vn_file_create_delete_on_close_utf8")] private static partial int NativeFileCreateDeleteOnClose( ReadOnlySpan pathUtf8, @@ -90,20 +83,6 @@ internal static bool ProcessImagePathEquals(uint processId, string expectedPath) } } - internal static bool ProcessAppUserModelIdEquals(IntPtr processHandle, string expected) - { - byte[]? rented = null; - try - { - ReadOnlySpan utf8 = PlatformShellNative.EncodeUtf8(expected, stackalloc byte[256], out rented); - return NativeProcessAppUserModelIdEquals(processHandle, utf8, (uint)utf8.Length, out byte equal) == 0 && equal != 0; - } - finally - { - if (rented is not null) ArrayPool.Shared.Return(rented); - } - } - /// CREATE_NEW read handle that deletes the file once every handle is closed; null on failure (last error set). internal static SafeFileHandle? CreateDeleteOnCloseFile(string path) { diff --git a/Services/Win32Interop.cs b/Services/Win32Interop.cs index 34752368..cb084ef1 100644 --- a/Services/Win32Interop.cs +++ b/Services/Win32Interop.cs @@ -121,9 +121,6 @@ private struct VnTwoUtf8SlicesRequest [LibraryImport(NativeDll, EntryPoint = "vn_win32_get_async_key_state")] private static partial int NativeGetAsyncKeyState(int vk, out short state); - [LibraryImport(NativeDll, EntryPoint = "vn_win32_send_extended_key_tap")] - private static partial int NativeSendExtendedKeyTap(byte vk); - [LibraryImport(NativeDll, EntryPoint = "vn_win32_register_hotkey_v2")] private static partial int NativeRegisterHotKey(in VnRegisterHotKeyRequest req, out int lastError); @@ -136,21 +133,12 @@ private struct VnTwoUtf8SlicesRequest [LibraryImport(NativeDll, EntryPoint = "vn_win32_dwm_set_window_attribute_int")] private static partial int NativeDwmSetWindowAttributeInt(long hwnd, int attribute, int value, out int hresult); - [LibraryImport(NativeDll, EntryPoint = "vn_win32_delete_gdi_object")] - private static partial int NativeDeleteGdiObject(long handle); - [LibraryImport(NativeDll, EntryPoint = "vn_win32_destroy_icon")] private static partial int NativeDestroyIcon(long handle); [LibraryImport(NativeDll, EntryPoint = "vn_win32_get_display_frequency_utf8")] private static partial int NativeGetDisplayFrequency(ReadOnlySpan deviceUtf8, uint deviceLen, out uint hz); - [LibraryImport(NativeDll, EntryPoint = "vn_win32_keyboard_hook_install_v2")] - private static partial int NativeKeyboardHookInstall(nint callback, long context, out int slot, out int lastError); - - [LibraryImport(NativeDll, EntryPoint = "vn_win32_keyboard_hook_uninstall")] - private static partial int NativeKeyboardHookUninstall(int slot); - [LibraryImport(NativeDll, EntryPoint = "vn_win32_get_current_process")] private static partial int NativeGetCurrentProcess(out long handle); @@ -220,9 +208,6 @@ public static int GetSystemMetrics(int nIndex) => public static short GetAsyncKeyState(int vKey) => NativeGetAsyncKeyState(vKey, out short state) == 0 ? state : (short)0; - /// Presses and releases an extended virtual key (media keys). - public static void SendExtendedKeyTap(byte virtualKey) => NativeSendExtendedKeyTap(virtualKey); - public static bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk) { var req = new VnRegisterHotKeyRequest @@ -255,8 +240,6 @@ public static int DwmSetWindowAttributeInt(IntPtr hwnd, int dwAttribute, ref int return hresult; } - public static bool DeleteObject(IntPtr hObject) => NativeDeleteGdiObject(hObject) == 0; - public static bool DestroyIcon(IntPtr hIcon) => NativeDestroyIcon(hIcon) == 0; /// Current refresh rate of the named display device (null = primary), or null when unknown. @@ -283,22 +266,12 @@ public static int DwmSetWindowAttributeInt(IntPtr hwnd, int dwAttribute, ref int - [LibraryImport(NativeDll, EntryPoint = "vn_win32_is_window_visible")] - private static partial int NativeIsWindowVisible(long hwnd, out byte visible); - - [LibraryImport(NativeDll, EntryPoint = "vn_win32_is_iconic")] - private static partial int NativeIsIconic(long hwnd, out byte iconic); - [LibraryImport(NativeDll, EntryPoint = "vn_win32_add_clipboard_format_listener")] private static partial int NativeAddClipboardFormatListener(long hwnd, out int lastError); [LibraryImport(NativeDll, EntryPoint = "vn_win32_remove_clipboard_format_listener")] private static partial int NativeRemoveClipboardFormatListener(long hwnd); - public static bool IsWindowVisible(IntPtr hWnd) => NativeIsWindowVisible(hWnd, out byte visible) == 0 && visible != 0; - - public static bool IsIconic(IntPtr hWnd) => NativeIsIconic(hWnd, out byte iconic) == 0 && iconic != 0; - public static bool AddClipboardFormatListener(IntPtr hwnd) { if (NativeAddClipboardFormatListener(hwnd, out int lastError) == 0) return true; @@ -439,9 +412,6 @@ public static bool CaptureScreenRect(IntPtr destDc, int width, int height, IntPt [LibraryImport(NativeDll, EntryPoint = "vn_win32_enum_top_level_windows")] private static partial int NativeEnumTopLevelWindows(long* buffer, int capacity, out int written); - [LibraryImport(NativeDll, EntryPoint = "vn_win32_get_window_text_length")] - private static partial int NativeGetWindowTextLength(long hwnd, out int length); - [LibraryImport(NativeDll, EntryPoint = "vn_win32_get_window_text_utf8")] private static partial int NativeGetWindowText(long hwnd, out VnOwnedBytes outUtf8); @@ -499,9 +469,6 @@ public static bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam) return true; } - public static int GetWindowTextLength(IntPtr hWnd) => - NativeGetWindowTextLength(hWnd, out int length) == 0 ? length : 0; - public static int GetWindowText(IntPtr hWnd, char* lpString, int nMaxCount) { if (lpString == null || nMaxCount <= 0) return 0; @@ -580,9 +547,6 @@ internal static bool CreateDibSurface(IntPtr screenDc, int width, int height, ou [LibraryImport(NativeDll, EntryPoint = "vn_win32_get_clipboard_owner")] private static partial int NativeGetClipboardOwner(out long hwnd); - [LibraryImport(NativeDll, EntryPoint = "vn_win32_lock_workstation")] - private static partial int NativeLockWorkStation(out int lastError); - [LibraryImport(NativeDll, EntryPoint = "vn_win32_set_rounded_window_region_v2")] private static partial int NativeSetRoundedWindowRegion(in VnRoundedWindowRegionRequest req); @@ -595,13 +559,6 @@ public static uint GetClipboardSequenceNumber() => public static IntPtr GetClipboardOwner() => NativeGetClipboardOwner(out long hwnd) == 0 ? (IntPtr)hwnd : IntPtr.Zero; - public static bool LockWorkStation() - { - if (NativeLockWorkStation(out int lastError) == 0) return true; - Marshal.SetLastPInvokeError(lastError); - return false; - } - /// Clips the window to a rounded rectangle; the window owns the region on success. public static bool SetRoundedWindowRegion(IntPtr hwnd, int left, int top, int right, int bottom, int ellipseWidth, int ellipseHeight) { @@ -682,148 +639,6 @@ public static IntPtr GetDesktopLayerInsertAfter(IntPtr window) => ? (IntPtr)insertAfter : HWND_NOTOPMOST; - - - [StructLayout(LayoutKind.Sequential)] - private struct KeyboardHookEvent - { - public uint VkCode; - public uint ScanCode; - public uint Flags; - public uint Time; - public long ExtraInfo; - public int Message; - private int _reserved; - } - - /// - /// WH_KEYBOARD_LL hook whose procedure lives in the native layer. Install and dispose on a thread - /// that pumps messages; the handler runs on that thread and returns true to swallow the key. - /// - internal sealed class LowLevelKeyboardHook(Func handler) : IDisposable - { - private sealed class KeyboardHookHandle : SafeHandle - { - private GCHandle _callbackRoot; - - internal KeyboardHookHandle(int slot, GCHandle callbackRoot) - : base(new IntPtr(-1), true) - { - SetHandle((nint)slot); - _callbackRoot = callbackRoot; - } - - public override bool IsInvalid => handle.ToInt64() < 0; - - protected override bool ReleaseHandle() - { - int slot = (int)handle.ToInt64(); - if (slot >= 0) - { - NativeKeyboardHookUninstall(slot); - } - - if (_callbackRoot.IsAllocated) - { - _callbackRoot.Free(); - } - - return true; - } - } - - private KeyboardHookHandle? _hookHandle; - private int _activeCallbackThreadId; - private int _disposed; - private int _disposeDeferred; - - internal int InstallationError { get; private set; } - internal bool IsInstalled => Volatile.Read(ref _hookHandle) is { IsInvalid: false, IsClosed: false }; - - internal bool Install() - { - if (Volatile.Read(ref _disposed) != 0) - { - return false; - } - - if (IsInstalled) - { - return true; - } - - using var pending = new PendingCallbackHandle(this); - delegate* unmanaged[Stdcall] callback = &OnKey; - if (NativeKeyboardHookInstall((nint)callback, pending.Context, out int slot, out int lastError) != 0) - { - InstallationError = lastError; - return false; - } - - Volatile.Write(ref _hookHandle, new KeyboardHookHandle(slot, pending.Transfer())); - return true; - } - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) - { - return; - } - - if (Volatile.Read(ref _activeCallbackThreadId) == Environment.CurrentManagedThreadId) - { - Volatile.Write(ref _disposeDeferred, 1); - return; - } - - Interlocked.Exchange(ref _hookHandle, null)?.Dispose(); - } - - [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] - private static int OnKey(long context, KeyboardHookEvent* data) - { - if (GCHandle.FromIntPtr((IntPtr)context).Target is not LowLevelKeyboardHook hook) - { - return 0; - } - - if (Volatile.Read(ref hook._disposed) != 0) - { - return 0; - } - - Volatile.Write(ref hook._activeCallbackThreadId, Environment.CurrentManagedThreadId); - try - { - var key = new KBDLLHOOKSTRUCT - { - vkCode = data->VkCode, - scanCode = data->ScanCode, - flags = data->Flags, - time = data->Time, - dwExtraInfo = (IntPtr)data->ExtraInfo, - }; - return hook.Handle(key, data->Message) ? 1 : 0; - } - catch - { - // Exceptions must never unwind through user32 or delay the keyboard chain. - return 0; - } - finally - { - Volatile.Write(ref hook._activeCallbackThreadId, 0); - if (Volatile.Read(ref hook._disposeDeferred) != 0) - { - Interlocked.Exchange(ref hook._hookHandle, null)?.Dispose(); - } - } - } - - private bool Handle(KBDLLHOOKSTRUCT key, int message) => handler(key, message); - } - [LibraryImport(NativeDll, EntryPoint = "vn_win32_win_event_hook_install_v2")] private static partial int NativeWinEventHookInstall(in VnWinEventHookInstallRequest req, out int slot); @@ -993,31 +808,11 @@ private static void OnEvent(long context, uint eventType, long hwnd) public const int WM_CLIPBOARDUPDATE = 0x031D; public const int WM_NCHITTEST = 0x0084; public const int WM_HOTKEY = 0x0312; - public const int WM_KEYDOWN = 0x0100; - public const int WM_KEYUP = 0x0101; - public const int WM_SYSKEYDOWN = 0x0104; - public const int WM_SYSKEYUP = 0x0105; public const int HTTRANSPARENT = -1; - public const byte VK_MEDIA_PLAY_PAUSE = 0xB3; - public const byte VK_MEDIA_NEXT_TRACK = 0xB0; - public const byte VK_MEDIA_PREV_TRACK = 0xB1; public const int DWMWA_TRANSITIONS_FORCEDISABLED = 3; public const uint MOD_ALT = 0x0001; public const uint MOD_NOREPEAT = 0x4000; public const uint VK_SPACE = 0x20; - public const uint LLKHF_ALTDOWN = 0x20; - - - - [StructLayout(LayoutKind.Sequential)] - public struct KBDLLHOOKSTRUCT - { - public uint vkCode; - public uint scanCode; - public uint flags; - public uint time; - public IntPtr dwExtraInfo; - } [StructLayout(LayoutKind.Sequential)] public struct WINDOWPOS diff --git a/Tests/AccentThemeTests.cs b/Tests/AccentThemeTests.cs index 249b96a7..2baed45c 100644 --- a/Tests/AccentThemeTests.cs +++ b/Tests/AccentThemeTests.cs @@ -275,13 +275,11 @@ private sealed class RecordingService : ISettingsApplicationService public Task ApplyAsync(NotchSettings settings, CancellationToken ct = default) { Applied = settings.Clone(); - SettingsApplied?.Invoke(this, Applied); return Task.CompletedTask; } public Task<(NotchSettings Settings, bool RequiresRestart)> ImportAsync(string filePath, NotchSettings? currentSettings = null, CancellationToken ct = default) => Task.FromResult((new NotchSettings(), false)); public void Export(string filePath, NotchSettings settings) { } public bool IsAutoStartEnabled() => false; - public event EventHandler? SettingsApplied; } } diff --git a/Tests/ApiKeySecurityTests.cs b/Tests/ApiKeySecurityTests.cs index 64f24051..c6af134f 100644 --- a/Tests/ApiKeySecurityTests.cs +++ b/Tests/ApiKeySecurityTests.cs @@ -1,4 +1,5 @@ using VNotch.Models; +using VNotch.Interop; using VNotch.Services; using VNotch.Services.Spotlight; using Xunit; @@ -23,10 +24,10 @@ public sealed class ApiKeySecurityTests [InlineData("token='private-session'; status=401", "token='[REDACTED]'; status=401", "private-session")] public void RealLogPayloadsPreserveStructureAndNeverExposeTheSecret(string input, string expected, string secret) { - string result = SensitiveDataScrubber.Scrub(input); + string result = SecurityNative.ScrubSensitiveText(input); Assert.Equal(expected, result); Assert.DoesNotContain(secret, result); - Assert.Equal(result, SensitiveDataScrubber.Scrub(result)); + Assert.Equal(result, SecurityNative.ScrubSensitiveText(result)); } [Theory] @@ -36,7 +37,7 @@ public void RealLogPayloadsPreserveStructureAndNeverExposeTheSecret(string input [InlineData("eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..aXY.Y2lwaGVy.dGFn")] public void StandaloneJwtIsRedactedIncludingUnsignedAndEncryptedForms(string token) { - string result = SensitiveDataScrubber.Scrub("WARN token dump: \"" + token + "\"; request=42"); + string result = SecurityNative.ScrubSensitiveText("WARN token dump: \"" + token + "\"; request=42"); Assert.Equal("WARN token dump: \"[REDACTED]\"; request=42", result); Assert.DoesNotContain(token, result); } @@ -46,13 +47,13 @@ public void StandaloneJwtIsRedactedIncludingUnsignedAndEncryptedForms(string tok [InlineData("version=1.2.3; host=example.com; password control visible")] [InlineData("ordinary_token=visible; mysession=visible; label=secret")] public void OrdinaryWordsAndVersionsKeepTheirOriginalString(string input) - => Assert.Same(input, SensitiveDataScrubber.Scrub(input)); + => Assert.Same(input, SecurityNative.ScrubSensitiveText(input)); [Fact] public void JsonStructureSurvivesEscapedPasswordValues() { const string input = "{\"password\":\"quotes \\\" and backslash \\\\ and 日本語 🌸\",\"status\":401}"; - string result = SensitiveDataScrubber.Scrub(input); + string result = SecurityNative.ScrubSensitiveText(input); using var json = System.Text.Json.JsonDocument.Parse(result); Assert.Equal("[REDACTED]", json.RootElement.GetProperty("password").GetString()); Assert.Equal(401, json.RootElement.GetProperty("status").GetInt32()); @@ -68,7 +69,7 @@ public void JsonStructureSurvivesEscapedPasswordValues() public void UnicodeEscapedJsonFieldNamesCannotBypassRedaction(string name) { string encodedName = string.Concat(name.Select(c => $"\\u{(int)c:x4}")); - string result = SensitiveDataScrubber.Scrub("{\"" + encodedName + "\"\n : \"private-secret\",\"status\":401}"); + string result = SecurityNative.ScrubSensitiveText("{\"" + encodedName + "\"\n : \"private-secret\",\"status\":401}"); using var json = System.Text.Json.JsonDocument.Parse(result); Assert.Equal("[REDACTED]", json.RootElement.GetProperty(name).GetString()); Assert.Equal(401, json.RootElement.GetProperty("status").GetInt32()); @@ -79,7 +80,7 @@ public void UnicodeEscapedJsonFieldNamesCannotBypassRedaction(string name) public void LongEscapedProviderKeyNameKeepsTheSensitiveSuffix() { string name = new string('x', 10_000) + "\\u0041piKey"; - string result = SensitiveDataScrubber.Scrub("{\"" + name + "\":\"private-secret\",\"status\":401}"); + string result = SecurityNative.ScrubSensitiveText("{\"" + name + "\":\"private-secret\",\"status\":401}"); using var json = System.Text.Json.JsonDocument.Parse(result); Assert.Equal("[REDACTED]", json.RootElement.GetProperty(new string('x', 10_000) + "ApiKey").GetString()); Assert.Equal(401, json.RootElement.GetProperty("status").GetInt32()); @@ -93,7 +94,7 @@ public void LongEscapedProviderKeyNameKeepsTheSensitiveSuffix() [InlineData("provider rejected sk-proj-arbitrary-secret")] public void DiagnosticsRedactKeys(string input) { - Assert.DoesNotContain("arbitrary-secret", SensitiveDataScrubber.Scrub(input)); + Assert.DoesNotContain("arbitrary-secret", SecurityNative.ScrubSensitiveText(input)); } [Theory] diff --git a/Tests/BatterySourceTests.cs b/Tests/BatterySourceTests.cs index 2c3ffa29..f31e369f 100644 --- a/Tests/BatterySourceTests.cs +++ b/Tests/BatterySourceTests.cs @@ -87,24 +87,6 @@ public void UnavailableExplicitSourceNeverSilentlyBecomesSystemBattery(string se Assert.False(info.IsCharging); } - [Theory] - [InlineData(0, true)] - [InlineData(100, true)] - [InlineData(101, false)] - [InlineData(255, false)] - public void WindowsBatteryPropertiesRejectUnknownAndInvalidPercentages(int level, bool valid) - { - int actual = M05Native.ParseBtBatteryPercentage(new[] { (byte)level }); - Assert.Equal(valid ? level : -1, actual); - } - - [Fact] - public void MissingOrMalformedBatteryPropertyIsNotAReading() - { - Assert.Equal(-1, M05Native.ParseBtBatteryPercentage(Array.Empty())); - Assert.Equal(-1, M05Native.ParseBtBatteryPercentage(new byte[] { 50, 0 })); - } - [Fact] public void BatteryModule_EmitUpdate_AvoidsAsyncVoid() { diff --git a/Tests/ClipboardSensitiveDataTests.cs b/Tests/ClipboardSensitiveDataTests.cs index 5ba5081e..e8a4414d 100644 --- a/Tests/ClipboardSensitiveDataTests.cs +++ b/Tests/ClipboardSensitiveDataTests.cs @@ -319,15 +319,15 @@ public void ScrubberRedactsAwsGitHubAndPrefixedSessionFields() string ghPat = string.Concat("ghp_", "1234567890abcdefghijklmnopqrstuvwxyz"); string jsonToken = "{ \"my_access_token\": \"secret123456\" }"; - string scrubbedAws = SensitiveDataScrubber.Scrub(awsKey); + string scrubbedAws = SecurityNative.ScrubSensitiveText(awsKey); Assert.DoesNotContain("IOSFODNN7EXAMPLE", scrubbedAws); Assert.Contains("[REDACTED]", scrubbedAws); - string scrubbedGh = SensitiveDataScrubber.Scrub(ghPat); + string scrubbedGh = SecurityNative.ScrubSensitiveText(ghPat); Assert.DoesNotContain("1234567890abcdefghijklmnopqrstuvwxyz", scrubbedGh); Assert.Contains("[REDACTED]", scrubbedGh); - string scrubbedJson = SensitiveDataScrubber.Scrub(jsonToken); + string scrubbedJson = SecurityNative.ScrubSensitiveText(jsonToken); Assert.DoesNotContain("secret123456", scrubbedJson); Assert.Contains("[REDACTED]", scrubbedJson); } diff --git a/Tests/CoreSafeConversionsTests.cs b/Tests/CoreSafeConversionsTests.cs index 5d9ced49..f3d2ea58 100644 --- a/Tests/CoreSafeConversionsTests.cs +++ b/Tests/CoreSafeConversionsTests.cs @@ -117,11 +117,5 @@ public void BackupNamePathPolicyCanvasUriAndBluetoothPercentage_ParityChecks() Assert.False(FileIconProvider.CanProbeLocalFilesystemPath(@"\\server\share\console.msc")); Assert.False(FileIconProvider.CanProbeLocalFilesystemPath("https://example.com/console.msc")); Assert.False(FileIconProvider.CanProbeLocalFilesystemPath("relative\\console.msc")); - - Assert.Equal(-1, M05Native.ParseBtBatteryPercentage(ReadOnlySpan.Empty)); - Assert.Equal(0, M05Native.ParseBtBatteryPercentage([0])); - Assert.Equal(100, M05Native.ParseBtBatteryPercentage([100])); - Assert.Equal(-1, M05Native.ParseBtBatteryPercentage([101])); - Assert.Equal(-1, M05Native.ParseBtBatteryPercentage([50, 0])); } } diff --git a/Tests/DiagnosticLogCapturePolicyTests.cs b/Tests/DiagnosticLogCapturePolicyTests.cs deleted file mode 100644 index 29bb50d9..00000000 --- a/Tests/DiagnosticLogCapturePolicyTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -using VNotch.Services; -using Xunit; - -namespace VNotch.Tests; - -public sealed class DiagnosticLogCapturePolicyTests -{ - [Fact] - public void LogStormIsBoundedAndCaptureResumesInTheNextWindow() - { - var policy = new DiagnosticLogCapturePolicy(); - int captured = 0; - for (int i = 0; i < 10000; i++) - if (policy.TryCapture(1500)) captured++; - Assert.Equal(DiagnosticLogCapturePolicy.MaxEntriesPerSecond, captured); - Assert.True(policy.TryCapture(2000)); - } - - [Fact] - public void ParallelWritersCannotExceedTheCaptureBudget() - { - var policy = new DiagnosticLogCapturePolicy(); - int captured = 0; - Parallel.For(0, 10000, _ => - { - if (policy.TryCapture(1500)) Interlocked.Increment(ref captured); - }); - Assert.InRange(captured, 1, DiagnosticLogCapturePolicy.MaxEntriesPerSecond); - } - - [Fact] - public void VerboseCaptureExistsOnlyWhileAViewerHoldsALease() - { - var service = new PerformanceDiagnosticService(subscribeToRuntimeLog: false); - service.CaptureRuntimeLogEntry(LogLevel.Info, "TEST", "hidden"); - Assert.DoesNotContain(service.GetRecentServiceLogs(), entry => entry.Message == "hidden"); - - var first = service.BeginVerboseServiceLogCapture(); - var second = service.BeginVerboseServiceLogCapture(); - first.Dispose(); - first.Dispose(); - service.CaptureRuntimeLogEntry(LogLevel.Info, "TEST", "visible"); - Assert.Contains(service.GetRecentServiceLogs(), entry => entry.Message == "visible"); - - second.Dispose(); - service.CaptureRuntimeLogEntry(LogLevel.Info, "TEST", "closed"); - service.CaptureRuntimeLogEntry(LogLevel.Warn, "TEST", "warning"); - Assert.DoesNotContain(service.GetRecentServiceLogs(), entry => entry.Message == "closed"); - Assert.Contains(service.GetRecentServiceLogs(), entry => entry.Message == "warning"); - } -} diff --git a/Tests/FirstOpenLatencyTests.cs b/Tests/FirstOpenLatencyTests.cs index bbc57222..18dee990 100644 --- a/Tests/FirstOpenLatencyTests.cs +++ b/Tests/FirstOpenLatencyTests.cs @@ -27,8 +27,6 @@ await WpfFrameWaiter.UntilAsync(() => "post-entrance settings preparation finishes", ct); var pauses = new List(); - void Capture(string message) => output.WriteLine(message); - SettingsWindow.FirstOpenProbe += Capture; for (int attempt = 0; attempt < 2; attempt++) { var watch = Stopwatch.StartNew(); @@ -64,7 +62,6 @@ await WpfFrameWaiter.UntilAsync(() => output.WriteLine($"Settings open {attempt + 1}: longest input timer delay {longestPause:F1} ms"); await WpfFrameWaiter.UntilAsync(() => !Animating(window), "settings return settles", ct); } - SettingsWindow.FirstOpenProbe -= Capture; Assert.True(pauses[0] < 100, $"First Settings click delayed the input timer by {pauses[0]:F1} ms (second: {pauses[1]:F1} ms)."); }); @@ -113,87 +110,6 @@ await WpfFrameWaiter.UntilAsync(() => !Animating(window) && Assert.True(pauses[0] < 100, $"First notch click delayed the input timer by {pauses[0]:F1} ms (second: {pauses[1]:F1} ms)."); }); - [Theory] - [InlineData(false, false)] - [InlineData(true, false)] - [InlineData(false, true)] - [InlineData(true, true)] - public void SettingsPreparationYieldsToAnimationAndHonorsCancellation(bool pauseAfterConstruction, bool cancel) => SharedStaTestRunner.RunAsync(async ct => - { - await using var fixture = Create(); - var window = fixture.Window; - window.Show(); - await WpfFrameWaiter.UntilAsync(() => !Animating(window), "notch startup settles", ct); - void Capture(string message) - { - if (pauseAfterConstruction && message.Contains("Settings snapshot", StringComparison.Ordinal)) - window.IsAnimating = true; - } - SettingsWindow.FirstOpenProbe += Capture; - window.IsAnimating = !pauseAfterConstruction; - Task? preparation = null; - try - { - preparation = window.SettingsPreparation.PrepareAsync(0); - await window.Dispatcher.InvokeAsync(static () => { }, DispatcherPriority.ContextIdle); - Assert.False(preparation.IsCompleted); - if (pauseAfterConstruction) - Assert.False(Assert.IsType(window.SettingsPreparation.Prepared).IsLoaded); - else - Assert.Null(window.SettingsPreparation.Prepared); - - if (cancel) - window.SettingsPreparation.Close(); - window.IsAnimating = false; - await preparation.WaitAsync(ct); - - if (cancel) - Assert.Null(window.SettingsPreparation.Prepared); - else - Assert.True(window.SettingsPreparation.Prepared is SettingsWindow { IsLoaded: true, IsVisible: false }); - } - finally - { - SettingsWindow.FirstOpenProbe -= Capture; - window.IsAnimating = false; - if (preparation != null) await preparation.WaitAsync(ct); - } - }); - - [Fact] - public void SettingsPreparationWaitsForUserIntentAndTheNotchEntrance() => SharedStaTestRunner.RunAsync(async ct => - { - await using var fixture = Create(); - var window = fixture.Window; - bool? afterEntrance = null; - void Capture(string message) - { - if (message.Contains("Settings XAML", StringComparison.Ordinal)) - afterEntrance = window.PostAppearInitializationStarted; - } - SettingsWindow.FirstOpenProbe += Capture; - try - { - window.Show(); - await WpfFrameWaiter.UntilAsync(() => !Animating(window) && - window.CoreModulesStarted, - "compact services start", ct); - await window.Dispatcher.InvokeAsync(static () => { }, DispatcherPriority.ApplicationIdle); - Assert.Null(window.SettingsPreparation.Prepared); - Assert.Null(afterEntrance); - window.TrayIcon.ContextMenu.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.ContextMenu.OpenedEvent)); - await window.Dispatcher.InvokeAsync(static () => { }, DispatcherPriority.ApplicationIdle); - Assert.Null(afterEntrance); - window.MenuSettings.RaiseEvent(new System.Windows.Input.MouseEventArgs( - System.Windows.Input.Mouse.PrimaryDevice, Environment.TickCount) { RoutedEvent = UIElement.MouseEnterEvent }); - await WpfFrameWaiter.UntilAsync(() => - window.SettingsPreparation.Prepared is SettingsWindow { IsLoaded: true, IsVisible: false }, - "deferred settings preparation completes", ct); - Assert.True(afterEntrance); - } - finally { SettingsWindow.FirstOpenProbe -= Capture; } - }); - [Fact] public void ExpiredSettingsPreparationReleasesTheWindowAndCanBePreparedAgain() => SharedStaTestRunner.RunAsync(async ct => { diff --git a/Tests/HotPathRegressionTests.cs b/Tests/HotPathRegressionTests.cs index d9d28cfe..1af2589c 100644 --- a/Tests/HotPathRegressionTests.cs +++ b/Tests/HotPathRegressionTests.cs @@ -8,6 +8,7 @@ using System.Windows.Media.Imaging; using System.Windows.Threading; using VNotch.Controls; +using VNotch.Interop; using VNotch.Services; using VNotch.Tests.Fixtures; using Xunit; @@ -199,14 +200,14 @@ private static Geometry GetDisplay(FrameworkElement icon, Type type) [InlineData("https://example.com?token=sk-abcdefghijk&x=1", "https://example.com?token=[REDACTED]&x=1")] [InlineData("x-goog-api-key: secret; Authorization: Bearer abc.def", "x-goog-api-key: [REDACTED]; Authorization: Bearer [REDACTED]")] public void ScrubberRedactsWholeValuesIncludingNestedTokenFormats(string input, string expected) - => Assert.Equal(expected, SensitiveDataScrubber.Scrub(input)); + => Assert.Equal(expected, SecurityNative.ScrubSensitiveText(input)); [Fact] public void ScrubberBoundsPathologicalInput() { var input = new string('a', 200_000) + "! api_key=private-value"; var timer = Stopwatch.StartNew(); - var result = SensitiveDataScrubber.Scrub(input); + var result = SecurityNative.ScrubSensitiveText(input); Assert.DoesNotContain("private-value", result); Assert.True(timer.Elapsed < TimeSpan.FromSeconds(3), $"Scrubbing took {timer.Elapsed}."); } @@ -231,7 +232,7 @@ public void BenchmarkRenderAndHighlightAllocations() => SharedStaTestRunner.Run( HighlightedText.SetQuery(block, "hello world"); Measure("matched-query title", 1000, () => HighlightedText.SetText(block, ++index % 2 == 0 ? "Hello world" : "Hello there")); string input = "sp_dc=cookie123; api_key=my-private-key Authorization: Bearer abc.def password=pass"; - Measure("scrub mixed secrets", 1000, () => SensitiveDataScrubber.Scrub(input)); + Measure("scrub mixed secrets", 1000, () => SecurityNative.ScrubSensitiveText(input)); }); private double MeasureMorph(FrameworkElement icon, Action render, diff --git a/Tests/MainWindowGlassPresentationTests.cs b/Tests/MainWindowGlassPresentationTests.cs index 93e749f3..aed46fe0 100644 --- a/Tests/MainWindowGlassPresentationTests.cs +++ b/Tests/MainWindowGlassPresentationTests.cs @@ -177,9 +177,6 @@ public void OpticalConfigurationClampsLayersAndReducedMotionKeepsRestingMaterial Assert.InRange(shadow.Opacity, 0.3, 0.55); Assert.InRange(shadow.BlurRadius, 12, 29); if (reducedMotion) Assert.Equal(12, shadow.BlurRadius); - window.GlassDarkOverlay.Opacity = 0.9; - Invoke(window, "UpdateDynamicGlassTint"); - Assert.Equal(0, window.GlassDarkOverlay.Opacity); settings.LiquidGlass.Noise = 0; settings.LiquidGlass.Opacity = 5; settings.LiquidGlass.ShadowOpacity = -1; diff --git a/Tests/MigrationBaseline/M00_RustAbiHandshakeTests.cs b/Tests/MigrationBaseline/M00_RustAbiHandshakeTests.cs index 69f0b836..ea4d4535 100644 --- a/Tests/MigrationBaseline/M00_RustAbiHandshakeTests.cs +++ b/Tests/MigrationBaseline/M00_RustAbiHandshakeTests.cs @@ -28,9 +28,6 @@ public sealed partial class M00_RustAbiHandshakeTests [LibraryImport(NativeAbi.RustLibraryName)] private static partial int vn_free_bytes(nint ptr, uint len); - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_free_string(nint ptr, uint len); - [Fact] public unsafe void RustAbiQuery_ReturnsAbi22AndRejectsInvalidBuffers() { @@ -71,8 +68,6 @@ public unsafe void RustFreeBytes_AndOwnedBytesContract_HandleEdgeCasesSafely() Assert.Equal(ExpectedOwnedBytesSize, sizeof(VnOwnedBytes)); Assert.Equal(VnOk, vn_free_bytes(0, 0)); Assert.Equal(VnErrInvalidArg, vn_free_bytes(0, 1)); - Assert.Equal(VnOk, vn_free_string(0, 0)); - Assert.Equal(VnErrInvalidArg, vn_free_string(0, 1)); byte dummy = 0; Assert.Equal(VnErrInvalidArg, vn_free_bytes((nint)(&dummy), 0)); diff --git a/Tests/MigrationBaseline/M01_FoundationBaselineTests.cs b/Tests/MigrationBaseline/M01_FoundationBaselineTests.cs index 918e8f61..ec2ab4f9 100644 --- a/Tests/MigrationBaseline/M01_FoundationBaselineTests.cs +++ b/Tests/MigrationBaseline/M01_FoundationBaselineTests.cs @@ -456,9 +456,6 @@ private struct VnMarkdownCloseSpansOut [LibraryImport(NativeAbi.RustLibraryName)] private static unsafe partial int vn_ai_markdown_close_stream_spans_v2(VnMarkdownCloseSpansRequest* req, char* outCloser, int cap, VnMarkdownCloseSpansOut* outRes); - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_foundation_catalog_select_utf8(byte* reqJson, uint reqLen, VnOwnedBytes* outResultJson); - [LibraryImport(NativeAbi.RustLibraryName)] private static partial int vn_orb_sequence_create(byte hasSeed, int seed, out long outHandle); @@ -1335,100 +1332,6 @@ public void OrbGeometryAndSequence_CharacterizeAllStatesAndBagCycles() Assert.Equal(expectedSeq, actualSeq); } - [Fact] - public unsafe void CatalogParser_CharacterizesAllKindsInvalidArgs() - { - using var doc = LoadGolden("orb-and-catalog-cases.json"); - - VnOwnedBytes outOwned = default; - Assert.Equal(VnErrInvalidArg, vn_foundation_catalog_select_utf8(null, 0, &outOwned)); - Assert.Equal(VnErrInvalidArg, vn_foundation_catalog_select_utf8(null, 10, &outOwned)); - byte[] unknownKindJson = "{\"kind\":8,\"json\":\"{}\"}"u8.ToArray(); - fixed (byte* pUnknown = unknownKindJson) - { - Assert.Equal(VnErrInvalidArg, vn_foundation_catalog_select_utf8(pUnknown, (uint)unknownKindJson.Length, &outOwned)); - } - - Assert.Equal(default, SelectCatalogViaNative(ReadOnlySpan.Empty, 0, "A", "B")); - byte[] oversized = new byte[2 * 1024 * 1024 + 1]; - Array.Fill(oversized, (byte)' '); - Assert.Equal(default, SelectCatalogViaNative(oversized, 0, "A", "B")); - - foreach (var item in doc.RootElement.GetProperty("catalogSelect").EnumerateArray()) - { - var sel = SelectCatalogViaNative( - Encoding.UTF8.GetBytes(item.GetProperty("json").GetString()!), - item.GetProperty("kind").GetInt32(), - item.GetProperty("title").GetString()!, - item.GetProperty("artist").GetString()!, - item.GetProperty("milliseconds").GetInt64(), - item.GetProperty("album").GetString()); - - if (item.TryGetProperty("expectedText", out var expText)) - Assert.Equal(expText.GetString(), sel.Text); - if (item.TryGetProperty("expectedKey", out var expKey)) - Assert.Equal(expKey.GetString(), sel.Key); - if (item.TryGetProperty("expectedId", out var expId)) - Assert.Equal(expId.GetInt64(), sel.Id); - if (item.TryGetProperty("expectedApiCode", out var expCode)) - Assert.Equal(expCode.GetInt32(), sel.ApiCode); - } - } - - private readonly record struct NativeCatalogSelection(string? Text, string? Key, long Id, int ApiCode); - - private static unsafe NativeCatalogSelection SelectCatalogViaNative( - ReadOnlySpan bytes, - int kind, - string title, - string artist, - long targetMs = 0, - string? album = null) - { - if (bytes.IsEmpty || bytes.Length > 2 * 1024 * 1024) - return default; - - byte[] reqBytes = JsonSerializer.SerializeToUtf8Bytes(new - { - kind, - json = Encoding.UTF8.GetString(bytes), - title, - artist, - album = album ?? string.Empty, - target_ms = targetMs, - }); - if (reqBytes.Length > 2 * 1024 * 1024) - return default; - - VnOwnedBytes owned = default; - fixed (byte* pReq = reqBytes) - { - int status = vn_foundation_catalog_select_utf8(pReq, (uint)reqBytes.Length, &owned); - if (status != VnOk) - { - owned.Free(); - return default; - } - } - - try - { - using var resDoc = JsonDocument.Parse(owned.AsSpan().ToArray()); - var root = resDoc.RootElement; - string? text = root.GetProperty("text").GetString(); - string? key = root.GetProperty("key").GetString(); - return new NativeCatalogSelection( - string.IsNullOrEmpty(text) ? null : text, - string.IsNullOrEmpty(key) ? null : key, - root.GetProperty("id").GetInt64(), - root.GetProperty("api_code").GetInt32()); - } - finally - { - owned.Free(); - } - } - [Fact] public unsafe void ConcurrentCalls_AreThreadSafeAcrossNativeAndManagedComponents() { @@ -1469,11 +1372,6 @@ public unsafe void ConcurrentCalls_AreThreadSafeAcrossNativeAndManagedComponents var parts = NumberFlowValue.Split($"{100 + i}", $"{99 + i}"); Assert.Equal("n:0:i:0", parts[^1].Key); - - var sel = SelectCatalogViaNative( - "{\"candidates\":[{\"id\":\"998877\",\"accesskey\":\"KEY\",\"song\":\"Yellow\",\"singer\":\"Coldplay\",\"duration\":266773}]}"u8, - 4, "Yellow", "Coldplay", 266773); - Assert.Equal("998877", sel.Text); }); } finally diff --git a/Tests/MigrationBaseline/M02_SecurityI18nLogBaselineTests.cs b/Tests/MigrationBaseline/M02_SecurityI18nLogBaselineTests.cs index 53d763cc..f06023af 100644 --- a/Tests/MigrationBaseline/M02_SecurityI18nLogBaselineTests.cs +++ b/Tests/MigrationBaseline/M02_SecurityI18nLogBaselineTests.cs @@ -352,7 +352,7 @@ public void DpapiJsonConverter_RoundTripsAndRejectsPlaintextOrInvalidData() [InlineData("")] public void SensitiveDataScrubber_NullOrEmpty_ReturnsEmpty(string? input) { - Assert.Equal(string.Empty, SensitiveDataScrubber.Scrub(input)); + Assert.Equal(string.Empty, SecurityNative.ScrubSensitiveText(input)); } [Fact] @@ -365,9 +365,9 @@ public void SensitiveDataScrubber_GoldenDataset_RedactsSecretsAndPreservesBenign string input = item.GetProperty("input").GetString()!; string expected = item.GetProperty("expected").GetString()!; - string actual = SensitiveDataScrubber.Scrub(input); + string actual = SecurityNative.ScrubSensitiveText(input); Assert.Equal(expected, actual); - Assert.Equal(actual, SensitiveDataScrubber.Scrub(actual)); + Assert.Equal(actual, SecurityNative.ScrubSensitiveText(actual)); foreach (JsonElement secret in item.GetProperty("secrets").EnumerateArray()) { @@ -378,7 +378,7 @@ public void SensitiveDataScrubber_GoldenDataset_RedactsSecretsAndPreservesBenign foreach (JsonElement benign in doc.RootElement.GetProperty("unchanged").EnumerateArray()) { string input = benign.GetString()!; - Assert.Same(input, SensitiveDataScrubber.Scrub(input)); + Assert.Same(input, SecurityNative.ScrubSensitiveText(input)); } } @@ -393,7 +393,7 @@ public void SensitiveDataScrubber_OneMiBPayload_AndConcurrentCalls_Succeed() Assert.True(hugePayload.Length > 1_000_000); - string scrubbed = SensitiveDataScrubber.Scrub(hugePayload); + string scrubbed = SecurityNative.ScrubSensitiveText(hugePayload); Assert.DoesNotContain("StartSecret123456", scrubbed, StringComparison.Ordinal); Assert.DoesNotContain("MidSecretValue", scrubbed, StringComparison.Ordinal); Assert.DoesNotContain("eyJhbGciOiJIUzI1NiJ9", scrubbed, StringComparison.Ordinal); @@ -402,7 +402,7 @@ public void SensitiveDataScrubber_OneMiBPayload_AndConcurrentCalls_Succeed() Parallel.For(0, 24, i => { string line = $"worker={i} api_key=key_{i}_secret999 ghp_abcdef1234567890abcdef"; - string outLine = SensitiveDataScrubber.Scrub(line); + string outLine = SecurityNative.ScrubSensitiveText(line); Assert.Equal($"worker={i} api_key=[REDACTED] [REDACTED]", outLine); }); } @@ -498,35 +498,9 @@ public async Task AppIntegrityService_ComputeFileSha256Async_FileAndStreamPositi } // ========================================================================= - // DiagnosticLogCapturePolicy & RuntimeLog + // RuntimeLog // ========================================================================= - [Fact] - public void DiagnosticLogCapturePolicy_EnforcesPerSecondCapAndConcurrentSafety() - { - var policy = new DiagnosticLogCapturePolicy(); - for (int i = 0; i < DiagnosticLogCapturePolicy.MaxEntriesPerSecond; i++) - { - Assert.True(policy.TryCapture(10_000 + i)); - } - - Assert.False(policy.TryCapture(10_999)); - - // Next 1000ms window resets the counter. - Assert.True(policy.TryCapture(11_000)); - - var concurrentPolicy = new DiagnosticLogCapturePolicy(); - int captured = 0; - Parallel.For(0, 128, _ => - { - if (concurrentPolicy.TryCapture(50_000)) - { - Interlocked.Increment(ref captured); - } - }); - Assert.InRange(captured, 1, DiagnosticLogCapturePolicy.MaxEntriesPerSecond); - } - [Fact] public async Task RuntimeLog_SessionLifecycleScrubbingConcurrencyAndRotation_WorkInIsolatedTempDir() { @@ -614,26 +588,6 @@ void Handler(LogLevel level, string category, string message) => } } - [Fact] - public async Task RuntimeLog_AsyncLogWriter_TruncatesOversizedEntryAndStopsCleanly() - { - string dir = CreateSubDir("async-writer"); - string path = Path.Combine(dir, "writer.log"); - - var writer = new RuntimeLog.AsyncLogWriter(path); - string hugeLine = new string('Z', 70_000); - Assert.True(writer.TryEnqueue(hugeLine, LogLevel.Info)); - await writer.EnqueueFlush(); - - writer.RequestStop(); - Assert.False(writer.TryEnqueue("after-stop", LogLevel.Error)); - await writer.Completion.WaitAsync(TimeSpan.FromSeconds(5)); - - string content = await File.ReadAllTextAsync(path); - Assert.Contains("[truncated]", content, StringComparison.Ordinal); - Assert.DoesNotContain("after-stop", content, StringComparison.Ordinal); - } - // ========================================================================= // CrashReporter // ========================================================================= diff --git a/Tests/MigrationBaseline/M03_SettingsPerfUpdateBaselineTests.cs b/Tests/MigrationBaseline/M03_SettingsPerfUpdateBaselineTests.cs index 4be45618..b3ee7691 100644 --- a/Tests/MigrationBaseline/M03_SettingsPerfUpdateBaselineTests.cs +++ b/Tests/MigrationBaseline/M03_SettingsPerfUpdateBaselineTests.cs @@ -978,45 +978,6 @@ public void SettingsSearchMatcher_NativeExports_HandleInvalidArgsAndSmallBuffers // 6. PerformancePresets & PerformancePresetSession // ─────────────────────────────────────────────────────────────────────────── - [Fact] - public void PerformancePresets_ApplyAndMatch_CoverAllPresetsAndCustomFallback() - { - Assert.Equal(4, PerformancePresetCatalog.All.Count); - - var glassStart = new PerfMonitorSafeHandle.VnPerformancePresetStateV2 - { - IsLiquidGlass = 1, - UseGpuRefraction = 1, - UseUltimateGpu = 0, - GlassTargetFps = 60, - AnimationFps = 144 - }; - - for (int presetId = 0; presetId < VnPerfPresetCount; presetId++) - { - Assert.Equal(VnOk, PerfMonitorSafeHandle.ApplyPresetV2(presetId, in glassStart, out var applied)); - Assert.Equal(VnOk, PerfMonitorSafeHandle.MatchPresetV2(in applied, out int matched)); - Assert.Equal(presetId, matched); - - if (presetId is VnPerfPresetEco or VnPerfPresetEveryday) - { - Assert.Equal((byte)0, applied.IsLiquidGlass); - Assert.Equal((byte)0, applied.UseGpuRefraction); - Assert.Equal((byte)0, applied.UseUltimateGpu); - } - else - { - Assert.Equal((byte)1, applied.IsLiquidGlass); - Assert.Equal((byte)1, applied.UseGpuRefraction); - } - } - - var custom = glassStart; - custom.AnimationFps = 165; - Assert.Equal(VnOk, PerfMonitorSafeHandle.MatchPresetV2(in custom, out int customMatch)); - Assert.Equal(VnPerfSelectionCustom, customMatch); - } - [Fact] public void PerformancePresets_RecommendHardwareTier_ReturnsValidPresetId() { @@ -1085,11 +1046,6 @@ public async Task PerformancePresetSession_ApplyBackupAndRollback_PersistAndRest [Fact] public void PerformancePresets_NativeExports_RejectNullPointersAndInvalidIds() { - var state = new PerfMonitorSafeHandle.VnPerformancePresetStateV2(); - Assert.Equal(VnErrInvalidArg, PerfMonitorSafeHandle.ApplyPresetV2(-1, in state, out _)); - Assert.Equal(VnErrInvalidArg, PerfMonitorSafeHandle.ApplyPresetV2(99, in state, out _)); - Assert.Equal(VnOk, PerfMonitorSafeHandle.DecideSelectionV2(in state, 0, -1, out int activeItem, out _)); - Assert.True(activeItem == -1 || PerformancePresetCatalog.IsValidPresetId(activeItem)); Assert.Equal(VnOk, PerfMonitorSafeHandle.RecommendHardwareTier(out int tier)); Assert.True(PerformancePresetCatalog.IsValidPresetId(tier)); } @@ -1226,24 +1182,6 @@ public void UpdateService_CompareVersions_EnforcesSemVerPrecedence(string left, Assert.Equal(expectedSign, Math.Sign(UpdateService.CompareVersions(left, right))); } - [Fact] - public void UpdateReleaseFeed_GoldenAtomXmlAndEdgeCases_ParseAndRejectDtdAndInvalidArgs() - { - byte[] xmlBytes = File.ReadAllBytes(ResolveGoldenPath("release-feed-atom.xml")); - Assert.Throws(() => UpdaterSafeHandle.ParseAtomReleases(ReadOnlySpan.Empty)); - byte[] oversized = new byte[(2 * 1024 * 1024) + 1]; - Assert.Throws(() => UpdaterSafeHandle.ParseAtomReleases(oversized)); - - var entries = UpdaterSafeHandle.ParseAtomReleases(xmlBytes); - Assert.Equal(3, entries.Count); // 4th entry missing is skipped - Assert.Equal("v99.5.0-beta.2", entries[0].ReleaseTag); - Assert.Equal("v99.4.0", entries[1].ReleaseTag); - Assert.Equal("v99.3.0", entries[2].ReleaseTag); - - byte[] dtdXml = "]>"u8.ToArray(); - Assert.Throws(() => UpdaterSafeHandle.ParseAtomReleases(dtdXml)); - } - [Fact] public async Task UpdateService_OfflineAtomAndApiFeeds_FormatMarkdownPaginateAndVerifySignedManifest() { diff --git a/Tests/MigrationBaseline/M04_PlatformShellBaselineTests.cs b/Tests/MigrationBaseline/M04_PlatformShellBaselineTests.cs index 6f40ac02..818f568d 100644 --- a/Tests/MigrationBaseline/M04_PlatformShellBaselineTests.cs +++ b/Tests/MigrationBaseline/M04_PlatformShellBaselineTests.cs @@ -1124,11 +1124,6 @@ public void Win32AndSystemInterop_InvalidArgsTempFilesDibAndTimers_WorkHeadlessl Assert.Equal(0, surface.MemoryDc); Assert.Equal(0, surface.Bitmap); } - - // LowLevelKeyboardHook disposed before install refuses installation cleanly - var hook = new Win32Interop.LowLevelKeyboardHook((_, _) => false); - hook.Dispose(); - Assert.False(hook.Install()); } [Fact] @@ -1258,14 +1253,9 @@ public async Task StaControllers_IdleFullscreenOverlayHoverNotchManagerAndInvisi // Managed NotchManager with synthetic anchor using var notchMgr = new NotchManager(new NotchSettings { Width = 220, Height = 32 }); - int posUpdated = 0, safeChanged = 0; - notchMgr.PositionUpdated += (_, _) => posUpdated++; - notchMgr.SafeAreaChanged += (_, _) => safeChanged++; notchMgr.GetAnchor = () => new DrawingPoint(500, 10); notchMgr.UpdatePosition(); Assert.Equal(1, notchMgr.GeometryComputeCount); - Assert.Equal(1, posUpdated); - Assert.Equal(1, safeChanged); Assert.Equal(10.0, notchMgr.SafeArea.Top, 6); } @@ -1382,8 +1372,7 @@ public void RustAbi22_M04Exports_AllPresentInRustLibrary() "vn_startup_greeting_policy_utf8", "vn_file_icon_classify_extension_utf8", "vn_file_icon_parse_msc_icon_xml_utf8", - "vn_shell_get_icon_or_thumbnail_utf8", - "vn_win32_send_unicode_text_utf8" + "vn_shell_get_icon_or_thumbnail_utf8" ]; foreach (string export in abi22Exports) { @@ -1570,7 +1559,6 @@ public unsafe void M04SafeHandles_RepeatedCreateDestroy1000CyclesAndErrorPaths_D Assert.Equal(VnErrInvalidArg, PlatformShellNative.vn_file_icon_classify_extension_utf8(null, 0, null)); Assert.Equal(VnErrInvalidArg, PlatformShellNative.vn_file_icon_parse_msc_icon_xml_utf8(null, 0, null)); Assert.Equal(VnErrInvalidArg, PlatformShellNative.vn_shell_get_icon_or_thumbnail_utf8(null, null, null)); - Assert.Equal(VnErrInvalidArg, PlatformShellNative.vn_win32_send_unicode_text_utf8(null, 0, out _, out _)); Assert.Equal(VnErrInvalidArg, PlatformShellNative.vn_shell_calc_centered_bounds_v2(null, null)); Assert.Equal(VnErrInvalidArg, PlatformShellNative.vn_shell_calc_scaled_pixels_v2(double.NaN, 1.0, out _)); Assert.Equal(VnOk, PlatformShellNative.vn_shell_calc_scaled_pixels_v2(100.0, 1.5, out int scaledPx)); @@ -1602,8 +1590,6 @@ public unsafe void M04SafeHandles_RepeatedCreateDestroy1000CyclesAndErrorPaths_D Assert.Equal(0, probeEmpty); Assert.Equal(VnOk, PlatformShellNative.vn_file_icon_compute_evict_count_v2(63, 64, out int evictZero)); Assert.Equal(0, evictZero); - Assert.Equal(VnErrInvalidArg, InputHookSafeHandle.SetRawMouseExcludedHwndRaw(0, 0)); - Assert.Equal(VnErrInvalidArg, ShellCoordinatorSafeHandle.ConfigureHoverRaw(0, default)); } [Fact] diff --git a/Tests/MigrationBaseline/M05_PowerPrivacyNotifyBaselineTests.cs b/Tests/MigrationBaseline/M05_PowerPrivacyNotifyBaselineTests.cs index c85c4c95..f4c021f2 100644 --- a/Tests/MigrationBaseline/M05_PowerPrivacyNotifyBaselineTests.cs +++ b/Tests/MigrationBaseline/M05_PowerPrivacyNotifyBaselineTests.cs @@ -202,13 +202,6 @@ public unsafe void BatteryAndBluetooth_GoldenBehaviorAndBoundaryChecks() Assert.Equal(item.GetProperty("expectedIsBatterySaver").GetBoolean(), selected.IsBatterySaver); } - // Bluetooth battery percentage parsing (M05 ABI 2.2) - foreach (var item in root.GetProperty("btParsePercentageCases").EnumerateArray()) - { - byte[] bytes = item.GetProperty("bytes").EnumerateArray().Select(e => e.GetByte()).ToArray(); - Assert.Equal(item.GetProperty("expected").GetInt32(), M05Native.ParseBtBatteryPercentage(bytes)); - } - // BluetoothMonitorService.DetectDeviceType & ExtractNameStart foreach (var item in root.GetProperty("btDeviceTypeCases").EnumerateArray()) { @@ -280,22 +273,10 @@ private static unsafe void AssertBatteryAndBluetoothNativeInvalidArgs() Assert.Equal(0.0, state.PowerWatts); // Bluetooth ABI 2.2 invalid args - int outVal = 0; VnOwnedBytes ownedName = default; Assert.Equal(VnErrInvalidArg, M05Native.vn_power_bt_detect_device_type(null, 0, null)); Assert.Equal(VnErrInvalidArg, M05Native.vn_power_bt_extract_name_from_id(null, 0, null)); Assert.Equal(VnErrInvalidArg, M05Native.vn_power_bt_extract_name_from_id(null, 1, &ownedName)); - Assert.Equal(VnErrInvalidArg, M05Native.vn_power_bt_parse_percentage(null, 0, null)); - Assert.Equal(VnErrInvalidArg, M05Native.vn_power_bt_parse_percentage(null, 1, &outVal)); - - Assert.Equal(-1, M05Native.ParseBtBatteryPercentage(ReadOnlySpan.Empty)); - Assert.Equal(0, M05Native.ParseBtBatteryPercentage([0])); - Assert.Equal(100, M05Native.ParseBtBatteryPercentage([100])); - Assert.Equal(-1, M05Native.ParseBtBatteryPercentage([101])); - Assert.Equal(-1, M05Native.ParseBtBatteryPercentage([50, 0])); - byte[] hugeBytes = new byte[256]; - hugeBytes[0] = 75; - Assert.Equal(-1, M05Native.ParseBtBatteryPercentage(hugeBytes)); Assert.Equal((int)BluetoothDeviceType.Unknown, M05Native.DetectBtDeviceType(null)); Assert.Equal((int)BluetoothDeviceType.Unknown, M05Native.DetectBtDeviceType(string.Empty)); @@ -941,7 +922,6 @@ public unsafe void ConcurrentCalls_AreThreadSafeAcrossM05Components() }); Assert.Equal(i % 101, info.Percentage); Assert.Equal(BluetoothDeviceType.Headphones, BluetoothMonitorService.DetectDeviceType($"Sony WH-{i}")); - Assert.Equal(i % 101, M05Native.ParseBtBatteryPercentage([(byte)(i % 101)])); // Privacy handle per thread using (var privacy = PrivacyMonitorHandle.Create(0, 1000)) diff --git a/Tests/MigrationBaseline/M06_ImagingColorBaselineTests.cs b/Tests/MigrationBaseline/M06_ImagingColorBaselineTests.cs index c5fee2bf..3002b0c1 100644 --- a/Tests/MigrationBaseline/M06_ImagingColorBaselineTests.cs +++ b/Tests/MigrationBaseline/M06_ImagingColorBaselineTests.cs @@ -121,30 +121,6 @@ public unsafe void DynamicIslandColor_GoldenMathAndPaletteExtraction_MatchBaseli { using var doc = LoadGolden("color-and-palette-cases.json"); - foreach (var c in doc.RootElement.GetProperty("clampedCropRect").EnumerateArray()) - { - var req = new ImagingNative.VnColorRequest - { - Op = ImagingNative.ColorOpClampCrop, - LeftOrH = c.GetProperty("left").ValueKind == JsonValueKind.Null ? double.NaN : c.GetProperty("left").GetDouble(), - TopOrS = c.GetProperty("top").GetDouble(), - RightOrL = c.GetProperty("right").GetDouble(), - BottomOrRatio = c.GetProperty("bottom").GetDouble(), - IsEmpty = c.GetProperty("isEmpty").GetBoolean() ? (byte)1 : (byte)0, - Width = c.GetProperty("pixelWidth").GetInt32(), - Height = c.GetProperty("pixelHeight").GetInt32(), - }; - - ImagingNative.VnCoreRect outRect = default; - byte valid = 99; - Assert.Equal(VnOk, ImagingNative.vn_dicolor_clamp_crop_v2(&req, &outRect, &valid)); - Assert.Equal(c.GetProperty("expectedValid").GetBoolean() ? (byte)1 : (byte)0, valid); - Assert.Equal(c.GetProperty("expectedX").GetInt32(), outRect.X); - Assert.Equal(c.GetProperty("expectedY").GetInt32(), outRect.Y); - Assert.Equal(c.GetProperty("expectedW").GetInt32(), outRect.Width); - Assert.Equal(c.GetProperty("expectedH").GetInt32(), outRect.Height); - } - foreach (var c in doc.RootElement.GetProperty("adaptiveBlurOpacity").EnumerateArray()) { double lum = c.GetProperty("luminance").ValueKind == JsonValueKind.Null ? double.NaN : c.GetProperty("luminance").GetDouble(); @@ -754,35 +730,7 @@ public void ThumbnailHeuristics_Profile24x24_And_SmtcDecisions_MatchGolden() }; int decision = ImagingNative.DecideSmtcThumbnail(in inputs); Assert.Equal(c.GetProperty("expected").GetInt32(), decision); - - var managedDecision = ThumbnailHeuristics.DecideSmtcThumbnail(new ThumbnailHeuristics.SmtcThumbnailInputs - { - IsYouTubeLikeSource = inputs.IsYouTubeLikeSource != 0, - IsSoundCloudSource = inputs.IsSoundCloudSource != 0, - IsBrowserOrYouTubePlatform = inputs.IsBrowserOrYouTubePlatform != 0, - IsBrowserSession = inputs.IsBrowserSession != 0, - TrackChanged = inputs.TrackChanged != 0, - BrowserSessionChanged = inputs.BrowserSessionChanged != 0, - HasVerifiedYouTubeThumb = inputs.HasVerifiedYouTubeThumb != 0, - HasVerifiedSoundCloudThumb = inputs.HasVerifiedSoundCloudThumb != 0, - LikelySoundCloudArtwork = inputs.LikelySoundCloudArtwork != 0, - RecentTrackChange = inputs.RecentTrackChange != 0, - CachedThumbnailIsNull = inputs.CachedThumbnailIsNull != 0, - PixelWidth = inputs.PixelWidth, - PixelHeight = inputs.PixelHeight, - }); - Assert.Equal((ThumbnailHeuristics.SmtcThumbnailDecision)decision, managedDecision); } - - // Managed bitmap heuristics - Assert.True(ThumbnailHeuristics.IsLikelyPlaceholderThumbnail(null)); - Assert.False(ThumbnailHeuristics.IsLikelyArtworkCandidate(null)); - var nonSquare = CreateFrozenBitmap(160, 90, CreateSolidBgra(160, 90, 640, 230, 230, 230, 255), 640); - Assert.False(ThumbnailHeuristics.IsLikelyPlaceholderThumbnail(nonSquare)); - Assert.False(ThumbnailHeuristics.IsLikelyArtworkCandidate(nonSquare)); - var flatLightSquare = CreateFrozenBitmap(200, 200, CreateSolidBgra(200, 200, 800, 230, 230, 230, 255), 800); - Assert.True(ThumbnailHeuristics.IsLikelyPlaceholderThumbnail(flatLightSquare)); - Assert.True(ThumbnailHeuristics.HasLowEntropyMonochromeProfile(flatLightSquare)); } [Fact] @@ -956,7 +904,6 @@ public unsafe void AbiV2_PodSizes_And_SafeHandles_And_ErrorPaths_Pass() int dec = 0; byte flag = 0; Assert.Equal(VnErrInvalidArg, ImagingNative.vn_dicolor_extract_palette_v2(null, &pal)); - Assert.Equal(VnErrInvalidArg, ImagingNative.vn_dicolor_clamp_crop_v2(null, &rect, &flag)); Assert.Equal(VnErrInvalidArg, ImagingNative.vn_dicolor_ensure_contrast_v2(null, &col)); Assert.Equal(VnErrInvalidArg, ImagingNative.vn_dicolor_eval_v2(null, &col)); Assert.Equal(VnErrInvalidArg, ImagingNative.vn_blur_process_bgra32_v2(null)); @@ -969,8 +916,6 @@ public unsafe void AbiV2_PodSizes_And_SafeHandles_And_ErrorPaths_Pass() // Raw destroy error-path checks Assert.Equal(VnOk, SmartCropEngineSafeHandle.DestroyRaw(0)); Assert.Equal(VnOk, SmartCropEngineSafeHandle.DestroyRaw(-1)); - Assert.Equal(VnOk, SmartCropSessionSafeHandle.DestroyRaw(0)); - Assert.Equal(VnOk, SmartCropSessionSafeHandle.DestroyRaw(-1)); // Repeated SmartCropEngineSafeHandle create/use/dispose leak check string validDir = AppContext.BaseDirectory; @@ -1014,29 +959,5 @@ public unsafe void AbiV2_PodSizes_And_SafeHandles_And_ErrorPaths_Pass() Assert.Throws(() => disposedEngine.Unload(true)); Assert.Throws(() => disposedEngine.AnalyzeBgra32(default, out _)); Assert.Throws(() => disposedEngine.CropBgra32(default, out _)); - - // SmartCropSessionSafeHandle create/infer/cancel/dispose check when model + ORT exist - bool hasOrt = File.Exists(Path.Combine(validDir, "onnxruntime.dll")) || - File.Exists(Path.Combine(validDir, "runtimes", "win-x64", "native", "onnxruntime.dll")); - if (File.Exists(modelPath) && hasOrt) - { - var dets = new ImagingNative.VnCoreDetection[SmartCropSessionSafeHandle.MinDetectionCapacity]; - for (int cycle = 0; cycle < 4; cycle++) - { - var (session, usedDml) = SmartCropSessionSafeHandle.Create(modelPath, validDir, preferDml: false); - using (session) - { - Assert.False(session.IsInvalid); - Assert.False(usedDml); - session.Cancel(); - int count = session.Infer(sampleImg, 160, 96, 160 * 4, dets, out bool inferDml); - Assert.InRange(count, 0, dets.Length); - Assert.False(inferDml); - } - - Assert.Throws(() => session.Cancel()); - Assert.Throws(() => session.Infer(sampleImg, 160, 96, 160 * 4, dets, out _)); - } - } } } diff --git a/Tests/MigrationBaseline/M08_ClipboardBaselineTests.cs b/Tests/MigrationBaseline/M08_ClipboardBaselineTests.cs index c4584eeb..2572506a 100644 --- a/Tests/MigrationBaseline/M08_ClipboardBaselineTests.cs +++ b/Tests/MigrationBaseline/M08_ClipboardBaselineTests.cs @@ -272,7 +272,7 @@ public async Task DropReader_DataObjectAndDataUriResolution_WorkOffline() } [Fact] - public async Task DirectoryImportSafety_And_NativeBufferStream_WorkOffline() + public async Task DirectoryImportSafety_WorksOffline() { string scanRoot = CreateSubDir("scan"); string f1 = Path.Combine(scanRoot, "a.txt"); @@ -284,19 +284,6 @@ public async Task DirectoryImportSafety_And_NativeBufferStream_WorkOffline() await Assert.ThrowsAsync(() => store.ImportAsync(new ClipboardCapture { FilePaths = [@"\??\C:\file.txt"] })); var okImport = await store.ImportAsync(new ClipboardCapture { FilePaths = [f1] }); Assert.NotNull(okImport.Entry); - - byte[] largeBytes = new byte[150_000]; - for (int i = 0; i < largeBytes.Length; i++) largeBytes[i] = (byte)(i % 251); - - using var dst = new NativeBufferStream(); - dst.Write(largeBytes, 0, largeBytes.Length); - Assert.Equal(largeBytes, dst.ReadBuffered(static b => b.ToArray())); - dst.SetLength(10); - Assert.Equal(10, dst.Length); - dst.Seek(-4, SeekOrigin.End); - byte[] tail = new byte[4]; - Assert.Equal(4, dst.Read(tail, 0, 4)); - Assert.Equal(largeBytes[6..10], tail); } [Fact] @@ -554,9 +541,21 @@ public unsafe void Abi22_PodLayouts_SafeHandleLeaks_ErrorPaths_AndStatelessEvalu Assert.NotEqual(VnOk, M08Native.vn_clipboard_store_open(0, null, out _)); Assert.Equal(VnErrInvalidArg, M08Native.vn_clipboard_store_close(0)); Assert.Equal(VnErrInvalidArg, M08Native.vn_clipboard_store_close(-1)); - Assert.Throws(() => ClipboardStoreSafeHandle.Open("", M08Native.VnClipboardPolicyPod.CreateDefault())); - - var policy = M08Native.VnClipboardPolicyPod.CreateDefault(); + var policy = new M08Native.VnClipboardPolicyPod + { + MaxUnpinnedEntries = M08Native.DefaultMaxUnpinnedEntries, + RetentionDays = M08Native.DefaultRetentionDays, + SensitiveTtlSeconds = M08Native.DefaultSensitiveTtlSeconds, + MaxImportItems = M08Native.DefaultMaxImportItems, + MaxImportContents = M08Native.DefaultMaxImportContents, + AutoDeleteSensitive = 1, + AllowNetworkArtwork = 0, + MaxUnpinnedBytes = M08Native.DefaultMaxUnpinnedBytes, + ApprovalThresholdBytes = M08Native.DefaultApprovalThresholdBytes, + MaxArchiveExtractBytes = M08Native.DefaultMaxArchiveExtractBytes, + MaxDropImageBytes = M08Native.DefaultMaxDropImageBytes, + }; + Assert.Throws(() => ClipboardStoreSafeHandle.Open("", policy)); using var pin = MakePin("135790"); string leakRoot = CreateSubDir("abi22-leak"); for (int cycle = 0; cycle < 20; cycle++) diff --git a/Tests/MigrationBaseline/M10_MediaLyricsBaselineTests.cs b/Tests/MigrationBaseline/M10_MediaLyricsBaselineTests.cs index 7dca34ca..02f5acf4 100644 --- a/Tests/MigrationBaseline/M10_MediaLyricsBaselineTests.cs +++ b/Tests/MigrationBaseline/M10_MediaLyricsBaselineTests.cs @@ -79,63 +79,11 @@ private sealed class StubAudioVolume : IMediaAudioVolume } [Fact] - public void Golden_LyricsParsing_LrcEnhancedTtmlAndTimedJson_MatchExpectedOutputs() + public void Golden_LyricsProviderOrder_MatchExpectedOutputs() { using var doc = LoadGoldenJson("lyrics-parsing-cases.json"); var root = doc.RootElement; - foreach (var lrcCase in root.GetProperty("lrcCases").EnumerateArray()) - { - string lrc = lrcCase.GetProperty("lrc").GetString()!; - var lines = M10Native.ParseLyricsText(lrc, M10Native.LyricKindLrc); - var expected = lrcCase.GetProperty("expectedLines").EnumerateArray().ToArray(); - Assert.Equal(expected.Length, lines.Count); - for (int i = 0; i < expected.Length; i++) - { - Assert.Equal(expected[i].GetProperty("timeMs").GetInt64(), (long)lines[i].Time.TotalMilliseconds); - Assert.Equal(expected[i].GetProperty("text").GetString(), lines[i].Text); - if (expected[i].TryGetProperty("words", out var wordsProp)) - { - var expWords = wordsProp.EnumerateArray().ToArray(); - Assert.NotNull(lines[i].Words); - Assert.Equal(expWords.Length, lines[i].Words!.Length); - for (int w = 0; w < expWords.Length; w++) - { - Assert.Equal(expWords[w].GetProperty("startMs").GetInt64(), (long)lines[i].Words![w].Start.TotalMilliseconds); - Assert.Equal(expWords[w].GetProperty("endMs").GetInt64(), (long)lines[i].Words![w].End.TotalMilliseconds); - Assert.Equal(expWords[w].GetProperty("offset").GetInt32(), lines[i].Words![w].Offset); - Assert.Equal(expWords[w].GetProperty("length").GetInt32(), lines[i].Words![w].Length); - } - } - } - } - - foreach (var ttmlCase in root.GetProperty("ttmlCases").EnumerateArray()) - { - byte[] xmlBytes = Encoding.UTF8.GetBytes(ttmlCase.GetProperty("xml").GetString()!); - var lines = M10Native.ParseLyricsBlob(xmlBytes, M10Native.LyricKindTtml); - var expLines = ttmlCase.GetProperty("expectedLines").EnumerateArray().ToArray(); - Assert.Equal(expLines.Length, lines.Count); - Assert.Equal(expLines[0].GetProperty("text").GetString(), lines[0].Text); - Assert.NotNull(lines[0].Words); - Assert.Equal(expLines[0].GetProperty("words").GetArrayLength(), lines[0].Words!.Length); - } - - foreach (var jsonCase in root.GetProperty("timedJsonCases").EnumerateArray()) - { - int kind = jsonCase.GetProperty("kind").GetInt32(); - string json = jsonCase.GetProperty("json").GetString()!; - byte[] jsonBytes = Encoding.UTF8.GetBytes(json); - var lines = M10Native.ParseLyricsBlob(jsonBytes, kind); - var expLines = jsonCase.GetProperty("expectedLines").EnumerateArray().ToArray(); - Assert.Equal(expLines.Length, lines.Count); - for (int i = 0; i < expLines.Length; i++) - { - Assert.Equal(expLines[i].GetProperty("timeMs").GetInt64(), (long)lines[i].Time.TotalMilliseconds); - Assert.Equal(expLines[i].GetProperty("text").GetString(), lines[i].Text); - } - } - foreach (var orderCase in root.GetProperty("providerOrderCases").EnumerateArray()) { var rawProp = orderCase.GetProperty("raw"); @@ -145,48 +93,6 @@ public void Golden_LyricsParsing_LrcEnhancedTtmlAndTimedJson_MatchExpectedOutput } } - [Fact] - public void NativeLyrics_KrcDecodeYrcWordMapAndConcurrent_BehaveDeterministically() - { - const string krcText = "[1000,1500]<0,500,0>Hel<500,1000,0>lo\n[0,100]作词:Test"; - byte[] compressed; - using (var ms = new MemoryStream()) - { - using (var zs = new ZLibStream(ms, CompressionLevel.Fastest, leaveOpen: true)) - { - byte[] utf8 = Encoding.UTF8.GetBytes(krcText); - zs.Write(utf8, 0, utf8.Length); - } - compressed = ms.ToArray(); - } - byte[] krcKey = [64, 71, 97, 119, 94, 50, 116, 71, 81, 54, 49, 45, 206, 210, 110, 105]; - byte[] rawKrc = new byte[4 + compressed.Length]; - Encoding.ASCII.GetBytes("krc1", rawKrc); - for (int i = 0; i < compressed.Length; i++) - { - rawKrc[4 + i] = (byte)(compressed[i] ^ krcKey[i & 15]); - } - - string decodedText = M10Native.DecodeKrc(rawKrc); - var krcLines = M10Native.ParseLyricsText(decodedText, M10Native.LyricKindKugouKrc); - Assert.Single(krcLines); - Assert.Equal("Hello", krcLines[0].Text); - Assert.Equal(2, krcLines[0].Words!.Length); - - const string wordMapJson = "{\"lines\":[{\"id\":0,\"start\":1000,\"text\":\"Hi all\"}],\"wordMap\":[[{\"start\":1000,\"end\":1300,\"text\":\"Hi\"},{\"start\":1300,\"end\":1800,\"text\":\"all\"}]]}"; - var mappedLines = M10Native.ParseLyricsBlob(Encoding.UTF8.GetBytes(wordMapJson), M10Native.LyricKindTimedJsonStartEnd); - Assert.Single(mappedLines); - Assert.Equal(2, mappedLines[0].Words!.Length); - - Parallel.For(0, 32, i => - { - string payload = $"[00:01.00]Parallel line {i}\n[00:02.50]Second {i}"; - var parsed = M10Native.ParseLyricsText(payload, M10Native.LyricKindLrc); - Assert.Equal(2, parsed.Count); - Assert.Equal($"Parallel line {i}", parsed[0].Text); - }); - } - [Fact] public async Task LyricsService_FacadeLifecycleAndGuardClauses_BehaveDeterministically() { @@ -198,7 +104,7 @@ public async Task LyricsService_FacadeLifecycleAndGuardClauses_BehaveDeterminist } [Fact] - public void Golden_YouTubeVideoIdAndSpotifyTotp_MatchExpectedOutputs() + public void Golden_YouTubeVideoId_MatchExpectedOutputs() { using var doc = LoadGoldenJson("platform-link-metadata-cases.json"); var root = doc.RootElement; @@ -217,11 +123,6 @@ public void Golden_YouTubeVideoIdAndSpotifyTotp_MatchExpectedOutputs() Assert.Null(actualId); } } - - var sp = root.GetProperty("spotifyMatching"); - byte[] secret = Convert.FromHexString(sp.GetProperty("totpTestSecretHex").GetString()!); - long tsMs = sp.GetProperty("totpTestTimestampMs").GetInt64(); - Assert.Equal(sp.GetProperty("expectedRfcTotp6").GetString(), M10Native.GenerateSpotifyTotp(secret, tsMs)); } [Fact] @@ -405,29 +306,15 @@ public void AbiV2_SafeHandleCreateDestroy_And_StatelessErrorPaths_DoNotLeakOrFai Assert.Throws(() => disposedEngine.GetSnapshotJson()); Assert.Throws(() => disposedEngine.ProgressTick(0)); - Assert.Throws(() => M10Native.ParseLyricsBlob("[]"u8, kind: 99)); - Assert.Throws(() => M10Native.DecodeKrc("bad01234"u8)); - Assert.Throws(() => M10Native.GenerateSpotifyTotp(ReadOnlySpan.Empty, 0)); - byte[] invalidPixels = [0, 1, 2, 3]; Assert.False(M10Native.TryDetectArtworkBounds(invalidPixels, stride: -4, sw: 8, sh: 8, width: 8, height: 8, scaleX: 1.0, scaleY: 1.0, out _)); Assert.False(M10Native.TryDetectArtworkBounds(invalidPixels, stride: 32, sw: 8, sh: 8, width: 8, height: 8, scaleX: 0.0, scaleY: 1.0, out _)); - const string emojiTtml = "

🎵 Đây

"; - var parsedEmoji = M10Native.ParseLyricsText(emojiTtml, M10Native.LyricKindTtml); - Assert.Single(parsedEmoji); - Assert.Equal("🎵 Đây", parsedEmoji[0].Text); - Assert.Equal(new[] { 0, 3 }, parsedEmoji[0].Words!.Select(w => w.Offset)); - Assert.Equal(new[] { 2, 3 }, parsedEmoji[0].Words!.Select(w => w.Length)); Assert.Equal("1:05:09", M10Native.FormatProgressTime(new TimeSpan(1, 5, 9))); Assert.Equal("dQw4w9WgXcQ", M10Native.ExtractYouTubeVideoId("https://www.youtube.com/watch?v=dQw4w9WgXcQ")); Assert.Null(M10Native.ExtractYouTubeVideoId("not a youtube id")); - var aliases = M10Native.GetVolumeProcessAliases(); - Assert.Contains(aliases, a => string.Equals(a.Token, "spotify", StringComparison.OrdinalIgnoreCase)); - Assert.True(M10Native.VolumeContainsSourceToken("Spotify Free", "spotify")); - Assert.True(M10Native.VolumeMatchesExecutable(@"C:\App\msedge.exe", "msedge;chrome")); Assert.True(M10Native.VolumeSessionMatchesSource("Spotify", "", "", "Spotify.exe")); var scoreReq = new M10Native.VnVolumeSessionScoreReq { Pid = 10, LastPid = 10, State = 1, ProcessMatch = 1, SameSource = 1 }; Assert.True(M10Native.ComputeVolumeSessionScore(in scoreReq) > 10_000.0); diff --git a/Tests/MigrationBaseline/M11_TranslationBaselineTests.cs b/Tests/MigrationBaseline/M11_TranslationBaselineTests.cs index 3f94c759..6c6c033b 100644 --- a/Tests/MigrationBaseline/M11_TranslationBaselineTests.cs +++ b/Tests/MigrationBaseline/M11_TranslationBaselineTests.cs @@ -372,8 +372,6 @@ public unsafe void HardwareOptionsAndErrorPaths_WorkDeterministically() { ownedRec.Free(); } - - Assert.Equal(VnErrInvalidArg, M11Native.vn_transoptions_can_reuse_cached_v2(null, null, null)); } [Fact] diff --git a/Tests/MigrationBaseline/M12_GlassGpuBaselineTests.cs b/Tests/MigrationBaseline/M12_GlassGpuBaselineTests.cs index 9f404692..2c5d14ae 100644 --- a/Tests/MigrationBaseline/M12_GlassGpuBaselineTests.cs +++ b/Tests/MigrationBaseline/M12_GlassGpuBaselineTests.cs @@ -151,13 +151,6 @@ private static unsafe partial int vn_glass_should_submit_frame_v2( M12Native.VnGlassSubmitFrameReq* req, byte* outShouldSubmit); - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_glass_score_d3d9_adapter_utf8( - byte* description, - int len, - uint vendorId, - long* outScore); - [LibraryImport(NativeAbi.RustLibraryName)] private static unsafe partial int vn_glass_display_cadence_get_refresh_rate_v2( nint hwnd, @@ -874,29 +867,6 @@ public unsafe void RenderPolicyAndDisplayCadence_MatchGoldenDataset_AndValidateI }; Assert.Equal(VnErrInvalidArg, vn_glass_should_submit_frame_v2(&submitReq, null)); - foreach (JsonElement ai in doc.RootElement.GetProperty("adapterScores").EnumerateArray()) - { - string desc = ai.GetProperty("description").GetString()!; - uint vendorId = ai.GetProperty("vendorId").GetUInt32(); - long score = 0; - byte[] utf8 = Encoding.UTF8.GetBytes(desc); - fixed (byte* dPtr = utf8) - { - int rc = vn_glass_score_d3d9_adapter_utf8(dPtr, utf8.Length, vendorId, &score); - Assert.Equal(ai.GetProperty("status").GetInt32(), rc); - } - - Assert.Equal(ai.GetProperty("score").GetInt64(), score); - } - - long dummyScore = 0; - Assert.Equal(VnErrInvalidArg, vn_glass_score_d3d9_adapter_utf8(null, 0, 0, null)); - Assert.Equal(VnErrInvalidArg, vn_glass_score_d3d9_adapter_utf8(null, 3, 0, &dummyScore)); - byte zeroByte = 0; - Assert.Equal(VnErrInvalidArg, vn_glass_score_d3d9_adapter_utf8(&zeroByte, -1, 0, &dummyScore)); - Assert.Equal(VnOk, vn_glass_score_d3d9_adapter_utf8(&zeroByte, 0, 0, &dummyScore)); - Assert.Equal(100L, dummyScore); - byte hasVal = 1; int outHz = 99; Assert.Equal(VnErrInvalidArg, vn_glass_display_cadence_get_refresh_rate_v2(IntPtr.Zero, null, &outHz)); @@ -1338,14 +1308,6 @@ public unsafe void AbiV2_SafeHandleErrorPathsAndCreateDestroyCycles_DoNotLeak() Assert.Equal((int)NativeStatus.Ok, MagnifierCaptureSafeHandle.DestroyRaw(999_999_999)); - var preparedFrame = new M12Native.VnGpuFrame { Width = 32, Height = 32, Blur = 0.25f }; - preparedFrame.Lens[0] = 64f; - preparedFrame.Lens[4] = 64f; - preparedFrame.Lens[8] = 32f; - preparedFrame.Lens[12] = 32f; - M12Native.PrepareGpuFrame(ref preparedFrame); - Assert.True(preparedFrame.Lens[1] > 0f); - SharedStaTestRunner.Run(() => { var window = new Window { Width = 64, Height = 64, ShowActivated = false, ShowInTaskbar = false }; @@ -1379,7 +1341,6 @@ public unsafe void AbiV2_SafeHandleErrorPathsAndCreateDestroyCycles_DoNotLeak() Assert.True(handle.CheckDevice(hwnd)); handle.SetInterval(16.0); handle.Reset(); - Assert.NotEqual(0, handle.GetD3D9Device()); var diag = handle.GetDiagnostics(); Assert.Equal(0UL, diag.CaptureFramesDelta); Assert.Throws(() => handle.WaitReady(9)); diff --git a/Tests/MigrationBaseline/M13_WebcamBaselineTests.cs b/Tests/MigrationBaseline/M13_WebcamBaselineTests.cs index 45b22af0..b7cffc17 100644 --- a/Tests/MigrationBaseline/M13_WebcamBaselineTests.cs +++ b/Tests/MigrationBaseline/M13_WebcamBaselineTests.cs @@ -22,7 +22,6 @@ public sealed partial class M13_WebcamBaselineTests : IDisposable private const int HResultFalse = 1; private const int HResultNoInterface = unchecked((int)0x80004002); private const int HResultInvalidArg = unchecked((int)0x80070057); - private const int MaxPixelCount = int.MaxValue / 4; private readonly string _tempRoot; @@ -68,532 +67,6 @@ private static string GetGoldenPath(string fileName) private static JsonDocument LoadGoldenJson(string fileName) => JsonDocument.Parse(File.ReadAllText(GetGoldenPath(fileName), Encoding.UTF8)); - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_webcam_convert_rgb_in_place( - byte* pixels, - int length, - byte is_rgba, - int alpha_mode); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_webcam_convert_gray8_to_bgra8( - byte* src, - int pixel_count, - byte* dst); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_webcam_convert_nv12_to_bgra8( - byte* src, - int width, - int height, - byte* dst); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static unsafe partial int vn_webcam_convert_yuy2_to_bgra8( - byte* src, - int pixel_count, - byte* dst); - - private static (byte b, byte g, byte r, byte a) ScalarBt601ToBgra(int y, int u, int v) - { - int lum = 298 * (y - 16); - int bd = u - 128; - int rd = v - 128; - int b = Math.Clamp((lum + 516 * bd + 128) >> 8, 0, 255); - int g = Math.Clamp((lum - 100 * bd - 208 * rd + 128) >> 8, 0, 255); - int r = Math.Clamp((lum + 409 * rd + 128) >> 8, 0, 255); - return ((byte)b, (byte)g, (byte)r, 255); - } - - [Fact] - public unsafe void ConvertRgbInPlace_MatchesGoldenVectors_And_RejectsInvalidArgs() - { - using var doc = LoadGoldenJson("rgb-in-place-cases.json"); - foreach (var item in doc.RootElement.GetProperty("cases").EnumerateArray()) - { - int length = item.GetProperty("length").GetInt32(); - byte isRgba = item.GetProperty("isRgba").GetByte(); - int alphaMode = item.GetProperty("alphaMode").GetInt32(); - int expectedStatus = item.GetProperty("expectedStatus").GetInt32(); - byte[] buf = Convert.FromBase64String(item.GetProperty("inputBase64").GetString()!); - byte[] expected = Convert.FromBase64String(item.GetProperty("expectedBase64").GetString()!); - - fixed (byte* p = buf) - { - int rc = vn_webcam_convert_rgb_in_place(p, length, isRgba, alphaMode); - Assert.Equal(expectedStatus, rc); - } - - Assert.Equal(expected, buf); - } - - byte[] dummy = new byte[4]; - fixed (byte* pDummy = dummy) - { - Assert.Equal(VnErrInvalidArg, vn_webcam_convert_rgb_in_place(null, 0, 1, 0)); - Assert.Equal(VnErrInvalidArg, vn_webcam_convert_rgb_in_place(null, 16, 0, 2)); - - foreach (var invalid in doc.RootElement.GetProperty("invalidCases").EnumerateArray()) - { - int badLen = invalid.GetProperty("length").GetInt32(); - byte isRgba = invalid.GetProperty("isRgba").GetByte(); - int alphaMode = invalid.GetProperty("alphaMode").GetInt32(); - int expectedStatus = invalid.GetProperty("expectedStatus").GetInt32(); - Assert.Equal(expectedStatus, vn_webcam_convert_rgb_in_place(pDummy, badLen, isRgba, alphaMode)); - } - } - } - - [Fact] - public unsafe void ConvertGray8ToBgra8_MatchesGoldenVectors_And_RejectsInvalidArgs() - { - using var doc = LoadGoldenJson("gray8-to-bgra8-cases.json"); - foreach (var item in doc.RootElement.GetProperty("cases").EnumerateArray()) - { - int pixelCount = item.GetProperty("pixelCount").GetInt32(); - int expectedStatus = item.GetProperty("expectedStatus").GetInt32(); - byte[] src = Convert.FromBase64String(item.GetProperty("srcBase64").GetString()!); - byte[] expected = Convert.FromBase64String(item.GetProperty("expectedBase64").GetString()!); - - // Pad dst with 4 sentinel bytes to prove out-of-bounds writes do not occur. - byte[] dst = new byte[expected.Length + 4]; - Array.Fill(dst, (byte)0xCD); - byte[] srcPinned = src.Length == 0 ? new byte[1] : src; - - fixed (byte* pSrc = srcPinned) - fixed (byte* pDst = dst) - { - int rc = vn_webcam_convert_gray8_to_bgra8(pSrc, pixelCount, pDst); - Assert.Equal(expectedStatus, rc); - } - - Assert.Equal(expected, dst.AsSpan(0, expected.Length).ToArray()); - Assert.All(dst.AsSpan(expected.Length).ToArray(), b => Assert.Equal(0xCD, b)); - } - - byte[] dummy = new byte[4]; - fixed (byte* pDummy = dummy) - { - Assert.Equal(VnErrInvalidArg, vn_webcam_convert_gray8_to_bgra8(null, 0, pDummy)); - Assert.Equal(VnErrInvalidArg, vn_webcam_convert_gray8_to_bgra8(pDummy, 0, null)); - Assert.Equal(VnErrInvalidArg, vn_webcam_convert_gray8_to_bgra8(null, 4, null)); - Assert.Equal(VnErrInvalidArg, vn_webcam_convert_gray8_to_bgra8(pDummy, MaxPixelCount + 1, pDummy)); - - foreach (var invalid in doc.RootElement.GetProperty("invalidCases").EnumerateArray()) - { - int badCount = invalid.GetProperty("pixelCount").GetInt32(); - int expectedStatus = invalid.GetProperty("expectedStatus").GetInt32(); - Assert.Equal(expectedStatus, vn_webcam_convert_gray8_to_bgra8(pDummy, badCount, pDummy)); - } - } - } - - [Fact] - public unsafe void ConvertNv12ToBgra8_MatchesGoldenVectors_And_RejectsOddOrInvalidDimensions() - { - using var doc = LoadGoldenJson("nv12-to-bgra8-cases.json"); - foreach (var item in doc.RootElement.GetProperty("cases").EnumerateArray()) - { - int width = item.GetProperty("width").GetInt32(); - int height = item.GetProperty("height").GetInt32(); - int expectedStatus = item.GetProperty("expectedStatus").GetInt32(); - byte[] src = Convert.FromBase64String(item.GetProperty("srcBase64").GetString()!); - byte[] expected = Convert.FromBase64String(item.GetProperty("expectedBase64").GetString()!); - - byte[] dst = new byte[expected.Length + 8]; - Array.Fill(dst, (byte)0xCD); - - fixed (byte* pSrc = src) - fixed (byte* pDst = dst) - { - int rc = vn_webcam_convert_nv12_to_bgra8(pSrc, width, height, pDst); - Assert.Equal(expectedStatus, rc); - } - - Assert.Equal(expected, dst.AsSpan(0, expected.Length).ToArray()); - Assert.All(dst.AsSpan(expected.Length).ToArray(), b => Assert.Equal(0xCD, b)); - } - - byte[] dummy = new byte[16]; - fixed (byte* pDummy = dummy) - { - Assert.Equal(VnErrInvalidArg, vn_webcam_convert_nv12_to_bgra8(null, 2, 2, pDummy)); - Assert.Equal(VnErrInvalidArg, vn_webcam_convert_nv12_to_bgra8(pDummy, 2, 2, null)); - - foreach (var invalid in doc.RootElement.GetProperty("invalidCases").EnumerateArray()) - { - int w = invalid.GetProperty("width").GetInt32(); - int h = invalid.GetProperty("height").GetInt32(); - int expectedStatus = invalid.GetProperty("expectedStatus").GetInt32(); - Assert.Equal(expectedStatus, vn_webcam_convert_nv12_to_bgra8(pDummy, w, h, pDummy)); - } - } - } - - [Fact] - public unsafe void ConvertYuy2ToBgra8_MatchesGoldenVectors_And_RejectsInvalidArgs() - { - using var doc = LoadGoldenJson("yuy2-to-bgra8-cases.json"); - foreach (var item in doc.RootElement.GetProperty("cases").EnumerateArray()) - { - int pixelCount = item.GetProperty("pixelCount").GetInt32(); - int expectedStatus = item.GetProperty("expectedStatus").GetInt32(); - byte[] src = Convert.FromBase64String(item.GetProperty("srcBase64").GetString()!); - byte[] expected = Convert.FromBase64String(item.GetProperty("expectedBase64").GetString()!); - - byte[] dst = new byte[expected.Length + 8]; - Array.Fill(dst, (byte)0xCD); - byte[] srcPinned = src.Length == 0 ? new byte[1] : src; - - fixed (byte* pSrc = srcPinned) - fixed (byte* pDst = dst) - { - int rc = vn_webcam_convert_yuy2_to_bgra8(pSrc, pixelCount, pDst); - Assert.Equal(expectedStatus, rc); - } - - Assert.Equal(expected, dst.AsSpan(0, expected.Length).ToArray()); - Assert.All(dst.AsSpan(expected.Length).ToArray(), b => Assert.Equal(0xCD, b)); - } - - byte[] dummy = new byte[8]; - fixed (byte* pDummy = dummy) - { - Assert.Equal(VnErrInvalidArg, vn_webcam_convert_yuy2_to_bgra8(null, 0, pDummy)); - Assert.Equal(VnErrInvalidArg, vn_webcam_convert_yuy2_to_bgra8(pDummy, 0, null)); - - foreach (var invalid in doc.RootElement.GetProperty("invalidCases").EnumerateArray()) - { - int badCount = invalid.GetProperty("pixelCount").GetInt32(); - int expectedStatus = invalid.GetProperty("expectedStatus").GetInt32(); - Assert.Equal(expectedStatus, vn_webcam_convert_yuy2_to_bgra8(pDummy, badCount, pDummy)); - } - } - } - - [Fact] - public unsafe void PixelConverters_Huge1920x1080_FullFrame_MatchScalarReference() - { - const int width = 1920; - const int height = 1080; - const int pixels = width * height; - const int bgraBytes = pixels * 4; - - // 1. RGB in-place (RGBA8 Straight -> BGRA8 Premultiplied) - byte[] rgb = new byte[bgraBytes]; - for (int i = 0; i < pixels; i++) - { - int o = i * 4; - rgb[o] = (byte)(i & 0xFF); - rgb[o + 1] = (byte)((i * 3) & 0xFF); - rgb[o + 2] = (byte)((i * 7) & 0xFF); - rgb[o + 3] = (byte)((i * 11) & 0xFF); - } - fixed (byte* pRgb = rgb) - { - Assert.Equal(VnOk, vn_webcam_convert_rgb_in_place(pRgb, rgb.Length, 1, 1)); - } - for (int i = 0; i < pixels; i += 97) - { - int o = i * 4; - byte origR = (byte)(i & 0xFF); - byte origG = (byte)((i * 3) & 0xFF); - byte origB = (byte)((i * 7) & 0xFF); - byte a = (byte)((i * 11) & 0xFF); - Assert.Equal((byte)((origB * a + 127) / 255), rgb[o]); - Assert.Equal((byte)((origG * a + 127) / 255), rgb[o + 1]); - Assert.Equal((byte)((origR * a + 127) / 255), rgb[o + 2]); - Assert.Equal(a, rgb[o + 3]); - } - - // 2. Gray8 -> BGRA8 - byte[] gray = new byte[pixels]; - for (int i = 0; i < pixels; i++) - { - gray[i] = (byte)((i * 13) & 0xFF); - } - byte[] dst = new byte[bgraBytes]; - fixed (byte* pGray = gray) - fixed (byte* pDst = dst) - { - Assert.Equal(VnOk, vn_webcam_convert_gray8_to_bgra8(pGray, pixels, pDst)); - } - for (int i = 0; i < pixels; i += 101) - { - int o = i * 4; - byte v = gray[i]; - Assert.Equal(v, dst[o]); - Assert.Equal(v, dst[o + 1]); - Assert.Equal(v, dst[o + 2]); - Assert.Equal(255, dst[o + 3]); - } - - // 3. NV12 -> BGRA8 - byte[] nv12 = new byte[pixels + pixels / 2]; - for (int i = 0; i < pixels; i++) - { - nv12[i] = (byte)(16 + ((i * 5) % 220)); - } - for (int i = pixels; i < nv12.Length; i += 2) - { - nv12[i] = (byte)(32 + ((i * 3) % 192)); - nv12[i + 1] = (byte)(48 + ((i * 7) % 192)); - } - fixed (byte* pNv12 = nv12) - fixed (byte* pDst = dst) - { - Assert.Equal(VnOk, vn_webcam_convert_nv12_to_bgra8(pNv12, width, height, pDst)); - } - for (int row = 0; row < height; row += 17) - { - for (int col = 0; col < width; col += 23) - { - int yVal = nv12[row * width + col]; - int uvIdx = pixels + (row >> 1) * width + (col & ~1); - var (eb, eg, er, ea) = ScalarBt601ToBgra(yVal, nv12[uvIdx], nv12[uvIdx + 1]); - int o = (row * width + col) * 4; - Assert.Equal(eb, dst[o]); - Assert.Equal(eg, dst[o + 1]); - Assert.Equal(er, dst[o + 2]); - Assert.Equal(ea, dst[o + 3]); - } - } - - // 4. YUY2 -> BGRA8 - byte[] yuy2 = new byte[pixels * 2]; - for (int i = 0; i < pixels; i += 2) - { - int o = i * 2; - yuy2[o] = (byte)(16 + ((i * 3) % 220)); - yuy2[o + 1] = (byte)(40 + ((i * 7) % 180)); - yuy2[o + 2] = (byte)(16 + (((i + 1) * 3) % 220)); - yuy2[o + 3] = (byte)(50 + ((i * 11) % 180)); - } - fixed (byte* pYuy2 = yuy2) - fixed (byte* pDst = dst) - { - Assert.Equal(VnOk, vn_webcam_convert_yuy2_to_bgra8(pYuy2, pixels, pDst)); - } - for (int i = 0; i < pixels; i += 131) - { - int pairBase = (i & ~1) * 2; - int yVal = yuy2[i * 2]; - int uVal = yuy2[pairBase + 1]; - int vVal = yuy2[pairBase + 3]; - var (eb, eg, er, ea) = ScalarBt601ToBgra(yVal, uVal, vVal); - int o = i * 4; - Assert.Equal(eb, dst[o]); - Assert.Equal(eg, dst[o + 1]); - Assert.Equal(er, dst[o + 2]); - Assert.Equal(ea, dst[o + 3]); - } - } - - [Fact] - public unsafe void PixelConverters_ConcurrentParallelConversions_AreDeterministicAndRaceFree() - { - using var rgbDoc = LoadGoldenJson("rgb-in-place-cases.json"); - using var nv12Doc = LoadGoldenJson("nv12-to-bgra8-cases.json"); - using var yuy2Doc = LoadGoldenJson("yuy2-to-bgra8-cases.json"); - - var rgbItem = rgbDoc.RootElement.GetProperty("cases")[5]; // exact_avx2_32_rgba_straight - byte[] rgbInput = Convert.FromBase64String(rgbItem.GetProperty("inputBase64").GetString()!); - byte[] rgbExpected = Convert.FromBase64String(rgbItem.GetProperty("expectedBase64").GetString()!); - - var nv12Item = nv12Doc.RootElement.GetProperty("cases")[6]; // valid_18x4_avx2_16_plus_2_tail - int nvW = nv12Item.GetProperty("width").GetInt32(); - int nvH = nv12Item.GetProperty("height").GetInt32(); - byte[] nvSrc = Convert.FromBase64String(nv12Item.GetProperty("srcBase64").GetString()!); - byte[] nvExpected = Convert.FromBase64String(nv12Item.GetProperty("expectedBase64").GetString()!); - - var yuy2Item = yuy2Doc.RootElement.GetProperty("cases")[9]; // avx2_16_plus_odd_3_tail - int yuyCount = yuy2Item.GetProperty("pixelCount").GetInt32(); - byte[] yuySrc = Convert.FromBase64String(yuy2Item.GetProperty("srcBase64").GetString()!); - byte[] yuyExpected = Convert.FromBase64String(yuy2Item.GetProperty("expectedBase64").GetString()!); - - var failures = new ConcurrentBag(); - Parallel.For(0, 64, iter => - { - try - { - byte[] rgbBuf = (byte[])rgbInput.Clone(); - fixed (byte* pRgb = rgbBuf) - { - if (vn_webcam_convert_rgb_in_place(pRgb, rgbBuf.Length, 1, 1) != VnOk) - { - failures.Add($"rgb status mismatch at {iter}"); - return; - } - } - if (!rgbBuf.AsSpan().SequenceEqual(rgbExpected)) - { - failures.Add($"rgb content mismatch at {iter}"); - } - - byte[] nvDst = new byte[nvExpected.Length]; - fixed (byte* pNvSrc = nvSrc) - fixed (byte* pNvDst = nvDst) - { - if (vn_webcam_convert_nv12_to_bgra8(pNvSrc, nvW, nvH, pNvDst) != VnOk) - { - failures.Add($"nv12 status mismatch at {iter}"); - return; - } - } - if (!nvDst.AsSpan().SequenceEqual(nvExpected)) - { - failures.Add($"nv12 content mismatch at {iter}"); - } - - byte[] yuyDst = new byte[yuyExpected.Length]; - fixed (byte* pYuySrc = yuySrc) - fixed (byte* pYuyDst = yuyDst) - { - if (vn_webcam_convert_yuy2_to_bgra8(pYuySrc, yuyCount, pYuyDst) != VnOk) - { - failures.Add($"yuy2 status mismatch at {iter}"); - return; - } - } - if (!yuyDst.AsSpan().SequenceEqual(yuyExpected)) - { - failures.Add($"yuy2 content mismatch at {iter}"); - } - - using var grayBitmap = SoftwareBitmap.CreateCopyFromBuffer( - new byte[] { 10, 40, 80, 120, 160, 200, 220, 255 }.AsBuffer(), - BitmapPixelFormat.Gray8, 4, 2, BitmapAlphaMode.Ignore); - byte[] managedOut = new byte[4 * 2 * 4]; - byte[] scratch = Array.Empty(); - CopyToBgra8Shim(grayBitmap, managedOut, managedOut.Length, ref scratch); - if (managedOut[0] != 10 || managedOut[3] != 255 || managedOut[28] != 255 || managedOut[31] != 255) - { - failures.Add($"managed gray8 mismatch at {iter}"); - } - } - catch (Exception ex) - { - failures.Add($"exception at {iter}: {ex.Message}"); - } - }); - - Assert.Empty(failures); - } - - private static unsafe void CopyToBgra8Shim(SoftwareBitmap bitmap, byte[] output, int requiredSize, ref byte[] scratch) - { - BitmapPixelFormat format = bitmap.BitmapPixelFormat; - if (format is BitmapPixelFormat.Bgra8 or BitmapPixelFormat.Rgba8) - { - bitmap.CopyToBuffer(output.AsBuffer(0, requiredSize)); - bool rgba = format == BitmapPixelFormat.Rgba8; - if (rgba || bitmap.BitmapAlphaMode != BitmapAlphaMode.Premultiplied) - { - fixed (byte* pOut = output) - { - _ = vn_webcam_convert_rgb_in_place(pOut, requiredSize, rgba ? (byte)1 : (byte)0, (int)bitmap.BitmapAlphaMode); - } - } - return; - } - - int width = bitmap.PixelWidth; - int height = bitmap.PixelHeight; - int pixels = checked(width * height); - int inputSize = format switch - { - BitmapPixelFormat.Gray8 => pixels, - BitmapPixelFormat.Nv12 when width % 2 == 0 && height % 2 == 0 => checked(pixels + pixels / 2), - BitmapPixelFormat.Yuy2 when width % 2 == 0 => checked(pixels * 2), - _ => 0, - }; - if (inputSize == 0) - { - using var converted = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); - converted.CopyToBuffer(output.AsBuffer(0, requiredSize)); - return; - } - - if (scratch.Length < inputSize) - { - scratch = GC.AllocateUninitializedArray(inputSize, pinned: true); - } - - bitmap.CopyToBuffer(scratch.AsBuffer(0, inputSize)); - fixed (byte* pSrc = scratch) - fixed (byte* pDst = output) - { - if (format == BitmapPixelFormat.Gray8) - { - _ = vn_webcam_convert_gray8_to_bgra8(pSrc, pixels, pDst); - } - else if (format == BitmapPixelFormat.Nv12) - { - _ = vn_webcam_convert_nv12_to_bgra8(pSrc, width, height, pDst); - } - else - { - _ = vn_webcam_convert_yuy2_to_bgra8(pSrc, pixels, pDst); - } - } - } - - [Fact] - public void ManagedWebcamPixelConverter_AllFormats_ScratchReuse_And_Fallback() - { - // 1. Bgra8 Premultiplied: direct copy, does not touch scratch. - byte[] bgraPremul = new byte[4 * 2 * 4]; - for (int i = 0; i < bgraPremul.Length; i++) bgraPremul[i] = (byte)(i * 7); - using (var bmp = SoftwareBitmap.CreateCopyFromBuffer(bgraPremul.AsBuffer(), BitmapPixelFormat.Bgra8, 4, 2, BitmapAlphaMode.Premultiplied)) - { - byte[] output = new byte[bgraPremul.Length + 16]; - Array.Fill(output, (byte)0xCD); - byte[] scratch = Array.Empty(); - CopyToBgra8Shim(bmp, output, bgraPremul.Length, ref scratch); - Assert.Empty(scratch); - Assert.Equal(bgraPremul, output.AsSpan(0, bgraPremul.Length).ToArray()); - Assert.All(output.AsSpan(bgraPremul.Length).ToArray(), b => Assert.Equal(0xCD, b)); - } - - // 2. Rgba8 Ignore: swaps R/B and sets alpha = 255 without allocating scratch. - byte[] rgbaIgnore = { 10, 20, 30, 0, 40, 50, 60, 128 }; - using (var bmp = SoftwareBitmap.CreateCopyFromBuffer(rgbaIgnore.AsBuffer(), BitmapPixelFormat.Rgba8, 2, 1, BitmapAlphaMode.Ignore)) - { - byte[] output = new byte[8]; - byte[] scratch = Array.Empty(); - CopyToBgra8Shim(bmp, output, 8, ref scratch); - Assert.Empty(scratch); - Assert.Equal(new byte[] { 30, 20, 10, 255, 60, 50, 40, 255 }, output); - } - - // 3. Gray8 -> NV12 -> smaller YUY2: scratch grows on larger input and is reused on smaller input. - byte[] scratchBuf = Array.Empty(); - byte[] largeOut = new byte[12 * 8 * 4]; - using (var nv12 = new SoftwareBitmap(BitmapPixelFormat.Nv12, 12, 8, BitmapAlphaMode.Ignore)) - { - CopyToBgra8Shim(nv12, largeOut, 12 * 8 * 4, ref scratchBuf); - Assert.True(scratchBuf.Length >= 12 * 8 + (12 * 8) / 2); - } - byte[] grownScratch = scratchBuf; - using (var smallGray = new SoftwareBitmap(BitmapPixelFormat.Gray8, 4, 2, BitmapAlphaMode.Ignore)) - { - CopyToBgra8Shim(smallGray, largeOut, 4 * 2 * 4, ref scratchBuf); - Assert.Same(grownScratch, scratchBuf); - } - - // 4. Fallback format (Rgba16 -> inputSize == 0 -> SoftwareBitmap.Convert) with odd dimensions. - byte[] rgba16 = new byte[3 * 3 * 8]; - using (var bmp16 = SoftwareBitmap.CreateCopyFromBuffer(rgba16.AsBuffer(), BitmapPixelFormat.Rgba16, 3, 3, BitmapAlphaMode.Premultiplied)) - { - byte[] out16 = new byte[3 * 3 * 4 + 4]; - Array.Fill(out16, (byte)0xEE); - byte[] untouchedScratch = Array.Empty(); - CopyToBgra8Shim(bmp16, out16, 3 * 3 * 4, ref untouchedScratch); - Assert.Empty(untouchedScratch); - Assert.All(out16.AsSpan(3 * 3 * 4).ToArray(), b => Assert.Equal(0xEE, b)); - } - } - [LibraryImport("user32.dll")] private static partial nint GetDesktopWindow(); @@ -656,7 +129,6 @@ public unsafe void AbiV2_SafeHandleErrorPathsAndCreateDestroyCycles_DoNotLeak() Assert.Equal(24, sizeof(M13Native.VnWebcamStartRequest)); Assert.Equal(24, sizeof(M13Native.VnWebcamAcquireRequest)); Assert.Equal(16, sizeof(M13Native.VnWebcamGpuCreateRequest)); - Assert.Equal(56, sizeof(M13Native.VnWebcamPlaneCopyRequest)); Assert.Equal((int)NativeStatus.InvalidArgument, WebcamCaptureSafeHandle.DestroyRaw(0)); Assert.Equal((int)NativeStatus.InvalidArgument, WebcamCaptureSafeHandle.DestroyRaw(999_999_999)); @@ -686,13 +158,6 @@ public unsafe void AbiV2_SafeHandleErrorPathsAndCreateDestroyCycles_DoNotLeak() Assert.Equal((int)NativeStatus.InvalidArgument, badStatus); Assert.Equal(HResultInvalidArg, badHr); - byte[] rgb24 = { 1, 2, 3, 10, 20, 30 }; - byte[] bgraOut = new byte[8]; - Assert.Equal((int)NativeStatus.Ok, M13Native.ConvertRgb24ToBgra8(rgb24, 2, isBgr: false, bgraOut)); - Assert.Equal(new byte[] { 3, 2, 1, 255, 30, 20, 10, 255 }, bgraOut); - Assert.Equal((int)NativeStatus.Ok, M13Native.ConvertRgb24ToBgra8(rgb24, 2, isBgr: true, bgraOut)); - Assert.Equal(new byte[] { 1, 2, 3, 255, 10, 20, 30, 255 }, bgraOut); - Assert.NotNull(M13Native.EnumerateColorDevices()); TestWebcamGpuV2HardwareCycle(); } diff --git a/Tests/MigrationBaseline/M14_AppSetupUninstallBaselineTests.cs b/Tests/MigrationBaseline/M14_AppSetupUninstallBaselineTests.cs index 305d55b3..82b9aa8d 100644 --- a/Tests/MigrationBaseline/M14_AppSetupUninstallBaselineTests.cs +++ b/Tests/MigrationBaseline/M14_AppSetupUninstallBaselineTests.cs @@ -195,29 +195,6 @@ public async Task NativeValidationExports_ConcurrentCalls_AreDeterministicAndThr Assert.Empty(failures); } - [Fact] - public unsafe void NativeSetupDialogs_InvalidArguments_ReturnVnErrInvalidArgWithoutShowingDialog() - { - int result = 123; - Assert.Equal(VnErrInvalidArg, M14Native.vn_setup_show_message_utf8(null, null)); - - byte[] textUtf8 = "Confirm uninstall?"u8.ToArray(); - byte[] titleUtf8 = "V-Notch"u8.ToArray(); - fixed (byte* pText = textUtf8, pTitle = titleUtf8) - { - var badMode = new M14Native.VnShowMessageRequest - { - TextUtf8 = pText, - TextLen = (uint)textUtf8.Length, - TitleUtf8 = pTitle, - TitleLen = (uint)titleUtf8.Length, - Mode = 9, - }; - Assert.Equal(VnErrInvalidArg, M14Native.vn_setup_show_message_utf8(&badMode, &result)); - Assert.Equal(0, result); - } - } - // ========================================================================= // InstallDirectoryCleanup: Directory & Install Validation // ========================================================================= @@ -920,11 +897,9 @@ public unsafe void M14Abi22_SessionSafeHandle_ErrorPaths_AndRepeatedCreateDestro { Assert.Equal(16, sizeof(M14Native.VnSessionInitPod)); Assert.Equal(8, sizeof(M14Native.VnCliDecision)); - Assert.Equal(12, sizeof(M14Native.VnSetupProgressPod)); Assert.Equal(24, sizeof(M14Native.VnCliParseRequest)); Assert.Equal(24, sizeof(M14Native.VnManifestEntryRef)); Assert.Equal(16, sizeof(M14Native.VnDialogModelRequest)); - Assert.Equal(32, sizeof(M14Native.VnShowMessageRequest)); Assert.Equal(VnErrInvalidArg, M14Native.vn_session_create(null, null, 0, null)); Assert.Equal(VnErrInvalidArg, M14Native.vn_events_drain(0, null, 0, null)); @@ -938,7 +913,6 @@ public unsafe void M14Abi22_SessionSafeHandle_ErrorPaths_AndRepeatedCreateDestro Assert.Equal(VnErrInvalidArg, M14Native.vn_setup_cancel_install(0, 1)); Assert.Equal(VnErrInvalidArg, M14Native.vn_setup_execute_uninstall_steps(null, 0, null, null)); Assert.Equal(VnErrInvalidArg, M14Native.vn_setup_build_dialog_model(0, null, null)); - Assert.Equal(VnErrInvalidArg, M14Native.vn_setup_show_message_utf8(null, null)); Assert.Equal(VnOk, VNotchSessionHandle.DestroyRaw(0)); Assert.Equal(VnOk, VNotchSessionHandle.DestroyRaw(-1)); diff --git a/Tests/NativeAuditHardeningTests.cs b/Tests/NativeAuditHardeningTests.cs index ab480d52..f262383f 100644 --- a/Tests/NativeAuditHardeningTests.cs +++ b/Tests/NativeAuditHardeningTests.cs @@ -252,7 +252,21 @@ public void Finding02_ClipboardStoreExportAndPathOverlap_EnforcesDirectoryBounda Assert.False(SecurityNative.PathsOverlap(@"C:\Temp\dir", @"C:\Temp\dir2\file.txt")); Assert.True(SecurityNative.PathsOverlap(@"C:\Temp\dir", @"C:\Temp\dir\file.txt")); - using var store = ClipboardStoreSafeHandle.Open(tempRoot, M08Native.VnClipboardPolicyPod.CreateDefault()); + var policy = new M08Native.VnClipboardPolicyPod + { + MaxUnpinnedEntries = M08Native.DefaultMaxUnpinnedEntries, + RetentionDays = M08Native.DefaultRetentionDays, + SensitiveTtlSeconds = M08Native.DefaultSensitiveTtlSeconds, + MaxImportItems = M08Native.DefaultMaxImportItems, + MaxImportContents = M08Native.DefaultMaxImportContents, + AutoDeleteSensitive = 1, + AllowNetworkArtwork = 0, + MaxUnpinnedBytes = M08Native.DefaultMaxUnpinnedBytes, + ApprovalThresholdBytes = M08Native.DefaultApprovalThresholdBytes, + MaxArchiveExtractBytes = M08Native.DefaultMaxArchiveExtractBytes, + MaxDropImageBytes = M08Native.DefaultMaxDropImageBytes, + }; + using var store = ClipboardStoreSafeHandle.Open(tempRoot, policy); string outsidePath = Path.Combine(Path.GetDirectoryName(tempRoot)!, "dir2", "escape.txt"); Assert.Empty(store.Export(1, ReadOnlySpan.Empty, [outsidePath])); Assert.False(File.Exists(outsidePath)); @@ -385,16 +399,6 @@ public void Finding05_SettingsStoreNormalize_OutOfRangeNumeric_ClampedSafely() Assert.InRange(brightness, 0.0, 1.0); } - [Fact] - public void Finding06_WebcamConvertNv12ToBgra8_OddDimensions_ReturnsInvalidArg() - { - Span src = stackalloc byte[64]; - Span dst = stackalloc byte[128]; - - Assert.Equal(VnErrInvalidArg, M13Native.ConvertNv12ToBgra8(src, width: 3, height: 2, dst)); - Assert.Equal(VnErrInvalidArg, M13Native.ConvertNv12ToBgra8(src, width: 2, height: 3, dst)); - } - [Fact] public void Finding07_SpotlightEngine_SequentialQueries_DoNotAccumulateStaleState() { @@ -471,23 +475,7 @@ public unsafe void Finding12_SmartCropAndImaging_InvalidDimensions_ReturnsInvali Span pixels = stackalloc byte[4 * 4 * 4]; fixed (byte* p = pixels) { - var req = new ImagingNative.VnColorRequest - { - Width = -1, - Height = 4, - Stride = 16, - ByteLen = pixels.Length, - Pixels = (nint)p, - LeftOrH = 0, - TopOrS = 0, - RightOrL = 1, - BottomOrRatio = 1, - }; ImagingNative.VnCoreRect rect = default; - byte valid = 1; - Assert.Equal(VnOk, ImagingNative.vn_dicolor_clamp_crop_v2(&req, &rect, &valid)); - Assert.Equal(0, valid); - var frameReq = new ImagingNative.VnArtworkDetectRequest { Pixels = (nint)p, diff --git a/Tests/NativeParsingAndClipboardIndexTests.cs b/Tests/NativeParsingAndClipboardIndexTests.cs deleted file mode 100644 index 1b2a1e0a..00000000 --- a/Tests/NativeParsingAndClipboardIndexTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.IO; -using System.Text; -using VNotch.Interop; -using VNotch.Services; -using VNotch.Services.Clipboard; -using Xunit; - -namespace VNotch.Tests; - -public sealed class NativeParsingAndClipboardIndexTests -{ - [Fact] - public void TtmlNamespacesEntitiesPreservedWhitespaceAndDuetsHaveStableUtf16Offsets() - { - const string xml = """ - - 🎵& hide - DuetLast - - """; - var utf8 = M10Native.ParseLyricsBlob(Encoding.UTF8.GetBytes(xml), M10Native.LyricKindTtml); - Assert.Equal(new[] { "🎵& Đây", "Duet", "Last" }, utf8.Select(line => line.Text)); - Assert.Equal(new[] { 0, 4 }, utf8[0].Words!.Select(word => word.Offset)); - Assert.Equal(new[] { 3, 3 }, utf8[0].Words!.Select(word => word.Length)); - } - - [Fact] - public void XmlRejectsBrokenDocumentsAndDeepNestingWithoutPartialResults() - { - Assert.Throws(() => - M10Native.ParseLyricsBlob(Encoding.UTF8.GetBytes("

valid

"), M10Native.LyricKindTtml)); - Assert.Throws(() => - M10Native.ParseLyricsBlob(Encoding.UTF8.GetBytes("valid"), M10Native.LyricKindYouTubeXml)); - } - - [Fact] - public void TimedJsonResolvesUnicodeWordMapAndRejectsInvalidUtf8AndTrailingTokens() - { - byte[] json = Encoding.UTF8.GetBytes("""{"lines":[{"id":"🎵","start":1000,"text":"🎵 Đây"}],"wordMap":{"🎵":[{"start":1000,"end":1500,"text":"🎵"},{"start":1500,"end":2000,"text":"Đây"}]}}"""); - var line = Assert.Single(M10Native.ParseLyricsBlob(json, M10Native.LyricKindTimedJsonStartEnd)); - Assert.Equal(new[] { 0, 3 }, line.Words!.Select(word => word.Offset)); - Assert.Throws(() => M10Native.ParseLyricsBlob([0xff], M10Native.LyricKindTimedJsonStartEnd)); - } - - [Fact] - public void NativeScratchStreamZerosHolesAndTruncatedBytesAndHandlesGrowth() - { - using var stream = new NativeBufferStream(); - stream.Write(new byte[100_000].AsSpan()); stream.Position = 10; stream.WriteByte(255); - stream.SetLength(5); stream.SetLength(20); stream.Position = 0; - Assert.All(ReadAll(stream), value => Assert.Equal(0, value)); - stream.Position = 70_000; stream.WriteByte(42); stream.Position = 20; - byte[] tail = ReadAll(stream); Assert.Equal(69_981, tail.Length); - Assert.All(tail[..^1], value => Assert.Equal(0, value)); Assert.Equal(42, tail[^1]); - stream.Dispose(); Assert.Throws(() => _ = stream.ReadByte()); - } - - [Fact] - public void LyricParserBoundaryInputsAreSafe() - { - Assert.Empty(M10Native.ParseLyricsBlob(ReadOnlySpan.Empty, M10Native.LyricKindTtml)); - for (int i = 0; i < 10; i++) - { - var parsed = M10Native.ParseLyricsBlob("{\"lines\":[{\"start\":1000,\"text\":\"hello\"}]}"u8, M10Native.LyricKindTimedJsonStartEnd); - Assert.Single(parsed); - } - } - - private static byte[] ReadAll(Stream stream) { using var result = new MemoryStream(); stream.CopyTo(result); return result.ToArray(); } -} diff --git a/Tests/NativePipelineOptimizationTests.cs b/Tests/NativePipelineOptimizationTests.cs index 55ce162a..56f42de0 100644 --- a/Tests/NativePipelineOptimizationTests.cs +++ b/Tests/NativePipelineOptimizationTests.cs @@ -1,64 +1,14 @@ -using System.Diagnostics; using System.IO; using Microsoft.Win32; using VNotch.Interop; using VNotch.Services; using Xunit; -using Xunit.Abstractions; namespace VNotch.Tests; [Collection("Localization")] -public sealed class NativePipelineOptimizationTests(ITestOutputHelper output) +public sealed class NativePipelineOptimizationTests { - [Theory] - [InlineData(false)] - [InlineData(true)] - public void NativeYoloxRunsWithCpuOrPreferredDirectMlWithoutManagedTensorAllocations(bool preferDml) - { - string directory = AppContext.BaseDirectory, model = Path.Combine(directory, "Models", "yolox_nano.onnx"); - TraceYolox(preferDml, $"create started; runtime={Environment.Version}; os={Environment.OSVersion}; cores={Environment.ProcessorCount}; modelExists={File.Exists(model)}"); - (SmartCropSessionSafeHandle session, bool backend) = SmartCropSessionSafeHandle.Create(model, directory, preferDml); - TraceYolox(preferDml, $"create completed; backend={backend}"); - using (session) - { - if (!preferDml) Assert.False(backend); - byte[] pixels = new byte[64 * 64 * 4]; - var detections = new ImagingNative.VnCoreDetection[SmartCropSessionSafeHandle.MinDetectionCapacity]; - TraceYolox(preferDml, "warmup started"); - _ = session.Infer(pixels, 64, 64, 256, detections, out _); - TraceYolox(preferDml, "measured inference started"); - var stopwatch = Stopwatch.StartNew(); - long allocated = GC.GetAllocatedBytesForCurrentThread(); - for (int i = 0; i < 5; ++i) - _ = session.Infer(pixels, 64, 64, 256, detections, out backend); - long delta = GC.GetAllocatedBytesForCurrentThread() - allocated; - stopwatch.Stop(); - TraceYolox(preferDml, $"measured inference completed; backend={backend}; allocated={delta}"); - Assert.Equal(0, delta); - output.WriteLine($"YOLOX backend={(backend ? "DirectML" : "CPU")}, mean={stopwatch.Elapsed.TotalMilliseconds / 5:F2} ms, managed tensor allocations={delta} bytes"); - } - } - - private void TraceYolox(bool preferDml, string stage) - { - string message = $"{DateTime.UtcNow:O} preferDml={preferDml}: {stage}"; - output.WriteLine(message); - // xUnit's buffered output can disappear with testhost. Flush each native - // phase to a separate artifact, outside the allocation measurement. - string? directory = Environment.GetEnvironmentVariable("VNOTCH_TEST_DIAGNOSTICS_DIRECTORY"); - if (string.IsNullOrWhiteSpace(directory)) return; - try - { - Directory.CreateDirectory(directory); - File.AppendAllText(Path.Combine(directory, $"native-yolox-{Environment.ProcessId}-{preferDml}.log"), message + Environment.NewLine); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - output.WriteLine($"Could not persist YOLOX diagnostic: {ex.Message}"); - } - } - [Theory] [InlineData(140, 140, 20)] [InlineData(220, 30, 80)] diff --git a/Tests/PerformancePresetsTests.cs b/Tests/PerformancePresetsTests.cs index 5a19f297..a67fb90f 100644 --- a/Tests/PerformancePresetsTests.cs +++ b/Tests/PerformancePresetsTests.cs @@ -1,9 +1,7 @@ using System; using System.IO; -using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; -using VNotch.Interop; using VNotch.Models; using VNotch.Services; using Xunit; @@ -12,78 +10,6 @@ namespace VNotch.Tests; public sealed partial class PerformancePresetsTests { - [StructLayout(LayoutKind.Sequential)] - private struct VnPerformancePresetStateV2 - { - public byte AutoAnimationFps; - private byte _pad0; - private byte _pad1; - private byte _pad2; - public int AnimationFps; - public byte EnableBlurEffects; - public byte EnableSubjectBlur; - public byte EnableSmartCrop; - public byte ShowMediaArtBackground; - public byte EnableShadow; - public byte IsLiquidGlass; - public byte UseGpuRefraction; - public byte UseUltimateGpu; - public int GlassTargetFps; - public int GpuPreference; - public int ProcessPriority; - } - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_perf_preset_apply_v2( - int presetId, - in VnPerformancePresetStateV2 currentState, - out VnPerformancePresetStateV2 outState); - - [LibraryImport(NativeAbi.RustLibraryName)] - private static partial int vn_perf_preset_match_v2( - in VnPerformancePresetStateV2 state, - out int outPresetId); - - [Fact] - public void StructLayout_MatchesNaturalNativeAbi() - { - Assert.Equal(28, Marshal.SizeOf()); - Assert.Equal(PerformancePresetCatalog.PresetCount, PerformancePresetCatalog.All.Count); - } - - [Theory] - [InlineData(PerformancePresetCatalog.PresetEco, 0)] - [InlineData(PerformancePresetCatalog.PresetEveryday, 0)] - [InlineData(PerformancePresetCatalog.PresetBalanced, 1)] - [InlineData(PerformancePresetCatalog.PresetHighEnd, 1)] - public void ApplyAndMatch_RoundTripsAllHardwareTiers(int presetId, byte expectedLiquidGlassWhenEnabled) - { - var initial = new VnPerformancePresetStateV2 - { - AutoAnimationFps = 1, - AnimationFps = 165, - EnableBlurEffects = 1, - EnableSubjectBlur = 1, - EnableSmartCrop = 1, - ShowMediaArtBackground = 1, - EnableShadow = 1, - IsLiquidGlass = 1, - UseGpuRefraction = 1, - UseUltimateGpu = 0, - GlassTargetFps = 60, - GpuPreference = 0, - ProcessPriority = 0, - }; - - int applyStatus = vn_perf_preset_apply_v2(presetId, in initial, out VnPerformancePresetStateV2 applied); - Assert.Equal((int)NativeStatus.Ok, applyStatus); - Assert.Equal(expectedLiquidGlassWhenEnabled, applied.IsLiquidGlass); - - int matchStatus = vn_perf_preset_match_v2(in applied, out int matchedId); - Assert.Equal((int)NativeStatus.Ok, matchStatus); - Assert.Equal(presetId, matchedId); - } - [Fact] public void Session_CapturesBackupOncePreservesAcrossPresetsAndRestoresWithoutManualLoad() { @@ -172,13 +98,10 @@ public void RecommendHardwareTier_ReturnsValidPresetIndex() private sealed class StubSettingsApplicationService : ISettingsApplicationService { - public event EventHandler? SettingsApplied; - public NotchSettings Load() => new(); public Task ApplyAsync(NotchSettings settings, CancellationToken ct = default) { - SettingsApplied?.Invoke(this, settings.Clone()); return Task.CompletedTask; } diff --git a/Tests/ReleaseFeedIntegrationTests.cs b/Tests/ReleaseFeedIntegrationTests.cs index e7c704c4..0909cde7 100644 --- a/Tests/ReleaseFeedIntegrationTests.cs +++ b/Tests/ReleaseFeedIntegrationTests.cs @@ -18,67 +18,6 @@ namespace VNotch.Tests; public sealed class ReleaseFeedIntegrationTests(ITestOutputHelper output) { - [Theory] - [InlineData("unclosed")] - [InlineData("")] - [InlineData(" \r\n\t ")] - [InlineData("{{{not-xml-garbage!@#$")] - [InlineData("]>")] - public void ParseAtom_MalformedOrInvalidXml_ReturnsError(string rawInput) - { - byte[] bytes = Encoding.UTF8.GetBytes(rawInput); - Assert.Throws(() => UpdaterSafeHandle.ParseAtomReleases(bytes)); - } - - [Fact] - public void ParseAtom_BoundsAndCapacityChecks_ReturnExpectedStatusCodes() - { - byte[] oversized = new byte[2 * 1024 * 1024 + 1]; - Assert.Throws(() => UpdaterSafeHandle.ParseAtomReleases(oversized)); - - byte[] validXml = Encoding.UTF8.GetBytes( - "tag:github.com,2008:Repository/1/v2.2.22026-10-31T00:00:00ZNotes"); - var parsed = UpdaterSafeHandle.ParseAtomReleases(validXml); - var entry = Assert.Single(parsed); - Assert.Equal("2.2.2", entry.Version); - } - - [Fact] - public void ParseAtom_EntriesMissingIdOrUpdatedOrWithEmptyTag_AreSkipped() - { - const string atomXml = """ - - - - 2026-10-30T10:00:00Z - <p>Missing id</p> - - - tag:github.com,2008:Repository/100/v2.1.0 - - <p>Missing updated timestamp</p> - - - tag:github.com,2008:Repository/100/ - 2026-10-30T11:00:00Z - <p>Empty tag after slash</p> - - - tag:github.com,2008:Repository/100/v2.2.2 - 2026-10-31T12:00:00Z - <h3>Valid entry</h3><p>Body text</p> - - - """; - - byte[] bytes = Encoding.UTF8.GetBytes(atomXml); - var entries = UpdaterSafeHandle.ParseAtomReleases(bytes); - var entry = Assert.Single(entries); - Assert.Equal("2.2.2", entry.Version); - Assert.Contains("Valid entry", entry.ReleaseNotes); - Assert.Contains("Body text", entry.ReleaseNotes); - } - [Fact] public async Task MultiEntryAtomFeed_ParsesStableAndPrereleaseTagsReleaseNotesAndMatchesAssets() { diff --git a/Tests/RuntimeLogPrivacyObsTests.cs b/Tests/RuntimeLogPrivacyObsTests.cs deleted file mode 100644 index ae242c74..00000000 --- a/Tests/RuntimeLogPrivacyObsTests.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using VNotch.Services; -using Xunit; - -namespace VNotch.Tests; - -public sealed class RuntimeLogPrivacyObsTests -{ - [Fact] - public async Task AsyncLogWriter_ConcurrentEnqueueFlushAndDispose_CompletesPromptlyWithoutSpinning() - { - string tempDir = Path.Combine(Path.GetTempPath(), "VNotch_RuntimeLogTests_" + Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(tempDir); - try - { - for (int iteration = 0; iteration < 15; iteration++) - { - string logPath = Path.Combine(tempDir, $"test-{iteration}.log"); - var writer = new RuntimeLog.AsyncLogWriter(logPath); - using var barrier = new ManualResetEventSlim(false); - - var tasks = new Task[6]; - for (int p = 0; p < 4; p++) - { - int producerId = p; - tasks[p] = Task.Run(() => - { - barrier.Wait(); - for (int i = 0; i < 200; i++) - { - writer.TryEnqueue($"[INFO] [TEST] producer={producerId} index={i}{Environment.NewLine}", LogLevel.Info); - } - }); - } - - tasks[4] = Task.Run(async () => - { - barrier.Wait(); - for (int i = 0; i < 10; i++) - { - await writer.EnqueueFlush().WaitAsync(TimeSpan.FromSeconds(5)); - } - }); - - tasks[5] = Task.Run(async () => - { - barrier.Wait(); - await Task.Delay(5); - writer.Dispose(); - }); - - barrier.Set(); - - await Task.WhenAll(tasks).WaitAsync(TimeSpan.FromSeconds(5)); - await writer.Completion.WaitAsync(TimeSpan.FromSeconds(5)); - Assert.True(writer.Completion.IsCompletedSuccessfully); - } - } - finally - { - try { Directory.Delete(tempDir, recursive: true); } catch { /* Best-effort cleanup */ } - } - } -} diff --git a/Tests/ScrubberAcceptanceTests.cs b/Tests/ScrubberAcceptanceTests.cs index d09689cc..e366ccf6 100644 --- a/Tests/ScrubberAcceptanceTests.cs +++ b/Tests/ScrubberAcceptanceTests.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using System.Text.Json; +using VNotch.Interop; using VNotch.Services; using Xunit; @@ -11,7 +12,7 @@ public sealed class ScrubberAcceptanceTests [InlineData(null)] [InlineData("")] public void NullAndEmptyInputReturnEmptyText(string? input) - => Assert.Equal(string.Empty, SensitiveDataScrubber.Scrub(input)); + => Assert.Equal(string.Empty, SecurityNative.ScrubSensitiveText(input)); [Theory] [InlineData("password: anh yeu em 123", "password: [REDACTED]")] @@ -27,8 +28,8 @@ public void NullAndEmptyInputReturnEmptyText(string? input) [InlineData("-PASSWORD: secret words\nrequest=42", "-PASSWORD: [REDACTED]\nrequest=42")] public void WholePasswordValueIsRedactedAndDelimitedContextSurvives(string input, string expected) { - Assert.Equal(expected, SensitiveDataScrubber.Scrub(input)); - Assert.Equal(expected, SensitiveDataScrubber.Scrub(expected)); + Assert.Equal(expected, SecurityNative.ScrubSensitiveText(input)); + Assert.Equal(expected, SecurityNative.ScrubSensitiveText(expected)); } [Theory] @@ -40,7 +41,7 @@ public void WholePasswordValueIsRedactedAndDelimitedContextSurvives(string input [InlineData("{\"password\": {\"secret\": [\"nested, value\", null]}, \"status\": 401}")] public void JsonPasswordIncludingEmptyAndNullBecomesRedactedString(string input) { - string output = SensitiveDataScrubber.Scrub(input); + string output = SecurityNative.ScrubSensitiveText(input); using var document = JsonDocument.Parse(output); var password = document.RootElement.EnumerateObject().First(p => p.Name.Equals("password", StringComparison.OrdinalIgnoreCase)); Assert.Equal("[REDACTED]", password.Value.GetString()); @@ -58,7 +59,7 @@ public void TenThousandCharacterTokenHasNoUnredactedTail(string prefix) { string token = new string('A', 10_000); string input = "WARN 日本語 🌸 " + prefix + token + "; request=42"; - string output = SensitiveDataScrubber.Scrub(input); + string output = SecurityNative.ScrubSensitiveText(input); Assert.DoesNotContain(new string('A', 32), output); Assert.Contains("WARN 日本語 🌸", output); Assert.Contains("request=42", output); @@ -71,7 +72,7 @@ public void LargeEntryPreservesDebugContextAndStillRedactsAllSecrets() string input = "ERROR request=42 日本語 🌸\npassword: two secret words\n" + "{\"password\":null,\"status\":401}\nAuthorization: Bearer private-token\n" + noise + "\n at App.Authenticate()"; - string result = SensitiveDataScrubber.Scrub(input); + string result = SecurityNative.ScrubSensitiveText(input); Assert.Contains("ERROR request=42 日本語 🌸", result); Assert.Contains("\"status\":401", result); Assert.Contains(" at App.Authenticate()", result); @@ -84,7 +85,7 @@ public void LongHyphenatedIdentifierDoesNotCauseQuadraticRetries() { string input = string.Concat(Enumerable.Repeat("a-", 100_000)) + "!\napi_key=private-key; request=42"; var timer = Stopwatch.StartNew(); - string result = SensitiveDataScrubber.Scrub(input); + string result = SecurityNative.ScrubSensitiveText(input); Assert.DoesNotContain("private-key", result); Assert.Contains("request=42", result); Assert.True(timer.Elapsed < TimeSpan.FromSeconds(3), $"Linear scan took {timer.Elapsed}."); @@ -93,8 +94,8 @@ public void LongHyphenatedIdentifierDoesNotCauseQuadraticRetries() [Fact] public void QuotedPrefixBeforeTokenOrFieldDelimiterDoesNotUnderflowOrOverRedact() { - Assert.Equal("token=\"[REDACTED]\"-1234567890", SensitiveDataScrubber.Scrub("token=\"sk\"-1234567890")); - Assert.Equal("token=\"[REDACTED]\":1234567890123456", SensitiveDataScrubber.Scrub("token=\"enc\":1234567890123456")); - Assert.Equal("token=\"[REDACTED]\":keep_this_value", SensitiveDataScrubber.Scrub("token=\"password\":keep_this_value")); + Assert.Equal("token=\"[REDACTED]\"-1234567890", SecurityNative.ScrubSensitiveText("token=\"sk\"-1234567890")); + Assert.Equal("token=\"[REDACTED]\":1234567890123456", SecurityNative.ScrubSensitiveText("token=\"enc\":1234567890123456")); + Assert.Equal("token=\"[REDACTED]\":keep_this_value", SecurityNative.ScrubSensitiveText("token=\"password\":keep_this_value")); } } diff --git a/Tests/ScrubberPerformanceTests.cs b/Tests/ScrubberPerformanceTests.cs index 1c27e218..6fe91a60 100644 --- a/Tests/ScrubberPerformanceTests.cs +++ b/Tests/ScrubberPerformanceTests.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using VNotch.Interop; using VNotch.Services; using Xunit; using Xunit.Abstractions; @@ -22,11 +23,11 @@ public void OrdinaryLogsReuseTheInputAndHaveNoSteadyStateAllocations() ]; foreach (string log in logs) { - for (int i = 0; i < 1000; i++) SensitiveDataScrubber.Scrub(log); + for (int i = 0; i < 1000; i++) SecurityNative.ScrubSensitiveText(log); long before = GC.GetAllocatedBytesForCurrentThread(); long started = Stopwatch.GetTimestamp(); string result = log; - for (int i = 0; i < 100_000; i++) result = SensitiveDataScrubber.Scrub(log); + for (int i = 0; i < 100_000; i++) result = SecurityNative.ScrubSensitiveText(log); var elapsed = Stopwatch.GetElapsedTime(started); long allocated = GC.GetAllocatedBytesForCurrentThread() - before; output.WriteLine($"normal {log.Length} chars: {elapsed.TotalMilliseconds:F2} ms / 100000 calls; {allocated} bytes"); @@ -44,9 +45,9 @@ public void TwentyMiBAsciiDumpPreservesSafeContextAndRedactsSecretsAtBothEnds(bo string filler = dense ? string.Concat(Enumerable.Repeat("api_key=private-key; ", 1_048_576)) : new string('x', 20 * 1024 * 1024); string input = "request=42\npassword='secret with spaces'\n" + filler + "\nAuthorization: Basic YWRtaW46MTIz\n at App.Authenticate() status=401"; - SensitiveDataScrubber.Scrub("password=warmup"); + SecurityNative.ScrubSensitiveText("password=warmup"); var timer = Stopwatch.StartNew(); - string result = SensitiveDataScrubber.Scrub(input); + string result = SecurityNative.ScrubSensitiveText(input); timer.Stop(); output.WriteLine($"20 MiB dump dense={dense}: {timer.Elapsed.TotalMilliseconds:F2} ms"); Assert.DoesNotContain("secret with spaces", result); diff --git a/Tests/SecurityAuditTests.cs b/Tests/SecurityAuditTests.cs index 9a622203..7ac0983f 100644 --- a/Tests/SecurityAuditTests.cs +++ b/Tests/SecurityAuditTests.cs @@ -4,6 +4,7 @@ using System.Text.Json; using VNotch.Controllers; using VNotch.Models; +using VNotch.Interop; using VNotch.Services; using Xunit; @@ -15,7 +16,7 @@ public sealed class SecurityAuditTests public void SensitiveDataScrubber_RedactsSpotifyCookie() { string input = "User logged in with cookie: sp_dc=AQB_secret_token_12345ABCDE in session"; - string scrubbed = SensitiveDataScrubber.Scrub(input); + string scrubbed = SecurityNative.ScrubSensitiveText(input); Assert.DoesNotContain("AQB_secret_token_12345ABCDE", scrubbed); Assert.Contains("sp_dc=[REDACTED]", scrubbed); @@ -25,7 +26,7 @@ public void SensitiveDataScrubber_RedactsSpotifyCookie() public void SensitiveDataScrubber_RedactsGoogleApiKey() //example key lol { string input = "Calling YouTube API with key=AIzaSyD_abc1234567890XYZ_abcdef12345678"; - string scrubbed = SensitiveDataScrubber.Scrub(input); + string scrubbed = SecurityNative.ScrubSensitiveText(input); Assert.DoesNotContain("AIzaSyD_abc1234567890XYZ_abcdef12345678", scrubbed); Assert.Contains("AIza[REDACTED]", scrubbed); @@ -35,7 +36,7 @@ public void SensitiveDataScrubber_RedactsGoogleApiKey() //example key lol public void SensitiveDataScrubber_RedactsDpapiCiphertext() { string input = "Saved encrypted value enc:AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA12345678 to disk"; - string scrubbed = SensitiveDataScrubber.Scrub(input); + string scrubbed = SecurityNative.ScrubSensitiveText(input); Assert.DoesNotContain("AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA12345678", scrubbed); Assert.Contains("enc:[REDACTED]", scrubbed); @@ -45,7 +46,7 @@ public void SensitiveDataScrubber_RedactsDpapiCiphertext() public void SensitiveDataScrubber_RedactsBearerToken() { string input = "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-ID"; - string scrubbed = SensitiveDataScrubber.Scrub(input); + string scrubbed = SecurityNative.ScrubSensitiveText(input); Assert.DoesNotContain("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9", scrubbed); Assert.Contains("Bearer [REDACTED]", scrubbed); @@ -55,7 +56,7 @@ public void SensitiveDataScrubber_RedactsBearerToken() public void SensitiveDataScrubber_RedactsSensitiveUrlQueryParameters() { string input = "https://api.example.com/v1?api_key=secret_value_123&client_secret=secret_xyz"; - string scrubbed = SensitiveDataScrubber.Scrub(input); + string scrubbed = SecurityNative.ScrubSensitiveText(input); Assert.DoesNotContain("secret_value_123", scrubbed); Assert.DoesNotContain("secret_xyz", scrubbed); diff --git a/Tests/SettingsActionsAndBaselineTests.cs b/Tests/SettingsActionsAndBaselineTests.cs index d1a32d98..607f2413 100644 --- a/Tests/SettingsActionsAndBaselineTests.cs +++ b/Tests/SettingsActionsAndBaselineTests.cs @@ -287,13 +287,11 @@ private sealed class RecordingService : ISettingsApplicationService public Task ApplyAsync(NotchSettings settings, CancellationToken ct = default) { Applied = settings.Clone(); - SettingsApplied?.Invoke(this, Applied); return Task.CompletedTask; } public Task<(NotchSettings Settings, bool RequiresRestart)> ImportAsync(string filePath, NotchSettings? currentSettings = null, CancellationToken ct = default) => Task.FromResult((new NotchSettings(), false)); public void Export(string filePath, NotchSettings settings) { } public bool IsAutoStartEnabled() => false; - public event EventHandler? SettingsApplied; } } diff --git a/Tests/SettingsApplicationServiceTests.cs b/Tests/SettingsApplicationServiceTests.cs index 52eb6580..fb083327 100644 --- a/Tests/SettingsApplicationServiceTests.cs +++ b/Tests/SettingsApplicationServiceTests.cs @@ -41,7 +41,7 @@ public void RuntimePreviewAppliesPrivacyFirstAndIsolatesFeatureSnapshots() } [Fact] - public async Task ApplyAsync_PersistsSettings_UpdatesAutoStart_AndFiresSettingsApplied() + public async Task ApplyAsync_PersistsSettings_AndUpdatesAutoStart() { var fakeService = new FakeSettingsService(); var fakeStartup = new FakeStartupManager(); @@ -54,20 +54,10 @@ public async Task ApplyAsync_PersistsSettings_UpdatesAutoStart_AndFiresSettingsA AutoStart = true }; - NotchSettings? eventArgs = null; - object? eventSender = null; - appService.SettingsApplied += (sender, args) => - { - eventSender = sender; - eventArgs = args; - }; - await appService.ApplyAsync(settings); Assert.True(settings.ValueEquals(fakeService.LastSaved)); Assert.True(fakeStartup.AutoStartEnabled); - Assert.Same(appService, eventSender); - Assert.True(settings.ValueEquals(eventArgs)); } [Fact] @@ -84,21 +74,17 @@ public async Task ApplyAsync_WhenAutoStartDisabled_UpdatesAutoStartAccordingly() } [Fact] - public async Task ApplyAsync_WhenSaveThrows_DoesNotUpdateAutoStartOrFireEvent() + public async Task ApplyAsync_WhenSaveThrows_DoesNotUpdateAutoStart() { var failingService = new ThrowingSaveSettingsService(new IOException("Disk full")); var fakeStartup = new FakeStartupManager(); var appService = new SettingsApplicationService(failingService, fakeStartup); - bool eventFired = false; - appService.SettingsApplied += (_, _) => eventFired = true; - var settings = new NotchSettings { AutoStart = true }; await Assert.ThrowsAsync(() => appService.ApplyAsync(settings)); Assert.True(fakeStartup.SetAutoStartCalled); Assert.False(fakeStartup.AutoStartEnabled); - Assert.False(eventFired); } [Fact] @@ -119,15 +105,12 @@ await Assert.ThrowsAnyAsync(() => } [Fact] - public async Task FailedStartupRegistrationDoesNotPublishSettingsAsApplied() + public async Task FailedStartupRegistrationDoesNotPersistSettings() { var startup = new FakeStartupManager { SetFailure = new System.ComponentModel.Win32Exception(5) }; var settings = new FakeSettingsService(); var service = new SettingsApplicationService(settings, startup); - bool published = false; - service.SettingsApplied += (_, _) => published = true; await Assert.ThrowsAsync(() => service.ApplyAsync(new NotchSettings { AutoStart = true })); - Assert.False(published); Assert.Null(settings.LastSaved); } @@ -139,16 +122,12 @@ public async Task ImportAsync_ImportsFromFile_AppliesSettings_AndReturnsResult() var fakeStartup = new FakeStartupManager(); var appService = new SettingsApplicationService(fakeService, fakeStartup); - NotchSettings? eventArgs = null; - appService.SettingsApplied += (_, args) => eventArgs = args; - var result = await appService.ImportAsync("dummy_path.vns"); Assert.Same(importedSettings, result.Settings); Assert.True(result.RequiresRestart); Assert.True(importedSettings.ValueEquals(fakeService.LastSaved)); Assert.True(fakeStartup.AutoStartEnabled); - Assert.True(importedSettings.ValueEquals(eventArgs)); } [Fact] diff --git a/Tests/SettingsNormalizationImportTests.cs b/Tests/SettingsNormalizationImportTests.cs index fc0ae29a..6fa49c54 100644 --- a/Tests/SettingsNormalizationImportTests.cs +++ b/Tests/SettingsNormalizationImportTests.cs @@ -298,54 +298,4 @@ public void LoadSettings_ClampsOutOfRangeAndNullLiquidGlass_AndPersistsNormalize Assert.Equal(100, persisted.HoverCollapseDelay); Assert.Equal(0, persisted.GpuPreference); } - - [Fact] - public void NormalizeSettings_SanitizesNaNAndInfinityFieldsToDefaults() - { - var method = typeof(SettingsService).GetMethod("NormalizeSettings", BindingFlags.NonPublic | BindingFlags.Static); - Assert.NotNull(method); - - var settings = new NotchSettings - { - AnimationSpeed = double.NaN, - MediaBlurBrightnessBoost = double.PositiveInfinity, - MediaBlurDarkOverlay = double.NegativeInfinity, - CompactExpandMultiplier = double.NaN, - MediumExpandMultiplier = double.PositiveInfinity, - LargeExpandMultiplier = double.NegativeInfinity, - DebugWindowX = double.NaN, - DebugWindowY = double.PositiveInfinity, - LiquidGlass = new LiquidGlassConfig - { - BlurAmount = double.NaN, - Refraction = double.PositiveInfinity, - EdgeBend = double.NegativeInfinity, - ChromaticAberration = double.NaN, - Noise = double.NaN, - Opacity = double.NaN - } - }; - - bool changed = (bool)method!.Invoke(null, [settings])!; - Assert.True(changed); - - Assert.Equal(2.0, settings.AnimationSpeed, precision: 6); - Assert.Equal(2.0, settings.MediaBlurBrightnessBoost, precision: 6); - Assert.Equal(0.0, settings.MediaBlurDarkOverlay, precision: 6); - Assert.Equal(1.2, settings.CompactExpandMultiplier, precision: 6); - Assert.Equal(1.8, settings.MediumExpandMultiplier, precision: 6); - Assert.Equal(2.5, settings.LargeExpandMultiplier, precision: 6); - Assert.Null(settings.DebugWindowX); - Assert.Null(settings.DebugWindowY); - Assert.Equal(0.3, settings.LiquidGlass.BlurAmount, precision: 6); - Assert.Equal(1.0, settings.LiquidGlass.Refraction, precision: 6); - Assert.Equal(1.65, settings.LiquidGlass.EdgeBend, precision: 6); - Assert.Equal(0.56, settings.LiquidGlass.ChromaticAberration, precision: 6); - Assert.Equal(0.066, settings.LiquidGlass.Noise, precision: 6); - Assert.Equal(1.0, settings.LiquidGlass.Opacity, precision: 6); - - // Second pass on already-normalized settings must report no changes - bool changedAgain = (bool)method.Invoke(null, [settings])!; - Assert.False(changedAgain); - } } diff --git a/Tests/SettingsWindowControlTests.cs b/Tests/SettingsWindowControlTests.cs index a1e3a390..045e0164 100644 --- a/Tests/SettingsWindowControlTests.cs +++ b/Tests/SettingsWindowControlTests.cs @@ -1938,16 +1938,13 @@ public void SettingsSaveClosesEverySectionOnceAndPersistsSnapshot(string section window.Top = 20; window.Left = 20; window.NavigateToSection(section); - int closing = 0; bool closed = false; - window.AnimatedClosing += (_, _) => closing++; window.Closed += (_, _) => closed = true; window.WidthSlider.Value = 400; window.Save_Click(window, new RoutedEventArgs()); window.CloseWithAnimation(); await WpfFrameWaiter.UntilAsync(() => closed && fixture.Service.Applied != null, "settings save and close", ct); Assert.Equal(400, fixture.Service.Applied!.Width); - Assert.Equal(1, closing); Assert.Equal(0, window.Opacity); } finally { AnimationConfig.SetReduceMotion(previousReducedMotion); } @@ -1961,16 +1958,13 @@ public void SettingsApplyClosesWindowEvenDuringEntranceTailAndPersistsSnapshot() window.Top = 20; window.Left = 20; window.PlayEntranceAnimation(); - int closing = 0; bool closed = false; - window.AnimatedClosing += (_, _) => closing++; window.Closed += (_, _) => closed = true; window.WidthSlider.Value = 380; window.Apply_Click(window, new RoutedEventArgs()); window.CloseWithAnimation(); await WpfFrameWaiter.UntilAsync(() => closed && fixture.Service.Applied != null, "settings apply and close", ct); Assert.Equal(380, fixture.Service.Applied!.Width); - Assert.Equal(1, closing); Assert.Equal(0, window.Opacity); }); @@ -2359,13 +2353,11 @@ private sealed class RecordingService : ISettingsApplicationService public Task ApplyAsync(NotchSettings settings, CancellationToken ct = default) { Applied = settings.Clone(); - SettingsApplied?.Invoke(this, Applied); return Task.CompletedTask; } public Task<(NotchSettings Settings, bool RequiresRestart)> ImportAsync(string filePath, NotchSettings? currentSettings = null, CancellationToken ct = default) => Task.FromResult((new NotchSettings(), false)); public void Export(string filePath, NotchSettings settings) { } public bool IsAutoStartEnabled() => false; - public event EventHandler? SettingsApplied; } } diff --git a/Tests/SettingsWindowDecouplingTests.cs b/Tests/SettingsWindowDecouplingTests.cs index 9570755d..b5a7f5ab 100644 --- a/Tests/SettingsWindowDecouplingTests.cs +++ b/Tests/SettingsWindowDecouplingTests.cs @@ -405,7 +405,6 @@ public async Task ApplyAsync(NotchSettings settings, CancellationToken ct = defa ApplyCount++; if (CompleteApply != null) await CompleteApply(); AppliedSettings = settings; - SettingsApplied?.Invoke(this, settings); } public Task<(NotchSettings Settings, bool RequiresRestart)> ImportAsync(string filePath, NotchSettings? currentSettings = null, CancellationToken ct = default) @@ -418,7 +417,5 @@ public void Export(string filePath, NotchSettings settings) } public bool IsAutoStartEnabled() => false; - - public event EventHandler? SettingsApplied; } } diff --git a/Tests/SmartCropRuntimeLifetimeTests.cs b/Tests/SmartCropRuntimeLifetimeTests.cs deleted file mode 100644 index 1fa354e6..00000000 --- a/Tests/SmartCropRuntimeLifetimeTests.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.IO; -using VNotch.Interop; -using Xunit; - -namespace VNotch.Tests; - -[Collection("Localization")] -public sealed class SmartCropRuntimeLifetimeTests -{ - [Fact] - public void RuntimeSurvivesAnotherSessionsDisposalAndCanReloadAfterTheLastSession() - { - const int width = 160, height = 96, stride = width * 4; - var pixels = new byte[height * stride]; - new Random(42).NextBytes(pixels); - var detections = new ImagingNative.VnCoreDetection[SmartCropSessionSafeHandle.MinDetectionCapacity]; - int? previousCount = null; - for (int cycle = 0; cycle < 3; cycle++) - { - SmartCropSessionSafeHandle? first = null; - SmartCropSessionSafeHandle? second = null; - try - { - first = CreateSession(); - second = CreateSession(); - first.Dispose(); - first = null; - int count = second.Infer(pixels, width, height, stride, detections, out bool usedDml); - Assert.False(usedDml); - if (previousCount.HasValue) Assert.Equal(previousCount.Value, count); - previousCount = count; - } - finally - { - first?.Dispose(); - second?.Dispose(); - } - } - } - - [Fact] - public void FailedSessionConstructionDoesNotPoisonTheNextRuntimeLoad() - { - string directory = AppContext.BaseDirectory; - string missingModel = Path.Combine(directory, "Models", "missing-memory-test.onnx"); - Assert.ThrowsAny(() => SmartCropSessionSafeHandle.Create(missingModel, directory, preferDml: false)); - using var valid = CreateSession(); - Assert.False(valid.IsInvalid); - } - - private static SmartCropSessionSafeHandle CreateSession() - { - string directory = AppContext.BaseDirectory; - string model = Path.Combine(directory, "Models", "yolox_nano.onnx"); - Assert.True(File.Exists(model)); - (SmartCropSessionSafeHandle handle, bool usedDml) = SmartCropSessionSafeHandle.Create(model, directory, preferDml: false); - Assert.False(handle.IsInvalid); - Assert.False(usedDml); - return handle; - } -} diff --git a/Tests/SpotlightNotchLocaleThumbnailTests.cs b/Tests/SpotlightNotchLocaleThumbnailTests.cs index e421deae..3e51dda3 100644 --- a/Tests/SpotlightNotchLocaleThumbnailTests.cs +++ b/Tests/SpotlightNotchLocaleThumbnailTests.cs @@ -39,7 +39,7 @@ public async Task ExcludedFolders_AddsRemovesAndPersistsOnRustPreferences() } [Fact] - public void NotchManager_UpdatePosition_ComputesGeometryOnceAndFiresSafeAreaChanged() + public void NotchManager_UpdatePosition_ComputesGeometryOnce() { var settings = new NotchSettings { @@ -48,20 +48,10 @@ public void NotchManager_UpdatePosition_ComputesGeometryOnceAndFiresSafeAreaChan }; using var manager = new NotchManager(settings); - Rect? observedSafeArea = null; - int safeAreaEvents = 0; - manager.SafeAreaChanged += (_, rect) => - { - safeAreaEvents++; - observedSafeArea = rect; - }; manager.UpdatePosition(); Assert.Equal(1, manager.GeometryComputeCount); - Assert.Equal(1, safeAreaEvents); - Assert.True(observedSafeArea.HasValue); - Assert.Equal(manager.SafeArea, observedSafeArea.Value); Assert.True(manager.SafeArea.Width > 0); Assert.True(manager.SafeArea.Height > 0); } diff --git a/Tests/ThumbnailHeuristicsTests.cs b/Tests/ThumbnailHeuristicsTests.cs deleted file mode 100644 index 1774e7d9..00000000 --- a/Tests/ThumbnailHeuristicsTests.cs +++ /dev/null @@ -1,391 +0,0 @@ -using System.IO; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using VNotch.Services; -using Xunit; - -namespace VNotch.Tests; - -public class ThumbnailHeuristicsTests -{ - - private static BitmapImage FromPixels(int width, int height, byte[] bgra) - { - var src = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgra32, null, bgra, width * 4); - var encoder = new PngBitmapEncoder(); - encoder.Frames.Add(BitmapFrame.Create(src)); - using var ms = new MemoryStream(); - encoder.Save(ms); - ms.Position = 0; - - var bmp = new BitmapImage(); - bmp.BeginInit(); - bmp.CacheOption = BitmapCacheOption.OnLoad; - bmp.StreamSource = ms; - bmp.EndInit(); - bmp.Freeze(); - return bmp; - } - - private static BitmapImage Solid(int width, int height, byte r, byte g, byte b) - { - var px = new byte[width * height * 4]; - for (int i = 0; i < px.Length; i += 4) - { - px[i] = b; px[i + 1] = g; px[i + 2] = r; px[i + 3] = 255; - } - return FromPixels(width, height, px); - } - - private static BitmapImage Colorful(int width, int height) - { - var px = new byte[width * height * 4]; - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - int i = (y * width + x) * 4; - bool red = ((x / 8) + (y / 8)) % 2 == 0; - px[i] = (byte)(red ? 0 : 255); - px[i + 1] = 0; - px[i + 2] = (byte)(red ? 255 : 0); - px[i + 3] = 255; - } - } - return FromPixels(width, height, px); - } - - #region IsLikelyPlaceholderThumbnail - - [Fact] - public void Placeholder_Null_True() - { - Assert.True(ThumbnailHeuristics.IsLikelyPlaceholderThumbnail(null)); - } - - [Fact] - public void Placeholder_SmallSquare_True() - { - Assert.True(ThumbnailHeuristics.IsLikelyPlaceholderThumbnail(Colorful(200, 200))); - } - - [Fact] - public void Placeholder_NonSquare_False() - { - Assert.False(ThumbnailHeuristics.IsLikelyPlaceholderThumbnail(Colorful(640, 320))); - } - - [Fact] - public void Placeholder_LargeSquare_LowEntropyGray_True() - { - Assert.True(ThumbnailHeuristics.IsLikelyPlaceholderThumbnail(Solid(500, 500, 235, 235, 235))); - } - - [Fact] - public void Placeholder_LargeSquare_Colorful_False() - { - Assert.False(ThumbnailHeuristics.IsLikelyPlaceholderThumbnail(Colorful(500, 500))); - } - - #endregion - - #region IsLikelyArtworkCandidate - - [Fact] - public void Candidate_Null_False() - { - Assert.False(ThumbnailHeuristics.IsLikelyArtworkCandidate(null)); - } - - [Fact] - public void Candidate_LargeColorfulSquare_True() - { - Assert.True(ThumbnailHeuristics.IsLikelyArtworkCandidate(Colorful(500, 500))); - } - - [Fact] - public void Candidate_TooSmall_False() - { - Assert.False(ThumbnailHeuristics.IsLikelyArtworkCandidate(Colorful(300, 300))); - } - - [Fact] - public void Candidate_NonSquare_False() - { - Assert.False(ThumbnailHeuristics.IsLikelyArtworkCandidate(Colorful(640, 360))); - } - - [Fact] - public void Candidate_CircularTransparentCornerBrowserIcon_False() - { - int width = 256, height = 256; - var px = new byte[width * height * 4]; - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - int i = (y * width + x) * 4; - double dx = x - 127.5, dy = y - 127.5; - if (dx * dx + dy * dy > 120.0 * 120.0) - { - px[i + 3] = 0; - continue; - } - px[i] = (byte)((x * 7 + y * 3) & 255); - px[i + 1] = (byte)((x * 5 + y * 11) & 255); - px[i + 2] = (byte)((x * 13 + y * 2) & 255); - px[i + 3] = 255; - } - } - var icon = FromPixels(width, height, px); - Assert.False(ThumbnailHeuristics.IsLikelyArtworkCandidate(icon)); - Assert.True(ThumbnailHeuristics.IsLikelyPlaceholderThumbnail(icon)); - } - - [Fact] - public void Candidate_LargeGraySquare_False() - { - Assert.False(ThumbnailHeuristics.IsLikelyArtworkCandidate(Solid(500, 500, 235, 235, 235))); - } - - [Fact] - public void Candidate_DarkNocturnal150x150SpotifyWebCover_True() - { - int width = 150, height = 150; - var px = new byte[width * height * 4]; - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - int i = (y * width + x) * 4; - byte lum = (byte)((x * 92 / width + y * 92 / height) / 2); - px[i] = (byte)(lum * 3 / 4); - px[i + 1] = (byte)(lum * 4 / 5); - px[i + 2] = lum; - px[i + 3] = 255; - } - } - var darkCover = FromPixels(width, height, px); - Assert.True(ThumbnailHeuristics.IsLikelyArtworkCandidate(darkCover)); - Assert.False(ThumbnailHeuristics.IsLikelyPlaceholderThumbnail(darkCover)); - } - - #endregion - - #region HasLowEntropyMonochromeProfile - - [Fact] - public void MonochromeProfile_LightGray_True() - { - Assert.True(ThumbnailHeuristics.HasLowEntropyMonochromeProfile(Solid(400, 400, 235, 235, 235))); - } - - [Fact] - public void MonochromeProfile_Colorful_False() - { - Assert.False(ThumbnailHeuristics.HasLowEntropyMonochromeProfile(Colorful(400, 400))); - } - - [Fact] - public void MonochromeProfile_SolidBlack_False() - { - Assert.False(ThumbnailHeuristics.HasLowEntropyMonochromeProfile(Solid(400, 400, 0, 0, 0))); - } - - #endregion - - #region DecideSmtcThumbnail - - private static readonly ThumbnailHeuristics.SmtcThumbnailInputs WideYouTube = new() - { - IsYouTubeLikeSource = true, - IsBrowserOrYouTubePlatform = true, - PixelWidth = 640, - PixelHeight = 360, - }; - - [Fact] - public void Decide_YouTubeWideFrame_OnTrackChange_Rejects() - { - Assert.Equal(ThumbnailHeuristics.SmtcThumbnailDecision.Reject, - ThumbnailHeuristics.DecideSmtcThumbnail(WideYouTube with { TrackChanged = true })); - } - - [Fact] - public void Decide_YouTubeSquareImage_AfterBrowserSessionReplacement_Rejects() - { - var inputs = new ThumbnailHeuristics.SmtcThumbnailInputs - { - IsYouTubeLikeSource = true, - IsBrowserOrYouTubePlatform = true, - TrackChanged = true, - BrowserSessionChanged = true, - HasVerifiedYouTubeThumb = false, - PixelWidth = 512, - PixelHeight = 512, - }; - - Assert.Equal( - ThumbnailHeuristics.SmtcThumbnailDecision.Reject, - ThumbnailHeuristics.DecideSmtcThumbnail(inputs)); - } - - [Fact] - public void Decide_YouTubeSquareImage_SameSession_CanStillBeAccepted() - { - var inputs = new ThumbnailHeuristics.SmtcThumbnailInputs - { - IsYouTubeLikeSource = true, - IsBrowserOrYouTubePlatform = true, - TrackChanged = true, - BrowserSessionChanged = false, - PixelWidth = 512, - PixelHeight = 512, - }; - - Assert.Equal( - ThumbnailHeuristics.SmtcThumbnailDecision.Accept, - ThumbnailHeuristics.DecideSmtcThumbnail(inputs)); - } - - [Fact] - public void Decide_LargeSquareBrowserIcon_WithoutVerifiedThumbnail_Skips() - { - var inputs = new ThumbnailHeuristics.SmtcThumbnailInputs - { - IsYouTubeLikeSource = true, - IsBrowserOrYouTubePlatform = true, - IsBrowserSession = true, - TrackChanged = true, - HasVerifiedYouTubeThumb = false, - PixelWidth = 512, - PixelHeight = 512, - }; - - Assert.Equal( - ThumbnailHeuristics.SmtcThumbnailDecision.Skip, - ThumbnailHeuristics.DecideSmtcThumbnail(inputs)); - } - - [Fact] - public void Decide_YouTubeWideFrame_RecentChangeNoCache_Rejects() - { - Assert.Equal(ThumbnailHeuristics.SmtcThumbnailDecision.Reject, - ThumbnailHeuristics.DecideSmtcThumbnail(WideYouTube with { RecentTrackChange = true, CachedThumbnailIsNull = true })); - } - - [Fact] - public void Decide_YouTubeWideFrame_StableTrackWithVerifiedThumb_Accepts() - { - Assert.Equal(ThumbnailHeuristics.SmtcThumbnailDecision.Accept, - ThumbnailHeuristics.DecideSmtcThumbnail(WideYouTube with - { - RecentTrackChange = true, - CachedThumbnailIsNull = false, - HasVerifiedYouTubeThumb = true, - })); - } - - [Fact] - public void Decide_YouTubeWideFrame_StableTrackNoVerifiedThumb_Skips() - { - Assert.Equal(ThumbnailHeuristics.SmtcThumbnailDecision.Skip, - ThumbnailHeuristics.DecideSmtcThumbnail(WideYouTube with { RecentTrackChange = true, CachedThumbnailIsNull = false })); - } - - [Fact] - public void Decide_SoundCloudNonArtwork_OnTrackChange_Rejects() - { - var inputs = new ThumbnailHeuristics.SmtcThumbnailInputs - { - IsSoundCloudSource = true, - TrackChanged = true, - HasVerifiedSoundCloudThumb = false, - LikelySoundCloudArtwork = false, - PixelWidth = 500, - PixelHeight = 500, - }; - Assert.Equal(ThumbnailHeuristics.SmtcThumbnailDecision.Reject, - ThumbnailHeuristics.DecideSmtcThumbnail(inputs)); - } - - [Fact] - public void Decide_SoundCloudRealArtwork_OnTrackChange_Accepts() - { - var inputs = new ThumbnailHeuristics.SmtcThumbnailInputs - { - IsSoundCloudSource = true, - TrackChanged = true, - LikelySoundCloudArtwork = true, - PixelWidth = 500, - PixelHeight = 500, - }; - Assert.Equal(ThumbnailHeuristics.SmtcThumbnailDecision.Accept, - ThumbnailHeuristics.DecideSmtcThumbnail(inputs)); - } - - [Fact] - public void Decide_LargeSquareArtwork_Accepts() - { - var inputs = new ThumbnailHeuristics.SmtcThumbnailInputs - { - TrackChanged = true, - PixelWidth = 640, - PixelHeight = 640, - }; - Assert.Equal(ThumbnailHeuristics.SmtcThumbnailDecision.Accept, - ThumbnailHeuristics.DecideSmtcThumbnail(inputs)); - } - - [Fact] - public void Decide_SmallSquareGenericIcon_Skips() - { - var inputs = new ThumbnailHeuristics.SmtcThumbnailInputs - { - IsBrowserOrYouTubePlatform = true, - TrackChanged = true, - PixelWidth = 256, - PixelHeight = 256, - }; - Assert.Equal(ThumbnailHeuristics.SmtcThumbnailDecision.Skip, - ThumbnailHeuristics.DecideSmtcThumbnail(inputs)); - } - - [Fact] - public void Decide_BrowserSessionIcon_AfterSpotifyWebDetection_SkipsUntilRealArtwork() - { - var iconInputs = new ThumbnailHeuristics.SmtcThumbnailInputs - { - IsBrowserOrYouTubePlatform = false, - IsBrowserSession = true, - TrackChanged = true, - LikelySoundCloudArtwork = false, - PixelWidth = 256, - PixelHeight = 256, - }; - Assert.Equal(ThumbnailHeuristics.SmtcThumbnailDecision.Skip, - ThumbnailHeuristics.DecideSmtcThumbnail(iconInputs)); - - var artworkInputs = iconInputs with { TrackChanged = false, LikelySoundCloudArtwork = true }; - Assert.Equal(ThumbnailHeuristics.SmtcThumbnailDecision.Accept, - ThumbnailHeuristics.DecideSmtcThumbnail(artworkInputs)); - } - - [Fact] - public void Decide_UnchangedYouTubeTrackWithoutVerifiedThumb_Skips() - { - var inputs = new ThumbnailHeuristics.SmtcThumbnailInputs - { - IsYouTubeLikeSource = true, - IsBrowserOrYouTubePlatform = true, - TrackChanged = false, - HasVerifiedYouTubeThumb = false, - PixelWidth = 640, - PixelHeight = 640, - }; - Assert.Equal(ThumbnailHeuristics.SmtcThumbnailDecision.Skip, - ThumbnailHeuristics.DecideSmtcThumbnail(inputs)); - } - - #endregion -} diff --git a/Tests/TranslationDownloadTests.cs b/Tests/TranslationDownloadTests.cs index b4eefc37..c9521a5f 100644 --- a/Tests/TranslationDownloadTests.cs +++ b/Tests/TranslationDownloadTests.cs @@ -148,8 +148,6 @@ public async Task ReimportKeepsVerifiedInstallationUsableAcrossFailureAndRetry() await File.WriteAllBytesAsync(source, DownloadFixture.Payload); await fixture.Store.ImportAsync(folder, default); File.SetAttributes(fixture.Final, FileAttributes.ReadOnly); - int replacements = 0; - fixture.Store.Replacing += () => replacements++; await File.WriteAllBytesAsync(source, [1, 2, 3]); await Assert.ThrowsAsync(() => fixture.Store.ImportAsync(folder, default)); @@ -159,7 +157,6 @@ public async Task ReimportKeepsVerifiedInstallationUsableAcrossFailureAndRetry() await File.WriteAllBytesAsync(source, DownloadFixture.Payload); await fixture.Store.ImportAsync(folder, default); Assert.True(fixture.Store.IsInstalled); - Assert.Equal(0, replacements); Assert.Equal(DownloadFixture.Payload, await File.ReadAllBytesAsync(fixture.Final)); } finally diff --git a/Tests/WebcamFramePipelineTests.cs b/Tests/WebcamFramePipelineTests.cs index e9f5b9c6..ec59d704 100644 --- a/Tests/WebcamFramePipelineTests.cs +++ b/Tests/WebcamFramePipelineTests.cs @@ -8,157 +8,6 @@ namespace VNotch.Tests; public sealed class WebcamFramePipelineTests { - [Fact] - public unsafe void ValidateAndCopyPlaneConvertsIntoPitchedRowsAndPreservesPadding() - { - byte[] pixels = Enumerable.Range(0, 24).Select(i => (byte)i).ToArray(); - const int width = 8; - const int height = 3; - const int pitch = 40; - byte[] output = Enumerable.Repeat((byte)0xCD, pitch * height).ToArray(); - - fixed (byte* pSrc = pixels) - fixed (byte* pDst = output) - { - var req = new M13Native.VnWebcamPlaneCopyRequest - { - Src = pSrc, - Desc = new M13Native.VnWebcamPlaneDesc - { - Width = width, - Height = height, - StartIndex = 0, - Stride = width, - BufferCapacity = (uint)pixels.Length, - }, - SrcCap = (uint)pixels.Length, - Format = M13Native.PixelFormatGray8, - AlphaMode = 2, - Dst = pDst, - DstPitch = pitch, - Reserved = 0, - }; - Assert.Equal((int)NativeStatus.Ok, M13Native.ValidateAndCopyPlane(in req)); - } - - for (int row = 0; row < height; row++) - { - for (int x = 0; x < width; x++) - { - byte value = pixels[row * width + x]; - Assert.Equal(new byte[] { value, value, value, 255 }, output.AsSpan(row * pitch + x * 4, 4).ToArray()); - } - - Assert.All(output.Skip(row * pitch + 32).Take(8), b => Assert.Equal(0xCD, b)); - } - } - - [Fact] - public unsafe void ValidateAndCopyPlaneSupportsNegativeBottomUpStride() - { - byte[] src = { 10, 20, 30, 40 }; - byte[] dst = Enumerable.Repeat((byte)0xA5, 24).ToArray(); - fixed (byte* pSrc = src) - fixed (byte* pDst = dst) - { - var req = new M13Native.VnWebcamPlaneCopyRequest - { - Src = pSrc, - Desc = new M13Native.VnWebcamPlaneDesc - { - Width = 2, - Height = 2, - StartIndex = 2, - Stride = -2, - BufferCapacity = (uint)src.Length, - }, - SrcCap = (uint)src.Length, - Format = M13Native.PixelFormatGray8, - AlphaMode = 2, - Dst = pDst, - DstPitch = 12, - Reserved = 0, - }; - Assert.Equal((int)NativeStatus.Ok, M13Native.ValidateAndCopyPlane(in req)); - } - - Assert.Equal(new byte[] { 30, 30, 30, 255, 40, 40, 40, 255 }, dst.AsSpan(0, 8).ToArray()); - Assert.All(dst.AsSpan(8, 4).ToArray(), b => Assert.Equal(0xA5, b)); - Assert.Equal(new byte[] { 10, 10, 10, 255, 20, 20, 20, 255 }, dst.AsSpan(12, 8).ToArray()); - } - - [Theory] - [InlineData(BitmapPixelFormat.Nv12, 8, 4, M13Native.PixelFormatNv12)] - [InlineData(BitmapPixelFormat.Nv12, 10, 6, M13Native.PixelFormatNv12)] - [InlineData(BitmapPixelFormat.Yuy2, 8, 4, M13Native.PixelFormatYuy2)] - [InlineData(BitmapPixelFormat.Yuy2, 10, 6, M13Native.PixelFormatYuy2)] - [InlineData(BitmapPixelFormat.Gray8, 8, 4, M13Native.PixelFormatGray8)] - [InlineData(BitmapPixelFormat.Bgra8, 8, 4, M13Native.PixelFormatBgra8)] - [InlineData(BitmapPixelFormat.Rgba8, 8, 4, M13Native.PixelFormatRgba8)] - public unsafe void PlaneCopyMatchesPlatformConversionAndLeavesHeadroomUntouched( - BitmapPixelFormat format, - int width, - int height, - uint nativeFormat) - { - int size = width * height * 4; - byte[] input = format switch - { - BitmapPixelFormat.Nv12 => Enumerable.Range(0, width * height).Select(i => (byte)(16 + i * 7)) - .Concat(Enumerable.Range(0, width * height / 4).SelectMany(_ => new byte[] { 90, 240 })).ToArray(), - BitmapPixelFormat.Yuy2 => Enumerable.Range(0, width * height / 2) - .SelectMany(i => new byte[] { (byte)(16 + i * 14), 90, (byte)(23 + i * 14), 240 }).ToArray(), - BitmapPixelFormat.Gray8 => Enumerable.Range(0, width * height).Select(i => (byte)(i * 8)).ToArray(), - _ => Enumerable.Range(0, width * height).SelectMany(_ => new byte[] { 50, 100, 200, 128 }).ToArray(), - }; - BitmapAlphaMode alpha = format is BitmapPixelFormat.Bgra8 or BitmapPixelFormat.Rgba8 - ? BitmapAlphaMode.Straight - : BitmapAlphaMode.Ignore; - using var bitmap = SoftwareBitmap.CreateCopyFromBuffer(input.AsBuffer(), format, width, height, alpha); - using var converted = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); - byte[] expected = new byte[size]; - converted.CopyToBuffer(expected.AsBuffer()); - - int srcStride = format switch - { - BitmapPixelFormat.Nv12 => width, - BitmapPixelFormat.Gray8 => width, - BitmapPixelFormat.Yuy2 => width * 2, - _ => width * 4, - }; - byte[] output = Enumerable.Repeat((byte)0xCD, size + 64).ToArray(); - fixed (byte* pSrc = input) - fixed (byte* pDst = output) - { - var req = new M13Native.VnWebcamPlaneCopyRequest - { - Src = pSrc, - Desc = new M13Native.VnWebcamPlaneDesc - { - Width = width, - Height = height, - StartIndex = 0, - Stride = srcStride, - BufferCapacity = (uint)input.Length, - }, - SrcCap = (uint)input.Length, - Format = nativeFormat, - AlphaMode = (int)alpha, - Dst = pDst, - DstPitch = width * 4, - Reserved = 0, - }; - Assert.Equal((int)NativeStatus.Ok, M13Native.ValidateAndCopyPlane(in req)); - } - - for (int i = 0; i < size; i++) - { - Assert.InRange(Math.Abs(output[i] - expected[i]), 0, 2); - } - - Assert.All(output.Skip(size), value => Assert.Equal(0xCD, value)); - } - [Fact] public async Task RepeatedStopAndRestartCyclesKeepSingleGenerationAndCompleteCleanly() { diff --git a/Tests/WebcamTestSurfaceHelper.cs b/Tests/WebcamTestSurfaceHelper.cs index 3775365e..f1016fc3 100644 --- a/Tests/WebcamTestSurfaceHelper.cs +++ b/Tests/WebcamTestSurfaceHelper.cs @@ -8,8 +8,6 @@ namespace VNotch.Tests; internal static class WebcamTestSurfaceHelper { - private const int AlphaModeIgnore = 2; - internal static unsafe bool UploadBgra8( D3DImageFramePresenter presenter, byte[] pixels, @@ -46,27 +44,16 @@ private static unsafe void WriteBgra8ToSurface(nint surfacePtr, byte[] pixels, i { fixed (byte* pSrc = pixels) { - var req = new M13Native.VnWebcamPlaneCopyRequest + int rowBytes = checked(width * 4); + byte* dst = (byte*)locked.DataPointer; + for (int y = 0; y < height; y++) { - Src = pSrc, - Desc = new M13Native.VnWebcamPlaneDesc - { - Width = width, - Height = height, - StartIndex = 0, - Stride = checked(width * 4), - BufferCapacity = (uint)pixels.Length, - }, - SrcCap = (uint)pixels.Length, - Format = M13Native.PixelFormatBgra8, - AlphaMode = AlphaModeIgnore, - Dst = (byte*)locked.DataPointer, - DstPitch = locked.Pitch, - Reserved = 0, - }; - NativeResult.RequireSuccess( - M13Native.ValidateAndCopyPlane(in req), - nameof(M13Native.ValidateAndCopyPlane)); + Buffer.MemoryCopy( + pSrc + (y * rowBytes), + dst + (y * locked.Pitch), + locked.Pitch, + rowBytes); + } } } finally diff --git a/Tools/Assert-UpdateCompatibility.ps1 b/Tools/Assert-UpdateCompatibility.ps1 index 2a0f6a4b..942a70b9 100644 --- a/Tools/Assert-UpdateCompatibility.ps1 +++ b/Tools/Assert-UpdateCompatibility.ps1 @@ -63,17 +63,45 @@ try { foreach ($dependency in 'NativeWinHttpHandler', 'Win32Interop', 'Win32Interop.Process', 'WindowAnimationPolicy') { [IO.File]::WriteAllText((Join-Path $temporary "$dependency.cs"), (Read-Legacy "Services/$dependency.cs")) } + # Preserve binary bytes and the installed client's native trust policy. + # Redirect stdin/stderr as well so git.exe never inherits Start-Job's + # pwsh -ServerMode IPC pipe and deadlocks Wait-Job in CI. + $start = [Diagnostics.ProcessStartInfo]::new((Get-Command git).Source) + $start.UseShellExecute = $false + $start.CreateNoWindow = $true + $start.RedirectStandardInput = $true + $start.RedirectStandardOutput = $true + $start.RedirectStandardError = $true + $start.ArgumentList.Add('-C'); $start.ArgumentList.Add($repository) + $start.ArgumentList.Add('--no-pager') + $start.ArgumentList.Add('show'); $start.ArgumentList.Add("${legacyCommit}:Native/out/VNotch.Native.dll") + $process = [Diagnostics.Process]::Start($start) + $process.StandardInput.Close() + $file = [IO.File]::Create((Join-Path $temporary 'VNotch.Native.dll')) + try { $process.StandardOutput.BaseStream.CopyTo($file) } finally { $file.Dispose() } + $null = $process.StandardError.ReadToEnd() + $process.WaitForExit() + if ($process.ExitCode -ne 0) { throw 'The installed client native library is required.' } + $process.Dispose() } } if ($useCurrentUpdater) { Copy-Item -LiteralPath (Join-Path $repository 'Services/AppVersion.cs') -Destination $temporary - Copy-Item -LiteralPath (Join-Path $repository 'Services/Win32Interop.cs') -Destination $temporary - Copy-Item -LiteralPath (Join-Path $repository 'Services/Win32Interop.Process.cs') -Destination $temporary - Copy-Item -LiteralPath (Join-Path $repository 'Services/WindowAnimationPolicy.cs') -Destination $temporary - $rustDll = Join-Path $repository 'rust/target/release/vnotch_rust.dll' - if (Test-Path -LiteralPath $rustDll -PathType Leaf) { - Copy-Item -LiteralPath $rustDll -Destination $temporary + foreach ($interop in 'NativeAbi', 'NativeStatus', 'VNotchSafeHandle', 'VnOwnedBytes', 'Sha256SafeHandle', 'SecurityNative', 'UpdaterSafeHandle') { + Copy-Item -LiteralPath (Join-Path $repository "Interop/$interop.cs") -Destination $temporary } + $rustDllCandidates = @( + $env:VNotchRustArtifactPath + (Join-Path $repository 'artifacts/native/vnotch_rust.dll') + (Join-Path $repository 'rust/target/release/vnotch_rust.dll') + (Join-Path $repository 'bin/Release/net10.0-windows10.0.19041.0/vnotch_rust.dll') + (Join-Path $repository 'bin/Debug/net10.0-windows10.0.19041.0/vnotch_rust.dll') + ) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } + $rustDll = $rustDllCandidates | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | Select-Object -First 1 + if (-not $rustDll) { + throw 'The current updater native library (vnotch_rust.dll) is required.' + } + Copy-Item -LiteralPath $rustDll -Destination (Join-Path $temporary 'vnotch_rust.dll') } [IO.File]::WriteAllText((Join-Path $temporary 'update-public-key.pem'), $legacyPem) Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'UpdateCompatibility/Program.cs') -Destination $temporary @@ -91,6 +119,7 @@ try { + diff --git a/Tools/TestSupport/NativeSessionReplacementTests.cpp b/Tools/TestSupport/NativeSessionReplacementTests.cpp deleted file mode 100644 index 0197e848..00000000 --- a/Tools/TestSupport/NativeSessionReplacementTests.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "../../Native/vnotch_session_replacement.h" -#include -#include -#include - -struct Session { - static inline int live = 0; - Session() { ++live; } - ~Session() { --live; } -}; - -int main() { - auto session = std::make_unique(); - vnotch::ReplaceSession(session, [] { - assert(Session::live == 0); // CPU allocation must not overlap the previous GPU session. - return std::make_unique(); - }); - assert(session && Session::live == 1); - try { - vnotch::ReplaceSession(session, []() -> std::unique_ptr { - assert(Session::live == 0); - throw std::runtime_error("CPU allocation failure"); - }); - assert(false); - } catch (const std::runtime_error&) { } - assert(!session && Session::live == 0); - vnotch::ReplaceSession(session, [] { return std::make_unique(); }); - assert(session && Session::live == 1); - session.reset(); - assert(Session::live == 0); -} diff --git a/V-Notch.csproj b/V-Notch.csproj index 13466ccf..e670e8d0 100644 --- a/V-Notch.csproj +++ b/V-Notch.csproj @@ -96,7 +96,6 @@ - diff --git a/Windows/MainWindow.LiquidGlass.cs b/Windows/MainWindow.LiquidGlass.cs index 8175bc6d..8da273b7 100644 --- a/Windows/MainWindow.LiquidGlass.cs +++ b/Windows/MainWindow.LiquidGlass.cs @@ -1161,12 +1161,6 @@ private void QueueGlassRendererRebuildIfTooSmall(int width, int height, double d private static bool IsSystemTransparencyEnabled() => LiquidGlassSurfaceBinder.ReadSystemTransparencySetting(); -#pragma warning disable S1144 // Invoked via reflection in MainWindowGlassPresentationTests - private void UpdateDynamicGlassTint() - { - if (GlassDarkOverlay != null) GlassDarkOverlay.Opacity = 0; - } - private double _lastActualHeight = -1; private double _lastDynamicTopCornerR = -1; private double _lastDynamicBottomCornerR = -1; diff --git a/Windows/MainWindow.xaml b/Windows/MainWindow.xaml index ffb4430b..2b0b2da2 100644 --- a/Windows/MainWindow.xaml +++ b/Windows/MainWindow.xaml @@ -53,45 +53,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0.16,1 0.3,1 - @@ -150,18 +147,6 @@ - - - - - - - - -