From 5c3303db3c75a87665e86cd7a51e85c51674992b Mon Sep 17 00:00:00 2001 From: VirtualGIT20 <149660135+VirtualGIT20@users.noreply.github.com> Date: Fri, 11 Sep 2026 19:57:40 +0200 Subject: [PATCH] feat: add Desktop to Fullscreen boot transition --- PlayniteBoot/Localization/en_US.xaml | 2 + PlayniteBoot/Localization/it_IT.xaml | 2 + .../Models/PlayniteBootSettingsData.cs | 4 +- PlayniteBoot/PlayniteBoot.csproj | 1 + PlayniteBoot/PlayniteBootPlugin.cs | 25 ++ PlayniteBoot/PlayniteBootSettings.cs | 7 + PlayniteBoot/PlayniteBootSettingsView.xaml | 5 + PlayniteBoot/RuntimeTemplate/PlayniteBoot.ps1 | 101 +++++++- .../RuntimeTemplate/SwitchBootstrap.ps1 | 177 +++++++++++++ PlayniteBoot/RuntimeTemplate/VERSION.txt | 2 +- .../DesktopFullscreenSwitchService.cs | 232 ++++++++++++++++++ PlayniteBoot/Services/RuntimeInstaller.cs | 61 ++++- 12 files changed, 608 insertions(+), 11 deletions(-) create mode 100644 PlayniteBoot/RuntimeTemplate/SwitchBootstrap.ps1 create mode 100644 PlayniteBoot/Services/DesktopFullscreenSwitchService.cs diff --git a/PlayniteBoot/Localization/en_US.xaml b/PlayniteBoot/Localization/en_US.xaml index b20eb88..257b6c6 100644 --- a/PlayniteBoot/Localization/en_US.xaml +++ b/PlayniteBoot/Localization/en_US.xaml @@ -42,10 +42,12 @@ Wait for the video to finish before revealing Playnite Loop the video Hide the mouse cursor + Show the boot screen when switching from Desktop to Fullscreen Mute video audio Enable runtime logging Enable streaming preload integration + Covers Playnite's built-in Desktop to Fullscreen transition with the configured boot video. Playnite starts in the background immediately, but the overlay fades only after Playnite is ready and the video reaches its natural end. Looping is unavailable while waiting for the natural end of the video. Ignored while waiting for the complete video. diff --git a/PlayniteBoot/Localization/it_IT.xaml b/PlayniteBoot/Localization/it_IT.xaml index 54a501a..b404dba 100644 --- a/PlayniteBoot/Localization/it_IT.xaml +++ b/PlayniteBoot/Localization/it_IT.xaml @@ -42,10 +42,12 @@ Attendi la fine del video prima di mostrare Playnite Ripeti il video Nascondi il cursore del mouse + Mostra la schermata di avvio quando passi da Desktop a Fullscreen Disattiva l'audio del video Abilita log del runtime Abilita integrazione preload streaming + Copre la transizione integrata di Playnite da Desktop a Fullscreen con il video di avvio configurato. Playnite parte subito in background, ma l'overlay sfuma solo quando Playnite è pronta e il video raggiunge la fine naturale. La ripetizione non è disponibile quando si attende la fine naturale del video. Ignorata quando si attende il video completo. diff --git a/PlayniteBoot/Models/PlayniteBootSettingsData.cs b/PlayniteBoot/Models/PlayniteBootSettingsData.cs index 204ed57..e264c72 100644 --- a/PlayniteBoot/Models/PlayniteBootSettingsData.cs +++ b/PlayniteBoot/Models/PlayniteBootSettingsData.cs @@ -5,7 +5,7 @@ namespace PlayniteBoot.Models { public class PlayniteBootSettingsData : ObservableObject { - public const int CurrentSettingsVersion = 2; + public const int CurrentSettingsVersion = 3; private int settingsVersion; private string playniteExecutable = "auto"; @@ -27,6 +27,7 @@ public class PlayniteBootSettingsData : ObservableObject private int fadeInMilliseconds = 80; private int fadeOutMilliseconds = 400; private bool hideMouseCursor = true; + private bool enableDesktopFullscreenSwitch = true; private bool logEnabled = true; private string shortcutName = "Playnite Fullscreen"; private StreamingSettings streaming = new StreamingSettings(); @@ -81,6 +82,7 @@ public double Volume public int FadeInMilliseconds { get => fadeInMilliseconds; set => SetValue(ref fadeInMilliseconds, value); } public int FadeOutMilliseconds { get => fadeOutMilliseconds; set => SetValue(ref fadeOutMilliseconds, value); } public bool HideMouseCursor { get => hideMouseCursor; set => SetValue(ref hideMouseCursor, value); } + public bool EnableDesktopFullscreenSwitch { get => enableDesktopFullscreenSwitch; set => SetValue(ref enableDesktopFullscreenSwitch, value); } public bool LogEnabled { get => logEnabled; set => SetValue(ref logEnabled, value); } public string ShortcutName { get => shortcutName; set => SetValue(ref shortcutName, value); } public StreamingSettings Streaming { get => streaming; set => SetValue(ref streaming, value); } diff --git a/PlayniteBoot/PlayniteBoot.csproj b/PlayniteBoot/PlayniteBoot.csproj index 51a1af2..feacc3c 100644 --- a/PlayniteBoot/PlayniteBoot.csproj +++ b/PlayniteBoot/PlayniteBoot.csproj @@ -73,6 +73,7 @@ + diff --git a/PlayniteBoot/PlayniteBootPlugin.cs b/PlayniteBoot/PlayniteBootPlugin.cs index a3974b8..2e2dbda 100644 --- a/PlayniteBoot/PlayniteBootPlugin.cs +++ b/PlayniteBoot/PlayniteBootPlugin.cs @@ -18,6 +18,7 @@ public class PlayniteBootPlugin : GenericPlugin private readonly RuntimeInstaller runtimeInstaller; private readonly RuntimeConfigWriter configWriter; private readonly ShortcutService shortcutService; + private readonly DesktopFullscreenSwitchService desktopFullscreenSwitchService; private readonly object runtimeOperationLock = new object(); public override Guid Id { get; } = Guid.Parse("71b5c099-3c25-4fe7-b26f-1262c7f0e138"); @@ -34,6 +35,9 @@ public PlayniteBootPlugin(IPlayniteAPI api) : base(api) configWriter = new RuntimeConfigWriter(Paths, PlayniteApi.Paths.ConfigurationPath); shortcutService = new ShortcutService(Paths); SettingsViewModel = new PlayniteBootSettingsViewModel(this); + desktopFullscreenSwitchService = new DesktopFullscreenSwitchService( + Paths, + () => SettingsViewModel.Settings.EnableDesktopFullscreenSwitch); Properties = new GenericPluginProperties { @@ -53,6 +57,22 @@ public override UserControl GetSettingsView(bool firstRunSettings) public override void OnApplicationStarted(OnApplicationStartedEventArgs args) { + if (PlayniteApi.ApplicationInfo.Mode == ApplicationMode.Desktop) + { + try + { + var appWindow = PlayniteApi.Dialogs.GetCurrentAppWindow(); + if (!desktopFullscreenSwitchService.Attach(appWindow)) + { + logger.Warn(ProductName + " could not attach Desktop-to-Fullscreen switch handling to the Playnite window."); + } + } + catch (Exception exception) + { + logger.Error(exception, ProductName + " failed to attach Desktop-to-Fullscreen switch handling."); + } + } + // Take a snapshot on Playnite's UI thread, then perform disk work in // the background. All runtime mutations are serialized by the lock. var settingsSnapshot = Serialization.GetClone(SettingsViewModel.Settings); @@ -69,6 +89,11 @@ public override void OnApplicationStarted(OnApplicationStartedEventArgs args) }); } + public override void OnApplicationStopped(OnApplicationStoppedEventArgs args) + { + desktopFullscreenSwitchService.Detach(); + } + public RuntimeInstallResult PrepareRuntime(PlayniteBootSettingsData settings, bool forceUpdate) { lock (runtimeOperationLock) diff --git a/PlayniteBoot/PlayniteBootSettings.cs b/PlayniteBoot/PlayniteBootSettings.cs index d212d25..98c5133 100644 --- a/PlayniteBoot/PlayniteBootSettings.cs +++ b/PlayniteBoot/PlayniteBootSettings.cs @@ -341,6 +341,12 @@ private void EnsureDefaultsAndMigrate() // Follow Playnite is selected later. settings.MonitorFallback = settings.Monitor; } + if (settings.SettingsVersion < 3) + { + // The Desktop -> Fullscreen boot transition is enabled by default + // for both new and existing installations. + settings.EnableDesktopFullscreenSwitch = true; + } settings.SettingsVersion = PlayniteBootSettingsData.CurrentSettingsVersion; @@ -753,6 +759,7 @@ private string BuildDiagnostics() b.AppendLine("Config version: " + RuntimeConfigWriter.CurrentConfigVersion); b.AppendLine("Mode: " + (Settings.WaitForVideoEnd ? "waitForVideoEnd" : "readyAndMinimumDuration")); b.AppendLine("Streaming preload: " + (Settings.Streaming != null && Settings.Streaming.Enabled ? "enabled" : "disabled")); + b.AppendLine("Desktop -> Fullscreen boot: " + (Settings.EnableDesktopFullscreenSwitch ? "enabled" : "disabled")); b.AppendLine("Runtime installed: " + YesNo(File.Exists(plugin.Paths.ScriptPath) && File.Exists(plugin.Paths.ConfigPath))); b.AppendLine("Video exists: " + YesNo(videoExists)); b.AppendLine("Desktop shortcut: " + YesNo(plugin.ShortcutExists(Settings, ShortcutLocation.Desktop))); diff --git a/PlayniteBoot/PlayniteBootSettingsView.xaml b/PlayniteBoot/PlayniteBootSettingsView.xaml index a9f8017..7168d23 100644 --- a/PlayniteBoot/PlayniteBootSettingsView.xaml +++ b/PlayniteBoot/PlayniteBootSettingsView.xaml @@ -26,6 +26,7 @@ + + diff --git a/PlayniteBoot/RuntimeTemplate/PlayniteBoot.ps1 b/PlayniteBoot/RuntimeTemplate/PlayniteBoot.ps1 index 8a7d901..5470680 100644 --- a/PlayniteBoot/RuntimeTemplate/PlayniteBoot.ps1 +++ b/PlayniteBoot/RuntimeTemplate/PlayniteBoot.ps1 @@ -25,8 +25,19 @@ param( [string]$ConfigPath, [Parameter(Mandatory = $false)] - [ValidateSet('Standalone', 'Preload', 'Continue', 'Host')] - [string]$Mode = 'Standalone' + [ValidateSet('Standalone', 'Preload', 'Continue', 'Host', 'Switch')] + [string]$Mode = 'Standalone', + + # Switch is an internal mode used by the Playnite Desktop plugin hook. + # Playnite Desktop owns the transition; the bootstrap and this runtime only + # cover it until the Fullscreen window is ready. + [Parameter(Mandatory = $false)] + [long]$SwitchStartUtcTicks = 0, + + # Set only by the lightweight SwitchBootstrap.ps1 path. The bootstrap + # already owns a rendered black cover and has released Playnite Desktop. + [Parameter(Mandatory = $false)] + [switch]$SwitchBootstrapActive ) Set-StrictMode -Version 2.0 @@ -241,6 +252,21 @@ function Find-PlayniteFullscreenExecutable { function Get-RunningFullscreenProcess { $processes = @(Get-Process -Name 'Playnite.FullscreenApp' -ErrorAction SilentlyContinue) + + # During Desktop -> Fullscreen switching, ignore stale/orphaned Fullscreen + # processes that predate the Closing callback which armed this overlay. + if ($Mode -eq 'Switch' -and $SwitchStartUtcTicks -gt 0 -and $processes.Count -gt 0) { + $minimumStartTicks = $SwitchStartUtcTicks - (250 * [TimeSpan]::TicksPerMillisecond) + $processes = @($processes | Where-Object { + try { + $_.StartTime.ToUniversalTime().Ticks -ge $minimumStartTicks + } + catch { + $false + } + }) + } + if ($processes.Count -eq 0) { return $null } @@ -1266,12 +1292,16 @@ public static class PlayniteBootNative } $existingProcess = Get-RunningFullscreenProcess - if ($null -ne $existingProcess) { + if ($null -ne $existingProcess -and $Mode -ne 'Switch') { Write-Log 'Playnite Fullscreen is already running. No new boot overlay will be shown.' Activate-PlayniteWindow -Process $existingProcess exit 0 } + if ($Mode -eq 'Switch' -and $null -ne $existingProcess) { + Write-Log "Switch bootstrap found Playnite Fullscreen PID $($existingProcess.Id) already starting. It will be adopted by the readiness tracker." + } + # Parametri generali. I valori e i limiti sono gli stessi della baseline. $settings = [PSCustomObject]@{ PlayniteExecutable = [string](Get-ConfigValue -Config $config -Name 'playniteExecutable' -DefaultValue 'auto') @@ -1303,7 +1333,12 @@ public static class PlayniteBootNative throw 'Invalid configuration: loopVideo and waitForVideoEnd cannot both be enabled.' } - $playniteExecutable = Find-PlayniteFullscreenExecutable -ConfiguredPath $settings.PlayniteExecutable -BaseDirectory $baseDirectory + $playniteExecutable = $null + if ($Mode -ne 'Switch') { + # Switch mode never starts Playnite itself. Skipping executable discovery + # also avoids unnecessary registry probing on the critical switch path. + $playniteExecutable = Find-PlayniteFullscreenExecutable -ConfiguredPath $settings.PlayniteExecutable -BaseDirectory $baseDirectory + } Add-Type -AssemblyName PresentationFramework Add-Type -AssemblyName PresentationCore @@ -1529,7 +1564,7 @@ public static class PlayniteBootNative # Stato condiviso dagli handler WPF. Le chiavi sono inizializzate in un # unico punto per rendere esplicito il ciclo di vita dell'overlay. $state = @{ - Process = $null + Process = $(if ($Mode -eq 'Switch') { $existingProcess } else { $null }) ReadySince = $null ReadyProcessId = $null ReadyWindowHandle = [IntPtr]::Zero @@ -1629,6 +1664,31 @@ public static class PlayniteBootNative Write-Log 'Preload-ready signal sent: the video is visible and advancing.' } + $closeSwitchBootstrapOverlay = { + if ($Mode -ne 'Switch' -or -not $SwitchBootstrapActive) { + return + } + + try { + $bootstrapVariable = Get-Variable -Name 'PlayniteBootSwitchBootstrapForm' -Scope Global -ErrorAction SilentlyContinue + if ($null -eq $bootstrapVariable -or $null -eq $bootstrapVariable.Value) { + return + } + + $bootstrapForm = $bootstrapVariable.Value + if (-not $bootstrapForm.IsDisposed) { + $bootstrapForm.Hide() + $bootstrapForm.Close() + $bootstrapForm.Dispose() + } + $global:PlayniteBootSwitchBootstrapForm = $null + Write-Log 'Switch bootstrap cover released after the main WPF overlay rendered.' + } + catch { + Write-Log "Could not release the switch bootstrap cover: $($_.Exception.Message)" 'WARN' + } + } + $revealVideo = { if ($state.VideoRevealed -or -not $videoExists -or $state.Closing) { return @@ -2264,6 +2324,10 @@ public static class PlayniteBootNative $window.Add_ContentRendered({ try { + # The lightweight bootstrap is already covering the target display. + # Replace it only after this normal WPF overlay has rendered black. + & $closeSwitchBootstrapOverlay + if ($settings.HideMouseCursor) { [System.Windows.Forms.Cursor]::Hide() $script:cursorHidden = $true @@ -2284,6 +2348,17 @@ public static class PlayniteBootNative $state.PreloadWatch.Restart() Write-Log "Preload overlay displayed. Waiting for video-ready and then Continue for up to $($streamingSettings.PreloadAbandonTimeoutMilliseconds) ms." } + elseif ($Mode -eq 'Switch') { + # Playnite Desktop owns the transition and launches Fullscreen + # after the Closing handler returns. The bootstrap cover has + # already released Desktop, so this runtime only tracks readiness. + $state.LaunchStarted = $true + $state.StartWatch.Restart() + Write-Log 'Desktop-to-Fullscreen switch overlay displayed. Waiting for Playnite Desktop to launch Fullscreen behind it.' + if ($SwitchBootstrapActive) { + Write-Log 'Desktop was already released by the switch bootstrap cover.' + } + } else { & $startPlaynite } @@ -2344,6 +2419,22 @@ finally { try { [System.Windows.Forms.Cursor]::Show() } catch {} } + if ($Mode -eq 'Switch' -and $SwitchBootstrapActive) { + try { + $bootstrapVariable = Get-Variable -Name 'PlayniteBootSwitchBootstrapForm' -Scope Global -ErrorAction SilentlyContinue + if ($null -ne $bootstrapVariable -and $null -ne $bootstrapVariable.Value) { + $bootstrapForm = $bootstrapVariable.Value + if (-not $bootstrapForm.IsDisposed) { + $bootstrapForm.Close() + $bootstrapForm.Dispose() + } + $global:PlayniteBootSwitchBootstrapForm = $null + } + } + catch { + } + } + if ($launcherMutexAcquired -and $null -ne $launcherMutex) { try { $launcherMutex.ReleaseMutex() } catch {} } diff --git a/PlayniteBoot/RuntimeTemplate/SwitchBootstrap.ps1 b/PlayniteBoot/RuntimeTemplate/SwitchBootstrap.ps1 new file mode 100644 index 0000000..f765cb8 --- /dev/null +++ b/PlayniteBoot/RuntimeTemplate/SwitchBootstrap.ps1 @@ -0,0 +1,177 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [string]$ConfigPath, + + [Parameter(Mandatory = $true)] + [string]$RuntimeScriptPath, + + [Parameter(Mandatory = $true)] + [string]$SwitchReadyEventName, + + [Parameter(Mandatory = $false)] + [long]$SwitchStartUtcTicks = 0 +) + +Set-StrictMode -Version 2.0 +$ErrorActionPreference = 'Stop' + +function Get-PropertyValue { + param( + [Parameter(Mandatory = $false)]$Object, + [Parameter(Mandatory = $true)][string]$Name, + [Parameter(Mandatory = $false)]$DefaultValue + ) + + if ($null -eq $Object) { + return $DefaultValue + } + + $property = $Object.PSObject.Properties[$Name] + if ($null -eq $property -or $null -eq $property.Value) { + return $DefaultValue + } + + return $property.Value +} + +function Select-BootstrapScreen { + param( + [Parameter(Mandatory = $true)]$Config, + [Parameter(Mandatory = $true)]$Screens + ) + + $selectionMode = [string](Get-PropertyValue -Object $Config -Name 'monitor' -DefaultValue 'playnite') + $fallbackMode = [string](Get-PropertyValue -Object $Config -Name 'monitorFallback' -DefaultValue 'primary') + + $selectByMode = { + param([string]$Mode) + + if ([string]::IsNullOrWhiteSpace($Mode)) { + return $null + } + + switch -Regex ($Mode.ToLowerInvariant()) { + '^playnite$|^followplaynite$' { + $configurationDirectory = [string](Get-PropertyValue -Object $Config -Name 'playniteConfigurationPath' -DefaultValue '') + if (-not [string]::IsNullOrWhiteSpace($configurationDirectory)) { + try { + $fullscreenConfigPath = Join-Path $configurationDirectory 'fullscreenConfig.json' + if (Test-Path -LiteralPath $fullscreenConfigPath -PathType Leaf) { + $fullscreenConfig = Get-Content -LiteralPath $fullscreenConfigPath -Raw -Encoding UTF8 | ConvertFrom-Json + $usePrimary = [bool](Get-PropertyValue -Object $fullscreenConfig -Name 'UsePrimaryDisplay' -DefaultValue $false) + if ($usePrimary) { + return [System.Windows.Forms.Screen]::PrimaryScreen + } + + $monitorIndex = [int](Get-PropertyValue -Object $fullscreenConfig -Name 'Monitor' -DefaultValue -1) + if ($monitorIndex -ge 0 -and $monitorIndex -lt $Screens.Count) { + return $Screens[$monitorIndex] + } + } + } + catch { + } + } + + return $null + } + '^primary$' { + return [System.Windows.Forms.Screen]::PrimaryScreen + } + '^cursor$|^auto$' { + return [System.Windows.Forms.Screen]::FromPoint([System.Windows.Forms.Cursor]::Position) + } + '^index:(\d+)$' { + $index = [int]$Matches[1] + if ($index -ge 0 -and $index -lt $Screens.Count) { + return $Screens[$index] + } + return $null + } + default { + return $null + } + } + } + + $selected = & $selectByMode $selectionMode + if ($null -eq $selected -and $selectionMode -match '^(?i:playnite|followplaynite)$') { + $selected = & $selectByMode $fallbackMode + } + if ($null -eq $selected) { + $selected = [System.Windows.Forms.Screen]::PrimaryScreen + } + + return $selected +} + +$readyEvent = $null +$form = $null +try { + $ConfigPath = [IO.Path]::GetFullPath($ConfigPath) + $RuntimeScriptPath = [IO.Path]::GetFullPath($RuntimeScriptPath) + + if (-not (Test-Path -LiteralPath $ConfigPath -PathType Leaf)) { + throw "Configuration file not found: $ConfigPath" + } + if (-not (Test-Path -LiteralPath $RuntimeScriptPath -PathType Leaf)) { + throw "Runtime script not found: $RuntimeScriptPath" + } + + Add-Type -AssemblyName System.Windows.Forms + Add-Type -AssemblyName System.Drawing + + $config = Get-Content -LiteralPath $ConfigPath -Raw -Encoding UTF8 | ConvertFrom-Json + $screens = @([System.Windows.Forms.Screen]::AllScreens) + if ($screens.Count -eq 0) { + throw 'No monitors were detected.' + } + + $selectedScreen = Select-BootstrapScreen -Config $config -Screens $screens + if ($null -eq $selectedScreen) { + $selectedScreen = [System.Windows.Forms.Screen]::PrimaryScreen + } + + $bounds = $selectedScreen.Bounds + $form = New-Object System.Windows.Forms.Form + $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None + $form.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual + $form.Bounds = $bounds + $form.BackColor = [System.Drawing.Color]::Black + $form.TopMost = $true + $form.ShowInTaskbar = $false + $form.ControlBox = $false + + $form.Show() + $form.BringToFront() + $form.Refresh() + [System.Windows.Forms.Application]::DoEvents() + + $readyEvent = [System.Threading.EventWaitHandle]::OpenExisting($SwitchReadyEventName) + [void]$readyEvent.Set() + + # Keep the bootstrap form alive in this same PowerShell process while the + # full runtime is parsed and initialized. PlayniteBoot.ps1 closes it only + # after its normal black WPF overlay has rendered, so the handoff remains + # black-to-black without a resident helper process. + $global:PlayniteBootSwitchBootstrapForm = $form + + & $RuntimeScriptPath ` + -ConfigPath $ConfigPath ` + -Mode Switch ` + -SwitchStartUtcTicks $SwitchStartUtcTicks ` + -SwitchBootstrapActive +} +finally { + if ($null -ne $readyEvent) { + try { $readyEvent.Dispose() } catch {} + } + + if ($null -ne $form -and -not $form.IsDisposed) { + try { $form.Close() } catch {} + try { $form.Dispose() } catch {} + } + + $global:PlayniteBootSwitchBootstrapForm = $null +} diff --git a/PlayniteBoot/RuntimeTemplate/VERSION.txt b/PlayniteBoot/RuntimeTemplate/VERSION.txt index af0b7dd..238d6e8 100644 --- a/PlayniteBoot/RuntimeTemplate/VERSION.txt +++ b/PlayniteBoot/RuntimeTemplate/VERSION.txt @@ -1 +1 @@ -1.0.6 +1.0.7 diff --git a/PlayniteBoot/Services/DesktopFullscreenSwitchService.cs b/PlayniteBoot/Services/DesktopFullscreenSwitchService.cs new file mode 100644 index 0000000..17b4bdd --- /dev/null +++ b/PlayniteBoot/Services/DesktopFullscreenSwitchService.cs @@ -0,0 +1,232 @@ +using Playnite.SDK; +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Threading; +using System.Windows; + +namespace PlayniteBoot.Services +{ + /// + /// Covers Playnite's built-in Desktop -> Fullscreen transition with the + /// external boot runtime. The integration is best-effort and always fails + /// open so Playnite can continue switching even if the cover cannot arm. + /// + internal sealed class DesktopFullscreenSwitchService + { + private const int ArmWaitMilliseconds = 2500; + private const string SwitchMethodName = "SwitchToFullscreenMode"; + private const string SwitchTypeName = "Playnite.DesktopApp.ViewModels.DesktopAppViewModel"; + + private static readonly ILogger logger = LogManager.GetLogger(); + private readonly RuntimePaths paths; + private readonly Func isEnabled; + private Window attachedWindow; + private bool switchHandled; + + public DesktopFullscreenSwitchService(RuntimePaths paths, Func isEnabled) + { + this.paths = paths ?? throw new ArgumentNullException(nameof(paths)); + this.isEnabled = isEnabled ?? throw new ArgumentNullException(nameof(isEnabled)); + } + + public bool Attach(Window window) + { + if (window == null) + { + return false; + } + + if (ReferenceEquals(attachedWindow, window)) + { + return true; + } + + Detach(); + attachedWindow = window; + switchHandled = false; + attachedWindow.Closing += Window_Closing; + return true; + } + + public void Detach() + { + if (attachedWindow != null) + { + attachedWindow.Closing -= Window_Closing; + attachedWindow = null; + } + } + + private void Window_Closing(object sender, CancelEventArgs eventArgs) + { + if (eventArgs.Cancel || switchHandled || !IsEnabled()) + { + return; + } + + if (!IsDesktopToFullscreenSwitch(new StackTrace(false))) + { + return; + } + + // Playnite calls Window.Close synchronously from SwitchToFullscreenMode. + // Hold that Closing callback only until a black external cover is + // rendered; once armed, Playnite is free to close Desktop and launch + // Fullscreen behind the cover. + switchHandled = true; + TryArmSwitchCover(Process.GetCurrentProcess().Id, DateTime.UtcNow); + } + + private bool IsEnabled() + { + try + { + return isEnabled(); + } + catch (Exception exception) + { + logger.Warn(PlayniteBootPlugin.ProductName + " could not read the Desktop-to-Fullscreen switch setting: " + exception.Message); + return false; + } + } + + private bool TryArmSwitchCover(int desktopProcessId, DateTime callbackUtc) + { + var bootstrapPath = Path.Combine(paths.RuntimeTemplateDirectory, "SwitchBootstrap.ps1"); + var runtimeScriptPath = Path.Combine(paths.RuntimeTemplateDirectory, "PlayniteBoot.ps1"); + + if (!File.Exists(bootstrapPath) || !File.Exists(runtimeScriptPath) || !File.Exists(paths.ConfigPath)) + { + logger.Warn(PlayniteBootPlugin.ProductName + " could not cover the Desktop-to-Fullscreen switch because the runtime is not ready."); + return false; + } + + var eventName = "Local\\PlayniteBootSwitchOverlay_" + desktopProcessId + "_" + Guid.NewGuid().ToString("N"); + using (var readyEvent = new EventWaitHandle(false, EventResetMode.ManualReset, eventName)) + { + var startInfo = new ProcessStartInfo + { + FileName = WindowsPowerShell.ExecutablePath, + Arguments = BuildArguments( + bootstrapPath, + runtimeScriptPath, + paths.ConfigPath, + callbackUtc.Ticks, + eventName), + UseShellExecute = false, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + WorkingDirectory = paths.RuntimeTemplateDirectory + }; + + Process helper = null; + try + { + helper = Process.Start(startInfo); + if (helper == null) + { + logger.Warn(PlayniteBootPlugin.ProductName + " could not start the Desktop-to-Fullscreen switch cover."); + return false; + } + + if (readyEvent.WaitOne(ArmWaitMilliseconds)) + { + return true; + } + + // A late cover is worse than no cover: it could appear after + // Desktop has already closed. Abort the helper and let Playnite + // continue its native switch normally. + TryTerminate(helper); + logger.Warn(PlayniteBootPlugin.ProductName + " switch cover did not become ready in time; continuing without it."); + return false; + } + catch (Exception exception) + { + TryTerminate(helper); + logger.Error(exception, PlayniteBootPlugin.ProductName + " failed to start the Desktop-to-Fullscreen switch cover."); + return false; + } + finally + { + if (helper != null) + { + helper.Dispose(); + } + } + } + } + + private static void TryTerminate(Process process) + { + if (process == null) + { + return; + } + + try + { + if (!process.HasExited) + { + process.Kill(); + } + } + catch + { + } + } + + private static string BuildArguments( + string bootstrapPath, + string runtimeScriptPath, + string configPath, + long callbackUtcTicks, + string eventName) + { + return string.Join(" ", new[] + { + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy Bypass", + "-STA", + "-WindowStyle Hidden", + "-File " + Quote(bootstrapPath), + "-ConfigPath " + Quote(configPath), + "-RuntimeScriptPath " + Quote(runtimeScriptPath), + "-SwitchReadyEventName " + Quote(eventName), + "-SwitchStartUtcTicks " + callbackUtcTicks + }); + } + + private static string Quote(string value) + { + return "\"" + (value ?? string.Empty).Replace("\"", "\\\"") + "\""; + } + + private static bool IsDesktopToFullscreenSwitch(StackTrace stack) + { + var frames = stack.GetFrames(); + if (frames == null) + { + return false; + } + + foreach (var frame in frames) + { + var method = frame.GetMethod(); + var declaringType = method != null ? method.DeclaringType : null; + if (declaringType != null && + string.Equals(declaringType.FullName, SwitchTypeName, StringComparison.Ordinal) && + string.Equals(method.Name, SwitchMethodName, StringComparison.Ordinal)) + { + return true; + } + } + + return false; + } + } +} diff --git a/PlayniteBoot/Services/RuntimeInstaller.cs b/PlayniteBoot/Services/RuntimeInstaller.cs index bc00ea4..8c265f3 100644 --- a/PlayniteBoot/Services/RuntimeInstaller.cs +++ b/PlayniteBoot/Services/RuntimeInstaller.cs @@ -16,6 +16,7 @@ public class RuntimeInstaller private static readonly string[] ManagedFiles = { "PlayniteBoot.ps1", + "SwitchBootstrap.ps1", "Launch-PlayniteBoot.vbs", "Install-Shortcut.ps1", "Test-Configuration.ps1", @@ -41,18 +42,29 @@ public RuntimeInstallResult EnsureInstalled(bool force = false) Directory.CreateDirectory(paths.LogsDirectory); var sourceVersionPath = Path.Combine(paths.RuntimeTemplateDirectory, "VERSION.txt"); - var targetVersionPath = Path.Combine(paths.RuntimeDirectory, "VERSION.txt"); var sourceVersion = File.Exists(sourceVersionPath) ? File.ReadAllText(sourceVersionPath).Trim() : "unknown"; - var targetVersion = File.Exists(targetVersionPath) ? File.ReadAllText(targetVersionPath).Trim() : string.Empty; - var updateManagedFiles = force || !string.Equals(sourceVersion, targetVersion, StringComparison.OrdinalIgnoreCase); var copied = 0; + // VERSION.txt is diagnostic metadata, not the update trigger. Compare + // each managed file by content so a runtime change is synchronized even + // if the runtime version was accidentally left unchanged. foreach (var relativePath in ManagedFiles) { var source = Path.Combine(paths.RuntimeTemplateDirectory, relativePath); var target = Path.Combine(paths.RuntimeDirectory, relativePath); - if (File.Exists(source) && (updateManagedFiles || !File.Exists(target))) + if (!File.Exists(source)) { + continue; + } + + if (force || !File.Exists(target) || !FilesHaveSameContent(source, target)) + { + var targetDirectory = Path.GetDirectoryName(target); + if (!string.IsNullOrWhiteSpace(targetDirectory)) + { + Directory.CreateDirectory(targetDirectory); + } + File.Copy(source, target, true); copied++; } @@ -73,5 +85,46 @@ public RuntimeInstallResult EnsureInstalled(bool force = false) CopiedFiles = copied }; } + + private static bool FilesHaveSameContent(string firstPath, string secondPath) + { + var firstInfo = new FileInfo(firstPath); + var secondInfo = new FileInfo(secondPath); + if (firstInfo.Length != secondInfo.Length) + { + return false; + } + + const int bufferSize = 81920; + var firstBuffer = new byte[bufferSize]; + var secondBuffer = new byte[bufferSize]; + + using (var firstStream = new FileStream(firstPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + using (var secondStream = new FileStream(secondPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + { + while (true) + { + var firstRead = firstStream.Read(firstBuffer, 0, firstBuffer.Length); + var secondRead = secondStream.Read(secondBuffer, 0, secondBuffer.Length); + if (firstRead != secondRead) + { + return false; + } + + if (firstRead == 0) + { + return true; + } + + for (var index = 0; index < firstRead; index++) + { + if (firstBuffer[index] != secondBuffer[index]) + { + return false; + } + } + } + } + } } }