Compare commits

..

21 Commits

Author SHA1 Message Date
Leilei Zhang
48df7911e4 Fix PDF generation – reset stream position 2025-06-17 12:24:20 +08:00
Leonardo Farias Bona
bdedc02ea5 [CropAndLock] theme (#38044)
## Summary of the Pull Request

Theme aware cropped windows.

## PR Checklist
- [x] **Closes:** #28348
- [ ] **Communication:** I've discussed this with core contributors
already. If work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end user facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

## Detailed Description of the Pull Request / Additional comments

Added a Theme aware implementation that was already found on other
components, the only difference is that we are dealing with multiple
windows.
It will follow the Power Toys application theme, (windows too in case
PowerToys follows the System).
I decided to change the scope of a variable to not create a second
control of croppedWindows, this may need to be taken into consideration.

## Validation Steps Performed

Using Crop (Win + Ctrl + Shift +R)
Crop one or multiple windows.
All of them have the same theme as the application.
Went to windows theme settings, change to light theme, the app changes
accordingly.

Same behavior was tested with Thumbnail (Win  + Ctrl + Shift + T)

Closing windows and changing the theme again.
2025-06-17 11:49:31 +08:00
Heiko
b2d7182dcd [RegPreview] Various improvements on how files are saved (#37628)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request

### This PR implements various fixes and improvements into
RegistryPreview for saving files:
1. Adds an unsaved file indicator in the title bar like in Notepad. (As
indicator we show the * character before the file title.)
2. The save button behaves like a "save as" button, if the file does not
exist on disk like in Notepad. (Without fix when running as non-admin
you get an access denied error message.)
3. If the app gets closed without saving and the file does not exist on
disk, then the user is now asked for the path. (Fixes crash on clicking
save button while closing the app.)
4. Failed save actions are handled now correctly on dirty closing,
opening files and all other actions that require saving the current
state. They will stop the process.
5. A fix for an incorrect enabled state of the save button after
opening, reloading and saving a file.
6. Reuse file name on save as button, if known. Otherwise use "new file"
template name like in Notepad.
7. Fix an app crash if you click the window's close button a second time
while the "Should save?" dialog is opened.
8. Added an reload dialog in case of unsaved changes.


![image](https://github.com/user-attachments/assets/9045446e-e9a3-4b81-8aa0-515b0821a969)


![image](https://github.com/user-attachments/assets/0888fbd2-851b-4101-a177-be9a3675b5ae)


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

- [x] **Closes:** #36876, #36875
- [x] **Communication:** I've discussed this with core contributors
already. If work hasn't been agreed, this work might be rejected
- [x] **Tests:** Added/updated and all pass
- [x] **Localization:** All end user facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed

Local test build.

---------

Co-authored-by: Gordon Lam (SH) <yeelam@microsoft.com>
2025-06-17 11:35:35 +08:00
Heiko
82e9d42e02 [CmdPal > Tiem & Date] Fix missing command of FallbackItem (#40048)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request

The fallback items of Time & Date plugin missing the command. This PR
add the missing copy command.

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

- [x] **Closes:** #40029
- [x] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end-user-facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
2025-06-17 00:20:47 +08:00
Jiří Polášek
74d92df078 Add 'Restart Windows Explorer' command, implemented using Restart Manager (#39258)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request
- Adds a new **"Restart Windows Explorer"** command to the **"Windows
System Commands"** provider
- Implemented using **Restart Manager** to allow restoring previously
opened Explorer windows after restart
- This depends on the *"Restore previous folder windows at logon"*
option in File Explorer Options
- An explicit timeout was added for terminating processes, since Restart
Manager uses very long timeouts 😴
- The shell process name (`explorer`) is hardcoded  
- The command attempts to terminate all `explorer` processes
indiscriminately
- Execution requires confirmation (if enabled in settings)


![image](https://github.com/user-attachments/assets/a9a955d5-a52b-4a57-bcb1-85293362c17a)


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

- [ ] **Closes:** #39213 
- [ ] **Communication:** I've discussed this with core contributors
already. If work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end user facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
2025-06-16 17:21:21 +08:00
Heiko
2255106a78 [CmdPal > Time&Date] Fix outdated result (#40050)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request

The results in Time&Date ext are cached. This leads to outdated results
and makes no sense for a time/date query.
The PR fixes this.

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

- [x] **Closes:** #39973 
- [x] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end-user-facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
2025-06-16 16:46:51 +08:00
leileizhang
2ade73834d [CmdPal]Integrate versioning into the CalculatorEngineCommon project (#40059)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request

Add a version project reference to the CalculatorEngineCommon project to
integrate versioning support.

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

- [ ] **Closes:** #xxx
- [ ] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end-user-facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
2025-06-16 15:12:17 +08:00
Gordon Lam
ecfc9e9ab2 Fix Build Warning on Host (#40027)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request
Fixed build warnings WMC1510 in `HostsMainPage.xaml` that were
preventing proper AOT (Ahead-of-Time) compilation compatibility for XAML
data bindings.
### Problem
The Hosts module was generating multiple WMC1510 warnings during build:
```
src\modules\Hosts\HostsUILib\HostsMainPage.xaml(614,13): Warning WMC1510: Ensure the property path is trimming and AOT compatible by making use of 'Compiled Bindings (x:bind)' if possible or by specifying the 'x:DataType' directive...
```

These warnings occurred on 6 different binding expressions in the
EntryDialog ContentDialog that bound to properties of the `Entry` model
class.

### Solution
Applied the recommended fix by adding proper type information for the
XAML compiler:

1. **Added `x:DataType="models:Entry"`** to the ContentDialog element to
specify the binding context type
2. **Added `[Bindable]` attribute** to the Entry model class to ensure
WinRT compatibility

### Changes Made
- **HostsMainPage.xaml**: Added `x:DataType="models:Entry"` attribute to
the EntryDialog ContentDialog
- **Entry.cs**: Added `[Bindable]` attribute and `using
Microsoft.UI.Xaml.Data;` directive

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments
-  Resolves all 6 WMC1510 warnings in the specified lines
-  Ensures AOT compilation compatibility
-  No functional changes to UI behavior
-  Minimal code changes (3 lines total)
-  Follows Microsoft's recommended approach for WinRT data binding

The fix enables proper trimming and AOT compilation while maintaining
all existing functionality.

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
Try to build and run locally without problem.
2025-06-16 14:13:16 +08:00
PesBandi
3afaa18343 [Hosts]Add learn more link to warning dialog (#39946)
## Summary of the Pull Request
Adds a *Learn more* link pointing
[here](https://aka.ms/PowerToysOverview_HostsFileEditor) (the same as in
the settings) to the warning dialog that shows up when Hosts File Editor
starts
## PR Checklist
- [x] **Closes:** #39859
- [ ] **Communication:** I've discussed this with core contributors
already. If work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [x] **Localization:** All end user facing strings can be localized
- [x] **Dev docs:** No need
- [x] **New binaries:** None
- [x] **Documentation updated:** No need
## Detailed Description of the Pull Request / Additional comments

![Image](https://github.com/user-attachments/assets/f26c4fc9-fc3f-45d1-9976-77295b524b97)
<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
Tested the UI manually
2025-06-16 14:08:29 +08:00
leileizhang
fa111538ae Fix Peek always showing warning message by updating IsWarningMessageVisible logic (#40056)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request
This PR fixes an issue where the warning message in Peek was always
displayed, even when not applicable.

**Root cause**
When non-video files were triggered, the logic did not call
`IsWarningMessageVisible(string? missingCodecName)`
as expected. As a result, the default UI state caused the warning
message to always appear.

**Fix**
Updated the method signature and call sites to:
`public Visibility IsWarningMessageVisible(IPreviewer? previewer,
PreviewState? state)`
This ensures that the logic is consistently triggered across different
preview handlers and has access to the necessary context to determine
whether the warning message should be shown.

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

- [ ] **Closes:** #xxx
- [ ] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end-user-facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
2025-06-16 13:39:56 +08:00
Yu Leng
be68bfd3ab [CmdPal][AOT] Fix fontIcon issue when build with AOT (#40058)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request
FontIcon will be trimmed, we need to create a rd.xml to keep them.

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

- [x] **Closes:** #40057
- [x] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [x] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end-user-facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed

Co-authored-by: Yu Leng <yuleng@microsoft.com>
2025-06-16 13:37:00 +08:00
leileizhang
790676844d [S360] Revert "[CmdPal][AOT] Replace CommunityToolkit.MarkdownTextBlock with CommunityToolkit.Lab.MarkdownTextBlock (#39974)" (#40055)
This reverts commit 7d257cf00c due to a
security concern involving multiple feeds

<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request

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

- [ ] **Closes:** #xxx
- [ ] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end-user-facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
2025-06-16 13:31:27 +08:00
PesBandi
64ad9b56ad [CmdPal][Apps]Add copy path command (#39984)
## Summary of the Pull Request
Adds a *Copy path* command to the <kbd>Ctrl</kbd>+<kbd>K</kbd> menu in
the All apps extension
## PR Checklist
- [x] **Closes:** #39500 (as mentioned in the discussion, the other
requests will be tracked over in #39501)
- [x] **Communication:** I've discussed this with core contributors
already + has Help wanted
- [x] **Tests:** All pass
- [x] **Localization:** All end user facing strings can be localized
- [x] **Dev docs:** No need
- [x] **New binaries:** None
- [x] **Documentation updated:** No need
## Detailed Description of the Pull Request / Additional comments
Copies the exe full path for standard programs. Copies the package
directory for UWPs.
Shows a *Copied to clipboard!* toast on a successful copy and closes.
Shows a toast when copying fails, keeps CmdPal open.

![image](https://github.com/user-attachments/assets/ad89a583-13c8-475c-973b-b0f5e7556e31)
## Validation Steps Performed
Manually tested copying for UWPs and Win32 programs
2025-06-16 12:10:50 +08:00
Yu Leng
7d257cf00c [CmdPal][AOT] Replace CommunityToolkit.MarkdownTextBlock with CommunityToolkit.Lab.MarkdownTextBlock (#39974)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request
Why?
The old library doesn't support native AOT. They implement the new one
but still in the lab project.
There are some breaking changes. So, seems we can not 100% to make it
align with the old version.

https://github.com/CommunityToolkit/Labs-Windows/tree/main/components/MarkdownTextBlock

compare:
old:

![image](https://github.com/user-attachments/assets/c2d20d1c-77b8-4bd5-a6e9-45ef30e90ea4)
new:

![image](https://github.com/user-attachments/assets/f65c1acd-ee91-491e-9efd-08ebd191dc58)

old:

![image](https://github.com/user-attachments/assets/129bee49-04c3-4667-88d8-b27718ccd51b)

![image](https://github.com/user-attachments/assets/10c6f845-13ce-4e6b-8fbf-017c8a654fa2)

![image](https://github.com/user-attachments/assets/6f95de3f-e6fb-43a8-9a81-487b20f97f23)

new:

![image](https://github.com/user-attachments/assets/f661731a-efc1-4ffd-86d1-f24cbbe3b9c3)

![image](https://github.com/user-attachments/assets/22cf3e24-f27b-4cef-8e80-352451323bb6)

![image](https://github.com/user-attachments/assets/46719831-905a-450e-b789-93bbedd418bd)

old:

![image](https://github.com/user-attachments/assets/3dd7713a-f5fa-4e1d-90a1-30a518b5df36)

new:

![image](https://github.com/user-attachments/assets/616a176f-a9aa-4f23-9f01-98b30a7c33c4)

old:

![image](https://github.com/user-attachments/assets/5758b51c-44a3-4748-9092-c827009ccc8e)

new:

![image](https://github.com/user-attachments/assets/8deed4cf-e87e-425f-b5a7-61dcab676e45)


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

- [ ] **Closes:** #xxx
- [ ] **Communication:** I've discussed this with core contributors
already. If work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end user facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed

---------

Co-authored-by: Yu Leng <yuleng@microsoft.com>
2025-06-16 08:36:45 +08:00
Clint Rutkas
106923db84 Moving chris to security org (#40038)
Chris, best of luck in security org :)
2025-06-13 21:02:59 +00:00
Davide Giacometti
6f68f5f34a [CmdPal] Fix and localize alias settings (#39708)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request

Fixes alias settings and add localization for Direct/Indirect.


![Animation](https://github.com/user-attachments/assets/64780f64-f695-4e34-9b90-828ec456c6d3)

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

- [x] **Closes:** #39569
- [ ] **Communication:** I've discussed this with core contributors
already. If work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end user facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed

Manually tested
2025-06-13 19:58:33 +02:00
Davide Giacometti
aa8cfd505a [CmdPal] Close Gracefully (#39589)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request

CmdPal is leaking extensions processes as the process is immediately
killed.
This PR fixes the 1.5s wait for the process to end correctly and also
close extensions.

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

- [ ] **Closes:** #xxx
- [ ] **Communication:** I've discussed this with core contributors
already. If work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end user facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed

- Verified that if CmdPal closes in 1.5s, extensions and process are
closed (note that GitHub extension doesn't close probably due to
https://github.com/microsoft/PowerToys/pull/39209)
- Verified that if CmdPal doesn't close in 1.5s the process is killed
and extensions aren't closed (tested adding a delay in the code)
2025-06-13 19:57:40 +02:00
Gordon Lam
349de60e47 Include all the Unittest as part of CI pipeline (#40024)
Include all the UnitTest as part of CI pipeline.

The results are promising:
a. All tests passed
b. No noticeable increase in execution time
c. Additional modules are now covered, including Settings, Color Picker,
Peek, Run V1, and others.
 
Here is all ~5000 Unittests - [Pipelines - Run PowerToys
CI_2506.12022](https://dev.azure.com/shine-oss/PowerToys/_build/results?buildId=133714&view=ms.vss-test-web.build-test-results-tab)
Here is the original ~3000 Unittests - [Pipelines - Run PowerToys
CI_2506.12021](https://dev.azure.com/shine-oss/PowerToys/_build/results?buildId=133677&view=ms.vss-test-web.build-test-results-tab)

Co-authored-by: Kai Tao <69313318+vanzue@users.noreply.github.com>
2025-06-13 08:59:25 -07:00
Heiko
abc5c3e249 [RegistryPreview] Extended preview for value data (#37689)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request

Add a button to the data grid that shows a windows for complex value
preview.

### Screenshots
**Button**

![image](https://github.com/user-attachments/assets/bb275831-be6d-490c-9193-5df719ce6c39)

**Context menu** (Usefull on long data, if button is scrolled out of
view.)

![image](https://github.com/user-attachments/assets/f5fb07ef-6f73-4eac-a289-9dce1c610ceb)

**Preview: REG_SZ**

![image](https://github.com/user-attachments/assets/e03fbbc7-adaa-40d0-967c-7783b1a97b74)

**Preview: REG_MULTI_SZ**

![image](https://github.com/user-attachments/assets/717590a6-7d91-4c9c-8e94-d875a5d2ba6b)

**Preview: REG_EXPAND_SZ**

![image](https://github.com/user-attachments/assets/20135b66-528f-40e7-beed-adfc2b50313d)

**Preview: REG_DWORD and REG_QWORD**

![image](https://github.com/user-attachments/assets/b60110ab-bfc7-40e7-ada3-d278a62b9d01)

**Preview: REG_BINARY**

![image](https://github.com/user-attachments/assets/95f81036-6833-439e-8c01-b3a45c2d8edd)

![image](https://github.com/user-attachments/assets/ce237664-da96-4dbd-835f-969982560b9f)


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

- [x] **Closes:** #36877
- [x] **Communication:** I've discussed this with core contributors
already. If work hasn't been agreed, this work might be rejected
- [x] **Tests:** Added/updated and all pass
- [x] **Localization:** All end user facing strings can be localized =>
missing yet
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

Additionally this PR updates the context menu for values.

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed

Tested code with a local build.
2025-06-13 18:08:01 +08:00
PesBandi
ce058f1dc7 [ColorPicker]Add option to choose what clicking individual mouse buttons does (#39025)
## Summary of the Pull Request
Enables the users to choose what left, right, and middle click does when
color picker is open.
<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist

- [x] **Closes:** #39006
- [x] **Communication:** I've discussed this with core contributors
already
- [x] **Tests:** All pass
- [x] **Localization:** All end user facing strings can be localized
- [x] **Dev docs:** No need
- [x] **New binaries:** None
- [x] **Documentation updated:** No need
## Detailed Description of the Pull Request / Additional comments
![Screenshot of the
settings](https://github.com/user-attachments/assets/a3e1349b-6bb9-4e2f-97f3-a5106a7d92ce)
Adds option to choose from 3 click behaviors for each standard mouse
button:
* **Pick color and open editor**: Copies color to clipboard, saves it to
the color history and opens the editor
* **Pick color and close**: Copies color to clipboard, saves it to the
color history and exits
* **Close**: Closes color picker without copying the color

Pressing <kbd>Enter</kbd> or <kbd>Space</kbd> does what clicking the
primary button would.
Left and middle click actions execute on mouse down, right click on
mouse up for reasons discussed previously (I can't find the conversation
now)
Default settings are chosen in such a way that very little or nothing
changes by updating.
## Validation Steps Performed
Tested:
* Migrating settings from v2.0 to v2.1 (v1 to v2.1 not tested)
* Settings page displays and saves settings correctly
* Default settings load correctly
* All three click actions do what they are supposed to
* Activation behavior works as expected, doesn't affect click actions
2025-06-13 18:01:40 +08:00
leileizhang
2d1676b7df [CmdPal][AOT] Using ExprTk to make the Cal extension AOT-compatible (#39972)
<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request
This PR replaces the original Mages-based expression evaluation engine
with a WinRT-wrapped version of Exprtk in the CmdPalCalculator module.

### Key Changes
**Expression Engine:**

- All expression parsing and evaluation now use Exprtk (via a WinRT
wrapper) instead of Mages.

**Base Conversion Handling:**

- Since Exprtk does not support non-decimal (binary, octal, hexadecimal)
input natively, added logic to convert all such inputs to decimal before
evaluation.

**Code Structure:**

- The overall logic and API surface remain unchanged except for the
engine and base conversion handling.
- All previous Mages references and dependencies have been removed.

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

- [ ] **Closes:** #xxx
- [ ] **Communication:** I've discussed this with core contributors
already. If work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end user facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
2025-06-13 12:27:53 +08:00
84 changed files with 5650 additions and 215 deletions

View File

@@ -91,6 +91,7 @@ Hemmerlein
hlaueriksson
Horvalds
Howett
hotkidfamily
htcfreek
Huynh
Ionut
@@ -98,6 +99,7 @@ jamrobot
Jaswal
Jaylyn
jefflord
Jeremic
Jordi
jyuwono
kai
@@ -222,6 +224,7 @@ openai
Quickime
regedit
roslyn
Skia
Spotify
Vanara
wangyi

View File

@@ -126,3 +126,4 @@
^src/common/sysinternals/Eula/
^tools/Verification scripts/Check preview handler registration\.ps1$
ignore$
^src/modules/registrypreview/RegistryPreviewUILib/Controls/HexBox/.*$

View File

@@ -910,6 +910,7 @@ metafile
mfc
Mgmt
Microwaved
middleclickaction
midl
mii
mindaro
@@ -1251,6 +1252,7 @@ prg
prgh
prgms
pri
primaryclickaction
PRINTCLIENT
printmanagement
prm
@@ -1426,6 +1428,7 @@ SDKDDK
sdns
searchterm
SEARCHUI
secondaryclickaction
SECONDARYDISPLAY
secpol
securestring
@@ -1510,6 +1513,7 @@ SICHINT
SIDs
siex
sigdn
Signedness
SIGNINGSCENARIO
signtool
SINGLEKEY
@@ -1659,6 +1663,7 @@ TDefault
TDevice
telephon
templatenamespace
TESTONLY
testprocess
TEXCOORD
TEXTBOXNEWLINE
@@ -1711,6 +1716,7 @@ trx
tsa
TSender
TServer
tskill
tstoi
TStr
tweakme

View File

@@ -41,6 +41,9 @@ Write-Output ""
Write-Output "Restoring dotnet tools..."
dotnet tool restore --disable-parallel --no-cache
# Use Regex syntax
$PathExcludes = "(\\obj\\)|(\\bin\\)|(\\x64\\)|(\\Generated Files\\PowerRenameXAML\\)|(\\RegistryPreviewUILib\\Controls\\HexBox\\)"
if (-not $Passive)
{
# Look for unstaged changed files by default
@@ -87,7 +90,7 @@ if (-not $Passive)
}
Write-Output "Running Git Diff: $gitDiffCommand"
$files = Invoke-Expression $gitDiffCommand | Select-String -Pattern "\.xaml$"
$files = Invoke-Expression $gitDiffCommand | Select-String -Pattern "\.xaml$" | Where-Object { $_ -notmatch $PathExcludes }
if (-not $Passive -and -not $Main -and -not $Unstaged -and -not $Staged -and -not $LastCommit)
{
@@ -107,7 +110,7 @@ if (-not $Passive)
else
{
Write-Output "Checking all files (passively)"
$files = Get-ChildItem -Path "$PSScriptRoot\..\src\*.xaml" -Recurse | Select-Object -ExpandProperty FullName | Where-Object { $_ -notmatch "(\\obj\\)|(\\bin\\)|(\\x64\\)|(\\Generated Files\\PowerRenameXAML\\)" }
$files = Get-ChildItem -Path "$PSScriptRoot\..\src\*.xaml" -Recurse | Select-Object -ExpandProperty FullName | Where-Object { $_ -notmatch $PathExcludes }
if ($files.count -gt 0)
{

View File

@@ -394,10 +394,7 @@ jobs:
testAssemblyVer2: |
**\KeyboardManagerEngineTest.dll
**\KeyboardManagerEditorTest.dll
**\UnitTests-CommonLib.dll
**\PowerRenameUnitTests.dll
**\UnitTests-FancyZones.dll
**\\WorkspacesLibUnitTests.dll
**\*UnitTest*.dll
!**\obj\**
- pwsh: |-

View File

@@ -28,6 +28,8 @@ $versionExceptions = @(
"ObjectModelCsProjection.dll",
"RendererCsProjection.dll") -join '|';
$nullVersionExceptions = @(
"SkiaSharp.Views.WinUI.Native.dll",
"libSkiaSharp.dll",
"codicon.ttf",
"e_sqlite3.dll",
"getfilesiginforedist.dll",

View File

@@ -181,7 +181,6 @@ ZoomIt source code was originally implemented by [Sysinternals](https://sysinter
## PowerToys core team
- [@cinnamon-msft](https://github.com/cinnamon-msft) - Kayla Cinnamon - Lead
- [@nguyen-dows](https://github.com/nguyen-dows) - Christopher Nguyen - Product Manager
- [@craigloewen-msft](https://github.com/craigloewen-msft) - Craig Loewen - Product Manager
- [@niels9001](https://github.com/niels9001/) - Niels Laute - Product Manager
- [@dhowett](https://github.com/dhowett) - Dustin Howett - Dev lead
@@ -213,6 +212,7 @@ ZoomIt source code was originally implemented by [Sysinternals](https://sysinter
- [@ethanfangg](https://github.com/ethanfangg) - Ethan Fang - Product Manager
- [@plante-msft](https://github.com/plante-msft) - Connor Plante - Product Manager
- [@joadoumie](https://github.com/joadoumie) - Jordi Adoumie - Product Manager
- [@nguyen-dows](https://github.com/nguyen-dows) - Christopher Nguyen - Product Manager
- [@enricogior](https://github.com/enricogior) - Enrico Giordani - Dev Lead
- [@bzoz](https://github.com/bzoz) - Bartosz Sosnowski - Dev
- [@ivan100sic](https://github.com/ivan100sic) - Ivan Stošić - Dev

View File

@@ -69,6 +69,8 @@
<PackageVersion Include="ReverseMarkdown" Version="4.1.0" />
<PackageVersion Include="ScipBe.Common.Office.OneNote" Version="3.0.1" />
<PackageVersion Include="SharpCompress" Version="0.37.2" />
<!-- Don't update SkiaSharp.Views.WinUI to version 3.* branch as this brakes the HexBox control in Registry Preview. -->
<PackageVersion Include="SkiaSharp.Views.WinUI" Version="2.88.9" />
<PackageVersion Include="StreamJsonRpc" Version="2.21.69" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
<!-- Package System.CodeDom added as a hack for being able to exclude the runtime assets so they don't conflict with 8.0.1. This is a dependency of System.Management but the 8.0.1 version wasn't published to nuget. -->

View File

@@ -1427,6 +1427,37 @@ EXHIBIT A -Mozilla Public License.
## Utility: Registry Preview
### HexBox.WinUI
We use HexBox.WinUI to show a preview of binary values.
**Source**: https://github.com/hotkidfamily/HexBox.WinUI
```
MIT License
Copyright (c) 2019 Filip Jeremic
Copyright (c) 2024~2025 hotkidfamily@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
### Monaco Editor
**Source**: https://github.com/Microsoft/monaco-editor
@@ -1457,6 +1488,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## NuGet Packages used by PowerToys
- AdaptiveCards.ObjectModel.WinUI3 2.0.0-beta
@@ -1517,6 +1549,7 @@ SOFTWARE.
- ReverseMarkdown 4.1.0
- ScipBe.Common.Office.OneNote 3.0.1
- SharpCompress 0.37.2
- SkiaSharp.Views.WinUI 2.88.9
- StreamJsonRpc 2.21.69
- StyleCop.Analyzers 1.2.0-beta.556
- System.CodeDom 9.0.6

View File

@@ -76,3 +76,47 @@ using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "MVVMTK0049:Using [INotifyPropertyChanged] is not AOT compatible for WinRT", Justification = "Updated MVVM toolkit package introduced this.", Scope = "namespaceanddescendants", Target = "Peek.FilePreviewer")]
[assembly: SuppressMessage("CommunityToolkit.Mvvm.SourceGenerators.INotifyPropertyChangedGenerator", "MVVMTK0049:Using [INotifyPropertyChanged] is not AOT compatible for WinRT", Justification = "Updated MVVM toolkit package introduced this.", Scope = "type", Target = "~T:Peek.UI.Views.TitleBar")]
[assembly: SuppressMessage("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "MVVMTK0049:Using [INotifyPropertyChanged] is not AOT compatible for WinRT", Justification = "Updated MVVM toolkit package introduced this.", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib")]
// HexBox control in RegistryPreviewUILib (We decided to copy the original code and not fix all theses problems for easier updating.)
[assembly: SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("Design", "CA1051:Do not declare visible instance fields", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("Globalization", "CA1305:Specify IFormatProvider", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("Naming", "CA1720:Identifiers should not contain type names", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("Performance", "CA1805:Do not initialize unnecessarily", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1623:Property summary documentation should match accessors", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1642:Constructor summary documentation should begin with standard text", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1648:<inheritdoc> has been used on an element that doesn't inherit from a base class or implement an interface.", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1649:File name should match first type name", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1500:Braces for multi-line statements should not share line", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1502:Element should not be on a single line", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1503:Braces should not be omitted", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1505:Opening braces should not be followed by blank line", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1507:Code should not contain multiple blank lines in a row", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1508:Closing braces should not be preceded by blank line", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1509:Opening braces should not be preceded by blank line", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1512:Single-line comments should not be followed by blank line", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1513:Closing brace should be followed by blank line", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1514:Element documentation header should be preceded by blank line", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1515:Single-line comment should be preceded by blank line", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1516:Elements should be separated by blank line", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1119:Statement should not use unnecessary parenthesis", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1407:Arithmetic expressions should declare precedence", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1413:Use trailing comma in multi-line initializers", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:Element should begin with upper-case letter", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:Field names should begin with lower-case letter", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.NamingRules", "SA1312:Variable names should begin with lower-case letter", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.NamingRules", "SA1313:Parameter names should begin with lower-case letter", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1200:Using directives should be placed correctly", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1108:Block statements should not contain embedded comments", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1116:Split parameters should start on line after declaration", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1117:Parameters should be on same line or separate lines", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1129:Do not use default value type constructor", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1000:Keywords should be spaced correctly", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1003:Symbols should be spaced correctly", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1005:Single line comments should begin with single space", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1024:Colons Should Be Spaced Correctly", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1025:Code should not contain multiple whitespace in a row", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1028:Code should not contain trailing whitespace", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]
[assembly: SuppressMessage("Usage", "CsWinRT1028:Class is not marked partial", Justification = "<Code port with style preservation>", Scope = "namespaceanddescendants", Target = "RegistryPreviewUILib.HexBox")]

View File

@@ -0,0 +1,36 @@
#include <windows.h>
#include "resource.h"
#include "../version/version.h"
1 VERSIONINFO
FILEVERSION FILE_VERSION
PRODUCTVERSION PRODUCT_VERSION
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
#ifdef _DEBUG
FILEFLAGS VS_FF_DEBUG
#else
FILEFLAGS 0x0L
#endif
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_DLL
FILESUBTYPE VFT2_UNKNOWN
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0" // US English (0x0409), Unicode (0x04B0) charset
BEGIN
VALUE "CompanyName", COMPANY_NAME
VALUE "FileDescription", FILE_DESCRIPTION
VALUE "FileVersion", FILE_VERSION_STRING
VALUE "InternalName", INTERNAL_NAME
VALUE "LegalCopyright", COPYRIGHT_NOTE
VALUE "OriginalFilename", ORIGINAL_FILENAME
VALUE "ProductName", PRODUCT_NAME
VALUE "ProductVersion", PRODUCT_VERSION_STRING
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200 // US English (0x0409), Unicode (1200) charset
END
END

View File

@@ -98,6 +98,11 @@
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ProjectReference Include="..\version\version.vcxproj">
<Project>{cc6e41ac-8174-4e8a-8d22-85dd7f4851df}</Project>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<ClInclude Include="ExprtkEvaluator.h" />
<ClInclude Include="pch.h" />
@@ -105,6 +110,7 @@
<ClInclude Include="Calculator.h">
<DependentUpon>Calculator.idl</DependentUpon>
</ClInclude>
<ClInclude Include="resource.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="ExprtkEvaluator.cpp">
@@ -128,6 +134,9 @@
<ItemGroup>
<None Include="PropertySheet.props" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="CalculatorEngineCommon.rc" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<Import Project="..\..\..\deps\spdlog.props" />
<ImportGroup Label="ExtensionTargets">

View File

@@ -0,0 +1,13 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by CalculatorEngineCommon.rc
//////////////////////////////
// Non-localizable
#define FILE_DESCRIPTION "CalculatorEngineCommon"
#define INTERNAL_NAME "CalculatorEngineCommon"
#define ORIGINAL_FILENAME "CalculatorEngineCommon.dll"
// Non-localizable
//////////////////////////////

View File

@@ -154,6 +154,9 @@
<ProjectReference Include="..\..\..\common\Telemetry\EtwTrace\EtwTrace.vcxproj">
<Project>{8f021b46-362b-485c-bfba-ccf83e820cbd}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\common\Themes\Themes.vcxproj">
<Project>{98537082-0fdb-40de-abd8-0dc5a4269bab}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<Import Project="..\..\..\..\deps\spdlog.props" />

View File

@@ -17,6 +17,9 @@
#include <common/Telemetry/EtwTrace/EtwTrace.h>
#include <common/Themes/theme_helpers.h>
#include <common/Themes/theme_listener.h>
#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
namespace winrt
@@ -35,6 +38,23 @@ namespace util
const std::wstring instanceMutexName = L"Local\\PowerToys_CropAndLock_InstanceMutex";
bool m_running = true;
// Theming
ThemeListener theme_listener{};
// Keep a list of our cropped windows
std::vector<std::shared_ptr<CropAndLockWindow>> croppedWindows;
void handleTheme()
{
auto theme = theme_listener.AppTheme;
auto isDark = theme == Theme::Dark;
Logger::info(L"Theme is now {}", isDark ? L"Dark" : L"Light");
for (auto&& croppedWindow : croppedWindows)
{
ThemeHelpers::SetImmersiveDarkMode(croppedWindow->Handle(), isDark);
}
}
int WINAPI wWinMain(_In_ HINSTANCE, _In_opt_ HINSTANCE, _In_ PWSTR lpCmdLine, _In_ int)
{
// Initialize COM
@@ -42,6 +62,8 @@ int WINAPI wWinMain(_In_ HINSTANCE, _In_opt_ HINSTANCE, _In_ PWSTR lpCmdLine, _I
Trace::CropAndLock::RegisterProvider();
theme_listener.AddChangedHandler(handleTheme);
Shared::Trace::ETWTrace trace;
trace.UpdateState(true);
@@ -107,8 +129,6 @@ int WINAPI wWinMain(_In_ HINSTANCE, _In_opt_ HINSTANCE, _In_ PWSTR lpCmdLine, _I
// Create our overlay window
std::unique_ptr<OverlayWindow> overlayWindow;
// Keep a list of our cropped windows
std::vector<std::shared_ptr<CropAndLockWindow>> croppedWindows;
// Handles and thread for the events sent from runner
HANDLE m_reparent_event_handle;
@@ -167,6 +187,7 @@ int WINAPI wWinMain(_In_ HINSTANCE, _In_opt_ HINSTANCE, _In_ PWSTR lpCmdLine, _I
croppedWindow->CropAndLock(targetWindow, cropRect);
croppedWindow->OnClosed(removeWindowCallback);
croppedWindows.push_back(croppedWindow);
handleTheme();
};
overlayWindow.reset();

View File

@@ -6,6 +6,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<DefineConstants>TESTONLY</DefineConstants>
</PropertyGroup>
<PropertyGroup>

View File

@@ -611,6 +611,7 @@
<ContentDialog
x:Name="EntryDialog"
x:Uid="EntryDialog"
x:DataType="models:Entry"
IsPrimaryButtonEnabled="{Binding Valid, Mode=OneWay}"
Loaded="ContentDialog_Loaded_ApplyMargin"
PrimaryButtonStyle="{StaticResource AccentButtonStyle}">

View File

@@ -139,10 +139,23 @@ namespace HostsUILib.Views
dialog.XamlRoot = XamlRoot;
dialog.Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style;
dialog.Title = resourceLoader.GetString("WarningDialog_Title");
dialog.Content = new TextBlock
dialog.Content = new StackPanel
{
Text = resourceLoader.GetString("WarningDialog_Text"),
TextWrapping = TextWrapping.Wrap,
Children =
{
new TextBlock
{
Text = resourceLoader.GetString("WarningDialog_Text"),
TextWrapping = TextWrapping.Wrap,
},
new HyperlinkButton
{
Content = resourceLoader.GetString("WarningDialog_LearnMore"),
NavigateUri = new Uri("https://aka.ms/PowerToysOverview_HostsFileEditor"),
Padding = new Thickness(0),
Margin = new Thickness(0, 5, 0, 5),
},
},
};
dialog.PrimaryButtonText = resourceLoader.GetString("WarningDialog_AcceptBtn");
dialog.PrimaryButtonStyle = Application.Current.Resources["AccentButtonStyle"] as Style;

View File

@@ -11,6 +11,9 @@ using HostsUILib.Helpers;
namespace HostsUILib.Models
{
#if !TESTONLY
[Microsoft.UI.Xaml.Data.Bindable]
#endif
public partial class Entry : ObservableObject
{
private static readonly char[] _spaceCharacters = new char[] { ' ', '\t' };

View File

@@ -331,6 +331,9 @@
<data name="WarningDialog_Title" xml:space="preserve">
<value>Warning</value>
</data>
<data name="WarningDialog_LearnMore" xml:space="preserve">
<value>Learn more</value>
</data>
<data name="WindowAdminTitle" xml:space="preserve">
<value>Administrator: Hosts File Editor</value>
<comment>Title of the window when running as administrator. "Hosts File Editor" is the name of the utility. "Hosts" refers to the system hosts file, do not loc</comment>

View File

@@ -117,16 +117,18 @@ private:
for (DWORD pid : processIds)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
HANDLE hProcess = OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE, FALSE, pid);
if (hProcess != NULL)
{
SetEvent(m_hTerminateEvent);
// Wait for 1.5 seconds for the process to end correctly and stop etw tracer
WaitForSingleObject(hProcess, 1500);
// Wait for 1.5 seconds for the process to end correctly, allowing time for ETW tracer and extensions to stop
if (WaitForSingleObject(hProcess, 1500) == WAIT_TIMEOUT)
{
TerminateProcess(hProcess, 0);
}
TerminateProcess(hProcess, 0);
CloseHandle(hProcess);
}
}

View File

@@ -102,6 +102,8 @@ public sealed partial class TopLevelViewModel : ObservableObject, IListItem
}
HandleChangeAlias();
OnPropertyChanged(nameof(AliasText));
OnPropertyChanged(nameof(IsDirectAlias));
}
}
@@ -116,6 +118,7 @@ public sealed partial class TopLevelViewModel : ObservableObject, IListItem
}
HandleChangeAlias();
OnPropertyChanged(nameof(IsDirectAlias));
}
}

View File

@@ -67,6 +67,7 @@ public partial class App : Application
"Local\\PowerToysCmdPal-ExitEvent-eb73f6be-3f22-4b36-aee3-62924ba40bfd", () =>
{
EtwTrace?.Dispose();
AppWindow?.Close();
Environment.Exit(0);
});
}

View File

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

View File

@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="utf-8" ?>
<Page
x:Class="Microsoft.CmdPal.UI.Settings.ExtensionPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
@@ -92,12 +92,11 @@
<controls:SettingsCard x:Uid="Settings_ExtensionPage_Alias_SettingsCard" HeaderIcon="{ui:FontIcon Glyph=&#xE8AC;}">
<StackPanel Orientation="Vertical">
<TextBox Text="{x:Bind AliasText, Mode=TwoWay}" />
<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}"
OffContent="Indirect"
OnContent="Direct" />
IsOn="{x:Bind IsDirectAlias, Mode=TwoWay}" />
</StackPanel>
</controls:SettingsCard>

View File

@@ -418,4 +418,10 @@ Right-click to remove the key combination, thereby deactivating the shortcut.</v
<data name="TrayMenu_Exit" xml:space="preserve">
<value>Exit</value>
</data>
<data name="Settings_ExtensionPage_Alias_ToggleSwitch.OnContent" xml:space="preserve">
<value>Direct</value>
</data>
<data name="Settings_ExtensionPage_Alias_ToggleSwitch.OffContent" xml:space="preserve">
<value>Indirect</value>
</data>
</root>

View File

@@ -0,0 +1,7 @@
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
<Application>
<Assembly Name="Microsoft.WinUI">
<Type Name="Microsoft.UI.Xaml.Controls.FontIconSource" Dynamic="Required All" />
</Assembly>
</Application>
</Directives>

View File

@@ -0,0 +1,49 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.Text;
using ManagedCommon;
using Microsoft.CmdPal.Ext.Apps.Properties;
using Microsoft.CommandPalette.Extensions.Toolkit;
namespace Microsoft.CmdPal.Ext.Apps.Commands;
internal sealed partial class CopyPathCommand : InvokableCommand
{
private static readonly IconInfo TheIcon = new("\ue8c8");
private readonly string _target;
public CopyPathCommand(string target)
{
Name = Resources.copy_path;
Icon = TheIcon;
_target = target;
}
private static readonly CompositeFormat CopyFailedFormat = CompositeFormat.Parse(Resources.copy_failed);
public override CommandResult Invoke()
{
try
{
ClipboardHelper.SetText(_target);
}
catch (Exception ex)
{
Logger.LogError("Copy failed: " + ex.Message);
return CommandResult.ShowToast(
new ToastArgs
{
Message = string.Format(CultureInfo.CurrentCulture, CopyFailedFormat, ex.Message),
Result = CommandResult.KeepOpen(),
});
}
return CommandResult.ShowToast(Resources.copied_to_clipboard);
}
}

View File

@@ -85,6 +85,10 @@ public class UWPApplication : IProgram
// We don't add context menu to 'run as different user', because UWP applications normally installed per user and not for all users.
}
commands.Add(
new CommandContextItem(
new CopyPathCommand(Location)));
commands.Add(
new CommandContextItem(
new OpenPathCommand(Location)

View File

@@ -198,6 +198,9 @@ public class Win32Program : IProgram
new RunAsUserCommand(!string.IsNullOrEmpty(LnkFilePath) ? LnkFilePath : FullPath, ParentDirectory)));
}
commands.Add(new CommandContextItem(
new CopyPathCommand(FullPath)));
commands.Add(new CommandContextItem(
new OpenPathCommand(ParentDirectory)));

View File

@@ -78,6 +78,33 @@ namespace Microsoft.CmdPal.Ext.Apps.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to Copied to clipboard!.
/// </summary>
internal static string copied_to_clipboard {
get {
return ResourceManager.GetString("copied_to_clipboard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copy failed ({0}). Please try again..
/// </summary>
internal static string copy_failed {
get {
return ResourceManager.GetString("copy_failed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copy path.
/// </summary>
internal static string copy_path {
get {
return ResourceManager.GetString("copy_path", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Include apps found on the desktop.
/// </summary>

View File

@@ -163,12 +163,22 @@
<data name="open_location" xml:space="preserve">
<value>Open location</value>
</data>
<data name="copy_path" xml:space="preserve">
<value>Copy path</value>
</data>
<data name="run_as_administrator" xml:space="preserve">
<value>Run as administrator</value>
</data>
<data name="run_as_different_user" xml:space="preserve">
<value>Run as different user</value>
</data>
<data name="copy_failed" xml:space="preserve">
<value>Copy failed ({0}). Please try again.</value>
<comment>{0} is the error message</comment>
</data>
<data name="copied_to_clipboard" xml:space="preserve">
<value>Copied to clipboard!</value>
</data>
<data name="enable_start_menu_source" xml:space="preserve">
<value>Include apps found in the Start Menu</value>
</data>

View File

@@ -110,6 +110,13 @@ internal static class Commands
});
}
results.Add(new ListItem(new ExecuteCommandConfirmation(Resources.Microsoft_plugin_sys_RestartShell_name!, confirmCommands, Resources.Microsoft_plugin_sys_RestartShell_confirmation!, static () => OpenInShellHelper.OpenInShell("cmd", "/C tskill explorer && start explorer", runWithHiddenWindow: true)))
{
Title = Resources.Microsoft_plugin_sys_RestartShell!,
Subtitle = Resources.Microsoft_plugin_sys_RestartShell_description!,
Icon = Icons.RestartShellIcon,
});
// UEFI command/result. It is only available on systems booted in UEFI mode.
if (isUefi)
{

View File

@@ -20,6 +20,8 @@ public static partial class Icons
public static IconInfo RestartIcon { get; } = new IconInfo("\uE777");
public static IconInfo RestartShellIcon { get; } = new IconInfo("\uEC50");
public static IconInfo ShutdownIcon { get; } = new IconInfo("\uE7E8");
public static IconInfo SleepIcon { get; } = new IconInfo("\uE708");

View File

@@ -645,6 +645,42 @@ namespace Microsoft.CmdPal.Ext.System {
}
}
/// <summary>
/// Looks up a localized string similar to Restart Windows Explorer.
/// </summary>
public static string Microsoft_plugin_sys_RestartShell {
get {
return ResourceManager.GetString("Microsoft_plugin_sys_RestartShell", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You are about to restart Windows Explorer, are you sure?.
/// </summary>
public static string Microsoft_plugin_sys_RestartShell_confirmation {
get {
return ResourceManager.GetString("Microsoft_plugin_sys_RestartShell_confirmation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to End and restart the Windows Explorer shell process.
/// </summary>
public static string Microsoft_plugin_sys_RestartShell_description {
get {
return ResourceManager.GetString("Microsoft_plugin_sys_RestartShell_description", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Restart.
/// </summary>
public static string Microsoft_plugin_sys_RestartShell_name {
get {
return ResourceManager.GetString("Microsoft_plugin_sys_RestartShell_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ip; mac; address.
/// </summary>

View File

@@ -417,4 +417,16 @@
<data name="Microsoft_plugin_ext_fallback_display_title" xml:space="preserve">
<value>Open System Command</value>
</data>
<data name="Microsoft_plugin_sys_RestartShell" xml:space="preserve">
<value>Restart Windows Explorer</value>
</data>
<data name="Microsoft_plugin_sys_RestartShell_description" xml:space="preserve">
<value>End and restart the Windows Explorer shell process</value>
</data>
<data name="Microsoft_plugin_sys_RestartShell_name" xml:space="preserve">
<value>Restart</value>
</data>
<data name="Microsoft_plugin_sys_RestartShell_confirmation" xml:space="preserve">
<value>You are about to restart Windows Explorer, are you sure?</value>
</data>
</root>

View File

@@ -68,6 +68,7 @@ internal sealed partial class FallbackTimeDateItem : FallbackCommandItem
Title = result.Title;
Subtitle = result.Subtitle;
Icon = result.Icon;
Command = result.Command;
}
else
{

View File

@@ -18,8 +18,6 @@ internal sealed partial class TimeDateExtensionPage : DynamicListPage
private IList<ListItem> _results = new List<ListItem>();
private bool initialized;
private SettingsManager _settingsManager;
public TimeDateExtensionPage(SettingsManager settingsManager)
@@ -35,12 +33,9 @@ internal sealed partial class TimeDateExtensionPage : DynamicListPage
public override IListItem[] GetItems()
{
if (!initialized)
{
DoExecuteSearch(string.Empty);
}
DoExecuteSearch(string.Empty);
lock (_resultsLock)
lock (_resultsLock)
{
ListItem[] results = _results.ToArray();
return results;
@@ -49,11 +44,6 @@ internal sealed partial class TimeDateExtensionPage : DynamicListPage
public override void UpdateSearchText(string oldSearch, string newSearch)
{
if (newSearch == oldSearch)
{
return;
}
DoExecuteSearch(newSearch);
}
@@ -84,7 +74,6 @@ internal sealed partial class TimeDateExtensionPage : DynamicListPage
{
lock (_resultsLock)
{
initialized = true;
this._results = result;
}

View File

@@ -107,21 +107,14 @@ namespace ColorPicker.Helpers
}
}
public void OnColorPickerMouseDown()
public void OpenColorEditor()
{
if (_userSettings.ActivationAction.Value == ColorPickerActivationAction.OpenColorPickerAndThenEditor || _userSettings.ActivationAction.Value == ColorPickerActivationAction.OpenEditor)
lock (_colorPickerVisibilityLock)
{
lock (_colorPickerVisibilityLock)
{
HideColorPicker();
}
HideColorPicker();
}
ShowColorPickerEditor();
}
else
{
EndUserSession();
}
ShowColorPickerEditor();
}
public static void SetTopMost()

View File

@@ -16,10 +16,12 @@ namespace ColorPicker.Mouse
// position and bool indicating zoom in or zoom out
event EventHandler<Tuple<System.Windows.Point, bool>> OnMouseWheel;
event MouseUpEventHandler OnMouseDown;
event PrimaryMouseDownEventHandler OnPrimaryMouseDown;
event SecondaryMouseUpEventHandler OnSecondaryMouseUp;
event MiddleMouseDownEventHandler OnMiddleMouseDown;
System.Windows.Point CurrentPosition { get; }
Color CurrentColor { get; }

View File

@@ -7,17 +7,18 @@ using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Input;
using ColorPicker.Helpers;
using ManagedCommon;
using static ColorPicker.NativeMethods;
namespace ColorPicker.Mouse
{
public delegate void MouseUpEventHandler(object sender, System.Drawing.Point p);
public delegate void PrimaryMouseDownEventHandler(object sender, IntPtr wParam);
public delegate void SecondaryMouseUpEventHandler(object sender, IntPtr wParam);
public delegate void MiddleMouseDownEventHandler(object sender, IntPtr wParam);
internal class MouseHook
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:Field names should not contain underscore", Justification = "Interop object")]
@@ -30,23 +31,25 @@ namespace ColorPicker.Mouse
private const int WM_RBUTTONUP = 0x0205;
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:Field names should not contain underscore", Justification = "Interop object")]
private const int WM_RBUTTONDOWN = 0x0204;
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:Field names should not contain underscore", Justification = "Interop object")]
private const int WM_MBUTTONDOWN = 0x0207;
private IntPtr _mouseHookHandle;
private HookProc _mouseDelegate;
private event MouseUpEventHandler MouseDown;
private event PrimaryMouseDownEventHandler PrimaryMouseDown;
public event MouseUpEventHandler OnMouseDown
public event PrimaryMouseDownEventHandler OnPrimaryMouseDown
{
add
{
Subscribe();
MouseDown += value;
PrimaryMouseDown += value;
}
remove
{
MouseDown -= value;
PrimaryMouseDown -= value;
Unsubscribe();
}
}
@@ -68,6 +71,23 @@ namespace ColorPicker.Mouse
}
}
private event MiddleMouseDownEventHandler MiddleMouseDown;
public event MiddleMouseDownEventHandler OnMiddleMouseDown
{
add
{
Subscribe();
MiddleMouseDown += value;
}
remove
{
MiddleMouseDown -= value;
Unsubscribe();
}
}
private event MouseWheelEventHandler MouseWheel;
public event MouseWheelEventHandler OnMouseWheel
@@ -126,9 +146,9 @@ namespace ColorPicker.Mouse
MSLLHOOKSTRUCT mouseHookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
if (wParam.ToInt32() == WM_LBUTTONDOWN)
{
if (MouseDown != null)
if (PrimaryMouseDown != null)
{
MouseDown.Invoke(null, new System.Drawing.Point(mouseHookStruct.pt.x, mouseHookStruct.pt.y));
PrimaryMouseDown.Invoke(null, wParam);
}
return new IntPtr(-1);
@@ -150,6 +170,16 @@ namespace ColorPicker.Mouse
return new IntPtr(-1);
}
if (wParam.ToInt32() == WM_MBUTTONDOWN)
{
if (MiddleMouseDown != null)
{
MiddleMouseDown.Invoke(null, wParam);
}
return new IntPtr(-1);
}
if (wParam.ToInt32() == WM_MOUSEWHEEL)
{
if (MouseWheel != null)

View File

@@ -56,10 +56,12 @@ namespace ColorPicker.Mouse
public event EventHandler<Tuple<System.Windows.Point, bool>> OnMouseWheel;
public event MouseUpEventHandler OnMouseDown;
public event PrimaryMouseDownEventHandler OnPrimaryMouseDown;
public event SecondaryMouseUpEventHandler OnSecondaryMouseUp;
public event MiddleMouseDownEventHandler OnMiddleMouseDown;
public System.Windows.Point CurrentPosition
{
get
@@ -148,9 +150,10 @@ namespace ColorPicker.Mouse
_timer.Start();
}
_mouseHook.OnMouseDown += MouseHook_OnMouseDown;
_mouseHook.OnPrimaryMouseDown += MouseHook_OnPrimaryMouseDown;
_mouseHook.OnMouseWheel += MouseHook_OnMouseWheel;
_mouseHook.OnSecondaryMouseUp += MouseHook_OnSecondaryMouseUp;
_mouseHook.OnMiddleMouseDown += MouseHook_OnMiddleMouseDown;
if (_userSettings.ChangeCursor.Value)
{
@@ -169,10 +172,10 @@ namespace ColorPicker.Mouse
OnMouseWheel?.Invoke(this, new Tuple<System.Windows.Point, bool>(_previousMousePosition, zoomIn));
}
private void MouseHook_OnMouseDown(object sender, Point p)
private void MouseHook_OnPrimaryMouseDown(object sender, IntPtr wParam)
{
DisposeHook();
OnMouseDown?.Invoke(this, p);
OnPrimaryMouseDown?.Invoke(this, wParam);
}
private void MouseHook_OnSecondaryMouseUp(object sender, IntPtr wParam)
@@ -181,6 +184,12 @@ namespace ColorPicker.Mouse
OnSecondaryMouseUp?.Invoke(this, wParam);
}
private void MouseHook_OnMiddleMouseDown(object sender, IntPtr wParam)
{
DisposeHook();
OnMiddleMouseDown?.Invoke(this, wParam);
}
private void CopiedColorRepresentation_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
_colorFormatChanged = true;
@@ -194,9 +203,10 @@ namespace ColorPicker.Mouse
}
_previousMousePosition = new System.Windows.Point(-1, 1);
_mouseHook.OnMouseDown -= MouseHook_OnMouseDown;
_mouseHook.OnPrimaryMouseDown -= MouseHook_OnPrimaryMouseDown;
_mouseHook.OnMouseWheel -= MouseHook_OnMouseWheel;
_mouseHook.OnSecondaryMouseUp -= MouseHook_OnSecondaryMouseUp;
_mouseHook.OnMiddleMouseDown -= MouseHook_OnMiddleMouseDown;
if (_userSettings.ChangeCursor.Value)
{

View File

@@ -21,6 +21,12 @@ namespace ColorPicker.Settings
SettingItem<ColorPickerActivationAction> ActivationAction { get; }
SettingItem<ColorPickerClickAction> PrimaryClickAction { get; }
SettingItem<ColorPickerClickAction> MiddleClickAction { get; }
SettingItem<ColorPickerClickAction> SecondaryClickAction { get; }
RangeObservableCollection<string> ColorHistory { get; }
SettingItem<int> ColorHistoryLimit { get; }

View File

@@ -49,7 +49,10 @@ namespace ColorPicker.Settings
ChangeCursor = new SettingItem<bool>(true);
ActivationShortcut = new SettingItem<string>(DefaultActivationShortcut);
CopiedColorRepresentation = new SettingItem<string>(ColorRepresentationType.HEX.ToString());
ActivationAction = new SettingItem<ColorPickerActivationAction>(ColorPickerActivationAction.OpenEditor);
ActivationAction = new SettingItem<ColorPickerActivationAction>(ColorPickerActivationAction.OpenColorPicker);
PrimaryClickAction = new SettingItem<ColorPickerClickAction>(ColorPickerClickAction.PickColorThenEditor);
MiddleClickAction = new SettingItem<ColorPickerClickAction>(ColorPickerClickAction.PickColorAndClose);
SecondaryClickAction = new SettingItem<ColorPickerClickAction>(ColorPickerClickAction.Close);
ColorHistoryLimit = new SettingItem<int>(20);
ColorHistory.CollectionChanged += ColorHistory_CollectionChanged;
ShowColorName = new SettingItem<bool>(false);
@@ -78,6 +81,12 @@ namespace ColorPicker.Settings
public SettingItem<ColorPickerActivationAction> ActivationAction { get; private set; }
public SettingItem<ColorPickerClickAction> PrimaryClickAction { get; private set; }
public SettingItem<ColorPickerClickAction> MiddleClickAction { get; private set; }
public SettingItem<ColorPickerClickAction> SecondaryClickAction { get; private set; }
public RangeObservableCollection<string> ColorHistory { get; private set; } = new RangeObservableCollection<string>();
public SettingItem<int> ColorHistoryLimit { get; }
@@ -121,6 +130,9 @@ namespace ColorPicker.Settings
CopiedColorRepresentation.Value = settings.Properties.CopiedColorRepresentation;
CopiedColorRepresentationFormat = new SettingItem<string>(string.Empty);
ActivationAction.Value = settings.Properties.ActivationAction;
PrimaryClickAction.Value = settings.Properties.PrimaryClickAction;
MiddleClickAction.Value = settings.Properties.MiddleClickAction;
SecondaryClickAction.Value = settings.Properties.SecondaryClickAction;
ColorHistoryLimit.Value = settings.Properties.ColorHistoryLimit;
ShowColorName.Value = settings.Properties.ShowColorName;

View File

@@ -16,6 +16,7 @@ using ColorPicker.Settings;
using ColorPicker.ViewModelContracts;
using Common.UI;
using ManagedCommon;
using Microsoft.PowerToys.Settings.UI.Library.Enumerations;
using PowerToys.Interop;
namespace ColorPicker.ViewModels
@@ -79,9 +80,10 @@ namespace ColorPicker.ViewModels
{
SetColorDetails(mouseInfoProvider.CurrentColor);
mouseInfoProvider.MouseColorChanged += Mouse_ColorChanged;
mouseInfoProvider.OnMouseDown += MouseInfoProvider_OnMouseDown;
mouseInfoProvider.OnPrimaryMouseDown += MouseInfoProvider_OnPrimaryMouseDown;
mouseInfoProvider.OnMouseWheel += MouseInfoProvider_OnMouseWheel;
mouseInfoProvider.OnSecondaryMouseUp += MouseInfoProvider_OnSecondaryMouseUp;
mouseInfoProvider.OnMiddleMouseDown += MouseInfoProvider_OnMiddleMouseDown;
}
_userSettings.ShowColorName.PropertyChanged += (s, e) => { OnPropertyChanged(nameof(ShowColorName)); };
@@ -113,7 +115,7 @@ namespace ColorPicker.ViewModels
private void AppStateHandler_EnterPressed(object sender, EventArgs e)
{
MouseInfoProvider_OnMouseDown(null, default(System.Drawing.Point));
MouseInfoProvider_OnPrimaryMouseDown(null, default);
}
/// <summary>
@@ -167,18 +169,50 @@ namespace ColorPicker.ViewModels
SetColorDetails(color);
}
/// <summary>
/// Tell the color picker that the user have press a mouse button (after release the button)
/// </summary>
/// <param name="sender">The sender of this event</param>
/// <param name="p">The current <see cref="System.Drawing.Point"/> of the mouse cursor</param>
private void MouseInfoProvider_OnMouseDown(object sender, System.Drawing.Point p)
private void MouseInfoProvider_OnPrimaryMouseDown(object sender, IntPtr wParam)
{
ClipboardHelper.CopyToClipboard(ColorText);
HandleMouseClickAction(_userSettings.PrimaryClickAction.Value);
}
var color = GetColorString();
private void MouseInfoProvider_OnMiddleMouseDown(object sender, IntPtr wParam)
{
HandleMouseClickAction(_userSettings.MiddleClickAction.Value);
}
var oldIndex = _userSettings.ColorHistory.IndexOf(color);
private void MouseInfoProvider_OnSecondaryMouseUp(object sender, IntPtr wParam)
{
HandleMouseClickAction(_userSettings.SecondaryClickAction.Value);
}
private void HandleMouseClickAction(ColorPickerClickAction action)
{
switch (action)
{
case ColorPickerClickAction.PickColorThenEditor:
ClipboardHelper.CopyToClipboard(ColorText);
UpdateColorHistory(GetColorString());
_appStateHandler.OpenColorEditor();
break;
case ColorPickerClickAction.PickColorAndClose:
ClipboardHelper.CopyToClipboard(ColorText);
UpdateColorHistory(GetColorString());
_appStateHandler.EndUserSession();
break;
case ColorPickerClickAction.Close:
_appStateHandler.EndUserSession();
break;
}
}
private void UpdateColorHistory(string color)
{
int oldIndex = _userSettings.ColorHistory.IndexOf(color);
if (oldIndex != -1)
{
_userSettings.ColorHistory.Move(oldIndex, 0);
@@ -192,13 +226,6 @@ namespace ColorPicker.ViewModels
{
_userSettings.ColorHistory.RemoveAt(_userSettings.ColorHistory.Count - 1);
}
_appStateHandler.OnColorPickerMouseDown();
}
private void MouseInfoProvider_OnSecondaryMouseUp(object sender, IntPtr wParam)
{
_appStateHandler.EndUserSession();
}
private string GetColorString()

View File

@@ -65,7 +65,7 @@
HorizontalAlignment="Center"
VerticalAlignment="Center"
Foreground="{StaticResource TextFillColorSecondaryBrush}"
Visibility="{x:Bind IsWarningMessageVisible(VideoPreviewer.MissingCodecName), Mode=OneWay}">
Visibility="{x:Bind IsWarningMessageVisible(VideoPreviewer, Previewer.State), Mode=OneWay}">
<Paragraph>
<Run Text="{x:Bind GetWarningMessage(VideoPreviewer.MissingCodecName), Mode=OneWay}" />
<Hyperlink Click="CodecSearchHyperlink_Click">

View File

@@ -150,9 +150,9 @@ namespace Peek.FilePreviewer
return isValidPreview ? Visibility.Visible : Visibility.Collapsed;
}
public Visibility IsWarningMessageVisible(string? missingCodecName)
public Visibility IsWarningMessageVisible(IPreviewer? previewer, PreviewState? state)
{
var shouldShow = !string.IsNullOrEmpty(missingCodecName);
var shouldShow = previewer is IVideoPreviewer videoPreviewer && MatchPreviewState(state, PreviewState.Loaded) && !string.IsNullOrEmpty(videoPreviewer.MissingCodecName);
return shouldShow ? Visibility.Visible : Visibility.Collapsed;
}

View File

@@ -228,6 +228,8 @@ namespace Microsoft.PowerToys.PreviewHandler.Pdf
DestinationWidth = (uint)this.ClientSize.Width,
}).GetAwaiter().GetResult();
stream.Seek(0); // Reset the stream position to the beginning before reading.
imageOfPage = Image.FromStream(stream.AsStream());
}

View File

@@ -31,7 +31,7 @@
<ItemGroup>
<Folder Include="RegistryPreviewXAML\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CommunityToolkit.WinUI.UI.Controls.DataGrid" />
<PackageReference Include="CommunityToolkit.WinUI.Controls.Sizers" />

View File

@@ -10,7 +10,31 @@
<XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
<!-- Other merged dictionaries here -->
</ResourceDictionary.MergedDictionaries>
<!-- Other app resources here -->
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
<SolidColorBrush x:Key="HexBox_SelectionTextBrush" Color="{ThemeResource TextOnAccentFillColorSelectedText}" />
<SolidColorBrush x:Key="HexBox_SelectionBackgroundBrush" Color="{ThemeResource SystemAccentColor}" />
<SolidColorBrush x:Key="HexBox_VerticalLineBrush" Color="{ThemeResource DividerStrokeColorDefault}" />
<StaticResource x:Key="HexBox_ControlBorderBrush" ResourceKey="TextControlElevationBorderBrush" />
<StaticResource x:Key="HexBox_ControlBorderFocusedBrush" ResourceKey="TextControlElevationBorderFocusedBrush" />
<Thickness x:Key="HexBox_ControlBorderThickness">1</Thickness>
<Thickness x:Key="HexBox_ControlBorderFocusedThickness">1,1,1,2</Thickness>
</ResourceDictionary>
<ResourceDictionary x:Key="HighContrast">
<SolidColorBrush x:Key="HexBox_SelectionTextBrush" Color="{ThemeResource SystemColorHighlightTextColor}" />
<SolidColorBrush x:Key="HexBox_SelectionBackgroundBrush" Color="{ThemeResource SystemColorHighlightColor}" />
<SolidColorBrush x:Key="HexBox_VerticalLineBrush" Color="{ThemeResource SystemColorWindowTextColor}" />
<LinearGradientBrush x:Key="HexBox_ControlBorderBrush" StartPoint="0,0" EndPoint="1,1">
<GradientStop Offset="0" Color="{ThemeResource SystemColorButtonTextColor}" />
</LinearGradientBrush>
<LinearGradientBrush x:Key="HexBox_ControlBorderFocusedBrush" StartPoint="0,0" EndPoint="1,1">
<GradientStop Offset="0" Color="{ThemeResource SystemColorHighlightColor}" />
</LinearGradientBrush>
<Thickness x:Key="HexBox_ControlBorderThickness">1</Thickness>
<Thickness x:Key="HexBox_ControlBorderFocusedThickness">2</Thickness>
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>

View File

@@ -0,0 +1,43 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// <history>
// 2020-... created by Filip Jeremic (fjeremic) as "HexView.Wpf".
// 2024-... republished by @hotkidfamily as "HexBox.WinUI".
// 2025 Included in PowerToys. (Branch master; commit 72dcf64dc858c693a7a16887004c8ddbab61fce7.)
// </history>
namespace RegistryPreviewUILib.HexBox
{
/// <summary>
/// Enumerates the address column formatting options.
/// </summary>
public enum AddressFormat
{
/// <summary>
/// 16 bit HEX address "0000".
/// </summary>
Address16,
/// <summary>
/// 24 bit HEX address "00:0000".
/// </summary>
Address24,
/// <summary>
/// 32 bit HEX address "0000:0000".
/// </summary>
Address32,
/// <summary>
/// 48 bit HEX address "0000:00000000".
/// </summary>
Address48,
/// <summary>
/// 64 bit HEX address "00000000:00000000".
/// </summary>
Address64,
}
}

View File

@@ -0,0 +1,43 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// <history>
// 2020-... created by Filip Jeremic (fjeremic) as "HexView.Wpf".
// 2024-... republished by @hotkidfamily as "HexBox.WinUI".
// 2025 Included in PowerToys. (Branch master; commit 72dcf64dc858c693a7a16887004c8ddbab61fce7.)
// </history>
using System;
using System.Windows.Input;
namespace RegistryPreviewUILib.HexBox
{
public class RelayCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Func<object, bool> _canExecute;
public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
}

View File

@@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// <history>
// 2020-... created by Filip Jeremic (fjeremic) as "HexView.Wpf".
// 2024-... republished by @hotkidfamily as "HexBox.WinUI".
// 2025 Included in PowerToys. (Branch master; commit 72dcf64dc858c693a7a16887004c8ddbab61fce7.)
// </history>
namespace RegistryPreviewUILib.HexBox
{
/// <summary>
/// Enumerates the format to display integral data in.
/// </summary>
public enum DataFormat
{
/// <summary>
/// Display the data in decimal format.
/// </summary>
Decimal,
/// <summary>
/// Display the data in hexadecimal format.
/// </summary>
Hexadecimal,
}
}

View File

@@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// <history>
// 2020-... created by Filip Jeremic (fjeremic) as "HexView.Wpf".
// 2024-... republished by @hotkidfamily as "HexBox.WinUI".
// 2025 Included in PowerToys. (Branch master; commit 72dcf64dc858c693a7a16887004c8ddbab61fce7.)
// </history>
namespace RegistryPreviewUILib.HexBox
{
/// <summary>
/// Enumerates the signedness of the data to display.
/// </summary>
public enum DataSignedness
{
/// <summary>
/// Display the data as signed values.
/// </summary>
Signed,
/// <summary>
/// Display the data as unsigned values.
/// </summary>
Unsigned,
}
}

View File

@@ -0,0 +1,43 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// <history>
// 2020-... created by Filip Jeremic (fjeremic) as "HexView.Wpf".
// 2024-... republished by @hotkidfamily as "HexBox.WinUI".
// 2025 Included in PowerToys. (Branch master; commit 72dcf64dc858c693a7a16887004c8ddbab61fce7.)
// </history>
namespace RegistryPreviewUILib.HexBox
{
/// <summary>
/// Enumerates how the data (bytes read from the buffer) is to be interpreted when displayed.
/// </summary>
public enum DataType
{
/// <summary>
/// Display the data as integral (integer) values.
/// </summary>
Int_1 = 1,
/// <summary>
/// Display the data as integral (integer) values.
/// </summary>
Int_2 = 2,
/// <summary>
/// Display the data as integral (integer) values.
/// </summary>
Int_4 = 4,
/// <summary>
/// Display the data as integral (integer) values.
/// </summary>
Int_8 = 8,
/// <summary>
/// Display the data as floating point values.
/// </summary>
Float_32 = 32,
/// <summary>
/// Display the data as floating point values.
/// </summary>
Float_64 = 64,
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,231 @@
// 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.
// <history>
// 2020-... created by Filip Jeremic (fjeremic) as "HexView.Wpf".
// 2024-... republished by @hotkidfamily as "HexBox.WinUI".
// 2025 Included in PowerToys. (Branch master; commit 72dcf64dc858c693a7a16887004c8ddbab61fce7.)
// </history>
namespace RegistryPreviewUILib.HexBox.Library.EndianConvert
{
using System;
using System.IO;
using System.Text;
/// <summary>
/// Reads primitive data types as binary values in a specific encoding and endianness.
/// </summary>
public class EndianBinaryReader : BinaryReader
{
/// <summary>
/// Initializes a new instance of the <see cref="EndianBinaryReader"/> class based on the specified stream, endianness, and using UTF-8
/// encoding.
/// </summary>
///
/// <param name="input">
/// The input stream.
/// </param>
///
/// <param name="endianness">
/// The endianness of the data in the input stream.
/// </param>
///
/// <exception cref="System.ArgumentException">
/// The stream does not support reading, is null, or is already closed.
/// </exception>
public EndianBinaryReader(Stream input, Endianness endianness)
: this(input, endianness, Encoding.UTF8)
{
// Void
}
/// <summary>
/// Initializes a new instance of the <see cref="EndianBinaryReader"/> class based on the specified stream, endianness, and character
/// encoding.
/// </summary>
///
/// <param name="input">
/// The input stream.
/// </param>
///
/// <param name="endianness">
/// The endianness of the data in the input stream.
/// </param>
///
/// <param name="encoding">
/// The character encoding to use.
/// </param>
///
/// <exception cref="System.ArgumentException">
/// The stream does not support reading, is null, or is already closed.
/// </exception>
public EndianBinaryReader(Stream input, Endianness endianness, Encoding encoding)
: this(input, endianness, encoding, false)
{
// Void
}
/// <summary>
/// Initializes a new instance of the <see cref="EndianBinaryReader"/> class based on the specified stream, endianness, and character
/// encoding, and optionally leaves the stream open.
/// </summary>
///
/// <param name="input">
/// The input stream.
/// </param>
///
/// <param name="endianness">
/// The endianness of the data in the input stream.
/// </param>
///
/// <param name="encoding">
/// The character encoding to use.
/// </param>
///
/// <param name="leaveOpen">
/// <c>true</c> to leave the stream open after the <see cref="EndianBinaryReader"/> object is disposed; <c>false</c> otherwise.
/// </param>
///
/// <exception cref="System.ArgumentException">
/// The stream does not support reading, is null, or is already closed.
/// </exception>
public EndianBinaryReader(Stream input, Endianness endianness, Encoding encoding, bool leaveOpen)
: base(input, encoding, leaveOpen)
{
Endianness = endianness;
}
/// <summary>
/// Gets the endianness of the data in the input stream.
/// </summary>
public Endianness Endianness
{
get;
}
/// <summary>
/// Reads a decimal value from the current stream and advances the current position of the stream by sixteen bytes.
/// </summary>
///
/// <returns>
/// A decimal value read from the current stream.
/// </returns>
public override decimal ReadDecimal()
{
throw new NotImplementedException();
}
/// <summary>
/// Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes.
/// </summary>
///
/// <returns>
/// An 8-byte floating point value read from the current stream.
/// </returns>
public override double ReadDouble()
{
throw new NotImplementedException();
}
/// <summary>
/// Reads a 2-byte signed integer from the current stream and advances the current position of the stream by two bytes.
/// </summary>
///
/// <returns>
/// A 2-byte signed integer read from the current stream.
/// </returns>
public override short ReadInt16()
{
return EndianBitConverter.Convert(base.ReadInt16(), Endianness);
}
/// <summary>
/// Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes.
/// </summary>
///
/// <returns>
/// A 4-byte signed integer read from the current stream.
/// </returns>
public override int ReadInt32()
{
return EndianBitConverter.Convert(base.ReadInt32(), Endianness);
}
/// <summary>
/// Reads an 8-byte signed integer from the current stream and advances the current position of the stream by eight bytes.
/// </summary>
///
/// <returns>
/// An 8-byte signed integer read from the current stream.
/// </returns>
public override long ReadInt64()
{
return EndianBitConverter.Convert(base.ReadInt64(), Endianness);
}
/// <summary>
/// Reads a 4-byte floating point value from the current stream and advances the current position of the stream by four bytes.
/// </summary>
///
/// <returns>
/// A 4-byte floating point value read from the current stream.
/// </returns>
public override float ReadSingle()
{
throw new NotImplementedException();
}
/// <summary>
/// Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.
/// </summary>
///
/// <returns>
/// The string being read.
/// </returns>
public override string ReadString()
{
throw new NotImplementedException();
}
/// <summary>
/// Reads a 2-byte unsigned integer from the current stream using little-endian encoding and advances the position of the stream by
/// two bytes.
/// </summary>
///
/// <returns>
/// A 2-byte unsigned integer read from this stream.
/// </returns>
public override ushort ReadUInt16()
{
return EndianBitConverter.Convert(base.ReadUInt16(), Endianness);
}
/// <summary>
/// Reads a 4-byte unsigned integer from the current stream using little-endian encoding and advances the position of the stream by
/// four bytes.
/// </summary>
///
/// <returns>
/// A 4-byte unsigned integer read from this stream.
/// </returns>
public override uint ReadUInt32()
{
return EndianBitConverter.Convert(base.ReadUInt32(), Endianness);
}
/// <summary>
/// Reads an 8-byte unsigned integer from the current stream using little-endian encoding and advances the position of the stream by
/// eight bytes.
/// </summary>
///
/// <returns>
/// An 8-byte unsigned integer read from this stream.
/// </returns>
public override ulong ReadUInt64()
{
return EndianBitConverter.Convert(base.ReadUInt64(), Endianness);
}
}
}

View File

@@ -0,0 +1,186 @@
// 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.
// <history>
// 2020-... created by Filip Jeremic (fjeremic) as "HexView.Wpf".
// 2024-... republished by @hotkidfamily as "HexBox.WinUI".
// 2025 Included in PowerToys. (Branch master; commit 72dcf64dc858c693a7a16887004c8ddbab61fce7.)
// </history>
namespace RegistryPreviewUILib.HexBox.Library.EndianConvert
{
using System;
/// <summary>
/// Converts integral values to the native endianness of this computer architecture.
/// </summary>
public static class EndianBitConverter
{
/// <summary>
/// Gets the native endianness of this computer architecture.
/// </summary>
public static readonly Endianness NativeEndianness = BitConverter.IsLittleEndian ? Endianness.LittleEndian : Endianness.BigEndian;
/// <summary>
/// Converts a value from the specified endianness to the native endianness.
/// </summary>
///
/// <param name="value">
/// The value to convert.
/// </param>
///
/// <param name="endianness">
/// The endianness of <paramref name="value"/>.
/// </param>
///
/// <returns>
/// The value converted from the specified endianness to the native endianness (<see cref="NativeEndianness"/>).
/// </returns>
public static ushort Convert(ushort value, Endianness endianness)
{
if (endianness == NativeEndianness)
{
return value;
}
else
{
unchecked
{
return (ushort)((value & 0x00FFU) << 8 |
(value & 0xFF00U) >> 8);
}
}
}
/// <summary>
/// Converts a value from the specified endianness to the native endianness.
/// </summary>
///
/// <param name="value">
/// The value to convert.
/// </param>
///
/// <param name="endianness">
/// The endianness of <paramref name="value"/>.
/// </param>
///
/// <returns>
/// The value converted from the specified endianness to the native endianness (<see cref="NativeEndianness"/>).
/// </returns>
public static uint Convert(uint value, Endianness endianness)
{
if (endianness == NativeEndianness)
{
return value;
}
else
{
unchecked
{
return (value & 0x000000FFU) << 24 |
(value & 0xFF000000U) >> 24 |
(value & 0x0000FF00U) << 8 |
(value & 0x00FF0000U) >> 8;
}
}
}
/// <summary>
/// Converts a value from the specified endianness to the native endianness.
/// </summary>
///
/// <param name="value">
/// The value to convert.
/// </param>
///
/// <param name="endianness">
/// The endianness of <paramref name="value"/>.
/// </param>
///
/// <returns>
/// The value converted from the specified endianness to the native endianness (<see cref="NativeEndianness"/>).
/// </returns>
public static ulong Convert(ulong value, Endianness endianness)
{
if (endianness == NativeEndianness)
{
return value;
}
else
{
unchecked
{
return (value & 0x00000000000000FFUL) << 56 |
(value & 0xFF00000000000000UL) >> 56 |
(value & 0x000000000000FF00UL) << 40 |
(value & 0x00FF000000000000UL) >> 40 |
(value & 0x0000000000FF0000UL) << 24 |
(value & 0x0000FF0000000000UL) >> 24 |
(value & 0x00000000FF000000UL) << 8 |
(value & 0x000000FF00000000UL) >> 8;
}
}
}
/// <summary>
/// Converts a value from the specified endianness to the native endianness.
/// </summary>
///
/// <param name="value">
/// The value to convert.
/// </param>
///
/// <param name="endianness">
/// The endianness of <paramref name="value"/>.
/// </param>
///
/// <returns>
/// The value converted from the specified endianness to the native endianness (<see cref="NativeEndianness"/>).
/// </returns>
public static short Convert(short value, Endianness endianness)
{
return (short)Convert((ushort)value, endianness);
}
/// <summary>
/// Converts a value from the specified endianness to the native endianness.
/// </summary>
///
/// <param name="value">
/// The value to convert.
/// </param>
///
/// <param name="endianness">
/// The endianness of <paramref name="value"/>.
/// </param>
///
/// <returns>
/// The value converted from the specified endianness to the native endianness (<see cref="NativeEndianness"/>).
/// </returns>
public static int Convert(int value, Endianness endianness)
{
return (int)Convert((uint)value, endianness);
}
/// <summary>
/// Converts a value from the specified endianness to the native endianness.
/// </summary>
///
/// <param name="value">
/// The value to convert.
/// </param>
///
/// <param name="endianness">
/// The endianness of <paramref name="value"/>.
/// </param>
///
/// <returns>
/// The value converted from the specified endianness to the native endianness (<see cref="NativeEndianness"/>).
/// </returns>
public static long Convert(long value, Endianness endianness)
{
return (long)Convert((ulong)value, endianness);
}
}
}

View File

@@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// <history>
// 2020-... created by Filip Jeremic (fjeremic) as "HexView.Wpf".
// 2024-... republished by @hotkidfamily as "HexBox.WinUI".
// 2025 Included in PowerToys. (Branch master; commit 72dcf64dc858c693a7a16887004c8ddbab61fce7.)
// </history>
namespace RegistryPreviewUILib.HexBox.Library.EndianConvert
{
/// <summary>
/// Represents the endianness of a value in a computer architecture.
/// </summary>
public enum Endianness
{
/// <summary>
/// Most significant byte first.
/// </summary>
BigEndian,
/// <summary>
/// Least significant byte first.
/// </summary>
LittleEndian,
}
}

View File

@@ -0,0 +1,60 @@
// 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.
// <history>
// 2020-... created by Filip Jeremic (fjeremic) as "HexView.Wpf".
// 2024-... republished by @hotkidfamily as "HexBox.WinUI".
// 2025 Included in PowerToys. (Branch master; commit 72dcf64dc858c693a7a16887004c8ddbab61fce7.)
// </history>
namespace RegistryPreviewUILib.HexBox.Library.EndianConvert
{
using System;
/// <summary>
/// The exception that is thrown when an input file or a data stream is malformed.
/// </summary>
[Serializable]
public sealed class FileFormatException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="FileFormatException"/> class.
/// </summary>
public FileFormatException()
{
// Void
}
/// <summary>
/// Initializes a new instance of the <see cref="FileFormatException"/> class with a specified error message.
/// </summary>
///
/// <param name="message">
/// The message that describes the error.
/// </param>
public FileFormatException(string message)
: base(message)
{
// Void
}
/// <summary>
/// Initializes a new instance of the <see cref="FileFormatException"/> class with a specified error message and a reference to the inner
/// exception that is the cause of this exception.
/// </summary>
///
/// <param name="message">
/// The message that describes the error.
/// </param>
///
/// <param name="innerException">
/// The exception that is the cause of the current exception, or a null reference if no inner exception is specified.
/// </param>
public FileFormatException(string message, Exception innerException)
: base(message, innerException)
{
// Void
}
}
}

View File

@@ -0,0 +1,23 @@
// 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.
// <history>
// 2020-... created by Filip Jeremic (fjeremic) as "HexView.Wpf".
// 2024-... republished by @hotkidfamily as "HexBox.WinUI".
// 2025 Included in PowerToys. (Branch master; commit 72dcf64dc858c693a7a16887004c8ddbab61fce7.)
// </history>
namespace RegistryPreviewUILib.HexBox
{
/// <summary>
/// Enumerates the text section encodings/formats that the control is able to display.
/// </summary>
public enum TextFormat
{
/// <summary>
/// Display data in ASCII (ISO-8859-1) encoding.
/// </summary>
Ascii,
}
}

View File

@@ -0,0 +1,170 @@
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:convert="using:CommunityToolkit.WinUI.Converters"
xmlns:local="using:RegistryPreviewUILib.HexBox"
xmlns:skia="using:SkiaSharp.Views.Windows">
<Style TargetType="local:HexBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:HexBox">
<Grid
Margin="{TemplateBinding Margin}"
Padding="4"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}"
IsTabStop="False">
<Grid.Resources>
<convert:BoolNegationConverter x:Key="BoolNegationConverter" />
<local:BigEndianConverter x:Key="BigEndianConverter" />
<local:HexboxDataFormatConverter x:Key="HexboxDataFormatConverter" />
<local:HexboxDataSignednessConverter x:Key="HexboxDataSignednessConverter" />
<local:HexboxDataFormatBoolConverter x:Key="HexboxDataFormatBoolConverter" />
<local:HexboxDataTypeConverter x:Key="HexboxDataTypeConverter" />
<MenuFlyout x:Key="DataMenuFlyout">
<!-- New code for PowerToys implementation -->
<MenuFlyoutItem
x:Uid="/PowerToys.RegistryPreviewUILib/Resources/HexBox_CopyCommand"
Command="{Binding CopyCommand, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Icon="Copy">
<MenuFlyoutItem.KeyboardAccelerators>
<KeyboardAccelerator Key="C" Modifiers="Control" />
</MenuFlyoutItem.KeyboardAccelerators>
</MenuFlyoutItem>
<MenuFlyoutItem
x:Uid="/PowerToys.RegistryPreviewUILib/Resources/HexBox_CopyTextCommand"
Command="{Binding CopyTextCommand, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Icon="Font">
<MenuFlyoutItem.KeyboardAccelerators>
<KeyboardAccelerator Key="C" Modifiers="Control,Shift" />
</MenuFlyoutItem.KeyboardAccelerators>
</MenuFlyoutItem>
<MenuFlyoutItem
x:Uid="/PowerToys.RegistryPreviewUILib/Resources/HexBox_SelectAllCommand"
Command="{Binding SelectAllCommand, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Icon="SelectAll">
<MenuFlyoutItem.KeyboardAccelerators>
<KeyboardAccelerator Key="A" Modifiers="Control" />
</MenuFlyoutItem.KeyboardAccelerators>
</MenuFlyoutItem>
<!-- Original source code from HexBox.WinUI.HexBox
<MenuFlyoutItem
Command="{Binding CopyCommand, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Icon="Copy"
Text="Copy">
<MenuFlyoutItem.KeyboardAccelerators>
<KeyboardAccelerator Key="C" Modifiers="Control" />
</MenuFlyoutItem.KeyboardAccelerators>
</MenuFlyoutItem>
<MenuFlyoutItem
Command="{Binding CopyTextCommand, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Icon="Font"
Text="Copy text">
<MenuFlyoutItem.KeyboardAccelerators>
<KeyboardAccelerator Key="C" Modifiers="Control,Shift"/>
</MenuFlyoutItem.KeyboardAccelerators>
</MenuFlyoutItem>
<MenuFlyoutItem
Command="{Binding SelectAllCommand, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Icon="SelectAll"
Text="Select all">
<MenuFlyoutItem.KeyboardAccelerators>
<KeyboardAccelerator Key="A" Modifiers="Control" />
</MenuFlyoutItem.KeyboardAccelerators>
</MenuFlyoutItem>
<MenuFlyoutSeparator />
<MenuFlyoutSubItem IsEnabled="{Binding EnforceProperties, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=OneWay, Converter={StaticResource BoolNegationConverter}}" Text="Address properties">
<ToggleMenuFlyoutItem IsChecked="{Binding ShowAddress, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource BoolNegationConverter}}" Text="No Address" />
</MenuFlyoutSubItem>
<MenuFlyoutSubItem IsEnabled="{Binding EnforceProperties, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=OneWay, Converter={StaticResource BoolNegationConverter}}" Text="Data properties">
<ToggleMenuFlyoutItem IsChecked="{Binding ShowData, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource BoolNegationConverter}}" Text="No Data" />
<RadioMenuFlyoutItem
GroupName="DataType"
IsChecked="{Binding DataType, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource HexboxDataTypeConverter}, ConverterParameter=Int_1}"
IsEnabled="{Binding ShowData, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Text="1 byte-integer" />
<RadioMenuFlyoutItem
GroupName="DataType"
IsChecked="{Binding DataType, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource HexboxDataTypeConverter}, ConverterParameter=Int_2}"
IsEnabled="{Binding ShowData, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Text="2 byte-integer" />
<RadioMenuFlyoutItem
GroupName="DataType"
IsChecked="{Binding DataType, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource HexboxDataTypeConverter}, ConverterParameter=Int_4}"
IsEnabled="{Binding ShowData, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Text="4 byte-integer" />
<RadioMenuFlyoutItem
GroupName="DataType"
IsChecked="{Binding DataType, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource HexboxDataTypeConverter}, ConverterParameter=Int_8}"
IsEnabled="{Binding ShowData, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Text="8 byte-integer" />
<RadioMenuFlyoutItem
GroupName="DataType"
IsChecked="{Binding DataType, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource HexboxDataTypeConverter}, ConverterParameter=Float_32}"
IsEnabled="{Binding ShowData, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Text="32-bit Floating Point" />
<RadioMenuFlyoutItem
GroupName="DataType"
IsChecked="{Binding DataType, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource HexboxDataTypeConverter}, ConverterParameter=Float_64}"
IsEnabled="{Binding ShowData, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Text="64-bit Floating Point" />
<MenuFlyoutSeparator />
<ToggleMenuFlyoutItem
IsChecked="{Binding DataSignedness, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource HexboxDataSignednessConverter}, ConverterParameter=Signed}"
IsEnabled="{Binding DataFormat, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource HexboxDataFormatBoolConverter}, ConverterParameter={Binding DataFormat}}"
Text="Signed" />
<ToggleMenuFlyoutItem
IsChecked="{Binding DataSignedness, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource HexboxDataSignednessConverter}, ConverterParameter=Unsigned}"
IsEnabled="{Binding DataFormat, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource HexboxDataFormatBoolConverter}, ConverterParameter={Binding DataFormat}}"
Text="Unsigned" />
<MenuFlyoutSeparator />
<ToggleMenuFlyoutItem IsChecked="{Binding DataFormat, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource HexboxDataFormatConverter}, ConverterParameter=Decimal}" Text="Decimal" />
<ToggleMenuFlyoutItem IsChecked="{Binding DataFormat, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource HexboxDataFormatConverter}, ConverterParameter=Hexadecimal}" Text="Hexadecimal" />
<MenuFlyoutSeparator />
<ToggleMenuFlyoutItem IsChecked="{Binding Endianness, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource BigEndianConverter}, ConverterParameter=BigEndian}" Text="Big-Endian" />
<ToggleMenuFlyoutItem IsChecked="{Binding Endianness, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource BigEndianConverter}, ConverterParameter=LittleEndian}" Text="Little-Endian" />
</MenuFlyoutSubItem>
<MenuFlyoutSubItem IsEnabled="{Binding EnforceProperties, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=OneWay, Converter={StaticResource BoolNegationConverter}}" Text="Text properties">
<ToggleMenuFlyoutItem IsChecked="{Binding ShowText, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Converter={StaticResource BoolNegationConverter}}" Text="No Text" />
<ToggleMenuFlyoutItem
IsChecked="{Binding ShowText, RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay}"
IsEnabled="False"
Text="ASCII" />
</MenuFlyoutSubItem>-->
</MenuFlyout>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="24" />
</Grid.ColumnDefinitions>
<skia:SKXamlCanvas
Name="ElementCanvas"
Grid.Column="0"
Margin="2,0,2,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ContextFlyout="{StaticResource DataMenuFlyout}" />
<ScrollBar
Name="ElementScrollBar"
Grid.Column="1"
Margin="0,0,2,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
FontFamily="{TemplateBinding FontFamily}"
FontSize="{TemplateBinding FontSize}"
IndicatorMode="MouseIndicator"
Orientation="Vertical" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

View File

@@ -0,0 +1,264 @@
// 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.
// <history>
// 2020-... created by Filip Jeremic (fjeremic) as "HexView.Wpf".
// 2024-... republished by @hotkidfamily as "HexBox.WinUI".
// 2025 Included in PowerToys. (Branch master; commit 72dcf64dc858c693a7a16887004c8ddbab61fce7.)
// </history>
#pragma warning disable SA1210 // Using directives should be ordered alphabetically by namespace
#pragma warning disable SA1208 // System using directives should be placed before other using directives
using RegistryPreviewUILib.HexBox.Library.EndianConvert;
using Microsoft.UI.Xaml.Data;
using System;
#pragma warning restore SA1208 // System using directives should be placed before other using directives
#pragma warning restore SA1210 // Using directives should be ordered alphabetically by namespace
namespace RegistryPreviewUILib.HexBox
{
public partial class HexboxDataTypeConverter : IValueConverter
{
/// <summary>
/// Convert a DataType value to its negation.
/// </summary>
/// <param name="value">The <see cref="DataType"/> value to negate.</param>
/// <param name="targetType">The type of the target property, as a type reference.</param>
/// <param name="parameter">Optional parameter. Not used.</param>
/// <param name="language">The language of the conversion. Not used</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is DataType b)
{
if (parameter is string c)
{
return c == b.ToString();
}
}
throw new NotImplementedException();
}
/// <summary>
/// Convert back a DataType value to its negation.
/// </summary>
/// <param name="value">The <see cref="DataType"/> value to negate.</param>
/// <param name="targetType">The type of the target property, as a type reference.</param>
/// <param name="parameter">Optional parameter. Not used.</param>
/// <param name="language">The language of the conversion. Not used</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (value is bool b && parameter is string c)
{
if(c == "Int_1")
{
return DataType.Int_1;
}
else if (c == "Int_2")
{
return DataType.Int_2;
}
else if (c == "Int_4")
{
return DataType.Int_4;
}
else if (c == "Int_8")
{
return DataType.Int_8;
}
else if (c == "Float_32")
{
return DataType.Float_32;
}
else /*if (c == "Float_64")*/
{
return DataType.Float_64;
}
}
throw new NotImplementedException();
}
}
public class HexboxDataSignednessConverter : IValueConverter
{
/// <summary>
/// Convert a DataSignedness value to its negation.
/// </summary>
/// <param name="value">The <see cref="DataSignedness"/> value to negate.</param>
/// <param name="targetType">The type of the target property, as a type reference.</param>
/// <param name="parameter">Optional parameter. Not used.</param>
/// <param name="language">The language of the conversion. Not used</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is DataSignedness b)
{
if (parameter is string c)
{
var end = c == "Signed" ? DataSignedness.Signed : DataSignedness.Unsigned;
return (b == end);
}
}
throw new NotImplementedException();
}
/// <summary>
/// Convert back a DataSignedness value to its negation.
/// </summary>
/// <param name="value">The <see cref="DataSignedness"/> value to negate.</param>
/// <param name="targetType">The type of the target property, as a type reference.</param>
/// <param name="parameter">Optional parameter. Not used.</param>
/// <param name="language">The language of the conversion. Not used</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (value is bool b && parameter is string c)
{
var end = c == "Signed" ? DataSignedness.Signed : DataSignedness.Unsigned;
if (b)
{
return end;
}
else
{
return c == "Signed" ? DataSignedness.Unsigned : DataSignedness.Signed;
}
}
throw new NotImplementedException();
}
}
public class HexboxDataFormatBoolConverter : IValueConverter
{
/// <summary>
/// Convert a DataFormat value to its negation.
/// </summary>
/// <param name="value">The <see cref="DataFormat"/> value to negate.</param>
/// <param name="targetType">The type of the target property, as a type reference.</param>
/// <param name="parameter">Optional parameter. Not used.</param>
/// <param name="language">The language of the conversion. Not used</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object Convert(object value, Type targetType, object parameter, string language)
{
if(value is DataFormat f)
{
return f != DataFormat.Hexadecimal;
}
throw new NotImplementedException();
}
/// <summary>
/// Convert back a DataFormat value to its negation.
/// </summary>
/// <param name="value">The <see cref="DataFormat"/> value to negate.</param>
/// <param name="targetType">The type of the target property, as a type reference.</param>
/// <param name="parameter">Optional parameter. Not used.</param>
/// <param name="language">The language of the conversion. Not used</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
public class HexboxDataFormatConverter : IValueConverter
{
/// <summary>
/// Convert a DataFormat value to its negation.
/// </summary>
/// <param name="value">The <see cref="DataFormat"/> value to negate.</param>
/// <param name="targetType">The type of the target property, as a type reference.</param>
/// <param name="parameter">Optional parameter. Not used.</param>
/// <param name="language">The language of the conversion. Not used</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is DataFormat b)
{
if (parameter is string c)
{
var end = c == "Decimal" ? DataFormat.Decimal: DataFormat.Hexadecimal;
return (b == end);
}
}
throw new NotImplementedException();
}
/// <summary>
/// Convert back a DataFormat value to its negation.
/// </summary>
/// <param name="value">The <see cref="DataFormat"/> value to negate.</param>
/// <param name="targetType">The type of the target property, as a type reference.</param>
/// <param name="parameter">Optional parameter. Not used.</param>
/// <param name="language">The language of the conversion. Not used</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (value is bool b && parameter is string c)
{
var end = c == "Decimal" ? DataFormat.Decimal : DataFormat.Hexadecimal;
if (b)
{
return end;
}
else
{
return end == DataFormat.Decimal ? DataFormat.Hexadecimal : DataFormat.Decimal;
}
}
throw new NotImplementedException();
}
}
public class BigEndianConverter : IValueConverter
{
/// <summary>
/// Convert a Endian value to its negation.
/// </summary>
/// <param name="value">The <see cref="Endian"/> value to negate.</param>
/// <param name="targetType">The type of the target property, as a type reference.</param>
/// <param name="parameter">Optional parameter. Not used.</param>
/// <param name="language">The language of the conversion. Not used</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is Endianness b)
{
if (parameter is string c)
{
var end = c == "BigEndian" ? Endianness.BigEndian : Endianness.LittleEndian;
return (b == end);
}
}
throw new NotImplementedException();
}
/// <summary>
/// Convert back a Endian value to its negation.
/// </summary>
/// <param name="value">The <see cref="Endian"/> value to negate.</param>
/// <param name="targetType">The type of the target property, as a type reference.</param>
/// <param name="parameter">Optional parameter. Not used.</param>
/// <param name="language">The language of the conversion. Not used</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (value is bool b && parameter is string c)
{
var end = c == "BigEndian" ? Endianness.BigEndian : Endianness.LittleEndian;
if (b)
{
return end;
}
else
{
return end == Endianness.BigEndian ? Endianness.LittleEndian : Endianness.BigEndian;
}
}
throw new NotImplementedException();
}
}
}

View File

@@ -0,0 +1,81 @@
// 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.
// <history>
// 2020-... created by Filip Jeremic (fjeremic) as "HexView.Wpf".
// 2024-... republished by @hotkidfamily as "HexBox.WinUI".
// 2025 Included in PowerToys. (Branch master; commit 72dcf64dc858c693a7a16887004c8ddbab61fce7.)
// </history>
namespace RegistryPreviewUILib.HexBox
{
using System;
/// <summary>
/// A utility class with miscellaneous methods.
/// </summary>
internal static class Utilities
{
/// <summary>
/// Clamps the <paramref name="value"/> to the range [<paramref name="min"/>, <paramref name="max"/>].
/// </summary>
///
/// <typeparam name="T">
/// The type of the value to clamp.
/// </typeparam>
///
/// <param name="value">
/// The value to clamp.
/// </param>
///
/// <param name="min">
/// The upper bound on the clamped value.
/// </param>
///
/// <param name="max">
/// The lower bound on the clmaped value.
/// </param>
///
/// <returns>
/// The nearest value of <paramref name="value"/> in the range [<paramref name="min"/>,
/// <paramref name="max"/>].
/// </returns>
public static T Clamp<T>(this T value, T min, T max)
where T : IComparable<T>
{
return value.CompareTo(min) < 0 ? min : value.CompareTo(max) > 0 ? max : value;
}
/// <summary>
/// Calculates the arithmetic modulus of <paramref name="n"/> modulo <paramref name="m"/>.
/// </summary>
///
/// <typeparam name="T">
/// The type of the values.
/// </typeparam>
///
/// <param name="n">
/// The value to compute the modulus of.
/// </param>
///
/// <param name="m">
/// The modulus.
/// </param>
///
/// <returns>
/// The non-negative value <c>r</c> such that for some integral value <c>q</c>:
/// <c><paramref name="n"/> = q*m + r</c>.
/// </returns>
public static T Mod<T>(this T n, T m)
where T : IComparable<T>
{
dynamic dn = n;
dynamic dm = m;
dynamic dr = dn % dm;
return dr.CompareTo(0) < 0 ? dr + dm : dr;
}
}
}

View File

@@ -0,0 +1,341 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Automation;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.Windows.ApplicationModel.Resources;
using Windows.Foundation.Metadata;
using HB = RegistryPreviewUILib.HexBox;
namespace RegistryPreviewUILib
{
public sealed partial class RegistryPreviewMainPage : Page
{
private static bool _isDataPreviewHexBoxLoaded;
internal async Task ShowExtendedDataPreview(string name, string type, string value)
{
// Create dialog
_isDataPreviewHexBoxLoaded = false;
var panel = new StackPanel()
{
Spacing = 16,
Padding = new Thickness(0),
};
ContentDialog contentDialog = new ContentDialog()
{
Title = resourceLoader.GetString("DataPreviewTitle") + " - " + name,
Content = panel,
CloseButtonText = resourceLoader.GetString("DataPreviewClose"),
DefaultButton = ContentDialogButton.Primary,
Padding = new Thickness(0),
};
contentDialog.Opened += ExtendedDataPreview_Opened;
// Add content based on value type
switch (type)
{
case "REG_DWORD":
case "REG_QWORD":
AddHexView(ref panel, ref resourceLoader, value);
break;
case "REG_NONE":
case "REG_BINARY":
// Convert value to BinaryReader
byte[] byteArray = Convert.FromHexString(value.Replace(" ", string.Empty));
MemoryStream memoryStream = new MemoryStream(byteArray);
BinaryReader binaryData = new BinaryReader(memoryStream);
binaryData.ReadBytes(byteArray.Length);
// Convert value to text
// For more printable asci characters the following code lines are required:
// var cpW1252 = CodePagesEncodingProvider.Instance.GetEncoding(1252);
// || b == 128 || (b >= 130 && b <= 140) || b == 142 || (b >= 145 & b <= 156) || b >= 158
// cpW1252.GetString([b]);
string binaryDataText = string.Empty;
foreach (byte b in byteArray)
{
// ASCII codes:
// 9, 10, 13: Space, Line Feed, Carriage Return
// 32-126: Printable characters
// 128, 130-140, 142, 145-156, 158-255: Extended printable characters
if (b == 9 || b == 10 || b == 13 || (b >= 32 && b <= 126))
{
binaryDataText += Convert.ToChar(b);
}
}
// Add controls
AddBinaryView(ref panel, ref resourceLoader, ref binaryData, binaryDataText);
break;
case "REG_MULTI_SZ":
var multiLineBox = new TextBox()
{
IsReadOnly = true,
AcceptsReturn = true,
TextWrapping = TextWrapping.NoWrap,
MaxHeight = 200,
FontSize = 14,
RequestedTheme = panel.ActualTheme,
Text = value,
};
ScrollViewer.SetVerticalScrollBarVisibility(multiLineBox, ScrollBarVisibility.Auto);
ScrollViewer.SetHorizontalScrollBarVisibility(multiLineBox, ScrollBarVisibility.Auto);
AutomationProperties.SetName(multiLineBox, resourceLoader.GetString("DataPreview_AutomationPropertiesName_MultilineTextValue"));
panel.Children.Add(multiLineBox);
break;
case "REG_EXPAND_SZ":
AddExpandStringView(ref panel, ref resourceLoader, value);
break;
default: // REG_SZ
var stringBox = new TextBox()
{
IsReadOnly = true,
FontSize = 14,
RequestedTheme = panel.ActualTheme,
Text = value,
};
AutomationProperties.SetName(stringBox, resourceLoader.GetString("DataPreview_AutomationPropertiesName_TextValue"));
panel.Children.Add(stringBox);
break;
}
// Use this code to associate the dialog to the appropriate AppWindow by setting
// the dialog's XamlRoot to the same XamlRoot as an element that is already present in the AppWindow.
if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8))
{
contentDialog.XamlRoot = this.Content.XamlRoot;
}
// Show dialog and wait.
ChangeCursor(gridPreview, false);
_ = await contentDialog.ShowAsync();
}
private static void AddHexView(ref StackPanel panel, ref ResourceLoader resourceLoader, string value)
{
var hexBox = new TextBox()
{
Header = resourceLoader.GetString("DataPreviewHex"),
IsReadOnly = true,
FontSize = 14,
RequestedTheme = panel.ActualTheme,
Text = value.Split(" ")[0],
};
var decimalBox = new TextBox()
{
Header = resourceLoader.GetString("DataPreviewDec"),
IsReadOnly = true,
FontSize = 14,
RequestedTheme = panel.ActualTheme,
Text = value.Split(" ")[1].TrimStart('(').TrimEnd(')'),
};
panel.Children.Add(hexBox);
panel.Children.Add(decimalBox);
}
private static void AddBinaryView(ref StackPanel panel, ref ResourceLoader resourceLoader, ref BinaryReader data, string dataText)
{
// Create SelectorBar
var navBar = new SelectorBar()
{
RequestedTheme = panel.ActualTheme,
};
navBar.SelectionChanged += BinaryPreview_SelectorChanged;
navBar.Items.Add(new SelectorBarItem()
{
Text = resourceLoader.GetString("DataPreviewDataView"),
Tag = "DataView",
FontSize = 14,
RequestedTheme = panel.ActualTheme,
IsSelected = true,
});
navBar.Items.Add(new SelectorBarItem()
{
Text = resourceLoader.GetString("DataPreviewVisibleText"),
Tag = "TextView",
FontSize = 14,
RequestedTheme = panel.ActualTheme,
IsSelected = false,
IsEnabled = !string.IsNullOrWhiteSpace(dataText),
});
// Create HexBox
var binaryPreviewBox = new HB.HexBox()
{
Height = 300,
Width = 495,
ShowAddress = true,
ShowData = true,
ShowText = true,
Columns = 8,
FontSize = 13,
RequestedTheme = panel.ActualTheme,
AddressBrush = (SolidColorBrush)Application.Current.Resources["AccentTextFillColorPrimaryBrush"],
AlternatingDataColumnTextBrush = (SolidColorBrush)Application.Current.Resources["TextFillColorSecondaryBrush"],
SelectionTextBrush = (SolidColorBrush)Application.Current.Resources["HexBox_SelectionTextBrush"],
SelectionBrush = (SolidColorBrush)Application.Current.Resources["HexBox_SelectionBackgroundBrush"],
VerticalSeparatorLineBrush = (SolidColorBrush)Application.Current.Resources["HexBox_VerticalLineBrush"],
BorderBrush = (LinearGradientBrush)Application.Current.Resources["HexBox_ControlBorderBrush"],
BorderThickness = (Thickness)Application.Current.Resources["HexBox_ControlBorderThickness"],
CornerRadius = (CornerRadius)Application.Current.Resources["ControlCornerRadius"],
DataFormat = HB.DataFormat.Hexadecimal,
DataSignedness = HB.DataSignedness.Unsigned,
DataType = HB.DataType.Int_1,
EnforceProperties = true,
Visibility = Visibility.Collapsed,
DataSource = data,
};
AutomationProperties.SetName(binaryPreviewBox, resourceLoader.GetString("DataPreview_AutomationPropertiesName_BinaryDataPreview"));
binaryPreviewBox.Loaded += BinaryPreview_HexBoxLoaded;
binaryPreviewBox.GotFocus += BinaryPreview_HexBoxFocused;
binaryPreviewBox.LostFocus += BinaryPreview_HexBoxFocusLost;
// Create TextBox
var visibleText = new TextBox()
{
IsReadOnly = true,
AcceptsReturn = true,
TextWrapping = TextWrapping.Wrap,
Height = 300,
Width = 495,
FontSize = 13,
Text = dataText,
RequestedTheme = panel.ActualTheme,
Visibility = Visibility.Collapsed,
};
AutomationProperties.SetName(visibleText, resourceLoader.GetString("DataPreview_AutomationPropertiesName_VisibleTextPreview"));
// Add controls: 0 = SelectorBar, 1 = ProgressRing, 2 = HexBox, 3 = TextBox
panel.Children.Add(navBar);
panel.Children.Add(new ProgressRing());
panel.Children.Add(binaryPreviewBox);
panel.Children.Add(visibleText);
}
private static void AddExpandStringView(ref StackPanel panel, ref ResourceLoader resourceLoader, string value)
{
var stringBoxRaw = new TextBox()
{
Header = resourceLoader.GetString("DataPreviewRawValue"),
IsReadOnly = true,
FontSize = 14,
RequestedTheme = panel.ActualTheme,
Text = value,
};
var stringBoxExp = new TextBox()
{
Header = resourceLoader.GetString("DataPreviewExpandedValue"),
IsReadOnly = true,
FontSize = 14,
RequestedTheme = panel.ActualTheme,
Text = Environment.ExpandEnvironmentVariables(value),
};
panel.Children.Add(stringBoxRaw);
panel.Children.Add(stringBoxExp);
}
private static void BinaryPreview_SelectorChanged(SelectorBar sender, SelectorBarSelectionChangedEventArgs args)
{
// Child controls: 0 = SelectorBar, 1 = ProgressRing, 2 = HexBox, 3 = TextBox
var stackPanel = sender.Parent as StackPanel;
var progressRing = (ProgressRing)stackPanel.Children[1];
var hexBox = (HB.HexBox)stackPanel.Children[2];
var textBox = (TextBox)stackPanel.Children[3];
if (sender.SelectedItem.Tag.ToString() == "DataView")
{
textBox.Visibility = Visibility.Collapsed;
if (_isDataPreviewHexBoxLoaded)
{
progressRing.Visibility = Visibility.Collapsed;
hexBox.Visibility = Visibility.Visible;
// Clear selection aligned to TextBox
hexBox.ClearSelection();
hexBox.Focus(FocusState.Programmatic);
}
else
{
hexBox.Visibility = Visibility.Collapsed;
progressRing.Visibility = Visibility.Visible;
progressRing.Focus(FocusState.Programmatic);
}
}
else
{
progressRing.Visibility = Visibility.Collapsed;
hexBox.Visibility = Visibility.Collapsed;
textBox.Visibility = Visibility.Visible;
// Workaround for wrong text selection (color) after switching back to "Visible text"
textBox.Focus(FocusState.Programmatic);
textBox.Select(0, 0);
}
}
private static void BinaryPreview_HexBoxLoaded(object sender, RoutedEventArgs e)
{
_isDataPreviewHexBoxLoaded = true;
// Child controls: 0 = SelectorBar, 1 = ProgressRing, 2 = HexBox, 3 = TextBox
var hexBox = (HB.HexBox)sender;
var stackPanel = hexBox.Parent as StackPanel;
var selectorBar = stackPanel.Children[0] as SelectorBar;
var progressRing = stackPanel.Children[1] as ProgressRing;
if (selectorBar.SelectedItem.Tag.ToString() == "DataView")
{
progressRing.Visibility = Visibility.Collapsed;
hexBox.Visibility = Visibility.Visible;
}
}
/// <summary>
/// Event handler to set correct control border if focused.
/// </summary>
private static void BinaryPreview_HexBoxFocused(object sender, RoutedEventArgs e)
{
var hexBox = (HB.HexBox)sender;
hexBox.BorderThickness = (Thickness)Application.Current.Resources["HexBox_ControlBorderFocusedThickness"];
hexBox.BorderBrush = (LinearGradientBrush)Application.Current.Resources["HexBox_ControlBorderFocusedBrush"];
}
/// <summary>
/// Event handler to set correct control border if not focused.
/// </summary>
private static void BinaryPreview_HexBoxFocusLost(object sender, RoutedEventArgs e)
{
var hexBox = (HB.HexBox)sender;
// Workaround: Verify that the newly focused control isn't the context menu of the HexBox control
if (FocusManager.GetFocusedElement(hexBox.XamlRoot).GetType() != typeof(MenuFlyoutPresenter))
{
hexBox.BorderThickness = (Thickness)Application.Current.Resources["HexBox_ControlBorderThickness"];
hexBox.BorderBrush = (LinearGradientBrush)Application.Current.Resources["HexBox_ControlBorderBrush"];
}
}
/// <summary>
/// Make sure that for REG_Binary preview the HexBox control is focused after opening.
/// </summary>
private static void ExtendedDataPreview_Opened(ContentDialog sender, ContentDialogOpenedEventArgs e)
{
// If <_isDataPreviewHexBoxLoaded == true> then we have the right content on the dialog.
if (_isDataPreviewHexBoxLoaded)
{
// Child controls: 0 = SelectorBar, 1 = ProgressRing, 2 = HexBox, 3 = TextBox
(sender.Content as StackPanel).Children[2].Focus(FocusState.Programmatic);
}
}
}
}

View File

@@ -8,7 +8,6 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using CommunityToolkit.WinUI.UI.Controls;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
@@ -23,6 +22,10 @@ namespace RegistryPreviewUILib
{
private readonly DispatcherQueue _dispatcherQueue = DispatcherQueue.GetForCurrentThread();
// Indicator if we loaded/reloaded/saved a file and need to skip TextChanged event one time.
// (Solves the problem that enabling the event handler fires it one time.)
private static bool editorContentChangedScripted;
/// <summary>
/// Event that is will prevent the app from closing if the "save file" flag is active
/// </summary>
@@ -77,6 +80,67 @@ namespace RegistryPreviewUILib
MonacoEditor.Focus(FocusState.Programmatic);
}
/// <summary>
/// New button action: Ask to save last changes and reset editor content to reg header only
/// </summary>
private async void NewButton_Click(object sender, RoutedEventArgs e)
{
// Check to see if the current file has been saved
if (saveButton.IsEnabled)
{
ContentDialog contentDialog = new ContentDialog()
{
Title = resourceLoader.GetString("YesNoCancelDialogTitle"),
Content = resourceLoader.GetString("YesNoCancelDialogContent"),
PrimaryButtonText = resourceLoader.GetString("YesNoCancelDialogPrimaryButtonText"),
SecondaryButtonText = resourceLoader.GetString("YesNoCancelDialogSecondaryButtonText"),
CloseButtonText = resourceLoader.GetString("YesNoCancelDialogCloseButtonText"),
DefaultButton = ContentDialogButton.Primary,
};
// Use this code to associate the dialog to the appropriate AppWindow by setting
// the dialog's XamlRoot to the same XamlRoot as an element that is already present in the AppWindow.
if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8))
{
contentDialog.XamlRoot = this.Content.XamlRoot;
}
ContentDialogResult contentDialogResult = await contentDialog.ShowAsync();
switch (contentDialogResult)
{
case ContentDialogResult.Primary:
// Save, then continue the new action
if (!AskFileName(string.Empty) ||
!SaveFile())
{
return;
}
break;
case ContentDialogResult.Secondary:
// Don't save and continue the new action!
break;
default:
// Don't open the new action!
return;
}
}
// mute the TextChanged handler to make for clean UI
MonacoEditor.TextChanged -= MonacoEditor_TextChanged;
// reset editor, file info and ui.
_appFileName = string.Empty;
ResetEditorAndFile();
// disable buttons that do not make sense
UpdateUnsavedFileState(false);
refreshButton.IsEnabled = false;
// restore the TextChanged handler
ButtonAction_RestoreTextChangedEvent();
}
/// <summary>
/// Uses a picker to select a new file to open
/// </summary>
@@ -107,11 +171,15 @@ namespace RegistryPreviewUILib
{
case ContentDialogResult.Primary:
// Save, then continue the file open
SaveFile();
if (!AskFileName(string.Empty) ||
!SaveFile())
{
return;
}
break;
case ContentDialogResult.Secondary:
// Don't save and continue the file open!
saveButton.IsEnabled = false;
break;
default:
// Don't open the new file!
@@ -138,14 +206,16 @@ namespace RegistryPreviewUILib
{
// mute the TextChanged handler to make for clean UI
MonacoEditor.TextChanged -= MonacoEditor_TextChanged;
// update file name
_appFileName = storageFile.Path;
UpdateToolBarAndUI(await OpenRegistryFile(_appFileName));
// disable the Save button as it's a new file
saveButton.IsEnabled = false;
UpdateUnsavedFileState(false);
// Restore the event handler as we're loaded
MonacoEditor.TextChanged += MonacoEditor_TextChanged;
ButtonAction_RestoreTextChangedEvent();
}
}
@@ -154,7 +224,14 @@ namespace RegistryPreviewUILib
/// </summary>
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
SaveFile();
if (!AskFileName(string.Empty))
{
return;
}
// save and update window title
// error handling and ui update happens in SaveFile() method
_ = SaveFile();
}
/// <summary>
@@ -162,47 +239,24 @@ namespace RegistryPreviewUILib
/// </summary>
private async void SaveAsButton_Click(object sender, RoutedEventArgs e)
{
// Save out a new REG file and then open it - we have to use the direct Win32 method because FileOpenPicker crashes when it's
// called while running as admin
IntPtr windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(_mainWindow);
string filename = SaveFilePicker.ShowDialog(
windowHandle,
resourceLoader.GetString("SuggestFileName"),
resourceLoader.GetString("FilterRegistryName") + '\0' + "*.reg" + '\0' + resourceLoader.GetString("FilterAllFiles") + '\0' + "*.*" + '\0' + '\0',
resourceLoader.GetString("SaveDialogTitle"));
// mute the TextChanged handler to make for clean UI
MonacoEditor.TextChanged -= MonacoEditor_TextChanged;
if (filename == string.Empty)
if (!AskFileName(_appFileName) || !SaveFile())
{
return;
}
_appFileName = filename;
SaveFile();
UpdateToolBarAndUI(await OpenRegistryFile(_appFileName));
// restore the TextChanged handler
ButtonAction_RestoreTextChangedEvent();
}
/// <summary>
/// Reloads the current REG file from storage
/// </summary>
private async void RefreshButton_Click(object sender, RoutedEventArgs e)
{
// mute the TextChanged handler to make for clean UI
MonacoEditor.TextChanged -= MonacoEditor_TextChanged;
// reload the current Registry file and update the toolbar accordingly.
UpdateToolBarAndUI(await OpenRegistryFile(_appFileName), true, true);
// disable the Save button as it's a new file
saveButton.IsEnabled = false;
// restore the TextChanged handler
MonacoEditor.TextChanged += MonacoEditor_TextChanged;
}
/// <summary>
/// Resets the editor content
/// </summary>
private async void NewButton_Click(object sender, RoutedEventArgs e)
{
// Check to see if the current file has been saved
if (saveButton.IsEnabled)
@@ -210,10 +264,9 @@ namespace RegistryPreviewUILib
ContentDialog contentDialog = new ContentDialog()
{
Title = resourceLoader.GetString("YesNoCancelDialogTitle"),
Content = resourceLoader.GetString("YesNoCancelDialogContent"),
PrimaryButtonText = resourceLoader.GetString("YesNoCancelDialogPrimaryButtonText"),
SecondaryButtonText = resourceLoader.GetString("YesNoCancelDialogSecondaryButtonText"),
CloseButtonText = resourceLoader.GetString("YesNoCancelDialogCloseButtonText"),
Content = resourceLoader.GetString("ReloadDialogContent"),
PrimaryButtonText = resourceLoader.GetString("ReloadDialogPrimaryButtonText"),
CloseButtonText = resourceLoader.GetString("ReloadDialogCloseButtonText"),
DefaultButton = ContentDialogButton.Primary,
};
@@ -228,15 +281,10 @@ namespace RegistryPreviewUILib
switch (contentDialogResult)
{
case ContentDialogResult.Primary:
// Save, then continue the file open
SaveFile();
break;
case ContentDialogResult.Secondary:
// Don't save and continue the file open!
saveButton.IsEnabled = false;
// Don't save and continue the reload action!
break;
default:
// Don't open the new file!
// Don't continue the reload action!
return;
}
}
@@ -244,16 +292,14 @@ namespace RegistryPreviewUILib
// mute the TextChanged handler to make for clean UI
MonacoEditor.TextChanged -= MonacoEditor_TextChanged;
// reset editor, file info and ui.
_appFileName = string.Empty;
ResetEditorAndFile();
// reload the current Registry file and update the toolbar accordingly.
UpdateToolBarAndUI(await OpenRegistryFile(_appFileName), true, true);
// disable the Save button as it's a new file
UpdateUnsavedFileState(false);
// restore the TextChanged handler
MonacoEditor.TextChanged += MonacoEditor_TextChanged;
// disable buttons that do not make sense
saveButton.IsEnabled = false;
refreshButton.IsEnabled = false;
ButtonAction_RestoreTextChangedEvent();
}
/// <summary>
@@ -314,15 +360,20 @@ namespace RegistryPreviewUILib
switch (contentDialogResult)
{
case ContentDialogResult.Primary:
// Save, then continue the file open
SaveFile();
// Save, then continue the merge action
if (!AskFileName(string.Empty) ||
!SaveFile())
{
return;
}
break;
case ContentDialogResult.Secondary:
// Don't save and continue the file open!
saveButton.IsEnabled = false;
// Don't save and continue the merge action!
UpdateUnsavedFileState(false);
break;
default:
// Don't open the new file!
// Don't merge the file!
return;
}
}
@@ -412,8 +463,70 @@ namespace RegistryPreviewUILib
_dispatcherQueue.TryEnqueue(() =>
{
RefreshRegistryFile();
saveButton.IsEnabled = true;
if (!editorContentChangedScripted)
{
UpdateUnsavedFileState(true);
}
editorContentChangedScripted = false;
});
}
/// <summary>
/// Sets indicator for programatic text change and adds text changed handler
/// </summary>
/// <remarks>
/// Use this always, if button actions temporary disable the text changed event
/// </remarks>
private void ButtonAction_RestoreTextChangedEvent()
{
// Solves the problem that enabling the event handler fires it one time.
// These one time fired event would causes wrong unsaved changes state.
editorContentChangedScripted = true;
MonacoEditor.TextChanged += MonacoEditor_TextChanged;
}
// Commands to show data preview
public void ButtonExtendedPreview_Click(object sender, RoutedEventArgs e)
{
var data = ((Button)sender).DataContext as RegistryValue;
InvokeExtendedDataPreview(data);
}
public void MenuExtendedPreview_Click(object sender, RoutedEventArgs e)
{
var data = ((MenuFlyoutItem)sender).DataContext as RegistryValue;
InvokeExtendedDataPreview(data);
}
private async void InvokeExtendedDataPreview(RegistryValue valueData)
{
// Only one content dialog can be open at the same time and multiple instances of data preview can crash the app.
if (_dialogSemaphore.CurrentCount == 0)
{
return;
}
try
{
// Lock ui and request dialog lock
_dialogSemaphore.Wait();
ChangeCursor(gridPreview, true);
await ShowExtendedDataPreview(valueData.Name, valueData.Type, valueData.Value);
}
catch
{
#if DEBUG
throw;
#endif
}
finally
{
// Unblock ui and release dialog lock
ChangeCursor(gridPreview, false);
_dialogSemaphore.Release();
}
}
}
}

View File

@@ -11,6 +11,7 @@ using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.UI.Input;
@@ -24,7 +25,10 @@ namespace RegistryPreviewUILib
{
private const string NEWFILEHEADER = "Windows Registry Editor Version 5.00\r\n\r\n";
private static readonly string _unsavedFileIndicator = "* ";
private static readonly char[] _unsavedFileIndicatorChars = [' ', '*'];
private static SemaphoreSlim _dialogSemaphore = new(1);
private string lastKeyPath;
public delegate void UpdateWindowTitleFunction(string title);
@@ -503,6 +507,7 @@ namespace RegistryPreviewUILib
case "REG_NONE":
if (value.Length <= 0)
{
registryValue.IsEmptyBinary = true;
value = resourceLoader.GetString("ZeroLength");
}
else
@@ -831,42 +836,66 @@ namespace RegistryPreviewUILib
/// </summary>
private async void HandleDirtyClosing(string title, string content, string primaryButtonText, string secondaryButtonText, string closeButtonText)
{
ContentDialog contentDialog = new ContentDialog()
if (_dialogSemaphore.CurrentCount == 0)
{
Title = title,
Content = content,
PrimaryButtonText = primaryButtonText,
SecondaryButtonText = secondaryButtonText,
CloseButtonText = closeButtonText,
DefaultButton = ContentDialogButton.Primary,
};
// Use this code to associate the dialog to the appropriate AppWindow by setting
// the dialog's XamlRoot to the same XamlRoot as an element that is already present in the AppWindow.
if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8))
{
contentDialog.XamlRoot = this.Content.XamlRoot;
return;
}
ContentDialogResult contentDialogResult = await contentDialog.ShowAsync();
switch (contentDialogResult)
try
{
case ContentDialogResult.Primary:
// Save, then close
SaveFile();
break;
case ContentDialogResult.Secondary:
// Don't save, and then close!
saveButton.IsEnabled = false;
break;
default:
// Cancel closing!
return;
}
await _dialogSemaphore.WaitAsync();
// if we got here, we should try to close again
Application.Current.Exit();
ContentDialog contentDialog = new ContentDialog()
{
Title = title,
Content = content,
PrimaryButtonText = primaryButtonText,
SecondaryButtonText = secondaryButtonText,
CloseButtonText = closeButtonText,
DefaultButton = ContentDialogButton.Primary,
};
// Use this code to associate the dialog to the appropriate AppWindow by setting
// the dialog's XamlRoot to the same XamlRoot as an element that is already present in the AppWindow.
if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8))
{
contentDialog.XamlRoot = this.Content.XamlRoot;
}
ContentDialogResult contentDialogResult = await contentDialog.ShowAsync();
switch (contentDialogResult)
{
case ContentDialogResult.Primary:
// Save, then close
if (!AskFileName(string.Empty) ||
!SaveFile())
{
return;
}
break;
case ContentDialogResult.Secondary:
// Don't save, and then close!
UpdateUnsavedFileState(false);
break;
default:
// Cancel closing!
return;
}
// if we got here, we should try to close again
Application.Current.Exit();
}
catch
{
// Normally nothing to catch here.
// But for safety the try-catch ensures that we always release the content dialog lock and exit correctly.
}
finally
{
_dialogSemaphore.Release();
}
}
/// <summary>
@@ -926,11 +955,71 @@ namespace RegistryPreviewUILib
type.InvokeMember("ProtectedCursor", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance, null, uiElement, new object[] { cursor }, CultureInfo.InvariantCulture);
}
public void UpdateUnsavedFileState(bool unsavedChanges)
{
// get, cut and analyze the current title
string currentTitle = Regex.Replace(_mainWindow.Title, APPNAME + @"$|\s-\s" + APPNAME + @"$", string.Empty);
bool titleContainsIndicator = currentTitle.StartsWith(_unsavedFileIndicator, StringComparison.CurrentCultureIgnoreCase);
// update window title and save button state
if (unsavedChanges)
{
saveButton.IsEnabled = true;
if (!titleContainsIndicator)
{
_updateWindowTitleFunction(_unsavedFileIndicator + currentTitle);
}
}
else
{
saveButton.IsEnabled = false;
if (titleContainsIndicator)
{
_updateWindowTitleFunction(currentTitle.TrimStart(_unsavedFileIndicatorChars));
}
}
}
/// <summary>
/// Ask the user for the file path if it is unknown because of an unsaved file
/// </summary>
/// <param name="fileName">If not empty always ask for a file path and use the value as name.</param>
/// <returns>Returns true if user selected a path, otherwise false</returns>
public bool AskFileName(string fileName)
{
if (string.IsNullOrEmpty(_appFileName) || !string.IsNullOrEmpty(fileName) )
{
string fName = string.IsNullOrEmpty(fileName) ? resourceLoader.GetString("SuggestFileName") : fileName;
// Save out a new REG file and then open it - we have to use the direct Win32 method because FileOpenPicker crashes when it's
// called while running as admin
IntPtr windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(_mainWindow);
string filename = SaveFilePicker.ShowDialog(
windowHandle,
fName,
resourceLoader.GetString("FilterRegistryName") + '\0' + "*.reg" + '\0' + resourceLoader.GetString("FilterAllFiles") + '\0' + "*.*" + '\0' + '\0',
resourceLoader.GetString("SaveDialogTitle"));
if (filename == string.Empty)
{
return false;
}
_appFileName = filename;
}
return true;
}
/// <summary>
/// Wrapper method that saves the current file in place, using the current text in editor.
/// </summary>
private void SaveFile()
private bool SaveFile()
{
bool saveSuccess = true;
ChangeCursor(gridPreview, true);
// set up the FileStream for all writing
@@ -954,10 +1043,13 @@ namespace RegistryPreviewUILib
streamWriter.Close();
// only change when the save is successful
saveButton.IsEnabled = false;
UpdateUnsavedFileState(false);
_updateWindowTitleFunction(_appFileName);
}
catch (UnauthorizedAccessException ex)
{
saveSuccess = false;
// this exception is thrown if the file is there but marked as read only
ShowMessageBox(
resourceLoader.GetString("ErrorDialogTitle"),
@@ -966,6 +1058,8 @@ namespace RegistryPreviewUILib
}
catch
{
saveSuccess = false;
// this catch handles all other exceptions thrown when trying to write the file out
ShowMessageBox(
resourceLoader.GetString("ErrorDialogTitle"),
@@ -983,6 +1077,8 @@ namespace RegistryPreviewUILib
// restore the cursor
ChangeCursor(gridPreview, false);
return saveSuccess;
}
/// <summary>

View File

@@ -2,6 +2,7 @@
x:Class="RegistryPreviewUILib.RegistryPreviewMainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converter="using:CommunityToolkit.WinUI.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:RegistryPreviewUILib"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
@@ -10,6 +11,12 @@
xmlns:ui="using:CommunityToolkit.WinUI"
mc:Ignorable="d">
<Page.Resources>
<ResourceDictionary>
<converter:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
</ResourceDictionary>
</Page.Resources>
<Grid
x:Name="gridPreview"
Grid.Row="1"
@@ -178,7 +185,7 @@
Spacing="8">
<StackPanel.ContextFlyout>
<MenuFlyout>
<MenuFlyoutItem x:Uid="ContextMenu_CopyName" Command="{Binding Content.CopyToClipboardName_Click}" />
<MenuFlyoutItem x:Uid="ContextMenu_CopyKeyName" Command="{Binding Content.CopyToClipboardName_Click}" />
<MenuFlyoutItem x:Uid="ContextMenu_CopyKeyPath" Command="{Binding Content.CopyToClipboardKeyPath_Click}" />
</MenuFlyout>
</StackPanel.ContextFlyout>
@@ -225,10 +232,18 @@
Spacing="8">
<StackPanel.ContextFlyout>
<MenuFlyout>
<MenuFlyoutItem x:Uid="ContextMenu_CopyName" Command="{Binding CopyToClipboardName_Click}" />
<MenuFlyoutSeparator />
<MenuFlyoutItem
x:Uid="ContextMenu_CopyName"
Command="{Binding CopyToClipboardName_Click}"
Icon="Copy" />
<MenuFlyoutItem x:Uid="ContextMenu_CopyValue" Command="{Binding CopyToClipboardEntry_Click}" />
<MenuFlyoutItem x:Uid="ContextMenu_CopyValueWithPath" Command="{Binding CopyToClipboardWithPath_Click}" />
<MenuFlyoutSeparator />
<MenuFlyoutItem
x:Uid="ContextMenu_DataPreview"
Click="MenuExtendedPreview_Click"
Icon="Zoom"
IsEnabled="{Binding ShowPreviewButton}" />
</MenuFlyout>
</StackPanel.ContextFlyout>
<Image
@@ -255,10 +270,18 @@
<Setter Property="ContextFlyout">
<Setter.Value>
<MenuFlyout>
<MenuFlyoutItem x:Uid="ContextMenu_CopyType" Command="{Binding CopyToClipboardType_Click}" />
<MenuFlyoutSeparator />
<MenuFlyoutItem
x:Uid="ContextMenu_CopyType"
Command="{Binding CopyToClipboardType_Click}"
Icon="Copy" />
<MenuFlyoutItem x:Uid="ContextMenu_CopyValue" Command="{Binding CopyToClipboardEntry_Click}" />
<MenuFlyoutItem x:Uid="ContextMenu_CopyValueWithPath" Command="{Binding CopyToClipboardWithPath_Click}" />
<MenuFlyoutSeparator />
<MenuFlyoutItem
x:Uid="ContextMenu_DataPreview"
Click="MenuExtendedPreview_Click"
Icon="Zoom"
IsEnabled="{Binding ShowPreviewButton}" />
</MenuFlyout>
</Setter.Value>
</Setter>
@@ -274,20 +297,36 @@
<StackPanel
Margin="4"
VerticalAlignment="Center"
Orientation="Horizontal">
Orientation="Horizontal"
Spacing="6">
<StackPanel.ContextFlyout>
<MenuFlyout>
<MenuFlyoutItem x:Uid="ContextMenu_CopyData" Command="{Binding CopyToClipboardData_Click}" />
<MenuFlyoutSeparator />
<MenuFlyoutItem
x:Uid="ContextMenu_CopyData"
Command="{Binding CopyToClipboardData_Click}"
Icon="Copy" />
<MenuFlyoutItem x:Uid="ContextMenu_CopyValue" Command="{Binding CopyToClipboardEntry_Click}" />
<MenuFlyoutItem x:Uid="ContextMenu_CopyValueWithPath" Command="{Binding CopyToClipboardWithPath_Click}" />
<MenuFlyoutSeparator />
<MenuFlyoutItem
x:Uid="ContextMenu_DataPreview"
Click="MenuExtendedPreview_Click"
Icon="Zoom"
IsEnabled="{Binding ShowPreviewButton}" />
</MenuFlyout>
</StackPanel.ContextFlyout>
<Button
x:Uid="ShowDataPreviewButton"
Padding="2"
Click="ButtonExtendedPreview_Click"
Content="&#xe71e;"
FontFamily="{StaticResource SymbolThemeFontFamily}"
Visibility="{Binding ShowPreviewButton, Mode=OneWay, Converter={StaticResource BoolToVisibilityConverter}}" />
<TextBlock
VerticalAlignment="Center"
IsTabStop="False"
Style="{StaticResource CaptionTextBlockStyle}"
Text="{Binding ValueOneLine}"
ToolTipService.ToolTip="{Binding Value}" />
Text="{Binding ValueOneLine}" />
</StackPanel>
</DataTemplate>
</tk7controls:DataGridTemplateColumn.CellTemplate>

View File

@@ -40,7 +40,9 @@
</ItemGroup>
<ItemGroup>
<None Remove="MonacoEditorControl.xaml" />
<None Remove="Controls\MonacoEditor\MonacoEditorControl.xaml" />
<None Remove="Controls\HexBox\Themes\Generic.xaml" />
<None Remove="Themes\Generic.xaml" />
</ItemGroup>
<ItemGroup>
@@ -51,6 +53,7 @@
<PackageReference Include="CommunityToolkit.WinUI.Extensions" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" />
<PackageReference Include="Microsoft.WindowsAppSDK" />
<PackageReference Include="SkiaSharp.Views.WinUI" />
<Manifest Include="$(ApplicationManifest)" />
</ItemGroup>
@@ -59,10 +62,21 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Page Update="MonacoEditorControl.xaml">
<Page Update="Controls\MonacoEditor\MonacoEditorControl.xaml">
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Update="Controls\HexBox\Themes\Generic.xaml">
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Update="Themes\Generic.xaml">
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
<ItemGroup>
<Folder Include="Controls\MonacoEditor\" />
<Folder Include="Controls\HexBox\" />
</ItemGroup>
</Project>

View File

@@ -6,7 +6,6 @@ using System;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input;
using Microsoft.UI.Xaml;
using Windows.ApplicationModel.DataTransfer;
namespace RegistryPreviewUILib
{
@@ -29,6 +28,8 @@ namespace RegistryPreviewUILib
public string Value { get; set; }
public bool IsEmptyBinary { private get; set; }
public string ValueOneLine => Value.Replace('\r', ' ');
public string ToolTipText { get; set; }
@@ -54,6 +55,10 @@ namespace RegistryPreviewUILib
}
}
public bool ShowPreviewButton =>
Type != "ERROR" && Type != string.Empty &&
Value != string.Empty && IsEmptyBinary != true;
public RegistryValue(string name, string type, string value, string key)
{
this.Name = name;

View File

@@ -258,12 +258,18 @@
<data name="YesNoCancelDialogCloseButtonText" xml:space="preserve">
<value>Cancel</value>
</data>
<data name="ReloadDialogCloseButtonText" xml:space="preserve">
<value>No</value>
</data>
<data name="YesNoCancelDialogContent" xml:space="preserve">
<value>Save changes?</value>
</data>
<data name="YesNoCancelDialogPrimaryButtonText" xml:space="preserve">
<value>Save</value>
</data>
<data name="ReloadDialogPrimaryButtonText" xml:space="preserve">
<value>Yes</value>
</data>
<data name="YesNoCancelDialogSecondaryButtonText" xml:space="preserve">
<value>Don't save</value>
</data>
@@ -277,16 +283,20 @@
<value>Copy path</value>
<comment>Like "Copy item"</comment>
</data>
<data name="ContextMenu_CopyName.Text" xml:space="preserve">
<data name="ContextMenu_CopyKeyName.Text" xml:space="preserve">
<value>Copy name</value>
<comment>Like "Copy item"</comment>
</data>
<data name="ContextMenu_CopyName.Text" xml:space="preserve">
<value>Copy</value>
<comment>Like "Copy item"</comment>
</data>
<data name="ContextMenu_CopyType.Text" xml:space="preserve">
<value>Copy type</value>
<value>Copy</value>
<comment>Like "Copy item"</comment>
</data>
<data name="ContextMenu_CopyData.Text" xml:space="preserve">
<value>Copy data</value>
<value>Copy</value>
<comment>Like "Copy item"</comment>
</data>
<data name="ContextMenu_CopyValue.Text" xml:space="preserve">
@@ -297,7 +307,69 @@
<value>Copy value with key path</value>
<comment>Like "Copy item"</comment>
</data>
<data name="ShowDataPreviewButton.ToolTipService.ToolTip" xml:space="preserve">
<value>Show extended preview</value>
</data>
<data name="ShowDataPreviewButton.[using:Microsoft.UI.Xaml.Automation]AutomationProperties.Name" xml:space="preserve">
<value>Show extended preview</value>
</data>
<data name="DataPreviewTitle" xml:space="preserve">
<value>View data</value>
</data>
<data name="DataPreviewClose" xml:space="preserve">
<value>Close</value>
<comment>like "Close window"</comment>
</data>
<data name="DataPreviewHex" xml:space="preserve">
<value>Hexadecimal</value>
</data>
<data name="DataPreviewDec" xml:space="preserve">
<value>Decimal</value>
</data>
<data name="DataPreviewRawValue" xml:space="preserve">
<value>Raw value</value>
</data>
<data name="DataPreviewExpandedValue" xml:space="preserve">
<value>Expanded value</value>
</data>
<data name="DataPreviewVisibleText" xml:space="preserve">
<value>Readable text</value>
<comment>Means text that is human readable and not only control characters.</comment>
</data>
<data name="DataPreviewDataView" xml:space="preserve">
<value>Data</value>
<comment>Like "binary data"</comment>
</data>
<data name="DataPreview_AutomationPropertiesName_MultilineTextValue" xml:space="preserve">
<value>Multiline text value</value>
</data>
<data name="DataPreview_AutomationPropertiesName_TextValue" xml:space="preserve">
<value>Text value</value>
</data>
<data name="DataPreview_AutomationPropertiesName_BinaryDataPreview" xml:space="preserve">
<value>Binary data preview</value>
</data>
<data name="DataPreview_AutomationPropertiesName_VisibleTextPreview" xml:space="preserve">
<value>Preview of readable text</value>
</data>
<data name="HexBox_CopyCommand.Text" xml:space="preserve">
<value>Copy</value>
<comment>Like "copy the value"</comment>
</data>
<data name="HexBox_CopyTextCommand.Text" xml:space="preserve">
<value>Copy text</value>
<comment>Like "Copy the text"</comment>
</data>
<data name="HexBox_SelectAllCommand.Text" xml:space="preserve">
<value>Select all</value>
</data>
<data name="ContextMenu_DataPreview.Text" xml:space="preserve">
<value>Extended data preview</value>
</data>
<data name="NewButton.Label" xml:space="preserve">
<value>New</value>
</data>
<data name="ReloadDialogContent" xml:space="preserve">
<value>You lose any unsaved changes. Reload anyway?</value>
</data>
</root>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:RegistryPreviewUILib">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/PowerToys.RegistryPreviewUILib/Controls/HexBox/Themes/Generic.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

View File

@@ -40,7 +40,10 @@ namespace Microsoft.PowerToys.Settings.UI.Library
VisibleColorFormats.Add("Decimal", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("Decimal")));
VisibleColorFormats.Add("HEX Int", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("HEX Int")));
ShowColorName = false;
ActivationAction = ColorPickerActivationAction.OpenColorPickerAndThenEditor;
ActivationAction = ColorPickerActivationAction.OpenColorPicker;
PrimaryClickAction = ColorPickerClickAction.PickColorThenEditor;
MiddleClickAction = ColorPickerClickAction.PickColorAndClose;
SecondaryClickAction = ColorPickerClickAction.Close;
CopiedColorRepresentation = "HEX";
}
@@ -57,6 +60,15 @@ namespace Microsoft.PowerToys.Settings.UI.Library
[JsonPropertyName("activationaction")]
public ColorPickerActivationAction ActivationAction { get; set; }
[JsonPropertyName("primaryclickaction")]
public ColorPickerClickAction PrimaryClickAction { get; set; }
[JsonPropertyName("middleclickaction")]
public ColorPickerClickAction MiddleClickAction { get; set; }
[JsonPropertyName("secondaryclickaction")]
public ColorPickerClickAction SecondaryClickAction { get; set; }
// Property ColorHistory is not used, the color history is saved separately in the colorHistory.json file
[JsonPropertyName("colorhistory")]
[CmdConfigureIgnoreAttribute]

View File

@@ -25,7 +25,7 @@ namespace Microsoft.PowerToys.Settings.UI.Library
VisibleColorFormats.Add("RGB", true);
VisibleColorFormats.Add("HSL", true);
ShowColorName = false;
ActivationAction = ColorPickerActivationAction.OpenColorPickerAndThenEditor;
ActivationAction = ColorPickerActivationAction.OpenColorPicker;
}
public HotkeySettings ActivationShortcut { get; set; }

View File

@@ -9,6 +9,7 @@ using System.Text.Json;
using System.Text.Json.Serialization;
using ManagedCommon;
using Microsoft.PowerToys.Settings.UI.Library.Enumerations;
using Microsoft.PowerToys.Settings.UI.Library.Interfaces;
namespace Microsoft.PowerToys.Settings.UI.Library
@@ -23,7 +24,7 @@ namespace Microsoft.PowerToys.Settings.UI.Library
public ColorPickerSettings()
{
Properties = new ColorPickerProperties();
Version = "2";
Version = "2.1";
Name = ModuleName;
}
@@ -47,7 +48,21 @@ namespace Microsoft.PowerToys.Settings.UI.Library
// This can be utilized in the future if the settings.json file is to be modified/deleted.
public bool UpgradeSettingsConfiguration()
=> false;
{
// Upgrading V1 to V2 doesn't set the version to 2.0, therefore V2 settings still report Version == 1.0
if (Version == "1.0")
{
if (!Enum.IsDefined(Properties.ActivationAction))
{
Properties.ActivationAction = ColorPickerActivationAction.OpenColorPicker;
}
Version = "2.1";
return true;
}
return false;
}
public static object UpgradeSettings(object oldSettingsObject)
{

View File

@@ -9,10 +9,7 @@ namespace Microsoft.PowerToys.Settings.UI.Library.Enumerations
// Activation shortcut opens editor
OpenEditor,
// Activation shortcut opens color picker and after picking a color is copied into clipboard and opens editor
OpenColorPickerAndThenEditor,
// Activation shortcut opens color picker only and picking color copies color into clipboard
OpenOnlyColorPicker,
// Activation shortcut opens color picker and after picking a color is copied into clipboard and editor optionally opens depending on which mouse button was pressed
OpenColorPicker,
}
}

View File

@@ -0,0 +1,18 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.PowerToys.Settings.UI.Library.Enumerations
{
public enum ColorPickerClickAction
{
// Clicking copies the picked color and opens the editor
PickColorThenEditor,
// Clicking only copies the picked color and then exits color picker
PickColorAndClose,
// Clicking exits color picker, without copying anything
Close,
}
}

View File

@@ -130,6 +130,13 @@ namespace Microsoft.PowerToys.Settings.UI.Library
T2 oldSettings = GetSettings<T2>(powertoy, fileName);
T newSettings = (T)settingsUpgrader(oldSettings);
Logger.LogInfo($"Settings file {fileName} for {powertoy} was read successfully in the old format.");
// If the file needs to be modified, to save the new configurations accordingly.
if (newSettings.UpgradeSettingsConfiguration())
{
SaveSettings(newSettings.ToJsonString(), powertoy, fileName);
}
return newSettings;
}
catch (Exception)

View File

@@ -50,12 +50,39 @@
<tkcontrols:SettingsCard x:Uid="ColorPicker_ActivationAction" HeaderIcon="{ui:FontIcon Glyph=&#xEC4E;}">
<ComboBox MinWidth="{StaticResource SettingActionControlMinWidth}" SelectedIndex="{x:Bind Path=ViewModel.ActivationBehavior, Mode=TwoWay}">
<ComboBoxItem x:Uid="EditorFirst" />
<ComboBoxItem x:Uid="ColorPickerFirst" />
<ComboBoxItem x:Uid="ColorPickerOnly" />
<ComboBoxItem x:Uid="ColorPicker_OpenEditor" />
<ComboBoxItem x:Uid="ColorPicker_PickColor" />
</ComboBox>
</tkcontrols:SettingsCard>
<tkcontrols:SettingsExpander
x:Uid="ColorPicker_MouseActions"
HeaderIcon="{ui:FontIcon Glyph=&#xE962;}"
IsEnabled="{x:Bind ViewModel.IsEnabled, Mode=OneWay}">
<tkcontrols:SettingsExpander.Items>
<tkcontrols:SettingsCard x:Uid="ColorPicker_PrimaryClick" IsEnabled="{x:Bind ViewModel.IsEnabled, Mode=OneWay}">
<ComboBox MinWidth="{StaticResource SettingActionControlMinWidth}" SelectedIndex="{x:Bind ViewModel.PrimaryClickBehavior, Mode=TwoWay}">
<ComboBoxItem x:Uid="ColorPicker_PickColorThenEditor" />
<ComboBoxItem x:Uid="ColorPicker_PickColorAndClose" />
<ComboBoxItem x:Uid="ColorPicker_Close" />
</ComboBox>
</tkcontrols:SettingsCard>
<tkcontrols:SettingsCard x:Uid="ColorPicker_MiddleClick" IsEnabled="{x:Bind ViewModel.IsEnabled, Mode=OneWay}">
<ComboBox MinWidth="{StaticResource SettingActionControlMinWidth}" SelectedIndex="{x:Bind ViewModel.MiddleClickBehavior, Mode=TwoWay}">
<ComboBoxItem x:Uid="ColorPicker_PickColorThenEditor" />
<ComboBoxItem x:Uid="ColorPicker_PickColorAndClose" />
<ComboBoxItem x:Uid="ColorPicker_Close" />
</ComboBox>
</tkcontrols:SettingsCard>
<tkcontrols:SettingsCard x:Uid="ColorPicker_SecondaryClick" IsEnabled="{x:Bind ViewModel.IsEnabled, Mode=OneWay}">
<ComboBox MinWidth="{StaticResource SettingActionControlMinWidth}" SelectedIndex="{x:Bind ViewModel.SecondaryClickBehavior, Mode=TwoWay}">
<ComboBoxItem x:Uid="ColorPicker_PickColorThenEditor" />
<ComboBoxItem x:Uid="ColorPicker_PickColorAndClose" />
<ComboBoxItem x:Uid="ColorPicker_Close" />
</ComboBox>
</tkcontrols:SettingsCard>
</tkcontrols:SettingsExpander.Items>
</tkcontrols:SettingsExpander>
</controls:SettingsGroup>
<controls:SettingsGroup x:Uid="ColorFormats" IsEnabled="{x:Bind ViewModel.IsEnabled, Mode=OneWay}">

View File

@@ -1507,18 +1507,39 @@ Made with 💗 by Microsoft and the PowerToys community.</value>
<data name="ColorPicker_CopiedColorRepresentation.Header" xml:space="preserve">
<value>Default color format</value>
</data>
<data name="ColorPickerFirst.Content" xml:space="preserve">
<value>Pick a color and open editor</value>
</data>
<data name="EditorFirst.Content" xml:space="preserve">
<value>Open editor</value>
</data>
<data name="ColorPickerOnly.Content" xml:space="preserve">
<value>Only pick a color</value>
</data>
<data name="ColorPicker_ActivationAction.Header" xml:space="preserve">
<value>Activation behavior</value>
</data>
<data name="ColorPicker_OpenEditor.Content" xml:space="preserve">
<value>Open editor</value>
</data>
<data name="ColorPicker_PickColor.Content" xml:space="preserve">
<value>Pick a color first</value>
</data>
<data name="ColorPicker_MouseActions.Header" xml:space="preserve">
<value>Mouse actions</value>
</data>
<data name="ColorPicker_MouseActions.Description" xml:space="preserve">
<value>Choose what clicking individual buttons does</value>
</data>
<data name="ColorPicker_PrimaryClick.Header" xml:space="preserve">
<value>Primary click</value>
</data>
<data name="ColorPicker_MiddleClick.Header" xml:space="preserve">
<value>Middle click</value>
</data>
<data name="ColorPicker_SecondaryClick.Header" xml:space="preserve">
<value>Secondary click</value>
</data>
<data name="ColorPicker_PickColorThenEditor.Content" xml:space="preserve">
<value>Pick a color and open editor</value>
</data>
<data name="ColorPicker_PickColorAndClose.Content" xml:space="preserve">
<value>Pick a color and close</value>
</data>
<data name="ColorPicker_Close.Content" xml:space="preserve">
<value>Close</value>
</data>
<data name="ColorFormats.Header" xml:space="preserve">
<value>Picker behavior</value>
</data>

View File

@@ -182,6 +182,51 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
}
}
public int PrimaryClickBehavior
{
get => (int)_colorPickerSettings.Properties.PrimaryClickAction;
set
{
if (value != (int)_colorPickerSettings.Properties.PrimaryClickAction)
{
_colorPickerSettings.Properties.PrimaryClickAction = (ColorPickerClickAction)value;
OnPropertyChanged(nameof(PrimaryClickBehavior));
NotifySettingsChanged();
}
}
}
public int MiddleClickBehavior
{
get => (int)_colorPickerSettings.Properties.MiddleClickAction;
set
{
if (value != (int)_colorPickerSettings.Properties.MiddleClickAction)
{
_colorPickerSettings.Properties.MiddleClickAction = (ColorPickerClickAction)value;
OnPropertyChanged(nameof(MiddleClickBehavior));
NotifySettingsChanged();
}
}
}
public int SecondaryClickBehavior
{
get => (int)_colorPickerSettings.Properties.SecondaryClickAction;
set
{
if (value != (int)_colorPickerSettings.Properties.SecondaryClickAction)
{
_colorPickerSettings.Properties.SecondaryClickAction = (ColorPickerClickAction)value;
OnPropertyChanged(nameof(SecondaryClickBehavior));
NotifySettingsChanged();
}
}
}
public bool ShowColorName
{
get => _colorPickerSettings.Properties.ShowColorName;