[Peek] Powertoys Peek MVP (#25922)

* Peek (#22498)

* Add peek dll project

* add spacebar preview and launch on hotkey press

* add todo

* add process handle to handle continuous press of hotkey

* add tool to stop all powertoys processes

* Add a blank Peek page and update nav menu

* Add some initial content to Peek page including a toggle

* refactor settings parsing

* rename spacebar peek to peek viewer

* rename script to stop powertoys processes

* remove tool

* Adding FileUtils for retrieving selected file in File Explorer

* Remove unnecessary SndPeekSettings

* Add shortcut setting

* Set the shortcut to ctrl+space

* Launching viewer with selected FE file

* Add PeekUI WinUI3 project with interop events

* Moving FileTypeUtils into PeekFileUtils project

* execute winui3 app on hotkey

* Fix paths with spaces

* remove winui3 project

* Resolve comment

* add wpf app with toggle visibility on hotkey

* fix visibility on startup

* remove window properties and add todos

* Fixed hidden extension and system file handling

* wip

* Add working WPF app with FileExplorer querying

* remove c++ projects

* Move native awaiter

* Working Image control with image files

* Resize and move window based on explorer monitor

* Image render, window positioning and sizing clean up

* add window management logic and selection logic

* add extension methods to add circular iterating capability to linkedlistnode

* Add OnArrowKeyPresshandler

* Added titlebar with file name and scaling with titlebar height

* fix flashing window on startup and process kept alive when powertoys exits

* remove wait for debugger loop in ui

* Add KeyIsDown method

* Fix KeyDown issue with Key handled and check for repeat

* Add thumbnail logic

* Add all folder items if only one item is selected

* File type helper

* Using hresult

* Add cancellation and rotation handling

* Use extension instead of path

* fIX CONFLICTS

* Fixing some file type checks

* Add new icon for Peek

* Update page with the new Peek icon

* Initialize IsEnabled and hook ActivationShortcut to dllmain

* add icon to taskbar and titlebar

* Add theme sensitive backgrounds

* rename event handlers

* add settings image

* Move window data into obserable object

* Refactor viewmodel, interop and helpers

* Clean up

* Add loading spinner

* Add todos

* Fix conflicts

* Move native code into its own folder

* Add peek to installer

* Fix building peek and peekui projects

* Replace UWP namespaces to WinAppSDK

* Working WASDK placeholder project

* Add exit when powertoys runner exit

* Working winui3 with image display

* Add WIC project with <TreatWarningAsErros> false for now

* Fit content to window

* Use Size from Windows.Foundation

* Change order

* Add some todos

* Refactored native/interop code and added helpers to imagepreviewer

* Rename projects

* Move some code

* Remove using

Co-authored-by: Michael Salmon <miksalmon@users.noreply.github.com>
Co-authored-by: Michael Salmon 🐟 <michaelpsalmon@outlook.com>
Co-authored-by: Alireza Ebadi Ghajari <alirezae@microsoft.com>
Co-authored-by: Jessie Su <Jessie.Su@microsoft.com>
Co-authored-by: sujessie <102062556+sujessie@users.noreply.github.com>

* Bump Microsoft.Windows.SDK.BuildTools version

* [Peek] Plugin pattern to enable any file type previewing (#22475)

* [Peek] Fetching image size through PropertyStore (#22530)

* Fetching metadata from PropertySTore

* Releasing objects to fix crash

* Creating new PropertyHelper

Co-authored-by: Daniel Chau <dancha@microsoft.com>

* Juliata/filetypes (#22538)

* Using the same list of file extensions as Lightbox's AppxManifest, and ensuring we convert file extension to lowercase

* Add IsFileTypeSupported to IPreviewer

* respond to PR comments

* Add scale awareness to window centering (#22541)

* [Peek] Fix installer builds, project configs and update assets (#22540)

* Update installer

* Fix installer errors

* Fix peek vcxproj

* Add package signing

* Add peek to arm64

* Add back ARM64 toMeasureToolUI

* Add versions to project

* Update assets and icons

* Add correct icon

* [Peek] Enable PropertyStore for offline files (#22567)

* Enabling PropertyStore for offline files

Co-authored-by: Daniel Chau <dancha@microsoft.com>

* [Peek] Adding unsupported file previewer (#22598)

* Unsupported file previewer

* Fix file display info

* Fix property store calls

* Update TODO

* [Peek] Add WebView2 integration (#22506)

* First commit with WIP logic to support WV2 in Peek module

* Minor code cleanup and try/catch block

* Added control to wrap WebView2 logic

* Cleanup

* Added logic to handle HTML previewing
Properly update FilePreview according to file type

* Code cleanup
Updated comments

* Updated comment

* Removed comment

* Code cleanup

* Improved opening of web browser preview to avoid "blank" or "seeing previous page" issue
Removed unused method
Added xaml fallback to guarantee default/starting state

* Removed folder

* Updated factory logic to match master

* address code review

* addressed PR review

* address PR review

* Address PR review

* address PR review

* Address PR review

* [Peek] Add basic file querying and navigation (#22589)

* Refactor to facilitate file data initialization

* Extract file-related code to new FileManager class

* Add temp basic version

* Clean + add todo for cancellations

* Fix various nav-related issues

* Temp - start moving iteration-related code to bg thread

* Minor tweaks

* Add FEHelper todo

* Rename FileManager + various tweaks

* Add basic throttling

* Improve bg thread synchronization

* Clean

* Clean

* Rename based on feedback

* Rename FileQuery

* Rename properties

* Rename remaining fields

* Add todos for nav success/failures

Co-authored-by: Esteban Margaron <emargaron@microsoft.com>

* [Peek] Add customized title bar  (#22600)

* Add basic button UI

* Add function to get default app name and to open file in default app

* Correct error output

* Add filename to titlebar

* Remove titlebar text from Resw

* Add basic button UI

* Add function to get default app name and to open file in default app

* Add filename to titlebar

* Correct error output

* Remove titlebar text from Resw

* Add SetDragRectangles

* Correct logic, update function name

* Add localization

* Cleanup and adaptive width

* Add fileIndex/NumberOfFiles for multiple files activation

* Refine titlebar styles

* Update error message; Return HResult from native methods; Update variable initialisation and string null testing

* Titlebar height and adaptive width refinement

* Add fallback to launch app picker if fail to open default app

* Temp change to hide AppTitle_FileCount

* Update launch button to command; Add keyboard accelerator

* Update titlebar inactive background color

* Update tooltip to add keyboard accelerator

* Add comments to resw file

* Fix accidental deletion from previous merge

Co-authored-by: Jojo Zhou <yizzho@microsoft.com>
Co-authored-by: Yawen Hou <yawenhou@microsoft.com>

* Fix crash

* Fix wrong thread exception

* Make CurrentItemIndex setter private

* Update titlebar filecount text

* Fix titlebar draggable region and interactive region (bump WinAppSdk to latest)

* [Peek] Unsupported File Previewer - Formatting string from resources (#22609)

* Moving to string resource usage

* Moving ReadableStringHelper to common project

* Fix comments

* [Peek] Fix foregrounding (#22633)

* Fixing foregrounding

* Get window handle inside BringToForeground extension method

Co-authored-by: Daniel Chau <dancha@microsoft.com>
Co-authored-by: Samuel Chapleau <sachaple@microsoft.com>

* [Peek] ImagePreviewer - Handle error states (#22637)

* add better preview state handling

* add error handling in imagepreviewer and better state handling

* fix error handling so exception is not bubbled up

* improve performance and hook up unsupported previewer on error

* remove commented code

* address pr comments

* [Peek] add PDF viewing support (#22636)

* [Peek] add PDF viewing support

* Fixed issue which would redirect some HTML and PDF files to external browser

* Fixed refactored interface name

* [Peek] Refine titlebar adaptive width (#22642)

* Adjust adaptive width of titlebar

* Remove visualstate setters for AppTitle_FileCount

Co-authored-by: Jojo Zhou <yizzho@microsoft.com>

* [Peek] New File Explorer tabs break Shell API to get selected files (#22641)

* fix FE tab bug

* remove unnecessary unsafe keyword

* [Peek] add extra logic to properly render PNG files with transparency (#22613)

* [Peek] added extra logic to render PNG files with proper transparency

* Moved logic to ThumbnailHelper
Cleanup

* Created a separated previewer for PNG to only load the preview image with thumbnail logic

* removed unused code

* Updated state loading change

* [Peek] Unsupported File Previewer - Setting Window Size (#22645)

* Adding setting for unsupported file window

* Fix

* [Peek] Add tooltip to File (#22640)

* Add tooltip to File

* Add placeholder text for no tooltip

* Address comments

* Use StringBuilder

Co-authored-by: Jojo Zhou <yizzho@microsoft.com>

* Add full image quality support (#22654)

* [Peek] Window foregrounding simplification and fixes + keep window visible if FE single selection changed (#22657)

* Use different apis to bring to foreground removing remote thread wait and work as well as library loading

* Keep window open if single selected file in FE is different

* Removed unused methods

* [Peek] Add cancellation token OnFilePropertyChanged (#22643)

* Cancel file loading before opening another file

* Add omitted cancellation checks

* Catch task cancelled exception; Add more cancellation checkpoints

* Add cancellation checkpoint beofre GetBitmapFromHBitmapAsync

* Correct typo

* Update to pass cancellation token individually to each async methods

* Add lost cancellationToken source

* Add cancellation token to PngPreviewer

Co-authored-by: Yawen Hou <yawenhou@microsoft.com>

* [Peek] Unsupported File Previewer - Preserve Transparency For File Icons (#22650)

* Preserving transparency or icons

* Remove TODO

Co-authored-by: Samuel Chapleau <sachaple@microsoft.com>

* [Peek] Update some installer build steps + assets update (#22683)

* Fix settings & peek.ui.wpf

* Add back missing icon

* Add missing files and actions to installer

* Keep window open if the selected file in explorer is different (only works for single file selection)

* Undo last

* [Peek] Add copy keyboard accelerator (#22647)

* add copy keyboard accelerator

* Fix comments

Co-authored-by: Samuel Chapleau <sachaple@microsoft.com>

* [Peek] add WV2 improvements (behavior and UX) (#22685)

* [Peek] added logic to get max monitor size for opening WebView2

* Removed ununsed dependency property

* Added workaround for cases where the web page would not finish navigating in a quick timing, for example google.com.

* Remove window extensions from common and use nullable size argument instead

Co-authored-by: Samuel Chapleau <sachaple@microsoft.com>

* [Peek] Merge main, self-contained .NET and fix WebView2 user data dir issue (#22899)

* Merge remote-tracking branch 'origin/main' into peek

* Test sc

* Set WebView2 user data dir

* spellcheck

* Fix comment

* Move check if higher quality image is already loaded to the exact line where we change the Preview bitmap (#23083)

* Fix opening Peek when FE window is set to full name path (#23082)

* Move check for png thubmnail loading priority

* Remove Peek.UI.WPF project

* Remove duplicated method in powertoys setup

* [Peek] Fix selecting files from the correct focused opened File Explorer tab & from Desktop (#23489)

* Get file based on active tab handle instead of window title

* Refactor code to get active tab

* Getting all items from the shell API working again, except for desktop

* Refactor and cleanup com & native code

* Add back removed peek xaml assets in Product.wxs

* Remove some dependencies that do not seem necessary in Product.wxs

* [Peek] Small images (#23554)

* change stretch value

* compare with actual window size

* consider scaling factor

* set max size

* clean up

* clean up

* clean up previewers

* scaling factor in bitmap previewer

* max image size property

* [Peek]Handle errors for HEIC/HEIF and fall back to default previewer if there is no thumbnail (#22684)

* Handle errors when getting filesize by falling back to default previewer

* Bringing back other file types that are fixed with these code changes

---------

Co-authored-by: Samuel Chapleau <sachaple@microsoft.com>

* [Peek] Add unsupported file icon fallback (#23735)

* Refactor icon retrieval, refactor hbitmap to bitmap conversion, add icon fallback

* Add svg to assets in installer

* [Peek] Refactoring of file system models, removal of PngPreviewer, retrieving of folder size via Scripting com reference and other fixes (#23955)

* Refactor icon retrieval, refactor hbitmap to bitmap conversion, add icon fallback

* Add svg to assets in installer

* - Refactor File class into IFileSystemItem, FileItem & FolderItem
- Display size for folders using Scripting namespace
- Remove default app buttons for files or folders not supporting it

* Add better content type via storage apis

* Add check for storagefile in PngPreviewer

* Fix png stretching

* Remove png previewer

* Rename ThumbnailOptions.None to ThumbnailOptions.ResizeToFit

* [Peek] Removed monitor percentage evaluation for the UnsupportedFilePreview control (#24002)

* Remove settings for percentage of windows and keep default min size.

* Fix margin on unsupported control

* Use nullable Size for image size & open file on background thread (#24004)

* [Peek] SVG support (#24237)

* svg previewer

* svg size

* set scaling factor

* set image size

* changed image source type

* non nullable image size

* notify svg previewer changed

* uncomment

* rename BitmapPreviewer

* move svg support

* remove svg previewer

* [Peek] Implementation of a performant and reliable Neighboring Files Query (#24943)

* Use IShellItemArray as the backing array of item

* Finalize and cleanup NFQ implementation

* Cleanup remainder of the code

* Remove unused using

* [Peek] Pin the window position  (#24927)

* [Peek] Telemetry and logging (#25231)

* text preview

* scrolling

* changed size

* webview2 preview

* common preview project

* previewpane: use common project

* peek: use common

* previewpane: moved md

* peek: md

* previewpane: clean up

* clean up

* moved monaco files

* moved formatters

* rename

* moved common monaco helper

* dev files support

* installer

* removed versions

* warnings: culture info

* warnings: names

* clean up

* warnings: dispose

* warnings: default values

* warnings

* warnings: charset

* warnings: exceptions

* suppress warning

* installer: added peek

* changed peek guid

* monaco folders

* peek deps

* peek files

* peek resources

* removed additional monaco folder

* set host name

* Update installer

* hardcode monaco path

* leave single webview control

* moved path to common

* project

* more meaningful todos

* moved temp folder cleanup

* todo

* extension check

* spell: monaco

* spellcheck

* spellcheck

* fix id

* fix spelling

* key to spelling

* id fix

* Fix monaco resolution at install time

* Fix user install. Add needed files

* installer: remove peek localization files. It's a WinUI app

* installer:fix signing

* removed unused

* settings: flyout enable/disable for Peek

* simplify string

* property changed handle

* [Peek][Settings] Peek OOBE page (#25895)

* [Peek] GPO (#25918)

* Add Native methods file to exception

* Fix merge issue on solution file

* Adjust spellcheck

* Remove boilerplate code

* Add module interface telemetry

* Remove change to README.md

* Add entry to README

* Clean up some non-changes

* Fix order of Peek in Settings menu

* [Settings] Make peek descriptions more descriptive

---------

Co-authored-by: Michael Salmon <miksalmon@users.noreply.github.com>
Co-authored-by: Michael Salmon 🐟 <michaelpsalmon@outlook.com>
Co-authored-by: Alireza Ebadi Ghajari <alirezae@microsoft.com>
Co-authored-by: Jessie Su <Jessie.Su@microsoft.com>
Co-authored-by: sujessie <102062556+sujessie@users.noreply.github.com>
Co-authored-by: Daniel Chau <d.chau@alumni.ubc.ca>
Co-authored-by: Daniel Chau <dancha@microsoft.com>
Co-authored-by: jth-ms <73617023+jth-ms@users.noreply.github.com>
Co-authored-by: Robson <rp.pontin@gmail.com>
Co-authored-by: estebanm123 <49930791+estebanm123@users.noreply.github.com>
Co-authored-by: Esteban Margaron <emargaron@microsoft.com>
Co-authored-by: Yawen Hou <Sytta@users.noreply.github.com>
Co-authored-by: Jojo Zhou <yizzho@microsoft.com>
Co-authored-by: Yawen Hou <yawenhou@microsoft.com>
Co-authored-by: Jojo Zhou <39350350+Joanna-Zhou@users.noreply.github.com>
Co-authored-by: Stefan Markovic <57057282+stefansjfw@users.noreply.github.com>
Co-authored-by: Seraphima Zykova <zykovas91@gmail.com>
Co-authored-by: Stefan Markovic <stefan@janeasystems.com>
Co-authored-by: Jaime Bernardo <jaime@janeasystems.com>
This commit is contained in:
Samuel Chapleau
2023-05-10 10:43:03 -07:00
committed by GitHub
parent 7ae93a9c7f
commit 648f30d1ab
361 changed files with 10709 additions and 182 deletions

View File

@@ -0,0 +1,18 @@
<!-- Copyright (c) Microsoft Corporation and Contributors. -->
<!-- Licensed under the MIT License. -->
<Application
x:Class="Peek.UI.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Peek.UI">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
<!-- Other merged dictionaries here -->
</ResourceDictionary.MergedDictionaries>
<!-- Other app resources here -->
</ResourceDictionary>
</Application.Resources>
</Application>

View File

@@ -0,0 +1,106 @@
// 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 ManagedCommon;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.PowerToys.Telemetry;
using Microsoft.UI.Xaml;
using Peek.FilePreviewer;
using Peek.UI.Telemetry.Events;
using Peek.UI.Views;
using WinUIEx;
namespace Peek.UI
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public partial class App : Application
{
public static int PowerToysPID { get; set; }
public IHost Host
{
get;
}
private Window? Window { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="App"/> class.
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
InitializeComponent();
Host = Microsoft.Extensions.Hosting.Host.
CreateDefaultBuilder().
UseContentRoot(AppContext.BaseDirectory).
ConfigureServices((context, services) =>
{
// Core Services
services.AddTransient<NeighboringItemsQuery>();
// Views and ViewModels
services.AddTransient<TitleBar>();
services.AddTransient<FilePreview>();
services.AddTransient<MainWindowViewModel>();
}).
Build();
UnhandledException += App_UnhandledException;
}
public static T GetService<T>()
where T : class
{
if ((App.Current as App)!.Host.Services.GetService(typeof(T)) is not T service)
{
throw new ArgumentException($"{typeof(T)} needs to be registered in ConfigureServices within App.xaml.cs.");
}
return service;
}
/// <summary>
/// Invoked when the application is launched.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
if (PowerToys.GPOWrapper.GPOWrapper.GetConfiguredPeekEnabledValue() == PowerToys.GPOWrapper.GpoRuleConfigured.Disabled)
{
Logger.LogWarning("Tried to start with a GPO policy setting the utility to always be disabled. Please contact your systems administrator.");
Environment.Exit(0); // Current.Exit won't work until there's a window opened.
return;
}
var cmdArgs = Environment.GetCommandLineArgs();
if (cmdArgs?.Length > 1)
{
if (int.TryParse(cmdArgs[cmdArgs.Length - 1], out int powerToysRunnerPid))
{
RunnerHelper.WaitForPowerToysRunner(powerToysRunnerPid, () =>
{
Environment.Exit(0);
});
}
}
Window = new MainWindow();
Window.Activate();
Window.Hide();
}
private void App_UnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)
{
PowerToysTelemetry.Log.WriteEvent(new ErrorEvent() { HResult = (Common.Models.HResult)e.Exception.HResult, Failure = ErrorEvent.FailureType.AppCrash });
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 513 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 638 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 745 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

View File

@@ -0,0 +1,5 @@
<svg width="auto" height="auto" viewBox="0 0 357 357" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M72.5156 323.531H284.484C287.561 323.531 290.062 321.029 290.062 317.953V100.406H239.859C230.632 100.406 223.125 92.8995 223.125 83.6719V33.4688H72.5156C69.4393 33.4688 66.9375 35.9705 66.9375 39.0469V317.953C66.9375 321.029 69.4393 323.531 72.5156 323.531Z" fill="white"/>
<path d="M284.964 89.25L234.281 38.5685V83.6719C234.281 86.7482 236.783 89.25 239.859 89.25H284.964Z" fill="white"/>
<path opacity="0.64" fill-rule="evenodd" clip-rule="evenodd" d="M301.219 94.8281C301.215 94.0033 301.026 93.1899 300.667 92.4476C299.925 89.5635 298.423 86.9315 296.317 84.8265L238.705 27.2156C235.574 24.0657 231.312 22.3 226.871 22.3124H72.5156C63.288 22.3124 55.7812 29.8192 55.7812 39.0468V317.953C55.7812 327.181 63.288 334.687 72.5156 334.687H284.484C293.712 334.687 301.219 327.181 301.219 317.953V96.6605C301.219 96.2629 301.191 95.8704 301.163 95.4781L301.159 95.4249C301.165 95.3614 301.174 95.2985 301.182 95.2357C301.201 95.1015 301.219 94.9677 301.219 94.8281ZM284.964 89.25H239.859C236.783 89.25 234.281 86.7482 234.281 83.6718V38.5685L284.964 89.25ZM72.5156 323.531H284.484C287.561 323.531 290.062 321.029 290.062 317.953V100.406H239.859C230.632 100.406 223.125 92.8995 223.125 83.6718V33.4687H72.5156C69.4393 33.4687 66.9375 35.9705 66.9375 39.0468V317.953C66.9375 321.029 69.4393 323.531 72.5156 323.531Z" fill="#605E5C"/>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

View File

@@ -0,0 +1,49 @@
// 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.Text;
using Peek.UI.Native;
using Windows.Win32;
using Windows.Win32.Foundation;
namespace Peek.UI.Extensions
{
public static class HWNDExtensions
{
internal static HWND GetActiveTab(this HWND windowHandle)
{
var activeTab = windowHandle.FindChildWindow("ShellTabWindowClass");
if (activeTab == HWND.Null)
{
activeTab = windowHandle.FindChildWindow("TabWindowClass");
}
return activeTab;
}
internal static bool IsDesktopWindow(this HWND windowHandle)
{
StringBuilder strClassName = new StringBuilder(256);
var result = NativeMethods.GetClassName(windowHandle, strClassName, 256);
if (result == 0)
{
return false;
}
var className = strClassName.ToString();
if (className != "Progman" && className != "WorkerW")
{
return false;
}
return windowHandle.FindChildWindow("SHELLDLL_DefView") != HWND.Null;
}
internal static HWND FindChildWindow(this HWND windowHandle, string className)
{
return PInvoke.FindWindowEx(windowHandle, HWND.Null, className, null);
}
}
}

View File

@@ -0,0 +1,30 @@
// 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 System.IO;
using Peek.Common.Helpers;
using Peek.Common.Models;
namespace Peek.UI.Extensions
{
public static class IShellItemExtensions
{
public static IFileSystemItem ToIFileSystemItem(this IShellItem shellItem)
{
string path = string.Empty;
try
{
path = shellItem.GetDisplayName(Windows.Win32.UI.Shell.SIGDN.SIGDN_FILESYSPATH);
}
catch (Exception ex)
{
// TODO: Handle cases that do not have a file system path like Recycle Bin.
Logger.LogError("Getting path failed. " + ex.Message);
}
return File.Exists(path) ? new FileItem(path) : new FolderItem(path);
}
}
}

View File

@@ -0,0 +1,49 @@
// 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 Windows.Foundation;
namespace Peek.UI.Extensions
{
public static class SizeExtensions
{
public static Size Fit(this Size sizeToFit, Size maxSize, Size minSize)
{
double fittedWidth = sizeToFit.Width;
double fittedHeight = sizeToFit.Height;
double ratioWidth = sizeToFit.Width / maxSize.Width;
double ratioHeight = sizeToFit.Height / maxSize.Height;
if (ratioWidth > ratioHeight)
{
if (ratioWidth > 1)
{
fittedWidth = maxSize.Width;
fittedHeight = sizeToFit.Height / ratioWidth;
}
}
else
{
if (ratioHeight > 1)
{
fittedWidth = sizeToFit.Width / ratioHeight;
fittedHeight = maxSize.Height;
}
}
if (fittedWidth < minSize.Width)
{
fittedWidth = minSize.Width;
}
if (fittedHeight < minSize.Height)
{
fittedHeight = minSize.Height;
}
return new Size(fittedWidth, fittedHeight);
}
}
}

View File

@@ -0,0 +1,57 @@
// 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 Microsoft.UI.Xaml;
using Windows.Foundation;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.Graphics.Gdi;
using WinUIEx;
namespace Peek.UI.Extensions
{
public static class WindowExtensions
{
public static Size GetMonitorSize(this Window window)
{
var hwnd = new HWND(window.GetWindowHandle());
var hwndDesktop = PInvoke.MonitorFromWindow(hwnd, MONITOR_FROM_FLAGS.MONITOR_DEFAULTTONEAREST);
MONITORINFO info = default(MONITORINFO);
info.cbSize = 40;
PInvoke.GetMonitorInfo(hwndDesktop, ref info);
double monitorWidth = info.rcMonitor.left + info.rcMonitor.right;
double monitorHeight = info.rcMonitor.bottom + info.rcMonitor.top;
return new Size(monitorWidth, monitorHeight);
}
public static double GetMonitorScale(this Window window)
{
var hwnd = new HWND(window.GetWindowHandle());
var dpi = PInvoke.GetDpiForWindow(new HWND(hwnd));
double scalingFactor = dpi / 96d;
return scalingFactor;
}
public static void BringToForeground(this Window window)
{
var foregroundWindowHandle = PInvoke.GetForegroundWindow();
uint targetProcessId = 0;
uint windowThreadProcessId = 0;
unsafe
{
windowThreadProcessId = PInvoke.GetWindowThreadProcessId(foregroundWindowHandle, &targetProcessId);
}
var windowHandle = window.GetWindowHandle();
var currentThreadId = PInvoke.GetCurrentThreadId();
PInvoke.AttachThreadInput(windowThreadProcessId, currentThreadId, true);
PInvoke.BringWindowToTop(new HWND(windowHandle));
PInvoke.ShowWindow(new HWND(windowHandle), Windows.Win32.UI.WindowsAndMessaging.SHOW_WINDOW_CMD.SW_SHOW);
PInvoke.AttachThreadInput(windowThreadProcessId, currentThreadId, false);
}
}
}

View File

@@ -0,0 +1,41 @@
// 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.Runtime.InteropServices;
using System.Text;
using Peek.Common.Helpers;
using Peek.Common.Models;
using Peek.UI.Native;
namespace Peek.UI.Helpers
{
public static class DefaultAppHelper
{
public static string TryGetDefaultAppName(string extension)
{
string appName = string.Empty;
// Get the length of the app name
uint length = 0;
HResult ret = NativeMethods.AssocQueryString(NativeMethods.AssocF.Verify, NativeMethods.AssocStr.FriendlyAppName, extension, null, null, ref length);
if (ret != HResult.False)
{
Logger.LogError($"Error when getting accessString for {extension} file: {Marshal.GetExceptionForHR((int)ret)!.Message}");
return appName;
}
// Get the app name
StringBuilder sb = new((int)length);
ret = NativeMethods.AssocQueryString(NativeMethods.AssocF.Verify, NativeMethods.AssocStr.FriendlyAppName, extension, null, sb, ref length);
if (ret != HResult.Ok)
{
Logger.LogError($"Error when getting accessString for {extension} file: {Marshal.GetExceptionForHR((int)ret)!.Message}" );
return appName;
}
appName = sb.ToString();
return appName;
}
}
}

View File

@@ -0,0 +1,96 @@
// 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 Peek.Common.Models;
using Peek.UI.Extensions;
using SHDocVw;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.UI.Shell;
using IServiceProvider = Peek.Common.Models.IServiceProvider;
namespace Peek.UI.Helpers
{
public static class FileExplorerHelper
{
internal static IShellItemArray? GetSelectedItems(HWND foregroundWindowHandle)
{
return GetItemsInternal(foregroundWindowHandle, onlySelectedFiles: true);
}
internal static IShellItemArray? GetItems(HWND foregroundWindowHandle)
{
return GetItemsInternal(foregroundWindowHandle, onlySelectedFiles: false);
}
private static IShellItemArray? GetItemsInternal(HWND foregroundWindowHandle, bool onlySelectedFiles)
{
if (foregroundWindowHandle.IsDesktopWindow())
{
return GetItemsFromDesktop(foregroundWindowHandle, onlySelectedFiles);
}
else
{
return GetItemsFromFileExplorer(foregroundWindowHandle, onlySelectedFiles);
}
}
private static IShellItemArray? GetItemsFromDesktop(HWND foregroundWindowHandle, bool onlySelectedFiles)
{
const int SWC_DESKTOP = 8;
const int SWFO_NEEDDISPATCH = 1;
var shell = new Shell32.Shell();
ShellWindows shellWindows = shell.Windows();
object? oNull1 = null;
object? oNull2 = null;
var serviceProvider = (IServiceProvider)shellWindows.FindWindowSW(ref oNull1, ref oNull2, SWC_DESKTOP, out int pHWND, SWFO_NEEDDISPATCH);
var shellBrowser = (IShellBrowser)serviceProvider.QueryService(PInvoke.SID_STopLevelBrowser, typeof(IShellBrowser).GUID);
IShellItemArray? shellItemArray = GetShellItemArray(shellBrowser, onlySelectedFiles);
return shellItemArray;
}
private static IShellItemArray? GetItemsFromFileExplorer(HWND foregroundWindowHandle, bool onlySelectedFiles)
{
IShellItemArray? shellItemArray = null;
var activeTab = foregroundWindowHandle.GetActiveTab();
var shell = new Shell32.Shell();
ShellWindows shellWindows = shell.Windows();
foreach (IWebBrowserApp webBrowserApp in shell.Windows())
{
var shellFolderView = (Shell32.IShellFolderViewDual2)webBrowserApp.Document;
var folderTitle = shellFolderView.Folder.Title;
if (webBrowserApp.HWND == foregroundWindowHandle)
{
var serviceProvider = (IServiceProvider)webBrowserApp;
var shellBrowser = (IShellBrowser)serviceProvider.QueryService(PInvoke.SID_STopLevelBrowser, typeof(IShellBrowser).GUID);
shellBrowser.GetWindow(out IntPtr shellBrowserHandle);
if (activeTab == shellBrowserHandle)
{
shellItemArray = GetShellItemArray(shellBrowser, onlySelectedFiles);
return shellItemArray;
}
}
}
return shellItemArray;
}
private static IShellItemArray? GetShellItemArray(IShellBrowser shellBrowser, bool onlySelectedFiles)
{
var shellView = (IFolderView)shellBrowser.QueryActiveShellView();
var selectionFlag = onlySelectedFiles ? (uint)_SVGIO.SVGIO_SELECTION : (uint)_SVGIO.SVGIO_ALLVIEW;
shellView.Items(selectionFlag, typeof(IShellItemArray).GUID, out var items);
return items as IShellItemArray;
}
}
}

View File

@@ -0,0 +1,43 @@
<!-- Copyright (c) Microsoft Corporation and Contributors. -->
<!-- Licensed under the MIT License. -->
<winuiex:WindowEx
x:Class="Peek.UI.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:fp="using:Peek.FilePreviewer"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:Peek.UI.Views"
xmlns:winuiex="using:WinUIEx"
mc:Ignorable="d">
<winuiex:WindowEx.Backdrop>
<winuiex:MicaSystemBackdrop />
</winuiex:WindowEx.Backdrop>
<Grid KeyboardAcceleratorPlacementMode="Hidden">
<Grid.KeyboardAccelerators>
<KeyboardAccelerator Key="Left" Invoked="LeftNavigationInvoked" />
<KeyboardAccelerator Key="Right" Invoked="RightNavigationInvoked" />
</Grid.KeyboardAccelerators>
<Grid.RowDefinitions>
<RowDefinition Height="48" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<views:TitleBar
x:Name="TitleBarControl"
Grid.Row="0"
FileIndex="{x:Bind ViewModel.CurrentIndex, Mode=OneWay}"
IsMultiSelection="{x:Bind ViewModel.NeighboringItemsQuery.IsMultipleFilesActivation, Mode=OneWay}"
Item="{x:Bind ViewModel.CurrentItem, Mode=OneWay}"
NumberOfFiles="{x:Bind ViewModel.Items.Count, Mode=OneWay}" />
<fp:FilePreview
Grid.Row="1"
Item="{x:Bind ViewModel.CurrentItem, Mode=OneWay}"
PreviewSizeChanged="FilePreviewer_PreviewSizeChanged"
ScalingFactor="{x:Bind ViewModel.ScalingFactor, Mode=OneWay}" />
</Grid>
</winuiex:WindowEx>

View File

@@ -0,0 +1,169 @@
// 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 interop;
using Microsoft.PowerToys.Telemetry;
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
{
public MainWindowViewModel ViewModel { get; }
public MainWindow()
{
InitializeComponent();
ViewModel = App.GetService<MainWindowViewModel>();
NativeEventWaiter.WaitForEventLoop(Constants.ShowPeekEvent(), OnPeekHotkey);
TitleBarControl.SetTitleBarToWindow(this);
AppWindow.Closing += AppWindow_Closing;
}
/// <summary>
/// Handle Peek hotkey, by toggling the window visibility and querying files when necessary.
/// </summary>
private void OnPeekHotkey()
{
if (AppWindow.IsVisible)
{
if (IsNewSingleSelectedItem())
{
Initialize();
}
else
{
Uninitialize();
}
}
else
{
Initialize();
}
}
private void LeftNavigationInvoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
{
ViewModel.AttemptLeftNavigation();
}
private void RightNavigationInvoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args)
{
ViewModel.AttemptRightNavigation();
}
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 monitorSize = this.GetMonitorSize();
// If no size is requested, try to fit to the monitor size.
Size requestedSize = e.WindowSizeRequested ?? monitorSize;
double titleBarHeight = TitleBarControl.ActualHeight;
double maxContentWidth = monitorSize.Width * WindowConstants.MaxWindowToMonitorRatio;
double maxContentHeight = (monitorSize.Height - titleBarHeight) * WindowConstants.MaxWindowToMonitorRatio;
Size maxContentSize = new(maxContentWidth, maxContentHeight);
double minContentWidth = WindowConstants.MinWindowWidth;
double minContentHeight = WindowConstants.MinWindowHeight - titleBarHeight;
Size minContentSize = new(minContentWidth, minContentHeight);
Size adjustedContentSize = requestedSize.Fit(maxContentSize, minContentSize);
// TODO: Only re-center if window has not been resized by user (or use design-defined logic).
// TODO: Investigate why portrait images do not perfectly fit edge-to-edge
double monitorScale = this.GetMonitorScale();
double scaledWindowWidth = adjustedContentSize.Width / monitorScale;
double scaledWindowHeight = adjustedContentSize.Height / monitorScale;
double desiredScaledHeight = scaledWindowHeight + titleBarHeight + WindowConstants.WindowWidthContentPadding;
double desiredScaledWidth = scaledWindowWidth + WindowConstants.WindowHeightContentPadding;
if (!TitleBarControl.Pinned)
{
this.CenterOnScreen(desiredScaledWidth, desiredScaledHeight); // re-center if not pinned
}
this.Show();
this.BringToForeground();
}
/// <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()
{
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;
}
}
}

View File

@@ -0,0 +1,99 @@
// 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 System.Linq;
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.UI.Xaml;
using Peek.Common.Helpers;
using Peek.Common.Models;
using Peek.UI.Models;
namespace Peek.UI
{
public partial class MainWindowViewModel : ObservableObject
{
private const int NavigationThrottleDelayMs = 100;
[ObservableProperty]
private int _currentIndex;
[ObservableProperty]
private IFileSystemItem? _currentItem;
[ObservableProperty]
private NeighboringItems? _items;
[ObservableProperty]
private double _scalingFactor = 1.0;
public NeighboringItemsQuery NeighboringItemsQuery { get; }
private DispatcherTimer NavigationThrottleTimer { get; set; } = new();
public MainWindowViewModel(NeighboringItemsQuery query)
{
NeighboringItemsQuery = query;
NavigationThrottleTimer.Tick += NavigationThrottleTimer_Tick;
NavigationThrottleTimer.Interval = TimeSpan.FromMilliseconds(NavigationThrottleDelayMs);
}
public void Initialize()
{
Items = NeighboringItemsQuery.GetNeighboringItems();
CurrentIndex = 0;
if (Items != null && Items.Count > 0)
{
CurrentItem = Items[0];
}
}
public void Uninitialize()
{
CurrentIndex = 0;
CurrentItem = null;
Items = null;
}
public void AttemptLeftNavigation()
{
if (NavigationThrottleTimer.IsEnabled)
{
return;
}
NavigationThrottleTimer.Start();
var itemCount = Items?.Count ?? 1;
CurrentIndex = MathHelper.Modulo(CurrentIndex - 1, itemCount);
CurrentItem = Items?.ElementAtOrDefault(CurrentIndex);
}
public void AttemptRightNavigation()
{
if (NavigationThrottleTimer.IsEnabled)
{
return;
}
NavigationThrottleTimer.Start();
var itemCount = Items?.Count ?? 1;
CurrentIndex = MathHelper.Modulo(CurrentIndex + 1, itemCount);
CurrentItem = Items?.ElementAtOrDefault(CurrentIndex);
}
private void NavigationThrottleTimer_Tick(object? sender, object e)
{
if (sender == null)
{
return;
}
((DispatcherTimer)sender).Stop();
}
}
}

View File

@@ -0,0 +1,39 @@
// 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.Collections;
using System.Collections.Generic;
using Peek.Common.Models;
using Peek.UI.Extensions;
namespace Peek.UI.Models
{
public class NeighboringItems : IReadOnlyList<IFileSystemItem>
{
public IFileSystemItem this[int index] => Items[index] = Items[index] ?? ShellItemArray.GetItemAt(index).ToIFileSystemItem();
public int Count { get; }
private IFileSystemItem[] Items { get; }
private IShellItemArray ShellItemArray { get; }
public NeighboringItems(IShellItemArray shellItemArray)
{
ShellItemArray = shellItemArray;
Count = ShellItemArray.GetCount();
Items = new IFileSystemItem[Count];
}
public IEnumerator<IFileSystemItem> GetEnumerator()
{
return new NeighboringItemsEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}

View File

@@ -0,0 +1,50 @@
// 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 System.Collections;
using System.Collections.Generic;
using Peek.Common.Models;
namespace Peek.UI.Models
{
public class NeighboringItemsEnumerator : IEnumerator<IFileSystemItem>
{
public IFileSystemItem Current => Items[CurrentIndex];
object IEnumerator.Current => Current;
private int CurrentIndex { get; set; }
private NeighboringItems Items { get; }
public NeighboringItemsEnumerator(NeighboringItems items)
{
CurrentIndex = -1;
Items = items;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public bool MoveNext()
{
if (CurrentIndex >= Items.Count)
{
return false;
}
CurrentIndex++;
return true;
}
public void Reset()
{
CurrentIndex = -1;
}
}
}

View File

@@ -0,0 +1,54 @@
// 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 System.Runtime.InteropServices;
using System.Text;
using Peek.Common.Models;
namespace Peek.UI.Native
{
public static class NativeMethods
{
[Flags]
public enum AssocF
{
None = 0,
Init_NoRemapCLSID = 0x1,
Init_ByExeName = 0x2,
Open_ByExeName = 0x3,
Init_DefaultToStar = 0x4,
Init_DefaultToFolder = 0x8,
NoUserSettings = 0x10,
NoTruncate = 0x20,
Verify = 0x40,
RemapRunDll = 0x80,
NoFixUps = 0x100,
IgnoreBaseClass = 0x200,
}
public enum AssocStr
{
Command = 1,
Executable,
FriendlyDocName,
FriendlyAppName,
NoOpen,
ShellNewValue,
DDECommand,
DDEIfExec,
DDEApplication,
DDETopic,
}
[DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern HResult AssocQueryString(AssocF flags, AssocStr str, string pszAssoc, string? pszExtra, [Out] StringBuilder? pszOut, [In][Out] ref uint pcchOut);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetWindowText(Windows.Win32.Foundation.HWND hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetClassName(IntPtr hWnd, StringBuilder buf, int nMaxCount);
}
}

View File

@@ -0,0 +1,29 @@
// 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 System.Threading;
using Microsoft.UI.Dispatching;
namespace Peek.UI.Native
{
public static class NativeEventWaiter
{
public static void WaitForEventLoop(string eventName, Action callback)
{
var dispatcherQueue = DispatcherQueue.GetForCurrentThread();
new Thread(() =>
{
var eventHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName);
while (true)
{
if (eventHandle.WaitOne())
{
dispatcherQueue.TryEnqueue(() => callback());
}
}
}).Start();
}
}
}

View File

@@ -0,0 +1,14 @@
MonitorFromWindow
GetMonitorInfo
GetDpiForWindow
GetForegroundWindow
GetWindowThreadProcessId
GetCurrentThreadId
AttachThreadInput
BringWindowToTop
ShowWindow
GetWindowTextLength
FindWindowEx
SID_STopLevelBrowser
GetClassName
_SVGIO

View File

@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap rescap">
<Identity
Name="62c2f436-8802-4c26-a73d-b3b8613016fd"
Publisher="CN=sachaple"
Version="1.0.0.0" />
<Properties>
<DisplayName>Peek.UI</DisplayName>
<PublisherDisplayName>sachaple</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.17763.0" MaxVersionTested="10.0.19041.0" />
<TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.17763.0" MaxVersionTested="10.0.19041.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate"/>
</Resources>
<Applications>
<Application Id="App"
Executable="$targetnametoken$.exe"
EntryPoint="$targetentrypoint$">
<uap:VisualElements
DisplayName="Peek.UI"
Description="Peek.UI"
BackgroundColor="transparent"
Square150x150Logo="Assets\Square150x150Logo.png"
Square44x44Logo="Assets\Square44x44Logo.png">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png" />
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
<Capabilities>
<rescap:Capability Name="runFullTrust" />
</Capabilities>
</Package>

View File

@@ -0,0 +1,118 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\..\Version.props" />
<PropertyGroup>
<AssemblyName>PowerToys.Peek.UI</AssemblyName>
<AssemblyTitle>PowerToys.Peek.UI</AssemblyTitle>
<AssemblyDescription>PowerToys Peek UI</AssemblyDescription>
<RootNamespace>Peek.UI</RootNamespace>
<OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows10.0.19041.0</TargetFramework>
<TargetPlatformMinVersion>10.0.19041.0</TargetPlatformMinVersion>
<OutputPath>..\..\..\..\$(Platform)\$(Configuration)\modules\Peek\</OutputPath>
<ApplicationManifest>app.manifest</ApplicationManifest>
<Platforms>x86;x64;ARM64</Platforms>
<RuntimeIdentifiers>win10-x86;win10-x64;win10-arm64</RuntimeIdentifiers>
<UseWinUI>true</UseWinUI>
<GenerateSatelliteAssembliesForCore>true</GenerateSatelliteAssembliesForCore>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
<EnablePreviewMsixTooling>true</EnablePreviewMsixTooling>
<WindowsPackageType>None</WindowsPackageType>
<WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained>
<SupportedOSPlatformVersion>10.0.19041.0</SupportedOSPlatformVersion>
<Nullable>Enable</Nullable>
<ApplicationIcon>Assets\Icon.ico</ApplicationIcon>
<SelfContained>true</SelfContained>
</PropertyGroup>
<!-- SelfContained=true requires RuntimeIdentifier to be set -->
<PropertyGroup Condition="'$(Platform)'=='x64'">
<RuntimeIdentifier>win10-x64</RuntimeIdentifier>
</PropertyGroup>
<PropertyGroup Condition="'$(Platform)'=='ARM64'">
<RuntimeIdentifier>win10-arm64</RuntimeIdentifier>
</PropertyGroup>
<!-- See https://learn.microsoft.com/windows/apps/develop/platform/csharp-winrt/net-projection-from-cppwinrt-component for more info -->
<PropertyGroup>
<CsWinRTIncludes>PowerToys.GPOWrapper</CsWinRTIncludes>
<CsWinRTGeneratedFilesDir>$(OutDir)</CsWinRTGeneratedFilesDir>
<ErrorOnDuplicatePublishOutputFiles>false</ErrorOnDuplicatePublishOutputFiles>
</PropertyGroup>
<ItemGroup>
<Content Include="Assets\Icon.ico" />
</ItemGroup>
<ItemGroup>
<None Remove="Assets\AppList.scale-100.png" />
<None Remove="Assets\AppList.scale-125.png" />
<None Remove="Assets\AppList.scale-150.png" />
<None Remove="Assets\AppList.scale-200.png" />
<None Remove="Assets\AppList.scale-400.png" />
<None Remove="Views\TitleBar.xaml" />
<None Remove="Views\UnsupportedFile.xaml" />
</ItemGroup>
<ItemGroup>
<COMReference Include="Shell32">
<VersionMinor>0</VersionMinor>
<VersionMajor>1</VersionMajor>
<Guid>50a7e9b0-70ef-11d1-b75a-00a0c90564fe</Guid>
<Lcid>0</Lcid>
<WrapperTool>tlbimp</WrapperTool>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
<COMReference Include="SHDocVw">
<VersionMinor>1</VersionMinor>
<VersionMajor>1</VersionMajor>
<Guid>eab22ac0-30c1-11cf-a7eb-0000c05bae0b</Guid>
<Lcid>0</Lcid>
<WrapperTool>tlbimp</WrapperTool>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" />
<PackageReference Include="Microsoft.Windows.CsWinRT" />
<PackageReference Include="Microsoft.Windows.CsWin32">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="CommunityToolkit.Mvvm" />
<PackageReference Include="Microsoft.WindowsAppSDK" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" />
<PackageReference Include="WinUIEx" />
<Manifest Include="$(ApplicationManifest)" />
</ItemGroup>
<!--
Defining the "Msix" ProjectCapability here allows the Single-project MSIX Packaging
Tools extension to be activated for this project even if the Windows App SDK Nuget
package has not yet been restored.
-->
<ItemGroup Condition="'$(DisableMsixProjectCapabilityAddedByProject)'!='true' and '$(EnableMsixTooling)'=='true'">
<ProjectCapability Include="Msix" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\common\GPOWrapper\GPOWrapper.vcxproj" />
<ProjectReference Include="..\..\..\common\interop\PowerToys.Interop.vcxproj" />
<ProjectReference Include="..\..\..\common\ManagedCommon\ManagedCommon.csproj" />
<ProjectReference Include="..\Peek.Common\Peek.Common.csproj" />
<ProjectReference Include="..\Peek.FilePreviewer\Peek.FilePreviewer.csproj" />
</ItemGroup>
<ItemGroup>
<Resource Include="Assets\Icon.ico" />
</ItemGroup>
<ItemGroup>
<Page Update="Views\UnsupportedFile.xaml">
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
<ItemGroup>
<Page Update="Views\TitleBar.xaml">
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,43 @@
// 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.Diagnostics;
using CommunityToolkit.Mvvm.ComponentModel;
using Peek.Common.Models;
using Peek.UI.Extensions;
using Peek.UI.Helpers;
using Peek.UI.Models;
namespace Peek.UI
{
public partial class NeighboringItemsQuery : ObservableObject
{
[ObservableProperty]
private bool isMultipleFilesActivation;
public NeighboringItems? GetNeighboringItems()
{
var foregroundWindowHandle = Windows.Win32.PInvoke.GetForegroundWindow();
var selectedItemsShellArray = FileExplorerHelper.GetSelectedItems(foregroundWindowHandle);
var selectedItemsCount = selectedItemsShellArray?.GetCount() ?? 0;
if (selectedItemsShellArray == null || selectedItemsCount < 1)
{
return null;
}
bool hasMoreThanOneItem = selectedItemsCount > 1;
IsMultipleFilesActivation = hasMoreThanOneItem;
var neighboringItemsShellArray = hasMoreThanOneItem ? selectedItemsShellArray : FileExplorerHelper.GetItems(foregroundWindowHandle);
if (neighboringItemsShellArray == null)
{
return null;
}
return new NeighboringItems(neighboringItemsShellArray);
}
}
}

View File

@@ -0,0 +1,216 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AppTitle.Title" xml:space="preserve">
<value>Peek</value>
<comment>Name of application.</comment>
</data>
<data name="AppTitle_FileCounts_Text" xml:space="preserve">
<value>({0}/{1})</value>
<comment>Text for the file count in the title bar. 0: the index of the current file. 1: the total number of files selected.</comment>
</data>
<data name="LaunchAppButton_OpenWith_Text" xml:space="preserve">
<value>Open with</value>
<comment>Text for button to launch the application picker.</comment>
</data>
<data name="LaunchAppButton_OpenWith_ToolTip" xml:space="preserve">
<value>Open with (Enter)</value>
<comment>Tooltip for button to launch the application picker.</comment>
</data>
<data name="LaunchAppButton_OpenWithApp_Text" xml:space="preserve">
<value>Open with {0}</value>
<comment>Text for button to launch default application. 0: name of the default application.</comment>
</data>
<data name="LaunchAppButton_OpenWithApp_ToolTip" xml:space="preserve">
<value>Open with {0} (Enter)</value>
<comment>Tooltip for button to launch default application. 0: name of the default application.</comment>
</data>
<data name="UnsupportedFile_FileType" xml:space="preserve">
<value>File Type: {0}</value>
<comment>File Type label for the unsupported files view. {0} is the type.</comment>
</data>
<data name="UnsupportedFile_FileSize" xml:space="preserve">
<value>Size: {0}</value>
<comment>File Size label for the unsupported files view. {0} is the size.</comment>
</data>
<data name="UnsupportedFile_DateModified" xml:space="preserve">
<value>Date Modified: {0}</value>
<comment>Date Modified label for the unsupported files view. {0} is the date.</comment>
</data>
<data name="ReadableString_ByteAbbreviationFormat" xml:space="preserve">
<value>{0} bytes</value>
<comment>Abbreviation for the size unit byte.</comment>
</data>
<data name="ReadableString_KiloByteAbbreviationFormat" xml:space="preserve">
<value>{0} KB</value>
<comment>Abbreviation for the size unit kilobyte.</comment>
</data>
<data name="ReadableString_MegaByteAbbreviationFormat" xml:space="preserve">
<value>{0} MB</value>
<comment>Abbreviation for the size unit megabyte.</comment>
</data>
<data name="ReadableString_GigaByteAbbreviationFormat" xml:space="preserve">
<value>{0} GB</value>
<comment>Abbreviation for the size unit gigabyte.</comment>
</data>
<data name="ReadableString_TeraByteAbbreviationFormat" xml:space="preserve">
<value>{0} TB</value>
<comment>Abbreviation for the size unit terabyte.</comment>
</data>
<data name="ReadableString_PetaByteAbbreviationFormat" xml:space="preserve">
<value>{0} PB</value>
<comment>Abbreviation for the size unit petabyte.</comment>
</data>
<data name="ReadableString_ExaByteAbbreviationFormat" xml:space="preserve">
<value>{0} EB</value>
<comment>Abbreviation for the size unit exabyte.</comment>
</data>
<data name="PreviewTooltip_FileName" xml:space="preserve">
<value>Filename: {0}</value>
<comment>Filename for the tooltip of preview. {0} is the name.</comment>
</data>
<data name="PreviewTooltip_FileType" xml:space="preserve">
<value>Item Type: {0}</value>
<comment>Item Type for the tooltip of preview. {0} is the type.</comment>
</data>
<data name="PreviewTooltip_DateModified" xml:space="preserve">
<value>Date Modified: {0}</value>
<comment>Date Modified label for the tooltip of preview. {0} is the date.</comment>
</data>
<data name="PreviewTooltip_Dimensions" xml:space="preserve">
<value>Dimensions: {0} x {1}</value>
<comment>Dimensions label for the tooltip of preview. {0} is the width, {1} is the height.</comment>
</data>
<data name="PreviewTooltip_FileSize" xml:space="preserve">
<value>Size: {0}</value>
<comment>File Size label for the tooltip of preview. {0} is the size.</comment>
</data>
<data name="PreviewTooltip_Blank" xml:space="preserve">
<value>File preview</value>
<comment>Tooltip of preview when there's no file info available.</comment>
</data>
<data name="PinButton_Tooltip" xml:space="preserve">
<value>Pin the window to the current location</value>
<comment>Tooltip for button to pin the Peek window.</comment>
</data>
<data name="UnpinButton_ToolTip" xml:space="preserve">
<value>Unpin the window</value>
<comment>Tooltip for button to unpin the Peek window.</comment>
</data>
</root>

View File

@@ -0,0 +1,149 @@
<!-- Copyright (c) Microsoft Corporation and Contributors. -->
<!-- Licensed under the MIT License. -->
<UserControl
x:Class="Peek.UI.Views.TitleBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:Peek.UI.Views"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid x:Name="TitleBarRootContainer" Height="48">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="SystemLeftPaddingColumn" Width="0" />
<ColumnDefinition x:Name="DraggableColumn" Width="*" />
<ColumnDefinition x:Name="LaunchAppButtonColumn" Width="Auto" />
<ColumnDefinition x:Name="AppRightPaddingColumn" Width="65" />
<ColumnDefinition x:Name="PinButtonColumn" Width="40" />
<ColumnDefinition x:Name="SystemRightPaddingColumn" Width="0" />
</Grid.ColumnDefinitions>
<Grid
x:Name="AppIconAndFileTitleContainer"
Grid.Column="1"
Margin="8,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
ColumnSpacing="4">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="AppIconColumn" Width="32" />
<ColumnDefinition x:Name="FileTitleColumn" Width="*" />
</Grid.ColumnDefinitions>
<Image
x:Name="PeekLogo"
x:Uid="PeekLogo"
Grid.Column="0"
Width="24"
Height="24"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Source="../Assets/AppList.scale-400.png"
Stretch="UniformToFill" />
<Grid
x:Name="FileCountAndNameContainer"
Grid.Column="1"
HorizontalAlignment="Left"
VerticalAlignment="Center"
ColumnSpacing="4">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="FileCountColumn" Width="auto" />
<ColumnDefinition x:Name="FileNameColumn" Width="*" />
</Grid.ColumnDefinitions>
<TextBlock
x:Name="AppTitle_FileCount"
x:Uid="AppTitle_FileCount"
Grid.Column="0"
FontWeight="Bold"
Style="{StaticResource CaptionTextBlockStyle}"
Text="{x:Bind FileCountText, Mode=OneWay}"
Visibility="{x:Bind IsMultiSelection, Mode=OneWay}" />
<TextBlock
x:Name="AppTitle_FileName"
x:Uid="AppTitle_FileName"
Grid.Column="1"
Style="{StaticResource CaptionTextBlockStyle}"
Text="{x:Bind Item.Name, Mode=OneWay}"
TextWrapping="NoWrap" />
</Grid>
</Grid>
<Button
x:Name="LaunchAppButton"
x:Uid="LaunchAppButton"
Grid.Column="2"
VerticalAlignment="Center"
Command="{x:Bind LaunchDefaultAppButtonAsyncCommand, Mode=OneWay}"
ToolTipService.ToolTip="{x:Bind OpenWithAppToolTip, Mode=OneWay}"
Visibility="{x:Bind IsLaunchDefaultAppButtonVisible(DefaultAppName), Mode=OneWay}">
<Button.Content>
<StackPanel Orientation="Horizontal" Spacing="4">
<FontIcon
x:Name="LaunchAppButton_Icon"
x:Uid="LaunchAppButton_Icon"
FontSize="{StaticResource CaptionTextBlockFontSize}"
Glyph="&#xE8E5;" />
<TextBlock
x:Name="LaunchAppButton_Text"
x:Uid="LaunchAppButton_Text"
Style="{StaticResource CaptionTextBlockStyle}"
Text="{x:Bind OpenWithAppText, Mode=OneWay}" />
</StackPanel>
</Button.Content>
<Button.KeyboardAccelerators>
<KeyboardAccelerator Key="Enter" />
</Button.KeyboardAccelerators>
</Button>
<Button
x:Name="PinButton"
x:Uid="PinButton"
Grid.Column="4"
VerticalAlignment="Center"
Command="{x:Bind PinCommand, Mode=OneWay}"
ToolTipService.ToolTip="{x:Bind PinToolTip(Pinned), Mode=OneWay}">
<Button.Content>
<FontIcon
x:Name="PinButton_Icon"
x:Uid="PinButton_Icon"
FontSize="{StaticResource CaptionTextBlockFontSize}"
Glyph="{x:Bind PinGlyph(Pinned), Mode=OneWay}" />
</Button.Content>
</Button>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="AdaptiveWidth">
<VisualState x:Name="MaximumLayout">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="560" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="LaunchAppButton_Text.Visibility" Value="Visible" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="MediumLayout">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="340" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="LaunchAppButton_Text.Visibility" Value="Collapsed" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="MinimumLayout">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="0" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="LaunchAppButton_Text.Visibility" Value="Collapsed" />
<Setter Target="LaunchAppButton.Visibility" Value="Collapsed" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</UserControl>

View File

@@ -0,0 +1,272 @@
// 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 System.Collections.Generic;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ManagedCommon;
using Microsoft.PowerToys.Telemetry;
using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Peek.Common.Models;
using Peek.UI.Extensions;
using Peek.UI.Helpers;
using Peek.UI.Telemetry.Events;
using Windows.ApplicationModel.Resources;
using Windows.Graphics;
using Windows.Storage;
using Windows.System;
using WinUIEx;
namespace Peek.UI.Views
{
[INotifyPropertyChanged]
public sealed partial class TitleBar : UserControl
{
public static readonly DependencyProperty ItemProperty =
DependencyProperty.Register(
nameof(Item),
typeof(IFileSystemItem),
typeof(TitleBar),
new PropertyMetadata(null, (d, e) => ((TitleBar)d).OnFilePropertyChanged()));
public static readonly DependencyProperty FileIndexProperty =
DependencyProperty.Register(
nameof(FileIndex),
typeof(int),
typeof(TitleBar),
new PropertyMetadata(-1, (d, e) => ((TitleBar)d).OnFileIndexPropertyChanged()));
public static readonly DependencyProperty IsMultiSelectionProperty =
DependencyProperty.Register(
nameof(IsMultiSelection),
typeof(bool),
typeof(TitleBar),
new PropertyMetadata(false));
public static readonly DependencyProperty NumberOfFilesProperty =
DependencyProperty.Register(
nameof(NumberOfFiles),
typeof(int),
typeof(TitleBar),
new PropertyMetadata(null, null));
[ObservableProperty]
private string openWithAppText = ResourceLoader.GetForViewIndependentUse().GetString("LaunchAppButton_OpenWith_Text");
[ObservableProperty]
private string openWithAppToolTip = ResourceLoader.GetForViewIndependentUse().GetString("LaunchAppButton_OpenWith_ToolTip");
[ObservableProperty]
private string? fileCountText;
[ObservableProperty]
private string defaultAppName = string.Empty;
[ObservableProperty]
private bool pinned = false;
public TitleBar()
{
InitializeComponent();
TitleBarRootContainer.SizeChanged += TitleBarRootContainer_SizeChanged;
}
public IFileSystemItem Item
{
get => (IFileSystemItem)GetValue(ItemProperty);
set => SetValue(ItemProperty, value);
}
public int FileIndex
{
get => (int)GetValue(FileIndexProperty);
set => SetValue(FileIndexProperty, value);
}
public bool IsMultiSelection
{
get => (bool)GetValue(IsMultiSelectionProperty);
set => SetValue(IsMultiSelectionProperty, value);
}
public int NumberOfFiles
{
get => (int)GetValue(NumberOfFilesProperty);
set => SetValue(NumberOfFilesProperty, value);
}
private Window? MainWindow { get; set; }
public void SetTitleBarToWindow(MainWindow mainWindow)
{
MainWindow = mainWindow;
if (AppWindowTitleBar.IsCustomizationSupported())
{
UpdateTitleBarCustomization(mainWindow);
}
else
{
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
ThemeHelpers.SetImmersiveDarkMode(hWnd, ThemeHelpers.GetAppTheme() == AppTheme.Dark);
Visibility = Visibility.Collapsed;
// Set window icon
WindowId windowId = Win32Interop.GetWindowIdFromWindow(hWnd);
AppWindow appWindow = AppWindow.GetFromWindowId(windowId);
appWindow.SetIcon("Assets/Icon.ico");
}
}
public Visibility IsLaunchDefaultAppButtonVisible(string appName)
{
return string.IsNullOrEmpty(appName) ? Visibility.Collapsed : Visibility.Visible;
}
[RelayCommand]
private async void LaunchDefaultAppButtonAsync()
{
if (Item is not FileItem fileItem)
{
return;
}
StorageFile? storageFile = await fileItem.GetStorageFileAsync();
LauncherOptions options = new();
PowerToysTelemetry.Log.WriteEvent(new OpenWithEvent() { App = DefaultAppName ?? string.Empty });
if (string.IsNullOrEmpty(DefaultAppName))
{
// If there's no default app found, open the App picker
options.DisplayApplicationPicker = true;
}
else
{
// Try to launch the default app for current file format
bool result = await Launcher.LaunchFileAsync(storageFile, options);
if (!result)
{
// If we couldn't successfully open the default app, open the App picker as a fallback
options.DisplayApplicationPicker = true;
await Launcher.LaunchFileAsync(storageFile, options);
}
}
}
public string PinGlyph(bool pinned)
{
return pinned ? "\xE840" : "\xE718";
}
public string PinToolTip(bool pinned)
{
return pinned ? ResourceLoader.GetForViewIndependentUse().GetString("UnpinButton_ToolTip") : ResourceLoader.GetForViewIndependentUse().GetString("PinButton_ToolTip");
}
[RelayCommand]
private void Pin()
{
Pinned = !Pinned;
}
private void TitleBarRootContainer_SizeChanged(object sender, SizeChangedEventArgs e)
{
UpdateDragRegion();
}
private void UpdateDragRegion()
{
if (MainWindow == null)
{
return;
}
var appWindow = MainWindow.GetAppWindow();
if (AppWindowTitleBar.IsCustomizationSupported() && appWindow != null && appWindow.TitleBar.ExtendsContentIntoTitleBar)
{
var scale = MainWindow.GetMonitorScale();
SystemRightPaddingColumn.Width = new GridLength(appWindow.TitleBar.RightInset / scale);
SystemLeftPaddingColumn.Width = new GridLength(appWindow.TitleBar.LeftInset / scale);
var dragRectsList = new List<RectInt32>();
RectInt32 dragRectangleLeft;
dragRectangleLeft.X = (int)(SystemLeftPaddingColumn.ActualWidth * scale);
dragRectangleLeft.Y = 0;
dragRectangleLeft.Height = (int)(TitleBarRootContainer.ActualHeight * scale);
dragRectangleLeft.Width = (int)(DraggableColumn.ActualWidth * scale);
RectInt32 dragRectangleRight;
dragRectangleRight.X = (int)((SystemLeftPaddingColumn.ActualWidth + DraggableColumn.ActualWidth + LaunchAppButtonColumn.ActualWidth) * scale);
dragRectangleRight.Y = 0;
dragRectangleRight.Height = (int)(TitleBarRootContainer.ActualHeight * scale);
dragRectangleRight.Width = (int)(AppRightPaddingColumn.ActualWidth * scale);
dragRectsList.Add(dragRectangleLeft);
dragRectsList.Add(dragRectangleRight);
appWindow.TitleBar.SetDragRectangles(dragRectsList.ToArray());
}
}
private void UpdateTitleBarCustomization(MainWindow mainWindow)
{
if (AppWindowTitleBar.IsCustomizationSupported())
{
AppWindow appWindow = mainWindow.GetAppWindow();
appWindow.TitleBar.ExtendsContentIntoTitleBar = true;
appWindow.TitleBar.ButtonBackgroundColor = Colors.Transparent;
appWindow.TitleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
mainWindow.SetTitleBar(this);
}
}
private void OnFilePropertyChanged()
{
if (Item == null)
{
return;
}
UpdateFileCountText();
UpdateDefaultAppToLaunch();
}
private void OnFileIndexPropertyChanged()
{
UpdateFileCountText();
}
private void UpdateFileCountText()
{
// Update file count
if (NumberOfFiles > 1)
{
string fileCountTextFormat = ResourceLoader.GetForViewIndependentUse().GetString("AppTitle_FileCounts_Text");
FileCountText = string.Format(CultureInfo.InvariantCulture, fileCountTextFormat, FileIndex + 1, NumberOfFiles);
}
}
private void UpdateDefaultAppToLaunch()
{
// Update the name of default app to launch
DefaultAppName = DefaultAppHelper.TryGetDefaultAppName(Item.Extension);
string openWithAppTextFormat = ResourceLoader.GetForViewIndependentUse().GetString("LaunchAppButton_OpenWithApp_Text");
OpenWithAppText = string.Format(CultureInfo.InvariantCulture, openWithAppTextFormat, DefaultAppName);
string openWithAppToolTipFormat = ResourceLoader.GetForViewIndependentUse().GetString("LaunchAppButton_OpenWithApp_ToolTip");
OpenWithAppToolTip = string.Format(CultureInfo.InvariantCulture, openWithAppToolTipFormat, DefaultAppName);
}
}
}

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="Peek.UI.app"/>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!--The ID below informs the system that this application is compatible with OS features first introduced in Windows 8.
For more info see https://docs.microsoft.com/windows/win32/sysinfo/targeting-your-application-at-windows-8-1
It is also necessary to support features in unpackaged applications, for example the custom title bar implementation.-->
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
</application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<!-- The combination of below two tags have the following effect:
1) Per-Monitor for >= Windows 10 Anniversary Update
2) System < Windows 10 Anniversary Update
-->
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
</windowsSettings>
</application>
</assembly>