Compare commits

..

4 Commits

Author SHA1 Message Date
vanzue
b2f0008473 fix unrecognized word 2025-07-25 15:34:38 +08:00
vanzue
8586dc88bb add local winget testing doc 2025-07-25 15:23:59 +08:00
vanzue
3322b8ca2f refine words 2025-07-25 14:37:20 +08:00
vanzue
50038cbf3e Add doc for build a local installer 2025-07-25 14:21:39 +08:00
202 changed files with 1285 additions and 1760 deletions

View File

@@ -1440,6 +1440,7 @@ secpol
securestring
SEEMASKINVOKEIDLIST
SELCHANGE
selfhost
SENDCHANGE
sendvirtualinput
serverside
@@ -1879,6 +1880,7 @@ winexe
winforms
winget
wingetcreate
wingetpkgs
Winhook
WINL
winlogon

View File

@@ -760,7 +760,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdvancedPaste.FuzzTests", "
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdvancedPaste.UnitTests", "src\modules\AdvancedPaste\AdvancedPaste.UnitTests\AdvancedPaste.UnitTests.csproj", "{988C9FAF-5AEC-EB15-578D-FED0DF52BF55}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.CmdPal.UITests", "src\modules\cmdpal\Tests\Microsoft.CmdPal.UITests\Microsoft.CmdPal.UITests.csproj", "{6748A29D-DA6A-033A-825B-752295FF6AA0}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.CmdPal.UITests", "src\modules\cmdpal\Microsoft.CmdPal.UITests\Microsoft.CmdPal.UITests.csproj", "{6748A29D-DA6A-033A-825B-752295FF6AA0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FancyZones.FuzzTests", "src\modules\fancyzones\FancyZones.FuzzTests\FancyZones.FuzzTests.csproj", "{6EABCF9A-6526-441F-932F-658B1DC3E403}"
EndProject
@@ -776,14 +776,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{8131151D-B
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.CmdPal.Ext.Calc.UnitTests", "src\modules\cmdpal\Tests\Microsoft.CmdPal.Ext.Calc.UnitTests\Microsoft.CmdPal.Ext.Calc.UnitTests.csproj", "{E816D7AC-4688-4ECB-97CC-3D8E798F3825}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.CmdPal.Ext.Registry.UnitTests", "src\modules\cmdpal\Tests\Microsoft.CmdPal.Ext.Registry.UnitTests\Microsoft.CmdPal.Ext.Registry.UnitTests.csproj", "{E816D7AD-4688-4ECB-97CC-3D8E798F3826}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.CmdPal.Ext.System.UnitTests", "src\modules\cmdpal\Tests\Microsoft.CmdPal.Ext.System.UnitTests\Microsoft.CmdPal.Ext.System.UnitTests.csproj", "{E816D7AE-4688-4ECB-97CC-3D8E798F3827}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.CmdPal.Ext.TimeDate.UnitTests", "src\modules\cmdpal\Tests\Microsoft.CmdPal.Ext.TimeDate.UnitTests\Microsoft.CmdPal.Ext.TimeDate.UnitTests.csproj", "{E816D7AF-4688-4ECB-97CC-3D8E798F3828}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.CmdPal.Ext.WindowWalker.UnitTests", "src\modules\cmdpal\Tests\Microsoft.CmdPal.Ext.WindowWalker.UnitTests\Microsoft.CmdPal.Ext.WindowWalker.UnitTests.csproj", "{E816D7B0-4688-4ECB-97CC-3D8E798F3829}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM64 = Debug|ARM64
@@ -2798,38 +2790,6 @@ Global
{E816D7AC-4688-4ECB-97CC-3D8E798F3825}.Release|ARM64.Build.0 = Release|ARM64
{E816D7AC-4688-4ECB-97CC-3D8E798F3825}.Release|x64.ActiveCfg = Release|x64
{E816D7AC-4688-4ECB-97CC-3D8E798F3825}.Release|x64.Build.0 = Release|x64
{E816D7AD-4688-4ECB-97CC-3D8E798F3826}.Debug|ARM64.ActiveCfg = Debug|ARM64
{E816D7AD-4688-4ECB-97CC-3D8E798F3826}.Debug|ARM64.Build.0 = Debug|ARM64
{E816D7AD-4688-4ECB-97CC-3D8E798F3826}.Debug|x64.ActiveCfg = Debug|x64
{E816D7AD-4688-4ECB-97CC-3D8E798F3826}.Debug|x64.Build.0 = Debug|x64
{E816D7AD-4688-4ECB-97CC-3D8E798F3826}.Release|ARM64.ActiveCfg = Release|ARM64
{E816D7AD-4688-4ECB-97CC-3D8E798F3826}.Release|ARM64.Build.0 = Release|ARM64
{E816D7AD-4688-4ECB-97CC-3D8E798F3826}.Release|x64.ActiveCfg = Release|x64
{E816D7AD-4688-4ECB-97CC-3D8E798F3826}.Release|x64.Build.0 = Release|x64
{E816D7AE-4688-4ECB-97CC-3D8E798F3827}.Debug|ARM64.ActiveCfg = Debug|ARM64
{E816D7AE-4688-4ECB-97CC-3D8E798F3827}.Debug|ARM64.Build.0 = Debug|ARM64
{E816D7AE-4688-4ECB-97CC-3D8E798F3827}.Debug|x64.ActiveCfg = Debug|x64
{E816D7AE-4688-4ECB-97CC-3D8E798F3827}.Debug|x64.Build.0 = Debug|x64
{E816D7AE-4688-4ECB-97CC-3D8E798F3827}.Release|ARM64.ActiveCfg = Release|ARM64
{E816D7AE-4688-4ECB-97CC-3D8E798F3827}.Release|ARM64.Build.0 = Release|ARM64
{E816D7AE-4688-4ECB-97CC-3D8E798F3827}.Release|x64.ActiveCfg = Release|x64
{E816D7AE-4688-4ECB-97CC-3D8E798F3827}.Release|x64.Build.0 = Release|x64
{E816D7AF-4688-4ECB-97CC-3D8E798F3828}.Debug|ARM64.ActiveCfg = Debug|ARM64
{E816D7AF-4688-4ECB-97CC-3D8E798F3828}.Debug|ARM64.Build.0 = Debug|ARM64
{E816D7AF-4688-4ECB-97CC-3D8E798F3828}.Debug|x64.ActiveCfg = Debug|x64
{E816D7AF-4688-4ECB-97CC-3D8E798F3828}.Debug|x64.Build.0 = Debug|x64
{E816D7AF-4688-4ECB-97CC-3D8E798F3828}.Release|ARM64.ActiveCfg = Release|ARM64
{E816D7AF-4688-4ECB-97CC-3D8E798F3828}.Release|ARM64.Build.0 = Release|ARM64
{E816D7AF-4688-4ECB-97CC-3D8E798F3828}.Release|x64.ActiveCfg = Release|x64
{E816D7AF-4688-4ECB-97CC-3D8E798F3828}.Release|x64.Build.0 = Release|x64
{E816D7B0-4688-4ECB-97CC-3D8E798F3829}.Debug|ARM64.ActiveCfg = Debug|ARM64
{E816D7B0-4688-4ECB-97CC-3D8E798F3829}.Debug|ARM64.Build.0 = Debug|ARM64
{E816D7B0-4688-4ECB-97CC-3D8E798F3829}.Debug|x64.ActiveCfg = Debug|x64
{E816D7B0-4688-4ECB-97CC-3D8E798F3829}.Debug|x64.Build.0 = Debug|x64
{E816D7B0-4688-4ECB-97CC-3D8E798F3829}.Release|ARM64.ActiveCfg = Release|ARM64
{E816D7B0-4688-4ECB-97CC-3D8E798F3829}.Release|ARM64.Build.0 = Release|ARM64
{E816D7B0-4688-4ECB-97CC-3D8E798F3829}.Release|x64.ActiveCfg = Release|x64
{E816D7B0-4688-4ECB-97CC-3D8E798F3829}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -3117,11 +3077,6 @@ Global
{D9BD324E-1D80-44AA-8E7B-73EB00944434} = {38BDB927-829B-4C65-9CD9-93FB05D66D65}
{8EF25507-2575-4ADE-BF7E-D23376903AB8} = {3846508C-77EB-4034-A702-F8BB263C4F79}
{070AC093-C9F2-20AD-0BCD-F318FC2761EA} = {B1234567-1234-1234-1234-123456789ABC}
{E816D7AC-4688-4ECB-97CC-3D8E798F3825} = {8EF25507-2575-4ADE-BF7E-D23376903AB8}
{E816D7AD-4688-4ECB-97CC-3D8E798F3826} = {8EF25507-2575-4ADE-BF7E-D23376903AB8}
{E816D7AE-4688-4ECB-97CC-3D8E798F3827} = {8EF25507-2575-4ADE-BF7E-D23376903AB8}
{E816D7AF-4688-4ECB-97CC-3D8E798F3828} = {8EF25507-2575-4ADE-BF7E-D23376903AB8}
{E816D7B0-4688-4ECB-97CC-3D8E798F3829} = {8EF25507-2575-4ADE-BF7E-D23376903AB8}
{2C318EC3-BA86-4372-B1BC-DB0F33C208B2} = {322566EF-20DC-43A6-B9F8-616AF942579A}
{BFFB607F-7C78-434B-86B9-DA4C8196A1B5} = {B6C42F16-73EB-477E-8B0D-4E6CF6C20AAC}
{66E1534A-1587-42B2-912F-45C994D32904} = {89E20BCE-EB9C-46C8-8B50-E01A82E6FDC3}

View File

@@ -87,6 +87,13 @@
### Building PowerToys Locally
#### One stop script for building installer
1. Open developer powershell for vs 2022
2. Run tools\build\build-installer.ps1
> For the first-time setup, please run the installer as an administrator. This ensures that the Wix tool can move wix.target to the desired location and trust the certificate used to sign the MSIX packages.
The following manual steps will not install the MSIX apps (such as Command Palette) on your local installer.
#### Prerequisites for building the MSI installer
1. Install the [WiX Toolset Visual Studio 2022 Extension](https://marketplace.visualstudio.com/items?itemName=WixToolset.WixToolsetVisualStudio2022Extension).

View File

@@ -0,0 +1,33 @@
## If for any reason, you'd like to test winget install scenario, you can follow this doc:
### Powertoys winget manifest definition:
[winget repository](https://github.com/microsoft/winget-pkgs/tree/master/manifests/m/Microsoft/PowerToys)
### How to test a winget installation locally:
1. Get artifacts from release CI pipeline Pipelines - Runs for PowerToys Signed YAML Release Build, or you can build one yourself by execute the
'tools\build\build-installer.ps1' script
2. Get the artifact hash, this is required to define winget manifest
```powershell
cd /path/to/your/directory/contains/installer
Get-FileHash -Path ".\<Installer-name>.exe" -Algorithm SHA256
```
3. Host your installer.exe - Attention: staged github release artifacts or artifacts in release pipeline is not OK in this step
You can self-host it or you can upload to a publicly available endpoint
**How to selfhost it** (A extremely simple way):
```powershell
python -m http.server 8000
```
4. Download a version folder from wingetpkgs like: [version 0.92.1](https://github.com/microsoft/winget-pkgs/tree/master/manifests/m/Microsoft/PowerToys/0.92.1)
and you get **a folder contains 3 yml files**
>note: Do not put any files other than these three in this folder
5. Modify the yml files based on your version and the self hosted artifact link, and modify the sha256 hash for the installer you'd like to use
6. Start winget install:
```powershell
#execute as admin
winget settings --enable LocalManifestFiles
winget install --manifest "<folder_path_of_manifest_files>" --architecture x64 --scope user
```

View File

@@ -1,583 +1,209 @@
# editorconfig: http://editorconfig.org/
# Help developers standardize spaces, tabs, encoding, end-line characters across editors
# Rules in this file were initially inferred by Visual Studio IntelliCode from the Template Studio codebase.
# You can modify the rules from these initially generated values to suit your own policies.
# You can learn more about editorconfig here: https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference.
# top-most .editorconfig file
root = true
# defaults for all files
[*]
charset = utf-8
end_of_line = crlf
tab_width = 4
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.cs]
file_header_template = Copyright (c) Microsoft Corporation\r\nThe Microsoft Corporation licenses this file to you under the MIT license.\r\nSee the LICENSE file in the project root for more information.
# markdown, diff overrides
# two trailing spaces are required for <br/> and hard line-breaks in markdown files
# see: (https://daringfireball.net/projects/markdown/syntax#p) and (http://spec.commonmark.org/0.27/#hard-line-break)
[*.{md,diff}]
trim_trailing_whitespace = false
#Core editorconfig formatting - indentation
[*.{md,xml,xsd,gprops,man,natvis}]
indent_size = 2
#use soft tabs (spaces) for indentation
indent_style = space
# manifest validation tool requires BOM
[*.man]
charset = utf-8-bom
#Formatting - new line options
# XML-based MSBuild and Visual Studio files
[*.{props,targets,settings,*proj,vcxitems,filters,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2
# Exceptions to the above *proj wildcard
[*.vdproj]
indent_size = 4
# Visual Studio uses hard tabs for SLN files, so don't fight it
[*.sln]
indent_style = tab
# Visual Studio removes the last empty line, so don't fight it
[*.{vcxproj}]
insert_final_newline = false
# YAML overrides
[*.{yml,yaml}]
indent_size = 2
# package.json overrides
# Updating package.json with NPM will revert indentation to 2 spaces so to
# reduce churn, let's align to NPM and specify indent size 2
[package.json]
indent_size = 2
# HTML5 content (*.html, *.js) included in the AppX package should properly encoded with the UTF-8 byte order mark (BOM) as this is a Store requirement.
[*.{html,js,css}]
charset = utf-8-bom
# JSON formats
[{*.{json,testlist,testpasses,testenv,pluginlist},testmd.definition}]
indent_size = 2
[*.{rc,rc2}]
trim_trailing_whitespace = true
insert_final_newline = true
[*.{c,w}]
trim_trailing_whitespace = true
insert_final_newline = true
[*.{c++,cc,cpp,cppm,cxx,h,h++,hh,hpp,hxx,inl,ipp,ixx,tlh,tli,idl}]
trim_trailing_whitespace = true
insert_final_newline = true
cpp_indent_braces = false
cpp_indent_multi_line_relative_to = innermost_parenthesis
cpp_indent_within_parentheses = indent
cpp_indent_preserve_within_parentheses = true
cpp_indent_case_contents = true
cpp_indent_case_labels = false
cpp_indent_case_contents_when_block = false
cpp_indent_lambda_braces_when_parameter = false
cpp_indent_goto_labels = one_left
cpp_indent_preprocessor = leftmost_column
cpp_indent_access_specifiers = false
cpp_indent_namespace_contents = true
cpp_indent_preserve_comments = false
cpp_new_line_before_open_brace_namespace = ignore
cpp_new_line_before_open_brace_type = ignore
cpp_new_line_before_open_brace_function = new_line
cpp_new_line_before_open_brace_block = new_line
cpp_new_line_before_open_brace_lambda = new_line
cpp_new_line_scope_braces_on_separate_lines = true
cpp_new_line_close_brace_same_line_empty_type = false
cpp_new_line_close_brace_same_line_empty_function = false
cpp_new_line_before_catch = true
cpp_new_line_before_else = true
cpp_new_line_before_while_in_do_while = true
cpp_space_before_function_open_parenthesis = remove
cpp_space_within_parameter_list_parentheses = false
cpp_space_between_empty_parameter_list_parentheses = false
cpp_space_after_keywords_in_control_flow_statements = true
cpp_space_within_control_flow_statement_parentheses = false
cpp_space_before_lambda_open_parenthesis = false
cpp_space_within_cast_parentheses = false
cpp_space_after_cast_close_parenthesis = false
cpp_space_within_expression_parentheses = false
cpp_space_before_block_open_brace = true
cpp_space_between_empty_braces = false
cpp_space_before_initializer_list_open_brace = false
cpp_space_within_initializer_list_braces = true
cpp_space_preserve_in_initializer_list = true
cpp_space_before_open_square_bracket = false
cpp_space_within_square_brackets = false
cpp_space_before_empty_square_brackets = false
cpp_space_between_empty_square_brackets = false
cpp_space_group_square_brackets = true
cpp_space_within_lambda_brackets = false
cpp_space_between_empty_lambda_brackets = false
cpp_space_before_comma = false
cpp_space_after_comma = true
cpp_space_remove_around_member_operators = true
cpp_space_before_inheritance_colon = true
cpp_space_before_constructor_colon = true
cpp_space_remove_before_semicolon = true
cpp_space_after_semicolon = true
cpp_space_remove_around_unary_operator = true
cpp_space_around_binary_operator = insert
cpp_space_around_assignment_operator = insert
cpp_space_pointer_reference_alignment = left
cpp_space_around_ternary_operator = insert
cpp_wrap_preserve_blocks = one_liners
# C# overrides
# Rules explanation: https://kent-boogaart.com/blog/editorconfig-reference-for-c-developers
[*.cs]
# 'using' directive preferences
csharp_using_directive_placement = outside_namespace:silent
# Indent settings
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_switch_labels = true
csharp_indent_case_contents_when_block = false
csharp_indent_labels = one_less_than_current
# Newline settings
csharp_new_line_before_catch = true
#place else statements on a new line
csharp_new_line_before_else = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_before_members_in_object_initializers = true
#require braces to be on a new line for lambdas, methods, control_blocks, types, properties, and accessors (also known as "Allman" style)
csharp_new_line_before_open_brace = all
csharp_new_line_between_query_expression_clauses = true
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent
csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent
csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent
csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent
# Braces settings
csharp_prefer_braces = when_multiline:suggestion
csharp_prefer_simple_default_expression = true:suggestion
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = false
#Formatting - organize using options
# Space settings
csharp_space_after_cast = false
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_after_comma = true
csharp_space_after_dot = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_after_semicolon_in_for_statement = true
csharp_space_around_binary_operators = before_and_after
csharp_space_around_declaration_statements = do_not_ignore
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_before_comma = false
csharp_space_before_dot = false
csharp_space_before_open_square_brackets = false
csharp_space_before_semicolon_in_for_statement = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_parentheses = false
csharp_space_between_square_brackets = false
# Code-block preferences
csharp_prefer_simple_using_statement = true:silent
csharp_style_namespace_declarations = file_scoped:silent
csharp_style_prefer_method_group_conversion = true:silent
csharp_style_prefer_primary_constructors = true:silent
csharp_style_prefer_top_level_statements = false:silent
# Expression-level preferences
csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_style_implicit_object_creation_when_type_is_apparent = true:silent
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_prefer_index_operator = true:suggestion
csharp_style_prefer_local_over_anonymous_function = true:suggestion
csharp_style_prefer_null_check_over_type_check = true:suggestion
csharp_style_prefer_range_operator = true:silent
csharp_style_prefer_tuple_swap = true:suggestion
csharp_style_prefer_utf8_string_literals = true:suggestion
csharp_style_unused_value_assignment_preference = discard_variable:silent
csharp_style_unused_value_expression_statement_preference = discard_variable:silent
# Suggest more modern language features when available
csharp_style_conditional_delegate_call = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_prefer_extended_property_pattern = true:suggestion
csharp_style_prefer_not_pattern = true:suggestion
csharp_style_prefer_pattern_matching = true:silent
csharp_style_prefer_switch_expression = true:suggestion
csharp_prefer_static_anonymous_function = true:suggestion
# Prefer property-like constructs to have an expression-body
csharp_style_expression_bodied_accessors = when_on_single_line:suggestion
csharp_style_expression_bodied_indexers = when_on_single_line:suggestion
csharp_style_expression_bodied_properties = when_on_single_line:suggestion
csharp_style_expression_bodied_lambdas = when_on_single_line:silent
csharp_style_expression_bodied_constructors = when_on_single_line:silent
csharp_style_expression_bodied_local_functions = false:silent
csharp_style_expression_bodied_methods = when_on_single_line:silent
csharp_style_expression_bodied_operators = when_on_single_line:silent
# Don't suggest "var" when type is apparent, as "new()" is better
csharp_style_var_when_type_is_apparent = false:silent
csharp_style_var_elsewhere = false:silent
csharp_style_var_for_built_in_types = false:silent
# Modifier preferences
csharp_prefer_static_local_function = true:suggestion
csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async
csharp_style_prefer_readonly_struct = true:suggestion
csharp_style_prefer_readonly_struct_member = true:suggestion
### dotnet ###
# Sort using directives with System.* appearing first
#sort System.* using directives alphabetically, and place them before other usings
dotnet_sort_system_directives_first = true
# Suggest more modern language features when available
dotnet_style_coalesce_expression = true:silent
dotnet_style_collection_initializer = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_object_initializer = true:suggestion
#Formatting - spacing options
# Use language keywords instead of framework type names for type references
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
#require NO space between a cast and the value
csharp_space_after_cast = false
#require a space before the colon for bases or interfaces in a type declaration
csharp_space_after_colon_in_inheritance_clause = true
#require a space after a keyword in a control flow statement such as a for loop
csharp_space_after_keywords_in_control_flow_statements = true
#require a space before the colon for bases or interfaces in a type declaration
csharp_space_before_colon_in_inheritance_clause = true
#remove space within empty argument list parentheses
csharp_space_between_method_call_empty_parameter_list_parentheses = false
#remove space between method call name and opening parenthesis
csharp_space_between_method_call_name_and_opening_parenthesis = false
#do not place space characters after the opening parenthesis and before the closing parenthesis of a method call
csharp_space_between_method_call_parameter_list_parentheses = false
#remove space within empty parameter list parentheses for a method declaration
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
#place a space character after the opening parenthesis and before the closing parenthesis of a method declaration parameter list.
csharp_space_between_method_declaration_parameter_list_parentheses = false
#Formatting - wrapping options
#leave code block on separate lines
csharp_preserve_single_line_blocks = true
#Style - Code block preferences
#prefer curly braces even for one line of code
csharp_prefer_braces = true:suggestion
#Style - expression bodied member options
#prefer expression bodies for accessors
csharp_style_expression_bodied_accessors = true:warning
#prefer block bodies for constructors
csharp_style_expression_bodied_constructors = false:suggestion
#prefer expression bodies for methods
csharp_style_expression_bodied_methods = when_on_single_line:silent
#prefer expression-bodied members for properties
csharp_style_expression_bodied_properties = true:warning
#Style - expression level options
#prefer out variables to be declared before the method call
csharp_style_inlined_variable_declaration = false:suggestion
#prefer the language keyword for member access expressions, instead of the type name, for types that have a keyword to represent them
dotnet_style_predefined_type_for_member_access = true:suggestion
# Other style
#Style - Expression-level preferences
#prefer default over default(T)
csharp_prefer_simple_default_expression = true:suggestion
#prefer objects to be initialized using object initializers when possible
dotnet_style_object_initializer = true:suggestion
#Style - implicit and explicit types
#prefer var over explicit type in all cases, unless overridden by another code style rule
csharp_style_var_elsewhere = true:suggestion
#prefer var is used to declare variables with built-in system types such as int
csharp_style_var_for_built_in_types = true:suggestion
#prefer var when the type is already mentioned on the right-hand side of a declaration expression
csharp_style_var_when_type_is_apparent = true:suggestion
#Style - language keyword and framework type options
#prefer the language keyword for local variables, method parameters, and class members, instead of the type name, for types that have a keyword to represent them
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
#Style - Language rules
csharp_style_implicit_object_creation_when_type_is_apparent = true:warning
csharp_style_var_for_built_in_types = true:warning
#Style - modifier options
#prefer accessibility modifiers to be declared except for public interface members. This will currently not differ from always and will act as future proofing for if C# adds default interface methods.
dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggestion
#Style - Modifier preferences
#when this rule is set to a list of modifiers, prefer the specified ordering.
csharp_preferred_modifier_order = public,private,protected,internal,static,async,readonly,override,sealed,abstract,virtual:warning
dotnet_style_readonly_field = true:warning
#Style - Pattern matching
#prefer pattern matching instead of is expression with type casts
csharp_style_pattern_matching_over_as_with_null_check = true:warning
#Style - qualification options
#prefer events not to be prefaced with this. or Me. in Visual Basic
dotnet_style_qualification_for_event = false:suggestion
#prefer fields not to be prefaced with this. or Me. in Visual Basic
dotnet_style_qualification_for_field = false:suggestion
#prefer methods not to be prefaced with this. or Me. in Visual Basic
dotnet_style_qualification_for_method = false:suggestion
#prefer properties not to be prefaced with this. or Me. in Visual Basic
dotnet_style_qualification_for_property = false:suggestion
csharp_indent_labels = one_less_than_current
csharp_using_directive_placement = outside_namespace:silent
csharp_prefer_simple_using_statement = true:warning
csharp_style_namespace_declarations = file_scoped:warning
csharp_style_expression_bodied_operators = false:silent
csharp_style_expression_bodied_indexers = true:silent
csharp_style_expression_bodied_lambdas = true:silent
csharp_style_expression_bodied_local_functions = false:silent
[*.{cs,vb}]
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent
dotnet_style_prefer_auto_properties = false:silent
tab_width = 4
indent_size = 4
end_of_line = crlf
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
dotnet_style_prefer_auto_properties = true:silent
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_collection_expression = never
dotnet_style_prefer_simplified_interpolation = true:suggestion
dotnet_style_namespace_match_folder = true:silent
dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggestion
dotnet_style_allow_multiple_blank_lines_experimental = false:suggestion
dotnet_style_allow_statement_immediately_after_block_experimental = true:silent
dotnet_code_quality_unused_parameters = all:suggestion
[*.{cs,vb}]
# Field preferences
dotnet_style_readonly_field = true:suggestion
# Suppression preferences
dotnet_remove_unnecessary_suppression_exclusions = none
# Avoid "this."
dotnet_style_qualification_for_event = false:silent
dotnet_style_qualification_for_field = false:silent
dotnet_style_qualification_for_method = false:silent
dotnet_style_qualification_for_property = false:silent
# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
#Style - Unnecessary code rules
csharp_style_unused_value_assignment_preference = discard_variable:warning
#### Naming styles ####
# Naming rules
dotnet_naming_rule.const_variables_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.const_variables_should_be_pascal_case.symbols = const_variables
dotnet_naming_rule.const_variables_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_rule.static_readonly_field_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.static_readonly_field_should_be_pascal_case.symbols = static_readonly_field
dotnet_naming_rule.static_readonly_field_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.fields__locals__params_should_be_camelcase.severity = suggestion
dotnet_naming_rule.fields__locals__params_should_be_camelcase.symbols = fields__locals__params
dotnet_naming_rule.fields__locals__params_should_be_camelcase.style = camelcase
dotnet_naming_rule.type_parameter_should_be_type_parameter.severity = suggestion
dotnet_naming_rule.type_parameter_should_be_type_parameter.symbols = type_parameter
dotnet_naming_rule.type_parameter_should_be_type_parameter.style = type_parameter
dotnet_naming_rule.all_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.all_should_be_pascal_case.symbols = all
dotnet_naming_rule.all_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
# Symbol specifications
dotnet_naming_symbols.fields__locals__params.applicable_kinds = field, parameter, local
dotnet_naming_symbols.fields__locals__params.applicable_accessibilities = *
dotnet_naming_symbols.fields__locals__params.required_modifiers =
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.type_parameter.applicable_kinds = type_parameter
dotnet_naming_symbols.type_parameter.applicable_accessibilities = *
dotnet_naming_symbols.type_parameter.required_modifiers =
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_symbols.const_variables.applicable_kinds = field, local
dotnet_naming_symbols.const_variables.applicable_accessibilities = *
dotnet_naming_symbols.const_variables.required_modifiers = const
dotnet_naming_symbols.all.applicable_kinds = *
dotnet_naming_symbols.all.applicable_accessibilities = *
dotnet_naming_symbols.all.required_modifiers =
dotnet_naming_symbols.static_readonly_field.applicable_kinds = field
dotnet_naming_symbols.static_readonly_field.applicable_accessibilities = *
dotnet_naming_symbols.static_readonly_field.required_modifiers = readonly, static
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
# Naming styles
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_naming_style.camelcase.required_prefix =
dotnet_naming_style.camelcase.required_suffix =
dotnet_naming_style.camelcase.word_separator =
dotnet_naming_style.camelcase.capitalization = camel_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_compound_assignment = true:warning
dotnet_style_prefer_simplified_interpolation = true:suggestion
dotnet_naming_style.type_parameter.required_prefix = T
dotnet_naming_style.type_parameter.required_suffix =
dotnet_naming_style.type_parameter.word_separator =
dotnet_naming_style.type_parameter.capitalization = pascal_case
### Dotnet diagnostics ###
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/categories
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/configuration-options#severity-level
# The rule for assigning severity is:
# error (build break) - this is always incorrect code; e.g., recursively assigning a property to itself
# warning (build break) - this is possibly correct, but too error-prone to be used without calling it out; e.g., testing for NaN correctly, or hidden perf costs
# suggestion (IDE squiggles and IDE message) - this violates (or is very very very likely to violate) a CoreGuideline
# silent (no squiggles or message, but refactoring may be avaliable) - this violates a CoreGuideline, but with a non-neglagable but not large false-positive rate
# none (no user notification) - this violates a CoreGuideline, but with high false-positive rate; is inconsistent with the CoreGuidelines; or is otherwise incorrect
# Default diagnostics
# https://github.com/dotnet/roslyn-analyzers/blob/main/src/NetAnalyzers/Core/AnalyzerReleases.Shipped.md
# Note that in this list "info" = suggestion, "hidden" = silent, and "disabled" = none in terms of the severity field:
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/configuration-options
# We can only enable the "Default" set of diagnostics automatically and not the "Recommended" set,
# as we'd get warnings for non-breaking issues, so we have to manually adjust a bunch of severities.
# "hidden" issues still may appear in IDE refactorings, so a rule must be disabled with "none" explicitly if not needed.
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/design-warnings
dotnet_diagnostic.CA1001.severity = warning
dotnet_diagnostic.CA1003.severity = suggestion
dotnet_diagnostic.CA1005.severity = suggestion
dotnet_diagnostic.CA1008.severity = suggestion
dotnet_diagnostic.CA1010.severity = suggestion
dotnet_diagnostic.CA1012.severity = warning
dotnet_diagnostic.CA1016.severity = none
dotnet_diagnostic.CA1019.severity = suggestion
dotnet_diagnostic.CA1024.severity = suggestion
dotnet_diagnostic.CA1027.severity = suggestion
dotnet_diagnostic.CA1028.severity = suggestion
dotnet_diagnostic.CA1030.severity = suggestion
dotnet_diagnostic.CA1032.severity = suggestion
dotnet_diagnostic.CA1033.severity = suggestion
dotnet_diagnostic.CA1034.severity = silent
dotnet_diagnostic.CA1036.severity = suggestion
dotnet_diagnostic.CA1040.severity = suggestion
dotnet_diagnostic.CA1052.severity = suggestion
dotnet_diagnostic.CA1054.severity = suggestion
dotnet_diagnostic.CA1055.severity = suggestion
dotnet_diagnostic.CA1056.severity = suggestion
dotnet_diagnostic.CA1058.severity = warning
dotnet_diagnostic.CA1060.severity = silent
dotnet_diagnostic.CA1063.severity = suggestion
dotnet_diagnostic.CA1064.severity = suggestion
dotnet_diagnostic.CA1065.severity = suggestion
dotnet_diagnostic.CA1066.severity = suggestion
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/globalization-warnings
dotnet_diagnostic.CA1303.severity = suggestion
dotnet_diagnostic.CA1307.severity = suggestion
dotnet_diagnostic.CA1308.severity = suggestion
dotnet_diagnostic.CA1309.severity = suggestion
dotnet_diagnostic.CA1310.severity = suggestion
dotnet_diagnostic.CA1311.severity = suggestion
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/interoperability-warnings
dotnet_diagnostic.CA1419.severity = warning
dotnet_diagnostic.CA1421.severity = warning
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/maintainability-warnings
dotnet_diagnostic.CA1501.severity = suggestion
dotnet_diagnostic.CA1502.severity = suggestion
dotnet_diagnostic.CA1505.severity = suggestion
dotnet_diagnostic.CA1506.severity = suggestion
dotnet_diagnostic.CA1508.severity = suggestion
dotnet_diagnostic.CA1509.severity = suggestion
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/naming-warnings
dotnet_diagnostic.CA1700.severity = suggestion
dotnet_diagnostic.CA1707.severity = suggestion
dotnet_diagnostic.CA1710.severity = suggestion
dotnet_diagnostic.CA1711.severity = suggestion
dotnet_diagnostic.CA1712.severity = suggestion
dotnet_diagnostic.CA1713.severity = suggestion
dotnet_diagnostic.CA1715.severity = suggestion
dotnet_diagnostic.CA1716.severity = warning
dotnet_diagnostic.CA1721.severity = suggestion
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/performance-warnings
dotnet_diagnostic.CA1802.severity = suggestion
dotnet_diagnostic.CA1805.severity = suggestion
dotnet_diagnostic.CA1806.severity = warning
# Flag any accidental use of static Equals without checking the return value, scenarios like "StringAssert.Equals" are falling through to a method
# that doesn't do what the caller expects.
dotnet_code_quality.CA1806.additional_use_results_methods = Equals
dotnet_diagnostic.CA1810.severity = suggestion
dotnet_diagnostic.CA1812.severity = suggestion
dotnet_diagnostic.CA1813.severity = suggestion
dotnet_diagnostic.CA1815.severity = suggestion
dotnet_diagnostic.CA1820.severity = suggestion
dotnet_diagnostic.CA1823.severity = suggestion
dotnet_diagnostic.CA1838.severity = suggestion
dotnet_diagnostic.CA1849.severity = suggestion
dotnet_diagnostic.CA1851.severity = suggestion
dotnet_diagnostic.CA1852.severity = suggestion
dotnet_diagnostic.CA1867.severity = suggestion
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/reliability-warnings
dotnet_diagnostic.CA2000.severity = warning
dotnet_diagnostic.CA2002.severity = warning
dotnet_diagnostic.CA2008.severity = warning
dotnet_diagnostic.CA2011.severity = warning
dotnet_diagnostic.CA2012.severity = warning
dotnet_diagnostic.CA2019.severity = warning
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/security-warnings
dotnet_diagnostic.CA2100.severity = warning
dotnet_diagnostic.CA2119.severity = warning
dotnet_diagnostic.CA2153.severity = warning
dotnet_diagnostic.CA2300.severity = warning
dotnet_diagnostic.CA2301.severity = warning
dotnet_diagnostic.CA2302.severity = warning
dotnet_diagnostic.CA2305.severity = warning
dotnet_diagnostic.CA2310.severity = warning
dotnet_diagnostic.CA2311.severity = warning
dotnet_diagnostic.CA2312.severity = warning
dotnet_diagnostic.CA2315.severity = warning
dotnet_diagnostic.CA2321.severity = warning
dotnet_diagnostic.CA2322.severity = warning
dotnet_diagnostic.CA2326.severity = warning
dotnet_diagnostic.CA2327.severity = warning
dotnet_diagnostic.CA2328.severity = warning
dotnet_diagnostic.CA2329.severity = warning
dotnet_diagnostic.CA2330.severity = warning
dotnet_diagnostic.CA2350.severity = warning
dotnet_diagnostic.CA2351.severity = warning
dotnet_diagnostic.CA2352.severity = warning
dotnet_diagnostic.CA2353.severity = warning
dotnet_diagnostic.CA2354.severity = warning
dotnet_diagnostic.CA2355.severity = warning
dotnet_diagnostic.CA2356.severity = warning
dotnet_diagnostic.CA2361.severity = warning
dotnet_diagnostic.CA2362.severity = warning
dotnet_diagnostic.CA3001.severity = warning
dotnet_diagnostic.CA3002.severity = warning
dotnet_diagnostic.CA3003.severity = warning
dotnet_diagnostic.CA3004.severity = warning
dotnet_diagnostic.CA3005.severity = warning
dotnet_diagnostic.CA3006.severity = warning
dotnet_diagnostic.CA3007.severity = warning
dotnet_diagnostic.CA3008.severity = warning
dotnet_diagnostic.CA3009.severity = warning
dotnet_diagnostic.CA3010.severity = warning
dotnet_diagnostic.CA3011.severity = warning
dotnet_diagnostic.CA3012.severity = warning
dotnet_diagnostic.CA3061.severity = warning
dotnet_diagnostic.CA3075.severity = warning
dotnet_diagnostic.CA3076.severity = warning
dotnet_diagnostic.CA3077.severity = warning
dotnet_diagnostic.CA3147.severity = warning
dotnet_diagnostic.CA5350.severity = warning
dotnet_diagnostic.CA5351.severity = warning
dotnet_diagnostic.CA5358.severity = warning
dotnet_diagnostic.CA5359.severity = warning
dotnet_diagnostic.CA5360.severity = warning
dotnet_diagnostic.CA5361.severity = warning
dotnet_diagnostic.CA5362.severity = warning
dotnet_diagnostic.CA5363.severity = warning
dotnet_diagnostic.CA5364.severity = warning
dotnet_diagnostic.CA5365.severity = warning
dotnet_diagnostic.CA5366.severity = warning
dotnet_diagnostic.CA5367.severity = warning
dotnet_diagnostic.CA5368.severity = warning
dotnet_diagnostic.CA5369.severity = warning
dotnet_diagnostic.CA5370.severity = warning
dotnet_diagnostic.CA5371.severity = warning
dotnet_diagnostic.CA5372.severity = warning
dotnet_diagnostic.CA5373.severity = warning
dotnet_diagnostic.CA5374.severity = warning
dotnet_diagnostic.CA5375.severity = warning
dotnet_diagnostic.CA5376.severity = warning
dotnet_diagnostic.CA5377.severity = warning
dotnet_diagnostic.CA5378.severity = warning
dotnet_diagnostic.CA5379.severity = warning
dotnet_diagnostic.CA5380.severity = warning
dotnet_diagnostic.CA5381.severity = warning
dotnet_diagnostic.CA5382.severity = warning
dotnet_diagnostic.CA5383.severity = warning
dotnet_diagnostic.CA5384.severity = warning
dotnet_diagnostic.CA5385.severity = warning
dotnet_diagnostic.CA5386.severity = warning
dotnet_diagnostic.CA5387.severity = warning
dotnet_diagnostic.CA5388.severity = warning
dotnet_diagnostic.CA5389.severity = warning
dotnet_diagnostic.CA5390.severity = warning
dotnet_diagnostic.CA5391.severity = warning
dotnet_diagnostic.CA5392.severity = silent
dotnet_diagnostic.CA5393.severity = warning
dotnet_diagnostic.CA5394.severity = warning
dotnet_diagnostic.CA5395.severity = warning
dotnet_diagnostic.CA5396.severity = warning
dotnet_diagnostic.CA5397.severity = warning
dotnet_diagnostic.CA5398.severity = warning
dotnet_diagnostic.CA5399.severity = warning
dotnet_diagnostic.CA5400.severity = warning
dotnet_diagnostic.CA5401.severity = warning
dotnet_diagnostic.CA5402.severity = warning
dotnet_diagnostic.CA5403.severity = warning
dotnet_diagnostic.CA5404.severity = warning
dotnet_diagnostic.CA5405.severity = warning
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/usage-warnings
dotnet_diagnostic.CA2201.severity = warning
dotnet_diagnostic.CA2207.severity = suggestion
dotnet_diagnostic.CA2211.severity = warning
dotnet_diagnostic.CA2213.severity = warning
dotnet_diagnostic.CA2215.severity = suggestion
dotnet_diagnostic.CA2217.severity = warning
dotnet_diagnostic.CA2219.severity = warning
dotnet_diagnostic.CA2226.severity = suggestion
dotnet_diagnostic.CA2234.severity = suggestion
dotnet_diagnostic.CA2242.severity = warning
dotnet_diagnostic.CA2243.severity = suggestion
dotnet_diagnostic.CA2245.severity = warning
dotnet_diagnostic.CA2251.severity = suggestion
# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/
# required by CELA
dotnet_diagnostic.IDE0073.severity = suggestion
# Diagnostic configuration
# CS8305: Type is for evaluation purposes only and is subject to change or removal in future updates.
dotnet_diagnostic.CS8305.severity = suggestion

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -13,10 +13,10 @@ public static partial class NativeEventWaiter
{
public static void WaitForEventLoop(string eventName, Action callback)
{
DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread();
Thread t = new Thread(() =>
var dispatcherQueue = DispatcherQueue.GetForCurrentThread();
var t = new Thread(() =>
{
EventWaitHandle eventHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName);
var eventHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName);
while (true)
{
if (eventHandle.WaitOne())
@@ -24,10 +24,9 @@ public static partial class NativeEventWaiter
dispatcherQueue.TryEnqueue(() => callback());
}
}
})
{
IsBackground = true,
};
});
t.IsBackground = true;
t.Start();
}
}

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -55,7 +55,7 @@ public interface IExtensionWrapper
/// <summary>
/// Gets the Unique Id for the extension
/// </summary>
string ExtensionUniqueId { get; }
public string ExtensionUniqueId { get; }
/// <summary>
/// Checks whether we have a reference to the extension process and we are able to call methods on the interface.

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -79,7 +79,7 @@ public abstract partial class AppExtensionHost : IExtensionHost
{
try
{
StatusMessageViewModel? vm = StatusMessages.Where(messageVM => messageVM.Model.Unsafe == message).FirstOrDefault();
var vm = StatusMessages.Where(messageVM => messageVM.Model.Unsafe == message).FirstOrDefault();
if (vm != null)
{
StatusMessages.Remove(vm);
@@ -96,7 +96,7 @@ public abstract partial class AppExtensionHost : IExtensionHost
public void ProcessLogMessage(ILogMessage message)
{
LogMessageViewModel vm = new LogMessageViewModel(message, _globalLogPageContext);
var vm = new LogMessageViewModel(message, _globalLogPageContext);
vm.SafeInitializePropertiesSynchronous();
Task.Factory.StartNew(
@@ -112,7 +112,7 @@ public abstract partial class AppExtensionHost : IExtensionHost
public void ProcessStatusMessage(IStatusMessage message, StatusContext context)
{
// If this message is already in the list of messages, just bring it to the top
StatusMessageViewModel? oldVm = StatusMessages.Where(messageVM => messageVM.Model.Unsafe == message).FirstOrDefault();
var oldVm = StatusMessages.Where(messageVM => messageVM.Model.Unsafe == message).FirstOrDefault();
if (oldVm != null)
{
Task.Factory.StartNew(
@@ -127,7 +127,7 @@ public abstract partial class AppExtensionHost : IExtensionHost
return;
}
StatusMessageViewModel vm = new StatusMessageViewModel(message, new(_globalLogPageContext));
var vm = new StatusMessageViewModel(message, new(_globalLogPageContext));
vm.SafeInitializePropertiesSynchronous();
Task.Factory.StartNew(

View File

@@ -2,6 +2,7 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.CmdPal.Core.ViewModels.Messages;
@@ -125,12 +126,12 @@ public partial class CommandBarViewModel : ObservableObject,
public ContextKeybindingResult CheckKeybinding(bool ctrl, bool alt, bool shift, bool win, VirtualKey key)
{
Dictionary<CommandPalette.Extensions.KeyChord, CommandContextItemViewModel>? keybindings = SelectedItem?.Keybindings();
var keybindings = SelectedItem?.Keybindings();
if (keybindings != null)
{
// Does the pressed key match any of the keybindings?
CommandPalette.Extensions.KeyChord pressedKeyChord = KeyChordHelpers.FromModifiers(ctrl, alt, shift, win, key, 0);
if (keybindings.TryGetValue(pressedKeyChord, out CommandContextItemViewModel? matchedItem))
var pressedKeyChord = KeyChordHelpers.FromModifiers(ctrl, alt, shift, win, key, 0);
if (keybindings.TryGetValue(pressedKeyChord, out var matchedItem))
{
return matchedItem != null ? PerformCommand(matchedItem) : ContextKeybindingResult.Unhandled;
}

View File

@@ -28,7 +28,7 @@ public partial class CommandContextItemViewModel(ICommandContextItem contextItem
base.InitializeProperties();
ICommandContextItem? contextItem = Model.Unsafe;
var contextItem = Model.Unsafe;
if (contextItem == null)
{
return; // throw?

View File

@@ -97,7 +97,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
return;
}
ICommandItem? model = _commandItemModel.Unsafe;
var model = _commandItemModel.Unsafe;
if (model == null)
{
return;
@@ -125,7 +125,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
FastInitializeProperties();
}
ICommandItem? model = _commandItemModel.Unsafe;
var model = _commandItemModel.Unsafe;
if (model == null)
{
return;
@@ -133,7 +133,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
Command.InitializeProperties();
IIconInfo listIcon = model.Icon;
var listIcon = model.Icon;
if (listIcon != null)
{
_listItemIcon = new(listIcon);
@@ -169,25 +169,25 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
InitializeProperties();
}
ICommandItem? model = _commandItemModel.Unsafe;
var model = _commandItemModel.Unsafe;
if (model == null)
{
return;
}
IContextItem[] more = model.MoreCommands;
var more = model.MoreCommands;
if (more != null)
{
MoreCommands = more
.Select<IContextItem, IContextItemViewModel>(item =>
.Select(item =>
{
if (item is ICommandContextItem contextItem)
{
return new CommandContextItemViewModel(contextItem, PageContext);
return new CommandContextItemViewModel(contextItem, PageContext) as IContextItemViewModel;
}
else
{
return new SeparatorContextItemViewModel();
return new SeparatorContextItemViewModel() as IContextItemViewModel;
}
})
.ToList();
@@ -297,7 +297,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
protected virtual void FetchProperty(string propertyName)
{
ICommandItem? model = this._commandItemModel.Unsafe;
var model = this._commandItemModel.Unsafe;
if (model == null)
{
return; // throw?
@@ -332,19 +332,19 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
break;
case nameof(model.MoreCommands):
IContextItem[] more = model.MoreCommands;
var more = model.MoreCommands;
if (more != null)
{
List<IContextItemViewModel> newContextMenu = more
.Select<IContextItem, IContextItemViewModel>(item =>
var newContextMenu = more
.Select(item =>
{
if (item is CommandContextItem contextItem)
{
return new CommandContextItemViewModel(contextItem, PageContext);
return new CommandContextItemViewModel(contextItem, PageContext) as IContextItemViewModel;
}
else
{
return new SeparatorContextItemViewModel();
return new SeparatorContextItemViewModel() as IContextItemViewModel;
}
})
.ToList();
@@ -381,7 +381,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
private void Command_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
string? propertyName = e.PropertyName;
var propertyName = e.PropertyName;
switch (propertyName)
{
case nameof(Command.Name):
@@ -415,7 +415,7 @@ public partial class CommandItemViewModel : ExtensionObjectViewModel, ICommandBa
Command.PropertyChanged -= Command_PropertyChanged;
Command.SafeCleanup();
ICommandItem? model = _commandItemModel.Unsafe;
var model = _commandItemModel.Unsafe;
if (model != null)
{
model.PropChanged -= Model_PropChanged;

View File

@@ -43,7 +43,7 @@ public partial class CommandViewModel : ExtensionObjectViewModel
return;
}
ICommand? model = Model.Unsafe;
var model = Model.Unsafe;
if (model == null)
{
return;
@@ -66,13 +66,13 @@ public partial class CommandViewModel : ExtensionObjectViewModel
FastInitializeProperties();
}
ICommand? model = Model.Unsafe;
var model = Model.Unsafe;
if (model == null)
{
return;
}
IIconInfo ico = model.Icon;
var ico = model.Icon;
if (ico != null)
{
Icon = new(ico);
@@ -97,7 +97,7 @@ public partial class CommandViewModel : ExtensionObjectViewModel
protected void FetchProperty(string propertyName)
{
ICommand? model = Model.Unsafe;
var model = Model.Unsafe;
if (model == null)
{
return; // throw?
@@ -109,7 +109,7 @@ public partial class CommandViewModel : ExtensionObjectViewModel
Name = model.Name;
break;
case nameof(Icon):
IIconInfo iconInfo = model.Icon;
var iconInfo = model.Icon;
Icon = new(iconInfo);
Icon.InitializeProperties();
break;
@@ -124,7 +124,7 @@ public partial class CommandViewModel : ExtensionObjectViewModel
Icon = new(null); // necessary?
ICommand? model = Model.Unsafe;
var model = Model.Unsafe;
if (model != null)
{
model.PropChanged -= Model_PropChanged;

View File

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

View File

@@ -62,11 +62,11 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
List<ContentViewModel> newContent = [];
try
{
IContent[] newItems = _model.Unsafe!.GetContent();
var newItems = _model.Unsafe!.GetContent();
foreach (IContent? item in newItems)
foreach (var item in newItems)
{
ContentViewModel? viewModel = ViewModelFromContent(item, PageContext);
var viewModel = ViewModelFromContent(item, PageContext);
if (viewModel != null)
{
viewModel.InitializeProperties();
@@ -80,7 +80,7 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
throw;
}
bool oneContent = newContent.Count == 1;
var oneContent = newContent.Count == 1;
newContent.ForEach(c => c.OnlyControlOnPage = oneContent);
// Now, back to a UI thread to update the observable collection
@@ -103,7 +103,7 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
{
base.InitializeProperties();
IContentPage? model = _model.Unsafe;
var model = _model.Unsafe;
if (model == null)
{
return; // throw?
@@ -132,7 +132,7 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
contextItem.InitializeProperties();
});
IDetails extensionDetails = model.Details;
var extensionDetails = model.Details;
if (extensionDetails != null)
{
Details = new(extensionDetails, PageContext);
@@ -155,7 +155,7 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
{
base.FetchProperty(propertyName);
IContentPage? model = this._model.Unsafe;
var model = this._model.Unsafe;
if (model == null)
{
return; // throw?
@@ -165,10 +165,10 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
{
case nameof(Commands):
IContextItem[] more = model.Commands;
var more = model.Commands;
if (more != null)
{
List<IContextItemViewModel> newContextMenu = more
var newContextMenu = more
.ToList()
.Select(item =>
{
@@ -215,7 +215,7 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
break;
case nameof(Details):
IDetails extensionDetails = model.Details;
var extensionDetails = model.Details;
Details = extensionDetails != null ? new(extensionDetails, PageContext) : null;
UpdateDetails();
break;
@@ -277,14 +277,14 @@ public partial class ContentPageViewModel : PageViewModel, ICommandBarContext
Commands.Clear();
foreach (ContentViewModel item in Content)
foreach (var item in Content)
{
item.SafeCleanup();
}
Content.Clear();
IContentPage? model = _model.Unsafe;
var model = _model.Unsafe;
if (model != null)
{
model.ItemsChanged -= Model_ItemsChanged;

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -8,6 +8,7 @@ using CommunityToolkit.Mvvm.Messaging;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
using Microsoft.Diagnostics.Utilities;
using Windows.System;
namespace Microsoft.CmdPal.Core.ViewModels;
@@ -98,11 +99,11 @@ public partial class ContextMenuViewModel : ObservableObject,
return;
}
IEnumerable<CommandContextItemViewModel> commands = CurrentContextMenu
var commands = CurrentContextMenu
.OfType<CommandContextItemViewModel>()
.Where(c => c.ShouldBeVisible);
IEnumerable<CommandContextItemViewModel> newResults = ListHelpers.FilterList<CommandContextItemViewModel>(commands, searchText, ScoreContextCommand);
var newResults = ListHelpers.FilterList<CommandContextItemViewModel>(commands, searchText, ScoreContextCommand);
ListHelpers.InPlaceUpdateList(FilteredItems, newResults);
}
@@ -118,9 +119,9 @@ public partial class ContextMenuViewModel : ObservableObject,
return 0;
}
MatchResult nameMatch = StringMatcher.FuzzySearch(query, item.Title);
var nameMatch = StringMatcher.FuzzySearch(query, item.Title);
MatchResult descriptionMatch = StringMatcher.FuzzySearch(query, item.Subtitle);
var descriptionMatch = StringMatcher.FuzzySearch(query, item.Subtitle);
return new[] { nameMatch.Score, (descriptionMatch.Score - 4) / 2, 0 }.Max();
}
@@ -150,12 +151,12 @@ public partial class ContextMenuViewModel : ObservableObject,
public ContextKeybindingResult? CheckKeybinding(bool ctrl, bool alt, bool shift, bool win, VirtualKey key)
{
Dictionary<KeyChord, CommandContextItemViewModel> keybindings = Keybindings();
var keybindings = Keybindings();
if (keybindings != null)
{
// Does the pressed key match any of the keybindings?
KeyChord pressedKeyChord = KeyChordHelpers.FromModifiers(ctrl, alt, shift, win, key, 0);
if (keybindings.TryGetValue(pressedKeyChord, out CommandContextItemViewModel? item))
var pressedKeyChord = KeyChordHelpers.FromModifiers(ctrl, alt, shift, win, key, 0);
if (keybindings.TryGetValue(pressedKeyChord, out var item))
{
return InvokeCommand(item);
}

View File

@@ -21,7 +21,7 @@ public partial class DetailsCommandsViewModel(
public override void InitializeProperties()
{
base.InitializeProperties();
IDetailsCommands? model = _dataModel.Unsafe;
var model = _dataModel.Unsafe;
if (model == null)
{
return;
@@ -31,7 +31,7 @@ public partial class DetailsCommandsViewModel(
.Commands?
.Select(c =>
{
CommandViewModel vm = new CommandViewModel(c, PageContext);
var vm = new CommandViewModel(c, PageContext);
vm.InitializeProperties();
return vm;
})

View File

@@ -2,6 +2,9 @@
// 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.Core.ViewModels.Models;
using Microsoft.CommandPalette.Extensions;
namespace Microsoft.CmdPal.Core.ViewModels;
public abstract partial class DetailsDataViewModel(IPageContext context) : ExtensionObjectViewModel(context)

View File

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

View File

@@ -25,7 +25,7 @@ public partial class DetailsLinkViewModel(
public override void InitializeProperties()
{
base.InitializeProperties();
IDetailsLink? model = _dataModel.Unsafe;
var model = _dataModel.Unsafe;
if (model == null)
{
return;

View File

@@ -2,6 +2,7 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CmdPal.Core.ViewModels.Models;
using Microsoft.CommandPalette.Extensions;
namespace Microsoft.CmdPal.Core.ViewModels;
@@ -10,6 +11,9 @@ public partial class DetailsSeparatorViewModel(
IDetailsElement _detailsElement,
WeakReference<IPageContext> context) : DetailsElementViewModel(_detailsElement, context)
{
private readonly ExtensionObject<IDetailsSeparator> _dataModel =
new(_detailsElement.Data as IDetailsSeparator);
public override void InitializeProperties()
{
base.InitializeProperties();

View File

@@ -21,7 +21,7 @@ public partial class DetailsTagsViewModel(
public override void InitializeProperties()
{
base.InitializeProperties();
IDetailsTags? model = _dataModel.Unsafe;
var model = _dataModel.Unsafe;
if (model == null)
{
return;
@@ -31,7 +31,7 @@ public partial class DetailsTagsViewModel(
.Tags?
.Select(t =>
{
TagViewModel vm = new TagViewModel(t, PageContext);
var vm = new TagViewModel(t, PageContext);
vm.InitializeProperties();
return vm;
})

View File

@@ -25,7 +25,7 @@ public partial class DetailsViewModel(IDetails _details, WeakReference<IPageCont
public override void InitializeProperties()
{
IDetails? model = _detailsModel.Unsafe;
var model = _detailsModel.Unsafe;
if (model == null)
{
return;
@@ -40,10 +40,10 @@ public partial class DetailsViewModel(IDetails _details, WeakReference<IPageCont
UpdateProperty(nameof(Body));
UpdateProperty(nameof(HeroImage));
IDetailsElement[] meta = model.Metadata;
var meta = model.Metadata;
if (meta != null)
{
foreach (IDetailsElement? element in meta)
foreach (var element in meta)
{
DetailsElementViewModel? vm = element.Data switch
{

View File

@@ -11,20 +11,20 @@ public abstract partial class ExtensionObjectViewModel : ObservableObject
{
public WeakReference<IPageContext> PageContext { get; set; }
protected ExtensionObjectViewModel(IPageContext? context)
public ExtensionObjectViewModel(IPageContext? context)
{
IPageContext realContext = context ?? (this is IPageContext c ? c : throw new ArgumentException("You need to pass in an IErrorContext"));
var realContext = context ?? (this is IPageContext c ? c : throw new ArgumentException("You need to pass in an IErrorContext"));
PageContext = new(realContext);
}
protected ExtensionObjectViewModel(WeakReference<IPageContext> context)
public ExtensionObjectViewModel(WeakReference<IPageContext> context)
{
PageContext = context;
}
public virtual async Task InitializePropertiesAsync()
public async virtual Task InitializePropertiesAsync()
{
Task t = new Task(() =>
var t = new Task(() =>
{
SafeInitializePropertiesSynchronous();
});
@@ -53,7 +53,7 @@ public abstract partial class ExtensionObjectViewModel : ObservableObject
protected void ShowException(Exception ex, string? extensionHint = null)
{
if (PageContext.TryGetTarget(out IPageContext? pageContext))
if (PageContext.TryGetTarget(out var pageContext))
{
pageContext.ShowException(ex, extensionHint);
}
@@ -61,7 +61,7 @@ public abstract partial class ExtensionObjectViewModel : ObservableObject
protected void DoOnUiThread(Action action)
{
if (PageContext.TryGetTarget(out IPageContext? pageContext))
if (PageContext.TryGetTarget(out var pageContext))
{
Task.Factory.StartNew(
action,

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -1,7 +1,13 @@
// Copyright (c) Microsoft Corporation
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CmdPal.Core.ViewModels;
public interface IContextItemViewModel

View File

@@ -35,7 +35,7 @@ public partial class IconDataViewModel : ObservableObject, IIconData
// Unsafe, needs to be called on BG thread
public void InitializeProperties()
{
IIconData? model = _model.Unsafe;
var model = _model.Unsafe;
if (model == null)
{
return;

View File

@@ -42,7 +42,7 @@ public partial class IconInfoViewModel : ObservableObject, IIconInfo
// Unsafe, needs to be called on BG thread
public void InitializeProperties()
{
IIconInfo? model = _model.Unsafe;
var model = _model.Unsafe;
if (model == null)
{
return;

View File

@@ -39,7 +39,7 @@ public partial class ListItemViewModel(IListItem model, WeakReference<IPageConte
// This sets IsInitialized = true
base.InitializeProperties();
IListItem? li = Model.Unsafe;
var li = Model.Unsafe;
if (li == null)
{
return; // throw?
@@ -49,7 +49,7 @@ public partial class ListItemViewModel(IListItem model, WeakReference<IPageConte
TextToSuggest = li.TextToSuggest;
Section = li.Section ?? string.Empty;
IDetails extensionDetails = li.Details;
var extensionDetails = li.Details;
if (extensionDetails != null)
{
Details = new(extensionDetails, PageContext);
@@ -66,7 +66,7 @@ public partial class ListItemViewModel(IListItem model, WeakReference<IPageConte
{
base.FetchProperty(propertyName);
IListItem? model = this.Model.Unsafe;
var model = this.Model.Unsafe;
if (model == null)
{
return; // throw?
@@ -84,7 +84,7 @@ public partial class ListItemViewModel(IListItem model, WeakReference<IPageConte
this.Section = model.Section ?? string.Empty;
break;
case nameof(Details):
IDetails extensionDetails = model.Details;
var extensionDetails = model.Details;
Details = extensionDetails != null ? new(extensionDetails, PageContext) : null;
Details?.InitializeProperties();
UpdateProperty(nameof(Details));
@@ -107,9 +107,9 @@ public partial class ListItemViewModel(IListItem model, WeakReference<IPageConte
private void UpdateTags(ITag[]? newTagsFromModel)
{
List<TagViewModel> newTags = newTagsFromModel?.Select(t =>
var newTags = newTagsFromModel?.Select(t =>
{
TagViewModel vm = new TagViewModel(t, PageContext);
var vm = new TagViewModel(t, PageContext);
vm.InitializeProperties();
return vm;
})
@@ -135,7 +135,7 @@ public partial class ListItemViewModel(IListItem model, WeakReference<IPageConte
Tags?.ForEach(t => t.SafeCleanup());
Details?.SafeCleanup();
IListItem? model = Model.Unsafe;
var model = Model.Unsafe;
if (model != null)
{
// We don't need to revoke the PropChanged event handler here,

View File

@@ -134,7 +134,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
try
{
IListItem[] newItems = _model.Unsafe!.GetItems();
var newItems = _model.Unsafe!.GetItems();
// Collect all the items into new viewmodels
Collection<ListItemViewModel> newViewModels = [];
@@ -142,7 +142,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
// TODO we can probably further optimize this by also keeping a
// HashSet of every ExtensionObject we currently have, and only
// building new viewmodels for the ones we haven't already built.
foreach (IListItem? item in newItems)
foreach (var item in newItems)
{
ListItemViewModel viewModel = new(item, new(this));
@@ -153,8 +153,8 @@ public partial class ListViewModel : PageViewModel, IDisposable
}
}
IEnumerable<ListItemViewModel> firstTwenty = newViewModels.Take(20);
foreach (ListItemViewModel? item in firstTwenty)
var firstTwenty = newViewModels.Take(20);
foreach (var item in firstTwenty)
{
item?.SafeInitializeProperties();
}
@@ -236,7 +236,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
iterable = Items.ToArray();
}
foreach (ListItemViewModel item in iterable)
foreach (var item in iterable)
{
ct.ThrowIfCancellationRequested();
@@ -269,8 +269,8 @@ public partial class ListViewModel : PageViewModel, IDisposable
return 1;
}
MatchResult nameMatch = StringMatcher.FuzzySearch(query, listItem.Title);
MatchResult descriptionMatch = StringMatcher.FuzzySearch(query, listItem.Subtitle);
var nameMatch = StringMatcher.FuzzySearch(query, listItem.Title);
var descriptionMatch = StringMatcher.FuzzySearch(query, listItem.Subtitle);
return new[] { nameMatch.Score, (descriptionMatch.Score - 4) / 2, 0 }.Max();
}
@@ -283,7 +283,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
// Similarly stolen from ListHelpers.FilterList
public static IEnumerable<ListItemViewModel> FilterList(IEnumerable<ListItemViewModel> items, string query)
{
IOrderedEnumerable<ScoredListItemViewModel> scores = items
var scores = items
.Where(i => !i.IsInErrorState)
.Select(li => new ScoredListItemViewModel() { ViewModel = li, Score = ScoreListItem(query, li) })
.Where(score => score.Score > 0)
@@ -381,7 +381,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
private void SelectedItemPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
ListItemViewModel? item = _lastSelectedItem;
var item = _lastSelectedItem;
if (item == null)
{
return;
@@ -436,7 +436,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
{
base.InitializeProperties();
IListPage? model = _model.Unsafe;
var model = _model.Unsafe;
if (model == null)
{
return; // throw?
@@ -463,7 +463,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
public void LoadMoreIfNeeded()
{
IListPage? model = this._model.Unsafe;
var model = this._model.Unsafe;
if (model == null)
{
return;
@@ -490,7 +490,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
{
base.FetchProperty(propertyName);
IListPage? model = this._model.Unsafe;
var model = this._model.Unsafe;
if (model == null)
{
return; // throw?
@@ -555,13 +555,13 @@ public partial class ListViewModel : PageViewModel, IDisposable
lock (_listLock)
{
foreach (ListItemViewModel item in Items)
foreach (var item in Items)
{
item.SafeCleanup();
}
Items.Clear();
foreach (ListItemViewModel item in FilteredItems)
foreach (var item in FilteredItems)
{
item.SafeCleanup();
}
@@ -569,7 +569,7 @@ public partial class ListViewModel : PageViewModel, IDisposable
FilteredItems.Clear();
}
IListPage? model = _model.Unsafe;
var model = _model.Unsafe;
if (model != null)
{
model.ItemsChanged -= Model_ItemsChanged;

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -21,7 +21,7 @@ public partial class LogMessageViewModel : ExtensionObjectViewModel
public override void InitializeProperties()
{
ILogMessage? model = _model.Unsafe;
var model = _model.Unsafe;
if (model == null)
{
return; // throw?

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -2,6 +2,9 @@
// 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.Core.ViewModels.Models;
using Microsoft.CommandPalette.Extensions;
namespace Microsoft.CmdPal.Core.ViewModels.Messages;
public record HideDetailsMessage()

View File

@@ -2,6 +2,9 @@
// 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.Core.ViewModels.Models;
using Microsoft.CommandPalette.Extensions;
namespace Microsoft.CmdPal.Core.ViewModels.Messages;
public record LaunchUriMessage(Uri Uri)

View File

@@ -2,6 +2,9 @@
// 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.Core.ViewModels.Models;
using Microsoft.CommandPalette.Extensions;
namespace Microsoft.CmdPal.Core.ViewModels.Messages;
public record ShowDetailsMessage(DetailsViewModel Details)

View File

@@ -16,11 +16,11 @@ public record UpdateCommandBarMessage(ICommandBarContext? ViewModel)
public interface IContextMenuContext : INotifyPropertyChanged
{
IEnumerable<IContextItemViewModel> MoreCommands { get; }
public IEnumerable<IContextItemViewModel> MoreCommands { get; }
bool HasMoreCommands { get; }
public bool HasMoreCommands { get; }
List<IContextItemViewModel> AllCommands { get; }
public List<IContextItemViewModel> AllCommands { get; }
/// <summary>
/// Generates a mapping of key -> command item for this particular item's
@@ -30,7 +30,7 @@ public interface IContextMenuContext : INotifyPropertyChanged
/// </summary>
/// <returns>a dictionary of KeyChord -> Context commands, for all commands
/// that have a shortcut key set.</returns>
Dictionary<KeyChord, CommandContextItemViewModel> Keybindings()
public Dictionary<KeyChord, CommandContextItemViewModel> Keybindings()
{
return MoreCommands
.OfType<CommandContextItemViewModel>()
@@ -48,9 +48,9 @@ public interface IContextMenuContext : INotifyPropertyChanged
// the two things with sub-commands.
public interface ICommandBarContext : IContextMenuContext
{
string SecondaryCommandName { get; }
public string SecondaryCommandName { get; }
CommandItemViewModel? PrimaryCommand { get; }
public CommandItemViewModel? PrimaryCommand { get; }
CommandItemViewModel? SecondaryCommand { get; }
public CommandItemViewModel? SecondaryCommand { get; }
}

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -45,4 +45,16 @@
</Compile>
</ItemGroup>
<!-- Just mark it as AOT compatible. Do not publish with AOT now. We need fully test before we really publish it as AOT enabled-->
<!--<PropertyGroup>
<SelfContained>true</SelfContained>
<WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained>
<PublishTrimmed>true</PublishTrimmed>
<PublishSingleFile>true</PublishSingleFile>
--><!-- <DisableRuntimeMarshalling>true</DisableRuntimeMarshalling> --><!--
<PublishAot>true</PublishAot>
<EnableMsixTooling>true</EnableMsixTooling>
</PropertyGroup>-->
</Project>

View File

@@ -88,7 +88,7 @@ public partial class PageViewModel : ExtensionObjectViewModel, IPageContext
{
if (ExtensionHost.StatusMessages.Any())
{
StatusMessageViewModel last = ExtensionHost.StatusMessages.Last();
var last = ExtensionHost.StatusMessages.Last();
MostRecentStatusMessage = last;
}
else
@@ -131,7 +131,7 @@ public partial class PageViewModel : ExtensionObjectViewModel, IPageContext
public override void InitializeProperties()
{
IPage? page = _pageModel.Unsafe;
var page = _pageModel.Unsafe;
if (page == null)
{
return; // throw?
@@ -157,7 +157,7 @@ public partial class PageViewModel : ExtensionObjectViewModel, IPageContext
{
try
{
string propName = args.PropertyName;
var propName = args.PropertyName;
FetchProperty(propName);
}
catch (Exception ex)
@@ -176,13 +176,13 @@ public partial class PageViewModel : ExtensionObjectViewModel, IPageContext
protected virtual void FetchProperty(string propertyName)
{
IPage? model = this._pageModel.Unsafe;
var model = this._pageModel.Unsafe;
if (model == null)
{
return; // throw?
}
bool updateProperty = true;
var updateProperty = true;
switch (propertyName)
{
case nameof(Name):
@@ -239,7 +239,7 @@ public partial class PageViewModel : ExtensionObjectViewModel, IPageContext
ExtensionHost.StatusMessages.CollectionChanged -= StatusMessages_CollectionChanged;
IPage? model = _pageModel.Unsafe;
var model = _pageModel.Unsafe;
if (model != null)
{
model.PropChanged -= Model_PropChanged;

View File

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

View File

@@ -1,7 +1,8 @@
// Copyright (c) Microsoft Corporation
// 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.Core.ViewModels;
using Microsoft.CommandPalette.Extensions;
namespace Microsoft.CmdPal.Core.ViewModels;

View File

@@ -38,7 +38,7 @@ public partial class ShellViewModel : ObservableObject,
get => _currentPage;
set
{
PageViewModel oldValue = _currentPage;
var oldValue = _currentPage;
if (SetProperty(ref _currentPage, value))
{
if (oldValue is IDisposable disposable)
@@ -60,7 +60,7 @@ public partial class ShellViewModel : ObservableObject,
private bool _isNested;
public bool IsNested => _isNested;
public bool IsNested { get => _isNested; }
public ShellViewModel(
TaskScheduler scheduler,
@@ -182,13 +182,13 @@ public partial class ShellViewModel : ObservableObject,
private void PerformCommand(PerformCommandMessage message)
{
ICommand? command = message.Command.Unsafe;
var command = message.Command.Unsafe;
if (command == null)
{
return;
}
AppExtensionHost host = _appHostService.GetHostForCommand(message.Context, CurrentPage.ExtensionHost);
var host = _appHostService.GetHostForCommand(message.Context, CurrentPage.ExtensionHost);
_rootPageService.OnPerformCommand(message.Context, !CurrentPage.IsNested, host);
@@ -198,11 +198,11 @@ public partial class ShellViewModel : ObservableObject,
{
Logger.LogDebug($"Navigating to page");
bool isMainPage = command == _rootPage;
var isMainPage = command == _rootPage;
_isNested = !isMainPage;
// Construct our ViewModel of the appropriate type and pass it the UI Thread context.
PageViewModel? pageViewModel = _pageViewModelFactory.TryCreatePageViewModel(page, _isNested, host);
var pageViewModel = _pageViewModelFactory.TryCreatePageViewModel(page, _isNested, host);
if (pageViewModel == null)
{
Logger.LogError($"Failed to create ViewModel for page {page.GetType().Name}");
@@ -259,7 +259,7 @@ public partial class ShellViewModel : ObservableObject,
// Call out to extension process.
// * May fail!
// * May never return!
ICommandResult result = invokable.Invoke(message.Context);
var result = invokable.Invoke(message.Context);
// But if it did succeed, we need to handle the result.
UnsafeHandleCommandResult(result);
@@ -284,66 +284,66 @@ public partial class ShellViewModel : ObservableObject,
return;
}
CommandResultKind kind = result.Kind;
var kind = result.Kind;
Logger.LogDebug($"handling {kind.ToString()}");
WeakReferenceMessenger.Default.Send<CmdPalInvokeResultMessage>(new(kind));
switch (kind)
{
case CommandResultKind.Dismiss:
{
// Reset the palette to the main page and dismiss
GoHome(withAnimation: false, focusSearch: false);
WeakReferenceMessenger.Default.Send<DismissMessage>();
break;
}
{
// Reset the palette to the main page and dismiss
GoHome(withAnimation: false, focusSearch: false);
WeakReferenceMessenger.Default.Send<DismissMessage>();
break;
}
case CommandResultKind.GoHome:
{
// Go back to the main page, but keep it open
GoHome();
break;
}
{
// Go back to the main page, but keep it open
GoHome();
break;
}
case CommandResultKind.GoBack:
{
GoBack();
break;
}
{
GoBack();
break;
}
case CommandResultKind.Hide:
{
// Keep this page open, but hide the palette.
WeakReferenceMessenger.Default.Send<DismissMessage>();
break;
}
{
// Keep this page open, but hide the palette.
WeakReferenceMessenger.Default.Send<DismissMessage>();
break;
}
case CommandResultKind.KeepOpen:
{
// Do nothing.
break;
}
{
// Do nothing.
break;
}
case CommandResultKind.Confirm:
{
if (result.Args is IConfirmationArgs a)
{
WeakReferenceMessenger.Default.Send<ShowConfirmationMessage>(new(a));
}
if (result.Args is IConfirmationArgs a)
{
WeakReferenceMessenger.Default.Send<ShowConfirmationMessage>(new(a));
}
break;
}
break;
}
case CommandResultKind.ShowToast:
{
if (result.Args is IToastArgs a)
{
WeakReferenceMessenger.Default.Send<ShowToastMessage>(new(a.Message));
UnsafeHandleCommandResult(a.Result);
}
if (result.Args is IToastArgs a)
{
WeakReferenceMessenger.Default.Send<ShowToastMessage>(new(a.Message));
UnsafeHandleCommandResult(a.Result);
}
break;
}
break;
}
}
}

View File

@@ -27,7 +27,7 @@ public partial class StatusMessageViewModel : ExtensionObjectViewModel
public override void InitializeProperties()
{
IStatusMessage? model = Model.Unsafe;
var model = Model.Unsafe;
if (model == null)
{
return; // throw?
@@ -35,7 +35,7 @@ public partial class StatusMessageViewModel : ExtensionObjectViewModel
Message = model.Message;
State = model.State;
IProgressState modelProgress = model.Progress;
var modelProgress = model.Progress;
if (modelProgress != null)
{
Progress = new(modelProgress, this.PageContext);
@@ -60,7 +60,7 @@ public partial class StatusMessageViewModel : ExtensionObjectViewModel
protected virtual void FetchProperty(string propertyName)
{
IStatusMessage? model = this.Model.Unsafe;
var model = this.Model.Unsafe;
if (model == null)
{
return; // throw?
@@ -75,7 +75,7 @@ public partial class StatusMessageViewModel : ExtensionObjectViewModel
this.State = model.State;
break;
case nameof(Progress):
IProgressState modelProgress = model.Progress;
var modelProgress = model.Progress;
if (modelProgress != null)
{
Progress = new(modelProgress, this.PageContext);

View File

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

View File

@@ -3,6 +3,8 @@
// See the LICENSE file in the project root for more information.
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.CmdPal.Core.ViewModels.Messages;
namespace Microsoft.CmdPal.Core.ViewModels;

View File

@@ -30,11 +30,11 @@ public partial class AliasManager : ObservableObject
public bool CheckAlias(string searchText)
{
if (_aliases.TryGetValue(searchText, out CommandAlias? alias))
if (_aliases.TryGetValue(searchText, out var alias))
{
try
{
TopLevelViewModel? topLevelCommand = _topLevelCommandManager.LookupCommand(alias.CommandId);
var topLevelCommand = _topLevelCommandManager.LookupCommand(alias.CommandId);
if (topLevelCommand != null)
{
WeakReferenceMessenger.Default.Send<ClearSearchMessage>();
@@ -89,7 +89,7 @@ public partial class AliasManager : ObservableObject
// If we already have _this exact alias_, do nothing
if (newAlias != null &&
_aliases.TryGetValue(newAlias.SearchPrefix, out CommandAlias? existingAlias))
_aliases.TryGetValue(newAlias.SearchPrefix, out var existingAlias))
{
if (existingAlias.CommandId == commandId)
{
@@ -99,7 +99,7 @@ public partial class AliasManager : ObservableObject
// Look for the old alias, and remove it
List<CommandAlias> toRemove = [];
foreach (KeyValuePair<string, CommandAlias> kv in _aliases)
foreach (var kv in _aliases)
{
if (kv.Value.CommandId == commandId)
{
@@ -107,7 +107,7 @@ public partial class AliasManager : ObservableObject
}
}
foreach (CommandAlias alias in toRemove)
foreach (var alias in toRemove)
{
// REMEMBER, SearchPrefix is what we use as keys
_aliases.Remove(alias.SearchPrefix);

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -51,9 +51,9 @@ public partial class AppStateModel : ObservableObject
try
{
// Read the JSON content from the file
string jsonContent = File.ReadAllText(FilePath);
var jsonContent = File.ReadAllText(FilePath);
AppStateModel? loaded = JsonSerializer.Deserialize<AppStateModel>(jsonContent, JsonSerializationContext.Default.AppStateModel);
var loaded = JsonSerializer.Deserialize<AppStateModel>(jsonContent, JsonSerializationContext.Default.AppStateModel);
Debug.WriteLine(loaded != null ? "Loaded settings file" : "Failed to parse");
@@ -77,23 +77,23 @@ public partial class AppStateModel : ObservableObject
try
{
// Serialize the main dictionary to JSON and save it to the file
string settingsJson = JsonSerializer.Serialize(model, JsonSerializationContext.Default.AppStateModel);
var settingsJson = JsonSerializer.Serialize(model, JsonSerializationContext.Default.AppStateModel);
// Is it valid JSON?
if (JsonNode.Parse(settingsJson) is JsonObject newSettings)
{
// Now, read the existing content from the file
string oldContent = File.Exists(FilePath) ? File.ReadAllText(FilePath) : "{}";
var oldContent = File.Exists(FilePath) ? File.ReadAllText(FilePath) : "{}";
// Is it valid JSON?
if (JsonNode.Parse(oldContent) is JsonObject savedSettings)
{
foreach (KeyValuePair<string, JsonNode?> item in newSettings)
foreach (var item in newSettings)
{
savedSettings[item.Key] = item.Value?.DeepClone();
}
string serialized = savedSettings.ToJsonString(JsonSerializationContext.Default.AppStateModel.Options);
var serialized = savedSettings.ToJsonString(JsonSerializationContext.Default.AppStateModel.Options);
File.WriteAllText(FilePath, serialized);
// TODO: Instead of just raising the event here, we should
@@ -119,7 +119,7 @@ public partial class AppStateModel : ObservableObject
internal static string StateJsonPath()
{
string directory = Utilities.BaseSettingsPath("Microsoft.CmdPal");
var directory = Utilities.BaseSettingsPath("Microsoft.CmdPal");
Directory.CreateDirectory(directory);
// now, the settings is just next to the exe

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -31,8 +31,8 @@ public class CommandAlias
public static CommandAlias FromSearchText(string text, string commandId)
{
bool trailingSpace = text.EndsWith(' ');
string realAlias = trailingSpace ? text.Substring(0, text.Length - 1) : text;
var trailingSpace = text.EndsWith(' ');
var realAlias = trailingSpace ? text.Substring(0, text.Length - 1) : text;
return new CommandAlias(realAlias, commandId, !trailingSpace);
}
}

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -43,7 +43,13 @@ public sealed class CommandProviderWrapper
public bool IsActive { get; private set; }
public string ProviderId => string.IsNullOrEmpty(Extension?.ExtensionUniqueId) ? Id : Extension.ExtensionUniqueId;
public string ProviderId
{
get
{
return string.IsNullOrEmpty(Extension?.ExtensionUniqueId) ? Id : Extension.ExtensionUniqueId;
}
}
public CommandProviderWrapper(ICommandProvider provider, TaskScheduler mainThread)
{
@@ -81,8 +87,8 @@ public sealed class CommandProviderWrapper
throw new ArgumentException("You forgot to start the extension. This is a CmdPal error - we need to make sure to call StartExtensionAsync");
}
IExtension? extensionImpl = extension.GetExtensionObject();
object? providerObject = extensionImpl?.GetProvider(ProviderType.Commands);
var extensionImpl = extension.GetExtensionObject();
var providerObject = extensionImpl?.GetProvider(ProviderType.Commands);
if (providerObject is not ICommandProvider provider)
{
throw new ArgumentException("extension didn't actually implement ICommandProvider");
@@ -92,7 +98,7 @@ public sealed class CommandProviderWrapper
try
{
ICommandProvider model = _commandProvider.Unsafe!;
var model = _commandProvider.Unsafe!;
// Hook the extension back into us
model.InitializeWithHost(ExtensionHost);
@@ -125,7 +131,7 @@ public sealed class CommandProviderWrapper
return;
}
SettingsModel settings = serviceProvider.GetService<SettingsModel>()!;
var settings = serviceProvider.GetService<SettingsModel>()!;
IsActive = GetProviderSettings(settings).IsEnabled;
if (!IsActive)
@@ -138,7 +144,7 @@ public sealed class CommandProviderWrapper
try
{
ICommandProvider model = _commandProvider.Unsafe!;
var model = _commandProvider.Unsafe!;
Task<ICommandItem[]> t = new(model.TopLevelCommands);
t.Start();
@@ -171,29 +177,28 @@ public sealed class CommandProviderWrapper
private void InitializeCommands(ICommandItem[] commands, IFallbackCommandItem[] fallbacks, IServiceProvider serviceProvider, WeakReference<IPageContext> pageContext)
{
SettingsModel settings = serviceProvider.GetService<SettingsModel>()!;
ProviderSettings providerSettings = GetProviderSettings(settings);
var settings = serviceProvider.GetService<SettingsModel>()!;
var providerSettings = GetProviderSettings(settings);
TopLevelViewModel MakeAndAdd(ICommandItem? i, bool fallback)
Func<ICommandItem?, bool, TopLevelViewModel> makeAndAdd = (ICommandItem? i, bool fallback) =>
{
CommandItemViewModel commandItemViewModel = new(new(i), pageContext);
TopLevelViewModel topLevelViewModel = new(commandItemViewModel, fallback, ExtensionHost, ProviderId, settings, providerSettings, serviceProvider);
topLevelViewModel.InitializeProperties();
return topLevelViewModel;
}
};
if (commands != null)
{
TopLevelItems = commands
.Select(c => MakeAndAdd(c, false))
.Select(c => makeAndAdd(c, false))
.ToArray();
}
if (fallbacks != null)
{
FallbackItems = fallbacks
.Select(c => MakeAndAdd(c, true))
.Select(c => makeAndAdd(c, true))
.ToArray();
}
}

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -23,7 +23,7 @@ public partial class CommandSettingsViewModel(ICommandSettings? _unsafeSettings,
private void UnsafeInitializeProperties()
{
ICommandSettings? model = _model.Unsafe;
var model = _model.Unsafe;
if (model == null)
{
return;

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -13,13 +13,13 @@ internal sealed partial class CreatedExtensionForm : NewExtensionFormBase
{
public CreatedExtensionForm(string name, string displayName, string path)
{
static string SerializeString(string? s) => JsonSerializer.Serialize(s, JsonSerializationContext.Default.String);
var serializeString = (string? s) => JsonSerializer.Serialize(s, JsonSerializationContext.Default.String);
TemplateJson = CardTemplate;
DataJson = $$"""
{
"name": {{SerializeString(name)}},
"directory": {{SerializeString(path)}},
"displayName": {{SerializeString(displayName)}}
"name": {{serializeString(name)}},
"directory": {{serializeString(path)}},
"displayName": {{serializeString(displayName)}}
}
""";
_name = name;
@@ -29,13 +29,13 @@ internal sealed partial class CreatedExtensionForm : NewExtensionFormBase
public override ICommandResult SubmitForm(string inputs, string data)
{
JsonObject? dataInput = JsonNode.Parse(data)?.AsObject();
var dataInput = JsonNode.Parse(data)?.AsObject();
if (dataInput == null)
{
return CommandResult.KeepOpen();
}
string verb = dataInput["x"]?.AsValue()?.ToString() ?? string.Empty;
var verb = dataInput["x"]?.AsValue()?.ToString() ?? string.Empty;
return verb switch
{
"sln" => OpenSolution(),
@@ -45,23 +45,23 @@ internal sealed partial class CreatedExtensionForm : NewExtensionFormBase
};
}
private CommandResult OpenSolution()
private ICommandResult OpenSolution()
{
string[] parts = [_path, _name, $"{_name}.sln"];
string pathToSolution = Path.Combine(parts);
var pathToSolution = Path.Combine(parts);
ShellHelpers.OpenInShell(pathToSolution);
return CommandResult.Hide();
}
private CommandResult OpenDirectory()
private ICommandResult OpenDirectory()
{
string[] parts = [_path, _name];
string pathToDir = Path.Combine(parts);
var pathToDir = Path.Combine(parts);
ShellHelpers.OpenInShell(pathToDir);
return CommandResult.Hide();
}
private CommandResult CreateNew()
private ICommandResult CreateNew()
{
RaiseFormSubmit(null);
return CommandResult.KeepOpen();

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -1,7 +1,8 @@
// Copyright (c) Microsoft Corporation
// 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 Microsoft.CommandPalette.Extensions.Toolkit;
namespace Microsoft.CmdPal.UI.ViewModels.BuiltinCommands;

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -25,11 +25,11 @@ public partial class LogMessagesPage : ListPage
{
if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems != null)
{
foreach (object? item in e.NewItems)
foreach (var item in e.NewItems)
{
if (item is LogMessageViewModel logMessageViewModel)
{
ListItem li = new ListItem(new NoOpCommand())
var li = new ListItem(new NoOpCommand())
{
Title = logMessageViewModel.Message,
};

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -40,7 +40,7 @@ public partial class MainListPage : DynamicListPage,
// The all apps page will kick off a BG thread to start loading apps.
// We just want to know when it is done.
AllAppsPage allApps = AllAppsCommandProvider.Page;
var allApps = AllAppsCommandProvider.Page;
allApps.PropChanged += (s, p) =>
{
if (p.PropertyName == nameof(allApps.IsLoading))
@@ -52,7 +52,7 @@ public partial class MainListPage : DynamicListPage,
WeakReferenceMessenger.Default.Register<ClearSearchMessage>(this);
WeakReferenceMessenger.Default.Register<UpdateFallbackItemsMessage>(this);
SettingsModel settings = _serviceProvider.GetService<SettingsModel>()!;
var settings = _serviceProvider.GetService<SettingsModel>()!;
settings.SettingsChanged += SettingsChangedHandler;
HotReloadSettings(settings);
@@ -86,7 +86,7 @@ public partial class MainListPage : DynamicListPage,
{
try
{
string currentSearchText = SearchText;
var currentSearchText = SearchText;
UpdateSearchText(currentSearchText, currentSearchText);
}
catch (Exception e)
@@ -122,14 +122,14 @@ public partial class MainListPage : DynamicListPage,
// Handle changes to the filter text here
if (!string.IsNullOrEmpty(SearchText))
{
AliasManager aliases = _serviceProvider.GetService<AliasManager>()!;
var aliases = _serviceProvider.GetService<AliasManager>()!;
if (aliases.CheckAlias(newSearch))
{
return;
}
}
System.Collections.ObjectModel.ObservableCollection<TopLevelViewModel> commands = _tlcManager.TopLevelCommands;
var commands = _tlcManager.TopLevelCommands;
lock (commands)
{
UpdateFallbacks(newSearch, commands.ToImmutableArray());
@@ -179,11 +179,11 @@ public partial class MainListPage : DynamicListPage,
// fire and forget
_ = Task.Run(() =>
{
bool needsToUpdate = false;
var needsToUpdate = false;
foreach (TopLevelViewModel command in commands)
foreach (var command in commands)
{
bool changedVisibility = command.SafeUpdateFallbackTextSynchronous(newSearch);
var changedVisibility = command.SafeUpdateFallbackTextSynchronous(newSearch);
needsToUpdate = needsToUpdate || changedVisibility;
}
@@ -196,8 +196,8 @@ public partial class MainListPage : DynamicListPage,
private bool ActuallyLoading()
{
TopLevelCommandManager tlcManager = _serviceProvider.GetService<TopLevelCommandManager>()!;
AllAppsPage allApps = AllAppsCommandProvider.Page;
var tlcManager = _serviceProvider.GetService<TopLevelCommandManager>()!;
var allApps = AllAppsCommandProvider.Page;
return allApps.IsLoading || tlcManager.IsLoading;
}
@@ -206,26 +206,26 @@ public partial class MainListPage : DynamicListPage,
// _always_ show up first.
private int ScoreTopLevelItem(string query, IListItem topLevelOrAppItem)
{
string title = topLevelOrAppItem.Title;
var title = topLevelOrAppItem.Title;
if (string.IsNullOrWhiteSpace(title))
{
return 0;
}
bool isWhiteSpace = string.IsNullOrWhiteSpace(query);
var isWhiteSpace = string.IsNullOrWhiteSpace(query);
bool isFallback = false;
bool isAliasSubstringMatch = false;
bool isAliasMatch = false;
string id = IdForTopLevelOrAppItem(topLevelOrAppItem);
var isFallback = false;
var isAliasSubstringMatch = false;
var isAliasMatch = false;
var id = IdForTopLevelOrAppItem(topLevelOrAppItem);
string extensionDisplayName = string.Empty;
var extensionDisplayName = string.Empty;
if (topLevelOrAppItem is TopLevelViewModel topLevel)
{
isFallback = topLevel.IsFallback;
if (topLevel.HasAlias)
{
string alias = topLevel.AliasText;
var alias = topLevel.AliasText;
isAliasMatch = alias == query;
isAliasSubstringMatch = isAliasMatch || alias.StartsWith(query, StringComparison.CurrentCultureIgnoreCase);
}
@@ -243,48 +243,48 @@ public partial class MainListPage : DynamicListPage,
// Title:
// * whitespace query: 1 point
// * otherwise full weight match
int nameMatch = isWhiteSpace ?
var nameMatch = isWhiteSpace ?
(title.Contains(query) ? 1 : 0) :
StringMatcher.FuzzySearch(query, title).Score;
// Subtitle:
// * whitespace query: 1/2 point
// * otherwise ~half weight match. Minus a bit, because subtitles tend to be longer
double descriptionMatch = isWhiteSpace ?
var descriptionMatch = isWhiteSpace ?
(topLevelOrAppItem.Subtitle.Contains(query) ? .5 : 0) :
(StringMatcher.FuzzySearch(query, topLevelOrAppItem.Subtitle).Score - 4) / 2.0;
// Extension title: despite not being visible, give the extension name itself some weight
// * whitespace query: 0 points
// * otherwise more weight than a subtitle, but not much
double extensionTitleMatch = isWhiteSpace ? 0 : StringMatcher.FuzzySearch(query, extensionDisplayName).Score / 1.5;
var extensionTitleMatch = isWhiteSpace ? 0 : StringMatcher.FuzzySearch(query, extensionDisplayName).Score / 1.5;
double[] scores = new[]
var scores = new[]
{
nameMatch,
descriptionMatch,
isFallback ? 1 : 0, // Always give fallbacks a chance
};
double max = scores.Max();
var max = scores.Max();
// _Add_ the extension name. This will bubble items that match both
// title and extension name up above ones that just match title.
// e.g. "git" will up-weight "GitHub searches" from the GitHub extension
// above "git" from "whatever"
max += extensionTitleMatch;
max = max + extensionTitleMatch;
double matchSomething = max
var matchSomething = max
+ (isAliasMatch ? 9001 : (isAliasSubstringMatch ? 1 : 0));
// If we matched title, subtitle, or alias (something real), then
// here we add the recent command weight boost
//
// Otherwise something like `x` will still match everything you've run before
double finalScore = matchSomething;
var finalScore = matchSomething;
if (matchSomething > 0)
{
RecentCommandsManager history = _serviceProvider.GetService<AppStateModel>()!.RecentCommands;
int recentWeightBoost = history.GetCommandHistoryWeight(id);
var history = _serviceProvider.GetService<AppStateModel>()!.RecentCommands;
var recentWeightBoost = history.GetCommandHistoryWeight(id);
finalScore += recentWeightBoost;
}
@@ -293,9 +293,9 @@ public partial class MainListPage : DynamicListPage,
public void UpdateHistory(IListItem topLevelOrAppItem)
{
string id = IdForTopLevelOrAppItem(topLevelOrAppItem);
AppStateModel state = _serviceProvider.GetService<AppStateModel>()!;
RecentCommandsManager history = state.RecentCommands;
var id = IdForTopLevelOrAppItem(topLevelOrAppItem);
var state = _serviceProvider.GetService<AppStateModel>()!;
var history = state.RecentCommands;
history.AddHistoryItem(id);
AppStateModel.SaveState(state);
}

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -97,15 +97,15 @@ internal sealed partial class NewExtensionForm : NewExtensionFormBase
public override CommandResult SubmitForm(string payload)
{
JsonObject? formInput = JsonNode.Parse(payload)?.AsObject();
var formInput = JsonNode.Parse(payload)?.AsObject();
if (formInput == null)
{
return CommandResult.KeepOpen();
}
string extensionName = formInput["ExtensionName"]?.AsValue()?.ToString() ?? string.Empty;
string displayName = formInput["DisplayName"]?.AsValue()?.ToString() ?? string.Empty;
string outputPath = formInput["OutputPath"]?.AsValue()?.ToString() ?? string.Empty;
var extensionName = formInput["ExtensionName"]?.AsValue()?.ToString() ?? string.Empty;
var displayName = formInput["DisplayName"]?.AsValue()?.ToString() ?? string.Empty;
var outputPath = formInput["OutputPath"]?.AsValue()?.ToString() ?? string.Empty;
_creatingMessage.State = MessageState.Info;
_creatingMessage.Message = _creatingText;
@@ -133,10 +133,10 @@ internal sealed partial class NewExtensionForm : NewExtensionFormBase
private void CreateExtension(string extensionName, string newDisplayName, string outputPath)
{
string newGuid = Guid.NewGuid().ToString();
var newGuid = Guid.NewGuid().ToString();
// Unzip `template.zip` to a temp dir:
string tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
// Does the output path exist?
if (!Directory.Exists(outputPath))
@@ -144,13 +144,13 @@ internal sealed partial class NewExtensionForm : NewExtensionFormBase
Directory.CreateDirectory(outputPath);
}
string assetsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "Microsoft.CmdPal.UI.ViewModels\\Assets\\template.zip");
var assetsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "Microsoft.CmdPal.UI.ViewModels\\Assets\\template.zip");
ZipFile.ExtractToDirectory(assetsPath, tempDir);
string[] files = Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories);
foreach (string file in files)
var files = Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories);
foreach (var file in files)
{
string text = File.ReadAllText(file);
var text = File.ReadAllText(file);
// Replace all the instances of `FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF` with a new random guid:
text = text.Replace("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF", newGuid);
@@ -162,9 +162,9 @@ internal sealed partial class NewExtensionForm : NewExtensionFormBase
text = text.Replace("TemplateDisplayName", newDisplayName);
// We're going to write the file to the same relative location in the output path
string relativePath = Path.GetRelativePath(tempDir, file);
var relativePath = Path.GetRelativePath(tempDir, file);
string newFileName = Path.Combine(outputPath, relativePath);
var newFileName = Path.Combine(outputPath, relativePath);
// if the file name had `TemplateCmdPalExtension` in it, replace it with `extensionName`
newFileName = newFileName.Replace("TemplateCmdPalExtension", extensionName);

View File

@@ -1,7 +1,13 @@
// Copyright (c) Microsoft Corporation
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using System.IO.Compression;
using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.CmdPal.Core.ViewModels.Messages;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
using Windows.Foundation;

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -44,8 +44,8 @@ public partial class ContentFormViewModel(IFormContent _form, WeakReference<IPag
try
{
AdaptiveCardTemplate template = new AdaptiveCardTemplate(templateJson);
string cardJson = template.Expand(dataJson);
var template = new AdaptiveCardTemplate(templateJson);
var cardJson = template.Expand(dataJson);
card = AdaptiveCard.FromJsonString(cardJson);
return true;
}
@@ -59,7 +59,7 @@ public partial class ContentFormViewModel(IFormContent _form, WeakReference<IPag
public override void InitializeProperties()
{
IFormContent? model = _formModel.Unsafe;
var model = _formModel.Unsafe;
if (model is null)
{
return;
@@ -69,14 +69,14 @@ public partial class ContentFormViewModel(IFormContent _form, WeakReference<IPag
StateJson = model.StateJson;
DataJson = model.DataJson;
if (TryBuildCard(TemplateJson, DataJson, out AdaptiveCardParseResult? builtCard, out Exception? renderingError))
if (TryBuildCard(TemplateJson, DataJson, out var builtCard, out var renderingError))
{
Card = builtCard;
UpdateProperty(nameof(Card));
return;
}
string errorPayload = $$"""
var errorPayload = $$"""
{
"error_message": {{Serialize(renderingError!.Message)}},
"error_stack": {{Serialize(renderingError.StackTrace)}},
@@ -86,7 +86,7 @@ public partial class ContentFormViewModel(IFormContent _form, WeakReference<IPag
}
""";
if (TryBuildCard(ErrorCardJson, errorPayload, out AdaptiveCardParseResult? errorCard, out Exception? _))
if (TryBuildCard(ErrorCardJson, errorPayload, out var errorCard, out var _))
{
Card = errorCard;
UpdateProperty(nameof(Card));
@@ -107,17 +107,17 @@ public partial class ContentFormViewModel(IFormContent _form, WeakReference<IPag
if (action is AdaptiveSubmitAction or AdaptiveExecuteAction)
{
// Get the data and inputs
string dataString = (action as AdaptiveSubmitAction)?.DataJson.Stringify() ?? string.Empty;
string inputString = inputs.Stringify();
var dataString = (action as AdaptiveSubmitAction)?.DataJson.Stringify() ?? string.Empty;
var inputString = inputs.Stringify();
_ = Task.Run(() =>
{
try
{
IFormContent model = _formModel.Unsafe!;
var model = _formModel.Unsafe!;
if (model != null)
{
ICommandResult result = model.SubmitForm(inputString, dataString);
var result = model.SubmitForm(inputString, dataString);
WeakReferenceMessenger.Default.Send<HandleCommandResultMessage>(new(new(result)));
}
}

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -19,7 +19,7 @@ public partial class ContentMarkdownViewModel(IMarkdownContent _markdown, WeakRe
public override void InitializeProperties()
{
IMarkdownContent? model = Model.Unsafe;
var model = Model.Unsafe;
if (model == null)
{
return;
@@ -35,7 +35,7 @@ public partial class ContentMarkdownViewModel(IMarkdownContent _markdown, WeakRe
{
try
{
string propName = args.PropertyName;
var propName = args.PropertyName;
FetchProperty(propName);
}
catch (Exception ex)
@@ -46,7 +46,7 @@ public partial class ContentMarkdownViewModel(IMarkdownContent _markdown, WeakRe
protected void FetchProperty(string propertyName)
{
IMarkdownContent? model = Model.Unsafe;
var model = Model.Unsafe;
if (model == null)
{
return; // throw?
@@ -65,7 +65,7 @@ public partial class ContentMarkdownViewModel(IMarkdownContent _markdown, WeakRe
protected override void UnsafeCleanup()
{
base.UnsafeCleanup();
IMarkdownContent? model = Model.Unsafe;
var model = Model.Unsafe;
if (model != null)
{
model.PropChanged -= Model_PropChanged;

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -29,13 +29,13 @@ public partial class ContentTreeViewModel(ITreeContent _tree, WeakReference<IPag
public override void InitializeProperties()
{
ITreeContent? model = Model.Unsafe;
var model = Model.Unsafe;
if (model == null)
{
return;
}
IContent root = model.RootContent;
var root = model.RootContent;
if (root != null)
{
RootContent = ViewModelFromContent(root, PageContext);
@@ -70,7 +70,7 @@ public partial class ContentTreeViewModel(ITreeContent _tree, WeakReference<IPag
{
try
{
string propName = args.PropertyName;
var propName = args.PropertyName;
FetchProperty(propName);
}
catch (Exception ex)
@@ -81,7 +81,7 @@ public partial class ContentTreeViewModel(ITreeContent _tree, WeakReference<IPag
protected void FetchProperty(string propertyName)
{
ITreeContent? model = Model.Unsafe;
var model = Model.Unsafe;
if (model == null)
{
return; // throw?
@@ -90,7 +90,7 @@ public partial class ContentTreeViewModel(ITreeContent _tree, WeakReference<IPag
switch (propertyName)
{
case nameof(RootContent):
IContent? root = model.RootContent;
var root = model.RootContent;
if (root != null)
{
RootContent = ViewModelFromContent(root, PageContext);
@@ -114,11 +114,11 @@ public partial class ContentTreeViewModel(ITreeContent _tree, WeakReference<IPag
List<ContentViewModel> newContent = [];
try
{
IContent[] newItems = Model.Unsafe!.GetChildren();
var newItems = Model.Unsafe!.GetChildren();
foreach (IContent? item in newItems)
foreach (var item in newItems)
{
ContentViewModel? viewModel = ViewModelFromContent(item, PageContext);
var viewModel = ViewModelFromContent(item, PageContext);
if (viewModel != null)
{
viewModel.InitializeProperties();
@@ -146,13 +146,13 @@ public partial class ContentTreeViewModel(ITreeContent _tree, WeakReference<IPag
{
base.UnsafeCleanup();
RootContent?.SafeCleanup();
foreach (ContentViewModel item in Children)
foreach (var item in Children)
{
item.SafeCleanup();
}
Children.Clear();
ITreeContent? model = Model.Unsafe;
var model = Model.Unsafe;
if (model != null)
{
model.PropChanged -= Model_PropChanged;

View File

@@ -1,7 +1,9 @@
// Copyright (c) Microsoft Corporation
// 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.ComponentModel;
namespace Microsoft.CmdPal.UI.ViewModels;
public record HistoryItem

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -21,7 +21,7 @@ public partial class HotkeyManager : ObservableObject
public void UpdateHotkey(string commandId, HotkeySettings? hotkey)
{
// If any of the commands were already bound to this hotkey, remove that
foreach (TopLevelHotkey item in _commandHotkeys)
foreach (var item in _commandHotkeys)
{
if (item.Hotkey == hotkey)
{
@@ -31,7 +31,7 @@ public partial class HotkeyManager : ObservableObject
_commandHotkeys.RemoveAll(item => item.Hotkey == null);
foreach (TopLevelHotkey item in _commandHotkeys)
foreach (var item in _commandHotkeys)
{
if (item.CommandId == commandId)
{

View File

@@ -83,12 +83,12 @@ public partial class ExtensionService : IExtensionService, IDisposable
private void InstallPackageUnderLock(Package package)
{
IsExtensionResult isCmdPalExtensionResult = Task.Run(() =>
var isCmdPalExtensionResult = Task.Run(() =>
{
return IsValidCmdPalExtension(package);
}).Result;
bool isExtension = isCmdPalExtensionResult.IsExtension;
AppExtension? extension = isCmdPalExtensionResult.Extension;
var isExtension = isCmdPalExtensionResult.IsExtension;
var extension = isCmdPalExtensionResult.Extension;
if (isExtension && extension != null)
{
CommandPaletteHost.Instance.DebugLog($"Installed new extension app {extension.DisplayName}");
@@ -98,7 +98,7 @@ public partial class ExtensionService : IExtensionService, IDisposable
await _getInstalledExtensionsLock.WaitAsync();
try
{
List<ExtensionWrapper> wrappers = await CreateWrappersForExtension(extension);
var wrappers = await CreateWrappersForExtension(extension);
UpdateExtensionsListsFromWrappers(wrappers);
@@ -115,7 +115,7 @@ public partial class ExtensionService : IExtensionService, IDisposable
private void UninstallPackageUnderLock(Package package)
{
List<IExtensionWrapper> removedExtensions = [];
foreach (IExtensionWrapper extension in _installedExtensions)
foreach (var extension in _installedExtensions)
{
if (extension.PackageFullName == package.Id.FullName)
{
@@ -144,12 +144,12 @@ public partial class ExtensionService : IExtensionService, IDisposable
private static async Task<IsExtensionResult> IsValidCmdPalExtension(Package package)
{
IReadOnlyList<AppExtension> extensions = await AppExtensionCatalog.Open("com.microsoft.commandpalette").FindAllAsync();
foreach (AppExtension? extension in extensions)
var extensions = await AppExtensionCatalog.Open("com.microsoft.commandpalette").FindAllAsync();
foreach (var extension in extensions)
{
if (package.Id?.FullName == extension.Package?.Id?.FullName)
{
(IPropertySet? cmdPalProvider, List<string> classId) = await GetCmdPalExtensionPropertiesAsync(extension);
var (cmdPalProvider, classId) = await GetCmdPalExtensionPropertiesAsync(extension);
return new(cmdPalProvider != null && classId.Count != 0, extension);
}
@@ -160,21 +160,21 @@ public partial class ExtensionService : IExtensionService, IDisposable
private static async Task<(IPropertySet? CmdPalProvider, List<string> ClassIds)> GetCmdPalExtensionPropertiesAsync(AppExtension extension)
{
List<string> classIds = new List<string>();
IPropertySet? properties = await extension.GetExtensionPropertiesAsync();
var classIds = new List<string>();
var properties = await extension.GetExtensionPropertiesAsync();
if (properties is null)
{
return (null, classIds);
}
IPropertySet? cmdPalProvider = GetSubPropertySet(properties, "CmdPalProvider");
var cmdPalProvider = GetSubPropertySet(properties, "CmdPalProvider");
if (cmdPalProvider is null)
{
return (null, classIds);
}
IPropertySet? activation = GetSubPropertySet(cmdPalProvider, "Activation");
var activation = GetSubPropertySet(cmdPalProvider, "Activation");
if (activation is null)
{
return (cmdPalProvider, classIds);
@@ -195,10 +195,10 @@ public partial class ExtensionService : IExtensionService, IDisposable
{
if (_installedExtensions.Count == 0)
{
IEnumerable<AppExtension> extensions = await GetInstalledAppExtensionsAsync();
foreach (AppExtension extension in extensions)
var extensions = await GetInstalledAppExtensionsAsync();
foreach (var extension in extensions)
{
List<ExtensionWrapper> wrappers = await CreateWrappersForExtension(extension);
var wrappers = await CreateWrappersForExtension(extension);
UpdateExtensionsListsFromWrappers(wrappers);
}
}
@@ -213,11 +213,11 @@ public partial class ExtensionService : IExtensionService, IDisposable
private static void UpdateExtensionsListsFromWrappers(List<ExtensionWrapper> wrappers)
{
foreach (ExtensionWrapper extensionWrapper in wrappers)
foreach (var extensionWrapper in wrappers)
{
// var localSettingsService = Application.Current.GetService<ILocalSettingsService>();
string extensionUniqueId = extensionWrapper.ExtensionUniqueId;
bool isExtensionDisabled = false; // await localSettingsService.ReadSettingAsync<bool>(extensionUniqueId + "-ExtensionDisabled");
var extensionUniqueId = extensionWrapper.ExtensionUniqueId;
var isExtensionDisabled = false; // await localSettingsService.ReadSettingAsync<bool>(extensionUniqueId + "-ExtensionDisabled");
_installedExtensions.Add(extensionWrapper);
if (!isExtensionDisabled)
@@ -234,7 +234,7 @@ public partial class ExtensionService : IExtensionService, IDisposable
private static async Task<List<ExtensionWrapper>> CreateWrappersForExtension(AppExtension extension)
{
(IPropertySet? cmdPalProvider, List<string> classIds) = await GetCmdPalExtensionPropertiesAsync(extension);
var (cmdPalProvider, classIds) = await GetCmdPalExtensionPropertiesAsync(extension);
if (cmdPalProvider == null || classIds.Count == 0)
{
@@ -242,9 +242,9 @@ public partial class ExtensionService : IExtensionService, IDisposable
}
List<ExtensionWrapper> wrappers = [];
foreach (string classId in classIds)
foreach (var classId in classIds)
{
ExtensionWrapper extensionWrapper = CreateExtensionWrapper(extension, cmdPalProvider, classId);
var extensionWrapper = CreateExtensionWrapper(extension, cmdPalProvider, classId);
wrappers.Add(extensionWrapper);
}
@@ -253,14 +253,15 @@ public partial class ExtensionService : IExtensionService, IDisposable
private static ExtensionWrapper CreateExtensionWrapper(AppExtension extension, IPropertySet cmdPalProvider, string classId)
{
ExtensionWrapper extensionWrapper = new ExtensionWrapper(extension, classId);
var extensionWrapper = new ExtensionWrapper(extension, classId);
IPropertySet? supportedInterfaces = GetSubPropertySet(cmdPalProvider, "SupportedInterfaces");
var supportedInterfaces = GetSubPropertySet(cmdPalProvider, "SupportedInterfaces");
if (supportedInterfaces is not null)
{
foreach (KeyValuePair<string, object> supportedInterface in supportedInterfaces)
foreach (var supportedInterface in supportedInterfaces)
{
if (Enum.TryParse(supportedInterface.Key, out ProviderType pt))
ProviderType pt;
if (Enum.TryParse(supportedInterface.Key, out pt))
{
extensionWrapper.AddProviderType(pt);
}
@@ -277,14 +278,14 @@ public partial class ExtensionService : IExtensionService, IDisposable
public IExtensionWrapper? GetInstalledExtension(string extensionUniqueId)
{
IEnumerable<IExtensionWrapper> extension = _installedExtensions.Where(extension => extension.ExtensionUniqueId.Equals(extensionUniqueId, StringComparison.Ordinal));
var extension = _installedExtensions.Where(extension => extension.ExtensionUniqueId.Equals(extensionUniqueId, StringComparison.Ordinal));
return extension.FirstOrDefault();
}
public async Task SignalStopExtensionsAsync()
{
IEnumerable<IExtensionWrapper> installedExtensions = await GetInstalledExtensionsAsync();
foreach (IExtensionWrapper installedExtension in installedExtensions)
var installedExtensions = await GetInstalledExtensionsAsync();
foreach (var installedExtension in installedExtensions)
{
if (installedExtension.IsRunning())
{
@@ -295,10 +296,10 @@ public partial class ExtensionService : IExtensionService, IDisposable
public async Task<IEnumerable<IExtensionWrapper>> GetInstalledExtensionsAsync(ProviderType providerType, bool includeDisabledExtensions = false)
{
IEnumerable<IExtensionWrapper> installedExtensions = await GetInstalledExtensionsAsync(includeDisabledExtensions);
var installedExtensions = await GetInstalledExtensionsAsync(includeDisabledExtensions);
List<IExtensionWrapper> filteredExtensions = [];
foreach (IExtensionWrapper installedExtension in installedExtensions)
foreach (var installedExtension in installedExtensions)
{
if (installedExtension.HasProviderType(providerType))
{
@@ -329,9 +330,9 @@ public partial class ExtensionService : IExtensionService, IDisposable
}
}
private static IPropertySet? GetSubPropertySet(IPropertySet propSet, string name) => propSet.TryGetValue(name, out object? value) ? value as IPropertySet : null;
private static IPropertySet? GetSubPropertySet(IPropertySet propSet, string name) => propSet.TryGetValue(name, out var value) ? value as IPropertySet : null;
private static object[]? GetSubPropertySetArray(IPropertySet propSet, string name) => propSet.TryGetValue(name, out object? value) ? value as object[] : null;
private static object[]? GetSubPropertySetArray(IPropertySet propSet, string name) => propSet.TryGetValue(name, out var value) ? value as object[] : null;
/// <summary>
/// There are cases where the extension creates multiple COM instances.
@@ -340,11 +341,11 @@ public partial class ExtensionService : IExtensionService, IDisposable
/// <returns>List of ClassId strings associated with the activation property</returns>
private static List<string> GetCreateInstanceList(IPropertySet activationPropSet)
{
List<string> propSetList = new List<string>();
IPropertySet? singlePropertySet = GetSubPropertySet(activationPropSet, CreateInstanceProperty);
var propSetList = new List<string>();
var singlePropertySet = GetSubPropertySet(activationPropSet, CreateInstanceProperty);
if (singlePropertySet != null)
{
string? classId = GetProperty(singlePropertySet, ClassIdProperty);
var classId = GetProperty(singlePropertySet, ClassIdProperty);
// If the instance has a classId as a single string, then it's only supporting a single instance.
if (classId != null)
@@ -354,17 +355,17 @@ public partial class ExtensionService : IExtensionService, IDisposable
}
else
{
object[]? propertySetArray = GetSubPropertySetArray(activationPropSet, CreateInstanceProperty);
var propertySetArray = GetSubPropertySetArray(activationPropSet, CreateInstanceProperty);
if (propertySetArray != null)
{
foreach (object prop in propertySetArray)
foreach (var prop in propertySetArray)
{
if (prop is not IPropertySet propertySet)
{
continue;
}
string? classId = GetProperty(propertySet, ClassIdProperty);
var classId = GetProperty(propertySet, ClassIdProperty);
if (classId != null)
{
propSetList.Add(classId);
@@ -380,13 +381,13 @@ public partial class ExtensionService : IExtensionService, IDisposable
public void EnableExtension(string extensionUniqueId)
{
IEnumerable<IExtensionWrapper> extension = _installedExtensions.Where(extension => extension.ExtensionUniqueId.Equals(extensionUniqueId, StringComparison.Ordinal));
var extension = _installedExtensions.Where(extension => extension.ExtensionUniqueId.Equals(extensionUniqueId, StringComparison.Ordinal));
_enabledExtensions.Add(extension.First());
}
public void DisableExtension(string extensionUniqueId)
{
IEnumerable<IExtensionWrapper> extension = _enabledExtensions.Where(extension => extension.ExtensionUniqueId.Equals(extensionUniqueId, StringComparison.Ordinal));
var extension = _enabledExtensions.Where(extension => extension.ExtensionUniqueId.Equals(extensionUniqueId, StringComparison.Ordinal));
_enabledExtensions.Remove(extension.First());
}

View File

@@ -108,15 +108,15 @@ public class ExtensionWrapper : IExtensionWrapper
unsafe
{
void* extensionPtr = (void*)nint.Zero;
var extensionPtr = (void*)nint.Zero;
try
{
// -2147024809: E_INVALIDARG
// -2147467262: E_NOINTERFACE
// -2147024893: E_PATH_NOT_FOUND
Guid guid = typeof(IExtension).GUID;
var guid = typeof(IExtension).GUID;
global::Windows.Win32.Foundation.HRESULT hr = PInvoke.CoCreateInstance(Guid.Parse(ExtensionClassId), null, CLSCTX.CLSCTX_LOCAL_SERVER, guid, out extensionPtr);
var hr = PInvoke.CoCreateInstance(Guid.Parse(ExtensionClassId), null, CLSCTX.CLSCTX_LOCAL_SERVER, guid, out extensionPtr);
if (hr.Value == -2147024893)
{
@@ -181,7 +181,7 @@ public class ExtensionWrapper : IExtensionWrapper
{
await StartExtensionAsync();
object? supportedProviders = GetExtensionObject()?.GetProvider(_providerTypeMap[typeof(T)]);
var supportedProviders = GetExtensionObject()?.GetProvider(_providerTypeMap[typeof(T)]);
if (supportedProviders is IEnumerable<T> multipleProvidersSupported)
{
return multipleProvidersSupported;

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -47,7 +47,7 @@ public class ProviderSettings
public bool IsFallbackEnabled(TopLevelViewModel command)
{
return !FallbackCommands.TryGetValue(command.Id, out bool enabled) || enabled;
return FallbackCommands.TryGetValue(command.Id, out var enabled) ? enabled : true;
}
public void SetFallbackEnabled(TopLevelViewModel command, bool enabled)

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -126,7 +126,10 @@ public partial class ProviderSettingsViewModel(
{
get
{
field ??= BuildTopLevelViewModels();
if (field == null)
{
field = BuildTopLevelViewModels();
}
return field;
}
@@ -134,8 +137,8 @@ public partial class ProviderSettingsViewModel(
private List<TopLevelViewModel> BuildTopLevelViewModels()
{
CommandProviderWrapper thisProvider = _provider;
TopLevelViewModel[] providersCommands = thisProvider.TopLevelItems;
var thisProvider = _provider;
var providersCommands = thisProvider.TopLevelItems;
// Remember! This comes in on the UI thread!
return [.. providersCommands];
@@ -146,7 +149,10 @@ public partial class ProviderSettingsViewModel(
{
get
{
field ??= BuildFallbackViewModels();
if (field == null)
{
field = BuildFallbackViewModels();
}
return field;
}
@@ -156,8 +162,8 @@ public partial class ProviderSettingsViewModel(
private List<TopLevelViewModel> BuildFallbackViewModels()
{
CommandProviderWrapper thisProvider = _provider;
TopLevelViewModel[] providersCommands = thisProvider.FallbackItems;
var thisProvider = _provider;
var providersCommands = thisProvider.FallbackItems;
// Remember! This comes in on the UI thread!
return [.. providersCommands];

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -22,7 +22,7 @@ public partial class RecentCommandsManager : ObservableObject
{
lock (_lock)
{
(int Index, HistoryItem Item) entry = History
var entry = History
.Index()
.Where(item => item.Item.CommandId == commandId)
.FirstOrDefault();
@@ -32,10 +32,10 @@ public partial class RecentCommandsManager : ObservableObject
// Usually it has a weight of 84, compared to 109 for the VS cmd prompt
if (entry.Item != null)
{
int index = entry.Index;
var index = entry.Index;
// First, add some weight based on how early in the list this appears
int bucket = index switch
var bucket = index switch
{
var i when index <= 2 => 35,
var i when index <= 10 => 25,
@@ -45,7 +45,7 @@ public partial class RecentCommandsManager : ObservableObject
};
// Then, add weight for how often this is used, but cap the weight from usage.
int uses = Math.Min(entry.Item.Uses * 5, 35);
var uses = Math.Min(entry.Item.Uses * 5, 35);
return bucket + uses;
}
@@ -58,12 +58,12 @@ public partial class RecentCommandsManager : ObservableObject
{
lock (_lock)
{
HistoryItem? entry = History
var entry = History
.Where(item => item.CommandId == commandId)
.FirstOrDefault();
if (entry == null)
{
HistoryItem newitem = new HistoryItem() { CommandId = commandId, Uses = 1 };
var newitem = new HistoryItem() { CommandId = commandId, Uses = 1 };
History.Insert(0, newitem);
}
else

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -60,7 +60,7 @@ public record HotkeySettings// : ICmdLineRepresentable
public override string ToString()
{
StringBuilder output = new StringBuilder();
var output = new StringBuilder();
if (Win)
{
@@ -84,7 +84,7 @@ public record HotkeySettings// : ICmdLineRepresentable
if (Code > 0)
{
string localKey = Helper.GetKeyName((uint)Code);
var localKey = Helper.GetKeyName((uint)Code);
output.Append(localKey);
}
else if (output.Length >= 2)
@@ -97,7 +97,7 @@ public record HotkeySettings// : ICmdLineRepresentable
public List<object> GetKeysList()
{
List<object> shortcutList = new List<object>();
var shortcutList = new List<object>();
if (Win)
{
@@ -135,7 +135,7 @@ public record HotkeySettings// : ICmdLineRepresentable
shortcutList.Add(Code);
break;
default:
string localKey = Helper.GetKeyName((uint)Code);
var localKey = Helper.GetKeyName((uint)Code);
shortcutList.Add(localKey);
break;
}
@@ -146,7 +146,7 @@ public record HotkeySettings// : ICmdLineRepresentable
public bool IsValid()
{
return !IsAccessibleShortcut() && (Alt || Ctrl || Win || Shift) && Code != 0;
return IsAccessibleShortcut() ? false : (Alt || Ctrl || Win || Shift) && Code != 0;
}
public bool IsEmpty()
@@ -164,10 +164,10 @@ public record HotkeySettings// : ICmdLineRepresentable
public static bool TryParseFromCmd(string cmd, out object? result)
{
bool win = false, ctrl = false, alt = false, shift = false;
int code = 0;
var code = 0;
string[] parts = cmd.Split('+');
foreach (string part in parts)
var parts = cmd.Split('+');
foreach (var part in parts)
{
switch (part.Trim().ToLower(CultureInfo.InvariantCulture))
{

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -60,7 +60,8 @@ public partial class SettingsModel : ObservableObject
public ProviderSettings GetProviderSettings(CommandProviderWrapper provider)
{
if (!ProviderSettings.TryGetValue(provider.ProviderId, out ProviderSettings? settings))
ProviderSettings? settings;
if (!ProviderSettings.TryGetValue(provider.ProviderId, out settings))
{
settings = new ProviderSettings(provider);
settings.Connect(provider);
@@ -90,9 +91,9 @@ public partial class SettingsModel : ObservableObject
try
{
// Read the JSON content from the file
string jsonContent = File.ReadAllText(FilePath);
var jsonContent = File.ReadAllText(FilePath);
SettingsModel? loaded = JsonSerializer.Deserialize<SettingsModel>(jsonContent, JsonSerializationContext.Default.SettingsModel);
var loaded = JsonSerializer.Deserialize<SettingsModel>(jsonContent, JsonSerializationContext.Default.SettingsModel);
Debug.WriteLine(loaded != null ? "Loaded settings file" : "Failed to parse");
@@ -116,23 +117,23 @@ public partial class SettingsModel : ObservableObject
try
{
// Serialize the main dictionary to JSON and save it to the file
string settingsJson = JsonSerializer.Serialize(model, JsonSerializationContext.Default.SettingsModel);
var settingsJson = JsonSerializer.Serialize(model, JsonSerializationContext.Default.SettingsModel);
// Is it valid JSON?
if (JsonNode.Parse(settingsJson) is JsonObject newSettings)
{
// Now, read the existing content from the file
string oldContent = File.Exists(FilePath) ? File.ReadAllText(FilePath) : "{}";
var oldContent = File.Exists(FilePath) ? File.ReadAllText(FilePath) : "{}";
// Is it valid JSON?
if (JsonNode.Parse(oldContent) is JsonObject savedSettings)
{
foreach (KeyValuePair<string, JsonNode?> item in newSettings)
foreach (var item in newSettings)
{
savedSettings[item.Key] = item.Value?.DeepClone();
}
string serialized = savedSettings.ToJsonString(JsonSerializationContext.Default.Options);
var serialized = savedSettings.ToJsonString(JsonSerializationContext.Default.Options);
File.WriteAllText(FilePath, serialized);
// TODO: Instead of just raising the event here, we should
@@ -158,7 +159,7 @@ public partial class SettingsModel : ObservableObject
internal static string SettingsJsonPath()
{
string directory = Utilities.BaseSettingsPath("Microsoft.CmdPal");
var directory = Utilities.BaseSettingsPath("Microsoft.CmdPal");
Directory.CreateDirectory(directory);
// now, the settings is just next to the exe

View File

@@ -125,22 +125,22 @@ public partial class SettingsViewModel : INotifyPropertyChanged
_settings = settings;
_serviceProvider = serviceProvider;
IEnumerable<CommandProviderWrapper> activeProviders = GetCommandProviders();
Dictionary<string, ProviderSettings> allProviderSettings = _settings.ProviderSettings;
var activeProviders = GetCommandProviders();
var allProviderSettings = _settings.ProviderSettings;
foreach (CommandProviderWrapper item in activeProviders)
foreach (var item in activeProviders)
{
ProviderSettings providerSettings = settings.GetProviderSettings(item);
var providerSettings = settings.GetProviderSettings(item);
ProviderSettingsViewModel settingsModel = new ProviderSettingsViewModel(item, providerSettings, _serviceProvider);
var settingsModel = new ProviderSettingsViewModel(item, providerSettings, _serviceProvider);
CommandProviders.Add(settingsModel);
}
}
private IEnumerable<CommandProviderWrapper> GetCommandProviders()
{
TopLevelCommandManager manager = _serviceProvider.GetService<TopLevelCommandManager>()!;
IEnumerable<CommandProviderWrapper> allProviders = manager.CommandProviders;
var manager = _serviceProvider.GetService<TopLevelCommandManager>()!;
var allProviders = manager.CommandProviders;
return allProviders;
}

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -56,7 +56,7 @@ public partial class TopLevelCommandManager : ObservableObject,
public async Task<bool> LoadBuiltinsAsync()
{
Stopwatch s = new Stopwatch();
var s = new Stopwatch();
s.Start();
lock (_commandProvidersLock)
@@ -66,8 +66,8 @@ public partial class TopLevelCommandManager : ObservableObject,
// Load built-In commands first. These are all in-proc, and
// owned by our ServiceProvider.
IEnumerable<ICommandProvider> builtInCommands = _serviceProvider.GetServices<ICommandProvider>();
foreach (ICommandProvider provider in builtInCommands)
var builtInCommands = _serviceProvider.GetServices<ICommandProvider>();
foreach (var provider in builtInCommands)
{
CommandProviderWrapper wrapper = new(provider, _taskScheduler);
lock (_commandProvidersLock)
@@ -75,10 +75,10 @@ public partial class TopLevelCommandManager : ObservableObject,
_builtInCommands.Add(wrapper);
}
IEnumerable<TopLevelViewModel> commands = await LoadTopLevelCommandsFromProvider(wrapper);
var commands = await LoadTopLevelCommandsFromProvider(wrapper);
lock (TopLevelCommands)
{
foreach (TopLevelViewModel c in commands)
foreach (var c in commands)
{
TopLevelCommands.Add(c);
}
@@ -99,16 +99,16 @@ public partial class TopLevelCommandManager : ObservableObject,
await commandProvider.LoadTopLevelCommands(_serviceProvider, weakSelf);
List<TopLevelViewModel> commands = await Task.Factory.StartNew(
var commands = await Task.Factory.StartNew(
() =>
{
List<TopLevelViewModel> commands = [];
foreach (TopLevelViewModel item in commandProvider.TopLevelItems)
foreach (var item in commandProvider.TopLevelItems)
{
commands.Add(item);
}
foreach (TopLevelViewModel item in commandProvider.FallbackItems)
foreach (var item in commandProvider.FallbackItems)
{
if (item.IsEnabled)
{
@@ -148,19 +148,19 @@ public partial class TopLevelCommandManager : ObservableObject,
// update to the actual observable list at the end
List<TopLevelViewModel> clone = [.. TopLevelCommands];
List<TopLevelViewModel> newItems = [];
int startIndex = -1;
TopLevelViewModel firstCommand = sender.TopLevelItems[0];
int commandsToRemove = sender.TopLevelItems.Length + sender.FallbackItems.Length;
var startIndex = -1;
var firstCommand = sender.TopLevelItems[0];
var commandsToRemove = sender.TopLevelItems.Length + sender.FallbackItems.Length;
// Tricky: all Commands from a single provider get added to the
// top-level list all together, in a row. So if we find just the first
// one, we can slice it out and insert the new ones there.
for (int i = 0; i < clone.Count; i++)
for (var i = 0; i < clone.Count; i++)
{
TopLevelViewModel wrapper = clone[i];
var wrapper = clone[i];
try
{
bool isTheSame = wrapper == firstCommand;
var isTheSame = wrapper == firstCommand;
if (isTheSame)
{
startIndex = i;
@@ -177,14 +177,14 @@ public partial class TopLevelCommandManager : ObservableObject,
// Fetch the new items
await sender.LoadTopLevelCommands(_serviceProvider, weakSelf);
SettingsModel settings = _serviceProvider.GetService<SettingsModel>()!;
var settings = _serviceProvider.GetService<SettingsModel>()!;
foreach (TopLevelViewModel i in sender.TopLevelItems)
foreach (var i in sender.TopLevelItems)
{
newItems.Add(i);
}
foreach (TopLevelViewModel i in sender.FallbackItems)
foreach (var i in sender.FallbackItems)
{
if (i.IsEnabled)
{
@@ -213,7 +213,7 @@ public partial class TopLevelCommandManager : ObservableObject,
public async Task ReloadAllCommandsAsync()
{
IsLoading = true;
IExtensionService extensionService = _serviceProvider.GetService<IExtensionService>()!;
var extensionService = _serviceProvider.GetService<IExtensionService>()!;
await extensionService.SignalStopExtensionsAsync();
lock (TopLevelCommands)
@@ -235,12 +235,12 @@ public partial class TopLevelCommandManager : ObservableObject,
[RelayCommand]
public async Task<bool> LoadExtensionsAsync()
{
IExtensionService extensionService = _serviceProvider.GetService<IExtensionService>()!;
var extensionService = _serviceProvider.GetService<IExtensionService>()!;
extensionService.OnExtensionAdded -= ExtensionService_OnExtensionAdded;
extensionService.OnExtensionRemoved -= ExtensionService_OnExtensionRemoved;
ImmutableList<IExtensionWrapper> extensions = (await extensionService.GetInstalledExtensionsAsync()).ToImmutableList();
var extensions = (await extensionService.GetInstalledExtensionsAsync()).ToImmutableList();
lock (_commandProvidersLock)
{
_extensionCommandProviders.Clear();
@@ -273,14 +273,14 @@ public partial class TopLevelCommandManager : ObservableObject,
private async Task StartExtensionsAndGetCommands(IEnumerable<IExtensionWrapper> extensions)
{
Stopwatch timer = new Stopwatch();
var timer = new Stopwatch();
timer.Start();
// Start all extensions in parallel
IEnumerable<Task<CommandProviderWrapper?>> startTasks = extensions.Select(StartExtensionWithTimeoutAsync);
var startTasks = extensions.Select(StartExtensionWithTimeoutAsync);
// Wait for all extensions to start
List<CommandProviderWrapper> wrappers = (await Task.WhenAll(startTasks)).Where(wrapper => wrapper != null).Select(w => w!).ToList();
var wrappers = (await Task.WhenAll(startTasks)).Where(wrapper => wrapper != null).Select(w => w!).ToList();
lock (_commandProvidersLock)
{
@@ -288,15 +288,15 @@ public partial class TopLevelCommandManager : ObservableObject,
}
// Load the commands from the providers in parallel
IEnumerable<Task<IEnumerable<TopLevelViewModel>?>> loadTasks = wrappers.Select(LoadCommandsWithTimeoutAsync);
var loadTasks = wrappers.Select(LoadCommandsWithTimeoutAsync);
List<IEnumerable<TopLevelViewModel>> commandSets = (await Task.WhenAll(loadTasks)).Where(results => results != null).Select(r => r!).ToList();
var commandSets = (await Task.WhenAll(loadTasks)).Where(results => results != null).Select(r => r!).ToList();
lock (TopLevelCommands)
{
foreach (IEnumerable<TopLevelViewModel>? commands in commandSets)
foreach (var commands in commandSets)
{
foreach (TopLevelViewModel? c in commands)
foreach (var c in commands)
{
TopLevelCommands.Add(c);
}
@@ -350,11 +350,11 @@ public partial class TopLevelCommandManager : ObservableObject,
List<TopLevelViewModel> commandsToRemove = [];
lock (TopLevelCommands)
{
foreach (IExtensionWrapper extension in extensions)
foreach (var extension in extensions)
{
foreach (TopLevelViewModel command in TopLevelCommands)
foreach (var command in TopLevelCommands)
{
CommandPaletteHost host = command.ExtensionHost;
var host = command.ExtensionHost;
if (host?.Extension == extension)
{
commandsToRemove.Add(command);
@@ -373,7 +373,7 @@ public partial class TopLevelCommandManager : ObservableObject,
{
if (commandsToRemove.Count != 0)
{
foreach (TopLevelViewModel deleted in commandsToRemove)
foreach (var deleted in commandsToRemove)
{
TopLevelCommands.Remove(deleted);
}
@@ -390,7 +390,7 @@ public partial class TopLevelCommandManager : ObservableObject,
{
lock (TopLevelCommands)
{
foreach (TopLevelViewModel command in TopLevelCommands)
foreach (var command in TopLevelCommands)
{
if (command.Id == id)
{
@@ -407,7 +407,7 @@ public partial class TopLevelCommandManager : ObservableObject,
void IPageContext.ShowException(Exception ex, string? extensionHint)
{
string errorMessage = $"A bug occurred in {$"the \"{extensionHint}\"" ?? "an unknown's"} extension's code:\n{ex.Message}\n{ex.Source}\n{ex.StackTrace}\n\n";
var errorMessage = $"A bug occurred in {$"the \"{extensionHint}\"" ?? "an unknown's"} extension's code:\n{ex.Message}\n{ex.Source}\n{ex.StackTrace}\n\n";
CommandPaletteHost.Instance.Log(errorMessage);
}

View File

@@ -1,7 +1,8 @@
// Copyright (c) Microsoft Corporation
// 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.Text.Json.Serialization;
using Microsoft.CmdPal.UI.ViewModels.Settings;
namespace Microsoft.CmdPal.UI.ViewModels;

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -185,7 +185,7 @@ public sealed partial class TopLevelViewModel : ObservableObject, IListItem
if (IsFallback)
{
ICommandItem? model = _commandItemViewModel.Model.Unsafe;
var model = _commandItemViewModel.Model.Unsafe;
// RPC to check type
if (model is IFallbackCommandItem fallback)
@@ -222,7 +222,7 @@ public sealed partial class TopLevelViewModel : ObservableObject, IListItem
public void SetAlias()
{
CommandAlias? commandAlias = Alias is null
var commandAlias = Alias is null
? null
: new CommandAlias(Alias.Alias, Alias.CommandId, Alias.IsDirect);
@@ -232,10 +232,10 @@ public sealed partial class TopLevelViewModel : ObservableObject, IListItem
private void FetchAliasFromAliasManager()
{
AliasManager? am = _serviceProvider.GetService<AliasManager>();
var am = _serviceProvider.GetService<AliasManager>();
if (am != null)
{
CommandAlias? commandAlias = am.AliasFromId(Id);
var commandAlias = am.AliasFromId(Id);
if (commandAlias is not null)
{
// Decouple from the alias manager alias object
@@ -246,7 +246,7 @@ public sealed partial class TopLevelViewModel : ObservableObject, IListItem
private void UpdateHotkey()
{
TopLevelHotkey? hotkey = _settings.CommandHotkeys.Where(hk => hk.CommandId == Id).FirstOrDefault();
var hotkey = _settings.CommandHotkeys.Where(hk => hk.CommandId == Id).FirstOrDefault();
if (hotkey != null)
{
_hotkey = hotkey.Hotkey;
@@ -279,13 +279,13 @@ public sealed partial class TopLevelViewModel : ObservableObject, IListItem
{
// Use WyHash64 to generate stable ID hashes.
// manually seeding with 0, so that the hash is stable across launches
ulong result = WyHash64.ComputeHash64(_commandProviderId + DisplayTitle + Title + Subtitle, seed: 0);
var result = WyHash64.ComputeHash64(_commandProviderId + DisplayTitle + Title + Subtitle, seed: 0);
_generatedId = $"{_commandProviderId}{result}";
}
private void DoOnUiThread(Action action)
{
if (_commandItemViewModel.PageContext.TryGetTarget(out IPageContext? pageContext))
if (_commandItemViewModel.PageContext.TryGetTarget(out var pageContext))
{
Task.Factory.StartNew(
action,
@@ -327,16 +327,16 @@ public sealed partial class TopLevelViewModel : ObservableObject, IListItem
/// <returns>true if our Title changed across this call</returns>
private bool UnsafeUpdateFallbackSynchronous(string newQuery)
{
ICommandItem? model = _commandItemViewModel.Model.Unsafe;
var model = _commandItemViewModel.Model.Unsafe;
// RPC to check type
if (model is IFallbackCommandItem fallback)
{
bool wasEmpty = string.IsNullOrEmpty(Title);
var wasEmpty = string.IsNullOrEmpty(Title);
// RPC for method
fallback.FallbackHandler.UpdateQuery(newQuery);
bool isEmpty = string.IsNullOrEmpty(Title);
var isEmpty = string.IsNullOrEmpty(Title);
return wasEmpty != isEmpty;
}

View File

@@ -81,7 +81,7 @@ public partial class App : Application
{
AppWindow = new MainWindow();
Windows.AppLifecycle.AppActivationArguments activatedEventArgs = Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().GetActivatedEventArgs();
var activatedEventArgs = Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().GetActivatedEventArgs();
((MainWindow)AppWindow).HandleLaunch(activatedEventArgs);
}
@@ -97,11 +97,8 @@ public partial class App : Application
services.AddSingleton(TaskScheduler.FromCurrentSynchronizationContext());
// Built-in Commands. Order matters - this is the order they'll be presented by default.
#pragma warning disable CA2000 // Dispose objects before losing scope
// justification: these two live for the life of the app
AllAppsCommandProvider allApps = new AllAppsCommandProvider();
IndexerCommandsProvider files = new IndexerCommandsProvider();
#pragma warning restore CA2000 // Dispose objects before losing scope
var allApps = new AllAppsCommandProvider();
var files = new IndexerCommandsProvider();
files.SuppressFallbackWhen(ShellCommandsProvider.SuppressFileFallbackIf);
services.AddSingleton<ICommandProvider>(allApps);
@@ -121,11 +118,8 @@ public partial class App : Application
// for WinGetStatics
try
{
#pragma warning disable CA2000 // Dispose objects before losing scope
// justification: lives for the life of the app
WinGetExtensionCommandsProvider winget = new WinGetExtensionCommandsProvider();
#pragma warning restore CA2000 // Dispose objects before losing scope
Func<string, ICommandItem?> callback = allApps.LookupApp;
var winget = new WinGetExtensionCommandsProvider();
var callback = allApps.LookupApp;
winget.SetAllLookup(callback);
services.AddSingleton<ICommandProvider>(winget);
}
@@ -147,9 +141,9 @@ public partial class App : Application
services.AddSingleton<TopLevelCommandManager>();
services.AddSingleton<AliasManager>();
services.AddSingleton<HotkeyManager>();
SettingsModel sm = SettingsModel.LoadSettings();
var sm = SettingsModel.LoadSettings();
services.AddSingleton(sm);
AppStateModel state = AppStateModel.LoadState();
var state = AppStateModel.LoadState();
services.AddSingleton(state);
services.AddSingleton<IExtensionService, ExtensionService>();
services.AddSingleton<TrayIconService>();

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -95,7 +95,7 @@ public sealed partial class CommandBar : UserControl,
return;
}
ContextKeybindingResult? result = ViewModel?.CheckKeybinding(msg.Ctrl, msg.Alt, msg.Shift, msg.Win, msg.Key);
var result = ViewModel?.CheckKeybinding(msg.Ctrl, msg.Alt, msg.Shift, msg.Win, msg.Key);
if (result == ContextKeybindingResult.Hide)
{

View File

@@ -38,7 +38,7 @@ public sealed partial class ContentFormControl : UserControl
public ContentFormControl()
{
this.InitializeComponent();
bool lightTheme = ActualTheme == Microsoft.UI.Xaml.ElementTheme.Light;
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,
@@ -66,7 +66,7 @@ public sealed partial class ContentFormControl : UserControl
{
_viewModel.PropertyChanged += ViewModel_PropertyChanged;
AdaptiveCardParseResult? c = _viewModel.Card;
var c = _viewModel.Card;
if (c != null)
{
DisplayCard(c);
@@ -83,7 +83,7 @@ public sealed partial class ContentFormControl : UserControl
if (e.PropertyName == nameof(ViewModel.Card))
{
AdaptiveCardParseResult? c = ViewModel.Card;
var c = ViewModel.Card;
if (c != null)
{
DisplayCard(c);
@@ -121,7 +121,7 @@ public sealed partial class ContentFormControl : UserControl
// Focus on the first focusable element asynchronously to ensure the visual tree is fully built
element.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
{
Control? focusableElement = FindFirstFocusableElement(element);
var focusableElement = FindFirstFocusableElement(element);
focusableElement?.Focus(FocusState.Programmatic);
});
}
@@ -129,12 +129,12 @@ public sealed partial class ContentFormControl : UserControl
private Control? FindFirstFocusableElement(DependencyObject parent)
{
int childCount = VisualTreeHelper.GetChildrenCount(parent);
var childCount = VisualTreeHelper.GetChildrenCount(parent);
// Process children first (depth-first search)
for (int i = 0; i < childCount; i++)
for (var i = 0; i < childCount; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is a focusable control like TextBox, ComboBox, etc.
if (child is Control control &&
@@ -147,7 +147,7 @@ public sealed partial class ContentFormControl : UserControl
}
// Recursively check children
Control? result = FindFirstFocusableElement(child);
var result = FindFirstFocusableElement(child);
if (result != null)
{
return result;

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -48,7 +48,7 @@ public sealed partial class ContextMenu : UserControl,
public void Receive(TryCommandKeybindingMessage msg)
{
ContextKeybindingResult? result = ViewModel?.CheckKeybinding(msg.Ctrl, msg.Alt, msg.Shift, msg.Win, msg.Key);
var result = ViewModel?.CheckKeybinding(msg.Ctrl, msg.Alt, msg.Shift, msg.Win, msg.Key);
if (result == ContextKeybindingResult.Hide)
{
@@ -87,13 +87,13 @@ public sealed partial class ContextMenu : UserControl,
return;
}
bool ctrlPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
bool altPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Menu).HasFlag(CoreVirtualKeyStates.Down);
bool shiftPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down);
bool winPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.LeftWindows).HasFlag(CoreVirtualKeyStates.Down) ||
var ctrlPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
var altPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Menu).HasFlag(CoreVirtualKeyStates.Down);
var shiftPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down);
var winPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.LeftWindows).HasFlag(CoreVirtualKeyStates.Down) ||
InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.RightWindows).HasFlag(CoreVirtualKeyStates.Down);
ContextKeybindingResult? result = ViewModel?.CheckKeybinding(ctrlPressed, altPressed, shiftPressed, winPressed, e.Key);
var result = ViewModel?.CheckKeybinding(ctrlPressed, altPressed, shiftPressed, winPressed, e.Key);
if (result == ContextKeybindingResult.Hide)
{
@@ -113,7 +113,7 @@ public sealed partial class ContextMenu : UserControl,
private void ViewModel_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
string? prop = e.PropertyName;
var prop = e.PropertyName;
if (prop == nameof(ContextMenuViewModel.FilteredItems))
{
@@ -133,10 +133,10 @@ public sealed partial class ContextMenu : UserControl,
private void ContextFilterBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
bool ctrlPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
bool altPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Menu).HasFlag(CoreVirtualKeyStates.Down);
bool shiftPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down);
bool winPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.LeftWindows).HasFlag(CoreVirtualKeyStates.Down) ||
var ctrlPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
var altPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Menu).HasFlag(CoreVirtualKeyStates.Down);
var shiftPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down);
var winPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.LeftWindows).HasFlag(CoreVirtualKeyStates.Down) ||
InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.RightWindows).HasFlag(CoreVirtualKeyStates.Down);
if (e.Key == VirtualKey.Enter)
@@ -192,7 +192,7 @@ public sealed partial class ContextMenu : UserControl,
private void NavigateUp()
{
int newIndex = CommandsDropdown.SelectedIndex;
var newIndex = CommandsDropdown.SelectedIndex;
if (CommandsDropdown.SelectedIndex > 0)
{
@@ -229,7 +229,7 @@ public sealed partial class ContextMenu : UserControl,
private void NavigateDown()
{
int newIndex = CommandsDropdown.SelectedIndex;
var newIndex = CommandsDropdown.SelectedIndex;
if (CommandsDropdown.SelectedIndex == CommandsDropdown.Items.Count - 1)
{

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -101,8 +101,8 @@ public partial class IconBox : ContentControl
// _ = @this._queue.EnqueueAsync(() =>
@this._queue.TryEnqueue(new(async () =>
{
ElementTheme requestedTheme = @this.ActualTheme;
SourceRequestedEventArgs eventArgs = new SourceRequestedEventArgs(e.NewValue, requestedTheme);
var requestedTheme = @this.ActualTheme;
var eventArgs = new SourceRequestedEventArgs(e.NewValue, requestedTheme);
if (@this.SourceRequested != null)
{
@@ -147,12 +147,12 @@ public partial class IconBox : ContentControl
{
if (!string.IsNullOrEmpty(iconData.Icon) && iconData.Icon.Length <= 2)
{
char ch = iconData.Icon[0];
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
bool isMDL2Icon = ch is >= '\uE700' and <= '\uF8FF';
var isMDL2Icon = ch is >= '\uE700' and <= '\uF8FF';
if (!isMDL2Icon)
{
@this.Padding = new Thickness(-4);

View File

@@ -1,7 +1,8 @@
// Copyright (c) Microsoft Corporation
// 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;
@@ -109,37 +110,27 @@ public sealed partial class KeyVisual : Control
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 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
PathIcon? winIcon = XamlReader.Load(@"<PathIcon xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" Data=""M683 1229H0V546h683v683zm819 0H819V546h683v683zm-819 819H0v-683h683v683zm819 0H819v-683h683v683z"" />") as PathIcon;
Viewbox winIconContainer = new Viewbox
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,
};
double iconDimensions = GetIconSize();
var iconDimensions = GetIconSize();
winIconContainer.Height = iconDimensions;
winIconContainer.Width = iconDimensions;
_keyVisual._keyPresenter.Content = winIconContainer;
break;
default:
_keyVisual._keyPresenter.Content = ((VirtualKey)_keyVisual.Content).ToString();
break;
default: _keyVisual._keyPresenter.Content = ((VirtualKey)_keyVisual.Content).ToString(); break;
}
}
}

View File

@@ -48,7 +48,7 @@ public sealed partial class SearchBar : UserControl,
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...
SearchBar? @this = (SearchBar)d;
var @this = (SearchBar)d;
if (@this != null
&& e.OldValue is PageViewModel old)
@@ -108,10 +108,10 @@ public sealed partial class SearchBar : UserControl,
return;
}
bool ctrlPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
bool altPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Menu).HasFlag(CoreVirtualKeyStates.Down);
bool shiftPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down);
bool winPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.LeftWindows).HasFlag(CoreVirtualKeyStates.Down) ||
var ctrlPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
var altPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Menu).HasFlag(CoreVirtualKeyStates.Down);
var shiftPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down);
var winPressed = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.LeftWindows).HasFlag(CoreVirtualKeyStates.Down) ||
InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.RightWindows).HasFlag(CoreVirtualKeyStates.Down);
if (ctrlPressed && e.Key == VirtualKey.Enter)
{
@@ -232,7 +232,7 @@ public sealed partial class SearchBar : UserControl,
return;
}
bool ignoreLeave =
var ignoreLeave =
e.Key == VirtualKey.Up ||
e.Key == VirtualKey.Down ||
@@ -320,7 +320,7 @@ public sealed partial class SearchBar : UserControl,
// Used to handle the case when a ListPage's `SearchText` may have changed
private void Page_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
string? property = e.PropertyName;
var property = e.PropertyName;
if (CurrentPageViewModel is ListViewModel list)
{
@@ -356,11 +356,11 @@ public sealed partial class SearchBar : UserControl,
public void Receive(UpdateSuggestionMessage message)
{
string suggestion = message.TextToSuggest;
var suggestion = message.TextToSuggest;
_queue.TryEnqueue(new(() =>
{
bool clearSuggestion = string.IsNullOrEmpty(suggestion);
var clearSuggestion = string.IsNullOrEmpty(suggestion);
if (clearSuggestion && _inSuggestion)
{
@@ -386,7 +386,7 @@ public sealed partial class SearchBar : UserControl,
_deletedSuggestion = null;
}
string currentText = _lastText ?? FilterBox.Text;
var currentText = _lastText ?? FilterBox.Text;
_lastText = currentText;
@@ -400,10 +400,10 @@ public sealed partial class SearchBar : UserControl,
// }
_inSuggestion = true;
int matchedChars = 0;
bool suggestionStartsWithQuote = suggestion.Length > 0 && suggestion[0] == '"';
bool currentStartsWithQuote = currentText.Length > 0 && currentText[0] == '"';
bool skipCheckingFirst = suggestionStartsWithQuote && !currentStartsWithQuote;
var matchedChars = 0;
var suggestionStartsWithQuote = suggestion.Length > 0 && suggestion[0] == '"';
var currentStartsWithQuote = currentText.Length > 0 && currentText[0] == '"';
var skipCheckingFirst = suggestionStartsWithQuote && !currentStartsWithQuote;
for (int i = skipCheckingFirst ? 1 : 0, j = 0;
i < suggestion.Length && j < currentText.Length;
i++, j++)
@@ -421,18 +421,18 @@ public sealed partial class SearchBar : UserControl,
}
}
string first = skipCheckingFirst ? "\"" : string.Empty;
ReadOnlySpan<char> second = currentText.AsSpan(0, matchedChars);
ReadOnlySpan<char> third = suggestion.AsSpan(matchedChars + (skipCheckingFirst ? 1 : 0));
var first = skipCheckingFirst ? "\"" : string.Empty;
var second = currentText.AsSpan(0, matchedChars);
var third = suggestion.AsSpan(matchedChars + (skipCheckingFirst ? 1 : 0));
string newText = string.Concat(
var newText = string.Concat(
first,
second,
third);
FilterBox.Text = newText;
bool wrappedInQuotes = suggestionStartsWithQuote && suggestion.Last() == '"';
var wrappedInQuotes = suggestionStartsWithQuote && suggestion.Last() == '"';
if (wrappedInQuotes)
{
FilterBox.Select(

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -1,7 +1,8 @@
// Copyright (c) Microsoft Corporation
// 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;
@@ -15,7 +16,10 @@ internal static class NativeKeyboardHelper
internal INPUTTYPE type;
internal InputUnion data;
internal static int Size => Marshal.SizeOf<INPUT>();
internal static int Size
{
get { return Marshal.SizeOf<INPUT>(); }
}
}
[StructLayout(LayoutKind.Explicit)]

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -17,8 +17,8 @@ public static partial class NativeMethods
internal const int SW_SHOWMAXIMIZED = 3;
internal const int SW_HIDE = 0;
[LibraryImport("user32.dll")]
internal static partial IntPtr GetActiveWindow();
[DllImport("user32.dll")]
internal static extern IntPtr GetActiveWindow();
[DllImport("user32.dll")]
internal static extern bool SetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
@@ -32,25 +32,25 @@ public static partial class NativeMethods
[LibraryImport("user32.dll")]
internal static partial short GetAsyncKeyState(int vKey);
[LibraryImport("user32.dll", SetLastError = true)]
internal static partial int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[LibraryImport("user32.dll")]
internal static partial int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[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);
[LibraryImport("shell32.dll")]
internal static partial int SHGetPathFromIDListW(IntPtr pidl, IntPtr pszPath);
[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(nint hWnd, int nCmdShow);
public static extern bool ShowWindow(System.IntPtr hWnd, int nCmdShow);
[LibraryImport("user32.dll")]
public static partial int GetDpiForWindow(nint hWnd);
[DllImport("user32.dll")]
public static extern int GetDpiForWindow(System.IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool IsWindowVisible(IntPtr hWnd);
@@ -61,8 +61,8 @@ public static partial class NativeMethods
[System.Runtime.InteropServices.DllImport("User32.dll")]
public static extern bool SetForegroundWindow(IntPtr handle);
[LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16)]
public static partial IntPtr LoadLibrary(string dllToLoad);
[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);

View File

@@ -1,7 +1,8 @@
// Copyright (c) Microsoft Corporation
// 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

View File

@@ -1,7 +1,8 @@
// Copyright (c) Microsoft Corporation
// 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

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.
@@ -38,21 +38,21 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
private static void OnAllowDisableChanged(DependencyObject d, DependencyPropertyChangedEventArgs? e)
{
ShortcutControl? me = d as ShortcutControl;
var me = d as ShortcutControl;
if (me == null)
{
return;
}
TextBlock? description = me.c?.FindDescendant<TextBlock>();
var description = me.c?.FindDescendant<TextBlock>();
if (description == null)
{
return;
}
Windows.ApplicationModel.Resources.ResourceLoader resourceLoader = Microsoft.CmdPal.UI.Helpers.ResourceLoaderInstance.ResourceLoader;
bool newValue = (bool)(e?.NewValue ?? false);
string text = newValue ?
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;
@@ -69,7 +69,10 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
public bool Enabled
{
get => _enabled;
get
{
return _enabled;
}
set
{
@@ -82,7 +85,10 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
public HotkeySettings? HotkeySettings
{
get => hotkeySettings;
get
{
return hotkeySettings;
}
set
{
@@ -102,7 +108,7 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
InitializeComponent();
internalSettings = new HotkeySettings();
Windows.ApplicationModel.Resources.ResourceLoader resourceLoader = Microsoft.CmdPal.UI.Helpers.ResourceLoaderInstance.ResourceLoader;
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
@@ -169,7 +175,7 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
private void KeyEventHandler(int key, bool matchValue, int matchValueCode)
{
VirtualKey virtualKey = (VirtualKey)key;
var virtualKey = (VirtualKey)key;
switch (virtualKey)
{
case VirtualKey.LeftWindows:
@@ -228,7 +234,7 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
// 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)
{
NativeKeyboardHelper.INPUT inputShift = new NativeKeyboardHelper.INPUT
var inputShift = new NativeKeyboardHelper.INPUT
{
type = NativeKeyboardHelper.INPUTTYPE.INPUT_KEYBOARD,
data = new NativeKeyboardHelper.InputUnion
@@ -442,7 +448,7 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
return;
}
HotkeySettings empty = new HotkeySettings();
var empty = new HotkeySettings();
HotkeySettings = empty;
PreviewKeysControl.ItemsSource = HotkeySettings.GetKeysList();
@@ -484,7 +490,10 @@ public sealed partial class ShortcutControl : UserControl, IDisposable, IRecipie
{
if (disposing)
{
hook?.Dispose();
if (hook != null)
{
hook.Dispose();
}
hook = null;
}

View File

@@ -1,7 +1,8 @@
// Copyright (c) Microsoft Corporation
// 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;
@@ -16,7 +17,8 @@ public sealed partial class ShortcutDialogContentControl : UserControl
public List<object> Keys
{
get => (List<object>)GetValue(KeysProperty); set => SetValue(KeysProperty, value);
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)));

View File

@@ -1,7 +1,9 @@
// Copyright (c) Microsoft Corporation
// 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;
@@ -11,14 +13,16 @@ namespace Microsoft.CmdPal.UI.Controls
{
public string Text
{
get => (string)GetValue(TextProperty); set => SetValue(TextProperty, value);
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 => (List<object>)GetValue(KeysProperty); set => SetValue(KeysProperty, value);
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)));

View File

@@ -1,7 +1,8 @@
// Copyright (c) Microsoft Corporation
// 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

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

View File

@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation
// 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.

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