Files
PowerToys/src/modules/peek/Peek.UI/PeekXAML/MainWindow.xaml.cs
Jaime Bernardo 864b862952 [General]Reduce installer size by flattening application paths (#27451)
* Flatten everything and succeed build

* Figure out Settings assets

* Remove UseCommonOutputDirectory tag

* Proper settings app path

* [VCM] Fix assets location

* Fix some runtime paths

* [RegistryPreview]Use MRTCore specific pri file

* [Hosts]Use MRTCore specific pri file

* [Settings]Use MRTCore specific pri file

* [Peek]Use MRTCore specific pri file

* [FileLocksmith]Use MRTCore specific pri file

* [ScreenRuler]Use MRTCore specific pri file

* [PowerRename]Use MRTCore specific pri file

* [Peek]Move assets to own folder

* [FileLocksmith] Use own Assets path

* [Hosts]Use own assets folder

* [PowerRename]Use own assets dir

* [MeasureTool] Use its own assets folder

* [ImageResizer]Use its own assets path

* Fix spellcheck

* Fix tab instead of space in project files

* Normalize target frameworks and platforms

* Remove WINRT_NO_MAKE_DETECTION flag. No longer needed?

* Fix AOT and Hosts locations

* Fix Dll version differences on dependency

* Add Common.UI.csproj as refernce to fix dll versions

* Update ControlzEx to normalize dll versions

* Update System.Management version to 7.0.2

* Add GPOWrapper to Registry Preview to fix dll versions

* [PTRun]Reference Microsoft.Extensions.Hosting to fix dll versions

* Fix remaining output paths / dll version conflicts

* [KeyboardManager]Executables still on their own directories

* Fix Monaco paths

* WinAppSDK apps get to play outside again

* Enable VCM settings again

* Fix KBM Editor path again

* [Monaco]Set to own Assets dir

* Fix installer preamble; Fix publish. remove unneeded publishes

* Remove Hardlink functions

* Installer builds again (still needs work to work)

* Readd Monaco to spellcheck excludes

* Fix spellcheck and call publish.cmd again

* [Installer] Remove components that don't need own dirs

* [Installer] Refactor Power Launcher

* [Installer] Refactor Color Picker

* [Installer] Refactor Monaco assets

* [Installer]Generate File script no longer needs to remove files

* [Installer]Refactor FileLocksmith

* [Installer] Refactor Hosts

* [Installer]Refactor Image Resizer

* [Installer]Refactor MouseUtils

* [Installer]Refactor MWB

* [Installer]Refactor MeasureTool

* [Installer]Refactor Peek

* [Installer]Refactor PowerRename and registry fixes

* [Installer]Refactor RegistryPreview

* [Installer]Refactor ShortcutGuide

* [Installer]Refactor Settings

* [Installer]Clean up some unused stuff

* [Installer]Clean up stuff for user install

* [Installer]Fix WinUi3Apps wxs

* [Installer]Fix misplaced folders

* [Installer]Move x86 VCM dll to right path

* Fix monaco language list location

* [Installer]Fix VCM directory reference

* [CI]Fix signing

* [Installer] Fix resources folder for release CI

* [ci]Looks like we still ship NLog on PowerToys Run

* [Settings]Add dependency to avoid dll collision with Experimentation

* [RegistryPreview]Move XAML files to own path

* [RegistryPreview]Fix app icon

* [Hosts]Move XAML files to their own path

* [FileLocksmith]Move XAML files to their own path

* [Peek]Move XAML files to own path

* [ScreenRuler]Move XAML files to its own path

* [Settings]Move XAML to its own path

* [ColorPicker]Move Resources to Assets

* [ShortcutGuide]Move svgs to own Assets path

* [Awake]Move images to assets path

* [Runner]Remove debug checks for PowerToys Run assets

* [PTRun]Move images to its own assets path

* [ImageResizer]Icon for context menu on own assets path

* [PowerRename]Move ico to its own path

* Remove unneeded intermediary directories

* Remove further int dirs

* Move tests to its own output path

* Fix spellcheck

* spellcheck: remove warnings

* [CppAnalyzers]Ignore rule in a tool

* [CI]Check if all deps.json files reference same versions

* fix spellcheck

* [ci]Fix task identation

* [ci]Add script to guard against asset conflicts

* [ci]Add more deps.json audit steps in the release build

* Add xbf to spellcheck expects

* Fix typo in asset conflict check scripts

* Fix some more dependency conflicts

* Downgrade CsWinRT to have the same dll version as sdk

* [ci]Do a recursive check for every deps.json

* Fix spellcheck error inside comment

* [ci]Fix asset script error

* [ci]Name deps.json verify tasks a bit better

* [ci]Improve deps json verify script output

* [ci]Update WinRT version to the same running in CI

* Also upgrade CsWinRT in NOTICE.MD

* [PowerRename]Move XAML files to own path

* [Common]Fix Settings executable path

* [ci]Verify there's no xbf files in app directories

* [installer]Fix firewall path

* [Monaco]Move new files to their proper assets path

* [Monaco]Fix paths for new files after merge

* [Feedback]Removed unneeded build conditions

* [Feedback]Clear vcxproj direct reference to frameworks

* [Feedback]RunPlugins name to hold PTRun plugins

* [Feedback]Remove unneeded foreach

* [Feedback]Shortcut Guide svgs with ** in project file

* [Feedback]Fix spellcheck
2023-07-20 00:12:46 +01:00

249 lines
8.6 KiB
C#

// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using interop;
using ManagedCommon;
using Microsoft.PowerToys.Telemetry;
using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml.Input;
using Peek.Common.Constants;
using Peek.FilePreviewer.Models;
using Peek.UI.Extensions;
using Peek.UI.Helpers;
using Peek.UI.Native;
using Peek.UI.Telemetry.Events;
using Windows.Foundation;
using WinUIEx;
namespace Peek.UI
{
/// <summary>
/// An empty window that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainWindow : WindowEx, IDisposable
{
public MainWindowViewModel ViewModel { get; }
private ThemeListener? themeListener;
private bool activated;
public MainWindow()
{
InitializeComponent();
this.Activated += PeekWindow_Activated;
try
{
themeListener = new ThemeListener();
themeListener.ThemeChanged += (_) => HandleThemeChange();
}
catch (Exception e)
{
Logger.LogError($"HandleThemeChange exception. Please install .NET 4.", e);
}
ViewModel = App.GetService<MainWindowViewModel>();
NativeEventWaiter.WaitForEventLoop(Constants.ShowPeekEvent(), OnPeekHotkey);
TitleBarControl.SetTitleBarToWindow(this);
AppWindow.Closing += AppWindow_Closing;
}
private void HandleThemeChange()
{
AppWindow appWindow = this.AppWindow;
if (ThemeHelpers.GetAppTheme() == AppTheme.Light)
{
appWindow.TitleBar.ButtonForegroundColor = Colors.DarkSlateGray;
}
else
{
appWindow.TitleBar.ButtonForegroundColor = Colors.White;
}
}
private void PeekWindow_Activated(object sender, Microsoft.UI.Xaml.WindowActivatedEventArgs args)
{
if (args.WindowActivationState == Microsoft.UI.Xaml.WindowActivationState.Deactivated)
{
var userSettings = App.GetService<IUserSettings>();
if (userSettings.CloseAfterLosingFocus)
{
Uninitialize();
}
}
}
/// <summary>
/// Handle Peek hotkey, by toggling the window visibility and querying files when necessary.
/// </summary>
private void OnPeekHotkey()
{
// First Peek activation
if (!activated)
{
Activate();
Initialize();
activated = true;
return;
}
if (AppWindow.IsVisible)
{
if (IsNewSingleSelectedItem())
{
Initialize();
}
else
{
Uninitialize();
}
}
else
{
Initialize();
}
}
private void PreviousNavigationInvoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
{
ViewModel.AttemptPreviousNavigation();
}
private void NextNavigationInvoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
{
ViewModel.AttemptNextNavigation();
}
private void EscKeyInvoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
{
Uninitialize();
}
private void Initialize()
{
var bootTime = new System.Diagnostics.Stopwatch();
bootTime.Start();
ViewModel.Initialize();
ViewModel.ScalingFactor = this.GetMonitorScale();
bootTime.Stop();
PowerToysTelemetry.Log.WriteEvent(new OpenedEvent() { FileExtension = ViewModel.CurrentItem?.Extension ?? string.Empty, HotKeyToVisibleTimeMs = bootTime.ElapsedMilliseconds });
}
private void Uninitialize()
{
this.Restore();
this.Hide();
ViewModel.Uninitialize();
ViewModel.ScalingFactor = 1;
}
/// <summary>
/// Handle FilePreviewerSizeChanged event to adjust window size and position accordingly.
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">PreviewSizeChangedArgs</param>
private void FilePreviewer_PreviewSizeChanged(object sender, PreviewSizeChangedArgs e)
{
var foregroundWindowHandle = Windows.Win32.PInvoke.GetForegroundWindow();
var monitorSize = foregroundWindowHandle.GetMonitorSize();
var monitorScale = foregroundWindowHandle.GetMonitorScale();
// If no size is requested, try to fit to the monitor size.
Size requestedSize = e.PreviewSize.MonitorSize ?? monitorSize;
var contentScale = e.PreviewSize.UseEffectivePixels ? 1 : monitorScale;
Size scaledRequestedSize = new Size(requestedSize.Width / contentScale, requestedSize.Height / contentScale);
// TODO: Investigate why portrait images do not perfectly fit edge-to-edge
Size monitorMinContentSize = GetMonitorMinContentSize(monitorScale);
Size monitorMaxContentSize = GetMonitorMaxContentSize(monitorSize, monitorScale);
Size adjustedContentSize = scaledRequestedSize.Fit(monitorMaxContentSize, monitorMinContentSize);
var titleBarHeight = TitleBarControl.ActualHeight;
var desiredWindowHeight = adjustedContentSize.Height + titleBarHeight + WindowConstants.WindowWidthContentPadding;
var desiredWindowWidth = adjustedContentSize.Width + WindowConstants.WindowHeightContentPadding;
if (!TitleBarControl.Pinned)
{
this.CenterOnMonitor(foregroundWindowHandle, desiredWindowWidth, desiredWindowHeight);
}
this.Show();
this.BringToForeground();
}
private Size GetMonitorMaxContentSize(Size monitorSize, double scaling)
{
var titleBarHeight = TitleBarControl.ActualHeight;
var maxContentWidth = monitorSize.Width * WindowConstants.MaxWindowToMonitorRatio;
var maxContentHeight = (monitorSize.Height - titleBarHeight) * WindowConstants.MaxWindowToMonitorRatio;
return new Size(maxContentWidth / scaling, maxContentHeight / scaling);
}
private Size GetMonitorMinContentSize(double scaling)
{
var titleBarHeight = TitleBarControl.ActualHeight;
var minContentWidth = WindowConstants.MinWindowWidth;
var minContentHeight = WindowConstants.MinWindowHeight - titleBarHeight;
return new Size(minContentWidth / scaling, minContentHeight / scaling);
}
/// <summary>
/// Handle AppWindow closing to prevent app termination on close.
/// </summary>
/// <param name="sender">AppWindow</param>
/// <param name="args">AppWindowClosingEventArgs</param>
private void AppWindow_Closing(AppWindow sender, AppWindowClosingEventArgs args)
{
args.Cancel = true;
PowerToysTelemetry.Log.WriteEvent(new ClosedEvent());
Uninitialize();
}
private bool IsNewSingleSelectedItem()
{
try
{
var foregroundWindowHandle = Windows.Win32.PInvoke.GetForegroundWindow();
var selectedItems = FileExplorerHelper.GetSelectedItems(foregroundWindowHandle);
var selectedItemsCount = selectedItems?.GetCount() ?? 0;
if (selectedItems == null || selectedItemsCount == 0 || selectedItemsCount > 1)
{
return false;
}
var fileExplorerSelectedItemPath = selectedItems.GetItemAt(0).ToIFileSystemItem().Path;
var currentItemPath = ViewModel.CurrentItem?.Path;
if (fileExplorerSelectedItemPath == null || currentItemPath == null || fileExplorerSelectedItemPath == currentItemPath)
{
return false;
}
return true;
}
catch (Exception ex)
{
Logger.LogError(ex.Message);
}
return false;
}
public void Dispose()
{
themeListener?.Dispose();
}
}
}