Compare commits

..

1 Commits

Author SHA1 Message Date
Leilei Zhang
3cde0b2a68 fix using wrong event 2025-08-06 09:43:02 +08:00
248 changed files with 1398 additions and 2465 deletions

View File

@@ -115,7 +115,6 @@ bigbar
bigobj
binlog
binres
binskim
BITMAPFILEHEADER
bitmapimage
BITMAPINFO
@@ -256,7 +255,6 @@ Corpor
cotaskmem
COULDNOT
countof
covrun
cpcontrols
cph
cplusplus
@@ -637,7 +635,6 @@ hmodule
hmonitor
homies
homljgmgpmcbpjbnjpfijnhipfkiclkd
HOOKPROC
HORZRES
HORZSIZE
Hostbackdropbrush
@@ -972,7 +969,6 @@ msc
mscorlib
msctls
msdata
msdia
MSDL
MSGFLT
MSHCTX

View File

@@ -17,7 +17,7 @@ jobs:
steps:
- name: BODGY - Set up Gnome Keyring for future Cert Auth
run: |-
sudo apt-get update && sudo apt-get install -y gnome-keyring
sudo apt-get install -y gnome-keyring
export $(dbus-launch --sh-syntax)
export $(echo 'anypass_just_to_unlock' | gnome-keyring-daemon --unlock)
export $(echo 'anypass_just_to_unlock' | gnome-keyring-daemon --start --components=gpg,pkcs11,secrets,ssh)

View File

@@ -64,10 +64,6 @@ extends:
tsa:
enabled: true
configFile: '$(Build.SourcesDirectory)\.pipelines\tsa.json'
binskim:
enabled: true
# Exclude every dll/exe in tests/*, as well as all msdia*, covrun* and vcruntime*
analyzeTargetGlob: +:file|$(Build.ArtifactStagingDirectory)/**/*.dll;+:file|$(Build.ArtifactStagingDirectory)/**/*.exe;-:file:regex|tests.*\.(dll|exe)$;-:file:regex|(covrun.*)\.dll$;-:file:regex|(msdia.*)\.dll$;-:file:regex|(vcruntime.*)\.dll$
stages:
- stage: Build

View File

@@ -34,22 +34,22 @@
<!-- Including MessagePack to force version, since it's used by StreamJsonRpc but contains vulnerabilities. After StreamJsonRpc updates the version of MessagePack, we can upgrade StreamJsonRpc instead. -->
<PackageVersion Include="MessagePack" Version="3.1.3" />
<PackageVersion Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="9.0.0" />
<PackageVersion Include="Microsoft.Data.Sqlite" Version="9.0.8" />
<PackageVersion Include="Microsoft.Data.Sqlite" Version="9.0.7" />
<!-- Including Microsoft.Bcl.AsyncInterfaces to force version, since it's used by Microsoft.SemanticKernel. -->
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="9.0.8" />
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="9.0.7" />
<PackageVersion Include="Microsoft.Diagnostics.Tracing.TraceEvent" Version="3.1.16" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="9.0.8" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="9.0.8" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.8" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="9.0.8" />
<PackageVersion Include="Microsoft.Extensions.Hosting.WindowsServices" Version="9.0.8" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="9.0.7" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="9.0.7" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.7" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="9.0.7" />
<PackageVersion Include="Microsoft.Extensions.Hosting.WindowsServices" Version="9.0.7" />
<PackageVersion Include="Microsoft.SemanticKernel" Version="1.15.0" />
<PackageVersion Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.2" />
<PackageVersion Include="Microsoft.Web.WebView2" Version="1.0.2903.40" />
<!-- Package Microsoft.Win32.SystemEvents added as a hack for being able to exclude the runtime assets so they don't conflict with 8.0.1. This is a dependency of System.Drawing.Common but the 8.0.1 version wasn't published to nuget. -->
<PackageVersion Include="Microsoft.Win32.SystemEvents" Version="9.0.8" />
<PackageVersion Include="Microsoft.Win32.SystemEvents" Version="9.0.7" />
<PackageVersion Include="Microsoft.WindowsPackageManager.ComInterop" Version="1.10.340" />
<PackageVersion Include="Microsoft.Windows.Compatibility" Version="9.0.8" />
<PackageVersion Include="Microsoft.Windows.Compatibility" Version="9.0.7" />
<PackageVersion Include="Microsoft.Windows.CsWin32" Version="0.3.183" />
<!-- CsWinRT version needs to be set to have a WinRT.Runtime.dll at the same version contained inside the NET SDK we're currently building on CI. -->
<!--
@@ -78,28 +78,28 @@
<PackageVersion Include="StreamJsonRpc" Version="2.21.69" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
<!-- Package System.CodeDom added as a hack for being able to exclude the runtime assets so they don't conflict with 8.0.1. This is a dependency of System.Management but the 8.0.1 version wasn't published to nuget. -->
<PackageVersion Include="System.CodeDom" Version="9.0.8" />
<PackageVersion Include="System.CodeDom" Version="9.0.7" />
<PackageVersion Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
<PackageVersion Include="System.ComponentModel.Composition" Version="9.0.8" />
<PackageVersion Include="System.Configuration.ConfigurationManager" Version="9.0.8" />
<PackageVersion Include="System.Data.OleDb" Version="9.0.8" />
<PackageVersion Include="System.ComponentModel.Composition" Version="9.0.7" />
<PackageVersion Include="System.Configuration.ConfigurationManager" Version="9.0.7" />
<PackageVersion Include="System.Data.OleDb" Version="9.0.7" />
<!-- Package System.Data.SqlClient added to force it as a dependency of Microsoft.Windows.Compatibility to the latest version available at this time. -->
<PackageVersion Include="System.Data.SqlClient" Version="4.9.0" />
<!-- Package System.Diagnostics.EventLog added as a hack for being able to exclude the runtime assets so they don't conflict with 8.0.1. This is a dependency of System.Data.OleDb but the 8.0.1 version wasn't published to nuget. -->
<PackageVersion Include="System.Diagnostics.EventLog" Version="9.0.8" />
<PackageVersion Include="System.Diagnostics.EventLog" Version="9.0.7" />
<!-- Package System.Diagnostics.PerformanceCounter added as a hack for being able to exclude the runtime assets so they don't conflict with 8.0.11. -->
<PackageVersion Include="System.Diagnostics.PerformanceCounter" Version="9.0.8" />
<PackageVersion Include="System.Drawing.Common" Version="9.0.8" />
<PackageVersion Include="System.Diagnostics.PerformanceCounter" Version="9.0.7" />
<PackageVersion Include="System.Drawing.Common" Version="9.0.7" />
<PackageVersion Include="System.IO.Abstractions" Version="22.0.13" />
<PackageVersion Include="System.IO.Abstractions.TestingHelpers" Version="22.0.13" />
<PackageVersion Include="System.Management" Version="9.0.8" />
<PackageVersion Include="System.Management" Version="9.0.7" />
<PackageVersion Include="System.Net.Http" Version="4.3.4" />
<PackageVersion Include="System.Private.Uri" Version="4.3.2" />
<PackageVersion Include="System.Reactive" Version="6.0.1" />
<PackageVersion Include="System.Runtime.Caching" Version="9.0.8" />
<PackageVersion Include="System.ServiceProcess.ServiceController" Version="9.0.8" />
<PackageVersion Include="System.Text.Encoding.CodePages" Version="9.0.8" />
<PackageVersion Include="System.Text.Json" Version="9.0.8" />
<PackageVersion Include="System.Runtime.Caching" Version="9.0.7" />
<PackageVersion Include="System.ServiceProcess.ServiceController" Version="9.0.7" />
<PackageVersion Include="System.Text.Encoding.CodePages" Version="9.0.7" />
<PackageVersion Include="System.Text.Json" Version="9.0.7" />
<PackageVersion Include="System.Text.RegularExpressions" Version="4.3.1" />
<PackageVersion Include="UnicodeInformation" Version="2.6.0" />
<PackageVersion Include="UnitsNet" Version="5.56.0" />

View File

@@ -1519,23 +1519,23 @@ SOFTWARE.
- Mages 3.0.0
- Markdig.Signed 0.34.0
- MessagePack 3.1.3
- Microsoft.Bcl.AsyncInterfaces 9.0.8
- Microsoft.Bcl.AsyncInterfaces 9.0.7
- Microsoft.Bot.AdaptiveExpressions.Core 4.23.0
- Microsoft.CodeAnalysis.NetAnalyzers 9.0.0
- Microsoft.Data.Sqlite 9.0.8
- Microsoft.Data.Sqlite 9.0.7
- Microsoft.Diagnostics.Tracing.TraceEvent 3.1.16
- Microsoft.DotNet.ILCompiler (A)
- Microsoft.Extensions.DependencyInjection 9.0.8
- Microsoft.Extensions.Hosting 9.0.8
- Microsoft.Extensions.Hosting.WindowsServices 9.0.8
- Microsoft.Extensions.Logging 9.0.8
- Microsoft.Extensions.Logging.Abstractions 9.0.8
- Microsoft.Extensions.DependencyInjection 9.0.7
- Microsoft.Extensions.Hosting 9.0.7
- Microsoft.Extensions.Hosting.WindowsServices 9.0.7
- Microsoft.Extensions.Logging 9.0.7
- Microsoft.Extensions.Logging.Abstractions 9.0.7
- Microsoft.NET.ILLink.Tasks (A)
- Microsoft.SemanticKernel 1.15.0
- Microsoft.Toolkit.Uwp.Notifications 7.1.2
- Microsoft.Web.WebView2 1.0.2903.40
- Microsoft.Win32.SystemEvents 9.0.8
- Microsoft.Windows.Compatibility 9.0.8
- Microsoft.Win32.SystemEvents 9.0.7
- Microsoft.Windows.Compatibility 9.0.7
- Microsoft.Windows.CsWin32 0.3.183
- Microsoft.Windows.CsWinRT 2.2.0
- Microsoft.Windows.SDK.BuildTools 10.0.26100.4188
@@ -1555,25 +1555,25 @@ SOFTWARE.
- SkiaSharp.Views.WinUI 2.88.9
- StreamJsonRpc 2.21.69
- StyleCop.Analyzers 1.2.0-beta.556
- System.CodeDom 9.0.8
- System.CodeDom 9.0.7
- System.CommandLine 2.0.0-beta4.22272.1
- System.ComponentModel.Composition 9.0.8
- System.Configuration.ConfigurationManager 9.0.8
- System.Data.OleDb 9.0.8
- System.ComponentModel.Composition 9.0.7
- System.Configuration.ConfigurationManager 9.0.7
- System.Data.OleDb 9.0.7
- System.Data.SqlClient 4.9.0
- System.Diagnostics.EventLog 9.0.8
- System.Diagnostics.PerformanceCounter 9.0.8
- System.Drawing.Common 9.0.8
- System.Diagnostics.EventLog 9.0.7
- System.Diagnostics.PerformanceCounter 9.0.7
- System.Drawing.Common 9.0.7
- System.IO.Abstractions 22.0.13
- System.IO.Abstractions.TestingHelpers 22.0.13
- System.Management 9.0.8
- System.Management 9.0.7
- System.Net.Http 4.3.4
- System.Private.Uri 4.3.2
- System.Reactive 6.0.1
- System.Runtime.Caching 9.0.8
- System.ServiceProcess.ServiceController 9.0.8
- System.Text.Encoding.CodePages 9.0.8
- System.Text.Json 9.0.8
- System.Runtime.Caching 9.0.7
- System.ServiceProcess.ServiceController 9.0.7
- System.Text.Encoding.CodePages 9.0.7
- System.Text.Json 9.0.7
- System.Text.RegularExpressions 4.3.1
- UnicodeInformation 2.6.0
- UnitsNet 5.56.0

204
README.md
View File

@@ -14,7 +14,7 @@ Microsoft PowerToys is a set of utilities for power users to tune and streamline
| [Color Picker](https://aka.ms/PowerToysOverview_ColorPicker) | [Command Not Found](https://aka.ms/PowerToysOverview_CmdNotFound) | [Command Palette](https://aka.ms/PowerToysOverview_CmdPal) |
| [Crop And Lock](https://aka.ms/PowerToysOverview_CropAndLock) | [Environment Variables](https://aka.ms/PowerToysOverview_EnvironmentVariables) | [FancyZones](https://aka.ms/PowerToysOverview_FancyZones) |
| [File Explorer Add-ons](https://aka.ms/PowerToysOverview_FileExplorerAddOns) | [File Locksmith](https://aka.ms/PowerToysOverview_FileLocksmith) | [Hosts File Editor](https://aka.ms/PowerToysOverview_HostsFileEditor) |
| [Image Resizer](https://aka.ms/PowerToysOverview_ImageResizer) | [Keyboard Manager](https://aka.ms/PowerToysOverview_KeyboardManager) | [Mouse Utilities](https://aka.ms/PowerToysOverview_MouseUtilities) |
| [Image Resizer](https://aka.ms/PowerToysOverview_ImageResizer) | [Keyboard Manager](https://aka.ms/PowerToysOverview_KeyboardManager) | [Mouse utilities](https://aka.ms/PowerToysOverview_MouseUtilities) |
| [Mouse Without Borders](https://aka.ms/PowerToysOverview_MouseWithoutBorders) | [New+](https://aka.ms/PowerToysOverview_NewPlus) | [Paste as Plain Text](https://aka.ms/PowerToysOverview_PastePlain) |
| [Peek](https://aka.ms/PowerToysOverview_Peek) | [PowerRename](https://aka.ms/PowerToysOverview_PowerRename) | [PowerToys Run](https://aka.ms/PowerToysOverview_PowerToysRun) |
| [Quick Accent](https://aka.ms/PowerToysOverview_QuickAccent) | [Registry Preview](https://aka.ms/PowerToysOverview_RegistryPreview) | [Screen Ruler](https://aka.ms/PowerToysOverview_ScreenRuler) |
@@ -35,19 +35,19 @@ Microsoft PowerToys is a set of utilities for power users to tune and streamline
Go to the [Microsoft PowerToys GitHub releases page][github-release-link] and click on `Assets` at the bottom to show the files available in the release. Please use the appropriate PowerToys installer that matches your machine's architecture and install scope. For most, it is `x64` and per-user.
<!-- items that need to be updated release to release -->
[github-next-release-work]: https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+milestone%3A%22PowerToys+0.94%22
[github-current-release-work]: https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+milestone%3A%22PowerToys+0.93%22
[ptUserX64]: https://github.com/microsoft/PowerToys/releases/download/v0.93.0/PowerToysUserSetup-0.93.0-x64.exe
[ptUserArm64]: https://github.com/microsoft/PowerToys/releases/download/v0.93.0/PowerToysUserSetup-0.93.0-arm64.exe
[ptMachineX64]: https://github.com/microsoft/PowerToys/releases/download/v0.93.0/PowerToysSetup-0.93.0-x64.exe
[ptMachineArm64]: https://github.com/microsoft/PowerToys/releases/download/v0.93.0/PowerToysSetup-0.93.0-arm64.exe
[github-next-release-work]: https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+milestone%3A%22PowerToys+0.93%22
[github-current-release-work]: https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+milestone%3A%22PowerToys+0.92%22
[ptUserX64]: https://github.com/microsoft/PowerToys/releases/download/v0.92.1/PowerToysUserSetup-0.92.1-x64.exe
[ptUserArm64]: https://github.com/microsoft/PowerToys/releases/download/v0.92.1/PowerToysUserSetup-0.92.1-arm64.exe
[ptMachineX64]: https://github.com/microsoft/PowerToys/releases/download/v0.92.1/PowerToysSetup-0.92.1-x64.exe
[ptMachineArm64]: https://github.com/microsoft/PowerToys/releases/download/v0.92.1/PowerToysSetup-0.92.1-arm64.exe
| Description | Filename |
|----------------|----------|
| Per user - x64 | [PowerToysUserSetup-0.93.0-x64.exe][ptUserX64] |
| Per user - ARM64 | [PowerToysUserSetup-0.93.0-arm64.exe][ptUserArm64] |
| Machine wide - x64 | [PowerToysSetup-0.93.0-x64.exe][ptMachineX64] |
| Machine wide - ARM64 | [PowerToysSetup-0.93.0-arm64.exe][ptMachineArm64] |
| Per user - x64 | [PowerToysUserSetup-0.92.1-x64.exe][ptUserX64] |
| Per user - ARM64 | [PowerToysUserSetup-0.92.1-arm64.exe][ptUserArm64] |
| Machine wide - x64 | [PowerToysSetup-0.92.1-x64.exe][ptMachineX64] |
| Machine wide - ARM64 | [PowerToysSetup-0.92.1-arm64.exe][ptMachineArm64] |
This is our preferred method.
@@ -93,119 +93,139 @@ For guidance on developing for PowerToys, please read the [developer docs](./doc
Our [prioritized roadmap][roadmap] of features and utilities that the core team is focusing on.
### 0.93 - Aug 2025 Update
### 0.92 - June 2025 Update
In this release, we focused on new features, stability, optimization improvements, and automation.
**✨Highlights**
- PowerToys settings debuts a modern, card-based dashboard with clearer descriptions and faster navigation for a streamlined user experience.
- Command Palette had over 99 issues resolved, including bringing back Clipboard History, adding context menu shortcuts, pinning favorite apps, and supporting history in Run.
- Command Palette reduced its startup memory usage by ~15%, load time by ~40%, built-in extensions loading time by ~70%, and installation size by ~55%—all due to using the full Ahead-of-Time (AOT) compilation mode in Windows App SDK.
- Peek now supports instant previews and embedded thumbnails for Binary G-code (.bgcode) 3D printing files, making it easy to inspect models at a glance. Thanks [@pedrolamas](https://github.com/pedrolamas)!
- Mouse Utilities introduces a new spotlight highlighting mode that dims the screen and draws attention to your cursor, perfect for presentations.
- Test coverage improvements for multiple PowerToys modules including Command Palette, Advanced Paste, Peek, Text Extractor, and PowerRename — ensuring better reliability and quality, with over 600 new unit tests (mostly for Command Palette) and doubled UI automation coverage.
- PowerToys settings now has a toggle for the system tray icon, giving users control over its visibility based on personal preference. Thanks [@BLM16](https://github.com/BLM16)!
- Command Palette now has Ahead-of-Time ([AOT](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot)) compatibility for all first-party extensions, improved extensibility, and core UX fixes, resulting in better performance and stability across commands.
- Color Picker now has customizable mouse button actions, enabling more personalized workflows by assigning functions to left, right, and middle clicks. Thanks [@PesBandi](https://github.com/PesBandi)!
- Bug Report Tool now has a faster and clearer reporting process, with progress indicators, improved compression, auto-cleanup of old trace logs, and inclusion of MSIX installer logs for more efficient diagnostics.
- File Explorer add-ons now have improved rendering stability, resolving issues with PDF previews, blank thumbnails, and text file crashes during file browsing.
### Color Picker
- Added mouse button actions so you can choose what left, right, or middle click does. Thanks [@PesBandi](https://github.com/PesBandi)!
### Crop & Lock
- Aligned window styling with current Windows theme for a cleaner look. Thanks [@sadirano](https://github.com/sadirano)!
### Command Palette
- Ensured screen readers are notified when the selected item in the list changes for better accessibility.
- Fixed command title changes not being properly notified to screen readers. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Made icon controls excluded from keyboard navigation by default for better accessibility. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Improved UI design with better text sizing and alignment.
- Fixed keyboard shortcuts to work better in text boxes and context menus.
- Added right-click context menus with critical command styling and separators.
- Improved various context menu issues, improving item selection, handling of long titles, search bar text scaling, initial item behavior, and primary button functionality.
- Fixed context menu crashes with better type handling.
- Fixed "Reload" command to work with both uppercase and lowercase letters.
- Added mouse back button support for easier navigation. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Fixed Alt+Left Arrow navigation not working when search box contains text. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Updated back button tooltip to show keyboard shortcut information. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Fixed Command Palette window not appearing properly when activated. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Fixed Command Palette window staying hidden from taskbar after File Explorer restarts. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Fixed window focus not returning to previous app properly.
- Fixed Command Palette window to always appear on top when shown and move to bottom when hidden. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Fixed window hiding to properly work on UI thread. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Fixed crashes and improved stability with better synchronization of Command list updates. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Improved extension disposal with better error handling to prevent crashes. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Improved stability by fixing a UI threading issue when loading more results, preventing possible crashes and ensuring the loading state resets if loading fails. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Enhanced icon loading stability with better exception handling. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Added thread safety to recent commands to prevent crashes. Thanks [@MaoShengelia](https://github.com/MaoShengelia)!
- Fixed acrylic (frosted glass) system backdrop display issues by ensuring proper UI thread handling. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Enhanced performance by resolving a regression in page loading.
- Applied consistent hotkey handling across all Command Palette commands for a smoother user experience.
- Improved graceful closing of Command Palette. Thanks [@davidegiacometti](https://github.com/davidegiacometti)!
- Fixed consistency issue for extensions' alias with "Direct" setting and enabled localization for "Direct" and "Indirect" for better user understanding. Thanks [@davidegiacometti](https://github.com/davidegiacometti)!
- Improved visual clarity by styling critical context items correctly.
- Automatically focused the field when only one is present on the content page.
- Improved stability and efficiency when loading file icons in SDK ThumbnailHelper.cs by removing unnecessary operations. Thanks [@OldUser101](https://github.com/OldUser101)!
- Enhanced details view with commands implementation. (See [Extension sample](./src/modules/cmdpal/ext/SamplePagesExtension/Pages/SampleListPageWithDetails.cs))
### Command Palette extensions
- Added settings to each provider to control which fallback commands are enabled. Thanks [@jiripolasek](https://github.com/jiripolasek)! for fixing a regression in this feature.
- Added sample code showing how Command Palette extensions can track when their pages are loaded or unloaded. [Check it out here](./src/modules/cmdpal/ext/SamplePagesExtension/OnLoadPage.cs).
- Fixed *Calculator* to accept regular spaces in numbers that use space separators. Thanks [@PesBandi](https://github.com/PesBandi)!
- Added a new setting to *Calculator* to make "Copy" the primary button (replacing “Save”) and enable "Close on Enter", streamlining the workflow. Thanks [@PesBandi](https://github.com/PesBandi)!
- Improved *Apps* indexing error handling and removed obsolete code. Thanks [@davidegiacometti](https://github.com/davidegiacometti)!
- Prevented apps from showing in search when the *Apps* extension is disabled. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Added ability to pin/unpin *Apps* using Ctrl+P shortcut.
- Added keyboard shortcuts to the *Apps* context menu items for faster access.
- Added all file context menu options to the *Apps* items context menu, making all file actions available there for better functionality.
- Streamlined All *Apps* extension settings by removing redundant descriptions, making the UI clearer.
- Added command history to the *Run* page for easier access to previous commands.
- Fixed directory path handling in *Run* fallback for better file navigation.
- Fixed URL fallback item hiding properly in *Web Search* extension when search query becomes invalid. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Added proper empty state message for *Web Search* extension when no results found. Thanks [@jiripolasek](https://github.com/jiripolasek)!
- Added fallback command to *Windows Settings* extension for better search results.
- Re-enabled *Clipboard History* feature with proper window handling.
- Improved *Add Bookmark* extension to automatically detect file, folder, or URL types without manual input.
- Updated terminology from "Kill process" to "End task" in *Window Walker* for consistency with Windows.
- Fixed minor grammar error in SamplePagesExtension code comments. Thanks [@purofle](https://github.com/purofle)!
- Added "Copy Path" command to *App* search results for convenience. Thanks [@PesBandi](https://github.com/PesBandi)!
- Improved *Calculator* input experience by ignoring leading equal signs. Thanks [@PesBandi](https://github.com/PesBandi)!
- Corrected input handling in the *Calculator* extension to avoid showing errors for input with only leading whitespace.
- Improved *New Extension* wizard by validating names to prevent namespace errors.
- Ensured consistent context items display for the *Run* extension between fallback and top-level results.
- Fixed missing *Time & Date* commands in fallback results. Thanks [@htcfreek](https://github.com/htcfreek)!
- Fixed outdated results in the *Time & Date* extension. Thanks [@htcfreek](https://github.com/htcfreek)!
- Fixed an issue where *Web Search* always opened Microsoft Edge instead of the user's default browser on Windows 11 24H2 and later. Thanks [@RuggMatt](https://github.com/RuggMatt)!
- Improved ordering of *Windows Settings* extension search results from alphabetical to relevance-based for quicker access.
- Added "Restart Windows Explorer" command to the *Windows System Commands* provider for gracefully terminate and relaunch explorer.exe. Thanks [@jiripolasek](https://github.com/jiripolasek)!
### Mouse Utilities
### Command Palette Ahead-of-Time (AOT) readiness
- Added a new spotlight highlighting mode that creates a large transparent circle around your cursor with a backdrop effect, providing an alternative to the traditional circle highlight. Perfect for presentations where you want to focus attention on a specific area while dimming the rest of the screen.
- Weve made foundational changes to prepare the Command Palette for future Ahead-of-Time (AOT) publishing. This includes replacing the calculator library with ExprTk, improving COM object handling, refining Win32 interop, and correcting trimming behavior—all to ensure compatibility, performance, and reliability under AOT constraints. All first-party extensions are now AOT-compatible. These improvements lay the groundwork for publishing Command Palette as an AOT application in the next release.
- Special thanks to [@Sergio0694](https://github.com/Sergio0694) for guidance on making COM APIs AOT-compatible, [@jtschuster](https://github.com/jtschuster) for fixing COM object handling, [@ArashPartow](https://github.com/ArashPartow) from ExprTk for integration suggestions, and [@tian-lt](https://github.com/tian-lt) from the Windows Calculator team for valuable suggestion throughout the migration journey and review.
- As part of the upcoming release, were also enabling AOT compatibility for key dependencies, including markdown rendering, Adaptive Cards, internal logging and telemetry library, and the core Command Palette UX.
### FancyZones
- Fixed DPI-scaling issues to ensure FancyZones Editor displays crisply on high-resolution monitors. Thanks [@HO-COOH](https://github.com/HO-COOH)! This inspired us a broader review across other PowerToys modules, leading to DPI display optimizations in Awake, Color Picker, PowerAccent, and more.
### File Explorer add-ons
- Fixed potential failures in PDF previewer and thumbnail generation, improving reliability when browsing PDF files. Thanks [@mohiuddin-khan-shiam](https://github.com/mohiuddin-khan-shiam)!
- Prevented Monaco Preview Handler crash when opening UTF-8-BOM text files.
### Hosts File Editor
- Added an in-app *“Learn more”* link to warning dialogs for quick guidance. Thanks [@PesBandi](https://github.com/PesBandi)!
### Mouse Without Borders
- Fixed firewall rule so MWB now accepts connections from IPs outside your local subnet.
- Cleaned legacy logs to reduce disk usage and noise.
### Peek
- Added preview and thumbnail support for Binary G-code (.bgcode) files used in 3D printing. You can now see embedded thumbnails and preview these compressed 3D printing files directly in Peek and File Explorer. Thanks [@pedrolamas](https://github.com/pedrolamas)!
- Updated QOI reader so 3-channel QOI images preview correctly in Peek and File Explorer. Thanks [@mbartlett21](https://github.com/mbartlett21)!
- Added codec detection with a clear warning when a video cant be previewed, along with a link to the Microsoft Store to download the required codec.
### Quick Accent
### PowerRename
- Added Vietnamese language support to Quick Accent, mappings for Vietnamese vowels (a, e, i, o, u, y) and the letter d. Thanks [@octastylos-pseudodipteros](https://github.com/octastylos-pseudodipteros)!
- Added support for $YY-$MM-$DD in ModificationTime and AccessTime to enable flexible date-based renaming.
### PowerToys Run
- Suppressed error UI for known WPF-related crashes to reduce user confusion, while retaining diagnostic logging for analysis. This targets COMException 0xD0000701 and 0x80263001 caused by temporary DWM unavailability.
### Registry Preview
- Added "Extended data preview" via magnifier icon and context menu in the Data Grid, enabled easier inspection of complex registry types like REG_BINARY, REG_EXPAND_SZ, and REG_MULTI_SZ, etc. Thanks [@htcfreek](https://github.com/htcfreek)!
- Improved file-saving experience in Registry Preview by aligning with Notepad-like behavior, enhancing user prompts, error handling, and preventing crashes during unsaved or interrupted actions. Thanks [@htcfreek](https://github.com/htcfreek)!
### Settings
- Completely redesigned the Settings dashboard with a modern card-based layout featuring organized sections for quick actions and shortcuts overview, replacing the old module list.
- Rewrote setting descriptions to be more concise and follow Windows writing style guidelines, making them easier to understand.
- Improved formatting and readability of release notes in the "What's New" section with better typography and spacing.
- Added missing deep link support for various settings pages (Peek, Quick Accent, PowerToys Run, etc.) so you can jump directly to specific settings.
- Resolved an issue where the settings page header would drift away from its position when resizing the settings window.
- Resolved a settings crash related to incompatible property names in ZoomIt configuration.
- Added an option to hide or show the PowerToys system tray icon. Thanks [@BLM16](https://github.com/BLM16)!
- Improved settings to show progress while a bug report package is being generated.
### Workspaces
- Stored Workspaces icons in user AppData to ensure profile portability and prevent loss during temporary folder cleanup.
- Enabled capture and launch of PWAs on non-default Edge or Chrome profiles, ensuring consistent behavior during creation and execution.
### Documentation
- Added detailed step-by-step instructions for first-time developers building the Command Palette module, including prerequisites and Visual Studio setup guidance. Thanks [@chatasweetie](https://github.com/chatasweetie)!
- **Fixed Broken SDK Link**: Corrected a broken markdown link in the Command Palette SDK README that was pointing to an incorrect directory path. Thanks [@ChrisGuzak](https://github.com/ChrisGuzak)!
- Added documentation for the "Open With Cursor" plugin that enables opening Visual Studio and VS Code recent files using Cursor AI. Thanks [@VictorNoxx](https://github.com/VictorNoxx)!
- Added documentation for two new community plugins - Hotkeys plugin for creating custom keyboard shortcuts, and RandomGen plugin for generating random data like passwords, colors, and placeholder text. Thanks [@ruslanlap](https://github.com/ruslanlap)!
- Added SpeedTest and Dictionary Definition to the third-party plugins documentation for PowerToys Run. Thanks [@ruslanlap](https://github.com/ruslanlap)!
- Corrected sample links and typo in Command Palette documentation. Thanks [@daverayment](https://github.com/daverayment) and [@roycewilliams](https://github.com/roycewilliams)!
### Development
- Updated .NET libraries to 9.0.8 for performance and security. Thanks [@snickler](https://github.com/snickler)!
- Updated the spell check system to version 0.0.25 with better GitHub integration and SARIF reporting, plus fixed numerous spelling errors throughout the codebase including property names and documentation. Thanks [@jsoref](https://github.com/jsoref)!
- Cleaned up spelling check configuration to eliminate false positives and excessive noise that was appearing in every pull request, making the development process smoother.
- Replaced NuGet feed with Azure Artifacts for better package management.
- Implemented configurable UI test pipeline that can use pre-built official releases instead of building everything from scratch, reducing test execution time from 2+ hours.
- Replaced brittle pixel-by-pixel image comparison with perceptual hash (pHash) technology that's more robust to minor rendering differences - no more test failures due to anti-aliasing or compression artifacts.
- Reduced CI/fuzzing/UI test timeouts from 4 hours to 90 minutes, dramatically improving developer feedback loops and preventing long waits when builds get stuck.
- Standardized test project naming across the entire codebase and improved pipeline result identification by adding platform/install mode context to test run titles. Thanks [@khmyznikov](https://github.com/khmyznikov)!
- Added comprehensive UI test suites for multiple PowerToys modules including Command Palette, Advanced Paste, Peek, Text Extractor, and PowerRename - ensuring better reliability and quality.
- Enhanced UI test automation with command-line argument support, better session management, and improved element location methods using pattern matching to avoid failures from minor differences in exact matches.
- Updated .NET libraries to 9.0.6 for performance and security. Thanks [@snickler](https://github.com/snickler)!
- Updated WinAppSDK to 1.7.2 for better stability and Windows support.
- Introduced a one-step local build script that generates a signed installer, enhancing developer productivity.
- Generated portable PDBs so cross-platform debuggers can read symbol files, improving debugging experience in VSCode and other tools.
- Simplified WinGet configuration files by using the [Microsoft.Windows.Settings](https://www.powershellgallery.com/packages/Microsoft.Windows.Settings) module to enable Developer Mode. Thanks [@mdanish-kh](https://github.com/mdanish-kh)!
- Adjusted build scripts for the latest Az.Accounts module to keep CI green.
- Streamlined release pipeline by removing hard-coded telemetry version numbers, and unified Command Palette versioning with Windows Terminal's versioning method for consistent updates.
- Enhanced the build validation step to show detailed differences between NOTICE.md and actual package dependencies and versions.
- Improved spell-checking accuracy across the repo. Thanks [@rovercoder](https://github.com/rovercoder)!
- Upgraded CI to TouchdownBuild v5 for faster pipelines.
- Added context comments to *Resources.resw* to help translators.
- Expanded fuzz testing coverage to include FancyZones.
- Integrated all unit tests into the CI pipeline, increasing from ~3,000 to ~5,000 tests.
- Enabled daily UI test automation on the main branch, now covering over 370 UI tests for end-to-end validation.
- Newly added unit tests for WorkspacesLib to improve reliability and maintainability.
### What is being planned over the next few releases
### General
For [v0.94][github-next-release-work], we'll work on the items below:
- Updated bug report compression library (cziplib 0.3.3) for faster and more reliable package creation. Thanks [@Chubercik](https://github.com/Chubercik)!
- Included App Installer (“AppX Deployment Server”) event logs in bug reports for more thorough diagnostics.
### What is being planned for version 0.93
For [v0.93][github-next-release-work], we'll work on the items below:
- Continued Command Palette polish
- Working on Shortcut Guide v2 (Thanks [@noraa-junker](https://github.com/noraa-junker)!)
- Working on upgrading the installer to WiX 5
- Working on shortcut conflict detection
- Working on setting search
- Upgrading Keyboard Manager's editor UI
- New UI automation tests
- Working on installer upgrades
- Working on shortcut conflict detection
- Upgrading Keyboard Manager's editor UI
- Stability, bug fixes
## PowerToys Community

View File

@@ -52,7 +52,7 @@ Once you've discussed your proposed feature/fix/etc. with a team member, and an
## Rules
- **Follow the pattern of what you already see in the code.**
- [Coding style](style.md).
- [Coding style](development/style.md).
- Try to package new functionality/components into libraries that have nicely defined interfaces.
- Package new functionality into classes or refactor existing functionality into a class as you extend the code.
- When adding new classes/methods/changing existing code, add new unit tests or update the existing tests.

View File

@@ -11,7 +11,7 @@
<Fragment>
<!-- Resource directories should be added only if the installer is built on the build farm -->
<?ifdef env.IsPipeline?>
<?foreach ParentDirectory in INSTALLFOLDER;WinUI3AppsInstallFolder;HistoryPluginFolder;CalculatorPluginFolder;FolderPluginFolder;ProgramPluginFolder;ShellPluginFolder;IndexerPluginFolder;UnitConverterPluginFolder;ValueGeneratorPluginFolder;UriPluginFolder;WindowWalkerPluginFolder;OneNotePluginFolder;RegistryPluginFolder;VSCodeWorkspacesPluginFolder;ServicePluginFolder;SystemPluginFolder;TimeDatePluginFolder;WindowsSettingsPluginFolder;WindowsTerminalPluginFolder;WebSearchPluginFolder;PowerToysPluginFolder?>
<?foreach ParentDirectory in INSTALLFOLDER;HistoryPluginFolder;CalculatorPluginFolder;FolderPluginFolder;ProgramPluginFolder;ShellPluginFolder;IndexerPluginFolder;UnitConverterPluginFolder;ValueGeneratorPluginFolder;UriPluginFolder;WindowWalkerPluginFolder;OneNotePluginFolder;RegistryPluginFolder;VSCodeWorkspacesPluginFolder;ServicePluginFolder;SystemPluginFolder;TimeDatePluginFolder;WindowsSettingsPluginFolder;WindowsTerminalPluginFolder;WebSearchPluginFolder;PowerToysPluginFolder?>
<DirectoryRef Id="$(var.ParentDirectory)">
<!-- Resource file directories -->
<?foreach Language in $(var.LocLanguageList)?>
@@ -181,7 +181,7 @@
</Component>
<Component
Id="ImageResizer_$(var.IdSafeLanguage)_Component"
Directory="Resource$(var.IdSafeLanguage)WinUI3AppsInstallFolder"
Directory="Resource$(var.IdSafeLanguage)INSTALLFOLDER"
Guid="$(var.CompGUIDPrefix)02">
<RegistryKey Root="$(var.RegistryScope)" Key="Software\Classes\powertoys\components">
<RegistryValue Type="string" Name="ImageResizer_$(var.IdSafeLanguage)_Component" Value="" KeyPath="yes"/>
@@ -553,7 +553,6 @@
<RemoveFolder Id="RemoveFolderResourcesResource$(var.IdSafeLanguage)HistoryPluginFolder" Directory="Resource$(var.IdSafeLanguage)HistoryPluginFolder" On="uninstall"/>
<RemoveFolder Id="RemoveFolderResourcesResource$(var.IdSafeLanguage)PowerToysPluginFolder" Directory="Resource$(var.IdSafeLanguage)PowerToysPluginFolder" On="uninstall"/>
<RemoveFolder Id="RemoveFolderResourcesResource$(var.IdSafeLanguage)ValueGeneratorPluginFolder" Directory="Resource$(var.IdSafeLanguage)ValueGeneratorPluginFolder" On="uninstall"/>
<RemoveFolder Id="RemoveFolderResourcesResource$(var.IdSafeLanguage)WinUI3AppsInstallFolder" Directory="Resource$(var.IdSafeLanguage)WinUI3AppsInstallFolder" On="uninstall"/>
<?undef IdSafeLanguage?>
<?endforeach?>
</Component>

View File

@@ -298,34 +298,5 @@ namespace Hosts.Tests
var hidden = fileSystem.FileInfo.New(service.HostsFilePath).Attributes.HasFlag(FileAttributes.Hidden);
Assert.IsTrue(hidden);
}
[TestMethod]
public async Task NoLeadingSpaces_Disabled_RemovesIndent()
{
var content =
@"10.1.1.1 host host.local # comment
10.1.1.2 host2 host2.local # another comment
";
var expected =
@"10.1.1.1 host host.local # comment
10.1.1.2 host2 host2.local # another comment
# 10.1.1.30 host30 host30.local # new entry
";
var fs = new CustomMockFileSystem();
var settings = new Mock<IUserSettings>();
settings.Setup(s => s.NoLeadingSpaces).Returns(true);
var svc = new HostsService(fs, settings.Object, _elevationHelper.Object);
fs.AddFile(svc.HostsFilePath, new MockFileData(content));
var data = await svc.ReadAsync();
var entries = data.Entries.ToList();
entries.Add(new Entry(0, "10.1.1.30", "host30 host30.local", "new entry", false));
await svc.WriteAsync(data.AdditionalLines, entries);
var result = fs.GetFile(svc.HostsFilePath);
Assert.AreEqual(expected, result.TextContents);
}
}
}

View File

@@ -26,8 +26,6 @@ namespace Hosts.Settings
private bool _loopbackDuplicates;
public bool NoLeadingSpaces { get; private set; }
public bool LoopbackDuplicates
{
get => _loopbackDuplicates;
@@ -90,7 +88,6 @@ namespace Hosts.Settings
AdditionalLinesPosition = (HostsAdditionalLinesPosition)settings.Properties.AdditionalLinesPosition;
Encoding = (HostsEncoding)settings.Properties.Encoding;
LoopbackDuplicates = settings.Properties.LoopbackDuplicates;
NoLeadingSpaces = settings.Properties.NoLeadingSpaces;
}
retry = false;

View File

@@ -157,7 +157,7 @@ namespace HostsUILib.Helpers
{
lineBuilder.Append('#').Append(' ');
}
else if (anyDisabled && !_userSettings.NoLeadingSpaces)
else if (anyDisabled)
{
lineBuilder.Append(' ').Append(' ');
}

View File

@@ -19,7 +19,5 @@ namespace HostsUILib.Settings
event EventHandler LoopbackDuplicatesChanged;
public delegate void OpenSettingsFunction();
public bool NoLeadingSpaces { get; }
}
}

View File

@@ -5,7 +5,6 @@
#include "MouseHighlighter.h"
#include "trace.h"
#include <cmath>
#include <algorithm>
#ifdef COMPOSITION
namespace winrt
@@ -50,9 +49,6 @@ private:
void BringToFront();
HHOOK m_mouseHook = NULL;
static LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam) noexcept;
// Helpers for spotlight overlay
float GetDpiScale() const;
void UpdateSpotlightMask(float cx, float cy, float radius, bool show);
static constexpr auto m_className = L"MouseHighlighter";
static constexpr auto m_windowTitle = L"PowerToys Mouse Highlighter";
@@ -71,14 +67,7 @@ private:
winrt::CompositionSpriteShape m_leftPointer{ nullptr };
winrt::CompositionSpriteShape m_rightPointer{ nullptr };
winrt::CompositionSpriteShape m_alwaysPointer{ nullptr };
// Spotlight overlay (mask with soft feathered edge)
winrt::SpriteVisual m_overlay{ nullptr };
winrt::CompositionMaskBrush m_spotlightMask{ nullptr };
winrt::CompositionRadialGradientBrush m_spotlightMaskGradient{ nullptr };
winrt::CompositionColorBrush m_spotlightSource{ nullptr };
winrt::CompositionColorGradientStop m_maskStopCenter{ nullptr };
winrt::CompositionColorGradientStop m_maskStopInner{ nullptr };
winrt::CompositionColorGradientStop m_maskStopOuter{ nullptr };
winrt::CompositionSpriteShape m_spotlightPointer{ nullptr };
bool m_leftPointerEnabled = true;
bool m_rightPointerEnabled = true;
@@ -134,35 +123,6 @@ bool Highlighter::CreateHighlighter()
m_shape.RelativeSizeAdjustment({ 1.0f, 1.0f });
m_root.Children().InsertAtTop(m_shape);
// Create spotlight overlay (soft feather, DPI-aware)
m_overlay = m_compositor.CreateSpriteVisual();
m_overlay.RelativeSizeAdjustment({ 1.0f, 1.0f });
m_spotlightSource = m_compositor.CreateColorBrush(m_alwaysColor);
m_spotlightMaskGradient = m_compositor.CreateRadialGradientBrush();
m_spotlightMaskGradient.MappingMode(winrt::CompositionMappingMode::Absolute);
// Center region fully transparent
m_maskStopCenter = m_compositor.CreateColorGradientStop();
m_maskStopCenter.Offset(0.0f);
m_maskStopCenter.Color(winrt::Windows::UI::ColorHelper::FromArgb(0, 0, 0, 0));
// Inner edge of feather (still transparent)
m_maskStopInner = m_compositor.CreateColorGradientStop();
m_maskStopInner.Offset(0.995f); // will be updated per-radius
m_maskStopInner.Color(winrt::Windows::UI::ColorHelper::FromArgb(0, 0, 0, 0));
// Outer edge (opaque mask -> overlay visible)
m_maskStopOuter = m_compositor.CreateColorGradientStop();
m_maskStopOuter.Offset(1.0f);
m_maskStopOuter.Color(winrt::Windows::UI::ColorHelper::FromArgb(255, 255, 255, 255));
m_spotlightMaskGradient.ColorStops().Append(m_maskStopCenter);
m_spotlightMaskGradient.ColorStops().Append(m_maskStopInner);
m_spotlightMaskGradient.ColorStops().Append(m_maskStopOuter);
m_spotlightMask = m_compositor.CreateMaskBrush();
m_spotlightMask.Source(m_spotlightSource);
m_spotlightMask.Mask(m_spotlightMaskGradient);
m_overlay.Brush(m_spotlightMask);
m_overlay.IsVisible(false);
m_root.Children().InsertAtTop(m_overlay);
return true;
}
catch (...)
@@ -205,8 +165,12 @@ void Highlighter::AddDrawingPoint(MouseButton button)
// always
if (m_spotlightMode)
{
UpdateSpotlightMask(static_cast<float>(pt.x), static_cast<float>(pt.y), m_radius, true);
return;
float borderThickness = static_cast<float>(std::hypot(GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN)));
circleGeometry.Radius({ static_cast<float>(borderThickness / 2.0 + m_radius), static_cast<float>(borderThickness / 2.0 + m_radius) });
circleShape.FillBrush(nullptr);
circleShape.StrokeBrush(m_compositor.CreateColorBrush(m_alwaysColor));
circleShape.StrokeThickness(borderThickness);
m_spotlightPointer = circleShape;
}
else
{
@@ -245,14 +209,20 @@ void Highlighter::UpdateDrawingPointPosition(MouseButton button)
}
else
{
// always / spotlight idle
// always
if (m_spotlightMode)
{
UpdateSpotlightMask(static_cast<float>(pt.x), static_cast<float>(pt.y), m_radius, true);
if (m_spotlightPointer)
{
m_spotlightPointer.Offset({ static_cast<float>(pt.x), static_cast<float>(pt.y) });
}
}
else if (m_alwaysPointer)
else
{
m_alwaysPointer.Offset({ static_cast<float>(pt.x), static_cast<float>(pt.y) });
if (m_alwaysPointer)
{
m_alwaysPointer.Offset({ static_cast<float>(pt.x), static_cast<float>(pt.y) });
}
}
}
}
@@ -296,9 +266,9 @@ void Highlighter::ClearDrawingPoint()
{
if (m_spotlightMode)
{
if (m_overlay)
if (m_spotlightPointer)
{
m_overlay.IsVisible(false);
m_spotlightPointer.StrokeBrush().as<winrt::Windows::UI::Composition::CompositionColorBrush>().Color(winrt::Windows::UI::ColorHelper::FromArgb(0, 0, 0, 0));
}
}
else
@@ -451,10 +421,7 @@ void Highlighter::StopDrawing()
m_leftPointer = nullptr;
m_rightPointer = nullptr;
m_alwaysPointer = nullptr;
if (m_overlay)
{
m_overlay.IsVisible(false);
}
m_spotlightPointer = nullptr;
ShowWindow(m_hwnd, SW_HIDE);
UnhookWindowsHookEx(m_mouseHook);
ClearDrawing();
@@ -485,16 +452,6 @@ void Highlighter::ApplySettings(MouseHighlighterSettings settings)
m_rightPointerEnabled = false;
}
// Keep spotlight overlay color updated
if (m_spotlightSource)
{
m_spotlightSource.Color(m_alwaysColor);
}
if (!m_spotlightMode && m_overlay)
{
m_overlay.IsVisible(false);
}
if (instance->m_visible)
{
instance->StopDrawing();
@@ -606,43 +563,6 @@ void Highlighter::Terminate()
}
}
float Highlighter::GetDpiScale() const
{
return static_cast<float>(GetDpiForWindow(m_hwnd)) / 96.0f;
}
// Update spotlight radial mask center/radius with DPI-aware feather
void Highlighter::UpdateSpotlightMask(float cx, float cy, float radius, bool show)
{
if (!m_spotlightMaskGradient)
{
return;
}
m_spotlightMaskGradient.EllipseCenter({ cx, cy });
m_spotlightMaskGradient.EllipseRadius({ radius, radius });
const float dpiScale = GetDpiScale();
// Target a very fine edge: ~1 physical pixel, convert to DIPs: 1 / dpiScale
const float featherDip = 1.0f / (dpiScale > 0.0f ? dpiScale : 1.0f);
const float safeRadius = (std::max)(radius, 1.0f);
const float featherRel = (std::min)(0.25f, featherDip / safeRadius);
if (m_maskStopInner)
{
m_maskStopInner.Offset((std::max)(0.0f, 1.0f - featherRel));
}
if (m_spotlightSource)
{
m_spotlightSource.Color(m_alwaysColor);
}
if (m_overlay)
{
m_overlay.IsVisible(show);
}
}
#pragma region MouseHighlighter_API
void MouseHighlighterApplySettings(MouseHighlighterSettings settings)

View File

@@ -12,6 +12,6 @@
<PackageVersion Include="Microsoft.WindowsAppSDK" Version="1.7.250513003" />
<PackageVersion Include="Shmuelie.WinRTServer" Version="2.1.1" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
<PackageVersion Include="System.Text.Json" Version="9.0.8" />
<PackageVersion Include="System.Text.Json" Version="9.0.7" />
</ItemGroup>
</Project>

View File

@@ -1,66 +0,0 @@
// 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;
namespace Microsoft.CmdPal.Common.Helpers;
/// <summary>
/// Provides utility methods for building diagnostic and error messages.
/// </summary>
public static class DiagnosticsHelper
{
/// <summary>
/// Builds a comprehensive exception message with timestamp and detailed diagnostic information.
/// </summary>
/// <param name="exception">The exception that occurred.</param>
/// <param name="extensionHint">A hint about which extension caused the exception to help with debugging.</param>
/// <returns>A string containing the exception details, timestamp, and source information for diagnostic purposes.</returns>
public static string BuildExceptionMessage(Exception exception, string? extensionHint)
{
var locationHint = string.IsNullOrWhiteSpace(extensionHint) ? "application" : $"'{extensionHint}' extension";
// let's try to get a message from the exception or inferred it from the HRESULT
// to show at least something
var message = exception.Message;
if (string.IsNullOrWhiteSpace(message))
{
var temp = Marshal.GetExceptionForHR(exception.HResult)?.Message;
if (!string.IsNullOrWhiteSpace(temp))
{
message = temp + $" (inferred from HRESULT 0x{exception.HResult:X8})";
}
}
if (string.IsNullOrWhiteSpace(message))
{
message = "[No message available]";
}
// note: keep date time kind and format consistent with the log
return $"""
============================================================
😢 An unexpected error occurred in the {locationHint}.
Summary:
Message: {message}
Type: {exception.GetType().FullName}
Source: {exception.Source ?? "N/A"}
Time: {DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fffffff}
HRESULT: 0x{exception.HResult:X8} ({exception.HResult})
Stack Trace:
{exception.StackTrace ?? "[No stack trace available]"}
------------------ Full Exception Details ------------------
{exception}
If you need further assistance, please include this information in your support request.
Before sending, take a quick look to make sure it doesn't contain any personal or sensitive information.
============================================================
""";
}
}

View File

@@ -24,7 +24,7 @@ public partial class ExtensionHostInstance
/// <param name="message">The log message to send</param>
public void LogMessage(ILogMessage message)
{
if (Host is not null)
if (Host != null)
{
_ = Task.Run(async () =>
{
@@ -47,7 +47,7 @@ public partial class ExtensionHostInstance
public void ShowStatus(IStatusMessage message, StatusContext context)
{
if (Host is not null)
if (Host != null)
{
_ = Task.Run(async () =>
{
@@ -64,7 +64,7 @@ public partial class ExtensionHostInstance
public void HideStatus(IStatusMessage message)
{
if (Host is not null)
if (Host != null)
{
_ = Task.Run(async () =>
{

View File

@@ -89,7 +89,7 @@ public class SupersedingAsyncGate : IDisposable
}
catch (OperationCanceledException)
{
CompleteIfCurrent(currentTcs, currentCallId, tcs => tcs.TrySetCanceled(currentCts.Token));
CompleteIfCurrent(currentTcs, currentCallId, tcs => tcs.SetCanceled(currentCts.Token));
}
catch (Exception ex)
{

View File

@@ -36,7 +36,7 @@ public abstract partial class AppExtensionHost : IExtensionHost
public IAsyncAction HideStatus(IStatusMessage? message)
{
if (message is null)
if (message == null)
{
return Task.CompletedTask.AsAsyncAction();
}
@@ -55,7 +55,7 @@ public abstract partial class AppExtensionHost : IExtensionHost
public IAsyncAction LogMessage(ILogMessage? message)
{
if (message is null)
if (message == null)
{
return Task.CompletedTask.AsAsyncAction();
}
@@ -80,7 +80,7 @@ public abstract partial class AppExtensionHost : IExtensionHost
try
{
var vm = StatusMessages.Where(messageVM => messageVM.Model.Unsafe == message).FirstOrDefault();
if (vm is not null)
if (vm != null)
{
StatusMessages.Remove(vm);
}
@@ -113,7 +113,7 @@ public abstract partial class AppExtensionHost : IExtensionHost
{
// If this message is already in the list of messages, just bring it to the top
var oldVm = StatusMessages.Where(messageVM => messageVM.Model.Unsafe == message).FirstOrDefault();
if (oldVm is not null)
if (oldVm != null)
{
Task.Factory.StartNew(
() =>
@@ -142,7 +142,7 @@ public abstract partial class AppExtensionHost : IExtensionHost
public IAsyncAction ShowStatus(IStatusMessage? message, StatusContext context)
{
if (message is null)
if (message == null)
{
return Task.CompletedTask.AsAsyncAction();
}

View File

@@ -2,6 +2,7 @@
// 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.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.CmdPal.Core.ViewModels.Messages;
@@ -34,13 +35,13 @@ public partial class CommandBarViewModel : ObservableObject,
[NotifyPropertyChangedFor(nameof(HasPrimaryCommand))]
public partial CommandItemViewModel? PrimaryCommand { get; set; }
public bool HasPrimaryCommand => PrimaryCommand is not null && PrimaryCommand.ShouldBeVisible;
public bool HasPrimaryCommand => PrimaryCommand != null && PrimaryCommand.ShouldBeVisible;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasSecondaryCommand))]
public partial CommandItemViewModel? SecondaryCommand { get; set; }
public bool HasSecondaryCommand => SecondaryCommand is not null;
public bool HasSecondaryCommand => SecondaryCommand != null;
[ObservableProperty]
public partial bool ShouldShowContextMenu { get; set; } = false;
@@ -57,14 +58,14 @@ public partial class CommandBarViewModel : ObservableObject,
private void SetSelectedItem(ICommandBarContext? value)
{
if (value is not null)
if (value != null)
{
PrimaryCommand = value.PrimaryCommand;
value.PropertyChanged += SelectedItemPropertyChanged;
}
else
{
if (SelectedItem is not null)
if (SelectedItem != null)
{
SelectedItem.PropertyChanged -= SelectedItemPropertyChanged;
}
@@ -87,7 +88,7 @@ public partial class CommandBarViewModel : ObservableObject,
private void UpdateContextItems()
{
if (SelectedItem is null)
if (SelectedItem == null)
{
SecondaryCommand = null;
ShouldShowContextMenu = false;
@@ -126,13 +127,13 @@ public partial class CommandBarViewModel : ObservableObject,
public ContextKeybindingResult CheckKeybinding(bool ctrl, bool alt, bool shift, bool win, VirtualKey key)
{
var keybindings = SelectedItem?.Keybindings();
if (keybindings is not null)
if (keybindings != null)
{
// Does the pressed key match any of the keybindings?
var pressedKeyChord = KeyChordHelpers.FromModifiers(ctrl, alt, shift, win, key, 0);
if (keybindings.TryGetValue(pressedKeyChord, out var matchedItem))
{
return matchedItem is not null ? PerformCommand(matchedItem) : ContextKeybindingResult.Unhandled;
return matchedItem != null ? PerformCommand(matchedItem) : ContextKeybindingResult.Unhandled;
}
}
@@ -141,7 +142,7 @@ public partial class CommandBarViewModel : ObservableObject,
private ContextKeybindingResult PerformCommand(CommandItemViewModel? command)
{
if (command is null)
if (command == null)
{
return ContextKeybindingResult.Unhandled;
}

View File

@@ -2,14 +2,11 @@
// 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.CodeAnalysis;
using Microsoft.CmdPal.Core.ViewModels.Models;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
namespace Microsoft.CmdPal.Core.ViewModels;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
public partial class CommandContextItemViewModel(ICommandContextItem contextItem, WeakReference<IPageContext> context) : CommandItemViewModel(new(contextItem), context), IContextItemViewModel
{
private readonly KeyChord nullKeyChord = new(0, 0, 0);
@@ -20,7 +17,7 @@ public partial class CommandContextItemViewModel(ICommandContextItem contextItem
public KeyChord? RequestedShortcut { get; private set; }
public bool HasRequestedShortcut => RequestedShortcut is not null && (RequestedShortcut.Value != nullKeyChord);
public bool HasRequestedShortcut => RequestedShortcut != null && (RequestedShortcut.Value != nullKeyChord);
public override void InitializeProperties()
{
@@ -32,7 +29,7 @@ public partial class CommandContextItemViewModel(ICommandContextItem contextItem
base.InitializeProperties();
var contextItem = Model.Unsafe;
if (contextItem is null)
if (contextItem == null)
{
return; // throw?
}

View File

@@ -2,7 +2,6 @@
// 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.CodeAnalysis;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CmdPal.Core.ViewModels.Models;
using Microsoft.CommandPalette.Extensions;
@@ -10,7 +9,6 @@ using Microsoft.CommandPalette.Extensions.Toolkit;
namespace Microsoft.CmdPal.Core.ViewModels;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBarContext
{
public ExtensionObject<ICommandItem> Model => _commandItemModel;
@@ -68,7 +66,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
{
get
{
List<IContextItemViewModel> l = _defaultCommandContextItem is null ?
List<IContextItemViewModel> l = _defaultCommandContextItem == null ?
new() :
[_defaultCommandContextItem];
@@ -100,7 +98,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
}
var model = _commandItemModel.Unsafe;
if (model is null)
if (model == null)
{
return;
}
@@ -128,7 +126,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
}
var model = _commandItemModel.Unsafe;
if (model is null)
if (model == null)
{
return;
}
@@ -136,7 +134,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
Command.InitializeProperties();
var listIcon = model.Icon;
if (listIcon is not null)
if (listIcon != null)
{
_listItemIcon = new(listIcon);
_listItemIcon.InitializeProperties();
@@ -172,13 +170,13 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
}
var model = _commandItemModel.Unsafe;
if (model is null)
if (model == null)
{
return;
}
var more = model.MoreCommands;
if (more is not null)
if (more != null)
{
MoreCommands = more
.Select(item =>
@@ -300,7 +298,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
protected virtual void FetchProperty(string propertyName)
{
var model = this._commandItemModel.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -308,7 +306,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
switch (propertyName)
{
case nameof(Command):
if (Command is not null)
if (Command != null)
{
Command.PropertyChanged -= Command_PropertyChanged;
}
@@ -339,7 +337,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
case nameof(model.MoreCommands):
var more = model.MoreCommands;
if (more is not null)
if (more != null)
{
var newContextMenu = more
.Select(item =>
@@ -394,7 +392,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
// Extensions based on Command Palette SDK < 0.3 CommandItem class won't notify when Title changes because Command
// or Command.Name change. This is a workaround to ensure that the Title is always up-to-date for extensions with old SDK.
var model = _commandItemModel.Unsafe;
if (model is not null)
if (model != null)
{
_itemTitle = model.Title;
}
@@ -430,7 +428,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
Command.SafeCleanup();
var model = _commandItemModel.Unsafe;
if (model is not null)
if (model != null)
{
model.PropChanged -= Model_PropChanged;
}

View File

@@ -44,7 +44,7 @@ public partial class CommandViewModel : ExtensionObjectViewModel
}
var model = Model.Unsafe;
if (model is null)
if (model == null)
{
return;
}
@@ -67,13 +67,13 @@ public partial class CommandViewModel : ExtensionObjectViewModel
}
var model = Model.Unsafe;
if (model is null)
if (model == null)
{
return;
}
var ico = model.Icon;
if (ico is not null)
if (ico != null)
{
Icon = new(ico);
Icon.InitializeProperties();
@@ -98,7 +98,7 @@ public partial class CommandViewModel : ExtensionObjectViewModel
protected void FetchProperty(string propertyName)
{
var model = Model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -125,7 +125,7 @@ public partial class CommandViewModel : ExtensionObjectViewModel
Icon = new(null); // necessary?
var model = Model.Unsafe;
if (model is not null)
if (model != null)
{
model.PropChanged -= Model_PropChanged;
}

View File

@@ -25,7 +25,7 @@ public partial class ConfirmResultViewModel(IConfirmationArgs _args, WeakReferen
public override void InitializeProperties()
{
var model = Model.Unsafe;
if (model is null)
if (model == null)
{
return;
}

View File

@@ -28,7 +28,7 @@ public abstract partial class ContentPageViewModel : PageViewModel, ICommandBarC
public DetailsViewModel? Details { get; private set; }
[MemberNotNullWhen(true, nameof(Details))]
public bool HasDetails => Details is not null;
public bool HasDetails => Details != null;
/////// ICommandBarContext ///////
public IEnumerable<IContextItemViewModel> MoreCommands => Commands.Skip(1);
@@ -67,7 +67,7 @@ public abstract partial class ContentPageViewModel : PageViewModel, ICommandBarC
foreach (var item in newItems)
{
var viewModel = ViewModelFromContent(item, PageContext);
if (viewModel is not null)
if (viewModel != null)
{
viewModel.InitializeProperties();
newContent.Add(viewModel);
@@ -104,7 +104,7 @@ public abstract partial class ContentPageViewModel : PageViewModel, ICommandBarC
base.InitializeProperties();
var model = _model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -133,7 +133,7 @@ public abstract partial class ContentPageViewModel : PageViewModel, ICommandBarC
});
var extensionDetails = model.Details;
if (extensionDetails is not null)
if (extensionDetails != null)
{
Details = new(extensionDetails, PageContext);
Details.InitializeProperties();
@@ -156,7 +156,7 @@ public abstract partial class ContentPageViewModel : PageViewModel, ICommandBarC
base.FetchProperty(propertyName);
var model = this._model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -166,7 +166,7 @@ public abstract partial class ContentPageViewModel : PageViewModel, ICommandBarC
case nameof(Commands):
var more = model.Commands;
if (more is not null)
if (more != null)
{
var newContextMenu = more
.ToList()
@@ -216,7 +216,7 @@ public abstract partial class ContentPageViewModel : PageViewModel, ICommandBarC
break;
case nameof(Details):
var extensionDetails = model.Details;
Details = extensionDetails is not null ? new(extensionDetails, PageContext) : null;
Details = extensionDetails != null ? new(extensionDetails, PageContext) : null;
UpdateDetails();
break;
}
@@ -248,7 +248,7 @@ public abstract partial class ContentPageViewModel : PageViewModel, ICommandBarC
[RelayCommand]
private void InvokePrimaryCommand(ContentPageViewModel page)
{
if (PrimaryCommand is not null)
if (PrimaryCommand != null)
{
WeakReferenceMessenger.Default.Send<PerformCommandMessage>(new(PrimaryCommand.Command.Model, PrimaryCommand.Model));
}
@@ -258,7 +258,7 @@ public abstract partial class ContentPageViewModel : PageViewModel, ICommandBarC
[RelayCommand]
private void InvokeSecondaryCommand(ContentPageViewModel page)
{
if (SecondaryCommand is not null)
if (SecondaryCommand != null)
{
WeakReferenceMessenger.Default.Send<PerformCommandMessage>(new(SecondaryCommand.Command.Model, SecondaryCommand.Model));
}
@@ -285,7 +285,7 @@ public abstract partial class ContentPageViewModel : PageViewModel, ICommandBarC
Content.Clear();
var model = _model.Unsafe;
if (model is not null)
if (model != null)
{
model.ItemsChanged -= Model_ItemsChanged;
}

View File

@@ -8,6 +8,7 @@ using CommunityToolkit.Mvvm.Messaging;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
using Microsoft.Diagnostics.Utilities;
using Windows.System;
namespace Microsoft.CmdPal.Core.ViewModels;
@@ -50,7 +51,7 @@ public partial class ContextMenuViewModel : ObservableObject,
public void UpdateContextItems()
{
if (SelectedItem is not null)
if (SelectedItem != null)
{
if (SelectedItem.MoreCommands.Count() > 1)
{
@@ -67,14 +68,14 @@ public partial class ContextMenuViewModel : ObservableObject,
return;
}
if (SelectedItem is null)
if (SelectedItem == null)
{
return;
}
_lastSearchText = searchText;
if (CurrentContextMenu is null)
if (CurrentContextMenu == null)
{
ListHelpers.InPlaceUpdateList(FilteredItems, []);
return;
@@ -123,7 +124,7 @@ public partial class ContextMenuViewModel : ObservableObject,
/// that have a shortcut key set.</returns>
public Dictionary<KeyChord, CommandContextItemViewModel> Keybindings()
{
if (CurrentContextMenu is null)
if (CurrentContextMenu == null)
{
return [];
}
@@ -139,7 +140,7 @@ public partial class ContextMenuViewModel : ObservableObject,
public ContextKeybindingResult? CheckKeybinding(bool ctrl, bool alt, bool shift, bool win, VirtualKey key)
{
var keybindings = Keybindings();
if (keybindings is not null)
if (keybindings != null)
{
// Does the pressed key match any of the keybindings?
var pressedKeyChord = KeyChordHelpers.FromModifiers(ctrl, alt, shift, win, key, 0);
@@ -189,7 +190,7 @@ public partial class ContextMenuViewModel : ObservableObject,
OnPropertyChanging(nameof(CurrentContextMenu));
OnPropertyChanged(nameof(CurrentContextMenu));
if (CurrentContextMenu is not null)
if (CurrentContextMenu != null)
{
ListHelpers.InPlaceUpdateList(FilteredItems, [.. CurrentContextMenu!]);
}
@@ -197,7 +198,7 @@ public partial class ContextMenuViewModel : ObservableObject,
public ContextKeybindingResult InvokeCommand(CommandItemViewModel? command)
{
if (command is null)
if (command == null)
{
return ContextKeybindingResult.Unhandled;
}

View File

@@ -22,7 +22,7 @@ public partial class DetailsCommandsViewModel(
{
base.InitializeProperties();
var model = _dataModel.Unsafe;
if (model is null)
if (model == null)
{
return;
}

View File

@@ -16,7 +16,7 @@ public abstract partial class DetailsElementViewModel(IDetailsElement _detailsEl
public override void InitializeProperties()
{
var model = _model.Unsafe;
if (model is null)
if (model == null)
{
return;
}

View File

@@ -18,7 +18,7 @@ public partial class DetailsLinkViewModel(
public Uri? Link { get; private set; }
public bool IsLink => Link is not null;
public bool IsLink => Link != null;
public bool IsText => !IsLink;
@@ -26,14 +26,14 @@ public partial class DetailsLinkViewModel(
{
base.InitializeProperties();
var model = _dataModel.Unsafe;
if (model is null)
if (model == null)
{
return;
}
Text = model.Text ?? string.Empty;
Link = model.Link;
if (string.IsNullOrEmpty(Text) && Link is not null)
if (string.IsNullOrEmpty(Text) && Link != null)
{
Text = Link.ToString();
}

View File

@@ -22,7 +22,7 @@ public partial class DetailsTagsViewModel(
{
base.InitializeProperties();
var model = _dataModel.Unsafe;
if (model is null)
if (model == null)
{
return;
}

View File

@@ -26,7 +26,7 @@ public partial class DetailsViewModel(IDetails _details, WeakReference<IPageCont
public override void InitializeProperties()
{
var model = _detailsModel.Unsafe;
if (model is null)
if (model == null)
{
return;
}
@@ -41,7 +41,7 @@ public partial class DetailsViewModel(IDetails _details, WeakReference<IPageCont
UpdateProperty(nameof(HeroImage));
var meta = model.Metadata;
if (meta is not null)
if (meta != null)
{
foreach (var element in meta)
{
@@ -53,7 +53,7 @@ public partial class DetailsViewModel(IDetails _details, WeakReference<IPageCont
IDetailsTags => new DetailsTagsViewModel(element, this.PageContext),
_ => null,
};
if (vm is not null)
if (vm != null)
{
vm.InitializeProperties();
Metadata.Add(vm);

View File

@@ -4,14 +4,12 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CmdPal.Core.ViewModels;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
public interface IContextItemViewModel
{
}

View File

@@ -16,7 +16,7 @@ public partial class IconDataViewModel : ObservableObject, IIconData
// If the extension previously gave us a Data, then died, the data will
// throw if we actually try to read it, but the pointer itself won't be
// null, so this is relatively safe.
public bool HasIcon => !string.IsNullOrEmpty(Icon) || Data.Unsafe is not null;
public bool HasIcon => !string.IsNullOrEmpty(Icon) || Data.Unsafe != null;
// Locally cached properties from IIconData.
public string Icon { get; private set; } = string.Empty;
@@ -36,7 +36,7 @@ public partial class IconDataViewModel : ObservableObject, IIconData
public void InitializeProperties()
{
var model = _model.Unsafe;
if (model is null)
if (model == null)
{
return;
}

View File

@@ -26,7 +26,7 @@ public partial class IconInfoViewModel : ObservableObject, IIconInfo
public bool HasIcon(bool light) => IconForTheme(light).HasIcon;
public bool IsSet => _model.Unsafe is not null;
public bool IsSet => _model.Unsafe != null;
IIconData? IIconInfo.Dark => Dark;
@@ -43,7 +43,7 @@ public partial class IconInfoViewModel : ObservableObject, IIconInfo
public void InitializeProperties()
{
var model = _model.Unsafe;
if (model is null)
if (model == null)
{
return;
}

View File

@@ -27,7 +27,7 @@ public partial class ListItemViewModel(IListItem model, WeakReference<IPageConte
public DetailsViewModel? Details { get; private set; }
[MemberNotNullWhen(true, nameof(Details))]
public bool HasDetails => Details is not null;
public bool HasDetails => Details != null;
public override void InitializeProperties()
{
@@ -40,7 +40,7 @@ public partial class ListItemViewModel(IListItem model, WeakReference<IPageConte
base.InitializeProperties();
var li = Model.Unsafe;
if (li is null)
if (li == null)
{
return; // throw?
}
@@ -50,7 +50,7 @@ public partial class ListItemViewModel(IListItem model, WeakReference<IPageConte
TextToSuggest = li.TextToSuggest;
Section = li.Section ?? string.Empty;
var extensionDetails = li.Details;
if (extensionDetails is not null)
if (extensionDetails != null)
{
Details = new(extensionDetails, PageContext);
Details.InitializeProperties();
@@ -67,7 +67,7 @@ public partial class ListItemViewModel(IListItem model, WeakReference<IPageConte
base.FetchProperty(propertyName);
var model = this.Model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -85,7 +85,7 @@ public partial class ListItemViewModel(IListItem model, WeakReference<IPageConte
break;
case nameof(Details):
var extensionDetails = model.Details;
Details = extensionDetails is not null ? new(extensionDetails, PageContext) : null;
Details = extensionDetails != null ? new(extensionDetails, PageContext) : null;
Details?.InitializeProperties();
UpdateProperty(nameof(Details));
UpdateProperty(nameof(HasDetails));
@@ -136,7 +136,7 @@ public partial class ListItemViewModel(IListItem model, WeakReference<IPageConte
Details?.SafeCleanup();
var model = Model.Unsafe;
if (model is not null)
if (model != null)
{
// We don't need to revoke the PropChanged event handler here,
// because we are just overriding CommandItem's FetchProperty and

View File

@@ -63,7 +63,6 @@ public partial class ListViewModel : PageViewModel, IDisposable
private Task? _initializeItemsTask;
private CancellationTokenSource? _cancellationTokenSource;
private CancellationTokenSource? _fetchItemsCancellationTokenSource;
private ListItemViewModel? _lastSelectedItem;
@@ -130,27 +129,14 @@ public partial class ListViewModel : PageViewModel, IDisposable
//// Run on background thread, from InitializeAsync or Model_ItemsChanged
private void FetchItems()
{
// Cancel any previous FetchItems operation
_fetchItemsCancellationTokenSource?.Cancel();
_fetchItemsCancellationTokenSource?.Dispose();
_fetchItemsCancellationTokenSource = new CancellationTokenSource();
var cancellationToken = _fetchItemsCancellationTokenSource.Token;
// TEMPORARY: just plop all the items into a single group
// see 9806fe5d8 for the last commit that had this with sections
_isFetching = true;
try
{
// Check for cancellation before starting expensive operations
cancellationToken.ThrowIfCancellationRequested();
var newItems = _model.Unsafe!.GetItems();
// Check for cancellation after getting items from extension
cancellationToken.ThrowIfCancellationRequested();
// Collect all the items into new viewmodels
Collection<ListItemViewModel> newViewModels = [];
@@ -159,9 +145,6 @@ public partial class ListViewModel : PageViewModel, IDisposable
// building new viewmodels for the ones we haven't already built.
foreach (var item in newItems)
{
// Check for cancellation during item processing
cancellationToken.ThrowIfCancellationRequested();
ListItemViewModel viewModel = new(item, new(this));
// If an item fails to load, silently ignore it.
@@ -171,22 +154,15 @@ public partial class ListViewModel : PageViewModel, IDisposable
}
}
// Check for cancellation before initializing first twenty items
cancellationToken.ThrowIfCancellationRequested();
var firstTwenty = newViewModels.Take(20);
foreach (var item in firstTwenty)
{
cancellationToken.ThrowIfCancellationRequested();
item?.SafeInitializeProperties();
}
// Cancel any ongoing search
_cancellationTokenSource?.Cancel();
// Check for cancellation before updating the list
cancellationToken.ThrowIfCancellationRequested();
lock (_listLock)
{
// Now that we have new ViewModels for everything from the
@@ -197,11 +173,6 @@ public partial class ListViewModel : PageViewModel, IDisposable
// TODO: Iterate over everything in Items, and prune items from the
// cache if we don't need them anymore
}
catch (OperationCanceledException)
{
// Cancellation is expected, don't treat as error
return;
}
catch (Exception ex)
{
// TODO: Move this within the for loop, so we can catch issues with individual items
@@ -327,11 +298,11 @@ public partial class ListViewModel : PageViewModel, IDisposable
[RelayCommand]
private void InvokeItem(ListItemViewModel? item)
{
if (item is not null)
if (item != null)
{
WeakReferenceMessenger.Default.Send<PerformCommandMessage>(new(item.Command.Model, item.Model));
}
else if (ShowEmptyContent && EmptyContent.PrimaryCommand?.Model.Unsafe is not null)
else if (ShowEmptyContent && EmptyContent.PrimaryCommand?.Model.Unsafe != null)
{
WeakReferenceMessenger.Default.Send<PerformCommandMessage>(new(
EmptyContent.PrimaryCommand.Command.Model,
@@ -343,14 +314,14 @@ public partial class ListViewModel : PageViewModel, IDisposable
[RelayCommand]
private void InvokeSecondaryCommand(ListItemViewModel? item)
{
if (item is not null)
if (item != null)
{
if (item.SecondaryCommand is not null)
if (item.SecondaryCommand != null)
{
WeakReferenceMessenger.Default.Send<PerformCommandMessage>(new(item.SecondaryCommand.Command.Model, item.Model));
}
}
else if (ShowEmptyContent && EmptyContent.SecondaryCommand?.Model.Unsafe is not null)
else if (ShowEmptyContent && EmptyContent.SecondaryCommand?.Model.Unsafe != null)
{
WeakReferenceMessenger.Default.Send<PerformCommandMessage>(new(
EmptyContent.SecondaryCommand.Command.Model,
@@ -361,12 +332,12 @@ public partial class ListViewModel : PageViewModel, IDisposable
[RelayCommand]
private void UpdateSelectedItem(ListItemViewModel? item)
{
if (_lastSelectedItem is not null)
if (_lastSelectedItem != null)
{
_lastSelectedItem.PropertyChanged -= SelectedItemPropertyChanged;
}
if (item is not null)
if (item != null)
{
SetSelectedItem(item);
}
@@ -412,7 +383,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
private void SelectedItemPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
var item = _lastSelectedItem;
if (item is null)
if (item == null)
{
return;
}
@@ -467,7 +438,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
base.InitializeProperties();
var model = _model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -494,7 +465,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
public void LoadMoreIfNeeded()
{
var model = this._model.Unsafe;
if (model is null)
if (model == null)
{
return;
}
@@ -538,7 +509,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
base.FetchProperty(propertyName);
var model = this._model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -569,7 +540,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
private void UpdateEmptyContent()
{
UpdateProperty(nameof(ShowEmptyContent));
if (!ShowEmptyContent || EmptyContent.Model.Unsafe is null)
if (!ShowEmptyContent || EmptyContent.Model.Unsafe == null)
{
return;
}
@@ -589,10 +560,6 @@ public partial class ListViewModel : PageViewModel, IDisposable
_cancellationTokenSource?.Cancel();
_cancellationTokenSource?.Dispose();
_cancellationTokenSource = null;
_fetchItemsCancellationTokenSource?.Cancel();
_fetchItemsCancellationTokenSource?.Dispose();
_fetchItemsCancellationTokenSource = null;
}
protected override void UnsafeCleanup()
@@ -603,7 +570,6 @@ public partial class ListViewModel : PageViewModel, IDisposable
EmptyContent = new(new(null), PageContext); // necessary?
_cancellationTokenSource?.Cancel();
_fetchItemsCancellationTokenSource?.Cancel();
lock (_listLock)
{
@@ -622,7 +588,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
}
var model = _model.Unsafe;
if (model is not null)
if (model != null)
{
model.ItemsChanged -= Model_ItemsChanged;
}

View File

@@ -22,7 +22,7 @@ public partial class LogMessageViewModel : ExtensionObjectViewModel
public override void InitializeProperties()
{
var model = _model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}

View File

@@ -2,7 +2,7 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CmdPal.UI.Messages;
namespace Microsoft.CmdPal.Core.ViewModels.Messages;
public record HotkeySummonMessage(string CommandId, IntPtr Hwnd)
{

View File

@@ -2,7 +2,7 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CmdPal.UI.Messages;
namespace Microsoft.CmdPal.Core.ViewModels.Messages;
public record OpenSettingsMessage()
{

View File

@@ -2,7 +2,7 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CmdPal.UI.ViewModels.Messages;
namespace Microsoft.CmdPal.Core.ViewModels.Messages;
/// <summary>
/// Message which closes the application. Used by <see cref="QuitCommand"/> via <see cref="BuiltInsCommandProvider"/>.

View File

@@ -2,7 +2,7 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CmdPal.UI.ViewModels.Messages;
namespace Microsoft.CmdPal.Core.ViewModels.Messages;
public record ReloadCommandsMessage()
{

View File

@@ -2,7 +2,7 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CmdPal.UI.Messages;
namespace Microsoft.CmdPal.Core.ViewModels.Messages;
public record SettingsWindowClosedMessage
{

View File

@@ -2,7 +2,7 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CmdPal.UI.ViewModels.Messages;
namespace Microsoft.CmdPal.Core.ViewModels.Messages;
public record UpdateFallbackItemsMessage()
{

View File

@@ -5,7 +5,6 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.CmdPal.Common.Helpers;
using Microsoft.CmdPal.Core.ViewModels.Models;
using Microsoft.CommandPalette.Extensions;
@@ -46,7 +45,7 @@ public partial class PageViewModel : ExtensionObjectViewModel, IPageContext
[ObservableProperty]
public partial AppExtensionHost ExtensionHost { get; private set; }
public bool HasStatusMessage => MostRecentStatusMessage is not null;
public bool HasStatusMessage => MostRecentStatusMessage != null;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasStatusMessage))]
@@ -133,7 +132,7 @@ public partial class PageViewModel : ExtensionObjectViewModel, IPageContext
public override void InitializeProperties()
{
var page = _pageModel.Unsafe;
if (page is null)
if (page == null)
{
return; // throw?
}
@@ -178,7 +177,7 @@ public partial class PageViewModel : ExtensionObjectViewModel, IPageContext
protected virtual void FetchProperty(string propertyName)
{
var model = this._pageModel.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -224,10 +223,9 @@ public partial class PageViewModel : ExtensionObjectViewModel, IPageContext
extensionHint ??= ExtensionHost.GetExtensionDisplayName() ?? Title;
Task.Factory.StartNew(
() =>
{
var message = DiagnosticsHelper.BuildExceptionMessage(ex, extensionHint);
ErrorMessage += message;
},
{
ErrorMessage += $"A bug occurred in {$"the \"{extensionHint}\"" ?? "an unknown's"} extension's code:\n{ex.Message}\n{ex.Source}\n{ex.StackTrace}\n\n";
},
CancellationToken.None,
TaskCreationOptions.None,
Scheduler);
@@ -242,7 +240,7 @@ public partial class PageViewModel : ExtensionObjectViewModel, IPageContext
ExtensionHost.StatusMessages.CollectionChanged -= StatusMessages_CollectionChanged;
var model = _pageModel.Unsafe;
if (model is not null)
if (model != null)
{
model.PropChanged -= Model_PropChanged;
}

View File

@@ -24,7 +24,7 @@ public partial class ProgressViewModel : ExtensionObjectViewModel
public override void InitializeProperties()
{
var model = Model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -50,7 +50,7 @@ public partial class ProgressViewModel : ExtensionObjectViewModel
protected virtual void FetchProperty(string propertyName)
{
var model = this.Model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}

View File

@@ -2,13 +2,11 @@
// 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.CodeAnalysis;
using Microsoft.CmdPal.Core.ViewModels;
using Microsoft.CommandPalette.Extensions;
namespace Microsoft.CmdPal.Core.ViewModels;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
public partial class SeparatorContextItemViewModel() : IContextItemViewModel, ISeparatorContextItem
{
}

View File

@@ -120,7 +120,7 @@ public partial class ShellViewModel : ObservableObject,
////LoadedState = ViewModelLoadedState.Loading;
if (!viewModel.IsInitialized
&& viewModel.InitializeCommand is not null)
&& viewModel.InitializeCommand != null)
{
_ = Task.Run(async () =>
{
@@ -185,7 +185,7 @@ public partial class ShellViewModel : ObservableObject,
private void PerformCommand(PerformCommandMessage message)
{
var command = message.Command.Unsafe;
if (command is null)
if (command == null)
{
return;
}
@@ -205,7 +205,7 @@ public partial class ShellViewModel : ObservableObject,
// Construct our ViewModel of the appropriate type and pass it the UI Thread context.
var pageViewModel = _pageViewModelFactory.TryCreatePageViewModel(page, _isNested, host);
if (pageViewModel is null)
if (pageViewModel == null)
{
Logger.LogError($"Failed to create ViewModel for page {page.GetType().Name}");
throw new NotSupportedException();
@@ -240,7 +240,7 @@ public partial class ShellViewModel : ObservableObject,
// TODO GH #525 This needs more better locking.
lock (_invokeLock)
{
if (_handleInvokeTask is not null)
if (_handleInvokeTask != null)
{
// do nothing - a command is already doing a thing
}
@@ -280,7 +280,7 @@ public partial class ShellViewModel : ObservableObject,
private void UnsafeHandleCommandResult(ICommandResult? result)
{
if (result is null)
if (result == null)
{
// No result, nothing to do.
return;

View File

@@ -17,7 +17,7 @@ public partial class StatusMessageViewModel : ExtensionObjectViewModel
public ProgressViewModel? Progress { get; private set; }
public bool HasProgress => Progress is not null;
public bool HasProgress => Progress != null;
public StatusMessageViewModel(IStatusMessage message, WeakReference<IPageContext> context)
: base(context)
@@ -28,7 +28,7 @@ public partial class StatusMessageViewModel : ExtensionObjectViewModel
public override void InitializeProperties()
{
var model = Model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -36,7 +36,7 @@ public partial class StatusMessageViewModel : ExtensionObjectViewModel
Message = model.Message;
State = model.State;
var modelProgress = model.Progress;
if (modelProgress is not null)
if (modelProgress != null)
{
Progress = new(modelProgress, this.PageContext);
Progress.InitializeProperties();
@@ -61,7 +61,7 @@ public partial class StatusMessageViewModel : ExtensionObjectViewModel
protected virtual void FetchProperty(string propertyName)
{
var model = this.Model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -76,7 +76,7 @@ public partial class StatusMessageViewModel : ExtensionObjectViewModel
break;
case nameof(Progress):
var modelProgress = model.Progress;
if (modelProgress is not null)
if (modelProgress != null)
{
Progress = new(modelProgress, this.PageContext);
Progress.InitializeProperties();

View File

@@ -28,7 +28,7 @@ public partial class TagViewModel(ITag _tag, WeakReference<IPageContext> context
public override void InitializeProperties()
{
var model = _tagModel.Unsafe;
if (model is null)
if (model == null)
{
return;
}

View File

@@ -35,7 +35,7 @@ public partial class AliasManager : ObservableObject
try
{
var topLevelCommand = _topLevelCommandManager.LookupCommand(alias.CommandId);
if (topLevelCommand is not null)
if (topLevelCommand != null)
{
WeakReferenceMessenger.Default.Send<ClearSearchMessage>();
@@ -88,7 +88,7 @@ public partial class AliasManager : ObservableObject
}
// If we already have _this exact alias_, do nothing
if (newAlias is not null &&
if (newAlias != null &&
_aliases.TryGetValue(newAlias.SearchPrefix, out var existingAlias))
{
if (existingAlias.CommandId == commandId)
@@ -113,7 +113,7 @@ public partial class AliasManager : ObservableObject
_aliases.Remove(alias.SearchPrefix);
}
if (newAlias is not null)
if (newAlias != null)
{
AddAlias(newAlias);
}

View File

@@ -55,7 +55,7 @@ public partial class AppStateModel : ObservableObject
var loaded = JsonSerializer.Deserialize<AppStateModel>(jsonContent, JsonSerializationContext.Default.AppStateModel);
Debug.WriteLine(loaded is not null ? "Loaded settings file" : "Failed to parse");
Debug.WriteLine(loaded != null ? "Loaded settings file" : "Failed to parse");
return loaded ?? new();
}

View File

@@ -15,7 +15,7 @@ namespace Microsoft.CmdPal.UI.ViewModels;
public sealed class CommandProviderWrapper
{
public bool IsExtension => Extension is not null;
public bool IsExtension => Extension != null;
private readonly bool isValid;
@@ -188,14 +188,14 @@ public sealed class CommandProviderWrapper
return topLevelViewModel;
};
if (commands is not null)
if (commands != null)
{
TopLevelItems = commands
.Select(c => makeAndAdd(c, false))
.ToArray();
}
if (fallbacks is not null)
if (fallbacks != null)
{
FallbackItems = fallbacks
.Select(c => makeAndAdd(c, true))

View File

@@ -18,18 +18,18 @@ public partial class CommandSettingsViewModel(ICommandSettings? _unsafeSettings,
public bool Initialized { get; private set; }
public bool HasSettings =>
_model.Unsafe is not null && // We have a settings model AND
(!Initialized || SettingsPage is not null); // we weren't initialized, OR we were, and we do have a settings page
_model.Unsafe != null && // We have a settings model AND
(!Initialized || SettingsPage != null); // we weren't initialized, OR we were, and we do have a settings page
private void UnsafeInitializeProperties()
{
var model = _model.Unsafe;
if (model is null)
if (model == null)
{
return;
}
if (model.SettingsPage is not null)
if (model.SettingsPage != null)
{
SettingsPage = new CommandPaletteContentPageViewModel(model.SettingsPage, mainThread, provider.ExtensionHost);
SettingsPage.InitializeProperties();

View File

@@ -30,7 +30,7 @@ internal sealed partial class CreatedExtensionForm : NewExtensionFormBase
public override ICommandResult SubmitForm(string inputs, string data)
{
var dataInput = JsonNode.Parse(data)?.AsObject();
if (dataInput is null)
if (dataInput == null)
{
return CommandResult.KeepOpen();
}

View File

@@ -23,7 +23,7 @@ public partial class LogMessagesPage : ListPage
private void LogMessages_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems is not null)
if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems != null)
{
foreach (var item in e.NewItems)
{

View File

@@ -9,7 +9,6 @@ using ManagedCommon;
using Microsoft.CmdPal.Common.Helpers;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CmdPal.Ext.Apps;
using Microsoft.CmdPal.UI.ViewModels.Messages;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
using Microsoft.Extensions.DependencyInjection;
@@ -61,7 +60,6 @@ public partial class MainListPage : DynamicListPage,
var settings = _serviceProvider.GetService<SettingsModel>()!;
settings.SettingsChanged += SettingsChangedHandler;
HotReloadSettings(settings);
_includeApps = _tlcManager.IsProviderActive(AllAppsCommandProvider.WellKnownId);
IsLoading = true;
}
@@ -203,7 +201,7 @@ public partial class MainListPage : DynamicListPage,
// If we don't have any previous filter results to work with, start
// with a list of all our commands & apps.
if (_filteredItems is null)
if (_filteredItems == null)
{
_filteredItems = commands;
_filteredItemsIncludesApps = _includeApps;

View File

@@ -98,7 +98,7 @@ internal sealed partial class NewExtensionForm : NewExtensionFormBase
public override CommandResult SubmitForm(string payload)
{
var formInput = JsonNode.Parse(payload)?.AsObject();
if (formInput is null)
if (formInput == null)
{
return CommandResult.KeepOpen();
}

View File

@@ -14,7 +14,7 @@ public partial class NewExtensionPage : ContentPage
public override IContent[] GetContent()
{
return _resultForm is not null ? [_resultForm] : [_inputForm];
return _resultForm != null ? [_resultForm] : [_inputForm];
}
public NewExtensionPage()
@@ -28,13 +28,13 @@ public partial class NewExtensionPage : ContentPage
private void FormSubmitted(NewExtensionFormBase sender, NewExtensionFormBase? args)
{
if (_resultForm is not null)
if (_resultForm != null)
{
_resultForm.FormSubmitted -= FormSubmitted;
}
_resultForm = args;
if (_resultForm is not null)
if (_resultForm != null)
{
_resultForm.FormSubmitted += FormSubmitted;
}

View File

@@ -3,7 +3,7 @@
// See the LICENSE file in the project root for more information.
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.CmdPal.UI.Messages;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;

View File

@@ -3,7 +3,7 @@
// See the LICENSE file in the project root for more information.
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.CmdPal.UI.ViewModels.Messages;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;

View File

@@ -4,7 +4,6 @@
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CmdPal.UI.ViewModels.Messages;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;

View File

@@ -98,107 +98,35 @@ public partial class ContentFormViewModel(IFormContent _form, WeakReference<IPag
public void HandleSubmit(IAdaptiveActionElement action, JsonObject inputs)
{
// BODGY circa GH #40979
// Usually, you're supposed to try to cast the action to a specific
// type, and use those objects to get the data you need.
// However, there's something weird with AdaptiveCards and the way it
// works when we consume it when built in Release, with AOT (and
// trimming) enabled. Any sort of `action.As<IAdaptiveSubmitAction>()`
// or similar will throw a System.InvalidCastException.
//
// Instead we have this horror show.
//
// The `action.ToJson()` blob ACTUALLY CONTAINS THE `type` field, which
// we can use to determine what kind of action it is. Then we can parse
// the JSON manually based on the type.
var actionJson = action.ToJson();
if (actionJson.TryGetValue("type", out var actionTypeValue))
if (action is AdaptiveOpenUrlAction openUrlAction)
{
var actionTypeString = actionTypeValue.GetString();
Logger.LogTrace($"atString={actionTypeString}");
var actionType = actionTypeString switch
{
"Action.Submit" => ActionType.Submit,
"Action.Execute" => ActionType.Execute,
"Action.OpenUrl" => ActionType.OpenUrl,
_ => ActionType.Unsupported,
};
Logger.LogDebug($"{actionTypeString}->{actionType}");
switch (actionType)
{
case ActionType.OpenUrl:
{
HandleOpenUrlAction(action, actionJson);
}
break;
case ActionType.Submit:
case ActionType.Execute:
{
HandleSubmitAction(action, actionJson, inputs);
}
break;
default:
Logger.LogError($"{actionType} was an unexpected action `type`");
break;
}
}
else
{
Logger.LogError($"actionJson.TryGetValue(type) failed");
}
}
private void HandleOpenUrlAction(IAdaptiveActionElement action, JsonObject actionJson)
{
if (actionJson.TryGetValue("url", out var actionUrlValue))
{
var actionUrl = actionUrlValue.GetString() ?? string.Empty;
if (Uri.TryCreate(actionUrl, default(UriCreationOptions), out var uri))
{
WeakReferenceMessenger.Default.Send<LaunchUriMessage>(new(uri));
}
else
{
Logger.LogError($"Failed to produce URI for {actionUrlValue}");
}
}
}
private void HandleSubmitAction(
IAdaptiveActionElement action,
JsonObject actionJson,
JsonObject inputs)
{
var dataString = string.Empty;
if (actionJson.TryGetValue("data", out var actionDataValue))
{
dataString = actionDataValue.Stringify() ?? string.Empty;
WeakReferenceMessenger.Default.Send<LaunchUriMessage>(new(openUrlAction.Url));
return;
}
var inputString = inputs.Stringify();
_ = Task.Run(() =>
if (action is AdaptiveSubmitAction or AdaptiveExecuteAction)
{
try
// Get the data and inputs
var dataString = (action as AdaptiveSubmitAction)?.DataJson.Stringify() ?? string.Empty;
var inputString = inputs.Stringify();
_ = Task.Run(() =>
{
var model = _formModel.Unsafe!;
if (model != null)
try
{
var result = model.SubmitForm(inputString, dataString);
Logger.LogDebug($"SubmitForm() returned {result}");
WeakReferenceMessenger.Default.Send<HandleCommandResultMessage>(new(new(result)));
var model = _formModel.Unsafe!;
if (model != null)
{
var result = model.SubmitForm(inputString, dataString);
WeakReferenceMessenger.Default.Send<HandleCommandResultMessage>(new(new(result)));
}
}
}
catch (Exception ex)
{
ShowException(ex);
}
});
catch (Exception ex)
{
ShowException(ex);
}
});
}
}
private static readonly string ErrorCardJson = """

View File

@@ -20,7 +20,7 @@ public partial class ContentMarkdownViewModel(IMarkdownContent _markdown, WeakRe
public override void InitializeProperties()
{
var model = Model.Unsafe;
if (model is null)
if (model == null)
{
return;
}
@@ -47,7 +47,7 @@ public partial class ContentMarkdownViewModel(IMarkdownContent _markdown, WeakRe
protected void FetchProperty(string propertyName)
{
var model = Model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -66,7 +66,7 @@ public partial class ContentMarkdownViewModel(IMarkdownContent _markdown, WeakRe
{
base.UnsafeCleanup();
var model = Model.Unsafe;
if (model is not null)
if (model != null)
{
model.PropChanged -= Model_PropChanged;
}

View File

@@ -30,13 +30,13 @@ public partial class ContentTreeViewModel(ITreeContent _tree, WeakReference<IPag
public override void InitializeProperties()
{
var model = Model.Unsafe;
if (model is null)
if (model == null)
{
return;
}
var root = model.RootContent;
if (root is not null)
if (root != null)
{
RootContent = ViewModelFromContent(root, PageContext);
RootContent?.InitializeProperties();
@@ -82,7 +82,7 @@ public partial class ContentTreeViewModel(ITreeContent _tree, WeakReference<IPag
protected void FetchProperty(string propertyName)
{
var model = Model.Unsafe;
if (model is null)
if (model == null)
{
return; // throw?
}
@@ -91,7 +91,7 @@ public partial class ContentTreeViewModel(ITreeContent _tree, WeakReference<IPag
{
case nameof(RootContent):
var root = model.RootContent;
if (root is not null)
if (root != null)
{
RootContent = ViewModelFromContent(root, PageContext);
}
@@ -119,7 +119,7 @@ public partial class ContentTreeViewModel(ITreeContent _tree, WeakReference<IPag
foreach (var item in newItems)
{
var viewModel = ViewModelFromContent(item, PageContext);
if (viewModel is not null)
if (viewModel != null)
{
viewModel.InitializeProperties();
newContent.Add(viewModel);
@@ -153,7 +153,7 @@ public partial class ContentTreeViewModel(ITreeContent _tree, WeakReference<IPag
Children.Clear();
var model = Model.Unsafe;
if (model is not null)
if (model != null)
{
model.PropChanged -= Model_PropChanged;
model.ItemsChanged -= Model_ItemsChanged;

View File

@@ -29,7 +29,7 @@ public partial class HotkeyManager : ObservableObject
}
}
_commandHotkeys.RemoveAll(item => item.Hotkey is null);
_commandHotkeys.RemoveAll(item => item.Hotkey == null);
foreach (var item in _commandHotkeys)
{

View File

@@ -90,7 +90,7 @@ public partial class ExtensionService : IExtensionService, IDisposable
}).Result;
var isExtension = isCmdPalExtensionResult.IsExtension;
var extension = isCmdPalExtensionResult.Extension;
if (isExtension && extension is not null)
if (isExtension && extension != null)
{
CommandPaletteHost.Instance.DebugLog($"Installed new extension app {extension.DisplayName}");
@@ -152,7 +152,7 @@ public partial class ExtensionService : IExtensionService, IDisposable
{
var (cmdPalProvider, classId) = await GetCmdPalExtensionPropertiesAsync(extension);
return new(cmdPalProvider is not null && classId.Count != 0, extension);
return new(cmdPalProvider != null && classId.Count != 0, extension);
}
}
@@ -237,7 +237,7 @@ public partial class ExtensionService : IExtensionService, IDisposable
{
var (cmdPalProvider, classIds) = await GetCmdPalExtensionPropertiesAsync(extension);
if (cmdPalProvider is null || classIds.Count == 0)
if (cmdPalProvider == null || classIds.Count == 0)
{
return [];
}
@@ -352,12 +352,12 @@ public partial class ExtensionService : IExtensionService, IDisposable
{
var propSetList = new List<string>();
var singlePropertySet = GetSubPropertySet(activationPropSet, CreateInstanceProperty);
if (singlePropertySet is not null)
if (singlePropertySet != null)
{
var classId = GetProperty(singlePropertySet, ClassIdProperty);
// If the instance has a classId as a single string, then it's only supporting a single instance.
if (classId is not null)
if (classId != null)
{
propSetList.Add(classId);
}
@@ -365,7 +365,7 @@ public partial class ExtensionService : IExtensionService, IDisposable
else
{
var propertySetArray = GetSubPropertySetArray(activationPropSet, CreateInstanceProperty);
if (propertySetArray is not null)
if (propertySetArray != null)
{
foreach (var prop in propertySetArray)
{
@@ -375,7 +375,7 @@ public partial class ExtensionService : IExtensionService, IDisposable
}
var classId = GetProperty(propertySet, ClassIdProperty);
if (classId is not null)
if (classId != null)
{
propSetList.Add(classId);
}

View File

@@ -35,7 +35,7 @@ public class ProviderSettings
public void Connect(CommandProviderWrapper wrapper)
{
ProviderId = wrapper.ProviderId;
IsBuiltin = wrapper.Extension is null;
IsBuiltin = wrapper.Extension == null;
ProviderDisplayName = wrapper.DisplayName;

View File

@@ -7,7 +7,7 @@ using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.CmdPal.Common.Services;
using Microsoft.CmdPal.Core.ViewModels;
using Microsoft.CmdPal.UI.ViewModels.Messages;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CmdPal.UI.ViewModels.Properties;
using Microsoft.Extensions.DependencyInjection;
@@ -33,7 +33,7 @@ public partial class ProviderSettingsViewModel(
Resources.builtin_disabled_extension;
[MemberNotNullWhen(true, nameof(Extension))]
public bool IsFromExtension => _provider.Extension is not null;
public bool IsFromExtension => _provider.Extension != null;
public IExtensionWrapper? Extension => _provider.Extension;
@@ -76,7 +76,7 @@ public partial class ProviderSettingsViewModel(
{
get
{
if (_provider.Settings is null)
if (_provider.Settings == null)
{
return false;
}
@@ -100,7 +100,7 @@ public partial class ProviderSettingsViewModel(
{
get
{
if (_provider.Settings is null)
if (_provider.Settings == null)
{
return null;
}
@@ -126,7 +126,7 @@ public partial class ProviderSettingsViewModel(
{
get
{
if (field is null)
if (field == null)
{
field = BuildTopLevelViewModels();
}
@@ -149,7 +149,7 @@ public partial class ProviderSettingsViewModel(
{
get
{
if (field is null)
if (field == null)
{
field = BuildFallbackViewModels();
}
@@ -173,7 +173,7 @@ public partial class ProviderSettingsViewModel(
private void InitializeSettingsPage()
{
if (_provider.Settings is null)
if (_provider.Settings == null)
{
return;
}

View File

@@ -30,7 +30,7 @@ public partial class RecentCommandsManager : ObservableObject
// These numbers are vaguely scaled so that "VS" will make "Visual Studio" the
// match after one use.
// Usually it has a weight of 84, compared to 109 for the VS cmd prompt
if (entry.Item is not null)
if (entry.Item != null)
{
var index = entry.Index;
@@ -61,7 +61,7 @@ public partial class RecentCommandsManager : ObservableObject
var entry = History
.Where(item => item.CommandId == commandId)
.FirstOrDefault();
if (entry is null)
if (entry == null)
{
var newitem = new HistoryItem() { CommandId = commandId, Uses = 1 };
History.Insert(0, newitem);

View File

@@ -95,7 +95,7 @@ public partial class SettingsModel : ObservableObject
var loaded = JsonSerializer.Deserialize<SettingsModel>(jsonContent, JsonSerializationContext.Default.SettingsModel);
Debug.WriteLine(loaded is not null ? "Loaded settings file" : "Failed to parse");
Debug.WriteLine(loaded != null ? "Loaded settings file" : "Failed to parse");
return loaded ?? new();
}

View File

@@ -12,7 +12,7 @@ using ManagedCommon;
using Microsoft.CmdPal.Common.Helpers;
using Microsoft.CmdPal.Common.Services;
using Microsoft.CmdPal.Core.ViewModels;
using Microsoft.CmdPal.UI.ViewModels.Messages;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
using Microsoft.Extensions.DependencyInjection;
@@ -151,7 +151,7 @@ public partial class TopLevelCommandManager : ObservableObject,
WeakReference<IPageContext> weakSelf = new(this);
await sender.LoadTopLevelCommands(_serviceProvider, weakSelf);
List<TopLevelViewModel> newItems = [.. sender.TopLevelItems];
List<TopLevelViewModel> newItems = [..sender.TopLevelItems];
foreach (var i in sender.FallbackItems)
{
if (i.IsEnabled)
@@ -170,29 +170,20 @@ public partial class TopLevelCommandManager : ObservableObject,
// TODO: just added a lock around all of this anyway, but keeping the clone
// while looking on some other ways to improve this; can be removed later.
List<TopLevelViewModel> clone = [.. TopLevelCommands];
var startIndex = -1;
var startIndex = FindIndexForFirstProviderItem(clone, sender.ProviderId);
clone.RemoveAll(item => item.CommandProviderId == sender.ProviderId);
clone.InsertRange(startIndex, newItems);
ListHelpers.InPlaceUpdateList(TopLevelCommands, clone);
}
return;
static int FindIndexForFirstProviderItem(List<TopLevelViewModel> topLevelItems, string providerId)
{
// Tricky: all Commands from a single provider get added to the
// top-level list all together, in a row. So if we find just the first
// one, we can slice it out and insert the new ones there.
for (var i = 0; i < topLevelItems.Count; i++)
for (var i = 0; i < clone.Count; i++)
{
var wrapper = topLevelItems[i];
var wrapper = clone[i];
try
{
if (providerId == wrapper.CommandProviderId)
if (sender.ProviderId == wrapper.CommandProviderId)
{
return i;
startIndex = i;
break;
}
}
catch
@@ -200,8 +191,9 @@ public partial class TopLevelCommandManager : ObservableObject,
}
}
// If we didn't find any, then we just append the new commands to the end of the list.
return topLevelItems.Count;
clone.RemoveAll(item => item.CommandProviderId == sender.ProviderId);
clone.InsertRange(startIndex, newItems);
ListHelpers.InPlaceUpdateList(TopLevelCommands, clone);
}
}
@@ -249,7 +241,7 @@ public partial class TopLevelCommandManager : ObservableObject,
_extensionCommandProviders.Clear();
}
if (extensions is not null)
if (extensions != null)
{
await StartExtensionsAndGetCommands(extensions);
}
@@ -283,7 +275,7 @@ public partial class TopLevelCommandManager : ObservableObject,
var startTasks = extensions.Select(StartExtensionWithTimeoutAsync);
// Wait for all extensions to start
var wrappers = (await Task.WhenAll(startTasks)).Where(wrapper => wrapper is not null).Select(w => w!).ToList();
var wrappers = (await Task.WhenAll(startTasks)).Where(wrapper => wrapper != null).Select(w => w!).ToList();
lock (_commandProvidersLock)
{
@@ -293,7 +285,7 @@ public partial class TopLevelCommandManager : ObservableObject,
// Load the commands from the providers in parallel
var loadTasks = wrappers.Select(LoadCommandsWithTimeoutAsync);
var commandSets = (await Task.WhenAll(loadTasks)).Where(results => results is not null).Select(r => r!).ToList();
var commandSets = (await Task.WhenAll(loadTasks)).Where(results => results != null).Select(r => r!).ToList();
lock (TopLevelCommands)
{
@@ -410,8 +402,8 @@ public partial class TopLevelCommandManager : ObservableObject,
void IPageContext.ShowException(Exception ex, string? extensionHint)
{
var message = DiagnosticsHelper.BuildExceptionMessage(ex, extensionHint ?? "TopLevelCommandManager");
CommandPaletteHost.Instance.Log(message);
var errorMessage = $"A bug occurred in {$"the \"{extensionHint}\"" ?? "an unknown's"} extension's code:\n{ex.Message}\n{ex.Source}\n{ex.StackTrace}\n\n";
CommandPaletteHost.Instance.Log(errorMessage);
}
internal bool IsProviderActive(string id)

View File

@@ -8,7 +8,6 @@ using CommunityToolkit.Mvvm.Messaging;
using ManagedCommon;
using Microsoft.CmdPal.Core.ViewModels;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CmdPal.UI.ViewModels.Messages;
using Microsoft.CmdPal.UI.ViewModels.Settings;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
@@ -240,7 +239,7 @@ public sealed partial class TopLevelViewModel : ObservableObject, IListItem
private void FetchAliasFromAliasManager()
{
var am = _serviceProvider.GetService<AliasManager>();
if (am is not null)
if (am != null)
{
var commandAlias = am.AliasFromId(Id);
if (commandAlias is not null)
@@ -254,7 +253,7 @@ public sealed partial class TopLevelViewModel : ObservableObject, IListItem
private void UpdateHotkey()
{
var hotkey = _settings.CommandHotkeys.Where(hk => hk.CommandId == Id).FirstOrDefault();
if (hotkey is not null)
if (hotkey != null)
{
_hotkey = hotkey.Hotkey;
}
@@ -264,12 +263,12 @@ public sealed partial class TopLevelViewModel : ObservableObject, IListItem
{
List<Tag> tags = [];
if (Hotkey is not null)
if (Hotkey != null)
{
tags.Add(new Tag() { Text = Hotkey.ToString() });
}
if (Alias is not null)
if (Alias != null)
{
tags.Add(new Tag() { Text = Alias.SearchPrefix });
}

View File

@@ -64,9 +64,6 @@ public partial class App : Application
this.InitializeComponent();
// Ensure types used in XAML are preserved for AOT compilation
TypePreservation.PreserveTypes();
NativeEventWaiter.WaitForEventLoop(
"Local\\PowerToysCmdPal-ExitEvent-eb73f6be-3f22-4b36-aee3-62924ba40bfd", () =>
{

View File

@@ -47,8 +47,7 @@
<Flyout
x:Name="ContextMenuFlyout"
FlyoutPresenterStyle="{StaticResource ContextMenuFlyoutStyle}"
Opened="ContextMenuFlyout_Opened"
ShouldConstrainToRootBounds="False">
Opened="ContextMenuFlyout_Opened">
<cpcontrols:ContextMenu x:Name="ContextControl" />
</Flyout>
@@ -60,24 +59,8 @@
<Setter Property="BorderBrush" Value="{ThemeResource DividerStrokeColorDefaultBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="6" />
<Setter Property="MinWidth" Value="20" />
</Style.Setters>
</Style>
<Style x:Key="HotkeyTextBlockStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="10" />
<Setter Property="CharacterSpacing" Value="4" />
<Setter Property="Foreground" Value="{ThemeResource TextFillColorPrimaryBrush}" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style x:Key="HotkeyFontIconStyle" TargetType="FontIcon">
<Setter Property="FontSize" Value="10" />
<Setter Property="Foreground" Value="{ThemeResource TextFillColorPrimaryBrush}" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</ResourceDictionary>
</UserControl.Resources>
@@ -172,7 +155,12 @@
Style="{StaticResource CaptionTextBlockStyle}"
Text="{x:Bind ViewModel.PrimaryCommand.Name, Mode=OneWay}" />
<Border Style="{StaticResource HotkeyStyle}">
<FontIcon Glyph="&#xE751;" Style="{StaticResource HotkeyFontIconStyle}" />
<FontIcon
HorizontalAlignment="Left"
VerticalAlignment="Center"
FontSize="10"
Foreground="{ThemeResource TextFillColorPrimaryBrush}"
Glyph="&#xE751;" />
</Border>
</StackPanel>
</Button>
@@ -191,10 +179,19 @@
Text="{x:Bind ViewModel.SecondaryCommand.Name, Mode=OneWay}" />
<StackPanel Orientation="Horizontal" Spacing="4">
<Border Padding="4,2,4,2" Style="{StaticResource HotkeyStyle}">
<TextBlock Style="{StaticResource HotkeyTextBlockStyle}" Text="Ctrl" />
<TextBlock
CharacterSpacing="4"
FontSize="10"
Foreground="{ThemeResource TextFillColorPrimaryBrush}"
Text="Ctrl" />
</Border>
<Border Style="{StaticResource HotkeyStyle}">
<FontIcon Glyph="&#xE751;" Style="{StaticResource HotkeyFontIconStyle}" />
<FontIcon
HorizontalAlignment="Left"
VerticalAlignment="Center"
FontSize="10"
Foreground="{ThemeResource TextFillColorPrimaryBrush}"
Glyph="&#xE751;" />
</Border>
</StackPanel>
</StackPanel>
@@ -202,7 +199,7 @@
<Button
x:Name="MoreCommandsButton"
x:Uid="MoreCommandsButton"
Padding="6,4,4,4"
Padding="4"
Click="MoreCommandsButton_Clicked"
Style="{StaticResource SubtleButtonStyle}"
ToolTipService.ToolTip="Ctrl+K"
@@ -212,12 +209,32 @@
VerticalAlignment="Center"
Style="{StaticResource CaptionTextBlockStyle}"
Text="More" />
<StackPanel Orientation="Horizontal" Spacing="4">
<Border Padding="4,2,4,2" Style="{StaticResource HotkeyStyle}">
<TextBlock Style="{StaticResource HotkeyTextBlockStyle}" Text="Ctrl" />
<StackPanel Orientation="Horizontal" Spacing="2">
<Border
Padding="4,2,4,2"
VerticalAlignment="Center"
Background="{ThemeResource SubtleFillColorSecondaryBrush}"
BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"
BorderThickness="1"
CornerRadius="4">
<TextBlock
CharacterSpacing="4"
FontSize="10"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
Text="Ctrl" />
</Border>
<Border Padding="4,2,4,2" Style="{StaticResource HotkeyStyle}">
<TextBlock Style="{StaticResource HotkeyTextBlockStyle}" Text="K" />
<Border
Padding="4,2,4,2"
VerticalAlignment="Center"
Background="{ThemeResource SubtleFillColorSecondaryBrush}"
BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"
BorderThickness="1"
CornerRadius="4">
<TextBlock
VerticalAlignment="Center"
FontSize="10"
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
Text="K" />
</Border>
</StackPanel>
</StackPanel>

View File

@@ -10,6 +10,7 @@ using Microsoft.CmdPal.UI.Views;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Input;
using Windows.System;
namespace Microsoft.CmdPal.UI.Controls;
@@ -49,7 +50,7 @@ public sealed partial class CommandBar : UserControl,
return;
}
if (message.Element is null)
if (message.Element == null)
{
_ = DispatcherQueue.TryEnqueue(
() =>

View File

@@ -44,7 +44,7 @@ public sealed partial class ContentFormControl : UserControl
// 5% BODGY: if we set this multiple times over the lifetime of the app,
// then the second call will explode, because "CardOverrideStyles is already the child of another element".
// SO only set this once.
if (_renderer.OverrideStyles is null)
if (_renderer.OverrideStyles == null)
{
_renderer.OverrideStyles = CardOverrideStyles;
}
@@ -55,19 +55,19 @@ public sealed partial class ContentFormControl : UserControl
private void AttachViewModel(ContentFormViewModel? vm)
{
if (_viewModel is not null)
if (_viewModel != null)
{
_viewModel.PropertyChanged -= ViewModel_PropertyChanged;
}
_viewModel = vm;
if (_viewModel is not null)
if (_viewModel != null)
{
_viewModel.PropertyChanged += ViewModel_PropertyChanged;
var c = _viewModel.Card;
if (c is not null)
if (c != null)
{
DisplayCard(c);
}
@@ -76,7 +76,7 @@ public sealed partial class ContentFormControl : UserControl
private void ViewModel_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (ViewModel is null)
if (ViewModel == null)
{
return;
}
@@ -84,7 +84,7 @@ public sealed partial class ContentFormControl : UserControl
if (e.PropertyName == nameof(ViewModel.Card))
{
var c = ViewModel.Card;
if (c is not null)
if (c != null)
{
DisplayCard(c);
}
@@ -95,7 +95,7 @@ public sealed partial class ContentFormControl : UserControl
{
_renderedCard = _renderer.RenderAdaptiveCard(result.AdaptiveCard);
ContentGrid.Children.Clear();
if (_renderedCard.FrameworkElement is not null)
if (_renderedCard.FrameworkElement != null)
{
ContentGrid.Children.Add(_renderedCard.FrameworkElement);
@@ -148,7 +148,7 @@ public sealed partial class ContentFormControl : UserControl
// Recursively check children
var result = FindFirstFocusableElement(child);
if (result is not null)
if (result != null)
{
return result;
}

View File

@@ -2,7 +2,6 @@
// 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.WinUI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
@@ -36,17 +35,6 @@ public partial class ContentIcon : FontIcon
{
if (this.FindDescendants().OfType<Grid>().FirstOrDefault() is Grid grid && Content is not null)
{
if (grid.Children.Contains(Content))
{
return;
}
if (Content is FrameworkElement element && element.Parent is not null)
{
Debug.Assert(false, $"IconBoxElement Content is already parented to {element.Parent.GetType().Name}");
return;
}
grid.Children.Add(Content);
}
}

View File

@@ -112,7 +112,7 @@
<Rectangle
Height="1"
Margin="-16,-12,-12,-12"
Fill="{ThemeResource MenuFlyoutSeparatorBackground}" />
Fill="{ThemeResource MenuFlyoutSeparatorThemeBrush}" />
</DataTemplate>
</ResourceDictionary>
</UserControl.Resources>

View File

@@ -31,7 +31,7 @@ public sealed partial class ContextMenu : UserControl,
WeakReferenceMessenger.Default.Register<UpdateCommandBarMessage>(this);
WeakReferenceMessenger.Default.Register<TryCommandKeybindingMessage>(this);
if (ViewModel is not null)
if (ViewModel != null)
{
ViewModel.PropertyChanged += ViewModel_PropertyChanged;
}

View File

@@ -91,7 +91,7 @@ public partial class IconBox : ContentControl
{
if (d is IconBox @this)
{
if (e.NewValue is null)
if (e.NewValue == null)
{
@this.Source = null;
}
@@ -104,7 +104,7 @@ public partial class IconBox : ContentControl
var requestedTheme = @this.ActualTheme;
var eventArgs = new SourceRequestedEventArgs(e.NewValue, requestedTheme);
if (@this.SourceRequested is not null)
if (@this.SourceRequested != null)
{
await @this.SourceRequested.InvokeAsync(@this, eventArgs);
@@ -142,7 +142,7 @@ public partial class IconBox : ContentControl
iconData = requestedTheme == ElementTheme.Light ? info.Light : info.Dark;
}
if (iconData is not null &&
if (iconData != null &&
@this.Source is FontIconSource)
{
if (!string.IsNullOrEmpty(iconData.Icon) && iconData.Icon.Length <= 2)

View File

@@ -2,6 +2,7 @@
// 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.CmdPal.UI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Markup;
@@ -79,12 +80,12 @@ public sealed partial class KeyVisual : Control
private void Update()
{
if (_keyVisual is null)
if (_keyVisual == null)
{
return;
}
if (_keyVisual.Content is not null)
if (_keyVisual.Content != null)
{
if (_keyVisual.Content.GetType() == typeof(string))
{

View File

@@ -51,13 +51,13 @@ public sealed partial class SearchBar : UserControl,
//// TODO: If the Debounce timer hasn't fired, we may want to store the current Filter in the OldValue/prior VM, but we don't want that to go actually do work...
var @this = (SearchBar)d;
if (@this is not null
if (@this != null
&& e.OldValue is PageViewModel old)
{
old.PropertyChanged -= @this.Page_PropertyChanged;
}
if (@this is not null
if (@this != null
&& e.NewValue is PageViewModel page)
{
// TODO: In some cases we probably want commands to clear a filter
@@ -85,7 +85,7 @@ public sealed partial class SearchBar : UserControl,
{
this.FilterBox.Text = string.Empty;
if (CurrentPageViewModel is not null)
if (CurrentPageViewModel != null)
{
CurrentPageViewModel.Filter = string.Empty;
}
@@ -143,7 +143,7 @@ public sealed partial class SearchBar : UserControl,
FilterBox.Text = string.Empty;
// hack TODO GH #245
if (CurrentPageViewModel is not null)
if (CurrentPageViewModel != null)
{
CurrentPageViewModel.Filter = FilterBox.Text;
}
@@ -154,7 +154,7 @@ public sealed partial class SearchBar : UserControl,
else if (e.Key == VirtualKey.Back)
{
// hack TODO GH #245
if (CurrentPageViewModel is not null)
if (CurrentPageViewModel != null)
{
CurrentPageViewModel.Filter = FilterBox.Text;
}
@@ -318,7 +318,7 @@ public sealed partial class SearchBar : UserControl,
}
// Actually plumb Filtering to the view model
if (CurrentPageViewModel is not null)
if (CurrentPageViewModel != null)
{
CurrentPageViewModel.Filter = FilterBox.Text;
}

View File

@@ -39,13 +39,13 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
private static void OnAllowDisableChanged(DependencyObject d, DependencyPropertyChangedEventArgs? e)
{
var me = d as ShortcutControl;
if (me is null)
if (me == null)
{
return;
}
var description = me.c?.FindDescendant<TextBlock>();
if (description is null)
if (description == null)
{
return;
}
@@ -431,7 +431,7 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
private void ShortcutDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
if (lastValidSettings is not null && ComboIsValid(lastValidSettings))
if (lastValidSettings != null && ComboIsValid(lastValidSettings))
{
HotkeySettings = lastValidSettings with { };
}
@@ -458,7 +458,7 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
private static bool ComboIsValid(HotkeySettings? settings)
{
return settings is not null && (settings.IsValid() || settings.IsEmpty());
return settings != null && (settings.IsValid() || settings.IsEmpty());
}
public void Receive(WindowActivatedEventArgs message) => DoWindowActivated(message);
@@ -466,12 +466,12 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
private void DoWindowActivated(WindowActivatedEventArgs args)
{
args.Handled = true;
if (args.WindowActivationState != WindowActivationState.Deactivated && (hook is null || hook.GetDisposedState() == true))
if (args.WindowActivationState != WindowActivationState.Deactivated && (hook == null || hook.GetDisposedState() == true))
{
// If the PT settings window gets focussed/activated again, we enable the keyboard hook to catch the keyboard input.
hook = new HotkeySettingsControlHook(Hotkey_KeyDown, Hotkey_KeyUp, Hotkey_IsActive, FilterAccessibleKeyboardEvents);
}
else if (args.WindowActivationState == WindowActivationState.Deactivated && hook is not null && hook.GetDisposedState() == false)
else if (args.WindowActivationState == WindowActivationState.Deactivated && hook != null && hook.GetDisposedState() == false)
{
// If the PT settings window lost focus/activation, we disable the keyboard hook to allow keyboard input on other windows.
hook.Dispose();
@@ -490,7 +490,7 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
{
if (disposing)
{
if (hook is not null)
if (hook != null)
{
hook.Dispose();
}

View File

@@ -15,7 +15,7 @@
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" IsTabStop="True" />
<TextBlock Grid.Row="0" />
<ItemsControl
x:Name="KeysControl"

View File

@@ -84,7 +84,7 @@ public partial class Tag : Control
return;
}
if (tag.ForegroundColor is not null &&
if (tag.ForegroundColor != null &&
OptionalColorBrushCacheProvider.Convert(tag.ForegroundColor.Value) is SolidColorBrush brush)
{
tag.Foreground = brush;
@@ -114,7 +114,7 @@ public partial class Tag : Control
return;
}
if (tag.BackgroundColor is not null &&
if (tag.BackgroundColor != null &&
OptionalColorBrushCacheProvider.Convert(tag.BackgroundColor.Value) is SolidColorBrush brush)
{
tag.Background = brush;

View File

@@ -2,7 +2,6 @@
// 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.CodeAnalysis;
using Microsoft.CmdPal.Core.ViewModels;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
@@ -11,7 +10,6 @@ using Microsoft.UI.Xaml.Data;
namespace Microsoft.CmdPal.UI;
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
internal sealed partial class ContextItemTemplateSelector : DataTemplateSelector
{
public DataTemplate? Default { get; set; }

View File

@@ -34,14 +34,8 @@ public sealed partial class ContentPage : Page,
public ContentPage()
{
this.InitializeComponent();
this.Unloaded += OnUnloaded;
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
// Unhook from everything to ensure nothing can reach us
// between this point and our complete and utter destruction.
WeakReferenceMessenger.Default.UnregisterAll(this);
WeakReferenceMessenger.Default.Register<ActivateSelectedListItemMessage>(this);
WeakReferenceMessenger.Default.Register<ActivateSecondaryCommandMessage>(this);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
@@ -51,16 +45,6 @@ public sealed partial class ContentPage : Page,
ViewModel = vm;
}
if (!WeakReferenceMessenger.Default.IsRegistered<ActivateSelectedListItemMessage>(this))
{
WeakReferenceMessenger.Default.Register<ActivateSelectedListItemMessage>(this);
}
if (!WeakReferenceMessenger.Default.IsRegistered<ActivateSecondaryCommandMessage>(this))
{
WeakReferenceMessenger.Default.Register<ActivateSecondaryCommandMessage>(this);
}
base.OnNavigatedTo(e);
}

View File

@@ -7,7 +7,6 @@ using CommunityToolkit.Mvvm.Messaging;
using ManagedCommon;
using Microsoft.CmdPal.Core.ViewModels;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CmdPal.UI.Helpers;
using Microsoft.CmdPal.UI.Messages;
using Microsoft.CmdPal.UI.ViewModels;
using Microsoft.Extensions.DependencyInjection;
@@ -16,7 +15,6 @@ using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using Windows.System;
namespace Microsoft.CmdPal.UI;
@@ -26,8 +24,6 @@ public sealed partial class ListPage : Page,
IRecipient<ActivateSelectedListItemMessage>,
IRecipient<ActivateSecondaryCommandMessage>
{
private InputSource _lastInputSource;
private ListViewModel? ViewModel
{
get => (ListViewModel?)GetValue(ViewModelProperty);
@@ -43,8 +39,6 @@ public sealed partial class ListPage : Page,
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Disabled;
this.ItemsList.Loaded += ItemsList_Loaded;
this.ItemsList.PreviewKeyDown += ItemsList_PreviewKeyDown;
this.ItemsList.PointerPressed += ItemsList_PointerPressed;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
@@ -80,7 +74,7 @@ public sealed partial class ListPage : Page,
WeakReferenceMessenger.Default.Unregister<ActivateSelectedListItemMessage>(this);
WeakReferenceMessenger.Default.Unregister<ActivateSecondaryCommandMessage>(this);
if (ViewModel is not null)
if (ViewModel != null)
{
ViewModel.PropertyChanged -= ViewModel_PropertyChanged;
ViewModel.ItemsUpdated -= Page_ItemsUpdated;
@@ -104,12 +98,6 @@ public sealed partial class ListPage : Page,
{
if (e.ClickedItem is ListItemViewModel item)
{
if (_lastInputSource == InputSource.Keyboard)
{
ViewModel?.InvokeItemCommand.Execute(item);
return;
}
var settings = App.Current.Services.GetService<SettingsModel>()!;
if (settings.SingleClickActivates)
{
@@ -154,20 +142,20 @@ public sealed partial class ListPage : Page,
// here, then in Page_ItemsUpdated trying to select that cached item if
// it's in the list (otherwise, clear the cache), but that seems
// aggressively BODGY for something that mostly just works today.
if (ItemsList.SelectedItem is not null)
if (ItemsList.SelectedItem != null)
{
ItemsList.ScrollIntoView(ItemsList.SelectedItem);
// Automation notification for screen readers
var listViewPeer = Microsoft.UI.Xaml.Automation.Peers.ListViewAutomationPeer.CreatePeerForElement(ItemsList);
if (listViewPeer is not null && li is not null)
if (listViewPeer != null && li != null)
{
var notificationText = li.Title;
UIHelper.AnnounceActionForAccessibility(
ItemsList,
notificationText,
"CommandPaletteSelectedItemChanged");
listViewPeer.RaiseNotificationEvent(
Microsoft.UI.Xaml.Automation.Peers.AutomationNotificationKind.Other,
Microsoft.UI.Xaml.Automation.Peers.AutomationNotificationProcessing.MostRecent,
notificationText,
"CommandPaletteSelectedItemChanged");
}
}
}
@@ -177,7 +165,7 @@ public sealed partial class ListPage : Page,
// Find the ScrollViewer in the ListView
var listViewScrollViewer = FindScrollViewer(this.ItemsList);
if (listViewScrollViewer is not null)
if (listViewScrollViewer != null)
{
listViewScrollViewer.ViewChanged += ListViewScrollViewer_ViewChanged;
}
@@ -186,7 +174,7 @@ public sealed partial class ListPage : Page,
private void ListViewScrollViewer_ViewChanged(object? sender, ScrollViewerViewChangedEventArgs e)
{
var scrollView = sender as ScrollViewer;
if (scrollView is null)
if (scrollView == null)
{
return;
}
@@ -268,7 +256,7 @@ public sealed partial class ListPage : Page,
page.PropertyChanged += @this.ViewModel_PropertyChanged;
page.ItemsUpdated += @this.Page_ItemsUpdated;
}
else if (e.NewValue is null)
else if (e.NewValue == null)
{
Logger.LogDebug("cleared view model");
}
@@ -286,7 +274,7 @@ public sealed partial class ListPage : Page,
// ItemsList_SelectionChanged again to give us another chance to change
// the selection from null -> something. Better to just update the
// selection once, at the end of all the updating.
if (ItemsList.SelectedItem is null)
if (ItemsList.SelectedItem == null)
{
ItemsList.SelectedIndex = 0;
}
@@ -319,7 +307,7 @@ public sealed partial class ListPage : Page,
{
var child = VisualTreeHelper.GetChild(parent, i);
var result = FindScrollViewer(child);
if (result is not null)
if (result != null)
{
return result;
}
@@ -341,7 +329,7 @@ public sealed partial class ListPage : Page,
_ => (null, null),
};
if (item is null || element is null)
if (item == null || element == null)
{
return;
}
@@ -375,21 +363,4 @@ public sealed partial class ListPage : Page,
{
_ = DispatcherQueue.TryEnqueue(() => WeakReferenceMessenger.Default.Send<CloseContextMenuMessage>());
}
private void ItemsList_PointerPressed(object sender, PointerRoutedEventArgs e) => _lastInputSource = InputSource.Pointer;
private void ItemsList_PreviewKeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key is VirtualKey.Enter or VirtualKey.Space)
{
_lastInputSource = InputSource.Keyboard;
}
}
private enum InputSource
{
None,
Keyboard,
Pointer,
}
}

View File

@@ -2,6 +2,13 @@
// 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.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CmdPal.Ext.Bookmarks;
using Microsoft.UI.Xaml.Documents;
using Microsoft.Win32;
namespace Microsoft.CmdPal.UI.Helpers;
@@ -56,7 +63,7 @@ internal static class GpoValueChecker
{
using (RegistryKey? key = rootKey.OpenSubKey(subKeyPath, false))
{
if (key is null)
if (key == null)
{
return null;
}

View File

@@ -4,6 +4,7 @@
using Microsoft.CmdPal.Core.ViewModels;
using Microsoft.CmdPal.UI.Controls;
using Microsoft.CmdPal.UI.Helpers;
namespace Microsoft.CmdPal.UI.Helpers;
@@ -18,7 +19,7 @@ public static partial class IconCacheProvider
public static async void SourceRequested(IconBox sender, SourceRequestedEventArgs args)
#pragma warning restore IDE0060 // Remove unused parameter
{
if (args.Key is null)
if (args.Key == null)
{
return;
}

View File

@@ -28,7 +28,7 @@ public sealed class IconCacheService(DispatcherQueue dispatcherQueue)
var source = IconPathConverter.IconSourceMUX(icon.Icon, false);
return source;
}
else if (icon.Data is not null)
else if (icon.Data != null)
{
try
{
@@ -49,7 +49,7 @@ public sealed class IconCacheService(DispatcherQueue dispatcherQueue)
private async Task<IconSource?> StreamToIconSource(IRandomAccessStreamReference iconStreamRef)
{
if (iconStreamRef is null)
if (iconStreamRef == null)
{
return null;
}

View File

@@ -1,157 +0,0 @@
// 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 ManagedCommon;
using Windows.System;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.UI.WindowsAndMessaging;
namespace Microsoft.CmdPal.UI.Helpers;
/// <summary>
/// A class that listens for local keyboard events using a Windows hook.
/// </summary>
internal sealed class LocalKeyboardListener : IDisposable
{
/// <summary>
/// Event that is raised when a key is pressed down.
/// </summary>
public event EventHandler<LocalKeyboardListenerKeyPressedEventArgs>? KeyPressed;
private bool _disposed;
private UnhookWindowsHookExSafeHandle? _handle;
private HOOKPROC? _hookProc; // Keep reference to prevent GC collection
/// <summary>
/// Registers a global keyboard hook to listen for key down events.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Throws if the hook could not be registered, which may happen if the system is unable to set the hook.
/// </exception>
public void RegisterKeyboardHook()
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_handle is not null && !_handle.IsInvalid)
{
// Hook is already set
return;
}
_hookProc = KeyEventHook;
if (!SetWindowKeyHook(_hookProc))
{
throw new InvalidOperationException("Failed to register keyboard hook.");
}
}
/// <summary>
/// Attempts to register a global keyboard hook to listen for key down events.
/// </summary>
/// <returns>
/// <see langword="true"/> if the keyboard hook was successfully registered; otherwise, <see langword="false"/>.
/// </returns>
public bool Start()
{
if (_disposed)
{
return false;
}
try
{
RegisterKeyboardHook();
return true;
}
catch (Exception ex)
{
Logger.LogError("Failed to register hook", ex);
return false;
}
}
private void UnregisterKeyboardHook()
{
if (_handle is not null && !_handle.IsInvalid)
{
// The SafeHandle should automatically call UnhookWindowsHookEx when disposed
_handle.Dispose();
_handle = null;
}
_hookProc = null;
}
private bool SetWindowKeyHook(HOOKPROC hookProc)
{
if (_handle is not null && !_handle.IsInvalid)
{
// Hook is already set
return false;
}
_handle = PInvoke.SetWindowsHookEx(
WINDOWS_HOOK_ID.WH_KEYBOARD,
hookProc,
PInvoke.GetModuleHandle(null),
PInvoke.GetCurrentThreadId());
// Check if the hook was successfully set
return _handle is not null && !_handle.IsInvalid;
}
private static bool IsKeyDownHook(LPARAM lParam)
{
// The 30th bit tells what the previous key state is with 0 being the "UP" state
// For more info see https://learn.microsoft.com/windows/win32/winmsg/keyboardproc#lparam-in
return ((lParam.Value >> 30) & 1) == 0;
}
private LRESULT KeyEventHook(int nCode, WPARAM wParam, LPARAM lParam)
{
try
{
if (nCode >= 0 && IsKeyDownHook(lParam))
{
InvokeKeyDown((VirtualKey)wParam.Value);
}
}
catch (Exception ex)
{
Logger.LogError("Failed when invoking key down keyboard hook event", ex);
}
// Call next hook in chain - pass null as first parameter for current hook
return PInvoke.CallNextHookEx(null, nCode, wParam, lParam);
}
private void InvokeKeyDown(VirtualKey virtualKey)
{
if (!_disposed)
{
KeyPressed?.Invoke(this, new LocalKeyboardListenerKeyPressedEventArgs(virtualKey));
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
UnregisterKeyboardHook();
}
_disposed = true;
}
}
}

View File

@@ -1,12 +0,0 @@
// 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.System;
namespace Microsoft.CmdPal.UI.Helpers;
public class LocalKeyboardListenerKeyPressedEventArgs(VirtualKey key) : EventArgs
{
public VirtualKey Key { get; } = key;
}

View File

@@ -5,9 +5,8 @@
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.CmdPal.UI.Messages;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CmdPal.UI.ViewModels;
using Microsoft.CmdPal.UI.ViewModels.Messages;
using Microsoft.UI.Xaml;
using Windows.Win32;
using Windows.Win32.Foundation;
@@ -50,7 +49,7 @@ internal sealed partial class TrayIconService
{
if (showSystemTrayIcon ?? _settingsModel.ShowSystemTrayIcon)
{
if (_window is null)
if (_window == null)
{
_window = new Window();
_hwnd = new HWND(WindowNative.GetWindowHandle(_window));
@@ -64,7 +63,7 @@ internal sealed partial class TrayIconService
_originalWndProc = Marshal.GetDelegateForFunctionPointer<WNDPROC>(PInvoke.SetWindowLongPtr(_hwnd, WINDOW_LONG_PTR_INDEX.GWL_WNDPROC, hotKeyPrcPointer));
}
if (_trayIconData is null)
if (_trayIconData == null)
{
// We need to stash this handle, so it doesn't clean itself up. If
// explorer restarts, we'll come back through here, and we don't
@@ -88,7 +87,7 @@ internal sealed partial class TrayIconService
// Add the notification icon
PInvoke.Shell_NotifyIcon(NOTIFY_ICON_MESSAGE.NIM_ADD, in d);
if (_popupMenu is null)
if (_popupMenu == null)
{
_popupMenu = PInvoke.CreatePopupMenu_SafeHandle();
PInvoke.InsertMenu(_popupMenu, 0, MENU_ITEM_FLAGS.MF_BYPOSITION | MENU_ITEM_FLAGS.MF_STRING, PInvoke.WM_USER + 1, RS_.GetString("TrayMenu_Settings"));
@@ -103,7 +102,7 @@ internal sealed partial class TrayIconService
public void Destroy()
{
if (_trayIconData is not null)
if (_trayIconData != null)
{
var d = (NOTIFYICONDATAW)_trayIconData;
if (PInvoke.Shell_NotifyIcon(NOTIFY_ICON_MESSAGE.NIM_DELETE, in d))
@@ -112,19 +111,19 @@ internal sealed partial class TrayIconService
}
}
if (_popupMenu is not null)
if (_popupMenu != null)
{
_popupMenu.Close();
_popupMenu = null;
}
if (_largeIcon is not null)
if (_largeIcon != null)
{
_largeIcon.Close();
_largeIcon = null;
}
if (_window is not null)
if (_window != null)
{
_window.Close();
_window = null;
@@ -167,7 +166,7 @@ internal sealed partial class TrayIconService
// WM_WINDOWPOSCHANGING which is always received on explorer startup sequence.
case PInvoke.WM_WINDOWPOSCHANGING:
{
if (_trayIconData is null)
if (_trayIconData == null)
{
SetupTrayIcon();
}
@@ -189,7 +188,7 @@ internal sealed partial class TrayIconService
{
case PInvoke.WM_RBUTTONUP:
{
if (_popupMenu is not null)
if (_popupMenu != null)
{
PInvoke.GetCursorPos(out var cursorPos);
PInvoke.SetForegroundWindow(_hwnd);

View File

@@ -46,7 +46,7 @@ public static class TypedEventHandlerExtensions
#pragma warning restore CA1715 // Identifiers should have correct prefix
where R : DeferredEventArgs
{
if (eventHandler is null)
if (eventHandler == null)
{
return Task.CompletedTask;
}

View File

@@ -1,32 +0,0 @@
// 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.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Automation.Peers;
namespace Microsoft.CmdPal.UI.Helpers;
public static partial class UIHelper
{
static UIHelper()
{
}
public static void AnnounceActionForAccessibility(UIElement ue, string announcement, string activityID)
{
if (FrameworkElementAutomationPeer.FromElement(ue) is AutomationPeer peer)
{
peer.RaiseNotificationEvent(
AutomationNotificationKind.ActionCompleted,
AutomationNotificationProcessing.ImportantMostRecent,
announcement,
activityID);
}
}
}

View File

@@ -13,7 +13,7 @@ internal sealed partial class WindowHelper
UserNotificationState state;
// https://learn.microsoft.com/en-us/windows/win32/api/shellapi/ne-shellapi-query_user_notification_state
if (Marshal.GetExceptionForHR(NativeMethods.SHQueryUserNotificationState(out state)) is null)
if (Marshal.GetExceptionForHR(NativeMethods.SHQueryUserNotificationState(out state)) == null)
{
if (state == UserNotificationState.QUNS_RUNNING_D3D_FULL_SCREEN ||
state == UserNotificationState.QUNS_BUSY ||

View File

@@ -10,12 +10,11 @@ using ManagedCommon;
using Microsoft.CmdPal.Common.Helpers;
using Microsoft.CmdPal.Common.Messages;
using Microsoft.CmdPal.Common.Services;
using Microsoft.CmdPal.Core.ViewModels;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CmdPal.UI.Events;
using Microsoft.CmdPal.UI.Helpers;
using Microsoft.CmdPal.UI.Messages;
using Microsoft.CmdPal.UI.ViewModels;
using Microsoft.CmdPal.UI.ViewModels.Messages;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.PowerToys.Telemetry;
using Microsoft.UI.Composition;
@@ -27,7 +26,6 @@ using Microsoft.Windows.AppLifecycle;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Graphics;
using Windows.System;
using Windows.UI;
using Windows.UI.WindowManagement;
using Windows.Win32;
@@ -45,8 +43,7 @@ public sealed partial class MainWindow : WindowEx,
IRecipient<DismissMessage>,
IRecipient<ShowWindowMessage>,
IRecipient<HideWindowMessage>,
IRecipient<QuitMessage>,
IDisposable
IRecipient<QuitMessage>
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:Field names should not contain underscore", Justification = "Stylistically, window messages are WM_")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:Field names should begin with lower-case letter", Justification = "Stylistically, window messages are WM_")]
@@ -56,7 +53,6 @@ public sealed partial class MainWindow : WindowEx,
private readonly WNDPROC? _originalWndProc;
private readonly List<TopLevelHotkey> _hotkeys = [];
private readonly KeyboardListener _keyboardListener;
private readonly LocalKeyboardListener _localKeyboardListener;
private bool _ignoreHotKeyWhenFullScreen = true;
private DesktopAcrylicController? _acrylicController;
@@ -119,18 +115,6 @@ public sealed partial class MainWindow : WindowEx,
{
Summon(string.Empty);
});
_localKeyboardListener = new LocalKeyboardListener();
_localKeyboardListener.KeyPressed += LocalKeyboardListener_OnKeyPressed;
_localKeyboardListener.Start();
}
private static void LocalKeyboardListener_OnKeyPressed(object? sender, LocalKeyboardListenerKeyPressedEventArgs e)
{
if (e.Key == VirtualKey.GoBack)
{
WeakReferenceMessenger.Default.Send(new GoBackMessage());
}
}
private void SettingsChangedHandler(SettingsModel sender, object? args) => HotReloadSettings();
@@ -391,7 +375,6 @@ public sealed partial class MainWindow : WindowEx,
// WinUI bug is causing a crash on shutdown when FailFastOnErrors is set to true (#51773592).
// Workaround by turning it off before shutdown.
App.Current.DebugSettings.FailFastOnErrors = false;
_localKeyboardListener.Dispose();
DisposeAcrylic();
_keyboardListener.Stop();
@@ -400,7 +383,7 @@ public sealed partial class MainWindow : WindowEx,
private void DisposeAcrylic()
{
if (_acrylicController is not null)
if (_acrylicController != null)
{
_acrylicController.Dispose();
_acrylicController = null!;
@@ -475,7 +458,7 @@ public sealed partial class MainWindow : WindowEx,
PowerToysTelemetry.Log.WriteEvent(new CmdPalDismissedOnLostFocus());
}
if (_configurationSource is not null)
if (_configurationSource != null)
{
_configurationSource.IsInputActive = args.WindowActivationState != WindowActivationState.Deactivated;
}
@@ -483,7 +466,7 @@ public sealed partial class MainWindow : WindowEx,
public void HandleLaunch(AppActivationArguments? activatedEventArgs)
{
if (activatedEventArgs is null)
if (activatedEventArgs == null)
{
Summon(string.Empty);
return;
@@ -551,7 +534,7 @@ public sealed partial class MainWindow : WindowEx,
UnregisterHotkeys();
var globalHotkey = settings.Hotkey;
if (globalHotkey is not null)
if (globalHotkey != null)
{
if (settings.UseLowLevelGlobalHotkey)
{
@@ -581,7 +564,7 @@ public sealed partial class MainWindow : WindowEx,
{
var key = commandHotkey.Hotkey;
if (key is not null)
if (key != null)
{
if (settings.UseLowLevelGlobalHotkey)
{
@@ -698,10 +681,4 @@ public sealed partial class MainWindow : WindowEx,
return PInvoke.CallWindowProc(_originalWndProc, hwnd, uMsg, wParam, lParam);
}
public void Dispose()
{
_localKeyboardListener.Dispose();
DisposeAcrylic();
}
}

View File

@@ -109,6 +109,10 @@
<ProjectCapability Include="Msix" />
</ItemGroup>
<ItemGroup>
<RdXmlFile Include="rd.xml" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\common\ManagedTelemetry\Telemetry\ManagedTelemetry.csproj" />
<ProjectReference Include="..\ext\Microsoft.CmdPal.Ext.ClipboardHistory\Microsoft.CmdPal.Ext.ClipboardHistory.csproj" />

View File

@@ -47,10 +47,4 @@ DWM_CLOAKED_APP
CoWaitForMultipleObjects
INFINITE
CWMO_FLAGS
GetCurrentThreadId
SetWindowsHookEx
UnhookWindowsHookEx
CallNextHookEx
GetModuleHandle
CWMO_FLAGS

View File

@@ -24,7 +24,7 @@ public sealed partial class LoadingPage : Page
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter is ShellViewModel shellVM
&& shellVM.LoadCommand is not null)
&& shellVM.LoadCommand != null)
{
// This will load the built-in commands, then navigate to the main page.
// Once the mainpage loads, we'll start loading extensions.

Some files were not shown because too many files have changed in this diff Show More