mirror of
https://github.com/microsoft/PowerToys.git
synced 2025-12-30 17:07:23 +01:00
Compare commits
13 Commits
dev/crutka
...
stable-bac
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b545597997 | ||
|
|
b995ffabd7 | ||
|
|
3c439eed55 | ||
|
|
dd33a45aec | ||
|
|
ca6f993be1 | ||
|
|
29687d588f | ||
|
|
6c999c32da | ||
|
|
fd2a3915ef | ||
|
|
4345b95527 | ||
|
|
c0f7ec0265 | ||
|
|
c2d1214974 | ||
|
|
f732185885 | ||
|
|
ad207da3f3 |
17
.github/actions/spell-check/expect.txt
vendored
17
.github/actions/spell-check/expect.txt
vendored
@@ -94,7 +94,6 @@ ASSOCSTR
|
||||
ASYNCWINDOWPLACEMENT
|
||||
ASYNCWINDOWPOS
|
||||
atl
|
||||
ATX
|
||||
ATRIOX
|
||||
aumid
|
||||
Authenticode
|
||||
@@ -114,7 +113,6 @@ azman
|
||||
bbwe
|
||||
BCIE
|
||||
bck
|
||||
backticks
|
||||
BESTEFFORT
|
||||
bezelled
|
||||
bhid
|
||||
@@ -195,7 +193,6 @@ changecursor
|
||||
CHILDACTIVATE
|
||||
CHILDWINDOW
|
||||
CHOOSEFONT
|
||||
CIBUILD
|
||||
cidl
|
||||
CIELCh
|
||||
cim
|
||||
@@ -270,7 +267,6 @@ countof
|
||||
covrun
|
||||
cpcontrols
|
||||
cph
|
||||
cppcoreguidelines
|
||||
cplusplus
|
||||
CPower
|
||||
cpptools
|
||||
@@ -373,7 +369,7 @@ devmgmt
|
||||
DEVMODE
|
||||
DEVMODEW
|
||||
devpal
|
||||
dfx
|
||||
DFX
|
||||
DIALOGEX
|
||||
digicert
|
||||
DINORMAL
|
||||
@@ -387,7 +383,6 @@ DISPLAYFREQUENCY
|
||||
displayname
|
||||
DISPLAYORIENTATION
|
||||
divyan
|
||||
djwsxzxb
|
||||
Dlg
|
||||
DLGFRAME
|
||||
DLGMODALFRAME
|
||||
@@ -448,7 +443,6 @@ EDITSHORTCUTS
|
||||
EDITTEXT
|
||||
EFile
|
||||
ekus
|
||||
eku
|
||||
emojis
|
||||
ENABLEDELAYEDEXPANSION
|
||||
ENABLEDPOPUP
|
||||
@@ -513,7 +507,6 @@ eyetracker
|
||||
FANCYZONESDRAWLAYOUTTEST
|
||||
FANCYZONESEDITOR
|
||||
FARPROC
|
||||
fdx
|
||||
fesf
|
||||
FFFF
|
||||
FILEEXPLORER
|
||||
@@ -642,7 +635,6 @@ Hiber
|
||||
Hiberboot
|
||||
HIBYTE
|
||||
hicon
|
||||
HICONSM
|
||||
HIDEREADONLY
|
||||
HIDEWINDOW
|
||||
Hif
|
||||
@@ -823,7 +815,6 @@ keyvault
|
||||
KILLFOCUS
|
||||
killrunner
|
||||
kmph
|
||||
ksa
|
||||
kvp
|
||||
Kybd
|
||||
LARGEICON
|
||||
@@ -930,7 +921,6 @@ LWA
|
||||
lwin
|
||||
LZero
|
||||
MAGTRANSFORM
|
||||
makeappx
|
||||
MAKEINTRESOURCE
|
||||
MAKEINTRESOURCEA
|
||||
MAKEINTRESOURCEW
|
||||
@@ -1158,7 +1148,6 @@ ntfs
|
||||
NTSTATUS
|
||||
NTSYSAPI
|
||||
NULLCURSOR
|
||||
nullref
|
||||
nullonfailure
|
||||
numberbox
|
||||
nwc
|
||||
@@ -1263,7 +1252,6 @@ pinvoke
|
||||
pipename
|
||||
PKBDLLHOOKSTRUCT
|
||||
pkgfamily
|
||||
PKI
|
||||
plib
|
||||
ploc
|
||||
ploca
|
||||
@@ -1705,7 +1693,6 @@ syskeydown
|
||||
SYSKEYUP
|
||||
SYSLIB
|
||||
SYSMENU
|
||||
systemai
|
||||
SYSTEMAPPS
|
||||
SYSTEMMODAL
|
||||
SYSTEMTIME
|
||||
@@ -1992,7 +1979,7 @@ WORKSPACESEDITOR
|
||||
WORKSPACESLAUNCHER
|
||||
WORKSPACESSNAPSHOTTOOL
|
||||
WORKSPACESWINDOWARRANGER
|
||||
worktree
|
||||
Worktree
|
||||
wox
|
||||
wparam
|
||||
wpf
|
||||
|
||||
64
.github/copilot-instructions.md
vendored
64
.github/copilot-instructions.md
vendored
@@ -1,59 +1,43 @@
|
||||
---
|
||||
description: PowerToys AI contributor guidance.
|
||||
applyTo: pullRequests
|
||||
---
|
||||
|
||||
# PowerToys - Copilot guide (concise)
|
||||
# PowerToys – Copilot guide (concise)
|
||||
|
||||
This is the top-level guide for AI changes. Keep edits small, follow existing patterns, and cite exact paths in PRs.
|
||||
|
||||
# Repo map (1-line per area)
|
||||
Repo map (1‑line per area)
|
||||
- Core apps: `src/runner/**` (tray/loader), `src/settings-ui/**` (Settings app)
|
||||
- Shared libs: `src/common/**`
|
||||
- Modules: `src/modules/*` (one per utility; Command Palette in `src/modules/cmdpal/**`)
|
||||
- Build tools/docs: `tools/**`, `doc/devdocs/**`
|
||||
|
||||
# Build and test (defaults)
|
||||
Build and test (defaults)
|
||||
- Prerequisites: Visual Studio 2022 17.4+, minimal Windows 10 1803+.
|
||||
- Build discipline:
|
||||
- One terminal per operation (build -> test). Do not switch or open new ones mid-flow.
|
||||
- One terminal per operation (build → test). Don’t switch/open new ones mid-flow.
|
||||
- After making changes, `cd` to the project folder that changed (`.csproj`/`.vcxproj`).
|
||||
- Use scripts to build, synchronously block and wait in foreground for completion: `tools/build/build.ps1|.cmd` (current folder), `build-essentials.*` (once per brand new build for missing nuget packages).
|
||||
- Treat build exit code 0 as success; any non-zero exit code is a failure. Read the errors log in the build folder (such as `build.*.*.errors.log`) and surface problems.
|
||||
- Do not start tests or launch Runner until the previous step succeeded.
|
||||
- Tests (fast and targeted):
|
||||
- Find the test project by product code prefix (for example FancyZones, AdvancedPaste). Look for a sibling folder or one to two levels up named like `<Product>*UnitTests` or `<Product>*UITests`.
|
||||
- Build the test project, wait for exit, then run only those tests via VS Test Explorer or `vstest.console.exe` with filters. Avoid `dotnet test` in this repo.
|
||||
- Add or adjust tests when changing behavior; if skipped, state why (for example comment-only or string rename).
|
||||
- Use script(s) to build, synchronously block and wait in foreground for it to finish: `tools/build/build.ps1|.cmd` (current folder), `build-essentials.*` (once per brand new build for missing nuget packages)
|
||||
- Treat build **exit code 0** as success; any non-zero exit code is a failure, have Copilot read the errors log in the build folder (e.g., `build.*.*.errors.log`) and surface problems.
|
||||
- Don’t start tests or launch Runner until the previous step succeeded.
|
||||
- Tests (fast + targeted):
|
||||
- Find the test project by product code prefix (e.g., FancyZones, AdvancedPaste). Look for a sibling folder or 1–2 levels up named like `<Product>*UnitTests` or `<Product>*UITests`.
|
||||
- Build the test project, wait for **exit**, then run only those tests via VS Test Explorer or `vstest.console.exe` with filters. Avoid `dotnet test` in this repo.
|
||||
- Add/adjust tests when changing behavior; if skipped, state why (e.g., comment-only, string rename).
|
||||
|
||||
# Pull requests (expectations)
|
||||
- Atomic: one logical change; no drive-by refactors.
|
||||
- Describe: problem, approach, risk, test evidence.
|
||||
Pull requests (expectations)
|
||||
- Atomic: one logical change; no drive‑by refactors.
|
||||
- Describe: problem / approach / risk / test evidence.
|
||||
- List: touched paths if not obvious.
|
||||
|
||||
# When to ask for clarification
|
||||
When to ask for clarification
|
||||
- Ambiguous spec after scanning relevant docs (see below).
|
||||
- Cross-module impact (shared enum or struct) not clear.
|
||||
- Security, elevation, or installer changes.
|
||||
- Cross-module impact (shared enum/struct) not clear.
|
||||
- Security / elevation / installer changes.
|
||||
|
||||
# Logging (use existing stacks)
|
||||
- C++ logging lives in `src/common/logger/**` (`Logger::info`, `Logger::warn`, `Logger::error`, `Logger::debug`). Keep hot paths quiet (hooks, tight loops).
|
||||
- C# logging goes through `ManagedCommon.Logger` (`LogInfo`, `LogWarning`, `LogError`, `LogDebug`, `LogTrace`). Some UIs use injected `ILogger` via `LoggerInstance.Logger`.
|
||||
Logging (use existing stacks)
|
||||
- C++: `src/common/logger/**` (`Logger::info|warn|error|debug`). Keep hot paths quiet (hooks, tight loops).
|
||||
- C#: `ManagedCommon.Logger` (`LogInfo|LogWarning|LogError|LogDebug|LogTrace`). Some UIs use injected `ILogger` via `LoggerInstance.Logger`.
|
||||
|
||||
# Docs to consult
|
||||
Docs to consult
|
||||
- `tools/build/BUILD-GUIDELINES.md`
|
||||
- `doc/devdocs/core/architecture.md`
|
||||
- `doc/devdocs/core/runner.md`
|
||||
- `doc/devdocs/core/settings/readme.md`
|
||||
- `doc/devdocs/modules/readme.md`
|
||||
- `doc/devdocs/core/architecture.md`, `doc/devdocs/core/runner.md`, `doc/devdocs/core/settings/readme.md`, `doc/devdocs/modules/readme.md`
|
||||
|
||||
# Language style rules
|
||||
- Always enforce repo analyzers: root `.editorconfig` plus any `stylecop.json`.
|
||||
- C# code follows StyleCop.Analyzers and Microsoft.CodeAnalysis.NetAnalyzers.
|
||||
- C++ code honors `.clang-format` plus `.clang-tidy` (modernize/cppcoreguidelines/readability).
|
||||
- Markdown files wrap at 80 characters and use ATX headers with fenced code blocks that include language tags.
|
||||
- YAML files indent two spaces and add comments for complex settings while keeping keys clear.
|
||||
- PowerShell scripts use Verb-Noun names and prefer single-quoted literals while documenting parameters and satisfying PSScriptAnalyzer.
|
||||
|
||||
# Done checklist (self review before finishing)
|
||||
- Build clean? Tests updated or passed? No unintended formatting? Any new dependency? Documented skips?
|
||||
Done checklist (self review before finishing)
|
||||
- Build clean? Tests updated/passed? No unintended formatting? Any new dependency? Documented skips?
|
||||
16
.github/prompts/create-commit-title.prompt.md
vendored
16
.github/prompts/create-commit-title.prompt.md
vendored
@@ -1,16 +0,0 @@
|
||||
---
|
||||
mode: 'agent'
|
||||
model: GPT-5-Codex (Preview)
|
||||
description: 'Generate an 80-character git commit title for the local diff.'
|
||||
---
|
||||
|
||||
**Goal:** Provide a ready-to-paste git commit title (<= 80 characters) that captures the most important local changes since `HEAD`.
|
||||
|
||||
**Workflow:**
|
||||
1. Run a single command to view the local diff since the last commit:
|
||||
```@terminal
|
||||
git diff HEAD
|
||||
```
|
||||
2. From that diff, identify the dominant area (reference key paths like `src/modules/*`, `doc/devdocs/**`, etc.), the type of change (bug fix, docs update, config tweak), and any notable impact.
|
||||
3. Draft a concise, imperative commit title summarizing the dominant change. Keep it plain ASCII, <= 80 characters, and avoid trailing punctuation. Mention the primary component when obvious (for example `FancyZones:` or `Docs:`).
|
||||
4. Respond with only the final commit title on a single line so it can be pasted directly into `git commit`.
|
||||
22
.github/prompts/create-pr-summary.prompt.md
vendored
22
.github/prompts/create-pr-summary.prompt.md
vendored
@@ -1,22 +0,0 @@
|
||||
---
|
||||
mode: 'agent'
|
||||
model: GPT-5-Codex (Preview)
|
||||
description: 'Generate a PowerToys-ready pull request description from the local diff.'
|
||||
---
|
||||
|
||||
**Goal:** Produce a ready-to-paste PR title and description that follows PowerToys conventions by comparing the current branch against a user-selected target branch.
|
||||
|
||||
**Repo guardrails:**
|
||||
- Treat `.github/pull_request_template.md` as the single source of truth; load it at runtime instead of embedding hardcoded content in this prompt.
|
||||
- Preserve section order from the template but only surface checklist lines that are relevant for the detected changes, filling them with `[x]`/`[ ]` as appropriate.
|
||||
- Cite touched paths with inline backticks, matching the guidance in `.github/copilot-instructions.md`.
|
||||
- Call out test coverage explicitly: list automated tests run (unit/UI) or state why they are not applicable.
|
||||
|
||||
**Workflow:**
|
||||
1. Determine the target branch from user context; default to `main` when no branch is supplied.
|
||||
2. Run `git status --short` once to surface uncommitted files that may influence the summary.
|
||||
3. Run `git diff <target-branch>...HEAD` a single time to review the detailed changes. Only when confidence stays low dig deeper with focused calls such as `git diff <target-branch>...HEAD -- <path>`.
|
||||
4. From the diff, capture impacted areas, key file changes, behavioral risks, migrations, and noteworthy edge cases.
|
||||
5. Confirm validation: list tests executed with results or state why tests were skipped in line with repo guidance.
|
||||
6. Load `.github/pull_request_template.md`, mirror its section order, and populate it with the gathered facts. Include only relevant checklist entries, marking them `[x]/[ ]` and noting any intentional omissions as "N/A".
|
||||
7. Present the filled template inside a fenced ```markdown code block with no extra commentary so it is ready to paste into a PR, clearly flagging any placeholders that still need user input.
|
||||
22
.github/prompts/fix-spelling.prompt.md
vendored
22
.github/prompts/fix-spelling.prompt.md
vendored
@@ -1,22 +0,0 @@
|
||||
---
|
||||
mode: 'agent'
|
||||
model: GPT-5-Codex (Preview)
|
||||
description: 'Resolve Code scanning / check-spelling comments on the active PR.'
|
||||
---
|
||||
|
||||
**Goal:** Clear every outstanding GitHub pull request comment created by the `Code scanning / check-spelling` workflow by explicitly allowing intentional terms.
|
||||
|
||||
**Guardrails:**
|
||||
- Update only discussion threads authored by `github-actions` or `github-actions[bot]` that mention `Code scanning results / check-spelling`.
|
||||
- Resolve findings solely by editing `.github/actions/spell-check/expect.txt`; reuse existing entries.
|
||||
- Leave all other files and topics untouched.
|
||||
|
||||
**Prerequisites:**
|
||||
- Install GitHub CLI if it is not present: `winget install GitHub.cli`.
|
||||
- Run `gh auth login` once before the first CLI use.
|
||||
|
||||
**Workflow:**
|
||||
1. Determine the active pull request with a single `gh pr view --json number` call (default to the current branch).
|
||||
2. Fetch all PR discussion data once via `gh pr view --json comments,reviews` and filter to check-spelling comments authored by `github-actions` or `github-actions[bot]` that are not minimized; when several remain, process only the most recent comment body.
|
||||
3. For each flagged token, review `.github/actions/spell-check/expect.txt` for an equivalent term (for example an existing lowercase variant); when found, reuse that normalized term rather than adding a new entry, even if the flagged token differs only by casing. Only add a new entry after confirming no equivalent already exists.
|
||||
4. Add any remaining missing token to `.github/actions/spell-check/expect.txt`, keeping surrounding formatting intact.
|
||||
@@ -235,9 +235,7 @@
|
||||
"*Microsoft.CmdPal.UI_*.msix",
|
||||
|
||||
"PowerToys.DSC.dll",
|
||||
"PowerToys.DSC.exe",
|
||||
|
||||
"PowerToysSparse.msix"
|
||||
"PowerToys.DSC.exe"
|
||||
],
|
||||
"SigningInfo": {
|
||||
"Operations": [
|
||||
|
||||
@@ -61,8 +61,6 @@
|
||||
<PackageVersion Include="Microsoft.Windows.CsWinRT" Version="2.2.0" />
|
||||
<PackageVersion Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.26100.4948" />
|
||||
<PackageVersion Include="Microsoft.WindowsAppSDK" Version="1.8.250907003" />
|
||||
<PackageVersion Include="Microsoft.WindowsAppSDK.AI" Version="1.8.37" />
|
||||
<PackageVersion Include="Microsoft.WindowsAppSDK.Runtime" Version="1.8.250907003" />
|
||||
<PackageVersion Include="Microsoft.Xaml.Behaviors.WinUI.Managed" Version="2.0.9" />
|
||||
<PackageVersion Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.39" />
|
||||
<PackageVersion Include="ModernWpfUI" Version="0.9.4" />
|
||||
|
||||
@@ -26,7 +26,6 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "runner", "src\runner\runner
|
||||
{D29DDD63-E2CF-4657-9FD5-2AEDE4257E5D} = {D29DDD63-E2CF-4657-9FD5-2AEDE4257E5D}
|
||||
{D940E07F-532C-4FF3-883F-790DA014F19A} = {D940E07F-532C-4FF3-883F-790DA014F19A}
|
||||
{DA425894-6E13-404F-8DCB-78584EC0557A} = {DA425894-6E13-404F-8DCB-78584EC0557A}
|
||||
{E2A5A82E-1E5B-4C8D-9A4F-2B1A8F9E5C3D} = {E2A5A82E-1E5B-4C8D-9A4F-2B1A8F9E5C3D}
|
||||
{E364F67B-BB12-4E91-B639-355866EBCD8B} = {E364F67B-BB12-4E91-B639-355866EBCD8B}
|
||||
{F9C68EDF-AC74-4B77-9AF1-005D9C9F6A99} = {F9C68EDF-AC74-4B77-9AF1-005D9C9F6A99}
|
||||
EndProjectSection
|
||||
@@ -51,8 +50,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "common", "common", "{1AFB64
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Common.Lib.UnitTests", "src\common\UnitTests-CommonLib\UnitTests-CommonLib.vcxproj", "{1A066C63-64B3-45F8-92FE-664E1CCE8077}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PackageIdentity", "src\PackageIdentity\PackageIdentity.vcxproj", "{E2A5A82E-1E5B-4C8D-9A4F-2B1A8F9E5C3D}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FancyZonesEditor", "src\modules\fancyzones\editor\FancyZonesEditor\FancyZonesEditor.csproj", "{5CCC8468-DEC8-4D36-99D4-5C891BEBD481}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "powerrename", "powerrename", "{89E20BCE-EB9C-46C8-8B50-E01A82E6FDC3}"
|
||||
@@ -870,14 +867,6 @@ Global
|
||||
{1A066C63-64B3-45F8-92FE-664E1CCE8077}.Release|ARM64.Build.0 = Release|ARM64
|
||||
{1A066C63-64B3-45F8-92FE-664E1CCE8077}.Release|x64.ActiveCfg = Release|x64
|
||||
{1A066C63-64B3-45F8-92FE-664E1CCE8077}.Release|x64.Build.0 = Release|x64
|
||||
{E2A5A82E-1E5B-4C8D-9A4F-2B1A8F9E5C3D}.Debug|ARM64.ActiveCfg = Debug|ARM64
|
||||
{E2A5A82E-1E5B-4C8D-9A4F-2B1A8F9E5C3D}.Debug|ARM64.Build.0 = Debug|ARM64
|
||||
{E2A5A82E-1E5B-4C8D-9A4F-2B1A8F9E5C3D}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{E2A5A82E-1E5B-4C8D-9A4F-2B1A8F9E5C3D}.Debug|x64.Build.0 = Debug|x64
|
||||
{E2A5A82E-1E5B-4C8D-9A4F-2B1A8F9E5C3D}.Release|ARM64.ActiveCfg = Release|ARM64
|
||||
{E2A5A82E-1E5B-4C8D-9A4F-2B1A8F9E5C3D}.Release|ARM64.Build.0 = Release|ARM64
|
||||
{E2A5A82E-1E5B-4C8D-9A4F-2B1A8F9E5C3D}.Release|x64.ActiveCfg = Release|x64
|
||||
{E2A5A82E-1E5B-4C8D-9A4F-2B1A8F9E5C3D}.Release|x64.Build.0 = Release|x64
|
||||
{5CCC8468-DEC8-4D36-99D4-5C891BEBD481}.Debug|ARM64.ActiveCfg = Debug|ARM64
|
||||
{5CCC8468-DEC8-4D36-99D4-5C891BEBD481}.Debug|ARM64.Build.0 = Debug|ARM64
|
||||
{5CCC8468-DEC8-4D36-99D4-5C891BEBD481}.Debug|x64.ActiveCfg = Debug|x64
|
||||
|
||||
313
README.md
313
README.md
@@ -10,11 +10,11 @@
|
||||
|
||||
<h3 align="center">
|
||||
<a href="#-installation">Installation</a>
|
||||
<span> . </span>
|
||||
<span> · </span>
|
||||
<a href="https://aka.ms/powertoys-docs">Documentation</a>
|
||||
<span> . </span>
|
||||
<span> · </span>
|
||||
<a href="https://aka.ms/powertoys-releaseblog">Blog</a>
|
||||
<span> . </span>
|
||||
<span> · </span>
|
||||
<a href="#-whats-new">Release notes</a>
|
||||
</h3>
|
||||
<br/><br/>
|
||||
@@ -27,12 +27,11 @@ Microsoft PowerToys is a collection of utilities that help you customize Windows
|
||||
| [<img src="doc/images/icons/Color%20Picker.png" alt="Color Picker icon" height="16"> Color Picker](https://aka.ms/PowerToysOverview_ColorPicker) | [<img src="doc/images/icons/Command%20Not%20Found.png" alt="Command Not Found icon" height="16"> Command Not Found](https://aka.ms/PowerToysOverview_CmdNotFound) | [<img src="doc/images/icons/Command Palette.png" alt="Command Palette icon" height="16"> Command Palette](https://aka.ms/PowerToysOverview_CmdPal) |
|
||||
| [<img src="doc/images/icons/Crop%20And%20Lock.png" alt="Crop and Lock icon" height="16"> Crop And Lock](https://aka.ms/PowerToysOverview_CropAndLock) | [<img src="doc/images/icons/Environment%20Manager.png" alt="Environment Variables icon" height="16"> Environment Variables](https://aka.ms/PowerToysOverview_EnvironmentVariables) | [<img src="doc/images/icons/FancyZones.png" alt="FancyZones icon" height="16"> FancyZones](https://aka.ms/PowerToysOverview_FancyZones) |
|
||||
| [<img src="doc/images/icons/File%20Explorer%20Preview.png" alt="File Explorer Add-ons icon" height="16"> File Explorer Add-ons](https://aka.ms/PowerToysOverview_FileExplorerAddOns) | [<img src="doc/images/icons/File%20Locksmith.png" alt="File Locksmith icon" height="16"> File Locksmith](https://aka.ms/PowerToysOverview_FileLocksmith) | [<img src="doc/images/icons/Host%20File%20Editor.png" alt="Hosts File Editor icon" height="16"> Hosts File Editor](https://aka.ms/PowerToysOverview_HostsFileEditor) |
|
||||
| [<img src="doc/images/icons/Image%20Resizer.png" alt="Image Resizer icon" height="16"> Image Resizer](https://aka.ms/PowerToysOverview_ImageResizer) | [<img src="doc/images/icons/Keyboard%20Manager.png" alt="Keyboard Manager icon" height="16"> Keyboard Manager](https://aka.ms/PowerToysOverview_KeyboardManager) | [<img src="doc/images/icons/Light Switch.png" alt="Light Switch icon" height="16"> Light Switch](https://aka.ms/PowerToysOverview_LightSwitch) |
|
||||
| [<img src="doc/images/icons/Find My Mouse.png" alt="Mouse Utilities icon" height="16"> Mouse Utilities](https://aka.ms/PowerToysOverview_MouseUtilities) | [<img src="doc/images/icons/MouseWithoutBorders.png" alt="Mouse Without Borders icon" height="16"> Mouse Without Borders](https://aka.ms/PowerToysOverview_MouseWithoutBorders) | [<img src="doc/images/icons/NewPlus.png" alt="New+ icon" height="16"> New+](https://aka.ms/PowerToysOverview_NewPlus) |
|
||||
| [<img src="doc/images/icons/Peek.png" alt="Peek icon" height="16"> Peek](https://aka.ms/PowerToysOverview_Peek) | [<img src="doc/images/icons/PowerRename.png" alt="PowerRename icon" height="16"> PowerRename](https://aka.ms/PowerToysOverview_PowerRename) | [<img src="doc/images/icons/PowerToys%20Run.png" alt="PowerToys Run icon" height="16"> PowerToys Run](https://aka.ms/PowerToysOverview_PowerToysRun) |
|
||||
| [<img src="doc/images/icons/PowerAccent.png" alt="Quick Accent icon" height="16"> Quick Accent](https://aka.ms/PowerToysOverview_QuickAccent) | [<img src="doc/images/icons/Registry%20Preview.png" alt="Registry Preview icon" height="16"> Registry Preview](https://aka.ms/PowerToysOverview_RegistryPreview) | [<img src="doc/images/icons/MeasureTool.png" alt="Screen Ruler icon" height="16"> Screen Ruler](https://aka.ms/PowerToysOverview_ScreenRuler) |
|
||||
| [<img src="doc/images/icons/Shortcut%20Guide.png" alt="Shortcut Guide icon" height="16"> Shortcut Guide](https://aka.ms/PowerToysOverview_ShortcutGuide) | [<img src="doc/images/icons/PowerOCR.png" alt="Text Extractor icon" height="16"> Text Extractor](https://aka.ms/PowerToysOverview_TextExtractor) | [<img src="doc/images/icons/Workspaces.png" alt="Workspaces icon" height="16"> Workspaces](https://aka.ms/PowerToysOverview_Workspaces) |
|
||||
| [<img src="doc/images/icons/ZoomIt.png" alt="ZoomIt icon" height="16"> ZoomIt](https://aka.ms/PowerToysOverview_ZoomIt) | | |
|
||||
| [<img src="doc/images/icons/Image%20Resizer.png" alt="Image Resizer icon" height="16"> Image Resizer](https://aka.ms/PowerToysOverview_ImageResizer) | [<img src="doc/images/icons/Keyboard%20Manager.png" alt="Keyboard Manager icon" height="16"> Keyboard Manager](https://aka.ms/PowerToysOverview_KeyboardManager) | [<img src="doc/images/icons/Find My Mouse.png" alt="Mouse Utilities icon" height="16"> Mouse Utilities](https://aka.ms/PowerToysOverview_MouseUtilities) |
|
||||
| [<img src="doc/images/icons/MouseWithoutBorders.png" alt="Mouse Without Borders icon" height="16"> Mouse Without Borders](https://aka.ms/PowerToysOverview_MouseWithoutBorders) | [<img src="doc/images/icons/NewPlus.png" alt="New+ icon" height="16"> New+](https://aka.ms/PowerToysOverview_NewPlus) | [<img src="doc/images/icons/Peek.png" alt="Peek icon" height="16"> Peek](https://aka.ms/PowerToysOverview_Peek) |
|
||||
| [<img src="doc/images/icons/PowerRename.png" alt="PowerRename icon" height="16"> PowerRename](https://aka.ms/PowerToysOverview_PowerRename) | [<img src="doc/images/icons/PowerToys%20Run.png" alt="PowerToys Run icon" height="16"> PowerToys Run](https://aka.ms/PowerToysOverview_PowerToysRun) | [<img src="doc/images/icons/PowerAccent.png" alt="Quick Accent icon" height="16"> Quick Accent](https://aka.ms/PowerToysOverview_QuickAccent) |
|
||||
| [<img src="doc/images/icons/Registry%20Preview.png" alt="Registry Preview icon" height="16"> Registry Preview](https://aka.ms/PowerToysOverview_RegistryPreview) | [<img src="doc/images/icons/MeasureTool.png" alt="Screen Ruler icon" height="16"> Screen Ruler](https://aka.ms/PowerToysOverview_ScreenRuler) | [<img src="doc/images/icons/Shortcut%20Guide.png" alt="Shortcut Guide icon" height="16"> Shortcut Guide](https://aka.ms/PowerToysOverview_ShortcutGuide) |
|
||||
| [<img src="doc/images/icons/PowerOCR.png" alt="Text Extractor icon" height="16"> Text Extractor](https://aka.ms/PowerToysOverview_TextExtractor) | [<img src="doc/images/icons/Workspaces.png" alt="Workspaces icon" height="16"> Workspaces](https://aka.ms/PowerToysOverview_Workspaces) | [<img src="doc/images/icons/ZoomIt.png" alt="ZoomIt icon" height="16"> ZoomIt](https://aka.ms/PowerToysOverview_ZoomIt) |
|
||||
|
||||
|
||||
## 📋 Installation
|
||||
@@ -48,25 +47,25 @@ Before you begin, make sure your device meets the system requirements:
|
||||
|
||||
Choose one of the installation methods below:
|
||||
|
||||
<details open>
|
||||
<details>
|
||||
<summary>Download .exe from GitHub</summary>
|
||||
|
||||
Go to the [PowerToys GitHub releases][github-release-link], click Assets to reveal the downloads, and choose the installer that matches your architecture and install scope. For most devices, that's the x64 per-user installer.
|
||||
|
||||
<!-- 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.96%22
|
||||
[github-current-release-work]: https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+milestone%3A%22PowerToys+0.95%22
|
||||
[ptUserX64]: https://github.com/microsoft/PowerToys/releases/download/v0.95.1/PowerToysUserSetup-0.95.1-x64.exe
|
||||
[ptUserArm64]: https://github.com/microsoft/PowerToys/releases/download/v0.95.1/PowerToysUserSetup-0.95.1-arm64.exe
|
||||
[ptMachineX64]: https://github.com/microsoft/PowerToys/releases/download/v0.95.1/PowerToysSetup-0.95.1-x64.exe
|
||||
[ptMachineArm64]: https://github.com/microsoft/PowerToys/releases/download/v0.95.1/PowerToysSetup-0.95.1-arm64.exe
|
||||
[github-next-release-work]: https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+milestone%3A%22PowerToys+0.95%22
|
||||
[github-current-release-work]: https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+milestone%3A%22PowerToys+0.94%22
|
||||
[ptUserX64]: https://github.com/microsoft/PowerToys/releases/download/v0.94.0/PowerToysUserSetup-0.94.0-x64.exe
|
||||
[ptUserArm64]: https://github.com/microsoft/PowerToys/releases/download/v0.94.0/PowerToysUserSetup-0.94.0-arm64.exe
|
||||
[ptMachineX64]: https://github.com/microsoft/PowerToys/releases/download/v0.94.0/PowerToysSetup-0.94.0-x64.exe
|
||||
[ptMachineArm64]: https://github.com/microsoft/PowerToys/releases/download/v0.94.0/PowerToysSetup-0.94.0-arm64.exe
|
||||
|
||||
| Description | Filename |
|
||||
|----------------|----------|
|
||||
| Per user - x64 | [PowerToysUserSetup-0.95.1-x64.exe][ptUserX64] |
|
||||
| Per user - ARM64 | [PowerToysUserSetup-0.95.1-arm64.exe][ptUserArm64] |
|
||||
| Machine wide - x64 | [PowerToysSetup-0.95.1-x64.exe][ptMachineX64] |
|
||||
| Machine wide - ARM64 | [PowerToysSetup-0.95.1-arm64.exe][ptMachineArm64] |
|
||||
| Per user - x64 | [PowerToysUserSetup-0.94.0-x64.exe][ptUserX64] |
|
||||
| Per user - ARM64 | [PowerToysUserSetup-0.94.0-arm64.exe][ptUserArm64] |
|
||||
| Machine wide - x64 | [PowerToysSetup-0.94.0-x64.exe][ptMachineX64] |
|
||||
| Machine wide - ARM64 | [PowerToysSetup-0.94.0-arm64.exe][ptMachineArm64] |
|
||||
|
||||
</details>
|
||||
|
||||
@@ -106,179 +105,175 @@ There are [community driven install methods](./doc/unofficialInstallMethods.md)
|
||||
</details>
|
||||
|
||||
## ✨ What's new
|
||||
**Version 0.95 (October 2025)**
|
||||
**Version 0.94 (September 2025)**
|
||||
|
||||
For an in-depth look at the latest changes, visit the [Windows Command Line blog](https://aka.ms/powertoys-releaseblog).
|
||||
|
||||
**✨ Highlights**
|
||||
- **NEW:** The **Light Switch** utility in PowerToys allows you to automatically switch between light and dark themes in Windows based on the time of day.
|
||||
- Command Palette delivered major search performance gains (new fuzzy matcher and smarter fallbacks) improving relevance and speed.
|
||||
- Peek can now be activated using just the Spacebar!
|
||||
- Find My Mouse added transparent spotlight with independent backdrop opacity, boosting focus and accessibility.
|
||||
- Settings now lets you delete shortcuts entirely and ignore conflicts.
|
||||
- Mouse Pointer Crosshairs gained orientation options (vertical / horizontal / both) for customizable accessibility. Thanks [@mikehall-ms](https://github.com/mikehall-ms)!
|
||||
- PowerRename fixed enumeration counter skipping ensuring reliable batch renames. Thanks [@daverayment](https://github.com/daverayment)!
|
||||
- ZoomIt restored legacy draw and snipping behaviors, and fixed recording issues, improving reliability. Thanks [@chakrik73](https://github.com/chakrik73)!
|
||||
|
||||
- PowerToys Settings added a Settings search with fuzzy matching, suggestions, a results page, and UX polish to make finding options faster.
|
||||
- A comprehensive hotkey conflict detection system was introduced in Settings to surface and help resolve conflicting shortcuts. Note that the default hotkey settings (Win+Ctrl+Shift+T, Win+Ctrl+V, Win+Ctrl+T, Win+Shift+T) may overlap with existing Windows system shortcuts. This is expected. You can resolve the conflict by assigning different hotkeys.
|
||||
- Mouse Utilities added a “Gliding cursor” accessibility feature to Mouse Pointer Crosshairs for single‑button cursor movement and clicking. Thanks [@mikehall-ms](https://github.com/mikehall-ms)!
|
||||
- The installer was upgraded to WiX 5 after WiX 3 reached end-of-life; this move improved installer security, reliability, and community support.
|
||||
- Tons of bug fixes and improvements for Command Palette, including visual updates and new support for filters on ListPages (handy for extension developers).
|
||||
- Hosts Editor now has a “No leading spaces” option so active host entries can start at column 0 even if others are disabled. Thanks [@mohammed-saalim](https://github.com/mohammed-saalim)!
|
||||
- Context menu registration was moved from the installer to runtime to avoid loading disabled modules (runtime registrations).
|
||||
- Quick Accent now supports Maltese, and frequently used accents appear first (and are remembered across sessions). Thanks [@rovercoder](https://github.com/rovercoder)! [@davidegiacometti](https://github.com/davidegiacometti)!
|
||||
|
||||
### Always On Top
|
||||
|
||||
- Fixed the border hover cursor so it shows the arrow instead of the wait cursor. Thanks [@davidegiacometti](https://github.com/davidegiacometti)!
|
||||
|
||||
### Command Palette
|
||||
- Applied conditional margin for icon-only tags to tighten layout. Thanks [@samrueby](https://github.com/samrueby)
|
||||
- Improved the reliability of accessing Command Palette settings through PowerToys Settings and executing other x-cmdpal:// protocol commands. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Enabled AOT by default for improved performance while simplifying publish configs.
|
||||
- Replaced service state color dots with play/pause/stop icons for enhanced accessibility. Thanks [@samrueby](https://github.com/samrueby)
|
||||
- Fixed filter dropdown sync and crash by binding SelectedValue and raising UI-thread notifications. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Ensured long links wrap correctly in details view.
|
||||
- Removed animation and enforced minimum width on filter dropdown for clarity. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Restored focus to More button after ESC closes context menu, improving keyboard flow. Thanks [@chatasweetie](https://github.com/chatasweetie)
|
||||
- Marked main and toast windows as tool windows to keep them out of Alt+Tab while preserving style. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Fixed AOT template and theming issues for filter separators. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Introduced grid layouts (small, medium, gallery) for richer page presentation.
|
||||
- Materialized result lists to avoid rescoring overhead.
|
||||
- Disabled problematic selection TextToSuggest behind environment flag.
|
||||
- Major search performance improvements (new fuzzy matcher, smarter fallbacks, fewer exceptions).
|
||||
- Added context menu "Show Details" command when details pane is hidden.
|
||||
- Reduced window flicker by avoiding unnecessary cloaking. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Restored EmptyContent rendering for blank states. Thanks [@DevLGuilherme](https://github.com/DevLGuilherme)
|
||||
- Saved new state even if prior app state file was corrupt (better resilience). Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Migrated settings window to WinUI TitleBar control. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Prevented crash on duplicate keybindings and simplified matching. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Hotkeys now always respect the “Ignore shortcut in fullscreen” setting. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Hid search box on content pages, improving focus and accessibility, and added Home title. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Blocked Ctrl+I from inserting stray tabs in search box.
|
||||
- Logged HRESULT codes in error logs for deeper diagnostics. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Advanced font and emoji icon classification and alignment improvements. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Ensured that fallback command icons are visible on the extension settings page. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Fixed breadcrumb margin misalignment (visual polish). Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Truncated overly long command labels with ellipsis to prevent overflow.
|
||||
- Added a setting to configure the page transition animation.
|
||||
- Collection of small improvements and nits for Run Commands.
|
||||
- Improved bookmarks performance and experience. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Added Ctrl+O shortcut in Clipboard History to open links directly.
|
||||
- Resolved conflict with external software that blocked Command Palette from hiding.
|
||||
- Updated context menu items to reflect name and icon changes, and ensured application icons are displayed correctly. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Added Alt+Home shortcut to return immediately to the Command Palette home page. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Fixed a crash when displaying code blocks in markdown on detail or content pages. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Fixed an issue where the search bar icon and title were not updated when rapidly switching pages. Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Improved the appearance of the search box in the context menu.
|
||||
|
||||
- Applied single-click activation only to pointer input; keyboard always activates immediately. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Let context menus open at the cursor by removing window-bound constraints. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Made error messages clearer with timestamps, HRESULTs, and full details for easier diagnosis. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Prevented crashes and improved robustness when updating providers without commands. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Ensured the Settings window reliably comes to the front when opened. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Replaced the Clipboard History icon with a colorful Fluent icon. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Hardened ContentIcon to avoid duplicate parenting and improve diagnostics. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Standardized null checks using C# pattern matching for safer behavior.
|
||||
- Improved accessibility by focusing the activation shortcut dialog and making text reachable. Thanks [@chatasweetie](https://github.com/chatasweetie)!
|
||||
- Moved the extension SDK to a stable Windows SDK and cleaned up message namespaces.
|
||||
- Added path shortcuts: ~ to home, and / or \\ to system root, plus UNC support. Thanks [@davidegiacometti](https://github.com/davidegiacometti)!
|
||||
- Fixed a race in cancellation handling to avoid InvalidOperationException. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Aligned separator styling with WinUI 3 for consistent visuals. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Added ARM64 PDBs to the Extensions SDK NuGet for better debugging.
|
||||
- Added single-select filters to DynamicListPage and updated Windows Services sample.
|
||||
- Updated main page placeholder text to better describe what can be searched. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Removed explicit WinAppSDK/WebView2 dependencies from toolkit and API. Thanks [@rluengen](https://github.com/rluengen)!
|
||||
- Added a local keyboard hook to handle the GoBack key reliably. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Propagated alias changes safely and resolved conflicts across view models.
|
||||
- Allowed providers to override Dispose with a virtual method.
|
||||
- Fixed memory leaks by cleaning up removed or cancelled list items.
|
||||
- Sorted DateTime extension results by relevance for better usability.
|
||||
- Reduced search text "jiggling" by avoiding redundant change notifications.
|
||||
- Centralized automation notifications in a UIHelper for better accessibility. Thanks [@chatasweetie](https://github.com/chatasweetie)!
|
||||
- Preserved Adaptive Card action types during trimming via DynamicDependency.
|
||||
- Added an acrylic backdrop and refined styling to the context menu. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Prevented disposed pages and Settings windows from handling stale messages. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Made the extension API easier to evolve without breaking clients.
|
||||
- Added "evil" sample pages to help reproduce tricky bugs.
|
||||
- Fixed WinGet trim-safety issues by replacing LINQ with manual iteration.
|
||||
- Cancelled stale list fetches to avoid older results overwriting newer ones in CmdPal.
|
||||
|
||||
### Command Palette Extensions
|
||||
- Replaced localized WebSearch setting keys with stable literals and numeric history count. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Enabled advanced markdown tables and emphasis extensions. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Added setting to choose Clipboard History primary action (Paste vs Copy). Thanks [@jiripolasek](https://github.com/jiripolasek)
|
||||
- Added actionable empty-state hints for File Search (search PC / open indexing settings). Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Ensured all WinGet extension assets copy reliably to output. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Improved Run command line parsing for paths with spaces; sped up related tests.
|
||||
- Updated WebSearch extension icon set for enhanced clarity and contrast. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Added Terminal profile sort order setting including MRU tracking. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Added Uninstall Application command (UWP direct, Win32 via Settings). Thanks [@mKpwnz](https://github.com/mKpwnz)!
|
||||
- Deferred WinGet details loading and added timing logs.
|
||||
- Removed LINQ from All Apps extension for performance.
|
||||
- Added standardized key chord system + shortcuts to File Search commands. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Added Terminal channel filter & remembered selection option. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Enabled loading local/data/app images in markdown with sizing hints. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Added external extension reload via x-cmdpal://reload (configurable). Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Instant WebSearch history updates with in-memory store & events. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Added keep-after-paste option and safe delete with confirmation for Clipboard History. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
### Command Palette extensions
|
||||
|
||||
### Environment Variables
|
||||
- Replaced custom window chrome with WinUI TitleBar for cleaner, maintainable Environment Variables UI.
|
||||
|
||||
### File Locksmith
|
||||
- Adopted WinUI TitleBar to simplify window chrome while preserving appearance.
|
||||
|
||||
### Find My Mouse
|
||||
- Added transparent spotlight support with separate backdrop opacity; migrated to Windows App SDK composition APIs.
|
||||
- Improved empty states and ranking logic for multiple extensions. Thanks [@htcfreek](https://github.com/htcfreek)!
|
||||
- Added app icons to the All Apps "Run" context command when available.
|
||||
- Restored missing builtin icons by standardizing extension dependencies.
|
||||
- Unblocked local deployment by adding WinAppSDK to two sample extensions.
|
||||
|
||||
### Hosts File Editor
|
||||
- Migrated to native WinUI TitleBar for cleaner, maintainable window chrome.
|
||||
|
||||
### Light Switch
|
||||
- Introduced as a brand-new PowerToy module.
|
||||
- Automatically switches between light and dark themes.
|
||||
- Supports time-based scheduling or location-based sunrise/sunset switching.
|
||||
- Supports using a keyboard shortcut to force a change.
|
||||
- Supports filtering changes for Apps and/or System Theme.
|
||||
- Added a "No leading spaces" option so active hosts entries can start at column 0 even when others are disabled. Thanks [@mohammed-saalim](https://github.com/mohammed-saalim)!
|
||||
|
||||
### Mouse Pointer Crosshairs
|
||||
- Added Esc key to cancel active gliding cursor sequence. Thanks [@mikehall-ms](https://github.com/mikehall-ms)!
|
||||
- Added orientation option (vertical / horizontal / both) for crosshairs customization. Thanks [@mikehall-ms](https://github.com/mikehall-ms)!
|
||||
### Image Resizer
|
||||
|
||||
- Fixed Image Resizer localization by installing satellite resources under the WinUI 3 apps culture path.
|
||||
|
||||
### Mouse Utilities
|
||||
|
||||
- Introduced "Gliding cursor" to control the pointer and click with a single hotkey for better accessibility. Thanks [@mikehall-ms](https://github.com/mikehall-ms)!
|
||||
|
||||
### Mouse Without Borders
|
||||
- Continued Common class refactor (part 5/7) by extracting clipboard and init/cleanup logic into focused classes. Thanks [@mikeclayton](https://github.com/mikeclayton)!
|
||||
|
||||
- Fix connection failures caused by conflicting MachineId across machines. Thanks [@noraa-junker](https://github.com/noraa-junker) for troubleshooting!
|
||||
- Blocked Easy Mouse from switching machines during fullscreen apps, with an allow-list for exceptions. Thanks [@dot-tb](https://github.com/dot-tb)!
|
||||
|
||||
### Peek
|
||||
- Added the option to activate Peek with just the Spacebar.
|
||||
|
||||
- Added Visual Studio shared project file types to XML preview and fixed bgcode handler registration. Thanks [@rezanid](https://github.com/rezanid)!
|
||||
- Fixes bgcode preview handler registration and events for reliable previews. Thanks [@pedrolamas](https://github.com/pedrolamas)!
|
||||
|
||||
### PowerRename
|
||||
- Fixed enumeration counter skipping when regex replacement equals original filename (counters now advance reliably). Thanks [@daverayment](https://github.com/daverayment)!
|
||||
|
||||
- Changed the Explorer accelerator key to PowErRename to avoid clashing with the New menu. Thanks [@aaron-ni](https://github.com/aaron-ni)!
|
||||
|
||||
### Quick Accent
|
||||
- Expanded Welsh layout with acute, grave, and dieresis variants for vowels (consistent ordering). Thanks [@PesBandi](https://github.com/PesBandi)!
|
||||
|
||||
### Registry Preview
|
||||
- Migrated to native TitleBar and AppWindow APIs for cleaner window chrome.
|
||||
|
||||
### Screen Ruler
|
||||
- Fixed ARM64 crash by aligning cursor position structure to 8-byte boundary.
|
||||
- Remembered character usage across sessions so frequently used accents appear first. Thanks [@davidegiacometti](https://github.com/davidegiacometti)!
|
||||
- Added Maltese language support with specific characters and the Euro symbol. Thanks [@rovercoder](https://github.com/rovercoder)!
|
||||
- Reduced GPU usage issues by making the window Topmost only when the picker is visible. Thanks [@daverayment](https://github.com/daverayment)!
|
||||
|
||||
### Settings
|
||||
- Added ability to ignore specific hotkey conflicts to reduce noise.
|
||||
- Stopped creating backup directory during dry-run status checks (cleaner first-run).
|
||||
- Standardized casing and localization for ZoomIt and modules header.
|
||||
- Improved search results page accessibility and conditional module grouping.
|
||||
|
||||
### ZoomIt
|
||||
- Updated resource file to reflect standalone v9.01 and current copyright year. Thanks [@foxmsft](https://github.com/foxmsft)!
|
||||
- Restored legacy draw/snipping behaviors and fixed recording race conditions. Thanks [@chakrik73](https://github.com/chakrik73)!
|
||||
- Added smooth image option for improved zoom quality using GDI+ for static zoom and Magnifier API for live zoom. Thanks [@markrussinovich](https://github.com/markrussinovich)!
|
||||
- Added telemetry to track usage of the new shortcut conflict detection workflow.
|
||||
- Moved the shutdown action from the title bar to a footer menu item with confirmation. Thanks [@davidegiacometti](https://github.com/davidegiacometti)!
|
||||
- Implemented comprehensive hotkey conflict detection with a dedicated resolution dialog.
|
||||
- Added branded visuals for Office and Copilot keys in the KeyVisual control.
|
||||
- Introduced Settings search with fuzzy matching and navigation to specific controls.
|
||||
- Corrected Spanish localization so product names like Awake remain in English across Settings and OOBE.
|
||||
- Simplified the Advanced Paste description in Settings for quicker reading and consistent capitalization. Thanks [@OldUser101](https://github.com/OldUser101)!
|
||||
- Localized conflict messages in the conflict window and dialog.
|
||||
|
||||
### Documentation
|
||||
- New Microsoft Learn documentation for the Light Switch module.
|
||||
- New dev docs for the Light Switch module.
|
||||
### Installer
|
||||
|
||||
### Development (Area-Build & Area-Tests)
|
||||
- Allowed debug launches to continue when modules fail to load, speeding developer iteration.
|
||||
- Fixed spell checker dictionary entry (advapi) to eliminate false error.
|
||||
- Added VS Code development guide and launch configs to streamline cross-editor workflows.
|
||||
- Upgraded Windows App SDK and related dependencies to 1.8 for newer platform features.
|
||||
- Rewrote YAML comment to resolve new spell checker forbidden pattern. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Corrected solution structure by returning misplaced Common project, reducing build confusion.
|
||||
- Modernized build scripts with shared helpers and VS environment autodetection for simpler CLI builds.
|
||||
- Standardized build scripts and platform detection to improve reliability and reuse.
|
||||
- Added missing Command Palette version bump to align module release cadence.
|
||||
- Added EXECUTEDEFAULT term to dictionary to prevent regression build failures. Thanks [@jiripolasek](https://github.com/jiripolasek)!
|
||||
- Introduced nightly pre-warm pipeline and configurable MSBuild cache mode to improve CI performance.
|
||||
- Resolved CI forbidden pattern spelling complaint to keep pipelines green.
|
||||
- Added AI contributor instruction set to clarify code area expectations.
|
||||
- Added accessibility IDs to settings and FancyZones toggles, stabilizing UI tests.
|
||||
- Added automatic log collection on UI test failures to speed root cause analysis.
|
||||
- Stabilized Mouse Utils tests by switching to AccessibilityId selectors.
|
||||
- Added Screen Ruler UI test coverage to validate core measurement workflows.
|
||||
- Upgraded the installer to WiX 5 with silent "Files in Use" handling for smoother winget installs.
|
||||
- Switched Win10 context menu modules to runtime registration and added cleanup on uninstall to avoid stale entries.
|
||||
|
||||
## 🛣️ Roadmap
|
||||
We are planning some nice new features and improvements for the next releases – a revamped Keyboard Manager UI, custom endpoint and local model support for Advanced Paste, Command Palette improvements and a brand-new Shortcut Guide experience! Stay tuned for [v0.96][github-next-release-work]!
|
||||
### Documentation
|
||||
|
||||
- Adds docs for building the installer locally and testing winget installs.
|
||||
- Fixed a broken style guide link in developer documentation. Thanks [@denizmaral](https://github.com/denizmaral)!
|
||||
|
||||
### Development
|
||||
|
||||
- Excluded test and coverage DLLs from BinSkim scans to cut false positives and speed up security analysis.
|
||||
- Simplified NOTICE maintenance by removing version numbers and filtering out Microsoft/System packages.
|
||||
- Improved NuGet dependency validation to prevent package downgrades and catch issues during restore.
|
||||
- Updated UTF.Unknown to a modern version to improve compatibility without breaking changes. Thanks [@304NotModified](https://github.com/304NotModified)!
|
||||
- Refreshed package catalog in CI before installing dependencies to prevent Linux workflow failures.
|
||||
- Refactored CmdPal tests with dependency injection and added coverage for queries and settings.
|
||||
- Added unit tests to verify Close on Enter swaps Copy/Save as expected. Thanks [@mohammed-saalim](https://github.com/mohammed-saalim)!
|
||||
- Added accessibility IDs to CmdPal UI for stable UI tests.
|
||||
- Rewrote system command tests with a new test base and cleaner patterns.
|
||||
- Added unit tests for WebSearch and Shell extensions with mockable settings.
|
||||
- Added unit tests and abstractions for Apps and Bookmarks extensions.
|
||||
- Cleans up AI-generated tests; adds meaningful query tests across extensions.
|
||||
- Removed the obsolete debug dialog from Settings for a smoother developer loop.
|
||||
|
||||
## 🛣️ Roadmap
|
||||
|
||||
For [v0.95][github-next-release-work], we'll work on the items below:
|
||||
|
||||
- Continued Command Palette polish
|
||||
- Working on Shortcut Guide v2 (Thanks [@noraa-junker](https://github.com/noraa-junker)!)
|
||||
- Upgrading Keyboard Manager's editor UI
|
||||
- UI tweaking utility with day/night theme switcher
|
||||
- DSC v3 support for top utilities
|
||||
- New UI automation tests
|
||||
- Stability, bug fixes
|
||||
|
||||
## ❤️ PowerToys Community
|
||||
|
||||
## ❤️ PowerToys Community
|
||||
The PowerToys team is extremely grateful to have the [support of an amazing active community][community-link]. The work you do is incredibly important. PowerToys wouldn't be nearly what it is today without your help filing bugs, updating documentation, guiding the design, or writing features. We want to say thank you and take time to recognize your work. Your contributions and feedback improve PowerToys month after month!
|
||||
|
||||
## Contributing
|
||||
This project welcomes contributions of all types. Besides coding features / bug fixes, other ways to assist include spec writing, design, documentation, and finding bugs. We are excited to work with the power user community to build a set of tools for helping you get the most out of Windows. We ask that **before you start work on a feature that you would like to contribute**, please read our [Contributor's Guide](CONTRIBUTING.md). We would be happy to work with you to figure out the best approach, provide guidance and mentorship throughout feature development, and help avoid any wasted or duplicate effort. Most contributions require you to agree to a [Contributor License Agreement (CLA)][oss-CLA] declaring that you grant us the rights to use your contribution and that you have permission to do so. For guidance on developing for PowerToys, please read the [developer docs](./doc/devdocs) for a detailed breakdown. This includes how to setup your computer to compile.
|
||||
## Contributing
|
||||
|
||||
## Code of Conduct
|
||||
This project has adopted the [Microsoft Open Source Code of Conduct][oss-conduct-code].
|
||||
This project welcomes contributions of all types. Besides coding features / bug fixes, other ways to assist include spec writing, design, documentation, and finding bugs. We are excited to work with the power user community to build a set of tools for helping you get the most out of Windows.
|
||||
|
||||
## Privacy Statement
|
||||
The application logs basic diagnostic data (telemetry). For more privacy information and what we collect, see our [PowerToys Data and Privacy documentation](https://aka.ms/powertoys-data-and-privacy-documentation).
|
||||
We ask that **before you start work on a feature that you would like to contribute**, please read our [Contributor's Guide](CONTRIBUTING.md). We would be happy to work with you to figure out the best approach, provide guidance and mentorship throughout feature development, and help avoid any wasted or duplicate effort.
|
||||
|
||||
[oss-CLA]: https://cla.opensource.microsoft.com
|
||||
[oss-conduct-code]: CODE_OF_CONDUCT.md
|
||||
[community-link]: COMMUNITY.md
|
||||
[github-release-link]: https://aka.ms/installPowerToys
|
||||
[microsoft-store-link]: https://aka.ms/getPowertoys
|
||||
[winget-link]: https://github.com/microsoft/winget-cli#installing-the-client
|
||||
Most contributions require you to agree to a [Contributor License Agreement (CLA)][oss-CLA] declaring that you grant us the rights to use your contribution and that you have permission to do so.
|
||||
|
||||
For guidance on developing for PowerToys, please read the [developer docs](./doc/devdocs) for a detailed breakdown. This includes how to setup your computer to compile.
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
This project has adopted the [Microsoft Open Source Code of Conduct][oss-conduct-code].
|
||||
|
||||
## Privacy Statement
|
||||
|
||||
The application logs basic diagnostic data (telemetry). For more privacy information and what we collect, see our [PowerToys Data and Privacy documentation](https://aka.ms/powertoys-data-and-privacy-documentation).
|
||||
|
||||
[oss-CLA]: https://cla.opensource.microsoft.com
|
||||
[oss-conduct-code]: CODE_OF_CONDUCT.md
|
||||
[community-link]: COMMUNITY.md
|
||||
[github-release-link]: https://aka.ms/installPowerToys
|
||||
[microsoft-store-link]: https://aka.ms/getPowertoys
|
||||
[winget-link]: https://github.com/microsoft/winget-cli#installing-the-client
|
||||
[roadmap]: https://github.com/microsoft/PowerToys/wiki/Roadmap
|
||||
[privacy-link]: http://go.microsoft.com/fwlink/?LinkId=521839
|
||||
[loc-bug]: https://github.com/microsoft/PowerToys/issues/new?assignees=&labels=&template=translation_issue.md&title=
|
||||
[privacy-link]: http://go.microsoft.com/fwlink/?LinkId=521839
|
||||
[loc-bug]: https://github.com/microsoft/PowerToys/issues/new?assignees=&labels=&template=translation_issue.md&title=
|
||||
[usingPowerToys-docs-link]: https://aka.ms/powertoys-docs
|
||||
|
||||
@@ -594,216 +594,6 @@ LExit:
|
||||
return WcaFinalize(er);
|
||||
}
|
||||
|
||||
UINT __stdcall InstallPackageIdentityMSIXCA(MSIHANDLE hInstall)
|
||||
{
|
||||
HRESULT hr = S_OK;
|
||||
UINT er = ERROR_SUCCESS;
|
||||
LPWSTR customActionData = nullptr;
|
||||
std::wstring installFolderPath;
|
||||
std::wstring installScope;
|
||||
std::wstring msixPath;
|
||||
std::wstring data;
|
||||
size_t delimiterPos;
|
||||
bool isMachineLevel = false;
|
||||
|
||||
hr = WcaInitialize(hInstall, "InstallPackageIdentityMSIXCA");
|
||||
ExitOnFailure(hr, "Failed to initialize");
|
||||
|
||||
hr = WcaGetProperty(L"CustomActionData", &customActionData);
|
||||
ExitOnFailure(hr, "Failed to get CustomActionData property");
|
||||
|
||||
// Parse CustomActionData: "[INSTALLFOLDER];[InstallScope]"
|
||||
data = customActionData;
|
||||
delimiterPos = data.find(L';');
|
||||
installFolderPath = data.substr(0, delimiterPos);
|
||||
installScope = data.substr(delimiterPos + 1);
|
||||
|
||||
// Check if this is a machine-level installation
|
||||
if (installScope == L"perMachine")
|
||||
{
|
||||
isMachineLevel = true;
|
||||
}
|
||||
|
||||
Logger::info(L"Installing PackageIdentity MSIX - perUser: {}", !isMachineLevel);
|
||||
|
||||
// Construct path to PackageIdentity MSIX
|
||||
msixPath = installFolderPath;
|
||||
msixPath += L"PowerToysSparse.msix";
|
||||
|
||||
if (std::filesystem::exists(msixPath))
|
||||
{
|
||||
using namespace winrt::Windows::Management::Deployment;
|
||||
using namespace winrt::Windows::Foundation;
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
std::wstring externalLocation = installFolderPath; // External content location (PowerToys install folder)
|
||||
Uri externalUri{ externalLocation }; // External location URI for sparse package content
|
||||
Uri packageUri{ msixPath }; // The MSIX file URI
|
||||
|
||||
PackageManager packageManager;
|
||||
|
||||
if (isMachineLevel)
|
||||
{
|
||||
// Machine-level installation
|
||||
|
||||
StagePackageOptions stageOptions;
|
||||
stageOptions.ExternalLocationUri(externalUri);
|
||||
|
||||
auto stageResult = packageManager.StagePackageByUriAsync(packageUri, stageOptions).get();
|
||||
|
||||
uint32_t stageErrorCode = static_cast<uint32_t>(stageResult.ExtendedErrorCode());
|
||||
if (stageErrorCode == 0)
|
||||
{
|
||||
std::wstring packageFamilyName = L"Microsoft.PowerToys.SparseApp_8wekyb3d8bbwe";
|
||||
|
||||
try
|
||||
{
|
||||
auto provisionResult = packageManager.ProvisionPackageForAllUsersAsync(packageFamilyName).get();
|
||||
uint32_t provisionErrorCode = static_cast<uint32_t>(provisionResult.ExtendedErrorCode());
|
||||
|
||||
if (provisionErrorCode != 0)
|
||||
{
|
||||
Logger::error(L"Machine-level provisioning failed: 0x{:08X}", provisionErrorCode);
|
||||
}
|
||||
}
|
||||
catch (const winrt::hresult_error& ex)
|
||||
{
|
||||
Logger::error(L"Provisioning exception: HRESULT 0x{:08X}", static_cast<uint32_t>(ex.code()));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger::error(L"Package staging failed: 0x{:08X}", stageErrorCode);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
AddPackageOptions addOptions;
|
||||
addOptions.ExternalLocationUri(externalUri);
|
||||
|
||||
auto addResult = packageManager.AddPackageByUriAsync(packageUri, addOptions).get();
|
||||
|
||||
if (!addResult.IsRegistered())
|
||||
{
|
||||
uint32_t errorCode = static_cast<uint32_t>(addResult.ExtendedErrorCode());
|
||||
Logger::error(L"Per-user installation failed: 0x{:08X}", errorCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
Logger::error(L"PackageIdentity MSIX installation failed - Exception: {}",
|
||||
winrt::to_hstring(ex.what()).c_str());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger::error(L"PackageIdentity MSIX not found: " + msixPath);
|
||||
}
|
||||
|
||||
LExit:
|
||||
ReleaseStr(customActionData);
|
||||
er = SUCCEEDED(hr) ? ERROR_SUCCESS : ERROR_INSTALL_FAILURE;
|
||||
return WcaFinalize(er);
|
||||
}
|
||||
|
||||
UINT __stdcall UninstallPackageIdentityMSIXCA(MSIHANDLE hInstall)
|
||||
{
|
||||
HRESULT hr = S_OK;
|
||||
UINT er = ERROR_SUCCESS;
|
||||
using namespace winrt::Windows::Management::Deployment;
|
||||
using namespace winrt::Windows::Foundation;
|
||||
|
||||
LPWSTR installScope = nullptr;
|
||||
bool isMachineLevel = false;
|
||||
|
||||
PackageManager pm;
|
||||
|
||||
hr = WcaInitialize(hInstall, "UninstallPackageIdentityMSIXCA");
|
||||
ExitOnFailure(hr, "Failed to initialize");
|
||||
|
||||
// Check if this was a machine-level installation
|
||||
hr = WcaGetProperty(L"InstallScope", &installScope);
|
||||
if (SUCCEEDED(hr) && installScope && wcscmp(installScope, L"perMachine") == 0)
|
||||
{
|
||||
isMachineLevel = true;
|
||||
}
|
||||
|
||||
Logger::info(L"Uninstalling PackageIdentity MSIX - perUser: {}", !isMachineLevel);
|
||||
|
||||
try
|
||||
{
|
||||
std::wstring packageFamilyName = L"Microsoft.PowerToys.SparseApp_8wekyb3d8bbwe";
|
||||
|
||||
if (isMachineLevel)
|
||||
{
|
||||
// Machine-level uninstallation: deprovision + remove for all users
|
||||
|
||||
// First deprovision the package
|
||||
try
|
||||
{
|
||||
auto deprovisionResult = pm.DeprovisionPackageForAllUsersAsync(packageFamilyName).get();
|
||||
if (deprovisionResult.IsRegistered())
|
||||
{
|
||||
Logger::warn(L"Machine-level deprovisioning completed with warnings");
|
||||
}
|
||||
}
|
||||
catch (const winrt::hresult_error& ex)
|
||||
{
|
||||
Logger::warn(L"Machine-level deprovisioning failed: HRESULT 0x{:08X}", static_cast<uint32_t>(ex.code()));
|
||||
}
|
||||
|
||||
// Then remove packages for all users
|
||||
auto packages = pm.FindPackagesForUserWithPackageTypes({}, packageFamilyName, PackageTypes::Main);
|
||||
for (const auto& package : packages)
|
||||
{
|
||||
try
|
||||
{
|
||||
auto machineResult = pm.RemovePackageAsync(package.Id().FullName(), RemovalOptions::RemoveForAllUsers).get();
|
||||
if (machineResult.IsRegistered())
|
||||
{
|
||||
uint32_t errorCode = static_cast<uint32_t>(machineResult.ExtendedErrorCode());
|
||||
Logger::error(L"Machine-level removal failed: 0x{:08X} - {}", errorCode, machineResult.ErrorText());
|
||||
}
|
||||
}
|
||||
catch (const winrt::hresult_error& ex)
|
||||
{
|
||||
Logger::error(L"Machine-level removal exception: HRESULT 0x{:08X}", static_cast<uint32_t>(ex.code()));
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Per-user uninstallation: standard removal
|
||||
|
||||
auto packages = pm.FindPackagesForUserWithPackageTypes({}, packageFamilyName, PackageTypes::Main);
|
||||
for (const auto& package : packages)
|
||||
{
|
||||
auto userResult = pm.RemovePackageAsync(package.Id().FullName()).get();
|
||||
if (userResult.IsRegistered())
|
||||
{
|
||||
uint32_t errorCode = static_cast<uint32_t>(userResult.ExtendedErrorCode());
|
||||
Logger::error(L"Per-user removal failed: 0x{:08X} - {}", errorCode, userResult.ErrorText());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
std::string errorMsg = "Failed to uninstall PackageIdentity MSIX: " + std::string(ex.what());
|
||||
Logger::error(errorMsg);
|
||||
// Don't fail the entire uninstallation if PackageIdentity fails
|
||||
Logger::warn(L"Continuing uninstallation despite PackageIdentity MSIX error");
|
||||
}
|
||||
|
||||
LExit:
|
||||
ReleaseStr(installScope);
|
||||
er = SUCCEEDED(hr) ? ERROR_SUCCESS : ERROR_INSTALL_FAILURE;
|
||||
return WcaFinalize(er);
|
||||
}
|
||||
|
||||
UINT __stdcall RemoveWindowsServiceByName(std::wstring serviceName)
|
||||
{
|
||||
SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
|
||||
|
||||
@@ -33,5 +33,3 @@ EXPORTS
|
||||
CleanPowerRenameRuntimeRegistryCA
|
||||
CleanNewPlusRuntimeRegistryCA
|
||||
SetBundleInstallLocationCA
|
||||
InstallPackageIdentityMSIXCA
|
||||
UninstallPackageIdentityMSIXCA
|
||||
|
||||
@@ -9,25 +9,6 @@
|
||||
<RegistryValue Type="string" Name="InstallScope" Value="$(var.InstallScope)" />
|
||||
</RegistryKey>
|
||||
</Component>
|
||||
<?if $(var.PerUser) = "true" ?>
|
||||
<Component Id="powertoys_env_path_user" Bitness="always64">
|
||||
<!-- Anchor registry for component key path -->
|
||||
<RegistryKey Root="$(var.RegistryScope)" Key="Software\Classes\powertoys\components">
|
||||
<RegistryValue Type="string" Name="powertoys_env_path_user" Value="" KeyPath="yes" />
|
||||
</RegistryKey>
|
||||
<!-- Append install folder to current user's PATH -->
|
||||
<Environment Id="AddPowerToysToUserPath" Name="PATH" Action="set" Part="last" System="no" Value="[INSTALLFOLDER]" />
|
||||
</Component>
|
||||
<?else?>
|
||||
<Component Id="powertoys_env_path_machine" Bitness="always64">
|
||||
<!-- Anchor registry for component key path -->
|
||||
<RegistryKey Root="$(var.RegistryScope)" Key="Software\Classes\powertoys\components">
|
||||
<RegistryValue Type="string" Name="powertoys_env_path_machine" Value="" KeyPath="yes" />
|
||||
</RegistryKey>
|
||||
<!-- Append install folder to machine PATH -->
|
||||
<Environment Id="AddPowerToysToMachinePath" Name="PATH" Action="set" Part="last" System="yes" Value="[INSTALLFOLDER]" />
|
||||
</Component>
|
||||
<?endif?>
|
||||
<Component Id="powertoys_toast_clsid" Bitness="always64">
|
||||
<RemoveFolder Id="Remove_powertoys_toast_clsid" On="uninstall" />
|
||||
<RegistryKey Root="$(var.RegistryScope)" Key="Software\Classes\CLSID\{DD5CACDA-7C2E-4997-A62A-04A597B58F76}">
|
||||
@@ -128,11 +109,6 @@
|
||||
<ComponentRef Id="powertoys_exe" />
|
||||
<ComponentRef Id="PowerToysStartMenuShortcut" />
|
||||
<ComponentRef Id="powertoys_per_machine_comp" />
|
||||
<?if $(var.PerUser) = "true" ?>
|
||||
<ComponentRef Id="powertoys_env_path_user" />
|
||||
<?else?>
|
||||
<ComponentRef Id="powertoys_env_path_machine" />
|
||||
<?endif?>
|
||||
<ComponentRef Id="powertoys_toast_clsid" />
|
||||
<ComponentRef Id="License_rtf" />
|
||||
<ComponentRef Id="Notice_md" />
|
||||
|
||||
@@ -112,7 +112,6 @@
|
||||
<Custom Action="SetUninstallCommandNotFoundParam" Before="UninstallCommandNotFound" />
|
||||
<Custom Action="SetUpgradeCommandNotFoundParam" Before="UpgradeCommandNotFound" />
|
||||
<Custom Action="SetApplyModulesRegistryChangeSetsParam" Before="ApplyModulesRegistryChangeSets" />
|
||||
<Custom Action="SetInstallPackageIdentityMSIXParam" Before="InstallPackageIdentityMSIX" />
|
||||
|
||||
<?if $(var.PerUser) = "true" ?>
|
||||
<Custom Action="SetInstallDSCModuleParam" Before="InstallDSCModule" />
|
||||
@@ -124,7 +123,6 @@
|
||||
<Custom Action="SetBundleInstallLocation" After="InstallFiles" Condition="NOT Installed" />
|
||||
<Custom Action="ApplyModulesRegistryChangeSets" After="InstallFiles" Condition="NOT Installed" />
|
||||
<Custom Action="InstallCmdPalPackage" After="InstallFiles" Condition="NOT Installed" />
|
||||
<Custom Action="InstallPackageIdentityMSIX" After="InstallFiles" Condition="NOT Installed" />
|
||||
<Custom Action="override Wix4CloseApplications_$(sys.BUILDARCHSHORT)" Before="RemoveFiles" />
|
||||
<Custom Action="RemovePowerToysSchTasks" After="RemoveFiles" />
|
||||
<!-- TODO: Use to activate embedded MSIX -->
|
||||
@@ -146,7 +144,6 @@
|
||||
<Custom Action="UnRegisterCmdPalPackage" Before="RemoveFiles" Condition="Installed AND (NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")" />
|
||||
<Custom Action="UninstallCommandNotFound" Before="RemoveFiles" Condition="Installed AND (NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")" />
|
||||
<Custom Action="UpgradeCommandNotFound" After="InstallFiles" Condition="WIX_UPGRADE_DETECTED" />
|
||||
<Custom Action="UninstallPackageIdentityMSIX" Before="RemoveFiles" Condition="Installed AND (NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")" />
|
||||
<Custom Action="UninstallServicesTask" After="InstallFinalize" Condition="Installed AND (NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")" />
|
||||
<!-- TODO: Use to activate embedded MSIX -->
|
||||
<!--<Custom Action="UninstallEmbeddedMSIXTask" After="InstallFinalize">
|
||||
@@ -202,12 +199,6 @@
|
||||
|
||||
<CustomAction Id="UninstallEmbeddedMSIXTask" Return="ignore" Impersonate="yes" DllEntry="UninstallEmbeddedMSIXCA" BinaryRef="PTCustomActions" />
|
||||
|
||||
<CustomAction Id="SetInstallPackageIdentityMSIXParam" Property="InstallPackageIdentityMSIX" Value="[INSTALLFOLDER];[InstallScope]" />
|
||||
|
||||
<CustomAction Id="InstallPackageIdentityMSIX" Return="ignore" Impersonate="yes" Execute="deferred" DllEntry="InstallPackageIdentityMSIXCA" BinaryRef="PTCustomActions" />
|
||||
|
||||
<CustomAction Id="UninstallPackageIdentityMSIX" Return="ignore" Impersonate="yes" DllEntry="UninstallPackageIdentityMSIXCA" BinaryRef="PTCustomActions" />
|
||||
|
||||
<CustomAction Id="InstallDSCModule" Return="ignore" Impersonate="yes" Execute="deferred" DllEntry="InstallDSCModuleCA" BinaryRef="PTCustomActions" />
|
||||
|
||||
<CustomAction Id="UninstallDSCModule" Return="ignore" Impersonate="yes" DllEntry="UninstallDSCModuleCA" BinaryRef="PTCustomActions" />
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Sparse package manifest (moved to PackageIdentity folder for cleaner organization).
|
||||
Based on Windows AI Foundry WPF sparse sample with PowerOCR customizations. -->
|
||||
<Package
|
||||
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
|
||||
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
|
||||
xmlns:uap2="http://schemas.microsoft.com/appx/manifest/uap/windows10/2"
|
||||
xmlns:uap3="http://schemas.microsoft.com/appx/manifest/uap/windows10/3"
|
||||
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
|
||||
xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10"
|
||||
xmlns:uap10="http://schemas.microsoft.com/appx/manifest/uap/windows10/10"
|
||||
xmlns:systemai="http://schemas.microsoft.com/appx/manifest/systemai/windows10"
|
||||
IgnorableNamespaces="uap uap2 uap3 rescap desktop uap10 systemai">
|
||||
<Identity
|
||||
Name="Microsoft.PowerToys.SparseApp"
|
||||
Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US"
|
||||
Version="0.0.1.0" />
|
||||
|
||||
<Properties>
|
||||
<DisplayName>PowerToys.SparseApp</DisplayName>
|
||||
<PublisherDisplayName>PowerToys</PublisherDisplayName>
|
||||
<Logo>Images\StoreLogo.png</Logo>
|
||||
<uap10:AllowExternalContent>true</uap10:AllowExternalContent>
|
||||
</Properties>
|
||||
|
||||
<Resources>
|
||||
<Resource Language="en-us" />
|
||||
</Resources>
|
||||
<Dependencies>
|
||||
<TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.19000.0" MaxVersionTested="10.0.26226.0" />
|
||||
</Dependencies>
|
||||
<Capabilities>
|
||||
<rescap:Capability Name="runFullTrust" />
|
||||
<systemai:Capability Name="systemAIModels"/>
|
||||
<rescap:Capability Name="unvirtualizedResources"/>
|
||||
</Capabilities>
|
||||
|
||||
<Applications>
|
||||
<Application Id="PowerToys.OCR" Executable="PowerToys.PowerOCR.exe" uap10:TrustLevel="mediumIL" uap10:RuntimeBehavior="win32App">
|
||||
<uap:VisualElements
|
||||
DisplayName="PowerToys.OCR"
|
||||
Description="PowerToys OCR Module"
|
||||
BackgroundColor="transparent"
|
||||
Square150x150Logo="Images\Square150x150Logo.png"
|
||||
Square44x44Logo="Images\Square44x44Logo.png">
|
||||
</uap:VisualElements>
|
||||
</Application>
|
||||
<Application Id="PowerToys.SettingsUI" Executable="PowerToys.Settings.exe" uap10:TrustLevel="mediumIL" uap10:RuntimeBehavior="win32App">
|
||||
<uap:VisualElements
|
||||
DisplayName="PowerToys.SettingsUI"
|
||||
Description="PowerToys Settings UI"
|
||||
BackgroundColor="transparent"
|
||||
Square150x150Logo="Images\Square150x150Logo.png"
|
||||
Square44x44Logo="Images\Square44x44Logo.png">
|
||||
</uap:VisualElements>
|
||||
</Application>
|
||||
<Application Id="PowerToys.ImageResizerUI" Executable="WinUI3Apps\PowerToys.ImageResizer.exe" uap10:TrustLevel="mediumIL" uap10:RuntimeBehavior="win32App">
|
||||
<uap:VisualElements
|
||||
DisplayName="PowerToys.ImageResizer"
|
||||
Description="PowerToys Image Resizer UI"
|
||||
BackgroundColor="transparent"
|
||||
Square150x150Logo="Images\Square150x150Logo.png"
|
||||
Square44x44Logo="Images\Square44x44Logo.png">
|
||||
</uap:VisualElements>
|
||||
</Application>
|
||||
</Applications>
|
||||
</Package>
|
||||
@@ -1,6 +0,0 @@
|
||||
@echo off
|
||||
REM Wrapper to invoke PowerToys sparse package build script.
|
||||
REM Pass through all arguments (e.g. Platform=arm64 Configuration=Debug -Clean)
|
||||
|
||||
powershell -ExecutionPolicy Bypass -NoLogo -NoProfile -File "%~dp0\BuildSparsePackage.ps1" %*
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -1,422 +0,0 @@
|
||||
#Requires -Version 5.1
|
||||
|
||||
[CmdletBinding()]
|
||||
Param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
[ValidateSet("arm64", "x64")]
|
||||
[string]$Platform = "x64",
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[ValidateSet("Debug", "Release")]
|
||||
[string]$Configuration = "Release",
|
||||
|
||||
[switch]$Clean,
|
||||
[switch]$ForceCert,
|
||||
[switch]$NoSign,
|
||||
[switch]$CIBuild
|
||||
)
|
||||
|
||||
# PowerToys sparse packaging helper.
|
||||
# Generates a sparse MSIX (no payload) that grants package identity to selected Win32 components.
|
||||
# Multiple applications (PowerOCR, Settings UI, etc.) can share this single sparse identity.
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$isCIBuild = $false
|
||||
if ($CIBuild.IsPresent) {
|
||||
$isCIBuild = $true
|
||||
} elseif ($env:CIBuild) {
|
||||
$isCIBuild = $env:CIBuild -ieq 'true'
|
||||
}
|
||||
|
||||
$currentPublisherHint = $script:Config.CertSubject
|
||||
|
||||
# Configuration constants - centralized management
|
||||
$script:Config = @{
|
||||
IdentityName = "Microsoft.PowerToys.SparseApp"
|
||||
SparseMsixName = "PowerToysSparse.msix"
|
||||
CertPrefix = "PowerToysSparse"
|
||||
CertSubject = 'CN=PowerToys Dev, O=PowerToys, L=Redmond, S=Washington, C=US'
|
||||
CertValidMonths = 12
|
||||
}
|
||||
|
||||
#region Helper Functions
|
||||
|
||||
function Find-WindowsSDKTool {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$ToolName,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$Architecture = "x64"
|
||||
)
|
||||
|
||||
# Simple fallback: check common Windows SDK locations
|
||||
$commonPaths = @(
|
||||
"${env:ProgramFiles}\Windows Kits\10\bin\*\$Architecture\$ToolName",
|
||||
"${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\$Architecture\$ToolName",
|
||||
"${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x86\$ToolName" # SignTool fallback
|
||||
)
|
||||
|
||||
foreach ($pattern in $commonPaths) {
|
||||
$found = Get-ChildItem $pattern -ErrorAction SilentlyContinue |
|
||||
Sort-Object Name -Descending |
|
||||
Select-Object -First 1
|
||||
if ($found) {
|
||||
Write-BuildLog "Found $ToolName at: $($found.FullName)" -Level Info
|
||||
return $found.FullName
|
||||
}
|
||||
}
|
||||
|
||||
throw "$ToolName not found. Please ensure Windows SDK is installed."
|
||||
}
|
||||
|
||||
function Test-CertificateValidity {
|
||||
param([string]$ThumbprintFile)
|
||||
|
||||
if (-not (Test-Path $ThumbprintFile)) { return $false }
|
||||
|
||||
try {
|
||||
$thumb = (Get-Content $ThumbprintFile -Raw).Trim()
|
||||
if (-not $thumb) { return $false }
|
||||
$cert = Get-Item "cert:\CurrentUser\My\$thumb" -ErrorAction Stop
|
||||
return $cert.HasPrivateKey -and $cert.NotAfter -gt (Get-Date)
|
||||
} catch {
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
function Write-BuildLog {
|
||||
param([string]$Message, [string]$Level = "Info")
|
||||
|
||||
$colors = @{ Error = "Red"; Warning = "Yellow"; Success = "Green"; Info = "Cyan" }
|
||||
$color = if ($colors.ContainsKey($Level)) { $colors[$Level] } else { "White" }
|
||||
|
||||
Write-Host "[$(Get-Date -f 'HH:mm:ss')] $Message" -ForegroundColor $color
|
||||
}
|
||||
|
||||
function Stop-FileProcesses {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$FilePath
|
||||
)
|
||||
|
||||
# This function is kept for compatibility but simplified since
|
||||
# the staging directory approach resolves the file lock issues
|
||||
Write-Verbose "File process check for: $FilePath"
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
# Environment diagnostics for troubleshooting
|
||||
Write-BuildLog "Starting PackageIdentity build process..." -Level Info
|
||||
Write-BuildLog "PowerShell Version: $($PSVersionTable.PSVersion)" -Level Info
|
||||
try {
|
||||
$execPolicy = Get-ExecutionPolicy
|
||||
Write-BuildLog "Execution Policy: $execPolicy" -Level Info
|
||||
} catch {
|
||||
Write-BuildLog "Execution Policy: Unable to determine (MSBuild environment)" -Level Info
|
||||
}
|
||||
Write-BuildLog "Current User: $env:USERNAME" -Level Info
|
||||
Write-BuildLog "Build Platform: $Platform, Configuration: $Configuration" -Level Info
|
||||
|
||||
# Check for Visual Studio environment
|
||||
if ($env:VSINSTALLDIR) {
|
||||
Write-BuildLog "Running in Visual Studio environment: $env:VSINSTALLDIR" -Level Info
|
||||
}
|
||||
|
||||
# Ensure certificate provider is available
|
||||
try {
|
||||
# Force load certificate provider for MSBuild environment
|
||||
if (-not (Get-PSProvider -PSProvider Certificate -ErrorAction SilentlyContinue)) {
|
||||
Write-BuildLog "Loading certificate provider..." -Level Warning
|
||||
Import-Module Microsoft.PowerShell.Security -Force
|
||||
}
|
||||
if (-not (Test-Path 'Cert:\CurrentUser')) {
|
||||
Write-BuildLog "Certificate drive not available, attempting to initialize..." -Level Warning
|
||||
Import-Module PKI -ErrorAction SilentlyContinue
|
||||
# Try to access the certificate store to force initialization
|
||||
Get-ChildItem "Cert:\CurrentUser\My" -ErrorAction SilentlyContinue | Out-Null
|
||||
}
|
||||
} catch {
|
||||
Write-BuildLog ("Note: Certificate provider setup may need manual configuration: {0}" -f $_) -Level Warning
|
||||
}
|
||||
|
||||
# Project root folder (now set to current script folder for local builds)
|
||||
$ProjectRoot = $PSScriptRoot
|
||||
$UserFolder = Join-Path $ProjectRoot '.user'
|
||||
if (-not (Test-Path $UserFolder)) { New-Item -ItemType Directory -Path $UserFolder | Out-Null }
|
||||
|
||||
# Certificate file paths using configuration
|
||||
$prefix = $script:Config.CertPrefix
|
||||
$CertThumbFile, $CertCerFile = @('.thumbprint', '.cer') |
|
||||
ForEach-Object { Join-Path $UserFolder "$prefix.certificate.sample$_" }
|
||||
|
||||
# Clean option: remove bin/obj and uninstall existing sparse package if present
|
||||
if ($Clean) {
|
||||
Write-BuildLog "Cleaning build artifacts..." -Level Info
|
||||
'bin','obj' | ForEach-Object {
|
||||
$target = Join-Path $ProjectRoot $_
|
||||
if (Test-Path $target) { Remove-Item $target -Recurse -Force }
|
||||
}
|
||||
Write-BuildLog "Attempting to remove existing sparse package (best effort)" -Level Info
|
||||
try { Get-AppxPackage -Name $script:Config.IdentityName | Remove-AppxPackage } catch {}
|
||||
}
|
||||
|
||||
# Force certificate regeneration if requested
|
||||
if ($ForceCert -and (Test-Path $UserFolder)) {
|
||||
Write-BuildLog "ForceCert specified: removing existing certificate artifacts..." -Level Warning
|
||||
Remove-Item $UserFolder -Recurse -Force
|
||||
New-Item -ItemType Directory -Path $UserFolder | Out-Null
|
||||
}
|
||||
|
||||
# Ensure dev cert (development only; not for production use) - skip if NoSign specified
|
||||
$needNewCert = -not $NoSign -and (-not (Test-Path $CertThumbFile) -or $ForceCert -or -not (Test-CertificateValidity -ThumbprintFile $CertThumbFile))
|
||||
|
||||
if ($needNewCert) {
|
||||
Write-BuildLog "Generating development certificate (prefix=$($script:Config.CertPrefix))..." -Level Info
|
||||
|
||||
# Clear stale files in the certificate cache
|
||||
if (Test-Path $UserFolder) {
|
||||
Get-ChildItem -Path $UserFolder | ForEach-Object {
|
||||
if ($_.PSIsContainer) {
|
||||
Remove-Item $_.FullName -Recurse -Force
|
||||
} else {
|
||||
Remove-Item $_.FullName -Force
|
||||
}
|
||||
}
|
||||
}
|
||||
if (-not (Test-Path $UserFolder)) {
|
||||
New-Item -ItemType Directory -Path $UserFolder | Out-Null
|
||||
}
|
||||
|
||||
$now = Get-Date
|
||||
$expiration = $now.AddMonths($script:Config.CertValidMonths)
|
||||
# Subject MUST match <Identity Publisher="..."> inside AppxManifest.xml
|
||||
$friendlyName = "PowerToys Dev Sparse Cert Create=$now"
|
||||
$keyFriendly = "PowerToys Dev Sparse Key Create=$now"
|
||||
|
||||
$certStore = 'cert:\CurrentUser\My'
|
||||
$ekuOid = '2.5.29.37'
|
||||
$ekuValue = '1.3.6.1.5.5.7.3.3,1.3.6.1.4.1.311.10.3.13'
|
||||
$eku = "$ekuOid={text}$ekuValue"
|
||||
|
||||
$cert = New-SelfSignedCertificate -CertStoreLocation $certStore `
|
||||
-NotAfter $expiration `
|
||||
-Subject $script:Config.CertSubject `
|
||||
-FriendlyName $friendlyName `
|
||||
-KeyFriendlyName $keyFriendly `
|
||||
-KeyDescription $keyFriendly `
|
||||
-TextExtension $eku
|
||||
|
||||
# Export certificate files
|
||||
Set-Content -Path $CertThumbFile -Value $cert.Thumbprint -Force
|
||||
Export-Certificate -Cert $cert -FilePath $CertCerFile -Force | Out-Null
|
||||
}
|
||||
|
||||
# Determine output directory - using PowerToys standard structure
|
||||
# Navigate to PowerToys root (two levels up from src/PackageIdentity)
|
||||
$PowerToysRoot = Split-Path (Split-Path $ProjectRoot -Parent) -Parent
|
||||
$outDir = Join-Path $PowerToysRoot "$Platform\$Configuration"
|
||||
|
||||
if (-not (Test-Path $outDir)) {
|
||||
Write-BuildLog "Creating output directory: $outDir" -Level Info
|
||||
New-Item -ItemType Directory -Path $outDir -Force | Out-Null
|
||||
}
|
||||
|
||||
# PackageIdentity folder (this script location) containing the sparse manifest and assets
|
||||
$sparseDir = $PSScriptRoot
|
||||
$manifestPath = Join-Path $sparseDir 'AppxManifest.xml'
|
||||
if (-not (Test-Path $manifestPath)) { throw "Missing AppxManifest.xml in PackageIdentity folder: $manifestPath" }
|
||||
|
||||
$versionPropsPath = Join-Path $PowerToysRoot 'src\Version.props'
|
||||
$targetManifestVersion = $null
|
||||
$versionCandidate = $null
|
||||
if (Test-Path $versionPropsPath) {
|
||||
try {
|
||||
[xml]$propsXml = Get-Content -Path $versionPropsPath -Raw
|
||||
$versionCandidate = $propsXml.Project.PropertyGroup.Version
|
||||
} catch {
|
||||
Write-BuildLog ("Unable to read version from {0}: {1}" -f $versionPropsPath, $_) -Level Warning
|
||||
}
|
||||
} else {
|
||||
Write-BuildLog "Version.props not found at $versionPropsPath; manifest version will remain unchanged." -Level Warning
|
||||
}
|
||||
|
||||
if ($versionCandidate) {
|
||||
$targetManifestVersion = $versionCandidate.Trim()
|
||||
if (($targetManifestVersion -split '\.').Count -lt 4) {
|
||||
$targetManifestVersion = "$targetManifestVersion.0"
|
||||
}
|
||||
Write-BuildLog "Using sparse package version from Version.props: $targetManifestVersion" -Level Info
|
||||
} else {
|
||||
Write-BuildLog "No version value provided; manifest version will remain unchanged." -Level Info
|
||||
}
|
||||
|
||||
# Find MakeAppx.exe from Windows SDK
|
||||
try {
|
||||
$hostSdkArchitecture = if ([System.Environment]::Is64BitProcess) { 'x64' } else { 'x86' }
|
||||
$makeAppxPath = Find-WindowsSDKTool -ToolName "makeappx.exe" -Architecture $hostSdkArchitecture
|
||||
} catch {
|
||||
Write-Error "MakeAppx.exe not found. Please ensure Windows SDK is installed."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Pack sparse MSIX from PackageIdentity folder
|
||||
$msixPath = Join-Path $outDir $script:Config.SparseMsixName
|
||||
|
||||
# Clean up existing MSIX file
|
||||
if (Test-Path $msixPath) {
|
||||
Write-BuildLog "Removing existing MSIX file..." -Level Info
|
||||
try {
|
||||
Remove-Item $msixPath -Force -ErrorAction Stop
|
||||
Write-BuildLog "Successfully removed existing MSIX file" -Level Success
|
||||
} catch {
|
||||
Write-BuildLog ("Warning: Could not remove existing MSIX file: {0}" -f $_) -Level Warning
|
||||
}
|
||||
}
|
||||
|
||||
# Create a clean staging directory to avoid file lock issues
|
||||
$stagingDir = Join-Path $outDir "staging"
|
||||
if (Test-Path $stagingDir) {
|
||||
Remove-Item $stagingDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
New-Item -ItemType Directory -Path $stagingDir -Force | Out-Null
|
||||
|
||||
try {
|
||||
Write-BuildLog "Creating clean staging directory for packaging..." -Level Info
|
||||
|
||||
# Copy only essential files to staging directory to avoid file locks
|
||||
$essentialFiles = @(
|
||||
"AppxManifest.xml"
|
||||
"Images\*"
|
||||
)
|
||||
|
||||
foreach ($filePattern in $essentialFiles) {
|
||||
$sourcePath = Join-Path $sparseDir $filePattern
|
||||
$relativePath = $filePattern
|
||||
|
||||
if ($filePattern.Contains('\')) {
|
||||
$targetDir = Join-Path $stagingDir (Split-Path $relativePath -Parent)
|
||||
if (-not (Test-Path $targetDir)) {
|
||||
New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
if ($filePattern.EndsWith('\*')) {
|
||||
# Copy directory contents
|
||||
$sourceDir = $sourcePath.TrimEnd('\*')
|
||||
$targetDir = Join-Path $stagingDir (Split-Path $relativePath.TrimEnd('\*') -Parent)
|
||||
if (Test-Path $sourceDir) {
|
||||
Copy-Item -Path "$sourceDir\*" -Destination $targetDir -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
} else {
|
||||
# Copy single file
|
||||
$targetPath = Join-Path $stagingDir $relativePath
|
||||
if (Test-Path $sourcePath) {
|
||||
Copy-Item -Path $sourcePath -Destination $targetPath -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Ensure publisher matches the dev certificate for local builds
|
||||
$manifestStagingPath = Join-Path $stagingDir 'AppxManifest.xml'
|
||||
$shouldUseDevPublisher = -not $isCIBuild
|
||||
if (Test-Path $manifestStagingPath) {
|
||||
try {
|
||||
[xml]$manifestXml = Get-Content -Path $manifestStagingPath -Raw
|
||||
$identityNode = $manifestXml.Package.Identity
|
||||
$manifestChanged = $false
|
||||
if ($identityNode) {
|
||||
$currentPublisherHint = $identityNode.Publisher
|
||||
}
|
||||
|
||||
if ($identityNode) {
|
||||
if ($targetManifestVersion -and $identityNode.Version -ne $targetManifestVersion) {
|
||||
Write-BuildLog "Updating manifest version to $targetManifestVersion" -Level Info
|
||||
$identityNode.SetAttribute('Version', $targetManifestVersion)
|
||||
$manifestChanged = $true
|
||||
}
|
||||
|
||||
if ($shouldUseDevPublisher -and $identityNode.Publisher -ne $script:Config.CertSubject) {
|
||||
Write-BuildLog "Updating manifest publisher for local build" -Level Warning
|
||||
$identityNode.SetAttribute('Publisher', $script:Config.CertSubject)
|
||||
$manifestChanged = $true
|
||||
}
|
||||
$currentPublisherHint = $identityNode.Publisher
|
||||
}
|
||||
|
||||
if ($manifestChanged) {
|
||||
$manifestXml.Save($manifestStagingPath)
|
||||
}
|
||||
} catch {
|
||||
Write-BuildLog ("Unable to adjust manifest metadata: {0}" -f $_) -Level Warning
|
||||
}
|
||||
}
|
||||
|
||||
Write-BuildLog "Staging directory prepared with essential files only" -Level Success
|
||||
|
||||
# Pack MSIX using staging directory
|
||||
Write-BuildLog "Packing sparse MSIX ($($script:Config.SparseMsixName)) from staging -> $msixPath" -Level Info
|
||||
|
||||
& $makeAppxPath pack /d $stagingDir /p $msixPath /nv /o
|
||||
|
||||
if ($LASTEXITCODE -eq 0 -and (Test-Path $msixPath)) {
|
||||
Write-BuildLog "MSIX packaging completed successfully" -Level Success
|
||||
} else {
|
||||
Write-BuildLog "MakeAppx failed with exit code $LASTEXITCODE" -Level Error
|
||||
exit 1
|
||||
}
|
||||
} finally {
|
||||
# Clean up staging directory
|
||||
if (Test-Path $stagingDir) {
|
||||
try {
|
||||
Remove-Item $stagingDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Write-BuildLog "Cleaned up staging directory" -Level Info
|
||||
} catch {
|
||||
Write-BuildLog ("Warning: Could not clean up staging directory: {0}" -f $_) -Level Warning
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Sign package (skip if NoSign specified for CI scenarios)
|
||||
if ($NoSign) {
|
||||
Write-BuildLog "Skipping signing (NoSign specified for CI build)" -Level Warning
|
||||
} else {
|
||||
# Use certificate thumbprint for signing (safer, no password)
|
||||
$certThumbprint = (Get-Content -Path $CertThumbFile -Raw).Trim()
|
||||
try {
|
||||
$signToolPath = Find-WindowsSDKTool -ToolName "signtool.exe"
|
||||
} catch {
|
||||
Write-Error "SignTool.exe not found. Please ensure Windows SDK is installed."
|
||||
exit 1
|
||||
}
|
||||
Write-BuildLog "Signing sparse MSIX using cert thumbprint $certThumbprint..." -Level Info
|
||||
& $signToolPath sign /fd SHA256 /sha1 $certThumbprint $msixPath
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Warning "SignTool failed (exit $LASTEXITCODE). Ensure the certificate is in CurrentUser\\My and try -ForceCert if needed."
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
}
|
||||
|
||||
$publisherHintFile = Join-Path $UserFolder "$($script:Config.CertPrefix).publisher.txt"
|
||||
try {
|
||||
Set-Content -Path $publisherHintFile -Value $currentPublisherHint -Force -NoNewline
|
||||
} catch {
|
||||
Write-BuildLog ("Unable to write publisher hint: {0}" -f $_) -Level Warning
|
||||
}
|
||||
|
||||
Write-BuildLog "`nPackage created: $msixPath" -Level Success
|
||||
|
||||
if ($NoSign) {
|
||||
Write-BuildLog "UNSIGNED package created for CI build. Sign before deployment." -Level Warning
|
||||
} else {
|
||||
Write-BuildLog "Install the dev certificate (once): $CertCerFile" -Level Info
|
||||
Write-BuildLog "Identity Name: $($script:Config.IdentityName)" -Level Info
|
||||
}
|
||||
|
||||
Write-BuildLog "Register sparse package:" -Level Info
|
||||
Write-BuildLog " Add-AppxPackage -Path `"$msixPath`" -ExternalLocation `"$outDir`"" -Level Warning
|
||||
Write-BuildLog "(If already installed and you changed manifest only): Add-AppxPackage -Register `"$manifestPath`" -ExternalLocation `"$outDir`" -ForceApplicationShutdown" -Level Warning
|
||||
@@ -1,43 +0,0 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Determine whether a given process (by PID) runs with an MSIX/UWP package identity.
|
||||
.DESCRIPTION
|
||||
Calls the Windows API GetPackageFullName to check if the target process executes under an MSIX/Sparse App/UWP package identity.
|
||||
Returns the package full name when identity is present, or "No package identity" otherwise.
|
||||
.PARAMETER ProcessId
|
||||
The process ID to inspect.
|
||||
.EXAMPLE
|
||||
.\Check-ProcessIdentity.ps1 -pid 12345
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory=$true)]
|
||||
[int]$ProcessId
|
||||
)
|
||||
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
public class P {
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
public static extern IntPtr OpenProcess(uint a, bool b, int p);
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
public static extern bool CloseHandle(IntPtr h);
|
||||
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
|
||||
public static extern int GetPackageFullName(IntPtr h, ref int l, StringBuilder b);
|
||||
public static string G(int pid) {
|
||||
IntPtr h = OpenProcess(0x1000, false, pid);
|
||||
if (h == IntPtr.Zero) return "Failed to open process";
|
||||
int len = 0;
|
||||
GetPackageFullName(h, ref len, null);
|
||||
if (len == 0) { CloseHandle(h); return "No package identity"; }
|
||||
var sb = new StringBuilder(len);
|
||||
int r = GetPackageFullName(h, ref len, sb);
|
||||
CloseHandle(h);
|
||||
return r == 0 ? sb.ToString() : "Error:" + r;
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
$result = [P]::G($ProcessId)
|
||||
Write-Output $result
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 68 B |
Binary file not shown.
|
Before Width: | Height: | Size: 68 B |
Binary file not shown.
|
Before Width: | Height: | Size: 68 B |
@@ -1,120 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
|
||||
<!-- CI Build Configuration -->
|
||||
<PropertyGroup Condition="'$(CIBuild)'=='true'">
|
||||
<ForceCIPackaging>true</ForceCIPackaging>
|
||||
<NoSignCI>true</NoSignCI>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Target to generate sparse MSIX package -->
|
||||
<Target Name="GenerateSparsePackage" BeforeTargets="PrepareForBuild">
|
||||
<!-- Use NoSign only for CI builds to avoid certificate issues on hosted agents -->
|
||||
<PropertyGroup>
|
||||
<NoSignParam Condition="'$(NoSignCI)' == 'true'">-NoSign</NoSignParam>
|
||||
<NoSignParam Condition="'$(NoSignCI)' != 'true'"></NoSignParam>
|
||||
<CIBuildParam Condition="'$(CIBuild)' == 'true'">-CIBuild</CIBuildParam>
|
||||
<CIBuildParam Condition="'$(CIBuild)' != 'true'"></CIBuildParam>
|
||||
</PropertyGroup>
|
||||
|
||||
<Exec Command="powershell -NonInteractive -ExecutionPolicy Bypass -File "$(MSBuildThisFileDirectory)BuildSparsePackage.ps1" -Platform $(Platform) -Configuration $(Configuration) $(NoSignParam) $(CIBuildParam)"
|
||||
ContinueOnError="false"
|
||||
WorkingDirectory="$(MSBuildThisFileDirectory)" />
|
||||
</Target>
|
||||
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|ARM64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>ARM64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|ARM64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>ARM64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup Label="Globals">
|
||||
<VCProjectVersion>15.0</VCProjectVersion>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
<ProjectGuid>{E2A5A82E-1E5B-4C8D-9A4F-2B1A8F9E5C3D}</ProjectGuid>
|
||||
<RootNamespace>PackageIdentity</RootNamespace>
|
||||
<ProjectName>PackageIdentity</ProjectName>
|
||||
<UseFastUpToDateCheck>false</UseFastUpToDateCheck>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Utility</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Utility</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration">
|
||||
<ConfigurationType>Utility</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="Configuration">
|
||||
<ConfigurationType>Utility</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
|
||||
<ImportGroup Label="Shared">
|
||||
</ImportGroup>
|
||||
|
||||
<ImportGroup Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="..\Solution.props" />
|
||||
</ImportGroup>
|
||||
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="AppxManifest.xml" />
|
||||
<None Include="BuildSparsePackage.ps1" />
|
||||
<None Include="BuildSparsePackage.cmd" />
|
||||
<None Include="Check-ProcessIdentity.ps1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Image Include="Images\Square150x150Logo.png">
|
||||
<Filter>Images</Filter>
|
||||
</Image>
|
||||
<Image Include="Images\Square44x44Logo.png">
|
||||
<Filter>Images</Filter>
|
||||
</Image>
|
||||
<Image Include="Images\StoreLogo.png">
|
||||
<Filter>Images</Filter>
|
||||
</Image>
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,25 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup>
|
||||
<Filter Include="Images">
|
||||
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
|
||||
<Extensions>png;jpg;jpeg;gif;bmp;ico</Extensions>
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="AppxManifest.xml" />
|
||||
<None Include="BuildSparsePackage.ps1" />
|
||||
<None Include="BuildSparsePackage.cmd" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Image Include="Images\Square150x150Logo.png">
|
||||
<Filter>Images</Filter>
|
||||
</Image>
|
||||
<Image Include="Images\Square44x44Logo.png">
|
||||
<Filter>Images</Filter>
|
||||
</Image>
|
||||
<Image Include="Images\StoreLogo.png">
|
||||
<Filter>Images</Filter>
|
||||
</Image>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,90 +0,0 @@
|
||||
# PowerToys sparse package identity
|
||||
|
||||
This document describes how to build, sign, register, and consume the shared sparse MSIX package that grants package identity to select Win32 components of PowerToys.
|
||||
|
||||
## Package overview
|
||||
|
||||
The sparse package lives under `src/PackageIdentity`. It produces a payload-free MSIX whose `Identity` matches `Microsoft.PowerToys.SparseApp`. The manifest contains one entry per Win32 surface that should run with identity (for example Settings, PowerOCR, Image Resizer).
|
||||
|
||||
> The MSIX contains only metadata. When the package is registered you must point `-ExternalLocation` to the output folder that hosts the Win32 binaries (for example `x64\Release`).
|
||||
|
||||
## Building the sparse package locally
|
||||
|
||||
Two options are available:
|
||||
|
||||
- Build the utility project from Visual Studio: `PackageIdentity.vcxproj` defines a `GenerateSparsePackage` target that runs before `PrepareForBuild` and invokes the helper script automatically.
|
||||
- Invoke the helper script directly from PowerShell:
|
||||
|
||||
```powershell
|
||||
$repoRoot = "C:/git/PowerToys"
|
||||
pwsh "$repoRoot/src/PackageIdentity/BuildSparsePackage.ps1" -Platform x64 -Configuration Release
|
||||
```
|
||||
|
||||
Supported switches:
|
||||
|
||||
- `-Clean` removes previous `bin`/`obj` outputs and uninstalls existing installation.
|
||||
- `-ForceCert` regenerates the local dev certificate (.pfx/.cer/.pwd/.thumbprint) under `src/PackageIdentity/.user`.
|
||||
- `-NoSign` skips signing. The MSIX still builds but must be signed before deployment.
|
||||
- `-CIBuild` (or setting `$env:CIBuild = 'true'`) keeps the manifest publisher intact and skips the local cert substitution.
|
||||
|
||||
The script determines the proper `makeappx.exe` for the host build machine (x64 on typical developer boxes) and creates `PowerToysSparse.msix` in `{repo}\<Platform>\<Configuration>`.
|
||||
|
||||
> After packaging finishes, the helper also emits `src/PackageIdentity/.user/PowerToysSparse.publisher.txt`. This file mirrors the publisher string Windows will see once the sparse package is registered, which downstream projects can read to stay in sync when generating their own manifests.
|
||||
|
||||
## Local signing basics
|
||||
|
||||
When `-NoSign` is not used the script generates (or reuses) a development certificate and signs the package via `signtool.exe`:
|
||||
|
||||
1. Artifacts are stored in `src/PackageIdentity/.user/PowerToysSparse.certificate.sample.*` (`.cer` and `.thumbprint`).
|
||||
2. Install the `.cer` into `CurrentUser` → `TrustedPeople` (and `TrustedRoot`, if necessary) so Windows trusts the signature:
|
||||
|
||||
```powershell
|
||||
$repoRoot = "C:/git/PowerToys"
|
||||
Import-Certificate -FilePath "$repoRoot/src/PackageIdentity/.user/PowerToysSparse.certificate.sample.cer" -CertStoreLocation Cert:\CurrentUser\TrustedPeople
|
||||
```
|
||||
|
||||
3. The private key stays in the current user's personal certificate store.
|
||||
|
||||
## Registering or unregistering the package
|
||||
|
||||
After `PowerToysSparse.msix` is generated:
|
||||
|
||||
```powershell
|
||||
# First time registration
|
||||
$repoRoot = "C:/git/PowerToys"
|
||||
$outputRoot = Join-Path $repoRoot "x64/Release"
|
||||
Add-AppxPackage -Path (Join-Path $outputRoot "PowerToysSparse.msix") -ExternalLocation $outputRoot
|
||||
|
||||
# Re-register after manifest tweaks only
|
||||
Add-AppxPackage -Register (Join-Path $repoRoot "src/PackageIdentity/AppxManifest.xml") -ExternalLocation $outputRoot -ForceApplicationShutdown
|
||||
|
||||
# Remove the sparse identity
|
||||
Get-AppxPackage -Name Microsoft.PowerToys.SparseApp | Remove-AppxPackage
|
||||
```
|
||||
|
||||
`-ExternalLocation` should match the output folder that contains the Win32 executables declared in the manifest. Re-run registration whenever the manifest or executable layout changes.
|
||||
|
||||
## CI-specific guidance
|
||||
|
||||
- Pass `-CIBuild` to `BuildSparsePackage.ps1` (or build with `msbuild PackageIdentity.vcxproj /p:CIBuild=true`). This prevents the script from rewriting the manifest publisher to the local dev certificate subject.
|
||||
- The project automatically adds `-NoSign` only when `$(CIBuild)` is `true`. Local Debug and Release builds are signed with the development certificate.
|
||||
- Make sure the agent trusts whichever certificate signs the package. If the package remains unsigned (`-NoSign`) it cannot be installed on test machines until it is signed.
|
||||
|
||||
## Consuming the identity from other components
|
||||
|
||||
1. Add a new `<Application>` entry inside `src/PackageIdentity/AppxManifest.xml`. Use a unique `Id` (for example `PowerToys.MyModuleUI`) and set `Executable` to the Win32 binary relative to the `-ExternalLocation` root.
|
||||
2. Ensure the binary is copied into the platform/configuration output folder (`x64\Release`, `ARM64\Debug`, etc.) so the sparse package can locate it.
|
||||
3. Embed a sparse identity manifest in the Win32 binary so it binds to the MSIX identity at runtime. The manifest must declare an `<msix>` element with `packageName="Microsoft.PowerToys.SparseApp"`, `applicationId` matching the `<Application Id>`, and a `publisher` that matches the sparse package. Keep the manifest’s publisher in sync with `src/PackageIdentity/.user/PowerToysSparse.publisher.txt` (emitted by `BuildSparsePackage.ps1`). See `src/modules/imageresizer/ui/ImageResizerUI.csproj` for an example that points `ApplicationManifest` to `ImageResizerUI.dev.manifest` for local builds and switches to `ImageResizerUI.prod.manifest` when `$(CIBuild)` is `true`.
|
||||
4. Register or re-register the sparse package so Windows learns about the new application Id.
|
||||
5. To launch the Win32 surface with identity, use the `shell:AppsFolder` activation form (for example: `shell:AppsFolder\Microsoft.PowerToys.SparseApp_<PackageFamilyName>!PowerToys.MyModuleUI`) or activate it via `IApplicationActivationManager::ActivateApplication` using the same AppUserModelID.
|
||||
|
||||
- For locally built packages, resolve the `<PackageFamilyName>` with `Get-AppxPackage -Name Microsoft.PowerToys.SparseApp | Select-Object -ExpandProperty PackageFamilyName`.
|
||||
- Store-distributed builds use `Microsoft.PowerToys.SparseApp_8wekyb3d8bbwe`. Local developer builds created by this script typically use a different family name derived from the dev certificate.
|
||||
|
||||
6. Context menu handlers or other launchers should fall back to the unpackaged executable path for environments where the sparse package is not present.
|
||||
|
||||
## Troubleshooting tips
|
||||
|
||||
- `Program 'makeappx.exe' failed to run`: make sure you are running an x64 PowerShell host. The script now chooses the appropriate makeappx automatically; update your repo if the log still points to an ARM64 binary.
|
||||
- `HRESULT 0x800B0109 (trust failure)`: install the development certificate into both `TrustedPeople` and `TrustedRoot` stores for the current user.
|
||||
- Stale registration: remove the package with `Remove-AppxPackage` and re-run the script with `-Clean` to rebuild from scratch.
|
||||
@@ -1,4 +1,4 @@
|
||||
#include <windows.h>
|
||||
#include <windows.h>
|
||||
#include <tchar.h>
|
||||
#include "ThemeScheduler.h"
|
||||
#include "ThemeHelper.h"
|
||||
@@ -11,13 +11,15 @@
|
||||
#include <logger/logger_settings.h>
|
||||
#include <logger/logger.h>
|
||||
#include <utils/logger_helper.h>
|
||||
#include <LightSwitchServiceObserver.h>
|
||||
|
||||
SERVICE_STATUS g_ServiceStatus = {};
|
||||
SERVICE_STATUS_HANDLE g_StatusHandle = nullptr;
|
||||
HANDLE g_ServiceStopEvent = nullptr;
|
||||
static int g_lastUpdatedDay = -1;
|
||||
extern int g_lastUpdatedDay = -1;
|
||||
static ScheduleMode prevMode = ScheduleMode::Off;
|
||||
static std::wstring prevLat, prevLon;
|
||||
static int prevMinutes = -1;
|
||||
|
||||
VOID WINAPI ServiceMain(DWORD argc, LPTSTR* argv);
|
||||
VOID WINAPI ServiceCtrlHandler(DWORD dwCtrl);
|
||||
@@ -148,7 +150,6 @@ static void update_sun_times(auto& settings)
|
||||
std::wstring wmsg(e.what(), e.what() + strlen(e.what()));
|
||||
Logger::error(L"[LightSwitchService] Exception during sun time update: {}", wmsg);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
DWORD WINAPI ServiceWorkerThread(LPVOID lpParam)
|
||||
@@ -161,25 +162,18 @@ DWORD WINAPI ServiceWorkerThread(LPVOID lpParam)
|
||||
Logger::info(L"[LightSwitchService] Worker thread starting...");
|
||||
Logger::info(L"[LightSwitchService] Parent PID: {}", parentPid);
|
||||
|
||||
// Initialize settings system
|
||||
LightSwitchSettings::instance().InitFileWatcher();
|
||||
|
||||
// Open the manual override event created by the module interface
|
||||
LightSwitchServiceObserver observer({ SettingId::LightTime,
|
||||
SettingId::DarkTime,
|
||||
SettingId::ScheduleMode,
|
||||
SettingId::Sunrise_Offset,
|
||||
SettingId::Sunset_Offset });
|
||||
|
||||
HANDLE hManualOverride = OpenEventW(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, L"POWERTOYS_LIGHTSWITCH_MANUAL_OVERRIDE");
|
||||
|
||||
auto applyTheme = [](int nowMinutes, int lightMinutes, int darkMinutes, const auto& settings) {
|
||||
bool isLightActive = false;
|
||||
|
||||
if (lightMinutes < darkMinutes)
|
||||
{
|
||||
// Normal case: sunrise < sunset
|
||||
isLightActive = (nowMinutes >= lightMinutes && nowMinutes < darkMinutes);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Wraparound case: e.g. light at 21:00, dark at 06:00
|
||||
isLightActive = (nowMinutes >= lightMinutes || nowMinutes < darkMinutes);
|
||||
}
|
||||
bool isLightActive = (lightMinutes < darkMinutes) ? (nowMinutes >= lightMinutes && nowMinutes < darkMinutes) : (nowMinutes >= lightMinutes || nowMinutes < darkMinutes);
|
||||
|
||||
bool isSystemCurrentlyLight = GetCurrentSystemTheme();
|
||||
bool isAppsCurrentlyLight = GetCurrentAppsTheme();
|
||||
@@ -212,85 +206,72 @@ DWORD WINAPI ServiceWorkerThread(LPVOID lpParam)
|
||||
}
|
||||
};
|
||||
|
||||
// --- Initial settings load ---
|
||||
LightSwitchSettings::instance().LoadSettings();
|
||||
auto& settings = LightSwitchSettings::instance().settings();
|
||||
|
||||
// --- Initial theme application (if schedule enabled) ---
|
||||
SYSTEMTIME st;
|
||||
GetLocalTime(&st);
|
||||
int nowMinutes = st.wHour * 60 + st.wMinute;
|
||||
|
||||
if (settings.scheduleMode != ScheduleMode::Off)
|
||||
{
|
||||
SYSTEMTIME st;
|
||||
GetLocalTime(&st);
|
||||
int nowMinutes = st.wHour * 60 + st.wMinute;
|
||||
applyTheme(nowMinutes, settings.lightTime + settings.sunrise_offset, settings.darkTime + settings.sunset_offset, settings);
|
||||
applyTheme(nowMinutes,
|
||||
settings.lightTime + settings.sunrise_offset,
|
||||
settings.darkTime + settings.sunset_offset,
|
||||
settings);
|
||||
Logger::trace(L"[LightSwitchService] Initialized g_lastUpdatedDay = {}", g_lastUpdatedDay);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger::info(L"[LightSwitchService] Schedule mode is OFF - ticker suspended, waiting for manual action or mode change.");
|
||||
}
|
||||
|
||||
// --- Main loop ---
|
||||
g_lastUpdatedDay = st.wDay;
|
||||
ULONGLONG lastSettingsReload = 0;
|
||||
|
||||
for (;;)
|
||||
{
|
||||
HANDLE waits[2] = { g_ServiceStopEvent, hParent };
|
||||
DWORD count = hParent ? 2 : 1;
|
||||
bool skipRest = false;
|
||||
|
||||
LightSwitchSettings::instance().LoadSettings();
|
||||
const auto& settings = LightSwitchSettings::instance().settings();
|
||||
|
||||
// Check for changes in schedule mode or coordinates
|
||||
bool modeChangedToSunset = (prevMode != settings.scheduleMode &&
|
||||
settings.scheduleMode == ScheduleMode::SunsetToSunrise);
|
||||
bool coordsChanged = (prevLat != settings.latitude || prevLon != settings.longitude);
|
||||
bool scheduleJustEnabled = (prevMode == ScheduleMode::Off && settings.scheduleMode != ScheduleMode::Off);
|
||||
prevMode = settings.scheduleMode;
|
||||
|
||||
if ((modeChangedToSunset || coordsChanged) && settings.scheduleMode == ScheduleMode::SunsetToSunrise)
|
||||
{
|
||||
Logger::info(L"[LightSwitchService] Mode or coordinates changed, recalculating sun times.");
|
||||
update_sun_times(settings);
|
||||
SYSTEMTIME st;
|
||||
GetLocalTime(&st);
|
||||
g_lastUpdatedDay = st.wDay;
|
||||
prevMode = settings.scheduleMode;
|
||||
prevLat = settings.latitude;
|
||||
prevLon = settings.longitude;
|
||||
}
|
||||
|
||||
// If schedule is off, idle but keep watching settings and manual override
|
||||
// ─── Handle "Schedule Off" Mode ─────────────────────────────────────────────
|
||||
if (settings.scheduleMode == ScheduleMode::Off)
|
||||
{
|
||||
Logger::info(L"[LightSwitchService] Schedule mode OFF - suspending scheduler but keeping service alive.");
|
||||
|
||||
if (!hManualOverride)
|
||||
{
|
||||
hManualOverride = OpenEventW(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, L"POWERTOYS_LIGHTSWITCH_MANUAL_OVERRIDE");
|
||||
}
|
||||
|
||||
HANDLE waits[4];
|
||||
DWORD count = 0;
|
||||
waits[count++] = g_ServiceStopEvent;
|
||||
HANDLE waitsOff[4];
|
||||
DWORD countOff = 0;
|
||||
waitsOff[countOff++] = g_ServiceStopEvent;
|
||||
if (hParent)
|
||||
waits[count++] = hParent;
|
||||
waitsOff[countOff++] = hParent;
|
||||
if (hManualOverride)
|
||||
waits[count++] = hManualOverride;
|
||||
waits[count++] = LightSwitchSettings::instance().GetSettingsChangedEvent();
|
||||
waitsOff[countOff++] = hManualOverride;
|
||||
waitsOff[countOff++] = LightSwitchSettings::instance().GetSettingsChangedEvent();
|
||||
|
||||
for (;;)
|
||||
{
|
||||
DWORD wait = WaitForMultipleObjects(count, waits, FALSE, INFINITE);
|
||||
DWORD wait = WaitForMultipleObjects(countOff, waitsOff, FALSE, INFINITE);
|
||||
|
||||
// --- Handle exit signals ---
|
||||
if (wait == WAIT_OBJECT_0) // stop event
|
||||
if (wait == WAIT_OBJECT_0)
|
||||
{
|
||||
Logger::info(L"[LightSwitchService] Stop event triggered - exiting worker loop.");
|
||||
break;
|
||||
goto cleanup;
|
||||
}
|
||||
if (hParent && wait == WAIT_OBJECT_0 + 1)
|
||||
{
|
||||
Logger::info(L"[LightSwitchService] Parent exited - stopping service.");
|
||||
break;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
// --- Manual override triggered ---
|
||||
if (wait == WAIT_OBJECT_0 + (hParent ? 2 : 1))
|
||||
{
|
||||
Logger::info(L"[LightSwitchService] Manual override received while schedule OFF.");
|
||||
@@ -298,15 +279,13 @@ DWORD WINAPI ServiceWorkerThread(LPVOID lpParam)
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- Settings file changed ---
|
||||
if (wait == WAIT_OBJECT_0 + (hParent ? 3 : 2))
|
||||
{
|
||||
Logger::trace(L"[LightSwitchService] Settings change event triggered, reloading settings...");
|
||||
|
||||
ResetEvent(LightSwitchSettings::instance().GetSettingsChangedEvent());
|
||||
|
||||
LightSwitchSettings::instance().LoadSettings();
|
||||
const auto& newSettings = LightSwitchSettings::instance().settings();
|
||||
lastSettingsReload = GetTickCount64();
|
||||
|
||||
if (newSettings.scheduleMode != ScheduleMode::Off)
|
||||
{
|
||||
@@ -315,68 +294,170 @@ DWORD WINAPI ServiceWorkerThread(LPVOID lpParam)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// ─── Normal Schedule Loop ───────────────────────────────────────────────────
|
||||
ULONGLONG nowTick = GetTickCount64();
|
||||
bool recentSettingsReload = (nowTick - lastSettingsReload < 5000);
|
||||
|
||||
// --- When schedule is active, run once per minute ---
|
||||
SYSTEMTIME st;
|
||||
GetLocalTime(&st);
|
||||
int nowMinutes = st.wHour * 60 + st.wMinute;
|
||||
|
||||
// Refresh suntimes at day boundary
|
||||
if ((g_lastUpdatedDay != st.wDay) && (settings.scheduleMode == ScheduleMode::SunsetToSunrise))
|
||||
if (g_lastUpdatedDay != -1)
|
||||
{
|
||||
update_sun_times(settings);
|
||||
g_lastUpdatedDay = st.wDay;
|
||||
Logger::info(L"[LightSwitchService] Recalculated sun times at new day boundary.");
|
||||
}
|
||||
bool manualOverrideActive = (hManualOverride && WaitForSingleObject(hManualOverride, 0) == WAIT_OBJECT_0);
|
||||
|
||||
// Have to do this again in case settings got updated in the refresh suntimes chunk
|
||||
LightSwitchSettings::instance().LoadSettings();
|
||||
const auto& currentSettings = LightSwitchSettings::instance().settings();
|
||||
|
||||
wchar_t msg[160];
|
||||
swprintf_s(msg,
|
||||
L"[LightSwitchService] now=%02d:%02d | light=%02d:%02d | dark=%02d:%02d | mode=%d",
|
||||
st.wHour,
|
||||
st.wMinute,
|
||||
currentSettings.lightTime / 60,
|
||||
currentSettings.lightTime % 60,
|
||||
currentSettings.darkTime / 60,
|
||||
currentSettings.darkTime % 60,
|
||||
static_cast<int>(currentSettings.scheduleMode));
|
||||
Logger::info(msg);
|
||||
|
||||
// --- Manual override check ---
|
||||
bool manualOverrideActive = false;
|
||||
if (hManualOverride)
|
||||
{
|
||||
manualOverrideActive = (WaitForSingleObject(hManualOverride, 0) == WAIT_OBJECT_0);
|
||||
}
|
||||
|
||||
if (manualOverrideActive)
|
||||
{
|
||||
if (nowMinutes == (currentSettings.lightTime + currentSettings.sunrise_offset) % 1440 ||
|
||||
nowMinutes == (currentSettings.darkTime + currentSettings.sunset_offset) % 1440)
|
||||
if (settings.scheduleMode != ScheduleMode::Off && !recentSettingsReload && !scheduleJustEnabled)
|
||||
{
|
||||
ResetEvent(hManualOverride);
|
||||
Logger::info(L"[LightSwitchService] Manual override cleared at boundary");
|
||||
Logger::debug(L"[LightSwitchService] Checking if manual override is active...");
|
||||
bool manualOverrideActive = (hManualOverride && WaitForSingleObject(hManualOverride, 0) == WAIT_OBJECT_0);
|
||||
Logger::debug(L"[LightSwitchService] Manual override active = {}", manualOverrideActive);
|
||||
|
||||
if (!manualOverrideActive)
|
||||
{
|
||||
bool currentSystemTheme = GetCurrentSystemTheme();
|
||||
bool currentAppsTheme = GetCurrentAppsTheme();
|
||||
|
||||
SYSTEMTIME st;
|
||||
GetLocalTime(&st);
|
||||
int nowMinutes = st.wHour * 60 + st.wMinute;
|
||||
|
||||
bool shouldBeLight = (settings.lightTime < settings.darkTime) ? (nowMinutes >= settings.lightTime && nowMinutes < settings.darkTime) : (nowMinutes >= settings.lightTime || nowMinutes < settings.darkTime);
|
||||
|
||||
Logger::debug(L"[LightSwitchService] shouldBeLight = {}", shouldBeLight);
|
||||
|
||||
if ((settings.changeSystem && (currentSystemTheme != shouldBeLight)) ||
|
||||
(settings.changeApps && (currentAppsTheme != shouldBeLight)))
|
||||
{
|
||||
Logger::debug(L"[LightSwitchService] External theme change detected - enabling manual override");
|
||||
|
||||
if (!hManualOverride)
|
||||
{
|
||||
hManualOverride = OpenEventW(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, L"POWERTOYS_LIGHTSWITCH_MANUAL_OVERRIDE");
|
||||
if (!hManualOverride)
|
||||
hManualOverride = CreateEventW(nullptr, TRUE, FALSE, L"POWERTOYS_LIGHTSWITCH_MANUAL_OVERRIDE");
|
||||
}
|
||||
|
||||
if (hManualOverride)
|
||||
{
|
||||
SetEvent(hManualOverride);
|
||||
Logger::info(L"[LightSwitchService] Detected manual theme change outside of LightSwitch. Triggering manual override.");
|
||||
skipRest = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger::info(L"[LightSwitchService] Skipping schedule due to manual override");
|
||||
goto sleep_until_next_minute;
|
||||
Logger::debug(L"[LightSwitchService] Skipping external-change detection (schedule off, recent reload, or just enabled).");
|
||||
}
|
||||
}
|
||||
|
||||
applyTheme(nowMinutes, currentSettings.lightTime + currentSettings.sunrise_offset, currentSettings.darkTime + currentSettings.sunset_offset, currentSettings);
|
||||
// ─── Apply Schedule Logic ───────────────────────────────────────────────────
|
||||
if (!skipRest)
|
||||
{
|
||||
bool modeChangedToSunset = (prevMode != settings.scheduleMode &&
|
||||
settings.scheduleMode == ScheduleMode::SunsetToSunrise);
|
||||
bool coordsChanged = (prevLat != settings.latitude || prevLon != settings.longitude);
|
||||
|
||||
sleep_until_next_minute:
|
||||
if ((modeChangedToSunset || coordsChanged) && settings.scheduleMode == ScheduleMode::SunsetToSunrise)
|
||||
{
|
||||
Logger::info(L"[LightSwitchService] Mode or coordinates changed, recalculating sun times.");
|
||||
update_sun_times(settings);
|
||||
SYSTEMTIME st;
|
||||
GetLocalTime(&st);
|
||||
g_lastUpdatedDay = st.wDay;
|
||||
prevMode = settings.scheduleMode;
|
||||
prevLat = settings.latitude;
|
||||
prevLon = settings.longitude;
|
||||
}
|
||||
|
||||
SYSTEMTIME st;
|
||||
GetLocalTime(&st);
|
||||
int nowMinutes = st.wHour * 60 + st.wMinute;
|
||||
|
||||
if ((g_lastUpdatedDay != st.wDay) && (settings.scheduleMode == ScheduleMode::SunsetToSunrise))
|
||||
{
|
||||
update_sun_times(settings);
|
||||
g_lastUpdatedDay = st.wDay;
|
||||
prevMinutes = -1;
|
||||
Logger::info(L"[LightSwitchService] Recalculated sun times at new day boundary.");
|
||||
}
|
||||
|
||||
LightSwitchSettings::instance().LoadSettings();
|
||||
const auto& currentSettings = LightSwitchSettings::instance().settings();
|
||||
|
||||
wchar_t msg[160];
|
||||
swprintf_s(msg,
|
||||
L"[LightSwitchService] now=%02d:%02d | light=%02d:%02d | dark=%02d:%02d | mode=%d",
|
||||
st.wHour,
|
||||
st.wMinute,
|
||||
currentSettings.lightTime / 60,
|
||||
currentSettings.lightTime % 60,
|
||||
currentSettings.darkTime / 60,
|
||||
currentSettings.darkTime % 60,
|
||||
static_cast<int>(currentSettings.scheduleMode));
|
||||
Logger::info(msg);
|
||||
|
||||
bool manualOverrideActive = false;
|
||||
if (hManualOverride)
|
||||
manualOverrideActive = (WaitForSingleObject(hManualOverride, 0) == WAIT_OBJECT_0);
|
||||
|
||||
if (manualOverrideActive)
|
||||
{
|
||||
int lightBoundary = (currentSettings.lightTime + currentSettings.sunrise_offset) % 1440;
|
||||
int darkBoundary = (currentSettings.darkTime + currentSettings.sunset_offset) % 1440;
|
||||
|
||||
bool crossedLight = false;
|
||||
bool crossedDark = false;
|
||||
|
||||
if (prevMinutes != -1)
|
||||
{
|
||||
if (nowMinutes < prevMinutes)
|
||||
{
|
||||
crossedLight = (prevMinutes <= lightBoundary || nowMinutes >= lightBoundary);
|
||||
crossedDark = (prevMinutes <= darkBoundary || nowMinutes >= darkBoundary);
|
||||
}
|
||||
else
|
||||
{
|
||||
crossedLight = (prevMinutes < lightBoundary && nowMinutes >= lightBoundary);
|
||||
crossedDark = (prevMinutes < darkBoundary && nowMinutes >= darkBoundary);
|
||||
}
|
||||
}
|
||||
|
||||
Logger::debug(L"[LightSwitchService] prevMinutes={} nowMinutes={} light={} dark={}",
|
||||
prevMinutes,
|
||||
nowMinutes,
|
||||
lightBoundary,
|
||||
darkBoundary);
|
||||
|
||||
if (crossedLight || crossedDark)
|
||||
{
|
||||
ResetEvent(hManualOverride);
|
||||
Logger::info(L"[LightSwitchService] Manual override cleared after crossing schedule boundary.");
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger::info(L"[LightSwitchService] Skipping schedule due to manual override");
|
||||
skipRest = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!skipRest)
|
||||
applyTheme(nowMinutes,
|
||||
currentSettings.lightTime + currentSettings.sunrise_offset,
|
||||
currentSettings.darkTime + currentSettings.sunset_offset,
|
||||
currentSettings);
|
||||
}
|
||||
|
||||
// ─── Wait For Next Minute Tick Or Stop Event ────────────────────────────────
|
||||
SYSTEMTIME st;
|
||||
GetLocalTime(&st);
|
||||
int msToNextMinute = (60 - st.wSecond) * 1000 - st.wMilliseconds;
|
||||
if (msToNextMinute < 50)
|
||||
msToNextMinute = 50;
|
||||
|
||||
prevMinutes = nowMinutes;
|
||||
|
||||
DWORD wait = WaitForMultipleObjects(count, waits, FALSE, msToNextMinute);
|
||||
if (wait == WAIT_OBJECT_0)
|
||||
{
|
||||
@@ -390,6 +471,7 @@ DWORD WINAPI ServiceWorkerThread(LPVOID lpParam)
|
||||
}
|
||||
}
|
||||
|
||||
cleanup:
|
||||
if (hManualOverride)
|
||||
CloseHandle(hManualOverride);
|
||||
if (hParent)
|
||||
@@ -398,6 +480,53 @@ DWORD WINAPI ServiceWorkerThread(LPVOID lpParam)
|
||||
return 0;
|
||||
}
|
||||
|
||||
void ApplyThemeNow()
|
||||
{
|
||||
LightSwitchSettings::instance().LoadSettings();
|
||||
const auto& settings = LightSwitchSettings::instance().settings();
|
||||
|
||||
SYSTEMTIME st;
|
||||
GetLocalTime(&st);
|
||||
int nowMinutes = st.wHour * 60 + st.wMinute;
|
||||
|
||||
bool shouldBeLight = false;
|
||||
if (settings.lightTime < settings.darkTime)
|
||||
shouldBeLight = (nowMinutes >= settings.lightTime && nowMinutes < settings.darkTime);
|
||||
else
|
||||
shouldBeLight = (nowMinutes >= settings.lightTime || nowMinutes < settings.darkTime);
|
||||
|
||||
bool isSystemCurrentlyLight = GetCurrentSystemTheme();
|
||||
bool isAppsCurrentlyLight = GetCurrentAppsTheme();
|
||||
|
||||
Logger::info(L"[LightSwitchService] Applying (if needed) theme immediately due to schedule change.");
|
||||
|
||||
if (shouldBeLight)
|
||||
{
|
||||
if (settings.changeSystem && !isSystemCurrentlyLight)
|
||||
{
|
||||
SetSystemTheme(true);
|
||||
Logger::info(L"[LightSwitchService] Changing system theme to light mode.");
|
||||
}
|
||||
if (settings.changeApps && !isAppsCurrentlyLight)
|
||||
{
|
||||
SetAppsTheme(true);
|
||||
Logger::info(L"[LightSwitchService] Changing apps theme to light mode.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (settings.changeSystem && isSystemCurrentlyLight)
|
||||
{
|
||||
SetSystemTheme(false);
|
||||
Logger::info(L"[LightSwitchService] Changing system theme to dark mode.");
|
||||
}
|
||||
if (settings.changeApps && isAppsCurrentlyLight)
|
||||
{
|
||||
SetAppsTheme(false);
|
||||
Logger::info(L"[LightSwitchService] Changing apps theme to dark mode.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int APIENTRY wWinMain(HINSTANCE, HINSTANCE, PWSTR, int)
|
||||
{
|
||||
|
||||
@@ -74,6 +74,7 @@
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="LightSwitchService.cpp" />
|
||||
<ClCompile Include="LightSwitchServiceObserver.cpp" />
|
||||
<ClCompile Include="LightSwitchSettings.cpp" />
|
||||
<ClCompile Include="SettingsConstants.cpp" />
|
||||
<ClCompile Include="ThemeHelper.cpp" />
|
||||
@@ -84,6 +85,7 @@
|
||||
<ResourceCompile Include="LightSwitchService.rc" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="LightSwitchServiceObserver.h" />
|
||||
<ClInclude Include="LightSwitchSettings.h" />
|
||||
<ClInclude Include="SettingsConstants.h" />
|
||||
<ClInclude Include="SettingsObserver.h" />
|
||||
|
||||
@@ -33,6 +33,9 @@
|
||||
<ClCompile Include="WinHookEventIDs.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="LightSwitchServiceObserver.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="ThemeScheduler.h">
|
||||
@@ -53,6 +56,9 @@
|
||||
<ClInclude Include="WinHookEventIDs.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="LightSwitchServiceObserver.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Natvis Include="$(MSBuildThisFileDirectory)..\..\natvis\wil.natvis" />
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
#include "LightSwitchServiceObserver.h"
|
||||
#include <logger.h>
|
||||
#include "LightSwitchSettings.h"
|
||||
|
||||
// These are defined elsewhere in your service module (ServiceWorkerThread.cpp)
|
||||
extern int g_lastUpdatedDay;
|
||||
void ApplyThemeNow();
|
||||
|
||||
void LightSwitchServiceObserver::SettingsUpdate(SettingId id)
|
||||
{
|
||||
Logger::info(L"[LightSwitchService] Setting changed: {}", static_cast<int>(id));
|
||||
g_lastUpdatedDay = -1;
|
||||
ApplyThemeNow();
|
||||
}
|
||||
|
||||
bool LightSwitchServiceObserver::WantsToBeNotified(SettingId id) const noexcept
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case SettingId::LightTime:
|
||||
case SettingId::DarkTime:
|
||||
case SettingId::ScheduleMode:
|
||||
case SettingId::Sunrise_Offset:
|
||||
case SettingId::Sunset_Offset:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
#include "SettingsObserver.h"
|
||||
|
||||
// The LightSwitchServiceObserver reacts when LightSwitchSettings changes.
|
||||
class LightSwitchServiceObserver : public SettingsObserver
|
||||
{
|
||||
public:
|
||||
explicit LightSwitchServiceObserver(std::unordered_set<SettingId> observedSettings) :
|
||||
SettingsObserver(std::move(observedSettings))
|
||||
{
|
||||
}
|
||||
|
||||
void SettingsUpdate(SettingId id) override;
|
||||
bool WantsToBeNotified(SettingId id) const noexcept override;
|
||||
};
|
||||
@@ -39,6 +39,7 @@ void LightSwitchSettings::InitFileWatcher()
|
||||
GetSettingsFileName(),
|
||||
[this]() {
|
||||
Logger::info(L"[LightSwitchSettings] Settings file changed, signaling event.");
|
||||
LoadSettings();
|
||||
SetEvent(m_settingsChangedEvent);
|
||||
});
|
||||
}
|
||||
@@ -65,6 +66,11 @@ void LightSwitchSettings::NotifyObservers(SettingId id) const
|
||||
}
|
||||
}
|
||||
|
||||
HANDLE LightSwitchSettings::GetSettingsChangedEvent() const
|
||||
{
|
||||
return m_settingsChangedEvent;
|
||||
}
|
||||
|
||||
void LightSwitchSettings::LoadSettings()
|
||||
{
|
||||
try
|
||||
|
||||
@@ -79,7 +79,7 @@ public:
|
||||
|
||||
void LoadSettings();
|
||||
|
||||
HANDLE GetSettingsChangedEvent() const { return m_settingsChangedEvent; }
|
||||
HANDLE GetSettingsChangedEvent() const;
|
||||
|
||||
private:
|
||||
LightSwitchSettings();
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <unordered_set>
|
||||
#include "SettingsConstants.h"
|
||||
#include "LightSwitchSettings.h"
|
||||
|
||||
class LightSwitchSettings;
|
||||
|
||||
@@ -22,7 +23,7 @@ public:
|
||||
// Override this in your class to respond to updates
|
||||
virtual void SettingsUpdate(SettingId type) {}
|
||||
|
||||
bool WantsToBeNotified(SettingId type) const noexcept
|
||||
virtual bool WantsToBeNotified(SettingId type) const noexcept
|
||||
{
|
||||
return m_observedSettings.contains(type);
|
||||
}
|
||||
|
||||
@@ -14,9 +14,6 @@ extern void InclusiveCrosshairsRequestUpdatePosition();
|
||||
extern void InclusiveCrosshairsEnsureOn();
|
||||
extern void InclusiveCrosshairsEnsureOff();
|
||||
extern void InclusiveCrosshairsSetExternalControl(bool enabled);
|
||||
extern void InclusiveCrosshairsSetOrientation(CrosshairsOrientation orientation);
|
||||
extern bool InclusiveCrosshairsIsEnabled();
|
||||
extern void InclusiveCrosshairsSwitch();
|
||||
|
||||
// Non-Localizable strings
|
||||
namespace
|
||||
@@ -247,19 +244,12 @@ public:
|
||||
return false;
|
||||
}
|
||||
|
||||
if (hotkeyId == 0) // Crosshairs activation
|
||||
if (hotkeyId == 0)
|
||||
{
|
||||
// If gliding cursor is active, cancel it and activate crosshairs
|
||||
if (m_glideState.load() != 0)
|
||||
{
|
||||
CancelGliding(true /*activateCrosshairs*/);
|
||||
return true;
|
||||
}
|
||||
// Otherwise, normal crosshairs toggle
|
||||
InclusiveCrosshairsSwitch();
|
||||
return true;
|
||||
}
|
||||
if (hotkeyId == 1) // Gliding cursor activation
|
||||
if (hotkeyId == 1)
|
||||
{
|
||||
HandleGlidingHotkey();
|
||||
return true;
|
||||
@@ -278,44 +268,25 @@ private:
|
||||
SendInput(2, inputs, sizeof(INPUT));
|
||||
}
|
||||
|
||||
// Cancel gliding with option to activate crosshairs in user's preferred orientation
|
||||
void CancelGliding(bool activateCrosshairs)
|
||||
// Cancel gliding without performing the final click (Escape handling)
|
||||
void CancelGliding()
|
||||
{
|
||||
int state = m_glideState.load();
|
||||
if (state == 0)
|
||||
{
|
||||
return; // nothing to cancel
|
||||
}
|
||||
|
||||
// Stop all gliding operations
|
||||
StopXTimer();
|
||||
StopYTimer();
|
||||
m_glideState = 0;
|
||||
UninstallKeyboardHook();
|
||||
|
||||
// Reset crosshairs control and restore user settings
|
||||
InclusiveCrosshairsEnsureOff();
|
||||
InclusiveCrosshairsSetExternalControl(false);
|
||||
InclusiveCrosshairsSetOrientation(m_inclusiveCrosshairsSettings.crosshairsOrientation);
|
||||
|
||||
if (activateCrosshairs)
|
||||
{
|
||||
// User is switching to crosshairs mode - enable with their settings
|
||||
InclusiveCrosshairsEnsureOn();
|
||||
}
|
||||
else
|
||||
{
|
||||
// User canceled (Escape) - turn off crosshairs completely
|
||||
InclusiveCrosshairsEnsureOff();
|
||||
}
|
||||
|
||||
// Reset gliding state
|
||||
if (auto s = m_state)
|
||||
{
|
||||
s->xFraction = 0.0;
|
||||
s->yFraction = 0.0;
|
||||
}
|
||||
|
||||
Logger::debug("Gliding cursor cancelled (activateCrosshairs={})", activateCrosshairs ? 1 : 0);
|
||||
Logger::debug("Gliding cursor cancelled via Escape key");
|
||||
}
|
||||
|
||||
// Stateless helpers operating on shared State
|
||||
@@ -454,22 +425,21 @@ private:
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Simulate the AHK state machine
|
||||
int state = m_glideState.load();
|
||||
switch (state)
|
||||
{
|
||||
case 0: // Starting gliding
|
||||
case 0:
|
||||
{
|
||||
// Install keyboard hook for Escape cancellation
|
||||
// For detect for cancel key
|
||||
InstallKeyboardHook();
|
||||
|
||||
// Force crosshairs visible in BOTH orientation for gliding, regardless of user setting
|
||||
// Set external control before enabling to prevent internal movement hook from attaching
|
||||
// Ensure crosshairs on (do not toggle off if already on)
|
||||
InclusiveCrosshairsEnsureOn();
|
||||
// Disable internal mouse hook so we control position updates explicitly
|
||||
InclusiveCrosshairsSetExternalControl(true);
|
||||
// Override crosshairs to show both for Gliding Cursor
|
||||
InclusiveCrosshairsSetOrientation(CrosshairsOrientation::Both);
|
||||
InclusiveCrosshairsEnsureOn(); // Always ensure they are visible
|
||||
|
||||
// Initialize gliding state
|
||||
s->currentXPos = 0;
|
||||
s->currentXSpeed = s->fastHSpeed;
|
||||
s->xFraction = 0.0;
|
||||
@@ -477,17 +447,20 @@ private:
|
||||
int y = GetSystemMetrics(SM_CYVIRTUALSCREEN) / 2;
|
||||
SetCursorPos(0, y);
|
||||
InclusiveCrosshairsRequestUpdatePosition();
|
||||
|
||||
m_glideState = 1;
|
||||
StartXTimer();
|
||||
break;
|
||||
}
|
||||
case 1: // Slow horizontal
|
||||
case 1:
|
||||
{
|
||||
// Slow horizontal
|
||||
s->currentXSpeed = s->slowHSpeed;
|
||||
m_glideState = 2;
|
||||
break;
|
||||
case 2: // Switch to vertical fast
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// Stop horizontal, start vertical (fast)
|
||||
StopXTimer();
|
||||
s->currentYSpeed = s->fastVSpeed;
|
||||
s->currentYPos = 0;
|
||||
@@ -498,37 +471,33 @@ private:
|
||||
StartYTimer();
|
||||
break;
|
||||
}
|
||||
case 3: // Slow vertical
|
||||
case 3:
|
||||
{
|
||||
// Slow vertical
|
||||
s->currentYSpeed = s->slowVSpeed;
|
||||
m_glideState = 4;
|
||||
break;
|
||||
case 4: // Finalize (click and end)
|
||||
}
|
||||
case 4:
|
||||
default:
|
||||
{
|
||||
// Complete the gliding sequence
|
||||
UninstallKeyboardHook();
|
||||
// Stop vertical, click, turn crosshairs off, re-enable internal tracking, reset state
|
||||
StopYTimer();
|
||||
m_glideState = 0;
|
||||
LeftClick();
|
||||
|
||||
// Restore normal crosshairs operation and turn them off
|
||||
InclusiveCrosshairsSetExternalControl(false);
|
||||
InclusiveCrosshairsSetOrientation(m_inclusiveCrosshairsSettings.crosshairsOrientation);
|
||||
InclusiveCrosshairsEnsureOff();
|
||||
|
||||
UninstallKeyboardHook();
|
||||
|
||||
// Reset state
|
||||
if (auto sp = m_state)
|
||||
{
|
||||
sp->xFraction = 0.0;
|
||||
sp->yFraction = 0.0;
|
||||
}
|
||||
InclusiveCrosshairsSetExternalControl(false);
|
||||
// Restore original crosshairs orientation setting
|
||||
InclusiveCrosshairsSetOrientation(m_inclusiveCrosshairsSettings.crosshairsOrientation);
|
||||
s->xFraction = 0.0;
|
||||
s->yFraction = 0.0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Low-level keyboard hook for Escape cancellation
|
||||
// Low-level keyboard hook procedures
|
||||
static LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
if (nCode == HC_ACTION)
|
||||
@@ -540,11 +509,14 @@ private:
|
||||
{
|
||||
if (inst->m_enabled && inst->m_glideState.load() != 0)
|
||||
{
|
||||
inst->CancelGliding(false); // Escape cancels without activating crosshairs
|
||||
inst->UninstallKeyboardHook();
|
||||
inst->CancelGliding();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Do not swallow Escape; pass it through
|
||||
return CallNextHookEx(nullptr, nCode, wParam, lParam);
|
||||
}
|
||||
|
||||
|
||||
@@ -112,7 +112,6 @@ namespace MouseWithoutBorders
|
||||
internal const int WM_RBUTTONDBLCLK = 0x206;
|
||||
internal const int WM_MBUTTONDBLCLK = 0x209;
|
||||
internal const int WM_MOUSEWHEEL = 0x020A;
|
||||
internal const int WM_MOUSEHWHEEL = 0x020E;
|
||||
|
||||
internal const int WM_KEYDOWN = 0x100;
|
||||
internal const int WM_KEYUP = 0x101;
|
||||
|
||||
@@ -204,9 +204,6 @@ namespace MouseWithoutBorders.Class
|
||||
case Common.WM_MOUSEWHEEL:
|
||||
mouse_input.mi.dwFlags |= (int)NativeMethods.MOUSEEVENTF.WHEEL;
|
||||
break;
|
||||
case Common.WM_MOUSEHWHEEL:
|
||||
mouse_input.mi.dwFlags |= (int)NativeMethods.MOUSEEVENTF.HWHEEL;
|
||||
break;
|
||||
case Common.WM_XBUTTONUP:
|
||||
mouse_input.mi.dwFlags |= (int)NativeMethods.MOUSEEVENTF.XUP;
|
||||
break;
|
||||
|
||||
@@ -556,7 +556,6 @@ namespace MouseWithoutBorders.Class
|
||||
XDOWN = 0x0080,
|
||||
XUP = 0x0100,
|
||||
WHEEL = 0x0800,
|
||||
HWHEEL = 0x1000,
|
||||
VIRTUALDESK = 0x4000,
|
||||
ABSOLUTE = 0x8000,
|
||||
}
|
||||
|
||||
@@ -281,7 +281,21 @@ namespace Awake.Core
|
||||
TimeSpan remainingTime = expireAt - DateTimeOffset.Now;
|
||||
|
||||
Observable.Timer(remainingTime).Subscribe(
|
||||
_ => HandleTimerCompletion("expirable"),
|
||||
_ =>
|
||||
{
|
||||
Logger.LogInfo("Completed expirable keep-awake.");
|
||||
CancelExistingThread();
|
||||
|
||||
if (IsUsingPowerToysConfig)
|
||||
{
|
||||
SetPassiveKeepAwake();
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogInfo("Exiting after expirable keep awake.");
|
||||
CompleteExit(Environment.ExitCode);
|
||||
}
|
||||
},
|
||||
_tokenSource.Token);
|
||||
}
|
||||
|
||||
@@ -334,46 +348,49 @@ namespace Awake.Core
|
||||
|
||||
SetModeShellIcon();
|
||||
|
||||
var targetExpiryTime = DateTimeOffset.Now.AddSeconds(seconds);
|
||||
ulong desiredDuration = (ulong)seconds * 1000;
|
||||
ulong targetDuration = Math.Min(desiredDuration, uint.MaxValue - 1) / 1000;
|
||||
|
||||
Observable.Interval(TimeSpan.FromSeconds(1))
|
||||
.Select(_ => targetExpiryTime - DateTimeOffset.Now)
|
||||
.TakeWhile(remaining => remaining.TotalSeconds > 0)
|
||||
.Subscribe(
|
||||
remainingTimeSpan =>
|
||||
if (desiredDuration > uint.MaxValue)
|
||||
{
|
||||
Logger.LogInfo($"The desired interval of {seconds} seconds ({desiredDuration}ms) exceeds the limit. Defaulting to maximum possible value: {targetDuration} seconds. Read more about existing limits in the official documentation: https://aka.ms/powertoys/awake");
|
||||
}
|
||||
|
||||
IObservable<long> timerObservable = Observable.Timer(TimeSpan.FromSeconds(targetDuration));
|
||||
IObservable<long> intervalObservable = Observable.Interval(TimeSpan.FromSeconds(1)).TakeUntil(timerObservable);
|
||||
IObservable<long> combinedObservable = Observable.CombineLatest(intervalObservable, timerObservable.StartWith(0), (elapsedSeconds, _) => elapsedSeconds + 1);
|
||||
|
||||
combinedObservable.Subscribe(
|
||||
elapsedSeconds =>
|
||||
{
|
||||
TimeRemaining = (uint)targetDuration - (uint)elapsedSeconds;
|
||||
if (TimeRemaining >= 0)
|
||||
{
|
||||
TimeRemaining = (uint)remainingTimeSpan.TotalSeconds;
|
||||
|
||||
TrayHelper.SetShellIcon(
|
||||
TrayHelper.WindowHandle,
|
||||
$"{Constants.FullAppName} [{Resources.AWAKE_TRAY_TEXT_TIMED}][{ScreenStateString}][{remainingTimeSpan.ToHumanReadableString()}]",
|
||||
$"{Constants.FullAppName} [{Resources.AWAKE_TRAY_TEXT_TIMED}][{ScreenStateString}][{TimeSpan.FromSeconds(TimeRemaining).ToHumanReadableString()}]",
|
||||
TrayHelper.TimedIcon,
|
||||
TrayIconAction.Update);
|
||||
},
|
||||
_ => HandleTimerCompletion("timed"),
|
||||
_tokenSource.Token);
|
||||
}
|
||||
}
|
||||
},
|
||||
() =>
|
||||
{
|
||||
Logger.LogInfo("Completed timed thread.");
|
||||
CancelExistingThread();
|
||||
|
||||
/// <summary>
|
||||
/// Handles the common logic that should execute when a keep-awake timer completes. Resets
|
||||
/// the application state to Passive if configured; otherwise it exits.
|
||||
/// </summary>
|
||||
private static void HandleTimerCompletion(string timerType)
|
||||
{
|
||||
Logger.LogInfo($"Completed {timerType} keep-awake.");
|
||||
CancelExistingThread();
|
||||
|
||||
if (IsUsingPowerToysConfig)
|
||||
{
|
||||
// If running under PowerToys settings, just revert to the default Passive state.
|
||||
SetPassiveKeepAwake();
|
||||
}
|
||||
else
|
||||
{
|
||||
// If running as a standalone process, exit cleanly.
|
||||
Logger.LogInfo($"Exiting after {timerType} keep-awake.");
|
||||
CompleteExit(Environment.ExitCode);
|
||||
}
|
||||
if (IsUsingPowerToysConfig)
|
||||
{
|
||||
// If we're using PowerToys settings, we need to make sure that
|
||||
// we just switch over the Passive Keep-Awake.
|
||||
SetPassiveKeepAwake();
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogInfo("Exiting after timed keep-awake.");
|
||||
CompleteExit(Environment.ExitCode);
|
||||
}
|
||||
},
|
||||
_tokenSource.Token);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Runtime.CompilerServices;
|
||||
using Windows.Win32;
|
||||
using Windows.Win32.Storage.FileSystem;
|
||||
|
||||
namespace Microsoft.CmdPal.Core.Common.Helpers;
|
||||
|
||||
public static class PathHelper
|
||||
{
|
||||
public static bool Exists(string path, out bool isDirectory)
|
||||
{
|
||||
isDirectory = false;
|
||||
if (string.IsNullOrEmpty(path))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string? fullPath;
|
||||
try
|
||||
{
|
||||
fullPath = Path.GetFullPath(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var result = ExistsCore(fullPath, out isDirectory);
|
||||
if (result && IsDirectorySeparator(fullPath[^1]))
|
||||
{
|
||||
// Some sys-calls remove all trailing slashes and may give false positives for existing files.
|
||||
// We want to make sure that if the path ends in a trailing slash, it's truly a directory.
|
||||
return isDirectory;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalize potential local/UNC file path text input: trim whitespace and surrounding quotes.
|
||||
/// Windows file paths cannot contain quotes, but user input can include them.
|
||||
/// </summary>
|
||||
public static string Unquote(string? text)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(text) ? (text ?? string.Empty) : text.Trim().Trim('"');
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quick heuristic to determine if the string looks like a Windows file path (UNC or drive-letter based).
|
||||
/// </summary>
|
||||
public static bool LooksLikeFilePath(string? path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// UNC path
|
||||
if (path.StartsWith(@"\\", StringComparison.Ordinal))
|
||||
{
|
||||
// Win32 File Namespaces \\?\
|
||||
if (path.StartsWith(@"\\?\", StringComparison.Ordinal))
|
||||
{
|
||||
return IsSlow(path[4..]);
|
||||
}
|
||||
|
||||
// Basic UNC path validation: \\server\share or \\server\share\path
|
||||
var parts = path[2..].Split('\\', StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
return parts.Length >= 2; // At minimum: server and share
|
||||
}
|
||||
|
||||
// Drive letter path (e.g., C:\ or C:)
|
||||
return path.Length >= 2 && char.IsLetter(path[0]) && path[1] == ':';
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates path syntax without performing any I/O by using Path.GetFullPath.
|
||||
/// </summary>
|
||||
public static bool HasValidPathSyntax(string? path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_ = Path.GetFullPath(path);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a string represents a valid Windows file path (local or network)
|
||||
/// using fast syntax validation only. Reuses LooksLikeFilePath and HasValidPathSyntax.
|
||||
/// </summary>
|
||||
public static bool IsValidFilePath(string? path)
|
||||
{
|
||||
return LooksLikeFilePath(path) && HasValidPathSyntax(path);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static bool IsDirectorySeparator(char c)
|
||||
{
|
||||
return c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar;
|
||||
}
|
||||
|
||||
private static bool ExistsCore(string fullPath, out bool isDirectory)
|
||||
{
|
||||
var attributes = PInvoke.GetFileAttributes(fullPath);
|
||||
var result = attributes != PInvoke.INVALID_FILE_ATTRIBUTES;
|
||||
isDirectory = result && (attributes & (uint)FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_DIRECTORY) != 0;
|
||||
return result;
|
||||
}
|
||||
|
||||
public static bool IsSlow(string path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var root = Path.GetPathRoot(path);
|
||||
if (!string.IsNullOrEmpty(root))
|
||||
{
|
||||
if (root.Length > 2 && char.IsLetter(root[0]) && root[1] == ':')
|
||||
{
|
||||
return new DriveInfo(root).DriveType is not (DriveType.Fixed or DriveType.Ram);
|
||||
}
|
||||
else if (root.StartsWith(@"\\", StringComparison.Ordinal))
|
||||
{
|
||||
return !root.StartsWith(@"\\?\", StringComparison.Ordinal) || IsSlow(root[4..]);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,4 @@ MonitorFromWindow
|
||||
|
||||
SHOW_WINDOW_CMD
|
||||
ShellExecuteEx
|
||||
SEE_MASK_INVOKEIDLIST
|
||||
|
||||
GetFileAttributes
|
||||
FILE_FLAGS_AND_ATTRIBUTES
|
||||
INVALID_FILE_ATTRIBUTES
|
||||
SEE_MASK_INVOKEIDLIST
|
||||
@@ -2,10 +2,8 @@
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Microsoft.CmdPal.Core.ViewModels.Models;
|
||||
using Microsoft.CommandPalette.Extensions;
|
||||
using Microsoft.CommandPalette.Extensions.Toolkit;
|
||||
|
||||
namespace Microsoft.CmdPal.Core.ViewModels;
|
||||
|
||||
@@ -13,13 +11,6 @@ public partial class DetailsLinkViewModel(
|
||||
IDetailsElement _detailsElement,
|
||||
WeakReference<IPageContext> context) : DetailsElementViewModel(_detailsElement, context)
|
||||
{
|
||||
private static readonly string[] _initProperties = [
|
||||
nameof(Text),
|
||||
nameof(Link),
|
||||
nameof(IsLink),
|
||||
nameof(IsText),
|
||||
nameof(NavigateCommand)];
|
||||
|
||||
private readonly ExtensionObject<IDetailsLink> _dataModel =
|
||||
new(_detailsElement.Data as IDetailsLink);
|
||||
|
||||
@@ -31,8 +22,6 @@ public partial class DetailsLinkViewModel(
|
||||
|
||||
public bool IsText => !IsLink;
|
||||
|
||||
public RelayCommand? NavigateCommand { get; private set; }
|
||||
|
||||
public override void InitializeProperties()
|
||||
{
|
||||
base.InitializeProperties();
|
||||
@@ -49,18 +38,9 @@ public partial class DetailsLinkViewModel(
|
||||
Text = Link.ToString();
|
||||
}
|
||||
|
||||
if (Link is not null)
|
||||
{
|
||||
// Custom command to open a link in the default browser or app,
|
||||
// depending on the link type.
|
||||
// Binding Link to a Hyperlink(Button).NavigateUri works only for
|
||||
// certain URI schemes (e.g., http, https) and cannot open file:
|
||||
// scheme URIs or local files.
|
||||
NavigateCommand = new RelayCommand(
|
||||
() => ShellHelpers.OpenInShell(Link.ToString()),
|
||||
() => Link is not null);
|
||||
}
|
||||
|
||||
UpdateProperty(_initProperties);
|
||||
UpdateProperty(nameof(Text));
|
||||
UpdateProperty(nameof(Link));
|
||||
UpdateProperty(nameof(IsLink));
|
||||
UpdateProperty(nameof(IsText));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,9 +265,6 @@ public partial class ShellViewModel : ObservableObject,
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
// Clear command bar, ViewModel initialization can already set new commands if it wants to
|
||||
OnUIThread(() => WeakReferenceMessenger.Default.Send<UpdateCommandBarMessage>(new(null)));
|
||||
|
||||
// Kick off async loading of our ViewModel
|
||||
LoadPageViewModelAsync(pageViewModel, navigationToken)
|
||||
.ContinueWith(
|
||||
@@ -278,6 +275,9 @@ public partial class ShellViewModel : ObservableObject,
|
||||
{
|
||||
newCts.Dispose();
|
||||
}
|
||||
|
||||
// When we're done loading the page, then update the command bar to match
|
||||
WeakReferenceMessenger.Default.Send<UpdateCommandBarMessage>(new(null));
|
||||
},
|
||||
navigationToken,
|
||||
TaskContinuationOptions.None,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<Project>
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Import Project="..\..\Common.Dotnet.CsWinRT.props" />
|
||||
<Import Project="..\..\Common.Dotnet.AotCompatibility.props" />
|
||||
<PropertyGroup>
|
||||
|
||||
@@ -52,7 +52,7 @@ public partial class ContentFormViewModel(IFormContent _form, WeakReference<IPag
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError("Error building card from template", ex);
|
||||
Logger.LogError("Error building card from template: {Message}", ex.Message);
|
||||
error = ex;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
x:Class="Microsoft.CmdPal.UI.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:controls="using:Microsoft.CmdPal.UI.Controls"
|
||||
xmlns:local="using:Microsoft.CmdPal.UI">
|
||||
<Application.Resources>
|
||||
<ResourceDictionary>
|
||||
@@ -16,12 +15,11 @@
|
||||
<ResourceDictionary Source="Styles/Settings.xaml" />
|
||||
<ResourceDictionary Source="Controls/Tag.xaml" />
|
||||
<ResourceDictionary Source="Controls/KeyVisual/KeyVisual.xaml" />
|
||||
<ResourceDictionary Source="Controls/IsEnabledTextBlock.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
<!-- Other app resources here -->
|
||||
|
||||
<x:Double x:Key="SettingActionControlMinWidth">240</x:Double>
|
||||
<Style BasedOn="{StaticResource DefaultCheckBoxStyle}" TargetType="controls:CheckBoxWithDescriptionControl" />
|
||||
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.ComponentModel;
|
||||
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Automation;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
public partial class CheckBoxWithDescriptionControl : CheckBox
|
||||
{
|
||||
private CheckBoxWithDescriptionControl _checkBoxSubTextControl;
|
||||
|
||||
public CheckBoxWithDescriptionControl()
|
||||
{
|
||||
_checkBoxSubTextControl = (CheckBoxWithDescriptionControl)this;
|
||||
this.Loaded += CheckBoxSubTextControl_Loaded;
|
||||
}
|
||||
|
||||
protected override void OnApplyTemplate()
|
||||
{
|
||||
Update();
|
||||
base.OnApplyTemplate();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (!string.IsNullOrEmpty(Header))
|
||||
{
|
||||
AutomationProperties.SetName(this, Header);
|
||||
}
|
||||
}
|
||||
|
||||
private void CheckBoxSubTextControl_Loaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
StackPanel panel = new StackPanel() { Orientation = Orientation.Vertical };
|
||||
panel.Children.Add(new TextBlock() { Text = Header, TextWrapping = TextWrapping.WrapWholeWords });
|
||||
|
||||
// Add text box only if the description is not empty. Required for additional plugin options.
|
||||
if (!string.IsNullOrWhiteSpace(Description))
|
||||
{
|
||||
panel.Children.Add(new IsEnabledTextBlock() { Style = (Style)App.Current.Resources["SecondaryIsEnabledTextBlockStyle"], Text = Description });
|
||||
}
|
||||
|
||||
_checkBoxSubTextControl.Content = panel;
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register(
|
||||
"Header",
|
||||
typeof(string),
|
||||
typeof(CheckBoxWithDescriptionControl),
|
||||
new PropertyMetadata(default(string)));
|
||||
|
||||
public static readonly DependencyProperty DescriptionProperty = DependencyProperty.Register(
|
||||
"Description",
|
||||
typeof(string),
|
||||
typeof(CheckBoxWithDescriptionControl),
|
||||
new PropertyMetadata(default(string)));
|
||||
|
||||
[Localizable(true)]
|
||||
public string Header
|
||||
{
|
||||
get => (string)GetValue(HeaderProperty);
|
||||
set => SetValue(HeaderProperty, value);
|
||||
}
|
||||
|
||||
[Localizable(true)]
|
||||
public string Description
|
||||
{
|
||||
get => (string)GetValue(DescriptionProperty);
|
||||
set => SetValue(DescriptionProperty, value);
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
<ResourceDictionary
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:controls="using:Microsoft.CmdPal.UI.Controls">
|
||||
|
||||
<Style x:Key="DefaultIsEnabledTextBlockStyle" TargetType="controls:IsEnabledTextBlock">
|
||||
<Setter Property="Foreground" Value="{ThemeResource DefaultTextForegroundThemeBrush}" />
|
||||
<Setter Property="IsTabStop" Value="False" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="controls:IsEnabledTextBlock">
|
||||
<Grid>
|
||||
<TextBlock
|
||||
x:Name="Label"
|
||||
FontFamily="{TemplateBinding FontFamily}"
|
||||
FontSize="{TemplateBinding FontSize}"
|
||||
FontWeight="{TemplateBinding FontWeight}"
|
||||
Foreground="{TemplateBinding Foreground}"
|
||||
Text="{TemplateBinding Text}"
|
||||
TextWrapping="WrapWholeWords" />
|
||||
<VisualStateManager.VisualStateGroups>
|
||||
<VisualStateGroup x:Name="CommonStates">
|
||||
<VisualState x:Name="Normal" />
|
||||
<VisualState x:Name="Disabled">
|
||||
<VisualState.Setters>
|
||||
<Setter Target="Label.Foreground" Value="{ThemeResource TextFillColorDisabledBrush}" />
|
||||
</VisualState.Setters>
|
||||
</VisualState>
|
||||
</VisualStateGroup>
|
||||
</VisualStateManager.VisualStateGroups>
|
||||
</Grid>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
<Style
|
||||
x:Key="SecondaryIsEnabledTextBlockStyle"
|
||||
BasedOn="{StaticResource DefaultIsEnabledTextBlockStyle}"
|
||||
TargetType="controls:IsEnabledTextBlock">
|
||||
<Setter Property="Foreground" Value="{ThemeResource TextFillColorSecondaryBrush}" />
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
@@ -1,51 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.ComponentModel;
|
||||
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
[TemplateVisualState(Name = "Normal", GroupName = "CommonStates")]
|
||||
[TemplateVisualState(Name = "Disabled", GroupName = "CommonStates")]
|
||||
public partial class IsEnabledTextBlock : Control
|
||||
{
|
||||
public IsEnabledTextBlock()
|
||||
{
|
||||
this.Style = (Style)App.Current.Resources["DefaultIsEnabledTextBlockStyle"];
|
||||
}
|
||||
|
||||
protected override void OnApplyTemplate()
|
||||
{
|
||||
IsEnabledChanged -= IsEnabledTextBlock_IsEnabledChanged;
|
||||
SetEnabledState();
|
||||
IsEnabledChanged += IsEnabledTextBlock_IsEnabledChanged;
|
||||
base.OnApplyTemplate();
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
|
||||
"Text",
|
||||
typeof(string),
|
||||
typeof(IsEnabledTextBlock),
|
||||
null);
|
||||
|
||||
[Localizable(true)]
|
||||
public string Text
|
||||
{
|
||||
get => (string)GetValue(TextProperty);
|
||||
set => SetValue(TextProperty, value);
|
||||
}
|
||||
|
||||
private void IsEnabledTextBlock_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
SetEnabledState();
|
||||
}
|
||||
|
||||
private void SetEnabledState()
|
||||
{
|
||||
VisualStateManager.GoToState(this, IsEnabled ? "Normal" : "Disabled", true);
|
||||
}
|
||||
}
|
||||
@@ -78,12 +78,6 @@ public sealed partial class ContentPage : Page,
|
||||
WeakReferenceMessenger.Default.Unregister<ActivateSecondaryCommandMessage>(this);
|
||||
|
||||
// Clean-up event listeners
|
||||
if (e.NavigationMode != NavigationMode.New)
|
||||
{
|
||||
ViewModel?.SafeCleanup();
|
||||
CleanupHelper.Cleanup(this);
|
||||
}
|
||||
|
||||
ViewModel = null;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ namespace Microsoft.CmdPal.UI.Helpers;
|
||||
/// <summary>
|
||||
/// A class that listens for local keyboard events using a Windows hook.
|
||||
/// </summary>
|
||||
internal sealed partial class LocalKeyboardListener : IDisposable
|
||||
internal sealed class LocalKeyboardListener : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Event that is raised when a key is pressed down.
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
[assembly: SuppressMessage("Interoperability", "CsWinRT1028: Class should be marked partial", Justification = "CsWin32 generated code; not used across WinRT boundary", Scope = "type", Target = "~T:Windows.Win32.DestroyIconSafeHandle")]
|
||||
[assembly: SuppressMessage("Interoperability", "CsWinRT1028: Class should be marked partial", Justification = "CsWin32 generated code; not used across WinRT boundary", Scope = "type", Target = "~T:Windows.Win32.DestroyMenuSafeHandle")]
|
||||
[assembly: SuppressMessage("Interoperability", "CsWinRT1028: Class should be marked partial", Justification = "CsWin32 generated code; not used across WinRT boundary", Scope = "type", Target = "~T:Windows.Win32.FreeLibrarySafeHandle")]
|
||||
[assembly: SuppressMessage("Interoperability", "CsWinRT1028: Class should be marked partial", Justification = "CsWin32 generated code; not used across WinRT boundary", Scope = "type", Target = "~T:Windows.Win32.UnhookWindowsHookExSafeHandle")]
|
||||
@@ -66,9 +66,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="Controls\ActionBar.xaml" />
|
||||
<None Remove="Controls\KeyVisual\KeyCharPresenter.xaml" />
|
||||
<None Remove="Controls\SearchBar.xaml" />
|
||||
<None Remove="IsEnabledTextBlock.xaml" />
|
||||
<None Remove="ListDetailPage.xaml" />
|
||||
<None Remove="LoadingPage.xaml" />
|
||||
<None Remove="MainPage.xaml" />
|
||||
@@ -182,18 +180,6 @@
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Page Update="IsEnabledTextBlock.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Page Update="Controls\KeyVisual\KeyCharPresenter.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Page Update="Styles\Colors.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
|
||||
@@ -108,7 +108,6 @@
|
||||
Visibility="{x:Bind IsText, Mode=OneWay}" />
|
||||
<HyperlinkButton
|
||||
Padding="0"
|
||||
Command="{x:Bind NavigateCommand, Mode=OneWay}"
|
||||
NavigateUri="{x:Bind Link, Mode=OneWay}"
|
||||
Visibility="{x:Bind IsLink, Mode=OneWay}">
|
||||
<TextBlock Text="{x:Bind Text, Mode=OneWay}" TextWrapping="Wrap" />
|
||||
|
||||
@@ -33,10 +33,6 @@
|
||||
x:Key="StringEmptyToBoolConverter"
|
||||
EmptyValue="False"
|
||||
NotEmptyValue="True" />
|
||||
<converters:BoolToObjectConverter
|
||||
x:Key="BoolToOptionConverter"
|
||||
FalseValue="1"
|
||||
TrueValue="0" />
|
||||
</ResourceDictionary>
|
||||
</Page.Resources>
|
||||
|
||||
@@ -51,34 +47,22 @@
|
||||
MaxWidth="1000"
|
||||
HorizontalAlignment="Stretch"
|
||||
Spacing="{StaticResource SettingsCardSpacing}">
|
||||
<controls:SettingsCard x:Uid="ExtensionEnableCard">
|
||||
<controls:SettingsCard.HeaderIcon>
|
||||
<cpcontrols:ContentIcon>
|
||||
<cpcontrols:ContentIcon.Content>
|
||||
<cpcontrols:IconBox
|
||||
Width="20"
|
||||
Height="20"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
SourceKey="{x:Bind ViewModel.Icon, Mode=OneWay}"
|
||||
SourceRequested="{x:Bind helpers:IconCacheProvider.SourceRequested}" />
|
||||
</cpcontrols:ContentIcon.Content>
|
||||
</cpcontrols:ContentIcon>
|
||||
</controls:SettingsCard.HeaderIcon>
|
||||
<controls:SettingsCard.Header>
|
||||
<TextBlock>
|
||||
<Run x:Uid="ExtensionEnable" Text="Enable" />
|
||||
<Run Text="{x:Bind ViewModel.DisplayName}" />
|
||||
</TextBlock>
|
||||
</controls:SettingsCard.Header>
|
||||
|
||||
<controls:SettingsCard x:Uid="ExtensionEnableCard" HeaderIcon="{ui:FontIcon Glyph=}">
|
||||
<ToggleSwitch IsOn="{x:Bind ViewModel.IsEnabled, Mode=TwoWay}" />
|
||||
</controls:SettingsCard>
|
||||
|
||||
<controls:SwitchPresenter
|
||||
HorizontalAlignment="Stretch"
|
||||
TargetType="x:Boolean"
|
||||
Value="{x:Bind ViewModel.IsEnabled, Mode=OneWay}">
|
||||
|
||||
<controls:Case Value="True">
|
||||
|
||||
<StackPanel Orientation="Vertical">
|
||||
|
||||
<TextBlock x:Uid="ExtensionCommandsHeader" Style="{StaticResource SettingsSectionHeaderTextBlockStyle}" />
|
||||
|
||||
<ItemsRepeater ItemsSource="{x:Bind ViewModel.TopLevelCommands, Mode=OneWay}" Layout="{StaticResource VerticalStackLayout}">
|
||||
<ItemsRepeater.ItemTemplate>
|
||||
<DataTemplate x:DataType="viewModels:TopLevelViewModel">
|
||||
@@ -100,22 +84,22 @@
|
||||
</controls:SettingsExpander.HeaderIcon>
|
||||
|
||||
<!-- Content goes here -->
|
||||
|
||||
<controls:SettingsExpander.Items>
|
||||
<controls:SettingsCard x:Uid="Settings_ExtensionPage_GlobalHotkey_SettingsCard">
|
||||
<controls:SettingsCard x:Uid="Settings_ExtensionPage_GlobalHotkey_SettingsCard" HeaderIcon="{ui:FontIcon Glyph=}">
|
||||
<cpcontrols:ShortcutControl HotkeySettings="{x:Bind Hotkey, Mode=TwoWay}" />
|
||||
</controls:SettingsCard>
|
||||
<controls:SettingsCard x:Uid="Settings_ExtensionPage_Alias_SettingsCard">
|
||||
<TextBox
|
||||
x:Uid="Settings_ExtensionPage_Alias_PlaceholderText"
|
||||
MinWidth="{StaticResource SettingActionControlMinWidth}"
|
||||
Text="{x:Bind AliasText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
|
||||
</controls:SettingsCard>
|
||||
<controls:SettingsCard x:Uid="Settings_ExtensionPage_AliasActivation_SettingsCard" IsEnabled="{x:Bind AliasText, Converter={StaticResource StringEmptyToBoolConverter}, Mode=OneWay}">
|
||||
<ComboBox MinWidth="{StaticResource SettingActionControlMinWidth}" SelectedIndex="{x:Bind IsDirectAlias, Converter={StaticResource BoolToOptionConverter}, Mode=TwoWay}">
|
||||
<ComboBoxItem x:Uid="Settings_ExtensionPage_Alias_DirectComboBox" />
|
||||
<ComboBoxItem x:Uid="Settings_ExtensionPage_Alias_IndirectComboBox" />
|
||||
</ComboBox>
|
||||
|
||||
<controls:SettingsCard x:Uid="Settings_ExtensionPage_Alias_SettingsCard" HeaderIcon="{ui:FontIcon Glyph=}">
|
||||
<StackPanel Orientation="Vertical">
|
||||
<TextBox Text="{x:Bind AliasText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
|
||||
<ToggleSwitch
|
||||
x:Uid="Settings_ExtensionPage_Alias_ToggleSwitch"
|
||||
IsEnabled="{x:Bind AliasText, Converter={StaticResource StringEmptyToBoolConverter}, Mode=OneWay}"
|
||||
IsOn="{x:Bind IsDirectAlias, Mode=TwoWay}" />
|
||||
</StackPanel>
|
||||
</controls:SettingsCard>
|
||||
|
||||
</controls:SettingsExpander.Items>
|
||||
</controls:SettingsExpander>
|
||||
</DataTemplate>
|
||||
@@ -146,8 +130,11 @@
|
||||
</cpcontrols:ContentIcon.Content>
|
||||
</cpcontrols:ContentIcon>
|
||||
</controls:SettingsCard.HeaderIcon>
|
||||
|
||||
<!-- Content goes here -->
|
||||
<ToggleSwitch IsOn="{x:Bind IsEnabled, Mode=TwoWay}" />
|
||||
|
||||
|
||||
</controls:SettingsCard>
|
||||
</DataTemplate>
|
||||
</ItemsRepeater.ItemTemplate>
|
||||
@@ -158,13 +145,8 @@
|
||||
Style="{StaticResource SettingsSectionHeaderTextBlockStyle}"
|
||||
Visibility="{x:Bind ViewModel.HasSettings}" />
|
||||
|
||||
<Frame
|
||||
x:Name="SettingsFrame"
|
||||
Background="{ThemeResource SettingsCardBackground}"
|
||||
BorderBrush="{ThemeResource SettingsCardBorderBrush}"
|
||||
BorderThickness="{ThemeResource SettingsCardBorderThickness}"
|
||||
CornerRadius="{StaticResource ControlCornerRadius}"
|
||||
Visibility="{x:Bind ViewModel.HasSettings}">
|
||||
<Frame x:Name="SettingsFrame" Visibility="{x:Bind ViewModel.HasSettings}">
|
||||
|
||||
<controls:SwitchPresenter
|
||||
HorizontalAlignment="Stretch"
|
||||
TargetType="x:Boolean"
|
||||
@@ -181,6 +163,7 @@
|
||||
<cmdpalUI:ContentPage ViewModel="{x:Bind ViewModel.SettingsPage, Mode=OneWay}" />
|
||||
</controls:Case>
|
||||
</controls:SwitchPresenter>
|
||||
|
||||
</Frame>
|
||||
|
||||
<TextBlock
|
||||
@@ -214,6 +197,8 @@
|
||||
Style="{StaticResource SettingsSectionHeaderTextBlockStyle}"
|
||||
Visibility="{x:Bind ViewModel.IsFromExtension, Mode=OneWay, Converter={StaticResource BoolToInvertedVisibilityConverter}}" />
|
||||
<controls:SettingsCard x:Uid="Settings_ExtensionPage_Builtin_SettingsCard" Visibility="{x:Bind ViewModel.IsFromExtension, Mode=OneWay, Converter={StaticResource BoolToInvertedVisibilityConverter}}" />
|
||||
|
||||
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</ScrollViewer>
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
MaxWidth="1000"
|
||||
HorizontalAlignment="Stretch"
|
||||
Spacing="{StaticResource SettingsCardSpacing}">
|
||||
|
||||
<ItemsRepeater ItemsSource="{x:Bind viewModel.CommandProviders, Mode=OneWay}" Layout="{StaticResource VerticalStackLayout}">
|
||||
<ItemsRepeater.ItemTemplate>
|
||||
<DataTemplate x:DataType="viewModels:ProviderSettingsViewModel">
|
||||
@@ -46,7 +47,9 @@
|
||||
</cpcontrols:ContentIcon.Content>
|
||||
</cpcontrols:ContentIcon>
|
||||
</controls:SettingsCard.HeaderIcon>
|
||||
|
||||
<ToggleSwitch IsOn="{x:Bind IsEnabled, Mode=TwoWay}" />
|
||||
|
||||
</controls:SettingsCard>
|
||||
</DataTemplate>
|
||||
</ItemsRepeater.ItemTemplate>
|
||||
|
||||
@@ -37,20 +37,22 @@
|
||||
<!-- 'Activation' section -->
|
||||
|
||||
<TextBlock x:Uid="ActivationSettingsHeader" Style="{StaticResource SettingsSectionHeaderTextBlockStyle}" />
|
||||
|
||||
<controls:SettingsExpander
|
||||
x:Uid="Settings_GeneralPage_ActivationKey_SettingsExpander"
|
||||
HeaderIcon="{ui:FontIcon Glyph=}"
|
||||
IsExpanded="True">
|
||||
<ptControls:ShortcutControl HotkeySettings="{x:Bind viewModel.Hotkey, Mode=TwoWay}" />
|
||||
|
||||
<controls:SettingsExpander.Items>
|
||||
<controls:SettingsCard ContentAlignment="Left">
|
||||
<ptControls:CheckBoxWithDescriptionControl x:Uid="Settings_GeneralPage_LowLevelHook_SettingsCard" IsChecked="{x:Bind viewModel.UseLowLevelGlobalHotkey, Mode=TwoWay}" />
|
||||
</controls:SettingsCard>
|
||||
<controls:SettingsCard ContentAlignment="Left">
|
||||
<ptControls:CheckBoxWithDescriptionControl x:Uid="Settings_GeneralPage_IgnoreShortcutWhenFullscreen_SettingsCard" IsChecked="{x:Bind viewModel.IgnoreShortcutWhenFullscreen, Mode=TwoWay}" />
|
||||
<controls:SettingsCard x:Uid="Settings_GeneralPage_LowLevelHook_SettingsCard">
|
||||
<ToggleSwitch IsOn="{x:Bind viewModel.UseLowLevelGlobalHotkey, Mode=TwoWay}" />
|
||||
</controls:SettingsCard>
|
||||
</controls:SettingsExpander.Items>
|
||||
</controls:SettingsExpander>
|
||||
<controls:SettingsCard x:Uid="Settings_GeneralPage_IgnoreShortcutWhenFullscreen_SettingsCard" HeaderIcon="{ui:FontIcon Glyph=}">
|
||||
<ToggleSwitch IsOn="{x:Bind viewModel.IgnoreShortcutWhenFullscreen, Mode=TwoWay}" />
|
||||
</controls:SettingsCard>
|
||||
<controls:SettingsCard x:Uid="Settings_GeneralPage_GoHome_SettingsCard" HeaderIcon="{ui:FontIcon Glyph=}">
|
||||
<ToggleSwitch IsOn="{x:Bind viewModel.HotkeyGoesHome, Mode=TwoWay}" />
|
||||
</controls:SettingsCard>
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:local="using:Microsoft.CmdPal.UI.Settings"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:text="using:Windows.UI.Text"
|
||||
xmlns:ui="using:CommunityToolkit.WinUI"
|
||||
xmlns:winuiex="using:WinUIEx"
|
||||
Title="SettingsWindow"
|
||||
@@ -74,14 +73,14 @@
|
||||
ItemsSource="{x:Bind BreadCrumbs, Mode=OneWay}">
|
||||
<BreadcrumbBar.ItemTemplate>
|
||||
<DataTemplate x:DataType="local:Crumb">
|
||||
<TextBlock Text="{x:Bind Label}" />
|
||||
<TextBlock Text="{x:Bind Label, Mode=OneWay}" />
|
||||
</DataTemplate>
|
||||
</BreadcrumbBar.ItemTemplate>
|
||||
<BreadcrumbBar.Resources>
|
||||
<ResourceDictionary>
|
||||
<x:Double x:Key="BreadcrumbBarItemThemeFontSize">28</x:Double>
|
||||
<Thickness x:Key="BreadcrumbBarChevronPadding">7,4,8,0</Thickness>
|
||||
<text:FontWeight x:Key="BreadcrumbBarItemFontWeight">SemiBold</text:FontWeight>
|
||||
<FontWeight x:Key="BreadcrumbBarItemFontWeight">SemiBold</FontWeight>
|
||||
<x:Double x:Key="BreadcrumbBarChevronFontSize">16</x:Double>
|
||||
</ResourceDictionary>
|
||||
</BreadcrumbBar.Resources>
|
||||
|
||||
@@ -257,8 +257,8 @@ Right-click to remove the key combination, thereby deactivating the shortcut.</v
|
||||
<value>Disabled</value>
|
||||
<comment>Displayed when an extension is disabled</comment>
|
||||
</data>
|
||||
<data name="ExtensionEnable.Text" xml:space="preserve">
|
||||
<value>Enable</value>
|
||||
<data name="ExtensionEnableCard.Header" xml:space="preserve">
|
||||
<value>Enable this extension</value>
|
||||
<comment>Displayed on a toggle controlling the extension's enabled / disabled state</comment>
|
||||
</data>
|
||||
<data name="ExtensionEnableCard.Description" xml:space="preserve">
|
||||
@@ -312,13 +312,7 @@ Right-click to remove the key combination, thereby deactivating the shortcut.</v
|
||||
<value>Alias</value>
|
||||
</data>
|
||||
<data name="Settings_ExtensionPage_Alias_SettingsCard.Description" xml:space="preserve">
|
||||
<value>A short keyword used to navigate to this command.</value>
|
||||
</data>
|
||||
<data name="Settings_ExtensionPage_AliasActivation_SettingsCard.Header" xml:space="preserve">
|
||||
<value>Alias activation</value>
|
||||
</data>
|
||||
<data name="Settings_ExtensionPage_AliasActivation_SettingsCard.Description" xml:space="preserve">
|
||||
<value>Choose when the alias runs. Direct runs as soon as you type the alias. Indirect runs after a trailing space.</value>
|
||||
<value>Typing this alias will navigate to this command. Direct aliases navigate as soon as you type the alias. Indirect aliases navigate after typing a trailing space.</value>
|
||||
</data>
|
||||
<data name="Settings_ExtensionPage_Builtin_SettingsCard.Header" xml:space="preserve">
|
||||
<value>Built-in</value>
|
||||
@@ -435,15 +429,12 @@ Right-click to remove the key combination, thereby deactivating the shortcut.</v
|
||||
<value>Close</value>
|
||||
<comment>Close as a verb, as in Close the application</comment>
|
||||
</data>
|
||||
<data name="Settings_ExtensionPage_Alias_DirectComboBox.Content" xml:space="preserve">
|
||||
<data name="Settings_ExtensionPage_Alias_ToggleSwitch.OnContent" xml:space="preserve">
|
||||
<value>Direct</value>
|
||||
</data>
|
||||
<data name="Settings_ExtensionPage_Alias_InDirectComboBox.Content" xml:space="preserve">
|
||||
<data name="Settings_ExtensionPage_Alias_ToggleSwitch.OffContent" xml:space="preserve">
|
||||
<value>Indirect</value>
|
||||
</data>
|
||||
<data name="Settings_ExtensionPage_Alias_PlaceholderText.PlaceholderText" xml:space="preserve">
|
||||
<value>Enter alias</value>
|
||||
</data>
|
||||
<data name="StatusMessagesButton.[using:Microsoft.UI.Xaml.Automation]AutomationProperties.Name" xml:space="preserve">
|
||||
<value>Show status messages</value>
|
||||
</data>
|
||||
@@ -463,7 +454,7 @@ Right-click to remove the key combination, thereby deactivating the shortcut.</v
|
||||
<value>Trigger reload of the extension externally with the x-cmdpal://reload command</value>
|
||||
</data>
|
||||
<data name="ForDevelopersSettingsHeader.Text" xml:space="preserve">
|
||||
<value>For developers</value>
|
||||
<value>For Developers</value>
|
||||
</data>
|
||||
<data name="UntitledPageTitle" xml:space="preserve">
|
||||
<value>an untitled</value>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
|
||||
<ResourceDictionary Source="ms-appx:///CommunityToolkit.WinUI.Controls.SettingsControls/Themes/Generic.xaml" />
|
||||
<!-- Other merged dictionaries here -->
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<x:Double x:Key="SettingsCardSpacing">4</x:Double>
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" />
|
||||
@@ -17,7 +17,6 @@ public class Settings : ISettingsInterface
|
||||
private readonly bool hideKillProcessOnElevatedProcesses;
|
||||
private readonly bool hideExplorerSettingInfo;
|
||||
private readonly bool inMruOrder;
|
||||
private readonly bool useWindowIcon;
|
||||
|
||||
public Settings(
|
||||
bool resultsFromVisibleDesktopOnly = false,
|
||||
@@ -28,8 +27,7 @@ public class Settings : ISettingsInterface
|
||||
bool openAfterKillAndClose = false,
|
||||
bool hideKillProcessOnElevatedProcesses = false,
|
||||
bool hideExplorerSettingInfo = true,
|
||||
bool inMruOrder = true,
|
||||
bool useWindowIcon = true)
|
||||
bool inMruOrder = true)
|
||||
{
|
||||
this.resultsFromVisibleDesktopOnly = resultsFromVisibleDesktopOnly;
|
||||
this.subtitleShowPid = subtitleShowPid;
|
||||
@@ -40,7 +38,6 @@ public class Settings : ISettingsInterface
|
||||
this.hideKillProcessOnElevatedProcesses = hideKillProcessOnElevatedProcesses;
|
||||
this.hideExplorerSettingInfo = hideExplorerSettingInfo;
|
||||
this.inMruOrder = inMruOrder;
|
||||
this.useWindowIcon = useWindowIcon;
|
||||
}
|
||||
|
||||
public bool ResultsFromVisibleDesktopOnly => resultsFromVisibleDesktopOnly;
|
||||
@@ -60,6 +57,4 @@ public class Settings : ISettingsInterface
|
||||
public bool HideExplorerSettingInfo => hideExplorerSettingInfo;
|
||||
|
||||
public bool InMruOrder => inMruOrder;
|
||||
|
||||
public bool UseWindowIcon => useWindowIcon;
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
[assembly: SuppressMessage("Interoperability", "CsWinRT1028: Class should be marked partial", Justification = "CsWin32 generated code; not used across WinRT boundary", Scope = "type", Target = "~T:Windows.Win32.SysFreeStringSafeHandle")]
|
||||
@@ -1,35 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.CmdPal.Ext.ClipboardHistory.Models;
|
||||
using Microsoft.CommandPalette.Extensions.Toolkit;
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
/// <summary>
|
||||
/// Abstraction for providers that can extract metadata and offer actions for a clipboard context.
|
||||
/// </summary>
|
||||
internal interface IClipboardMetadataProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the section title to show in the UI for this provider's metadata.
|
||||
/// </summary>
|
||||
string SectionTitle { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if this provider can produce metadata for the given item.
|
||||
/// </summary>
|
||||
bool CanHandle(ClipboardItem item);
|
||||
|
||||
/// <summary>
|
||||
/// Returns metadata elements for the UI. Caller decides section grouping.
|
||||
/// </summary>
|
||||
IEnumerable<DetailsElement> GetDetails(ClipboardItem item);
|
||||
|
||||
/// <summary>
|
||||
/// Returns context actions to be appended to MoreCommands. Use unique IDs for de-duplication.
|
||||
/// </summary>
|
||||
IEnumerable<ProviderAction> GetActions(ClipboardItem item);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
internal sealed record ImageMetadata(
|
||||
uint Width,
|
||||
uint Height,
|
||||
double DpiX,
|
||||
double DpiY,
|
||||
ulong? StorageSize);
|
||||
@@ -1,55 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Windows.Graphics.Imaging;
|
||||
using Windows.Storage.Streams;
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
internal static class ImageMetadataAnalyzer
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads image metadata from a RandomAccessStreamReference without decoding pixels.
|
||||
/// Returns oriented dimensions (EXIF rotation applied).
|
||||
/// </summary>
|
||||
public static async Task<ImageMetadata> GetAsync(RandomAccessStreamReference reference)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(reference);
|
||||
|
||||
using IRandomAccessStream ras = await reference.OpenReadAsync().AsTask().ConfigureAwait(false);
|
||||
var sizeBytes = TryGetSize(ras);
|
||||
|
||||
// BitmapDecoder does not decode pixel data unless you ask it to,
|
||||
// so this is fast and memory-friendly.
|
||||
var decoder = await BitmapDecoder.CreateAsync(ras).AsTask().ConfigureAwait(false);
|
||||
|
||||
// OrientedPixelWidth/Height account for EXIF orientation
|
||||
var width = decoder.OrientedPixelWidth;
|
||||
var height = decoder.OrientedPixelHeight;
|
||||
|
||||
return new ImageMetadata(
|
||||
Width: width,
|
||||
Height: height,
|
||||
DpiX: decoder.DpiX,
|
||||
DpiY: decoder.DpiY,
|
||||
StorageSize: sizeBytes);
|
||||
}
|
||||
|
||||
private static ulong? TryGetSize(IRandomAccessStream s)
|
||||
{
|
||||
try
|
||||
{
|
||||
// On file-backed streams this is accurate.
|
||||
// On some URI/virtual streams this may be unsupported or 0.
|
||||
var size = s.Size;
|
||||
return size == 0 ? (ulong?)0 : size;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using ManagedCommon;
|
||||
using Microsoft.CmdPal.Ext.ClipboardHistory.Models;
|
||||
using Microsoft.CommandPalette.Extensions.Toolkit;
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
internal sealed class ImageMetadataProvider : IClipboardMetadataProvider
|
||||
{
|
||||
public string SectionTitle => "Image metadata";
|
||||
|
||||
public bool CanHandle(ClipboardItem item) => item.IsImage;
|
||||
|
||||
public IEnumerable<DetailsElement> GetDetails(ClipboardItem item)
|
||||
{
|
||||
var result = new List<DetailsElement>();
|
||||
if (!CanHandle(item) || item.ImageData is null)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var metadata = ImageMetadataAnalyzer.GetAsync(item.ImageData).GetAwaiter().GetResult();
|
||||
|
||||
result.Add(new DetailsElement
|
||||
{
|
||||
Key = "Dimensions",
|
||||
Data = new DetailsLink($"{metadata.Width} x {metadata.Height}"),
|
||||
});
|
||||
result.Add(new DetailsElement
|
||||
{
|
||||
Key = "DPI",
|
||||
Data = new DetailsLink($"{metadata.DpiX:0.###} x {metadata.DpiY:0.###}"),
|
||||
});
|
||||
|
||||
if (metadata.StorageSize != null)
|
||||
{
|
||||
result.Add(new DetailsElement
|
||||
{
|
||||
Key = "Storage size",
|
||||
Data = new DetailsLink(SizeFormatter.FormatSize(metadata.StorageSize.Value)),
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogDebug("Failed to retrieve image metadata:" + ex);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public IEnumerable<ProviderAction> GetActions(ClipboardItem item) => [];
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
internal enum LineEndingType
|
||||
{
|
||||
None,
|
||||
Windows, // \r\n (CRLF)
|
||||
Unix, // \n (LF)
|
||||
Mac, // \r (CR)
|
||||
Mixed,
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.CommandPalette.Extensions.Toolkit;
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an action exposed by a metadata provider.
|
||||
/// </summary>
|
||||
/// <param name="Id">Unique identifier for de-duplication (case-insensitive).</param>
|
||||
/// <param name="Action">The actual context menu item to be shown.</param>
|
||||
internal readonly record struct ProviderAction(string Id, CommandContextItem Action);
|
||||
@@ -1,49 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Globalization;
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
/// <summary>
|
||||
/// Utility for formatting byte sizes to a human-readable string.
|
||||
/// </summary>
|
||||
internal static class SizeFormatter
|
||||
{
|
||||
private const long KB = 1024;
|
||||
private const long MB = 1024 * KB;
|
||||
private const long GB = 1024 * MB;
|
||||
|
||||
public static string FormatSize(long bytes)
|
||||
{
|
||||
return bytes switch
|
||||
{
|
||||
>= GB => string.Format(CultureInfo.CurrentCulture, "{0:F2} GB", (double)bytes / GB),
|
||||
>= MB => string.Format(CultureInfo.CurrentCulture, "{0:F2} MB", (double)bytes / MB),
|
||||
>= KB => string.Format(CultureInfo.CurrentCulture, "{0:F2} KB", (double)bytes / KB),
|
||||
_ => string.Format(CultureInfo.CurrentCulture, "{0} B", bytes),
|
||||
};
|
||||
}
|
||||
|
||||
public static string FormatSize(ulong bytes)
|
||||
{
|
||||
// Use double for division to avoid overflow; thresholds mirror long version
|
||||
if (bytes >= (ulong)GB)
|
||||
{
|
||||
return string.Format(CultureInfo.CurrentCulture, "{0:F2} GB", bytes / (double)GB);
|
||||
}
|
||||
|
||||
if (bytes >= (ulong)MB)
|
||||
{
|
||||
return string.Format(CultureInfo.CurrentCulture, "{0:F2} MB", bytes / (double)MB);
|
||||
}
|
||||
|
||||
if (bytes >= (ulong)KB)
|
||||
{
|
||||
return string.Format(CultureInfo.CurrentCulture, "{0:F2} KB", bytes / (double)KB);
|
||||
}
|
||||
|
||||
return string.Format(CultureInfo.CurrentCulture, "{0} B", bytes);
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using ManagedCommon;
|
||||
using Microsoft.CmdPal.Core.Common.Helpers;
|
||||
using Microsoft.CmdPal.Ext.ClipboardHistory.Models;
|
||||
using Microsoft.CommandPalette.Extensions.Toolkit;
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
/// <summary>
|
||||
/// Detects when text content is a valid existing file or directory path and exposes basic metadata.
|
||||
/// </summary>
|
||||
internal sealed class TextFileSystemMetadataProvider : IClipboardMetadataProvider
|
||||
{
|
||||
public string SectionTitle => "File";
|
||||
|
||||
public bool CanHandle(ClipboardItem item)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
|
||||
if (!item.IsText || string.IsNullOrWhiteSpace(item.Content))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var text = PathHelper.Unquote(item.Content);
|
||||
return PathHelper.IsValidFilePath(text);
|
||||
}
|
||||
|
||||
public IEnumerable<DetailsElement> GetDetails(ClipboardItem item)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
|
||||
var result = new List<DetailsElement>();
|
||||
if (!item.IsText || string.IsNullOrWhiteSpace(item.Content))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
var path = PathHelper.Unquote(item.Content);
|
||||
|
||||
if (PathHelper.IsSlow(path) || !PathHelper.Exists(path, out var isDirectory))
|
||||
{
|
||||
result.Add(new DetailsElement { Key = "Name", Data = new DetailsLink(Path.GetFileName(path)) });
|
||||
result.Add(new DetailsElement { Key = "Location", Data = new DetailsLink(UrlHelper.NormalizeUrl(path), path) });
|
||||
return result;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (!isDirectory)
|
||||
{
|
||||
var fi = new FileInfo(path);
|
||||
result.Add(new DetailsElement { Key = "Name", Data = new DetailsLink(fi.Name) });
|
||||
result.Add(new DetailsElement { Key = "Location", Data = new DetailsLink(UrlHelper.NormalizeUrl(fi.FullName), fi.FullName) });
|
||||
result.Add(new DetailsElement { Key = "Type", Data = new DetailsLink(fi.Extension) });
|
||||
result.Add(new DetailsElement { Key = "Size", Data = new DetailsLink(SizeFormatter.FormatSize(fi.Length)) });
|
||||
result.Add(new DetailsElement { Key = "Modified", Data = new DetailsLink(fi.LastWriteTime.ToString(CultureInfo.CurrentCulture)) });
|
||||
result.Add(new DetailsElement { Key = "Created", Data = new DetailsLink(fi.CreationTime.ToString(CultureInfo.CurrentCulture)) });
|
||||
}
|
||||
else
|
||||
{
|
||||
var di = new DirectoryInfo(path);
|
||||
result.Add(new DetailsElement { Key = "Name", Data = new DetailsLink(di.Name) });
|
||||
result.Add(new DetailsElement { Key = "Location", Data = new DetailsLink(UrlHelper.NormalizeUrl(di.FullName), di.FullName) });
|
||||
result.Add(new DetailsElement { Key = "Type", Data = new DetailsLink("Folder") });
|
||||
result.Add(new DetailsElement { Key = "Modified", Data = new DetailsLink(di.LastWriteTime.ToString(CultureInfo.CurrentCulture)) });
|
||||
result.Add(new DetailsElement { Key = "Created", Data = new DetailsLink(di.CreationTime.ToString(CultureInfo.CurrentCulture)) });
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError("Failed to retrieve file system metadata.", ex);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public IEnumerable<ProviderAction> GetActions(ClipboardItem item)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
|
||||
if (!item.IsText || string.IsNullOrWhiteSpace(item.Content))
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
var path = PathHelper.Unquote(item.Content);
|
||||
|
||||
if (PathHelper.IsSlow(path) || !PathHelper.Exists(path, out var isDirectory))
|
||||
{
|
||||
// One anything
|
||||
var open = new CommandContextItem(new OpenFileCommand(path)) { RequestedShortcut = KeyChords.OpenUrl };
|
||||
yield return new ProviderAction(WellKnownActionIds.Open, open);
|
||||
|
||||
yield break;
|
||||
}
|
||||
|
||||
if (!isDirectory)
|
||||
{
|
||||
// Open file
|
||||
var open = new CommandContextItem(new OpenFileCommand(path)) { RequestedShortcut = KeyChords.OpenUrl };
|
||||
yield return new ProviderAction(WellKnownActionIds.Open, open);
|
||||
|
||||
// Show in folder (select)
|
||||
var show = new CommandContextItem(new ShowFileInFolderCommand(path)) { RequestedShortcut = WellKnownKeyChords.OpenFileLocation };
|
||||
yield return new ProviderAction(WellKnownActionIds.OpenLocation, show);
|
||||
|
||||
// Copy path
|
||||
var copy = new CommandContextItem(new CopyPathCommand(path)) { RequestedShortcut = WellKnownKeyChords.CopyFilePath };
|
||||
yield return new ProviderAction(WellKnownActionIds.CopyPath, copy);
|
||||
|
||||
// Open in console at file location
|
||||
var openConsole = new CommandContextItem(OpenInConsoleCommand.FromFile(path)) { RequestedShortcut = WellKnownKeyChords.OpenInConsole };
|
||||
yield return new ProviderAction(WellKnownActionIds.OpenConsole, openConsole);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Open folder
|
||||
var openFolder = new CommandContextItem(new OpenFileCommand(path)) { RequestedShortcut = KeyChords.OpenUrl };
|
||||
yield return new ProviderAction(WellKnownActionIds.Open, openFolder);
|
||||
|
||||
// Open in console
|
||||
var openConsole = new CommandContextItem(OpenInConsoleCommand.FromDirectory(path)) { RequestedShortcut = WellKnownKeyChords.OpenInConsole };
|
||||
yield return new ProviderAction(WellKnownActionIds.OpenConsole, openConsole);
|
||||
|
||||
// Copy path
|
||||
var copy = new CommandContextItem(new CopyPathCommand(path)) { RequestedShortcut = WellKnownKeyChords.CopyFilePath };
|
||||
yield return new ProviderAction(WellKnownActionIds.CopyPath, copy);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
internal sealed record TextMetadata
|
||||
{
|
||||
public int CharacterCount { get; init; }
|
||||
|
||||
public int WordCount { get; init; }
|
||||
|
||||
public int SentenceCount { get; init; }
|
||||
|
||||
public int LineCount { get; init; }
|
||||
|
||||
public int ParagraphCount { get; init; }
|
||||
|
||||
public LineEndingType LineEnding { get; init; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"Characters: {CharacterCount}, Words: {WordCount}, Sentences: {SentenceCount}, Lines: {LineCount}, Paragraphs: {ParagraphCount}, Line Ending: {LineEnding}";
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
internal partial class TextMetadataAnalyzer
|
||||
{
|
||||
public TextMetadata Analyze(string input)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
|
||||
return new TextMetadata
|
||||
{
|
||||
CharacterCount = input.Length,
|
||||
WordCount = CountWords(input),
|
||||
SentenceCount = CountSentences(input),
|
||||
LineCount = CountLines(input),
|
||||
ParagraphCount = CountParagraphs(input),
|
||||
LineEnding = DetectLineEnding(input),
|
||||
};
|
||||
}
|
||||
|
||||
private LineEndingType DetectLineEnding(string text)
|
||||
{
|
||||
var crlfCount = Regex.Matches(text, "\r\n").Count;
|
||||
var lfCount = Regex.Matches(text, "(?<!\r)\n").Count;
|
||||
var crCount = Regex.Matches(text, "\r(?!\n)").Count;
|
||||
|
||||
var endingTypes = (crlfCount > 0 ? 1 : 0) + (lfCount > 0 ? 1 : 0) + (crCount > 0 ? 1 : 0);
|
||||
|
||||
if (endingTypes > 1)
|
||||
{
|
||||
return LineEndingType.Mixed;
|
||||
}
|
||||
|
||||
if (crlfCount > 0)
|
||||
{
|
||||
return LineEndingType.Windows;
|
||||
}
|
||||
|
||||
if (lfCount > 0)
|
||||
{
|
||||
return LineEndingType.Unix;
|
||||
}
|
||||
|
||||
if (crCount > 0)
|
||||
{
|
||||
return LineEndingType.Mac;
|
||||
}
|
||||
|
||||
return LineEndingType.None;
|
||||
}
|
||||
|
||||
private int CountLines(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return text.Count(c => c == '\n') + 1;
|
||||
}
|
||||
|
||||
private int CountParagraphs(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var paragraphs = ParagraphsRegex()
|
||||
.Split(text)
|
||||
.Count(static p => !string.IsNullOrWhiteSpace(p));
|
||||
|
||||
return paragraphs > 0 ? paragraphs : 1;
|
||||
}
|
||||
|
||||
private int CountWords(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Regex.Matches(text, @"\b\w+\b").Count;
|
||||
}
|
||||
|
||||
private int CountSentences(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var matches = SentencesRegex().Matches(text);
|
||||
return matches.Count > 0 ? matches.Count : (text.Trim().Length > 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"(\r?\n){2,}")]
|
||||
private static partial Regex ParagraphsRegex();
|
||||
|
||||
[GeneratedRegex(@"[.!?]+(?=\s|$)")]
|
||||
private static partial Regex SentencesRegex();
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using Microsoft.CmdPal.Ext.ClipboardHistory.Models;
|
||||
using Microsoft.CommandPalette.Extensions.Toolkit;
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
internal sealed class TextMetadataProvider : IClipboardMetadataProvider
|
||||
{
|
||||
public string SectionTitle => "Text statistics";
|
||||
|
||||
public bool CanHandle(ClipboardItem item) => item.IsText;
|
||||
|
||||
public IEnumerable<DetailsElement> GetDetails(ClipboardItem item)
|
||||
{
|
||||
var result = new List<DetailsElement>();
|
||||
if (!CanHandle(item) || string.IsNullOrEmpty(item.Content))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
var r = new TextMetadataAnalyzer().Analyze(item.Content);
|
||||
|
||||
result.Add(new DetailsElement
|
||||
{
|
||||
Key = "Characters",
|
||||
Data = new DetailsLink(r.CharacterCount.ToString(CultureInfo.CurrentCulture)),
|
||||
});
|
||||
result.Add(new DetailsElement
|
||||
{
|
||||
Key = "Words",
|
||||
Data = new DetailsLink(r.WordCount.ToString(CultureInfo.CurrentCulture)),
|
||||
});
|
||||
result.Add(new DetailsElement
|
||||
{
|
||||
Key = "Sentences",
|
||||
Data = new DetailsLink(r.SentenceCount.ToString(CultureInfo.CurrentCulture)),
|
||||
});
|
||||
result.Add(new DetailsElement
|
||||
{
|
||||
Key = "Lines",
|
||||
Data = new DetailsLink(r.LineCount.ToString(CultureInfo.CurrentCulture)),
|
||||
});
|
||||
result.Add(new DetailsElement
|
||||
{
|
||||
Key = "Paragraphs",
|
||||
Data = new DetailsLink(r.ParagraphCount.ToString(CultureInfo.CurrentCulture)),
|
||||
});
|
||||
result.Add(new DetailsElement
|
||||
{
|
||||
Key = "Line Ending",
|
||||
Data = new DetailsLink(r.LineEnding.ToString()),
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public IEnumerable<ProviderAction> GetActions(ClipboardItem item) => [];
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using Microsoft.CmdPal.Ext.ClipboardHistory.Models;
|
||||
using Microsoft.CommandPalette.Extensions.Toolkit;
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
/// <summary>
|
||||
/// Detects web links in text and shows normalized URL and key parts.
|
||||
/// </summary>
|
||||
internal sealed class WebLinkMetadataProvider : IClipboardMetadataProvider
|
||||
{
|
||||
public string SectionTitle => "Link";
|
||||
|
||||
public bool CanHandle(ClipboardItem item)
|
||||
{
|
||||
if (!item.IsText || string.IsNullOrWhiteSpace(item.Content))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!UrlHelper.IsValidUrl(item.Content))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var normalized = UrlHelper.NormalizeUrl(item.Content);
|
||||
if (!Uri.TryCreate(normalized, UriKind.Absolute, out var uri))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Exclude file: scheme; it's handled by TextFileSystemMetadataProvider
|
||||
return !uri.Scheme.Equals(Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public IEnumerable<DetailsElement> GetDetails(ClipboardItem item)
|
||||
{
|
||||
var result = new List<DetailsElement>();
|
||||
if (!item.IsText || string.IsNullOrWhiteSpace(item.Content))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var normalized = UrlHelper.NormalizeUrl(item.Content);
|
||||
if (!Uri.TryCreate(normalized, UriKind.Absolute, out var uri))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
// Skip file: at runtime as well (defensive)
|
||||
if (uri.Scheme.Equals(Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
result.Add(new DetailsElement { Key = "URL", Data = new DetailsLink(normalized) });
|
||||
result.Add(new DetailsElement { Key = "Host", Data = new DetailsLink(uri.Host) });
|
||||
|
||||
if (!uri.IsDefaultPort)
|
||||
{
|
||||
result.Add(new DetailsElement { Key = "Port", Data = new DetailsLink(uri.Port.ToString(CultureInfo.CurrentCulture)) });
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(uri.AbsolutePath) && uri.AbsolutePath != "/")
|
||||
{
|
||||
result.Add(new DetailsElement { Key = "Path", Data = new DetailsLink(uri.AbsolutePath) });
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(uri.Query))
|
||||
{
|
||||
var q = uri.Query;
|
||||
var count = q.Count(static c => c == '&') + (q.Length > 1 ? 1 : 0);
|
||||
result.Add(new DetailsElement { Key = "Query params", Data = new DetailsLink(count.ToString(CultureInfo.CurrentCulture)) });
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(uri.Fragment))
|
||||
{
|
||||
result.Add(new DetailsElement { Key = "Fragment", Data = new DetailsLink(uri.Fragment) });
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignore malformed inputs
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public IEnumerable<ProviderAction> GetActions(ClipboardItem item)
|
||||
{
|
||||
if (!CanHandle(item))
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
var normalized = UrlHelper.NormalizeUrl(item.Content!);
|
||||
|
||||
var open = new CommandContextItem(new OpenUrlCommand(normalized))
|
||||
{
|
||||
RequestedShortcut = KeyChords.OpenUrl,
|
||||
};
|
||||
yield return new ProviderAction(WellKnownActionIds.Open, open);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
|
||||
/// <summary>
|
||||
/// Well-known action id constants used to de-duplicate provider actions.
|
||||
/// </summary>
|
||||
internal static class WellKnownActionIds
|
||||
{
|
||||
public const string Open = "open";
|
||||
public const string OpenLocation = "openLocation";
|
||||
public const string CopyPath = "copyPath";
|
||||
public const string OpenConsole = "openConsole";
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using Microsoft.CmdPal.Core.Common.Helpers;
|
||||
using System.IO;
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.ClipboardHistory.Helpers;
|
||||
|
||||
@@ -31,7 +31,7 @@ internal static class UrlHelper
|
||||
}
|
||||
|
||||
// Check if it's a valid file path (local or network)
|
||||
if (PathHelper.IsValidFilePath(url))
|
||||
if (IsValidFilePath(url))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -78,7 +78,7 @@ internal static class UrlHelper
|
||||
url = url.Trim();
|
||||
|
||||
// If it's a valid file path, convert to file:// URI
|
||||
if (!url.StartsWith("file://", StringComparison.OrdinalIgnoreCase) && PathHelper.IsValidFilePath(url))
|
||||
if (IsValidFilePath(url) && !url.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -105,4 +105,40 @@ internal static class UrlHelper
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a string represents a valid file path (local or network)
|
||||
/// </summary>
|
||||
/// <param name="path">The string to check</param>
|
||||
/// <returns>True if the string is a valid file path, false otherwise</returns>
|
||||
private static bool IsValidFilePath(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Check for UNC paths (network paths starting with \\)
|
||||
if (path.StartsWith(@"\\", StringComparison.Ordinal))
|
||||
{
|
||||
// Basic UNC path validation: \\server\share or \\server\share\path
|
||||
var parts = path.Substring(2).Split('\\', StringSplitOptions.RemoveEmptyEntries);
|
||||
return parts.Length >= 2; // At minimum: server and share
|
||||
}
|
||||
|
||||
// Check for drive letters (C:\ or C:)
|
||||
if (path.Length >= 2 && char.IsLetter(path[0]) && path[1] == ':')
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\common\ManagedCommon\ManagedCommon.csproj" />
|
||||
<ProjectReference Include="..\..\Core\Microsoft.CmdPal.Core.Common\Microsoft.CmdPal.Core.Common.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
@@ -9,7 +9,6 @@ using System.Linq;
|
||||
using Microsoft.CmdPal.Common.Commands;
|
||||
using Microsoft.CmdPal.Ext.ClipboardHistory.Commands;
|
||||
using Microsoft.CmdPal.Ext.ClipboardHistory.Helpers;
|
||||
using Microsoft.CmdPal.Ext.ClipboardHistory.Helpers.Analyzers;
|
||||
using Microsoft.CommandPalette.Extensions;
|
||||
using Microsoft.CommandPalette.Extensions.Toolkit;
|
||||
|
||||
@@ -17,20 +16,13 @@ namespace Microsoft.CmdPal.Ext.ClipboardHistory.Models;
|
||||
|
||||
internal sealed partial class ClipboardListItem : ListItem
|
||||
{
|
||||
private static readonly IClipboardMetadataProvider[] MetadataProviders =
|
||||
[
|
||||
new ImageMetadataProvider(),
|
||||
new TextFileSystemMetadataProvider(),
|
||||
new WebLinkMetadataProvider(),
|
||||
new TextMetadataProvider(),
|
||||
];
|
||||
|
||||
private readonly SettingsManager _settingsManager;
|
||||
private readonly ClipboardItem _item;
|
||||
|
||||
private readonly CommandContextItem _deleteContextMenuItem;
|
||||
private readonly CommandContextItem? _pasteCommand;
|
||||
private readonly CommandContextItem? _copyCommand;
|
||||
private readonly CommandContextItem? _openUrlCommand;
|
||||
private readonly Lazy<Details> _lazyDetails;
|
||||
|
||||
public override IDetails? Details
|
||||
@@ -81,11 +73,26 @@ internal sealed partial class ClipboardListItem : ListItem
|
||||
|
||||
_pasteCommand = new CommandContextItem(new PasteCommand(_item, ClipboardFormat.Text, _settingsManager));
|
||||
_copyCommand = new CommandContextItem(new CopyCommand(_item, ClipboardFormat.Text));
|
||||
|
||||
// Check if the text content is a valid URL and add OpenUrl command
|
||||
if (UrlHelper.IsValidUrl(_item.Content ?? string.Empty))
|
||||
{
|
||||
var normalizedUrl = UrlHelper.NormalizeUrl(_item.Content ?? string.Empty);
|
||||
_openUrlCommand = new CommandContextItem(new OpenUrlCommand(normalizedUrl))
|
||||
{
|
||||
RequestedShortcut = KeyChords.OpenUrl,
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
_openUrlCommand = null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_pasteCommand = null;
|
||||
_copyCommand = null;
|
||||
_openUrlCommand = null;
|
||||
}
|
||||
|
||||
RefreshCommands();
|
||||
@@ -156,74 +163,27 @@ internal sealed partial class ClipboardListItem : ListItem
|
||||
commands.Add(firstCommand);
|
||||
}
|
||||
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var temp = new List<IContextItem>();
|
||||
foreach (var provider in MetadataProviders)
|
||||
if (_openUrlCommand != null)
|
||||
{
|
||||
if (!provider.CanHandle(_item))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var action in provider.GetActions(_item))
|
||||
{
|
||||
if (string.IsNullOrEmpty(action.Id) || !seen.Add(action.Id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
temp.Add(action.Action);
|
||||
}
|
||||
}
|
||||
|
||||
if (temp.Count > 0)
|
||||
{
|
||||
if (commands.Count > 0)
|
||||
{
|
||||
commands.Add(new Separator());
|
||||
}
|
||||
|
||||
commands.AddRange(temp);
|
||||
commands.Add(_openUrlCommand);
|
||||
}
|
||||
|
||||
commands.Add(new Separator());
|
||||
commands.Add(_deleteContextMenuItem);
|
||||
|
||||
return [.. commands];
|
||||
return commands.ToArray();
|
||||
}
|
||||
|
||||
private Details CreateDetails()
|
||||
{
|
||||
List<IDetailsElement> metadata = [];
|
||||
|
||||
foreach (var provider in MetadataProviders)
|
||||
{
|
||||
if (provider.CanHandle(_item))
|
||||
IDetailsElement[] metadata =
|
||||
[
|
||||
new DetailsElement
|
||||
{
|
||||
var details = provider.GetDetails(_item);
|
||||
if (details.Any())
|
||||
{
|
||||
metadata.Add(new DetailsElement
|
||||
{
|
||||
Key = provider.SectionTitle,
|
||||
Data = new DetailsSeparator(),
|
||||
});
|
||||
|
||||
metadata.AddRange(details);
|
||||
}
|
||||
Key = "Copied on",
|
||||
Data = new DetailsLink(_item.Timestamp.DateTime.ToString(DateTimeFormatInfo.CurrentInfo)),
|
||||
}
|
||||
}
|
||||
|
||||
metadata.Add(new DetailsElement
|
||||
{
|
||||
Key = "General",
|
||||
Data = new DetailsSeparator(),
|
||||
});
|
||||
metadata.Add(new DetailsElement
|
||||
{
|
||||
Key = "Copied",
|
||||
Data = new DetailsLink(_item.Timestamp.DateTime.ToString(DateTimeFormatInfo.CurrentInfo)),
|
||||
});
|
||||
];
|
||||
|
||||
if (_item.IsImage)
|
||||
{
|
||||
@@ -233,7 +193,7 @@ internal sealed partial class ClipboardListItem : ListItem
|
||||
{
|
||||
Title = _item.GetDataType(),
|
||||
HeroImage = heroImage,
|
||||
Metadata = [.. metadata],
|
||||
Metadata = metadata,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -243,7 +203,7 @@ internal sealed partial class ClipboardListItem : ListItem
|
||||
{
|
||||
Title = _item.GetDataType(),
|
||||
Body = $"```text\n{_item.Content}\n```",
|
||||
Metadata = [.. metadata],
|
||||
Metadata = metadata,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ namespace Microsoft.CmdPal.Ext.ClipboardHistory.Properties {
|
||||
// class via a tool like ResGen or Visual Studio.
|
||||
// To add or remove a member, edit your .ResX file then rerun ResGen
|
||||
// with the /str option, or rebuild your VS project.
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "18.0.0.0")]
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
|
||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
public class Resources {
|
||||
@@ -187,7 +187,7 @@ namespace Microsoft.CmdPal.Ext.ClipboardHistory.Properties {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Show a confirmation dialog when manually deleting an item.
|
||||
/// Looks up a localized string similar to .
|
||||
/// </summary>
|
||||
public static string settings_confirm_delete_description {
|
||||
get {
|
||||
@@ -196,7 +196,7 @@ namespace Microsoft.CmdPal.Ext.ClipboardHistory.Properties {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Ask for confirmation before deleting items.
|
||||
/// Looks up a localized string similar to Show a confirmation dialog when manually deleting an item.
|
||||
/// </summary>
|
||||
public static string settings_confirm_delete_title {
|
||||
get {
|
||||
@@ -205,7 +205,7 @@ namespace Microsoft.CmdPal.Ext.ClipboardHistory.Properties {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Keep items in clipboard history after pasting.
|
||||
/// Looks up a localized string similar to .
|
||||
/// </summary>
|
||||
public static string settings_keep_after_paste_description {
|
||||
get {
|
||||
@@ -214,7 +214,7 @@ namespace Microsoft.CmdPal.Ext.ClipboardHistory.Properties {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Keep items after pasting.
|
||||
/// Looks up a localized string similar to Keep items in clipboard history after pasting.
|
||||
/// </summary>
|
||||
public static string settings_keep_after_paste_title {
|
||||
get {
|
||||
|
||||
@@ -151,16 +151,16 @@
|
||||
<value>Deleted from clipboard history</value>
|
||||
</data>
|
||||
<data name="settings_keep_after_paste_description" xml:space="preserve">
|
||||
<value>Keep items in clipboard history after pasting</value>
|
||||
<value />
|
||||
</data>
|
||||
<data name="settings_keep_after_paste_title" xml:space="preserve">
|
||||
<value>Keep items after pasting</value>
|
||||
<value>Keep items in clipboard history after pasting</value>
|
||||
</data>
|
||||
<data name="settings_confirm_delete_title" xml:space="preserve">
|
||||
<value>Ask for confirmation before deleting items</value>
|
||||
<value>Show a confirmation dialog when manually deleting an item</value>
|
||||
</data>
|
||||
<data name="settings_confirm_delete_description" xml:space="preserve">
|
||||
<value>Show a confirmation dialog when manually deleting an item</value>
|
||||
<value />
|
||||
</data>
|
||||
<data name="delete_confirmation_title" xml:space="preserve">
|
||||
<value>Delete item?</value>
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
[assembly: SuppressMessage("Interoperability", "CsWinRT1028: Class should be marked partial", Justification = "CsWin32 generated code; not used across WinRT boundary", Scope = "type", Target = "~T:Windows.Win32.LocalFreeSafeHandle")]
|
||||
@@ -27,14 +27,6 @@ internal sealed class NetworkConnectionProperties
|
||||
/// <seealso cref="https://github.com/xoofx/markdig/blob/master/src/Markdig/Extensions/Emoji/EmojiMapping.cs"/>
|
||||
private const int GreenCircleCharacter = 128994;
|
||||
|
||||
/// <summary>
|
||||
/// Decimal unicode value for green circle emoji.
|
||||
/// We need to generate it in the code because it does not render using Markdown emoji syntax or Unicode character syntax.
|
||||
/// </summary>
|
||||
/// <seealso cref="https://github.com/CommunityToolkit/Labs-Windows/blob/main/components/MarkdownTextBlock/samples/MarkdownTextBlock.md"/>
|
||||
/// <seealso cref="https://github.com/xoofx/markdig/blob/master/src/Markdig/Extensions/Emoji/EmojiMapping.cs"/>
|
||||
private const int RedCircleCharacter = 128308;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the adapter
|
||||
/// </summary>
|
||||
@@ -178,7 +170,7 @@ internal sealed class NetworkConnectionProperties
|
||||
internal string GetAdapterDetails()
|
||||
{
|
||||
return $"**{Resources.Microsoft_plugin_sys_AdapterName}:** {Adapter}" +
|
||||
$"\n\n**{Resources.Microsoft_plugin_sys_State}:** " + (State == OperationalStatus.Up ? char.ConvertFromUtf32(GreenCircleCharacter) + " " + Resources.Microsoft_plugin_sys_Connected : char.ConvertFromUtf32(RedCircleCharacter) + " " + Resources.Microsoft_plugin_sys_Disconnected) +
|
||||
$"\n\n**{Resources.Microsoft_plugin_sys_State}:** " + (State == OperationalStatus.Up ? char.ConvertFromUtf32(GreenCircleCharacter) + " " + Resources.Microsoft_plugin_sys_Connected : ":red_circle: " + Resources.Microsoft_plugin_sys_Disconnected) +
|
||||
$"\n\n**{Resources.Microsoft_plugin_sys_PhysicalAddress}:** {PhysicalAddress}" +
|
||||
$"\n\n**{Resources.Microsoft_plugin_sys_Speed}:** {GetFormattedSpeedValue(Speed)}" +
|
||||
$"\n\n**{Resources.Microsoft_plugin_sys_Type}:** {GetAdapterTypeAsString(Type)}" +
|
||||
@@ -192,7 +184,7 @@ internal sealed class NetworkConnectionProperties
|
||||
internal string GetConnectionDetails()
|
||||
{
|
||||
return $"**{Resources.Microsoft_plugin_sys_ConnectionName}:** {ConnectionName}" +
|
||||
$"\n\n**{Resources.Microsoft_plugin_sys_State}:** " + (State == OperationalStatus.Up ? char.ConvertFromUtf32(GreenCircleCharacter) + " " + Resources.Microsoft_plugin_sys_Connected : char.ConvertFromUtf32(RedCircleCharacter) + " " + Resources.Microsoft_plugin_sys_Disconnected) +
|
||||
$"\n\n**{Resources.Microsoft_plugin_sys_State}:** " + (State == OperationalStatus.Up ? char.ConvertFromUtf32(GreenCircleCharacter) + " " + Resources.Microsoft_plugin_sys_Connected : ":red_circle: " + Resources.Microsoft_plugin_sys_Disconnected) +
|
||||
$"\n\n**{Resources.Microsoft_plugin_sys_Type}:** {GetAdapterTypeAsString(Type)}" +
|
||||
$"\n\n**{Resources.Microsoft_plugin_sys_Suffix}:** {Suffix}" +
|
||||
CreateIpInfoForDetailsText($"**{Resources.Microsoft_plugin_sys_Ip4Address}:** ", IPv4) +
|
||||
|
||||
@@ -2,16 +2,11 @@
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using Microsoft.CmdPal.Ext.WindowWalker.Components;
|
||||
using Microsoft.CmdPal.Ext.WindowWalker.Helpers;
|
||||
using Microsoft.CmdPal.Ext.WindowWalker.Properties;
|
||||
using Microsoft.CommandPalette.Extensions;
|
||||
using Microsoft.CommandPalette.Extensions.Toolkit;
|
||||
using Windows.Storage.Streams;
|
||||
|
||||
namespace Microsoft.CmdPal.Ext.WindowWalker.Commands;
|
||||
|
||||
@@ -21,53 +16,20 @@ internal sealed partial class SwitchToWindowCommand : InvokableCommand
|
||||
|
||||
public SwitchToWindowCommand(Window? window)
|
||||
{
|
||||
Icon = Icons.GenericAppIcon; // Fallback to default icon
|
||||
Name = Resources.switch_to_command_title;
|
||||
_window = window;
|
||||
if (_window is not null)
|
||||
{
|
||||
// Use window icon
|
||||
if (SettingsManager.Instance.UseWindowIcon)
|
||||
var p = Process.GetProcessById((int)_window.Process.ProcessID);
|
||||
if (p is not null)
|
||||
{
|
||||
if (_window.TryGetWindowIcon(out var icon) && icon is not null)
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
using var bitmap = icon.ToBitmap();
|
||||
using var memoryStream = new MemoryStream();
|
||||
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
|
||||
var raStream = new InMemoryRandomAccessStream();
|
||||
using var outputStream = raStream.GetOutputStreamAt(0);
|
||||
using var dataWriter = new DataWriter(outputStream);
|
||||
dataWriter.WriteBytes(memoryStream.ToArray());
|
||||
dataWriter.StoreAsync().AsTask().Wait();
|
||||
dataWriter.FlushAsync().AsTask().Wait();
|
||||
Icon = IconInfo.FromStream(raStream);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
icon.Dispose();
|
||||
}
|
||||
var processFileName = p.MainModule?.FileName;
|
||||
Icon = new IconInfo(processFileName);
|
||||
}
|
||||
}
|
||||
|
||||
// Use process icon
|
||||
else
|
||||
{
|
||||
var p = Process.GetProcessById((int)_window.Process.ProcessID);
|
||||
if (p is not null)
|
||||
catch
|
||||
{
|
||||
try
|
||||
{
|
||||
var processFileName = p.MainModule?.FileName;
|
||||
Icon = new IconInfo(processFileName);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,62 +188,6 @@ internal sealed class Window
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the window icon.
|
||||
/// </summary>
|
||||
/// <param name="icon">The window icon if found; otherwise, null.</param>
|
||||
/// <returns>True if an icon was found; otherwise, false.</returns>
|
||||
internal bool TryGetWindowIcon(out System.Drawing.Icon? icon)
|
||||
{
|
||||
icon = null;
|
||||
|
||||
if (hwnd == IntPtr.Zero)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Try WM_GETICON with SendMessageTimeout
|
||||
if (NativeMethods.SendMessageTimeout(hwnd, Win32Constants.WM_GETICON, (UIntPtr)Win32Constants.ICON_BIG, IntPtr.Zero, Win32Constants.SMTO_ABORTIFHUNG, 100, out var result) != 0 && result != 0)
|
||||
{
|
||||
icon = System.Drawing.Icon.FromHandle((IntPtr)result);
|
||||
NativeMethods.DestroyIcon((IntPtr)result);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (NativeMethods.SendMessageTimeout(hwnd, Win32Constants.WM_GETICON, (UIntPtr)Win32Constants.ICON_SMALL, IntPtr.Zero, Win32Constants.SMTO_ABORTIFHUNG, 100, out result) != 0 && result != 0)
|
||||
{
|
||||
icon = System.Drawing.Icon.FromHandle((IntPtr)result);
|
||||
NativeMethods.DestroyIcon((IntPtr)result);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (NativeMethods.SendMessageTimeout(hwnd, Win32Constants.WM_GETICON, (UIntPtr)Win32Constants.ICON_SMALL2, IntPtr.Zero, Win32Constants.SMTO_ABORTIFHUNG, 100, out result) != 0 && result != 0)
|
||||
{
|
||||
icon = System.Drawing.Icon.FromHandle((IntPtr)result);
|
||||
NativeMethods.DestroyIcon((IntPtr)result);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Fallback to GetClassLongPtr
|
||||
var iconHandle = NativeMethods.GetClassLongPtr(hwnd, Win32Constants.GCLP_HICON);
|
||||
if (iconHandle != IntPtr.Zero)
|
||||
{
|
||||
icon = System.Drawing.Icon.FromHandle(iconHandle);
|
||||
NativeMethods.DestroyIcon((IntPtr)iconHandle);
|
||||
return true;
|
||||
}
|
||||
|
||||
iconHandle = NativeMethods.GetClassLongPtr(hwnd, Win32Constants.GCLP_HICONSM);
|
||||
if (iconHandle != IntPtr.Zero)
|
||||
{
|
||||
icon = System.Drawing.Icon.FromHandle(iconHandle);
|
||||
NativeMethods.DestroyIcon((IntPtr)iconHandle);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the window name to string along with the process name
|
||||
/// </summary>
|
||||
@@ -380,7 +324,7 @@ internal sealed class Window
|
||||
|
||||
// Correct the process data if the window belongs to a uwp app hosted by 'ApplicationFrameHost.exe'
|
||||
// (This only works if the window isn't minimized. For minimized windows the required child window isn't assigned.)
|
||||
if (_handlesToProcessCache[hWindow].IsUwpAppFrameHost)
|
||||
if (string.Equals(_handlesToProcessCache[hWindow].Name, "ApplicationFrameHost.exe", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
new Task(() =>
|
||||
{
|
||||
|
||||
@@ -23,7 +23,7 @@ internal sealed class WindowProcess
|
||||
/// <summary>
|
||||
/// An indicator if the window belongs to an 'Universal Windows Platform (UWP)' process
|
||||
/// </summary>
|
||||
private bool _isUwpAppFrameHost;
|
||||
private readonly bool _isUwpAppFrameHost;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the id of the process
|
||||
@@ -126,14 +126,6 @@ internal sealed class WindowProcess
|
||||
get; private set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the type of the process (UWP app, packaged Win32 app, unpackaged Win32 app, ...).
|
||||
/// </summary>
|
||||
internal ProcessPackagingInfo ProcessType
|
||||
{
|
||||
get; private set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WindowProcess"/> class.
|
||||
/// </summary>
|
||||
@@ -142,10 +134,13 @@ internal sealed class WindowProcess
|
||||
/// <param name="name">New process name.</param>
|
||||
internal WindowProcess(uint pid, uint tid, string name)
|
||||
{
|
||||
ProcessType = ProcessPackagingInfo.Empty;
|
||||
UpdateProcessInfo(pid, tid, name);
|
||||
ProcessType = ProcessPackagingInspector.Inspect((int)pid);
|
||||
_isUwpAppFrameHost = string.Equals(Name, "ApplicationFrameHost.exe", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public ProcessPackagingInfo ProcessType { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Updates the process information of the <see cref="WindowProcess"/> instance.
|
||||
/// </summary>
|
||||
@@ -161,10 +156,6 @@ internal sealed class WindowProcess
|
||||
|
||||
// Process can be elevated only if process id is not 0 (Dummy value on error)
|
||||
IsFullAccessDenied = (pid != 0) ? TestProcessAccessUsingAllAccessFlag(pid) : false;
|
||||
|
||||
// Update process type
|
||||
ProcessType = ProcessPackagingInspector.Inspect((int)pid);
|
||||
_isUwpAppFrameHost = string.Equals(Name, "ApplicationFrameHost.exe", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -23,6 +23,4 @@ public interface ISettingsInterface
|
||||
public bool HideExplorerSettingInfo { get; }
|
||||
|
||||
public bool InMruOrder { get; }
|
||||
|
||||
public bool UseWindowIcon { get; }
|
||||
}
|
||||
|
||||
@@ -84,12 +84,6 @@ public static partial class NativeMethods
|
||||
[DllImport("user32.dll")]
|
||||
public static extern int SendMessageTimeout(IntPtr hWnd, uint msg, UIntPtr wParam, IntPtr lParam, int fuFlags, int uTimeout, out int lpdwResult);
|
||||
|
||||
[DllImport("user32.dll", EntryPoint = "GetClassLongPtr")]
|
||||
public static extern IntPtr GetClassLongPtr(IntPtr hWnd, int nIndex);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||
internal static extern bool DestroyIcon(IntPtr hIcon);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static extern bool CloseHandle(IntPtr hObject);
|
||||
@@ -149,41 +143,6 @@ public static class Win32Constants
|
||||
/// </summary>
|
||||
public const int SC_CLOSE = 0xF060;
|
||||
|
||||
/// <summary>
|
||||
/// Sent to a window to retrieve a handle to the large or small icon associated with a window.
|
||||
/// </summary>
|
||||
public const uint WM_GETICON = 0x007F;
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve the large icon for the window.
|
||||
/// </summary>
|
||||
public const int ICON_BIG = 1;
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve the small icon for the window.
|
||||
/// </summary>
|
||||
public const int ICON_SMALL = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve the small icon provided by the application.
|
||||
/// </summary>
|
||||
public const int ICON_SMALL2 = 2;
|
||||
|
||||
/// <summary>
|
||||
/// The function returns if the receiving thread does not respond within the timeout period.
|
||||
/// </summary>
|
||||
public const int SMTO_ABORTIFHUNG = 0x0002;
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a handle to the icon associated with the class.
|
||||
/// </summary>
|
||||
public const int GCLP_HICON = -14;
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a handle to the small icon associated with the class.
|
||||
/// </summary>
|
||||
public const int GCLP_HICONSM = -34;
|
||||
|
||||
/// <summary>
|
||||
/// RPC call succeeded
|
||||
/// </summary>
|
||||
|
||||
@@ -11,13 +11,4 @@ internal sealed record ProcessPackagingInfo(
|
||||
bool IsAppContainer,
|
||||
string? PackageFullName,
|
||||
int? LastError
|
||||
)
|
||||
{
|
||||
public static ProcessPackagingInfo Empty { get; } = new(
|
||||
Pid: 0,
|
||||
Kind: ProcessPackagingKind.Unknown,
|
||||
HasPackageIdentity: false,
|
||||
IsAppContainer: false,
|
||||
PackageFullName: null,
|
||||
LastError: null);
|
||||
}
|
||||
);
|
||||
|
||||
@@ -70,12 +70,6 @@ public class SettingsManager : JsonSettingsManager, ISettingsInterface
|
||||
Resources.windowwalker_SettingInMruOrder_Description,
|
||||
true);
|
||||
|
||||
private readonly ToggleSetting _useWindowIcon = new(
|
||||
Namespaced(nameof(UseWindowIcon)),
|
||||
Resources.windowwalker_SettingUseWindowIcon,
|
||||
Resources.windowwalker_SettingUseWindowIcon_Description,
|
||||
true);
|
||||
|
||||
public bool ResultsFromVisibleDesktopOnly => _resultsFromVisibleDesktopOnly.Value;
|
||||
|
||||
public bool SubtitleShowPid => _subtitleShowPid.Value;
|
||||
@@ -94,8 +88,6 @@ public class SettingsManager : JsonSettingsManager, ISettingsInterface
|
||||
|
||||
public bool InMruOrder => _inMruOrder.Value;
|
||||
|
||||
public bool UseWindowIcon => _useWindowIcon.Value;
|
||||
|
||||
internal static string SettingsJsonPath()
|
||||
{
|
||||
var directory = Utilities.BaseSettingsPath("Microsoft.CmdPal");
|
||||
@@ -118,7 +110,6 @@ public class SettingsManager : JsonSettingsManager, ISettingsInterface
|
||||
Settings.Add(_hideKillProcessOnElevatedProcesses);
|
||||
Settings.Add(_hideExplorerSettingInfo);
|
||||
Settings.Add(_inMruOrder);
|
||||
Settings.Add(_useWindowIcon);
|
||||
|
||||
// Load settings from file upon initialization
|
||||
LoadSettings();
|
||||
|
||||
@@ -15,6 +15,4 @@ internal sealed class Icons
|
||||
internal static IconInfo CloseWindow { get; } = new IconInfo("\uE894"); // Clear
|
||||
|
||||
internal static IconInfo Info { get; } = new IconInfo("\uE946"); // Info
|
||||
|
||||
internal static IconInfo GenericAppIcon { get; } = new("\uE737"); // Favicon
|
||||
}
|
||||
|
||||
@@ -401,23 +401,5 @@ namespace Microsoft.CmdPal.Ext.WindowWalker.Properties {
|
||||
return ResourceManager.GetString("windowwalker_SettingTagPid", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Use window icons.
|
||||
/// </summary>
|
||||
public static string windowwalker_SettingUseWindowIcon {
|
||||
get {
|
||||
return ResourceManager.GetString("windowwalker_SettingUseWindowIcon", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Show the actual window icon instead of the process icon.
|
||||
/// </summary>
|
||||
public static string windowwalker_SettingUseWindowIcon_Description {
|
||||
get {
|
||||
return ResourceManager.GetString("windowwalker_SettingUseWindowIcon_Description", resourceCulture);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,10 +235,4 @@
|
||||
<data name="windowwalker_NoResultsMessage" xml:space="preserve">
|
||||
<value>No open windows found</value>
|
||||
</data>
|
||||
<data name="windowwalker_SettingUseWindowIcon" xml:space="preserve">
|
||||
<value>Use window icons</value>
|
||||
</data>
|
||||
<data name="windowwalker_SettingUseWindowIcon_Description" xml:space="preserve">
|
||||
<value>Show the actual window icon instead of the process icon</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -64,7 +64,7 @@ public class TerminalQuery : ITerminalQuery
|
||||
public IEnumerable<TerminalPackage> GetTerminals()
|
||||
{
|
||||
var user = WindowsIdentity.GetCurrent().User;
|
||||
var localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
var localAppDataPath = Environment.GetEnvironmentVariable("LOCALAPPDATA");
|
||||
|
||||
foreach (var p in _packageManager.FindPackagesForUser(user.Value).Where(p => Packages.Contains(p.Id.Name)))
|
||||
{
|
||||
|
||||
@@ -24,14 +24,6 @@
|
||||
<ApplicationIcon>Resources\ImageResizer.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<ApplicationManifest>ImageResizerUI.dev.manifest</ApplicationManifest>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(CIBuild)'=='true'">
|
||||
<ApplicationManifest>ImageResizerUI.prod.manifest</ApplicationManifest>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Update="Properties\Resources.resx">
|
||||
<Generator>PublicResXFileCodeGenerator</Generator>
|
||||
@@ -63,14 +55,4 @@
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Ensure Resources directory and ImageResizer.png are available for dependent projects -->
|
||||
<Target Name="CopyResourcesToSharedLocation" AfterTargets="Build">
|
||||
<ItemGroup>
|
||||
<ResourceFiles Include="$(MSBuildProjectDirectory)\Resources\ImageResizer.png" />
|
||||
</ItemGroup>
|
||||
<MakeDir Directories="$(OutputPath)Resources" Condition="!Exists('$(OutputPath)Resources')" />
|
||||
<Copy SourceFiles="@(ResourceFiles)" DestinationFolder="$(OutputPath)Resources" SkipUnchangedFiles="true" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.0.0.0" name="PowerToys.ImageResizer.app" />
|
||||
<msix xmlns="urn:schemas-microsoft-com:msix.v1"
|
||||
publisher="CN=PowerToys Dev, O=PowerToys, L=Redmond, S=Washington, C=US"
|
||||
packageName="Microsoft.PowerToys.SparseApp"
|
||||
applicationId="PowerToys.ImageResizerUI" />
|
||||
</assembly>
|
||||
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.0.0.0" name="PowerToys.ImageResizer.app" />
|
||||
<msix xmlns="urn:schemas-microsoft-com:msix.v1"
|
||||
publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US"
|
||||
packageName="Microsoft.PowerToys.SparseApp"
|
||||
applicationId="PowerToys.ImageResizerUI" />
|
||||
</assembly>
|
||||
@@ -10,10 +10,10 @@
|
||||
<Setter Property="AutomationProperties.AccessibilityView" Value="Raw" />
|
||||
<Setter Property="IsTabStop" Value="False" />
|
||||
<Setter Property="MinHeight" Value="16" />
|
||||
<Setter Property="Background" Value="{ThemeResource CardBackgroundFillColorSecondaryBrush}" />
|
||||
<Setter Property="Background" Value="{ThemeResource SubtleFillColorTransparentBrush}" />
|
||||
<Setter Property="Foreground" Value="{ThemeResource TextFillColorPrimaryBrush}" />
|
||||
<Setter Property="BorderBrush" Value="{ThemeResource CardStrokeColorDefaultBrush}" />
|
||||
<Setter Property="BorderThickness" Value="{ThemeResource ButtonBorderThemeThickness}" />
|
||||
<Setter Property="BorderBrush" Value="{ThemeResource ControlStrokeColorDefaultBrush}" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="Padding" Value="4,4,4,4" />
|
||||
<Setter Property="FontWeight" Value="Normal" />
|
||||
<Setter Property="FontSize" Value="14" />
|
||||
@@ -33,7 +33,6 @@
|
||||
HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
|
||||
VerticalAlignment="{TemplateBinding VerticalAlignment}"
|
||||
Background="{TemplateBinding Background}"
|
||||
BackgroundSizing="{TemplateBinding BackgroundSizing}"
|
||||
BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}"
|
||||
CornerRadius="{TemplateBinding CornerRadius}">
|
||||
@@ -146,6 +145,7 @@
|
||||
x:Key="AccentKeyVisualStyle"
|
||||
BasedOn="{StaticResource DefaultKeyVisualStyle}"
|
||||
TargetType="local:KeyVisual">
|
||||
|
||||
<Setter Property="Background" Value="{ThemeResource AccentFillColorDefaultBrush}" />
|
||||
<Setter Property="Foreground" Value="{ThemeResource TextOnAccentFillColorPrimaryBrush}" />
|
||||
<Setter Property="BorderBrush" Value="{ThemeResource AccentControlElevationBorderBrush}" />
|
||||
@@ -161,7 +161,6 @@
|
||||
VerticalAlignment="{TemplateBinding VerticalAlignment}"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
Background="{TemplateBinding Background}"
|
||||
BackgroundSizing="{TemplateBinding BackgroundSizing}"
|
||||
BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}"
|
||||
CornerRadius="{TemplateBinding CornerRadius}">
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
HorizontalAlignment="Right"
|
||||
Click="OpenDialogButton_Click"
|
||||
Style="{StaticResource SubtleButtonStyle}">
|
||||
<StackPanel Orientation="Horizontal" Spacing="4">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<ItemsControl
|
||||
x:Name="PreviewKeysControl"
|
||||
Margin="2"
|
||||
@@ -37,12 +37,12 @@
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<controls:KeyVisual
|
||||
MinWidth="36"
|
||||
Padding="8,8,8,8"
|
||||
Padding="12,8,12,8"
|
||||
VerticalAlignment="Center"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
Content="{Binding}"
|
||||
CornerRadius="{StaticResource ControlCornerRadius}"
|
||||
FontWeight="SemiBold"
|
||||
IsTabStop="False"
|
||||
State="{Binding ElementName=LayoutRoot, Path=KeyVisualShouldShowConflict, Mode=OneWay, Converter={StaticResource BoolToKeyVisualStateConverter}, ConverterParameter=Warning}"
|
||||
Style="{StaticResource AccentKeyVisualStyle}" />
|
||||
@@ -57,28 +57,24 @@
|
||||
CornerRadius="{StaticResource ControlCornerRadius}"
|
||||
Orientation="Horizontal"
|
||||
Spacing="8">
|
||||
<controls:IsEnabledTextBlock
|
||||
VerticalAlignment="Center"
|
||||
FontFamily="Segoe Fluent Icons"
|
||||
<!--<FontIcon
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
FontSize="12"
|
||||
Text="" />
|
||||
<controls:IsEnabledTextBlock
|
||||
Glyph="" />-->
|
||||
<TextBlock
|
||||
x:Uid="ConfigureShortcutText"
|
||||
Margin="0,-1,0,0"
|
||||
VerticalAlignment="Center"
|
||||
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
|
||||
</StackPanel>
|
||||
<controls:IsEnabledTextBlock
|
||||
x:Name="EditIcon"
|
||||
Margin="0,0,4,0"
|
||||
VerticalAlignment="Center"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
AutomationProperties.Name=""
|
||||
FontFamily="{ThemeResource SymbolThemeFontFamily}"
|
||||
FontSize="12"
|
||||
FontSize="14"
|
||||
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
|
||||
Text=""
|
||||
Visibility="Collapsed" />
|
||||
Text="" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<VisualStateManager.VisualStateGroups>
|
||||
@@ -88,7 +84,6 @@
|
||||
<VisualState.Setters>
|
||||
<Setter Target="PlaceholderPanel.Visibility" Value="Collapsed" />
|
||||
<Setter Target="PreviewKeysControl.Visibility" Value="Visible" />
|
||||
<Setter Target="EditIcon.Visibility" Value="Visible" />
|
||||
</VisualState.Setters>
|
||||
</VisualState>
|
||||
</VisualStateGroup>
|
||||
|
||||
@@ -231,7 +231,7 @@
|
||||
Padding="20,16"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
Content="{Binding}"
|
||||
CornerRadius="{StaticResource OverlayCornerRadius}"
|
||||
CornerRadius="{StaticResource ControlCornerRadius}"
|
||||
FontSize="16"
|
||||
FontWeight="SemiBold"
|
||||
IsTabStop="False"
|
||||
|
||||
@@ -5173,7 +5173,7 @@ To record a specific window, enter the hotkey with the Alt key in the opposite m
|
||||
<value>Configure shortcut</value>
|
||||
</data>
|
||||
<data name="ConfigureShortcutText.Text" xml:space="preserve">
|
||||
<value>Assign shortcut</value>
|
||||
<value>Configure shortcut</value>
|
||||
</data>
|
||||
<data name="QuickAccessTitle.Title" xml:space="preserve">
|
||||
<value>Quick access</value>
|
||||
|
||||
Reference in New Issue
Block a user