Compare commits

..

29 Commits

Author SHA1 Message Date
Niels Laute
aab26c35f7 Update src/settings-ui/Settings.UI/Strings/en-us/Resources.resw 2025-08-20 16:37:59 +02:00
copilot-swe-agent[bot]
8b8268b703 Add localization prevention comments for remaining Awake product name instances
Co-authored-by: niels9001 <9866362+niels9001@users.noreply.github.com>
2025-08-19 12:12:43 +00:00
copilot-swe-agent[bot]
d293162ccb Fix Spanish translation for Awake module name
Co-authored-by: niels9001 <9866362+niels9001@users.noreply.github.com>
2025-08-19 11:27:31 +00:00
copilot-swe-agent[bot]
f94471a6fa Initial plan 2025-08-19 11:16:42 +00:00
Jiří Polášek
fa741470bc CmdPal: Add local keyboard listener and use it to handle GoBack key (#41122)
## Summary of the Pull Request

Listener registers a hook on WH_KEYBOARD and raises an event when a key
is pressed down. Main window then uses it to handle the GoBack key that
we can't reach any other way.


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

- [x] Related to: #41011
- [ ] **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-08-19 05:54:27 -05:00
Deniz
446d8087a3 Update readme.md (#41150)
<!-- 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 link to styling in developer documentation was not working. The path
was wrong.
<!-- 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
- [x] **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-08-19 05:17:01 -05:00
Niels Laute
a0a8ce9f69 Adding Office / Copilot templates to KeyVisual (#41167)
Small change for #41161. For shortcuts in Settings, I guess we need to
figure out later how the Copilot/Office keys are mapped in our
shortcuts, but at least we have the right visual templates available.
2025-08-19 11:32:28 +02:00
Jiří Polášek
7b06fb3bdb CmdPal: Remove constrain that keeps the context menu flyout in the bounds of the window (#41133)
## Summary of the Pull Request

Added `ShouldConstrainToRootBounds="False"` to the Flyout element,
allowing it to extend beyond the bounds of its parent container. This
allows the menu to always open with top-left corner at the cursor
position as is common for the context menus.

This affects the menu only when opened as a context menu on the list
item (e.g. mouse right-click), not when opened from the Command Bar
(that opens same as before).

After screenshot:

<img width="834" height="589" alt="image"
src="https://github.com/user-attachments/assets/acb40e08-074e-4bae-afe7-87c6a73a6581"
/>


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

- [x] Closes: #41131 
- [ ] **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-08-19 14:32:16 +08:00
Mohammed Saalim K
6130d2ad39 Hosts: add “No leading spaces” option and honor it when saving (#41206)
## Summary of the Pull Request

Adds a new Hosts File Editor setting “No leading spaces” that prevents
prepending spaces to active lines when saving the hosts file (when any
entry is disabled). Default is Off to preserve current behavior.



## PR Checklist

- [x] Closes: #36386  

- [ ] Communication: N/A (small, scoped option)

- [x] Tests: Added/updated and all pass

- [x] Localization: New en-US strings added; other locales handled by
loc pipeline

- [ ] Dev docs: N/A

- [x] New binaries: None

- [x] Documentation updated: N/A



## Detailed Description of the Pull Request / Additional comments

- Settings surface:

  - `src/settings-ui/Settings.UI.Library/HostsProperties.cs`: add
`NoLeadingSpaces`

  - `src/modules/Hosts/HostsUILib/Settings/IUserSettings.cs`: add
`NoLeadingSpaces`

  - `src/modules/Hosts/Hosts/Settings/UserSettings.cs`: load/save value
from settings.json

  - `src/settings-ui/Settings.UI/ViewModels/HostsViewModel.cs`: expose
`NoLeadingSpaces`

  - `src/settings-ui/Settings.UI/SettingsXAML/Views/HostsPage.xaml`: new
SettingsCard toggle

  - `src/settings-ui/Settings.UI/Strings/en-us/Resources.resw`: add
`Hosts_NoLeadingSpaces.Header/Description`

- Writer change:

  - `src/modules/Hosts/HostsUILib/Helpers/HostsService.cs`: gate indent
with `anyDisabled && !_userSettings.NoLeadingSpaces`

- Tests:

  - `src/modules/Hosts/Hosts.Tests/HostsServiceTest.cs`:
`NoLeadingSpaces_Disabled_RemovesIndent`



Backward compatibility: default Off, current formatting unchanged unless
the user enables the option.



## Validation Steps Performed

- Automated: `HostsEditor.UnitTests` including
`NoLeadingSpaces_Disabled_RemovesIndent` passing.

- Manual:

  1. Run PowerToys (runner) as Admin.

  2. Settings → Hosts File Editor → enable “No leading spaces”.

  3. In editor, add active `127.0.0.10 example1` and disabled
`127.0.0.11 example2`; Save.

  4. Open `C:\Windows\System32\drivers\etc\hosts` in Notepad.

     - ON: active line starts at column 0; disabled is `# 127...`.

     - OFF: active line begins with two spaces when a disabled entry
exists.
2025-08-19 13:58:10 +08:00
Mike Griese
8737de29af CmdPal: mark CommandProvider.Dispose as virtual (#41184)
If your provider wants to implement this, they should be able to
2025-08-18 16:52:49 -05:00
Mike Griese
2f6876b85f CmdPal: Add a couple evil samples for testing (#41158)
This doesn't fix any bugs, it just makes them easier to repro

RE: #38190
RE: #41149
also accidentally a great example for RE: #39837
2025-08-18 16:46:36 -05:00
Jiří Polášek
8f93d0269f CmdPal: Honor "Single-click activation" only for pointer clicks and not for keyboard (#41119)
## Summary of the Pull Request

Changes the behavior of keyboard item activation when the item list view
has focus.
Previously, the list view handled item activation according to the
"Single-click activation" setting regardless of the input source (mouse,
pen, touch, or keyboard).

Now, when handling a ListView item click, the input source is detected,
and the "Single-click activation" setting is applied only for
pointer-raised clicks. For keyboard-triggered clicks, items are always
activated immediately.

Since the event `ListView.ItemClick` doesn't provide information about
what caused the item activation, this PR work around that by observing
last user input on the list immediately before `ItemClick` event is
invoked.

## PR Checklist

- [x] Closes: #41101
- [ ] **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-08-18 16:46:08 -05:00
Jiří Polášek
d2a4c96e12 CmdPal: Prevent disposed ContentPage from handling messages (#41083)
## Summary of the Pull Request

Changes the timing of when `ContentPage` registers to messages from the
Toolkit Messenger so it happens only when navigated to, mirroring the
unregister on navigation from. Also unregisters from all messages when
unloaded.

Proactively unregisters the Settings window from all messages on close
instead of relying on the GC’s nondeterministic cleanup. Since the
Settings window is newly created each time, old instances can still
react to messages even after their time is over, merely waiting for GC
to collect them.

Co-authored-by: zadjii-msft <migrie@microsoft.com>


## PR Checklist

- [x] Closes: #40846 
- [ ] **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-08-18 11:45:25 -05:00
Jiří Polášek
409ae3d73a CmdPal: Improve page exception details for users (#41035)
## Summary of the Pull Request

Show timestamp, HRESULT (hex/decimal), and full Exception.ToString() in
the error message. Centralize message generation in a helper class for
consistency.

Example:

```
============================================================
😢 An unexpected error occurred in the 'Open' extension.

Summary:
  Message:    Operation is not valid due to the current state of the object. (inferred from HRESULT 0x80131509)
  Type:       System.Runtime.InteropServices.COMException
  Source:     WinRT.Runtime
  Time:       2025-08-07 15:54:20.4189499
  HRESULT:    0x80131509 (-2146233079)

Stack Trace:
   at WinRT.ExceptionHelpers.<ThrowExceptionForHR>g__Throw|38_0(Int32 hr)
   at ABI.Microsoft.CommandPalette.Extensions.IListPageMethods.GetItems(IObjectReference _obj)
   at Microsoft.CmdPal.Core.ViewModels.ListViewModel.FetchItems()
   at Microsoft.CmdPal.Core.ViewModels.ListViewModel.InitializeProperties()
   at Microsoft.CmdPal.Core.ViewModels.PageViewModel.InitializeAsync()

------------------ Full Exception Details ------------------
System.Runtime.InteropServices.COMException (0x80131509)
   at WinRT.ExceptionHelpers.<ThrowExceptionForHR>g__Throw|38_0(Int32 hr)
   at ABI.Microsoft.CommandPalette.Extensions.IListPageMethods.GetItems(IObjectReference _obj)
   at Microsoft.CmdPal.Core.ViewModels.ListViewModel.FetchItems()
   at Microsoft.CmdPal.Core.ViewModels.ListViewModel.InitializeProperties()
   at Microsoft.CmdPal.Core.ViewModels.PageViewModel.InitializeAsync()

ℹ️ If you need further assistance, please include this information in your support request.
ℹ️ Before sending, take a quick look to make sure it doesn't contain any personal or sensitive information.
============================================================

```

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

- [x] Closes: #41034
- [ ] **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

## Validation Steps Performed

I crashed an extension on purpose and read the message.
2025-08-18 11:31:41 -05:00
Heiko
65b752b3ff [CmdPal > Ext] Use empty content for WindowWalker, Windows Settings and Windows Search (#40722)
<!-- 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 improves the behavior of CmdPal on empty or wrong search query
for the following exts:
- Window Walker
- Windows Settings
- Windows Search (indexer)

### Window Walker
<img width="795" height="482" alt="image"
src="https://github.com/user-attachments/assets/352a122d-2b8f-45be-bf49-6a56f6ca0848"
/>

### Windows Settings - Empty query
<img width="796" height="485" alt="image"
src="https://github.com/user-attachments/assets/12f193b3-22c5-45d8-89c0-bba5740da62b"
/>

### Windows Settings - No search match
<img width="855" height="483" alt="image"
src="https://github.com/user-attachments/assets/e521f63d-65ae-4b93-992d-2bb0a11edaa7"
/>

### Windows search (indexer)
<img width="796" height="483" alt="image"
src="https://github.com/user-attachments/assets/c2e6a218-de2b-4657-a9e7-9def26c9258e"
/>



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

- [x] **Closes:** #40614 , #38293 , #40565
- [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
- [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

---------

Co-authored-by: Niels Laute <niels.laute@live.nl>
Co-authored-by: Mike Griese <migrie@microsoft.com>
2025-08-18 11:22:26 -05:00
Michael Jolley
6acb793184 CmdPal: Null pattern matching based on is expression rather than overridable operators (#40972)
What the title says. 😄 

Rather than relying on the potentially overloaded `!=` or `==` operators
when checking for null, now we'll use the `is` expression (possibly
combined with the `not` operator) to ensure correct checking. Probably
overkill for many of these classes, but decided to err on the side of
consistency. Would matter more on classes that may be inherited or
extended.

Using `is` and `is not` will provide us a guarantee that no
user-overloaded equality operators (`==`/`!=`) is invoked when a
`expression is null` is evaluated.

In code form, changed all instances of:

```c#
something != null

something == null
```

to:

```c#
something is not null

something is null
```

The one exception was checking null on a `KeyChord`. `KeyChord` is a
struct which is never null so VS will raise an error when trying this
versus just providing a warning when using `keyChord != null`. In
reality, we shouldn't do this check because it can't ever be null. In
the case of a `KeyChord` it **would** be a `KeyChord` equivalent to:

```c#
KeyChord keyChord = new ()
{
    Modifiers = 0,
    Vkey = 0,
    ScanCode = 0
};
```
2025-08-18 06:07:28 -05:00
Dustin L. Howett
efb48aa163 build: remove *tests* and all coverage/DIA DLLs from binskim (#41108)
This thing files about 900 bugs a month on us.

Before:

```
Done. 11,036 files scanned.
```

After:

```
Done. 4,753 files scanned.
```
2025-08-18 06:00:13 -05:00
leileizhang
e8754e4cd6 Fix: Move ImageResizer satellite resource dlls under WinUI3Apps<culture> (#41152)
<!-- 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
### Root cause:
Problem Previously the installer installed ImageResizer satellite
assemblies into [INSTALLFOLDER]<culture>*.dll. The runtime probes
WinUI3Apps<culture>\ for WinUI3 app resource assemblies, so localization
failed.

### Fix:
Updated Resources.wxs: ImageResizer_$(var.IdSafeLanguage)_Component now
targets
Directory="Resource$(var.IdSafeLanguage)WinUI3AppsInstallFolder".

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

- [x] Closes: #41142
- [ ] **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

## AI Summary
This pull request updates the installer configuration in `Resources.wxs`
to support resource management for WinUI 3 apps. The main changes ensure
that resource directories and uninstall logic properly handle the new
`WinUI3AppsInstallFolder`, and update the component registration for
localized resources.

**Installer resource management updates:**

* Added `WinUI3AppsInstallFolder` to the list of parent directories for
resource file generation, ensuring resources for WinUI 3 apps are
included during installer builds.

**Component and uninstall logic updates:**

* Updated the `ImageResizer` component to register its resources under
`Resource$(var.IdSafeLanguage)WinUI3AppsInstallFolder` instead of the
default install folder, aligning with the new directory structure for
WinUI 3 apps.
* Added uninstall logic to remove the localized resource folder for
`WinUI3AppsInstallFolder`, ensuring cleanup of WinUI 3 app resources
during uninstall.
2025-08-18 10:18:47 +08:00
Jiří Polášek
c4c9277f3f CmdPal: Fix regression when updating a command provider without commands (#40984)
Improves item insertion logic in TopLevelCommandManager.

Updated the insertion logic to handle invalid startIndex values. If
startIndex is -1, new items will be appended to the end of the
collection, enhancing robustness.

Fixes regression introduced in #40752

<!-- 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-08-15 09:17:57 -05:00
Jiří Polášek
67cd0f055c CmdPal: Check icon parent before adding in ContentIcon (Closes: #40928) (#40931)
## Summary of the Pull Request

This pull request introduces a minor but important update to the
`ContentIcon` control in the `Microsoft.CmdPal.UI` module. The changes
improve robustness by adding checks to prevent duplicate parenting of
the `Content` element and include a debug assertion for better
diagnostics during development.

## PR Checklist

- [x] Closes: #40928 
- [ ] **Communication:** not yet
- [ ] **Tests:** nope
- [ ] **Localization:** none
- [ ] **Dev docs:** nay
- [ ] **New binaries:** no nothing
- [ ] **Documentation updated:** too lazy for that

## Detailed Description of the Pull Request / Additional comments

### Key changes:

#### Diagnostics and robustness improvements:
* Added a `Debug.Assert` statement to verify that the `Content` element
is not already parented to another element, helping to catch potential
issues during development.
(`[src/modules/cmdpal/Microsoft.CmdPal.UI/Controls/ContentIcon.csR39-R49](diffhunk://#diff-330aad69f925cf7a9e07bb7147af8e6cd09776a4c745455ac8a91a24b482d076R39-R49)`)
* Introduced checks to ensure the `Content` element is not added to the
`Grid`'s `Children` collection if it already exists there, preventing
redundant operations.
(`[src/modules/cmdpal/Microsoft.CmdPal.UI/Controls/ContentIcon.csR39-R49](diffhunk://#diff-330aad69f925cf7a9e07bb7147af8e6cd09776a4c745455ac8a91a24b482d076R39-R49)`)

#### Code maintenance:
* Added a `using System.Diagnostics` directive to enable the use of the
`Debug` class for assertions.
(`[src/modules/cmdpal/Microsoft.CmdPal.UI/Controls/ContentIcon.csR5](diffhunk://#diff-330aad69f925cf7a9e07bb7147af8e6cd09776a4c745455ac8a91a24b482d076R5)`)

## Validation Steps Performed

Turned extensions off and on and off and on and off and on and off and
on and off and on and off and on and off and on and off and on and off
and on and off and on and off and on and off and on and off and on and
off and on and off and on.
And then off and on again, just to be sure.

---------

Co-authored-by: Mike Griese <migrie@microsoft.com>
2025-08-15 06:48:54 -05:00
Jiří Polášek
051c07885e CmdPal: Replace the brush used for the menu item separator (#41130)
## Summary of the Pull Request

Replace the brush used for the menu item separator in
SeparatorContextMenuViewModelTemplate with the brush used by WinUI 3 for
flyout menus.

The brush previously used is a legacy brush and a WinUI trap.

After screenshot:

<img width="830" height="513" alt="image"
src="https://github.com/user-attachments/assets/32620050-29a3-40a5-aa6a-fe83afb55090"
/>


## PR Checklist

- [x] Closes: #41128
- [ ] **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-08-14 10:52:37 -05:00
Jiří Polášek
a5b9a38517 CmdPal: Bring existing Settings window to the foreground when opened (#41087)
## Summary of the Pull Request

Adds extra BringToFront after Activate. Don't ask.

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

- [x] Closes: #41086
- [ ] **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-08-13 13:48:07 -05:00
Jiří Polášek
7a3616e996 CmdPal: Replace Clipboard History extension outline icon with colorful icon (#41012)
## Summary of the Pull Request

Replace Clipboard History extension icon with an icon derived from
Fluent UI System Color set
(https://github.com/microsoft/fluentui-system-icons/). Icon is under MIT
license.

<img width="786" height="473" alt="image"
src="https://github.com/user-attachments/assets/6b9471d8-c98f-45c7-85e3-9521ce2a9717"
/>

## PR Checklist

- [x] Closes: #41018
- [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


## Detailed Description of the Pull Request / Additional comments


## Validation Steps Performed

I looked at the icon in the top-level list. Looks nice.
I looked at the icon in the settings page. Also looks nice.
2025-08-13 13:45:47 -05:00
Jiří Polášek
b36530bf87 CmdPal: Fix race condition in SupersedingAsyncGate cancellation handling [MSH] (#40983)
## Summary of the Pull Request

Change SetCanceled to TrySetCanceled in OperationCanceledException
handler to prevent InvalidOperationException when external and internal
cancellation tokens complete the TaskCompletionSource simultaneously.


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

- [x] Closes: #40982
- [ ] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [ ] **Tests:** none
- [ ] **Localization:** nope
- [ ] **Dev docs:** none
- [ ] **New binaries:** none
- [ ] **Documentation updated:** none

<!-- 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-08-13 13:44:31 -05:00
Jessica Dene Earley-Cha
e260c01553 CmdPal: Setting Activation Shortcut now auto focuses on window & delivers dialog (#40968)
## Summary of the Pull Request
Screen readers now will focus on the activation shortcut windows and
read out the text

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

- [x] Closes: #40967
- [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


https://github.com/user-attachments/assets/d72a9aea-28b8-49d1-b51f-7a7d2a8ff42f
2025-08-13 13:43:54 -05:00
Mike Griese
7f4a97cac5 CmdPal: extension nuget should target a lower windows SDK version (#40902)
related to some #40113 work

The extension SDK shouldn't rely on a preview version of the Windows
SDK. It should use the stable one.

Also moves some messages around that we didn't need
2025-08-13 13:42:52 -05:00
Davide Giacometti
ab76dd1255 [CmdPal] Search PATH starting with ~ / \ (#40887)
<!-- 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

Love that we have now environment variables expanding! 🚀 
Porting also few small features I implemented in Run Folder plugin a
long time ago and I love:
- https://github.com/microsoft/PowerToys/pull/7711
- https://github.com/microsoft/PowerToys/pull/9579

Threat `/` and `\` as root of system drive (typically `C:\`)
Threat `~` as user home directory `%USERPROFILE%`

<!-- 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

<img width="591" height="356" alt="image"
src="https://github.com/user-attachments/assets/9c1f196a-bd4d-428c-a4e6-af9f269acd1f"
/>

<img width="591" height="356" alt="image"
src="https://github.com/user-attachments/assets/4295ebca-f12b-43b0-b3d0-c130b6faf419"
/>


<img width="591" height="356" alt="image"
src="https://github.com/user-attachments/assets/87748864-e250-4141-b366-29b45d58edcf"
/>

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

- Tested search starting with `~` `/` `\`
- Tested UNC network path starting with `\\...` and `//...`
2025-08-13 13:42:40 -05:00
Dustin L. Howett
911989bac1 store: update package catalog before running install (#41121)
It's actually failing because we're bad at... Linux?
2025-08-13 11:01:25 -05:00
Gordon Lam
c690cb1bb8 Initial draft for 0.93 release note (#41036)
<!-- 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

## AI Summary
This pull request updates the `README.md` to document the 0.93 (August
2025) release of Microsoft PowerToys. It introduces a new, modern
settings dashboard, details major improvements and new features across
multiple modules, and updates installation links and documentation. The
release focuses on enhanced user experience, accessibility, performance,
stability, and test coverage.

Most important changes:

**Release and Installation Updates**
- Updated all installer links and release references from version 0.92.1
to 0.93.0, and milestone tracking for the next release to 0.94.
- Updated the release highlights and version number to reflect the 0.93
(August 2025) release, with a summary of new features and improvements.

**Settings and User Experience**
- Introduced a completely redesigned, card-based settings dashboard with
clearer descriptions, faster navigation, and improved release notes
formatting for a better user experience.
- Rewrote setting descriptions for clarity and consistency, added deep
link support to specific settings pages, and fixed various UI/UX issues
in the settings module.

**Command Palette and Extensions**
- Resolved over 99 issues in Command Palette, including accessibility
improvements, context menu enhancements, new navigation shortcuts, AOT
compilation mode (reducing install size and memory usage), and
re-enabled Clipboard History.
- Added new settings and features to Command Palette extensions, such as
command history in Run, improved Apps extension handling, and new
context menu options.

**Module Improvements and New Features**
- Mouse Utilities: Added a new spotlight highlighting mode for
presentations.
- Peek: Added instant previews and embedded thumbnail support for Binary
G-code (.bgcode) 3D printing files.
- Quick Accent: Added Vietnamese language support.

**Development, Testing, and Documentation**
- Upgraded .NET libraries and spell check system, improved CI pipelines,
reduced test timeouts, and added over 600 new unit tests (mainly for
Command Palette), doubling UI automation coverage.
- Added detailed developer documentation, fixed broken SDK links, and
documented new community plugins.

Other minor changes:
- Standardized naming, improved spelling, and cleaned up configuration
files for smoother development.
- Minor capitalization fix for "Mouse Utilities" in the utilities table.
2025-08-13 17:19:06 +02:00
217 changed files with 2979 additions and 2236 deletions

View File

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

View File

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

View File

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

202
README.md
View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,284 @@
// 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.Linq;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Threading;
// <summary>
// Initialization and clean up.
// </summary>
// <history>
// 2008 created by Truong Do (ductdo).
// 2009-... modified by Truong Do (TruongDo).
// 2023- Included in PowerToys.
// </history>
using Microsoft.Win32;
using MouseWithoutBorders.Class;
using MouseWithoutBorders.Core;
using MouseWithoutBorders.Form;
using Windows.UI.Input.Preview.Injection;
using Thread = MouseWithoutBorders.Core.Thread;
namespace MouseWithoutBorders
{
internal partial class Common
{
private static bool initDone;
internal static int REOPEN_WHEN_WSAECONNRESET = -10054;
internal static int REOPEN_WHEN_HOTKEY = -10055;
internal static int PleaseReopenSocket;
internal static bool ReopenSocketDueToReadError;
internal static DateTime LastResumeSuspendTime { get; set; } = DateTime.UtcNow;
internal static bool InitDone
{
get => Common.initDone;
set => Common.initDone = value;
}
internal static void UpdateMachineTimeAndID()
{
Common.MachineName = Common.MachineName.Trim();
_ = MachineStuff.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, true);
}
private static void InitializeMachinePoolFromSettings()
{
try
{
MachineInf[] info = MachinePoolHelpers.LoadMachineInfoFromMachinePoolStringSetting(Setting.Values.MachinePoolString);
for (int i = 0; i < info.Length; i++)
{
info[i].Name = info[i].Name.Trim();
}
MachineStuff.MachinePool.Initialize(info);
MachineStuff.MachinePool.ResetIPAddressesForDeadMachines(true);
}
catch (Exception ex)
{
Logger.Log(ex);
MachineStuff.MachinePool.Clear();
}
}
internal static void SetupMachineNameAndID()
{
try
{
GetMachineName();
DesMachineID = MachineStuff.NewDesMachineID = MachineID;
// MessageBox.Show(machineID.ToString(CultureInfo.CurrentCulture)); // For test
InitializeMachinePoolFromSettings();
Common.MachineName = Common.MachineName.Trim();
_ = MachineStuff.MachinePool.LearnMachine(Common.MachineName);
_ = MachineStuff.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, true);
MachineStuff.UpdateMachinePoolStringSetting();
}
catch (Exception e)
{
Logger.Log(e);
}
}
internal static void Init()
{
_ = Helper.GetUserName();
Common.GeneratedKey = true;
try
{
Common.MyKey = Setting.Values.MyKey;
int tmp = Setting.Values.MyKeyDaysToExpire;
}
catch (FormatException e)
{
Common.KeyCorrupted = true;
Setting.Values.MyKey = Common.MyKey = Common.CreateRandomKey();
Logger.Log(e.Message);
}
catch (CryptographicException e)
{
Common.KeyCorrupted = true;
Setting.Values.MyKey = Common.MyKey = Common.CreateRandomKey();
Logger.Log(e.Message);
}
try
{
InputSimulation.Injector = InputInjector.TryCreate();
if (InputSimulation.Injector != null)
{
InputSimulation.MoveMouseRelative(0, 0);
NativeMethods.InjectMouseInputAvailable = true;
}
}
catch (EntryPointNotFoundException)
{
NativeMethods.InjectMouseInputAvailable = false;
Logger.Log($"{nameof(NativeMethods.InjectMouseInputAvailable)} = false");
}
bool dummy = Setting.Values.DrawMouseEx;
Is64bitOS = IntPtr.Size == 8;
tcpPort = Setting.Values.TcpPort;
GetScreenConfig();
PackageSent = new PackageMonitor(0);
PackageReceived = new PackageMonitor(0);
SetupMachineNameAndID();
InitEncryption();
CreateHelperThreads();
SystemEvents.DisplaySettingsChanged += new EventHandler(SystemEvents_DisplaySettingsChanged);
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);
PleaseReopenSocket = 9;
/* TODO: Telemetry for the matrix? */
}
private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
Helper.WndProcCounter++;
if (e.Mode is PowerModes.Resume or PowerModes.Suspend)
{
Logger.TelemetryLogTrace($"{nameof(SystemEvents_PowerModeChanged)}: {e.Mode}", SeverityLevel.Information);
LastResumeSuspendTime = DateTime.UtcNow;
MachineStuff.SwitchToMultipleMode(false, true);
}
}
private static void CreateHelperThreads()
{
// NOTE(@yuyoyuppe): service crashes while trying to obtain this info, disabling.
/*
Thread watchDogThread = new(new ThreadStart(WatchDogThread), nameof(WatchDogThread));
watchDogThread.Priority = ThreadPriority.Highest;
watchDogThread.Start();
*/
helper = new Thread(new ThreadStart(Helper.HelperThread), "Helper Thread");
helper.SetApartmentState(ApartmentState.STA);
helper.Start();
}
private static void AskHelperThreadsToExit(int waitTime)
{
Helper.signalHelperToExit = true;
Helper.signalWatchDogToExit = true;
_ = EvSwitch.Set();
int c = 0;
if (helper != null && c < waitTime)
{
while (Helper.signalHelperToExit)
{
Thread.Sleep(1);
}
helper = null;
}
}
internal static void Cleanup()
{
try
{
SendByeBye();
// UnhookClipboard();
AskHelperThreadsToExit(500);
MainForm.NotifyIcon.Visible = false;
MainForm.NotifyIcon.Dispose();
CloseAllFormsAndHooks();
DoSomethingInUIThread(() =>
{
Sk?.Close(true);
});
}
catch (Exception e)
{
Logger.Log(e);
}
}
private static long lastReleaseAllKeysCall;
internal static void ReleaseAllKeys()
{
if (Math.Abs(GetTick() - lastReleaseAllKeysCall) < 2000)
{
return;
}
lastReleaseAllKeysCall = GetTick();
KEYBDDATA kd;
kd.dwFlags = (int)LLKHF.UP;
VK[] keys = new VK[]
{
VK.LSHIFT, VK.LCONTROL, VK.LMENU, VK.LWIN, VK.RSHIFT,
VK.RCONTROL, VK.RMENU, VK.RWIN, VK.SHIFT, VK.MENU, VK.CONTROL,
};
Logger.LogDebug("***** ReleaseAllKeys has been called! *****:");
foreach (VK vk in keys)
{
if ((NativeMethods.GetAsyncKeyState((IntPtr)vk) & 0x8000) != 0)
{
Logger.LogDebug(vk.ToString() + " is down, release it...");
Hook?.ResetLastSwitchKeys(); // Sticky key can turn ALL PC mode on (CtrlCtrlCtrl)
kd.wVk = (int)vk;
InputSimulation.SendKey(kd);
Hook?.ResetLastSwitchKeys();
}
}
}
private static void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
Logger.LogDebug("NetworkAvailabilityEventArgs.IsAvailable: " + e.IsAvailable.ToString(CultureInfo.InvariantCulture));
Helper.WndProcCounter++;
ScheduleReopenSocketsDueToNetworkChanges(!e.IsAvailable);
}
private static void ScheduleReopenSocketsDueToNetworkChanges(bool closeSockets = true)
{
if (closeSockets)
{
// Slept/hibernated machine may still have the sockets' status as Connected:( (unchanged) so it would not re-connect after a timeout when waking up.
// Closing the sockets when it is going to sleep/hibernate will trigger the reconnection faster when it wakes up.
DoSomethingInUIThread(
() =>
{
SocketStuff s = Sk;
Sk = null;
s?.Close(false);
},
true);
}
if (!Common.IsMyDesktopActive())
{
PleaseReopenSocket = 0;
}
else if (PleaseReopenSocket != 10)
{
PleaseReopenSocket = 10;
}
}
}
}

View File

@@ -36,7 +36,7 @@ namespace MouseWithoutBorders
internal static string ActiveDesktop => Common.activeDesktop;
internal static void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
private static void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
{
GetScreenConfig();
}
@@ -340,7 +340,7 @@ namespace MouseWithoutBorders
Setting.Values.LastX = JUST_GOT_BACK_FROM_SCREEN_SAVER;
if (cleanupIfExit)
{
InitAndCleanup.Cleanup();
Common.Cleanup();
}
Process.GetCurrentProcess().KillProcess();

View File

@@ -32,7 +32,6 @@ using MouseWithoutBorders.Class;
using MouseWithoutBorders.Core;
using MouseWithoutBorders.Exceptions;
using Clipboard = MouseWithoutBorders.Core.Clipboard;
using Thread = MouseWithoutBorders.Core.Thread;
// Log is enough
@@ -90,8 +89,8 @@ namespace MouseWithoutBorders
private static FrmMatrix matrixForm;
private static FrmInputCallback inputCallbackForm;
private static FrmAbout aboutForm;
private static Thread helper;
#pragma warning disable SA1307 // Accessible fields should begin with upper-case letter
internal static Thread helper;
internal static int screenWidth;
internal static int screenHeight;
#pragma warning restore SA1307
@@ -121,9 +120,7 @@ namespace MouseWithoutBorders
internal static int switchCount;
#pragma warning restore SA1307
private static long lastReconnectByHotKeyTime;
#pragma warning disable SA1307 // Accessible fields should begin with upper-case names
internal static int tcpPort;
#pragma warning restore SA1307
private static int tcpPort;
private static bool secondOpenSocketTry;
private static string binaryName;
@@ -212,7 +209,7 @@ namespace MouseWithoutBorders
internal static bool Is64bitOS
{
get; set;
get; private set;
// set { Common.is64bitOS = value; }
}
@@ -613,7 +610,7 @@ namespace MouseWithoutBorders
}
* */
internal static void SendByeBye()
private static void SendByeBye()
{
Logger.LogDebug($"{nameof(SendByeBye)}");
SendPackage(ID.ALL, PackageType.ByeBye);
@@ -727,7 +724,7 @@ namespace MouseWithoutBorders
internal static void SendImage(string machine, string file)
{
Clipboard.LastDragDropFile = file;
LastDragDropFile = file;
// Send ClipboardCapture
if (machine.Equals("All", StringComparison.OrdinalIgnoreCase))
@@ -746,7 +743,7 @@ namespace MouseWithoutBorders
internal static void SendImage(ID src, string file)
{
Clipboard.LastDragDropFile = file;
LastDragDropFile = file;
// Send ClipboardCapture
SendPackage(src, PackageType.ClipboardCapture);
@@ -1293,7 +1290,7 @@ namespace MouseWithoutBorders
});
}
internal static string GetMyStorageDir()
private static string GetMyStorageDir()
{
string st = string.Empty;

View File

@@ -28,7 +28,6 @@ using MouseWithoutBorders.Core;
using SystemClipboard = System.Windows.Forms.Clipboard;
#if !MM_HELPER
using Clipboard = MouseWithoutBorders.Core.Clipboard;
using Thread = MouseWithoutBorders.Core.Thread;
#endif
@@ -160,7 +159,7 @@ namespace MouseWithoutBorders
public void SendClipboardData(ByteArrayOrString data, bool isFilePath)
{
_ = Clipboard.CheckClipboardEx(data, isFilePath);
_ = Common.CheckClipboardEx(data, isFilePath);
}
}
#endif

View File

@@ -579,7 +579,7 @@ namespace MouseWithoutBorders.Class
{
Common.ShowToolTip("Reconnecting...", 2000);
Common.LastReconnectByHotKeyTime = Common.GetTick();
InitAndCleanup.PleaseReopenSocket = InitAndCleanup.REOPEN_WHEN_HOTKEY;
Common.PleaseReopenSocket = Common.REOPEN_WHEN_HOTKEY;
return false;
}
@@ -632,7 +632,7 @@ namespace MouseWithoutBorders.Class
{
// Common.DoSomethingInUIThread(delegate()
{
InitAndCleanup.ReleaseAllKeys();
Common.ReleaseAllKeys();
}
// );

View File

@@ -407,7 +407,7 @@ namespace MouseWithoutBorders.Class
{
ResetModifiersState(Setting.Values.HotKeyLockMachine);
eatKey = true;
InitAndCleanup.ReleaseAllKeys();
Common.ReleaseAllKeys();
_ = NativeMethods.LockWorkStation();
}
}
@@ -439,7 +439,7 @@ namespace MouseWithoutBorders.Class
{
ctrlDown = altDown = false;
eatKey = true;
InitAndCleanup.ReleaseAllKeys();
Common.ReleaseAllKeys();
}
break;
@@ -449,7 +449,7 @@ namespace MouseWithoutBorders.Class
{
winDown = false;
eatKey = true;
InitAndCleanup.ReleaseAllKeys();
Common.ReleaseAllKeys();
uint rv = NativeMethods.LockWorkStation();
Logger.LogDebug("LockWorkStation returned " + rv.ToString(CultureInfo.CurrentCulture));
}

View File

@@ -235,7 +235,7 @@ namespace MouseWithoutBorders.Class
_ = Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
Application.SetCompatibleTextRenderingDefault(false);
InitAndCleanup.Init();
Common.Init();
Core.Helper.WndProcCounter++;
var formScreen = new FrmScreen();
@@ -314,7 +314,7 @@ namespace MouseWithoutBorders.Class
MachineStuff.UpdateMachinePoolStringSetting();
SocketStuff.InvalidKeyFound = false;
InitAndCleanup.ReopenSocketDueToReadError = true;
Common.ReopenSocketDueToReadError = true;
Common.ReopenSockets(true);
MachineStuff.SendMachineMatrix();
@@ -340,7 +340,7 @@ namespace MouseWithoutBorders.Class
public void Reconnect()
{
SocketStuff.InvalidKeyFound = false;
InitAndCleanup.ReopenSocketDueToReadError = true;
Common.ReopenSocketDueToReadError = true;
Common.ReopenSockets(true);
for (int i = 0; i < 10; i++)
@@ -397,7 +397,7 @@ namespace MouseWithoutBorders.Class
using var asyncFlowControl = ExecutionContext.SuppressFlow();
Common.InputCallbackThreadID = Thread.CurrentThread.ManagedThreadId;
while (!InitAndCleanup.InitDone)
while (!Common.InitDone)
{
Thread.Sleep(100);
}

View File

@@ -118,7 +118,7 @@ namespace MouseWithoutBorders.Class
if (shouldReopenSockets)
{
SocketStuff.InvalidKeyFound = false;
InitAndCleanup.ReopenSocketDueToReadError = true;
Common.ReopenSocketDueToReadError = true;
Common.ReopenSockets(true);
}

View File

@@ -29,7 +29,6 @@ using MouseWithoutBorders.Core;
// </history>
using MouseWithoutBorders.Exceptions;
using Clipboard = MouseWithoutBorders.Core.Clipboard;
using Thread = MouseWithoutBorders.Core.Thread;
[module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "MouseWithoutBorders.SocketStuff.#SendData(System.Byte[])", Justification = "Dotnet port with style preservation")]
@@ -282,7 +281,7 @@ namespace MouseWithoutBorders.Class
* */
Common.GetMachineName(); // IPs might have been changed
InitAndCleanup.UpdateMachineTimeAndID();
Common.UpdateMachineTimeAndID();
Logger.LogDebug("Creating sockets...");
@@ -309,7 +308,7 @@ namespace MouseWithoutBorders.Class
{
Logger.TelemetryLogTrace("Restarting the service dues to WSAEADDRINUSE.", SeverityLevel.Warning);
Program.StartService();
InitAndCleanup.PleaseReopenSocket = InitAndCleanup.REOPEN_WHEN_WSAECONNRESET;
Common.PleaseReopenSocket = Common.REOPEN_WHEN_WSAECONNRESET;
}
break;
@@ -1249,7 +1248,7 @@ namespace MouseWithoutBorders.Class
// WSAECONNRESET
if (e is ExpectedSocketException se && se.ShouldReconnect)
{
InitAndCleanup.PleaseReopenSocket = InitAndCleanup.REOPEN_WHEN_WSAECONNRESET;
Common.PleaseReopenSocket = Common.REOPEN_WHEN_WSAECONNRESET;
Logger.Log($"MainTCPRoutine: {nameof(FlagReopenSocketIfNeeded)}");
}
}
@@ -1307,7 +1306,7 @@ namespace MouseWithoutBorders.Class
}
catch (ObjectDisposedException e)
{
InitAndCleanup.PleaseReopenSocket = InitAndCleanup.REOPEN_WHEN_WSAECONNRESET;
Common.PleaseReopenSocket = Common.REOPEN_WHEN_WSAECONNRESET;
UpdateTcpSockets(currentTcp, SocketStatus.ForceClosed);
currentSocket.Close();
Logger.Log($"{nameof(MainTCPRoutine)}: The socket could have been closed/disposed by other threads: {e.Message}");
@@ -1354,10 +1353,10 @@ namespace MouseWithoutBorders.Class
* In this case, we should give ONE try to reconnect.
*/
if (InitAndCleanup.ReopenSocketDueToReadError)
if (Common.ReopenSocketDueToReadError)
{
InitAndCleanup.PleaseReopenSocket = InitAndCleanup.REOPEN_WHEN_WSAECONNRESET;
InitAndCleanup.ReopenSocketDueToReadError = false;
Common.PleaseReopenSocket = Common.REOPEN_WHEN_WSAECONNRESET;
Common.ReopenSocketDueToReadError = false;
}
break;
@@ -1642,7 +1641,7 @@ namespace MouseWithoutBorders.Class
bool clientPushData = true;
ClipboardPostAction postAction = ClipboardPostAction.Other;
bool handShaken = Clipboard.ShakeHand(ref remoteEndPoint, s, out Stream enStream, out Stream deStream, ref clientPushData, ref postAction);
bool handShaken = Common.ShakeHand(ref remoteEndPoint, s, out Stream enStream, out Stream deStream, ref clientPushData, ref postAction);
if (!handShaken)
{
@@ -1657,7 +1656,7 @@ namespace MouseWithoutBorders.Class
if (clientPushData)
{
Clipboard.ReceiveAndProcessClipboardData(remoteEndPoint, s, enStream, deStream, $"{postAction}");
Common.ReceiveAndProcessClipboardData(remoteEndPoint, s, enStream, deStream, $"{postAction}");
}
else
{
@@ -1681,23 +1680,23 @@ namespace MouseWithoutBorders.Class
const int CLOSE_TIMEOUT = 10;
byte[] header = new byte[1024];
string headerString = string.Empty;
if (Clipboard.LastDragDropFile != null)
if (Common.LastDragDropFile != null)
{
string fileName = null;
if (!Launch.ImpersonateLoggedOnUserAndDoSomething(() =>
{
if (!File.Exists(Clipboard.LastDragDropFile))
if (!File.Exists(Common.LastDragDropFile))
{
headerString = Directory.Exists(Clipboard.LastDragDropFile)
? $"{0}*{Clipboard.LastDragDropFile} - Folder is not supported, zip it first!"
: Clipboard.LastDragDropFile.Contains("- File too big")
? $"{0}*{Clipboard.LastDragDropFile}"
: $"{0}*{Clipboard.LastDragDropFile} not found!";
headerString = Directory.Exists(Common.LastDragDropFile)
? $"{0}*{Common.LastDragDropFile} - Folder is not supported, zip it first!"
: Common.LastDragDropFile.Contains("- File too big")
? $"{0}*{Common.LastDragDropFile}"
: $"{0}*{Common.LastDragDropFile} not found!";
}
else
{
fileName = Clipboard.LastDragDropFile;
fileName = Common.LastDragDropFile;
headerString = $"{new FileInfo(fileName).Length}*{fileName}";
}
}))
@@ -1740,11 +1739,11 @@ namespace MouseWithoutBorders.Class
Logger.Log(log);
}
}
else if (!Clipboard.IsClipboardDataImage && Clipboard.LastClipboardData != null)
else if (!Common.IsClipboardDataImage && Common.LastClipboardData != null)
{
try
{
byte[] data = Clipboard.LastClipboardData;
byte[] data = Common.LastClipboardData;
headerString = $"{data.Length}*{"text"}";
Common.GetBytesU(headerString).CopyTo(header, 0);
@@ -1774,9 +1773,9 @@ namespace MouseWithoutBorders.Class
Logger.Log(log);
}
}
else if (Clipboard.LastClipboardData != null && Clipboard.LastClipboardData.Length > 0)
else if (Common.LastClipboardData != null && Common.LastClipboardData.Length > 0)
{
byte[] data = Clipboard.LastClipboardData;
byte[] data = Common.LastClipboardData;
headerString = $"{data.Length}*{"image"}";
Common.GetBytesU(headerString).CopyTo(header, 0);
@@ -1985,8 +1984,8 @@ namespace MouseWithoutBorders.Class
{
tcp = null;
Setting.Values.MachineId = Common.Ran.Next();
InitAndCleanup.UpdateMachineTimeAndID();
InitAndCleanup.PleaseReopenSocket = InitAndCleanup.REOPEN_WHEN_HOTKEY;
Common.UpdateMachineTimeAndID();
Common.PleaseReopenSocket = Common.REOPEN_WHEN_HOTKEY;
Logger.TelemetryLogTrace("MachineID conflict.", SeverityLevel.Information);
}

File diff suppressed because it is too large Load Diff

View File

@@ -83,7 +83,7 @@ internal static class DragDrop
if (wParam == Common.WM_RBUTTONUP && IsDropping)
{
IsDropping = false;
Clipboard.LastIDWithClipboardData = ID.NONE;
Common.LastIDWithClipboardData = ID.NONE;
}
}
@@ -193,7 +193,7 @@ internal static class DragDrop
{
if (!string.IsNullOrEmpty(dragFileName) && (File.Exists(dragFileName) || Directory.Exists(dragFileName)))
{
Clipboard.LastDragDropFile = dragFileName;
Common.LastDragDropFile = dragFileName;
/*
* possibleDropMachineID is used as desID sent in DragDropStep06();
* */
@@ -270,7 +270,7 @@ internal static class DragDrop
else
{
IsDragging = false;
Clipboard.LastIDWithClipboardData = ID.NONE;
Common.LastIDWithClipboardData = ID.NONE;
}
}
}
@@ -280,7 +280,7 @@ internal static class DragDrop
Logger.LogDebug("DragDropStep10: Hide the form and get data...");
IsDropping = false;
IsDragging = false;
Clipboard.LastIDWithClipboardData = ID.NONE;
Common.LastIDWithClipboardData = ID.NONE;
Common.DoSomethingInUIThread(() =>
{
@@ -288,7 +288,7 @@ internal static class DragDrop
});
PowerToysTelemetry.Log.WriteEvent(new MouseWithoutBorders.Telemetry.MouseWithoutBordersDragAndDropEvent());
Clipboard.GetRemoteClipboard("desktop");
Common.GetRemoteClipboard("desktop");
}
internal static void DragDropStep11()
@@ -298,8 +298,8 @@ internal static class DragDrop
IsDropping = false;
IsDragging = false;
DragMachine = (ID)1;
Clipboard.LastIDWithClipboardData = ID.NONE;
Clipboard.LastDragDropFile = null;
Common.LastIDWithClipboardData = ID.NONE;
Common.LastDragDropFile = null;
MouseDown = false;
}
@@ -307,7 +307,7 @@ internal static class DragDrop
{
Logger.LogDebug("DragDropStep12: ClipboardDragDropEnd received");
IsDropping = false;
Clipboard.LastIDWithClipboardData = ID.NONE;
Common.LastIDWithClipboardData = ID.NONE;
Common.DoSomethingInUIThread(() =>
{

View File

@@ -74,7 +74,7 @@ internal static class Event
if (!p.IsEmpty)
{
Clipboard.HasSwitchedMachineSinceLastCopy = true;
Common.HasSwitchedMachineSinceLastCopy = true;
Logger.LogDebug(string.Format(
CultureInfo.CurrentCulture,
@@ -213,10 +213,10 @@ internal static class Event
if (MachineStuff.desMachineID == Common.MachineID)
{
if (Common.GetTick() - Clipboard.clipboardCopiedTime < Clipboard.BIG_CLIPBOARD_DATA_TIMEOUT)
if (Common.GetTick() - Common.clipboardCopiedTime < Common.BIG_CLIPBOARD_DATA_TIMEOUT)
{
Clipboard.clipboardCopiedTime = 0;
Clipboard.GetRemoteClipboard("PrepareToSwitchToMachine");
Common.clipboardCopiedTime = 0;
Common.GetRemoteClipboard("PrepareToSwitchToMachine");
}
}
else

View File

@@ -119,7 +119,7 @@ internal static class Helper
if (MachineStuff.NewDesMachineID == Common.MachineID)
{
InitAndCleanup.ReleaseAllKeys();
Common.ReleaseAllKeys();
}
}
}
@@ -317,7 +317,7 @@ internal static class Helper
Common.GetInputDesktop(),
0);
Clipboard.HasSwitchedMachineSinceLastCopy = true;
Common.HasSwitchedMachineSinceLastCopy = true;
// Common.CreateLowIntegrityProcess("\"" + Path.GetDirectoryName(Application.ExecutablePath) + "\\MouseWithoutBordersHelper.exe\"", string.Empty, 0, false, 0);
var processes = Process.GetProcessesByName(HelperProcessName);

View File

@@ -1,278 +0,0 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Threading;
using Microsoft.Win32;
using MouseWithoutBorders.Class;
using Windows.UI.Input.Preview.Injection;
// <summary>
// Initialization and clean up.
// </summary>
// <history>
// 2008 created by Truong Do (ductdo).
// 2009-... modified by Truong Do (TruongDo).
// 2023- Included in PowerToys.
// </history>
namespace MouseWithoutBorders.Core;
internal static class InitAndCleanup
{
private static bool initDone;
internal static int REOPEN_WHEN_WSAECONNRESET = -10054;
internal static int REOPEN_WHEN_HOTKEY = -10055;
internal static int PleaseReopenSocket;
internal static bool ReopenSocketDueToReadError;
private static DateTime LastResumeSuspendTime { get; set; } = DateTime.UtcNow;
internal static bool InitDone
{
get => InitAndCleanup.initDone;
set => InitAndCleanup.initDone = value;
}
internal static void UpdateMachineTimeAndID()
{
Common.MachineName = Common.MachineName.Trim();
_ = MachineStuff.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, true);
}
private static void InitializeMachinePoolFromSettings()
{
try
{
MachineInf[] info = MachinePoolHelpers.LoadMachineInfoFromMachinePoolStringSetting(Setting.Values.MachinePoolString);
for (int i = 0; i < info.Length; i++)
{
info[i].Name = info[i].Name.Trim();
}
MachineStuff.MachinePool.Initialize(info);
MachineStuff.MachinePool.ResetIPAddressesForDeadMachines(true);
}
catch (Exception ex)
{
Logger.Log(ex);
MachineStuff.MachinePool.Clear();
}
}
private static void SetupMachineNameAndID()
{
try
{
Common.GetMachineName();
Common.DesMachineID = MachineStuff.NewDesMachineID = Common.MachineID;
// MessageBox.Show(machineID.ToString(CultureInfo.CurrentCulture)); // For test
InitializeMachinePoolFromSettings();
Common.MachineName = Common.MachineName.Trim();
_ = MachineStuff.MachinePool.LearnMachine(Common.MachineName);
_ = MachineStuff.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, true);
MachineStuff.UpdateMachinePoolStringSetting();
}
catch (Exception e)
{
Logger.Log(e);
}
}
internal static void Init()
{
_ = Helper.GetUserName();
Common.GeneratedKey = true;
try
{
Common.MyKey = Setting.Values.MyKey;
int tmp = Setting.Values.MyKeyDaysToExpire;
}
catch (FormatException e)
{
Common.KeyCorrupted = true;
Setting.Values.MyKey = Common.MyKey = Common.CreateRandomKey();
Logger.Log(e.Message);
}
catch (CryptographicException e)
{
Common.KeyCorrupted = true;
Setting.Values.MyKey = Common.MyKey = Common.CreateRandomKey();
Logger.Log(e.Message);
}
try
{
InputSimulation.Injector = InputInjector.TryCreate();
if (InputSimulation.Injector != null)
{
InputSimulation.MoveMouseRelative(0, 0);
NativeMethods.InjectMouseInputAvailable = true;
}
}
catch (EntryPointNotFoundException)
{
NativeMethods.InjectMouseInputAvailable = false;
Logger.Log($"{nameof(NativeMethods.InjectMouseInputAvailable)} = false");
}
bool dummy = Setting.Values.DrawMouseEx;
Common.Is64bitOS = IntPtr.Size == 8;
Common.tcpPort = Setting.Values.TcpPort;
Common.GetScreenConfig();
Common.PackageSent = new PackageMonitor(0);
Common.PackageReceived = new PackageMonitor(0);
SetupMachineNameAndID();
Common.InitEncryption();
CreateHelperThreads();
SystemEvents.DisplaySettingsChanged += new EventHandler(Common.SystemEvents_DisplaySettingsChanged);
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);
PleaseReopenSocket = 9;
/* TODO: Telemetry for the matrix? */
}
private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
Helper.WndProcCounter++;
if (e.Mode is PowerModes.Resume or PowerModes.Suspend)
{
Logger.TelemetryLogTrace($"{nameof(SystemEvents_PowerModeChanged)}: {e.Mode}", SeverityLevel.Information);
LastResumeSuspendTime = DateTime.UtcNow;
MachineStuff.SwitchToMultipleMode(false, true);
}
}
private static void CreateHelperThreads()
{
// NOTE(@yuyoyuppe): service crashes while trying to obtain this info, disabling.
/*
Thread watchDogThread = new(new ThreadStart(WatchDogThread), nameof(WatchDogThread));
watchDogThread.Priority = ThreadPriority.Highest;
watchDogThread.Start();
*/
Common.helper = new Thread(new ThreadStart(Helper.HelperThread), "Helper Thread");
Common.helper.SetApartmentState(ApartmentState.STA);
Common.helper.Start();
}
private static void AskHelperThreadsToExit(int waitTime)
{
Helper.signalHelperToExit = true;
Helper.signalWatchDogToExit = true;
_ = Common.EvSwitch.Set();
int c = 0;
if (Common.helper != null && c < waitTime)
{
while (Helper.signalHelperToExit)
{
Thread.Sleep(1);
}
Common.helper = null;
}
}
internal static void Cleanup()
{
try
{
Common.SendByeBye();
// UnhookClipboard();
AskHelperThreadsToExit(500);
Common.MainForm.NotifyIcon.Visible = false;
Common.MainForm.NotifyIcon.Dispose();
Common.CloseAllFormsAndHooks();
Common.DoSomethingInUIThread(() =>
{
Common.Sk?.Close(true);
});
}
catch (Exception e)
{
Logger.Log(e);
}
}
private static long lastReleaseAllKeysCall;
internal static void ReleaseAllKeys()
{
if (Math.Abs(Common.GetTick() - lastReleaseAllKeysCall) < 2000)
{
return;
}
lastReleaseAllKeysCall = Common.GetTick();
KEYBDDATA kd;
kd.dwFlags = (int)Common.LLKHF.UP;
VK[] keys = new VK[]
{
VK.LSHIFT, VK.LCONTROL, VK.LMENU, VK.LWIN, VK.RSHIFT,
VK.RCONTROL, VK.RMENU, VK.RWIN, VK.SHIFT, VK.MENU, VK.CONTROL,
};
Logger.LogDebug("***** ReleaseAllKeys has been called! *****:");
foreach (VK vk in keys)
{
if ((NativeMethods.GetAsyncKeyState((IntPtr)vk) & 0x8000) != 0)
{
Logger.LogDebug(vk.ToString() + " is down, release it...");
Common.Hook?.ResetLastSwitchKeys(); // Sticky key can turn ALL PC mode on (CtrlCtrlCtrl)
kd.wVk = (int)vk;
InputSimulation.SendKey(kd);
Common.Hook?.ResetLastSwitchKeys();
}
}
}
private static void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
Logger.LogDebug("NetworkAvailabilityEventArgs.IsAvailable: " + e.IsAvailable.ToString(CultureInfo.InvariantCulture));
Helper.WndProcCounter++;
ScheduleReopenSocketsDueToNetworkChanges(!e.IsAvailable);
}
private static void ScheduleReopenSocketsDueToNetworkChanges(bool closeSockets = true)
{
if (closeSockets)
{
// Slept/hibernated machine may still have the sockets' status as Connected:( (unchanged) so it would not re-connect after a timeout when waking up.
// Closing the sockets when it is going to sleep/hibernate will trigger the reconnection faster when it wakes up.
Common.DoSomethingInUIThread(
() =>
{
SocketStuff s = Common.Sk;
Common.Sk = null;
s?.Close(false);
},
true);
}
if (!Common.IsMyDesktopActive())
{
PleaseReopenSocket = 0;
}
else if (PleaseReopenSocket != 10)
{
PleaseReopenSocket = 10;
}
}
}

View File

@@ -247,24 +247,22 @@ internal static class Logger
internal static void DumpStaticTypes(StringBuilder sb, int level)
{
var staticTypes = new List<Type>
{
typeof(Clipboard),
typeof(DragDrop),
typeof(Event),
typeof(InitAndCleanup),
typeof(Helper),
typeof(Launch),
typeof(Logger),
typeof(MachineStuff),
typeof(Receiver),
typeof(Service),
};
foreach (var staticType in staticTypes)
{
sb.AppendLine(CultureInfo.InvariantCulture, $"[{staticType.Name}]\r\n===============");
Logger.DumpType(sb, staticType, 0, level);
}
sb.AppendLine($"[{nameof(DragDrop)}]\r\n===============");
Logger.DumpType(sb, typeof(DragDrop), 0, level);
sb.AppendLine($"[{nameof(Event)}]\r\n===============");
Logger.DumpType(sb, typeof(Event), 0, level);
sb.AppendLine($"[{nameof(Helper)}]\r\n===============");
Logger.DumpType(sb, typeof(Helper), 0, level);
sb.AppendLine($"[{nameof(Launch)}]\r\n===============");
Logger.DumpType(sb, typeof(Launch), 0, level);
sb.AppendLine($"[{nameof(Logger)}]\r\n===============");
Logger.DumpType(sb, typeof(Logger), 0, level);
sb.AppendLine($"[{nameof(MachineStuff)}]\r\n===============");
Logger.DumpType(sb, typeof(MachineStuff), 0, level);
sb.AppendLine($"[{nameof(Receiver)}]\r\n===============");
Logger.DumpType(sb, typeof(Receiver), 0, level);
sb.AppendLine($"[{nameof(Service)}]\r\n===============");
Logger.DumpType(sb, typeof(Service), 0, level);
}
internal static bool PrivateDump(StringBuilder sb, object obj, string objName, int level, int maxLevel, bool stop)

View File

@@ -992,7 +992,7 @@ internal static class MachineStuff
Setting.Values.MatrixOneRow = !((package.Type & PackageType.MatrixTwoRowFlag) == PackageType.MatrixTwoRowFlag);
MachineMatrix = MachineMatrix; // Save
InitAndCleanup.ReopenSocketDueToReadError = true;
Common.ReopenSocketDueToReadError = true;
UpdateClientSockets("UpdateMachineMatrix");
@@ -1044,7 +1044,7 @@ internal static class MachineStuff
Common.MoveMouseToCenter();
}
InitAndCleanup.ReleaseAllKeys();
Common.ReleaseAllKeys();
Common.UpdateMultipleModeIconAndMenu();
}

View File

@@ -157,7 +157,7 @@ internal static class Receiver
if (!p.IsEmpty)
{
Clipboard.HasSwitchedMachineSinceLastCopy = true;
Common.HasSwitchedMachineSinceLastCopy = true;
Logger.LogDebug(string.Format(
CultureInfo.CurrentCulture,
@@ -274,7 +274,7 @@ internal static class Receiver
Common.PackageReceived.Clipboard++;
if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop)
{
Clipboard.clipboardCopiedTime = Common.GetTick();
Common.clipboardCopiedTime = Common.GetTick();
GetNameOfMachineWithClipboardData(package);
SignalBigClipboardData();
}
@@ -282,10 +282,10 @@ internal static class Receiver
break;
case PackageType.MachineSwitched:
if (Common.GetTick() - Clipboard.clipboardCopiedTime < Clipboard.BIG_CLIPBOARD_DATA_TIMEOUT && (package.Des == Common.MachineID))
if (Common.GetTick() - Common.clipboardCopiedTime < Common.BIG_CLIPBOARD_DATA_TIMEOUT && (package.Des == Common.MachineID))
{
Clipboard.clipboardCopiedTime = 0;
Clipboard.GetRemoteClipboard("PackageType.MachineSwitched");
Common.clipboardCopiedTime = 0;
Common.GetRemoteClipboard("PackageType.MachineSwitched");
}
break;
@@ -297,7 +297,7 @@ internal static class Receiver
if (package.Des == Common.MachineID || package.Des == ID.ALL)
{
GetNameOfMachineWithClipboardData(package);
Clipboard.GetRemoteClipboard("mspaint," + Clipboard.LastMachineWithClipboardData);
Common.GetRemoteClipboard("mspaint," + Common.LastMachineWithClipboardData);
}
}
@@ -326,10 +326,10 @@ internal static class Receiver
Thread.UpdateThreads(thread);
string remoteMachine = package.MachineName;
System.Net.Sockets.TcpClient client = Clipboard.ConnectToRemoteClipboardSocket(remoteMachine);
System.Net.Sockets.TcpClient client = Common.ConnectToRemoteClipboardSocket(remoteMachine);
bool clientPushData = true;
if (Clipboard.ShakeHand(ref remoteMachine, client.Client, out Stream enStream, out Stream deStream, ref clientPushData, ref package.PostAction))
if (Common.ShakeHand(ref remoteMachine, client.Client, out Stream enStream, out Stream deStream, ref clientPushData, ref package.PostAction))
{
SocketStuff.SendClipboardData(client.Client, enStream);
}
@@ -360,7 +360,7 @@ internal static class Receiver
case PackageType.ClipboardText:
case PackageType.ClipboardImage:
Clipboard.clipboardCopiedTime = 0;
Common.clipboardCopiedTime = 0;
if (package.Type == PackageType.ClipboardImage)
{
Common.PackageReceived.ClipboardImage++;
@@ -372,7 +372,7 @@ internal static class Receiver
if (tcp != null)
{
Clipboard.ReceiveClipboardDataUsingTCP(
Common.ReceiveClipboardDataUsingTCP(
package,
package.Type == PackageType.ClipboardImage,
tcp);
@@ -381,10 +381,10 @@ internal static class Receiver
break;
case PackageType.HideMouse:
Clipboard.HasSwitchedMachineSinceLastCopy = true;
Common.HasSwitchedMachineSinceLastCopy = true;
Common.HideMouseCursor(true);
Helper.MainFormDotEx(false);
InitAndCleanup.ReleaseAllKeys();
Common.ReleaseAllKeys();
break;
default:
@@ -405,11 +405,11 @@ internal static class Receiver
internal static void GetNameOfMachineWithClipboardData(DATA package)
{
Clipboard.LastIDWithClipboardData = package.Src;
List<MachineInf> matchingMachines = MachineStuff.MachinePool.TryFindMachineByID(Clipboard.LastIDWithClipboardData);
Common.LastIDWithClipboardData = package.Src;
List<MachineInf> matchingMachines = MachineStuff.MachinePool.TryFindMachineByID(Common.LastIDWithClipboardData);
if (matchingMachines.Count >= 1)
{
Clipboard.LastMachineWithClipboardData = matchingMachines[0].Name.Trim();
Common.LastMachineWithClipboardData = matchingMachines[0].Name.Trim();
}
/*

View File

@@ -84,7 +84,7 @@ namespace MouseWithoutBorders
if ((connectedClientSocket = Common.GetConnectedClientSocket()) != null)
{
ShowStatus($"Connected from local IP Address: {connectedClientSocket.Address}.");
InitAndCleanup.UpdateMachineTimeAndID();
Common.UpdateMachineTimeAndID();
Common.MMSleep(1);
connected = true;

View File

@@ -22,8 +22,6 @@ using Microsoft.PowerToys.Telemetry;
// </history>
using MouseWithoutBorders.Class;
using MouseWithoutBorders.Core;
using Clipboard = MouseWithoutBorders.Core.Clipboard;
using Timer = System.Windows.Forms.Timer;
[module: SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions", Scope = "member", Target = "MouseWithoutBorders.frmMatrix.#buttonOK_Click(System.Object,System.EventArgs)", Justification = "Dotnet port with style preservation")]
@@ -112,7 +110,7 @@ namespace MouseWithoutBorders
{
SocketStuff.InvalidKeyFound = false;
showInvalidKeyMessage = false;
InitAndCleanup.ReopenSocketDueToReadError = true;
Common.ReopenSocketDueToReadError = true;
Common.ReopenSockets(true);
for (int i = 0; i < 10; i++)
@@ -782,7 +780,7 @@ namespace MouseWithoutBorders
ShowUpdateMessage();
Clipboard.HasSwitchedMachineSinceLastCopy = true;
Common.HasSwitchedMachineSinceLastCopy = true;
}
private void CheckBoxDisableCAD_CheckedChanged(object sender, EventArgs e)

View File

@@ -139,13 +139,13 @@ namespace MouseWithoutBorders
{
if (cleanup)
{
InitAndCleanup.Cleanup();
Common.Cleanup();
}
Helper.WndProcCounter++;
if (!Common.RunOnScrSaverDesktop)
{
InitAndCleanup.ReleaseAllKeys();
Common.ReleaseAllKeys();
}
Helper.RunDDHelper(true);
@@ -412,7 +412,7 @@ namespace MouseWithoutBorders
count = 0;
InitAndCleanup.InitDone = true;
Common.InitDone = true;
#if SHOW_ON_WINLOGON
if (Common.RunOnLogonDesktop)
{
@@ -423,39 +423,39 @@ namespace MouseWithoutBorders
if ((count % 2) == 0)
{
if (InitAndCleanup.PleaseReopenSocket == 10 || (InitAndCleanup.PleaseReopenSocket > 0 && count > 0 && count % 300 == 0))
if (Common.PleaseReopenSocket == 10 || (Common.PleaseReopenSocket > 0 && count > 0 && count % 300 == 0))
{
if (!Common.AtLeastOneSocketEstablished() || InitAndCleanup.PleaseReopenSocket == 10)
if (!Common.AtLeastOneSocketEstablished() || Common.PleaseReopenSocket == 10)
{
Thread.Sleep(1000);
if (InitAndCleanup.PleaseReopenSocket > 0)
if (Common.PleaseReopenSocket > 0)
{
InitAndCleanup.PleaseReopenSocket--;
Common.PleaseReopenSocket--;
}
// Double check.
if (!Common.AtLeastOneSocketEstablished())
{
Common.GetMachineName();
Logger.LogDebug("Common.pleaseReopenSocket: " + InitAndCleanup.PleaseReopenSocket.ToString(CultureInfo.InvariantCulture));
Logger.LogDebug("Common.pleaseReopenSocket: " + Common.PleaseReopenSocket.ToString(CultureInfo.InvariantCulture));
Common.ReopenSockets(false);
MachineStuff.NewDesMachineID = Common.DesMachineID = Common.MachineID;
}
}
else
{
InitAndCleanup.PleaseReopenSocket = 0;
Common.PleaseReopenSocket = 0;
}
}
if (InitAndCleanup.PleaseReopenSocket == InitAndCleanup.REOPEN_WHEN_HOTKEY)
if (Common.PleaseReopenSocket == Common.REOPEN_WHEN_HOTKEY)
{
InitAndCleanup.PleaseReopenSocket = 0;
Common.PleaseReopenSocket = 0;
Common.ReopenSockets(true);
}
else if (InitAndCleanup.PleaseReopenSocket == InitAndCleanup.REOPEN_WHEN_WSAECONNRESET)
else if (Common.PleaseReopenSocket == Common.REOPEN_WHEN_WSAECONNRESET)
{
InitAndCleanup.PleaseReopenSocket = 0;
Common.PleaseReopenSocket = 0;
Thread.Sleep(1000);
MachineStuff.UpdateClientSockets("REOPEN_WHEN_WSAECONNRESET");
}

View File

@@ -4,6 +4,28 @@
[Other Logs]
===============
= MouseWithoutBorders.Common
Comma = System.Char[]
--System.Char[] = System.Char[]: N/A
Star = System.Char[]
--System.Char[] = System.Char[]: N/A
NullSeparator = System.Char[]
--System.Char[] = System.Char[]: N/A
lastClipboardEventTime = 0
clipboardCopiedTime = 0
<LastIDWithClipboardData>k__BackingField = NONE
<NextClipboardViewer>k__BackingField = 0
<IsClipboardDataImage>k__BackingField = False
lastClipboardObject =
<HasSwitchedMachineSinceLastCopy>k__BackingField = False
ClipboardThreadOldLock = Lock
--_owningThreadId = 0
--_state = 0
--_recursionCount = 0
--_spinCount = 22
--_waiterStartTimeMs = 0
--s_contentionCount = 0
--s_maxSpinCount = 22
--s_minSpinCountForAdaptiveSpin = -100
screenWidth = 0
screenHeight = 0
lastX = 0
@@ -77,6 +99,17 @@ LegalKeyDictionary = Concurrent.ConcurrentDictionary`2[System.String,System.Byte
--_budget = ????????????
--_growLockArray = True
--_comparerIsDefaultForClasses = False
initDone = False
REOPEN_WHEN_WSAECONNRESET = -10054
REOPEN_WHEN_HOTKEY = -10055
PleaseReopenSocket = 0
ReopenSocketDueToReadError = False
<LastResumeSuspendTime>k__BackingField = ????????????
--_dateData = ????????????
--MinValue = 01/01/0001 00:00:00
--MaxValue = 31/12/9999 23:59:59
--UnixEpoch = 01/01/1970 00:00:00
lastReleaseAllKeysCall = 0
PackageSent = MouseWithoutBorders.PackageMonitor
--Keyboard = 0
--Mouse = 0
@@ -120,6 +153,12 @@ p = {X=0,Y=0}
--y = 0
--Empty = {X=0,Y=0}
<IpcChannelCreated>k__BackingField = False
BIG_CLIPBOARD_DATA_TIMEOUT = 30000
MAX_CLIPBOARD_DATA_SIZE_CAN_BE_SENT_INSTANTLY_TCP = 1048576
MAX_CLIPBOARD_FILE_SIZE_CAN_BE_SENT = 104857600
TEXT_HEADER_SIZE = 12
DATA_SIZE = 48
TEXT_TYPE_SEP = {4CFF57F7-BEDD-43d5-AE8F-27A61E886F2F}
TOGGLE_ICONS_SIZE = 4
ICON_ONE = 0
ICON_ALL = 1
@@ -156,36 +195,6 @@ WM_KEYDOWN = 256
WM_KEYUP = 257
WM_SYSKEYDOWN = 260
WM_SYSKEYUP = 261
[Clipboard]
===============
Comma = System.Char[]
--System.Char[] = System.Char[]: N/A
Star = System.Char[]
--System.Char[] = System.Char[]: N/A
NullSeparator = System.Char[]
--System.Char[] = System.Char[]: N/A
lastClipboardEventTime = 0
clipboardCopiedTime = 0
<LastIDWithClipboardData>k__BackingField = NONE
<NextClipboardViewer>k__BackingField = 0
<IsClipboardDataImage>k__BackingField = False
lastClipboardObject =
<HasSwitchedMachineSinceLastCopy>k__BackingField = False
ClipboardThreadOldLock = Lock
--_owningThreadId = 0
--_state = 0
--_recursionCount = 0
--_spinCount = 22
--_waiterStartTimeMs = 0
--s_contentionCount = 0
--s_maxSpinCount = 22
--s_minSpinCountForAdaptiveSpin = -100
BIG_CLIPBOARD_DATA_TIMEOUT = 30000
MAX_CLIPBOARD_DATA_SIZE_CAN_BE_SENT_INSTANTLY_TCP = 1048576
MAX_CLIPBOARD_FILE_SIZE_CAN_BE_SENT = 104857600
TEXT_HEADER_SIZE = 12
DATA_SIZE = 48
TEXT_TYPE_SEP = {4CFF57F7-BEDD-43d5-AE8F-27A61E886F2F}
[DragDrop]
===============
isDragging = False
@@ -240,19 +249,6 @@ actualLastPos = {X=0,Y=0}
--Empty = {X=0,Y=0}
myLastX = 0
myLastY = 0
[InitAndCleanup]
===============
initDone = False
REOPEN_WHEN_WSAECONNRESET = -10054
REOPEN_WHEN_HOTKEY = -10055
PleaseReopenSocket = 0
ReopenSocketDueToReadError = False
<LastResumeSuspendTime>k__BackingField = ????????????
--_dateData = ????????????
--MinValue = 01/01/0001 00:00:00
--MaxValue = 31/12/9999 23:59:59
--UnixEpoch = 01/01/1970 00:00:00
lastReleaseAllKeysCall = 0
[Helper]
===============
signalHelperToExit = False

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -20,7 +20,7 @@ public partial class CommandContextItemViewModel(ICommandContextItem contextItem
public KeyChord? RequestedShortcut { get; private set; }
public bool HasRequestedShortcut => RequestedShortcut != null && (RequestedShortcut.Value != nullKeyChord);
public bool HasRequestedShortcut => RequestedShortcut is not null && (RequestedShortcut.Value != nullKeyChord);
public override void InitializeProperties()
{
@@ -32,7 +32,7 @@ public partial class CommandContextItemViewModel(ICommandContextItem contextItem
base.InitializeProperties();
var contextItem = Model.Unsafe;
if (contextItem == null)
if (contextItem is null)
{
return; // throw?
}

View File

@@ -68,7 +68,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
{
get
{
List<IContextItemViewModel> l = _defaultCommandContextItem == null ?
List<IContextItemViewModel> l = _defaultCommandContextItem is null ?
new() :
[_defaultCommandContextItem];
@@ -100,7 +100,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
}
var model = _commandItemModel.Unsafe;
if (model == null)
if (model is null)
{
return;
}
@@ -128,7 +128,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
}
var model = _commandItemModel.Unsafe;
if (model == null)
if (model is null)
{
return;
}
@@ -136,7 +136,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
Command.InitializeProperties();
var listIcon = model.Icon;
if (listIcon != null)
if (listIcon is not null)
{
_listItemIcon = new(listIcon);
_listItemIcon.InitializeProperties();
@@ -172,13 +172,13 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
}
var model = _commandItemModel.Unsafe;
if (model == null)
if (model is null)
{
return;
}
var more = model.MoreCommands;
if (more != null)
if (more is not null)
{
MoreCommands = more
.Select(item =>
@@ -300,7 +300,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
protected virtual void FetchProperty(string propertyName)
{
var model = this._commandItemModel.Unsafe;
if (model == null)
if (model is null)
{
return; // throw?
}
@@ -308,7 +308,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
switch (propertyName)
{
case nameof(Command):
if (Command != null)
if (Command is not null)
{
Command.PropertyChanged -= Command_PropertyChanged;
}
@@ -339,7 +339,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
case nameof(model.MoreCommands):
var more = model.MoreCommands;
if (more != null)
if (more is not null)
{
var newContextMenu = more
.Select(item =>
@@ -394,7 +394,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
// Extensions based on Command Palette SDK < 0.3 CommandItem class won't notify when Title changes because Command
// or Command.Name change. This is a workaround to ensure that the Title is always up-to-date for extensions with old SDK.
var model = _commandItemModel.Unsafe;
if (model != null)
if (model is not null)
{
_itemTitle = model.Title;
}
@@ -430,7 +430,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
Command.SafeCleanup();
var model = _commandItemModel.Unsafe;
if (model != null)
if (model is not null)
{
model.PropChanged -= Model_PropChanged;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -298,11 +298,11 @@ public partial class ListViewModel : PageViewModel, IDisposable
[RelayCommand]
private void InvokeItem(ListItemViewModel? item)
{
if (item != null)
if (item is not null)
{
WeakReferenceMessenger.Default.Send<PerformCommandMessage>(new(item.Command.Model, item.Model));
}
else if (ShowEmptyContent && EmptyContent.PrimaryCommand?.Model.Unsafe != null)
else if (ShowEmptyContent && EmptyContent.PrimaryCommand?.Model.Unsafe is not null)
{
WeakReferenceMessenger.Default.Send<PerformCommandMessage>(new(
EmptyContent.PrimaryCommand.Command.Model,
@@ -314,14 +314,14 @@ public partial class ListViewModel : PageViewModel, IDisposable
[RelayCommand]
private void InvokeSecondaryCommand(ListItemViewModel? item)
{
if (item != null)
if (item is not null)
{
if (item.SecondaryCommand != null)
if (item.SecondaryCommand is not null)
{
WeakReferenceMessenger.Default.Send<PerformCommandMessage>(new(item.SecondaryCommand.Command.Model, item.Model));
}
}
else if (ShowEmptyContent && EmptyContent.SecondaryCommand?.Model.Unsafe != null)
else if (ShowEmptyContent && EmptyContent.SecondaryCommand?.Model.Unsafe is not null)
{
WeakReferenceMessenger.Default.Send<PerformCommandMessage>(new(
EmptyContent.SecondaryCommand.Command.Model,
@@ -332,12 +332,12 @@ public partial class ListViewModel : PageViewModel, IDisposable
[RelayCommand]
private void UpdateSelectedItem(ListItemViewModel? item)
{
if (_lastSelectedItem != null)
if (_lastSelectedItem is not null)
{
_lastSelectedItem.PropertyChanged -= SelectedItemPropertyChanged;
}
if (item != null)
if (item is not null)
{
SetSelectedItem(item);
}
@@ -383,7 +383,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
private void SelectedItemPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
var item = _lastSelectedItem;
if (item == null)
if (item is null)
{
return;
}
@@ -438,7 +438,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
base.InitializeProperties();
var model = _model.Unsafe;
if (model == null)
if (model is null)
{
return; // throw?
}
@@ -465,7 +465,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
public void LoadMoreIfNeeded()
{
var model = this._model.Unsafe;
if (model == null)
if (model is null)
{
return;
}
@@ -509,7 +509,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
base.FetchProperty(propertyName);
var model = this._model.Unsafe;
if (model == null)
if (model is null)
{
return; // throw?
}
@@ -540,7 +540,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
private void UpdateEmptyContent()
{
UpdateProperty(nameof(ShowEmptyContent));
if (!ShowEmptyContent || EmptyContent.Model.Unsafe == null)
if (!ShowEmptyContent || EmptyContent.Model.Unsafe is null)
{
return;
}
@@ -588,7 +588,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
}
var model = _model.Unsafe;
if (model != null)
if (model is not null)
{
model.ItemsChanged -= Model_ItemsChanged;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -9,6 +9,7 @@ using ManagedCommon;
using Microsoft.CmdPal.Common.Helpers;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CmdPal.Ext.Apps;
using Microsoft.CmdPal.UI.ViewModels.Messages;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
using Microsoft.Extensions.DependencyInjection;
@@ -202,7 +203,7 @@ public partial class MainListPage : DynamicListPage,
// If we don't have any previous filter results to work with, start
// with a list of all our commands & apps.
if (_filteredItems == null)
if (_filteredItems is null)
{
_filteredItems = commands;
_filteredItemsIncludesApps = _includeApps;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -47,7 +47,8 @@
<Flyout
x:Name="ContextMenuFlyout"
FlyoutPresenterStyle="{StaticResource ContextMenuFlyoutStyle}"
Opened="ContextMenuFlyout_Opened">
Opened="ContextMenuFlyout_Opened"
ShouldConstrainToRootBounds="False">
<cpcontrols:ContextMenu x:Name="ContextControl" />
</Flyout>

View File

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

View File

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

View File

@@ -2,6 +2,7 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using CommunityToolkit.WinUI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
@@ -35,6 +36,17 @@ public partial class ContentIcon : FontIcon
{
if (this.FindDescendants().OfType<Grid>().FirstOrDefault() is Grid grid && Content is not null)
{
if (grid.Children.Contains(Content))
{
return;
}
if (Content is FrameworkElement element && element.Parent is not null)
{
Debug.Assert(false, $"IconBoxElement Content is already parented to {element.Parent.GetType().Name}");
return;
}
grid.Children.Add(Content);
}
}

View File

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

View File

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

View File

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

View File

@@ -2,7 +2,6 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CmdPal.UI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Markup;
@@ -80,12 +79,12 @@ public sealed partial class KeyVisual : Control
private void Update()
{
if (_keyVisual == null)
if (_keyVisual is null)
{
return;
}
if (_keyVisual.Content != null)
if (_keyVisual.Content is not null)
{
if (_keyVisual.Content.GetType() == typeof(string))
{

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,13 +2,6 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CmdPal.Ext.Bookmarks;
using Microsoft.UI.Xaml.Documents;
using Microsoft.Win32;
namespace Microsoft.CmdPal.UI.Helpers;
@@ -63,7 +56,7 @@ internal static class GpoValueChecker
{
using (RegistryKey? key = rootKey.OpenSubKey(subKeyPath, false))
{
if (key == null)
if (key is null)
{
return null;
}

View File

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

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