mirror of
https://github.com/microsoft/PowerToys.git
synced 2026-04-05 18:57:19 +02:00
Add the Command Palette module (#37908)
Windows Command Palette ("CmdPal") is the next iteration of PowerToys Run. With extensibility at its core, the Command Palette is your one-stop launcher to start _anything_.
By default, CmdPal is bound to <kbd>Win+Alt+Space</kbd>.


----
This brings the current preview version of CmdPal into the upstream PowerToys repo. There are still lots of bugs to work out, but it's reached the state we're ready to start sharing it with the world. From here, we can further collaborate with the community on the features that are important, and ensuring that we've got a most robust API to enable developers to build whatever extensions they want.
Most of the built-in PT Run modules have already been ported to CmdPal's extension API. Those include:
* Installed apps
* Shell commands
* File search (powered by the indexer)
* Windows Registry search
* Web search
* Windows Terminal Profiles
* Windows Services
* Windows settings
There are a couple new extensions built-in
* You can now search for packages on `winget` and install them right from the palette. This also powers searching for extensions for the palette
* The calculator has an entirely new implementation. This is currently less feature complete than the original PT Run one - we're looking forward to updating it to be more complete for future ingestion in Windows
* "Bookmarks" allow you to save shortcuts to files, folders, and webpages as top-level commands in the palette.
We've got a bunch of other samples too, in this repo and elsewhere
### PowerToys specific notes
CmdPal will eventually graduate out of PowerToys to live as its own application, which is why it's implemented just a little differently than most other modules. Enabling CmdPal will install its `msix` package.
The CI was minorly changed to support CmdPal version numbers independent of PowerToys itself. It doesn't make sense for us to start CmdPal at v0.90, and in the future, we want to be able to rev CmdPal independently of PT itself.
Closes #3200, closes #3600, closes #7770, closes #34273, closes #36471, closes #20976, closes #14495
-----
TODOs et al
**Blocking:**
- [ ] Images and descriptions in Settings and OOBE need to be properly defined, as mentioned before
- [ ] Niels is on it
- [x] Doesn't start properly from PowerToys unless the fix PR is merged.
- https://github.com/zadjii-msft/PowerToys/pull/556 merged
- [x] I seem to lose focus a lot when I press on some limits, like between the search bar and the results.
- This is https://github.com/zadjii-msft/PowerToys/issues/427
- [x] Turned off an extension like Calculator and it was still working.
- Need to get rid of that toggle, it doesn't do anything currently
- [x] `ListViewModel.<FetchItems>` crash
- Pretty confident that was fixed in https://github.com/zadjii-msft/PowerToys/pull/553
**Not blocking / improvements:**
- Show the shortcut through settings, as mentioned before, or create a button that would open CmdPalette settings.
- When PowerToys starts, CmdPalette is always shown if enabled. That's weird when just starting PowerToys/ logging in to the computer with PowerToys auto-start activated. I think this should at least be a setting.
- Needing to double press a result for it to do the default action seems quirky. If one is already selected, I think just pressing should be enough for it to do the action.
- This is currently a setting, though we're thinking of changing the setting even more: https://github.com/zadjii-msft/PowerToys/issues/392
- There's no URI extension. Was surprised when typing a URL that it only proposed a web search.
- [x] There's no System commands extension. Was expecting to be able to quickly restart the computer by typing restart but it wasn't there.
- This is in PR https://github.com/zadjii-msft/PowerToys/pull/452
---------
Co-authored-by: joadoumie <98557455+joadoumie@users.noreply.github.com>
Co-authored-by: Jordi Adoumie <jordiadoumie@microsoft.com>
Co-authored-by: Mike Griese <zadjii@gmail.com>
Co-authored-by: Niels Laute <niels.laute@live.nl>
Co-authored-by: Michael Hawker <24302614+michael-hawker@users.noreply.github.com>
Co-authored-by: Stefan Markovic <57057282+stefansjfw@users.noreply.github.com>
Co-authored-by: Seraphima <zykovas91@gmail.com>
Co-authored-by: Jaime Bernardo <jaime@janeasystems.com>
Co-authored-by: Kristen Schau <47155823+krschau@users.noreply.github.com>
Co-authored-by: Eric Johnson <ericjohnson327@gmail.com>
Co-authored-by: Ethan Fang <ethanfang@microsoft.com>
Co-authored-by: Yu Leng (from Dev Box) <yuleng@microsoft.com>
Co-authored-by: Clint Rutkas <clint@rutkas.com>
This commit is contained in:
@@ -0,0 +1,342 @@
|
||||
// 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 AdaptiveCards.Rendering.WinUI3;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
public sealed class AdaptiveCardsConfig
|
||||
{
|
||||
public static AdaptiveHostConfig Light { get; }
|
||||
|
||||
public static AdaptiveHostConfig Dark { get; }
|
||||
|
||||
static AdaptiveCardsConfig()
|
||||
{
|
||||
Light = AdaptiveHostConfig.FromJsonString(LightHostConfigString).HostConfig;
|
||||
Dark = AdaptiveHostConfig.FromJsonString(DarkHostConfigString).HostConfig;
|
||||
}
|
||||
|
||||
public static readonly string DarkHostConfigString = """
|
||||
{
|
||||
"spacing": {
|
||||
"small": 4,
|
||||
"default": 8,
|
||||
"medium": 20,
|
||||
"large": 30,
|
||||
"extraLarge": 40,
|
||||
"padding": 8
|
||||
},
|
||||
"separator": {
|
||||
"lineThickness": 0,
|
||||
"lineColor": "#C8FFFFFF"
|
||||
},
|
||||
"supportsInteractivity": true,
|
||||
"fontTypes": {
|
||||
"default": {
|
||||
"fontFamily": "'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif",
|
||||
"fontSizes": {
|
||||
"small": 12,
|
||||
"default": 12,
|
||||
"medium": 14,
|
||||
"large": 20,
|
||||
"extraLarge": 26
|
||||
},
|
||||
"fontWeights": {
|
||||
"lighter": 200,
|
||||
"default": 400,
|
||||
"bolder": 600
|
||||
}
|
||||
},
|
||||
"monospace": {
|
||||
"fontFamily": "'Courier New', Courier, monospace",
|
||||
"fontSizes": {
|
||||
"small": 12,
|
||||
"default": 12,
|
||||
"medium": 14,
|
||||
"large": 18,
|
||||
"extraLarge": 26
|
||||
},
|
||||
"fontWeights": {
|
||||
"lighter": 200,
|
||||
"default": 400,
|
||||
"bolder": 600
|
||||
}
|
||||
}
|
||||
},
|
||||
"containerStyles": {
|
||||
"default": {
|
||||
"backgroundColor": "#00000000",
|
||||
"borderColor": "#00000000",
|
||||
"foregroundColors": {
|
||||
"default": {
|
||||
"default": "#FFFFFF",
|
||||
"subtle": "#C8FFFFFF"
|
||||
},
|
||||
"accent": {
|
||||
"default": "#0063B1",
|
||||
"subtle": "#880063B1"
|
||||
},
|
||||
"attention": {
|
||||
"default": "#FF5555",
|
||||
"subtle": "#DDFF5555"
|
||||
},
|
||||
"good": {
|
||||
"default": "#54a254",
|
||||
"subtle": "#DD54a254"
|
||||
},
|
||||
"warning": {
|
||||
"default": "#c3ab23",
|
||||
"subtle": "#DDc3ab23"
|
||||
}
|
||||
}
|
||||
},
|
||||
"emphasis": {
|
||||
"backgroundColor": "#09FFFFFF",
|
||||
"borderColor": "#09FFFFFF",
|
||||
"foregroundColors": {
|
||||
"default": {
|
||||
"default": "#FFFFFF",
|
||||
"subtle": "#C8FFFFFF"
|
||||
},
|
||||
"accent": {
|
||||
"default": "#2E89FC",
|
||||
"subtle": "#882E89FC"
|
||||
},
|
||||
"attention": {
|
||||
"default": "#FF5555",
|
||||
"subtle": "#DDFF5555"
|
||||
},
|
||||
"good": {
|
||||
"default": "#54a254",
|
||||
"subtle": "#DD54a254"
|
||||
},
|
||||
"warning": {
|
||||
"default": "#c3ab23",
|
||||
"subtle": "#DDc3ab23"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"imageSizes": {
|
||||
"small": 16,
|
||||
"medium": 24,
|
||||
"large": 32
|
||||
},
|
||||
"actions": {
|
||||
"maxActions": 5,
|
||||
"spacing": "default",
|
||||
"buttonSpacing": 8,
|
||||
"showCard": {
|
||||
"actionMode": "inline",
|
||||
"inlineTopMargin": 8
|
||||
},
|
||||
"actionsOrientation": "horizontal",
|
||||
"actionAlignment": "stretch"
|
||||
},
|
||||
"adaptiveCard": {
|
||||
"allowCustomStyle": false
|
||||
},
|
||||
"imageSet": {
|
||||
"imageSize": "medium",
|
||||
"maxImageHeight": 100
|
||||
},
|
||||
"factSet": {
|
||||
"title": {
|
||||
"color": "default",
|
||||
"size": "default",
|
||||
"isSubtle": false,
|
||||
"weight": "bolder",
|
||||
"wrap": true,
|
||||
"maxWidth": 150
|
||||
},
|
||||
"value": {
|
||||
"color": "default",
|
||||
"size": "default",
|
||||
"isSubtle": false,
|
||||
"weight": "default",
|
||||
"wrap": true
|
||||
},
|
||||
"spacing": 8
|
||||
},
|
||||
"textStyles": {
|
||||
"heading": {
|
||||
"size": "large",
|
||||
"weight": "bolder",
|
||||
"color": "default",
|
||||
"isSubtle": false,
|
||||
"fontType": "default"
|
||||
},
|
||||
"columnHeader": {
|
||||
"size": "medium",
|
||||
"weight": "bolder",
|
||||
"color": "default",
|
||||
"isSubtle": false,
|
||||
"fontType": "default"
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
public static readonly string LightHostConfigString = """
|
||||
{
|
||||
"spacing": {
|
||||
"small": 4,
|
||||
"default": 8,
|
||||
"medium": 20,
|
||||
"large": 30,
|
||||
"extraLarge": 40,
|
||||
"padding": 8
|
||||
},
|
||||
"separator": {
|
||||
"lineThickness": 0,
|
||||
"lineColor": "#606060"
|
||||
},
|
||||
"supportsInteractivity": true,
|
||||
"fontTypes": {
|
||||
"default": {
|
||||
"fontFamily": "'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif",
|
||||
"fontSizes": {
|
||||
"small": 12,
|
||||
"default": 12,
|
||||
"medium": 14,
|
||||
"large": 20,
|
||||
"extraLarge": 26
|
||||
},
|
||||
"fontWeights": {
|
||||
"lighter": 200,
|
||||
"default": 400,
|
||||
"bolder": 600
|
||||
}
|
||||
},
|
||||
"monospace": {
|
||||
"fontFamily": "'Courier New', Courier, monospace",
|
||||
"fontSizes": {
|
||||
"small": 12,
|
||||
"default": 12,
|
||||
"medium": 14,
|
||||
"large": 18,
|
||||
"extraLarge": 26
|
||||
},
|
||||
"fontWeights": {
|
||||
"lighter": 200,
|
||||
"default": 400,
|
||||
"bolder": 600
|
||||
}
|
||||
}
|
||||
},
|
||||
"containerStyles": {
|
||||
"default": {
|
||||
"backgroundColor": "#00000000",
|
||||
"borderColor": "#00000000",
|
||||
"foregroundColors": {
|
||||
"default": {
|
||||
"default": "#E6000000",
|
||||
"subtle": "#99000000"
|
||||
},
|
||||
"accent": {
|
||||
"default": "#0063B1",
|
||||
"subtle": "#880063B1"
|
||||
},
|
||||
"attention": {
|
||||
"default": "#C00000",
|
||||
"subtle": "#DDC00000"
|
||||
},
|
||||
"good": {
|
||||
"default": "#54a254",
|
||||
"subtle": "#DD54a254"
|
||||
},
|
||||
"warning": {
|
||||
"default": "#c3ab23",
|
||||
"subtle": "#DDc3ab23"
|
||||
}
|
||||
}
|
||||
},
|
||||
"emphasis": {
|
||||
"backgroundColor": "#80F6F6F6",
|
||||
"borderColor": "#80F6F6F6",
|
||||
"foregroundColors": {
|
||||
"default": {
|
||||
"default": "#E6000000",
|
||||
"subtle": "#99000000"
|
||||
},
|
||||
"accent": {
|
||||
"default": "#2E89FC",
|
||||
"subtle": "#882E89FC"
|
||||
},
|
||||
"attention": {
|
||||
"default": "#C00000",
|
||||
"subtle": "#DDC00000"
|
||||
},
|
||||
"good": {
|
||||
"default": "#54a254",
|
||||
"subtle": "#DD54a254"
|
||||
},
|
||||
"warning": {
|
||||
"default": "#c3ab23",
|
||||
"subtle": "#DDc3ab23"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"imageSizes": {
|
||||
"small": 16,
|
||||
"medium": 24,
|
||||
"large": 32
|
||||
},
|
||||
"actions": {
|
||||
"maxActions": 5,
|
||||
"spacing": "default",
|
||||
"buttonSpacing": 8,
|
||||
"showCard": {
|
||||
"actionMode": "inline",
|
||||
"inlineTopMargin": 8
|
||||
},
|
||||
"actionsOrientation": "horizontal",
|
||||
"actionAlignment": "stretch"
|
||||
},
|
||||
"adaptiveCard": {
|
||||
"allowCustomStyle": false
|
||||
},
|
||||
"imageSet": {
|
||||
"imageSize": "medium",
|
||||
"maxImageHeight": 100
|
||||
},
|
||||
"factSet": {
|
||||
"title": {
|
||||
"color": "default",
|
||||
"size": "default",
|
||||
"isSubtle": false,
|
||||
"weight": "bolder",
|
||||
"wrap": true,
|
||||
"maxWidth": 150
|
||||
},
|
||||
"value": {
|
||||
"color": "default",
|
||||
"size": "default",
|
||||
"isSubtle": false,
|
||||
"weight": "default",
|
||||
"wrap": true
|
||||
},
|
||||
"spacing": 8
|
||||
},
|
||||
"textStyles": {
|
||||
"heading": {
|
||||
"size": "large",
|
||||
"weight": "bolder",
|
||||
"color": "default",
|
||||
"isSubtle": false,
|
||||
"fontType": "default"
|
||||
},
|
||||
"columnHeader": {
|
||||
"size": "medium",
|
||||
"weight": "bolder",
|
||||
"color": "default",
|
||||
"isSubtle": false,
|
||||
"fontType": "default"
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
}
|
||||
261
src/modules/cmdpal/Microsoft.CmdPal.UI/Controls/CommandBar.xaml
Normal file
261
src/modules/cmdpal/Microsoft.CmdPal.UI/Controls/CommandBar.xaml
Normal file
@@ -0,0 +1,261 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<UserControl
|
||||
x:Class="Microsoft.CmdPal.UI.Controls.CommandBar"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:cmdpalUI="using:Microsoft.CmdPal.UI"
|
||||
xmlns:converters="using:CommunityToolkit.WinUI.Converters"
|
||||
xmlns:cpcontrols="using:Microsoft.CmdPal.UI.Controls"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:help="using:Microsoft.CmdPal.UI.Helpers"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:ui="using:CommunityToolkit.WinUI"
|
||||
xmlns:viewmodels="using:Microsoft.CmdPal.UI.ViewModels"
|
||||
Background="Transparent"
|
||||
mc:Ignorable="d">
|
||||
|
||||
<UserControl.Resources>
|
||||
<ResourceDictionary>
|
||||
<converters:StringVisibilityConverter
|
||||
x:Key="StringNotEmptyToVisibilityConverter"
|
||||
EmptyValue="Collapsed"
|
||||
NotEmptyValue="Visible" />
|
||||
<converters:BoolToVisibilityConverter
|
||||
x:Key="BoolToInvertedVisibilityConverter"
|
||||
FalseValue="Visible"
|
||||
TrueValue="Collapsed" />
|
||||
|
||||
<cmdpalUI:MessageStateToSeverityConverter x:Key="MessageStateToSeverityConverter" />
|
||||
<cmdpalUI:KeyChordToStringConverter x:Key="KeyChordToStringConverter" />
|
||||
|
||||
<StackLayout
|
||||
x:Name="VerticalStackLayout"
|
||||
Orientation="Vertical"
|
||||
Spacing="4" />
|
||||
|
||||
<!-- Template for actions in the mode actions dropdown button -->
|
||||
<DataTemplate x:Key="ContextMenuViewModelTemplate" x:DataType="viewmodels:CommandContextItemViewModel">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="32" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<cpcontrols:IconBox
|
||||
Width="16"
|
||||
Height="16"
|
||||
Margin="4,0,0,0"
|
||||
HorizontalAlignment="Left"
|
||||
SourceKey="{x:Bind Icon, Mode=OneWay}"
|
||||
SourceRequested="{x:Bind help:IconCacheProvider.SourceRequested}" />
|
||||
<TextBlock
|
||||
Grid.Column="1"
|
||||
VerticalAlignment="Center"
|
||||
Text="{x:Bind Title, Mode=OneWay}" />
|
||||
<TextBlock
|
||||
Grid.Column="2"
|
||||
Margin="16,0,0,0"
|
||||
HorizontalAlignment="Right"
|
||||
VerticalAlignment="Center"
|
||||
Foreground="{ThemeResource MenuFlyoutItemKeyboardAcceleratorTextForeground}"
|
||||
Style="{StaticResource CaptionTextBlockStyle}"
|
||||
Text="{x:Bind RequestedShortcut, Mode=OneWay, Converter={StaticResource KeyChordToStringConverter}}" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ResourceDictionary>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid
|
||||
MinHeight="40"
|
||||
Padding="4"
|
||||
ColumnSpacing="8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<Grid
|
||||
x:Name="IconRoot"
|
||||
Margin="8,0,0,0"
|
||||
Tapped="PageIcon_Tapped"
|
||||
Visibility="{x:Bind CurrentPageViewModel.IsNested, Mode=OneWay}">
|
||||
|
||||
<cpcontrols:IconBox
|
||||
x:Name="IconBorder"
|
||||
Width="16"
|
||||
Height="16"
|
||||
x:Load="{x:Bind IsLoaded, Mode=OneWay}"
|
||||
CornerRadius="{StaticResource ControlCornerRadius}"
|
||||
SourceKey="{x:Bind CurrentPageViewModel.Icon, Mode=OneWay}"
|
||||
SourceRequested="{x:Bind help:IconCacheProvider.SourceRequested}" />
|
||||
<InfoBadge Visibility="{x:Bind CurrentPageViewModel.HasStatusMessage, Mode=OneWay}" Value="{x:Bind CurrentPageViewModel.StatusMessages.Count, Mode=OneWay}" />
|
||||
<Grid.ContextFlyout>
|
||||
<Flyout x:Name="StatusMessagesFlyout" Placement="TopEdgeAlignedLeft">
|
||||
<ItemsRepeater
|
||||
x:Name="MessagesDropdown"
|
||||
Margin="-8"
|
||||
ItemsSource="{x:Bind CurrentPageViewModel.StatusMessages, Mode=OneWay}"
|
||||
Layout="{StaticResource VerticalStackLayout}">
|
||||
<ItemsRepeater.ItemTemplate>
|
||||
<DataTemplate x:DataType="viewmodels:StatusMessageViewModel">
|
||||
<StackPanel
|
||||
Grid.Row="0"
|
||||
Margin="0"
|
||||
HorizontalAlignment="Stretch"
|
||||
VerticalAlignment="Bottom"
|
||||
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
|
||||
CornerRadius="0">
|
||||
<InfoBar
|
||||
CornerRadius="{ThemeResource ControlCornerRadius}"
|
||||
IsClosable="False"
|
||||
IsOpen="True"
|
||||
Message="{x:Bind Message, Mode=OneWay}"
|
||||
Severity="{x:Bind State, Mode=OneWay, Converter={StaticResource MessageStateToSeverityConverter}}" />
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ItemsRepeater.ItemTemplate>
|
||||
</ItemsRepeater>
|
||||
</Flyout>
|
||||
</Grid.ContextFlyout>
|
||||
</Grid>
|
||||
<Button
|
||||
x:Name="SettingsIconButton"
|
||||
Margin="0,0,0,0"
|
||||
Style="{StaticResource SubtleButtonStyle}"
|
||||
Tapped="SettingsIcon_Tapped"
|
||||
Visibility="{x:Bind CurrentPageViewModel.IsNested, Mode=OneWay, Converter={StaticResource BoolToInvertedVisibilityConverter}}">
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<FontIcon
|
||||
HorizontalAlignment="Left"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="16"
|
||||
Glyph="" />
|
||||
<TextBlock
|
||||
VerticalAlignment="Center"
|
||||
Style="{StaticResource CaptionTextBlockStyle}"
|
||||
Text="Settings" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
|
||||
<TextBlock
|
||||
Grid.Column="1"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="12"
|
||||
Text="{x:Bind CurrentPageViewModel.Title, Mode=OneWay}"
|
||||
Visibility="{x:Bind CurrentPageViewModel.IsNested, Mode=OneWay}" />
|
||||
|
||||
<StackPanel
|
||||
Grid.Column="2"
|
||||
HorizontalAlignment="Right"
|
||||
Orientation="Horizontal"
|
||||
Spacing="4">
|
||||
<Button
|
||||
x:Name="PrimaryButton"
|
||||
Padding="6,4,4,4"
|
||||
x:Load="{x:Bind IsLoaded, Mode=OneWay}"
|
||||
Background="Transparent"
|
||||
Style="{StaticResource SubtleButtonStyle}"
|
||||
Tapped="PrimaryButton_Tapped"
|
||||
Visibility="{x:Bind ViewModel.HasPrimaryCommand, Mode=OneWay}">
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<TextBlock
|
||||
VerticalAlignment="Center"
|
||||
Style="{StaticResource CaptionTextBlockStyle}"
|
||||
Text="{x:Bind ViewModel.PrimaryCommand.Name, Mode=OneWay}" />
|
||||
<Border
|
||||
Padding="4"
|
||||
Background="{ThemeResource SubtleFillColorSecondaryBrush}"
|
||||
BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="4">
|
||||
<FontIcon
|
||||
HorizontalAlignment="Left"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="10"
|
||||
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
|
||||
Glyph="" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button
|
||||
x:Name="SecondaryButton"
|
||||
Padding="6,4,4,4"
|
||||
x:Load="{x:Bind IsLoaded, Mode=OneWay}"
|
||||
Style="{StaticResource SubtleButtonStyle}"
|
||||
Tapped="SecondaryButton_Tapped"
|
||||
Visibility="{x:Bind ViewModel.HasSecondaryCommand, Mode=OneWay}">
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<TextBlock
|
||||
VerticalAlignment="Center"
|
||||
Style="{StaticResource CaptionTextBlockStyle}"
|
||||
Text="{x:Bind ViewModel.SecondaryCommand.Name, Mode=OneWay}" />
|
||||
<StackPanel Orientation="Horizontal" Spacing="2">
|
||||
<Border
|
||||
Padding="4,2,4,2"
|
||||
VerticalAlignment="Center"
|
||||
Background="{ThemeResource SubtleFillColorSecondaryBrush}"
|
||||
BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="4">
|
||||
<TextBlock
|
||||
CharacterSpacing="4"
|
||||
FontSize="10"
|
||||
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
|
||||
Text="Ctrl" />
|
||||
</Border>
|
||||
<Border
|
||||
Padding="4"
|
||||
VerticalAlignment="Center"
|
||||
Background="{ThemeResource SubtleFillColorSecondaryBrush}"
|
||||
BorderBrush="{ThemeResource DividerStrokeColorDefaultBrush}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="4">
|
||||
<FontIcon
|
||||
HorizontalAlignment="Left"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="10"
|
||||
Foreground="{ThemeResource TextFillColorSecondaryBrush}"
|
||||
Glyph="" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button
|
||||
x:Name="MoreCommandsButton"
|
||||
Padding="4"
|
||||
Content="{ui:FontIcon Glyph=,
|
||||
FontSize=16}"
|
||||
Style="{StaticResource SubtleButtonStyle}"
|
||||
ToolTipService.ToolTip="Ctrl+k"
|
||||
Visibility="{x:Bind ViewModel.ShouldShowContextMenu, Mode=OneWay}">
|
||||
<Button.Flyout>
|
||||
<Flyout Placement="TopEdgeAlignedRight">
|
||||
<ListView
|
||||
x:Name="CommandsDropdown"
|
||||
MinWidth="248"
|
||||
Margin="-16,-12,-16,-12"
|
||||
IsItemClickEnabled="True"
|
||||
ItemClick="CommandsDropdown_ItemClick"
|
||||
ItemTemplate="{StaticResource ContextMenuViewModelTemplate}"
|
||||
ItemsSource="{x:Bind ViewModel.ContextCommands, Mode=OneWay}"
|
||||
SelectionMode="None">
|
||||
<ListView.ItemContainerStyle>
|
||||
<Style BasedOn="{StaticResource DefaultListViewItemStyle}" TargetType="ListViewItem">
|
||||
<Setter Property="MinHeight" Value="0" />
|
||||
<Setter Property="Padding" Value="12,7,12,7" />
|
||||
</Style>
|
||||
</ListView.ItemContainerStyle>
|
||||
<ListView.ItemContainerTransitions>
|
||||
<TransitionCollection />
|
||||
</ListView.ItemContainerTransitions>
|
||||
</ListView>
|
||||
</Flyout>
|
||||
</Button.Flyout>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,92 @@
|
||||
// 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 CommunityToolkit.Mvvm.Messaging;
|
||||
using Microsoft.CmdPal.UI.ViewModels;
|
||||
using Microsoft.CmdPal.UI.ViewModels.Messages;
|
||||
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;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
public sealed partial class CommandBar : UserControl,
|
||||
IRecipient<OpenContextMenuMessage>,
|
||||
ICurrentPageAware
|
||||
{
|
||||
public CommandBarViewModel ViewModel { get; set; } = new();
|
||||
|
||||
public PageViewModel? CurrentPageViewModel
|
||||
{
|
||||
get => (PageViewModel?)GetValue(CurrentPageViewModelProperty);
|
||||
set => SetValue(CurrentPageViewModelProperty, value);
|
||||
}
|
||||
|
||||
// Using a DependencyProperty as the backing store for CurrentPage. This enables animation, styling, binding, etc...
|
||||
public static readonly DependencyProperty CurrentPageViewModelProperty =
|
||||
DependencyProperty.Register(nameof(CurrentPageViewModel), typeof(PageViewModel), typeof(CommandBar), new PropertyMetadata(null));
|
||||
|
||||
public CommandBar()
|
||||
{
|
||||
this.InitializeComponent();
|
||||
|
||||
// RegisterAll isn't AOT compatible
|
||||
WeakReferenceMessenger.Default.Register<OpenContextMenuMessage>(this);
|
||||
}
|
||||
|
||||
public void Receive(OpenContextMenuMessage message)
|
||||
{
|
||||
if (!ViewModel.ShouldShowContextMenu)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var options = new FlyoutShowOptions
|
||||
{
|
||||
ShowMode = FlyoutShowMode.Standard,
|
||||
};
|
||||
MoreCommandsButton.Flyout.ShowAt(MoreCommandsButton, options);
|
||||
CommandsDropdown.SelectedIndex = 0;
|
||||
CommandsDropdown.Focus(FocusState.Programmatic);
|
||||
}
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "VS has a tendency to delete XAML bound methods over-aggressively")]
|
||||
private void PrimaryButton_Tapped(object sender, TappedRoutedEventArgs e)
|
||||
{
|
||||
ViewModel.InvokePrimaryCommand();
|
||||
}
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "VS has a tendency to delete XAML bound methods over-aggressively")]
|
||||
private void SecondaryButton_Tapped(object sender, TappedRoutedEventArgs e)
|
||||
{
|
||||
ViewModel.InvokeSecondaryCommand();
|
||||
}
|
||||
|
||||
private void PageIcon_Tapped(object sender, TappedRoutedEventArgs e)
|
||||
{
|
||||
if (CurrentPageViewModel?.StatusMessages.Count > 0)
|
||||
{
|
||||
StatusMessagesFlyout.ShowAt(
|
||||
placementTarget: IconRoot,
|
||||
showOptions: new FlyoutShowOptions() { ShowMode = FlyoutShowMode.Standard });
|
||||
}
|
||||
}
|
||||
|
||||
private void SettingsIcon_Tapped(object sender, TappedRoutedEventArgs e)
|
||||
{
|
||||
WeakReferenceMessenger.Default.Send<OpenSettingsMessage>();
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
private void CommandsDropdown_ItemClick(object sender, ItemClickEventArgs e)
|
||||
{
|
||||
if (e.ClickedItem is CommandContextItemViewModel item)
|
||||
{
|
||||
ViewModel?.InvokeItemCommand.Execute(item);
|
||||
MoreCommandsButton.Flyout.Hide();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<UserControl
|
||||
x:Class="Microsoft.CmdPal.UI.Controls.ContentFormControl"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:converters="using:CommunityToolkit.WinUI.Converters"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:local="using:Microsoft.CmdPal.UI.Controls"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:ui="using:CommunityToolkit.WinUI"
|
||||
xmlns:viewmodels="using:Microsoft.CmdPal.UI.ViewModels"
|
||||
Background="Transparent"
|
||||
mc:Ignorable="d">
|
||||
|
||||
<UserControl.Resources>
|
||||
<ResourceDictionary x:Name="CardOverrideStyles">
|
||||
<Style x:Key="Adaptive.TextBlock" TargetType="TextBlock">
|
||||
<Setter Property="IsTextSelectionEnabled" Value="True" />
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid x:Name="ContentGrid" />
|
||||
</UserControl>
|
||||
@@ -0,0 +1,106 @@
|
||||
// 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 AdaptiveCards.ObjectModel.WinUI3;
|
||||
using AdaptiveCards.Rendering.WinUI3;
|
||||
using Microsoft.CmdPal.UI.ViewModels;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
public sealed partial class ContentFormControl : UserControl
|
||||
{
|
||||
private static readonly AdaptiveCardRenderer _renderer;
|
||||
private ContentFormViewModel? _viewModel;
|
||||
|
||||
// LOAD-BEARING: if you don't hang onto a reference to the RenderedAdaptiveCard
|
||||
// then the GC might clean it up sometime, even while the card is in the UI
|
||||
// tree. If this gets GC'd, then it'll revoke our Action handler, and the
|
||||
// form will do seemingly nothing.
|
||||
private RenderedAdaptiveCard? _renderedCard;
|
||||
|
||||
public ContentFormViewModel? ViewModel { get => _viewModel; set => AttachViewModel(value); }
|
||||
|
||||
static ContentFormControl()
|
||||
{
|
||||
// We can't use `CardOverrideStyles` here yet, because we haven't called InitializeComponent once.
|
||||
// But also, the default value isn't `null` here. It's... some other default empty value.
|
||||
// So clear it out so that we know when the first time we get created is
|
||||
_renderer = new AdaptiveCardRenderer()
|
||||
{
|
||||
OverrideStyles = null,
|
||||
};
|
||||
}
|
||||
|
||||
public ContentFormControl()
|
||||
{
|
||||
this.InitializeComponent();
|
||||
var lightTheme = ActualTheme == Microsoft.UI.Xaml.ElementTheme.Light;
|
||||
_renderer.HostConfig = lightTheme ? AdaptiveCardsConfig.Light : AdaptiveCardsConfig.Dark;
|
||||
|
||||
// 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)
|
||||
{
|
||||
_renderer.OverrideStyles = CardOverrideStyles;
|
||||
}
|
||||
|
||||
// TODO in the future, we should handle ActualThemeChanged and replace
|
||||
// our rendered card with one for that theme. But today is not that day
|
||||
}
|
||||
|
||||
private void AttachViewModel(ContentFormViewModel? vm)
|
||||
{
|
||||
if (_viewModel != null)
|
||||
{
|
||||
_viewModel.PropertyChanged -= ViewModel_PropertyChanged;
|
||||
}
|
||||
|
||||
_viewModel = vm;
|
||||
|
||||
if (_viewModel != null)
|
||||
{
|
||||
_viewModel.PropertyChanged += ViewModel_PropertyChanged;
|
||||
|
||||
var c = _viewModel.Card;
|
||||
if (c != null)
|
||||
{
|
||||
DisplayCard(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ViewModel_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
|
||||
{
|
||||
if (ViewModel == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.PropertyName == nameof(ViewModel.Card))
|
||||
{
|
||||
var c = ViewModel.Card;
|
||||
if (c != null)
|
||||
{
|
||||
DisplayCard(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void DisplayCard(AdaptiveCardParseResult result)
|
||||
{
|
||||
_renderedCard = _renderer.RenderAdaptiveCard(result.AdaptiveCard);
|
||||
ContentGrid.Children.Clear();
|
||||
if (_renderedCard.FrameworkElement != null)
|
||||
{
|
||||
ContentGrid.Children.Add(_renderedCard.FrameworkElement);
|
||||
}
|
||||
|
||||
_renderedCard.Action += Rendered_Action;
|
||||
}
|
||||
|
||||
private void Rendered_Action(RenderedAdaptiveCard sender, AdaptiveActionEventArgs args) =>
|
||||
ViewModel?.HandleSubmit(args.Action, args.Inputs.AsJson());
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// 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 CommunityToolkit.WinUI;
|
||||
using Microsoft.CmdPal.UI.Deferred;
|
||||
using Microsoft.CmdPal.UI.ViewModels;
|
||||
using Microsoft.UI.Dispatching;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Windows.Foundation;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
/// <summary>
|
||||
/// A helper control which takes an <see cref="IconSource"/> and creates the corresponding <see cref="IconElement"/>.
|
||||
/// </summary>
|
||||
public partial class ContentIcon : FontIcon
|
||||
{
|
||||
public UIElement Content
|
||||
{
|
||||
get => (UIElement)GetValue(ContentProperty);
|
||||
set => SetValue(ContentProperty, value);
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty ContentProperty =
|
||||
DependencyProperty.Register(
|
||||
nameof(Content),
|
||||
typeof(UIElement),
|
||||
typeof(ContentIcon),
|
||||
new PropertyMetadata(null));
|
||||
|
||||
public ContentIcon()
|
||||
{
|
||||
Loaded += IconBoxElement_Loaded;
|
||||
}
|
||||
|
||||
private void IconBoxElement_Loaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this.FindDescendants().OfType<Grid>().FirstOrDefault() is Grid grid && Content is not null)
|
||||
{
|
||||
grid.Children.Add(Content);
|
||||
}
|
||||
}
|
||||
}
|
||||
159
src/modules/cmdpal/Microsoft.CmdPal.UI/Controls/IconBox.cs
Normal file
159
src/modules/cmdpal/Microsoft.CmdPal.UI/Controls/IconBox.cs
Normal file
@@ -0,0 +1,159 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.CmdPal.UI.Deferred;
|
||||
using Microsoft.CmdPal.UI.ViewModels;
|
||||
using Microsoft.UI.Dispatching;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Windows.Foundation;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
/// <summary>
|
||||
/// A helper control which takes an <see cref="IconSource"/> and creates the corresponding <see cref="IconElement"/>.
|
||||
/// </summary>
|
||||
public partial class IconBox : ContentControl
|
||||
{
|
||||
private readonly DispatcherQueue _queue = DispatcherQueue.GetForCurrentThread();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="IconSource"/> to display within the <see cref="IconBox"/>. Overwritten, if <see cref="SourceKey"/> is used instead.
|
||||
/// </summary>
|
||||
public IconSource? Source
|
||||
{
|
||||
get => (IconSource?)GetValue(SourceProperty);
|
||||
set => SetValue(SourceProperty, value);
|
||||
}
|
||||
|
||||
// Using a DependencyProperty as the backing store for Source. This enables animation, styling, binding, etc...
|
||||
public static readonly DependencyProperty SourceProperty =
|
||||
DependencyProperty.Register(nameof(Source), typeof(IconSource), typeof(IconBox), new PropertyMetadata(null, OnSourcePropertyChanged));
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value to use as the <see cref="SourceKey"/> to retrieve an <see cref="IconSource"/> to set as the <see cref="Source"/>.
|
||||
/// </summary>
|
||||
public object? SourceKey
|
||||
{
|
||||
get => (object?)GetValue(SourceKeyProperty);
|
||||
set => SetValue(SourceKeyProperty, value);
|
||||
}
|
||||
|
||||
// Using a DependencyProperty as the backing store for SourceKey. This enables animation, styling, binding, etc...
|
||||
public static readonly DependencyProperty SourceKeyProperty =
|
||||
DependencyProperty.Register(nameof(SourceKey), typeof(object), typeof(IconBox), new PropertyMetadata(null, OnSourceKeyPropertyChanged));
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="SourceRequested"/> event handler to provide the value of the <see cref="IconSource"/> for the <see cref="Source"/> property from the provided <see cref="SourceKey"/>.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<IconBox, SourceRequestedEventArgs>? SourceRequested;
|
||||
|
||||
private static void OnSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is IconBox @this)
|
||||
{
|
||||
switch (e.NewValue)
|
||||
{
|
||||
case null:
|
||||
@this.Content = null;
|
||||
break;
|
||||
case FontIconSource fontIco:
|
||||
fontIco.FontSize = double.IsNaN(@this.Width) ? @this.Height : @this.Width;
|
||||
|
||||
// For inexplicable reasons, FontIconSource.CreateIconElement
|
||||
// doesn't work, so do it ourselves
|
||||
// TODO: File platform bug?
|
||||
IconSourceElement elem = new()
|
||||
{
|
||||
IconSource = fontIco,
|
||||
};
|
||||
@this.Content = elem;
|
||||
break;
|
||||
case IconSource source:
|
||||
@this.Content = source.CreateIconElement();
|
||||
break;
|
||||
default:
|
||||
throw new InvalidOperationException($"New value of {e.NewValue} is not of type IconSource.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnSourceKeyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is IconBox @this)
|
||||
{
|
||||
if (e.NewValue == null)
|
||||
{
|
||||
@this.Source = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO GH #239 switch back when using the new MD text block
|
||||
// _ = @this._queue.EnqueueAsync(() =>
|
||||
@this._queue.TryEnqueue(new(async () =>
|
||||
{
|
||||
var requestedTheme = @this.ActualTheme;
|
||||
var eventArgs = new SourceRequestedEventArgs(e.NewValue, requestedTheme);
|
||||
|
||||
if (@this.SourceRequested != null)
|
||||
{
|
||||
await @this.SourceRequested.InvokeAsync(@this, eventArgs);
|
||||
|
||||
// After the await:
|
||||
// Is the icon we're looking up now, the one we still
|
||||
// want to find? Since this IconBox might be used in a
|
||||
// list virtualization situation, it's very possible we
|
||||
// may have already been set to a new icon before we
|
||||
// even got back from the await.
|
||||
if (eventArgs.Key != @this.SourceKey)
|
||||
{
|
||||
// If the requested icon has changed, then just bail
|
||||
return;
|
||||
}
|
||||
|
||||
@this.Source = eventArgs.Value;
|
||||
|
||||
// Here's a little lesson in trickery:
|
||||
// Emoji are rendered just a bit bigger than Segoe Icons.
|
||||
// Just enough bigger that they get clipped if you put
|
||||
// them in a box at the same size.
|
||||
//
|
||||
// So, if the icon we get back was a font icon,
|
||||
// and the glyph for that icon is NOT in the range of
|
||||
// Segoe icons, then let's give the icon some extra space
|
||||
@this.Padding = new Thickness(0);
|
||||
|
||||
IconDataViewModel? iconData = null;
|
||||
if (eventArgs.Key is IconDataViewModel)
|
||||
{
|
||||
iconData = eventArgs.Key as IconDataViewModel;
|
||||
}
|
||||
else if (eventArgs.Key is IconInfoViewModel info)
|
||||
{
|
||||
iconData = requestedTheme == ElementTheme.Light ? info.Light : info.Dark;
|
||||
}
|
||||
|
||||
if (iconData != null &&
|
||||
@this.Source is FontIconSource)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(iconData.Icon) && iconData.Icon.Length <= 2)
|
||||
{
|
||||
var ch = iconData.Icon[0];
|
||||
|
||||
// The range of MDL2 Icons isn't explicitly defined, but
|
||||
// we're using this based off the table on:
|
||||
// https://docs.microsoft.com/en-us/windows/uwp/design/style/segoe-ui-symbol-font
|
||||
var isMDL2Icon = ch is >= '\uE700' and <= '\uF8FF';
|
||||
if (!isMDL2Icon)
|
||||
{
|
||||
@this.Padding = new Thickness(-4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.CmdPal.UI;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Microsoft.UI.Xaml.Markup;
|
||||
using Windows.System;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
[TemplatePart(Name = KeyPresenter, Type = typeof(ContentPresenter))]
|
||||
[TemplateVisualState(Name = "Normal", GroupName = "CommonStates")]
|
||||
[TemplateVisualState(Name = "Disabled", GroupName = "CommonStates")]
|
||||
[TemplateVisualState(Name = "Default", GroupName = "StateStates")]
|
||||
[TemplateVisualState(Name = "Error", GroupName = "StateStates")]
|
||||
public sealed partial class KeyVisual : Control
|
||||
{
|
||||
private const string KeyPresenter = "KeyPresenter";
|
||||
private KeyVisual? _keyVisual;
|
||||
private ContentPresenter _keyPresenter = new();
|
||||
|
||||
public object Content
|
||||
{
|
||||
get => GetValue(ContentProperty);
|
||||
set => SetValue(ContentProperty, value);
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(object), typeof(KeyVisual), new PropertyMetadata(default(string), OnContentChanged));
|
||||
|
||||
public VisualType VisualType
|
||||
{
|
||||
get => (VisualType)GetValue(VisualTypeProperty);
|
||||
set => SetValue(VisualTypeProperty, value);
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty VisualTypeProperty = DependencyProperty.Register("VisualType", typeof(VisualType), typeof(KeyVisual), new PropertyMetadata(default(VisualType), OnSizeChanged));
|
||||
|
||||
public bool IsError
|
||||
{
|
||||
get => (bool)GetValue(IsErrorProperty);
|
||||
set => SetValue(IsErrorProperty, value);
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty IsErrorProperty = DependencyProperty.Register("IsError", typeof(bool), typeof(KeyVisual), new PropertyMetadata(false, OnIsErrorChanged));
|
||||
|
||||
public KeyVisual()
|
||||
{
|
||||
this.DefaultStyleKey = typeof(KeyVisual);
|
||||
this.Style = GetStyleSize("TextKeyVisualStyle");
|
||||
}
|
||||
|
||||
protected override void OnApplyTemplate()
|
||||
{
|
||||
IsEnabledChanged -= KeyVisual_IsEnabledChanged;
|
||||
_keyVisual = this;
|
||||
_keyPresenter = (ContentPresenter)_keyVisual.GetTemplateChild(KeyPresenter);
|
||||
Update();
|
||||
SetEnabledState();
|
||||
SetErrorState();
|
||||
IsEnabledChanged += KeyVisual_IsEnabledChanged;
|
||||
base.OnApplyTemplate();
|
||||
}
|
||||
|
||||
private static void OnContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
((KeyVisual)d).Update();
|
||||
}
|
||||
|
||||
private static void OnSizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
((KeyVisual)d).Update();
|
||||
}
|
||||
|
||||
private static void OnIsErrorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
((KeyVisual)d).SetErrorState();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (_keyVisual == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_keyVisual.Content != null)
|
||||
{
|
||||
if (_keyVisual.Content.GetType() == typeof(string))
|
||||
{
|
||||
_keyVisual.Style = GetStyleSize("TextKeyVisualStyle");
|
||||
_keyVisual._keyPresenter.Content = _keyVisual.Content;
|
||||
}
|
||||
else
|
||||
{
|
||||
_keyVisual.Style = GetStyleSize("IconKeyVisualStyle");
|
||||
|
||||
switch ((int)_keyVisual.Content)
|
||||
{
|
||||
/* We can enable other glyphs in the future
|
||||
case 13: // The Enter key or button.
|
||||
_keyVisual._keyPresenter.Content = "\uE751"; break;
|
||||
|
||||
case 8: // The Back key or button.
|
||||
_keyVisual._keyPresenter.Content = "\uE750"; break;
|
||||
|
||||
case 16: // The right Shift key or button.
|
||||
case 160: // The left Shift key or button.
|
||||
case 161: // The Shift key or button.
|
||||
_keyVisual._keyPresenter.Content = "\uE752"; break; */
|
||||
|
||||
case 38: _keyVisual._keyPresenter.Content = "\uE0E4"; break; // The Up Arrow key or button.
|
||||
case 40: _keyVisual._keyPresenter.Content = "\uE0E5"; break; // The Down Arrow key or button.
|
||||
case 37: _keyVisual._keyPresenter.Content = "\uE0E2"; break; // The Left Arrow key or button.
|
||||
case 39: _keyVisual._keyPresenter.Content = "\uE0E3"; break; // The Right Arrow key or button.
|
||||
|
||||
case 91: // The left Windows key
|
||||
case 92: // The right Windows key
|
||||
var winIcon = XamlReader.Load(@"<PathIcon xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" Data=""M683 1229H0V546h683v683zm819 0H819V546h683v683zm-819 819H0v-683h683v683zm819 0H819v-683h683v683z"" />") as PathIcon;
|
||||
var winIconContainer = new Viewbox
|
||||
{
|
||||
Child = winIcon,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
};
|
||||
|
||||
var iconDimensions = GetIconSize();
|
||||
winIconContainer.Height = iconDimensions;
|
||||
winIconContainer.Width = iconDimensions;
|
||||
_keyVisual._keyPresenter.Content = winIconContainer;
|
||||
break;
|
||||
default: _keyVisual._keyPresenter.Content = ((VirtualKey)_keyVisual.Content).ToString(); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Style GetStyleSize(string styleName)
|
||||
{
|
||||
return VisualType == VisualType.Small
|
||||
? (Style)App.Current.Resources["Small" + styleName]
|
||||
: VisualType == VisualType.SmallOutline
|
||||
? (Style)App.Current.Resources["SmallOutline" + styleName]
|
||||
: VisualType == VisualType.TextOnly
|
||||
? (Style)App.Current.Resources["Only" + styleName]
|
||||
: (Style)App.Current.Resources["Default" + styleName];
|
||||
}
|
||||
|
||||
public double GetIconSize()
|
||||
{
|
||||
return VisualType == VisualType.Small || VisualType == VisualType.SmallOutline
|
||||
? (double)App.Current.Resources["SmallIconSize"]
|
||||
: (double)App.Current.Resources["DefaultIconSize"];
|
||||
}
|
||||
|
||||
private void KeyVisual_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
SetEnabledState();
|
||||
}
|
||||
|
||||
private void SetErrorState()
|
||||
{
|
||||
VisualStateManager.GoToState(this, IsError ? "Error" : "Default", true);
|
||||
}
|
||||
|
||||
private void SetEnabledState()
|
||||
{
|
||||
VisualStateManager.GoToState(this, IsEnabled ? "Normal" : "Disabled", true);
|
||||
}
|
||||
}
|
||||
|
||||
public enum VisualType
|
||||
{
|
||||
Small,
|
||||
SmallOutline,
|
||||
TextOnly,
|
||||
Large,
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
<ResourceDictionary
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:controls="using:Microsoft.CmdPal.UI.Controls">
|
||||
|
||||
<x:Double x:Key="DefaultIconSize">16</x:Double>
|
||||
<x:Double x:Key="SmallIconSize">12</x:Double>
|
||||
<Style x:Key="DefaultTextKeyVisualStyle" TargetType="controls:KeyVisual">
|
||||
<Setter Property="MinWidth" Value="56" />
|
||||
<Setter Property="MinHeight" Value="48" />
|
||||
<Setter Property="Background" Value="{ThemeResource AccentButtonBackground}" />
|
||||
<Setter Property="Foreground" Value="{ThemeResource AccentButtonForeground}" />
|
||||
<Setter Property="BorderBrush" Value="{ThemeResource AccentButtonBorderBrush}" />
|
||||
<Setter Property="BorderThickness" Value="{ThemeResource ButtonBorderThemeThickness}" />
|
||||
<Setter Property="Padding" Value="16,8,16,8" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="HorizontalAlignment" Value="Center" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
<Setter Property="FontSize" Value="18" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="controls:KeyVisual">
|
||||
<Grid>
|
||||
<Grid>
|
||||
<Rectangle
|
||||
x:Name="ContentHolder"
|
||||
Height="{TemplateBinding Height}"
|
||||
MinWidth="{TemplateBinding MinWidth}"
|
||||
Fill="{TemplateBinding Background}"
|
||||
RadiusX="4"
|
||||
RadiusY="4"
|
||||
Stroke="{TemplateBinding BorderBrush}"
|
||||
StrokeThickness="{TemplateBinding BorderThickness}" />
|
||||
<ContentPresenter
|
||||
x:Name="KeyPresenter"
|
||||
Margin="{TemplateBinding Padding}"
|
||||
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
|
||||
VerticalAlignment="Center"
|
||||
Content="{TemplateBinding Content}"
|
||||
FontSize="{TemplateBinding FontSize}"
|
||||
FontWeight="{TemplateBinding FontWeight}"
|
||||
Foreground="{TemplateBinding Foreground}" />
|
||||
</Grid>
|
||||
<VisualStateManager.VisualStateGroups>
|
||||
<VisualStateGroup x:Name="CommonStates">
|
||||
<VisualState x:Name="Normal" />
|
||||
<VisualState x:Name="Disabled">
|
||||
<VisualState.Setters>
|
||||
<Setter Target="ContentHolder.Fill" Value="{ThemeResource AccentButtonBackgroundDisabled}" />
|
||||
<Setter Target="KeyPresenter.Foreground" Value="{ThemeResource AccentButtonForegroundDisabled}" />
|
||||
<Setter Target="ContentHolder.Stroke" Value="{ThemeResource AccentButtonBorderBrushDisabled}" />
|
||||
<!--<Setter Target="ContentHolder.StrokeThickness" Value="{TemplateBinding BorderThickness}" />-->
|
||||
</VisualState.Setters>
|
||||
</VisualState>
|
||||
</VisualStateGroup>
|
||||
<VisualStateGroup x:Name="StateStates">
|
||||
<VisualState x:Name="Default" />
|
||||
<VisualState x:Name="Error">
|
||||
<VisualState.Setters>
|
||||
<Setter Target="ContentHolder.Fill" Value="{ThemeResource InfoBarErrorSeverityBackgroundBrush}" />
|
||||
<Setter Target="KeyPresenter.Foreground" Value="{ThemeResource InfoBarErrorSeverityIconBackground}" />
|
||||
<Setter Target="ContentHolder.Stroke" Value="{ThemeResource InfoBarErrorSeverityIconBackground}" />
|
||||
<Setter Target="ContentHolder.StrokeThickness" Value="2" />
|
||||
</VisualState.Setters>
|
||||
</VisualState>
|
||||
</VisualStateGroup>
|
||||
</VisualStateManager.VisualStateGroups>
|
||||
</Grid>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style
|
||||
x:Key="SmallTextKeyVisualStyle"
|
||||
BasedOn="{StaticResource DefaultTextKeyVisualStyle}"
|
||||
TargetType="controls:KeyVisual">
|
||||
<Setter Property="MinWidth" Value="40" />
|
||||
<Setter Property="Height" Value="36" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Padding" Value="12,0,12,2" />
|
||||
<Setter Property="FontSize" Value="14" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
|
||||
<Style
|
||||
x:Key="SmallOutlineTextKeyVisualStyle"
|
||||
BasedOn="{StaticResource DefaultTextKeyVisualStyle}"
|
||||
TargetType="controls:KeyVisual">
|
||||
<Setter Property="MinWidth" Value="40" />
|
||||
<Setter Property="Background" Value="{ThemeResource ButtonBackground}" />
|
||||
<Setter Property="Foreground" Value="{ThemeResource ButtonForeground}" />
|
||||
<Setter Property="BorderBrush" Value="{ThemeResource ButtonBorderBrush}" />
|
||||
<Setter Property="Height" Value="36" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Padding" Value="8,0,8,2" />
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
|
||||
|
||||
|
||||
<Style
|
||||
x:Key="DefaultIconKeyVisualStyle"
|
||||
BasedOn="{StaticResource DefaultTextKeyVisualStyle}"
|
||||
TargetType="controls:KeyVisual">
|
||||
<Setter Property="MinWidth" Value="56" />
|
||||
<Setter Property="MinHeight" Value="48" />
|
||||
<Setter Property="FontFamily" Value="{ThemeResource SymbolThemeFontFamily}" />
|
||||
<Setter Property="Padding" Value="16,8,16,8" />
|
||||
<Setter Property="FontSize" Value="14" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
|
||||
<Style
|
||||
x:Key="SmallIconKeyVisualStyle"
|
||||
BasedOn="{StaticResource DefaultTextKeyVisualStyle}"
|
||||
TargetType="controls:KeyVisual">
|
||||
<Setter Property="MinWidth" Value="40" />
|
||||
<Setter Property="Height" Value="36" />
|
||||
<Setter Property="FontFamily" Value="{ThemeResource SymbolThemeFontFamily}" />
|
||||
<Setter Property="FontWeight" Value="Normal" />
|
||||
<Setter Property="Padding" Value="0" />
|
||||
<Setter Property="FontSize" Value="10" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
|
||||
<Style
|
||||
x:Key="SmallOutlineIconKeyVisualStyle"
|
||||
BasedOn="{StaticResource DefaultTextKeyVisualStyle}"
|
||||
TargetType="controls:KeyVisual">
|
||||
<Setter Property="MinWidth" Value="40" />
|
||||
<Setter Property="Background" Value="{ThemeResource ButtonBackground}" />
|
||||
<Setter Property="Foreground" Value="{ThemeResource ButtonForeground}" />
|
||||
<Setter Property="BorderBrush" Value="{ThemeResource ButtonBorderBrush}" />
|
||||
<Setter Property="FontFamily" Value="{ThemeResource SymbolThemeFontFamily}" />
|
||||
<Setter Property="Height" Value="36" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Padding" Value="0" />
|
||||
<Setter Property="FontSize" Value="9" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
|
||||
<Style
|
||||
x:Key="OnlyTextKeyVisualStyle"
|
||||
BasedOn="{StaticResource DefaultTextKeyVisualStyle}"
|
||||
TargetType="controls:KeyVisual">
|
||||
<Setter Property="MinHeight" Value="12" />
|
||||
<Setter Property="MinWidth" Value="12" />
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="Foreground" Value="{ThemeResource ButtonForeground}" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
<Setter Property="FontWeight" Value="Normal" />
|
||||
<Setter Property="Padding" Value="0" />
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
|
||||
<Style
|
||||
x:Key="OnlyIconKeyVisualStyle"
|
||||
BasedOn="{StaticResource DefaultTextKeyVisualStyle}"
|
||||
TargetType="controls:KeyVisual">
|
||||
<Setter Property="MinHeight" Value="10" />
|
||||
<Setter Property="MinWidth" Value="10" />
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="Foreground" Value="{ThemeResource ButtonForeground}" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
<Setter Property="FontFamily" Value="{ThemeResource SymbolThemeFontFamily}" />
|
||||
<Setter Property="FontWeight" Value="Normal" />
|
||||
<Setter Property="Padding" Value="0,0,0,3" />
|
||||
<!--<Setter Property="FontSize" Value="9" />-->
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<UserControl
|
||||
x:Class="Microsoft.CmdPal.UI.Controls.SearchBar"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:cmdpalUi="using:Microsoft.CmdPal.UI"
|
||||
xmlns:converters="using:CommunityToolkit.WinUI.Converters"
|
||||
xmlns:cpcontrols="using:Microsoft.CmdPal.UI.Controls"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d">
|
||||
|
||||
<UserControl.Resources>
|
||||
<ResourceDictionary>
|
||||
<cmdpalUi:PlaceholderTextConverter x:Key="PlaceholderTextConverter" />
|
||||
</ResourceDictionary>
|
||||
</UserControl.Resources>
|
||||
|
||||
<!-- Search box -->
|
||||
<TextBox
|
||||
x:Name="FilterBox"
|
||||
MinHeight="32"
|
||||
VerticalAlignment="Stretch"
|
||||
VerticalContentAlignment="Stretch"
|
||||
KeyDown="FilterBox_KeyDown"
|
||||
PlaceholderText="{x:Bind CurrentPageViewModel.PlaceholderText, Converter={StaticResource PlaceholderTextConverter}, Mode=OneWay}"
|
||||
PreviewKeyDown="FilterBox_PreviewKeyDown"
|
||||
PreviewKeyUp="FilterBox_PreviewKeyUp"
|
||||
Style="{StaticResource SearchTextBoxStyle}"
|
||||
TextChanged="FilterBox_TextChanged" />
|
||||
<!-- Disabled Description="{x:Bind CurrentPageViewModel.TextToSuggest, Mode=OneWay}" for now, needs more work -->
|
||||
</UserControl>
|
||||
@@ -0,0 +1,271 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Diagnostics;
|
||||
using CommunityToolkit.Mvvm.Messaging;
|
||||
using CommunityToolkit.WinUI;
|
||||
using Microsoft.CmdPal.UI.ViewModels;
|
||||
using Microsoft.CmdPal.UI.ViewModels.Messages;
|
||||
using Microsoft.CmdPal.UI.Views;
|
||||
using Microsoft.UI.Dispatching;
|
||||
using Microsoft.UI.Input;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Microsoft.UI.Xaml.Input;
|
||||
using CoreVirtualKeyStates = Windows.UI.Core.CoreVirtualKeyStates;
|
||||
using VirtualKey = Windows.System.VirtualKey;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
public sealed partial class SearchBar : UserControl,
|
||||
IRecipient<GoHomeMessage>,
|
||||
IRecipient<FocusSearchBoxMessage>,
|
||||
ICurrentPageAware
|
||||
{
|
||||
private readonly DispatcherQueue _queue = DispatcherQueue.GetForCurrentThread();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="DispatcherQueueTimer"/> that we create to track keyboard input and throttle/debounce before we make queries.
|
||||
/// </summary>
|
||||
private readonly DispatcherQueueTimer _debounceTimer = DispatcherQueue.GetForCurrentThread().CreateTimer();
|
||||
private bool _isBackspaceHeld;
|
||||
|
||||
public PageViewModel? CurrentPageViewModel
|
||||
{
|
||||
get => (PageViewModel?)GetValue(CurrentPageViewModelProperty);
|
||||
set => SetValue(CurrentPageViewModelProperty, value);
|
||||
}
|
||||
|
||||
// Using a DependencyProperty as the backing store for CurrentPageViewModel. This enables animation, styling, binding, etc...
|
||||
public static readonly DependencyProperty CurrentPageViewModelProperty =
|
||||
DependencyProperty.Register(nameof(CurrentPageViewModel), typeof(PageViewModel), typeof(SearchBar), new PropertyMetadata(null, OnCurrentPageViewModelChanged));
|
||||
|
||||
private static void OnCurrentPageViewModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
//// 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
|
||||
&& e.OldValue is PageViewModel old)
|
||||
{
|
||||
old.PropertyChanged -= @this.Page_PropertyChanged;
|
||||
}
|
||||
|
||||
if (@this != null
|
||||
&& e.NewValue is PageViewModel page)
|
||||
{
|
||||
// TODO: In some cases we probably want commands to clear a filter
|
||||
// somewhere in the process, so we need to figure out when that is.
|
||||
@this.FilterBox.Text = page.Filter;
|
||||
@this.FilterBox.Select(@this.FilterBox.Text.Length, 0);
|
||||
|
||||
page.PropertyChanged += @this.Page_PropertyChanged;
|
||||
}
|
||||
}
|
||||
|
||||
public SearchBar()
|
||||
{
|
||||
this.InitializeComponent();
|
||||
WeakReferenceMessenger.Default.Register<GoHomeMessage>(this);
|
||||
WeakReferenceMessenger.Default.Register<FocusSearchBoxMessage>(this);
|
||||
}
|
||||
|
||||
public void ClearSearch()
|
||||
{
|
||||
// TODO GH #239 switch back when using the new MD text block
|
||||
// _ = _queue.EnqueueAsync(() =>
|
||||
_queue.TryEnqueue(new(() =>
|
||||
{
|
||||
this.FilterBox.Text = string.Empty;
|
||||
|
||||
if (CurrentPageViewModel != null)
|
||||
{
|
||||
CurrentPageViewModel.Filter = string.Empty;
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
public void SelectSearch()
|
||||
{
|
||||
// TODO GH #239 switch back when using the new MD text block
|
||||
// _ = _queue.EnqueueAsync(() =>
|
||||
_queue.TryEnqueue(new(() =>
|
||||
{
|
||||
this.FilterBox.SelectAll();
|
||||
}));
|
||||
}
|
||||
|
||||
private void FilterBox_KeyDown(object sender, KeyRoutedEventArgs e)
|
||||
{
|
||||
if (e.Handled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var ctrlPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
|
||||
var altPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Menu).HasFlag(CoreVirtualKeyStates.Down);
|
||||
if (e.Key == VirtualKey.Down)
|
||||
{
|
||||
WeakReferenceMessenger.Default.Send<NavigateNextCommand>();
|
||||
|
||||
e.Handled = true;
|
||||
}
|
||||
else if (e.Key == VirtualKey.Up)
|
||||
{
|
||||
WeakReferenceMessenger.Default.Send<NavigatePreviousCommand>();
|
||||
|
||||
e.Handled = true;
|
||||
}
|
||||
else if (ctrlPressed && e.Key == VirtualKey.Enter)
|
||||
{
|
||||
// ctrl+enter
|
||||
WeakReferenceMessenger.Default.Send<ActivateSecondaryCommandMessage>();
|
||||
e.Handled = true;
|
||||
}
|
||||
else if (e.Key == VirtualKey.Enter)
|
||||
{
|
||||
WeakReferenceMessenger.Default.Send<ActivateSelectedListItemMessage>();
|
||||
e.Handled = true;
|
||||
}
|
||||
else if (ctrlPressed && e.Key == VirtualKey.K)
|
||||
{
|
||||
// ctrl+k
|
||||
WeakReferenceMessenger.Default.Send<OpenContextMenuMessage>();
|
||||
e.Handled = true;
|
||||
}
|
||||
else if (e.Key == VirtualKey.Right)
|
||||
{
|
||||
if (CurrentPageViewModel != null && !string.IsNullOrEmpty(CurrentPageViewModel.TextToSuggest))
|
||||
{
|
||||
FilterBox.Text = CurrentPageViewModel.TextToSuggest;
|
||||
FilterBox.Select(FilterBox.Text.Length, 0);
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
else if (e.Key == VirtualKey.Escape)
|
||||
{
|
||||
if (string.IsNullOrEmpty(FilterBox.Text))
|
||||
{
|
||||
WeakReferenceMessenger.Default.Send<NavigateBackMessage>(new());
|
||||
}
|
||||
else
|
||||
{
|
||||
// Clear the search box
|
||||
FilterBox.Text = string.Empty;
|
||||
|
||||
// hack TODO GH #245
|
||||
if (CurrentPageViewModel != null)
|
||||
{
|
||||
CurrentPageViewModel.Filter = FilterBox.Text;
|
||||
}
|
||||
}
|
||||
|
||||
e.Handled = true;
|
||||
}
|
||||
else if (e.Key == VirtualKey.Back)
|
||||
{
|
||||
// hack TODO GH #245
|
||||
if (CurrentPageViewModel != null)
|
||||
{
|
||||
CurrentPageViewModel.Filter = FilterBox.Text;
|
||||
}
|
||||
}
|
||||
else if (e.Key == VirtualKey.Left && altPressed)
|
||||
{
|
||||
WeakReferenceMessenger.Default.Send<NavigateBackMessage>(new());
|
||||
}
|
||||
}
|
||||
|
||||
private void FilterBox_PreviewKeyDown(object sender, KeyRoutedEventArgs e)
|
||||
{
|
||||
if (e.Key == VirtualKey.Back)
|
||||
{
|
||||
if (string.IsNullOrEmpty(FilterBox.Text))
|
||||
{
|
||||
if (!_isBackspaceHeld)
|
||||
{
|
||||
// Navigate back on single backspace when empty
|
||||
WeakReferenceMessenger.Default.Send<NavigateBackMessage>(new(true));
|
||||
}
|
||||
|
||||
e.Handled = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Mark backspace as held to handle continuous deletion
|
||||
_isBackspaceHeld = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void FilterBox_PreviewKeyUp(object sender, KeyRoutedEventArgs e)
|
||||
{
|
||||
if (e.Key == VirtualKey.Back)
|
||||
{
|
||||
// Reset the backspace state on key release
|
||||
_isBackspaceHeld = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void FilterBox_TextChanged(object sender, TextChangedEventArgs e)
|
||||
{
|
||||
Debug.WriteLine($"FilterBox_TextChanged: {FilterBox.Text}");
|
||||
|
||||
// TERRIBLE HACK TODO GH #245
|
||||
// There's weird wacky bugs with debounce currently. We're trying
|
||||
// to get them ingested, but while we wait for the toolkit feeds to
|
||||
// bubble, just manually send the first character, always
|
||||
// (otherwise aliases just stop working)
|
||||
if (FilterBox.Text.Length == 1)
|
||||
{
|
||||
if (CurrentPageViewModel != null)
|
||||
{
|
||||
CurrentPageViewModel.Filter = FilterBox.Text;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: We could encapsulate this in a Behavior if we wanted to bind to the Filter property.
|
||||
_debounceTimer.Debounce(
|
||||
() =>
|
||||
{
|
||||
// Actually plumb Filtering to the viewmodel
|
||||
if (CurrentPageViewModel != null)
|
||||
{
|
||||
CurrentPageViewModel.Filter = FilterBox.Text;
|
||||
}
|
||||
},
|
||||
//// Couldn't find a good recommendation/resource for value here. PT uses 50ms as default, so that is a reasonable default
|
||||
//// This seems like a useful testing site for typing times: https://keyboardtester.info/keyboard-latency-test/
|
||||
//// i.e. if another keyboard press comes in within 50ms of the last, we'll wait before we fire off the request
|
||||
interval: TimeSpan.FromMilliseconds(50),
|
||||
//// If we're not already waiting, and this is blanking out or the first character type, we'll start filtering immediately instead to appear more responsive and either clear the filter to get back home faster or at least chop to the first starting letter.
|
||||
immediate: FilterBox.Text.Length <= 1);
|
||||
}
|
||||
|
||||
// Used to handle the case when a ListPage's `SearchText` may have changed
|
||||
private void Page_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
|
||||
{
|
||||
var property = e.PropertyName;
|
||||
if (CurrentPageViewModel is ListViewModel list &&
|
||||
property == nameof(ListViewModel.SearchText))
|
||||
{
|
||||
// Only if the text actually changed...
|
||||
// (sometimes this triggers on a round-trip of the SearchText)
|
||||
if (FilterBox.Text != list.SearchText)
|
||||
{
|
||||
// ... Update our displayed text, and...
|
||||
FilterBox.Text = list.SearchText;
|
||||
|
||||
// ... Move the cursor to the end of the input
|
||||
FilterBox.Select(FilterBox.Text.Length, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Receive(GoHomeMessage message) => ClearSearch();
|
||||
|
||||
public void Receive(FocusSearchBoxMessage message) => this.Focus(Microsoft.UI.Xaml.FocusState.Programmatic);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// 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 PowerToys.Interop;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Library;
|
||||
|
||||
public delegate void KeyEvent(int key);
|
||||
|
||||
public delegate bool IsActive();
|
||||
|
||||
public delegate bool FilterAccessibleKeyboardEvents(int key, UIntPtr extraInfo);
|
||||
|
||||
public class HotkeySettingsControlHook : IDisposable
|
||||
{
|
||||
private const int WmKeyDown = 0x100;
|
||||
private const int WmKeyUp = 0x101;
|
||||
private const int WmSysKeyDown = 0x0104;
|
||||
private const int WmSysKeyUp = 0x0105;
|
||||
|
||||
private readonly KeyboardHook _hook;
|
||||
private readonly KeyEvent _keyDown;
|
||||
private readonly KeyEvent _keyUp;
|
||||
private readonly IsActive _isActive;
|
||||
|
||||
private readonly FilterAccessibleKeyboardEvents _filterKeyboardEvent;
|
||||
|
||||
private bool disposedValue;
|
||||
|
||||
public HotkeySettingsControlHook(KeyEvent keyDown, KeyEvent keyUp, IsActive isActive, FilterAccessibleKeyboardEvents filterAccessibleKeyboardEvents)
|
||||
{
|
||||
_keyDown = keyDown;
|
||||
_keyUp = keyUp;
|
||||
_isActive = isActive;
|
||||
_filterKeyboardEvent = filterAccessibleKeyboardEvents;
|
||||
_hook = new KeyboardHook(HotkeySettingsHookCallback, IsActive, FilterKeyboardEvents);
|
||||
_hook.Start();
|
||||
}
|
||||
|
||||
private bool IsActive()
|
||||
{
|
||||
return _isActive();
|
||||
}
|
||||
|
||||
private void HotkeySettingsHookCallback(KeyboardEvent ev)
|
||||
{
|
||||
switch (ev.message)
|
||||
{
|
||||
case WmKeyDown:
|
||||
case WmSysKeyDown:
|
||||
_keyDown(ev.key);
|
||||
break;
|
||||
case WmKeyUp:
|
||||
case WmSysKeyUp:
|
||||
_keyUp(ev.key);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private bool FilterKeyboardEvents(KeyboardEvent ev)
|
||||
{
|
||||
#pragma warning disable CA2020 // Prevent from behavioral change
|
||||
return _filterKeyboardEvent(ev.key, (UIntPtr)ev.dwExtraInfo);
|
||||
#pragma warning restore CA2020 // Prevent from behavioral change
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!disposedValue)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
// Dispose the KeyboardHook object to terminate the hook threads
|
||||
_hook.Dispose();
|
||||
}
|
||||
|
||||
disposedValue = true;
|
||||
}
|
||||
}
|
||||
|
||||
public bool GetDisposedState() => disposedValue;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(disposing: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Microsoft.PowerToys.Settings.UI.Helpers
|
||||
{
|
||||
internal static class NativeKeyboardHelper
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:Accessible fields should begin with upper-case letter", Justification = "Matching Native Structure")]
|
||||
internal struct INPUT
|
||||
{
|
||||
internal INPUTTYPE type;
|
||||
internal InputUnion data;
|
||||
|
||||
internal static int Size
|
||||
{
|
||||
get { return Marshal.SizeOf(typeof(INPUT)); }
|
||||
}
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Explicit)]
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:Accessible fields should begin with upper-case letter", Justification = "Matching Native Structure")]
|
||||
internal struct InputUnion
|
||||
{
|
||||
[FieldOffset(0)]
|
||||
internal MOUSEINPUT mi;
|
||||
[FieldOffset(0)]
|
||||
internal KEYBDINPUT ki;
|
||||
[FieldOffset(0)]
|
||||
internal HARDWAREINPUT hi;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:Accessible fields should begin with upper-case letter", Justification = "Matching Native Structure")]
|
||||
internal struct MOUSEINPUT
|
||||
{
|
||||
internal int dx;
|
||||
internal int dy;
|
||||
internal int mouseData;
|
||||
internal uint dwFlags;
|
||||
internal uint time;
|
||||
internal UIntPtr dwExtraInfo;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:Accessible fields should begin with upper-case letter", Justification = "Matching Native Structure")]
|
||||
internal struct KEYBDINPUT
|
||||
{
|
||||
internal short wVk;
|
||||
internal short wScan;
|
||||
internal uint dwFlags;
|
||||
internal int time;
|
||||
internal UIntPtr dwExtraInfo;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:Accessible fields should begin with upper-case letter", Justification = "Matching Native Structure")]
|
||||
internal struct HARDWAREINPUT
|
||||
{
|
||||
internal int uMsg;
|
||||
internal short wParamL;
|
||||
internal short wParamH;
|
||||
}
|
||||
|
||||
internal enum INPUTTYPE : uint
|
||||
{
|
||||
INPUT_MOUSE = 0,
|
||||
INPUT_KEYBOARD = 1,
|
||||
INPUT_HARDWARE = 2,
|
||||
}
|
||||
|
||||
[Flags]
|
||||
internal enum KeyEventF
|
||||
{
|
||||
KeyDown = 0x0000,
|
||||
ExtendedKey = 0x0001,
|
||||
KeyUp = 0x0002,
|
||||
Unicode = 0x0004,
|
||||
Scancode = 0x0008,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace Microsoft.PowerToys.Settings.UI.Helpers;
|
||||
|
||||
public static class NativeMethods
|
||||
{
|
||||
private const int WS_POPUP = 1 << 31; // 0x80000000
|
||||
internal const int GWL_STYLE = -16;
|
||||
internal const int WS_CAPTION = 0x00C00000;
|
||||
internal const int SPI_GETDESKWALLPAPER = 0x0073;
|
||||
internal const int SW_SHOWNORMAL = 1;
|
||||
internal const int SW_SHOWMAXIMIZED = 3;
|
||||
internal const int SW_HIDE = 0;
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
internal static extern IntPtr GetActiveWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
internal static extern bool SetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
internal static extern bool GetWindowPlacement(IntPtr hWnd, out WINDOWPLACEMENT lpwndpl);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
internal static extern uint SendInput(uint nInputs, NativeKeyboardHelper.INPUT[] pInputs, int cbSize);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
|
||||
internal static extern short GetAsyncKeyState(int vKey);
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
internal static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
|
||||
|
||||
// [DllImport("shell32.dll")]
|
||||
// internal static extern IntPtr SHBrowseForFolderW(ref ShellGetFolder.BrowseInformation browseInfo);
|
||||
[DllImport("shell32.dll")]
|
||||
internal static extern int SHGetPathFromIDListW(IntPtr pidl, IntPtr pszPath);
|
||||
|
||||
// [DllImport("Comdlg32.dll", CharSet = CharSet.Unicode)]
|
||||
// internal static extern bool GetOpenFileName([In, Out] OpenFileName openFileName);
|
||||
#pragma warning disable CA1401 // P/Invokes should not be visible
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool ShowWindow(System.IntPtr hWnd, int nCmdShow);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern int GetDpiForWindow(System.IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool AllowSetForegroundWindow(int dwProcessId);
|
||||
|
||||
[System.Runtime.InteropServices.DllImport("User32.dll")]
|
||||
public static extern bool SetForegroundWindow(IntPtr handle);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||
public static extern IntPtr LoadLibrary(string dllToLoad);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||
public static extern bool FreeLibrary(IntPtr hModule);
|
||||
|
||||
#pragma warning restore CA1401 // P/Invokes should not be visible
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
|
||||
internal static extern bool SystemParametersInfo(int uiAction, int uiParam, StringBuilder pvParam, int fWinIni);
|
||||
|
||||
public static void SetPopupStyle(IntPtr hwnd)
|
||||
{
|
||||
_ = SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_POPUP);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Microsoft.PowerToys.Settings.UI.Helpers
|
||||
{
|
||||
[Serializable]
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct POINT
|
||||
{
|
||||
public int X { get; set; }
|
||||
|
||||
public int Y { get; set; }
|
||||
|
||||
public POINT(int x, int y)
|
||||
{
|
||||
X = x;
|
||||
Y = y;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// 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.PowerToys.Settings.UI.Helpers
|
||||
{
|
||||
[Serializable]
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct RECT
|
||||
{
|
||||
public int Left { get; set; }
|
||||
|
||||
public int Top { get; set; }
|
||||
|
||||
public int Right { get; set; }
|
||||
|
||||
public int Bottom { get; set; }
|
||||
|
||||
public RECT(int left, int top, int right, int bottom)
|
||||
{
|
||||
Left = left;
|
||||
Top = top;
|
||||
Right = right;
|
||||
Bottom = bottom;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<UserControl
|
||||
x:Class="Microsoft.CmdPal.UI.Controls.ShortcutControl"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:controls="using:Microsoft.CmdPal.UI.Controls"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
x:Name="LayoutRoot"
|
||||
d:DesignHeight="300"
|
||||
d:DesignWidth="400"
|
||||
mc:Ignorable="d">
|
||||
|
||||
<Grid HorizontalAlignment="Right">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Button
|
||||
x:Name="EditButton"
|
||||
Padding="0"
|
||||
Click="OpenDialogButton_Click"
|
||||
CornerRadius="8">
|
||||
<StackPanel
|
||||
Margin="12,6,12,6"
|
||||
Orientation="Horizontal"
|
||||
Spacing="16">
|
||||
<ItemsControl
|
||||
x:Name="PreviewKeysControl"
|
||||
VerticalAlignment="Center"
|
||||
IsEnabled="{Binding ElementName=EditButton, Path=IsEnabled}"
|
||||
IsTabStop="False">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Horizontal" Spacing="4" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<controls:KeyVisual
|
||||
VerticalAlignment="Center"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
Content="{Binding}"
|
||||
IsTabStop="False"
|
||||
VisualType="Small" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<FontIcon
|
||||
FontFamily="{ThemeResource SymbolThemeFontFamily}"
|
||||
FontSize="16"
|
||||
Glyph="" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,511 @@
|
||||
// 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 CommunityToolkit.Mvvm.Messaging;
|
||||
using CommunityToolkit.WinUI;
|
||||
using Microsoft.CmdPal.UI.Library;
|
||||
using Microsoft.CmdPal.UI.ViewModels.Settings;
|
||||
using Microsoft.PowerToys.Settings.UI.Helpers;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Automation;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Microsoft.UI.Xaml.Input;
|
||||
using Windows.System;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipient<WindowActivatedEventArgs>
|
||||
{
|
||||
private readonly UIntPtr ignoreKeyEventFlag = 0x5555;
|
||||
private readonly System.Collections.Generic.HashSet<VirtualKey> _modifierKeysOnEntering = new();
|
||||
private bool _enabled;
|
||||
private HotkeySettings? hotkeySettings;
|
||||
private HotkeySettings internalSettings;
|
||||
private HotkeySettings? lastValidSettings;
|
||||
private HotkeySettingsControlHook? hook;
|
||||
private bool _isActive;
|
||||
private bool disposedValue;
|
||||
|
||||
public string Header { get; set; } = string.Empty;
|
||||
|
||||
public string Keys { get; set; } = string.Empty;
|
||||
|
||||
public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register("Enabled", typeof(bool), typeof(ShortcutControl), null);
|
||||
public static readonly DependencyProperty HotkeySettingsProperty = DependencyProperty.Register("HotkeySettings", typeof(HotkeySettings), typeof(ShortcutControl), null);
|
||||
|
||||
public static readonly DependencyProperty AllowDisableProperty = DependencyProperty.Register("AllowDisable", typeof(bool), typeof(ShortcutControl), new PropertyMetadata(false, OnAllowDisableChanged));
|
||||
|
||||
private static void OnAllowDisableChanged(DependencyObject d, DependencyPropertyChangedEventArgs? e)
|
||||
{
|
||||
var me = d as ShortcutControl;
|
||||
if (me == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var description = me.c?.FindDescendant<TextBlock>();
|
||||
if (description == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var resourceLoader = Microsoft.CmdPal.UI.Helpers.ResourceLoaderInstance.ResourceLoader;
|
||||
var newValue = (bool)(e?.NewValue ?? false);
|
||||
var text = newValue ?
|
||||
resourceLoader.GetString("Activation_Shortcut_With_Disable_Description") :
|
||||
resourceLoader.GetString("Activation_Shortcut_Description");
|
||||
description.Text = text;
|
||||
}
|
||||
|
||||
private readonly ShortcutDialogContentControl c = new();
|
||||
private readonly ContentDialog shortcutDialog;
|
||||
|
||||
public bool AllowDisable
|
||||
{
|
||||
get => (bool)GetValue(AllowDisableProperty);
|
||||
set => SetValue(AllowDisableProperty, value);
|
||||
}
|
||||
|
||||
public bool Enabled
|
||||
{
|
||||
get
|
||||
{
|
||||
return _enabled;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
SetValue(IsActiveProperty, value);
|
||||
_enabled = value;
|
||||
|
||||
EditButton.IsEnabled = value;
|
||||
}
|
||||
}
|
||||
|
||||
public HotkeySettings? HotkeySettings
|
||||
{
|
||||
get
|
||||
{
|
||||
return hotkeySettings;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
if (hotkeySettings != value)
|
||||
{
|
||||
hotkeySettings = value;
|
||||
SetValue(HotkeySettingsProperty, value);
|
||||
PreviewKeysControl.ItemsSource = HotkeySettings?.GetKeysList() ?? new List<object>();
|
||||
AutomationProperties.SetHelpText(EditButton, HotkeySettings?.ToString() ?? string.Empty);
|
||||
c.Keys = HotkeySettings?.GetKeysList() ?? new List<object>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ShortcutControl()
|
||||
{
|
||||
InitializeComponent();
|
||||
internalSettings = new HotkeySettings();
|
||||
|
||||
var resourceLoader = Microsoft.CmdPal.UI.Helpers.ResourceLoaderInstance.ResourceLoader;
|
||||
|
||||
// We create the Dialog in C# because doing it in XAML is giving WinUI/XAML Island bugs when using dark theme.
|
||||
shortcutDialog = new ContentDialog
|
||||
{
|
||||
XamlRoot = this.XamlRoot,
|
||||
Title = resourceLoader.GetString("Activation_Shortcut_Title"),
|
||||
Content = c,
|
||||
PrimaryButtonText = resourceLoader.GetString("Activation_Shortcut_Save"),
|
||||
SecondaryButtonText = resourceLoader.GetString("Activation_Shortcut_Reset"),
|
||||
CloseButtonText = resourceLoader.GetString("Activation_Shortcut_Cancel"),
|
||||
DefaultButton = ContentDialogButton.Primary,
|
||||
};
|
||||
shortcutDialog.SecondaryButtonClick += ShortcutDialog_Reset;
|
||||
shortcutDialog.RightTapped += ShortcutDialog_Disable;
|
||||
|
||||
// The original ShortcutControl from PowerToys would hook up the bodies
|
||||
// of DoLoad and DoUnload as `Loaded` and `Unloaded` handlers for `this`.
|
||||
// We can't do that - since we might be virtualized in a list /
|
||||
// ItemsRepeater, where those events are weirdly busted. We'd get both
|
||||
// a Loaded and Unloaded as soon as we're displayed, which won't do.
|
||||
//
|
||||
// Instead, we'll do the work they used to do on Load/Unload when the
|
||||
// dialog for this control is Opened/Close, respectively.
|
||||
shortcutDialog.Opened += (s, e) => DoLoad();
|
||||
shortcutDialog.Closed += (s, e) => DoUnload();
|
||||
shortcutDialog.Opened += ShortcutDialog_Opened;
|
||||
shortcutDialog.Closing += ShortcutDialog_Closing;
|
||||
|
||||
AutomationProperties.SetName(EditButton, resourceLoader.GetString("Activation_Shortcut_Title"));
|
||||
|
||||
WeakReferenceMessenger.Default.Register<WindowActivatedEventArgs>(this);
|
||||
|
||||
OnAllowDisableChanged(this, null);
|
||||
}
|
||||
|
||||
private void DoUnload()
|
||||
{
|
||||
shortcutDialog.PrimaryButtonClick -= ShortcutDialog_PrimaryButtonClick;
|
||||
|
||||
// The original version of this control in PowerToys would add an event
|
||||
// handler to the AppWindow here, to track if the window was active or
|
||||
// inactive.
|
||||
//
|
||||
// That doesn't really work in our setup, as we might have multiple
|
||||
// AppWindows per instance. Instead, we're having the SettingsWindow
|
||||
// send us the WindowActivatedEventArgs, so that we can know when to
|
||||
// stop our hook thread
|
||||
|
||||
// Dispose the HotkeySettingsControlHook object to terminate the hook threads when the textbox is unloaded
|
||||
hook?.Dispose();
|
||||
|
||||
hook = null;
|
||||
}
|
||||
|
||||
private void DoLoad()
|
||||
{
|
||||
// These all belong here; because of virtualization in e.g. a ListView, the control can go through several Loaded / Unloaded cycles.
|
||||
hook?.Dispose();
|
||||
|
||||
hook = new HotkeySettingsControlHook(Hotkey_KeyDown, Hotkey_KeyUp, Hotkey_IsActive, FilterAccessibleKeyboardEvents);
|
||||
|
||||
shortcutDialog.PrimaryButtonClick += ShortcutDialog_PrimaryButtonClick;
|
||||
}
|
||||
|
||||
private void KeyEventHandler(int key, bool matchValue, int matchValueCode)
|
||||
{
|
||||
var virtualKey = (VirtualKey)key;
|
||||
switch (virtualKey)
|
||||
{
|
||||
case VirtualKey.LeftWindows:
|
||||
case VirtualKey.RightWindows:
|
||||
if (!matchValue && _modifierKeysOnEntering.Contains(virtualKey))
|
||||
{
|
||||
SendSingleKeyboardInput((short)virtualKey, (uint)NativeKeyboardHelper.KeyEventF.KeyUp);
|
||||
_ = _modifierKeysOnEntering.Remove(virtualKey);
|
||||
}
|
||||
|
||||
internalSettings.Win = matchValue;
|
||||
break;
|
||||
case VirtualKey.Control:
|
||||
case VirtualKey.LeftControl:
|
||||
case VirtualKey.RightControl:
|
||||
if (!matchValue && _modifierKeysOnEntering.Contains(VirtualKey.Control))
|
||||
{
|
||||
SendSingleKeyboardInput((short)virtualKey, (uint)NativeKeyboardHelper.KeyEventF.KeyUp);
|
||||
_ = _modifierKeysOnEntering.Remove(VirtualKey.Control);
|
||||
}
|
||||
|
||||
internalSettings.Ctrl = matchValue;
|
||||
break;
|
||||
case VirtualKey.Menu:
|
||||
case VirtualKey.LeftMenu:
|
||||
case VirtualKey.RightMenu:
|
||||
if (!matchValue && _modifierKeysOnEntering.Contains(VirtualKey.Menu))
|
||||
{
|
||||
SendSingleKeyboardInput((short)virtualKey, (uint)NativeKeyboardHelper.KeyEventF.KeyUp);
|
||||
_ = _modifierKeysOnEntering.Remove(VirtualKey.Menu);
|
||||
}
|
||||
|
||||
internalSettings.Alt = matchValue;
|
||||
break;
|
||||
case VirtualKey.Shift:
|
||||
case VirtualKey.LeftShift:
|
||||
case VirtualKey.RightShift:
|
||||
if (!matchValue && _modifierKeysOnEntering.Contains(VirtualKey.Shift))
|
||||
{
|
||||
SendSingleKeyboardInput((short)virtualKey, (uint)NativeKeyboardHelper.KeyEventF.KeyUp);
|
||||
_ = _modifierKeysOnEntering.Remove(VirtualKey.Shift);
|
||||
}
|
||||
|
||||
internalSettings.Shift = matchValue;
|
||||
break;
|
||||
case VirtualKey.Escape:
|
||||
internalSettings = new HotkeySettings();
|
||||
shortcutDialog.IsPrimaryButtonEnabled = false;
|
||||
return;
|
||||
default:
|
||||
internalSettings.Code = matchValueCode;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Function to send a single key event to the system which would be ignored by the hotkey control.
|
||||
private void SendSingleKeyboardInput(short keyCode, uint keyStatus)
|
||||
{
|
||||
var inputShift = new NativeKeyboardHelper.INPUT
|
||||
{
|
||||
type = NativeKeyboardHelper.INPUTTYPE.INPUT_KEYBOARD,
|
||||
data = new NativeKeyboardHelper.InputUnion
|
||||
{
|
||||
ki = new NativeKeyboardHelper.KEYBDINPUT
|
||||
{
|
||||
wVk = keyCode,
|
||||
dwFlags = keyStatus,
|
||||
|
||||
// Any keyevent with the extraInfo set to this value will be ignored by the keyboard hook and sent to the system instead.
|
||||
dwExtraInfo = ignoreKeyEventFlag,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
NativeKeyboardHelper.INPUT[] inputs = [inputShift];
|
||||
|
||||
_ = NativeMethods.SendInput(1, inputs, NativeKeyboardHelper.INPUT.Size);
|
||||
}
|
||||
|
||||
private bool FilterAccessibleKeyboardEvents(int key, UIntPtr extraInfo)
|
||||
{
|
||||
// A keyboard event sent with this value in the extra Information field should be ignored by the hook so that it can be captured by the system instead.
|
||||
if (extraInfo == ignoreKeyEventFlag)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// If the current key press is tab, based on the other keys ignore the key press so as to shift focus out of the hotkey control.
|
||||
if ((VirtualKey)key == VirtualKey.Tab)
|
||||
{
|
||||
// Shift was not pressed while entering and Shift is not pressed while leaving the hotkey control, treat it as a normal tab key press.
|
||||
if (!internalSettings.Shift && !_modifierKeysOnEntering.Contains(VirtualKey.Shift) && !internalSettings.Win && !internalSettings.Alt && !internalSettings.Ctrl)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Shift was not pressed while entering but it was pressed while leaving the hotkey, therefore simulate a shift key press as the system does not know about shift being pressed in the hotkey.
|
||||
else if (internalSettings.Shift && !_modifierKeysOnEntering.Contains(VirtualKey.Shift) && !internalSettings.Win && !internalSettings.Alt && !internalSettings.Ctrl)
|
||||
{
|
||||
// This is to reset the shift key press within the control as it was not used within the control but rather was used to leave the hotkey.
|
||||
internalSettings.Shift = false;
|
||||
|
||||
SendSingleKeyboardInput((short)VirtualKey.Shift, (uint)NativeKeyboardHelper.KeyEventF.KeyDown);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Shift was pressed on entering and remained pressed, therefore only ignore the tab key so that it can be passed to the system.
|
||||
// As the shift key is already assumed to be pressed by the system while it entered the hotkey control, shift would still remain pressed, hence ignoring the tab input would simulate a Shift+Tab key press.
|
||||
else if (!internalSettings.Shift && _modifierKeysOnEntering.Contains(VirtualKey.Shift) && !internalSettings.Win && !internalSettings.Alt && !internalSettings.Ctrl)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Either the cancel or save button has keyboard focus.
|
||||
return FocusManager.GetFocusedElement(LayoutRoot.XamlRoot).GetType() != typeof(Button);
|
||||
}
|
||||
|
||||
private void Hotkey_KeyDown(int key)
|
||||
{
|
||||
KeyEventHandler(key, true, key);
|
||||
|
||||
c.Keys = internalSettings.GetKeysList();
|
||||
|
||||
if (internalSettings.GetKeysList().Count == 0)
|
||||
{
|
||||
// Empty, disable save button
|
||||
shortcutDialog.IsPrimaryButtonEnabled = false;
|
||||
}
|
||||
else if (internalSettings.GetKeysList().Count == 1)
|
||||
{
|
||||
// 1 key, disable save button
|
||||
shortcutDialog.IsPrimaryButtonEnabled = false;
|
||||
|
||||
// Check if the one key is a hotkey
|
||||
c.IsError = !internalSettings.Shift && !internalSettings.Win && !internalSettings.Alt && !internalSettings.Ctrl;
|
||||
}
|
||||
|
||||
// Tab and Shift+Tab are accessible keys and should not be displayed in the hotkey control.
|
||||
if (internalSettings.Code > 0 && !internalSettings.IsAccessibleShortcut())
|
||||
{
|
||||
lastValidSettings = internalSettings with { };
|
||||
|
||||
if (!ComboIsValid(lastValidSettings))
|
||||
{
|
||||
DisableKeys();
|
||||
}
|
||||
else
|
||||
{
|
||||
EnableKeys();
|
||||
}
|
||||
}
|
||||
|
||||
c.IsWarningAltGr = internalSettings.Ctrl && internalSettings.Alt && !internalSettings.Win && (internalSettings.Code > 0);
|
||||
}
|
||||
|
||||
private void EnableKeys()
|
||||
{
|
||||
shortcutDialog.IsPrimaryButtonEnabled = true;
|
||||
c.IsError = false;
|
||||
|
||||
// WarningLabel.Style = (Style)App.Current.Resources["SecondaryTextStyle"];
|
||||
}
|
||||
|
||||
private void DisableKeys()
|
||||
{
|
||||
shortcutDialog.IsPrimaryButtonEnabled = false;
|
||||
c.IsError = true;
|
||||
|
||||
// WarningLabel.Style = (Style)App.Current.Resources["SecondaryWarningTextStyle"];
|
||||
}
|
||||
|
||||
private void Hotkey_KeyUp(int key)
|
||||
{
|
||||
KeyEventHandler(key, false, 0);
|
||||
}
|
||||
|
||||
private bool Hotkey_IsActive()
|
||||
{
|
||||
return _isActive;
|
||||
}
|
||||
|
||||
private void ShortcutDialog_Opened(ContentDialog sender, ContentDialogOpenedEventArgs args)
|
||||
{
|
||||
if (!ComboIsValid(hotkeySettings))
|
||||
{
|
||||
DisableKeys();
|
||||
}
|
||||
else
|
||||
{
|
||||
EnableKeys();
|
||||
}
|
||||
|
||||
// Reset the status on entering the hotkey each time.
|
||||
_modifierKeysOnEntering.Clear();
|
||||
|
||||
// To keep track of the modifier keys, whether it was pressed on entering.
|
||||
if ((NativeMethods.GetAsyncKeyState((int)VirtualKey.Shift) & 0x8000) != 0)
|
||||
{
|
||||
_modifierKeysOnEntering.Add(VirtualKey.Shift);
|
||||
}
|
||||
|
||||
if ((NativeMethods.GetAsyncKeyState((int)VirtualKey.Control) & 0x8000) != 0)
|
||||
{
|
||||
_modifierKeysOnEntering.Add(VirtualKey.Control);
|
||||
}
|
||||
|
||||
if ((NativeMethods.GetAsyncKeyState((int)VirtualKey.Menu) & 0x8000) != 0)
|
||||
{
|
||||
_modifierKeysOnEntering.Add(VirtualKey.Menu);
|
||||
}
|
||||
|
||||
if ((NativeMethods.GetAsyncKeyState((int)VirtualKey.LeftWindows) & 0x8000) != 0)
|
||||
{
|
||||
_modifierKeysOnEntering.Add(VirtualKey.LeftWindows);
|
||||
}
|
||||
|
||||
if ((NativeMethods.GetAsyncKeyState((int)VirtualKey.RightWindows) & 0x8000) != 0)
|
||||
{
|
||||
_modifierKeysOnEntering.Add(VirtualKey.RightWindows);
|
||||
}
|
||||
|
||||
_isActive = true;
|
||||
}
|
||||
|
||||
private async void OpenDialogButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
// c.Keys = null;
|
||||
c.Keys = HotkeySettings?.GetKeysList() ?? new List<object>();
|
||||
|
||||
// 92 means the Win key. The logic is: warning should be visible if the shortcut contains Alt AND contains Ctrl AND NOT contains Win.
|
||||
// Additional key must be present, as this is a valid, previously used shortcut shown at dialog open. Check for presence of non-modifier-key is not necessary therefore
|
||||
c.IsWarningAltGr = c.Keys.Contains("Ctrl") && c.Keys.Contains("Alt") && !c.Keys.Contains(92);
|
||||
|
||||
shortcutDialog.XamlRoot = this.XamlRoot;
|
||||
shortcutDialog.RequestedTheme = this.ActualTheme;
|
||||
await shortcutDialog.ShowAsync();
|
||||
}
|
||||
|
||||
private void ShortcutDialog_Reset(ContentDialog sender, ContentDialogButtonClickEventArgs args)
|
||||
{
|
||||
hotkeySettings = null;
|
||||
|
||||
SetValue(HotkeySettingsProperty, hotkeySettings);
|
||||
PreviewKeysControl.ItemsSource = HotkeySettings?.GetKeysList() ?? new List<object>();
|
||||
|
||||
lastValidSettings = hotkeySettings;
|
||||
|
||||
AutomationProperties.SetHelpText(EditButton, HotkeySettings?.ToString() ?? string.Empty);
|
||||
shortcutDialog.Hide();
|
||||
}
|
||||
|
||||
private void ShortcutDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
|
||||
{
|
||||
if (lastValidSettings != null && ComboIsValid(lastValidSettings))
|
||||
{
|
||||
HotkeySettings = lastValidSettings with { };
|
||||
}
|
||||
|
||||
PreviewKeysControl.ItemsSource = hotkeySettings?.GetKeysList() ?? new List<object>();
|
||||
AutomationProperties.SetHelpText(EditButton, HotkeySettings?.ToString() ?? string.Empty);
|
||||
shortcutDialog.Hide();
|
||||
}
|
||||
|
||||
private void ShortcutDialog_Disable(object sender, RightTappedRoutedEventArgs e)
|
||||
{
|
||||
if (!AllowDisable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var empty = new HotkeySettings();
|
||||
HotkeySettings = empty;
|
||||
|
||||
PreviewKeysControl.ItemsSource = HotkeySettings.GetKeysList();
|
||||
AutomationProperties.SetHelpText(EditButton, HotkeySettings.ToString());
|
||||
shortcutDialog.Hide();
|
||||
}
|
||||
|
||||
private static bool ComboIsValid(HotkeySettings? settings)
|
||||
{
|
||||
return settings != null && (settings.IsValid() || settings.IsEmpty());
|
||||
}
|
||||
|
||||
public void Receive(WindowActivatedEventArgs message) => DoWindowActivated(message);
|
||||
|
||||
private void DoWindowActivated(WindowActivatedEventArgs args)
|
||||
{
|
||||
args.Handled = true;
|
||||
if (args.WindowActivationState != WindowActivationState.Deactivated && (hook == 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)
|
||||
{
|
||||
// If the PT settings window lost focus/activation, we disable the keyboard hook to allow keyboard input on other windows.
|
||||
hook.Dispose();
|
||||
hook = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void ShortcutDialog_Closing(ContentDialog sender, ContentDialogClosingEventArgs args)
|
||||
{
|
||||
_isActive = false;
|
||||
}
|
||||
|
||||
private void Dispose(bool disposing)
|
||||
{
|
||||
if (!disposedValue)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
if (hook != null)
|
||||
{
|
||||
hook.Dispose();
|
||||
}
|
||||
|
||||
hook = null;
|
||||
}
|
||||
|
||||
disposedValue = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
|
||||
Dispose(disposing: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<UserControl
|
||||
x:Class="Microsoft.CmdPal.UI.Controls.ShortcutDialogContentControl"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:controls="using:Microsoft.CmdPal.UI.Controls"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:tk7controls="using:CommunityToolkit.WinUI.UI.Controls"
|
||||
x:Name="ShortcutContentControl"
|
||||
mc:Ignorable="d">
|
||||
<Grid MinWidth="498" MinHeight="220">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition MinHeight="110" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0" />
|
||||
|
||||
<ItemsControl
|
||||
x:Name="KeysControl"
|
||||
Grid.Row="1"
|
||||
Height="56"
|
||||
Margin="0,64,0,0"
|
||||
HorizontalAlignment="Center"
|
||||
VerticalAlignment="Top"
|
||||
HorizontalContentAlignment="Center"
|
||||
ItemsSource="{x:Bind Keys, Mode=OneWay}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<controls:KeyVisual
|
||||
Height="56"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
Content="{Binding}"
|
||||
IsError="{Binding ElementName=ShortcutContentControl, Path=IsError, Mode=OneWay}"
|
||||
IsTabStop="False"
|
||||
VisualType="Large" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
|
||||
<StackPanel
|
||||
Grid.Row="2"
|
||||
Margin="0,24,0,0"
|
||||
VerticalAlignment="Top"
|
||||
Orientation="Vertical"
|
||||
Spacing="8">
|
||||
<Grid Height="62">
|
||||
|
||||
<InfoBar
|
||||
x:Uid="InvalidShortcut"
|
||||
IsClosable="False"
|
||||
IsOpen="{Binding ElementName=ShortcutContentControl, Path=IsError, Mode=OneWay}"
|
||||
IsTabStop="{Binding ElementName=ShortcutContentControl, Path=IsError, Mode=OneWay}"
|
||||
Severity="Error" />
|
||||
|
||||
<InfoBar
|
||||
x:Uid="WarningShortcutAltGr"
|
||||
IsClosable="False"
|
||||
IsOpen="{Binding ElementName=ShortcutContentControl, Path=IsWarningAltGr, Mode=OneWay}"
|
||||
IsTabStop="{Binding ElementName=ShortcutContentControl, Path=IsWarningAltGr, Mode=OneWay}"
|
||||
Severity="Warning" />
|
||||
</Grid>
|
||||
<tk7controls:MarkdownTextBlock
|
||||
x:Uid="InvalidShortcutWarningLabel"
|
||||
Background="Transparent"
|
||||
FontSize="12"
|
||||
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,41 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.CmdPal.UI;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
public sealed partial class ShortcutDialogContentControl : UserControl
|
||||
{
|
||||
public ShortcutDialogContentControl()
|
||||
{
|
||||
this.InitializeComponent();
|
||||
}
|
||||
|
||||
public List<object> Keys
|
||||
{
|
||||
get { return (List<object>)GetValue(KeysProperty); }
|
||||
set { SetValue(KeysProperty, value); }
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty KeysProperty = DependencyProperty.Register("Keys", typeof(List<object>), typeof(ShortcutDialogContentControl), new PropertyMetadata(default(string)));
|
||||
|
||||
public bool IsError
|
||||
{
|
||||
get => (bool)GetValue(IsErrorProperty);
|
||||
set => SetValue(IsErrorProperty, value);
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty IsErrorProperty = DependencyProperty.Register("IsError", typeof(bool), typeof(ShortcutDialogContentControl), new PropertyMetadata(false));
|
||||
|
||||
public bool IsWarningAltGr
|
||||
{
|
||||
get => (bool)GetValue(IsWarningAltGrProperty);
|
||||
set => SetValue(IsWarningAltGrProperty, value);
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty IsWarningAltGrProperty = DependencyProperty.Register("IsWarningAltGr", typeof(bool), typeof(ShortcutDialogContentControl), new PropertyMetadata(false));
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<UserControl
|
||||
x:Class="Microsoft.CmdPal.UI.Controls.ShortcutWithTextLabelControl"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:controls="using:Microsoft.CmdPal.UI.Controls"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:tk7controls="using:CommunityToolkit.WinUI.UI.Controls"
|
||||
d:DesignHeight="300"
|
||||
d:DesignWidth="400"
|
||||
mc:Ignorable="d">
|
||||
|
||||
<Grid ColumnSpacing="8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ItemsControl
|
||||
VerticalAlignment="Center"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
IsTabStop="False"
|
||||
ItemsSource="{x:Bind Keys}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Horizontal" Spacing="4" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<controls:KeyVisual
|
||||
VerticalAlignment="Center"
|
||||
AutomationProperties.AccessibilityView="Raw"
|
||||
Content="{Binding}"
|
||||
IsTabStop="False"
|
||||
VisualType="SmallOutline" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<tk7controls:MarkdownTextBlock
|
||||
Grid.Column="1"
|
||||
VerticalAlignment="Center"
|
||||
Background="Transparent"
|
||||
Text="{x:Bind Text}" />
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,35 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls
|
||||
{
|
||||
public sealed partial class ShortcutWithTextLabelControl : UserControl
|
||||
{
|
||||
public string Text
|
||||
{
|
||||
get { return (string)GetValue(TextProperty); }
|
||||
set { SetValue(TextProperty, value); }
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(ShortcutWithTextLabelControl), new PropertyMetadata(default(string)));
|
||||
|
||||
public List<object> Keys
|
||||
{
|
||||
get { return (List<object>)GetValue(KeysProperty); }
|
||||
set { SetValue(KeysProperty, value); }
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty KeysProperty = DependencyProperty.Register("Keys", typeof(List<object>), typeof(ShortcutWithTextLabelControl), new PropertyMetadata(default(string)));
|
||||
|
||||
public ShortcutWithTextLabelControl()
|
||||
{
|
||||
this.InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// 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.PowerToys.Settings.UI.Helpers
|
||||
{
|
||||
[Serializable]
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct WINDOWPLACEMENT
|
||||
{
|
||||
public int Length { get; set; }
|
||||
|
||||
public int Flags { get; set; }
|
||||
|
||||
public int ShowCmd { get; set; }
|
||||
|
||||
public POINT MinPosition { get; set; }
|
||||
|
||||
public POINT MaxPosition { get; set; }
|
||||
|
||||
public RECT NormalPosition { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// 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 CommunityToolkit.Common.Deferred;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
/// <summary>
|
||||
/// See <see cref="IconBox.SourceRequested"/> event.
|
||||
/// </summary>
|
||||
public class SourceRequestedEventArgs(object? key, ElementTheme requestedTheme) : DeferredEventArgs
|
||||
{
|
||||
public object? Key { get; private set; } = key;
|
||||
|
||||
public IconSource? Value { get; set; }
|
||||
|
||||
public ElementTheme Theme => requestedTheme;
|
||||
}
|
||||
88
src/modules/cmdpal/Microsoft.CmdPal.UI/Controls/Tag.xaml
Normal file
88
src/modules/cmdpal/Microsoft.CmdPal.UI/Controls/Tag.xaml
Normal file
@@ -0,0 +1,88 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<ResourceDictionary
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="using:Microsoft.CmdPal.UI.Controls">
|
||||
|
||||
<ResourceDictionary.ThemeDictionaries>
|
||||
<ResourceDictionary x:Key="Default">
|
||||
<StaticResource x:Key="TagBackground" ResourceKey="CardBackgroundFillColorDefaultBrush" />
|
||||
<StaticResource x:Key="TagBorderBrush" ResourceKey="CardStrokeColorDefaultBrush" />
|
||||
<StaticResource x:Key="TagForeground" ResourceKey="TextFillColorTertiaryBrush" />
|
||||
</ResourceDictionary>
|
||||
|
||||
<ResourceDictionary x:Key="Light">
|
||||
<StaticResource x:Key="TagBackground" ResourceKey="CardBackgroundFillColorDefaultBrush" />
|
||||
<StaticResource x:Key="TagBorderBrush" ResourceKey="CardStrokeColorDefaultBrush" />
|
||||
<StaticResource x:Key="TagForeground" ResourceKey="TextFillColorTertiaryBrush" />
|
||||
</ResourceDictionary>
|
||||
|
||||
<ResourceDictionary x:Key="HighContrast">
|
||||
<StaticResource x:Key="TagBackground" ResourceKey="SystemColorButtonFaceColorBrush" />
|
||||
<StaticResource x:Key="TagBorderBrush" ResourceKey="ControlFillColorTransparent" />
|
||||
<StaticResource x:Key="TagForeground" ResourceKey="SystemColorButtonTextColorBrush" />
|
||||
</ResourceDictionary>
|
||||
|
||||
</ResourceDictionary.ThemeDictionaries>
|
||||
<Thickness x:Key="TagPadding">4,2,4,2</Thickness>
|
||||
<Thickness x:Key="TagBorderThickness">1</Thickness>
|
||||
|
||||
<Style BasedOn="{StaticResource DefaultTagStyle}" TargetType="local:Tag" />
|
||||
|
||||
<Style x:Key="DefaultTagStyle" TargetType="local:Tag">
|
||||
<Style.Setters>
|
||||
<Setter Property="Background" Value="{ThemeResource TagBackground}" />
|
||||
<Setter Property="Foreground" Value="{ThemeResource TagForeground}" />
|
||||
<Setter Property="BorderBrush" Value="{ThemeResource TagBorderBrush}" />
|
||||
<Setter Property="BorderThickness" Value="{ThemeResource TagBorderThickness}" />
|
||||
<Setter Property="CornerRadius" Value="{ThemeResource ControlCornerRadius}" />
|
||||
<Setter Property="IsTabStop" Value="False" />
|
||||
<Setter Property="HorizontalAlignment" Value="Center" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="BackgroundSizing" Value="InnerBorderEdge" />
|
||||
<Setter Property="Padding" Value="{ThemeResource TagPadding}" />
|
||||
<Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}" />
|
||||
<Setter Property="FontWeight" Value="Normal" />
|
||||
<Setter Property="FontSize" Value="{StaticResource CaptionTextBlockFontSize}" />
|
||||
<Setter Property="UseSystemFocusVisuals" Value="{StaticResource UseSystemFocusVisuals}" />
|
||||
<Setter Property="FocusVisualMargin" Value="-3" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="local:Tag">
|
||||
<Grid
|
||||
x:Name="PART_RootGrid"
|
||||
MinWidth="{TemplateBinding MinWidth}"
|
||||
MinHeight="{TemplateBinding MinHeight}"
|
||||
MaxWidth="{TemplateBinding MaxWidth}"
|
||||
Padding="{TemplateBinding Padding}"
|
||||
HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
|
||||
VerticalAlignment="{TemplateBinding VerticalAlignment}"
|
||||
Background="{TemplateBinding Background}"
|
||||
BackgroundSizing="{TemplateBinding BackgroundSizing}"
|
||||
BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}"
|
||||
CornerRadius="{TemplateBinding CornerRadius}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<local:IconBox
|
||||
x:Name="PART_Icon"
|
||||
Grid.Column="0"
|
||||
Height="12"
|
||||
Margin="0,0,4,0"
|
||||
SourceKey="{TemplateBinding Icon}" />
|
||||
<TextBlock
|
||||
Grid.Column="1"
|
||||
CharacterSpacing="{TemplateBinding CharacterSpacing}"
|
||||
FontFamily="{TemplateBinding FontFamily}"
|
||||
FontSize="{TemplateBinding FontSize}"
|
||||
FontWeight="{TemplateBinding FontWeight}"
|
||||
Text="{TemplateBinding Text}" />
|
||||
</Grid>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style.Setters>
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
153
src/modules/cmdpal/Microsoft.CmdPal.UI/Controls/Tag.xaml.cs
Normal file
153
src/modules/cmdpal/Microsoft.CmdPal.UI/Controls/Tag.xaml.cs
Normal file
@@ -0,0 +1,153 @@
|
||||
// Copyright (c) Microsoft Corporation
|
||||
// The Microsoft Corporation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using Microsoft.CmdPal.UI.Helpers;
|
||||
using Microsoft.CmdPal.UI.ViewModels;
|
||||
using Microsoft.CommandPalette.Extensions;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Microsoft.UI.Xaml.Media;
|
||||
|
||||
namespace Microsoft.CmdPal.UI.Controls;
|
||||
|
||||
[TemplatePart(Name = TagIconBox, Type = typeof(IconBox))]
|
||||
|
||||
public partial class Tag : Control
|
||||
{
|
||||
internal const string TagIconBox = "PART_Icon";
|
||||
|
||||
public OptionalColor? BackgroundColor
|
||||
{
|
||||
get => (OptionalColor?)GetValue(BackgroundColorProperty);
|
||||
set => SetValue(BackgroundColorProperty, value);
|
||||
}
|
||||
|
||||
public OptionalColor? ForegroundColor
|
||||
{
|
||||
get => (OptionalColor?)GetValue(ForegroundColorProperty);
|
||||
set => SetValue(ForegroundColorProperty, value);
|
||||
}
|
||||
|
||||
public bool HasIcon => Icon?.HasIcon(this.ActualTheme == ElementTheme.Light) ?? false;
|
||||
|
||||
public IconInfoViewModel? Icon
|
||||
{
|
||||
get => (IconInfoViewModel?)GetValue(IconProperty);
|
||||
set => SetValue(IconProperty, value);
|
||||
}
|
||||
|
||||
public string? Text
|
||||
{
|
||||
get => (string?)GetValue(TextProperty);
|
||||
set => SetValue(TextProperty, value);
|
||||
}
|
||||
|
||||
private static Brush? OriginalBg => Application.Current.Resources["TagBackground"] as Brush;
|
||||
|
||||
private static Brush? OriginalFg => Application.Current.Resources["TagForeground"] as Brush;
|
||||
|
||||
private static Brush? OriginalBorder => Application.Current.Resources["TagBorderBrush"] as Brush;
|
||||
|
||||
public static readonly DependencyProperty ForegroundColorProperty =
|
||||
DependencyProperty.Register(nameof(ForegroundColor), typeof(OptionalColor), typeof(Tag), new PropertyMetadata(null, OnForegroundColorPropertyChanged));
|
||||
|
||||
public static readonly DependencyProperty BackgroundColorProperty =
|
||||
DependencyProperty.Register(nameof(BackgroundColor), typeof(OptionalColor), typeof(Tag), new PropertyMetadata(null, OnBackgroundColorPropertyChanged));
|
||||
|
||||
public static readonly DependencyProperty IconProperty =
|
||||
DependencyProperty.Register(nameof(Icon), typeof(IconInfoViewModel), typeof(Tag), new PropertyMetadata(null));
|
||||
|
||||
public static readonly DependencyProperty TextProperty =
|
||||
DependencyProperty.Register(nameof(Text), typeof(string), typeof(Tag), new PropertyMetadata(null));
|
||||
|
||||
public Tag()
|
||||
{
|
||||
this.DefaultStyleKey = typeof(Tag);
|
||||
}
|
||||
|
||||
protected override void OnApplyTemplate()
|
||||
{
|
||||
base.OnApplyTemplate();
|
||||
|
||||
if (GetTemplateChild(TagIconBox) is IconBox iconBox)
|
||||
{
|
||||
iconBox.SourceRequested += IconCacheProvider.SourceRequested;
|
||||
iconBox.Visibility = HasIcon ? Visibility.Visible : Visibility.Collapsed;
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnForegroundColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is not Tag tag)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (tag.ForegroundColor != null &&
|
||||
OptionalColorBrushCacheProvider.Convert(tag.ForegroundColor.Value) is SolidColorBrush brush)
|
||||
{
|
||||
tag.Foreground = brush;
|
||||
|
||||
// If we have a BG color, then don't apply a border.
|
||||
if (tag.BackgroundColor is OptionalColor bg && bg.HasValue)
|
||||
{
|
||||
tag.BorderBrush = OriginalBorder;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise (no background), use the FG as the border
|
||||
tag.BorderBrush = brush;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
tag.Foreground = OriginalFg;
|
||||
tag.BorderBrush = OriginalBorder;
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnBackgroundColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is not Tag tag)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (tag.BackgroundColor != null &&
|
||||
OptionalColorBrushCacheProvider.Convert(tag.BackgroundColor.Value) is SolidColorBrush brush)
|
||||
{
|
||||
tag.Background = brush;
|
||||
|
||||
// Since we have a BG here, we never want a border.
|
||||
tag.BorderBrush = OriginalBorder;
|
||||
|
||||
// If we have a FG color, then don't apply a border.
|
||||
if (tag.ForegroundColor is OptionalColor fg && fg.HasValue)
|
||||
{
|
||||
tag.BorderBrush = OriginalBorder;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise (no foreground), use the FG as the border
|
||||
tag.BorderBrush = brush;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// No BG color here.
|
||||
tag.Background = OriginalBg;
|
||||
|
||||
// If we have a FG color, then don't apply a border.
|
||||
if (tag.ForegroundColor is OptionalColor fg && fg.HasValue)
|
||||
{
|
||||
tag.BorderBrush = tag.Foreground;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise (no foreground), use the FG as the border
|
||||
tag.BorderBrush = OriginalBorder;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user