Merge branch 'master' into dev/crutkas/buildFarmVersioningTake3

This commit is contained in:
Clint Rutkas 2020-10-20 15:58:08 -07:00 committed by GitHub
commit f4d0ef19fb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
950 changed files with 102910 additions and 14004 deletions

7
.gitmodules vendored Normal file
View File

@ -0,0 +1,7 @@
[submodule "deps/spdlog"]
path = deps/spdlog
url = https://github.com/gabime/spdlog.git
[submodule "deps/cxxopts"]
path = deps/cxxopts
url = https://github.com/jarro2783/cxxopts.git

View File

@ -26,4 +26,8 @@ dotnet "%XLocPath%\tools\netcore\Microsoft.Localization.XLoc.dll" /f "%LocProjec
echo Localization build finished with exit code '%errorlevel%'.
rem Move UWP resource files to correct file paths as per file path expected by UWP project
cd %RepoRootWithoutBackslash%
powershell -NonInteractive -executionpolicy Unrestricted ".\tools\localization\move_uwp_resources.ps1"
exit /b %errorlevel%

View File

@ -81,6 +81,7 @@ steps:
configuration: '$(BuildConfiguration)'
testSelector: 'testAssemblies'
testAssemblyVer2: |
**\Microsoft.Plugin.Folder.UnitTest.dll
**\Microsoft.Plugin.Program.UnitTests.dll
**\Microsoft.Plugin.Calculator.UnitTest.dll
**\Microsoft.Plugin.Uri.UnitTests.dll

View File

@ -41,6 +41,15 @@ restore:
build:
commands:
# Localize the files after the build procedure to avoid existing localized files from getting overwritten. To be moved before the Build PowerToys step once the lcl files have been checked in. Tracked at https://github.com/microsoft/PowerToys/issues/6046
- !!buildcommand
name: 'Localize Power Toys'
command: '.pipelines\build-localization.cmd'
artifacts:
- from: 'out\loc'
to: 'loc'
include:
- '**/*'
- !!buildcommand
name: 'Build Power Toys'
command: '.pipelines\build.cmd'
@ -56,25 +65,7 @@ build:
- 'action_runner.exe'
- 'modules\ColorPicker\ColorPicker.dll'
- 'modules\ColorPicker\ColorPicker.exe'
- 'modules\ImageResizer\ar\ImageResizer.resources.dll'
- 'modules\ImageResizer\bg\ImageResizer.resources.dll'
- 'modules\ImageResizer\ca\ImageResizer.resources.dll'
- 'modules\ImageResizer\cs\ImageResizer.resources.dll'
- 'modules\ImageResizer\de\ImageResizer.resources.dll'
- 'modules\ImageResizer\es\ImageResizer.resources.dll'
- 'modules\ImageResizer\eu-ES\ImageResizer.resources.dll'
- 'modules\ImageResizer\fr\ImageResizer.resources.dll'
- 'modules\ImageResizer\he\ImageResizer.resources.dll'
- 'modules\ImageResizer\hu\ImageResizer.resources.dll'
- 'modules\ImageResizer\it\ImageResizer.resources.dll'
- 'modules\ImageResizer\nb-NO\ImageResizer.resources.dll'
- 'modules\ImageResizer\nl\ImageResizer.resources.dll'
- 'modules\ImageResizer\pl\ImageResizer.resources.dll'
- 'modules\ImageResizer\pt-BR\ImageResizer.resources.dll'
- 'modules\ImageResizer\ru\ImageResizer.resources.dll'
- 'modules\ImageResizer\sk\ImageResizer.resources.dll'
- 'modules\ImageResizer\tr\ImageResizer.resources.dll'
- 'modules\ImageResizer\zh-Hans\ImageResizer.resources.dll'
- '**\*.resources.dll'
- 'modules\FancyZones\fancyzones.dll'
- 'modules\FancyZones\FancyZonesEditor.exe'
- 'modules\FileExplorerPreview\MarkdownPreviewHandler.dll'
@ -152,15 +143,6 @@ build:
- 'PowerToysSetup-*.exe'
signing_options:
sign_inline: true # This does signing a soon as this command completes
# Localize the files after the build procedure to avoid existing localized files from getting overwritten. To be moved before the Build PowerToys step once the lcl files have been checked in. Tracked at https://github.com/microsoft/PowerToys/issues/6046
- !!buildcommand
name: 'Localize Power Toys'
command: '.pipelines\build-localization.cmd'
artifacts:
- from: 'out\loc'
to: 'loc'
include:
- '**/*'
#package:
@ -192,4 +174,8 @@ static_analysis_options:
- '**/webpack.config.js'
- '**/webpack.serve.config.js'
- '**/dist/bundle.js'
policheck_options:
files_to_scan:
- exclude:
- '**/*.lcl'

View File

@ -267,6 +267,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.PowerToys.Setting
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Plugin.Calculator.UnitTest", "src\modules\launcher\Plugins\Microsoft.Plugin.Calculator.UnitTest\Microsoft.Plugin.Calculator.UnitTest.csproj", "{632BBE62-5421-49EA-835A-7FFA4F499BD6}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Plugin.Folder.UnitTests", "src\modules\launcher\Plugins\Microsoft.Plugin.Folder.UnitTests\Microsoft.Plugin.Folder.UnitTests.csproj", "{4FA206A5-F69F-4193-BF8F-F6EEB496734C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "logging", "src\logging\logging.vcxproj", "{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@ -537,6 +541,14 @@ Global
{632BBE62-5421-49EA-835A-7FFA4F499BD6}.Debug|x64.Build.0 = Debug|x64
{632BBE62-5421-49EA-835A-7FFA4F499BD6}.Release|x64.ActiveCfg = Release|x64
{632BBE62-5421-49EA-835A-7FFA4F499BD6}.Release|x64.Build.0 = Release|x64
{4FA206A5-F69F-4193-BF8F-F6EEB496734C}.Debug|x64.ActiveCfg = Debug|x64
{4FA206A5-F69F-4193-BF8F-F6EEB496734C}.Debug|x64.Build.0 = Debug|x64
{4FA206A5-F69F-4193-BF8F-F6EEB496734C}.Release|x64.ActiveCfg = Release|x64
{4FA206A5-F69F-4193-BF8F-F6EEB496734C}.Release|x64.Build.0 = Release|x64
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}.Debug|x64.ActiveCfg = Debug|x64
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}.Debug|x64.Build.0 = Debug|x64
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}.Release|x64.ActiveCfg = Release|x64
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -614,6 +626,8 @@ Global
{B81FB7B6-D30E-428F-908A-41422EFC1172} = {4AFC9975-2456-4C70-94A4-84073C1CED93}
{0F85E674-34AE-443D-954C-8321EB8B93B1} = {C3081D9A-1586-441A-B5F4-ED815B3719C1}
{632BBE62-5421-49EA-835A-7FFA4F499BD6} = {4AFC9975-2456-4C70-94A4-84073C1CED93}
{4FA206A5-F69F-4193-BF8F-F6EEB496734C} = {4AFC9975-2456-4C70-94A4-84073C1CED93}
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F} = {1AFB6476-670D-4E80-A464-657E01DFF482}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C3A2F9D1-7930-4EF4-A6FC-7EE0A99821D0}

113
README.md
View File

@ -4,7 +4,9 @@
Microsoft PowerToys is a set of utilities for power users to tune and streamline their Windows experience for greater productivity. Inspired by the [Windows 95 era PowerToys project](https://en.wikipedia.org/wiki/Microsoft_PowerToys), this reboot provides power users with ways to squeeze more efficiency out of the Windows 10 shell and customize it for individual workflows. A great overview of the Windows 95 PowerToys can be found [here](https://socket3.wordpress.com/2016/10/22/using-windows-95-powertoys/).
[What's Happening](#whats-happening) | [Downloading & Release notes][github-release-link] | [Contributing to PowerToys](#contributing) | [Known issues](#known-issues)
For a video overview of PowerToys, including install steps and a walkthrough of the available utilities, check out the [PowerToys: Utilities to customize Windows 10](https://www.youtube.com/watch?v=F-d7KiwpnMA) episode of Tabs vs Spaces on YouTube.
[Downloading & Release notes][github-release-link] | [What's Happening](#whats-happening) | [Contributing to PowerToys](#contributing) | [Known issues](#known-issues)
## Build status
@ -80,7 +82,7 @@ Preview Pane is an existing feature in the File Explorer. To enable it, you jus
[<img align="left" src="https://aka.ms/powerToysVideoConferenceImageSmall" />](https://aka.ms/PowerToysOverview_VideoConference) [Video Conference Mute](https://aka.ms/PowerToysOverview_VideoConference) is a quick and easy way to do a global "mute" of both your microphone and webcam via <kbd>Win</kbd>+<kbd>N</kbd>. Just set your webcam in the target application to the PowerToys VideoConference camera.
**Note:** This is only included in the [pre-release version of PowerToys installer][github-prerelease-link]. This PowerToy requires Windows 10 1903 (build 18362) or later.
**Note:** This is only included in the [pre-release experimental version of PowerToys installer][github-prerelease-link]. This PowerToy requires Windows 10 1903 (build 18362) or later.
<br/>
<br/>
<br/>
@ -97,7 +99,7 @@ Preview Pane is an existing feature in the File Explorer. To enable it, you jus
### Via GitHub with EXE [Recommended]
Install from the [Microsoft PowerToys GitHub releases page][github-release-link]. Click on `Assets` to show the files available in the release and then click on `PowerToysSetup-0.21.1-x64.exe` to download the PowerToys installer.
Install from the [Microsoft PowerToys GitHub releases page][github-release-link]. Click on `Assets` to show the files available in the release and then click on `PowerToysSetup-0.23.2-x64.exe` to download the PowerToys installer.
This is our preferred method.
@ -108,9 +110,13 @@ Download PowerToys from [WinGet](https://github.com/microsoft/winget-cli/release
WinGet install powertoys
```
### Experiential PowerToys utility with Video conference muting
Install the [pre-release experimental version of PowerToys][github-prerelease-link] to try out this version. It includes all improvements from 0.23 in addition to the Video conference utility. Click on `Assets` to show the files available in the release and then download the .exe installer.
### Other install methods
There are [community driven install methods](./doc/unofficalInstallMethods.md) such as Chocolatey and Scoop. If these are your perferred install solutions, this will have the install instructions.
There are [community driven install methods](./doc/unofficalInstallMethods.md) such as Chocolatey and Scoop. If these are your preferred install solutions, this will have the install instructions.
### Known issues
@ -126,74 +132,77 @@ We currently support the matrix below.
## What's Happening
### August 2020 Update
### September 2020 Update
Our goals for 0.21 release cycle was to focus on stability, localization and quality of life improvements for both the development team and our end users.
Our goals for 0.23 release cycle was to focus on stability, accessibility, localization and quality of life improvements for both the development team and our end users. We have a full accessibility pass being done starting end of September to audit all of PowerToys. Our localization efforts now had data flowing both directions as well.
One of the longer term goal items we have made progress on is the Out of Box experience / initial onboarding experience (OOBE) improvements.[@Niels9001](https://github.com/niels9001/) created a [wicked awesome proof of concept of what the OOBE experience could be](https://github.com/microsoft/PowerToys/issues/1285#issuecomment-679268558). We are pretty stoked about this since it handles one an important item, critical shortcut default adjustments.
Our [prioritized roadmap][roadmap] of features and utilites that the core team is focusing on.
#### Highlights from August
#### Highlights from September
- We shipped [v0.21][github-release-link]!
- [Video conference muting first public release][vidConfOverview]
- We shipped [v0.23][github-release-link]! (0.24 Experimental build coming shortly)
**PT Run:**
- Removed need for space in action keywords. This means you now can type `>ipconfig`
- Icon caches fixed and now has colored icons
- Improved font rendering via ClearType (Shout out to [@AnuthaDev](https://github.com/AnuthaDev) doing the heavy lifting here)
- Result speed improvements
- URLs are supported
- Fixed bugs including calculating bugs
**General**
**FancyZone:**
- <kbd>Win</kbd>+<kbd>Arrow key</kbd> is directional based on zone rect
- Fixed bugs
- Localization pipeline is flowing from our Github to the loc system and back. 0.25 should be localized now.
- The EXE installer should be at parity now with the MSI. Please go to the wiki for [installer args](https://github.com/microsoft/PowerToys/wiki/Installer-arguments-for-exe)
**Runner:**
- Fixed toast notifications running elevated from non-admin account
**FancyZones**
**Shortcut Guide:**
- Improved vkey catching which will fix some use cases of it not showing up
- Fixed bug on not seeing a newly attached screen
- Fixed spanning across monitors bug
- Added in default layout for new users, a Priority Grid
- Added keyboard support to grow / shrink to multiple zones
- General bug fixes
**SVG in File Explorer:**
- Embedded image tags will now render in Explorer
**PT Run**
**Color Picker:**
- Fixed bug where it would launch via false positive keystrokes
- Multiple crash bugs fixed. Prioritized any users reported along with top hits from Watson reporting
- Stopped PT Run from interfering with an install
- Fixed folder bug if it had a # in it (Thanks @jjw24 for the PR!)
- Fixed a screen flicker for
- General bug fixes
- Allow Command Line args in PowerToys Run (Thanks @@royvou)
**Accessibility:**
- Settings, PT Run and KBM undergoing improvements
**Keyboard manager**
**Localization:**
- Pipeline is now setup and will be doing a full E2E pass on all utilities shortly.
- Multiple crash bugs fixed. Prioritized any users reported along with top hits from Watson reporting
- Fixed multiple accessibility issues.
- General bug fixes
**Dev quality of life improvements:**
- Continued warning count reduction. This release ~80 removed
- StyleCop enabled E2E
- FxCop starting to be added in E2E
**Preview Pane**
#### New experiential PowerToys utility - Video conference muting:
- Added in Frontmatter and better (but still basic) latex support.
**Note:** This is only included in the [pre-release version of PowerToys installer][github-prerelease-link]. This PowerToy requires Windows 10 1903 (build 18362) or later.
**Settings**
Back in the June timeframe, we started prototyping an idea. With COVID-19, we're all multi-tasking and trying to make the best of everything and being able to quickly mute while on a conference call is critical regardless of where you are on your computer and what application has focus.
- Fixed scaling issue for responsive design on Image Resizer
- Fixed crash on empty color value.
- Fixed crash for toggling FancyZones on/off
- Fixed 0x00 NFTS crash for settings
- Fixed multiple accessibility issues.
- Layout adjustments (Thanks @niels9001)
- General bug fixes
The utility will mute not just your audio but your video as well with a single keystroke. You can do audio, video both. We knew this would impact our roadmap and goals but felt extremely strong that this is the right decision. We're all multi-tasking and trying to make the best of everything and being able to quickly mute while on a conference call is critical regardless of where you are on your computer.
**Dev related**
We know we have some issues and we have a [master tracking issue - #6246](https://github.com/microsoft/PowerToys/issues/6246). We know a certain laptops currently the video forwarding does not work and are proactively working on fixing this.
- FxCop is being rolled out across all PowerToys. This should catch a lot of possible leaks.
- Unified PT Run's log system
- PT Run's calc plugin now has unit tests (Thanks @P-Storm)
- Dev setup install script now supports VS preview (Thanks @TobiasSekan)
- @CaelestisZ, @kameshkotwani, @adriancampos, @RahulDas782 for doc tweaks
- Thanks @Aaron-Junker, @jay-o-way and @htcfreek for helping triage!
- Thanks for everyone that filled an issue. It really does help us prioritize
To use:
#### Video / GIF capture functional spec for public review
- Set your camera to the PowerToys Video driver in the target application
- <kbd>Win</kbd>+<kbd>N</kbd> to toggle both Audio and Video at the same time
- <kbd>Win</kbd>+<kbd>Shift</kbd>+<kbd>O</kbd> to toggle video
- <kbd>Win</kbd>+<kbd>Shift</kbd>+<kbd>A</kbd> to toggle microphone
Deondre Davis created our [functional spec for creating a light weight, video / GIF recording tool](https://github.com/microsoft/PowerToys/pull/6900). We encourage everyone to review it and please leave comments in the pull request so we can adjust as needed. We'll be closing it for feedback on October 12th, 2020.
For a more information, head over to the [Video conference mute overview][vidConfOverview]
This is for work [post-stabilization of current roadmap work](https://github.com/microsoft/PowerToys/wiki/Roadmap#post-stabilization) and is only the spec for what we are thinking about support. Just want to set expectations here.
### What is being planned for 0.23
### What is being planned for 0.25
For [0.23](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen+is%3Aissue+project%3Amicrosoft%2FPowerToys%2F12), we are proactively working on:
For [0.25](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen+is%3Aissue+project%3Amicrosoft%2FPowerToys%2F13), we are proactively working on:
- Stability
- Localization
@ -202,7 +211,7 @@ For [0.23](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen+is%3Aissue+
### PowerToys roadmap
Our [prioritized roadmap][roadmap] of features and utilites that the core team is focusing on..
Our [prioritized roadmap][roadmap] of features and utilites that the core team is focusing on.
## Developer Guidance
@ -212,7 +221,7 @@ Please read the [developer docs](/doc/devdocs) for a detailed breakdown.
This project welcomes contributions of all types. Help spec'ing, design, documentation, finding bugs are ways everyone can help on top of coding features / bug fixes. We are excited to work with the power user community to build a set of tools for helping you get the most out of Windows.
We ask that **before you start work on a feature that you would like to contribute**, please read our [Contributor's Guide](contributing.md). We will be happy to work with you to figure out the best approach, provide guidance and mentorship throughout feature development, and help avoid any wasted or duplicate effort.
We ask that **before you start work on a feature that you would like to contribute**, please read our [Contributor's Guide](CONTRIBUTING.md). We will be happy to work with you to figure out the best approach, provide guidance and mentorship throughout feature development, and help avoid any wasted or duplicate effort.
### ⚠ State of code ⚠
@ -233,7 +242,7 @@ The application logs basic telemetry. Our Telemetry Data page (Coming Soon) has
[oss-CLA]: https://cla.opensource.microsoft.com
[oss-conduct-code]: CODE_OF_CONDUCT.md
[github-release-link]: https://github.com/microsoft/PowerToys/releases/
[github-prerelease-link]: https://github.com/microsoft/PowerToys/releases/tag/v0.22.0-Experimental
[github-prerelease-link]: https://github.com/microsoft/PowerToys/releases/tag/v0.24.0-Experimental
[roadmap]: https://github.com/microsoft/PowerToys/wiki/Roadmap
[privacyLink]: http://go.microsoft.com/fwlink/?LinkId=521839
[vidConfOverview]: https://aka.ms/PowerToysOverview_VideoConference

18
SUPPORT.md Normal file
View File

@ -0,0 +1,18 @@
# Support
## How to file issues and get help
This project uses [GitHub Issues][gh-issue] to [track bugs][gh-bug] and [feature requests][gh-feature]. Please search the existing issues before filing new issues to avoid duplicates. For new issues, file your bug or
feature request as a new Issue.
For help and questions about using this project, please look at our Wiki for using PowerToys and our [Contributor's Guide][contributor] if you want to work on PowerToys.
## Microsoft Support Policy
Support for PowerToys is limited to the resources listed above.
[gh-issue]: https://github.com/microsoft/PowerToys/issues/new/choose
[gh-bug]: https://github.com/microsoft/PowerToys/issues/new?assignees=&labels=Issue-Bug&template=bug_report.md&title=
[gh-feature]: https://github.com/microsoft/PowerToys/issues/new?assignees=&labels=&template=feature_request.md&title=
[wiki]: https://github.com/microsoft/PowerToys/wiki
[contributor]: https://github.com/microsoft/PowerToys/blob/master/CONTRIBUTING.md

1
deps/cxxopts vendored Submodule

@ -0,0 +1 @@
Subproject commit 12e496da3d486b87fa9df43edea65232ed852510

7
deps/cxxopts.props vendored Normal file
View File

@ -0,0 +1,7 @@
<Project>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(MSBuildThisFileDirectory)cxxopts\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
</Project>

1
deps/spdlog vendored Submodule

@ -0,0 +1 @@
Subproject commit cbe9448650176797739dbab13961ef4c07f4290f

8
deps/spdlog.props vendored Normal file
View File

@ -0,0 +1,8 @@
<Project>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(MSBuildThisFileDirectory)spdlog\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>SPDLOG_WCHAR_TO_UTF8_SUPPORT;SPDLOG_COMPILED_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
</Project>

9
doc/devdocs/logging.md Normal file
View File

@ -0,0 +1,9 @@
# How to use
We use the awesome [spdlog](https://github.com/gabime/spdlog) library for logging as a git submodule under the `deps` directory. To use it in your project, just include [spdlog.props](../../deps/spdlog.props) in a .vcxproj like this:
```xml
<Import Project="..\..\..\deps\spdlog.props" />
```
It'll add the required include dirs and link the library binary itself.
You can see many example usage of the library in its repository or in the [bootstrapper project](../../installer/PowerToysBootstrapper/bootstrapper/bootstrapper.cpp).

View File

@ -0,0 +1,48 @@
# Architecture
## Overview
`PowerToys Run` is a plugin-based .net core desktop application. It is written in WPF using `Model-View-ViewModel (MVVM)` structural design pattern. This article provides an overview of `PowerToys Run` architecture and introduces major components in the data flow.
Note : We refer to base application without plugins as `PowerLauncher`, which is same as the name of startup WPF project.
## UI
PowerToys Run UI is written in the WPF framework. The UI code is present in the Powerlauncher project and is spanned across three high-level components: [`MainWindow.xaml`](/src/modules/launcher/PowerLauncher/MainWindow.xaml), [`LauncherControl.xaml`](/src/modules/launcher/PowerLauncher/LauncherControl.xaml) and [`ResultList.xaml`](/src/modules/launcher/PowerLauncher/LauncherControl.xaml). These components are discussed below.
![Image of PowerToys Run UI](/doc/images/launcher/pt_run_ui.png)
**Fig 1: PowerToys Run UI architecture**
1. **[`MainWindow.xaml`](/src/modules/launcher/PowerLauncher/MainWindow.xaml)**: This is the outermost-level UI control. It is composed of lower-level UI components such as [`LauncherControl.xaml`](/src/modules/launcher/PowerLauncher/LauncherControl.xaml) and [`ResultList.xaml`](/src/modules/launcher/PowerLauncher/LauncherControl.xaml). The corresponding code-behind file implements all the UI related functionalities such as autosuggest, key-bindings, toggling visibility of WPF window and animations.
2. **[`LauncherControl.xaml`](/src/modules/launcher/PowerLauncher/LauncherControl.xaml)**: This control implements the UI component for editing query text.(marked in red in Fig 1) It consists of two overlapping WPF controls, `TextBox` and `TextBlock`. The outer `TextBox` is used for editing query whereas the inner `TextBlock` is used to display autosuggest text.
3. **[`ResultList.xaml`](/src/modules/launcher/PowerLauncher/LauncherControl.xaml)**: This control implements the UI component for displaying results (marked in green in Fig 1). It consists of a `ListView` WPF control with a custom `ItemTemplate` to display application logo, name, tooltip text, and context menu.
## Data flow
The backend code is written using the `Model-View-ViewModel (MVVM)` structural design pattern. Plugins act as `Model` in this project. A detailed overview of the project's structure is given [here](/doc/devdocs/modules/launcher/project_structure.md).
#### Flow of data between UI(view) and ViewModels
Data flow between View and ViewModel follows typical `MVVM` scheme. Properties in viewModels are bound to WPF controls and when these properties are updated, `INotifyPropertyChanged` handler is invoked, which in turn updates UI. The diagram below provides a rough sketch of the components involved.
![Flow of data between UI(view) and ViewModels](/doc/images/launcher/ui_vm_interaction.PNG)
**Fig 2: Flow of data between UI and ViewModels.**
#### Flow of data between ViewModels and Plugins(Model)
`PowerLauncher` interact with plugins using [`IPlugin`](/src/modules/launcher/Wox.Plugin/IPlugin.cs) and `IDelayedExecutionPlugin` interface. [`IPlugin`](/src/modules/launcher/Wox.Plugin/IPlugin.cs) is used for initialization and making queries which are fast (typically return results in less than 100ms).[`IDelayedExecutionPlugin`](/src/modules/launcher/Wox.Plugin/IDelayedExecutionPlugin.cs) is used for long-running queries and is implemented only when required. For example, [`IDelayedExecutionPlugin`](/src/modules/launcher/Wox.Plugin/IDelayedExecutionPlugin.cs) is implemented by indexer plugin for searching files with names of form \*abc\*.
```
public interface IPlugin
{
// Query plugin
List<Result> Query(Query query);
// Initialize plugin
void Init(PluginInitContext context);
}
public interface IDelayedExecutionPlugin : IFeatures
{
// Query plugin
List<Result> Query(Query query, bool delayedExecution);
}
```
![Flow of data between UI(view) and ViewModels](/doc/images/launcher/vm_plugin_interaction.PNG)
**Fig 3: Flow of data between ViewModels and Plugins.**
#### Requesting services from powerlauncher
Plugins could use the [`IPublicAPI`](/src/modules/launcher/Wox.Plugin/IPublicAPI.cs) interface to request services such as getting the current theme (for deciding logo background), displaying messages to the user, and toggling the visibility of PowerLauncher.

View File

@ -0,0 +1,20 @@
# Debugging
`PowerToys Run` is a single exe file associated with `launcher.exe` process and debugger should be attached to this process. There are two approaches to debug `PowerToys Run`. Both these approaches differ in the compile-time and the range of functionalities that could be debugged. These methods are discussed in detail in the following sections.
## Debugging Prerequisite
Setup development environment for PowerToys by following instruction [here.](https://github.com/microsoft/PowerToys/tree/master/doc/devdocs#prerequisites-for-compiling-powertoys)
## Direct debugging
This approach is used to test UI, plugins, and core `PowerToys Run` functionality. This **cannot** be used to test `PowerToys Run` settings. The approach is significantly faster compared to `Debugging with runner`, as it requires compiling projects relevant to `PowerToys Run`. Please follow the steps below for direct debugging.
1. Right-click on `modules->launcher->PowerLauncher` and select `Set as startup Project`.
2. Press `F5` to start debugging.
## Debugging with runner
This approach can be used to test UI, plugins, core `PowerToys Run` functionality and `PowerToys Run` settings. This approach **cannot** be used to debugg functions that execute on starting `launcher.exe` process. This requires building runner along with all the other modules on first compile, making it slower than `Direct debugging` approach. The subsequent compilations should be fast.
1. Right-click on `runner` and select `Set as startup Project`.
2. Press `F5` to start debugging.
3. Attach debugger to `launcher.exe` process.
1. Go to `Debug->Attach to process..`
2. Filter and select `launcher.exe` process.
3. Click on `Attach`.

View File

@ -0,0 +1,23 @@
# Calculator Plugin
The Calculator plugin as the name suggests is used to perform calculations on the user entered query.
![Image of Calculator plugin](/doc/images/launcher/plugins/calculator.png)
### [`CalculateHelper`](src/modules/launcher/Plugins/Microsoft.Plugin.Calculator/CalculateHelper.cs)
- The [`CalculateHelper.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.Calculator/CalculateHelper.cs) class checks to see if the user entered query is a valid input to the calculator and only if the input is valid does it perform the operation.
- It does so by matching the user query to a valid regex.
### [`CalculateEngine`](src/modules/launcher/Plugins/Microsoft.Plugin.Calculator/CalculateEngine.cs)
- The main computation is done in the [`CalculateEngine.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.Calculator/CalculateEngine.cs) file using the `Mages` library.
```csharp
var result = CalculateEngine.Interpret(query.Search, CultureInfo.CurrentUICulture);
```
### [`CalculateResult`](src/modules/launcher/Plugins/Microsoft.Plugin.Calculator/CalculateResult.cs)
- The class which encapsulates the result of the computation.
- It comprises of the `Result` and `RoundedResult` properties.
### Score
The score of each result from the calculator plugin is `300`.

View File

@ -0,0 +1,17 @@
# Folder Plugin
The Folder plugin is used to navigate the directory structure and display the sub-folders and files within a folder.
![Image of Folder plugin](/doc/images/launcher/plugins/folder.png)
### [`FolderHelper.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.Folder/Sources/Path/FolderHelper.cs)
- The [`FolderHelper`](src/modules/launcher/Plugins/Microsoft.Plugin.Folder/Sources/Path/FolderHelper.cs) class leverages the `DriveInformation` and `folderLinks` to get the folder results for a user query.
- The [`DriveInformation`](src/modules/launcher/Plugins/Microsoft.Plugin.Folder/Sources/Path/DriveInformation.cs) class gets the list of all drives on the system.
- The [`FolderLink`](src/modules/launcher/Plugins/Microsoft.Plugin.Folder/Sources/FolderLink.cs) object corresponds to a user created link for frequently accessed projects. This was inherited from Wox but is presently not functional as we don't have the UI setup in settings to get this user input. Each folderLink object has a `nickname`, which is the name of the folder and this can be used to directly access that folder instead of entering the entire path.
### [`IFolderProcessor.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.Folder/Sources/IFolderProcessor.cs)
The `IFolderProcessor` utilizes the `FolderHelper` class to extract the folders and return the results.
There are two types of Folder Processors, based on the type of information they are processing -
1. [`UserFolderProcessor`](src/modules/launcher/Plugins/Microsoft.Plugin.Folder/UserFolderProcessor.cs) - This Processor is currently not used in PT Run but it is used to process the user created folder links.
2. [`InternalDirectoryProcessor`](src/modules/launcher/Plugins/Microsoft.Plugin.Folder/InternalDirectoryProcessor.cs) - This processor is used to retrieve the files and folders located within the current drive or shared folder.
### Score
The first result is of score 500 and the following results are scored 10.

View File

@ -0,0 +1,39 @@
# Indexer Plugin
The indexer plugin is used to search for files within the indexed locations of the system.
![Image of Indexer plugin](/doc/images/launcher/plugins/indexer.png)
### [Drive Detection](src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/DriveDetection)
- There are two indexing modes in Windows:
1. **Classic mode**: Only the desktop and certain customizable locations in the system are indexed. All the systems have the classic mode enabled by default.
2. **Enhanced Mode**: This mode indexes the entire PC when enabled. The user can exclude certain locations from being indexed in this mode from the Windows Search settings options.
- A drive detection warning is displayed to the users when only the custom mode is enabled on the system informing the user that not all the locations on their PC are indexed as this could lead to some results not showing up.
- The [`IndexerDriveDetection.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/DriveDetection/IndexerDriveDetection.cs) file gets the status of the drive detection checkbox in the settings UI and depending on whether the enhanced mode is enabled or disabled, displays the warning.
- To determine whether the `EnhancedMode` is enabled or not, we check the local machine registry entry for `EnableFindMyFiles`. If it is set to 1, the enhanced mode is enabled.
### [`OleDBSearch`](src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/SearchHelper/OleDBSearch.cs)
- The `Query` function within the [`OleDBSearch.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/SearchHelper/OleDBSearch.cs) class takes in the query and the connection string to the SystemIndex catalog as arguments and returns a list of results.
- It first opens a [connection][OLEDBConnection] to the Windows Indexer database, creates an [OleDB command][OLEDBCommand] and executes the command to get a list of results.
### [`WindowsSearchAPI`](src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/SearchHelper/WindowsSearchAPI.cs)
- The [`WindowsSearchAPI`](src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/SearchHelper/WindowsSearchAPI.cs) class leverages the [`OleDBSearch.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/SearchHelper/OleDBSearch.cs) class to execute the query.
- It initializes the `QueryHelper` in the `InitQueryHelper()` function by creating a catalog manager to the SystemIndex catalog.
- The metadata is initialized within the query helper, such as the number of results to retrive, the type of information to retrieve for each file (currently we retrieve the item URL, the file name and the file attributes).
- The query helper matches results using the name of the file only and they are sorted by the last modified date, ensuring that the recently modified files are ranked higher.
- The File attributes are utilized to filter out hidden files from being displayed.
### Additional Information
- There are two major types of queries generated by the indexer plugin:
1. Full Text predicates - eg: [CONTAINS][Contains]
2. Non-Full Text predicates - eg: [LIKE][Like]
- The Full text predicates are much faster than non-full text predicates as they are based on finding matches rather than comparing the query with each item in the indexer database. Hence, queries which have the `CONTAINS` keyword are much faster than those which contain the `LIKE` keyword.
- To prevent the indexer query from taking a long time and blocking the UI thread, there are two types of indexer queries which are executed. A simplified query and a full query, without and with the `LIKE` keyword respectively.
- The result list is updated with the results of the full query once they are obtained.
### Score
Each of the indexer plugin results has a score set to 0 so they are present at the bottom of the list.
[OLEDBCommand]: https://docs.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand?view=dotnet-plat-ext-3.1
[OLEDBConnection]: https://docs.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbconnection?view=dotnet-plat-ext-3.1
[Contains]: https://docs.microsoft.com/en-us/windows/win32/search/-search-sql-contains
[Like]: https://docs.microsoft.com/en-us/windows/win32/search/-search-sql-like

View File

@ -0,0 +1,35 @@
# Structural Overview
The following basic functions are common to each of the plugins. They perform some rudimentary operations such as initialization of the plugin, executing the query that has been entered, loading context menu icons, updating settings when configurations are altered in the settings UI, and updating the theme of the icons when the theme changed event is triggered.
## IPlugin Interface
Each plugin implements the `IPlugin` interface which comprises of the `Init()` and `Query()` functions.
### `Init`
- The `Init()` function initializes the context, storage and settings of each plugin. This is equivalent to a contructor and is the first function to be called in the `Main.cs` file for each plugin.
### `Query`
- For every query that the user enters into PT Run, the `PluginManager.cs` executes the `Query()` function in the `Main.cs` file corresponding to each Plugin.
### Context Menu Icons
- The `ContextMenus` are loaded for each result based on the type of the result.
- The various types of `ContextMenu` functionalities are:
- Open containing folder
- Run as Administrator
- Open in console
- Copy path
### UpdateSettings
- This function updates the settings of each plugin based on the changes made by the user in the settings UI.
- Eg: To disable drive detection in the indexer plugin, when the user checks or unchecks the drive detection check box, the `UpdateSettings()` function dispatches the changes in the check box to the plugin.
### ThemeChanged
- This function is invoked when there is a change in the theme of PT Run.
- It is used to update the `IconPath` for each plugin based on the theme.
### Save
- This function saves the configurations of each plugin so that they can be loaded the next time.
### Score
- The user query is executed against each of the plugins and the result list view is updated with results from each of the plugins.
- The ordering of the results is based on the `Score` of each Result.
- Each plugin assigns a score to a result based on it's relevance. The results with higher scores are displayed higher in the list view and vice versa.

View File

@ -0,0 +1,43 @@
# Program Plugin
The program plugin as the name suggests is used to search for programs installed on the system.
![Image of Program plugin](/doc/images/launcher/plugins/program.png)
There are broadly two different categories of applications:
1. Packaged applications
2. Win32 applications
### [UWP](src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/UWP.cs)
- The logic for indexing Packaged applications is present within the [`UWP.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/UWP.cs) file.
- There can be multiple applications present within a package. The [`UWPApplication.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/UWPApplication.cs) file encapsulates the properties of a packaged application.
- To index packaged applications, the `PackageManager` retrives all the packages for the current user and indexes all the applications.
- To retrieve the app icon for packaged applications, the assets path is retrieved from the `Application Manifest` file. There are multiple icons corresponding to each scale, target size and theme. The best icon is chosen given the theme of powerToys Run.
### [Win32Program](src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/Win32Program.cs)
- Win32 programs in the following locations are indexed by PT Run-
1. Desktop
2. Public Desktop (Applications present on the desktop of all the users)
3. Registry (Some programs)
4. Start Menu
5. Common start menu (Applications which are common to all users)
8. Locations pointed to by the PATH environment variable.
- To prevent applications and shortcuts present in multiple locations from showing up as duplicate results, we consider apps with the same name, executable name and full path to be the same.
- The subtitle of the application result is set based on it's application type. It could be one of the following:
1. Lnk Shortcuts
2. Appref files
3. Internet shortcut - steam and epic games
4. PWAs
5. Run commands - these are indexed by the PATH environment variable
### Score
- The score for each application result is based on the how many letters are matched, how close the matched letters are to the actual word and the index of the matched characters.
- There is a threshold score to decide the apps which are to be displayed and applications which have a lower score are not displayed by PT Run.
### Update Program List in Runtime
- Packaged and Win32 app helpers exist to reflect changes in the list of indexed apps when applications are installed on the system while PT Run is executing.
- Packaged applications trigger events when the package is being installed and uninstalled. PT Run listens to those events to index applications which are newly installed or to delete an app which no longer exists from the database.
- No such events exist for Win32 applications. We therefore use FileSystem Watchers to monitor the locations that we index for newly created, deleted or renamed application files and update the indexed Win32 catalog accordingly.
### Additional Notes
- Arguments can be provided to the program plugin by entering them after `--` (a double dash).

View File

@ -0,0 +1,14 @@
# Shell Plugin
- Shell plugin emulates the Windows Run Prompt (Win+R).
- Shell Plugin is one of the non-global plugins which has an action keyword set to `>`.
![Image of Shell plugin](/doc/images/launcher/plugins/shell.png)
### Functionality
- The Shell command expands environment variables, so `>%appdata%` works as expected.
- On inheriting the Shell plugin from Wox, there are three different ways of executing a command, using the command prompt, powershell or the run prompt. To uphold the name of PT Run, the Shell plugin always executes commands as the Run prompt would.
- The Shell plugin has a concept of history where the previously executed commands show up in the drop down list along with the number of times they have been executed.
- The Run prompt has the folder plugin function where we can navigate to different locations and entering the path to a directory displays all the sub-directories. To prevent reimplementing this logic, the shell plugin references the folder plugin to implement this functionality.
### Score
The Shell plugin results have a very high score of 5000. Hence, they are one of the first results in the list.

View File

@ -0,0 +1,19 @@
# URI Plugin
The URI Plugin, as the name suggests is used to dierctly run the URI that has been entered by the user as a query. This is done by parsing the entry and validating the URI, followed by executing it.
![Image of URI plugin](/doc/images/launcher/plugins/uri.png)
### [`URI Parser`](src/modules/launcher/Plugins/Microsoft.Plugin.Uri/UriHelper/ExtendedUriParser.cs)
- The [`ExtendedUriParser.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.Uri/UriHelper/ExtendedUriParser.cs) file tries to parse the user input and returns a `System.Uri` result by using the `UriBuilder`.
- It also captures other cases which the UriBuilder does not handle such as when the input ends with a `:`, `.` or `:/`.
### [`URI Resolver`](src/modules/launcher/Plugins/Microsoft.Plugin.Uri/UriHelper/UriResolver.cs)
- The [`UriResolver.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.Uri/UriHelper/UriResolver.cs) file returns true for Valid hosts.
- Currently there is no additional logic for filtering out invalid hosts and it always returns true for a valid Uri that was created by parsing the user query. It can be expanded in the future to filter out certain hosts.
### Default Browser Icon
- The icon for each uri result is that of the default browser set by the user.
- These details are obtained from the user registry and updated each time the theme of PT Run is changed.
### Score
- All uri plugin results have a score of 0 which indicates that they would show up after each of the other plugins, other than the indexer plugin which also has a score of 0.

View File

@ -0,0 +1,18 @@
# Window Walker plugin
The window walker plugin matches the user entered query with the open windows on the system.
![Image of Window Walker plugin](/doc/images/launcher/plugins/windowwalker.png)
### [`OpenWindows.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.WindowWalker/Components/OpenWindows.cs)
- The window walker plugin uses the `EnumWindows` function to enumerate all the open windows in the [`OpenWindows.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.WindowWalker/Components/OpenWindows.cs) class.
### [`SearchController.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.WindowWalker/Components/SearchController.cs)
- The [`SearchController`](src/modules/launcher/Plugins/Microsoft.Plugin.WindowWalker/Components/SearchController.cs) encapsulates the functions needed to search and find matches.
- It is responsible for updating the search text and performing a fuzzy search on all the open windows in an asynchronous manner.
### [`Window.cs`](src/modules/launcher/Plugins/Microsoft.Plugin.WindowWalker/Components/Window.cs)
- The [`Window`](src/modules/launcher/Plugins/Microsoft.Plugin.WindowWalker/Components/Window.cs) class represents a specific window and has functions to get the name of the process, the state of the window (whether it is visible or not), and the `SwitchTowindow` function which switches the desktop focus to the selected window. This action is performed when the user clicks on a window walker plugin result.
### Score
The window walker plugin uses [`FuzzyMatching`](src/modules/launcher/Plugins/Microsoft.Plugin.WindowWalker/Components/FuzzyMatching.cs) to get the matching indices and calculates the score by creating a 2 dimensional array of the window and the query text.

View File

@ -0,0 +1,24 @@
# Project Structure
## Overview
`PowerToys Run` is divided across several projects to keep a logical separation between plugins and core functionality. The following sections provide a brief overview of each project.
![Image of project dependency](/doc/images/launcher/launcher_dependency.PNG)
Fig 1. Project along with their dependencies in `PowerToys Run` ecosystem.
## Project Description
#### [`PowerLauncher`](/src/modules/launcher/PowerLauncher)
This is the startup project for the `PowerToys Run.` It is a WPF desktop application and follows the `Model-View-ViewModel (MVVM)` design pattern. Plugins play the role of `Model` and provide data to `ViewModel.`
#### [`PowerLauncher.Telemetry`](/src/modules/launcher/PowerLauncher.Telemetry)
[`PowerLauncher.Telemetry`](/src/modules/launcher/PowerLauncher.Telemetry) is a .net core project that contains telemetry events generated by `PowerLauncher.` These events have been discussed in detail [here](/doc/devdocs/modules/launcher/telemetry.md).
#### [`Wox.Core`](/src/modules/launcher/Wox.Core)
[`Wox.Core`](/src/modules/launcher/Wox.Core) is a .net core project that contains helper classes required by the `PowerLauncher` project. Two major functionalities encapsulated in this project are [`PluginManager`](/src/modules/launcher/Wox.Core/Plugin/PluginManager.cs) and [`Query Builder.`](/src/modules/launcher/Wox.Core/Plugin/QueryBuilder.cs) [`PluginManager`](/src/modules/launcher/Wox.Core/Plugin/PluginManager.cs) provides an interface for managing C# plugins. [`Query Builder.`](/src/modules/launcher/Wox.Core/Plugin/QueryBuilder.cs) decimate user-typed query string and creates a [`Query`](/src/modules/launcher/Wox.Plugin/Query.cs) object. [`Query`](/src/modules/launcher/Wox.Plugin/Query.cs) object contains the action keyword and cleaned query, which is then sent to all plugins.
#### [`Wox.Infrastructure`](/src/modules/launcher/Wox.Infrastructure)
[`Wox.Infrastructure`](/src/modules/launcher/Wox.Infrastructure) is a .net core project that contains helper classes required for logging, image manipulation, and storage by the `PowerLauncher` project and the plugins. [`ImageLoader.cs`](/src/modules/launcher/Wox.Infrastructure/Image/ImageLoader.cs) class is used to load icons for `Win32` program. It also provides caching functionality to speed up image loading for frequently queried programs. [`Log.cs`](/src/modules/launcher/Wox.Infrastructure/Logger/Log.cs) provides an abstraction for logging error, information, and output to text files. These files are stored at `%userprofile%/appdata/local/microsoft/powertoys/powertoys run/Logs.`
#### [`Wox.Plugin`](/src/modules/launcher/Wox.Plugin)
[`Wox.Plugin`](/src/modules/launcher/Wox.Plugin) contains interfaces that facilitate communication between `PowerLauncher` and plugins. These interfaces have been discussed in detail [here](/doc/devdocs/modules/launcher/architecture.md#flow-of-data-between-viewmodels-and-pluginsmodel).

View File

@ -0,0 +1,14 @@
# Table of Contents
1. [Architecture](/doc/devdocs/modules/launcher/architecture.md)
2. [Debugging](/doc/devdocs/modules/launcher/debugging.md)
3. [Project Structure](/doc/devdocs/modules/launcher/project_structure.md)
4. [Telemetry](/doc/devdocs/modules/launcher/telemetry.md)
5. Plugins
- [Overview](/doc/devdocs/modules/launcher/plugins/overview.md)
- [Calculator](/doc/devdocs/modules/launcher/plugins/calculator.md)
- [Folder](/doc/devdocs/modules/launcher/plugins/folder.md)
- [Indexer](/doc/devdocs/modules/launcher/plugins/indexer.md)
- [Program](/doc/devdocs/modules/launcher/plugins/program.md)
- [Shell](/doc/devdocs/modules/launcher/plugins/shell.md)
- [Uri](/doc/devdocs/modules/launcher/plugins/uri.md)
- [Window Walker](/doc/devdocs/modules/launcher/plugins/windowwalker.md)

View File

@ -0,0 +1,14 @@
# Telemetry
## Overview
`PowerLauncher.Telemetry` project contains telemetry events generated by `PowerToys Run.` These event classes are derived from the [`EventBase`](/src/common/ManagedTelemetry/Telemetry/Events/EventBase.cs) class and [`IEvent`](/src/common/ManagedTelemetry/Telemetry/Events/IEvent.cs) class. [`IEvent`](/src/common/ManagedTelemetry/Telemetry/Events/IEvent.cs) class provides the lowest level abstraction, containing attributes such as privacy tags needed for every telemetry data. [`EventBase`](/src/common/ManagedTelemetry/Telemetry/Events/EventBase.cs) class provides a higher-level abstraction, having attributes common to all `PowerToys` telemetry events.
## Events
The following events are generated by `PowerLauncher`:
1. [`LauncherBootEvent`](/src/modules/launcher/PowerLauncher.Telemetry/Events/LauncherBootEvent.cs): This event captures the time taken by `PowerLauncher` to load all plugins, perform cold start, and setup UI environment.
2. [`LauncherHideEvent`](/src/modules/launcher/PowerLauncher.Telemetry/Events/LauncherHideEvent.cs): This event is generated when the `PowerLauncher` window is hidden.
3. [`LauncherColdStateHotkeyEvent`](/src/modules/launcher/PowerLauncher.Telemetry/Events/LauncherColdStateHotkeyEvent.cs): This event logs time from the first Alt+Space press till the `PowerLauncher` window is visible.
4. [`LauncherFirstDeleteEvent`](/src/modules/launcher/PowerLauncher.Telemetry/Events/LauncherFirstDeleteEvent.cs): This event is generated after the first delete is pressed after `PowerLauncher` is visible.
5. [`LauncherQueryEvent`](/src/modules/launcher/PowerLauncher.Telemetry/Events/LauncherQueryEvent.cs): This event is generated for every query that is typed in the searchbox. It logs query time, number of results, and query length.
6. [`LauncherResultActionEvent`](/src/modules/launcher/PowerLauncher.Telemetry/Events/LauncherResultActionEvent.cs): This event is generated when a context menu action is triggered.
7. [`LauncherShowEvent`](/src/modules/launcher/PowerLauncher.Telemetry/Events/LauncherShowEvent.cs): This event is generated when the `PowerLauncher` window is shown.
8. [`LauncherWarmStateHotkeyEvent`](/src/modules/launcher/PowerLauncher.Telemetry/Events/LauncherWarmStateHotkeyEvent.cs): This event logs time from the Alt+Space press until the PT Run window is visible.

View File

@ -57,6 +57,7 @@ Various tools used by PowerToys. Includes the Visual Studio 2019 project templat
```shell
cd "%ProgramFiles(x86)%\Microsoft Visual Studio\2019"
SET targetFolder="\"
IF EXIST Preview\NUL (SET targetFolder=Preview)
IF EXIST Enterprise\NUL (SET targetFolder=Enterprise)
IF EXIST Professional\NUL (SET targetFolder=Professional)
IF EXIST Community\NUL (SET targetFolder=Community)

View File

@ -0,0 +1,15 @@
# Communication with modules
## Through runner
- The settings process communicates changes in the UI to most modules using the runner through delegates.
- More details on this are mentioned in [`runner-ipc.md`](settingsv2/runner-ipc.md).
## PT Run
- Any changes to the UI are saved by the settings process in the `settings.json` file located within the `/Local/Microsoft/PowerToys/Launcher/` folder.
- PT Run watches for any changes within this file and updates it's general settings or propagates the information to the plugins, depending on the type of information.
Eg: The maximum number of results drop down updates the maximum number of rows in the results list which updates the general settings of PT Run whereas the drive detection checkbox details are dispatched to the indexer plugin.
## Keyboard Manager
- The Settings process and keyboard manager share access to a common `default.json` file which contains information about the remapped keys and shortcuts.
- To ensure that there is no contention while both processes try to access the common file, there is a named file mutex.
- The settings process expects the keyboard manager process to create the `default.json` file if it does not exist. It does not create the file in case it is not present.

View File

@ -0,0 +1,12 @@
# Compatibility with legacy settings and runner
The following must be kept in mind regarding compatibility with settings v1 and runner.
### 1. Folder Naming structure
- Each of the modules has a folder within the `Local/Microsoft/PowerToys` directory which contains the module configurations within the `settings.json` file. The name of this folder must be the same across settingsv1 and settingsv2.
- The name of the settings folder for each powertoy is the same as the `ModuleName`. It is set within each of the viewModel files. This name must not be changed to ensure that the user configurations for each of the powertoys rolls over on update.
### 2. Communication with runner
- The status of each of the modules is communicated with the runner in the form of a json object. The names of all the powerToys is set in the [`EnableModules.cs`](src/core/Microsoft.PowerToys.Settings.UI.Lib/EnabledModules.cs) file. The `JsonPropertyName` must not be changed to ensure that the information is dispatched properly to all the modules by the runner.
### ImageResizer anomaly
All the powertoys have the same folder name as well as JsonPropertyName to communicate information with the runner. However that is not the case with ImageResizer. The folder name is `ImageResizer` whereas the JsonPropertyName is `Image Resizer`(Note the additional space). This should not be changed to ensure backward compatibity as well as proper functioning of the module.

View File

@ -0,0 +1,46 @@
# Custom HotKey Control
The Settings project provides a custom hotkey control which consumes key presses. This control can be used to set the hotkey of any PowerToy.
## HotKey Control in FancyZones
![Image of hotkey control](/doc/images/settingsv2/settingshotkeycontrol.png)
## Hotkey related files
#### [`HotkeySettingsControlHook.cs`](/src/core/Microsoft.PowerToys.Settings.UI.Lib/HotkeySettingsControlHook.cs)
- This function initializes and starts the [`keyboardHook`](src/common/interop/KeyboardHook.cpp) for the hotkey control.
```csharp
public HotkeySettingsControlHook(KeyEvent keyDown, KeyEvent keyUp, IsActive isActive, FilterAccessibleKeyboardEvents filterAccessibleKeyboardEvents)
{
_keyDown = keyDown;
_keyUp = keyUp;
_isActive = isActive;
_filterKeyboardEvent = filterAccessibleKeyboardEvents;
_hook = new KeyboardHook(HotkeySettingsHookCallback, IsActive, FilterKeyboardEvents);
_hook.Start();
}
```
#### [`HotkeySettingsControl.xaml.cs`](/src/core/Microsoft.PowerToys.Settings.UI/HotkeySettingsControl.xaml.cs)
- The function of this class is to update the state of the keys being pressed within the custom control. This information is stored in `internalSettings`.
- It provides the following callbacks to the `HotKeySettingsControlHook`:
- `KeyUp`: Resets the key state in `internalSettings` when a key is released.
- `KeyDown`: Updates the user facing text of the hotkey control as soon as a key is pressed.
- `isActive`: Sets the current status of the keyboard hook.
- `FilterAccessibleKeyboardEvents`: This function is used to ignore the `Tab` and `Shift+Tab` key presses to meet the accessibility requirements.
#### [`HotkeySettings.cs`](/src/core/Microsoft.PowerToys.Settings.UI.Lib/HotkeySettings.cs)
- Contains the structure of a HotKey where it is represented as a combination of one of the modifier keys (`Alt`, `Shift`, `Win` and `Ctrl`) and a non-modifier key.
#### Note
- The control displays all key presses to the user (except Tab and Shift+Tab which move focus out of the control). However, when the focus is being lost from the control, the `lastValidHotkeySettings` is set as the user facing text.

View File

@ -0,0 +1,17 @@
# Overview
`Settingsv2` is WPF .net core desktop application. It uses the `WindowsXamlHost` control from the Windows Community Toolkit to host UWP controls from `WinUI3` library. More details about WinUI can be found [here](https://microsoft.github.io/microsoft-ui-xaml/about.html#what-is-it).
## Settings V2 Project structure
The Settings project is a XAML island based project which
follows the [MVVM architectural pattern][MVVM] where the graphical user interface is separated from the view models.
#### [UI Components:](/src/core/Microsoft.PowerToys.Settings.UI)
The Settings.UI project contains the xaml files for each of the UI components. It also contains the Hotkey logic for the settings control.
#### [Viewmodels:](/src/core/Microsoft.PowerToys.Settings.UI.Lib)
The Settings.UI.Lib project contains the data that is to be rendered by the UI components.
#### [Settings Runner:](/src/core/Microsoft.PowerToys.Settings.UI.Runner)
The function of the settings runner project is to communicate all changes that the user makes in the user interface, to the runner so that it can be dispatched and reflected in all the modules.
[MVVM]: https://docs.microsoft.com/en-us/windows/uwp/data-binding/data-binding-and-mvvm

View File

@ -0,0 +1,12 @@
# Table of Contents
1. [Settings overview](/doc/devdocs/settingsv2/project-overview.md)
2. [UI Architecture](/doc/devdocs/settingsv2/ui-architecture.md)
3. [ViewModels](/doc/devdocs/settingsv2/viewmodels.md)
4. Data flow
- [Inter-Process Communication with runner](/doc/devdocs/settingsv2/runner-ipc.md)
- [Communication with modules](/doc/devdocs/settingsv2/communication-with-modules.md)
5. [Settings Utilities](/doc/devdocs/settingsv2/settings-utilities.md)
6. [Custom Hotkey control and keyboard hook handling](hotkeycontrol.md)
7. [Compatibility with legacy settings and runner](/doc/devdocs/settingsv2/compatibility-legacy-settings.md)
8. [XAML Island tweaks](/doc/devdocs/settingsv2/xaml-island-tweaks.md)
9. [Telemetry](/doc/devdocs/settingsv2/telemetry.md)

View File

@ -0,0 +1,46 @@
# Inter-Process Communication with Runner
The Settings v2 process uses two way IPC to communicate with the runner process.
## Initialization
- On the settings' side, the two way IPC delegates are contained with the [`ShellPage.xaml.cs`](/src/core/Microsoft.PowerToys.Settings.UI/Views/ShellPage.xaml.cs) file. The delegates are static and the views for all the powerToys send the ipc information to the viewmodels as `ShellPage.DefaultSndMSGCallBack`.
- These delegates are initialized within the [`Mainwindow.xaml.cs`](/src/core/Microsoft.PowerToys.Settings.UI.Runner/MainWindow.xaml.cs) file in the `Settings.Runner` project.
## Types of IPC delegates
- There are three types of delegates for the settings to communicate with the runner:
1. `SendDefaultMessage` - This is used by all the viewmodels to communicate changes in the UI to the runner so that the information can be dispatched to the modules.
2. `RestartAsAdmin`
3. `CheckForUpdates`
## Sending information to runner
- The settings process communicates with the runner by using the delegates defined within the [`ShellPage.xaml.cs`](/src/core/Microsoft.PowerToys.Settings.UI/Views/ShellPage.xaml.cs) file.
- Depending on the type of object sending the information, the json is created accordingly.
- If any information has been modified by the user in the GeneralSettings page, then the json file sent to the runner has the name set to `general`, whereas if any information has been modified by the user in any powertoy related settings page, the name of the json file being communicated with the runner is set to `powertoy`.
## Receiving information from runner
- The `ShellPage`object has a `IPCResponseHandleList` which is a list of functions which handle IPC responses.
```csharp
// receive IPC Message
Program.IPCMessageReceivedCallback = (string msg) =>
{
if (ShellPage.ShellHandler.IPCResponseHandleList != null)
{
try
{
JsonObject json = JsonObject.Parse(msg);
foreach (Action<JsonObject> handle in ShellPage.ShellHandler.IPCResponseHandleList)
{
handle(json);
}
}
catch (Exception)
{
}
}
};
```
- Whenever any information is sent from the runner each of the functions in the handle list perform their action on that json object.
- One example of where information sent from the runner is being processed by the settings is in [`GeneralPage.xaml.cs`](/src/core/Microsoft.PowerToys.Settings.UI/Views/GeneralPage.xaml.cs) when the user clicks the check for updates button. The information displayed after, such as the user has the latest version installed is a result of this handle.

View File

@ -0,0 +1,13 @@
# Settings Utilities
- Abstractions for each of the file/folder related operations are present in [`SettingsUtils.cs`](src/core/Microsoft.PowerToys.Settings.UI.Lib/SettingsUtils.cs).
- To reduce contention between the settings process and runner while trying to access the `settings.json` file of any powertoy, the settings process tries to access the file only when it needs to load the information for the first time. However, there is still no mechanism in place which ensures that both the settings and runner processes do not access the information simultaneously leading to `IOExceptions`.
## Utilities
### `GetSettings<T>(powertoy, filename)`
- The GetSettings function tries to read the file in the powertoy settings folder and creates a new file with default configurations if it does not exist.
- Ideally this function should only be called by the [`SettingsRepository`](src/core/Microsoft.PowerToys.Settings.UI.Lib/SettingsRepository`1.cs) which would be accessed only when a powertoy settings object is being loaded for the first time.
- The reason behind ensuring that it is not accessed elsewhere is to avoid contention with the runner during file access.
- Each of the objects which are deserialized using this function must implement the `ISettingsConfig` interface.

View File

@ -0,0 +1,8 @@
# Telemetry
## Overview
[`Microsoft.PowerToys.Settings.UI.Lib/Telemetry`](/src/core/Microsoft.PowerToys.Settings.UI.Lib/Telemetry) contains telemetry events generated by `Settingsv2.` These event classes are derived from the [`EventBase`](/src/common/ManagedTelemetry/Telemetry/Events/EventBase.cs) class and [`IEvent`](/src/common/ManagedTelemetry/Telemetry/Events/IEvent.cs) class. [`IEvent`](/src/common/ManagedTelemetry/Telemetry/Events/IEvent.cs) class provides the lowest level abstraction, containing attributes such as privacy tags needed for every telemetry data. [`EventBase`](/src/common/ManagedTelemetry/Telemetry/Events/EventBase.cs) class provides a higher-level abstraction, having attributes common to all `PowerToys` telemetry events.
## Events
The following events are generated by `Settingsv2`:
1. [`SettingsBootEvent`](/src/core/Microsoft.PowerToys.Settings.UI.Lib/Telemetry/Events/SettingsBootEvent.cs): This event captures the time taken by `Settingsv2` to initialize `MainWindow` UI control.
2. [`SettingsEnabledEvent.cs`](/src/core/Microsoft.PowerToys.Settings.UI.Lib/Telemetry/Events/SettingsEnabledEvent.cs): This event is generated when a module is enabled or disabled.

View File

@ -0,0 +1,9 @@
# UI Architecture
The UI code is distributed between two projects: [`Microsoft.PowerToys.Settings.UI.Runner`](/src/core/Microsoft.PowerToys.Settings.UI.Runner) and [`Microsoft.PowerToys.Settings.UI`](/src/core/Microsoft.PowerToys.Settings.UI.Lib). [`Microsoft.PowerToys.Settings.UI.Runner`](/src/core/Microsoft.PowerToys.Settings.UI.Runner) is a WPF .net core application. It contains the parent display window and corresponding code is present in [`MainWindow.xaml.`](/src/core/Microsoft.PowerToys.Settings.UI.Runner/MainWindow.xaml) [`Microsoft.PowerToys.Settings.UI`](/src/core/Microsoft.PowerToys.Settings.UI.Lib) is UWP applications and contains views for base navigation and modules. Fig 1 provides a description of the UI controls hierarchy and each of the controls have been summarized below :
- [`MainWindow.xaml`](/src/core/Microsoft.PowerToys.Settings.UI.Runner/MainWindow.xaml) is the parent WPF control.
- `WindowsXamlHost` control is used to host UWP control to [`MainWindow.xaml`](/src/core/Microsoft.PowerToys.Settings.UI.Runner/MainWindow.xaml) parent control.
- [`ShellPage.xaml`](/src/core/Microsoft.PowerToys.Settings.UI/Views/ShellPage.xaml) is a UWP control, consisting of a side navigation panel with an icon for each module. Clicking on a module icon loads the corresponding `setting.json` file and displays the data in the UI.
![Settings UI architecture](/doc/images/settingsv2/ui-architecture.png)
**Fig 1: UI Architecture for settingsv2**

View File

@ -0,0 +1,26 @@
# Viewmodels
The viewmodels are located within the [`Microsoft.PowerToys.Settings.UI.Lib`](/src/core/Microsoft.PowerToys.Settings.UI.Lib) project.
## Components
- Each viewmodel takes in the general `settingsRepository`, the `moduleSettingsRepository` if it exists and the delegates for IPC communication.
- The general `settingsRepository` contains the general configurations of all powertoys whereas the `moduleSettingsRepository` is spcific to the module. This is to ensure that the configuration details are shared amongst the viewmodels without having to re-open the `settings.json` file.
- Whenever there is a change in the UI, the `OnPropertyChanged` event is invoked and the viewmodel sends a corresponding IPC message to the runner which would perform the designated action such as dispatching the change to the modules or enabling/disabling the powertoy etc.
#### Difference between viewmodels
- The [`GeneralViewModel`](/src/core/Microsoft.PowerToys.Settings.UI.Lib/ViewModels/GeneralViewModel.cs) is different from the rest of the view models with regard to the IPC communication wherein it sends special IPC messages to the runner to check for updates and to restart as admin.
- Each of the powerToy viewmodels have two types of IPC communications, one for the general status of the powerToy and the other for communication powerToy specific change in properties to the runner.
## [`SettingsRepository`](src/core/Microsoft.PowerToys.Settings.UI.Lib/SettingsRepository`1.cs)
- The [`SettingsRepository`](src/core/Microsoft.PowerToys.Settings.UI.Lib/SettingsRepository`1.cs) is a generic singleton which contains the configurations for each viewmodel.
- As it is a generic singleton, there can only be one instance of the settings repository of a particular type. This ensures that all the viewmodels are modifying a common object and a change made in one locations reflects everywhere.
- The singleton implementation is thread-safe. Unit tests have been added for the same.
### Settings viewmodel anomalies
- The reason behind using the `SettingsRepository` is to ensure that the settings process does not try to access the `settings.json` files directly but rather does it through this class which encapsulates all the file operations from the viewmodels.
- However, this could not be expanded to all the viewmodels directly for the following reasons. Some refactoring must be done to unify these cases and to bring them under the same model:
- The PowerRename viewodel does not save the settings configurations in the same format as the rest of the powertoys, ie. {name, version, properties}. However, it only stores the properties directly.
- Some viewmodels expect the runner to create the file instead of creating the file themselves, like in keyboard manager.
- The colorpicker powertoy creates the `settings.json` within the module. This must be taken care of when encapsulated within the settingsRepository.
- Currently, all modules use the `SettingsRepository` to access the General Settings config.
- However, only Fancyzones, ShortcutGuide and PowerPreview use the `SettingsRepository` to access the module properties.

View File

@ -0,0 +1,30 @@
# XAML Island Tweaks
Few tweaks were made to fix issues with Xaml Islands. These tweaks should be removed after migrating to WINUI3. The tweaks are listed below:
1. Workaround to ensure XAML Island application terminates if attempted to close from taskbar while minimized:
```
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
isOpen = false;
// XAML Islands: If the window is closed while minimized, exit the process. Required to avoid process not terminating issue - https://github.com/microsoft/PowerToys/issues/4430
if (WindowState == WindowState.Minimized)
{
// Run Environment.Exit on a separate task to avoid performance impact
System.Threading.Tasks.Task.Run(() => { Environment.Exit(0); });
}
}
```
2. Workaround to hide the XAML Island blank icon in the taskbar when the XAML Island application is loading:
```
var coreWindow = Windows.UI.Core.CoreWindow.GetForCurrentThread();
var coreWindowInterop = Interop.GetInterop(coreWindow);
Interop.ShowWindow(coreWindowInterop.WindowHandle, Interop.SW_HIDE);
```
3. Workaround to prevent XAML Island failing to render on Nvidia workstation graphics cards:
```
// XAML Islands: If the window is open, explicity force it to be shown to solve the blank dialog issue https://github.com/microsoft/PowerToys/issues/3384
if (isOpen)
{
Show();
}
```

View File

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 53 KiB

View File

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 27 KiB

View File

Before

Width:  |  Height:  |  Size: 5.7 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 455 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

View File

@ -9,6 +9,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "common", "..\..\src\common\
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bootstrapper", "bootstrapper\bootstrapper.vcxproj", "{D194E3AA-F824-4CA9-9A58-034DD6B7D022}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "logging", "..\..\src\logging\logging.vcxproj", "{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@ -27,6 +29,10 @@ Global
{D194E3AA-F824-4CA9-9A58-034DD6B7D022}.Debug|x64.Build.0 = Debug|x64
{D194E3AA-F824-4CA9-9A58-034DD6B7D022}.Release|x64.ActiveCfg = Release|x64
{D194E3AA-F824-4CA9-9A58-034DD6B7D022}.Release|x64.Build.0 = Release|x64
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}.Debug|x64.ActiveCfg = Debug|x64
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}.Debug|x64.Build.0 = Debug|x64
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}.Release|x64.ActiveCfg = Release|x64
{7E1E3F13-2BD6-3F75-A6A7-873A2B55C60F}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -10,16 +10,22 @@
#include <common/appMutex.h>
#include <common/processApi.h>
#include <runner/action_runner_utils.h>
extern "C" IMAGE_DOS_HEADER __ImageBase;
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
namespace
{
const wchar_t APPLICATION_ID[] = L"PowerToysInstaller";
const wchar_t TOAST_TAG[] = L"PowerToysInstallerProgress";
const char LOG_FILENAME[] = "powertoys-bootstrapper-" STR(VERSION_MAJOR) "." STR(VERSION_MINOR) "." STR(VERSION_REVISION) ".log";
const char MSI_LOG_FILENAME[] = "powertoys-bootstrapper-msi-" STR(VERSION_MAJOR) "." STR(VERSION_MINOR) "." STR(VERSION_REVISION) ".log";
}
#undef STR
#undef STR_HELPER
namespace localized_strings
{
@ -59,63 +65,89 @@ std::optional<fs::path> extractIcon()
return iconRes->saveAsFile(icoPath) ? std::make_optional(std::move(icoPath)) : std::nullopt;
}
enum class CmdArgs
void setup_log(const spdlog::level::level_enum severity)
{
silent,
noFullUI,
noStartPT,
skipDotnetInstall,
showHelp
};
namespace
{
const std::unordered_map<std::wstring_view, CmdArgs> knownArgs = {
{ L"--help", CmdArgs::showHelp },
{ L"--no_full_ui", CmdArgs::noFullUI },
{ L"--silent", CmdArgs::silent },
{ L"--no_start_pt", CmdArgs::noStartPT },
{ L"--skip_dotnet_install", CmdArgs::skipDotnetInstall }
};
}
std::unordered_set<CmdArgs> parseCmdArgs(const int nCmdArgs, LPWSTR* argList)
{
std::unordered_set<CmdArgs> result;
for (size_t i = 1; i < nCmdArgs; ++i)
try
{
if (auto it = knownArgs.find(argList[i]); it != end(knownArgs))
std::shared_ptr<spdlog::logger> logger;
if (severity != spdlog::level::off)
{
result.emplace(it->second);
logger = spdlog::basic_logger_mt("file", LOG_FILENAME);
std::error_code _;
const DWORD msiSev = severity == spdlog::level::debug ? INSTALLLOGMODE_VERBOSE : INSTALLLOGMODE_ERROR;
const auto msiLogPath = fs::current_path(_) / MSI_LOG_FILENAME;
MsiEnableLogW(msiSev, msiLogPath.c_str(), INSTALLLOGATTRIBUTES_APPEND);
}
else
{
logger = spdlog::null_logger_mt("null");
}
logger->set_pattern("[%L][%d-%m-%C-%T] %v");
logger->set_level(severity);
spdlog::set_default_logger(std::move(logger));
spdlog::set_level(severity);
spdlog::flush_every(std::chrono::seconds(5));
}
catch (...)
{
}
return result;
}
int bootstrapper()
{
using namespace localized_strings;
winrt::init_apartment();
int nCmdArgs = 0;
LPWSTR* argList = CommandLineToArgvW(GetCommandLineW(), &nCmdArgs);
const auto cmdArgs = parseCmdArgs(nCmdArgs, argList);
std::wostringstream oss;
if (cmdArgs.contains(CmdArgs::showHelp))
cxxopts::Options options{ "PowerToysBootstrapper" };
// clang-format off
options.add_options()
("h,help", "Show help")
("no_full_ui", "Use reduced UI for MSI")
("s,silent", "Suppress MSI UI and notifications")
("no_start_pt", "Do not launch PowerToys after the installation is complete")
("skip_dotnet_install", "Skip dotnet 3.X installation even if it's not detected")
("log_level", "Log level. Possible values: off|debug|error", cxxopts::value<std::string>()->default_value("off"));
// clang-format on
cxxopts::ParseResult cmdArgs;
options.allow_unrecognised_options();
try
{
oss << "Supported arguments:\n\n";
for (auto [arg, _] : knownArgs)
{
oss << arg << '\n';
}
MessageBoxW(nullptr, oss.str().c_str(), L"Help", MB_OK | MB_ICONINFORMATION);
cmdArgs = options.parse(__argc, const_cast<const char**>(__argv));
}
catch (...)
{
}
const bool showHelp = cmdArgs["help"].as<bool>();
const bool noFullUI = cmdArgs["no_full_ui"].as<bool>();
const bool silent = cmdArgs["silent"].as<bool>();
const bool skipDotnetInstall = cmdArgs["skip_dotnet_install"].as<bool>();
const bool noStartPT = cmdArgs["no_start_pt"].as<bool>();
const auto logLevel = cmdArgs["log_level"].as<std::string>();
spdlog::level::level_enum severity = spdlog::level::off;
if (logLevel == "debug")
{
severity = spdlog::level::debug;
}
else if (logLevel == "error")
{
severity = spdlog::level::err;
}
setup_log(severity);
if (showHelp)
{
std::ostringstream helpMsg;
helpMsg << options.help();
MessageBoxA(nullptr, helpMsg.str().c_str(), "Help", MB_OK | MB_ICONINFORMATION);
return 0;
}
if (!cmdArgs.contains(CmdArgs::noFullUI))
spdlog::debug("PowerToys Bootstrapper is launched!\nnoFullUI: {}\nsilent: {}\nno_start_pt: {}\nskip_dotnet_install: {}\nlog_level: {}", noFullUI, silent, noStartPT, skipDotnetInstall, logLevel);
if (!noFullUI)
{
MsiSetInternalUI(INSTALLUILEVEL_FULL, nullptr);
}
if (cmdArgs.contains(CmdArgs::silent))
if (silent)
{
if (is_process_elevated())
{
@ -123,8 +155,12 @@ int bootstrapper()
}
else
{
// MSI fails to run in silent mode due to a suppressed UAC w/o elevation, so we restart elevated
spdlog::debug("MSI doesn't support silent mode without elevation => restarting elevated");
// MSI fails to run in silent mode due to a suppressed UAC w/o elevation,
// so we restart ourselves elevated with the same args
std::wstring params;
int nCmdArgs = 0;
LPWSTR* argList = CommandLineToArgvW(GetCommandLineW(), &nCmdArgs);
for (int i = 1; i < nCmdArgs; ++i)
{
params += argList[i];
@ -136,6 +172,7 @@ int bootstrapper()
const auto processHandle = run_elevated(argList[0], params.c_str());
if (!processHandle)
{
spdlog::error("Couldn't restart elevated to enable silent mode! ({})", GetLastError());
return 1;
}
if (WaitForSingleObject(processHandle, 3600000) == WAIT_OBJECT_0)
@ -146,6 +183,7 @@ int bootstrapper()
}
else
{
spdlog::error("Elevated setup process timed out after 60m => using basic MSI UI ({})", GetLastError());
// Couldn't install using the completely silent mode in an hour, use basic UI.
TerminateProcess(processHandle, 0);
MsiSetInternalUI(INSTALLUILEVEL_BASIC, nullptr);
@ -163,16 +201,17 @@ int bootstrapper()
auto instanceMutex = createAppMutex(POWERTOYS_BOOTSTRAPPER_MUTEX_NAME);
if (!instanceMutex)
{
spdlog::error("Couldn't acquire PowerToys global mutex. That means setup couldn't kill PowerToys.exe process");
return 1;
}
notifications::override_application_id(APPLICATION_ID);
spdlog::debug("Extracting icon for toast notifications");
fs::path iconPath{ L"C:\\" };
if (auto extractedIcon = extractIcon())
{
iconPath = std::move(*extractedIcon);
}
spdlog::debug("Registering app id for toast notifications");
notifications::register_application_id(TOAST_TITLE, iconPath.c_str());
auto removeShortcut = wil::scope_exit([&] {
@ -186,6 +225,7 @@ int bootstrapper()
auto msi_path = updating::get_msi_package_path();
if (!msi_path.empty())
{
spdlog::error(L"Detected a newer {} version => launching its installer", installedVersion->toWstring());
MsiInstallProductW(msi_path.c_str(), nullptr);
return 0;
}
@ -196,19 +236,22 @@ int bootstrapper()
progressParams.progress = 0.0f;
progressParams.progress_title = EXTRACTING_INSTALLER;
notifications::toast_params params{ TOAST_TAG, false, std::move(progressParams) };
if (!cmdArgs.contains(CmdArgs::silent))
if (!silent)
{
spdlog::debug("Launching progress toast notification");
notifications::show_toast_with_activations({}, TOAST_TITLE, {}, {}, std::move(params));
}
auto processToasts = wil::scope_exit([&] {
spdlog::debug("Processing HWND messages for 2s so toast have time to show up");
run_message_loop(true, 2);
});
if (!cmdArgs.contains(CmdArgs::silent))
if (!silent)
{
// Worker thread to periodically increase progress and keep the progress toast from losing focus
std::thread{ [&] {
spdlog::debug("Started worker thread for progress bar update");
for (;; Sleep(3000))
{
std::scoped_lock lock{ progressLock };
@ -223,7 +266,7 @@ int bootstrapper()
}
auto updateProgressBar = [&](const float value, const wchar_t* title) {
if (cmdArgs.contains(CmdArgs::silent))
if (silent)
{
return;
}
@ -233,13 +276,15 @@ int bootstrapper()
notifications::update_progress_bar_toast(TOAST_TAG, progressParams);
};
spdlog::debug("Extracting embedded MSI installer");
const auto installerPath = extractEmbeddedInstaller();
if (!installerPath)
{
if (!cmdArgs.contains(CmdArgs::silent))
if (!silent)
{
notifications::show_toast(INSTALLER_EXTRACT_ERROR, TOAST_TITLE);
}
spdlog::error("Couldn't install the MSI installer ({})", GetLastError());
return 1;
}
auto removeExtractedInstaller = wil::scope_exit([&] {
@ -248,12 +293,22 @@ int bootstrapper()
});
updateProgressBar(.25f, UNINSTALLING_PREVIOUS_VERSION);
spdlog::debug("Acquiring existing MSI package path");
const auto package_path = updating::get_msi_package_path();
if (!package_path.empty() && !updating::uninstall_msi_version(package_path) && !cmdArgs.contains(CmdArgs::silent))
if (!package_path.empty())
{
spdlog::debug(L"Existing MSI package path: {}", package_path);
}
else
{
spdlog::debug("Existing MSI package path not found");
}
if (!package_path.empty() && !updating::uninstall_msi_version(package_path) && !silent)
{
spdlog::error("Couldn't install the existing MSI package ({})", GetLastError());
notifications::show_toast(UNINSTALL_PREVIOUS_VERSION_ERROR, TOAST_TITLE);
}
const bool installDotnet = !cmdArgs.contains(CmdArgs::skipDotnetInstall);
const bool installDotnet = !skipDotnetInstall;
if (installDotnet)
{
updateProgressBar(.5f, INSTALLING_DOTNET);
@ -261,16 +316,22 @@ int bootstrapper()
try
{
if (installDotnet &&
!updating::dotnet_is_installed() &&
!updating::install_dotnet(cmdArgs.contains(CmdArgs::silent)) &&
!cmdArgs.contains(CmdArgs::silent))
if (installDotnet)
{
notifications::show_toast(DOTNET_INSTALL_ERROR, TOAST_TITLE);
spdlog::debug("Detecting if dotnet is installed");
const bool dotnetInstalled = updating::dotnet_is_installed();
spdlog::debug("Dotnet is installed: {}", dotnetInstalled);
if (!dotnetInstalled &&
!updating::install_dotnet(silent) &&
!silent)
{
notifications::show_toast(DOTNET_INSTALL_ERROR, TOAST_TITLE);
}
}
}
catch (...)
{
spdlog::error("Unknown exception during dotnet installation");
MessageBoxW(nullptr, L".NET Core installation", L"Unknown exception encountered!", MB_OK | MB_ICONERROR);
}
@ -278,18 +339,23 @@ int bootstrapper()
// Always skip dotnet install, because we should've installed it from here earlier
std::wstring msiProps = L"SKIPDOTNETINSTALL=1 ";
spdlog::debug("Launching MSI installation for new package {}", installerPath->string());
const bool installationDone = MsiInstallProductW(installerPath->c_str(), msiProps.c_str()) == ERROR_SUCCESS;
updateProgressBar(1.f, installationDone ? NEW_VERSION_INSTALLATION_DONE : NEW_VERSION_INSTALLATION_ERROR);
if (!installationDone)
{
spdlog::error("Couldn't install new MSI package ({})", GetLastError());
return 1;
}
spdlog::debug("Installation completed");
if (!cmdArgs.contains(CmdArgs::noStartPT) && !cmdArgs.contains(CmdArgs::silent))
if (!noStartPT && !silent)
{
spdlog::debug("Starting the newly installed PowerToys.exe");
auto newPTPath = updating::get_msi_package_installed_path();
if (!newPTPath)
{
spdlog::error("Couldn't determine new MSI package install location ({})", GetLastError());
return 1;
}
*newPTPath += L"\\PowerToys.exe";

View File

@ -28,6 +28,8 @@
<ProjectName>bootstrapper</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<Import Project="..\..\..\deps\spdlog.props" />
<Import Project="..\..\..\deps\cxxopts.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
@ -78,7 +80,7 @@
<TreatWarningAsError>true</TreatWarningAsError>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<AdditionalIncludeDirectories>../../../src/</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>../../../src/;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
@ -99,7 +101,7 @@
<TreatWarningAsError>true</TreatWarningAsError>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<AdditionalIncludeDirectories>../../../src/</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>../../../src/;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
@ -137,6 +139,9 @@
<ProjectReference Include="..\..\..\src\common\updating\updating.vcxproj">
<Project>{17da04df-e393-4397-9cf0-84dabe11032e}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\src\logging\logging.vcxproj">
<Project>{7e1e3f13-2bd6-3f75-a6a7-873a2b55c60f}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">

View File

@ -14,3 +14,10 @@
#include <unordered_set>
#include <tuple>
#include <sstream>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/null_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <cxxopts.hpp>

View File

@ -219,25 +219,7 @@
<Directory Id="INSTALLFOLDER" Name="PowerToys">
<Directory Id="SvgsInstallFolder" Name="svgs"/>
<Directory Id="ModulesInstallFolder" Name="modules">
<Directory Id="ImageResizerInstallFolder" Name="$(var.ImageResizerProjectName)">
<!-- Resource file directories -->
<?foreach Language in ar;bg;ca;cs;de;es;eu-ES;fr;he;hu;it;nb-NO;nl;pl;pt-BR;ru;sk;tr;zh-Hans?>
<!--NB: Ids can't contain hyphens-->
<?if $(var.Language) = eu-ES?>
<?define IdSafeLanguage = eu_ES?>
<?elseif $(var.Language) = nb-NO?>
<?define IdSafeLanguage = nb_NO?>
<?elseif $(var.Language) = pt-BR?>
<?define IdSafeLanguage = pt_BR?>
<?elseif $(var.Language) = zh-Hans?>
<?define IdSafeLanguage = zh_Hans?>
<?else?>
<?define IdSafeLanguage = $(var.Language)?>
<?endif?>
<Directory Id="Resources$(var.IdSafeLanguage)Folder" Name="$(var.Language)" />
<?undef IdSafeLanguage?>
<?endforeach?>
</Directory>
<Directory Id="ImageResizerInstallFolder" Name="$(var.ImageResizerProjectName)" />
<Directory Id="PowerRenameInstallFolder" Name="$(var.PowerRenameProjectName)"/>
<Directory Id="ShortcutGuideInstallFolder" Name="$(var.ShortcutGuideProjectName)"/>
<Directory Id="FileExplorerPreviewInstallFolder" Name="FileExplorerPreview" />
@ -817,27 +799,95 @@
<ComponentRef Id="settings_js_bundle" />
</ComponentGroup>
</Fragment>
<!-- Languages for localization on build farm -->
<?define LocLanguageList = cs;de;es;fr;hu;it;ja;ko;nl;pl;pt-BR;pt-PT;ru;sv;tr;zh-Hans;zh-Hant?>
<Fragment>
<!-- Resource directories should be added only if the installer is built on the build farm -->
<?ifdef env.IsPipeline?>
<?foreach ParentDirectory in LauncherInstallFolder;FancyZonesInstallFolder;ImageResizerInstallFolder;ColorPickerInstallFolder;FileExplorerPreviewInstallFolder;CalculatorPluginFolder;FolderPluginFolder;ProgramPluginFolder;ShellPluginFolder;IndexerPluginFolder;UriPluginFolder;WindowWalkerPluginFolder?>
<DirectoryRef Id="$(var.ParentDirectory)">
<!-- Resource file directories -->
<?foreach Language in $(var.LocLanguageList)?>
<!--NB: Ids can't contain hyphens-->
<?if $(var.Language) = pt-BR?>
<?define IdSafeLanguage = pt_BR?>
<?elseif $(var.Language) = pt-PT?>
<?define IdSafeLanguage = pt_PT?>
<?elseif $(var.Language) = zh-Hans?>
<?define IdSafeLanguage = zh_Hans?>
<?elseif $(var.Language) = zh-Hant?>
<?define IdSafeLanguage = zh_Hant?>
<?else?>
<?define IdSafeLanguage = $(var.Language)?>
<?endif?>
<Directory Id="Resource$(var.IdSafeLanguage)$(var.ParentDirectory)" Name="$(var.Language)" />
<?undef IdSafeLanguage?>
<?endforeach?>
</DirectoryRef>
<?endforeach?>
<?endif?>
<ComponentGroup Id="ResourcesComponents">
<!-- Components for adding resource files -->
<?foreach Language in ar;bg;ca;cs;de;es;eu-ES;fr;he;hu;it;nb-NO;nl;pl;pt-BR;ru;sk;tr;zh-Hans?>
<!--NB: Ids can't contain hyphens-->
<?if $(var.Language) = eu-ES?>
<?define IdSafeLanguage = eu_ES?>
<?elseif $(var.Language) = nb-NO?>
<?define IdSafeLanguage = nb_NO?>
<?elseif $(var.Language) = pt-BR?>
<?define IdSafeLanguage = pt_BR?>
<?elseif $(var.Language) = zh-Hans?>
<?define IdSafeLanguage = zh_Hans?>
<?else?>
<?define IdSafeLanguage = $(var.Language)?>
<!-- Resource components should be added only if the installer is built on the build farm -->
<?ifdef env.IsPipeline?>
<!-- Components for adding resource files -->
<?foreach Language in $(var.LocLanguageList)?>
<!--NB: Ids can't contain hyphens-->
<?if $(var.Language) = pt-BR?>
<?define IdSafeLanguage = pt_BR?>
<?elseif $(var.Language) = pt-PT?>
<?define IdSafeLanguage = pt_PT?>
<?elseif $(var.Language) = zh-Hans?>
<?define IdSafeLanguage = zh_Hans?>
<?elseif $(var.Language) = zh-Hant?>
<?define IdSafeLanguage = zh_Hant?>
<?else?>
<?define IdSafeLanguage = $(var.Language)?>
<?endif?>
<Component Id="Launcher_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)LauncherInstallFolder">
<File Id="Launcher_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\launcher\$(var.Language)\PowerLauncher.resources.dll" />
</Component>
<Component Id="FancyZonesEditor_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)FancyZonesInstallFolder">
<File Id="FancyZonesEditor_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\$(var.FancyZonesProjectName)\$(var.Language)\FancyZonesEditor.resources.dll" />
</Component>
<Component Id="ImageResizer_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)ImageResizerInstallFolder">
<File Id="ImageResizer_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\$(var.ImageResizerProjectName)\$(var.Language)\ImageResizer.resources.dll" />
</Component>
<Component Id="ColorPicker_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)ColorPickerInstallFolder">
<File Id="ColorPicker_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\$(var.ColorPickerProjectName)\$(var.Language)\ColorPicker.resources.dll" />
</Component>
<Component Id="MarkdownPreviewHandler_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)FileExplorerPreviewInstallFolder">
<File Id="MarkdownPreviewHandler_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\FileExplorerPreview\$(var.Language)\MarkdownPreviewHandler.resources.dll" />
</Component>
<Component Id="SVGPreviewHandler_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)FileExplorerPreviewInstallFolder">
<File Id="SVGPreviewHandler_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\FileExplorerPreview\$(var.Language)\SvgPreviewHandler.resources.dll" />
</Component>
<!-- Launcher plugin resources -->
<Component Id="Launcher_Calculator_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)CalculatorPluginFolder">
<File Id="Launcher_Calculator_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\launcher\Plugins\Microsoft.Plugin.Calculator\$(var.Language)\Microsoft.Plugin.Calculator.resources.dll" />
</Component>
<Component Id="Launcher_Folder_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)FolderPluginFolder">
<File Id="Launcher_Folder_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\launcher\Plugins\Microsoft.Plugin.Folder\$(var.Language)\Microsoft.Plugin.Folder.resources.dll" />
</Component>
<Component Id="Launcher_Program_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)ProgramPluginFolder">
<File Id="Launcher_Program_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\launcher\Plugins\Microsoft.Plugin.Program\$(var.Language)\Microsoft.Plugin.Program.resources.dll" />
</Component>
<Component Id="Launcher_Shell_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)ShellPluginFolder">
<File Id="Launcher_Shell_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\launcher\Plugins\Microsoft.Plugin.Shell\$(var.Language)\Microsoft.Plugin.Shell.resources.dll" />
</Component>
<Component Id="Launcher_Indexer_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)IndexerPluginFolder">
<File Id="Launcher_Indexer_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\launcher\Plugins\Microsoft.Plugin.Indexer\$(var.Language)\Microsoft.Plugin.Indexer.resources.dll" />
</Component>
<Component Id="Launcher_Uri_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)UriPluginFolder">
<File Id="Launcher_Uri_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\launcher\Plugins\Microsoft.Plugin.Uri\$(var.Language)\Microsoft.Plugin.Uri.resources.dll" />
</Component>
<Component Id="Launcher_WindowWalker_$(var.IdSafeLanguage)_Component" Directory="Resource$(var.IdSafeLanguage)WindowWalkerPluginFolder">
<File Id="Launcher_WindowWalker_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\launcher\Plugins\Microsoft.Plugin.WindowWalker\$(var.Language)\Microsoft.Plugin.WindowWalker.resources.dll" />
</Component>
<?undef IdSafeLanguage?>
<?endforeach?>
<?endif?>
<Component Id="Resources_$(var.IdSafeLanguage)_Component" Directory="Resources$(var.IdSafeLanguage)Folder">
<File Id="Resources_ImageResizer_$(var.IdSafeLanguage)_File" Source="$(var.BinX64Dir)modules\$(var.ImageResizerProjectName)\$(var.Language)\ImageResizer.resources.dll" />
</Component>
<?undef IdSafeLanguage?>
<?endforeach?>
</ComponentGroup>
</Fragment>
<Fragment>

View File

@ -53,11 +53,12 @@ namespace UnitTestsCommonLib
private:
const std::wstring m_json = L"{\"name\":\"Module Name\",\"properties\" : {\"bool_toggle_true\":{\"value\":true},\"bool_toggle_false\":{\"value\":false},\"color_picker\" : {\"value\":\"#ff8d12\"},\"int_spinner\" : {\"value\":10},\"string_text\" : {\"value\":\"a quick fox\"}},\"version\" : \"1.0\" }";
const std::wstring m_moduleName = L"Module Name";
const std::wstring m_moduleKey = L"Module Key";
public:
TEST_METHOD (LoadFromJsonBoolTrue)
{
PowerToyValues values = PowerToyValues::from_json_string(m_json);
PowerToyValues values = PowerToyValues::from_json_string(m_json, m_moduleKey);
auto value = values.get_bool_value(L"bool_toggle_true");
Assert::IsTrue(value.has_value());
Assert::AreEqual(true, *value);
@ -65,7 +66,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (LoadFromJsonBoolFalse)
{
PowerToyValues values = PowerToyValues::from_json_string(m_json);
PowerToyValues values = PowerToyValues::from_json_string(m_json, m_moduleKey);
auto value = values.get_bool_value(L"bool_toggle_false");
Assert::IsTrue(value.has_value());
Assert::AreEqual(false, *value);
@ -73,7 +74,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (LoadFromJsonInt)
{
PowerToyValues values = PowerToyValues::from_json_string(m_json);
PowerToyValues values = PowerToyValues::from_json_string(m_json, m_moduleKey);
auto value = values.get_int_value(L"int_spinner");
Assert::IsTrue(value.has_value());
Assert::AreEqual(10, *value);
@ -81,7 +82,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (LoadFromJsonString)
{
PowerToyValues values = PowerToyValues::from_json_string(m_json);
PowerToyValues values = PowerToyValues::from_json_string(m_json, m_moduleKey);
auto value = values.get_string_value(L"string_text");
Assert::IsTrue(value.has_value());
@ -91,7 +92,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (LoadFromJsonColorPicker)
{
PowerToyValues values = PowerToyValues::from_json_string(m_json);
PowerToyValues values = PowerToyValues::from_json_string(m_json, m_moduleKey);
auto value = values.get_string_value(L"color_picker");
Assert::IsTrue(value.has_value());
@ -101,19 +102,19 @@ namespace UnitTestsCommonLib
TEST_METHOD (LoadFromEmptyString)
{
auto func = [] { PowerToyValues values = PowerToyValues::from_json_string(L""); };
auto func = [] { PowerToyValues values = PowerToyValues::from_json_string(L"", L"Module Key"); };
Assert::ExpectException<winrt::hresult_error>(func);
}
TEST_METHOD (LoadFromInvalidString_NameMissed)
{
auto func = [] { PowerToyValues values = PowerToyValues::from_json_string(L"{\"properties\" : {\"bool_toggle_true\":{\"value\":true},\"bool_toggle_false\":{\"value\":false},\"color_picker\" : {\"value\":\"#ff8d12\"},\"int_spinner\" : {\"value\":10},\"string_text\" : {\"value\":\"a quick fox\"}},\"version\" : \"1.0\" }"); };
auto func = [] { PowerToyValues values = PowerToyValues::from_json_string(L"{\"properties\" : {\"bool_toggle_true\":{\"value\":true},\"bool_toggle_false\":{\"value\":false},\"color_picker\" : {\"value\":\"#ff8d12\"},\"int_spinner\" : {\"value\":10},\"string_text\" : {\"value\":\"a quick fox\"}},\"version\" : \"1.0\" }", L"Module Key"); };
Assert::ExpectException<winrt::hresult_error>(func);
}
TEST_METHOD (LoadFromInvalidString_VersionMissed)
{
PowerToyValues values = PowerToyValues::from_json_string(L"{\"name\":\"Module Name\",\"properties\" : {}}");
PowerToyValues values = PowerToyValues::from_json_string(L"{\"name\":\"Module Name\",\"properties\" : {}}", L"Module Key");
const std::wstring expectedStr = L"{\"name\" : \"Module Name\", \"properties\" : {},\"version\" : \"1.0\"}";
const auto expected = json::JsonObject::Parse(expectedStr);
const auto actual = json::JsonObject::Parse(values.serialize());
@ -123,7 +124,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (LoadFromInvalidString_PropertiesMissed)
{
PowerToyValues values = PowerToyValues::from_json_string(L"{\"name\":\"Module Name\",\"version\" : \"1.0\" }");
PowerToyValues values = PowerToyValues::from_json_string(L"{\"name\":\"Module Name\",\"version\" : \"1.0\" }", L"Module Key");
const std::wstring expectedStr = L"{\"name\":\"Module Name\",\"version\" : \"1.0\" }";
const auto expected = json::JsonObject::Parse(expectedStr);
const auto actual = json::JsonObject::Parse(values.serialize());
@ -133,7 +134,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (LoadFromValidString_EmptyProperties)
{
PowerToyValues values = PowerToyValues::from_json_string(L"{\"name\":\"Module Name\",\"properties\" : {}, \"version\" : \"1.0\" }");
PowerToyValues values = PowerToyValues::from_json_string(L"{\"name\":\"Module Name\",\"properties\" : {}, \"version\" : \"1.0\" }", L"Module Key");
const std::wstring expectedStr = L"{\"name\":\"Module Name\",\"properties\" : {},\"version\" : \"1.0\" }";
const auto expected = json::JsonObject::Parse(expectedStr);
const auto actual = json::JsonObject::Parse(values.serialize());
@ -143,7 +144,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (LoadFromValidString_ChangedVersion)
{
PowerToyValues values = PowerToyValues::from_json_string(L"{\"name\":\"Module Name\",\"properties\" : {},\"version\" : \"2.0\"}");
PowerToyValues values = PowerToyValues::from_json_string(L"{\"name\":\"Module Name\",\"properties\" : {},\"version\" : \"2.0\"}", L"Module Key");
const std::wstring expectedStr = L"{\"name\" : \"Module Name\", \"properties\" : {},\"version\" : \"1.0\"}"; //version from input json is ignored
const auto expected = json::JsonObject::Parse(expectedStr);
@ -154,7 +155,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (CreateWithName)
{
PowerToyValues values(m_moduleName);
PowerToyValues values(m_moduleName, m_moduleKey);
const std::wstring expectedStr = L"{\"name\":\"Module Name\",\"properties\" : {},\"version\" : \"1.0\" }";
const auto expected = json::JsonObject::Parse(expectedStr);
@ -165,7 +166,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (AddPropertyBoolPositive)
{
PowerToyValues values(m_moduleName);
PowerToyValues values(m_moduleName, m_moduleKey);
values.add_property<bool>(L"positive_bool_value", true);
auto value = values.get_bool_value(L"positive_bool_value");
@ -175,7 +176,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (AddPropertyBoolNegative)
{
PowerToyValues values(m_moduleName);
PowerToyValues values(m_moduleName, m_moduleKey);
values.add_property<bool>(L"negative_bool_value", false);
auto value = values.get_bool_value(L"negative_bool_value");
@ -185,7 +186,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (AddPropertyIntPositive)
{
PowerToyValues values(m_moduleName);
PowerToyValues values(m_moduleName, m_moduleKey);
const int intVal = 4392854;
values.add_property<int>(L"integer", intVal);
@ -196,7 +197,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (AddPropertyIntNegative)
{
PowerToyValues values(m_moduleName);
PowerToyValues values(m_moduleName, m_moduleKey);
const int intVal = -4392854;
values.add_property<int>(L"integer", intVal);
@ -207,7 +208,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (AddPropertyIntZero)
{
PowerToyValues values(m_moduleName);
PowerToyValues values(m_moduleName, m_moduleKey);
const int intVal = 0;
values.add_property<int>(L"integer", intVal);
@ -218,7 +219,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (AddPropertyStringEmpty)
{
PowerToyValues values(m_moduleName);
PowerToyValues values(m_moduleName, m_moduleKey);
const std::wstring stringVal = L"";
values.add_property<std::wstring>(L"stringval", stringVal);
@ -229,7 +230,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (AddPropertyString)
{
PowerToyValues values(m_moduleName);
PowerToyValues values(m_moduleName, m_moduleKey);
const std::wstring stringVal = L"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
values.add_property<std::wstring>(L"stringval", stringVal);
@ -240,7 +241,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (AddPropertyJsonEmpty)
{
PowerToyValues values(m_moduleName);
PowerToyValues values(m_moduleName, m_moduleKey);
const auto json = json::JsonObject();
values.add_property<json::JsonObject>(L"jsonval", json);
@ -251,7 +252,7 @@ namespace UnitTestsCommonLib
TEST_METHOD (AddPropertyJsonObject)
{
PowerToyValues values(m_moduleName);
PowerToyValues values(m_moduleName, m_moduleKey);
const auto json = json::JsonObject::Parse(m_json);
values.add_property<json::JsonObject>(L"jsonval", json);

View File

@ -60,7 +60,10 @@ LRESULT __clrcall KeyboardHook::HookProc(int nCode, WPARAM wParam, LPARAM lParam
KeyboardEvent ^ ev = gcnew KeyboardEvent();
ev->message = wParam;
ev->key = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam)->vkCode;
if (filterKeyboardEvent != nullptr && !filterKeyboardEvent->Invoke(ev))
ev->dwExtraInfo = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam)->dwExtraInfo;
// Ignore the keyboard hook if the FilterkeyboardEvent returns false.
if ((filterKeyboardEvent != nullptr && !filterKeyboardEvent->Invoke(ev)))
{
return CallNextHookEx(hookHandle, nCode, wParam, lParam);
}

View File

@ -1,5 +1,7 @@
#pragma once
#include <cinttypes>
using namespace System::Threading;
using namespace System::Collections::Generic;
@ -10,6 +12,7 @@ public
{
WPARAM message;
int key;
uint64_t dwExtraInfo;
};
public

View File

@ -98,6 +98,8 @@
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</MultiProcessorCompilation>
<MultiProcessorCompilation Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</MultiProcessorCompilation>
<TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</TreatWarningAsError>
<TreatWarningAsError Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</TreatWarningAsError>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>

View File

@ -27,7 +27,7 @@ std::vector<DWORD> LayoutMap::GetKeyCodeList(const bool isShortcut)
return impl->GetKeyCodeList(isShortcut);
}
std::vector<std::wstring> LayoutMap::GetKeyNameList(const bool isShortcut)
std::vector<std::pair<DWORD, std::wstring>> LayoutMap::GetKeyNameList(const bool isShortcut)
{
return impl->GetKeyNameList(isShortcut);
}
@ -215,6 +215,7 @@ void LayoutMap::LayoutMapImpl::UpdateLayout()
keyboardLayoutMap[VK_NONCONVERT] = L"IME Non-Convert";
keyboardLayoutMap[VK_ACCEPT] = L"IME Kana";
keyboardLayoutMap[VK_MODECHANGE] = L"IME Mode Change";
keyboardLayoutMap[CommonSharedConstants::VK_DISABLED] = L"Disable";
}
// Function to return the list of key codes in the order for the drop down. It creates it if it doesn't exist
@ -304,25 +305,25 @@ std::vector<DWORD> LayoutMap::LayoutMapImpl::GetKeyCodeList(const bool isShortcu
return keyCodes;
}
std::vector<std::wstring> LayoutMap::LayoutMapImpl::GetKeyNameList(const bool isShortcut)
std::vector<std::pair<DWORD, std::wstring>> LayoutMap::LayoutMapImpl::GetKeyNameList(const bool isShortcut)
{
std::vector<std::wstring> keyNames;
std::vector<std::pair<DWORD, std::wstring>> keyNames;
std::vector<DWORD> keyCodes = GetKeyCodeList(isShortcut);
std::lock_guard<std::mutex> lock(keyboardLayoutMap_mutex);
// If it is a key list for the shortcut control then we add a "None" key at the start
if (isShortcut)
{
keyNames.push_back(L"None");
keyNames.push_back({ 0, L"None" });
for (int i = 1; i < keyCodes.size(); i++)
{
keyNames.push_back(keyboardLayoutMap[keyCodes[i]]);
keyNames.push_back({ keyCodes[i], keyboardLayoutMap[keyCodes[i]] });
}
}
else
{
for (int i = 0; i < keyCodes.size(); i++)
{
keyNames.push_back(keyboardLayoutMap[keyCodes[i]]);
keyNames.push_back({ keyCodes[i], keyboardLayoutMap[keyCodes[i]] });
}
}

View File

@ -12,7 +12,7 @@ public:
void UpdateLayout();
std::wstring GetKeyName(DWORD key);
std::vector<DWORD> GetKeyCodeList(const bool isShortcut = false);
std::vector<std::wstring> GetKeyNameList(const bool isShortcut = false);
std::vector<std::pair<DWORD, std::wstring>> GetKeyNameList(const bool isShortcut = false);
private:
class LayoutMapImpl;

View File

@ -46,6 +46,6 @@ public:
// Function to return the list of key codes in the order for the drop down. It creates it if it doesn't exist
std::vector<DWORD> GetKeyCodeList(const bool isShortcut);
// Function to return the list of key name in the order for the drop down based on the key codes
std::vector<std::wstring> GetKeyNameList(const bool isShortcut);
// Function to return the list of key name pairs in the order for the drop down based on the key codes
std::vector<std::pair<DWORD, std::wstring>> GetKeyNameList(const bool isShortcut);
};

View File

@ -16,6 +16,14 @@ std::future<void> OnThreadExecutor::submit(task_t task)
return future;
}
void OnThreadExecutor::cancel()
{
std::lock_guard lock{ _task_mutex };
_task_queue = {};
_task_cv.notify_one();
}
void OnThreadExecutor::worker_thread()
{
while (!_shutdown_request)

View File

@ -18,6 +18,7 @@ public:
OnThreadExecutor();
~OnThreadExecutor();
std::future<void> submit(task_t task);
void cancel();
private:
void worker_thread();

View File

@ -23,11 +23,11 @@ namespace PTSettingsHelper
return result;
}
std::wstring get_module_save_folder_location(std::wstring_view powertoy_name)
std::wstring get_module_save_folder_location(std::wstring_view powertoy_key)
{
std::wstring result = get_root_save_folder_location();
result += L"\\";
result += powertoy_name;
result += powertoy_key;
std::filesystem::path save_path(result);
if (!std::filesystem::exists(save_path))
{
@ -36,9 +36,9 @@ namespace PTSettingsHelper
return result;
}
std::wstring get_module_save_file_location(std::wstring_view powertoy_name)
std::wstring get_module_save_file_location(std::wstring_view powertoy_key)
{
return get_module_save_folder_location(powertoy_name) + settings_filename;
return get_module_save_folder_location(powertoy_key) + settings_filename;
}
std::wstring get_powertoys_general_save_file_location()
@ -46,15 +46,15 @@ namespace PTSettingsHelper
return get_root_save_folder_location() + settings_filename;
}
void save_module_settings(std::wstring_view powertoy_name, json::JsonObject& settings)
void save_module_settings(std::wstring_view powertoy_key, json::JsonObject& settings)
{
const std::wstring save_file_location = get_module_save_file_location(powertoy_name);
const std::wstring save_file_location = get_module_save_file_location(powertoy_key);
json::to_file(save_file_location, settings);
}
json::JsonObject load_module_settings(std::wstring_view powertoy_name)
json::JsonObject load_module_settings(std::wstring_view powertoy_key)
{
const std::wstring save_file_location = get_module_save_file_location(powertoy_name);
const std::wstring save_file_location = get_module_save_file_location(powertoy_key);
auto saved_settings = json::from_file(save_file_location);
return saved_settings.has_value() ? std::move(*saved_settings) : json::JsonObject{};
}

View File

@ -1,6 +1,7 @@
#include "pch.h"
#include "settings_objects.h"
#include "settings_helpers.h"
#include <winrt/base.h>
namespace PowerToysSettings
{
@ -277,27 +278,33 @@ namespace PowerToysSettings
return L"RESOURCE ID NOT FOUND: " + std::to_wstring(resource_id);
}
PowerToyValues::PowerToyValues(std::wstring_view powertoy_name)
PowerToyValues::PowerToyValues(std::wstring_view powertoy_name, std::wstring_view powertoy_key)
{
_name = powertoy_name;
_key = powertoy_key;
set_version();
m_json.SetNamedValue(L"name", json::value(powertoy_name));
m_json.SetNamedValue(L"properties", json::JsonObject{});
}
PowerToyValues PowerToyValues::from_json_string(std::wstring_view json)
PowerToyValues PowerToyValues::from_json_string(std::wstring_view json, std::wstring_view powertoy_key)
{
PowerToyValues result = PowerToyValues();
json::JsonObject jsonObject = json::JsonValue::Parse(json).GetObjectW();
if (!jsonObject.HasKey(L"name"))
{
throw winrt::hresult_error(E_NOT_SET, L"name field not set");
}
result.m_json = json::JsonValue::Parse(json).GetObjectW();
result._name = result.m_json.GetNamedString(L"name");
result._key = powertoy_key;
return result;
}
PowerToyValues PowerToyValues::load_from_settings_file(std::wstring_view powertoy_name)
PowerToyValues PowerToyValues::load_from_settings_file(std::wstring_view powertoy_key)
{
PowerToyValues result = PowerToyValues();
result.m_json = PTSettingsHelper::load_module_settings(powertoy_name);
result._name = powertoy_name;
result.m_json = PTSettingsHelper::load_module_settings(powertoy_key);
result._key = powertoy_key;
return result;
}
@ -357,7 +364,7 @@ namespace PowerToysSettings
void PowerToyValues::save_to_settings_file()
{
set_version();
PTSettingsHelper::save_module_settings(_name, m_json);
PTSettingsHelper::save_module_settings(_key, m_json);
}
void PowerToyValues::set_version()

View File

@ -67,9 +67,9 @@ namespace PowerToysSettings
class PowerToyValues
{
public:
PowerToyValues(std::wstring_view powertoy_name);
static PowerToyValues from_json_string(std::wstring_view json);
static PowerToyValues load_from_settings_file(std::wstring_view powertoy_name);
PowerToyValues(std::wstring_view powertoy_name, std::wstring_view powertoy_key);
static PowerToyValues from_json_string(std::wstring_view json, std::wstring_view powertoy_key);
static PowerToyValues load_from_settings_file(std::wstring_view powertoy_key);
template<typename T>
inline void add_property(std::wstring_view name, T value)
@ -92,7 +92,7 @@ namespace PowerToysSettings
const std::wstring m_version = L"1.0";
void set_version();
json::JsonObject m_json;
std::wstring _name;
std::wstring _key;
PowerToyValues() {}
};

View File

@ -11,4 +11,7 @@ namespace CommonSharedConstants
// Path to the event used by PowerLauncher
const wchar_t POWER_LAUNCHER_SHARED_EVENT[] = L"Local\\PowerToysRunInvokeEvent-30f26ad7-d36d-4c0e-ab02-68bb5ff3c4ab";
}
// Max DWORD for key code to disable keys.
const DWORD VK_DISABLED = 0x100;
}

View File

@ -102,6 +102,11 @@ namespace updating
std::future<std::optional<new_version_download_info>> get_new_github_version_info_async()
{
// If the current version starts with 0.0.*, it means we're on a local build from a farm and shouldn't check for updates.
if (VERSION_MAJOR == 0 && VERSION_MINOR == 0)
{
co_return std::nullopt;
}
try
{
http::HttpClient client;

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;
using System.Collections.Generic;
using System.Text.Json.Serialization;
@ -12,19 +13,27 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
[JsonPropertyName("targetApp")]
public string TargetApp { get; set; }
public new List<string> GetOriginalKeys()
public new List<string> GetMappedOriginalKeys()
{
return base.GetOriginalKeys();
return base.GetMappedOriginalKeys();
}
public new List<string> GetNewRemapKeys()
public new List<string> GetMappedNewRemapKeys()
{
return base.GetNewRemapKeys();
return base.GetMappedNewRemapKeys();
}
public bool Compare(AppSpecificKeysDataModel arg)
{
return OriginalKeys.Equals(arg.OriginalKeys) && NewRemapKeys.Equals(arg.NewRemapKeys) && TargetApp.Equals(arg.TargetApp);
if (arg == null)
{
throw new ArgumentNullException(nameof(arg));
}
// Using Ordinal comparison for internal text
return OriginalKeys.Equals(arg.OriginalKeys, StringComparison.Ordinal) &&
NewRemapKeys.Equals(arg.NewRemapKeys, StringComparison.Ordinal) &&
TargetApp.Equals(arg.TargetApp, StringComparison.Ordinal);
}
}
}

View File

@ -5,11 +5,11 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Lib.Utilities;
using Microsoft.PowerToys.Settings.UI.Lib.Interface;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class ColorPickerSettings : BasePTModuleSettings
public class ColorPickerSettings : BasePTModuleSettings, ISettingsConfig
{
public const string ModuleName = "ColorPicker";
@ -31,7 +31,23 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
WriteIndented = true,
};
if (settingsUtils == null)
{
throw new ArgumentNullException(nameof(settingsUtils));
}
settingsUtils.SaveSettings(JsonSerializer.Serialize(this, options), ModuleName);
}
public string GetModuleName()
{
return Name;
}
// This can be utilized in the future if the settings.json file is to be modified/deleted.
public bool UpgradeSettingsConfiguration()
{
return false;
}
}
}

View File

@ -25,7 +25,8 @@ namespace Microsoft.PowerToys.Settings.UI.Lib.CustomAction
{
PropertyNamingPolicy = new CustomNamePolicy((propertyName) =>
{
return propertyName.Equals("ModuleAction") ? moduleName : propertyName;
// Using Ordinal as this is an internal property name
return propertyName.Equals("ModuleAction", System.StringComparison.Ordinal) ? moduleName : propertyName;
}),
};

View File

@ -148,7 +148,7 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
return JsonSerializer.Serialize(this);
}
private void LogTelemetryEvent(bool value, [CallerMemberName] string moduleName = null)
private static void LogTelemetryEvent(bool value, [CallerMemberName] string moduleName = null)
{
var dataEvent = new SettingsEnabledEvent()
{

View File

@ -3,19 +3,33 @@
// See the LICENSE file in the project root for more information.
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Lib.Interface;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class FancyZonesSettings : BasePTModuleSettings
public class FancyZonesSettings : BasePTModuleSettings, ISettingsConfig
{
public const string ModuleName = "FancyZones";
public FancyZonesSettings()
{
Version = string.Empty;
Name = string.Empty;
Version = "1.0";
Name = ModuleName;
Properties = new FZConfigProperties();
}
[JsonPropertyName("properties")]
public FZConfigProperties Properties { get; set; }
public string GetModuleName()
{
return Name;
}
// This can be utilized in the future if the settings.json file is to be modified/deleted.
public bool UpgradeSettingsConfiguration()
{
return false;
}
}
}

View File

@ -2,12 +2,15 @@
// 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.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Lib.Interface;
using Microsoft.PowerToys.Settings.UI.Lib.Utilities;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class GeneralSettings
public class GeneralSettings : ISettingsConfig
{
// Gets or sets a value indicating whether packaged.
[JsonPropertyName("packaged")]
@ -78,9 +81,36 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
return JsonSerializer.Serialize(this);
}
private string DefaultPowertoysVersion()
private static string DefaultPowertoysVersion()
{
return interop.CommonManaged.GetProductVersion();
}
// This function is to implement the ISettingsConfig interface.
// This interface helps in getting the settings configurations.
public string GetModuleName()
{
// The SettingsUtils functions access general settings when the module name is an empty string.
return string.Empty;
}
public bool UpgradeSettingsConfiguration()
{
try
{
if (Helper.CompareVersions(PowertoysVersion, Helper.GetProductVersion()) != 0)
{
// Update settings
PowertoysVersion = Helper.GetProductVersion();
return true;
}
}
catch (FormatException)
{
// If there is an issue with the version number format, don't migrate settings.
}
return false;
}
}
}

View File

@ -10,6 +10,8 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class HotkeySettings
{
private const int VKTAB = 0x09;
public HotkeySettings()
{
Win = false;
@ -100,6 +102,11 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
public bool IsValid()
{
if (IsAccessibleShortcut())
{
return false;
}
return (Alt || Ctrl || Win || Shift) && Code != 0;
}
@ -107,5 +114,17 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
{
return !Alt && !Ctrl && !Win && !Shift && Code == 0;
}
public bool IsAccessibleShortcut()
{
// Shift+Tab and Tab are accessible shortcuts
if ((!Alt && !Ctrl && !Win && Shift && Code == VKTAB)
|| (!Alt && !Ctrl && !Win && !Shift && Code == VKTAB))
{
return true;
}
return false;
}
}
}

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;
using interop;
namespace Microsoft.PowerToys.Settings.UI.Lib
@ -10,7 +11,9 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
public delegate bool IsActive();
public class HotkeySettingsControlHook
public delegate bool FilterAccessibleKeyboardEvents(int key, UIntPtr extraInfo);
public class HotkeySettingsControlHook : IDisposable
{
private const int WmKeyDown = 0x100;
private const int WmKeyUp = 0x101;
@ -21,13 +24,17 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
private KeyEvent _keyDown;
private KeyEvent _keyUp;
private IsActive _isActive;
private bool disposedValue;
public HotkeySettingsControlHook(KeyEvent keyDown, KeyEvent keyUp, IsActive isActive)
private FilterAccessibleKeyboardEvents _filterKeyboardEvent;
public HotkeySettingsControlHook(KeyEvent keyDown, KeyEvent keyUp, IsActive isActive, FilterAccessibleKeyboardEvents filterAccessibleKeyboardEvents)
{
_keyDown = keyDown;
_keyUp = keyUp;
_isActive = isActive;
_hook = new KeyboardHook(HotkeySettingsHookCallback, IsActive, null);
_filterKeyboardEvent = filterAccessibleKeyboardEvents;
_hook = new KeyboardHook(HotkeySettingsHookCallback, IsActive, FilterKeyboardEvents);
_hook.Start();
}
@ -51,10 +58,29 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
}
}
private bool FilterKeyboardEvents(KeyboardEvent ev)
{
return _filterKeyboardEvent(ev.key, (UIntPtr)ev.dwExtraInfo);
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// Dispose the KeyboardHook object to terminate the hook threads
_hook.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
// Dispose the KeyboardHook object to terminate the hook threads
_hook.Dispose();
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}

View File

@ -2,11 +2,14 @@
// 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.PowerToys.Settings.UI.Lib.Interface;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public interface ISettingsUtils
{
T GetSettings<T>(string powertoy = "", string fileName = "settings.json");
T GetSettings<T>(string powertoy = "", string fileName = "settings.json")
where T : ISettingsConfig, new();
void SaveSettings(string jsonSettings, string powertoy = "", string fileName = "settings.json");

View File

@ -4,12 +4,13 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Lib.Interface;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class ImageResizerSettings : BasePTModuleSettings
public class ImageResizerSettings : BasePTModuleSettings, ISettingsConfig
{
public const string ModuleName = "Image Resizer";
public const string ModuleName = "ImageResizer";
[JsonPropertyName("properties")]
public ImageResizerProperties Properties { get; set; }
@ -29,5 +30,16 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
};
return JsonSerializer.Serialize(this, options);
}
public string GetModuleName()
{
return Name;
}
// This can be utilized in the future if the settings.json file is to be modified/deleted.
public bool UpgradeSettingsConfiguration()
{
return false;
}
}
}

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;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text.Json;
@ -203,8 +204,8 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
{
_unit = value;
OnPropertyChanged();
OnPropertyChanged("ExtraBoxOpacity");
OnPropertyChanged("EnableEtraBoxes");
OnPropertyChanged(nameof(ExtraBoxOpacity));
OnPropertyChanged(nameof(EnableEtraBoxes));
}
}
}
@ -222,6 +223,11 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
public void Update(ImageSize modifiedSize)
{
if (modifiedSize == null)
{
throw new ArgumentNullException(nameof(modifiedSize));
}
Id = modifiedSize.Id;
Name = modifiedSize.Name;
Fit = modifiedSize.Fit;

View File

@ -10,8 +10,13 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class ImageResizerSizes
{
// Suppressing this warning because removing the setter breaks
// deserialization with System.Text.Json. This affects the UI display.
// See: https://github.com/dotnet/runtime/issues/30258
[JsonPropertyName("value")]
#pragma warning disable CA2227 // Collection properties should be read only
public ObservableCollection<ImageSize> Value { get; set; }
#pragma warning restore CA2227 // Collection properties should be read only
public ImageResizerSizes()
{

View File

@ -0,0 +1,16 @@
// 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.
namespace Microsoft.PowerToys.Settings.UI.Lib.Interface
{
// Common interface to be implemented by all the objects which get and store settings properties.
public interface ISettingsConfig
{
string ToJsonString();
string GetModuleName();
bool UpgradeSettingsConfiguration();
}
}

View File

@ -0,0 +1,11 @@
// 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.
namespace Microsoft.PowerToys.Settings.UI.Lib.Interface
{
public interface ISettingsRepository<T>
{
T SettingsConfig { get; set; }
}
}

View File

@ -2,11 +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.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Lib.Interface;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class KeyboardManagerProfile
public class KeyboardManagerProfile : ISettingsConfig
{
[JsonPropertyName("remapKeys")]
public RemapKeysDataModel RemapKeys { get; set; }
@ -19,5 +21,21 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
RemapKeys = new RemapKeysDataModel();
RemapShortcuts = new ShortcutsKeyDataModel();
}
public string ToJsonString()
{
return JsonSerializer.Serialize(this);
}
public string GetModuleName()
{
return KeyboardManagerSettings.ModuleName;
}
// This can be utilized in the future if the default.json file is to be modified/deleted.
public bool UpgradeSettingsConfiguration()
{
return false;
}
}
}

View File

@ -3,11 +3,14 @@
// See the LICENSE file in the project root for more information.
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Lib.Interface;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class KeyboardManagerSettings : BasePTModuleSettings
public class KeyboardManagerSettings : BasePTModuleSettings, ISettingsConfig
{
public const string ModuleName = "Keyboard Manager";
[JsonPropertyName("properties")]
public KeyboardManagerProperties Properties { get; set; }
@ -15,14 +18,18 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
{
Properties = new KeyboardManagerProperties();
Version = "1";
Name = "_unset_";
Name = ModuleName;
}
public KeyboardManagerSettings(string ptName)
public string GetModuleName()
{
Properties = new KeyboardManagerProperties();
Version = "1";
Name = ptName;
return Name;
}
// This can be utilized in the future if the settings.json file is to be modified/deleted.
public bool UpgradeSettingsConfiguration()
{
return false;
}
}
}

View File

@ -4,6 +4,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Lib.Utilities;
@ -17,7 +18,7 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
[JsonPropertyName("newRemapKeys")]
public string NewRemapKeys { get; set; }
private List<string> MapKeys(string stringOfKeys)
private static List<string> MapKeys(string stringOfKeys)
{
return stringOfKeys
.Split(';')
@ -26,14 +27,19 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
.ToList();
}
public List<string> GetOriginalKeys()
public List<string> GetMappedOriginalKeys()
{
return MapKeys(OriginalKeys);
}
public List<string> GetNewRemapKeys()
public List<string> GetMappedNewRemapKeys()
{
return MapKeys(NewRemapKeys);
}
public string ToJsonString()
{
return JsonSerializer.Serialize(this);
}
}
}

View File

@ -5,11 +5,11 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Lib.Utilities;
using Microsoft.PowerToys.Settings.UI.Lib.Interface;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class PowerLauncherSettings : BasePTModuleSettings
public class PowerLauncherSettings : BasePTModuleSettings, ISettingsConfig
{
public const string ModuleName = "PowerToys Run";
@ -31,7 +31,23 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
WriteIndented = true,
};
if (settingsUtils == null)
{
throw new ArgumentNullException(nameof(settingsUtils));
}
settingsUtils.SaveSettings(JsonSerializer.Serialize(this, options), ModuleName);
}
public string GetModuleName()
{
return Name;
}
// This can be utilized in the future if the settings.json file is to be modified/deleted.
public bool UpgradeSettingsConfiguration()
{
return false;
}
}
}

View File

@ -72,7 +72,7 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
return JsonSerializer.Serialize(this);
}
private void LogTelemetryEvent(bool value, [CallerMemberName] string propertyName = null)
private static void LogTelemetryEvent(bool value, [CallerMemberName] string propertyName = null)
{
var dataEvent = new SettingsEnabledEvent()
{

View File

@ -3,14 +3,15 @@
// See the LICENSE file in the project root for more information.
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Lib.Interface;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class PowerPreviewSettings : BasePTModuleSettings
public class PowerPreviewSettings : BasePTModuleSettings, ISettingsConfig
{
public const string ModuleName = "File Explorer";
[JsonPropertyName("Properties")]
[JsonPropertyName("properties")]
public PowerPreviewProperties Properties { get; set; }
public PowerPreviewSettings()
@ -20,11 +21,15 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
Name = ModuleName;
}
public PowerPreviewSettings(string ptName)
public string GetModuleName()
{
Properties = new PowerPreviewProperties();
Version = "1";
Name = ptName;
return Name;
}
// This can be utilized in the future if the settings.json file is to be modified/deleted.
public bool UpgradeSettingsConfiguration()
{
return false;
}
}
}

View File

@ -3,10 +3,11 @@
// See the LICENSE file in the project root for more information.
using System.Text.Json;
using Microsoft.PowerToys.Settings.UI.Lib.Interface;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class PowerRenameLocalProperties
public class PowerRenameLocalProperties : ISettingsConfig
{
public PowerRenameLocalProperties()
{
@ -51,5 +52,18 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
{
return JsonSerializer.Serialize(this);
}
// This function is required to implement the ISettingsConfig interface and obtain the settings configurations.
public string GetModuleName()
{
string moduleName = PowerRenameSettings.ModuleName;
return moduleName;
}
// This can be utilized in the future if the settings.json file is to be modified/deleted.
public bool UpgradeSettingsConfiguration()
{
return false;
}
}
}

View File

@ -2,11 +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.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Lib.Interface;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class PowerRenameSettings : BasePTModuleSettings
public class PowerRenameSettings : BasePTModuleSettings, ISettingsConfig
{
public const string ModuleName = "PowerRename";
@ -22,6 +24,11 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
public PowerRenameSettings(PowerRenameLocalProperties localProperties)
{
if (localProperties == null)
{
throw new ArgumentNullException(nameof(localProperties));
}
Properties = new PowerRenameProperties();
Properties.PersistState.Value = localProperties.PersistState;
Properties.MRUEnabled.Value = localProperties.MRUEnabled;
@ -39,5 +46,16 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
Version = "1";
Name = ptName;
}
public string GetModuleName()
{
return Name;
}
// This can be utilized in the future if the power-rename-settings.json file is to be modified/deleted.
public bool UpgradeSettingsConfiguration()
{
return false;
}
}
}

View File

@ -3,18 +3,29 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
public class RemapKeysDataModel
{
// Suppressing this warning because removing the setter breaks
// deserialization with System.Text.Json. This affects the UI display.
// See: https://github.com/dotnet/runtime/issues/30258
[JsonPropertyName("inProcess")]
#pragma warning disable CA2227 // Collection properties should be read only
public List<KeysDataModel> InProcessRemapKeys { get; set; }
#pragma warning restore CA2227 // Collection properties should be read only
public RemapKeysDataModel()
{
InProcessRemapKeys = new List<KeysDataModel>();
}
public string ToJsonString()
{
return JsonSerializer.Serialize(this);
}
}
}

View File

@ -0,0 +1,70 @@
// 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 Microsoft.PowerToys.Settings.UI.Lib.Interface;
namespace Microsoft.PowerToys.Settings.UI.Lib
{
// This Singleton class is a wrapper around the settings configurations that are accessed by viewmodels.
// This class can have only one instance and therefore the settings configurations are common to all.
public class SettingsRepository<T> : ISettingsRepository<T>
where T : class, ISettingsConfig, new()
{
private static readonly object _SettingsRepoLock = new object();
private static ISettingsUtils _settingsUtils;
private static SettingsRepository<T> settingsRepository;
private T settingsConfig;
// Suppressing the warning as this is a singleton class and this method is
// necessarily static
#pragma warning disable CA1000 // Do not declare static members on generic types
public static SettingsRepository<T> GetInstance(ISettingsUtils settingsUtils)
#pragma warning restore CA1000 // Do not declare static members on generic types
{
// To ensure that only one instance of Settings Repository is created in a multi-threaded environment.
lock (_SettingsRepoLock)
{
if (settingsRepository == null)
{
settingsRepository = new SettingsRepository<T>();
_settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));
}
return settingsRepository;
}
}
// The Singleton class must have a private constructor so that it cannot be instantiated by any other object other than itself.
private SettingsRepository()
{
}
// Settings configurations shared across all viewmodels
public T SettingsConfig
{
get
{
if (settingsConfig == null)
{
T settingsItem = new T();
settingsConfig = _settingsUtils.GetSettings<T>(settingsItem.GetModuleName());
}
return settingsConfig;
}
set
{
if (value != null)
{
settingsConfig = value;
}
}
}
}
}

View File

@ -4,6 +4,7 @@
using System;
using System.Text.Json;
using Microsoft.PowerToys.Settings.UI.Lib.Interface;
using Microsoft.PowerToys.Settings.UI.Lib.Utilities;
namespace Microsoft.PowerToys.Settings.UI.Lib
@ -59,16 +60,42 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
/// <summary>
/// Get a Deserialized object of the json settings string.
/// This function creates a file in the powertoy folder if it does not exist and returns an object with default properties.
/// </summary>
/// <returns>Deserialized json settings object.</returns>
public T GetSettings<T>(string powertoy = DefaultModuleName, string fileName = DefaultFileName)
where T : ISettingsConfig, new()
{
if (SettingsExists(powertoy, fileName))
{
// Given the file already exists, to deserialize the file and read it's content.
T deserializedSettings = GetFile<T>(powertoy, fileName);
// IF the file needs to be modified, to save the new configurations accordingly.
if (deserializedSettings.UpgradeSettingsConfiguration())
{
SaveSettings(deserializedSettings.ToJsonString(), powertoy, fileName);
}
return deserializedSettings;
}
else
{
// If the settings file does not exist, to create a new object with default parameters and save it to a newly created settings file.
T newSettingsItem = new T();
SaveSettings(newSettingsItem.ToJsonString(), powertoy, fileName);
return newSettingsItem;
}
}
// Given the powerToy folder name and filename to be accessed, this function deserializes and returns the file.
private T GetFile<T>(string powertoyFolderName = DefaultModuleName, string fileName = DefaultFileName)
{
// Adding Trim('\0') to overcome possible NTFS file corruption.
// Look at issue https://github.com/microsoft/PowerToys/issues/6413 you'll see the file has a large sum of \0 to fill up a 4096 byte buffer for writing to disk
// This, while not totally ideal, does work around the problem by trimming the end.
// The file itself did write the content correctly but something is off with the actual end of the file, hence the 0x00 bug
var jsonSettingsString = _ioProvider.ReadAllText(GetSettingsPath(powertoy, fileName)).Trim('\0');
var jsonSettingsString = _ioProvider.ReadAllText(GetSettingsPath(powertoyFolderName, fileName)).Trim('\0');
return JsonSerializer.Deserialize<T>(jsonSettingsString);
}

View File

@ -12,7 +12,7 @@ namespace Microsoft.PowerToys.Settings.UI.Lib
{
OverlayOpacity = new IntProperty(90);
PressTime = new IntProperty(900);
Theme = new StringProperty("light");
Theme = new StringProperty("system");
}
[JsonPropertyName("overlay_opacity")]

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