Compare commits

...

112 Commits

Author SHA1 Message Date
vanzue
31874dff23 Add first UI automation for workspaces editor 2025-04-29 12:32:14 +08:00
yaqingmi
1a14dce5a3 Add FindMyMouseSettings Tests (#39078)
* empowering users to maximize OOBE to their heart desire (#37823)

empowering users to maximize to their heart desire

* Add More Elements support for UITestAutomation

* Add Mouse Click and Base Components Test

* Add FindMyMouse Tests for Enable and Disable

* Add Mouse Highlighter Enable/Disable Test Case

* Add Mouse Actions Support for UITest Framework

* Delete src/modules/MouseUtils/FindMyMouse.UITests/FindMyMouseSettingTests.cs

* Update NameSpace and remove redundant code

* Update the SessionHelper and Sleep Time for Actions

* Add SendKey for Session and Fix Spelling Errors

* Add Tests for Mouse Pointer Crosshairs Enable/Disable

* Add Sleep Time to Action Parameters

* Add Edit System Settings

* Add MouseJump Enable/Disable Tests

* Fix Pipeline error for MouseHighlighter

* Fix pipeline error

* Resolve Spelling errors

* Fix pipeline errors

* Add FindMyMouse Setting Tests

* Update the Sleep time

* Update Sleep Time

* Fix pipeline errors

* Revert pipeline settings

---------

Co-authored-by: Clint Rutkas <clint@rutkas.com>
Co-authored-by: Yaqing Mi (from Dev Box) <yaqingmi@microsoft.com>
2025-04-25 11:43:47 +08:00
Xiaofeng Wang (from Dev Box)
211bb15be0 Merge branch 'feature/UITestAutomation' of https://github.com/microsoft/PowerToys into feature/UITestAutomation 2025-04-23 17:07:20 +08:00
Xiaofeng Wang (from Dev Box)
2752b217e5 Add cover list and TestCategory 2025-04-23 17:07:02 +08:00
XiaofengWang
b0afc57e77 Add timeout for ui test job (#39037)
Co-authored-by: Xiaofeng Wang (from Dev Box) <xiaofengwang@microsoft.com>
2025-04-23 11:43:22 +08:00
yaqingmi
2eb51a1861 Add Tests for MouseJump and Fix Pipeline Errors (#39024)
* empowering users to maximize OOBE to their heart desire (#37823)

empowering users to maximize to their heart desire

* Add More Elements support for UITestAutomation

* Add Mouse Click and Base Components Test

* Add FindMyMouse Tests for Enable and Disable

* Add Mouse Highlighter Enable/Disable Test Case

* Add Mouse Actions Support for UITest Framework

* Delete src/modules/MouseUtils/FindMyMouse.UITests/FindMyMouseSettingTests.cs

* Update NameSpace and remove redundant code

* Update the SessionHelper and Sleep Time for Actions

* Add SendKey for Session and Fix Spelling Errors

* Add Tests for Mouse Pointer Crosshairs Enable/Disable

* Add Sleep Time to Action Parameters

* Add Edit System Settings

* Add MouseJump Enable/Disable Tests

* Fix Pipeline error for MouseHighlighter

* Fix pipeline error

* Resolve Spelling errors

---------

Co-authored-by: Clint Rutkas <clint@rutkas.com>
Co-authored-by: Yaqing Mi (from Dev Box) <yaqingmi@microsoft.com>
2025-04-22 17:17:13 +08:00
Mengyuan
91077c71a9 [UITestAutomation > UITests-Fancyzones] Add UI tests on Switch between windows in the current zone (#38999)
* fancytest oneswitch test

* add GetActiveWindowTitle

* testcase1 add set layout

* change shortcut to win pgdn

* add hold key

* Snap several windows to one zone, verify switching works.

* pack snaptoonezone

* pack snaptoonezone

* Add Fancy Zone Switch tests

* Add Fancyzones switch zones

* remove code and change zoneuuid to zonesets

* fix spell error and remove files

* remove unuse keyup in elements

* remove to common api

* fix spell error
2025-04-22 17:08:55 +08:00
XiaofengWang
997622fac8 Separate visual check by platform (#39022)
* Separate visual check by pipeline platform

* Update baseline file

* Add image to attachments when baseline file does not exist

* Update baseline resource file

---------

Co-authored-by: Xiaofeng Wang (from Dev Box) <xiaofengwang@microsoft.com>
2025-04-22 14:49:28 +08:00
yaqingmi
ddb9d8ecc6 UI Test Automation for FindMyMouse Enable/Disable and MouseHighlighter Enable/Disable (#38891)
* empowering users to maximize OOBE to their heart desire (#37823)

empowering users to maximize to their heart desire

* Add More Elements support for UITestAutomation

* Add Mouse Click and Base Components Test

* Add FindMyMouse Tests for Enable and Disable

* Add Mouse Highlighter Enable/Disable Test Case

* Add Mouse Actions Support for UITest Framework

* Delete src/modules/MouseUtils/FindMyMouse.UITests/FindMyMouseSettingTests.cs

* Update NameSpace and remove redundant code

* Update the SessionHelper and Sleep Time for Actions

* Add SendKey for Session and Fix Spelling Errors

* Add Tests for Mouse Pointer Crosshairs Enable/Disable

* Add Sleep Time to Action Parameters

---------

Co-authored-by: Clint Rutkas <clint@rutkas.com>
Co-authored-by: Yaqing Mi (from Dev Box) <yaqingmi@microsoft.com>
2025-04-21 15:20:57 +08:00
Zhaopeng Wang (from Dev Box)
856cbaa293 fix command palette pipeline error 2025-04-18 15:42:53 +08:00
Zhaopeng Wang (from Dev Box)
4067be17b2 fix merge 2025-04-18 14:53:33 +08:00
Zhaopeng Wang (from Dev Box)
b4020c6720 delete createmonitor 2025-04-18 14:33:53 +08:00
Xiaofeng Wang (from Dev Box)
f87c1bc448 Update hosts baseline file 2025-04-18 14:28:43 +08:00
Xiaofeng Wang (from Dev Box)
f49daa24e0 Run all UI tests in automation pipeline 2025-04-17 16:46:38 +08:00
Xiaofeng Wang (from Dev Box)
c1c9720992 keep original image 2025-04-17 16:42:20 +08:00
Xiaofeng Wang (from Dev Box)
750bb429c5 Merge branch 'feature/UITestAutomation' of https://github.com/microsoft/PowerToys into feature/UITestAutomation 2025-04-17 16:37:32 +08:00
Xiaofeng Wang (from Dev Box)
7f5aaf26dc Test visual in pipeline 2025-04-17 16:37:27 +08:00
Mengyuan
af8d5402c8 [UITestAutomation > KeyBoardHelper] Add PressKey, ReleaseKey, and KeyDownAndDrag combinationschen/UI automationtools (#38921)
* Add PressKey and ReleaseKey Seperately Add KeyDownAndDrag combination operator in element
2025-04-17 16:27:03 +08:00
Xiaofeng Wang (from Dev Box)
77852f2137 Update keyboardhelper to lowercase 2025-04-15 16:56:13 +08:00
Xiaofeng Wang (from Dev Box)
b902d3adf0 Update pipeline-ui-tests-automation.yml 2025-04-15 10:56:33 +08:00
Xiaofeng Wang (from Dev Box)
82ff0615d4 Add parameter in job-build-project.yml 2025-04-15 10:54:25 +08:00
Xiaofeng Wang (from Dev Box)
5081d6d31e Add build yml for ui automation 2025-04-15 10:43:00 +08:00
Xiaofeng Wang (from Dev Box)
abec5eb96a update yml format 2025-04-14 16:36:46 +08:00
Xiaofeng Wang (from Dev Box)
71ec39ff89 Separate UI automation pipeline yml file 2025-04-14 16:09:00 +08:00
Zhaopeng Wang (from Dev Box)
017b9e6339 create new virtual monitor 2025-04-14 12:03:15 +08:00
Zhaopeng Wang (from Dev Box)
c8b1a925b3 check montor number 2025-04-14 10:59:30 +08:00
Zhaopeng Wang (from Dev Box)
e0e3772cdd fix change display resolution bug 2025-04-14 10:46:15 +08:00
Zhaopeng Wang (from Dev Box)
6b8798fb94 add change display resolution 2025-04-14 08:21:32 +08:00
Zhaopeng Wang (from Dev Box)
836cfbf698 test change display resolution 2025-04-12 20:55:29 +08:00
Zhaopeng Wang (from Dev Box)
91d504511f delete assert 2025-04-11 17:21:29 +08:00
Zhaopeng Wang (from Dev Box)
3d3682672c add enum display setting 2025-04-11 16:08:43 +08:00
Zhaopeng Wang (from Dev Box)
b9474e9f60 Merge branch 'feature/UITestAutomation' of https://github.com/microsoft/PowerToys into feature/UITestAutomation 2025-04-11 14:28:17 +08:00
Zhaopeng Wang (from Dev Box)
c5b29188b8 add display resolution change 2025-04-11 14:28:07 +08:00
Xiaofeng Wang (from Dev Box)
e59b6d3051 Fix sendkey issue 2025-04-11 14:00:15 +08:00
Xiaofeng Wang (from Dev Box)
6625289a10 Add env in VSTest@3 2025-04-11 12:27:43 +08:00
Xiaofeng Wang (from Dev Box)
2f0dae347f Add env in VSTest@3 2025-04-11 12:18:33 +08:00
Xiaofeng Wang (from Dev Box)
f3ddba8aa5 Update pipeline parameter 2025-04-11 10:19:01 +08:00
Zhaopeng Wang (from Dev Box)
4744d23857 test in pipeline 2025-04-11 03:18:51 +08:00
Zhaopeng Wang (from Dev Box)
c42f8b0a1b fix error 2025-04-11 01:38:39 +08:00
Zhaopeng Wang (from Dev Box)
70da33783d add test code 2025-04-11 00:44:03 +08:00
Xiaofeng Wang (from Dev Box)
5fa416b962 Add GetDisplaySize 2025-04-10 17:28:45 +08:00
Xiaofeng Wang (from Dev Box)
aa7d89c8de Remove duplicate init 2025-04-10 17:11:44 +08:00
Xiaofeng Wang (from Dev Box)
fd7cccefa2 Continuous screenshots in pipeline env 2025-04-10 15:55:23 +08:00
Xiaofeng Wang (from Dev Box)
ae2bb61d26 Merge branch 'feature/UITestAutomation' of https://github.com/microsoft/PowerToys into feature/UITestAutomation 2025-04-10 15:47:37 +08:00
Xiaofeng Wang (from Dev Box)
52b4150e3b Continuous Screenshots in pipeline env 2025-04-10 15:47:32 +08:00
Zhaopeng Wang (from Dev Box)
6dc0211867 Merge branch 'main' into feature/UITestAutomation 2025-04-10 11:14:25 +08:00
dependabot[bot]
a708a3afaa Bump msstore-submissions.yml actions/setup-dotnet from 3 to 4 (#38626)
Bumps [actions/setup-dotnet](https://github.com/actions/setup-dotnet) from 3 to 4.
- [Release notes](https://github.com/actions/setup-dotnet/releases)
- [Commits](https://github.com/actions/setup-dotnet/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-dotnet
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-09 19:16:32 +08:00
Xiaofeng Wang (from Dev Box)
fc4d3a96c3 Add GetPixelGolor 2025-04-09 17:38:54 +08:00
Xiaofeng Wang (from Dev Box)
a347d740ca Add MouseHelper 2025-04-09 17:12:36 +08:00
Xiaofeng Wang (from Dev Box)
e8359931ac Add Enum Key 2025-04-09 16:00:35 +08:00
Xiaofeng Wang (from Dev Box)
1cb215d1a6 Add KeyboardHelper 2025-04-09 14:40:39 +08:00
Jeremy Sinclair
b7f99e88ef [Deps] Update .NET packages from 9.0.3 to 9.0.4 (#38676)
* [Deps] Update .NET packages from 9.0.3 to 9.0.4

* [Deps] Update NOTICE.md
2025-04-09 12:36:13 +08:00
Kai Tao
6f43aac26a [CmdPal] [Install] do not install dependency if already satisfied. (#38531)
* do not install dependency if already satisfied.
* self contain winappsdk
2025-04-09 07:16:08 +08:00
Mike Griese
d7e826d2ac Fix the WinGet missing / Admin crash (#38493)
This is a fix for a pair of related crashes. 

Basically, we'd crash on startup if we failed to initialize WinGet. This could happen in two different places:
* If WinGet wasn't installed, then we'd explode, cause obviously we can't call its APIs
* If we're running as Admin, we won't be able to instantiate it's COM server. 

Regardless of how it happens, I've defaulted us to just _not enabling the winget built-in_. That's the simplest solution here. 

As I was helpfully reminded, there's also an elevated WindowsPackageManagerFactory we could use too - though, that wouldn't solve the case of "winget isn't installed"

Closes #38460
Closes #38440 (most likely)
2025-04-08 04:22:29 -07:00
Clint Rutkas
9e8754a592 Fixing settings for mouse pointer for pt run and cmdpal (#38649)
In CmdPal and PT Run, if you currently try to go to mouse pointer, it fails.  This looks to be due to capitalization in the command.  This can be validated via run dialog also.

shifting to lowercase fixes the bug.

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist

- [x] **Closes:** #38223
2025-04-08 04:21:03 -07:00
moooyo
49687251d3 [cmdpal] Simplify time And Date extension code to make it easier to understand (#38075)
Co-authored-by: Yu Leng (from Dev Box) <yuleng@microsoft.com>
2025-04-08 16:19:13 +08:00
DanielEScherzer
f72ccd12fd doc/devdocs/UITests.md: add missing period [skip ci] (#38605) 2025-04-08 15:29:18 +08:00
Clint Rutkas
4b44858a48 Adding in Hawker for CmdPal to Readme (#38647)
Update README.md

We missed Hawker!!!
2025-04-07 18:02:30 -07:00
Kayla Cinnamon
53ae118e72 Update version placeholder in bug_report.yml (#38504) 2025-04-07 17:06:34 -07:00
Clint Rutkas
31df702704 Updating the community md for recent adjustments (#38366)
* Update COMMUNITY.md

Adjusting team

* Update names.txt

* Update expect.txt
2025-04-07 12:42:56 -07:00
Clint Rutkas
ea2542b235 Adding Pedro for his hard 3D file work (#38599)
Adding Pedro
2025-04-07 12:42:38 -07:00
Davide Giacometti
c6776d0d45 [CmdPal] Fix Up/Down keyboard navigation + continuous navigation (#38499)
## Summary of the Pull Request

Fix #38337 and implement continuous navigation like PT Run v1

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist

- [x] **Closes:** #38337
2025-04-03 06:47:23 -05:00
Mike Griese
d48286a3eb Scale the toast window for DPI (#38198)
Ah of course, AppWindow.Resize doesn't use DIPs. Why would it? It's not like literally everything else in XAML does.

Related to half of https://github.com/zadjii-msft/PowerToys/issues/508
2025-04-03 06:44:10 -05:00
Jaime Bernardo
7a5b25cd3e [Settings]Fix blank icon in the taskbar (#38259) 2025-04-02 17:59:46 -07:00
Clint Rutkas
1eccbc3021 WinGet installer fix (#38422)
Update package.h
2025-04-01 16:21:15 -07:00
Heiko
ce620e427f [PT Run > Time and Date plugin] Custom formats and other improvements (#37743)
* add settings definition

* fix typos and improve settings

* make spell checker happy

* new icon type error

* first code to handle custom formats

* support parsing of new formats

* spelling and typos

* comment fix

* spell check

* start implement custom format results

* last changes

* finish implementation

* spell checker

* settings name

* add missing format

* reorder settings

* dev docs

* change ELF to EAB

* update dev docs

* last changes

* test cases

* fix typos

* fix typo

* port changes

* fixes

* changes

* fixes

* leap year support

* days in month

* tests

* comment

* fix comment
2025-04-01 21:31:35 +08:00
Zhaopeng Wang (from Dev Box)
0f6ff59d2e merge main and fix error 2025-04-01 17:39:28 +08:00
Hao Liu
721c84d3a6 Install .NET 9 for MSStore release (#38361)
fix dotnet 9
2025-04-01 10:08:25 +08:00
Hao Liu
96ba445cfa 0.90 changelog (#38072)
* First draft. Some PRs are still under review.

* update wording

* remove the Svg thumbnail since it has been reverted

* update cmdpal

* add cmdpal

* clear old hashes

* address comments

* Update README.md

Co-authored-by: Jay <65828559+Jay-o-Way@users.noreply.github.com>

* address more comments

* Update README.md

Co-authored-by: Mike Griese <migrie@microsoft.com>

* Add Command Palette gif to README

* upload gif of cmdpal

* Update README.md

Co-authored-by: Mike Griese <migrie@microsoft.com>

* Address comments

Co-authored-by: Kayla Cinnamon <cinnamon@microsoft.com>

* Update README.md

Co-authored-by: Kayla Cinnamon <cinnamon@microsoft.com>

* Update CmdPal description

Co-authored-by: Kayla Cinnamon <cinnamon@microsoft.com>

* Remove extra spacing

Co-authored-by: PesBandi <127593627+PesBandi@users.noreply.github.com>

* update hash

* update gif with new icon

---------

Co-authored-by: Jay <65828559+Jay-o-Way@users.noreply.github.com>
Co-authored-by: Clint Rutkas <clint@rutkas.com>
Co-authored-by: Mike Griese <migrie@microsoft.com>
Co-authored-by: Kayla Cinnamon <cinnamon@microsoft.com>
Co-authored-by: PesBandi <127593627+PesBandi@users.noreply.github.com>
2025-03-31 16:09:26 -07:00
Xiaofeng Wang (from Dev Box)
25a8c95049 Common out continuous screenshots 2025-03-26 14:02:09 +08:00
Xiaofeng Wang (from Dev Box)
c60c79af67 Send ESC in testinit 2025-03-26 11:40:33 +08:00
Xiaofeng Wang (from Dev Box)
dd5279b9b8 Add screenshots to result 2025-03-26 09:57:27 +08:00
Xiaofeng Wang (from Dev Box)
78921eb7d3 Add TestEmptyView back 2025-03-25 16:44:22 +08:00
Xiaofeng Wang (from Dev Box)
9173ac27df Continuous screenshots for failed cases 2025-03-25 16:36:13 +08:00
Xiaofeng Wang (from Dev Box)
ce57d818a7 Remove TestEmptyView 2025-03-20 17:34:13 +08:00
Xiaofeng Wang (from Dev Box)
595231f64b Add waiting time before starting to run 2025-03-17 14:42:07 +08:00
Jerry Xu
7894c1e5ad Merge branch 'feature/UITestAutomation' of https://github.com/microsoft/powertoys into feature/UITestAutomation 2025-03-17 14:01:26 +08:00
Jerry Xu
d2d71bf797 Save last-screenshot for all failed ui-test-cases 2025-03-17 14:01:23 +08:00
Jerry Xu
3eb5ca294a Save last-screenshot for all failed ui-test-cases 2025-03-17 12:30:00 +08:00
Xiaofeng Wang (from Dev Box)
0277938f18 Set window always on top 2025-03-15 15:04:43 +08:00
Xiaofeng Wang (from Dev Box)
dd7b6f3ea9 Update CloseWarningDialog for testing 2025-03-15 13:05:28 +08:00
Xiaofeng Wang (from Dev Box)
0187d1abcd Add waiting time after window resize 2025-03-15 11:41:56 +08:00
Xiaofeng Wang (from Dev Box)
7bd2b50126 Implement retry logic instead of using ImplicitWait 2025-03-15 10:00:28 +08:00
Jerry Xu
b127611462 Prototype save to attachment 2025-03-14 16:38:05 +08:00
Xiaofeng Wang (from Dev Box)
622770134e Comment out visualassert 2025-03-14 16:13:58 +08:00
Xiaofeng Wang (from Dev Box)
ceca607142 Update xpath in RemoveAllEntries 2025-03-14 14:38:08 +08:00
Xiaofeng Wang (from Dev Box)
77a5ef7d32 Check window in RemoveAllEntries 2025-03-14 12:13:22 +08:00
Xiaofeng Wang (from Dev Box)
75f2b0927c Update visual default fuzz value 2025-03-13 23:20:13 +08:00
Xiaofeng Wang (from Dev Box)
f54ab6ebd5 Add VisualHelper 2025-03-13 22:22:00 +08:00
Xiaofeng Wang (from Dev Box)
dd5997ab06 Update click in NavigationViewItem 2025-03-13 16:27:31 +08:00
Xiaofeng Wang (from Dev Box)
6bdbb6b552 Add click hold time 2025-03-13 15:47:38 +08:00
Xiaofeng Wang (from Dev Box)
84dd551d84 Extend waiting time 2025-03-13 13:19:07 +08:00
Xiaofeng Wang (from Dev Box)
83bb82322d Add CloseMainWindow in Session and Update HostSettingTests 2025-03-12 22:08:25 +08:00
Jerry Xu
c4f8f09fab Initialize setting app w/ Medium size 2025-03-12 20:13:56 +08:00
Jerry Xu
9c95835384 Address script out-of-date issue 2025-03-12 16:41:40 +08:00
Jerry Xu
1867ac8f02 Support VisualAssert - Image based validation 2025-03-12 15:51:40 +08:00
Jerry Xu
127e079efe fix build issue 2025-03-12 14:13:35 +08:00
Jerry Xu
03540e307c sync & merge 2025-03-12 14:02:53 +08:00
Xiaofeng Wang (from Dev Box)
a10578f7d3 Run UI tests in CI pipeline 2025-03-12 13:57:14 +08:00
Zhaopeng Wang
9c08c957e5 add Automation clean up code
Rebase from origin/dev/nxu/ImproveUIAutomation
2025-03-12 13:55:44 +08:00
Jerry Xu
c73b88f575 sync & merge 2025-03-12 13:47:37 +08:00
Jerry Xu
fc1c4abd0a sync 2025-03-12 13:46:25 +08:00
Jerry Xu
22efeb3f63 Improve UIAutomation to support:
1. SetWindowSize
2. Auto-close
3. Better window search logic
2025-03-12 13:37:23 +08:00
Xiaofeng Wang (from Dev Box)
63c4089441 Run UI tests in CI pipeline 2025-03-12 11:36:32 +08:00
Zhaopeng Wang
fd206ecdee add Automation clean up code 2025-03-12 11:36:32 +08:00
Jerry Xu
d243b58715 Fix code-style 2025-02-24 15:51:53 +08:00
Jerry Xu
abf4626843 Merge branch 'dev/nxu/ImproveUIAutomation' of https://github.com/microsoft/powertoys into dev/nxu/ImproveUIAutomation 2025-02-24 15:47:08 +08:00
Jerry Xu
3874a3b893 Exclude all UI-Test projects instead of just fancyZone UITest 2025-02-24 15:47:05 +08:00
Jerry Xu
8687b310db Exclude all UI-Test projects instead of just fancyZone UITest 2025-02-24 15:43:56 +08:00
Jerry Xu
c7ed8ee0c3 Add double-click 2025-02-24 15:43:05 +08:00
Jerry Xu
8c21f794af Improve UITest Automation 2025-02-24 15:28:46 +08:00
Jerry Xu
18befd7149 Improve UITest Automation 2025-02-24 15:24:33 +08:00
100 changed files with 7277 additions and 538 deletions

View File

@@ -11,7 +11,7 @@ body:
- type: input
attributes:
label: Microsoft PowerToys version
placeholder: 0.70.0
placeholder: X.XX.X
description: Hover over system tray icon or look at Settings
validations:
required: true

View File

@@ -110,6 +110,7 @@ Lambson
Laute
laviusmotileng
Leilei
Loewen
Luecking
Mahalingam
Markovic

View File

@@ -15,6 +15,7 @@ ACTIVATEAPP
activationaction
ACVS
adaptivecards
ADate
ADDSTRING
ADDUNDORECORD
ADifferent
@@ -199,8 +200,7 @@ CLIPCHILDREN
CLIPSIBLINGS
closesocket
CLSCTX
CLSIDs
Clsids
clsids
Clusion
cmder
CMDNOTFOUNDMODULEINTERFACE
@@ -417,6 +417,7 @@ DWORDLONG
dworigin
dwrite
dxgi
eab
easeofaccess
ecount
Edid
@@ -466,6 +467,7 @@ EXAND
EXCLUDEFROMCAPTURE
executionpolicy
exename
exf
EXITSIZEMOVE
exlist
EXPCMDFLAGS
@@ -898,6 +900,7 @@ MARKDOWNPREVIEWHANDLERCPP
MAXIMIZEBOX
MAXSHORTCUTSIZE
maxversiontested
mber
MBM
MBR
MDICHILD
@@ -1779,6 +1782,8 @@ USRDLL
UType
uuidv
uwp
ums
uxt
uxtheme
vabdq
validmodulename
@@ -1859,10 +1864,10 @@ webbrowsers
webpage
websites
wekyb
wft
wgpocpl
WHEREID
Wholegrain
WIC
wic
wifi
wil
@@ -1919,6 +1924,7 @@ WNDCLASSEXW
WNDCLASSW
WNDPROC
wnode
wom
WORKSPACESEDITOR
WORKSPACESLAUNCHER
WORKSPACESSNAPSHOTTOOL
@@ -1990,4 +1996,4 @@ zoomit
ZOOMITX
ZXk
ZXNs
zzz
zzz

View File

@@ -39,6 +39,11 @@ jobs:
echo powerToysInstallerX64Url=$(jq -n "$powerToysSetup" | jq -r '[.[]|select(.name | contains("x64"))][0].browser_download_url') >> $GITHUB_OUTPUT
echo powerToysInstallerArm64Url=$(jq -n "$powerToysSetup" | jq -r '[.[]|select(.name | contains("arm64"))][0].browser_download_url') >> $GITHUB_OUTPUT
- name: Setup .NET 9.0
uses: actions/setup-dotnet@v4
with:
dotnet-version: '9.0.x'
- uses: microsoft/setup-msstore-cli@v1
- name: Fetch Store Credential

View File

@@ -50,6 +50,9 @@ parameters:
- name: runTests
type: boolean
default: true
- name: buildTests
type: boolean
default: true
- name: useVSPreview
type: boolean
default: false
@@ -110,7 +113,7 @@ jobs:
JobOutputArtifactName: build-$(BuildPlatform)-$(BuildConfiguration)${{ parameters.artifactStem }}
NUGET_RESTORE_MSBUILD_ARGS: /p:Platform=$(BuildPlatform) # Required for nuget to work due to self contained
NODE_OPTIONS: --max_old_space_size=16384
${{ if eq(parameters.runTests, true) }}:
${{ if or(eq(parameters.runTests, true), eq(parameters.buildTests, true)) }}:
MSBuildMainBuildTargets: Build;Test
${{ else }}:
MSBuildMainBuildTargets: Build
@@ -514,7 +517,7 @@ jobs:
displayName: Stage GPO files
# Running the tests may result in future jobs consuming artifacts out of this build
- ${{ if eq(parameters.runTests, true) }}:
- ${{ if or(eq(parameters.runTests, true), eq(parameters.buildTests, true)) }}:
- task: CopyFiles@2
displayName: Stage entire build output
inputs:

View File

@@ -11,10 +11,14 @@ parameters:
- name: useLatestWebView2
type: boolean
default: false
- name: isUIAutomationPipeline
type: boolean
default: false
jobs:
- job: Test${{ parameters.platform }}${{ parameters.configuration }}
displayName: Test ${{ parameters.platform }} ${{ parameters.configuration }}
timeoutInMinutes: 300
variables:
BuildPlatform: ${{ parameters.platform }}
BuildConfiguration: ${{ parameters.configuration }}
@@ -101,8 +105,16 @@ jobs:
vsTestVersion: 'toolsInstaller'
uiTests: true
rerunFailedTests: true
testAssemblyVer2: |
**\UITests-FancyZones.dll
**\UITests-FancyZonesEditor.dll
!**\obj\**
!**\ref\**
${{ if eq(parameters.isUIAutomationPipeline, true) }}:
testAssemblyVer2: |
**\*UITest*.dll
!**\obj\**
!**\ref\**
${{ else }}:
testAssemblyVer2: |
**\UITests-FancyZones.dll
**\UITests-FancyZonesEditor.dll
!**\obj\**
!**\ref\**
env:
platform: '$(BuildPlatform)'

View File

@@ -0,0 +1,60 @@
variables:
- name: runCodesignValidationInjectionBG
value: false
- name: EnablePipelineCache
value: true
- ${{ if eq(parameters.enableMsBuildCaching, true) }}:
- name: EnablePipelineCache
value: true
parameters:
- name: buildPlatforms
type: object
default:
- x64
- arm64
- name: enableMsBuildCaching
type: boolean
default: false
- name: useVSPreview
type: boolean
default: false
- name: useLatestWebView2
type: boolean
default: false
stages:
- ${{ each platform in parameters.buildPlatforms }}:
- stage: Build_${{ platform }}
displayName: Build ${{ platform }}
dependsOn: []
jobs:
- template: job-build-project.yml
parameters:
pool:
${{ if eq(variables['System.CollectionId'], 'cb55739e-4afe-46a3-970f-1b49d8ee7564') }}:
name: SHINE-INT-L
${{ else }}:
name: SHINE-OSS-L
${{ if eq(parameters.useVSPreview, true) }}:
demands: ImageOverride -equals SHINE-VS17-Preview
buildPlatforms:
- ${{ platform }}
buildConfigurations: [Release]
enablePackageCaching: true
enableMsBuildCaching: ${{ parameters.enableMsBuildCaching }}
runTests: false
buildTests: true
useVSPreview: ${{ parameters.useVSPreview }}
- stage: Test_${{ platform }}
displayName: Test ${{ platform }}
dependsOn:
- Build_${{platform}}
jobs:
- template: job-test-project.yml
parameters:
platform: ${{ platform }}
configuration: Release
useLatestWebView2: ${{ parameters.useLatestWebView2 }}
isUIAutomationPipeline: true

View File

@@ -91,5 +91,4 @@ if ($totalFailures -gt 0) {
}
Write-Host -ForegroundColor Green "All " $referencedFileVersionsPerDll.keys.Count " libraries are mentioned with the same version across the dependencies.`r`n"
exit 0
exit 0

View File

@@ -16,7 +16,7 @@ Christian contributed New+ utility
CleanCodeDeveloper helped do massive amounts of code stability and image resizer work.
### [@plante-msft](https://github.com/plante-msft) - Connor Plante
Connor was the creator of Workspaces and helped create PowerToys Run v2
Connor was the creator of Workspaces and helped create Command Palette (PowerToys Run v2)
### [@damienleroy](https://github.com/damienleroy) - [Damien Leroy](https://www.linkedin.com/in/Damien-Leroy-b2734416a/)
Damien has helped out by developing and contributing the Quick Accent utility.
@@ -46,7 +46,7 @@ Jeff added in multiple new features into Keyboard manager, such as key chord sup
Joe has helped triaging, discussing, issues as well as fixing bugs and building features for Text Extractor.
### [@joadoumie](https://github.com/joadoumie) - Jordi Adoumie
Jordi helped innovate amazing new features into Advanced Paste and helped create PowerToys Run v2
Jordi helped innovate amazing new features into Advanced Paste and helped create Command Palette (PowerToys Run v2)
### [@jsoref](https://github.com/jsoref) - [Josh Soref](https://check-spelling.dev/)
Helping keep our spelling correct :)
@@ -57,6 +57,9 @@ Color Picker is from Martin.
### [@mikeclayton](https://github.com/mikeclayton) - [Michael Clayton](https://michael-clayton.com)
Michael contributed the [initial version](https://github.com/microsoft/PowerToys/issues/23216) of the Mouse Jump tool and [a number of updates](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+author%3Amikeclayton) based on his FancyMouse utility.
### [@pedrolamas](https://github.com/pedrolamas/) - Pedro Lamas
Pedro helped create the thumbnail and File Explorer previewers for 3D files like STL and GCode. If you like 3D printing, these are very helpful.
### [@PesBandi](https://github.com/PesBandi/) - PesBandi
PesBandi has helped do massive amounts of Quick Accent and bug fixes.
@@ -184,15 +187,10 @@ ZoomIt source code was originally implemented by [Sysinternals](https://sysinter
- [@crutkas](https://github.com/crutkas/) - Clint Rutkas - Lead
- [@cinnamon-msft](https://github.com/cinnamon-msft) - Kayla Cinnamon - Lead
- [@nguyen-dows](https://github.com/nguyen-dows) - Christopher Nguyen - Product Manager
- [@jaimecbernardo](https://github.com/jaimecbernardo) - Jaime Bernardo - Dev lead
- [@craigloewen-msft](https://github.com/craigloewen-msft) - Craig Loewen - Product Manager
- [@dhowett](https://github.com/dhowett) - Dustin Howett - Dev lead
- [@yeelam-gordon](https://github.com/yeelam-gordon) - Gordon Lam - Dev lead
- [@jamrobot](https://github.com/jamrobot) - Jerry Xu - Dev lead
- [@drawbyperpetual](https://github.com/drawbyperpetual) - Anirudha Shankar - Dev
- [@mantaionut](https://github.com/mantaionut) - Ionut Manta - Dev
- [@donlaci](https://github.com/donlaci) - Laszlo Nemeth - Dev
- [@SeraphimaZykova](https://github.com/SeraphimaZykova) - Seraphima Zykova - Dev
- [@stefansjfw](https://github.com/stefansjfw) - Stefan Markovic - Dev
- [@lei9444](https://github.com/lei9444) - Leilei Zhang - Dev
- [@shuaiyuanxx](https://github.com/shuaiyuanxx) - Shawn Yuan - Dev
- [@moooyo](https://github.com/moooyo) - Yu Leng - Dev
@@ -206,7 +204,7 @@ ZoomIt source code was originally implemented by [Sysinternals](https://sysinter
- [@wang563681252](https://github.com/wang563681252) - Zhaopeng Wang - Dev
- [@vanzue](https://github.com/vanzue) - Kai Tao - Dev
# Former PowerToys core team members
## Former PowerToys core team members
- [@indierawk2k2](https://github.com/indierawk2k2) - Mike Harsh - Product Manager
- [@ethanfangg](https://github.com/ethanfangg) - Ethan Fang - Product Manager
@@ -219,3 +217,9 @@ ZoomIt source code was originally implemented by [Sysinternals](https://sysinter
- [@taras-janea](https://github.com/taras-janea) - Taras Sich - Dev
- [@yuyoyuppe](https://github.com/yuyoyuppe) - Andrey Nekrasov - Dev
- [@gokcekantarci](https://github.com/gokcekantarci) - Gokce Kantarci - Dev
- [@drawbyperpetual](https://github.com/drawbyperpetual) - Anirudha Shankar - Dev
- [@mantaionut](https://github.com/mantaionut) - Ionut Manta - Dev
- [@donlaci](https://github.com/donlaci) - Laszlo Nemeth - Dev
- [@SeraphimaZykova](https://github.com/SeraphimaZykova) - Seraphima Zykova - Dev
- [@stefansjfw](https://github.com/stefansjfw) - Stefan Markovic - Dev
- [@jaimecbernardo](https://github.com/jaimecbernardo) - Jaime Bernardo - Dev lead

View File

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

View File

@@ -1420,22 +1420,22 @@ SOFTWARE.
- Mages 3.0.0
- Markdig.Signed 0.34.0
- MessagePack 2.5.187
- Microsoft.Bcl.AsyncInterfaces 9.0.3
- Microsoft.Bcl.AsyncInterfaces 9.0.4
- Microsoft.CodeAnalysis.NetAnalyzers 9.0.0
- Microsoft.Data.Sqlite 9.0.3
- Microsoft.Data.Sqlite 9.0.4
- Microsoft.Diagnostics.Tracing.TraceEvent 3.1.16
- Microsoft.DotNet.ILCompiler (A)
- Microsoft.Extensions.DependencyInjection 9.0.3
- Microsoft.Extensions.Hosting 9.0.3
- Microsoft.Extensions.Hosting.WindowsServices 9.0.3
- Microsoft.Extensions.Logging 9.0.3
- Microsoft.Extensions.Logging.Abstractions 9.0.3
- Microsoft.Extensions.DependencyInjection 9.0.4
- Microsoft.Extensions.Hosting 9.0.4
- Microsoft.Extensions.Hosting.WindowsServices 9.0.4
- Microsoft.Extensions.Logging 9.0.4
- Microsoft.Extensions.Logging.Abstractions 9.0.4
- Microsoft.NET.ILLink.Tasks (A)
- Microsoft.SemanticKernel 1.15.0
- Microsoft.Toolkit.Uwp.Notifications 7.1.2
- Microsoft.Web.WebView2 1.0.2903.40
- Microsoft.Win32.SystemEvents 9.0.3
- Microsoft.Windows.Compatibility 9.0.3
- Microsoft.Win32.SystemEvents 9.0.4
- Microsoft.Windows.Compatibility 9.0.4
- Microsoft.Windows.CsWin32 0.2.46-beta
- Microsoft.Windows.CsWinRT 2.2.0
- Microsoft.Windows.SDK.BuildTools 10.0.22621.2428
@@ -1454,23 +1454,23 @@ SOFTWARE.
- SharpCompress 0.37.2
- StreamJsonRpc 2.19.27
- StyleCop.Analyzers 1.2.0-beta.556
- System.CodeDom 9.0.3
- System.CodeDom 9.0.4
- System.CommandLine 2.0.0-beta4.22272.1
- System.ComponentModel.Composition 9.0.3
- System.Configuration.ConfigurationManager 9.0.3
- System.Data.OleDb 9.0.3
- System.ComponentModel.Composition 9.0.4
- System.Configuration.ConfigurationManager 9.0.4
- System.Data.OleDb 9.0.4
- System.Data.SqlClient 4.8.6
- System.Diagnostics.EventLog 9.0.3
- System.Diagnostics.PerformanceCounter 9.0.3
- System.Drawing.Common 9.0.3
- System.Diagnostics.EventLog 9.0.4
- System.Diagnostics.PerformanceCounter 9.0.4
- System.Drawing.Common 9.0.4
- System.IO.Abstractions 21.0.29
- System.IO.Abstractions.TestingHelpers 21.0.29
- System.Management 9.0.3
- System.Management 9.0.4
- System.Reactive 6.0.1
- System.Runtime.Caching 9.0.3
- System.ServiceProcess.ServiceController 9.0.3
- System.Text.Encoding.CodePages 9.0.3
- System.Text.Json 9.0.3
- System.Runtime.Caching 9.0.4
- System.ServiceProcess.ServiceController 9.0.4
- System.Text.Encoding.CodePages 9.0.4
- System.Text.Json 9.0.4
- UnicodeInformation 2.6.0
- UnitsNet 5.56.0
- UTF.Unknown 2.5.1

View File

@@ -706,6 +706,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RegistryPreview.FuzzTests",
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.CmdPal.Ext.System", "src\modules\cmdpal\Exts\Microsoft.CmdPal.Ext.System\Microsoft.CmdPal.Ext.System.csproj", "{64B88F02-CD88-4ED8-9624-989A800230F9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MouseUtils.UITests", "src\modules\MouseUtils\MouseUtils.UITests\MouseUtils.UITests.csproj", "{4E0AE3A4-2EE0-44D7-A2D0-8769977254A1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkspacesEditorUITest", "src\modules\Workspaces\WorkspacesEditorUITest\WorkspacesEditorUITest.csproj", "{43E779F3-D83C-48B1-BA8D-1912DBD76FC9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM64 = Debug|ARM64
@@ -2574,14 +2578,26 @@ Global
{64B88F02-CD88-4ED8-9624-989A800230F9}.Debug|ARM64.Build.0 = Debug|ARM64
{64B88F02-CD88-4ED8-9624-989A800230F9}.Debug|x64.ActiveCfg = Debug|x64
{64B88F02-CD88-4ED8-9624-989A800230F9}.Debug|x64.Build.0 = Debug|x64
{64B88F02-CD88-4ED8-9624-989A800230F9}.Debug|x86.ActiveCfg = Debug|x64
{64B88F02-CD88-4ED8-9624-989A800230F9}.Debug|x86.Build.0 = Debug|x64
{64B88F02-CD88-4ED8-9624-989A800230F9}.Release|ARM64.ActiveCfg = Release|ARM64
{64B88F02-CD88-4ED8-9624-989A800230F9}.Release|ARM64.Build.0 = Release|ARM64
{64B88F02-CD88-4ED8-9624-989A800230F9}.Release|x64.ActiveCfg = Release|x64
{64B88F02-CD88-4ED8-9624-989A800230F9}.Release|x64.Build.0 = Release|x64
{64B88F02-CD88-4ED8-9624-989A800230F9}.Release|x86.ActiveCfg = Release|x64
{64B88F02-CD88-4ED8-9624-989A800230F9}.Release|x86.Build.0 = Release|x64
{4E0AE3A4-2EE0-44D7-A2D0-8769977254A1}.Debug|ARM64.ActiveCfg = Debug|ARM64
{4E0AE3A4-2EE0-44D7-A2D0-8769977254A1}.Debug|ARM64.Build.0 = Debug|ARM64
{4E0AE3A4-2EE0-44D7-A2D0-8769977254A1}.Debug|x64.ActiveCfg = Debug|x64
{4E0AE3A4-2EE0-44D7-A2D0-8769977254A1}.Debug|x64.Build.0 = Debug|x64
{4E0AE3A4-2EE0-44D7-A2D0-8769977254A1}.Release|ARM64.ActiveCfg = Release|ARM64
{4E0AE3A4-2EE0-44D7-A2D0-8769977254A1}.Release|ARM64.Build.0 = Release|ARM64
{4E0AE3A4-2EE0-44D7-A2D0-8769977254A1}.Release|x64.ActiveCfg = Release|x64
{4E0AE3A4-2EE0-44D7-A2D0-8769977254A1}.Release|x64.Build.0 = Release|x64
{43E779F3-D83C-48B1-BA8D-1912DBD76FC9}.Debug|ARM64.ActiveCfg = Debug|ARM64
{43E779F3-D83C-48B1-BA8D-1912DBD76FC9}.Debug|ARM64.Build.0 = Debug|ARM64
{43E779F3-D83C-48B1-BA8D-1912DBD76FC9}.Debug|x64.ActiveCfg = Debug|x64
{43E779F3-D83C-48B1-BA8D-1912DBD76FC9}.Debug|x64.Build.0 = Debug|x64
{43E779F3-D83C-48B1-BA8D-1912DBD76FC9}.Release|ARM64.ActiveCfg = Release|ARM64
{43E779F3-D83C-48B1-BA8D-1912DBD76FC9}.Release|ARM64.Build.0 = Release|ARM64
{43E779F3-D83C-48B1-BA8D-1912DBD76FC9}.Release|x64.ActiveCfg = Release|x64
{43E779F3-D83C-48B1-BA8D-1912DBD76FC9}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -2721,7 +2737,7 @@ Global
{25C91A4E-BA4E-467A-85CD-8B62545BF674} = {A50C70A6-2DA0-4027-B90E-B1A40755A8A5}
{6AB6A2D6-F859-4A82-9184-0BD29C9F07D1} = {A50C70A6-2DA0-4027-B90E-B1A40755A8A5}
{212AD910-8488-4036-BE20-326931B75FB2} = {4AFC9975-2456-4C70-94A4-84073C1CED93}
{7AC943C9-52E8-44CF-9083-744D8049667B} = {4574FDD0-F61D-4376-98BF-E5A1262C11EC}
{7AC943C9-52E8-44CF-9083-744D8049667B} = {322566EF-20DC-43A6-B9F8-616AF942579A}
{54A93AF7-60C7-4F6C-99D2-FBB1F75F853A} = {7AC943C9-52E8-44CF-9083-744D8049667B}
{92C39820-9F84-4529-BC7D-22AAE514D63B} = {7AC943C9-52E8-44CF-9083-744D8049667B}
{515554D1-D004-4F7F-A107-2211FC0F6B2C} = {7AC943C9-52E8-44CF-9083-744D8049667B}
@@ -2852,6 +2868,8 @@ Global
{4E0AE3A4-2EE0-44D7-A2D0-8769977254A0} = {F05E590D-AD46-42BE-9C25-6A63ADD2E3EA}
{5702B3CC-8575-48D5-83D8-15BB42269CD3} = {929C1324-22E8-4412-A9A8-80E85F3985A5}
{64B88F02-CD88-4ED8-9624-989A800230F9} = {ECB8E0D1-7603-4E5C-AB10-D1E545E6F8E2}
{4E0AE3A4-2EE0-44D7-A2D0-8769977254A1} = {322566EF-20DC-43A6-B9F8-616AF942579A}
{43E779F3-D83C-48B1-BA8D-1912DBD76FC9} = {A2221D7E-55E7-4BEA-90D1-4F162D670BBF}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C3A2F9D1-7930-4EF4-A6FC-7EE0A99821D0}

148
README.md
View File

@@ -11,14 +11,15 @@ Microsoft PowerToys is a set of utilities for power users to tune and streamline
| | Current utilities: | |
|--------------|--------------------|--------------|
| [Advanced Paste](https://aka.ms/PowerToysOverview_AdvancedPaste) | [Always on Top](https://aka.ms/PowerToysOverview_AoT) | [PowerToys Awake](https://aka.ms/PowerToysOverview_Awake) |
| [Command Not Found](https://aka.ms/PowerToysOverview_CmdNotFound) | [Color Picker](https://aka.ms/PowerToysOverview_ColorPicker) | [Crop And Lock](https://aka.ms/PowerToysOverview_CropAndLock) |
| [Environment Variables](https://aka.ms/PowerToysOverview_EnvironmentVariables) | [FancyZones](https://aka.ms/PowerToysOverview_FancyZones) | [File Explorer Add-ons](https://aka.ms/PowerToysOverview_FileExplorerAddOns) |
| [File Locksmith](https://aka.ms/PowerToysOverview_FileLocksmith) | [Hosts File Editor](https://aka.ms/PowerToysOverview_HostsFileEditor) | [Image Resizer](https://aka.ms/PowerToysOverview_ImageResizer) |
| [Keyboard Manager](https://aka.ms/PowerToysOverview_KeyboardManager) | [Mouse utilities](https://aka.ms/PowerToysOverview_MouseUtilities) | [Mouse Without Borders](https://aka.ms/PowerToysOverview_MouseWithoutBorders) |
| [New+](https://aka.ms/PowerToysOverview_NewPlus) | [Peek](https://aka.ms/PowerToysOverview_Peek) | [Paste as Plain Text](https://aka.ms/PowerToysOverview_PastePlain) |
| [PowerRename](https://aka.ms/PowerToysOverview_PowerRename) | [PowerToys Run](https://aka.ms/PowerToysOverview_PowerToysRun) | [Quick Accent](https://aka.ms/PowerToysOverview_QuickAccent) |
| [Registry Preview](https://aka.ms/PowerToysOverview_RegistryPreview) | [Screen Ruler](https://aka.ms/PowerToysOverview_ScreenRuler) | [Shortcut Guide](https://aka.ms/PowerToysOverview_ShortcutGuide) |
| [Text Extractor](https://aka.ms/PowerToysOverview_TextExtractor) | [Workspaces](https://aka.ms/PowerToysOverview_Workspaces) | [ZoomIt](https://aka.ms/PowerToysOverview_ZoomIt) |
| [Color Picker](https://aka.ms/PowerToysOverview_ColorPicker) | [Command Not Found](https://aka.ms/PowerToysOverview_CmdNotFound) | [Command Palette](https://aka.ms/PowerToysOverview_CmdPal) |
| [Crop And Lock](https://aka.ms/PowerToysOverview_CropAndLock) | [Environment Variables](https://aka.ms/PowerToysOverview_EnvironmentVariables) | [FancyZones](https://aka.ms/PowerToysOverview_FancyZones) |
| [File Explorer Add-ons](https://aka.ms/PowerToysOverview_FileExplorerAddOns) | [File Locksmith](https://aka.ms/PowerToysOverview_FileLocksmith) | [Hosts File Editor](https://aka.ms/PowerToysOverview_HostsFileEditor) |
| [Image Resizer](https://aka.ms/PowerToysOverview_ImageResizer) | [Keyboard Manager](https://aka.ms/PowerToysOverview_KeyboardManager) | [Mouse utilities](https://aka.ms/PowerToysOverview_MouseUtilities) |
| [Mouse Without Borders](https://aka.ms/PowerToysOverview_MouseWithoutBorders) | [New+](https://aka.ms/PowerToysOverview_NewPlus) | [Paste as Plain Text](https://aka.ms/PowerToysOverview_PastePlain) |
| [Peek](https://aka.ms/PowerToysOverview_Peek) | [PowerRename](https://aka.ms/PowerToysOverview_PowerRename) | [PowerToys Run](https://aka.ms/PowerToysOverview_PowerToysRun) |
| [Quick Accent](https://aka.ms/PowerToysOverview_QuickAccent) | [Registry Preview](https://aka.ms/PowerToysOverview_RegistryPreview) | [Screen Ruler](https://aka.ms/PowerToysOverview_ScreenRuler) |
| [Shortcut Guide](https://aka.ms/PowerToysOverview_ShortcutGuide) | [Text Extractor](https://aka.ms/PowerToysOverview_TextExtractor) | [Workspaces](https://aka.ms/PowerToysOverview_Workspaces) |
| [ZoomIt](https://aka.ms/PowerToysOverview_ZoomIt) |
## Installing and running Microsoft PowerToys
@@ -34,19 +35,19 @@ Microsoft PowerToys is a set of utilities for power users to tune and streamline
Go to the [Microsoft PowerToys GitHub releases page][github-release-link] and click on `Assets` at the bottom to show the files available in the release. Please use the appropriate PowerToys installer that matches your machine's architecture and install scope. For most, it is `x64` and per-user.
<!-- items that need to be updated release to release -->
[github-next-release-work]: https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+milestone%3A%22PowerToys+0.90%22
[github-current-release-work]: https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+milestone%3A%22PowerToys+0.89%22
[ptUserX64]: https://github.com/microsoft/PowerToys/releases/download/v0.89.0/PowerToysUserSetup-0.89.0-x64.exe
[ptUserArm64]: https://github.com/microsoft/PowerToys/releases/download/v0.89.0/PowerToysUserSetup-0.89.0-arm64.exe
[ptMachineX64]: https://github.com/microsoft/PowerToys/releases/download/v0.89.0/PowerToysSetup-0.89.0-x64.exe
[ptMachineArm64]: https://github.com/microsoft/PowerToys/releases/download/v0.89.0/PowerToysSetup-0.89.0-arm64.exe
[github-next-release-work]: https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+milestone%3A%22PowerToys+0.91%22
[github-current-release-work]: https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+milestone%3A%22PowerToys+0.90%22
[ptUserX64]: https://github.com/microsoft/PowerToys/releases/download/v0.90.0/PowerToysUserSetup-0.90.0-x64.exe
[ptUserArm64]: https://github.com/microsoft/PowerToys/releases/download/v0.90.0/PowerToysUserSetup-0.90.0-arm64.exe
[ptMachineX64]: https://github.com/microsoft/PowerToys/releases/download/v0.90.0/PowerToysSetup-0.90.0-x64.exe
[ptMachineArm64]: https://github.com/microsoft/PowerToys/releases/download/v0.90.0/PowerToysSetup-0.90.0-arm64.exe
| Description | Filename | sha256 hash |
|----------------|----------|-------------|
| Per user - x64 | [PowerToysUserSetup-0.89.0-x64.exe][ptUserX64] | B4F130CC96F321024A257499247F6FF6DA56612215ED3882E868AAE26C689E33 |
| Per user - ARM64 | [PowerToysUserSetup-0.89.0-arm64.exe][ptUserArm64] | F69B00F4E520EB09FA0D1D1669E21910C5225FE7A2EEDC0FA7C283B201A5F9C6 |
| Machine wide - x64 | [PowerToysSetup-0.89.0-x64.exe][ptMachineX64] | E18AC8F9023E341CF7DAD35367FB9DDDB6565D83D8155DBCDDB40AE8A24AE731 |
| Machine wide - ARM64 | [PowerToysSetup-0.89.0-arm64.exe][ptMachineArm64] | 17DEADEC601D6061D7AF4F487595CC36D9191813003CC2ECE381017F0EC71FBB |
| Per user - x64 | [PowerToysUserSetup-0.90.0-x64.exe][ptUserX64] | 2A6036F5B2D454084E55816C306E1E57EF1D14C916691CBDA42B469797605CE0 |
| Per user - ARM64 | [PowerToysUserSetup-0.90.0-arm64.exe][ptUserArm64] | AB2E4DC87A9D764BE897C5170E2890E174C89CA912A1916FA3AE1E427536EA4A |
| Machine wide - x64 | [PowerToysSetup-0.90.0-x64.exe][ptMachineX64] | 12801C44F43D0CC61E90DF1EFDC40E4F3C88341E0199D5B20791042D9B173DCF |
| Machine wide - ARM64 | [PowerToysSetup-0.90.0-arm64.exe][ptMachineArm64] | 2998007C8FCD7BD2770767C6502AAA2CC75B85EC30DE62986EC7005EB0014EDB |
This is our preferred method.
@@ -92,102 +93,95 @@ For guidance on developing for PowerToys, please read the [developer docs](/doc/
Our [prioritized roadmap][roadmap] of features and utilities that the core team is focusing on.
### 0.89 - February 2025 Update
### 0.90 - March 2025 Update
In this release, we focused on new features, stability, accessibility and automation.
In this release, we focused on new features, stability, and automation.
**✨Highlights**
- Enhanced Advanced Paste by adding media transcoding support to convert different video and audio file formats! Thanks [@snickler](https://github.com/snickler) for your help!
- Fixed crashes when loading thumbnails after the .NET 9 update and resolved PowerLauncher.exe blocking other MSI installers from creating shortcuts!
- Fixed accessibility issues across FancyZones, Image Resizer, and Settings to improve screen reader support and clarity!
- Enhanced UI automation framework across modules and added new tests to cover manual checks, with more improvements coming!
![Gif for Command Palette](doc/images/overview/CmdPal_Hero.gif)
### General
- New module: Command Palette ("CmdPal") - Created as the evolution of PowerToys Run with extensibility at the forefront, Command Palette is a quick launcher with a richer display and additional capabilities without sacrificing performance, allowing you to start anything with the shortcut **Win+Alt+Space**! Thanks [@zadjii-msft](https://github.com/zadjii-msft), [@niels9001](https://github.com/niels9001), [@michael-hawker](https://github.com/michael-hawker), [@joadoumie](https://github.com/joadoumie), [@plante-msft](https://github.com/plante-msft), [@ethanfangg](https://github.com/ethanfangg) and [@krschau](https://github.com/krschau)!
- Enhanced the Color Picker by switching from WPF UI to .NET WPF, resulting in improved themes and visual consistency across different modes. Thanks [@mantaionut](https://github.com/mantaionut)! Thanks [@Jay-o-Way](https://github.com/Jay-o-Way) and [@niels9001](https://github.com/niels9001) for helping with the review!
- Added the ability to delete files directly from Peek, enhancing file management efficiency. Thanks [@daverayment](https://github.com/daverayment) and thanks [@htcfreek](https://github.com/htcfreek) for the review!
- Added support for variables in template filenames, enabling dynamic elements like date components and environment variables for enhanced customization in New+. Thanks [@cgaarden](https://github.com/cgaarden)!
- Fixed an issue where updating PowerToys on Windows 11 did not properly update context menu entries, impacting New+, PowerRename, Image Resizer, and File Locksmith.
- Updated .NET Packages from 9.0.1 to 9.0.2. Thanks [@snickler](https://github.com/snickler) for this.
- Enabled compatibility with VS17.3 and later, for C++23. Thanks [@LNKLEO](https://github.com/LNKLEO) for this.
### Color Picker
### Advanced Paste
- Replaced WPF UI with .NET WPF for the Color Picker, enhancing compatibility and improving theme support. Thanks [@mantaionut](https://github.com/mantaionut)! Thanks [@Jay-o-Way](https://github.com/Jay-o-Way) and [@niels9001](https://github.com/niels9001) for helping with the review!
- Added media transcoding support to convert different video and audio file formats, improved UI layouts, refined clipboard handling, and integrated Semantic Kernel for smarter pasting. Thanks [@snickler](https://github.com/snickler) for your help!
### Command Palette
- Introduced the Windows Command Palette ("CmdPal"), the next iteration of PowerToys Run, designed with extensibility at its core. CmdPal includes features such as searching for installed apps, shell commands, files and WinGet package installation. This module aims to provide a more powerful and flexible launcher experience. Thanks [@zadjii-msft](https://github.com/zadjii-msft), [@niels9001](https://github.com/niels9001), [@michael-hawker](https://github.com/michael-hawker), [@joadoumie](https://github.com/joadoumie), [@plante-msft](https://github.com/plante-msft), and the whole team!
### FancyZones
- Fixed accessibility by improving the text for monitors, ensuring clearer naming and help text for screen readers.
- Fixed a bug where deleting a layout resulted in incorrect data being written to the JSON file.
- Fixed a bug where layout hotkeys were displayed incorrectly, ensuring the hotkey list does not include invalid entries.
- Fixed an issue where the "None" option was missing in the editor layout.
### Image Resizer
- Fixed issues with Width and Height fields in Image Resizer's Custom preset, ensuring empty values no longer cause errors, settings save correctly, and auto-scaling behaves as expected. Thanks [@daverayment](https://github.com/daverayment)!
- Fixed accessibility by ensuring screen readers announce selected image dimensions in the combo-box for better navigation.
### Monaco Preview
- Fixed open link in default browser rather than Microsoft Edge. Thanks [@OldUser101](https://github.com/OldUser101)!
### Mouse Highlighter
- Fixed a highlight released on an Administrator window will start fading, instead of staying on the screen indefinitely until the mouse button is pressed again on an unelevated window.
- Fixed warnings in ImageResizer regarding the use of variables "shellItem" and "itemName" without being initialized.
### Mouse Without Borders
- Fixed an issue in service mode where copy-paste and drag-drop file transfers didnt work, ensuring seamless file operations.
- Enabled GPO for enable/disable for Mouse Without Borders in Service Mode. Thanks [@htcfreek](https://github.com/htcfreek) for review and comments!
- Fixed code maintainability by refactoring the oversized 'Common' class in Mouse Without Borders into smaller, focused classes for better structure and clarity. Thanks [@mikeclayton](https://github.com/mikeclayton) and thanks [@htcfreek](https://github.com/htcfreek) for review!
### PowerRename
- Supported negative value as Start value in regular expression, e.g. ${start=-1314}
- Enhanced RegEx help by adding $, ^, quantifiers, and common patterns for better usability. Thanks [@PesBandi](https://github.com/PesBandi) and thanks [@htcfreek](https://github.com/htcfreek) for review.
- Enhanced the logger to properly track the file path for easier debugging.
- Refactored the "Common" class into distinct individual classes to enhance maintainability, and updated all references and unit tests to reflect these changes. Thanks [@mikeclayton](https://github.com/mikeclayton) for this!
### New+
- Added support for variables in template filenames, including date/time components, parent folder name, and environment variables. Thanks [@cgaarden](https://github.com/cgaarden)!
### Peek
- Added the ability to delete the file currently being previewed in Peek, including navigation updates and handling for deleted items. Thanks [@daverayment](https://github.com/daverayment) and thanks [@htcfreek](https://github.com/htcfreek) for your help reviewing this!
### PowerToys Run
- Fixed crashes when loading thumbnails after the .NET 9 update by disabling CETCompat.
- Fixed PowerLauncher.exe blocking other MSI installers creating shortcuts. Thanks [@OneBlue](https://github.com/OneBlue)!
- Fixed Runs dark mode detection to work reliably, preventing issues with incorrect theme detection and ensuring a smoother user experience. Thanks [@daverayment](https://github.com/daverayment)!
- Fixed list separator handling in Calculator, allowing functions with multiple arguments to work correctly across different locales. For example pow(2;3) would be replaced with pow(2,3). Thanks [@PesBandi](https://github.com/PesBandi) and thanks [@htcfreek](https://github.com/htcfreek) for review!
- Fixed angle unit conversions in the PowerToys Run calculator, allowing quick conversions between radians, degrees, and gradians. Thanks [@OldUser101](https://github.com/OldUser101)!
### Quick Accent
- Added ǎ, ǒ and ǔ to the IPA character set. Thanks [@PesBandi](https://github.com/PesBandi)!
- Added ` (backtick) and ~ (tilde) to the VK_OEM_5 character set. Thanks [@xanatos](https://github.com/xanatos)!
- Added ς (final sigma) to the Greek character set. Thanks [@IamSmeagol](https://github.com/IamSmeagol)!
- Fixed an issue where duplicated applications were shown by ensuring the shell link helper opens .ink files non-exclusively and correctly retrieves the "FullPath". Thanks [@htcfreek](https://github.com/htcfreek) and [@davidegiacometti](https://github.com/davidegiacometti) for review!
- Fixed an issue where applying round corners on Windows 11 build 22000 caused crashes.
- Async the OnRename method to unblock the thread. Thanks [@davidegiacometti](https://github.com/davidegiacometti) for review!
- Added support for using `sq` instead of `^2` in the Unit Converter. Thanks [@PesBandi](https://github.com/PesBandi)!
### Settings
- Enabled GPO for the "run at startup" setting. Thanks [@htcfreek](https://github.com/htcfreek) for review and comments!
- Fixed accessibility issue by allowing screen readers to announce the group name for secondary links in Settings pages, instead of reading link descriptions without context.
- Fixed an issue where the Color Picker shortcut was not displaying correctly in the Dashboard.
- Disabled the spell check feature in the text boxes of plugin settings for PowerToys Run. Thanks [@htcfreek](https://github.com/htcfreek)!
- Fixed an issue where InfoBars for release notes errors were not displayed properly, and added a retry button. Thanks [@davidegiacometti](https://github.com/davidegiacometti)!
### Workspaces
- Fixed if a window was last placed on a disconnected monitor, it launches minimized and repositions within the main monitor's visible area when restored, instead of remaining off-screen and invisible.
- Fixed on ARM64 to correctly display icons for packaged apps by resolving path mismatches.
### ZoomIt
- Fixed warning C4706 and related error C2220 during build. Thanks [@xanatos](https://github.com/xanatos)!
- Fixed an issue where some minimized packaged apps (e.g., Microsoft ToDo, Settings) were not snapshotted.
### Documentation
- Fixed runner-ipc.md doc on the broken link. Thanks [@daverayment](https://github.com/daverayment)!
- Fixed the new plugin checklist by updating the target framework, removing duplicates, and improving statement organization. Thanks [@hlaueriksson](https://github.com/hlaueriksson)!
- Updated runner documentation to align with the latest code structure.
- Added the FirefoxBookmark plugin to the list of Third-Party plugins for PowerToys Run. Thanks [@8LWXpg](https://github.com/8LWXpg)!
- Added the SVGL third-party plugin to PowerToys Run, enabling users to search, browse, and copy SVG logos. Thanks [@SameerJS6](https://github.com/SameerJS6)!
- Added Monaco usage for the Registry Preview.
### Development
- Stabilized pipeline on ARM64 and forked build.
- Added fuzz testing for HostUILib, added as part of pipeline for OneFuzz.
- Fixed and improved UI-Test automation framework, and added new test cases for the FancyZones and Hosts module.
- Optimized Logger function as AOT compatible, improving performance by 18%.
- Made Common.UI and Setting.UI to be AOT compatible.
- Updated WinGet configuration file location and extension. Thanks [@mdanish-kh](https://github.com/mdanish-kh)!
- Removed the Markdown file bypass to ensure CI runs for commits that only update Markdown files.
- Fixed an issue where the default generated file path exceeded the length limit of 260 characters for EnvironmentVariablesUILib.csproj, causing build failures.
- Upgraded WindowsAppSDK to 1.6.250205002 and CsWinRT to 2.2.0. Thanks [@htcfreek](https://github.com/htcfreek) for review!
- Upgraded XamlStyler to 3.2501.8 and dotnet-consolidate to 4.2.0. Thanks [@davidegiacometti](https://github.com/davidegiacometti)!
- Updated .NET Packages from 9.0.2 to 9.0.3.
- Optimized the UI Test Automation Framework and added UI test cases for the Hosts File Editor module.
- Added fuzz testing for RegistryPreview.
- Added new UI tests for the FancyZones editor, including tests for creating, duplicating, editing, and deleting layouts.
- Added telemetry code to measure the module editor open time and evaluate the benefits of applying AOT.
### What is being planned for version 0.90
### What is being planned for version 0.91
For [v0.90][github-next-release-work], we'll work on the items below:
For [v0.91][github-next-release-work], we'll work on the items below:
- New module: PowerToys Run v2
- New module: File Actions Menu
- New UI Automation tests
- Working on installer upgrades
- Upgrading keyboard manager's editor UI
- Upgrading Keyboard Manager's editor UI
- Stability / bug fixes
## PowerToys Community

View File

@@ -88,4 +88,4 @@ namespace UITests_KeyboardManager
## Extra tools and information
**Accessibility Tools**:
While working on tests, you may need a tool that helps you to view the element's accessibility data, e.g. for finding the button to click. For this purpose, you could use [AccessibilityInsights](https://accessibilityinsights.io/docs/windows/overview)
While working on tests, you may need a tool that helps you to view the element's accessibility data, e.g. for finding the button to click. For this purpose, you could use [AccessibilityInsights](https://accessibilityinsights.io/docs/windows/overview).

View File

@@ -16,49 +16,70 @@ The 'Time and Date' plugin shows the date and time in different formats. For the
### Available formats
**Remarks**
- The following formats requires a prefix in the query:
- The following formats requires a prefix in the query when using them as date input:
- Unix Timestamp: `u`
- Unix Timestamp in milliseconds: `ums`
- Windows file time: `ft`
- OLE Automation date: `oa`
- Excel 1900 date value: `exc`
- Excel 1904 date value: `exf`
- On invalid number inputs we show a warning that tells the user which prefixes are allowed/required.
**List of available formats**
The following formats are currently available:
| Format | Example (Based on default settings) | As result | As input |
| Format | Example (Based on default settings) | As result | As input | Result as custom format only
|--------------|-----------|------------|------------|
| Time | 5:10 PM | x | x |
| Date | 3/5/2022 | x | x |
| Now | 3/5/2022 5:10 PM | x | x |
| Time UTC | 4:10 PM | x | x |
| Now UTC | 3/5/2022 4:10 PM | x | x |
| Unix Timestamp | 1646496622 | x | x |
| Unix Timestamp in milliseconds | 1646496622500 | x | x |
| Hour | 10 | x | |
| Minute | 30 | x | |
| Second | 45 | x | |
| Millisecond | 678 | x | |
| Day (Week day) | Saturday | x | |
| Day of the week | 6 | x | |
| Day of the month | 5 | x | |
| Day of the year | 64 | x | |
| Week of the month | 1 | x | |
| Week of the year (Calendar week, Week number) | 10 | x | |
| Month | March | x | |
| Month of the year | 3 | x | |
| Month and day | March 7 | x | x |
| Year | 2022 | x | |
| Era | AD | x | |
| Era abbreviation | A | x | |
| Month and year | March 2022 | x | x |
| Windows file time (Int64 number) | 637820976123938199 | x | x |
| Universal time format: YYYY-MM-DD hh:mm:ss| 2022-03-05 16:20:12Z | x | x |
| ISO 8601 | 2022-03-05T17:23:04 | x | x |
| ISO 8601 UTC | 2022-03-05T16:23:04 | x | x |
| ISO 8601 with time zone | 2022-03-05T17:23:04+01:00 | x | x |
| ISO 8601 UTC with time zone | 2022-03-05T16:23:04Z | x | x |
| RFC1123 | Sat, 05 Mar 2022 16:23:04 GMT | x | x |
| Time | 5:10 PM | x | x | |
| Date | 3/5/2022 | x | x | |
| Now | 3/5/2022 5:10 PM | x | x | |
| Time UTC | 4:10 PM | x | x | |
| Now UTC | 3/5/2022 4:10 PM | x | x | |
| Unix Timestamp | 1646496622 | x | x | |
| Unix Timestamp in milliseconds | 1646496622500 | x | x | |
| Hour | 10 | x | | |
| Minute | 30 | x | | |
| Second | 45 | x | | |
| Millisecond | 678 | x | | |
| Day (Week day) | Saturday | x | | |
| Day of the week | 6 | x | | |
| Day of the month | 5 | x | | |
| Day of the year | 64 | x | | |
| Week of the month | 1 | x | | |
| Week of the year (Calendar week, Week number) | 10 | x | | |
| Month | March | x | | |
| Month of the year | 3 | x | | |
| Month and day | March 7 | x | x | |
| Year | 2022 | x | | |
| Era | AD | x | | |
| Era abbreviation | A | x | | |
| Month and year | March 2022 | x | x | |
| Windows file time (Int64 number) | 637820976123938199 | x | x | |
| Universal time format: YYYY-MM-DD hh:mm:ss| 2022-03-05 16:20:12Z | x | x | |
| ISO 8601 | 2022-03-05T17:23:04 | x | x | |
| ISO 8601 UTC | 2022-03-05T16:23:04 | x | x | |
| ISO 8601 with time zone | 2022-03-05T17:23:04+01:00 | x | x | |
| ISO 8601 UTC with time zone | 2022-03-05T16:23:04Z | x | x | |
| RFC1123 | Sat, 05 Mar 2022 16:23:04 GMT | x | x | |
| OLE Automation date | 45723.44143763889 | | x | x |
| Excel's 1900 date value | 45723.44143763889 | | x | x |
| Excel's 1904 date value | 44261.44143763889 | | x | x |
**Custom format definition**
The user can create its own formats. One per line in the settings text box. The format of each line is `<name>=<syntax pattern>`.
If the syntax pattern starting with `UTC:` then we use the UTC time instead of the local time.
As syntax pattern the pattern from `DateTime.ToString()` and the following custom pattern are available:
- DOW: Number of the day in the week.
- WOM: Number of week in the month.
- WOY: Number of the week in the year.
- EAB: Era abbreviation.
- WFT: Windows file time.
- UXT: Unix time stamp.
- UMS: Unix time stamp in milliseconds.
- OAD: OLE Automation date.
- EXC: Excel's 1900 based date value.
- EXF: Excel's 1904 based date value.
### Add new formats
- To add a new formats you have to add them to the method `GetList()` of the [`AvailableResultsList`](/src/modules/launcher/Plugins/Microsoft.PowerToys.Run.Plugin.TimeDate/Components/AvailableResultsList.cs) class.
@@ -73,13 +94,13 @@ The following formats are currently available:
| Key | Type | Default value | Name | Description |
|--------------|--------------|-----------|------------|------------|
| `CalendarFirstWeekRule` | Combo box | `-1` (Use system settings) | First week of the year | Configure the calendar rule for the first week of the year. |
| `FirstDayOfWeek` | Combo box | `-1` (Use system settings) | First day of the week | |
| `OnlyDateTimeNowGlobal` | Checkbox | `true` | Show only 'Time', 'Date', and 'Now' result for system time on global queries | Regardless of this setting, for global queries the first word of the query has to be a complete match. |
| `TimeWithSeconds` | Checkbox | `false` | Show time with seconds | This setting applies to the 'Time' and 'Now' result. |
| `DateWithWeekday` | Checkbox | `false` | Show date with weekday and name of month | This setting applies to the 'Date' and 'Now' result. |
| `HideNumberMessageOnGlobalQuery` | Checkbox | `false` | Hide 'Invalid number input' error message on global queries | |
| `CalendarFirstWeekRule` | Combo box | `-1` (Use system settings) | First week of the year | Configure the calendar rule for the first week of the year. |
| `FirstDayOfWeek` | Combo box | `-1` (Use system settings) | First day of the week | |
| `CustomFormats` | Multiline text box | `string.Empty` | Custom formats | Use date and time string format syntax and DOW (Day of Week), WOM (Week of Month), WOY (Week of the year), EAB (Era abbreviation), WFT (Windows File Time), UXT (Unix Time), UMS (Unix Time in milliseconds), OAD (OLE Automation date), EXC (Excel's 1900 based date value), EXF (Excel's 1904 based date value). If the format starts with UTC:, then Universal Time (UTC) is used. (Use a backslash to escape format sequences and the backslash character as text.) |
## Classes

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 MiB

View File

@@ -40,7 +40,6 @@
<RegistryValue Type="string" Name="Module_CmdPal_Deps" Value="" KeyPath="yes"/>
</RegistryKey>
<File Source="$(var.CmdPalBuildDir)AppPackages\Microsoft.CmdPal.UI_$(var.CmdPalVersion).0_Test\Dependencies\x64\Microsoft.VCLibs.x64.14.00.Desktop.appx" />
<File Source="$(var.CmdPalBuildDir)AppPackages\Microsoft.CmdPal.UI_$(var.CmdPalVersion).0_Test\Dependencies\x64\Microsoft.WindowsAppRuntime.1.6.msix" />
</Component>
</DirectoryRef>
<?else ?>
@@ -50,7 +49,6 @@
<RegistryValue Type="string" Name="Module_CmdPal_Deps" Value="" KeyPath="yes"/>
</RegistryKey>
<File Source="$(var.CmdPalBuildDir)AppPackages\Microsoft.CmdPal.UI_$(var.CmdPalVersion).0_Test\Dependencies\arm64\Microsoft.VCLibs.ARM64.14.00.Desktop.appx" />
<File Source="$(var.CmdPalBuildDir)AppPackages\Microsoft.CmdPal.UI_$(var.CmdPalVersion).0_Test\Dependencies\arm64\Microsoft.WindowsAppRuntime.1.6.msix" />
</Component>
</DirectoryRef>
<?endif ?>

View File

@@ -0,0 +1,998 @@
## Telemetry Prologue
* Before starting your tests, go to General settings, enable "Diagnostic data" and "Enable viewing" and restart PowerToys.
## Telemetry Epilogue
* After finishing your tests, go to General settings, press Diagnostic data viewer and check if you have xml files for the utilities you've tested and if it looks like the events in those xml files were generated by the actions you did with the utilities you've tested.
## [Install tests](tests-checklist-template-installer-section.md)
* install a **previous version** on a clean machine (a clean machine doesn't have the `%localappdata%\Microsoft\PowerToys` folder)
* open the Settings and for each module change at least one option
* open the FancyZones editor and create two custom layouts:
* a canvas layout with 2 zones, use unicode chars in the layout's name
* one from grid template using 4 zones and splitting one zone
* apply the custom canvas layout to the primary desktop
* create a virtual desktop and apply the custom grid layout
* if you have a second monitor apply different templates layouts for the primary desktop and for the second virtual desktop
* install the new version (it will uninstall the old version and install the new version)
- [ ] 1. verify the settings are preserved and FancyZones configuration is still the same
- [ ] 2. test installing as SYSTEM (LocalSystem account)
* Remove current PowerToys.
* Download PsTools from https://learn.microsoft.com/en-us/sysinternals/downloads/psexec
* Run PowerToys installer with psexec tool `psexec.exe -sid <path_to_installer_exe`
* Brief check if all modules are working
* PER-USER and PER-MACHINE TESTS:
* Install **previous version** on a clean machine and update with new per-machine version. Ensure that it is installed in Program files and that registry entries are under **HKLM**/Software/Classes/PowerToys. Go trhough different modules and ensure that they are working correctly.
* Try installing per-user version over already installed per-machine version and ensure that proper error message is shown.
* Remove PowerToys and install per-user version. Ensure that it is installed in <APPDATA>/Local/PowerToys and that registry entries are under **HKCU**/Software/Classes/PowerToys. Go trhough different modules and ensure that they are working correctly.
* Create a new user and install per-user version there as well. Go trhough different modules and ensure that they are working correctly. Ensure that changing settings for one user does not change settings of other user.
## Functional tests
Regressions:
- [ ] 1. https://github.com/microsoft/PowerToys/issues/1414#issuecomment-593529038
- [ ] 2. https://github.com/microsoft/PowerToys/issues/1524
## Localization
Change the Windows language to a language different than English. Then verify if the following screens change their language:
- [ ] 1. System tray menu items
- [ ] 2. Settings
- [ ] 3. OOBE (What's new)
- [ ] 4. Keyboard Manager Editor
- [ ] 5. Color Picker (check the tooltips)
- [ ] 6. FancyZones Editor
- [ ] 7. Power Rename (new WinUI 3 may not be localized)
- [ ] 8. PowerToys Run ("Start typing" string is localized, for example)
- [ ] 9. Image Resizer
- [ ] 10. Shortcut Guide (Windows controls are localized)
- [ ] 11. File Explorer menu entries for Image Resizer, Power Rename and FileLocksmith
- [ ] 12. Hosts File Editor
- [ ] 13. File Locksmith
- [ ] 14. Registry Preview
- [ ] 15. Environment Variables
## [General Settings](tests-checklist-template-settings-section.md)
**Admin mode:**
- [ ] 1. restart PT and verify it runs as user
- [ ] 2. restart as admin and set "Always run as admin"
- [ ] 3. restart PT and verify it runs as admin
* if it's not on, turn on "Run at startup"
- [ ] 4. reboot the machine and verify PT runs as admin (it should not prompt the UAC dialog)
* turn Always run as admin" off
- [ ] 5. reboot the machine and verify it now runs as user
**Modules on/off:**
- [ ] 6. turn off all the modules and verify all module are off
- [ ] 7. restart PT and verify that all module are still off in the settings page and they are actually inactive
- [ ] 8. turn on all the module, all module are now working
- [ ] 9. restart PT and verify that all module are still on in the settings page and they are actually working
**Quick access tray icon flyout:**
- [ ] 10. Use left click on the system tray icon and verify the flyout appears. (It'll take a bit the first time)
- [ ] 11. Try to launch a module from the launch screen in the flyout.
- [ ] 12. Try disabling a module in the all apps screen in the flyout, make it a module that's launchable from the launch screen. Verify that the module is disabled and that it also disappeared from the launch screen in the flyout.
- [ ] 13. Open the main settings screen on a module page. Verify that when you disable/enable the module on the flyout, that the Settings page is updated too.
**Settings backup/restore:**
- [ ] 14. In the General tab, create a backup of the settings.
- [ ] 15. Change some settings in some PowerToys.
- [ ] 16. Restore the settings in the General tab and verify the Settings you've applied were reset.
## Color Picker
* Enable the Color Picker in settings and ensure that the hotkey brings up Color Picker
- [ ] 1. when PowerToys is running unelevated on start-up
- [ ] 2. when PowerToys is running as admin on start-up
- [ ] 3. when PowerToys is restarted as admin, by clicking the restart as admin button in the settings
- [ ] 4. Change `Activate Color Picker shortcut` and check the new shortcut is working
- [ ] 5. Try all three `Activation behavior`s(`Color Picker with editor mode enabled`, `Editor`, `Color Picker only`)
- [ ] 6. Change `Color format for clipboard` and check if the correct format is copied from the Color picker
- [ ] 7. Try to copy color formats to the clipboard from the Editor
- [ ] 8. Check `Show color name` and verify if color name is shown in the Color picker
- [ ] 9. Enable one new format, disable one existing format, reorder enabled formats and check if settings are populated to the Editor
- [ ] 10. Select a color from the history in the Editor
- [ ] 11. Remove color from the history in the Editor
- [ ] 12. Open the Color Picker from the Editor
- [ ] 13. Open Adjust color from the Editor
- [ ] 14. Check Color Picker logs for errors
## [FancyZones Editor](tests-checklist-template-fancyzones-section.md)
- [ ] 1. Open editor from the settings
- [ ] 2. Open editor with a shortcut
- [ ] 3. Create a new layout (grid and canvas)
- [ ] 4. Duplicate a template and a custom layout
- [ ] 5. Delete layout
- [ ] 6. Edit templates (number of zones, spacing, distance to highlight adjacent zones). Verify after reopening the editor that saved settings are kept the same.
- [ ] 7. Edit canvas layout: zones size and position, create or delete zones.
- [ ] 8. Edit grid layout: split, merge, resize zones.
- [ ] 9. Check `Save and apply` and `Cancel` buttons behavior after editing.
- [ ] 10. Assign a layout to each monitor.
- [ ] 11. Assign keys to quickly switch layouts (custom layouts only), `Win + Ctrl + Alt + number`.
- [ ] 12. Assign horizontal and vertical default layouts
- [ ] 13. Test duplicate layout focus
* Select any layout X in 'Templates' or 'Custom' section by click left mouse button
* Mouse right button click on any layout Y in 'Templates' or 'Custom' sections
* Duplicate it by clicking 'Create custom layout' (Templates section) or 'Duplicate' in 'Custom' section
* Expect the layout Y is duplicated
## [FancyZones](tests-checklist-template-fancyzones-section.md)
### Appearance
- [ ] 1. Change colors, opacity and `Show zone number` options. Verify they're applied.
### Excluded apps
- [ ] 1. Exclude some apps, verify that they're not applicable to a zone.
### Dragging
- [ ] 1. `Hold Shift key to activate zones while dragging` on, `Use a non-primary mouse button to toggle zone activation` off. Start dragging a window, then press shift. Zones are shown when dragging a window with shift pressed, hidden when you released shift or snapped zone.
- [ ] 2. `Hold Shift key to activate zones while dragging` on, `Use a non-primary mouse button to toggle zone activation` off. Press shift first, then start dragging a window. Zones are shown when dragging a window with shift pressed, hidden when you released shift or snapped zone.
- [ ] 3. `Hold Shift key to activate zones while dragging` off, `Use a non-primary mouse button to toggle zone activation` on. Zones are shown immediately when dragging a window and hidden when you click a non-primary mouse button or press shift.
- [ ] 4. `Hold Shift key to activate zones while dragging` off, `Use a non-primary mouse button to toggle zone activation` off. Zones are shown immediately when dragging a window, hidden when you press shift.
- [ ] 5. `Hold Shift key to activate zones while dragging` on, `Use a non-primary mouse button to toggle zone activation` on. Zones aren't shown immediately, only when shift is pressed or when a non-primary mouse click changes the state.
- [ ] 6. `Show zones on all monitor whilw dragging a window` - turn on,off, verify behavior.
- [ ] 7. Create a canvas layout with overlapping zones, check zone activation behavior with all `When multiple zones overlap` options
- [ ] 8. `Make dragged window transparent` - turn on, off, verify behavior
### Snapping
Disable FZ and clear `app-zone-history.json` before starting. FancyZones should be disabled, otherwise, it'll save cashed values back to the file.
- [ ] 1. Snap a window to a zone by dragging, verify `app-zone-history.json` contains info about the window position on the corresponding work area.
- [ ] 2. Snap a window to a zone by a keyboard shortcut, verify `app-zone-history.json` contains info about the window position on the corresponding work area.
- [ ] 3. Snap a window to another monitor, verify `app-zone-history.json` contains positions about zones on both monitors.
- [ ] 4. Snap a window to several zones, verify zone numbers in the json file are correct.
- [ ] 5. Snap a window to a zone, unsnap it, verify this app was removed from the json file.
- [ ] 6. Snap the same window to a zone on two different monitors or virtual desktops. Then unsnap from one of them, verify that info about unsnapped zone was removed from `app-zone-history.json`. Verify info about the second monitor/virtual desktop is kept.
- [ ] 7. Enable `Restore the original size of windows when unsnapping`, snap window, unsnap window, verify the window changed its size to original.
- [ ] 8. Disable `Restore the original size of windows when unsnapping`, snap window, unsnap window, verify window size wasn't changed.
- [ ] 9. Disable `Restore the original size of windows when unsnapping`, snap window, enable `Restore the original size of windows when unsnapping`, unsnap window, verify window size wasn't changed.
- [ ] 10. Launch PT in user mode, try to assign a window with administrator privileges to a zone. Verify the notification is shown.
- [ ] 11. Launch PT in administrator mode, assign a window with administrator privileges.
- [ ] 12. Enable `Allow child windows snapping`, drag any child window (e.g. Solution Explorer, Notepad++ search window), verify it can be snapped to a zone.
- [ ] 13. Disable `Allow child windows snapping`, drag any child window (e.g. Solution Explorer, Notepad++ search window), verify it can't be snapped to a zone.
* Open `Task view` , right-click on the window, check the `Show this window on all desktops` or the `Show windows from this app on all desktops` option to turn it on.
- [ ] 14. Turn Show this window on all desktops on, verify you can snap this window to a zone.
- [ ] 15. Turn Show windows from this app on all desktops on, verify you can snap this window to a zone.
### Snapped window behavior
- [ ] 1. `Keep windows in their zones when the screen resolution changes` on, snap a window to a zone, change the screen resolution or scaling, verify window changed its size and position.
- [ ] 2. `Keep windows in their zones when the screen resolution changes` on, snap a window to a zone on the secondary monitor. Disconnect the secondary monitor (the window will be moved to the primary monitor). Reconnect the secondary monitor. Verify the window returned to its zone.
- [ ] 3. `Keep windows in their zones when the screen resolution changes` off, snap a window to a zone, change the screen resolution or scaling, verify window didn't change its size and position.
Enable `During zone layout changes, windows assigned to a zone will match new size/positions` and prepare layouts with 1 and 3 zones where zone size/positions are different.
- [ ] 4. Snap a window to zone 1, change the layout, verify window changed its size/position.
- [ ] 5. Snap a window to zone 3, change the layout, verify window didn't change its size/position because another layout doesn't have a zone with this zone number.
- [ ] 6. Snap a window to zones 1-2, change the layout, verify window changed its size/position to fit zone 1.
- [ ] 7. Snap a window to zones 1-2, change the layout (the window will be snapped to zone 1), then return back to the previous layout, verify the window snapped to 1-2 zones.
- [ ] 8. Disable `During zone layout changes, windows assigned to a zone will match new size/positions`, snap window to zone 1, change layout, verify window didn't change its size/position
Enable `Move newly created windows to their last known zone`.
- [ ] 9. Snap a window to the primary monitor, close and reopen the window. Verify it's snapped to its zone.
- [ ] 10. Snap a window to zones on the primary and secondary monitors. Close and reopen the app. Verify it's snapped to the zone on the active monitor.
- [ ] 11. Snap a window to the secondary monitor (use a different app or unsnap the window from the zone on the primary monitor), close and reopen the window. Verify it's snapped to its zone.
- [ ] 12. Snap a window, turn off FancyZones, move that window, turn FZ on. Verify window returned to its zone.
- [ ] 13. Move unsnapped window to a secondary monitor, switch virtual desktop and return back. Verify window didn't change its position and size.
- [ ] 14. Snap a window, then resize it (it's still snapped, but doesn't fit the zone). Switch the virtual desktop and return back, verify window didn't change its size.
- [ ] 15. Snap a popup window (e.g. Teams), close and reopen it, verify the window appears in its zone.
- [ ] 16. Snap Visual Studio Code to a zone, and open any menu. Verify the menu is where it's supposed to be and not on the top left corner of the zone.
Enable `Move newly created windows to the current active monitor`.
- [ ] 17. Open a window that wasn't snapped anywhere, verify it's opened on the active monitor.
- [ ] 18. Open a window that was snapped on the current virtual desktop and current monitor, verify it's opened in its zone.
- [ ] 19. Open a window that was snappen on the current virtual desktop and another monitor, verify it's opened on the active monitor.
- [ ] 20. Open a window that was snapped on another virtual desktop, verify it's opened on the active monitor.
### Switch between windows in the current zone
Enable `Switch between windows in the current zone` (default shortcut is `Win + PgUp/PgDown`)
- [ ] 1. Snap several windows to one zone, verify switching works.
- [ ] 2. Snap several windows to one zone, switch virtual desktop, return back, verify window switching works.
- [ ] 3. Disable `Switch between windows in the current zone`, verify switching doesn't work.
### Override Windows Snap
- [ ] 1. Disable `Override Windows Snap`, verify it's disabled.
Enable `Override Windows Snap`.
Select Move windows based on `Zone index`.
- [ ] 2. Open the previously not snapped window, press `Win`+`LeftArrow` / `Win`+`RightArrow`, verify it's snapped to a first/last zone.
- [ ] 3. Verify `Win`+`LeftArrow` moves the window to a zone with the previous index.
- [ ] 4. Verify `Win`+`RightArrow` moves the window to a zone with the next index.
- [ ] 5. Verify `Win`+`ArrowUp` and `Win`+`ArrowDown` work as usual.
- [ ] 6. `Move windows between zones across all monitors` disabled. Verify `Win`+`LeftArrow` doesn't move the window to any zone when the window is in the first zone.
- [ ] 7. `Move windows between zones across all monitors` disabled. Verify `Win`+`RightArrow` doesn't move the window to any zone when the window is in the last zone.
One monitor:
- [ ] 8. `Move windows between zones across all monitors` enabled. Verify `Win`+`LeftArrow` and `Win`+`RightArrow` cycles the window between zones.
- [ ] 9. `Move windows between zones across all monitors` disabled. Verify `Win`+`LeftArrow` and `Win`+`RightArrow` cycles the window between zones.
Two and more monitors:
- [ ] 10. `Move windows between zones across all monitors` enabled. Verify `Win`+`LeftArrow` cycles window position moving it from the first zone on the current monitor to the last zone of the left (or rightmost, if the current monitor is leftmost) monitor.
- [ ] 11. `Move windows between zones across all monitors` enabled. Verify `Win`+`RightArrow` cycles window position moving it from the last zone on the current monitor to the first zone of the right (or leftmost, if the current monitor is rightmost) monitor.
Select Move windows based on `Relative position`.
- [ ] 12. Open the previously not snapped window, press `Win`+`Arrow`, verify it's snapped.
- [ ] 13. Extend the window using `Ctrl`+`Alt`+`Win`+`Arrow`. Verify the window is snapped to all zones.
- [ ] 14. Extend the window using `Ctrl`+`Alt`+`Win`+`Arrow` and return it back using the opposite arrow. Verify it could be reverted while you hold `Ctrl`+`Alt`+`Win`.
- [ ] 15. `Move windows between zones across all monitors` disabled. Verify `Win`+`LeftArrow` cycles the window position to the left (from the leftmost zone moves to the rightmost in the same row) within one monitor.
- [ ] 16. `Move windows between zones across all monitors` disabled. Verify `Win`+`RightArrow` cycles the window position to the right within one monitor.
- [ ] 17. `Move windows between zones across all monitors` disabled. Verify `Win`+`UpArrow` cycles the window position up within one monitor.
- [ ] 18. `Move windows between zones across all monitors` disabled. Verify `Win`+`DownArrow` cycles the window position down within one monitor.
- [ ] 19. `Move windows between zones across all monitors` enabled. Verify `Win`+`LeftArrow` cycles the window position to the left (from the leftmost zone moves to the rightmost in the same row) within all monitors.
- [ ] 20. `Move windows between zones across all monitors` enabled. Verify `Win`+`RightArrow` cycles the window position to the right within all monitors.
- [ ] 21. `Move windows between zones across all monitors` enabled. Verify `Win`+`UpArrow` cycles the window position up within all monitors.
- [ ] 22. `Move windows between zones across all monitors` enabled. Verify `Win`+`DownArrow` cycles the window position down within all monitors.
### Layout apply
Enable `Enable quick layout switch`, assign numbers to custom layouts.
- [ ] 1. Switch with `Win` + `Ctrl` + `Alt` + `key`.
- [ ] 2. Switch with just a key while dragging a window.
- [ ] 3. Turn `Flash zones when switching layout` on/off, verify it's flashing/not flashing after pressing the shortcut.
- [ ] 4. Disable `Enable quick layout switch`, verify shortcuts don't work.
- [ ] 5. Disable spacing on any grid layout, verify that there is no space between zones while dragging a window.
- [ ] 6. Create a new virtual desktop, verify that there are the same layouts as applied to the previous virtual desktop.
- [ ] 7. After creating a virtual desktop apply another layout or edit the applied one. Verify that the other virtual desktop layout wasn't changed.
- [ ] 8. Delete an applied custom layout in the Editor, verify that there is no layout applied instead of it.
- [ ] 9. Apply a grid layout, change the screen resolution or scaling, verify that the assigned layout fits the screen. NOTE: canvas layout could not fit the screen if it was created on a monitor with a different resolution.
### Layout reset
* Test layout resetting.
Before testing
* Remove all virtual desktops
* Remove `CurrentVirtualDesktop` from `\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\SessionInfo\1\VirtualDesktops`
* Remove `VirtualDesktopIDs` from `\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\VirtualDesktops`
- [ ] 1. Test screen locking
* Set custom layouts on each monitor
* Lock screen / unplug monitor / plug monitor
* Verify that layouts weren't reset to defaults
- [ ] 2. Test restart
* Set custom layouts on each monitor
* Restart the computer
* Verify that layouts weren't reset to defaults
- [ ] 3. Test applying default layouts on reset
* Set default horizontal and vertical layouts
* Delete `applied-layouts.json`
* Verify that selected default layout is applied according to configuration
### Span zones across monitors
- [ ] 1. Switch between `Allow zones to span across monitors` on and off. Verify that layouts are applied correctly in both cases.
Repeat the previous subsections steps after enabling `Allow zones to span across monitors`
- [ ] 2. Dragging
- [ ] 3. Snapping
- [ ] 4. Snapped window behavior
- [ ] 5. Switch between windows in the current zone
- [ ] 6. Override Windows Snap
- [ ] 7. Layout apply
- [ ] 8. Layout reset
## File Explorer Add-ons
* Running as user:
* go to PowerToys repo root
- [ ] 1. verify the README.md Preview Pane shows the correct content
* go to PowerToys repo and visit src\modules\ShortcutGuide\ShortcutGuide\svgs
- [ ] 2. verify Preview Pane works for the SVG files
- [ ] 3. verify the Icon Preview works for the SVG file (loop through different icon preview sizes)
* go to PowerToys repo and visit src\modules\previewpane\UnitTests-PdfPreviewHandler\HelperFiles
- [ ] 4. verify Preview Pane works for the PDF file
- [ ] 5. verify the Icon Preview works for the PDF file (loop through different icon preview sizes)
* go to PowerToys repo and visit src\modules\previewpane\UnitTests-GcodePreviewHandler\HelperFiles
- [ ] 6. verify Preview Pane works for the gcode file
- [ ] 7. verify the Icon Preview works for the gcode file (loop through different icon preview sizes)
* go to PowerToys repo and visit src\modules\previewpane\UnitTests-StlThumbnailProvider\HelperFiles
- [ ] 8. verify the Icon Preview works for the stl file (loop through different icon preview sizes)
* go to PowerToys repo and visit src\runner
- [ ] 9. verify Preview Pane works for source files (shows syntax highlighting)
* Running as admin (or user since recently):
* open the Settings and turn off the Preview Pane and Icon Previous toggles
* go to PowerToys repo root
- [ ] 10. verify the README.md Preview Pane doesn't show any content
* go to PowerToys repo and visit src\modules\ShortcutGuide\ShortcutGuide\svgs
- [ ] 11. verify Preview Pane doesn't show the preview for the SVG files
* the Icon Preview for the existing SVG will still show since the icons are cached (you can also use `cleanmgr.exe` to clean all thumbnails cached in your system). You may need to restart the machine for this setting to apply as well.
- [ ] 12. copy and paste one of the SVG file and verify the new file show the generic SVG icon
* go to PowerToys repo and visit src\modules\previewpane\UnitTests-PdfPreviewHandler\HelperFiles
- [ ] 13. verify Preview Pane doesn't show the preview for the PDF file
* go to PowerToys repo and visit src\modules\previewpane\UnitTests-GcodePreviewHandler\HelperFiles
- [ ] 14. verify Preview Pane doesn't show the preview for the gcode file
* go to PowerToys repo and visit src\modules\previewpane\UnitTests-StlThumbnailProvider\HelperFiles
- [ ] 15. verify Preview Pane doesn't show the preview for the stl file (a generated thumbnail would show when there's no preview)
* go to PowerToys repo and visit src\runner
- [ ] 16. verify Preview Pane doesn't show the preview for source code files or that it's a default previewer instead of Monaco
## Image Resizer
- [ ] 1. Disable the Image Resizer and check that `Resize images` is absent in the context menu
- [ ] 2. Enable the Image Resizer and check that `Resize images` is present in the context menu. (On Win11) Check if both old context menu and Win11 tier1 context menu items are present when module is enabled.
- [ ] 3. Remove one image size and add a custom image size. Open the Image Resize window from the context menu and verify that changes are populated
- [ ] 4. Resize one image
- [ ] 5. Resize multiple images
- [ ] 6. Open the image resizer to resize a `.gif` file and verify the "Gif files with animations may not be correctly resized." warning appears.
- [ ] 7. Resize images with `Fill` option
- [ ] 8. Resize images with `Fit` option
- [ ] 9. Resize images with `Stretch` option
- [ ] 10. Resize images using dimension: Centimeters
- [ ] 11. Resize images using dimension: Inches
- [ ] 12. Resize images using dimension: Percents
- [ ] 13. Resize images using dimension: Pixels
- [ ] 14. Change `Filename format` to `%1 - %2 - %3 - %4 - %5 - %6` and check if the new format is applied to resized images
- [ ] 15. Check `Use original date modified` and verify that modified date is not changed for resized images. Take into account that `Resize the original pictures(don't create copy)` should be selected
- [ ] 16. Check `Make pictures smaller but not larger` and verify that smaller pictures are not resized
- [ ] 17. Check `Resize the original pictures (don't create copies)` and verify that the original picture is resized and a copy is not created
- [ ] 18. Uncheck `Ignore the orientation of pictures` and verify that swapped width and height will actually resize a picture if the width is not equal to the height
## [Keyboard Manager](tests-checklist-template-keyboard-manager-section.md)
UI Validation:
- [ ] 1. In Remap keys, add and remove rows to validate those buttons. While the blank rows are present, pressing the OK button should result in a warning dialog that some mappings are invalid.
- [ ] 2. Using only the Type buttons, for both the remap windows, try adding keys/shortcuts in all the columns. The right-side column in both windows should accept both keys and shortcuts, while the left-side column will accept only keys or only shortcuts for Remap keys and Remap shortcuts respectively. Validate that the Hold Enter and Esc accessibility features work as expected.
- [ ] 3. Using the drop downs try to add key to key, key to shortcut, shortcut to key and shortcut to shortcut remapping and ensure that you are able to select remapping both by using mouse and by keyboard navigation.
- [ ] 4. Validate that remapping can be saved by pressing the OK button and re-opening the windows loads existing remapping.
Remapping Validation:
For all the remapping below, try pressing and releasing the remapped key/shortcut and pressing and holding it. Try different behaviors like releasing the modifier key before the action key and vice versa.
- [ ] 5. Test key to key remapping
- A->B
- Ctrl->A
- A->Ctrl
- Win->B (make sure Start menu doesn't appear accidentally)
- B->Win (make sure Start menu doesn't appear accidentally)
- A->Disable
- Win->Disable
- [ ] 6. Test key to shortcut remapping
- A->Ctrl+V
- B->Win+A
- [ ] 7. Test shortcut to shortcut remapping
- Ctrl+A->Ctrl+V
- Win+A->Ctrl+V
- Ctrl+V->Win+A
- Win+A->Win+F
- [ ] 8. Test shortcut to key remapping
- Ctrl+A->B
- Ctrl+A->Win
- Win+A->B
* Test app-specific remaps
- [ ] 9. Similar remaps to above with Edge (entered as `msedge`), VSCode (entered as `code`) and cmd (entered as `windowsterminal`). For cmd try admin and non-admin (requires PT to run as admin)
- [ ] 10. Try some cases where focus is lost due to the shortcut. Example remapping to Alt+Tab or Alt+F4
- [ ] 11. Test switching between remapping while holding down modifiers - Eg. Ctrl+D->Ctrl+A and Ctrl+E->Ctrl+V, hold Ctrl and press D followed by E. Should select all and paste over it in a text editor. Similar steps for Windows key shortcuts.
## PowerRename
- [ ] 1. Check if disable and enable of the module works. (On Win11) Check if both old context menu and Win11 tier1 context menu items are present when module is enabled.
- [ ] 2. Check that with the `Show icon on context menu` icon is shown and vice versa.
- [ ] 3. Check if `Appear only in extended context menu` works.
- [ ] 4. Enable/disable autocomplete.
- [ ] 5. Enable/disable `Show values from last use`.
* Select several files and folders and check PowerRename options:
- [ ] 6. Make Uppercase/Lowercase/Titlecase (could be selected only one at the time)
- [ ] 7. Exclude Folders/Files/Subfolder Items (could be selected several)
- [ ] 8. Item Name/Extension Only (one at the time)
- [ ] 9. Enumerate Items. Test advanced enumeration using different values for every field ${start=10,increment=2,padding=4}.
- [ ] 10. Case Sensitive
- [ ] 11. Match All Occurrences. If checked, all matches of text in the `Search` field will be replaced with the Replace text. Otherwise, only the first instance of the `Search` for text in the file name will be replaced (left to right).
* Use regular expressions
- [ ] 12. Search with an expression (e.g. `(.*).png`)
- [ ] 13. Replace with an expression (e.g. `foo_$1.png`)
- [ ] 14. Replace using file creation date and time (e.g. `$hh-$mm-$ss-$fff` `$DD_$MMMM_$YYYY`)
- [ ] 15. Turn on `Use Boost library` and test with Perl Regular Expression Syntax (e.g. `(?<=t)est`)
* File list filters.
- [ ] 16. In the `preview` window uncheck some items to exclude them from renaming.
- [ ] 17. Click on the `Renamed` column to filter results.
- [ ] 18. Click on the `Original` column to cycle between checked and unchecked items.
## [PowerToys Run](tests-checklist-template-powertoys-runner-section.md)
* Enable PT Run in settings and ensure that the hotkey brings up PT Run
- [ ] 1. when PowerToys is running unelevated on start-up
- [ ] 2. when PowerToys is running as admin on start-up
- [ ] 3. when PowerToys is restarted as admin, by clicking the restart as admin button in settings.
* Check that each of the plugins is working:
- [ ] 4. Program - launch a Win32 application
- [ ] 5. Program - launch a Win32 application as admin
- [ ] 6. Program - launch a packaged application
- [ ] 7. Calculator - ensure a mathematical input returns a correct response and is copied on enter.
- [ ] 8. Windows Search - open a file on the disk.
- [ ] 9. Windows Search - find a file and copy file path.
- [ ] 10. Windows Search - find a file and open containing folder.
- [ ] 11. Shell - execute a command. Enter the action keyword `>`, followed by the query, both with and without space (e.g. `> ping localhost`).
- [ ] 12. Folder - Search and open a sub-folder on entering the path.
- [ ] 13. Uri - launch a web page on entering the uri.
- [ ] 14. Window walker - Switch focus to a running window.
- [ ] 15. Service - start, stop, restart windows service. Enter the action keyword `!` to get the list of services.
- [ ] 16. Registry - navigate through the registry tree and open registry editor. Enter the action keyword `:` to get the root keys.
- [ ] 17. Registry - navigate through the registry tree and copy key path.
- [ ] 18. System - test `lock`.
- [ ] 19. System - test `empty recycle bin`.
- [ ] 20. System - test `shutdown`.
- [ ] 21. Disable PT Run and ensure that the hotkey doesn't bring up PT Run.
- [ ] 22. Test tab navigation.
* Test Plugin Manager
- [ ] 23. Enable/disable plugins and verify changes are picked up by PT Run
- [ ] 24. Change `Direct activation phrase` and verify changes are picked up by PT Run
- [ ] 25. Change `Include in global result` and verify changes picked up by PT Run
- [ ] 26. Clear `Direct activation phrase` and uncheck `Include in global result`. Verify a warning message is shown.
- [ ] 27. Disable all plugins and verify the warning message is shown.
## Shortcut Guide
* Run PowerToys as user:
- [ ] 1. Verify `Win + Shift + /` opens the guide
- [ ] 2. Change the hotkey to a different shortcut (e.g. `Win + /`) and verify it works
- [ ] 3. Set Shortcut Guide to start with a Windows key press and verify it works.
* Restore the `Win + Shift + /` hotkey.
- [ ] 4. Open the guide and close it pressing `Esc`
- [ ] 5. Open the guide and close it pressing and releasing the `Win` key
* With PowerToys running as a user, open an elevated app and keep it on foreground:
- [ ] 6. Verify `Win + Shift + /` opens the guide
- [ ] 7. Verify some of the shortcuts shown in the guide work and the guide is closed when pressed
## OOBE
* Quit PowerToys
* Delete %localappdata%\Microsoft\PowerToys
- [ ] 1. Start PowerToys and verify OOBE opens
* Change version saved on `%localappdata%\Microsoft\PowerToys\last_version.txt`
- [ ] 2. Start PowerToys and verify OOBE opens in the "What's New" page
* Visit each OOBE section and for each section:
- [ ] 3. open the Settings for that module
- [ ] 4. verify the Settings work as expected (toggle some controls on/off etc.)
- [ ] 5. close the Settings
- [ ] 6. if it's available, test the `Launch module name` button
* Close OOBE
- [ ] 7. Open the Settings and from the General page open OOBE using the `Welcome to PowerToys` link
## [Mouse Utils](tests-checklist-template-mouse-utils-section.md)
Find My Mouse:
* Enable FindMyMouse. Then, without moving your mouse:
- [ ] 1. Press Left Ctrl twice and verify the overlay appears.
- [ ] 2. Press any other key and verify the overlay disappears.
- [ ] 3. Press Left Ctrl twice and verify the overlay appears.
- [ ] 4. Press a mouse button and verify the overlay disappears.
* Disable FindMyMouse. Verify the overlay no longer appears when you press Left Ctrl twice.
* Enable FindMyMouse. Then, without moving your mouse:
- [ ] 5. Press Left Ctrl twice and verify the overlay appears.
* Enable the "Do not activate on game mode" option. Start playing a game that uses CG native full screen.
- [ ] 6. Verify the overlay no longer appears when you press Left Ctrl twice.
* Disable the "Do not activate on game mode" option. Start playing the same game.
- [ ] 7. Verify the overlay appears when you press Left Ctrl twice. (though it'll likely minimize the game)
* Test the different settings and verify they apply:
- [ ] 8. Overlay opacity
- [ ] 9. Background color
- [ ] 10. Spotlight color
- [ ] 11. Spotlight radius
- [ ] 12. Spotlight initial zoom (1x vs 9x will show the difference)
- [ ] 13. Animation duration
- [ ] 14. Change activation method to shake and activate by shaking your mouse pointer
- [ ] 15. Excluded apps
Mouse Highlighter:
* Enable Mouse Highlighter. Then:
- [ ] 16. Press the activation shortcut and press left and right click somewhere, verifying the hightlights are applied.
- [ ] 17. With left mouse button pressed, drag the mouse and verify the hightlight is dragged with the pointer.
- [ ] 18. With right mouse button pressed, drag the mouse and verify the hightlight is dragged with the pointer.
- [ ] 19. Press the activation shortcut again and verify no highlights appear when the mouse buttons are clicked.
- [ ] 20. Disable Mouse Highlighter and verify that the module is not activated when you press the activation shortcut.
* Test the different settings and verify they apply:
- [ ] 21. Change activation shortcut and test it
- [ ] 22. Left button highlight color
- [ ] 23. Right button highlight color
- [ ] 24. Opacity
- [ ] 25. Radius
- [ ] 26. Fade delay
- [ ] 27. Fade duration
Mouse Pointer Crosshairs:
* Enable Mouse Pointer Crosshairs. Then:
- [ ] 28. Press the activation shortcut and verify the crosshairs appear, and that they follow the mouse around.
- [ ] 29. Press the activation shortcut again and verify the crosshairs disappear.
- [ ] 30. Disable Mouse Pointer Crosshairs and verify that the module is not activated when you press the activation shortcut.
* Test the different settings and verify they apply:
- [ ] 31. Change activation shortcut and test it
- [ ] 32. Crosshairs color
- [ ] 33. Crosshairs opacity
- [ ] 34. Crosshairs center radius
- [ ] 35. Crosshairs thickness
- [ ] 36. Crosshairs border color
- [ ] 37. Crosshairs border size
Mouse Jump:
* Enable Mouse Jump. Then:
- [ ] 38. Press the activation shortcut and verify the screens preview appears.
- [ ] 39. Change activation shortcut and verify that new shorctut triggers Mouse Jump.
- [ ] 40. Click around the screen preview and ensure that mouse cursor jumped to clicked location.
- [ ] 41. Reorder screens in Display settings and confirm that Mouse Jump reflects the change and still works correctly.
- [ ] 42. Change scaling of screens and confirm that Mouse Jump still works correctly.
- [ ] 43. Unplug additional monitors and confirm that Mouse Jump still works correctly.
- [ ] 44. Disable Mouse Jump and verify that the module is not activated when you press the activation shortcut.
## Awake
- [ ] 1. Try out the features and see if they work, no list at this time.
## Always on Top
- [ ] 1. Pin/unpin a window, verify it's topmost/not topmost.
- [ ] 2. Pin/unpin a window, verify the border appeared/disappeared.
- [ ] 3. Switch virtual desktop, verify border doesn't show up on another desktop.
- [ ] 4. Minimize and maximize pinned window, verify the border looks as usual.
- [ ] 5. Change border color and thickness.
- [ ] 6. Verify if sound is played according to the sound setting.
- [ ] 7. Exclude app, try to pin it.
- [ ] 8. Exclude already pinned app, verify it was unpinned.
- [ ] 9. Try to pin the app in the Game Mode.
## Screen Ruler
* Enable Screen Ruler. Then:
- [ ] 1. Press the activation shortcut and verify the toolbar appears.
- [ ] 2. Press the activation shortcut again and verify the toolbar disappears.
- [ ] 3. Disable Screen Ruler and verify that the activation shortuct no longer activates the utility.
- [ ] 4. Enable Screen Ruler and press the activation shortcut and verify the toolbar appears.
- [ ] 5. Select the close button in the toolbar and verify it closes the utility.
* With Screen Ruler enabled and activated:
- [ ] 6. Use the Bounds utility to measure a zone by dragging with left-click. Verify right click dismisses the utility and that the measurement was copied into the clipboard.
- [ ] 7. Use the Spacing utility to measure something and verify that left-click copies the measurement to the clipboard. Verify that right-click dismisses the utility.
- [ ] 8. Use the Horizontal Spacing utility to measure something and verify that left-click copies the measurement to the clipboard. Verify that right-click dismisses the utility.
- [ ] 9. Use the Vertical Spacing utility to measure something and verify that left-click copies the measurement to the clipboard. Verify that right-click dismisses the utility.
- [ ] 10. While using a Spacing utility, verify that using the mouse scroll wheel will adjust pixel color tolerance while measuring.
- [ ] 11. Open mspaint and draw 1px-thick straight line, also click with a pencil to draw a single pixel. In any Spacing mode, verify that one of line's dimension is 1, and pixel's dimensions are 1x1.
* In a multi-monitor setup with different dpis on each monitor:
- [ ] 12. Verify that the utilities work well on each monitor, with continuous mode on and off.
- [ ] 13. Without any window opened and a solid color as your background, verify the horizontal spacing matches the monitor's pixel width.
- [ ] 14. Move your mouse back and forth around the edge of two monitors really quickly in each mode - verify nothing is broken.
* Test the different settings and verify they are applied:
- [ ] 15. Activation shortcut
- [ ] 16. Continous mode
- [ ] 17. Per color channel edge detection
- [ ] 18. Pixel tolerance for edge detection
- [ ] 19. Draw feet on cross
- [ ] 20. Line color
## Quick Accent
* Enable Quick Accent and open notepad. Then:
- [ ] 1. Press `a` and the left or right arrow and verify the accent menu appears and adds the accented letter you've selected. Use left and arrow keys to cycle through the options.
- [ ] 2. Press `a` and the space key and verify the accent menu appears and adds the accented letter you've selected. Use <kbd>Space</kbd> to navigate forward, <kbd>Space</kbd> + <kbd>Shift</kbd> to navigate backward.
- [ ] 3. Disable Quick Accent and verify you can no longer add accented characters through Quick Accent.
* Test the different settings and verify they are applied:
- [ ] 4. Activation key
- [ ] 5. Language (for example, Currency has no accents for 'a' but has for 's')
- [ ] 6. Toolbar position (test every option, some had issues before)
- [ ] 7. Input delay
- [ ] 8. Exclude some apps. Verify that Quick Accent is not activated for them.
- [ ] 9. Sort characters by frequency.
- [ ] 10. Always start on the first character when using left/right arrows as activation method.
## [Text Extractor](tests-checklist-template-text-extractor-section.md)
* Enable Text Extractor. Then:
- [ ] 1. Press the activation shortcut and verify the overlay appears.
- [ ] 2. Press Escape and verify the overlay disappears.
- [ ] 3. Press the activation shortcut and verify the overlay appears.
- [ ] 4. Right-click and select Cancel. Verify the overlay disappears.
- [ ] 5. Disable Text Extractor and verify that the activation shortuct no longer activates the utility.
* With Text Extractor enabled and activated:
- [ ] 6. Try to select text and verify it is copied to the clipboard.
- [ ] 7. Try to select a different OCR language by right-clicking and verify the change is applied.
* In a multi-monitor setup with different dpis on each monitor:
- [ ] 8. Verify text is correctly captured on all monitors.
* Test the different settings and verify they are applied:
- [ ] 9. Activation shortcut
- [ ] 10. OCR Language
## Hosts File Editor
* Launch Host File Editor:
- [x] 1. Verify the application exits if "Quit" is clicked on the initial warning.
- TestMethod("Hosts.Settings.ShowWarningDialogIfRunAsAdmin")
- [ ] 2. Launch Host File Editor again and click "Accept". The module should not close. Open the hosts file (`%WinDir%\System32\Drivers\Etc`) in a text editor that auto-refreshes so you can see the changes applied by the editor in real time. (VSCode is an editor like this, for example)
- [ ] 3. Enable and disable lines and verify they are applied to the file.
- [x] 4. Add a new entry and verify it's applied.
- TestMethod("Hosts.Basic.EmptyViewShouldWork")
- TestMethod("Hosts.Basic.AddEntryButtonShouldWork")
- [x] 5. Add manually an entry with more than 9 hosts in hosts file (Windows limitation) and verify it is split correctly on loading and the info bar is shown.
- TestMethod("Hosts.Basic.CanNotAddMoreThenNighHosts")
- [x] 6. Try to filter for lines and verify you can find them.
- TestMethod("Hosts.Basic.FiltersControlShouldWork")
- [ ] 7. Click the "Open hosts file" button and verify it opens in your default editor. (likely Notepad)
* Test the different settings and verify they are applied:
- [x] 8. Launch as Administrator.
- TestMethod("Hosts.Basic.ErrorMessgeShowupIfNotRunAsAdmin")
- TestMethod("Hosts.Basic.NoErrorMessgeShowupIfRunAsAdmin")
- [x] 9. Show a warning at startup.
- TestMethod("Hosts.Settings.ShowWarningDialogIfRunAsAdmin")
- [ ] 10. Additional lines position.
## File Locksmith
* Start the PowerToys installer executable and let it stay in the initial screen.
- [ ] 1. Right-click the executable file, select "What's using this file?" and verify it shows up. (2 entries will show, since the installer starts two processes)
- [ ] 2. End the tasks in File Locksmith UI and verify that closes the installer.
- [ ] 3. Start the installer executable again and press the Refresh button in File Locksmith UI. It should find new processes using the files.
- [ ] 4. Close the installer window and verify the processes are delisted from the File Locksmith UI. Close the window
* Start the PowerToys installer executable again and let it stay in the initial screen.
- [ ] 5. Right click the directory where the executable is located, select "What's using this file?" and verify it shows up.
- [ ] 6. Right click the drive where the executable is located, select "What's using this file?" and verify it shows up. You can close the PowerToys installer now.
* Restart PowerToys as admin.
- [ ] 7. Right click "Program Files", select "What's using this file?" and verify "PowerToys.exe" doesn't show up.
- [ ] 8. Press the File Locksmith "Restart as an administrator" button and verify "PowerToys.exe" shows up.
- [ ] 9. Right-click the drive where Windows is installed, select "What's using this file?" and scroll down and up, verify File Locksmith doesn't crash with all those entries being shown. Repeat after clicking the File Locksmith "Restart as an administrator" button.
- [ ] 10. Disable File Locksmith in Settings and verify the context menu entry no longer appears.
## GPO
* Copy the "PowerToys.admx" file to your Policy Definition template folder. (Example: C:\Windows\PolicyDefinitions) and copy the "PowerToys.adml" file to the matching language folder in your Policy Definition folder. (Example: C:\Windows\PolicyDefinitions\en-US)
- [ ] 1. Open the "Local Group Policy Editor" on Windows and verify there is a "Microsoft PowerToys" folder in Administrative Templates for both Computer Configuration and User Configuration.
* In GPO, disable a module that can run as a standalone (FancyZones sounds good for this). Restart PowerToys.
- [ ] 2. Verify the module is not enabled.
- [ ] 3. Open settings and verify the module is not enabled and you can't enable it.
- [ ] 4. Try to open FancyZones Editor directly from the install folder and verify it doesn't run and adds a message to the log saying it didn't run because of GPO.
- [ ] 5. Verify the module can't be launched from the quick launcher system tray flyout launcher screen (FancyZones editor in this case).
- [ ] 6. Verify the module can't be enabled/disabled from the quick launcher system tray flyout.
* In GPO, enable a module that can run as a standalone (FancyZones sounds good for this). Restart PowerToys.
- [ ] 7. Verify the module is enabled.
- [ ] 8. Open settings and verify the module is enabled and you can't disable it.
- [ ] 9. Verify the module can't be enabled/disabled from the quick launcher system tray flyout.
* In GPO, try to set different settings in the Computer and User Configurations for a PowerToy. Restart PowerToys.
- [ ] 10. Verify that the setting in Computer Configuration has priority over the setting in User Configuration.
* In GPO, disable a module that has a context menu entry (File Locksmith sounds good for this). Restart PowerToys.
- [ ] 11. Verify the module is not enabled. (No context menu entry)
- [ ] 12. Open settings and verify the module is not enabled and you can't enable it.
- [ ] 13. Try to open File Locksmith directly from the install folder and verify it doesn't run and adds a message to the log saying it didn't run because of GPO.
* In GPO, disable a module that is a Preview Handler (Markdown Preview is good for this). Restart PowerToys.
- [ ] 14. Verify the module is not enabled. (Markdown files won't appear in the preview pane)
- [ ] 15. Open settings and verify the module is not enabled and you can't enable it.
* Remember to reset all you Settings to Not Configured after the tests, both in Conputer and User Configurations.
## Registry Preview
* Open Registry Editor, add new registry key with 1 string value and 1 binary value in e.g. HKLM/Software/Classes/PowerToysTest. Right click new registry key->export and export it to file.
* Launch Registry Preview by right-clicking exported .reg file->'Preview'. Then:
- [ ] 1. Edit file content. Ensure that visual try is being re-populated while typing. Save the file by pressing Save file button. Confirm that file is properly saved by pressing Edit file... button which will open file in Notepad. Try saving file using Save file as... button.
- [ ] 2. Edit file externaly (e.g. in Notepad) and save it there. Pres Reload from file button and ensure that file content and visual tree are reloaded and show new content.
- [ ] 3. Select some registry key with registry values in visual tree and ensure that registry values are shown properly in bottom-right area.
- [ ] 4. Try opening different registry file by pressing Open file button.
- [ ] 5. Delete newly created registry key from first step manually in Registry Editor, then try writing registry changes to registry by pressing Write to Registry button in Registry Preview. *Be careful what you are writing!*
* Open Registry Preview Settings. Then:
- [ ] 6. Disable Registry Preview and ensure that Preview context menu option for .reg files no longer appears.
- [ ] 7. Try to launch Registry Preview from it's OOBE page while Registry Preview is disabled and ensure that it does not start.
- [ ] 8. Enable Registry Preview again and ensure that Preview context menu option for .reg files appears and that it starts Registry Preview correctly.
- [ ] 9. Try to launch Registry Preview from it's Settings page and ensure that it is launched properly.
- [ ] 10. Try to launch Registry Preview from it's OOBE page and ensure that it is launched properly.
- [ ] 11. Enable Default app setting. Verify that .reg files are opened with Registry Preview by default. Disable Default app setting. Verify that Registry Editor is now default app.
## [Peek](tests-checklist-template-peek-section.md)
* Open different files to check that they're shown properly
- [ ] 1. Image
- [ ] 2. Text or dev file
- [ ] 3. Markdown file
- [ ] 4. PDF
- [ ] 5. HTML
- [ ] 6. Archive files (.zip, .tar, .rar)
- [ ] 7. Any other not mentioned file (.exe for example) to verify the unsupported file view is shown
* Pinning/unpinning
- [ ] 8. Pin the window, switch between images of different size, verify the window stays at the same place and the same size.
- [ ] 9. Pin the window, close and reopen Peek, verify the new window is opened at the same place and the same size as before.
- [ ] 10. Unpin the window, switch to a different file, verify the window is moved to the default place.
- [ ] 11. Unpin the window, close and reopen Peek, verify the new window is opened on the default place.
* Open with a default program
- [ ] 12. By clicking a button.
- [ ] 13. By pressing enter.
- [ ] 14. Switch between files in the folder using `LeftArrow` and `RightArrow`, verify you can switch between all files in the folder.
- [ ] 15. Open multiple files, verify you can switch only between selected files.
- [ ] 16. Change the shortcut, verify the new one works.
## [Mouse Without Borders](tests-checklist-template-mouse-without-borders-section.md)
* Install PowerToys on two PCs in the same local network:
- [ ] 1. Verify that PowerToys is properly installed on both PCs.
* Setup Connection:
- [ ] 2. Open MWB's settings on the first PC and click the "New Key" button. Verify that a new security key is generated.
- [ ] 3. Copy the generated security key and paste it in the corresponding input field in the settings of MWB on the second PC. Also enter the name of the first PC in the required field.
- [ ] 4. Press "Connect" and verify that the machine layout now includes two PC tiles, each displaying their respective PC names.
* Verify Connection Status:
- [ ] 5. Ensure that the border of the remote PC turns green, indicating a successful connection.
- [ ] 6. Enter an incorrect security key and verify that the border of the remote PC turns red, indicating a failed connection.
* Test Remote Mouse/Keyboard Control:
- [ ] 7. With the PCs connected, test the mouse/keyboard control from one PC to another. Verify that the mouse/keyboard inputs are correctly registered on the other PC.
- [ ] 8. Test remote mouse/keyboard control across all four PCs, if available. Verify that inputs are correctly registered on each connected PC when the mouse is active there.
* Test Remote Control with Elevated Apps:
- [ ] 9. Open an elevated app on one of the PCs. Verify that without "Use Service" enabled, PowerToys does not control the elevated app.
- [ ] 10. Enable "Use Service" in MWB's settings. Verify that PowerToys can now control the elevated app remotely. Verify that MWB processes are running as LocalSystem, while the MWB helper process is running non-elevated.
- [ ] 11. Toggle "Use Service" again, verify that each time you do that, the MWB processes are restarted.
- [ ] 12. Run PowerToys elevated on one of the machines, verify that you can control elevated apps remotely now on that machine.
* Test Module Enable Status:
- [ ] 13. For all combinations of "Use Service"/"Run PowerToys as admin", try enabling/disabling MWB module and verify that it's indeed being toggled using task manager.
* Test Disconnection/Reconnection:
- [ ] 14. Disconnect one of the PCs from network. Verify that the machine layout updates to reflect the disconnection.
- [ ] 15. Do the same, but now by exiting PowerToys.
- [ ] 16. Start PowerToys again, verify that the PCs are reconnected.
* Test Various Local Network Conditions:
- [ ] 17. Test MWB performance under various network conditions (e.g., low bandwidth, high latency). Verify that the tool maintains a stable connection and functions correctly.
* Clipboard Sharing:
- [ ] 18. Copy some text on one PC and verify that the same text can be pasted on another PC.
- [ ] 19. Use the screenshot key and Win+Shift+S to take a screenshot on one PC and verify that the screenshot can be pasted on another PC.
- [ ] 20. Copy a file in Windows Explorer and verify that the file can be pasted on another PC. Make sure the file size is below 100MB.
- [ ] 21. Try to copy multiple files and directories and verify that it's not possible (only the first selected file is being copied).
* Drag and Drop:
- [ ] 22. Drag a file from Windows Explorer on one PC, cross the screen border onto another PC, and release it there. Verify that the file is copied to the other PC. Make sure the file size is below 100MB.
- [ ] 23. While dragging the file, verify that a corresponding icon is displayed under the mouse cursor.
- [ ] 24. Without moving the mouse from one PC to the target PC, press CTRL+ALT+F1/2/3/4 hotkey to switch to the target PC directly and verify that file sharing/dropping is not working.
* Lock and Unlock with "Use Service" Enabled:
- [ ] 25. Enable "Use Service" in MWB's settings.
- [ ] 26. Lock a remote PC using Win+L, move the mouse to it remotely, and try to unlock it. Verify that you can unlock the remote PC.
- [ ] 27. Disable "Use Service" in MWB's settings, lock the remote PC, move the mouse to it remotely, and try to unlock it. Verify that you can't unlock the remote PC.
* Test Settings:
- [ ] 28. Change the rest of available settings on MWB page and verify that each setting works as described.
## Crop And Lock
* Thumbnail mode
- [ ] 1. Test with win32 app
- [ ] 2. Test with packaged app
* Reparent mode (there are known issues where reparent mode doesn't work for some apps)
- [ ] 3. Test with win32 app
- [ ] 4. Test with packaged app
## Environment Variables
* NOTE: Make backup of USER and SYSTEM Path and TMP variables before testing so you can revert those is something goes wrong!
* Open Environment Variables settings
- [ ] 1. Launch as administrator ON - Launch Environment Variables and confirm that SYSTEM variables ARE editable and Add variable button is enabled
- [ ] 2. Launch as administrator OFF - Launch Environment Variables and confirm that SYSTEM variables ARE NOT editable and Add variable button is disabled
* User/System variables
- [ ] 3. Add new User variable. Open OS Environment variables window and confirm that added variable is there. Also, confirm that it's added to "Applied variables" list.
- [ ] 4. Edit one User variable. Open OS Environment variables window and confirm that variable is changed. Also, confirm that change is applied to "Applied variables" list.
- [ ] 5. Remove one User variable. Open OS Environment variables window and confirm that variable is removed. Also, confirm that variable is removed from "Applied variables" list.
- Repeat the steps for System variables.
* Profiles - Basic tests
- [ ] 6. Add new profile with no variables and name it "Test_profile_1" (referenced below by name)
- [ ] 7. Edit "Test_profile_1": Add one new variable to profile e.g. name: "profile_1_variable_1" value: "profile_1_value_1"
- [ ] 8. Add new profile "Test_profile_2": From "Add profile dialog" add two new variables (profile_2_variable_1:profile_2_value_1 and profile_2_variable_2:profile_2_value_2). Set profile to enabled and click Save. Open OS Environment variables window and confirm that all variables from the profile are applied correctly. Also, confirm that "Applied variables" list contains all variables from the profile.
- [ ] 9. Apply "Test_profile_1" while "Test_profile_2" is still aplpied. Open OS Environment variables window and confirm that all variables from Test_profile_2 are unapplied and that all variables from Test_profile_1 are applied. Also, confirm that state of "Applied variables" list is updated correctly.
- [ ] 10. Unapply applied profile. Open OS Environment variables window and confirm that all variables from the profile are unapplied correctly. Also, confirm that "Applied variables" list does not contain variables from the profile.
* Overriding existing variable
- [ ] 11. To "Test_profile_1" add one existing variable from USER variables, e.g. TMP. After adding, change it's value to e.g "test_TMP" (or manually add variable named TMP with value test_TMP).
- [ ] 12. Apply "Test_profile_1". Open OS Environment variables window and confirm that TMP variable in USER variables has value "test_TMP". Confirm that there is backup variable "TMP_PowerToys_Test_profile_1" with original value of TMP var. Also, confirm that "Applied variables" list is updated correctly - there is TMP profile variable, and backup User variable..
- [ ] 13. Unapply "Test_profile_1". Open OS Environment variables window and confirm that TMP variable in USER variable has original value and that there is no backup variable. Also, confirm that "Applied variables" list is updated correctly.
* PATH variable
- [ ] 14. In "Applied variables" list confirm that PATH variable is shown properly: value of USER Path concatenated to the end of SYSTEM Path.
- [ ] 15. To "Test_profile_1" add variable named PATH with value "path1;path2;path3" and click Save. Confirm that PATH variable in profile is shown as list (list of 3 values and not as path1;path2;path3).
- [ ] 16. Edit PATH variable from "Test_profile_1". Try different options from ... menu (Delete, Move up, Move down, etc...). Click Save.
- [ ] 17. Apply "Test_profile_1". Open OS Environment variables window and confirm that profile is applied correctly - Path value and backup variable. Also, in "Applied variables" list check that Path variable has correct value: value of profile PATH concatenated to the end of SYSTEM Path.
* Loading profiles on startup
- [ ] 18. Close the app and reopen it. Confirm that the state of the app is the same as before closing.
- [ ] 19. "Test_profile_1" should still be applied (if not apply it). Delete "Test_profile_1". Confirm that profile is unapplied (both in OS Environment variables window and "Applied variables" list).
- [ ] 20. Delete "Test_profile_2". Check profiles.json file and confirm that both profiles are gone.
## Command Not Found
* Go to Command Not Found module settings
- [ ] 1. If you have PowerShell 7.4 installed, confirm that Install PowerShell 7.4 button is not visible and PowerShell 7.4 is shown as detected. If you don't have PowerShell 7.4, Install it by clicking the button and confirm that it's properly installed. Check Installation logs text box bellow and confirm there are no errors.
- [ ] 2. If you have Microsoft.WinGet.Client installed, confirm that Install Microsoft.WinGet.Client button is not visible and Microsoft.WinGet.Client is shown as detected. If you don't have Microsoft.WinGet.Client, Install it by clicking the button and confirm that it's properly installed. Check Installation logs text box bellow and confirm there are no errors.
- [ ] 3. Install the Command Not Found module. Check Installation logs text box bellow and confirm there are no errors. Check PowerShell 7 $PROFILE file and confirm Import-Module command is added there. Start new PowerShell 7.4 session and execute "powertoys" (or "atom"). Confirm that suggestion is given to install powertoys (or atom) winget package. (If suggestion is not given, try running the same command few more times, it might take some time for the first time to load the module). Check Installation logs text box bellow and confirm there are no errors.
- [ ] 4. Uninstall the module. Check Installation logs text box bellow and confirm there are no errors. Check PowerShell 7 $PROFILE file and confirm Import-Module command is removed. Start new PowerShell 7.4 session and confirm no errors are shown on start.
- [ ] 5. Install module again. Uninstall PowerToys. Check PowerShell 7 $PROFILE file and confirm Import-Module command is removed after installer is done.
## DSC
* You need to have some prerequisites installed:
- PowerShell >= 7.2 .
- PSDesiredStateConfiguration 2.0.7 or higher `Install-Module -Name PSDesiredStateConfiguration`.
- WinGet [version v1.6.2631 or later](https://github.com/microsoft/winget-cli/releases). (You'll likely have this one already)
* Open a PowerShell 7 instance and navigate to the sample scripts from PowerToys (`src/dsc/Microsoft.PowerToys.Configure/examples/`).
- [ ] 1. Run `winget configure .\disableAllModules.winget`. Open PowerToys Settings and verify all modules are disabled.
- [ ] 2. Run `winget configure .\enableAllModules.winget`. Open PowerToys Settings and verify all modules are enabled.
- [ ] 3. Run `winget configure .\configureLauncherPlugins.winget`. Open PowerToys Settings and verify all PowerToys Run plugins are enabled, and the Program plugin is not global and its Activation Keyword has changed to "P:".
- [ ] 4. Run `winget configure .\configuration.winget`. Open PowerToys Settings the Settings have been applied. File Locksmith is disabled. Shortcut Guide is disabled with an overlay opacity set to 50. FancyZones is enabled with the Editor hotkey set to "Shift+Ctrl+Alt+F".
- [ ] 5. If you run a winget configure command above and PowerToys is running, it will eventually close and automatically reopen after the configuration process is done.
- [ ] 6. If you run a winget configure command above and PowerToys is not running, it won't automatically reopen after the configuration process is done.
## [Advanced Paste](tests-checklist-template-advanced-paste-section.md)
NOTES:
When using Advanced Paste, make sure that window focused while starting/using Advanced paste is text editor or has text input field focused (e.g. Word).
* Paste As Plain Text
- [ ] 1. Copy some rich text (e.g word of the text is different color, another work is bold, underlined, etd.).
- [ ] 2. Paste the text using standard Windows Ctrl + V shortcut and ensure that rich text is pasted (with all colors, formatting, etc.)
- [ ] 3. Paste the text using Paste As Plain Text activation shortcut and ensure that plain text without any formatting is pasted.
- [ ] 4. Paste again the text using standard Windows Ctrl + V shortcut and ensure the text is now pasted plain without formatting as well.
- [ ] 5. Copy some rich text again.
- [ ] 6. Open Advanced Paste window using hotkey, click Paste as Plain Text button and confirm that plain text without any formatting is pasted.
- [ ] 7. Copy some rich text again.
- [ ] 8. Open Advanced Paste window using hotkey, press Ctrl + 1 and confirm that plain text without any formatting is pasted.
* Paste As Markdown
- [ ] 9. Open Settings and set Paste as Markdown directly hotkey
- [ ] 10. Copy some text (e.g. some HTML text - convertible to Markdown)
- [ ] 11. Paste the text using set hotkey and confirm that pasted text is converted to markdown
- [ ] 12. Copy some text (same as in the previous step or different. If nothing is coppied between steps, previously pasted Markdown text will be picked up from clipboard and converted again to nested Markdown).
- [ ] 13. Open Advanced Paste window using hotkey, click Paste as markdown button and confirm that pasted text is converted to markdown
- [ ] 14. Copy some text (same as in the previous step or different. If nothing is coppied between steps, previously pasted Markdown text will be picked up from clipboard and converted again to nested Markdown).
- [ ] 15. Open Advanced Paste window using hotkey, press Ctrl + 2 and confirm that pasted text is converted to markdown
* Paste As JSON
- [ ] 16. Open Settings and set Paste as JSON directly hotkey
- [ ] 17. Copy some XML or CSV text (or any other text, it will be converted to simple JSON object)
- [ ] 18. Paste the text using set hotkey and confirm that pasted text is converted to JSON
- [ ] 19. Copy some text (same as in the previous step or different. If nothing is coppied between steps, previously pasted JSON text will be picked up from clipboard and converted again to nested JSON).
- [ ] 20. Open Advanced Paste window using hotkey, click Paste as markdown button and confirm that pasted text is converted to markdown
- [ ] 21. Copy some text (same as in the previous step or different. If nothing is coppied between steps, previously pasted JSON text will be picked up from clipboard and converted again to nested JSON).
- [ ] 22. Open Advanced Paste window using hotkey, press Ctrl + 3 and confirm that pasted text is converted to markdown
* Paste as custom format using AI
- [ ] 23. Open Settings, navigate to Enable Paste with AI and set OpenAI key.
- [ ] 24. Copy some text to clipboard. Any text.
- [ ] 25. Open Advanced Paste window using hotkey, and confirm that Custom intput text box is now enabled. Write "Insert smiley after every word" and press Enter. Observe that result preview shows coppied text with smileys between words. Press Enter to paste the result and observe that it is pasted.
- [ ] 26. Open Advanced Paste window using hotkey. Input some query (any, feel free to play around) and press Enter. When result is shown, click regenerate button, to see if new result is generated. Select one of the results and paste. Observe that correct result is pasted.
- [ ] 27. Create few custom actions. Set up hotkey for custom actions and confirm they work. Enable/disable custom actions and confirm that the change is reflected in Advanced Paste UI - custom action is not listed. Try different ctrl + <num> in-app shortcuts for custom actions. Try moving custom actions up/down and confirm that the change is reflected in Advanced Paste UI.
- [ ] 28. Open Settings and disable Custom format preview. Open Advanced Paste window with hotkey, enter some query and press enter. Observe that result is now pasted right away, without showing the preview first.
- [ ] 29. Open Settings and Disable Enable Paste with AI. Open Advanced Paste window with hotkey and observe that Custom Input text box is now disabled.
* Clipboard History
- [ ] 30. Open Settings and Enable clipboard history (if not enabled already). Open Advanced Paste window with hotkey, click Clipboard history and try deleting some entry. Check OS clipboard history (Win+V), and confirm that the same entry no longer exist.
- [ ] 31. Open Advanced Paste window with hotkey, click Clipboard history, and click any entry (but first). Observe that entry is put on top of clipboard history. Check OS clipboard history (Win+V), and confirm that the same entry is on top of the clipboard.
- [ ] 32. Open Settings and Disable clipboard history. Open Advanced Paste window with hotkey and observe that Clipboard history button is disabled.
* Disable Advanced Paste, try different Advanced Paste hotkeys and confirm that it's disabled and nothing happens.
## [Workspaces](tests-checklist-template-workspaces-section.md)
* Settings
- [ ] 1. Launch the Editor by clicking the button on the settings page.
- [ ] 2. Launch the Editor from quick access.
- [ ] 3. Launch the Editor by the Activation shortcut.
- [ ] 4. Disable the module and and verify it won't launch by the shortcut.
* Snapshot tool: try with elevated and non-elevated PT
* Open non-packaged apps, e.g., VisualStudio, VisualStudioCode.
* Open packaged apps, e.g., Notepad, Settings.
* Run any app as an administrator.
* Minimize any app.
* Click `Create Workspace`.
* Open any other window.
* Click `Capture`
- [ ] 5. Verify Editor shows all opened windows (the elevated window will be captured if PT is also elevated).
- [ ] 6. Verify windows are in the correct positions.
- [ ] 7. Verify elevated app has the `Admin` box checked (if captured).
* Editor
- [ ] 8. Verify that the new Workspace appears in the list after capturing.
- [ ] 9. Verify that the new Workspace doesn't appear after canceling the Capture.
- [ ] 10. Verify `Search` filters Workspaces (by workspace name or app name).
- [ ] 11. Verify `SortBy` works.
- [ ] 12. Verify `SortBy` keeps its value when you close and open the editor again.
- [ ] 13. Verify `Remove` removes the Workspace from the list.
- [ ] 14. Verify `Edit` opens the Workspace editing page.
- [ ] 15. Verify clicking at the Workspace opens the Workspace editing page.
* Editing page
- [ ] 16. `Remove` an app and verify it disappeared on the preview.
- [ ] 17. `Remove` and `Add back` an app, verify it's returned back to the preview.
- [ ] 18. Set an app minimized, check the preview.
- [ ] 19. Set an app maximized, check the preview.
- [ ] 20. Check `Launch as admin` for the app where it's available.
- [ ] 21. Add CLI args, e.g. path to the PowerToys.sln file for VisualStudio.
- [ ] 22. Manually change the position for the app, check the preview.
- [ ] 23. Change the Workspace name.
- [ ] 24. Verify `Save` and `Cancel` work as expected.
- [ ] 25. Change anything in the project, click at the `Workspaces` on the top of the page, and verify you returned to the main page without saving any changes.
- [ ] 26. Check `Create desktop shortcut`, save the project, verify the shortcut appears on the desktop.
- [ ] 27. Verify that `Create desktop shortcut` is checked when the shortcut is on the desktop and unchecked when there is no shortcut on the desktop.
- [ ] 28. Click `Launch and Edit`, wait for the apps to launch, click `Capture`, verify opened apps are added to the project.
* Launcher
- [ ] 29. Click `Launch` in the editor, verify the Workspace apps launching.
- [ ] 30. Launch Workspace by a shortcut, verify the Workspace apps launching.
- [ ] 31. Verify a window with launching progress is shown while apps are launching and presents the correct launching state (launching, launched, not launched) for every app.
- [ ] 32. Click `Cancel launch`, verify launching is stopped at the current state (opened apps will stay opened), and the window is closed.
- [ ] 33. Click `Dismiss` and verify apps keep launching, but the LauncherUI window is closed.
* To verify that the launcher works correctly with different apps, try to capture and launch:
- [ ] 34. Non-packaged app, e.g., VisualStudio code
- [ ] 35. As admin
- [ ] 36. With CLI args
- [ ] 37. Packaged app, e.g. Terminal
- [ ] 38. As admin
- [ ] 39. With CLI args
* Try to launch the Workspace with a different setup
- [ ] 40. Create a Workspace with one monitor connected, connect the second monitor, launch the Workspace, verify apps are opened on the first one, as captured.
- [ ] 41. Create a Workspace with two monitors connected, disconnect a monitor, verify apps are opened on the remaining one.
## New+
* Enable New+ in Settings.
- [ ] 1. Verify NewPlus menu is in Explorer context menu. (Windows 11 tier 1 context menu only. May need Explorer restart.)
* Disable New+ in Settings.
- [ ] 2. Verify NewPlus menu is not in Explorer context menu.
* Choose a different path for template folder.
- [ ] 3. Verify the folder is created and empty.
- [ ] 4. Copy a file to the templates folder, verify it's added to the New+ context menu and that if you select it the file is created.
- [ ] 5. Copy a folder with files inside to the templates folder, verify it's added to the New+ context menu and that if you select it the folder and files inside are created.
- [ ] 6. Delete all files and folders from inside the templates folder. Verify that no templates are available in the context menu.
- [ ] 7. Disable and re-Enable New+ while the templates folder is still empty. Verify the default templates were copied over and are available in the context menu.
* Test some Settings:
- [ ] 8. Test the "Hide template filename extension" option in Settings.
- [ ] 9. Test the "Hide template filename starting digits, spaces and dots" option in Settings.
## [ZoomIt](tests-checklist-template-zoomit-section.md)
* Enable ZoomIt in Settings.
- [ ] 1. Verify ZoomIt tray icon appears in the tray icons, and that when you left-click or right-click, it just shows the 4 action entries: "Break Timer", "Draw", "Zoom" and "Record".
- [ ] 2. Turn the "Show tray icon" option off and verify the tray icon is gone.
- [ ] 3. Turn the "Show tray icon" option on and verify the tray icon is back.
* Test the base modes through a shortcuts:
- [ ] 4. Press the Zoom Toggle Hotkey and verify ZoomIt zooms in on the mouse. You can exit Zoom by pressing Escape or the Hotkey again.
- [ ] 5. Press the Live Zoom Toggle Hotkey and verify ZoomIt zooms in on the mouse, while the screen still updates instead of showing a still image. You can exit Live Zoom by pressing the Hotkey again.
- [ ] 6. Press the Draw without Zoom Hotkey and verify you can draw. You can leave this mode by pressing the Escape.
- [ ] 7. Select a text file as the Input file for Demo Type, focus notepad and press the Demo Type hotkey. It should start typing the text file. You can exit Demo Type by pressing Escape.
- [ ] 8. Press the Start Break Timer Hotkey and verify it starts the Timer. You can exit by pressing Escape.
- [ ] 9. Press the Record Toggle Hotkey to start recording a screen. Press the Record Toggle Hotkey again to exit the mode and save the recording to a file.
- [ ] 10. Press the Snip Toggle Hotkey to take a snip of the screen. Paste it to Paint to verify a snip was taken.
* Test some Settings to verify the types are being passed correctly to ZoomIt:
- [ ] 11. Change the "Animate zoom in and zoom out" setting and activate Zoom mode to verify it applies.
- [ ] 12. Change the "Specify the initial level of magnification when zooming in" and activate Zoom mode to verify it applies.
- [ ] 13. Change the Type Font to another font. Enter Break mode to quickly verify the font changed.
- [ ] 14. Change the Demo Type typing speed and verify the change applies.
- [ ] 15. Change the timer Opacity for Break mode and verify that the change applies.
- [ ] 16. Change the timer Position for Break mode and verify that the change applies.
- [ ] 17. Select a Background Image file as background for Break mode and verify that the change applies.
- [ ] 18. Turn on "Play Sound on Expiration", select a sound file, aset the timer to 1 minute, activate the Break Mode and verify the sound plays after 1 minute. (Alarm1.wav from "C:\Windows\Media" should be long enough to notice)
- [ ] 19. Open the Microphone combo box in the Record section and verify it lists your microphones.
* Test the tray icon actions:
- [ ] 20. Verify pressing "Break Timer" enters Break mode.
- [ ] 21. Verify pressing "Draw" enters Draw mode.
- [ ] 22. Verify pressing "Zoom" enters Zoom mode.
- [ ] 23. Verify pressing "Record" enters Record mode.
## [Command Palette](tests-checklist-template-command-palette-section.md)
* Check if Command Palette successfully install/uninstall with PowerToys.
- [ ] 1. Install PowerToys. Then check if Command Palette exist in the System Settings/App/Installed Apps.
- [ ] 2. UnInstall PowerToys. Then check if Command Palette doesn't exist in the System Settings/App/Installed Apps.
* Enable Command Palette in settings and ensure that the hotkey brings up Command Palette
- [ ] 3. when PowerToys is running unelevated on start-up
- [ ] 4. when PowerToys is running as admin on start-up
- [ ] 5. when PowerToys is restarted as admin, by clicking the restart as admin button in settings.
* Check that each of the plugins is working:
- [ ] 6. Installed Apps - launch a Win32 application
- [ ] 7. Installed Apps - launch a Win32 application as admin
- [ ] 8. Installed Apps - launch a packaged application
- [ ] 9. Calculator - ensure a mathematical input returns a correct response and is copied on enter.
- [ ] 10. File Search - open a file on the disk.
- [ ] 11. File Search - find a file and copy file path.
- [ ] 12. File Search - find a file and open containing folder.
- [ ] 13. Run Commands - execute a command. (e.g. `ping google.com`).
- [ ] 14. Windows Walker - Switch to another opening window.
- [ ] 15. Windows Walker - Switch to another opening window when powertoys run as admin.
- [ ] 16. WinGet - Search and install application through WinGet. (eg. `vscode`)
- [ ] 17. Web Search - Search anything by this extension.
- [ ] 18. Windows Terminal Profiles - Open profile.
- [ ] 19. Windows Terminal Profiles - Open profile as Admin.
- [ ] 20. Windows Settings - Open settings from extension.
- [ ] 21. Registry - navigate through the registry tree and open registry editor. Enter the action keyword `:` to get the root keys.
- [ ] 22. Registry - navigate through the registry tree and copy key path.
- [ ] 23. Windows Service - start, stop, restart windows service.
- [ ] 24. Time And Date - type `now`, `year`, `week` and verify the result is correct.
- [ ] 25. Windows System Command - test `lock`.
- [ ] 26. Windows System Command - test `empty recycle bin`.
- [ ] 27. Windows System Command - test `shutdown`.
- [ ] 28. Windows System Command - Click your network adapter item and paste the result at notepad.
- [ ] 29. Bookmark - Add bookmarks to command palette.
- [ ] 30. Bookmark - Open your bookmarks (in Command Palette).
- [ ] 31. Disable Command Palette and ensure that the hotkey doesn't bring up Command Palette.
* Test Extensions Manager
- [ ] 32. Enable/disable extensions and verify changes are picked up by Command Palette
- [ ] 33. Change `Global hot key` and verify changes are picked up by Command Palette
- [ ] 34. Change `Alias` and verify changes picked up by Command Palette
- [ ] 35. Disable all extensions and verify the warning message is shown (Currently not support).

View File

@@ -0,0 +1,28 @@
// 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.UITest
{
public class ComboBox : Element
{
private static readonly string ExpectedControlType = "ControlType.ComboBox";
/// <summary>
/// Initializes a new instance of the <see cref="ComboBox"/> class.
/// </summary>
public ComboBox()
{
this.TargetControlType = ComboBox.ExpectedControlType;
}
/// <summary>
/// Select the item of the ComboBox.
/// </summary>
/// <param name="value">The text to select from the list view.</param>
public void Select(string value)
{
this.Find<NavigationViewItem>(value).Click();
}
}
}

View File

@@ -0,0 +1,25 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.PowerToys.UITest
{
public class Custom : Element
{
private static readonly string ExpectedControlType = "ControlType.Custom";
/// <summary>
/// Initializes a new instance of the <see cref="Custom"/> class.
/// </summary>
public Custom()
{
this.TargetControlType = Custom.ExpectedControlType;
}
}
}

View File

@@ -7,6 +7,7 @@ using System.Drawing;
using System.Runtime.CompilerServices;
using System.Xml.Linq;
using ABI.Windows.Foundation;
using Microsoft.PowerToys.UITest;
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
@@ -112,9 +113,10 @@ namespace Microsoft.PowerToys.UITest
/// Click the UI element.
/// </summary>
/// <param name="rightClick">If true, performs a right-click; otherwise, performs a left-click. Default value is false</param>
public virtual void Click(bool rightClick = false)
public virtual void Click(bool rightClick = false, int msPreAction = 500, int msPostAction = 500)
{
PerformAction((actions, windowElement) =>
PerformAction(
(actions, windowElement) =>
{
actions.MoveToElement(windowElement);
@@ -131,7 +133,9 @@ namespace Microsoft.PowerToys.UITest
}
actions.Build().Perform();
});
},
msPreAction,
msPostAction);
}
/// <summary>
@@ -199,6 +203,42 @@ namespace Microsoft.PowerToys.UITest
});
}
/// <summary>
/// Simulates holding a key, clicking and dragging a UI element to the specified screen coordinates.
/// </summary>
/// <param name="key">The keyboard key to press and hold during the drag operation.</param>
/// <param name="targetX">The target X-coordinate to drag the element to.</param>
/// <param name="targetY">The target Y-coordinate to drag the element to.</param>
public void KeyDownAndDrag(Key key, int targetX, int targetY)
{
PerformAction((actions, windowElement) =>
{
KeyboardHelper.PressKey(key);
actions.MoveToElement(windowsElement)
.ClickAndHold()
.Perform();
int dx = targetX - windowElement.Rect.X;
int dy = targetY - windowElement.Rect.Y;
int stepCount = 10;
int stepX = dx / stepCount;
int stepY = dy / stepCount;
for (int i = 0; i < stepCount; i++)
{
var stepAction = new Actions(driver);
stepAction.MoveByOffset(stepX, stepY).Perform();
}
var releaseAction = new Actions(driver);
releaseAction.Release().Perform();
KeyboardHelper.ReleaseKey(key);
});
}
/// <summary>
/// Gets the attribute value of the UI element.
/// </summary>
@@ -218,7 +258,7 @@ namespace Microsoft.PowerToys.UITest
/// <param name="by">The selector to use for finding the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds.</param>
/// <returns>The found element.</returns>
public T Find<T>(By by, int timeoutMS = 3000)
public T Find<T>(By by, int timeoutMS = 5000)
where T : Element, new()
{
Assert.IsNotNull(this.windowsElement, $"WindowsElement is null in method Find<{typeof(T).Name}> with parameters: by = {by}, timeoutMS = {timeoutMS}");
@@ -226,7 +266,7 @@ namespace Microsoft.PowerToys.UITest
// leverage findAll to filter out mismatched elements
var collection = this.FindAll<T>(by, timeoutMS);
Assert.IsTrue(collection.Count > 0, $"Element not found using selector: {by}");
Assert.IsTrue(collection.Count > 0, $"UI-Element({typeof(T).Name}) not found using selector: {by}");
return collection[0];
}
@@ -239,7 +279,7 @@ namespace Microsoft.PowerToys.UITest
/// <param name="name">The name for finding the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds.</param>
/// <returns>The found element.</returns>
public T Find<T>(string name, int timeoutMS = 3000)
public T Find<T>(string name, int timeoutMS = 5000)
where T : Element, new()
{
return this.Find<T>(By.Name(name), timeoutMS);
@@ -252,7 +292,7 @@ namespace Microsoft.PowerToys.UITest
/// <param name="by">The selector to use for finding the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds.</param>
/// <returns>The found element.</returns>
public Element Find(By by, int timeoutMS = 3000)
public Element Find(By by, int timeoutMS = 5000)
{
return this.Find<Element>(by, timeoutMS);
}
@@ -264,7 +304,7 @@ namespace Microsoft.PowerToys.UITest
/// <param name="name">The name for finding the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds.</param>
/// <returns>The found element.</returns>
public Element Find(string name, int timeoutMS = 3000)
public Element Find(string name, int timeoutMS = 5000)
{
return this.Find<Element>(By.Name(name), timeoutMS);
}
@@ -276,7 +316,7 @@ namespace Microsoft.PowerToys.UITest
/// <param name="by">The selector to use for finding the elements.</param>
/// <param name="timeoutMS">The timeout in milliseconds.</param>
/// <returns>A read-only collection of the found elements.</returns>
public ReadOnlyCollection<T> FindAll<T>(By by, int timeoutMS = 3000)
public ReadOnlyCollection<T> FindAll<T>(By by, int timeoutMS = 5000)
where T : Element, new()
{
Assert.IsNotNull(this.windowsElement, $"WindowsElement is null in method FindAll<{typeof(T).Name}> with parameters: by = {by}, timeoutMS = {timeoutMS}");
@@ -308,7 +348,7 @@ namespace Microsoft.PowerToys.UITest
/// <param name="name">The name for finding the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds.</param>
/// <returns>A read-only collection of the found elements.</returns>
public ReadOnlyCollection<T> FindAll<T>(string name, int timeoutMS = 3000)
public ReadOnlyCollection<T> FindAll<T>(string name, int timeoutMS = 5000)
where T : Element, new()
{
return this.FindAll<T>(By.Name(name), timeoutMS);
@@ -321,7 +361,7 @@ namespace Microsoft.PowerToys.UITest
/// <param name="by">The selector to use for finding the elements.</param>
/// <param name="timeoutMS">The timeout in milliseconds.</param>
/// <returns>A read-only collection of the found elements.</returns>
public ReadOnlyCollection<Element> FindAll(By by, int timeoutMS = 3000)
public ReadOnlyCollection<Element> FindAll(By by, int timeoutMS = 5000)
{
return this.FindAll<Element>(by, timeoutMS);
}
@@ -333,7 +373,7 @@ namespace Microsoft.PowerToys.UITest
/// <param name="name">The name for finding the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds.</param>
/// <returns>A read-only collection of the found elements.</returns>
public ReadOnlyCollection<Element> FindAll(string name, int timeoutMS = 3000)
public ReadOnlyCollection<Element> FindAll(string name, int timeoutMS = 5000)
{
return this.FindAll<Element>(By.Name(name), timeoutMS);
}
@@ -360,5 +400,15 @@ namespace Microsoft.PowerToys.UITest
Task.Delay(msPostAction).Wait();
}
}
/// <summary>
/// Save UI Element to a PNG file.
/// </summary>
/// <param name="path">the full path</param>
internal void SaveToPngFile(string path)
{
Assert.IsNotNull(this.windowsElement, $"WindowsElement is null in method SaveToFile with parameter: path = {path}");
this.windowsElement.GetScreenshot().SaveAsFile(path);
}
}
}

View File

@@ -0,0 +1,25 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.PowerToys.UITest
{
public class Group : Element
{
private static readonly string ExpectedControlType = "ControlType.Group";
/// <summary>
/// Initializes a new instance of the <see cref="Group"/> class.
/// </summary>
public Group()
{
this.TargetControlType = Group.ExpectedControlType;
}
}
}

View File

@@ -24,9 +24,12 @@ namespace Microsoft.PowerToys.UITest
/// Click the ListItem element.
/// </summary>
/// <param name="rightClick">If true, performs a right-click; otherwise, performs a left-click. Default value is false</param>
public override void Click(bool rightClick = false)
/// <param name="msPreAction">Pre action delay in milliseconds. Default value is 500</param>
/// <param name="msPostAction">Post action delay in milliseconds. Default value is 500</param>
public override void Click(bool rightClick = false, int msPreAction = 500, int msPostAction = 500)
{
PerformAction((actions, windowElement) =>
PerformAction(
(actions, windowElement) =>
{
actions.MoveToElement(windowElement, 10, 10);
@@ -40,7 +43,35 @@ namespace Microsoft.PowerToys.UITest
}
actions.Build().Perform();
});
},
msPreAction,
msPostAction);
}
/// <summary>
/// Click the ListItem element.
/// </summary>
/// <param name="rightClick">If true, performs a right-click; otherwise, performs a left-click. Default value is false</param>
/// <param name="msPreAction">Pre action delay in milliseconds. Default value is 500</param>
/// <param name="msPostAction">Post action delay in milliseconds. Default value is 500</param>
public void ClickCenter(bool rightClick = false, int msPreAction = 500, int msPostAction = 500)
{
PerformAction(
(actions, windowElement) =>
{
if (rightClick)
{
actions.ContextClick();
}
else
{
actions.Click();
}
actions.Build().Perform();
},
msPreAction,
msPostAction);
}
/// <summary>

View File

@@ -0,0 +1,119 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium.Windows;
namespace Microsoft.PowerToys.UITest
{
public class Slider : Element
{
private static readonly string ExpectedControlType = "ControlType.Slider";
/// <summary>
/// Initializes a new instance of the <see cref="Slider"/> class.
/// </summary>
public Slider()
{
this.TargetControlType = Slider.ExpectedControlType;
}
/// <summary>
/// Gets the value of a Slider (WindowsElement)
/// </summary>
/// <returns>The integer value of the slider</returns>
public int GetValue()
{
return this.Text == string.Empty ? 0 : int.Parse(this.Text);
}
/// <summary>
/// Sets the value of a Slider (WindowsElement) to the specified integer value.
/// Throws an exception if the value is out of the slider's valid range.
/// </summary>
/// <param name="targetValue">The target integer value to set</param>
public void SetValue(int targetValue)
{
// Read range and current value
int min = int.Parse(this.GetAttribute("RangeValue.Minimum"));
int max = int.Parse(this.GetAttribute("RangeValue.Maximum"));
int current = int.Parse(this.Text);
// Use Assert to check if the target value is within the valid range
Assert.IsTrue(
targetValue >= min && targetValue <= max,
$"Target value {targetValue} is out of range (min: {min}, max: {max}).");
// Compute difference
int diff = targetValue - current;
if (diff == 0)
{
return;
}
string key = diff > 0 ? OpenQA.Selenium.Keys.Right : OpenQA.Selenium.Keys.Left;
int steps = Math.Abs(diff);
for (int i = 0; i < steps; i++)
{
this.SendKeys(key);
// Thread.Sleep(2);
}
// Final check
int finalValue = int.Parse(this.Text);
Assert.AreEqual(
targetValue, finalValue, $"Slider value mismatch: expected {targetValue}, but got {finalValue}.");
}
/// <summary>
/// Sets the value of a Slider (WindowsElement) to the specified integer value.
/// Throws an exception if the value is out of the slider's valid range.
/// </summary>
/// <param name="targetValue">The target integer value to set</param>
public void QuickSetValue(int targetValue)
{
// Read range and current value
int min = int.Parse(this.GetAttribute("RangeValue.Minimum"));
int max = int.Parse(this.GetAttribute("RangeValue.Maximum"));
int current = int.Parse(this.Text);
// Use Assert to check if the target value is within the valid range
Assert.IsTrue(
targetValue >= min && targetValue <= max,
$"Target value {targetValue} is out of range (min: {min}, max: {max}).");
// Compute difference
int diff = targetValue - current;
if (diff == 0)
{
return;
}
string key = diff > 0 ? OpenQA.Selenium.Keys.Right : OpenQA.Selenium.Keys.Left;
int steps = Math.Abs(diff);
int maxKeysPerSend = 50;
int fullChunks = steps / maxKeysPerSend;
int remainder = steps % maxKeysPerSend;
for (int i = 0; i < fullChunks; i++)
{
SendKeys(new string(key[0], maxKeysPerSend));
Thread.Sleep(2);
}
if (remainder > 0)
{
SendKeys(new string(key[0], remainder));
Thread.Sleep(2);
}
// Final check
int finalValue = int.Parse(this.Text);
Assert.AreEqual(
targetValue, finalValue, $"Slider value mismatch: expected {targetValue}, but got {finalValue}.");
}
}
}

View File

@@ -2,8 +2,6 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using OpenQA.Selenium;
namespace Microsoft.PowerToys.UITest
{
/// <summary>
@@ -35,8 +33,8 @@ namespace Microsoft.PowerToys.UITest
PerformAction((actions, windowElement) =>
{
// select all text and delete it
windowElement.SendKeys(Keys.Control + "a");
windowElement.SendKeys(Keys.Delete);
windowElement.SendKeys(OpenQA.Selenium.Keys.Control + "a");
windowElement.SendKeys(OpenQA.Selenium.Keys.Delete);
});
}

View File

@@ -33,7 +33,7 @@ namespace Microsoft.PowerToys.UITest
public static ReadOnlyCollection<T>? FindAll<T, TW>(Func<ReadOnlyCollection<TW>> findElementsFunc, WindowsDriver<WindowsElement>? driver, int timeoutMS)
where T : Element, new()
{
var items = findElementsFunc();
var items = FindElementsWithRetry(findElementsFunc, timeoutMS);
var res = items.Select(item =>
{
var element = item as WindowsElement;
@@ -43,6 +43,27 @@ namespace Microsoft.PowerToys.UITest
return new ReadOnlyCollection<T>(res);
}
private static ReadOnlyCollection<TW> FindElementsWithRetry<TW>(Func<ReadOnlyCollection<TW>> findElementsFunc, int timeoutMS)
{
int retryIntervalMS = 500;
timeoutMS = 1;
int elapsedTime = 0;
while (elapsedTime < timeoutMS)
{
var items = findElementsFunc();
if (items.Count > 0)
{
return items;
}
Task.Delay(retryIntervalMS).Wait();
elapsedTime += retryIntervalMS;
}
return new ReadOnlyCollection<TW>(new List<TW>());
}
public static T NewElement<T>(WindowsElement? element, WindowsDriver<WindowsElement>? driver, int timeoutMS)
where T : Element, new()
{
@@ -50,11 +71,6 @@ namespace Microsoft.PowerToys.UITest
Assert.IsNotNull(element, $"New Element {typeof(T).Name} error: element is null.");
T newElement = new T();
if (timeoutMS > 0)
{
// Only set timeout if it is positive value
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(timeoutMS);
}
newElement.SetSession(driver);
newElement.SetWindowsElement(element);

View File

@@ -0,0 +1,351 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.PowerToys.UITest
{
/// <summary>
/// Represents keyboard keys.
/// </summary>
public enum Key
{
Ctrl,
LCtrl,
RCtrl,
Alt,
Shift,
Tab,
Esc,
Enter,
Win,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
Space,
Backspace,
Delete,
Insert,
Home,
End,
PageUp,
PageDown,
Up,
Down,
Left,
Right,
Other,
}
/// <summary>
    /// Provides methods for simulating keyboard input.
    /// </summary>
internal static class KeyboardHelper
{
[DllImport("user32.dll")]
#pragma warning disable SA1300 // Element should begin with upper-case letter
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
#pragma warning restore SA1300 // Element should begin with upper-case letter
#pragma warning disable SA1310 // Field names should not contain underscore
private const byte VK_LWIN = 0x5B;
private const uint KEYEVENTF_KEYDOWN = 0x0000;
private const uint KEYEVENTF_KEYUP = 0x0002;
#pragma warning restore SA1310 // Field names should not contain underscore
/// <summary>
/// Sends a combination of keys.
/// </summary>
/// <param name="keys">The keys to send.</param>
public static void SendKeys(params Key[] keys)
{
string keysToSend = string.Join(string.Empty, keys.Select(TranslateKey));
SendWinKeyCombination(keysToSend);
}
public static void PressKey(Key key)
{
PressVirtualKey(TranslateKeyHex(key));
}
public static void ReleaseKey(Key key)
{
ReleaseVirtualKey(TranslateKeyHex(key));
}
public static void SendKey(Key key)
{
PressVirtualKey(TranslateKeyHex(key));
ReleaseVirtualKey(TranslateKeyHex(key));
}
/// <summary>
        /// Translates a key to its corresponding SendKeys representation.
        /// </summary>
        /// <param name="key">The key to translate.</param>
        /// <returns>The SendKeys representation of the key.</returns>
private static string TranslateKey(Key key)
{
switch (key)
{
case Key.Ctrl:
return "^";
case Key.LCtrl:
return "^";
case Key.RCtrl:
return "^";
case Key.Alt:
return "%";
case Key.Shift:
return "+";
case Key.Tab:
return "{TAB}";
case Key.Esc:
return "{ESC}";
case Key.Enter:
return "{ENTER}";
case Key.Win:
return "{WIN}";
case Key.Space:
return " ";
case Key.Backspace:
return "{BACKSPACE}";
case Key.Delete:
return "{DELETE}";
case Key.Insert:
return "{INSERT}";
case Key.Home:
return "{HOME}";
case Key.End:
return "{END}";
case Key.PageUp:
return "{PGUP}";
case Key.PageDown:
return "{PGDN}";
case Key.Up:
return "{UP}";
case Key.Down:
return "{DOWN}";
case Key.Left:
return "{LEFT}";
case Key.Right:
return "{RIGHT}";
case Key.F1:
return "{F1}";
case Key.F2:
return "{F2}";
case Key.F3:
return "{F3}";
case Key.F4:
return "{F4}";
case Key.F5:
return "{F5}";
case Key.F6:
return "{F6}";
case Key.F7:
return "{F7}";
case Key.F8:
return "{F8}";
case Key.F9:
return "{F9}";
case Key.F10:
return "{F10}";
case Key.F11:
return "{F11}";
case Key.F12:
return "{F12}";
case Key.A:
return "a";
case Key.B:
return "b";
case Key.C:
return "c";
case Key.D:
return "d";
case Key.E:
return "e";
case Key.F:
return "f";
case Key.G:
return "g";
case Key.H:
return "h";
case Key.I:
return "i";
case Key.J:
return "j";
case Key.K:
return "k";
case Key.L:
return "l";
case Key.M:
return "m";
case Key.N:
return "n";
case Key.O:
return "o";
case Key.P:
return "p";
case Key.Q:
return "q";
case Key.R:
return "r";
case Key.S:
return "s";
case Key.T:
return "t";
case Key.U:
return "u";
case Key.V:
return "v";
case Key.W:
return "w";
case Key.X:
return "x";
case Key.Y:
return "y";
case Key.Z:
return "z";
case Key.Num0:
return "0";
case Key.Num1:
return "1";
case Key.Num2:
return "2";
case Key.Num3:
return "3";
case Key.Num4:
return "4";
case Key.Num5:
return "5";
case Key.Num6:
return "6";
case Key.Num7:
return "7";
case Key.Num8:
return "8";
case Key.Num9:
return "9";
default:
return string.Empty;
}
}
/// <summary>
/// map the virtual key codes to the corresponding keys.
/// </summary>
private static byte TranslateKeyHex(Key key)
{
switch (key)
{
case Key.Win:
return 0x5B; // Windows Key - 0x5B in hex
case Key.Ctrl:
return 0x11; // Ctrl Key - 0x11 in hex
case Key.Alt:
return 0x12; // Alt Key - 0x12 in hex
case Key.Shift:
return 0x10; // Shift Key - 0x10 in hex
case Key.LCtrl:
return 0xA2; // Left Ctrl Key - 0xA2 in hex
case Key.RCtrl: // Right Ctrl Key - 0xA3 in hex
return 0xA3;
case Key.A:
return 0x41; // A Key - 0x41 in hex
default:
throw new ArgumentException($"Key {key} is not supported, Please add your key at TranslateKeyHex for translation to hex.");
}
}
/// <summary>
/// Sends a combination of keys, including the Windows key, to the system.
/// </summary>
/// <param name="keys">The keys to send.</param>
private static void SendWinKeyCombination(string keys)
{
bool winKeyDown = false;
if (keys.Contains("{WIN}"))
{
keybd_event(VK_LWIN, 0, KEYEVENTF_KEYDOWN, UIntPtr.Zero);
winKeyDown = true;
keys = keys.Replace("{WIN}", string.Empty); // Remove {WIN} from the string
        }
System.Windows.Forms.SendKeys.SendWait(keys);
        // Release Windows key
if (winKeyDown)
{
keybd_event(VK_LWIN, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
}
}
/// <summary>
/// Just press the key.(no release)
/// </summary>
private static void PressVirtualKey(byte key)
{
keybd_event(key, 0, KEYEVENTF_KEYDOWN, UIntPtr.Zero);
}
/// <summary>
/// Release only the button (if pressed first)
/// </summary>
private static void ReleaseVirtualKey(byte key)
{
keybd_event(key, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
}
}
}

View File

@@ -29,6 +29,49 @@ namespace Microsoft.PowerToys.UITest
PowerToysSettings,
FancyZone,
Hosts,
Runner,
Workspaces,
}
/// <summary>
/// Represents the window size for the UI test.
/// </summary>
public enum WindowSize
{
/// <summary>
/// Unspecified window size, won't make any size change
/// </summary>
UnSpecified,
/// <summary>
/// Small window size, 640 * 480
/// </summary>
Small,
/// <summary>
/// Small window size, 480 * 640
/// </summary>
Small_Vertical,
/// <summary>
/// Medium window size, 1024 * 768
/// </summary>
Medium,
/// <summary>
/// Medium window size, 768 * 1024
/// </summary>
Medium_Vertical,
/// <summary>
/// Large window size, 1920 * 1080
/// </summary>
Large,
/// <summary>
/// Large window size, 1080 * 1920
/// </summary>
Large_Vertical,
}
internal class ModuleConfigData
@@ -52,6 +95,8 @@ namespace Microsoft.PowerToys.UITest
[PowerToysModule.PowerToysSettings] = "PowerToys Settings",
[PowerToysModule.FancyZone] = "FancyZones Layout",
[PowerToysModule.Hosts] = "Hosts File Editor",
[PowerToysModule.Runner] = "PowerToys",
[PowerToysModule.Workspaces] = "Workspaces Editor",
};
// Exe start path for the module if it exists.
@@ -60,6 +105,8 @@ namespace Microsoft.PowerToys.UITest
[PowerToysModule.PowerToysSettings] = @"\..\..\..\WinUI3Apps\PowerToys.Settings.exe",
[PowerToysModule.FancyZone] = @"\..\..\..\PowerToys.FancyZonesEditor.exe",
[PowerToysModule.Hosts] = @"\..\..\..\WinUI3Apps\PowerToys.Hosts.exe",
[PowerToysModule.Runner] = @"\..\..\..\PowerToys.exe",
[PowerToysModule.Workspaces] = @"\..\..\..\PowerToys.WorkspacesEditor.exe",
};
}

View File

@@ -0,0 +1,217 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.PowerToys.UITest
{
public enum MouseActionType
{
LeftClick,
RightClick,
MiddleClick,
LeftDoubleClick,
RightDoubleClick,
LeftDown,
LeftUp,
RightDown,
RightUp,
MiddleDown,
MiddleUp,
ScrollUp,
ScrollDown,
}
internal static class MouseHelper
{
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
}
[Flags]
internal enum MouseEvent
{
LeftDown = 0x0002,
LeftUp = 0x0004,
RightDown = 0x0008,
RightUp = 0x0010,
MiddleDown = 0x0020,
MiddleUp = 0x0040,
Wheel = 0x0800,
}
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int x, int y);
[DllImport("user32.dll")]
#pragma warning disable SA1300 // Element should begin with upper-case letter
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, UIntPtr dwExtraInfo);
#pragma warning restore SA1300 // Element should begin with upper-case letter
        /// <summary>
        /// Gets the current position of the mouse cursor as a tuple.
        /// </summary>
        /// <returns>A tuple containing the X and Y coordinates of the cursor.</returns>
public static Tuple<int, int> GetMousePosition()
{
GetCursorPos(out POINT point);
return Tuple.Create(point.X, point.Y);
}
/// <summary>
    /// Moves the mouse cursor to the specified screen coordinates.
    /// </summary>
    /// <param name="x">The new x-coordinate of the cursor.</param>
    /// <param name="y">The new y-coordinate of the cursor.</param
public static void MoveMouseTo(int x, int y)
{
SetCursorPos(x, y);
}
/// <summary>
/// The delay in milliseconds between mouse down and up events to simulate a click.
/// </summary>
private const int ClickDelay = 100;
/// <summary>
/// The amount of scroll units to simulate a single mouse wheel tick.
/// </summary>
private const int ScrollAmount = 120;
/// <summary>
/// Simulates a left mouse click (press and release).
/// </summary>
public static void LeftClick()
{
LeftDown();
Thread.Sleep(ClickDelay);
LeftUp();
}
/// <summary>
/// Simulates a right mouse click (press and release).
/// </summary>
public static void RightClick()
{
RightDown();
Thread.Sleep(ClickDelay);
RightUp();
}
/// <summary>
/// Simulates a middle mouse click (press and release).
/// </summary>
public static void MiddleClick()
{
MiddleDown();
Thread.Sleep(ClickDelay);
MiddleUp();
}
/// <summary>
/// Simulates a left mouse double-click.
/// </summary>
public static void LeftDoubleClick()
{
LeftClick();
Thread.Sleep(ClickDelay);
LeftClick();
}
/// <summary>
/// Simulates a right mouse double-click.
/// </summary>
public static void RightDoubleClick()
{
RightClick();
Thread.Sleep(ClickDelay);
RightClick();
}
/// <summary>
/// Simulates pressing the left mouse button down.
/// </summary>
public static void LeftDown()
{
mouse_event((uint)MouseEvent.LeftDown, 0, 0, 0, UIntPtr.Zero);
}
/// <summary>
/// Simulates pressing the right mouse button down.
/// </summary>
public static void RightDown()
{
mouse_event((uint)MouseEvent.RightDown, 0, 0, 0, UIntPtr.Zero);
}
/// <summary>
/// Simulates pressing the middle mouse button down.
/// </summary>
public static void MiddleDown()
{
mouse_event((uint)MouseEvent.MiddleDown, 0, 0, 0, UIntPtr.Zero);
}
/// <summary>
/// Simulates releasing the left mouse button.
/// </summary>
public static void LeftUp()
{
mouse_event((uint)MouseEvent.LeftUp, 0, 0, 0, UIntPtr.Zero);
}
/// <summary>
/// Simulates releasing the right mouse button.
/// </summary>
public static void RightUp()
{
mouse_event((uint)MouseEvent.RightUp, 0, 0, 0, UIntPtr.Zero);
}
/// <summary>
/// Simulates releasing the middle mouse button.
/// </summary>
public static void MiddleUp()
{
mouse_event((uint)MouseEvent.MiddleUp, 0, 0, 0, UIntPtr.Zero);
}
/// <summary>
/// Simulates a mouse scroll wheel action by a specified amount.
/// Positive values scroll up, negative values scroll down.
/// </summary>
/// <param name="amount">The scroll amount. Typically 120 or -120 per tick.</param>
public static void ScrollWheel(int amount)
{
mouse_event((uint)MouseEvent.Wheel, 0, 0, (uint)amount, UIntPtr.Zero);
}
/// <summary>
/// Simulates scrolling the mouse wheel up by one tick.
/// </summary>
public static void ScrollUp()
{
ScrollWheel(ScrollAmount);
}
/// <summary>
/// Simulates scrolling the mouse wheel down by one tick.
/// </summary>
public static void ScrollDown()
{
ScrollWheel(-ScrollAmount);
}
}
}

View File

@@ -0,0 +1,133 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.PowerToys.UITest
{
/// <summary>
/// Provides methods for capturing the screen with the mouse cursor.
/// </summary>
internal static class ScreenCapture
{
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
[DllImport("user32.dll")]
private static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("user32.dll")]
private static extern bool GetCursorInfo(out CURSORINFO pci);
[DllImport("user32.dll")]
private static extern bool DrawIconEx(IntPtr hdc, int x, int y, IntPtr hIcon, int cx, int cy, int istepIfAniCur, IntPtr hbrFlickerFreeDraw, int diFlags);
/// <summary>
/// Represents a point with X and Y coordinates.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
}
/// <summary>
/// Contains information about the cursor.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct CURSORINFO
{
/// <summary>
/// Gets or sets the size of the structure.
/// </summary>
public int CbSize;
/// <summary>
/// Gets or sets the cursor state.
/// </summary>
public int Flags;
/// <summary>
/// Gets or sets the handle to the cursor.
/// </summary>
public IntPtr HCursor;
/// <summary>
/// Gets or sets the screen position of the cursor.
/// </summary>
public POINT PTScreenPos;
}
private const int CURSORSHOWING = 0x00000001;
private const int DESKTOPHORZRES = 118;
private const int DESKTOPVERTRES = 117;
private const int DINORMAL = 0x0003;
/// <summary>
/// Captures the screen with the mouse cursor and saves it to the specified file path.
/// </summary>
/// <param name="filePath">The file path to save the captured image.</param>
private static void CaptureScreenWithMouse(string filePath)
{
IntPtr hdc = GetDC(IntPtr.Zero);
int screenWidth = GetDeviceCaps(hdc, DESKTOPHORZRES);
int screenHeight = GetDeviceCaps(hdc, DESKTOPVERTRES);
ReleaseDC(IntPtr.Zero, hdc);
Rectangle bounds = new Rectangle(0, 0, screenWidth, screenHeight);
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
{
g.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size);
CURSORINFO cursorInfo;
cursorInfo.CbSize = Marshal.SizeOf<CURSORINFO>();
if (GetCursorInfo(out cursorInfo) && cursorInfo.Flags == CURSORSHOWING)
{
using (System.Drawing.Graphics gIcon = System.Drawing.Graphics.FromImage(bitmap))
{
IntPtr hdcDest = gIcon.GetHdc();
DrawIconEx(hdcDest, cursorInfo.PTScreenPos.X, cursorInfo.PTScreenPos.Y, cursorInfo.HCursor, 0, 0, 0, IntPtr.Zero, DINORMAL);
gIcon.ReleaseHdc(hdcDest);
}
}
}
bitmap.Save(filePath, ImageFormat.Png);
}
}
/// <summary>
/// Captures a screenshot and saves it to the specified directory.
/// </summary>
/// <param name="directory">The directory to save the screenshot.</param>
private static void CaptureScreenshot(string directory)
{
string filePath = Path.Combine(directory, $"screenshot_{DateTime.Now:yyyyMMdd_HHmmssfff}.png");
CaptureScreenWithMouse(filePath);
}
/// <summary>
/// Timer callback method to capture a screenshot.
/// </summary>
/// <param name="state">The state object passed to the callback method.</param>
public static void TimerCallback(object? state)
{
string directory = (string)state!;
CaptureScreenshot(directory);
}
}
}

View File

@@ -3,8 +3,9 @@
// See the LICENSE file in the project root for more information.
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Xml.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Windows;
@@ -17,27 +18,78 @@ namespace Microsoft.PowerToys.UITest
/// </summary>
public class Session
{
private WindowsDriver<WindowsElement> Root { get; set; }
public WindowsDriver<WindowsElement> Root { get; set; }
private WindowsDriver<WindowsElement> WindowsDriver { get; set; }
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(nint hWnd);
private const string AdministratorPrefix = "Administrator: ";
public Session(WindowsDriver<WindowsElement> root, WindowsDriver<WindowsElement> windowsDriver)
private List<IntPtr> windowHandlers = new List<IntPtr>();
private Window? MainWindow { get; set; }
/// <summary>
/// Gets Main Window Handler
/// </summary>
public IntPtr MainWindowHandler { get; private set; }
/// <summary>
/// Gets the RunAsAdmin flag.
/// If true, the session is running as admin.
/// If false, the session is not running as admin.
/// If null, no information is available.
/// </summary>
public bool? IsElevated { get; private set; }
public Session(WindowsDriver<WindowsElement> root, WindowsDriver<WindowsElement> windowsDriver, PowerToysModule scope, WindowSize size)
{
this.MainWindowHandler = IntPtr.Zero;
this.Root = root;
this.WindowsDriver = windowsDriver;
// Attach to the scope & reset MainWindowHandler
this.Attach(scope, size);
}
/// <summary>
/// Finds an element by selector.
/// Cleans up the Session Exe.
/// </summary>
public void Cleanup()
{
/*
foreach (var windowHandle in this.windowHandlers)
{
if (windowHandle == IntPtr.Zero)
{
continue;
}
try
{
var process = Process.GetProcessById((int)windowHandle);
if (process != null && !process.HasExited)
{
process.Kill();
process.WaitForExit();
}
}
catch
{
}
}
*/
windowHandlers.Clear();
}
/// <summary>
/// Finds an Element or its derived class by selector.
/// </summary>
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
/// <param name="by">The selector to find the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>The found element.</returns>
public T Find<T>(By by, int timeoutMS = 3000)
public T Find<T>(By by, int timeoutMS = 5000)
where T : Element, new()
{
Assert.IsNotNull(this.WindowsDriver, $"WindowsElement is null in method Find<{typeof(T).Name}> with parameters: by = {by}, timeoutMS = {timeoutMS}");
@@ -45,7 +97,7 @@ namespace Microsoft.PowerToys.UITest
// leverage findAll to filter out mismatched elements
var collection = this.FindAll<T>(by, timeoutMS);
Assert.IsTrue(collection.Count > 0, $"Element not found using selector: {by}");
Assert.IsTrue(collection.Count > 0, $"UI-Element({typeof(T).Name}) not found using selector: {by}");
return collection[0];
}
@@ -55,9 +107,9 @@ namespace Microsoft.PowerToys.UITest
/// </summary>
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
/// <param name="name">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>The found element.</returns>
public T Find<T>(string name, int timeoutMS = 3000)
public T Find<T>(string name, int timeoutMS = 5000)
where T : Element, new()
{
return this.Find<T>(By.Name(name), timeoutMS);
@@ -67,9 +119,9 @@ namespace Microsoft.PowerToys.UITest
/// Shortcut for this.Find<Element>(by, timeoutMS)
/// </summary>
/// <param name="by">The selector to find the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>The found element.</returns>
public Element Find(By by, int timeoutMS = 3000)
public Element Find(By by, int timeoutMS = 5000)
{
return this.Find<Element>(by, timeoutMS);
}
@@ -78,21 +130,117 @@ namespace Microsoft.PowerToys.UITest
/// Shortcut for this.Find<Element>(By.Name(name), timeoutMS)
/// </summary>
/// <param name="name">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>The found element.</returns>
public Element Find(string name, int timeoutMS = 3000)
public Element Find(string name, int timeoutMS = 5000)
{
return this.Find<Element>(By.Name(name), timeoutMS);
}
/// <summary>
/// Finds all elements by selector.
/// Has only one Element or its derived class by selector.
/// </summary>
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
/// <param name="by">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if only has one element, otherwise false.</returns>
public bool HasOne<T>(By by, int timeoutMS = 5000)
where T : Element, new()
{
return this.FindAll<T>(by, timeoutMS).Count == 1;
}
/// <summary>
/// Shortcut for this.HasOne<Element>(by, timeoutMS)
/// </summary>
/// <param name="by">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if only has one element, otherwise false.</returns>
public bool HasOne(By by, int timeoutMS = 5000)
{
return this.HasOne<Element>(by, timeoutMS);
}
/// <summary>
/// Shortcut for this.HasOne<T>(By.Name(name), timeoutMS)
/// </summary>
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
/// <param name="name">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if only has one element, otherwise false.</returns>
public bool HasOne<T>(string name, int timeoutMS = 5000)
where T : Element, new()
{
return this.HasOne<T>(By.Name(name), timeoutMS);
}
/// <summary>
/// Shortcut for this.HasOne<Element>(name, timeoutMS)
/// </summary>
/// <param name="name">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if only has one element, otherwise false.</returns>
public bool HasOne(string name, int timeoutMS = 5000)
{
return this.HasOne<Element>(By.Name(name), timeoutMS);
}
/// <summary>
/// Has one or more Element or its derived class by selector.
/// </summary>
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
/// <param name="by">The selector to find the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if has one or more element, otherwise false.</returns>
public bool Has<T>(By by, int timeoutMS = 5000)
where T : Element, new()
{
return this.FindAll<T>(by, timeoutMS).Count >= 1;
}
/// <summary>
/// Shortcut for this.Has<Element>(by, timeoutMS)
/// </summary>
/// <param name="by">The selector to find the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if has one or more element, otherwise false.</returns>
public bool Has(By by, int timeoutMS = 5000)
{
return this.Has<Element>(by, timeoutMS);
}
/// <summary>
/// Shortcut for this.Has<T>(By.Name(name), timeoutMS)
/// </summary>
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
/// <param name="name">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if has one or more element, otherwise false.</returns>
public bool Has<T>(string name, int timeoutMS = 5000)
where T : Element, new()
{
return this.Has<T>(By.Name(name), timeoutMS);
}
/// <summary>
/// Shortcut for this.Has<Element>(name, timeoutMS)
/// </summary>
/// <param name="name">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if has one or more element, otherwise false.</returns>
public bool Has(string name, int timeoutMS = 5000)
{
return this.Has<Element>(name, timeoutMS);
}
/// <summary>
/// Finds all Element or its derived class by selector.
/// </summary>
/// <typeparam name="T">The class of the elements, should be Element or its derived class.</typeparam>
/// <param name="by">The selector to find the elements.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>A read-only collection of the found elements.</returns>
public ReadOnlyCollection<T> FindAll<T>(By by, int timeoutMS = 3000)
public ReadOnlyCollection<T> FindAll<T>(By by, int timeoutMS = 5000)
where T : Element, new()
{
Assert.IsNotNull(this.WindowsDriver, $"WindowsElement is null in method FindAll<{typeof(T).Name}> with parameters: by = {by}, timeoutMS = {timeoutMS}");
@@ -122,9 +270,9 @@ namespace Microsoft.PowerToys.UITest
/// </summary>
/// <typeparam name="T">The class of the elements, should be Element or its derived class.</typeparam>
/// <param name="name">The name to find the elements.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>A read-only collection of the found elements.</returns>
public ReadOnlyCollection<T> FindAll<T>(string name, int timeoutMS = 3000)
public ReadOnlyCollection<T> FindAll<T>(string name, int timeoutMS = 5000)
where T : Element, new()
{
return this.FindAll<T>(By.Name(name), timeoutMS);
@@ -135,9 +283,9 @@ namespace Microsoft.PowerToys.UITest
/// Shortcut for this.FindAll<Element>(by, timeoutMS)
/// </summary>
/// <param name="by">The selector to find the elements.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>A read-only collection of the found elements.</returns>
public ReadOnlyCollection<Element> FindAll(By by, int timeoutMS = 3000)
public ReadOnlyCollection<Element> FindAll(By by, int timeoutMS = 5000)
{
return this.FindAll<Element>(by, timeoutMS);
}
@@ -147,55 +295,327 @@ namespace Microsoft.PowerToys.UITest
/// Shortcut for this.FindAll<Element>(By.Name(name), timeoutMS)
/// </summary>
/// <param name="name">The name to find the elements.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>A read-only collection of the found elements.</returns>
public ReadOnlyCollection<Element> FindAll(string name, int timeoutMS = 3000)
public ReadOnlyCollection<Element> FindAll(string name, int timeoutMS = 5000)
{
return this.FindAll<Element>(By.Name(name), timeoutMS);
}
/// <summary>
/// Keyboard Action key.
/// Sets the main window size.
/// </summary>
/// <param name="key1">The Keys1 to click.</param>
/// <param name="key2">The Keys2 to click.</param>
/// <param name="key3">The Keys3 to click.</param>
/// <param name="key4">The Keys4 to click.</param>
public void KeyboardAction(string key1, string key2 = "", string key3 = "", string key4 = "")
/// <param name="size">WindowSize enum</param>
public void SetMainWindowSize(WindowSize size)
{
PerformAction((actions, windowElement) =>
if (size == WindowSize.UnSpecified)
{
if (string.IsNullOrEmpty(key2))
{
actions.SendKeys(key1);
}
else if (string.IsNullOrEmpty(key3))
{
actions.SendKeys(key1).SendKeys(key2);
}
else if (string.IsNullOrEmpty(key4))
{
actions.SendKeys(key1).SendKeys(key2).SendKeys(key3);
}
else
{
actions.SendKeys(key1).SendKeys(key2).SendKeys(key3).SendKeys(key4);
}
return;
}
actions.Release();
actions.Build().Perform();
int width = 0, height = 0;
switch (size)
{
case WindowSize.Small:
width = 640;
height = 480;
break;
case WindowSize.Small_Vertical:
width = 480;
height = 640;
break;
case WindowSize.Medium:
width = 1024;
height = 768;
break;
case WindowSize.Medium_Vertical:
width = 768;
height = 1024;
break;
case WindowSize.Large:
width = 1920;
height = 1080;
break;
case WindowSize.Large_Vertical:
width = 1080;
height = 1920;
break;
}
if (width > 0 && height > 0)
{
this.SetMainWindowSize(width, height);
}
}
/// <summary>
/// Gets the main window center coordinates.
/// </summary>
/// <returns>(x, y)</returns>
public (int CenterX, int CenterY) GetWindowCenter()
{
if (this.MainWindowHandler == IntPtr.Zero)
{
return (0, 0);
}
else
{
var rect = ApiHelper.GetWindowCenter(this.MainWindowHandler);
return (rect.CenterX, rect.CenterY);
}
}
/// <summary>
/// Gets the screen center coordinates.
/// </summary>
/// <returns>(x, y)</returns>
public (int CenterX, int CenterY) GetScreenCenter()
{
return ApiHelper.GetScreenCenter();
}
/// <summary>
/// Sets the main window size based on Width and Height.
/// </summary>
/// <param name="width">the width in pixel</param>
/// <param name="height">the height in pixel</param>
public void SetMainWindowSize(int width, int height)
{
if (this.MainWindowHandler == IntPtr.Zero
|| width <= 0
|| height <= 0)
{
return;
}
ApiHelper.SetWindowPos(this.MainWindowHandler, IntPtr.Zero, 0, 0, width, height, ApiHelper.SetWindowPosNoZorder | ApiHelper.SetWindowPosShowWindow);
// Wait for 1000ms after resize
Task.Delay(1000).Wait();
}
/// <summary>
/// Close the main window.
/// </summary>
public void CloseMainWindow()
{
if (MainWindow != null)
{
MainWindow.Close();
MainWindow = null;
}
}
/// <summary>
/// Retrieves the color of the pixel at the specified screen coordinates.
/// </summary>
/// <param name="x">The X coordinate on the screen.</param>
/// <param name="y">The Y coordinate on the screen.</param>
/// <returns>The color of the pixel at the specified coordinates.</returns>
public Color GetPixelColor(int x, int y)
{
IntPtr hdc = ApiHelper.GetDC(IntPtr.Zero);
uint pixel = ApiHelper.GetPixel(hdc, x, y);
_ = ApiHelper.ReleaseDC(IntPtr.Zero, hdc);
int r = (int)(pixel & 0x000000FF);
int g = (int)((pixel & 0x0000FF00) >> 8);
int b = (int)((pixel & 0x00FF0000) >> 16);
return Color.FromArgb(r, g, b);
}
/// <summary>
/// Retrieves the color of the pixel at the specified screen coordinates as a string.
/// </summary>
/// <param name="x">The X coordinate on the screen.</param>
/// <param name="y">The Y coordinate on the screen.</param>
/// <returns>The color of the pixel at the specified coordinates.</returns>
public string GetPixelColorString(int x, int y)
{
Color color = this.GetPixelColor(x, y);
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
/// <summary>
/// Gets the size of the display.
/// </summary>
/// <returns>
/// A tuple containing the width and height of the display.
/// </returns
public Tuple<int, int> GetDisplaySize()
{
IntPtr hdc = ApiHelper.GetDC(IntPtr.Zero);
int screenWidth = ApiHelper.GetDeviceCaps(hdc, ApiHelper.DESKTOPHORZRES);
int screenHeight = ApiHelper.GetDeviceCaps(hdc, ApiHelper.DESKTOPVERTRES);
_ = ApiHelper.ReleaseDC(IntPtr.Zero, hdc);
return Tuple.Create(screenWidth, screenHeight);
}
/// <summary>
/// Sends a combination of keys.
/// </summary>
/// <param name="keys">The keys to send.</param>
public void SendKeys(params Key[] keys)
{
PerformAction(() =>
{
KeyboardHelper.SendKeys(keys);
});
}
/// <summary>
/// release the key (after the hold key and drag is completed.)
/// </summary>
/// <param name="key">The key release.</param>
public void PressKey(Key key)
{
PerformAction(() =>
{
KeyboardHelper.PressKey(key);
});
}
/// <summary>
/// press and hold the specified key.
/// </summary>
/// <param name="key">The key to press and hold .</param>
public void ReleaseKey(Key key)
{
PerformAction(() =>
{
KeyboardHelper.ReleaseKey(key);
});
}
/// <summary>
/// press and hold the specified key.
/// </summary>
/// <param name="key">The key to press and release .</param>
public void SendKey(Key key, int msPreAction = 500, int msPostAction = 500)
{
PerformAction(
() =>
{
KeyboardHelper.SendKey(key);
},
msPreAction,
msPostAction);
}
/// <summary>
/// Sends a sequence of keys.
/// </summary>
/// <param name="keys">An array of keys to send.</param>
public void SendKeySequence(params Key[] keys)
{
PerformAction(() =>
{
foreach (var key in keys)
{
KeyboardHelper.SendKeys(key);
}
});
}
        /// <summary>
        /// Gets the current position of the mouse cursor as a tuple.
        /// </summary>
        /// <returns>A tuple containing the X and Y coordinates of the cursor.</returns>
public Tuple<int, int> GetMousePosition()
{
return MouseHelper.GetMousePosition();
}
/// <summary>
    /// Moves the mouse cursor to the specified screen coordinates.
    /// </summary>
    /// <param name="x">The new x-coordinate of the cursor.</param>
    /// <param name="y">The new y-coordinate of the cursor.</param
public void MoveMouseTo(int x, int y, int msPreAction = 500, int msPostAction = 500)
{
PerformAction(
() =>
{
MouseHelper.MoveMouseTo(x, y);
},
msPreAction,
msPostAction);
}
/// <summary>
/// Performs a mouse action based on the specified action type.
/// </summary>
/// <param name="action">The mouse action to perform.</param>
/// <param name="msPreAction">Pre-action delay in milliseconds.</param>
/// <param name="msPostAction">Post-action delay in milliseconds.</param>
public void PerformMouseAction(MouseActionType action, int msPreAction = 500, int msPostAction = 500)
{
PerformAction(
() =>
{
switch (action)
{
case MouseActionType.LeftClick:
MouseHelper.LeftClick();
break;
case MouseActionType.RightClick:
MouseHelper.RightClick();
break;
case MouseActionType.MiddleClick:
MouseHelper.MiddleClick();
break;
case MouseActionType.LeftDoubleClick:
MouseHelper.LeftDoubleClick();
break;
case MouseActionType.RightDoubleClick:
MouseHelper.RightDoubleClick();
break;
case MouseActionType.LeftDown:
MouseHelper.LeftDown();
break;
case MouseActionType.LeftUp:
MouseHelper.LeftUp();
break;
case MouseActionType.RightDown:
MouseHelper.RightDown();
break;
case MouseActionType.RightUp:
MouseHelper.RightUp();
break;
case MouseActionType.MiddleDown:
MouseHelper.MiddleDown();
break;
case MouseActionType.MiddleUp:
MouseHelper.MiddleUp();
break;
case MouseActionType.ScrollUp:
MouseHelper.ScrollUp();
break;
case MouseActionType.ScrollDown:
MouseHelper.ScrollDown();
break;
default:
throw new ArgumentException("Unsupported mouse action.", nameof(action));
throw new ArgumentException("Unsupported mouse action.", nameof(action));
}
},
msPreAction,
msPostAction);
}
/// <summary>
/// Attaches to an existing PowerToys module.
/// </summary>
/// <param name="module">The PowerToys module to attach to.</param>
/// <param name="size">The window size to set. Default is no change to window size</param>
/// <returns>The attached session.</returns>
public Session Attach(PowerToysModule module)
public Session Attach(PowerToysModule module, WindowSize size = WindowSize.UnSpecified)
{
string windowName = ModuleConfigData.Instance.GetModuleWindowName(module);
return this.Attach(windowName);
return this.Attach(windowName, size);
}
/// <summary>
@@ -203,26 +623,44 @@ namespace Microsoft.PowerToys.UITest
/// The session should be attached when a new app is started.
/// </summary>
/// <param name="windowName">The window name to attach to.</param>
/// <param name="size">The window size to set. Default is no change to window size</param>
/// <returns>The attached session.</returns>
public Session Attach(string windowName)
public Session Attach(string windowName, WindowSize size = WindowSize.UnSpecified)
{
this.IsElevated = null;
this.MainWindowHandler = IntPtr.Zero;
if (this.Root != null)
{
var window = this.Root.FindElementByName(windowName);
Assert.IsNotNull(window, $"Failed to attach. Window '{windowName}' not found");
// search window handler by window title (admin and non-admin titles)
var matchingWindows = ApiHelper.FindDesktopWindowHandler([windowName, AdministratorPrefix + windowName]);
if (matchingWindows.Count == 0 || matchingWindows[0].HWnd == IntPtr.Zero)
{
Assert.Fail($"Failed to attach. Window '{windowName}' not found");
}
// pick one from matching windows
this.MainWindowHandler = matchingWindows[0].HWnd;
this.IsElevated = matchingWindows[0].Title.StartsWith(AdministratorPrefix);
ApiHelper.SetForegroundWindow(this.MainWindowHandler);
var hexWindowHandle = this.MainWindowHandler.ToInt64().ToString("x");
var windowHandle = new nint(int.Parse(window.GetAttribute("NativeWindowHandle")));
SetForegroundWindow(windowHandle);
var hexWindowHandle = windowHandle.ToString("x");
var appCapabilities = new AppiumOptions();
appCapabilities.AddAdditionalCapability("appTopLevelWindow", hexWindowHandle);
appCapabilities.AddAdditionalCapability("deviceName", "WindowsPC");
this.WindowsDriver = new WindowsDriver<WindowsElement>(new Uri(ModuleConfigData.Instance.GetWindowsApplicationDriverUrl()), appCapabilities);
Assert.IsNotNull(this.WindowsDriver, "Attach WindowsDriver is null");
// Set implicit timeout to make element search retry every 500 ms
this.WindowsDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3);
this.windowHandlers.Add(this.MainWindowHandler);
if (size != WindowSize.UnSpecified)
{
this.SetMainWindowSize(size);
}
// Set MainWindow
MainWindow = Find<Window>(matchingWindows[0].Title);
}
else
{
@@ -232,6 +670,176 @@ namespace Microsoft.PowerToys.UITest
return this;
}
public bool IsWindowOpen(string windowName)
{
var matchingWindows = ApiHelper.FindDesktopWindowHandler([windowName, AdministratorPrefix + windowName]);
return matchingWindows.Count > 0;
}
private static class ApiHelper
{
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
public const uint SetWindowPosNoMove = 0x0002;
public const uint SetWindowPosNoZorder = 0x0004;
public const uint SetWindowPosShowWindow = 0x0040;
[DllImport("user32.dll", SetLastError = true)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
// Delegate for the EnumWindows callback function
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
// P/Invoke declaration for EnumWindows
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
// P/Invoke declaration for GetWindowTextLength
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int GetWindowTextLength(IntPtr hWnd);
// P/Invoke declaration for GetWindowText
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
public static extern uint GetPixel(IntPtr hdc, int x, int y);
[DllImport("gdi32.dll")]
public static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
public const int DESKTOPHORZRES = 118;
public const int DESKTOPVERTRES = 117;
[DllImport("user32.dll")]
public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
// Define the Win32 RECT structure
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left; // X coordinate of the left edge of the window
public int Top; // Y coordinate of the top edge of the window
public int Right; // X coordinate of the right edge of the window
public int Bottom; // Y coordinate of the bottom edge of the window
}
// Import GetWindowRect API to retrieve window's screen coordinates
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
public static List<(IntPtr HWnd, string Title)> FindDesktopWindowHandler(string[] matchingWindowsTitles)
{
var windows = new List<(IntPtr HWnd, string Title)>();
_ = EnumWindows(
(hWnd, lParam) =>
{
int length = GetWindowTextLength(hWnd);
if (length > 0)
{
var builder = new StringBuilder(length + 1);
_ = GetWindowText(hWnd, builder, builder.Capacity);
var title = builder.ToString();
if (matchingWindowsTitles.Contains(title))
{
windows.Add((hWnd, title));
}
}
return true; // Continue enumeration
},
IntPtr.Zero);
return windows;
}
/// <summary>
/// Get the center point coordinates of a specified window (in screen coordinates)
/// </summary>
/// <param name="hWnd">The window handle</param>
/// <returns>The center point (x, y)</returns>
public static (int CenterX, int CenterY) GetWindowCenter(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
{
throw new ArgumentException("Invalid window handle");
}
if (GetWindowRect(hWnd, out RECT rect))
{
int width = rect.Right - rect.Left;
int height = rect.Bottom - rect.Top;
int centerX = rect.Left + (width / 2);
int centerY = rect.Top + (height / 2);
return (centerX, centerY);
}
else
{
throw new InvalidOperationException("Failed to retrieve window coordinates");
}
}
[DllImport("user32.dll")]
public static extern int GetSystemMetrics(int nIndex);
public enum SystemMetric
{
ScreenWidth = 0, // Width of the primary screen in pixels (SM_CXSCREEN)
ScreenHeight = 1, // Height of the primary screen in pixels (SM_CYSCREEN)
VirtualScreenWidth = 78, // Width of the virtual screen that includes all monitors (SM_CXVIRTUALSCREEN)
VirtualScreenHeight = 79, // Height of the virtual screen that includes all monitors (SM_CYVIRTUALSCREEN)
MonitorCount = 80, // Number of display monitors (SM_CMONITORS, available on Windows XP+)
}
public static (int CenterX, int CenterY) GetScreenCenter()
{
int width = GetSystemMetrics((int)SystemMetric.ScreenWidth);
int height = GetSystemMetrics((int)SystemMetric.ScreenHeight);
return (width / 2, height / 2);
}
}
public void StartExe(string executablePath, string arguments = "", int msPreAction = 0, int msPostAction = 2000)
{
PerformAction(
() =>
{
StartExeInternal(executablePath, arguments);
},
msPreAction,
msPostAction);
}
private void StartExeInternal(string executablePath, string arguments = "")
{
var processInfo = new ProcessStartInfo
{
FileName = executablePath,
Arguments = arguments,
UseShellExecute = true,
};
Process.Start(processInfo);
}
public void KillAllProcessesByName(string processName)
{
foreach (var process in Process.GetProcessesByName(processName))
{
process.Kill();
process.WaitForExit();
}
}
/// <summary>
/// Simulates a manual operation on the element.
/// </summary>
@@ -254,5 +862,26 @@ namespace Microsoft.PowerToys.UITest
Task.Delay(msPostAction).Wait();
}
}
/// <summary>
/// Simulates a manual operation on the element.
/// </summary>
/// <param name="action">The action to perform on the element.</param>
/// <param name="msPreAction">The number of milliseconds to wait before the action. Default value is 500 ms</param>
/// <param name="msPostAction">The number of milliseconds to wait after the action. Default value is 500 ms</param>
protected void PerformAction(Action action, int msPreAction = 500, int msPostAction = 500)
{
if (msPreAction > 0)
{
Task.Delay(msPreAction).Wait();
}
action();
if (msPostAction > 0)
{
Task.Delay(msPostAction).Wait();
}
}
}
}

View File

@@ -20,6 +20,8 @@ namespace Microsoft.PowerToys.UITest
// Default session path is PowerToys settings dashboard
private readonly string sessionPath = ModuleConfigData.Instance.GetModulePath(PowerToysModule.PowerToysSettings);
private readonly string runnerPath = ModuleConfigData.Instance.GetModulePath(PowerToysModule.Runner);
private string? locationPath;
private WindowsDriver<WindowsElement> Root { get; set; }
@@ -27,10 +29,14 @@ namespace Microsoft.PowerToys.UITest
private WindowsDriver<WindowsElement>? Driver { get; set; }
private Process? appDriver;
private Process? runner;
private PowerToysModule scope;
[UnconditionalSuppressMessage("SingleFile", "IL3000:Avoid accessing Assembly file path when publishing as a single file", Justification = "<Pending>")]
public SessionHelper(PowerToysModule scope)
{
this.scope = scope;
this.sessionPath = ModuleConfigData.Instance.GetModulePath(scope);
this.locationPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
@@ -40,14 +46,23 @@ namespace Microsoft.PowerToys.UITest
Verb = "runas",
};
this.ExitExe(winAppDriverProcessInfo.FileName);
this.appDriver = Process.Start(winAppDriverProcessInfo);
var runnerProcessInfo = new ProcessStartInfo
{
FileName = locationPath + this.runnerPath,
Verb = "runas",
};
if (scope == PowerToysModule.PowerToysSettings)
{
this.runner = Process.Start(runnerProcessInfo);
}
var desktopCapabilities = new AppiumOptions();
desktopCapabilities.AddAdditionalCapability("app", "Root");
this.Root = new WindowsDriver<WindowsElement>(new Uri(ModuleConfigData.Instance.GetWindowsApplicationDriverUrl()), desktopCapabilities);
// Set default timeout to 5 seconds
this.Root.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
}
/// <summary>
@@ -56,7 +71,11 @@ namespace Microsoft.PowerToys.UITest
/// <param name="scope">The PowerToys module to start.</param>
public SessionHelper Init()
{
this.StartExe(locationPath + this.sessionPath);
// Exit setting exe to fix CommandPalette error, remove after fixing the issue
this.ExitExe(this.locationPath + ModuleConfigData.Instance.GetModulePath(PowerToysModule.PowerToysSettings));
this.ExitExe(this.locationPath + this.sessionPath);
this.StartExe(this.locationPath + this.sessionPath);
Assert.IsNotNull(this.Driver, $"Failed to initialize the test environment. Driver is null.");
@@ -73,6 +92,11 @@ namespace Microsoft.PowerToys.UITest
{
appDriver?.Kill();
appDriver?.WaitForExit(); // Optional: Wait for the process to exit
if (this.scope == PowerToysModule.PowerToysSettings)
{
runner?.Kill();
runner?.WaitForExit(); // Optional: Wait for the process to exit
}
}
catch (Exception ex)
{
@@ -81,31 +105,15 @@ namespace Microsoft.PowerToys.UITest
}
}
/// <summary>
/// Starts a new exe and takes control of it.
/// </summary>
/// <param name="appPath">The path to the application executable.</param>
public void StartExe(string appPath)
{
var opts = new AppiumOptions();
opts.AddAdditionalCapability("app", appPath);
Console.WriteLine($"appPath: {appPath}");
this.Driver = new WindowsDriver<WindowsElement>(new Uri(ModuleConfigData.Instance.GetWindowsApplicationDriverUrl()), opts);
// Set default timeout to 5 seconds
this.Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
}
/// <summary>
/// Exit a exe.
/// </summary>
/// <param name="path">The path to the application executable.</param>
public void ExitExe(string path)
/// <param name="appPath">The path to the application executable.</param>
public void ExitExe(string appPath)
{
// Exit Exe
string exeName = Path.GetFileNameWithoutExtension(path);
string exeName = Path.GetFileNameWithoutExtension(appPath);
// PowerToys.FancyZonesEditor
Process[] processes = Process.GetProcessesByName(exeName);
foreach (Process process in processes)
{
@@ -121,6 +129,21 @@ namespace Microsoft.PowerToys.UITest
}
}
/// <summary>
/// Starts a new exe and takes control of it.
/// </summary>
/// <param name="appPath">The path to the application executable.</param>
public void StartExe(string appPath)
{
var opts = new AppiumOptions();
opts.AddAdditionalCapability("app", appPath);
opts.AddAdditionalCapability("ms:waitForAppLaunch", "5");
this.Driver = new WindowsDriver<WindowsElement>(new Uri(ModuleConfigData.Instance.GetWindowsApplicationDriverUrl()), opts);
// Set default timeout to 5 seconds
this.Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
}
/// <summary>
/// Exit now exe.
/// </summary>

View File

@@ -8,6 +8,9 @@
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<InvariantGlobalization>true</InvariantGlobalization>
<TargetFramework>net9.0-windows10.0.22621.0</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<PublishTrimmed>false</PublishTrimmed>
</PropertyGroup>
<ItemGroup>

View File

@@ -6,10 +6,15 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Windows;
using Windows.Devices.Display.Core;
using Windows.Foundation.Metadata;
using static Microsoft.PowerToys.UITest.UITestBase.NativeMethods;
namespace Microsoft.PowerToys.UITest
{
@@ -17,19 +22,36 @@ namespace Microsoft.PowerToys.UITest
/// Base class that should be inherited by all Test Classes.
/// </summary>
[TestClass]
public class UITestBase
public class UITestBase : IDisposable
{
public Session Session { get; set; }
public required TestContext TestContext { get; set; }
private readonly SessionHelper sessionHelper;
public required Session Session { get; set; }
private readonly bool isInPipeline;
private readonly PowerToysModule scope;
private readonly WindowSize size;
private SessionHelper? sessionHelper;
private System.Threading.Timer? screenshotTimer;
private string? screenshotDirectory;
public UITestBase(PowerToysModule scope = PowerToysModule.PowerToysSettings)
// private System.Threading.Timer? screenshotTimer;
// private string? screenshotDirectory;
public UITestBase(PowerToysModule scope = PowerToysModule.PowerToysSettings, WindowSize size = WindowSize.UnSpecified)
{
this.isInPipeline = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("platform"));
Console.WriteLine($"Running tests on platform: {Environment.GetEnvironmentVariable("platform")}");
if (isInPipeline)
{
NativeMethods.ChangeDispalyResolution();
NativeMethods.GetMonitorInfo();
// Escape Popups before starting
System.Windows.Forms.SendKeys.SendWait("{ESC}");
}
this.scope = scope;
this.sessionHelper = new SessionHelper(scope).Init();
this.Session = new Session(this.sessionHelper.GetRoot(), this.sessionHelper.GetDriver());
this.size = size;
}
/// <summary>
@@ -38,6 +60,18 @@ namespace Microsoft.PowerToys.UITest
[TestInitialize]
public void TestInit()
{
if (isInPipeline)
{
screenshotDirectory = Path.Combine(this.TestContext.TestResultsDirectory ?? string.Empty, "UITestScreenshots_" + Guid.NewGuid().ToString());
Directory.CreateDirectory(screenshotDirectory);
// Take screenshot every 1 second
screenshotTimer = new System.Threading.Timer(ScreenCapture.TimerCallback, screenshotDirectory, TimeSpan.Zero, TimeSpan.FromMilliseconds(1000));
}
this.sessionHelper = new SessionHelper(scope).Init();
this.Session = new Session(this.sessionHelper.GetRoot(), this.sessionHelper.GetDriver(), scope, size);
if (this.scope == PowerToysModule.PowerToysSettings)
{
// close Debug warning dialog if any
@@ -50,12 +84,32 @@ namespace Microsoft.PowerToys.UITest
}
/// <summary>
/// UnInitializes the test.
/// Cleanups the test.
/// </summary>
[TestCleanup]
public void TestClean()
public void TestCleanup()
{
this.sessionHelper.Cleanup();
if (isInPipeline)
{
screenshotTimer?.Change(Timeout.Infinite, Timeout.Infinite);
Dispose();
if (TestContext.CurrentTestOutcome is UnitTestOutcome.Failed
or UnitTestOutcome.Error
or UnitTestOutcome.Unknown)
{
Task.Delay(1000).Wait();
AddScreenShotsToTestResultsDirectory();
}
}
this.Session.Cleanup();
this.sessionHelper!.Cleanup();
}
public void Dispose()
{
screenshotTimer?.Dispose();
GC.SuppressFinalize(this);
}
/// <summary>
@@ -64,22 +118,22 @@ namespace Microsoft.PowerToys.UITest
/// </summary>
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
/// <param name="by">The selector to find the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>The found element.</returns>
protected T Find<T>(By by, int timeoutMS = 3000)
protected T Find<T>(By by, int timeoutMS = 5000)
where T : Element, new()
{
return this.Session.Find<T>(by, timeoutMS);
}
/// <summary>
/// Shortcut for this.Session.Find<Element>(By.Name(name), timeoutMS)
/// Shortcut for this.Session.Find<Element>(name, timeoutMS)
/// </summary>
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
/// <param name="name">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>The found element.</returns>
protected T Find<T>(string name, int timeoutMS = 3000)
protected T Find<T>(string name, int timeoutMS = 5000)
where T : Element, new()
{
return this.Session.Find<T>(By.Name(name), timeoutMS);
@@ -89,33 +143,129 @@ namespace Microsoft.PowerToys.UITest
/// Shortcut for this.Session.Find<Element>(by, timeoutMS)
/// </summary>
/// <param name="by">The selector to find the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>The found element.</returns>
protected Element Find(By by, int timeoutMS = 3000)
protected Element Find(By by, int timeoutMS = 5000)
{
return this.Session.Find(by, timeoutMS);
}
/// <summary>
/// Shortcut for this.Session.Find<Element>(By.Name(name), timeoutMS)
/// Shortcut for this.Session.Find<Element>(name, timeoutMS)
/// </summary>
/// <param name="name">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>The found element.</returns>
protected Element Find(string name, int timeoutMS = 3000)
protected Element Find(string name, int timeoutMS = 5000)
{
return this.Session.Find(name, timeoutMS);
}
/// <summary>
/// Has only one Element or its derived class by selector.
/// </summary>
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
/// <param name="by">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if only has one element, otherwise false.</returns>
public bool HasOne<T>(By by, int timeoutMS = 5000)
where T : Element, new()
{
return this.FindAll<T>(by, timeoutMS).Count == 1;
}
/// <summary>
/// Shortcut for this.Session.HasOne<Element>(by, timeoutMS)
/// </summary>
/// <param name="by">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if only has one element, otherwise false.</returns>
public bool HasOne(By by, int timeoutMS = 5000)
{
return this.Session.HasOne<Element>(by, timeoutMS);
}
/// <summary>
/// Shortcut for this.Session.HasOne<T>(name, timeoutMS)
/// </summary>
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
/// <param name="name">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if only has one element, otherwise false.</returns>
public bool HasOne<T>(string name, int timeoutMS = 5000)
where T : Element, new()
{
return this.Session.HasOne<T>(By.Name(name), timeoutMS);
}
/// <summary>
/// Shortcut for this.Session.HasOne<Element>(name, timeoutMS)
/// </summary>
/// <param name="name">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if only has one element, otherwise false.</returns>
public bool HasOne(string name, int timeoutMS = 5000)
{
return this.Session.HasOne<Element>(name, timeoutMS);
}
/// <summary>
/// Shortcut for this.Session.Has<T>(by, timeoutMS)
/// </summary>
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
/// <param name="by">The selector to find the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if has one or more element, otherwise false.</returns>
public bool Has<T>(By by, int timeoutMS = 5000)
where T : Element, new()
{
return this.Session.FindAll<T>(by, timeoutMS).Count >= 1;
}
/// <summary>
/// Shortcut for this.Session.Has<Element>(by, timeoutMS)
/// </summary>
/// <param name="by">The selector to find the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if has one or more element, otherwise false.</returns>
public bool Has(By by, int timeoutMS = 5000)
{
return this.Session.Has<Element>(by, timeoutMS);
}
/// <summary>
/// Shortcut for this.Session.Has<T>(By.Name(name), timeoutMS)
/// </summary>
/// <typeparam name="T">The class of the element, should be Element or its derived class.</typeparam>
/// <param name="name">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if has one or more element, otherwise false.</returns>
public bool Has<T>(string name, int timeoutMS = 5000)
where T : Element, new()
{
return this.Session.Has<T>(By.Name(name), timeoutMS);
}
/// <summary>
/// Shortcut for this.Session.Has<Element>(name, timeoutMS)
/// </summary>
/// <param name="name">The name of the element.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>True if has one or more element, otherwise false.</returns>
public bool Has(string name, int timeoutMS = 5000)
{
return this.Session.Has<Element>(name, timeoutMS);
}
/// <summary>
/// Finds all elements by selector.
/// Shortcut for this.Session.FindAll<T>(by, timeoutMS)
/// </summary>
/// <typeparam name="T">The class of the elements, should be Element or its derived class.</typeparam>
/// <param name="by">The selector to find the elements.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>A read-only collection of the found elements.</returns>
protected ReadOnlyCollection<T> FindAll<T>(By by, int timeoutMS = 3000)
protected ReadOnlyCollection<T> FindAll<T>(By by, int timeoutMS = 5000)
where T : Element, new()
{
return this.Session.FindAll<T>(by, timeoutMS);
@@ -127,9 +277,9 @@ namespace Microsoft.PowerToys.UITest
/// </summary>
/// <typeparam name="T">The class of the elements, should be Element or its derived class.</typeparam>
/// <param name="name">The name of the elements.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>A read-only collection of the found elements.</returns>
protected ReadOnlyCollection<T> FindAll<T>(string name, int timeoutMS = 3000)
protected ReadOnlyCollection<T> FindAll<T>(string name, int timeoutMS = 5000)
where T : Element, new()
{
return this.Session.FindAll<T>(By.Name(name), timeoutMS);
@@ -140,9 +290,9 @@ namespace Microsoft.PowerToys.UITest
/// Shortcut for this.Session.FindAll<Element>(by, timeoutMS)
/// </summary>
/// <param name="by">The selector to find the elements.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>A read-only collection of the found elements.</returns>
protected ReadOnlyCollection<Element> FindAll(By by, int timeoutMS = 3000)
protected ReadOnlyCollection<Element> FindAll(By by, int timeoutMS = 5000)
{
return this.Session.FindAll<Element>(by, timeoutMS);
}
@@ -152,20 +302,105 @@ namespace Microsoft.PowerToys.UITest
/// Shortcut for this.Session.FindAll<Element>(By.Name(name), timeoutMS)
/// </summary>
/// <param name="name">The name of the elements.</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 3000).</param>
/// <param name="timeoutMS">The timeout in milliseconds (default is 5000).</param>
/// <returns>A read-only collection of the found elements.</returns>
protected ReadOnlyCollection<Element> FindAll(string name, int timeoutMS = 3000)
protected ReadOnlyCollection<Element> FindAll(string name, int timeoutMS = 5000)
{
return this.Session.FindAll<Element>(By.Name(name), timeoutMS);
}
/// <summary>
/// Captures the last screenshot when the test fails.
/// </summary>
protected void CaptureLastScreenshot()
{
// Implement your screenshot capture logic here
// For example, save a screenshot to a file and return the file path
string screenshotPath = Path.Combine(this.TestContext.TestResultsDirectory ?? string.Empty, "last_screenshot.png");
this.Session.Root.GetScreenshot().SaveAsFile(screenshotPath, ScreenshotImageFormat.Png);
// Save screenshot to screenshotPath & upload to test attachment
this.TestContext.AddResultFile(screenshotPath);
}
/// <summary>
/// Retrieves the color of the pixel at the specified screen coordinates.
/// </summary>
/// <param name="x">The X coordinate on the screen.</param>
/// <param name="y">The Y coordinate on the screen.</param>
/// <returns>The color of the pixel at the specified coordinates.</returns>
public Color GetPixelColor(int x, int y)
{
return this.Session.GetPixelColor(x, y);
}
/// <summary>
/// Gets the size of the display.
/// </summary>
/// <returns>
/// A tuple containing the width and height of the display.
/// </returns
public Tuple<int, int> GetDisplaySize()
{
return this.Session.GetDisplaySize();
}
/// <summary>
/// Sends a combination of keys.
/// </summary>
/// <param name="keys">The keys to send.</param>
public void SendKeys(params Key[] keys)
{
this.Session.SendKeys(keys);
}
/// <summary>
/// Sends a sequence of keys.
/// </summary>
/// <param name="keys">An array of keys to send.</param>
public void SendKeySequence(params Key[] keys)
{
this.Session.SendKeySequence(keys);
}
/// <summary>
        /// Gets the current position of the mouse cursor as a tuple.
        /// </summary>
        /// <returns>A tuple containing the X and Y coordinates of the cursor.</returns>
public Tuple<int, int> GetMousePosition()
{
return this.Session.GetMousePosition();
}
/// <summary>
    /// Moves the mouse cursor to the specified screen coordinates.
    /// </summary>
    /// <param name="x">The new x-coordinate of the cursor.</param>
    /// <param name="y">The new y-coordinate of the cursor.</param
public void MoveMouseTo(int x, int y)
{
        this.Session.MoveMouseTo(x, y);
}
protected void AddScreenShotsToTestResultsDirectory()
{
if (screenshotDirectory != null)
{
foreach (string file in Directory.GetFiles(screenshotDirectory))
{
this.TestContext.AddResultFile(file);
}
}
}
/// <summary>
/// Restart scope exe.
/// </summary>
public void RestartScopeExe()
{
this.sessionHelper.RestartScopeExe();
this.Session = new Session(this.sessionHelper.GetRoot(), this.sessionHelper.GetDriver());
this.sessionHelper!.RestartScopeExe();
this.Session = new Session(this.sessionHelper.GetRoot(), this.sessionHelper.GetDriver(), this.scope, this.size);
return;
}
@@ -174,8 +409,165 @@ namespace Microsoft.PowerToys.UITest
/// </summary>
public void ExitScopeExe()
{
this.sessionHelper.ExitScopeExe();
this.sessionHelper!.ExitScopeExe();
return;
}
public class NativeMethods
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct DISPLAY_DEVICE
{
public int cb;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string DeviceName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string DeviceString;
public int StateFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string DeviceID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string DeviceKey;
}
[DllImport("user32.dll")]
private static extern int EnumDisplaySettings(IntPtr deviceName, int modeNum, ref DEVMODE devMode);
[DllImport("user32.dll")]
private static extern int EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE devMode);
[DllImport("user32.dll", CharSet = CharSet.Ansi)]
private static extern bool EnumDisplayDevices(IntPtr lpDevice, int iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, int dwFlags);
[DllImport("user32.dll")]
private static extern int ChangeDisplaySettings(ref DEVMODE devMode, int flags);
[DllImport("user32.dll", CharSet = CharSet.Ansi)]
private static extern int ChangeDisplaySettingsEx(IntPtr lpszDeviceName, ref DEVMODE lpDevMode, IntPtr hwnd, uint dwflags, IntPtr lParam);
private const int DM_PELSWIDTH = 0x80000;
private const int DM_PELSHEIGHT = 0x100000;
public const int ENUM_CURRENT_SETTINGS = -1;
public const int CDS_TEST = 0x00000002;
public const int CDS_UPDATEREGISTRY = 0x01;
public const int DISP_CHANGE_SUCCESSFUL = 0;
public const int DISP_CHANGE_RESTART = 1;
public const int DISP_CHANGE_FAILED = -1;
[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string DmDeviceName;
public short DmSpecVersion;
public short DmDriverVersion;
public short DmSize;
public short DmDriverExtra;
public int DmFields;
public int DmPositionX;
public int DmPositionY;
public int DmDisplayOrientation;
public int DmDisplayFixedOutput;
public short DmColor;
public short DmDuplex;
public short DmYResolution;
public short DmTTOption;
public short DmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string DmFormName;
public short DmLogPixels;
public int DmBitsPerPel;
public int DmPelsWidth;
public int DmPelsHeight;
public int DmDisplayFlags;
public int DmDisplayFrequency;
public int DmICMMethod;
public int DmICMIntent;
public int DmMediaType;
public int DmDitherType;
public int DmReserved1;
public int DmReserved2;
public int DmPanningWidth;
public int DmPanningHeight;
}
public static void GetMonitorInfo()
{
int deviceIndex = 0;
DISPLAY_DEVICE d = default(DISPLAY_DEVICE);
d.cb = Marshal.SizeOf(d);
Console.WriteLine("monitor list :");
while (EnumDisplayDevices(IntPtr.Zero, deviceIndex, ref d, 0))
{
Console.WriteLine($"monitor {deviceIndex + 1}:");
Console.WriteLine($" name: {d.DeviceName}");
Console.WriteLine($"  string: {d.DeviceString}");
Console.WriteLine($"  ID: {d.DeviceID}");
Console.WriteLine($"  key: {d.DeviceKey}");
Console.WriteLine();
DEVMODE dm = default(DEVMODE);
dm.DmSize = (short)Marshal.SizeOf<DEVMODE>();
int modeNum = 0;
while (EnumDisplaySettings(d.DeviceName, modeNum, ref dm) > 0)
{
Console.WriteLine($"  mode {modeNum}: {dm.DmPelsWidth}x{dm.DmPelsHeight} @ {dm.DmDisplayFrequency}Hz");
modeNum++;
}
deviceIndex++;
d.cb = Marshal.SizeOf(d); // Reset the size for the next device
}
}
public static void ChangeDispalyResolution()
{
Screen screen = Screen.PrimaryScreen!;
if (screen.Bounds.Width == 1920 && screen.Bounds.Height == 1080)
{
return;
}
DEVMODE devMode = default(DEVMODE);
devMode.DmDeviceName = new string(new char[32]);
devMode.DmFormName = new string(new char[32]);
devMode.DmSize = (short)Marshal.SizeOf<DEVMODE>();
int modeNum = 0;
while (EnumDisplaySettings(IntPtr.Zero, modeNum, ref devMode) > 0)
{
Console.WriteLine($"Mode {modeNum}: {devMode.DmPelsWidth}x{devMode.DmPelsHeight} @ {devMode.DmDisplayFrequency}Hz");
modeNum++;
}
devMode.DmPelsWidth = 1920;
devMode.DmPelsHeight = 1080;
int result = NativeMethods.ChangeDisplaySettings(ref devMode, NativeMethods.CDS_TEST);
if (result == DISP_CHANGE_SUCCESSFUL)
{
result = ChangeDisplaySettings(ref devMode, CDS_UPDATEREGISTRY);
if (result == DISP_CHANGE_SUCCESSFUL)
{
Console.WriteLine($"Changing display resolution to {devMode.DmPelsWidth}x{devMode.DmPelsHeight}");
}
else
{
Console.WriteLine($"Failed to change display resolution. Error code: {result}");
}
}
else if (result == DISP_CHANGE_RESTART)
{
Console.WriteLine($"Changing display resolution to {devMode.DmPelsWidth}x{devMode.DmPelsHeight} requires a restart");
}
else
{
Console.WriteLine($"Failed to change display resolution. Error code: {result}");
}
}
}
}
}

View File

@@ -0,0 +1,160 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.PowerToys.UITest
{
public static class VisualAssert
{
/// <summary>
/// Asserts current visual state of the element is equal with base line image.
/// To use this VisualAssert, you need to set Window Theme to Light-Mode to avoid Theme color difference in baseline image.
/// Such limiation could be removed either Auto-generate baseline image for both Light & Dark mode
/// </summary>
/// <param name="testContext">TestContext object</param>
/// <param name="element">Element object</param>
/// <param name="scenarioSubname">additional scenario name if two or more scenarios in one test</param>
[RequiresUnreferencedCode("This method uses reflection which may not be compatible with trimming.")]
public static void AreEqual(TestContext? testContext, Element element, string scenarioSubname = "")
{
var pipelinePlatform = Environment.GetEnvironmentVariable("platform");
// Perform visual validation only in the pipeline
if (string.IsNullOrEmpty(pipelinePlatform))
{
Console.WriteLine("Skip visual validation in the local run.");
return;
}
if (element == null)
{
Assert.Fail("Element object is null or invalid");
}
var stackTrace = new StackTrace();
var callerFrame = stackTrace.GetFrame(1);
var callerMethod = callerFrame?.GetMethod();
var callerName = callerMethod?.Name;
var callerClassName = callerMethod?.DeclaringType?.Name;
if (string.IsNullOrEmpty(callerName) || string.IsNullOrEmpty(callerClassName))
{
Assert.Fail("Unable to determine the caller method and class name.");
}
if (string.IsNullOrWhiteSpace(scenarioSubname))
{
scenarioSubname = string.Join("_", callerClassName, callerName, pipelinePlatform);
}
else
{
scenarioSubname = string.Join("_", callerClassName, callerName, scenarioSubname.Trim(), pipelinePlatform);
}
var baselineImageResourceName = callerMethod!.DeclaringType!.Assembly.GetManifestResourceNames().Where(name => name.Contains(scenarioSubname)).FirstOrDefault();
var tempTestImagePath = GetTempFilePath(scenarioSubname, "test", ".png");
element.SaveToPngFile(tempTestImagePath);
if (string.IsNullOrEmpty(baselineImageResourceName)
|| !Path.GetFileNameWithoutExtension(baselineImageResourceName).EndsWith(scenarioSubname))
{
testContext?.AddResultFile(tempTestImagePath);
Assert.Fail($"Baseline image for scenario {scenarioSubname} can not be found, test image saved in file://{tempTestImagePath.Replace('\\', '/')}");
}
var tempBaselineImagePath = GetTempFilePath(scenarioSubname, "baseline", Path.GetExtension(baselineImageResourceName));
bool isSame = false;
using (var stream = callerMethod!.DeclaringType!.Assembly.GetManifestResourceStream(baselineImageResourceName))
{
if (stream == null)
{
Assert.Fail($"Resource stream '{baselineImageResourceName}' is null.");
}
using (var baselineImage = new Bitmap(stream))
{
using (var testImage = new Bitmap(tempTestImagePath))
{
isSame = VisualAssert.AreEqual(baselineImage, testImage);
if (!isSame)
{
// Copy baseline image to temp folder as well
baselineImage.Save(tempBaselineImagePath);
}
}
}
}
if (!isSame)
{
if (testContext != null)
{
testContext.AddResultFile(tempBaselineImagePath);
testContext.AddResultFile(tempTestImagePath);
}
Assert.Fail($"Fail to validate visual result for scenario {scenarioSubname}, baseline image can be found file://{tempBaselineImagePath.Replace('\\', '/')}, and test image can be found file://{tempTestImagePath.Replace('\\', '/')}");
}
}
/// <summary>
/// Get temp file path
/// </summary>
/// <param name="scenario">scenario name</param>
/// <param name="imageType">baseline or test image</param>
/// <param name="extension">image file extension</param>
/// <returns>full temp file path</returns>
private static string GetTempFilePath(string scenario, string imageType, string extension)
{
var tempFileFullName = $"{scenario}_{imageType}{extension}";
// Remove invalid filename character if any
Path.GetInvalidFileNameChars().ToList().ForEach(c => tempFileFullName = tempFileFullName.Replace(c, '-'));
return Path.Combine(Path.GetTempPath(), tempFileFullName);
}
/// <summary>
/// Test if two images are equal bit-by-bit
/// </summary>
/// <param name="baselineImage">baseline image</param>
/// <param name="testImage">test image</param>
/// <returns>true if are equal,otherwise false</returns>
private static bool AreEqual(Bitmap baselineImage, Bitmap testImage)
{
if (baselineImage.Width != testImage.Width || baselineImage.Height != testImage.Height)
{
return false;
}
// WinAppDriver sometimes adds a border to the screenshot (around 2 pix width), and it is not always consistent.
// So we exclude the border when comparing the images, and usually it is the edge of the windows, won't affect the comparison.
int excludeBorderWidth = 5, excludeBorderHeight = 5;
for (int x = excludeBorderWidth; x < baselineImage.Width - excludeBorderWidth; x++)
{
for (int y = excludeBorderHeight; y < baselineImage.Height - excludeBorderHeight; y++)
{
if (!VisualHelper.PixIsSame(baselineImage.GetPixel(x, y), testImage.GetPixel(x, y)))
{
return false;
}
}
}
return true;
}
}
}

View File

@@ -0,0 +1,170 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.PowerToys.UITest
{
internal static class VisualHelper
{
#pragma warning disable SA1307
[StructLayout(LayoutKind.Sequential)]
private struct IMMERSIVE_COLOR_PREFERENCE
{
public uint dwColorSetIndex;
public uint crStartColor;
public uint crAccentColor;
}
#pragma warning restore SA1307
[DllImport("uxtheme.dll", EntryPoint = "#120")]
private static extern IntPtr GetUserColorPreference(ref IMMERSIVE_COLOR_PREFERENCE pcpPreference, bool fForceReload);
/// <summary>
/// Gets the system accent color.
/// </summary>
/// <returns>The system accent color as a Color object.</returns>
private static Color GetSystemAccentColor()
{
IMMERSIVE_COLOR_PREFERENCE colorPreference = default(IMMERSIVE_COLOR_PREFERENCE);
GetUserColorPreference(ref colorPreference, true);
return ToColor(colorPreference.crStartColor);
}
/// <summary>
/// Converts a color value to a Color object.
/// </summary>
/// <param name="c">The color value.</param>
/// <returns>The Color object.</returns>
private static Color ToColor(uint c)
{
int r = (int)(c & 0xFF) % 256;
int g = (int)((c >> 8) & 0xFF) % 256;
int b = (int)(c >> 16) % 256;
return Color.FromArgb(r, g, b);
}
/// <summary>
/// Gets HSL values from a Color object.
/// </summary>
/// <param name="color">The Color object.</param>
/// <returns>A tuple containing the HSL values.</returns>
private static (double H, double S, double L) GetHSL(Color color)
{
double rNorm = color.R / 255.0;
double gNorm = color.G / 255.0;
double bNorm = color.B / 255.0;
double max = Math.Max(rNorm, Math.Max(gNorm, bNorm));
double min = Math.Min(rNorm, Math.Min(gNorm, bNorm));
double h = 0, s = 0, l = (max + min) / 2;
if (max != min)
{
double delta = max - min;
s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min);
if (max == rNorm)
{
h = ((gNorm - bNorm) / delta) + (gNorm < bNorm ? 6 : 0);
}
else if (max == gNorm)
{
h = ((bNorm - rNorm) / delta) + 2;
}
else if (max == bNorm)
{
h = ((rNorm - gNorm) / delta) + 4;
}
h /= 6;
}
return (h * 360, s * 100, l * 100);
}
/// <summary>
/// Makes a specific color in an image transparent.
/// </summary>
/// <param name="imagePath">The path to the image file.</param>
/// <param name="outputPath">The path to save the output image file.</param>
/// <param name="targetColor">The target color to make transparent.</param>
/// <param name="fuzz">The fuzz factor for color comparison, default is 2.</param>
private static void MakeColorTransparent(string imagePath, string outputPath, Color targetColor, int fuzz = 2)
{
var hsl = GetHSL(targetColor);
// Assert.IsNotNull(null, $"Target Color - H: {hsl.H}, S: {hsl.S}, L: {hsl.L}");
using (Bitmap originalBitmap = new Bitmap(imagePath))
{
using (Bitmap bitmap = new Bitmap(originalBitmap))
{
for (int y = 0; y < bitmap.Height; y++)
{
for (int x = 0; x < bitmap.Width; x++)
{
Color pixelColor = bitmap.GetPixel(x, y);
if (HueIsSame(pixelColor, targetColor, fuzz))
{
bitmap.SetPixel(x, y, Color.Transparent);
}
}
}
bitmap.Save(outputPath, ImageFormat.Png);
}
}
}
/// <summary>
/// Erases the user preference color from an image. Will overwrite this image.
/// </summary>
/// <param name="imagePath">The path to the image file.</param>
/// <param name="fuzz">The fuzz factor for color comparison, default is 2.</param>
public static void EraseUserPreferenceColor(string imagePath, int fuzz = 2)
{
Color systemColor = GetSystemAccentColor();
string tempPath = Path.GetTempFileName();
MakeColorTransparent(imagePath, tempPath, systemColor, fuzz);
File.Delete(imagePath);
File.Move(tempPath, imagePath);
}
/// <summary>
/// Compare two pixels with a fuzz factor
/// </summary>
/// <param name="c1">base color</param>
/// <param name="c2">test color</param>
/// <param name="fuzz">fuzz factor, default is 10</param>
/// <returns>true if same, otherwise is false</returns>
public static bool PixIsSame(Color c1, Color c2, int fuzz = 10)
{
return Math.Abs(c1.A - c2.A) <= fuzz && Math.Abs(c1.R - c2.R) <= fuzz && Math.Abs(c1.G - c2.G) <= fuzz && Math.Abs(c1.B - c2.B) <= fuzz;
}
/// <summary>
/// Compares the hue of two colors with a fuzz factor.
/// </summary>
/// <param name="c1">The first color.</param>
/// <param name="c2">The second color.</param>
/// <param name="fuzz">The fuzz factor, default is 2.</param>
/// <returns>True if the hues are the same, otherwise false.</returns>
public static bool HueIsSame(Color c1, Color c2, int fuzz = 2)
{
var h1 = GetHSL(c1).H;
var h2 = GetHSL(c2).H;
return Math.Abs(h1 - h2) <= fuzz;
}
}
}

View File

@@ -2,11 +2,14 @@
#include <Windows.h>
#include <appxpackaging.h>
#include <exception>
#include <filesystem>
#include <regex>
#include <string>
#include <optional>
#include <Shlwapi.h>
#include <wrl/client.h>
#include <winrt/Windows.ApplicationModel.h>
#include <winrt/Windows.Foundation.h>
@@ -15,11 +18,12 @@
#include "../logger/logger.h"
#include "../version/version.h"
namespace package {
namespace package
{
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::ApplicationModel;
using namespace winrt::Windows::Management::Deployment;
using Microsoft::WRL::ComPtr;
inline BOOL IsWin11OrGreater()
{
@@ -46,6 +50,118 @@ namespace package {
dwlConditionMask);
}
struct PACKAGE_VERSION
{
UINT16 Major;
UINT16 Minor;
UINT16 Build;
UINT16 Revision;
};
class ComInitializer
{
public:
explicit ComInitializer(DWORD coInitFlags = COINIT_MULTITHREADED) :
_initialized(false)
{
const HRESULT hr = CoInitializeEx(nullptr, coInitFlags);
_initialized = SUCCEEDED(hr);
}
~ComInitializer()
{
if (_initialized)
{
CoUninitialize();
}
}
bool Succeeded() const { return _initialized; }
private:
bool _initialized;
};
inline bool GetPackageNameAndVersionFromAppx(
const std::wstring& appxPath,
std::wstring& outName,
PACKAGE_VERSION& outVersion)
{
try
{
ComInitializer comInit;
if (!comInit.Succeeded())
{
Logger::error(L"COM initialization failed.");
return false;
}
ComPtr<IAppxFactory> factory;
ComPtr<IStream> stream;
ComPtr<IAppxPackageReader> reader;
ComPtr<IAppxManifestReader> manifest;
ComPtr<IAppxManifestPackageId> packageId;
HRESULT hr = CoCreateInstance(__uuidof(AppxFactory), nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&factory));
if (FAILED(hr))
return false;
hr = SHCreateStreamOnFileEx(appxPath.c_str(), STGM_READ | STGM_SHARE_DENY_WRITE, FILE_ATTRIBUTE_NORMAL, FALSE, nullptr, &stream);
if (FAILED(hr))
return false;
hr = factory->CreatePackageReader(stream.Get(), &reader);
if (FAILED(hr))
return false;
hr = reader->GetManifest(&manifest);
if (FAILED(hr))
return false;
hr = manifest->GetPackageId(&packageId);
if (FAILED(hr))
return false;
LPWSTR name = nullptr;
hr = packageId->GetName(&name);
if (FAILED(hr))
return false;
UINT64 version = 0;
hr = packageId->GetVersion(&version);
if (FAILED(hr))
return false;
outName = std::wstring(name);
CoTaskMemFree(name);
outVersion.Major = static_cast<UINT16>((version >> 48) & 0xFFFF);
outVersion.Minor = static_cast<UINT16>((version >> 32) & 0xFFFF);
outVersion.Build = static_cast<UINT16>((version >> 16) & 0xFFFF);
outVersion.Revision = static_cast<UINT16>(version & 0xFFFF);
Logger::info(L"Package name: {}, version: {}.{}.{}.{}, appxPath: {}",
outName,
outVersion.Major,
outVersion.Minor,
outVersion.Build,
outVersion.Revision,
appxPath);
return true;
}
catch (const std::exception& ex)
{
Logger::error(L"Standard exception: {}", winrt::to_hstring(ex.what()));
return false;
}
catch (...)
{
Logger::error(L"Unknown or non-standard exception occurred.");
return false;
}
}
inline std::optional<Package> GetRegisteredPackage(std::wstring packageDisplayName, bool checkVersion)
{
PackageManager packageManager;
@@ -229,6 +345,59 @@ namespace package {
return matchedFiles;
}
inline bool IsPackageSatisfied(const std::wstring& appxPath)
{
std::wstring targetName;
PACKAGE_VERSION targetVersion{};
if (!GetPackageNameAndVersionFromAppx(appxPath, targetName, targetVersion))
{
Logger::error(L"Failed to get package name and version from appx: " + appxPath);
return false;
}
PackageManager pm;
for (const auto& package : pm.FindPackagesForUser({}))
{
const auto& id = package.Id();
if (std::wstring(id.Name()) == targetName)
{
const auto& version = id.Version();
if (version.Major > targetVersion.Major ||
(version.Major == targetVersion.Major && version.Minor > targetVersion.Minor) ||
(version.Major == targetVersion.Major && version.Minor == targetVersion.Minor && version.Build > targetVersion.Build) ||
(version.Major == targetVersion.Major && version.Minor == targetVersion.Minor && version.Build == targetVersion.Build && version.Revision >= targetVersion.Revision))
{
Logger::info(
L"Package {} is already satisfied with version {}.{}.{}.{}; target version {}.{}.{}.{}; appxPath: {}",
id.Name(),
version.Major,
version.Minor,
version.Build,
version.Revision,
targetVersion.Major,
targetVersion.Minor,
targetVersion.Build,
targetVersion.Revision,
appxPath);
return true;
}
}
}
Logger::info(
L"Package {} is not satisfied. Target version: {}.{}.{}.{}; appxPath: {}",
targetName,
targetVersion.Major,
targetVersion.Minor,
targetVersion.Build,
targetVersion.Revision,
appxPath);
return false;
}
inline bool RegisterPackage(std::wstring pkgPath, std::vector<std::wstring> dependencies)
{
try
@@ -238,7 +407,7 @@ namespace package {
PackageManager packageManager;
// Declare use of an external location
DeploymentOptions options = DeploymentOptions::ForceApplicationShutdown;
DeploymentOptions options = DeploymentOptions::ForceTargetApplicationShutdown;
Collections::IVector<Uri> uris = winrt::single_threaded_vector<Uri>();
if (!dependencies.empty())
@@ -247,7 +416,14 @@ namespace package {
{
try
{
uris.Append(Uri(dependency));
if (IsPackageSatisfied(dependency))
{
Logger::info(L"Dependency already satisfied: {}", dependency);
}
else
{
uris.Append(Uri(dependency));
}
}
catch (const winrt::hresult_error& ex)
{
@@ -282,7 +458,6 @@ namespace package {
{
Logger::debug(L"Register {} package started.", pkgPath);
}
}
catch (std::exception& e)
{
@@ -293,4 +468,4 @@ namespace package {
return true;
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@@ -13,7 +13,7 @@ namespace Hosts.UITests
public class HostModuleTests : UITestBase
{
public HostModuleTests()
: base(PowerToysModule.Hosts)
: base(PowerToysModule.Hosts, WindowSize.Small_Vertical)
{
}
@@ -31,14 +31,17 @@ namespace Hosts.UITests
/// </item>
/// </list>
/// </summary>
[TestMethod]
[TestMethod("Hosts.Basic.EmptyViewShouldWork")]
[TestCategory("Hosts File Editor #4")]
public void TestEmptyView()
{
this.CloseWarningDialog();
this.RemoveAllEntries();
// 'Add an entry' button (only show-up when list is empty) should be visible
Assert.IsTrue(this.FindAll<HyperlinkButton>("Add an entry").Count == 1, "'Add an entry' button should be visible in the empty view");
Assert.IsTrue(this.HasOne<HyperlinkButton>("Add an entry"), "'Add an entry' button should be visible in the empty view");
VisualAssert.AreEqual(this.TestContext, this.Find("Entries"), "EmptyView");
// Click 'Add an entry' from empty-view for adding Host override rule
this.Find<HyperlinkButton>("Add an entry").Click();
@@ -46,8 +49,10 @@ namespace Hosts.UITests
this.AddEntry("192.168.0.1", "localhost", false, false);
// Should have one row now and not more empty view
Assert.IsTrue(this.FindAll<Button>("Delete").Count == 1, "Should have one row now");
Assert.IsTrue(this.FindAll<HyperlinkButton>("Add an entry").Count == 0, "'Add an entry' button should be invisible if not empty view");
Assert.IsTrue(this.Has<Button>("Delete"), "Should have one row now");
Assert.IsFalse(this.Has<HyperlinkButton>("Add an entry"), "'Add an entry' button should be invisible if not empty view");
VisualAssert.AreEqual(this.TestContext, this.Find("Entries"), "NonEmptyView");
}
/// <summary>
@@ -58,17 +63,20 @@ namespace Hosts.UITests
/// </item>
/// </list>
/// </summary>
[TestMethod]
[TestMethod("Hosts.Basic.AddEntryButtonShouldWork")]
[TestCategory("Hosts File Editor #4")]
public void TestAddingEntry()
{
this.CloseWarningDialog();
this.RemoveAllEntries();
Assert.IsTrue(this.FindAll<Button>("Delete").Count == 0, "Should have no row after removing all");
Assert.IsFalse(this.Has<Button>("Delete"), "Should have no row after removing all");
this.AddEntry("192.168.0.1", "localhost", true);
Assert.IsTrue(this.FindAll<Button>("Delete").Count == 1, "Should have one row now");
Assert.IsTrue(this.Has<Button>("Delete"), "Should have one row now");
VisualAssert.AreEqual(this.TestContext, this.Find("Entries"));
}
/// <summary>
@@ -82,7 +90,8 @@ namespace Hosts.UITests
/// </item>
/// </list>
/// </summary>
[TestMethod]
[TestMethod("Hosts.Basic.CanNotAddMoreThenNighHosts")]
[TestCategory("Hosts File Editor #5")]
public void TestTooManyHosts()
{
this.CloseWarningDialog();
@@ -116,18 +125,48 @@ namespace Hosts.UITests
/// </item>
/// </list>
/// </summary>
[TestMethod]
[TestMethod("Hosts.Basic.ErrorMessgeShowupIfNotRunAsAdmin")]
[TestCategory("Hosts File Editor #8")]
public void TestErrorMessageWithNonAdminPermission()
{
this.CloseWarningDialog();
this.RemoveAllEntries();
if (this.Session.IsElevated == false)
{
this.CloseWarningDialog();
this.RemoveAllEntries();
// Add new URL override and a warning tip should be shown
this.AddEntry("192.168.0.1", "localhost", true);
// Add new URL override and a warning tip should be shown
this.AddEntry("192.168.0.1", "localhost", true);
Assert.IsTrue(
this.FindAll<TextBlock>("The hosts file cannot be saved because the program isn't running as administrator.").Count == 1,
"Should display host-file saving error if not run as administrator");
Assert.IsTrue(
this.FindAll<TextBlock>("The hosts file cannot be saved because the program isn't running as administrator.").Count == 1,
"Should display host-file saving error if not run as administrator");
}
}
/// <summary>
/// Test No Error-message in the Hosts-File-Editor
/// <list type="bullet">
/// <item>
/// <description>Validating error message should be shown if not run as admin.</description>
/// </item>
/// </list>
/// </summary>
[TestMethod("Hosts.Basic.NoErrorMessgeShowupIfRunAsAdmin")]
[TestCategory("Hosts File Editor #8")]
public void TestNoErrorMessageWithNonAdminPermission()
{
if (this.Session.IsElevated == true)
{
this.CloseWarningDialog();
this.RemoveAllEntries();
// Add new URL override and a warning tip should be shown
this.AddEntry("192.168.0.1", "localhost", true);
Assert.IsFalse(
this.FindAll<TextBlock>("The hosts file cannot be saved because the program isn't running as administrator.").Count > 0,
"Should display host-file saving error if not run as administrator");
}
}
/// <summary>
@@ -144,7 +183,8 @@ namespace Hosts.UITests
/// </item>
/// </list>
/// </summary>
[TestMethod]
[TestMethod("Hosts.Basic.FiltersControlShouldWork")]
[TestCategory("Hosts File Editor #6")]
public void TestFilterControl()
{
this.CloseWarningDialog();
@@ -212,7 +252,7 @@ namespace Hosts.UITests
// Close-filter-panel
this.Find<Button>("Filters").Click();
Assert.IsFalse(this.FindAll<Button>("Clear filters").Count == 1, "Filter panel should be closed afer click Filter Button");
Assert.IsFalse(this.FindAll<Button>("Clear filters").Count == 1, "Filter panel should be closed after clicking Filter Button");
}
private void AddEntry(string ip, string host, bool active = true, bool clickAddEntryButton = true)

View File

@@ -17,6 +17,14 @@
<PropertyGroup>
<OutputPath>$(SolutionDir)$(Platform)\$(Configuration)\tests\Hosts.UITests\</OutputPath>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="Baseline\HostModuleTests_TestAddingEntry_arm64.png" />
<EmbeddedResource Include="Baseline\HostModuleTests_TestEmptyView_EmptyView_arm64.png" />
<EmbeddedResource Include="Baseline\HostModuleTests_TestEmptyView_NonEmptyView_arm64.png" />
<EmbeddedResource Include="Baseline\HostModuleTests_TestAddingEntry_x64.png" />
<EmbeddedResource Include="Baseline\HostModuleTests_TestEmptyView_EmptyView_x64.png" />
<EmbeddedResource Include="Baseline\HostModuleTests_TestEmptyView_NonEmptyView_x64.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MSTest" />

View File

@@ -12,6 +12,11 @@ namespace Hosts.UITests
[TestClass]
public class HostsSettingTests : UITestBase
{
public HostsSettingTests()
: base(PowerToysModule.PowerToysSettings, WindowSize.Medium)
{
}
/// <summary>
/// Test Warning Dialog at startup
/// <list type="bullet">
@@ -29,7 +34,9 @@ namespace Hosts.UITests
/// </item>
/// </list>
/// </summary>
[TestMethod]
[TestMethod("Hosts.Settings.ShowWarningDialogIfRunAsAdmin")]
[TestCategory("Hosts File Editor #1")]
[TestCategory("Hosts File Editor #9")]
public void TestWarningDialog()
{
this.LaunchFromSetting(showWarning: true);
@@ -54,7 +61,7 @@ namespace Hosts.UITests
// wait for 500 ms to make sure Hosts File Editor is launched
Task.Delay(500).Wait();
this.Session.Attach(PowerToysModule.Hosts);
this.Session.Attach(PowerToysModule.Hosts, WindowSize.Small_Vertical);
// Should show warning dialog
Assert.IsTrue(this.FindAll("Warning").Count > 0, "Should show warning dialog");
@@ -68,7 +75,7 @@ namespace Hosts.UITests
Assert.IsFalse(this.IsHostsFileEditorClosed(), "Hosts File Editor should NOT be closed after click Accept button in Warning Dialog");
// Close Hosts File Editor window
this.Session.Find<Window>("Hosts File Editor").Close();
this.Session.CloseMainWindow();
// Restore back to PowerToysSettings Session
this.Session.Attach(PowerToysModule.PowerToysSettings);
@@ -82,7 +89,7 @@ namespace Hosts.UITests
Assert.IsFalse(this.IsHostsFileEditorClosed(), "Hosts File Editor should NOT be closed");
// Close Hosts File Editor window
this.Session.Find<Window>("Hosts File Editor").Close();
this.Session.CloseMainWindow();
// Restore back to PowerToysSettings Session
this.Session.Attach(PowerToysModule.PowerToysSettings);

View File

@@ -0,0 +1,558 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.PowerToys.UITest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Windows.Devices.Printers;
namespace MouseUtils.UITests
{
[TestClass]
public class FindMyMouseTests : UITestBase
{
/// <summary>
/// Test Warning Dialog at startup
/// <list type="bullet">
/// <item>
/// <description>Validating Warning-Dialog will be shown if 'Show a warning at startup' toggle is On.</description>
/// </item>
/// <item>
/// <description>Validating Warning-Dialog will NOT be shown if 'Show a warning at startup' toggle is Off.</description>
/// </item>
/// <item>
/// <description>Validating click 'Quit' button in Warning-Dialog, the Hosts File Editor window would be closed.</description>
/// </item>
/// <item>
/// <description>Validating click 'Accept' button in Warning-Dialog, the Hosts File Editor window would NOT be closed.</description>
/// </item>
/// </list>
/// </summary>
[TestMethod]
public void TestEnableFindMyMouse()
{
LaunchFromSetting();
var settings = new FindMyMouseSettings();
settings.OverlayOpacity = "100";
settings.Radius = "50";
settings.InitialZoom = "1";
settings.AnimationDuration = "0";
settings.BackgroundColor = "000000";
settings.SpotlightColor = "FFFFFF";
var foundCustom = this.Find<Custom>("Find My Mouse");
Assert.IsNotNull(foundCustom);
if (CheckAnimationEnable(ref foundCustom))
{
foundCustom = this.Find<Custom>("Find My Mouse");
}
if (foundCustom != null)
{
foundCustom.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(true);
// foundCustom.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(false);
SetFindMyMouseActivationMethod(ref foundCustom, "Press Left Control twice");
Assert.IsNotNull(foundCustom, "Find My Mouse group not found.");
SetFindMyMouseAppearanceBehavior(ref foundCustom, ref settings);
var excludedApps = foundCustom.Find<TextBlock>("Excluded apps");
if (excludedApps != null)
{
excludedApps.Click();
excludedApps.Click();
}
else
{
Assert.Fail("Activation method group not found.");
}
}
else
{
Assert.Fail("Find My Mouse group not found.");
}
// [Test Case]Enable FindMyMouse. Then, without moving your mouse: Press Left Ctrl twice and verify the overlay appears.
VerifySpotlightSettings(ref settings);
// [Test Case]Enable FindMyMouse. Then, without moving your mouse: Press any other key and verify the overlay disappears.
Session.SendKeys(Key.A);
VerifySpotlightDisappears(ref settings);
// [Test Case]Enable FindMyMouse. Then, without moving your mouse: Press Left Ctrl twice and verify the overlay appears.
VerifySpotlightSettings(ref settings);
// [Test Case]Enable FindMyMouse. Then, without moving your mouse: Press a mouse button and verify the overlay disappears.
Task.Delay(1000).Wait();
// MouseSimulator.LeftClick();
Session.PerformMouseAction(MouseActionType.LeftClick, 500, 1000);
VerifySpotlightDisappears(ref settings);
}
[TestMethod]
public void TestEnableFindMyMouse2()
{
LaunchFromSetting();
var settings = new FindMyMouseSettings();
settings.OverlayOpacity = "100";
settings.Radius = "80";
settings.InitialZoom = "1";
settings.AnimationDuration = "0";
settings.BackgroundColor = "FFFFFF";
settings.SpotlightColor = "000000";
var foundCustom = this.Find<Custom>("Find My Mouse");
Assert.IsNotNull(foundCustom);
if (CheckAnimationEnable(ref foundCustom))
{
foundCustom = this.Find<Custom>("Find My Mouse");
}
if (foundCustom != null)
{
foundCustom.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(true);
// foundCustom.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(false);
SetFindMyMouseActivationMethod(ref foundCustom, "Press Left Control twice");
Assert.IsNotNull(foundCustom, "Find My Mouse group not found.");
SetFindMyMouseAppearanceBehavior(ref foundCustom, ref settings);
var excludedApps = foundCustom.Find<TextBlock>("Excluded apps");
if (excludedApps != null)
{
excludedApps.Click();
excludedApps.Click();
}
else
{
Assert.Fail("Excluded apps group not found.");
}
}
else
{
Assert.Fail("Find My Mouse group not found.");
}
// [Test Case]Test the different settings and verify they apply, Background color
// [Test Case]Test the different settings and verify they apply, Spotlight color
// [Test Case]Test the different settings and verify they apply, Spotlight radius
VerifySpotlightSettings(ref settings);
// [Test Case]Enable FindMyMouse. Then, without moving your mouse: Press any other key and verify the overlay disappears.
Session.SendKeys(Key.A);
VerifySpotlightDisappears(ref settings);
}
[TestMethod]
public void TestDisableFindMyMouse()
{
LaunchFromSetting();
var settings = new FindMyMouseSettings();
settings.OverlayOpacity = "100";
settings.Radius = "50";
settings.InitialZoom = "1";
settings.AnimationDuration = "0";
settings.BackgroundColor = "000000";
settings.SpotlightColor = "FFFFFF";
var foundCustom = this.Find<Custom>("Find My Mouse");
Assert.IsNotNull(foundCustom);
if (CheckAnimationEnable(ref foundCustom))
{
foundCustom = this.Find<Custom>("Find My Mouse");
}
if (foundCustom != null)
{
foundCustom.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(true);
// foundCustom.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(false);
SetFindMyMouseActivationMethod(ref foundCustom, "Press Left Control twice");
Assert.IsNotNull(foundCustom);
SetFindMyMouseAppearanceBehavior(ref foundCustom, ref settings);
var excludedApps = foundCustom.Find<TextBlock>("Excluded apps");
if (excludedApps != null)
{
excludedApps.Click();
excludedApps.Click();
}
else
{
Assert.Fail("Activation method group not found.");
}
}
else
{
Assert.Fail("Find My Mouse group not found.");
}
// [Test Case]Enable FindMyMouse. Then, without moving your mouse: Press Left Ctrl twice and verify the overlay appears.
// VerifySpotlightSettings(ref settings);
ActivateSpotlight(ref settings);
VerifySpotlightAppears(ref settings);
// [Test Case] Disable FindMyMouse. Verify the overlay no longer appears when you press Left Ctrl twice
foundCustom.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(false);
Task.Delay(1000).Wait();
ActivateSpotlight(ref settings);
VerifySpotlightDisappears(ref settings);
// [Test Case] Press Left Ctrl twice and verify the overlay appears
foundCustom.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(true);
ActivateSpotlight(ref settings);
VerifySpotlightAppears(ref settings);
Session.PerformMouseAction(MouseActionType.LeftClick);
}
[TestMethod]
public void TestDisableFindMyMouse2()
{
LaunchFromSetting();
var settings = new FindMyMouseSettings();
settings.OverlayOpacity = "100";
settings.Radius = "50";
settings.InitialZoom = "1";
settings.AnimationDuration = "0";
settings.BackgroundColor = "000000";
settings.SpotlightColor = "FFFFFF";
var foundCustom = this.Find<Custom>("Find My Mouse");
if (foundCustom != null)
{
foundCustom.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(true);
// foundCustom.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(false);
SetFindMyMouseActivationMethod(ref foundCustom, "Press Left Control twice");
Assert.IsNotNull(foundCustom, "Find My Mouse group not found.");
// SetFindMyMouseAppearanceBehavior(ref foundCustom, ref settings);
var excludedApps = foundCustom.Find<TextBlock>("Excluded apps");
if (excludedApps != null)
{
excludedApps.Click();
excludedApps.Click();
}
else
{
Assert.Fail("Activation method group not found.");
}
}
else
{
Assert.Fail("Find My Mouse group not found.");
}
// [Test Case]Enable FindMyMouse. Then, without moving your mouse: Press Left Ctrl twice and verify the overlay appears.
// VerifySpotlightSettings(ref settings);
// [Test Case] Disable FindMyMouse. Verify the overlay no longer appears when you press Left Ctrl twice
foundCustom.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(false);
Task.Delay(2000).Wait();
Session.SendKey(Key.LCtrl, 0, 0);
Task.Delay(100).Wait();
Session.SendKey(Key.LCtrl, 0, 0);
VerifySpotlightDisappears(ref settings);
}
private void VerifySpotlightDisappears(ref FindMyMouseSettings settings)
{
Task.Delay(2000).Wait();
var location = Session.GetMousePosition();
int radius = int.Parse(settings.Radius, CultureInfo.InvariantCulture);
var colorSpotlight = Session.GetPixelColorString(location.Item1, location.Item2);
Assert.AreNotEqual("#" + settings.SpotlightColor, colorSpotlight);
var colorBackground = Session.GetPixelColorString(location.Item1 + radius + 50, location.Item2 + radius + 50);
Assert.AreNotEqual("#" + settings.BackgroundColor, colorBackground);
var colorBackground2 = Session.GetPixelColorString(location.Item1 + radius + 100, location.Item2 + radius + 100);
Assert.AreNotEqual("#" + settings.BackgroundColor, colorBackground2);
}
private void VerifySpotlightAppears(ref FindMyMouseSettings settings)
{
Task.Delay(2000).Wait();
var location = Session.GetMousePosition();
int radius = int.Parse(settings.Radius, CultureInfo.InvariantCulture);
var colorSpotlight = Session.GetPixelColorString(location.Item1, location.Item2);
Assert.AreEqual("#" + settings.SpotlightColor, colorSpotlight);
var colorSpotlight2 = Session.GetPixelColorString(location.Item1 + radius - 1, location.Item2);
// Session.MoveMouseTo(location.Item1 + radius - 10, location.Item2);
Assert.AreEqual("#" + settings.SpotlightColor, colorSpotlight2);
Task.Delay(100).Wait();
var colorBackground = Session.GetPixelColorString(location.Item1 + radius + 50, location.Item2 + radius + 50);
Assert.AreEqual("#" + settings.BackgroundColor, colorBackground);
var colorBackground2 = Session.GetPixelColorString(location.Item1 + radius + 100, location.Item2 + radius + 100);
Assert.AreEqual("#" + settings.BackgroundColor, colorBackground2);
}
private void ActivateSpotlight(ref FindMyMouseSettings settings)
{
var xy = Session.GetMousePosition();
Session.MoveMouseTo(xy.Item1 - 200, xy.Item2 - 100);
Task.Delay(1000).Wait();
Session.PerformMouseAction(MouseActionType.LeftClick);
Task.Delay(5000).Wait();
if (settings.SelectedActivationMethod == FindMyMouseSettings.ActivationMethod.PressLeftControlTwice)
{
Session.SendKey(Key.LCtrl, 0, 0);
Task.Delay(100).Wait();
Session.SendKey(Key.LCtrl, 0, 0);
}
else if (settings.SelectedActivationMethod == FindMyMouseSettings.ActivationMethod.PressRightControlTwice)
{
Session.SendKey(Key.RCtrl, 0, 0);
Task.Delay(100).Wait();
Session.SendKey(Key.RCtrl, 0, 0);
}
else if (settings.SelectedActivationMethod == FindMyMouseSettings.ActivationMethod.ShakeMouse)
{
// Simulate shake mouse;
}
else if (settings.SelectedActivationMethod == FindMyMouseSettings.ActivationMethod.CustomShortcut)
{
// Simulate custom shortcut
}
}
private void VerifySpotlightSettings(ref FindMyMouseSettings settings, bool equal = true)
{
ActivateSpotlight(ref settings);
VerifySpotlightAppears(ref settings);
}
private void SetFindMyMouseActivationMethod(ref Custom? foundCustom, string method)
{
Assert.IsNotNull(foundCustom);
var groupActivation = foundCustom.Find<TextBlock>("Activation method");
if (groupActivation != null)
{
groupActivation.Click();
string findMyMouseComboBoxKey = "Activation method";
var foundElements = foundCustom.FindAll<ComboBox>(findMyMouseComboBoxKey);
if (foundElements.Count != 0)
{
var myMouseComboBox = foundCustom.Find<ComboBox>(findMyMouseComboBoxKey);
Assert.IsNotNull(myMouseComboBox);
myMouseComboBox.Click();
var selectedItem = myMouseComboBox.Find<NavigationViewItem>(method);
Assert.IsNotNull(selectedItem);
selectedItem.Click();
}
else
{
Assert.IsTrue(false, "ComboBox is not found in the setting page.");
}
}
else
{
Assert.Fail("Activation method group not found.");
}
}
private void SetFindMyMouseAppearanceBehavior(ref Custom foundCustom, ref FindMyMouseSettings settings)
{
Assert.IsNotNull(foundCustom);
var groupAppearanceBehavior = foundCustom.Find<TextBlock>("Appearance & behavior");
if (groupAppearanceBehavior != null)
{
// groupAppearanceBehavior.Click();
if (foundCustom.FindAll<Slider>("Overlay opacity (%)").Count == 0)
{
groupAppearanceBehavior.Click();
}
// Set the BackGround color
var backgroundColor = foundCustom.Find<Group>("Background color");
Assert.IsNotNull(backgroundColor);
var button = backgroundColor.Find<Button>(By.XPath(".//Button"));
Assert.IsNotNull(button);
button.Click();
var popupWindow = this.Find<Window>("Popup");
Assert.IsNotNull(popupWindow);
Task.Delay(1000).Wait();
var colorModelComboBox = this.Find<ComboBox>("Color model");
Assert.IsNotNull(colorModelComboBox);
colorModelComboBox.Click();
var selectedItem = colorModelComboBox.Find<NavigationViewItem>("RGB");
selectedItem.Click();
Task.Delay(100).Wait();
var rgbHexEdit = this.Find<TextBox>("RGB hex");
Assert.IsNotNull(rgbHexEdit);
Task.Delay(100).Wait();
rgbHexEdit.SetText(settings.BackgroundColor);
Task.Delay(100).Wait();
button.Click();
// Set the Spotlight color
var spotlightColor = foundCustom.Find<Group>("Spotlight color");
Assert.IsNotNull(spotlightColor);
var spotlightColorButton = spotlightColor.Find<Button>(By.XPath(".//Button"));
Assert.IsNotNull(spotlightColorButton);
spotlightColorButton.Click();
var spotlightColorPopupWindow = Session.Find<Window>("Popup");
Assert.IsNotNull(spotlightColorPopupWindow);
var spotlightColorModelComboBox = this.Find<ComboBox>("Color model");
Assert.IsNotNull(spotlightColorModelComboBox);
spotlightColorModelComboBox.Click();
var selectedItem2 = spotlightColorModelComboBox.Find<NavigationViewItem>("RGB");
Assert.IsNotNull(selectedItem2);
selectedItem2.Click();
Task.Delay(100).Wait();
var rgbHexEdit2 = this.Find<TextBox>("RGB hex");
Assert.IsNotNull(rgbHexEdit2);
Task.Delay(100).Wait();
rgbHexEdit2.SetText(settings.SpotlightColor);
Task.Delay(100).Wait();
spotlightColorButton.Click(false, 500, 1500);
// Set the overlay opacity to overlayOpacity%
var overlayOpacitySlider = foundCustom.Find<Slider>("Overlay opacity (%)");
Assert.IsNotNull(overlayOpacitySlider);
Assert.IsNotNull(settings.OverlayOpacity);
int overlayOpacityValue = int.Parse(settings.OverlayOpacity, CultureInfo.InvariantCulture);
overlayOpacitySlider.QuickSetValue(overlayOpacityValue);
Assert.AreEqual(settings.OverlayOpacity, overlayOpacitySlider.Text);
Task.Delay(1000).Wait();
// Set the Fade Initial zoom to 0
var spotlightInitialZoomSlider = foundCustom.Find<Slider>("Spotlight initial zoom");
Assert.IsNotNull(spotlightInitialZoomSlider);
Task.Delay(1000).Wait();
spotlightInitialZoomSlider.QuickSetValue(int.Parse(settings.InitialZoom, CultureInfo.InvariantCulture));
Assert.AreEqual(settings.InitialZoom, spotlightInitialZoomSlider.Text);
Task.Delay(1000).Wait();
//// Change the edit value
var spotlightRadiusEdit = foundCustom.Find<TextBox>("Spotlight radius (px) Minimum5");
Assert.IsNotNull(spotlightRadiusEdit);
Task.Delay(1000).Wait();
spotlightRadiusEdit.SetText(settings.Radius);
Assert.AreEqual(settings.Radius, spotlightRadiusEdit.Text);
Task.Delay(1000).Wait();
// Set the duration to 0 ms
var spotlightAnimationDuration = foundCustom.Find<TextBox>("Animation duration (ms) Minimum0");
Assert.IsNotNull(spotlightAnimationDuration);
Task.Delay(1000).Wait();
spotlightAnimationDuration.SetText(settings.AnimationDuration);
Assert.AreEqual(settings.AnimationDuration, spotlightAnimationDuration.Text);
Task.Delay(1000).Wait();
// groupAppearanceBehavior.Click();
}
else
{
Assert.Fail("Appearance & behavior group not found.");
}
}
private bool FindGroup(string groupName)
{
try
{
var foundElements = this.FindAll<Element>(groupName);
foreach (var element in foundElements)
{
string className = element.ClassName;
string name = element.Name;
string text = element.Text;
string helptext = element.HelpText;
string controlType = element.ControlType;
}
if (foundElements.Count == 0)
{
return false;
}
}
catch (Exception ex)
{
// Validate if group is not found by checking exception.Message
return ex.Message.Contains("No element found");
}
return true;
}
private bool CheckAnimationEnable(ref Custom? foundCustom)
{
Assert.IsNotNull(foundCustom, "Find My Mouse group not found.");
var foundElements = foundCustom.FindAll<TextBlock>("Animations are disabled in your system settings.");
// Assert.IsNull(animationDisabledWarning);
if (foundElements.Count != 0)
{
var openSettingsLink = foundCustom.Find<Element>("Open settings");
Assert.IsNotNull(openSettingsLink);
openSettingsLink.Click(false, 500, 3000);
string settingsWindow = "Settings";
this.Session.Attach(settingsWindow);
var animationEffects = this.Find<ToggleSwitch>("Animation effects");
Assert.IsNotNull(animationEffects);
animationEffects.Toggle(true);
Task.Delay(2000).Wait();
Session.SendKeys(Key.Alt, Key.F4);
this.Session.Attach(PowerToysModule.PowerToysSettings);
this.LaunchFromSetting(reload: true);
}
else
{
return false;
}
return true;
}
private void LaunchFromSetting(bool reload = false, bool launchAsAdmin = false)
{
// this.Session.Attach(PowerToysModule.PowerToysSettings);
Session.SetMainWindowSize(WindowSize.Large);
// Goto Hosts File Editor setting page
if (this.FindAll<NavigationViewItem>("Mouse utilities", 10000).Count == 0)
{
// Expand Advanced list-group if needed
this.Find<NavigationViewItem>("Input / Output").Click();
}
if (reload)
{
this.Find<NavigationViewItem>("Keyboard Manager").Click();
}
Task.Delay(1000).Wait();
this.Find<NavigationViewItem>("Mouse utilities").Click();
}
}
}

View File

@@ -0,0 +1,382 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.PowerToys.UITest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Windows.Devices.Printers;
namespace MouseUtils.UITests
{
[TestClass]
public class MouseHighlighterTests : UITestBase
{
[TestMethod]
public void TestEnableMouseHighlighter()
{
LaunchFromSetting();
var foundCustom0 = this.Find<Custom>("Find My Mouse");
if (foundCustom0 != null)
{
foundCustom0.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(false);
}
else
{
Assert.Fail("Find My Mouse custom not found.");
}
var settings = new MouseHighlighterSettings();
settings.PrimaryButtonHighlightColor = "FFFF0000";
settings.SecondaryButtonHighlightColor = "FF00FF00";
settings.AlwaysHighlightColor = "004cFF71";
settings.Radius = "50";
settings.FadeDelay = "0";
settings.FadeDuration = "90";
var foundCustom = this.Find<Custom>("Mouse Highlighter");
if (foundCustom != null)
{
foundCustom.Find<ToggleSwitch>("Enable Mouse Highlighter").Toggle(true);
foundCustom.Find<ToggleSwitch>("Enable Mouse Highlighter").Toggle(false);
var xy = Session.GetMousePosition();
Session.MoveMouseTo(xy.Item1, xy.Item2 - 100);
Session.PerformMouseAction(MouseActionType.ScrollDown);
Session.PerformMouseAction(MouseActionType.ScrollDown);
Session.PerformMouseAction(MouseActionType.ScrollDown);
foundCustom.Find<ToggleSwitch>("Enable Mouse Highlighter").Toggle(true);
// Change the shortcut key for MouseHighlighter
// [TestCase]Change activation shortcut and test it
var activationShortcutButton = foundCustom.Find<Button>("Activation shortcut");
Assert.IsNotNull(activationShortcutButton);
activationShortcutButton.Click();
Task.Delay(500).Wait();
var activationShortcutWindow = Session.Find<Window>("Activation shortcut");
Assert.IsNotNull(activationShortcutWindow);
// Invalid shortcut key
Session.SendKeySequence(Key.H);
// IOUtil.SimulateKeyPress(0x41);
var invalidShortcutText = activationShortcutWindow.Find<TextBlock>("Invalid shortcut");
Assert.IsNotNull(invalidShortcutText);
// IOUtil.SimulateShortcut(0x5B, 0x10, 0x45);
Session.SendKeys(Key.Win, Key.Shift, Key.H);
// Assert.IsNull(activationShortcutWindow.Find<TextBlock>("Invalid shortcut"));
var saveButton = activationShortcutWindow.Find<Button>("Save");
Assert.IsNotNull(saveButton);
saveButton.Click(false, 500, 1000);
SetMouseHighlighterAppearanceBehavior(ref foundCustom, ref settings);
var xy0 = Session.GetMousePosition();
Session.MoveMouseTo(xy0.Item1 - 100, xy0.Item2);
Session.PerformMouseAction(MouseActionType.LeftClick);
// Check the mouse highlighter is enabled
Session.SendKeys(Key.Win, Key.Shift, Key.H);
// IOUtil.SimulateShortcut(0x5B, 0x10, 0x45);
Task.Delay(1000).Wait();
// MouseSimulator.LeftClick();
// [Test Case] Press the activation shortcut and press left and right click somewhere, verifying the highlights are applied.
// [Test Case] Press the activation shortcut again and verify no highlights appear when the mouse buttons are clicked.
VerifyMouseHighlighterAppears(ref settings, "leftClick");
VerifyMouseHighlighterAppears(ref settings, "rightClick");
// Disable mouse highlighter
Session.SendKeys(Key.Win, Key.Shift, Key.H);
Task.Delay(1000).Wait();
VerifyMouseHighlighterNotAppears(ref settings, "leftClick");
VerifyMouseHighlighterNotAppears(ref settings, "rightClick");
// [Test Case] Disable Mouse Highlighter and verify that the module is not activated when you press the activation shortcut.
foundCustom.Find<ToggleSwitch>("Enable Mouse Highlighter").Toggle(false);
xy = Session.GetMousePosition();
Session.MoveMouseTo(xy.Item1 - 100, xy.Item2);
Session.SendKeys(Key.Win, Key.Shift, Key.H);
Task.Delay(1000).Wait();
VerifyMouseHighlighterNotAppears(ref settings, "leftClick");
VerifyMouseHighlighterNotAppears(ref settings, "rightClick");
foundCustom.Find<ToggleSwitch>("Enable Mouse Highlighter").Toggle(true);
xy = Session.GetMousePosition();
Session.MoveMouseTo(xy.Item1 - 100, xy.Item2);
Session.SendKeys(Key.Win, Key.Shift, Key.H);
Task.Delay(1000).Wait();
VerifyMouseHighlighterDrag(ref settings, "leftClick");
VerifyMouseHighlighterDrag(ref settings, "rightClick");
}
else
{
Assert.Fail("Mouse Highlighter Custom not found.");
}
Task.Delay(500).Wait();
}
private void VerifyMouseHighlighterDrag(ref MouseHighlighterSettings settings, string action = "leftClick")
{
Task.Delay(500).Wait();
string expectedColor = string.Empty;
if (action == "leftClick")
{
// MouseSimulator.LeftDown();
Session.PerformMouseAction(MouseActionType.LeftDown);
expectedColor = settings.PrimaryButtonHighlightColor.Substring(2);
}
else if (action == "rightClick")
{
// MouseSimulator.RightDown();
Session.PerformMouseAction(MouseActionType.RightDown);
expectedColor = settings.SecondaryButtonHighlightColor.Substring(2);
}
else
{
Assert.Fail("Invalid action specified.");
}
expectedColor = "#" + expectedColor;
var location = Session.GetMousePosition();
int radius = int.Parse(settings.Radius, CultureInfo.InvariantCulture);
var colorLeftClick = Session.GetPixelColorString(location.Item1, location.Item2);
Assert.AreEqual(expectedColor, colorLeftClick);
var colorLeftClick2 = Session.GetPixelColorString(location.Item1 + radius - 1, location.Item2);
Assert.AreEqual(expectedColor, colorLeftClick2);
var colorBackground = Session.GetPixelColorString(location.Item1 + radius + 50, location.Item2 + radius + 50);
Assert.AreNotEqual(expectedColor, colorBackground);
// Drag the mouse
Session.MoveMouseTo(location.Item1 - 200, location.Item2);
Task.Delay(2000).Wait();
location = Session.GetMousePosition();
colorLeftClick = Session.GetPixelColorString(location.Item1, location.Item2);
Assert.AreEqual(expectedColor, colorLeftClick);
colorLeftClick2 = Session.GetPixelColorString(location.Item1 + radius - 1, location.Item2);
Assert.AreEqual(expectedColor, colorLeftClick2);
colorBackground = Session.GetPixelColorString(location.Item1 + radius + 50, location.Item2 + radius + 50);
Assert.AreNotEqual(expectedColor, colorBackground);
if (action == "leftClick")
{
// MouseSimulator.LeftUp();
Session.PerformMouseAction(MouseActionType.LeftUp);
}
else if (action == "rightClick")
{
// MouseSimulator.RightUp();
Session.PerformMouseAction(MouseActionType.RightUp);
}
int duration = int.Parse(settings.FadeDuration, CultureInfo.InvariantCulture);
Task.Delay(duration + 100).Wait();
colorLeftClick = Session.GetPixelColorString(location.Item1, location.Item2);
Assert.AreNotEqual("#" + settings.PrimaryButtonHighlightColor, colorLeftClick);
}
private void VerifyMouseHighlighterNotAppears(ref MouseHighlighterSettings settings, string action = "leftClick")
{
Task.Delay(500).Wait();
string expectedColor = string.Empty;
if (action == "leftClick")
{
// MouseSimulator.LeftDown();
Session.PerformMouseAction(MouseActionType.LeftDown);
expectedColor = settings.PrimaryButtonHighlightColor.Substring(2);
}
else if (action == "rightClick")
{
// MouseSimulator.RightDown();
Session.PerformMouseAction(MouseActionType.RightDown);
expectedColor = settings.SecondaryButtonHighlightColor.Substring(2);
}
else
{
Assert.Fail("Invalid action specified.");
}
expectedColor = "#" + expectedColor;
var location = Session.GetMousePosition();
int radius = int.Parse(settings.Radius, CultureInfo.InvariantCulture);
var colorLeftClick = Session.GetPixelColorString(location.Item1, location.Item2);
Assert.AreNotEqual(expectedColor, colorLeftClick);
var colorLeftClick2 = Session.GetPixelColorString(location.Item1 + radius - 1, location.Item2);
Assert.AreNotEqual(expectedColor, colorLeftClick2);
if (action == "leftClick")
{
Session.PerformMouseAction(MouseActionType.LeftUp);
}
else if (action == "rightClick")
{
Session.PerformMouseAction(MouseActionType.RightUp);
}
}
private void VerifyMouseHighlighterAppears(ref MouseHighlighterSettings settings, string action = "leftClick")
{
Task.Delay(500).Wait();
string expectedColor = string.Empty;
if (action == "leftClick")
{
// MouseSimulator.LeftDown();
Session.PerformMouseAction(MouseActionType.LeftDown);
expectedColor = settings.PrimaryButtonHighlightColor.Substring(2);
}
else if (action == "rightClick")
{
// MouseSimulator.RightDown();
Session.PerformMouseAction(MouseActionType.RightDown);
expectedColor = settings.SecondaryButtonHighlightColor.Substring(2);
}
else
{
Assert.Fail("Invalid action specified.");
}
expectedColor = "#" + expectedColor;
var location = Session.GetMousePosition();
int radius = int.Parse(settings.Radius, CultureInfo.InvariantCulture);
var colorLeftClick = Session.GetPixelColorString(location.Item1, location.Item2);
Assert.AreEqual(expectedColor, colorLeftClick);
var colorLeftClick2 = Session.GetPixelColorString(location.Item1 + radius - 1, location.Item2);
Assert.AreEqual(expectedColor, colorLeftClick2);
Task.Delay(500).Wait();
var colorBackground = Session.GetPixelColorString(location.Item1 + radius + 50, location.Item2 + radius + 50);
Assert.AreNotEqual(expectedColor, colorBackground);
if (action == "leftClick")
{
// MouseSimulator.LeftUp();
Session.PerformMouseAction(MouseActionType.LeftUp);
}
else if (action == "rightClick")
{
// MouseSimulator.RightUp();
Session.PerformMouseAction(MouseActionType.RightUp);
}
int duration = int.Parse(settings.FadeDuration, CultureInfo.InvariantCulture);
Task.Delay(duration + 100).Wait();
colorLeftClick = Session.GetPixelColorString(location.Item1, location.Item2);
Assert.AreNotEqual("#" + settings.PrimaryButtonHighlightColor, colorLeftClick);
}
private void SetColor(ref Custom foundCustom, string colorName = "Primary button highlight color", string colorValue = "000000", string opacity = "0")
{
Assert.IsNotNull(foundCustom);
var groupAppearanceBehavior = foundCustom.Find<TextBlock>("Appearance & behavior");
if (groupAppearanceBehavior != null)
{
if (foundCustom.FindAll<TextBox>("Fade duration (ms) Minimum0").Count == 0)
{
groupAppearanceBehavior.Click();
}
// Set primary button highlight color
var primaryButtonHighlightColor = foundCustom.Find<Group>(colorName);
Assert.IsNotNull(primaryButtonHighlightColor);
var button = primaryButtonHighlightColor.Find<Button>(By.XPath(".//Button"));
Assert.IsNotNull(button);
button.Click(false, 500, 700);
var popupWindow = Session.Find<Window>("Popup");
Assert.IsNotNull(popupWindow);
var colorModelComboBox = this.Find<ComboBox>("Color model");
Assert.IsNotNull(colorModelComboBox);
colorModelComboBox.Click(false, 500, 700);
var selectedItem = colorModelComboBox.Find<NavigationViewItem>("RGB");
selectedItem.Click();
var rgbHexEdit = this.Find<TextBox>("RGB hex");
Assert.IsNotNull(rgbHexEdit);
rgbHexEdit.SetText(colorValue);
button.Click();
}
}
private void SetMouseHighlighterAppearanceBehavior(ref Custom foundCustom, ref MouseHighlighterSettings settings)
{
Assert.IsNotNull(foundCustom);
var groupAppearanceBehavior = foundCustom.Find<TextBlock>("Appearance & behavior");
if (groupAppearanceBehavior != null)
{
// groupAppearanceBehavior.Click();
if (foundCustom.FindAll<TextBox>(settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.FadeDurationEdit)).Count == 0)
{
groupAppearanceBehavior.Click();
}
// Set primary button highlight color
SetColor(ref foundCustom, settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.PrimaryButtonHighlightColorGroup), settings.PrimaryButtonHighlightColor);
// Set secondary button highlight color
SetColor(ref foundCustom, settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.SecondaryButtonHighlightColorGroup), settings.SecondaryButtonHighlightColor);
// Set the duration to duration ms
var fadeDurationEdit = foundCustom.Find<TextBox>(settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.FadeDurationEdit));
Assert.IsNotNull(fadeDurationEdit);
fadeDurationEdit.SetText(settings.FadeDuration);
Assert.AreEqual(settings.FadeDuration, fadeDurationEdit.Text);
// Set Fade delay(ms)
var fadeDelayEdit = foundCustom.Find<TextBox>(settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.FadeDelayEdit));
Assert.IsNotNull(fadeDelayEdit);
fadeDelayEdit.SetText(settings.FadeDelay);
Assert.AreEqual(settings.FadeDelay, fadeDelayEdit.Text);
// Set the fade radius (px)
var fadeRadiusEdit = foundCustom.Find<TextBox>(settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.RadiusEdit));
Assert.IsNotNull(fadeRadiusEdit);
fadeRadiusEdit.SetText(settings.Radius);
Assert.AreEqual(settings.Radius, fadeRadiusEdit.Text);
// Set always highlight color
SetColor(ref foundCustom, settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.AlwaysHighlightColorGroup), settings.AlwaysHighlightColor);
}
else
{
Assert.Fail("Appearance & behavior group not found.");
}
}
private void LaunchFromSetting(bool showWarning = false, bool launchAsAdmin = false)
{
Session.SetMainWindowSize(WindowSize.Large);
// Goto Hosts File Editor setting page
if (this.FindAll<NavigationViewItem>("Mouse utilities").Count == 0)
{
// Expand Advanced list-group if needed
this.Find<NavigationViewItem>("Input / Output").Click();
}
this.Find<NavigationViewItem>("Mouse utilities").Click();
}
}
}

View File

@@ -0,0 +1,144 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading.Tasks;
using Microsoft.PowerToys.UITest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MouseUtils.UITests
{
[TestClass]
public class MouseJumpTests : UITestBase
{
[TestMethod]
public void TestEnableMouseJump()
{
LaunchFromSetting();
var foundCustom0 = this.Find<Custom>("Find My Mouse");
if (foundCustom0 != null)
{
foundCustom0.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(true);
foundCustom0.Find<ToggleSwitch>("Enable Find My Mouse").Toggle(false);
}
else
{
Assert.Fail("Find My Mouse custom not found.");
}
for (int i = 0; i < 10; i++)
{
Session.PerformMouseAction(MouseActionType.ScrollDown);
}
var foundCustom = this.Find<Custom>("Mouse Jump");
if (foundCustom != null)
{
foundCustom.Find<ToggleSwitch>("Enable Mouse Jump").Toggle(true);
var xy = Session.GetMousePosition();
Session.MoveMouseTo(xy.Item1, xy.Item2 - 100);
// Change the shortcut key for MouseHighlighter
// [TestCase]Change activation shortcut and test it
var activationShortcutButton = foundCustom.Find<Button>("Activation shortcut");
Assert.IsNotNull(activationShortcutButton);
activationShortcutButton.Click(false, 500, 1000);
var activationShortcutWindow = Session.Find<Window>("Activation shortcut");
Assert.IsNotNull(activationShortcutWindow);
// Invalid shortcut key
Session.SendKeySequence(Key.H);
// IOUtil.SimulateKeyPress(0x41);
var invalidShortcutText = activationShortcutWindow.Find<TextBlock>("Invalid shortcut");
Assert.IsNotNull(invalidShortcutText);
// IOUtil.SimulateShortcut(0x5B, 0x10, 0x45);
Session.SendKeys(Key.Win, Key.Shift, Key.Z);
// Assert.IsNull(activationShortcutWindow.Find<TextBlock>("Invalid shortcut"));
var saveButton = activationShortcutWindow.Find<Button>("Save");
Assert.IsNotNull(saveButton);
saveButton.Click(false, 500, 1500);
var screenCenter = this.Session.GetScreenCenter();
Session.MoveMouseTo(screenCenter.CenterX, screenCenter.CenterY, 500, 1000);
Session.MoveMouseTo(screenCenter.CenterX, screenCenter.CenterY - 300, 500, 1000);
Session.SendKeys(Key.Win, Key.Shift, Key.Z);
VerifyWindowAppears();
Task.Delay(1000).Wait();
foundCustom.Find<ToggleSwitch>("Enable Mouse Jump").Toggle(false);
Session.MoveMouseTo(screenCenter.CenterX, screenCenter.CenterY - 300, 500, 1000);
Session.SendKeys(Key.Win, Key.Shift, Key.Z);
Task.Delay(500).Wait();
VerifyWindowNotAppears();
}
else
{
Assert.Fail("Mouse Highlighter Custom not found.");
}
Task.Delay(500).Wait();
}
private void VerifyWindowAppears()
{
string windowName = "MouseJump";
Session.Attach(windowName);
var center = this.Session.GetWindowCenter();
Session.MoveMouseTo(center.CenterX, center.CenterY);
Session.PerformMouseAction(MouseActionType.LeftClick, 1000, 1000);
var screenCenter = this.Session.GetScreenCenter();
// Get Mouse position
var xy = Session.GetMousePosition();
double distance = CalculateDistance(xy.Item1, xy.Item2, screenCenter.CenterX, screenCenter.CenterY);
Assert.IsTrue(distance <= 10, "Mouse Jump window should be opened and mouse should be moved to the center of the screen.");
}
private void VerifyWindowNotAppears()
{
string windowName = "MouseJump";
bool open = Session.IsWindowOpen(windowName);
Assert.IsFalse(open, "Mouse Jump window should not be opened.");
}
/// <summary>
/// Calculate the Euclidean distance between two 2D points
/// </summary>
/// <param name="x1">X coordinate of first point</param>
/// <param name="y1">Y coordinate of first point</param>
/// <param name="x2">X coordinate of second point</param>
/// <param name="y2">Y coordinate of second point</param>
/// <returns>Distance (double)</returns>
public double CalculateDistance(int x1, int y1, int x2, int y2)
{
int dx = x2 - x1;
int dy = y2 - y1;
return Math.Sqrt((dx * dx) + (dy * dy));
}
private void LaunchFromSetting(bool showWarning = false, bool launchAsAdmin = false)
{
Session.SetMainWindowSize(WindowSize.Large);
Task.Delay(1000).Wait();
// Goto Hosts File Editor setting page
if (this.FindAll<NavigationViewItem>("Mouse utilities").Count == 0)
{
// Expand Advanced list-group if needed
this.Find<NavigationViewItem>("Input / Output").ClickCenter();
}
// Click on the Mouse utilities
Task.Delay(2000).Wait();
this.Find<NavigationViewItem>("Mouse utilities").Click();
}
}
}

View File

@@ -0,0 +1,310 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.Reflection;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.PowerToys.UITest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Windows.Devices.Printers;
namespace MouseUtils.UITests
{
[TestClass]
public class MousePointerCrosshairsTests : UITestBase
{
[TestMethod]
public void TestEnableMousePointerCrosshairs()
{
LaunchFromSetting();
var settings = new MousePointerCrosshairsSettings();
settings.CrosshairsColor = "FF0000";
settings.CrosshairsBorderColor = "FF0000";
settings.Opacity = "100";
settings.CenterRadius = "0";
settings.Thickness = "20";
settings.BorderSize = "0";
settings.IsFixLength = false;
settings.FixedLength = "1";
var foundCustom = FindMouseUtilElement(MouseUtilsSettings.MouseUtils.FindMyMouse);
MouseUtilsSettings.SetMouseUtilEnabled(foundCustom, MouseUtilsSettings.MouseUtils.FindMyMouse, false);
foundCustom = FindMouseUtilElement(MouseUtilsSettings.MouseUtils.MouseHighlighter);
MouseUtilsSettings.SetMouseUtilEnabled(foundCustom, MouseUtilsSettings.MouseUtils.MouseHighlighter, true);
MouseUtilsSettings.SetMouseUtilEnabled(foundCustom, MouseUtilsSettings.MouseUtils.MouseHighlighter, false);
for (int i = 0; i < 10; i++)
{
Session.PerformMouseAction(MouseActionType.ScrollDown);
}
foundCustom = FindMouseUtilElement(MouseUtilsSettings.MouseUtils.MousePointerCrosshairs);
// this.FindGroup("Enable Mouse Pointer Crosshairs");
MouseUtilsSettings.SetMouseUtilEnabled(foundCustom, MouseUtilsSettings.MouseUtils.MousePointerCrosshairs, false);
Task.Delay(500).Wait();
MouseUtilsSettings.SetMouseUtilEnabled(foundCustom, MouseUtilsSettings.MouseUtils.MousePointerCrosshairs, true);
Assert.IsNotNull(foundCustom);
// [Test Case] Change activation shortcut and test it.
var activationShortcutButton = foundCustom.Find<Button>("Activation shortcut");
Assert.IsNotNull(activationShortcutButton);
activationShortcutButton.Click(false, 500, 1000);
var activationShortcutWindow = Session.Find<Window>("Activation shortcut");
Assert.IsNotNull(activationShortcutWindow);
// Invalid shortcut key
Session.SendKeySequence(Key.H);
var invalidShortcutText = activationShortcutWindow.Find<TextBlock>("Invalid shortcut");
Assert.IsNotNull(invalidShortcutText);
Session.SendKeys(Key.Win, Key.Alt, Key.A);
// Assert.IsNull(activationShortcutWindow.Find<TextBlock>("Invalid shortcut"));
var saveButton = activationShortcutWindow.Find<Button>("Save");
Assert.IsNotNull(saveButton);
saveButton.Click(false, 500, 1000);
SetMousePointerCrosshairsAppearanceBehavior(ref foundCustom, ref settings);
Task.Delay(500).Wait();
// [Test Case] Press the activation shortcut and verify the crosshairs appear, and that they follow the mouse around.
var xy0 = Session.GetMousePosition();
Session.MoveMouseTo(xy0.Item1 - 100, xy0.Item2);
Session.PerformMouseAction(MouseActionType.LeftClick);
Session.SendKeys(Key.Win, Key.Alt, Key.A);
Task.Delay(1000).Wait();
xy0 = Session.GetMousePosition();
Session.MoveMouseTo(xy0.Item1 - 100, xy0.Item2 - 100);
Session.PerformMouseAction(MouseActionType.LeftClick);
VerifyMousePointerCrosshairsAppears(ref settings);
Task.Delay(500).Wait();
xy0 = Session.GetMousePosition();
Session.MoveMouseTo(xy0.Item1 - 50, xy0.Item2 - 50);
VerifyMousePointerCrosshairsAppears(ref settings);
// [Test Case] Press the activation shortcut again and verify the crosshairs disappear.
Session.SendKeys(Key.Win, Key.Alt, Key.A);
Task.Delay(1000).Wait();
xy0 = Session.GetMousePosition();
Session.MoveMouseTo(xy0.Item1 - 10, xy0.Item2);
Session.PerformMouseAction(MouseActionType.LeftClick);
VerifyMousePointerCrosshairsNotAppears(ref settings);
Task.Delay(500).Wait();
// [Test Case] Disable Mouse Pointer Crosshairs and verify that the module is not activated when you press the activation shortcut.
MouseUtilsSettings.SetMouseUtilEnabled(foundCustom, MouseUtilsSettings.MouseUtils.MousePointerCrosshairs, false);
xy0 = Session.GetMousePosition();
Session.MoveMouseTo(xy0.Item1 - 100, xy0.Item2);
Session.PerformMouseAction(MouseActionType.LeftClick);
Session.SendKeys(Key.Win, Key.Alt, Key.A);
Task.Delay(1000).Wait();
VerifyMousePointerCrosshairsNotAppears(ref settings);
}
private void VerifyMousePointerCrosshairsNotAppears(ref MousePointerCrosshairsSettings settings)
{
Task.Delay(500).Wait();
string expectedColor = string.Empty;
expectedColor = "#" + settings.CrosshairsColor;
var location = Session.GetMousePosition();
int radius = int.Parse(settings.CenterRadius, CultureInfo.InvariantCulture);
var color = Session.GetPixelColorString(location.Item1, location.Item2);
Assert.AreNotEqual(expectedColor, color);
}
private void VerifyMousePointerCrosshairsAppears(ref MousePointerCrosshairsSettings settings)
{
Task.Delay(1000).Wait();
string expectedColor = string.Empty;
expectedColor = "#" + settings.CrosshairsColor;
var location = Session.GetMousePosition();
int radius = int.Parse(settings.CenterRadius, CultureInfo.InvariantCulture);
var color = Session.GetPixelColorString(location.Item1, location.Item2);
Assert.AreEqual(expectedColor, color, "Center color check failed");
var colorX = Session.GetPixelColorString(location.Item1 + 50, location.Item2);
Assert.AreEqual(expectedColor, colorX, "Center x + 50 color check failed");
colorX = Session.GetPixelColorString(location.Item1 - 50, location.Item2);
Assert.AreEqual(expectedColor, colorX, "Center x - 50 color check failed");
var colorY = Session.GetPixelColorString(location.Item1, location.Item2 + 50);
Assert.AreEqual(expectedColor, colorY, "Center y + 50 color check failed");
colorY = Session.GetPixelColorString(location.Item1, location.Item2 - 50);
Assert.AreEqual(expectedColor, colorY, "Center y + 50 color check failed");
}
private void SetColor(ref Custom foundCustom, string colorName, string colorValue = "000000")
{
Assert.IsNotNull(foundCustom);
var groupAppearanceBehavior = foundCustom.Find<TextBlock>("Appearance & behavior");
if (groupAppearanceBehavior != null)
{
// Set primary button highlight color
var primaryButtonHighlightColor = foundCustom.Find<Group>(colorName);
Assert.IsNotNull(primaryButtonHighlightColor);
var button = primaryButtonHighlightColor.Find<Button>(By.XPath(".//Button"));
Assert.IsNotNull(button);
button.Click(false);
var popupWindow = Session.Find<Window>("Popup");
Assert.IsNotNull(popupWindow);
var colorModelComboBox = this.Find<ComboBox>("Color model");
Assert.IsNotNull(colorModelComboBox);
colorModelComboBox.Click();
var selectedItem = colorModelComboBox.Find<NavigationViewItem>("RGB");
selectedItem.Click();
var rgbHexEdit = this.Find<TextBox>("RGB hex");
Assert.IsNotNull(rgbHexEdit);
rgbHexEdit.SetText(colorValue);
button.Click();
}
}
private void SetMousePointerCrosshairsAppearanceBehavior(ref Custom foundCustom, ref MousePointerCrosshairsSettings settings)
{
Assert.IsNotNull(foundCustom);
var groupAppearanceBehavior = foundCustom.Find<TextBlock>("Appearance & behavior");
if (groupAppearanceBehavior != null)
{
// groupAppearanceBehavior.Click();
if (foundCustom.FindAll<TextBox>(settings.GetElementName(MousePointerCrosshairsSettings.SettingsUIElements.ThicknessEdit)).Count == 0)
{
groupAppearanceBehavior.Click();
Session.PerformMouseAction(MouseActionType.ScrollDown);
Session.PerformMouseAction(MouseActionType.ScrollDown);
Session.PerformMouseAction(MouseActionType.ScrollDown);
}
// Set the crosshairs color
SetColor(ref foundCustom, settings.GetElementName(MousePointerCrosshairsSettings.SettingsUIElements.CrosshairsColorGroup), settings.CrosshairsColor);
// Set the crosshairs border color
SetColor(ref foundCustom, settings.GetElementName(MousePointerCrosshairsSettings.SettingsUIElements.CrosshairsBorderColorGroup), settings.CrosshairsBorderColor);
// Set the duration to duration ms
var opacitySlider = foundCustom.Find<Slider>(settings.GetElementName(MousePointerCrosshairsSettings.SettingsUIElements.OpacitySlider));
Assert.IsNotNull(opacitySlider);
Assert.IsNotNull(settings.Opacity);
int opacityValue = int.Parse(settings.Opacity, CultureInfo.InvariantCulture);
opacitySlider.QuickSetValue(opacityValue);
Assert.AreEqual(settings.Opacity, opacitySlider.Text);
Task.Delay(500).Wait();
// Set the center radius (px)
var centerRadiusEdit = foundCustom.Find<TextBox>(settings.GetElementName(MousePointerCrosshairsSettings.SettingsUIElements.CenterRadiusEdit));
Assert.IsNotNull(centerRadiusEdit);
centerRadiusEdit.SetText(settings.CenterRadius);
Assert.AreEqual(settings.CenterRadius, centerRadiusEdit.Text);
// Set the thickness (px)
var thicknessEdit = foundCustom.Find<TextBox>(settings.GetElementName(MousePointerCrosshairsSettings.SettingsUIElements.ThicknessEdit));
Assert.IsNotNull(thicknessEdit);
thicknessEdit.SetText(settings.Thickness);
Assert.AreEqual(settings.Thickness, thicknessEdit.Text);
// Set the border size (px)
var borderSizeEdit = foundCustom.Find<TextBox>(settings.GetElementName(MousePointerCrosshairsSettings.SettingsUIElements.BorderSizeEdit));
Assert.IsNotNull(borderSizeEdit);
borderSizeEdit.SetText(settings.BorderSize);
Assert.AreEqual(settings.BorderSize, borderSizeEdit.Text);
// Set the fixed length (px)
var isFixedLength = foundCustom.Find<ToggleSwitch>(settings.GetElementName(MousePointerCrosshairsSettings.SettingsUIElements.IsFixLengthToggle));
Assert.IsNotNull(isFixedLength);
isFixedLength.Toggle(settings.IsFixLength);
Assert.AreEqual(settings.IsFixLength, isFixedLength.IsOn);
if (settings.IsFixLength)
{
var fixedLengthEdit = foundCustom.Find<TextBox>(settings.GetElementName(MousePointerCrosshairsSettings.SettingsUIElements.FixedLengthEdit));
Assert.IsNotNull(fixedLengthEdit);
fixedLengthEdit.SetText(settings.FixedLength);
Assert.AreEqual(settings.FixedLength, fixedLengthEdit.Text);
}
}
else
{
Assert.Fail("Appearance & behavior group not found.");
}
}
private bool FindGroup(string groupName)
{
try
{
var foundElements = this.FindAll<Element>(groupName);
foreach (var element in foundElements)
{
string className = element.ClassName;
string name = element.Name;
string text = element.Text;
string helptext = element.HelpText;
string controlType = element.ControlType;
}
if (foundElements.Count == 0)
{
return false;
}
}
catch (Exception ex)
{
// Validate if group is not found by checking exception.Message
return ex.Message.Contains("No element found");
}
return true;
}
public Custom? FindMouseUtilElement(MouseUtilsSettings.MouseUtils element)
{
var elementName = MouseUtilsSettings.GetMouseUtilUIName(element);
var foundCustom = this.Find<Custom>(elementName);
for (int i = 0; i < 20; i++)
{
if (foundCustom != null)
{
break;
}
Session.PerformMouseAction(MouseActionType.ScrollDown);
foundCustom = this.Find<Custom>(elementName);
}
return foundCustom;
}
private void LaunchFromSetting(bool showWarning = false, bool launchAsAdmin = false)
{
Session.SetMainWindowSize(WindowSize.Large);
// Goto Hosts File Editor setting page
if (this.FindAll<NavigationViewItem>("Mouse utilities").Count == 0)
{
// Expand Advanced list-group if needed
this.Find<NavigationViewItem>("Input / Output").Click();
}
this.Find<NavigationViewItem>("Mouse utilities").Click();
}
}
}

View File

@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Look at Directory.Build.props in root for common stuff as well -->
<Import Project="..\..\..\Common.Dotnet.CsWinRT.props" />
<PropertyGroup>
<ProjectGuid>{4E0AE3A4-2EE0-44D7-A2D0-8769977254A1}</ProjectGuid>
<RootNamespace>PowerToys.MouseUtils.UITests</RootNamespace>
<AssemblyName>PowerToys.MouseUtils.UITests</AssemblyName>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<Nullable>enable</Nullable>
<OutputType>Library</OutputType>
<!-- This is a UI test, so don't run as part of MSBuild -->
<RunVSTest>false</RunVSTest>
</PropertyGroup>
<PropertyGroup>
<OutputPath>$(SolutionDir)$(Platform)\$(Configuration)\tests\MouseUtils.UITests\</OutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MSTest" />
<ProjectReference Include="..\..\..\common\UITestAutomation\UITestAutomation.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,26 @@
## This is for tracking UI-Tests migration progress for Hosts File Editor Module
Refer to [release check list] (https://github.com/microsoft/PowerToys/blob/releaseChecklist/doc/releases/tests-checklist-template.md#hosts-file-editor) for all manual tests.
### Existing Manual Test-cases run by previous PowerToys owner
For existing manual test-cases, we will convert them to UI-Tests and run them in CI and Release pipeline
* Launch Host File Editor:
- [x] Verify the application exits if "Quit" is clicked on the initial warning. (**HostsSettingTests.TestWarningDialog**)
- [x] Launch Host File Editor again and click "Accept". The module should not close. (**HostModuleTests.TestEmptyView**)
- [ ] Launch Host File Editor again and click "Accept". The module should not close. Open the hosts file (`%WinDir%\System32\Drivers\Etc`) in a text editor that auto-refreshes so you can see the changes applied by the editor in real time. (VSCode is an editor like this, for example)
- [ ] Enable and disable lines and verify they are applied to the file.
- [ ] Add a new entry and verify it's applied.
- [ ] Add manually an entry with more than 9 hosts in hosts file (Windows limitation) and verify it is split correctly on loading and the info bar is shown.
- [x] Try to filter for lines and verify you can find them. (**HostModuleTests.TestFilterControl**)
- [ ] Click the "Open hosts file" button and verify it opens in your default editor. (likely Notepad)
* Test the different settings and verify they are applied:
- [ ] Launch as Administrator.
- [x] Show a warning at startup. (**HostsSettingTests.TestWarningDialog**)
- [ ] Additional lines position.
### Additional UI-Tests cases
- [x] Add manually an entry with more than 9 hosts and Add button should be disabled. (**HostModuleTests.TestTooManyHosts**)
- [x] Add manually an entry with less or equal 9 hosts and Add button should be enabled. (**HostModuleTests.TestTooManyHosts**)
- [x] Should show empty view if no entries. (**HostModuleTests.TestEmptyView**)
- [x] Add a new entry with valid or invalid input (**HostModuleTests.TestAddHost**)
- [x] Show save host file error if not run as Administrator. (**HostModuleTests.TestErrorMessageWithNonAdminPermission**)

View File

@@ -0,0 +1,58 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MouseUtils.UITests
{
public class FindMyMouseSettings
{
// Appearance settings
public string OverlayOpacity { get; set; }
public string Radius { get; set; }
public string InitialZoom { get; set; }
public string AnimationDuration { get; set; }
// Color settings
public string BackgroundColor { get; set; }
public string SpotlightColor { get; set; }
// Activation method settings
public enum ActivationMethod
{
PressLeftControlTwice,
PressRightControlTwice,
ShakeMouse,
CustomShortcut,
}
public ActivationMethod SelectedActivationMethod { get; set; }
// Optional constructor to initialize properties
public FindMyMouseSettings(
string overlayOpacity = "",
string radius = "",
string initialZoom = "",
string animationDuration = "",
string backgroundColor = "",
string spotlightColor = "")
{
OverlayOpacity = overlayOpacity;
Radius = radius;
InitialZoom = initialZoom;
AnimationDuration = animationDuration;
BackgroundColor = backgroundColor;
SpotlightColor = spotlightColor;
SelectedActivationMethod = ActivationMethod.PressLeftControlTwice; // Default value
}
}
}

View File

@@ -0,0 +1,74 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MouseUtils.UITests
{
public class MouseHighlighterSettings
{
// Appearance settings
public string Radius { get; set; }
public string FadeDelay { get; set; }
public string FadeDuration { get; set; }
// Color settings
public string PrimaryButtonHighlightColor { get; set; }
public string SecondaryButtonHighlightColor { get; set; }
public string AlwaysHighlightColor { get; set; }
// Settings UI Elements
public enum SettingsUIElements
{
PrimaryButtonHighlightColorGroup,
SecondaryButtonHighlightColorGroup,
AlwaysHighlightColorGroup,
RadiusEdit,
FadeDelayEdit,
FadeDurationEdit,
}
private Dictionary<SettingsUIElements, string> ElementNameMap { get; }
// Optional constructor to initialize properties
public MouseHighlighterSettings(
string radius = "",
string fadeDelay = "",
string fadeDuration = "",
string primaryButtonHighlightColor = "",
string secondaryButtonHighlightColor = "",
string alwaysHighlightColor = "")
{
this.Radius = radius;
this.FadeDelay = fadeDelay;
this.FadeDuration = fadeDuration;
this.PrimaryButtonHighlightColor = primaryButtonHighlightColor;
this.SecondaryButtonHighlightColor = secondaryButtonHighlightColor;
this.AlwaysHighlightColor = alwaysHighlightColor;
ElementNameMap = new Dictionary<SettingsUIElements, string>
{
[SettingsUIElements.PrimaryButtonHighlightColorGroup] = @"Primary button highlight color",
[SettingsUIElements.SecondaryButtonHighlightColorGroup] = @"Secondary button highlight color",
[SettingsUIElements.AlwaysHighlightColorGroup] = @"Always highlight color",
[SettingsUIElements.RadiusEdit] = @"Radius (px) Minimum5",
[SettingsUIElements.FadeDelayEdit] = @"Fade delay (ms) Minimum0",
[SettingsUIElements.FadeDurationEdit] = @"Fade duration (ms) Minimum0",
};
}
public string GetElementName(SettingsUIElements element)
{
return ElementNameMap[element];
}
}
}

View File

@@ -0,0 +1,86 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core.AnimationMetrics;
namespace MouseUtils.UITests
{
public class MousePointerCrosshairsSettings
{
// Appearance settings
public string Opacity { get; set; }
public string CenterRadius { get; set; }
public string Thickness { get; set; }
public string BorderSize { get; set; }
public bool IsFixLength { get; set; }
public string FixedLength { get; set; }
// Color settings
public string CrosshairsColor { get; set; }
public string CrosshairsBorderColor { get; set; }
// Settings UI Elements
public enum SettingsUIElements
{
CrosshairsColorGroup,
CrosshairsBorderColorGroup,
OpacitySlider,
CenterRadiusEdit,
ThicknessEdit,
BorderSizeEdit,
FixedLengthEdit,
IsFixLengthToggle,
}
private Dictionary<SettingsUIElements, string> ElementNameMap { get; }
// Optional constructor to initialize properties
public MousePointerCrosshairsSettings(
string opacity = "",
string centerRadius = "",
string thickness = "",
string borderSize = "",
bool isFixLength = false,
string fixedLength = "",
string crosshairsColor = "",
string crosshairsBorderColor = "")
{
this.Opacity = opacity;
this.CenterRadius = centerRadius;
this.Thickness = thickness;
this.BorderSize = borderSize;
this.IsFixLength = isFixLength;
this.FixedLength = fixedLength;
this.CrosshairsColor = crosshairsColor;
this.CrosshairsBorderColor = crosshairsBorderColor;
ElementNameMap = new Dictionary<SettingsUIElements, string>
{
[SettingsUIElements.CrosshairsColorGroup] = @"Crosshairs color",
[SettingsUIElements.CrosshairsBorderColorGroup] = @"Crosshairs border color",
[SettingsUIElements.OpacitySlider] = @"Crosshairs opacity (%)",
[SettingsUIElements.CenterRadiusEdit] = @"Crosshairs center radius (px) Minimum0 Maximum500",
[SettingsUIElements.ThicknessEdit] = @"Crosshairs thickness (px) Minimum1 Maximum50",
[SettingsUIElements.BorderSizeEdit] = @"Crosshairs border size (px) Minimum0 Maximum50",
[SettingsUIElements.FixedLengthEdit] = @"Crosshairs fixed length (px) Minimum1",
[SettingsUIElements.IsFixLengthToggle] = @"Fix crosshairs length",
};
}
public string GetElementName(SettingsUIElements element)
{
return ElementNameMap[element];
}
}
}

View File

@@ -0,0 +1,59 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.PowerToys.UITest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium.Windows;
namespace MouseUtils.UITests
{
public class MouseUtilsSettings
{
// Mouse Utils Modules
public enum MouseUtils
{
MouseHighlighter,
FindMyMouse,
MousePointerCrosshairs,
MouseJump,
}
private static readonly Dictionary<MouseUtils, string> MouseUtilUINameMap = new()
{
[MouseUtils.MouseHighlighter] = @"Mouse Highlighter",
[MouseUtils.FindMyMouse] = @"Find My Mouse",
[MouseUtils.MousePointerCrosshairs] = @"Mouse Pointer Crosshairs",
[MouseUtils.MouseJump] = @"Mouse Jump",
};
private static readonly Dictionary<MouseUtils, string> MouseUtilUIToggleMap = new()
{
[MouseUtils.MouseHighlighter] = @"Enable Mouse Highlighter",
[MouseUtils.FindMyMouse] = @"Enable Find My Mouse",
[MouseUtils.MousePointerCrosshairs] = @"Enable Mouse Pointer Crosshairs",
[MouseUtils.MouseJump] = @"Enable Mouse Jump",
};
public static string GetMouseUtilUIName(MouseUtils element)
{
return MouseUtilUINameMap[element];
}
public static void SetMouseUtilEnabled(Custom? custom, MouseUtils element, bool isEnable = true)
{
if (custom != null)
{
string toggleName = MouseUtilUIToggleMap[element];
var toggle = custom.Find<ToggleSwitch>(toggleName);
toggle.Toggle(isEnable);
}
else
{
Assert.Fail(element + " custom not found.");
}
}
}
}

View File

@@ -0,0 +1,24 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.PowerToys.UITest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace WorkspacesEditorUITest;
[TestClass]
public class WorkspacesEditorTests : UITestBase
{
public WorkspacesEditorTests()
: base(PowerToysModule.Workspaces, WindowSize.Medium)
{
}
[TestMethod("WorkspacesEditor.Items.Present")]
[TestCategory("Workspaces UI")]
public void TestItemsPresents()
{
Assert.IsTrue(this.Has<Button>("Create Workspace"), "Should have create workspace button");
}
}

View File

@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\..\Common.Dotnet.CsWinRT.props" />
<PropertyGroup>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<OutputType>Library</OutputType>
<RunVSTest>false</RunVSTest>
<IsTestProject>true</IsTestProject>
<IsPackable>false</IsPackable>
<AssemblyName>PowerToys.Workspaces.UITests</AssemblyName>
</PropertyGroup>
<PropertyGroup>
<OutputPath>..\..\..\..\$(Platform)\$(Configuration)\tests\Workspaces.UITests\</OutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Appium.WebDriver" />
<PackageReference Include="MSTest" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\common\UITestAutomation\UITestAutomation.csproj" />
</ItemGroup>
</Project>

View File

@@ -4,6 +4,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CmdPal.Ext.TimeDate.Helpers;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
@@ -12,6 +14,12 @@ namespace Microsoft.CmdPal.Ext.TimeDate.Pages;
internal sealed partial class TimeDateExtensionPage : DynamicListPage
{
private readonly Lock _resultsLock = new();
private IList<ListItem> _results = new List<ListItem>();
private bool initialized;
private SettingsManager _settingsManager;
public TimeDateExtensionPage(SettingsManager settingsManager)
@@ -24,20 +32,36 @@ internal sealed partial class TimeDateExtensionPage : DynamicListPage
_settingsManager = settingsManager;
}
public override IListItem[] GetItems() => DoExecuteSearch(SearchText).ToArray();
public override IListItem[] GetItems()
{
if (!initialized)
{
DoExecuteSearch(string.Empty);
}
lock (_resultsLock)
{
ListItem[] results = _results.ToArray();
return results;
}
}
public override void UpdateSearchText(string oldSearch, string newSearch)
{
if (newSearch == oldSearch)
{
return;
}
DoExecuteSearch(newSearch);
RaiseItemsChanged(0);
}
private List<ListItem> DoExecuteSearch(string query)
private void DoExecuteSearch(string query)
{
try
{
var result = TimeDateCalculator.ExecuteSearch(_settingsManager, query);
return result;
UpdateResult(result);
}
catch (Exception)
{
@@ -51,7 +75,18 @@ internal sealed partial class TimeDateExtensionPage : DynamicListPage
ResultHelper.CreateInvalidInputErrorResult(),
};
return items;
UpdateResult(items);
}
}
private void UpdateResult(IList<ListItem> result)
{
lock (_resultsLock)
{
initialized = true;
this._results = result;
}
RaiseItemsChanged(this._results.Count);
}
}

View File

@@ -295,7 +295,7 @@
"Areas": [ "AreaEaseOfAccess" ],
"Type": "AppSettingsApp",
"AltNames": [ "TouchFeedback" ],
"Command": "ms-settings:easeofaccess-MousePointer"
"Command": "ms-settings:easeofaccess-mousepointer"
},
{
"Name": "Display",

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 ManagedCommon;
using Microsoft.CmdPal.Common.Helpers;
using Microsoft.CmdPal.Common.Services;
using Microsoft.CmdPal.Ext.Apps;
@@ -78,7 +79,7 @@ public partial class App : Application
var cmdArgs = Environment.GetCommandLineArgs();
bool runFromPT = false;
var runFromPT = false;
foreach (var arg in cmdArgs)
{
if (arg == "RunFromPT")
@@ -107,9 +108,6 @@ public partial class App : Application
// Built-in Commands. Order matters - this is the order they'll be presented by default.
var allApps = new AllAppsCommandProvider();
var winget = new WinGetExtensionCommandsProvider();
var callback = allApps.LookupApp;
winget.SetAllLookup(callback);
services.AddSingleton<ICommandProvider>(allApps);
services.AddSingleton<ICommandProvider, ShellCommandsProvider>();
services.AddSingleton<ICommandProvider, CalculatorCommandProvider>();
@@ -120,7 +118,25 @@ public partial class App : Application
// services.AddSingleton<ICommandProvider, ClipboardHistoryCommandsProvider>();
services.AddSingleton<ICommandProvider, WindowWalkerCommandsProvider>();
services.AddSingleton<ICommandProvider, WebSearchCommandsProvider>();
services.AddSingleton<ICommandProvider>(winget);
// GH #38440: Users might not have WinGet installed! Or they might have
// a ridiculously old version. Or might be running as admin.
// We shouldn't explode in the App ctor if we fail to instantiate an
// instance of PackageManager, which will happen in the static ctor
// for WinGetStatics
try
{
var winget = new WinGetExtensionCommandsProvider();
var callback = allApps.LookupApp;
winget.SetAllLookup(callback);
services.AddSingleton<ICommandProvider>(winget);
}
catch (Exception ex)
{
Logger.LogError("Couldn't load winget");
Logger.LogError(ex.ToString());
}
services.AddSingleton<ICommandProvider, WindowsTerminalCommandsProvider>();
services.AddSingleton<ICommandProvider, WindowsSettingsCommandsProvider>();
services.AddSingleton<ICommandProvider, RegistryCommandsProvider>();

View File

@@ -105,19 +105,8 @@ public sealed partial class SearchBar : UserControl,
var ctrlPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
var altPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Menu).HasFlag(CoreVirtualKeyStates.Down);
if (e.Key == VirtualKey.Down)
{
WeakReferenceMessenger.Default.Send<NavigateNextCommand>();
e.Handled = true;
}
else if (e.Key == VirtualKey.Up)
{
WeakReferenceMessenger.Default.Send<NavigatePreviousCommand>();
e.Handled = true;
}
else if (ctrlPressed && e.Key == VirtualKey.Enter)
if (ctrlPressed && e.Key == VirtualKey.Enter)
{
// ctrl+enter
WeakReferenceMessenger.Default.Send<ActivateSecondaryCommandMessage>();
@@ -197,6 +186,18 @@ public sealed partial class SearchBar : UserControl,
_isBackspaceHeld = true;
}
}
else if (e.Key == VirtualKey.Up)
{
WeakReferenceMessenger.Default.Send<NavigatePreviousCommand>();
e.Handled = true;
}
else if (e.Key == VirtualKey.Down)
{
WeakReferenceMessenger.Default.Send<NavigateNextCommand>();
e.Handled = true;
}
}
private void FilterBox_PreviewKeyUp(object sender, KeyRoutedEventArgs e)

View File

@@ -187,6 +187,10 @@ public sealed partial class ListPage : Page,
{
ItemsList.SelectedIndex++;
}
else
{
ItemsList.SelectedIndex = 0;
}
}
public void Receive(NavigatePreviousCommand message)
@@ -195,6 +199,10 @@ public sealed partial class ListPage : Page,
{
ItemsList.SelectedIndex--;
}
else
{
ItemsList.SelectedIndex = ItemsList.Items.Count - 1;
}
}
public void Receive(ActivateSelectedListItemMessage message)

View File

@@ -13,6 +13,7 @@
<EnableMsixTooling>true</EnableMsixTooling>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained>
<Version>$(CmdPalVersion)</Version>

View File

@@ -19,6 +19,7 @@ SetFocus
SetActiveWindow
MonitorFromWindow
GetMonitorInfo
GetDpiForMonitor
SHCreateStreamOnFileEx
CoAllowSetForegroundWindow
SHCreateStreamOnFileEx

View File

@@ -4,6 +4,7 @@
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.WinUI;
using ManagedCommon;
using Microsoft.CmdPal.UI.Helpers;
using Microsoft.CmdPal.UI.ViewModels;
using Microsoft.CmdPal.UI.ViewModels.Messages;
@@ -13,6 +14,8 @@ using Microsoft.UI.Xaml;
using Windows.Graphics;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.Graphics.Gdi;
using Windows.Win32.UI.HiDpi;
using Windows.Win32.UI.WindowsAndMessaging;
using RS_ = Microsoft.CmdPal.UI.Helpers.ResourceLoaderInstance;
@@ -44,6 +47,21 @@ public sealed partial class ToastWindow : Window,
WeakReferenceMessenger.Default.Register<QuitMessage>(this);
}
private static double GetScaleFactor(HWND hwnd)
{
try
{
var monitor = PInvoke.MonitorFromWindow(hwnd, MONITOR_FROM_FLAGS.MONITOR_DEFAULTTONEAREST);
_ = PInvoke.GetDpiForMonitor(monitor, MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI, out var dpiX, out _);
return dpiX / 96.0;
}
catch (Exception ex)
{
Logger.LogError($"Failed to get scale factor, error: {ex.Message}");
return 1.0;
}
}
private void PositionCentered()
{
var intSize = new SizeInt32
@@ -51,7 +69,14 @@ public sealed partial class ToastWindow : Window,
Width = Convert.ToInt32(ToastText.ActualWidth),
Height = Convert.ToInt32(ToastText.ActualHeight),
};
AppWindow.Resize(intSize);
var scaleAdjustment = GetScaleFactor(_hwnd);
var scaled = new SizeInt32
{
Width = (int)Math.Round(intSize.Width * scaleAdjustment),
Height = (int)Math.Round(intSize.Height * scaleAdjustment),
};
AppWindow.Resize(scaled);
var displayArea = DisplayArea.GetFromWindowId(AppWindow.Id, DisplayAreaFallback.Nearest);
if (displayArea is not null)

View File

@@ -189,7 +189,7 @@ public partial class InstallPackageListItem : ListItem
private void InstallStateChangedHandler(object? sender, InstallPackageCommand e)
{
if (!ApiInformation.IsApiContractPresent("Microsoft.Management.Deployment", 12))
if (!ApiInformation.IsApiContractPresent("Microsoft.Management.Deployment.WindowsPackageManagerContract", 12))
{
Logger.LogError($"RefreshPackageCatalogAsync isn't available");
e.FakeChangeStatus();

View File

@@ -12,6 +12,7 @@ using System.Threading.Tasks;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
using Microsoft.Management.Deployment;
using Windows.Foundation.Metadata;
using WindowsPackageManager.Interop;
namespace Microsoft.CmdPal.Ext.WinGet;
@@ -51,9 +52,12 @@ internal static class WinGetStatics
_storeCatalog,
];
foreach (var catalogReference in AvailableCatalogs)
if (ApiInformation.IsApiContractPresent("Microsoft.Management.Deployment.WindowsPackageManagerContract", 8))
{
catalogReference.PackageCatalogBackgroundUpdateInterval = new(0);
foreach (var catalogReference in AvailableCatalogs)
{
catalogReference.PackageCatalogBackgroundUpdateInterval = new(0);
}
}
// Immediately start the lazy-init of the all packages catalog, but

View File

@@ -0,0 +1,221 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.DirectoryServices;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using FancyZonesEditor.Models;
using FancyZonesEditorCommon.Data;
using Microsoft.FancyZones.UITests.Utils;
using Microsoft.FancyZonesEditor.UITests.Utils;
using Microsoft.FancyZonesEditor.UnitTests.Utils;
using Microsoft.PowerToys.UITest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using static Microsoft.FancyZonesEditor.UnitTests.Utils.FancyZonesEditorHelper;
namespace UITests_FancyZones
{
[TestClass]
public class OneZoneSwitchTests : UITestBase
{
private static readonly string WindowName = "Windows (C:) - File Explorer"; // set launch explorer window name
private static readonly string PowertoysWindowName = "PowerToys Settings"; // set powertoys settings window name
private static readonly int SubZones = 2;
private static readonly IOTestHelper AppZoneHistory = new FancyZonesEditorFiles().AppZoneHistoryIOHelper;
public OneZoneSwitchTests()
: base(PowerToysModule.PowerToysSettings, WindowSize.Medium)
{
}
[TestInitialize]
public void TestInitialize()
{
// set a custom layout with 2 subzones
CustomLayouts customLayouts = new CustomLayouts();
CustomLayouts.CustomLayoutListWrapper customLayoutListWrapper = CustomLayoutsList;
Files.CustomLayoutsIOHelper.WriteData(customLayouts.Serialize(customLayoutListWrapper));
// clear the app zone history
AppZoneHistory.DeleteFile();
// Goto Hosts File Editor setting page
if (this.FindAll<NavigationViewItem>("FancyZones").Count == 0)
{
// Expand Advanced list-group if needed
this.Find<NavigationViewItem>("Windowing & Layouts").Click();
}
this.Find<NavigationViewItem>("FancyZones").Click();
this.Find<ToggleSwitch>("Enable FancyZones").Toggle(true);
this.Session.SetMainWindowSize(WindowSize.Large_Vertical);
int tries = 5;
Pull(tries, "down"); // Pull the setting page up to make sure the setting is visible
bool switchWindowEnable = TestContext.TestName == "TestSwitchShortCutDisable" ? false : true;
this.Find<ToggleSwitch>("Switch between windows in the current zone").Toggle(switchWindowEnable);
Task.Delay(500).Wait(); // Wait for the setting to be applied
Pull(tries, "up"); // Pull the setting page down to make sure the setting is visible
this.Find<Microsoft.PowerToys.UITest.Button>("Launch layout editor").Click();
Task.Delay(1000).Wait();
this.Session.Attach(PowerToysModule.FancyZone);
this.Find<Element>(By.Name("Custom Column")).Click();
this.Find<Microsoft.PowerToys.UITest.Button>("Close").Click();
this.RestartScopeExe();
}
[TestMethod]
public void TestSwitchWindow()
{
SnapToOneZone();
string? activeWindowTitle = ZoneSwitchHelper.GetActiveWindowTitle();
Assert.AreEqual(PowertoysWindowName, activeWindowTitle);
// switch to the previous window by shortcut win+page down
SendKeys(Key.Win, Key.PageDown);
activeWindowTitle = ZoneSwitchHelper.GetActiveWindowTitle();
Assert.AreEqual(WindowName, activeWindowTitle);
// Clean settings
Clean();
}
[TestMethod]
public void TestSwitchAfterDesktopChange()
{
SnapToOneZone();
string? windowTitle = ZoneSwitchHelper.GetActiveWindowTitle();
Assert.AreEqual(PowertoysWindowName, windowTitle);
// Add virtual desktop
SendKeys(Key.Ctrl, Key.Win, Key.D);
string? switchWindowTitle = ZoneSwitchHelper.GetActiveWindowTitle(); // Fixed variable name to start with lower-case letter and removed unnecessary assignment warning by using the variable meaningfully.
// return back
SendKeys(Key.Ctrl, Key.Win, Key.Left);
Task.Delay(500).Wait(); // Optional: Wait for a moment to ensure window switch
string? returnWindowTitle = ZoneSwitchHelper.GetActiveWindowTitle();
Assert.AreEqual(PowertoysWindowName, returnWindowTitle);
// check shortcut
SendKeys(Key.Win, Key.PageDown);
string? activeWindowTitle = ZoneSwitchHelper.GetActiveWindowTitle();
Assert.AreEqual(WindowName, activeWindowTitle);
// close the virtual desktop
SendKeys(Key.Ctrl, Key.Win, Key.Right);
Task.Delay(500).Wait(); // Optional: Wait for a moment to ensure window switch
SendKeys(Key.Ctrl, Key.Win, Key.F4);
Task.Delay(500).Wait(); // Optional: Wait for a moment to ensure window switch
// Clean settings
Clean();
}
[TestMethod]
public void TestSwitchShortCutDisable()
{
SnapToOneZone();
string? activeWindowTitle = ZoneSwitchHelper.GetActiveWindowTitle();
Assert.AreEqual(PowertoysWindowName, activeWindowTitle);
// switch to the previous window by shortcut win+page down
SendKeys(Key.Win, Key.PageDown);
Task.Delay(500).Wait(); // Optional: Wait for a moment to ensure window switch
activeWindowTitle = ZoneSwitchHelper.GetActiveWindowTitle();
Assert.AreNotEqual(WindowName, activeWindowTitle);
// Clean Setting
Clean();
}
private void SnapToOneZone()
{
// Set drag position of target zone
int screenWidth = Screen.PrimaryScreen?.Bounds.Width ?? 1920; // default 1920
int screenHeight = Screen.PrimaryScreen?.Bounds.Height ?? 1080;
int targetX = screenWidth / SubZones / 3;
int targetY = screenWidth / SubZones / 2;
// assert the AppZoneHistory layout is set
Session.KillAllProcessesByName("explorer");
Session.StartExe("explorer.exe", "C:\\");
// Start Windows Explorer process
Session.Attach(WindowName, WindowSize.UnSpecified); // display window1
var tabView = Find<Element>(By.AccessibilityId("TabView"));
tabView.DoubleClick(); // maximize the window
tabView.KeyDownAndDrag(Key.Shift, targetX, targetY);
// Attach the PowerToys settings window to the front
Session.Attach(PowertoysWindowName, WindowSize.UnSpecified);
string name = "Non Client Input Sink Window";
Element settingsView = Find<Element>(By.Name(name));
settingsView.DoubleClick(); // maximize the window
settingsView.KeyDownAndDrag(Key.Shift, targetX, targetY);
// check the AppZoneHistory layout is set and in the same zone
string appZoneHistoryJson = AppZoneHistory.GetData();
Console.WriteLine($"{ZoneSwitchHelper.GetZoneIndexSetByAppName(WindowName, appZoneHistoryJson)},{ZoneSwitchHelper.GetZoneIndexSetByAppName(WindowName, appZoneHistoryJson)}");
Assert.AreEqual(
ZoneSwitchHelper.GetZoneIndexSetByAppName(WindowName, appZoneHistoryJson),
ZoneSwitchHelper.GetZoneIndexSetByAppName(PowertoysWindowName, appZoneHistoryJson));
}
private static readonly CustomLayouts.CustomLayoutListWrapper CustomLayoutsList = new CustomLayouts.CustomLayoutListWrapper
{
CustomLayouts = new List<CustomLayouts.CustomLayoutWrapper>
{
new CustomLayouts.CustomLayoutWrapper
{
Uuid = "{63F09977-D327-4DAC-98F4-0C886CAE9517}",
Type = CustomLayout.Grid.TypeToString(),
Name = "Custom Column",
Info = new CustomLayouts().ToJsonElement(new CustomLayouts.GridInfoWrapper
{
Rows = 1,
Columns = SubZones,
RowsPercentage = new List<int> { 10000 },
ColumnsPercentage = new List<int> { 5000, 5000 },
CellChildMap = new int[][] { [0, 1] },
SensitivityRadius = 20,
ShowSpacing = true,
Spacing = 10,
}),
},
},
};
private void Pull(int tries = 5, string direction = "up")
{
Key keyToSend = direction == "up" ? Key.Up : Key.Down;
for (int i = 0; i < tries; i++)
{
SendKeys(keyToSend);
}
}
private void Clean()
{
Session.KillAllProcessesByName("explorer");
}
}
}

View File

@@ -25,4 +25,11 @@
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\editor\FancyZonesEditor\FancyZonesEditor.csproj" />
<ProjectReference Include="..\UITests-FancyZonesEditor\UITests-FancyZonesEditor.csproj" />
<ProjectReference Include="..\..\..\common\UITestAutomation\UITestAutomation.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,84 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace Microsoft.FancyZones.UITests.Utils
{
public class ZoneSwitchHelper
{
public static void LaunchExplorer(string path)
{
var explorerProcessInfo = new ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = path,
};
Process.Start(explorerProcessInfo);
Task.Delay(2000).Wait(); // Wait for the Explorer window to fully launch
}
public static string? GetZoneIndexSetByAppName(string exeName, string json)
{
if (string.IsNullOrEmpty(exeName) || string.IsNullOrEmpty(json))
{
return null;
}
try
{
using var doc = JsonDocument.Parse(json);
var historyArray = doc.RootElement.GetProperty("app-zone-history");
foreach (var item in historyArray.EnumerateArray())
{
if (item.TryGetProperty("app-path", out var appPathElement) &&
appPathElement.GetString() is string path &&
path.EndsWith(exeName, StringComparison.OrdinalIgnoreCase))
{
var history = item.GetProperty("history");
if (history.GetArrayLength() > 0)
{
return history[0].GetProperty("zone-index-set")[0].GetString();
}
}
}
}
catch (JsonException ex)
{
throw new InvalidOperationException("JSON parse error: " + ex.Message, ex);
}
return null;
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
public static string? GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, buff, nChars) > 0)
{
return buff.ToString();
}
return null;
}
}
}

View File

@@ -135,6 +135,7 @@ namespace Microsoft.FancyZonesEditor.UITests
[TestInitialize]
public void TestInitialize()
{
FancyZonesEditorHelper.Files.Restore();
EditorParameters editorParameters = new EditorParameters();
FancyZonesEditorHelper.Files.ParamsIOHelper.WriteData(editorParameters.Serialize(Parameters));
@@ -195,12 +196,6 @@ namespace Microsoft.FancyZonesEditor.UITests
this.RestartScopeExe();
}
[TestCleanup]
public void TestCleanup()
{
FancyZonesEditorHelper.Files.Restore();
}
[TestMethod]
public void ApplyCustomLayout()
{

View File

@@ -76,6 +76,7 @@ namespace Microsoft.FancyZonesEditor.UITests
[TestInitialize]
public void TestInitialize()
{
FancyZonesEditorHelper.Files.Restore();
EditorParameters editorParameters = new EditorParameters();
ParamsWrapper parameters = new ParamsWrapper
{
@@ -172,12 +173,6 @@ namespace Microsoft.FancyZonesEditor.UITests
this.RestartScopeExe();
}
[TestCleanup]
public void TestCleanup()
{
FancyZonesEditorHelper.Files.Restore();
}
[TestMethod]
public void CopyTemplate_FromEditLayoutWindow()
{

View File

@@ -23,6 +23,8 @@ namespace Microsoft.FancyZonesEditor.UITests
[TestInitialize]
public void TestInitialize()
{
FancyZonesEditorHelper.Files.Restore();
// prepare test editor parameters with 2 monitors before launching the editor
EditorParameters editorParameters = new EditorParameters();
EditorParameters.ParamsWrapper parameters = new EditorParameters.ParamsWrapper
@@ -132,12 +134,6 @@ namespace Microsoft.FancyZonesEditor.UITests
this.RestartScopeExe();
}
[TestCleanup]
public void TestCleanup()
{
FancyZonesEditorHelper.Files.Restore();
}
[TestMethod]
public void CreateWithDefaultName()
{

View File

@@ -104,6 +104,7 @@ namespace Microsoft.FancyZonesEditor.UITests
[TestInitialize]
public void TestInitialize()
{
FancyZonesEditorHelper.Files.Restore();
CustomLayouts customLayouts = new CustomLayouts();
FancyZonesEditorHelper.Files.CustomLayoutsIOHelper.WriteData(customLayouts.Serialize(Layouts));
@@ -208,12 +209,6 @@ namespace Microsoft.FancyZonesEditor.UITests
this.RestartScopeExe();
}
[TestCleanup]
public void TestCleanup()
{
FancyZonesEditorHelper.Files.Restore();
}
[TestMethod]
public void Name_Initialize()
{

View File

@@ -121,6 +121,7 @@ namespace Microsoft.FancyZonesEditor.UITests
[TestInitialize]
public void TestInitialize()
{
FancyZonesEditorHelper.Files.Restore();
var defaultLayouts = new DefaultLayouts();
FancyZonesEditorHelper.Files.DefaultLayoutsIOHelper.WriteData(defaultLayouts.Serialize(Layouts));
@@ -237,12 +238,6 @@ namespace Microsoft.FancyZonesEditor.UITests
this.RestartScopeExe();
}
[TestCleanup]
public void TestCleanup()
{
FancyZonesEditorHelper.Files.Restore();
}
[TestMethod]
public void Initialize()
{

View File

@@ -142,6 +142,7 @@ namespace Microsoft.FancyZonesEditor.UITests
[TestInitialize]
public void TestInitialize()
{
FancyZonesEditorHelper.Files.Restore();
EditorParameters editorParameters = new EditorParameters();
FancyZonesEditorHelper.Files.ParamsIOHelper.WriteData(editorParameters.Serialize(Parameters));
@@ -215,19 +216,13 @@ namespace Microsoft.FancyZonesEditor.UITests
Session.Find<Element>(CustomLayouts.CustomLayouts[0].Name).Click();
}
[TestCleanup]
public void TestCleanup()
{
FancyZonesEditorHelper.Files.Restore();
}
[TestMethod]
public void DeleteNotAppliedLayout()
{
var deletedLayout = CustomLayouts.CustomLayouts[1].Name;
Session.Find<Element>(deletedLayout).Find<Button>(PowerToys.UITest.By.AccessibilityId(AccessibilityId.EditLayoutButton)).Click();
Session.Find<Button>(PowerToys.UITest.By.AccessibilityId(AccessibilityId.DeleteLayoutButton)).Click();
Session.KeyboardAction(Keys.Tab, Keys.Enter);
Session.SendKeySequence(Key.Tab, Key.Enter);
// verify the layout is removed
Assert.IsTrue(Session.FindAll<Element>(deletedLayout).Count == 0);
@@ -245,7 +240,8 @@ namespace Microsoft.FancyZonesEditor.UITests
var deletedLayout = CustomLayouts.CustomLayouts[0].Name;
Session.Find<Element>(deletedLayout).Find<Button>(PowerToys.UITest.By.AccessibilityId(AccessibilityId.EditLayoutButton)).Click();
Session.Find<Button>(PowerToys.UITest.By.AccessibilityId(AccessibilityId.DeleteLayoutButton)).Click();
Session.KeyboardAction(Keys.Tab, Keys.Enter);
Session.SendKeySequence(Key.Tab, Key.Enter);
// verify the layout is removed
Assert.IsTrue(Session.FindAll<Element>(deletedLayout).Count == 0);
@@ -270,7 +266,7 @@ namespace Microsoft.FancyZonesEditor.UITests
var deletedLayout = CustomLayouts.CustomLayouts[1].Name;
Session.Find<Element>(deletedLayout).Find<Button>(PowerToys.UITest.By.AccessibilityId(AccessibilityId.EditLayoutButton)).Click();
Session.Find<Button>(PowerToys.UITest.By.AccessibilityId(AccessibilityId.DeleteLayoutButton)).Click();
Session.KeyboardAction(Keys.Tab, Keys.Tab, Keys.Enter);
Session.SendKeySequence(Key.Tab, Key.Tab, Key.Enter);
// verify the layout is not removed
Assert.IsNotNull(Session.Find<Element>(deletedLayout));
@@ -287,7 +283,7 @@ namespace Microsoft.FancyZonesEditor.UITests
{
var deletedLayout = CustomLayouts.CustomLayouts[1].Name;
FancyZonesEditorHelper.ClickContextMenuItem(Session, deletedLayout, FancyZonesEditorHelper.ElementName.Delete);
Session.KeyboardAction(Keys.Tab, Keys.Enter);
Session.SendKeySequence(Key.Tab, Key.Enter);
// verify the layout is removed
Assert.IsTrue(Session.FindAll<Element>(deletedLayout).Count == 0);
@@ -304,7 +300,7 @@ namespace Microsoft.FancyZonesEditor.UITests
{
var deletedLayout = CustomLayouts.CustomLayouts[1].Name;
FancyZonesEditorHelper.ClickContextMenuItem(Session, deletedLayout, FancyZonesEditorHelper.ElementName.Delete);
Session.KeyboardAction(Keys.Tab, Keys.Enter);
Session.SendKeySequence(Key.Tab, Key.Enter);
// verify the default layout is reset to the "default" default
Session.Find<Element>(TestConstants.TemplateLayoutNames[LayoutType.PriorityGrid]).Find<Button>(PowerToys.UITest.By.AccessibilityId(AccessibilityId.EditLayoutButton)).Click();
@@ -323,7 +319,7 @@ namespace Microsoft.FancyZonesEditor.UITests
{
var deletedLayout = CustomLayouts.CustomLayouts[1].Name;
FancyZonesEditorHelper.ClickContextMenuItem(Session, deletedLayout, FancyZonesEditorHelper.ElementName.Delete);
Session.KeyboardAction(Keys.Tab, Keys.Enter);
Session.SendKeySequence(Key.Tab, Key.Enter);
// verify the hotkey is available
Session.Find<Element>(CustomLayouts.CustomLayouts[0].Name).Find<Button>(PowerToys.UITest.By.AccessibilityId(AccessibilityId.EditLayoutButton)).Click();

View File

@@ -105,6 +105,7 @@ namespace Microsoft.FancyZonesEditor.UITests
[TestInitialize]
public void TestInitialize()
{
FancyZonesEditorHelper.Files.Restore();
EditorParameters editorParameters = new EditorParameters();
ParamsWrapper parameters = new ParamsWrapper
{
@@ -209,12 +210,6 @@ namespace Microsoft.FancyZonesEditor.UITests
this.RestartScopeExe();
}
[TestCleanup]
public void TestCleanup()
{
FancyZonesEditorHelper.Files.Restore();
}
[TestMethod]
public void OpenEditMode()
{

View File

@@ -32,6 +32,7 @@ namespace Microsoft.FancyZonesEditor.UITests
[TestInitialize]
public void TestInitialize()
{
FancyZonesEditorHelper.Files.Restore();
EditorParameters editorParameters = new EditorParameters();
ParamsWrapper parameters = new ParamsWrapper
{
@@ -141,12 +142,6 @@ namespace Microsoft.FancyZonesEditor.UITests
this.RestartScopeExe();
}
[TestCleanup]
public void TestCleanup()
{
FancyZonesEditorHelper.Files.Restore();
}
[TestMethod]
public void FirstLaunch()
{

View File

@@ -106,6 +106,7 @@ namespace Microsoft.FancyZonesEditor.UITests
[TestInitialize]
public void TestInitialize()
{
FancyZonesEditorHelper.Files.Restore();
EditorParameters editorParameters = new EditorParameters();
ParamsWrapper parameters = new ParamsWrapper
{
@@ -206,12 +207,6 @@ namespace Microsoft.FancyZonesEditor.UITests
this.RestartScopeExe();
}
[TestCleanup]
public void TestCleanup()
{
FancyZonesEditorHelper.Files.Restore();
}
[TestMethod]
public void Initialize()
{

View File

@@ -80,6 +80,7 @@ namespace Microsoft.FancyZonesEditor.UITests
[TestInitialize]
public void TestInitialize()
{
FancyZonesEditorHelper.Files.Restore();
EditorParameters editorParameters = new EditorParameters();
ParamsWrapper parameters = new ParamsWrapper
{
@@ -191,12 +192,6 @@ namespace Microsoft.FancyZonesEditor.UITests
this.RestartScopeExe();
}
[TestCleanup]
public void TestCleanup()
{
FancyZonesEditorHelper.Files.Restore();
}
[TestMethod]
public void ZoneNumber_Cancel()
{

View File

@@ -27,12 +27,6 @@ namespace Microsoft.FancyZonesEditor.UITests
{
}
[TestCleanup]
public void TestCleanup()
{
FancyZonesEditorHelper.Files.Restore();
}
[TestMethod]
public void EditorParams_VerifySelectedMonitor()
{
@@ -737,6 +731,7 @@ namespace Microsoft.FancyZonesEditor.UITests
private void InitFileData()
{
FancyZonesEditorHelper.Files.Restore();
EditorParameters editorParameters = new EditorParameters();
ParamsWrapper parameters = new ParamsWrapper
{

View File

@@ -0,0 +1,78 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Text.Json;
using static FancyZonesEditorCommon.Data.AppZoneHistory.AppZoneHistoryWrapper;
using static FancyZonesEditorCommon.Data.CustomLayouts;
namespace FancyZonesEditorCommon.Data
{
public class AppZoneHistory : EditorData<AppZoneHistory.AppZoneHistoryListWrapper>
{
public string File
{
get
{
return GetDataFolder() + "\\Microsoft\\PowerToys\\FancyZones\\app-zone-history.json";
}
}
public struct AppZoneHistoryWrapper
{
public struct ZoneHistoryWrapper
{
public int[][] ZoneIndexSet { get; set; }
public DeviceIdWrapper Device { get; set; }
public string ZonesetUuid { get; set; }
}
public struct DeviceIdWrapper
{
public string Monitor { get; set; }
public string MonitorInstance { get; set; }
public int MonitorNumber { get; set; }
public string SerialNumber { get; set; }
public string VirtualDesktop { get; set; }
}
public string AppPath { get; set; }
public List<ZoneHistoryWrapper> History { get; set; }
}
public struct AppZoneHistoryListWrapper
{
public List<AppZoneHistoryWrapper> AppZoneHistory { get; set; }
}
public JsonElement ToJsonElement(ZoneHistoryWrapper info)
{
string json = JsonSerializer.Serialize(info, this.JsonOptions);
return JsonSerializer.Deserialize<JsonElement>(json);
}
public JsonElement ToJsonElement(DeviceIdWrapper info)
{
string json = JsonSerializer.Serialize(info, this.JsonOptions);
return JsonSerializer.Deserialize<JsonElement>(json);
}
public ZoneHistoryWrapper ZoneHistoryFromJsonElement(string json)
{
return JsonSerializer.Deserialize<ZoneHistoryWrapper>(json, this.JsonOptions);
}
public DeviceIdWrapper GridFromJsonElement(string json)
{
return JsonSerializer.Deserialize<DeviceIdWrapper>(json, this.JsonOptions);
}
}
}

View File

@@ -20,6 +20,8 @@ namespace Microsoft.FancyZonesEditor.UITests.Utils
public IOTestHelper LayoutTemplatesIOHelper { get; }
public IOTestHelper AppZoneHistoryIOHelper { get; }
public FancyZonesEditorFiles()
{
ParamsIOHelper = new IOTestHelper(new EditorParameters().File);
@@ -28,6 +30,7 @@ namespace Microsoft.FancyZonesEditor.UITests.Utils
DefaultLayoutsIOHelper = new IOTestHelper(new DefaultLayouts().File);
LayoutHotkeysIOHelper = new IOTestHelper(new LayoutHotkeys().File);
LayoutTemplatesIOHelper = new IOTestHelper(new LayoutTemplates().File);
AppZoneHistoryIOHelper = new IOTestHelper(new AppZoneHistory().File);
}
public void Restore()
@@ -38,6 +41,7 @@ namespace Microsoft.FancyZonesEditor.UITests.Utils
DefaultLayoutsIOHelper.RestoreData();
LayoutHotkeysIOHelper.RestoreData();
LayoutTemplatesIOHelper.RestoreData();
AppZoneHistoryIOHelper.RestoreData();
}
}
}

View File

@@ -70,6 +70,12 @@ namespace Microsoft.FancyZonesEditor.UITests.Utils
}
}
// For get app zone history data
public string GetData()
{
return ReadFile(_file);
}
private string ReadFile(string fileName)
{
var attempts = 0;

View File

@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.PowerToys.Run.Plugin.TimeDate.Components;
@@ -23,7 +24,7 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.UnitTests
var result = settings?.Length;
// Assert
Assert.AreEqual(6, result);
Assert.AreEqual(7, result);
}
[DataTestMethod]
@@ -33,6 +34,7 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.UnitTests
[DataRow("TimeWithSeconds")]
[DataRow("DateWithWeekday")]
[DataRow("HideNumberMessageOnGlobalQuery")]
[DataRow("CustomFormats")]
public void DoesSettingExist(string name)
{
// Setup
@@ -78,5 +80,20 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.UnitTests
// Assert
Assert.AreEqual(valueExpected, result);
}
[DataTestMethod]
[DataRow("CustomFormats")]
public void DefaultEmptyMultilineTextValues(string name)
{
// Setup
TimeDateSettings setting = TimeDateSettings.Instance;
// Act
PropertyInfo propertyInfo = setting?.GetType()?.GetProperty(name, BindingFlags.NonPublic | BindingFlags.Instance);
List<string> result = (List<string>)propertyInfo?.GetValue(setting);
// Assert
Assert.AreEqual(0, result.Count);
}
}
}

View File

@@ -54,11 +54,11 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.UnitTests
[DataTestMethod]
[DataRow("(time", 18)]
[DataRow("(date", 26)]
[DataRow("(year", 7)]
[DataRow("(now", 32)]
[DataRow("(current", 32)]
[DataRow("(", 32)]
[DataRow("(date", 28)]
[DataRow("(year", 8)]
[DataRow("(now", 34)]
[DataRow("(current", 34)]
[DataRow("(", 34)]
[DataRow("(now::10:10:10", 1)] // Windows file time
[DataRow("(current::10:10:10", 0)]
public void CountWithPluginKeyword(string typedString, int expectedResultCount)
@@ -140,6 +140,8 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.UnitTests
[DataRow("(week day", "Day of the week (Week day) -")]
[DataRow("(cal week", "Week of the year (Calendar week, Week number) -")]
[DataRow("(week num", "Week of the year (Calendar week, Week number) -")]
[DataRow("(days in mo", "Days in month -")]
[DataRow("(Leap y", "Leap year -")]
public void CanFindFormatResult(string typedString, string expectedResult)
{
// Setup

View File

@@ -41,10 +41,29 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.UnitTests
[DataRow("ums-10456", true, "", "")] // Value is UTC and can be different based on system
[DataRow("ums+10456", true, "", "")] // Value is UTC and can be different based on system
[DataRow("ft10456", true, "", "")] // Value is UTC and can be different based on system
[DataRow("oa-657434.99999999", true, "G", "1/1/0100 11:59:59 PM")]
[DataRow("oa2958465.99999999", true, "G", "12/31/9999 11:59:59 PM")]
[DataRow("oa-657435", false, "", "")] // Value to low
[DataRow("oa2958466", false, "", "")] // Value to large
[DataRow("exc1.99998843", true, "G", "1/1/1900 11:59:59 PM")]
[DataRow("exc59.99998843", true, "G", "2/28/1900 11:59:59 PM")]
[DataRow("exc61", true, "G", "3/1/1900 12:00:00 AM")]
[DataRow("exc62.99998843", true, "G", "3/2/1900 11:59:59 PM")]
[DataRow("exc2958465.99998843", true, "G", "12/31/9999 11:59:59 PM")]
[DataRow("exc0", false, "", "")] // Day 0 means in Excel 0/1/1900 and this is a fake date.
[DataRow("exc0.99998843", false, "", "")] // Day 0 means in Excel 0/1/1900 and this is a fake date.
[DataRow("exc60.99998843", false, "", "")] // Day 60 means in Excel 2/29/1900 and this is a fake date in Excel which we cannot support.
[DataRow("exc60", false, "", "")] // Day 60 means in Excel 2/29/1900 and this is a fake date in Excel which we cannot support.
[DataRow("exc-1", false, "", "")] // Value to low
[DataRow("exc2958466", false, "", "")] // Value to large
[DataRow("exf0.99998843", true, "G", "1/1/1904 11:59:59 PM")]
[DataRow("exf2957003.99998843", true, "G", "12/31/9999 11:59:59 PM")]
[DataRow("exf-0.5", false, "", "")] // Value to low
[DataRow("exf2957004", false, "", "")] // Value to large
public void ConvertStringToDateTime(string typedString, bool expectedBool, string stringType, string expectedString)
{
// Act
bool boolResult = TimeAndDateHelper.ParseStringAsDateTime(in typedString, out DateTime result);
bool boolResult = TimeAndDateHelper.ParseStringAsDateTime(in typedString, out DateTime result, out string _);
// Assert
Assert.AreEqual(expectedBool, boolResult);

View File

@@ -13,6 +13,19 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.UnitTests
[TestClass]
public class TimeAndDateHelperTests
{
private CultureInfo originalCulture;
private CultureInfo originalUiCulture;
[TestInitialize]
public void Setup()
{
// Set culture to 'en-us'
originalCulture = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = new CultureInfo("en-us", false);
originalUiCulture = CultureInfo.CurrentUICulture;
CultureInfo.CurrentUICulture = new CultureInfo("en-us", false);
}
[DataTestMethod]
[DataRow(-1, null)] // default setting
[DataRow(0, CalendarWeekRule.FirstDay)]
@@ -62,5 +75,103 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.UnitTests
Assert.AreEqual(valueExpected, result);
}
}
[DataTestMethod]
[DataRow(0, "12/30/1899 12:00 PM", 0.5)] // OLE Automation date
[DataRow(1, "12/31/1898 12:00 PM", null)] // Excel based 1900: Date to low
[DataRow(1, "1/1/1900, 00:00 AM", 1.0)] // Excel based 1900
[DataRow(2, "12/31/1898 12:00 PM", null)] // Excel based 1904: Date to low
[DataRow(2, "1/1/1904, 00:00 AM", 0.0)] // Excel based 1904
public void ConvertToOADateFormat(int type, string date, double? valueExpected)
{
// Act
DateTime dt = DateTime.Parse(date, DateTimeFormatInfo.CurrentInfo);
// Assert
if (valueExpected == null)
{
Assert.ThrowsException<ArgumentOutOfRangeException>(() => TimeAndDateHelper.ConvertToOleAutomationFormat(dt, (OADateFormats)type));
}
else
{
var result = TimeAndDateHelper.ConvertToOleAutomationFormat(dt, (OADateFormats)type);
Assert.AreEqual(valueExpected, result);
}
}
[DataTestMethod]
[DataRow("dow")]
[DataRow("\\DOW")]
[DataRow("wom")]
[DataRow("\\WOM")]
[DataRow("woy")]
[DataRow("\\WOY")]
[DataRow("eab")]
[DataRow("\\EAB")]
[DataRow("wft")]
[DataRow("\\WFT")]
[DataRow("uxt")]
[DataRow("\\UXT")]
[DataRow("ums")]
[DataRow("\\UMS")]
[DataRow("oad")]
[DataRow("\\OAD")]
[DataRow("exc")]
[DataRow("\\EXC")]
[DataRow("exf")]
[DataRow("\\EXF")]
[DataRow("My super Test String with \\EXC pattern.")]
public void CustomFormatIgnoreInvalidPattern(string format)
{
// Act
string result = TimeAndDateHelper.ConvertToCustomFormat(DateTime.Now, 0, 0, 1, "AD", format, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
// Assert
Assert.AreEqual(format, result);
}
[DataTestMethod]
[DataRow("DOW")]
[DataRow("DIM")]
[DataRow("WOM")]
[DataRow("WOY")]
[DataRow("EAB")]
[DataRow("WFT")]
[DataRow("UXT")]
[DataRow("UMS")]
[DataRow("OAD")]
[DataRow("EXC")]
[DataRow("EXF")]
public void CustomFormatReplacesValidPattern(string format)
{
// Act
string result = TimeAndDateHelper.ConvertToCustomFormat(DateTime.Now, 0, 0, 1, "AD", format, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
// Assert
Assert.IsFalse(result.Contains(format, StringComparison.CurrentCulture));
}
[DataTestMethod]
[DataRow("01/01/0001", 1)] // First possible date
[DataRow("12/31/9999", 5)] // Last possible date
[DataRow("03/20/2025", 4)]
[DataRow("09/01/2025", 1)] // First day in month is first day of week
[DataRow("03/03/2025", 2)] // First monday is in second week
public void GetWeekOfMonth(string date, int week)
{
// Act
int result = TimeAndDateHelper.GetWeekOfMonth(DateTime.Parse(date, CultureInfo.GetCultureInfo("en-us")), DayOfWeek.Monday);
// Assert
Assert.AreEqual(result, week);
}
[TestCleanup]
public void CleanUp()
{
// Set culture to original value
CultureInfo.CurrentCulture = originalCulture;
CultureInfo.CurrentUICulture = originalUiCulture;
}
}
}

View File

@@ -7,7 +7,7 @@ using System.Runtime.CompilerServices;
namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
{
internal class AvailableResult
internal sealed class AvailableResult
{
/// <summary>
/// Gets or sets the time/date value
@@ -41,6 +41,7 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
ResultIconType.Time => $"Images\\time.{theme}.png",
ResultIconType.Date => $"Images\\calendar.{theme}.png",
ResultIconType.DateTime => $"Images\\timeDate.{theme}.png",
ResultIconType.Error => $"Images\\Warning.{theme}.png",
_ => string.Empty,
};
}
@@ -51,5 +52,6 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
Time,
Date,
DateTime,
Error,
}
}

View File

@@ -6,7 +6,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.PowerToys.Run.Plugin.TimeDate.Properties;
namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
@@ -72,6 +72,86 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
string era = DateTimeFormatInfo.CurrentInfo.GetEraName(calendar.GetEra(dateTimeNow));
string eraShort = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedEraName(calendar.GetEra(dateTimeNow));
// Custom formats
foreach (string f in TimeDateSettings.Instance.CustomFormats)
{
string[] formatParts = f.Split("=", 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
string formatSyntax = formatParts.Length == 2 ? formatParts[1] : string.Empty;
string searchTags = ResultHelper.SelectStringFromResources(isSystemDateTime, "Microsoft_plugin_timedate_SearchTagCustom");
DateTime dtObject = dateTimeNow;
// If Length = 0 then empty string.
if (formatParts.Length >= 1)
{
try
{
// Verify and check input and update search tags
if (formatParts.Length == 1)
{
throw new FormatException("Format syntax part after equal sign is missing.");
}
bool containsCustomSyntax = TimeAndDateHelper.StringContainsCustomFormatSyntax(formatSyntax);
if (formatSyntax.StartsWith("UTC:", StringComparison.InvariantCulture))
{
searchTags = ResultHelper.SelectStringFromResources(isSystemDateTime, "Microsoft_plugin_timedate_SearchTagCustomUtc");
dtObject = dateTimeNowUtc;
}
// Get formated date
var value = TimeAndDateHelper.ConvertToCustomFormat(dtObject, unixTimestamp, unixTimestampMilliseconds, weekOfYear, eraShort, Regex.Replace(formatSyntax, "^UTC:", string.Empty), firstWeekRule, firstDayOfTheWeek);
try
{
value = dtObject.ToString(value, CultureInfo.CurrentCulture);
}
catch
{
if (!containsCustomSyntax)
{
throw;
}
else
{
// Do not fail as we have custom format syntax. Instead fix backslashes.
value = Regex.Replace(value, @"(?<!\\)\\", string.Empty).Replace("\\\\", "\\");
}
}
// Add result
results.Add(new AvailableResult()
{
Value = value,
Label = formatParts[0],
AlternativeSearchTag = searchTags,
IconType = ResultIconType.DateTime,
});
}
catch (ArgumentOutOfRangeException e)
{
Wox.Plugin.Logger.Log.Exception($"Failed to convert into custom format {formatParts[0]}: {formatSyntax}", e, typeof(AvailableResultsList));
results.Add(new AvailableResult()
{
Value = Resources.Microsoft_plugin_timedate_ErrorConvertCustomFormat + " " + e.Message,
Label = formatParts[0],
AlternativeSearchTag = searchTags,
IconType = ResultIconType.Error,
});
}
catch (Exception e)
{
Wox.Plugin.Logger.Log.Exception($"Failed to convert into custom format {formatParts[0]}: {formatSyntax}", e, typeof(AvailableResultsList));
results.Add(new AvailableResult()
{
Value = Resources.Microsoft_plugin_timedate_InvalidCustomFormat + " " + formatSyntax,
Label = formatParts[0],
AlternativeSearchTag = searchTags,
IconType = ResultIconType.Error,
});
}
}
}
// Predefined formats
results.AddRange(new[]
{
new AvailableResult()
@@ -152,6 +232,13 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
IconType = ResultIconType.Date,
},
new AvailableResult()
{
Value = DateTime.DaysInMonth(dateTimeNow.Year, dateTimeNow.Month).ToString(CultureInfo.CurrentCulture),
Label = Resources.Microsoft_plugin_timedate_DaysInMonth,
AlternativeSearchTag = ResultHelper.SelectStringFromResources(isSystemDateTime, "Microsoft_plugin_timedate_SearchTagDate"),
IconType = ResultIconType.Date,
},
new AvailableResult()
{
Value = dateTimeNow.DayOfYear.ToString(CultureInfo.CurrentCulture),
Label = Resources.Microsoft_plugin_timedate_DayOfYear,
@@ -201,6 +288,13 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
IconType = ResultIconType.Date,
},
new AvailableResult()
{
Value = DateTime.IsLeapYear(dateTimeNow.Year) ? Resources.Microsoft_plugin_timedate_LeapYear : Resources.Microsoft_plugin_timedate_NoLeapYear,
Label = Resources.Microsoft_plugin_timedate_LeapYear,
AlternativeSearchTag = ResultHelper.SelectStringFromResources(isSystemDateTime, "Microsoft_plugin_timedate_SearchTagDate"),
IconType = ResultIconType.Date,
},
new AvailableResult()
{
Value = era,
Label = Resources.Microsoft_plugin_timedate_Era,
@@ -221,13 +315,31 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
AlternativeSearchTag = ResultHelper.SelectStringFromResources(isSystemDateTime, "Microsoft_plugin_timedate_SearchTagDate"),
IconType = ResultIconType.Date,
},
new AvailableResult()
});
try
{
results.Add(new AvailableResult()
{
Value = dateTimeNow.ToFileTime().ToString(CultureInfo.CurrentCulture),
Label = Resources.Microsoft_plugin_timedate_WindowsFileTime,
AlternativeSearchTag = ResultHelper.SelectStringFromResources(isSystemDateTime, "Microsoft_plugin_timedate_SearchTagFormat"),
IconType = ResultIconType.DateTime,
},
});
}
catch
{
results.Add(new AvailableResult()
{
Value = Resources.Microsoft_plugin_timedate_ErrorConvertWft,
Label = Resources.Microsoft_plugin_timedate_WindowsFileTime,
AlternativeSearchTag = ResultHelper.SelectStringFromResources(isSystemDateTime, "Microsoft_plugin_timedate_SearchTagFormat"),
IconType = ResultIconType.Error,
});
}
results.AddRange(new[]
{
new AvailableResult()
{
Value = dateTimeNowUtc.ToString("u"),

View File

@@ -83,10 +83,10 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
/// Gets a result with an error message that only numbers can't be parsed
/// </summary>
/// <returns>Element of type <see cref="Result"/>.</returns>
internal static Result CreateNumberErrorResult(string theme) => new Result()
internal static Result CreateNumberErrorResult(string theme, string title, string subtitle) => new Result()
{
Title = Resources.Microsoft_plugin_timedate_ErrorResultTitle,
SubTitle = Resources.Microsoft_plugin_timedate_ErrorResultSubTitle,
Title = title,
SubTitle = subtitle,
ToolTipData = new ToolTipData(Resources.Microsoft_plugin_timedate_ErrorResultTitle, Resources.Microsoft_plugin_timedate_ErrorResultSubTitle),
IcoPath = $"Images\\Warning.{theme}.png",
};

View File

@@ -40,9 +40,12 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
List<AvailableResult> availableFormats = new List<AvailableResult>();
List<Result> results = new List<Result>();
bool isKeywordSearch = !string.IsNullOrEmpty(query.ActionKeyword);
bool isEmptySearchInput = string.IsNullOrEmpty(query.Search);
bool isEmptySearchInput = string.IsNullOrWhiteSpace(query.Search);
string searchTerm = query.Search;
// Last input parsing error
string lastInputParsingErrorReason = string.Empty;
// Conjunction search without keyword => return no results
// (This improves the results on global queries.)
if (!isKeywordSearch && _conjunctionList.Any(x => x.Equals(searchTerm, StringComparison.CurrentCultureIgnoreCase)))
@@ -61,13 +64,13 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
{
// Search for specified format with specified time/date value
var userInput = searchTerm.Split(InputDelimiter);
if (TimeAndDateHelper.ParseStringAsDateTime(userInput[1], out DateTime timestamp))
if (TimeAndDateHelper.ParseStringAsDateTime(userInput[1], out DateTime timestamp, out lastInputParsingErrorReason))
{
availableFormats.AddRange(AvailableResultsList.GetList(isKeywordSearch, null, null, timestamp));
searchTerm = userInput[0];
}
}
else if (TimeAndDateHelper.ParseStringAsDateTime(searchTerm, out DateTime timestamp))
else if (TimeAndDateHelper.ParseStringAsDateTime(searchTerm, out DateTime timestamp, out lastInputParsingErrorReason))
{
// Return all formats for specified time/date value
availableFormats.AddRange(AvailableResultsList.GetList(isKeywordSearch, null, null, timestamp));
@@ -122,12 +125,15 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
}
// If search term is only a number that can't be parsed return an error message
if (!isEmptySearchInput && results.Count == 0 && Regex.IsMatch(searchTerm, @"\w+\d+.*$") && !searchTerm.Any(char.IsWhiteSpace) && (TimeAndDateHelper.IsSpecialInputParsing(searchTerm) || !Regex.IsMatch(searchTerm, @"\d+[\.:/]\d+")))
if (!isEmptySearchInput && results.Count == 0 && Regex.IsMatch(searchTerm, @"\w+[+-]?\d+.*$") && !searchTerm.Any(char.IsWhiteSpace) && (TimeAndDateHelper.IsSpecialInputParsing(searchTerm) || !Regex.IsMatch(searchTerm, @"\d+[\.:/]\d+")))
{
// Without plugin key word show only if message is not hidden by setting
string title = !string.IsNullOrEmpty(lastInputParsingErrorReason) ? Resources.Microsoft_plugin_timedate_ErrorResultValue : Resources.Microsoft_plugin_timedate_ErrorResultTitle;
string message = !string.IsNullOrEmpty(lastInputParsingErrorReason) ? lastInputParsingErrorReason : Resources.Microsoft_plugin_timedate_ErrorResultSubTitle;
// Without plugin key word show only if not hidden by setting
if (isKeywordSearch || !TimeDateSettings.Instance.HideNumberMessageOnGlobalQuery)
{
results.Add(ResultHelper.CreateNumberErrorResult(iconTheme));
results.Add(ResultHelper.CreateNumberErrorResult(iconTheme, title, message));
}
}

View File

@@ -5,7 +5,9 @@
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.PowerToys.Run.Plugin.TimeDate.Properties;
[assembly: InternalsVisibleTo("Microsoft.PowerToys.Run.Plugin.TimeDate.UnitTests")]
@@ -13,6 +15,33 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
{
internal static class TimeAndDateHelper
{
private static readonly Regex _regexSpecialInputFormats = new Regex(@"^.*(::)?(u|ums|ft|oa|exc|exf)[+-]\d");
private static readonly Regex _regexCustomDateTimeFormats = new Regex(@"(?<!\\)(DOW|DIM|WOM|WOY|EAB|WFT|UXT|UMS|OAD|EXC|EXF)");
private static readonly Regex _regexCustomDateTimeDow = new Regex(@"(?<!\\)DOW");
private static readonly Regex _regexCustomDateTimeDim = new Regex(@"(?<!\\)DIM");
private static readonly Regex _regexCustomDateTimeWom = new Regex(@"(?<!\\)WOM");
private static readonly Regex _regexCustomDateTimeWoy = new Regex(@"(?<!\\)WOY");
private static readonly Regex _regexCustomDateTimeEab = new Regex(@"(?<!\\)EAB");
private static readonly Regex _regexCustomDateTimeWft = new Regex(@"(?<!\\)WFT");
private static readonly Regex _regexCustomDateTimeUxt = new Regex(@"(?<!\\)UXT");
private static readonly Regex _regexCustomDateTimeUms = new Regex(@"(?<!\\)UMS");
private static readonly Regex _regexCustomDateTimeOad = new Regex(@"(?<!\\)OAD");
private static readonly Regex _regexCustomDateTimeExc = new Regex(@"(?<!\\)EXC");
private static readonly Regex _regexCustomDateTimeExf = new Regex(@"(?<!\\)EXF");
private const long UnixTimeSecondsMin = -62135596800;
private const long UnixTimeSecondsMax = 253402300799;
private const long UnixTimeMillisecondsMin = -62135596800000;
private const long UnixTimeMillisecondsMax = 253402300799999;
private const long WindowsFileTimeMin = 0;
private const long WindowsFileTimeMax = 2650467707991000000;
private const double OADateMin = -657434.99999999;
private const double OADateMax = 2958465.99999999;
private const double Excel1900DateMin = 1;
private const double Excel1900DateMax = 2958465.99998843;
private const double Excel1904DateMin = 0;
private const double Excel1904DateMax = 2957003.99998843;
/// <summary>
/// Get the format for the time string
/// </summary>
@@ -56,18 +85,25 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
/// Returns the number week in the month (Used code from 'David Morton' from <see href="https://social.msdn.microsoft.com/Forums/vstudio/bf504bba-85cb-492d-a8f7-4ccabdf882cb/get-week-number-for-month"/>)
/// </summary>
/// <param name="date">date</param>
/// <param name="formatSettingFirstDayOfWeek">Setting for the first day in the week.</param>
/// <returns>Number of week in the month</returns>
internal static int GetWeekOfMonth(DateTime date, DayOfWeek formatSettingFirstDayOfWeek)
{
DateTime beginningOfMonth = new DateTime(date.Year, date.Month, 1);
int adjustment = 1; // We count from 1 to 7 and not from 0 to 6
int weekCount = 1;
while (date.Date.AddDays(1).DayOfWeek != formatSettingFirstDayOfWeek)
for (int i = 1; i <= date.Day; i++)
{
date = date.AddDays(1);
DateTime d = new(date.Year, date.Month, i);
// Count week number +1 if day is the first day of a week and not day 1 of the month.
// (If we count on day one of a month we would start the month with week number 2.)
if (i > 1 && d.DayOfWeek == formatSettingFirstDayOfWeek)
{
weekCount += 1;
}
}
return (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays / 7f) + adjustment;
return weekCount;
}
/// <summary>
@@ -83,40 +119,170 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
return ((date.DayOfWeek + daysInWeek - formatSettingFirstDayOfWeek) % daysInWeek) + adjustment;
}
internal static double ConvertToOleAutomationFormat(DateTime date, OADateFormats type)
{
double v = date.ToOADate();
switch (type)
{
case OADateFormats.Excel1904:
// Excel with base 1904: Adjust by -1462
v -= 1462;
// Date starts at 1/1/1904 = 0
if (Math.Truncate(v) < 0)
{
throw new ArgumentOutOfRangeException("Not a valid Excel date.", innerException: null);
}
return v;
case OADateFormats.Excel1900:
// Excel with base 1900: Adjust by -1 if v < 61
v = v < 61 ? v - 1 : v;
// Date starts at 1/1/1900 = 1
if (Math.Truncate(v) < 1)
{
throw new ArgumentOutOfRangeException("Not a valid Excel date.", innerException: null);
}
return v;
default:
// OLE Automation date: Return as is.
return v;
}
}
/// <summary>
/// Convert input string to a <see cref="DateTime"/> object in local time
/// </summary>
/// <param name="input">String with date/time</param>
/// <param name="timestamp">The new <see cref="DateTime"/> object</param>
/// <param name="inputParsingErrorMsg">Error message shown to the user</param>
/// <returns>True on success, otherwise false</returns>
internal static bool ParseStringAsDateTime(in string input, out DateTime timestamp)
internal static bool ParseStringAsDateTime(in string input, out DateTime timestamp, out string inputParsingErrorMsg)
{
inputParsingErrorMsg = string.Empty;
CompositeFormat errorMessage = CompositeFormat.Parse(Resources.Microsoft_plugin_timedate_InvalidInput_SupportedRange);
if (DateTime.TryParse(input, out timestamp))
{
// Known date/time format
return true;
}
else if (Regex.IsMatch(input, @"^u[\+-]?\d{1,10}$") && long.TryParse(input.TrimStart('u'), out long secondsU))
else if (Regex.IsMatch(input, @"^u[\+-]?\d+$"))
{
// Unix time stamp
// We use long instead of int, because int is too small after 03:14:07 UTC 2038-01-19
var canParse = long.TryParse(input.TrimStart('u'), out var secondsU);
// Value has to be in the range from -62135596800 to 253402300799
if (!canParse || secondsU < UnixTimeSecondsMin || secondsU > UnixTimeSecondsMax)
{
inputParsingErrorMsg = string.Format(CultureInfo.CurrentCulture, errorMessage, Resources.Microsoft_plugin_timedate_Unix, UnixTimeSecondsMin, UnixTimeSecondsMax);
timestamp = new DateTime(1, 1, 1, 1, 1, 1);
return false;
}
timestamp = DateTimeOffset.FromUnixTimeSeconds(secondsU).LocalDateTime;
return true;
}
else if (Regex.IsMatch(input, @"^ums[\+-]?\d{1,13}$") && long.TryParse(input.TrimStart("ums".ToCharArray()), out long millisecondsUms))
else if (Regex.IsMatch(input, @"^ums[\+-]?\d+$"))
{
// Unix time stamp in milliseconds
// We use long instead of int because int is too small after 03:14:07 UTC 2038-01-19
var canParse = long.TryParse(input.TrimStart("ums".ToCharArray()), out var millisecondsUms);
// Value has to be in the range from -62135596800000 to 253402300799999
if (!canParse || millisecondsUms < UnixTimeMillisecondsMin || millisecondsUms > UnixTimeMillisecondsMax)
{
inputParsingErrorMsg = string.Format(CultureInfo.CurrentCulture, errorMessage, Resources.Microsoft_plugin_timedate_Unix_Milliseconds, UnixTimeMillisecondsMin, UnixTimeMillisecondsMax);
timestamp = new DateTime(1, 1, 1, 1, 1, 1);
return false;
}
timestamp = DateTimeOffset.FromUnixTimeMilliseconds(millisecondsUms).LocalDateTime;
return true;
}
else if (Regex.IsMatch(input, @"^ft\d+$") && long.TryParse(input.TrimStart("ft".ToCharArray()), out long secondsFt))
else if (Regex.IsMatch(input, @"^ft\d+$"))
{
var canParse = long.TryParse(input.TrimStart("ft".ToCharArray()), out var secondsFt);
// Windows file time
// Value has to be in the range from 0 to 2650467707991000000
if (!canParse || secondsFt < WindowsFileTimeMin || secondsFt > WindowsFileTimeMax)
{
inputParsingErrorMsg = string.Format(CultureInfo.CurrentCulture, errorMessage, Resources.Microsoft_plugin_timedate_WindowsFileTime, WindowsFileTimeMin, WindowsFileTimeMax);
timestamp = new DateTime(1, 1, 1, 1, 1, 1);
return false;
}
// DateTime.FromFileTime returns as local time.
timestamp = DateTime.FromFileTime(secondsFt);
return true;
}
else if (Regex.IsMatch(input, @"^oa[+-]?\d+[,.0-9]*$"))
{
var canParse = double.TryParse(input.TrimStart("oa".ToCharArray()), out var oADate);
// OLE Automation date
// Input has to be in the range from -657434.99999999 to 2958465.99999999
// DateTime.FromOADate returns as local time.
if (!canParse || oADate < OADateMin || oADate > OADateMax)
{
inputParsingErrorMsg = string.Format(CultureInfo.CurrentCulture, errorMessage, Resources.Microsoft_plugin_timedate_OADate, OADateMin, OADateMax);
timestamp = new DateTime(1, 1, 1, 1, 1, 1);
return false;
}
timestamp = DateTime.FromOADate(oADate);
return true;
}
else if (Regex.IsMatch(input, @"^exc[+-]?\d+[,.0-9]*$"))
{
var canParse = double.TryParse(input.TrimStart("exc".ToCharArray()), out var excDate);
// Excel's 1900 date value
// Input has to be in the range from 1 (0 = Fake date) to 2958465.99998843 and not 60 whole number
// Because of a bug in Excel and the way it behaves before 3/1/1900 we have to adjust all inputs lower than 61 for +1
// DateTime.FromOADate returns as local time.
if (!canParse || excDate < 0 || excDate > Excel1900DateMax)
{
// For the if itself we use 0 as min value that we can show a special message if input is 0.
inputParsingErrorMsg = string.Format(CultureInfo.CurrentCulture, errorMessage, Resources.Microsoft_plugin_timedate_Excel1900, Excel1900DateMin, Excel1900DateMax);
timestamp = new DateTime(1, 1, 1, 1, 1, 1);
return false;
}
if (Math.Truncate(excDate) == 0 || Math.Truncate(excDate) == 60)
{
inputParsingErrorMsg = Resources.Microsoft_plugin_timedate_InvalidInput_FakeExcel1900;
timestamp = new DateTime(1, 1, 1, 1, 1, 1);
return false;
}
excDate = excDate <= 60 ? excDate + 1 : excDate;
timestamp = DateTime.FromOADate(excDate);
return true;
}
else if (Regex.IsMatch(input, @"^exf[+-]?\d+[,.0-9]*$"))
{
var canParse = double.TryParse(input.TrimStart("exf".ToCharArray()), out var exfDate);
// Excel's 1904 date value
// Input has to be in the range from 0 to 2957003.99998843
// Because Excel uses 01/01/1904 as base we need to adjust for +1462
// DateTime.FromOADate returns as local time.
if (!canParse || exfDate < Excel1904DateMin || exfDate > Excel1904DateMax)
{
inputParsingErrorMsg = string.Format(CultureInfo.CurrentCulture, errorMessage, Resources.Microsoft_plugin_timedate_Excel1904, Excel1904DateMin, Excel1904DateMax);
timestamp = new DateTime(1, 1, 1, 1, 1, 1);
return false;
}
timestamp = DateTime.FromOADate(exfDate + 1462);
return true;
}
else
{
timestamp = new DateTime(1, 1, 1, 1, 1, 1);
@@ -125,13 +291,85 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
}
/// <summary>
/// Test if input is special parsing for Unix time, Unix time in milliseconds or File time.
/// Test if input is special parsing for Unix time, Unix time in milliseconds, file time, ...
/// </summary>
/// <param name="input">String with date/time</param>
/// <returns>True if yes, otherwise false</returns>
internal static bool IsSpecialInputParsing(string input)
{
return Regex.IsMatch(input, @"^.*(u|ums|ft)\d");
return _regexSpecialInputFormats.IsMatch(input);
}
/// <summary>
/// Converts a DateTime object based on the format string
/// </summary>
/// <param name="date">Date/time object.</param>
/// <param name="unix">Value for replacing "Unix Time Stamp".</param>
/// <param name="unixMilliseconds">Value for replacing "Unix Time Stamp in milliseconds".</param>
/// <param name="calWeek">Value for relacing calendar week.</param>
/// <param name="eraShortFormat">Era abbreviation.</param>
/// <param name="format">Format definition.</param>
/// <returns>Formated date/time string.</returns>
internal static string ConvertToCustomFormat(DateTime date, long unix, long unixMilliseconds, int calWeek, string eraShortFormat, string format, CalendarWeekRule firstWeekRule, DayOfWeek firstDayOfTheWeek)
{
string result = format;
// DOW: Number of day in week
result = _regexCustomDateTimeDow.Replace(result, GetNumberOfDayInWeek(date, firstDayOfTheWeek).ToString(CultureInfo.CurrentCulture));
// DIM: Days in Month
result = _regexCustomDateTimeDim.Replace(result, DateTime.DaysInMonth(date.Year, date.Month).ToString(CultureInfo.CurrentCulture));
// WOM: Week of Month
result = _regexCustomDateTimeWom.Replace(result, GetWeekOfMonth(date, firstDayOfTheWeek).ToString(CultureInfo.CurrentCulture));
// WOY: Week of Year
result = _regexCustomDateTimeWoy.Replace(result, calWeek.ToString(CultureInfo.CurrentCulture));
// EAB: Era abbreviation
result = _regexCustomDateTimeEab.Replace(result, eraShortFormat);
// WFT: Week of Month
if (_regexCustomDateTimeWft.IsMatch(result))
{
// Special handling as very early dates can't convert.
result = _regexCustomDateTimeWft.Replace(result, date.ToFileTime().ToString(CultureInfo.CurrentCulture));
}
// UXT: Unix time stamp
result = _regexCustomDateTimeUxt.Replace(result, unix.ToString(CultureInfo.CurrentCulture));
// UMS: Unix time stamp milli seconds
result = _regexCustomDateTimeUms.Replace(result, unixMilliseconds.ToString(CultureInfo.CurrentCulture));
// OAD: OLE Automation date
result = _regexCustomDateTimeOad.Replace(result, ConvertToOleAutomationFormat(date, OADateFormats.OLEAutomation).ToString(CultureInfo.CurrentCulture));
// EXC: Excel date value with base 1900
if (_regexCustomDateTimeExc.IsMatch(result))
{
// Special handling as very early dates can't convert.
result = _regexCustomDateTimeExc.Replace(result, ConvertToOleAutomationFormat(date, OADateFormats.Excel1900).ToString(CultureInfo.CurrentCulture));
}
// EXF: Excel date value with base 1904
if (_regexCustomDateTimeExf.IsMatch(result))
{
// Special handling as very early dates can't convert.
result = _regexCustomDateTimeExf.Replace(result, ConvertToOleAutomationFormat(date, OADateFormats.Excel1904).ToString(CultureInfo.CurrentCulture));
}
return result;
}
/// <summary>
/// Test a string for our custom date and time format syntax
/// </summary>
/// <param name="str">String to test.</param>
/// <returns>True if yes and otherwise false</returns>
internal static bool StringContainsCustomFormatSyntax(string str)
{
return _regexCustomDateTimeFormats.IsMatch(str);
}
/// <summary>
@@ -190,4 +428,14 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
Date,
DateTime,
}
/// <summary>
/// Different versions of Date formats based on OLE Automation date
/// </summary>
internal enum OADateFormats
{
OLEAutomation,
Excel1900,
Excel1904,
}
}

View File

@@ -61,6 +61,11 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
/// </summary>
internal bool HideNumberMessageOnGlobalQuery { get; private set; }
/// <summary>
/// Gets a value containing the custom format definitions
/// </summary>
internal List<string> CustomFormats { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="TimeDateSettings"/> class.
/// Private constructor to make sure there is never more than one instance of this class
@@ -100,29 +105,6 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
{
var optionList = new List<PluginAdditionalOption>
{
new PluginAdditionalOption()
{
Key = nameof(CalendarFirstWeekRule),
DisplayLabel = Resources.Microsoft_plugin_timedate_SettingFirstWeekRule,
DisplayDescription = Resources.Microsoft_plugin_timedate_SettingFirstWeekRule_Description,
PluginOptionType = PluginAdditionalOption.AdditionalOptionType.Combobox,
ComboBoxItems = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>(Resources.Microsoft_plugin_timedate_Setting_UseSystemSetting, "-1"),
new KeyValuePair<string, string>(Resources.Microsoft_plugin_timedate_SettingFirstWeekRule_FirstDay, "0"),
new KeyValuePair<string, string>(Resources.Microsoft_plugin_timedate_SettingFirstWeekRule_FirstFullWeek, "1"),
new KeyValuePair<string, string>(Resources.Microsoft_plugin_timedate_SettingFirstWeekRule_FirstFourDayWeek, "2"),
},
ComboBoxValue = -1,
},
new PluginAdditionalOption()
{
Key = nameof(FirstDayOfWeek),
DisplayLabel = Resources.Microsoft_plugin_timedate_SettingFirstDayOfWeek,
PluginOptionType = PluginAdditionalOption.AdditionalOptionType.Combobox,
ComboBoxItems = GetSortedListForWeekDaySetting(),
ComboBoxValue = -1,
},
new PluginAdditionalOption()
{
Key = nameof(OnlyDateTimeNowGlobal),
@@ -150,6 +132,38 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
DisplayLabel = Resources.Microsoft_plugin_timedate_SettingHideNumberMessageOnGlobalQuery,
Value = false,
},
new PluginAdditionalOption()
{
Key = nameof(CalendarFirstWeekRule),
DisplayLabel = Resources.Microsoft_plugin_timedate_SettingFirstWeekRule,
DisplayDescription = Resources.Microsoft_plugin_timedate_SettingFirstWeekRule_Description,
PluginOptionType = PluginAdditionalOption.AdditionalOptionType.Combobox,
ComboBoxItems = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>(Resources.Microsoft_plugin_timedate_Setting_UseSystemSetting, "-1"),
new KeyValuePair<string, string>(Resources.Microsoft_plugin_timedate_SettingFirstWeekRule_FirstDay, "0"),
new KeyValuePair<string, string>(Resources.Microsoft_plugin_timedate_SettingFirstWeekRule_FirstFullWeek, "1"),
new KeyValuePair<string, string>(Resources.Microsoft_plugin_timedate_SettingFirstWeekRule_FirstFourDayWeek, "2"),
},
ComboBoxValue = -1,
},
new PluginAdditionalOption()
{
Key = nameof(FirstDayOfWeek),
DisplayLabel = Resources.Microsoft_plugin_timedate_SettingFirstDayOfWeek,
PluginOptionType = PluginAdditionalOption.AdditionalOptionType.Combobox,
ComboBoxItems = GetSortedListForWeekDaySetting(),
ComboBoxValue = -1,
},
new PluginAdditionalOption()
{
Key = nameof(CustomFormats),
PluginOptionType = PluginAdditionalOption.AdditionalOptionType.MultilineTextbox,
DisplayLabel = Resources.Microsoft_plugin_timedate_Setting_CustomFormats,
DisplayDescription = string.Format(CultureInfo.CurrentCulture, Resources.Microsoft_plugin_timedate_Setting_CustomFormatsDescription.ToString(), "DOW", "DIM", "WOM", "WOY", "EAB", "WFT", "UXT", "UMS", "OAD", "EXC", "EXF", "UTC:"),
PlaceholderText = "MyFormat=dd-MMM-yyyy\rMySecondFormat=dddd (Da\\y nu\\mber: DOW)\rMyUtcFormat=UTC:hh:mm:ss",
TextValue = string.Empty,
},
};
return optionList;
@@ -172,6 +186,7 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
TimeWithSeconds = GetSettingOrDefault(settings, nameof(TimeWithSeconds));
DateWithWeekday = GetSettingOrDefault(settings, nameof(DateWithWeekday));
HideNumberMessageOnGlobalQuery = GetSettingOrDefault(settings, nameof(HideNumberMessageOnGlobalQuery));
CustomFormats = GetMultilineTextSettingOrDefault(settings, nameof(CustomFormats));
}
/// <summary>
@@ -204,6 +219,21 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Components
return option?.ComboBoxValue ?? GetAdditionalOptions().First(x => x.Key == name).ComboBoxValue;
}
/// <summary>
/// Return the combobox value of the given settings list with the given name.
/// </summary>
/// <param name="settings">The object that contain all settings.</param>
/// <param name="name">The name of the setting.</param>
/// <returns>A settings value.</returns>
private static List<string> GetMultilineTextSettingOrDefault(PowerLauncherPluginSettings settings, string name)
{
var option = settings?.AdditionalOptions?.FirstOrDefault(x => x.Key == name);
// If a setting isn't available, we use the value defined in the method GetAdditionalOptions() as fallback.
// We can use First() instead of FirstOrDefault() because the values must exist. Otherwise, we made a mistake when defining the settings.
return option?.TextValueAsMultilineList ?? GetAdditionalOptions().First(x => x.Key == name).TextValueAsMultilineList;
}
/// <summary>
/// Returns a sorted list of values for the combo box of 'first day of week' setting.
/// The list is sorted based on the current system culture setting.

View File

@@ -150,6 +150,15 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to Days in month.
/// </summary>
internal static string Microsoft_plugin_timedate_DaysInMonth {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_DaysInMonth", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Era.
/// </summary>
@@ -169,7 +178,25 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Properties {
}
/// <summary>
/// Looks up a localized string similar to Valid prefixes: &apos;u&apos; for Unix Timestamp, &apos;ums&apos; for Unix Timestamp in milliseconds, &apos;ft&apos; for Windows file time.
/// Looks up a localized string similar to Failed to convert into custom format:.
/// </summary>
internal static string Microsoft_plugin_timedate_ErrorConvertCustomFormat {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_ErrorConvertCustomFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Not a valid Windows file time.
/// </summary>
internal static string Microsoft_plugin_timedate_ErrorConvertWft {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_ErrorConvertWft", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Valid prefixes: &apos;u&apos; for Unix Timestamp, &apos;ums&apos; for Unix Timestamp in milliseconds, &apos;ft&apos; for Windows file time, &apos;oa&apos; for OLE Automation date, &apos;exc&apos; for Excel&apos;s 1900 date value, &apos;exf&apos; for Excel&apos;s 1904 date value.
/// </summary>
internal static string Microsoft_plugin_timedate_ErrorResultSubTitle {
get {
@@ -178,7 +205,7 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Properties {
}
/// <summary>
/// Looks up a localized string similar to Error: Invalid number input.
/// Looks up a localized string similar to Error: Invalid input.
/// </summary>
internal static string Microsoft_plugin_timedate_ErrorResultTitle {
get {
@@ -186,6 +213,33 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to Error: Invalid number.
/// </summary>
internal static string Microsoft_plugin_timedate_ErrorResultValue {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_ErrorResultValue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Excel&apos;s 1900 date value.
/// </summary>
internal static string Microsoft_plugin_timedate_Excel1900 {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_Excel1900", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Excel&apos;s 1904 date value.
/// </summary>
internal static string Microsoft_plugin_timedate_Excel1904 {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_Excel1904", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Date and time in filename-compatible format.
/// </summary>
@@ -204,6 +258,33 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to Invalid custom format:.
/// </summary>
internal static string Microsoft_plugin_timedate_InvalidCustomFormat {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_InvalidCustomFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot parse the input as Excel&apos;s 1900 date value because it is a fake date. (In Excel 0 stands for 0/1/1900 and this date doesn&apos;t exist. And 60 stands for 2/29/1900 and this date only exists in Excel for compatibility with Lotus 123.).
/// </summary>
internal static string Microsoft_plugin_timedate_InvalidInput_FakeExcel1900 {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_InvalidInput_FakeExcel1900", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Your input for {0} is outside the range from {1} to {2}..
/// </summary>
internal static string Microsoft_plugin_timedate_InvalidInput_SupportedRange {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_InvalidInput_SupportedRange", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ISO 8601.
/// </summary>
@@ -240,6 +321,15 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to Leap year.
/// </summary>
internal static string Microsoft_plugin_timedate_LeapYear {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_LeapYear", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Millisecond.
/// </summary>
@@ -285,6 +375,15 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to Not a leap year.
/// </summary>
internal static string Microsoft_plugin_timedate_NoLeapYear {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_NoLeapYear", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Now.
/// </summary>
@@ -303,6 +402,15 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to OLE Automation Date.
/// </summary>
internal static string Microsoft_plugin_timedate_OADate {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_OADate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Provides time and date values for the system time or a custom time stamp (e.g.&apos;{0}&apos;, &apos;{1}&apos;, &apos;{2}&apos;, &apos;{3}&apos;).
/// </summary>
@@ -366,6 +474,42 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to Date and time; Time and Date; Custom format.
/// </summary>
internal static string Microsoft_plugin_timedate_SearchTagCustom {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_SearchTagCustom", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Current date and time; Current time and date; Now; Custom format.
/// </summary>
internal static string Microsoft_plugin_timedate_SearchTagCustomNow {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_SearchTagCustomNow", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Date and time UTC; Time UTC and Date; Custom UTC format.
/// </summary>
internal static string Microsoft_plugin_timedate_SearchTagCustomUtc {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_SearchTagCustomUtc", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Current date and time UTC; Current time UTC and date; Now UTC; Custom UTC format.
/// </summary>
internal static string Microsoft_plugin_timedate_SearchTagCustomUtcNow {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_SearchTagCustomUtcNow", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Date.
/// </summary>
@@ -447,6 +591,24 @@ namespace Microsoft.PowerToys.Run.Plugin.TimeDate.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to Custom formats.
/// </summary>
internal static string Microsoft_plugin_timedate_Setting_CustomFormats {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_Setting_CustomFormats", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use date and time string format syntax and {0} (Day of Week), {1} (Days in Month), {2} (Week of Month), {3} (Week of the year), {4} (Era abbreviation), {5} (Windows File Time), {6} (Unix Time), {7} (Unix Time in milliseconds), {8} (OLE Automation date), {9} (Excel&apos;s 1900 based date value), {10} (Excel&apos;s 1904 based date value). If the format starts with {11}, then Universal Time (UTC) is used. (Use a backslash to escape format sequences and the backslash character as text.).
/// </summary>
internal static string Microsoft_plugin_timedate_Setting_CustomFormatsDescription {
get {
return ResourceManager.GetString("Microsoft_plugin_timedate_Setting_CustomFormatsDescription", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use system setting.
/// </summary>

View File

@@ -156,10 +156,13 @@
<value>Era abbreviation</value>
</data>
<data name="Microsoft_plugin_timedate_ErrorResultSubTitle" xml:space="preserve">
<value>Valid prefixes: 'u' for Unix Timestamp, 'ums' for Unix Timestamp in milliseconds, 'ft' for Windows file time</value>
<value>Valid prefixes: 'u' for Unix Timestamp, 'ums' for Unix Timestamp in milliseconds, 'ft' for Windows file time, 'oa' for OLE Automation date, 'exc' for Excel's 1900 date value, 'exf' for Excel's 1904 date value</value>
</data>
<data name="Microsoft_plugin_timedate_ErrorResultTitle" xml:space="preserve">
<value>Error: Invalid number input</value>
<value>Error: Invalid input</value>
</data>
<data name="Microsoft_plugin_timedate_ErrorResultValue" xml:space="preserve">
<value>Error: Invalid number</value>
</data>
<data name="Microsoft_plugin_timedate_Hour" xml:space="preserve">
<value>Hour</value>
@@ -243,10 +246,26 @@
<value>Date and time; Time and Date</value>
<comment>Don't change order</comment>
</data>
<data name="Microsoft_plugin_timedate_SearchTagCustom" xml:space="preserve">
<value>Date and time; Time and Date; Custom format</value>
<comment>Don't change order</comment>
</data>
<data name="Microsoft_plugin_timedate_SearchTagCustomUtc" xml:space="preserve">
<value>Date and time UTC; Time UTC and Date; Custom UTC format</value>
<comment>Don't change order</comment>
</data>
<data name="Microsoft_plugin_timedate_SearchTagFormatNow" xml:space="preserve">
<value>Current date and time; Current time and date; Now</value>
<comment>Don't change order</comment>
</data>
<data name="Microsoft_plugin_timedate_SearchTagCustomNow" xml:space="preserve">
<value>Current date and time; Current time and date; Now; Custom format</value>
<comment>Don't change order</comment>
</data>
<data name="Microsoft_plugin_timedate_SearchTagCustomUtcNow" xml:space="preserve">
<value>Current date and time UTC; Current time UTC and date; Now UTC; Custom UTC format</value>
<comment>Don't change order</comment>
</data>
<data name="Microsoft_plugin_timedate_SearchTagTime" xml:space="preserve">
<value>Time</value>
<comment>Don't change order</comment>
@@ -262,6 +281,9 @@
<data name="Microsoft_plugin_timedate_Second" xml:space="preserve">
<value>Second</value>
</data>
<data name="Microsoft_plugin_timedate_InvalidCustomFormat" xml:space="preserve">
<value>Invalid custom format:</value>
</data>
<data name="Microsoft_plugin_timedate_SettingDateWithWeekday" xml:space="preserve">
<value>Show date with weekday and name of month</value>
</data>
@@ -360,4 +382,42 @@
<data name="Microsoft_plugin_timedate_Setting_UseSystemSetting" xml:space="preserve">
<value>Use system setting</value>
</data>
<data name="Microsoft_plugin_timedate_Setting_CustomFormats" xml:space="preserve">
<value>Custom formats</value>
</data>
<data name="Microsoft_plugin_timedate_Setting_CustomFormatsDescription" xml:space="preserve">
<value>Use date and time string format syntax and {0} (Day of Week), {1} (Days in Month), {2} (Week of Month), {3} (Week of the year), {4} (Era abbreviation), {5} (Windows File Time), {6} (Unix Time), {7} (Unix Time in milliseconds), {8} (OLE Automation date), {9} (Excel's 1900 based date value), {10} (Excel's 1904 based date value). If the format starts with {11}, then Universal Time (UTC) is used. (Use a backslash to escape format sequences and the backslash character as text.)</value>
<comment>The {n} parts are place holders and get replaced in the code.</comment>
</data>
<data name="Microsoft_plugin_timedate_ErrorConvertCustomFormat" xml:space="preserve">
<value>Failed to convert into custom format:</value>
</data>
<data name="Microsoft_plugin_timedate_ErrorConvertWft" xml:space="preserve">
<value>Not a valid Windows file time</value>
</data>
<data name="Microsoft_plugin_timedate_InvalidInput_SupportedRange" xml:space="preserve">
<value>Your input for {0} is outside the range from {1} to {2}.</value>
<comment>The placeholder will be replace in code.</comment>
</data>
<data name="Microsoft_plugin_timedate_OADate" xml:space="preserve">
<value>OLE Automation Date</value>
</data>
<data name="Microsoft_plugin_timedate_Excel1900" xml:space="preserve">
<value>Excel's 1900 date value</value>
</data>
<data name="Microsoft_plugin_timedate_InvalidInput_FakeExcel1900" xml:space="preserve">
<value>Cannot parse the input as Excel's 1900 date value because it is a fake date. (In Excel 0 stands for 0/1/1900 and this date doesn't exist. And 60 stands for 2/29/1900 and this date only exists in Excel for compatibility with Lotus 123.)</value>
</data>
<data name="Microsoft_plugin_timedate_Excel1904" xml:space="preserve">
<value>Excel's 1904 date value</value>
</data>
<data name="Microsoft_plugin_timedate_LeapYear" xml:space="preserve">
<value>Leap year</value>
</data>
<data name="Microsoft_plugin_timedate_NoLeapYear" xml:space="preserve">
<value>Not a leap year</value>
</data>
<data name="Microsoft_plugin_timedate_DaysInMonth" xml:space="preserve">
<value>Days in month</value>
</data>
</root>

View File

@@ -295,7 +295,7 @@
"Areas": [ "AreaEaseOfAccess" ],
"Type": "AppSettingsApp",
"AltNames": [ "TouchFeedback" ],
"Command": "ms-settings:easeofaccess-MousePointer"
"Command": "ms-settings:easeofaccess-mousepointer"
},
{
"Name": "Display",

View File

@@ -28,18 +28,15 @@ namespace Microsoft.PowerToys.Settings.UI
var bootTime = new System.Diagnostics.Stopwatch();
bootTime.Start();
this.Activated += Window_Activated_SetIcon;
App.ThemeService.ThemeChanged += OnThemeChanged;
App.ThemeService.ApplyTheme();
ShellPage.SetElevationStatus(App.IsElevated);
ShellPage.SetIsUserAnAdmin(App.IsUserAnAdmin);
// Set window icon
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
WindowId windowId = Win32Interop.GetWindowIdFromWindow(hWnd);
AppWindow appWindow = AppWindow.GetFromWindowId(windowId);
appWindow.SetIcon("Assets\\Settings\\icon.ico");
var placement = WindowHelper.DeserializePlacementOrDefault(hWnd);
if (createHidden)
{
@@ -221,6 +218,15 @@ namespace Microsoft.PowerToys.Settings.UI
App.ThemeService.ThemeChanged -= OnThemeChanged;
}
private void Window_Activated_SetIcon(object sender, WindowActivatedEventArgs args)
{
// Set window icon
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
WindowId windowId = Win32Interop.GetWindowIdFromWindow(hWnd);
AppWindow appWindow = AppWindow.GetFromWindowId(windowId);
appWindow.SetIcon("Assets\\Settings\\icon.ico");
}
private void Window_Activated(object sender, WindowActivatedEventArgs args)
{
if (args.WindowActivationState != WindowActivationState.Deactivated)

View File

@@ -31,7 +31,6 @@ namespace Microsoft.PowerToys.Settings.UI
private WindowId _windowId;
private IntPtr _hWnd;
private AppWindow _appWindow;
private WindowMessageMonitor _msgMonitor;
private bool disposedValue;
public OobeWindow(PowerToysModules initialModule)
@@ -41,15 +40,10 @@ namespace Microsoft.PowerToys.Settings.UI
this.InitializeComponent();
// Set window icon
_hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
_windowId = Win32Interop.GetWindowIdFromWindow(_hWnd);
_appWindow = AppWindow.GetFromWindowId(_windowId);
_appWindow.SetIcon("Assets\\Settings\\icon.ico");
OverlappedPresenter presenter = _appWindow.Presenter as OverlappedPresenter;
presenter.IsMinimizable = false;
presenter.IsMaximizable = false;
this.Activated += Window_Activated_SetIcon;
var dpi = NativeMethods.GetDpiForWindow(_hWnd);
_currentDPI = dpi;
@@ -64,18 +58,6 @@ namespace Microsoft.PowerToys.Settings.UI
this.initialModule = initialModule;
_msgMonitor = new WindowMessageMonitor(this);
_msgMonitor.WindowMessageReceived += (_, e) =>
{
const int WM_NCLBUTTONDBLCLK = 0x00A3;
if (e.Message.MessageId == WM_NCLBUTTONDBLCLK)
{
// Disable double click on title bar to maximize window
e.Result = 0;
e.Handled = true;
}
};
this.SizeChanged += OobeWindow_SizeChanged;
var loader = Helpers.ResourceLoaderInstance.ResourceLoader;
@@ -110,6 +92,12 @@ namespace Microsoft.PowerToys.Settings.UI
}
}
private void Window_Activated_SetIcon(object sender, WindowActivatedEventArgs args)
{
// Set window icon
_appWindow.SetIcon("Assets\\Settings\\icon.ico");
}
private void OobeWindow_SizeChanged(object sender, WindowSizeChangedEventArgs args)
{
var dpi = NativeMethods.GetDpiForWindow(_hWnd);
@@ -149,8 +137,6 @@ namespace Microsoft.PowerToys.Settings.UI
{
if (!disposedValue)
{
_msgMonitor?.Dispose();
disposedValue = true;
}
}