Skip to content

A Swiss Army knife for developers.

Added Monaco editor to DevToys (#19)

Etienne Baudoux5b2a5e0ac2ff
diff --git a/.gitignore b/.gitignore
index d40420dab..ee5c567d0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -36,6 +36,13 @@ Generated\ Files/
# Assembly Info file that is automatically updated on build
SharedAssemblyInfo.cs
+# TypeScript ignores
+*.js
+*.js.map
+
+# Monaco Dependency (Download from https://microsoft.github.io/monaco-editor/)
+src/dev/impl/DevToys.MonacoEditor/monaco-editor
+
# NUNIT
*.VisualState.xml
TestResult.xml
diff --git a/.vsconfig b/.vsconfig
index 6ba3f91f2..2a18ba6de 100644
--- a/.vsconfig
+++ b/.vsconfig
@@ -9,6 +9,9 @@
"Microsoft.VisualStudio.Component.NuGet",
"Microsoft.VisualStudio.Component.Roslyn.Compiler",
"Microsoft.VisualStudio.Component.Roslyn.LanguageServices",
+ "Microsoft.VisualStudio.ComponentGroup.WebToolsExtensions",
+ "Microsoft.VisualStudio.Component.TypeScript.4.3",
+ "Microsoft.VisualStudio.Component.JavaScript.TypeScript",
"Microsoft.Component.MSBuild",
"Microsoft.VisualStudio.Component.TextTemplating",
"Microsoft.VisualStudio.Component.SQL.CLR",
@@ -17,6 +20,7 @@
"Microsoft.VisualStudio.Component.AppInsights.Tools",
"Microsoft.VisualStudio.Component.IntelliCode",
"Microsoft.VisualStudio.Component.Windows10SDK.19041",
+ "Microsoft.VisualStudio.Component.Node.Tools",
"Microsoft.ComponentGroup.Blend",
"Microsoft.VisualStudio.ComponentGroup.MSIX.Packaging",
"Microsoft.Component.NetFX.Native",
@@ -25,7 +29,6 @@
"Microsoft.VisualStudio.ComponentGroup.UWP.Xamarin",
"Microsoft.VisualStudio.ComponentGroup.UWP.Support",
"Microsoft.VisualStudio.Workload.Universal",
- "Component.GitHub.VisualStudio",
"Microsoft.VisualStudio.Component.Git"
]
}
\ No newline at end of file
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index 9bb291e1d..399b42cf5 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -3,12 +3,14 @@ THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
This project incorporates components from the projects listed below. The original copyright notices and the licenses under which Etienne Baudoux received such components are set forth below. Etienne Baudoux reserves all rights not expressly granted herein, whether by implication, estoppel or otherwise.
1. Newtonsoft.Json (https://github.com/JamesNK/Newtonsoft.Json)
-2. ColorCode-Universal (https://github.com/CommunityToolkit/ColorCode-Universal)
-3. DiffPlex (https://github.com/mmanela/diffplex)
4. GitInfo (https://github.com/devlooped/GitInfo)
5. Windows Community Toolkit (https://github.com/CommunityToolkit/WindowsCommunityToolkit)
6. Notepads App (https://github.com/JasonStein/Notepads)
7. YamlDotNet (https://github.com/aaubry/YamlDotNet)
+8. Fluent UI System Icons (https://github.com/microsoft/fluentui-system-icons)
+9. Monaco Editor (https://github.com/Microsoft/monaco-editor)
+10. Monaco Editor UWP (https://github.com/hawkerm/monaco-editor-uwp)
+11. Observable Vector (https://github.com/jamesqo/observable-vector)
Newtonsoft.Json NOTICES AND INFORMATION BEGIN HERE
=========================================
@@ -33,110 +35,6 @@ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-ColorCode-Universal NOTICES AND INFORMATION BEGIN HERE
-=========================================
-# Microsoft Public License (Ms-PL)
-
-This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
-
-1. Definitions
-
- The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
-
- A "contribution" is the original software, or any additions or changes to the software.
-
- A "contributor" is any person that distributes its contribution under this license.
-
- "Licensed patents" are a contributor's patent claims that read directly on its contribution.
-
-2. Grant of Rights
-
- (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
-
- (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
-
-3. Conditions and Limitations
-
- (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
-
- (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
-
- (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
-
- (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
-
- (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
-
-DiffPlex NOTICES AND INFORMATION BEGIN HERE
-=========================================
-Apache License
-Version 2.0, January 2004
-http://www.apache.org/licenses/
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
-"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
-
-"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
-
-"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
-
-"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
-
-"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
-
-"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
-
-"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
-
-"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
-
-"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
-
-"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
-
-2. Grant of Copyright License.
-
-Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
-
-3. Grant of Patent License.
-
-Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
-
-4. Redistribution.
-
-You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
-
-You must give any other recipients of the Work or Derivative Works a copy of this License; and
-You must cause any modified files to carry prominent notices stating that You changed the files; and
-You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
-If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
-You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
-
-5. Submission of Contributions.
-
-Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
-
-6. Trademarks.
-
-This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty.
-
-Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
-
-8. Limitation of Liability.
-
-In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability.
-
-While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
-
GitInfo NOTICES AND INFORMATION BEGIN HERE
=========================================
The MIT License (MIT)
@@ -215,6 +113,76 @@ so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+Fluent UI System Icons NOTICES AND INFORMATION BEGIN HERE
+=========================================
+MIT License
+
+Copyright (c) 2020 Microsoft Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+Monaco Editor NOTICES AND INFORMATION BEGIN HERE
+=========================================
+The MIT License (MIT)
+
+Copyright (c) 2016 - present Microsoft Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Monaco Editor UWP NOTICES AND INFORMATION BEGIN HERE
+=========================================
+Copyright 2017 Michael A. Hawker
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Observable Vector NOTICES AND INFORMATION BEGIN HERE
+=========================================
+The MIT License (MIT)
+
+Copyright (c) 2016 James Ko
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
diff --git a/init.ps1 b/init.ps1
index 8108bd168..f62544994 100644
--- a/init.ps1
+++ b/init.ps1
@@ -15,6 +15,12 @@ Function Restore-PackagesUnder($searchRoot) {
}
}
+Function Restore-MonacoEditor() {
+ # Restore Monaco Editor
+ Write-Host "Restoring Monaco Editor..." -ForegroundColor $HeaderColor
+ & "$toolsPath\Restore-MonacoEditor.ps1"
+}
+
Push-Location $PSScriptRoot
try {
$EnvVarsSet = $false
@@ -26,6 +32,8 @@ try {
Restore-PackagesUnder "$PSScriptRoot\src"
+ Restore-MonacoEditor
+
Write-Host "Successfully restored all dependencies" -ForegroundColor Yellow
}
catch {
diff --git a/src/DevToys.sln b/src/DevToys.sln
index 4c72f757f..2f46acf51 100644
--- a/src/DevToys.sln
+++ b/src/DevToys.sln
@@ -36,12 +36,16 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "shared", "shared", "{EE2227
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevToys.Tests", "tests\DevToys.Tests\DevToys.Tests.csproj", "{E1C4AB49-CFFF-420E-A182-E3028BD0493C}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevToys.MonacoEditor", "dev\impl\DevToys.MonacoEditor\DevToys.MonacoEditor.csproj", "{0FE678BB-9F9B-4495-B777-F9B1E11DA20C}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM
+ Debug|ARM64 = Debug|ARM64
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|ARM = Release|ARM
+ Release|ARM64 = Release|ARM64
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
@@ -49,6 +53,7 @@ Global
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Debug|ARM.ActiveCfg = Debug|ARM
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Debug|ARM.Build.0 = Debug|ARM
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Debug|ARM.Deploy.0 = Debug|ARM
+ {361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Debug|ARM64.ActiveCfg = Debug|x86
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Debug|x64.ActiveCfg = Debug|x64
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Debug|x64.Build.0 = Debug|x64
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Debug|x64.Deploy.0 = Debug|x64
@@ -58,6 +63,7 @@ Global
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Release|ARM.ActiveCfg = Release|ARM
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Release|ARM.Build.0 = Release|ARM
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Release|ARM.Deploy.0 = Release|ARM
+ {361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Release|ARM64.ActiveCfg = Release|x86
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Release|x64.ActiveCfg = Release|x64
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Release|x64.Build.0 = Release|x64
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Release|x64.Deploy.0 = Release|x64
@@ -66,12 +72,14 @@ Global
{361DB7BC-BE7B-41A2-A29A-978A9E3B4AA7}.Release|x86.Deploy.0 = Release|x86
{E3E4E200-B380-4207-9A7E-4C9421904502}.Debug|ARM.ActiveCfg = Debug|ARM
{E3E4E200-B380-4207-9A7E-4C9421904502}.Debug|ARM.Build.0 = Debug|ARM
+ {E3E4E200-B380-4207-9A7E-4C9421904502}.Debug|ARM64.ActiveCfg = Debug|x86
{E3E4E200-B380-4207-9A7E-4C9421904502}.Debug|x64.ActiveCfg = Debug|x64
{E3E4E200-B380-4207-9A7E-4C9421904502}.Debug|x64.Build.0 = Debug|x64
{E3E4E200-B380-4207-9A7E-4C9421904502}.Debug|x86.ActiveCfg = Debug|x86
{E3E4E200-B380-4207-9A7E-4C9421904502}.Debug|x86.Build.0 = Debug|x86
{E3E4E200-B380-4207-9A7E-4C9421904502}.Release|ARM.ActiveCfg = Release|ARM
{E3E4E200-B380-4207-9A7E-4C9421904502}.Release|ARM.Build.0 = Release|ARM
+ {E3E4E200-B380-4207-9A7E-4C9421904502}.Release|ARM64.ActiveCfg = Release|x86
{E3E4E200-B380-4207-9A7E-4C9421904502}.Release|x64.ActiveCfg = Release|x64
{E3E4E200-B380-4207-9A7E-4C9421904502}.Release|x64.Build.0 = Release|x64
{E3E4E200-B380-4207-9A7E-4C9421904502}.Release|x86.ActiveCfg = Release|x86
@@ -79,6 +87,7 @@ Global
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Debug|ARM.ActiveCfg = Debug|ARM
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Debug|ARM.Build.0 = Debug|ARM
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Debug|ARM.Deploy.0 = Debug|ARM
+ {E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Debug|ARM64.ActiveCfg = Debug|x86
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Debug|x64.ActiveCfg = Debug|x64
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Debug|x64.Build.0 = Debug|x64
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Debug|x64.Deploy.0 = Debug|x64
@@ -88,12 +97,29 @@ Global
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Release|ARM.ActiveCfg = Release|ARM
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Release|ARM.Build.0 = Release|ARM
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Release|ARM.Deploy.0 = Release|ARM
+ {E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Release|ARM64.ActiveCfg = Release|x86
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Release|x64.ActiveCfg = Release|x64
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Release|x64.Build.0 = Release|x64
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Release|x64.Deploy.0 = Release|x64
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Release|x86.ActiveCfg = Release|x86
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Release|x86.Build.0 = Release|x86
{E1C4AB49-CFFF-420E-A182-E3028BD0493C}.Release|x86.Deploy.0 = Release|x86
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Debug|ARM.ActiveCfg = Debug|ARM
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Debug|ARM.Build.0 = Debug|ARM
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Debug|ARM64.ActiveCfg = Debug|ARM64
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Debug|ARM64.Build.0 = Debug|ARM64
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Debug|x64.ActiveCfg = Debug|x64
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Debug|x64.Build.0 = Debug|x64
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Debug|x86.ActiveCfg = Debug|x86
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Debug|x86.Build.0 = Debug|x86
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Release|ARM.ActiveCfg = Release|ARM
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Release|ARM.Build.0 = Release|ARM
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Release|ARM64.ActiveCfg = Release|ARM64
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Release|ARM64.Build.0 = Release|ARM64
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Release|x64.ActiveCfg = Release|x64
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Release|x64.Build.0 = Release|x64
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Release|x86.ActiveCfg = Release|x86
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -104,6 +130,7 @@ Global
{E3E4E200-B380-4207-9A7E-4C9421904502} = {93B72B9C-08BA-4838-9163-3ED67EC3EB9F}
{EE2227BC-954E-4053-AE38-4AE7A391AEEA} = {2C2B8C64-7BA1-4244-86E1-48CA7D85D7D9}
{E1C4AB49-CFFF-420E-A182-E3028BD0493C} = {F8A9E843-7AC1-414A-8F27-A8F416D2D489}
+ {0FE678BB-9F9B-4495-B777-F9B1E11DA20C} = {93B72B9C-08BA-4838-9163-3ED67EC3EB9F}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {78B10789-385B-4F7D-8E06-D86143CD76B5}
diff --git a/src/Directory.Build.props b/src/Directory.Build.props
index 3b90dc2d2..05cb25b19 100644
--- a/src/Directory.Build.props
+++ b/src/Directory.Build.props
@@ -21,19 +21,21 @@
</PropertyGroup>
<PropertyGroup>
- <Nuget_ColorCodeUwp>2.0.6</Nuget_ColorCodeUwp>
- <Nuget_DiffPlex>1.7.0</Nuget_DiffPlex>
<Nuget_GitInfo>2.2.0</Nuget_GitInfo>
<NuGet_MicrosoftNETCoreUniversalWindowsPlatform>6.2.12</NuGet_MicrosoftNETCoreUniversalWindowsPlatform>
<NuGet_MicrosoftToolkitMvvm>7.0.2</NuGet_MicrosoftToolkitMvvm>
+ <Nuget_MicrosoftToolkitUwpUI>7.0.2</Nuget_MicrosoftToolkitUwpUI>
<Nuget_MicrosoftToolkitUwpUIBehaviors>7.0.2</Nuget_MicrosoftToolkitUwpUIBehaviors>
<Nuget_MicrosoftToolkitUwpUIControls>7.0.2</Nuget_MicrosoftToolkitUwpUIControls>
+ <Nuget_MicrosoftTypeScriptMSBuild>4.4.2</Nuget_MicrosoftTypeScriptMSBuild>
<NuGet_MicrosoftUIXaml>2.6.2</NuGet_MicrosoftUIXaml>
<NuGet_MicrosoftWindowsSDKBuildTools>10.0.20348.19</NuGet_MicrosoftWindowsSDKBuildTools>
<NuGet_MSTestTestAdapter>2.1.1</NuGet_MSTestTestAdapter>
<NuGet_MSTestTestFramework>2.1.1</NuGet_MSTestTestFramework>
<NuGet_NewtonsoftJson>12.0.3</NuGet_NewtonsoftJson>
+ <Nuget_ObservableVector>2.1.0</Nuget_ObservableVector>
<NuGet_SystemComposition>5.0.0</NuGet_SystemComposition>
+ <NuGet_Win2D>1.26.0</NuGet_Win2D>
<NuGet_YamlDotNet>11.2.1</NuGet_YamlDotNet>
</PropertyGroup>
</Project>
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/CodeEditorControl/CodeEditorCore.cs b/src/dev/impl/DevToys.MonacoEditor/CodeEditorControl/CodeEditorCore.cs
new file mode 100644
index 000000000..6defa1070
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/CodeEditorControl/CodeEditorCore.cs
@@ -0,0 +1,1088 @@
+#nullable enable
+
+using Collections.Generic;
+using DevToys.MonacoEditor.Extensions;
+using DevToys.MonacoEditor.Helpers;
+using DevToys.MonacoEditor.Monaco;
+using DevToys.MonacoEditor.Monaco.Editor;
+using DevToys.MonacoEditor.Monaco.Helpers;
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices.WindowsRuntime;
+using System.Threading;
+using System.Threading.Tasks;
+using Windows.Foundation;
+using Windows.Foundation.Collections;
+using Windows.UI.Xaml;
+using Windows.UI.Xaml.Controls;
+using Windows.UI.Xaml.Input;
+
+namespace DevToys.MonacoEditor.CodeEditorControl
+{
+ /// <summary>
+ /// Action delegate for <see cref="CodeEditorCore.AddCommandAsync(int, CommandHandler)"/> and <see cref="CodeEditorCore.AddCommandAsync(int, CommandHandler, string)"/>.
+ /// </summary>
+ public delegate void CommandHandler();
+
+ /// <summary>
+ /// UWP Windows Runtime Component wrapper for the Monaco CodeEditorCore
+ /// https://microsoft.github.io/monaco-editor/
+ /// This file contains Monaco IEditor method implementations we can call on our control.
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.ieditor.html
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.icommoncodeeditor.html
+ /// </summary>
+ [TemplatePart(Name = "WebViewElement", Type = typeof(WebView))]
+ [TemplateVisualState(Name = NormalState, GroupName = CommonStates)]
+ [TemplateVisualState(Name = PointerOverState, GroupName = CommonStates)]
+ [TemplateVisualState(Name = FocusedState, GroupName = CommonStates)]
+ [TemplateVisualState(Name = DisabledState, GroupName = CommonStates)]
+ public sealed partial class CodeEditorCore : Control, IDisposable, IParentAccessorAcceptor
+ {
+ internal const string CommonStates = "CommonStates";
+ internal const string NormalState = "Normal";
+ internal const string PointerOverState = "PointerOver";
+ internal const string FocusedState = "Focused";
+ internal const string DisabledState = "Disabled";
+
+ private readonly DisposableSempahore _mutexMarkers = new DisposableSempahore();
+ private readonly DisposableSempahore _mutexLineDecorations = new DisposableSempahore();
+
+ private bool _initialized;
+ private WebView? _view;
+ private ModelHelper? _model;
+ private ThemeListener? _themeListener;
+ private KeyboardListener? _keyboardListener;
+ private long _themeToken;
+
+ public ParentAccessor? ParentAccessor { get; private set; }
+
+ public bool IsSettingValue { get; set; }
+
+ public static DependencyProperty TextProperty { get; }
+ = DependencyProperty.Register(
+ nameof(Text),
+ typeof(string),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(
+ string.Empty,
+ (d, e) =>
+ {
+ if (!((CodeEditorCore)d).IsSettingValue)
+ {
+ _ = ((CodeEditorCore)d).InvokeScriptAsync("updateContent", e.NewValue.ToString());
+ }
+ }));
+
+ /// <summary>
+ /// Get or Set the CodeEditorCore Text.
+ /// </summary>
+ public string Text
+ {
+ get => (string)GetValue(TextProperty);
+ set => SetValue(TextProperty, value);
+ }
+
+ public static DependencyProperty SelectedTextProperty { get; }
+ = DependencyProperty.Register(
+ nameof(SelectedText),
+ typeof(string),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(
+ string.Empty,
+ (d, e) =>
+ {
+ if (!((CodeEditorCore)d).IsSettingValue)
+ {
+ _ = ((CodeEditorCore)d).InvokeScriptAsync("updateSelectedContent", e.NewValue.ToString());
+ }
+ }));
+
+ /// <summary>
+ /// Get the current Primary Selected CodeEditorCore Text.
+ /// </summary>
+ public string SelectedText
+ {
+ get => (string)GetValue(SelectedTextProperty);
+ set => SetValue(SelectedTextProperty, value);
+ }
+
+ public static DependencyProperty SelectedRangeProperty { get; }
+ = DependencyProperty.Register(
+ nameof(SelectedRange),
+ typeof(Selection),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(null));
+
+ public Selection SelectedRange
+ {
+ get => (Selection)GetValue(SelectedRangeProperty);
+ set => SetValue(SelectedRangeProperty, value);
+ }
+
+ internal static DependencyProperty CodeLanguageProperty { get; }
+ = DependencyProperty.Register(
+ nameof(CodeLanguage),
+ typeof(string),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(
+ string.Empty,
+ (d, e) =>
+ {
+ if (!(d is CodeEditorCore editor))
+ {
+ return;
+ }
+
+ if (editor.Options != null && editor.IsEditorLoaded)
+ {
+ editor.Options.Language = e.NewValue.ToString();
+ }
+ }));
+
+ /// <summary>
+ /// Set the Syntax Language for the Code CodeEditorCore.
+ ///
+ /// Note: Most likely to change or move location.
+ /// </summary>
+ public string? CodeLanguage
+ {
+ get => (string?)GetValue(CodeLanguageProperty);
+ set => SetValue(CodeLanguageProperty, value);
+ }
+
+ internal static DependencyProperty ReadOnlyProperty { get; }
+ = DependencyProperty.Register(
+ nameof(ReadOnly),
+ typeof(bool),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(
+ false,
+ (d, e) =>
+ {
+ if (!(d is CodeEditorCore editor))
+ {
+ return;
+ }
+
+ if (editor.Options != null && editor.IsEditorLoaded)
+ {
+ editor.Options.ReadOnly = bool.Parse(e.NewValue?.ToString() ?? "false");
+ }
+ if (editor.DiffOptions != null && editor.IsEditorLoaded)
+ {
+ editor.DiffOptions.OriginalEditable = !bool.Parse(e.NewValue?.ToString() ?? "false");
+ editor.DiffOptions.ReadOnly = bool.Parse(e.NewValue?.ToString() ?? "false");
+ }
+ }));
+
+ /// <summary>
+ /// Set the ReadOnly option for the Code CodeEditorCore.
+ /// </summary>
+ public bool ReadOnly
+ {
+ get => (bool)GetValue(ReadOnlyProperty);
+ set => SetValue(ReadOnlyProperty, value);
+ }
+
+ public static DependencyProperty OptionsProperty { get; }
+ = DependencyProperty.Register(
+ nameof(Options),
+ typeof(StandaloneEditorConstructionOptions),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(
+ null,
+ (d, e) =>
+ {
+ if (d is CodeEditorCore editor)
+ {
+ if (e.OldValue is StandaloneEditorConstructionOptions oldValue)
+ {
+ oldValue.PropertyChanged -= editor.Options_PropertyChanged;
+ }
+
+ if (e.NewValue is StandaloneEditorConstructionOptions value)
+ {
+ value.PropertyChanged += editor.Options_PropertyChanged;
+ }
+ }
+ }));
+
+ /// <summary>
+ /// Get or set the CodeEditorCore Options. Node: Will overwrite CodeLanguage.
+ /// </summary>
+ public StandaloneEditorConstructionOptions Options
+ {
+ get => (StandaloneEditorConstructionOptions)GetValue(OptionsProperty);
+ set => SetValue(OptionsProperty, value);
+ }
+
+ public static DependencyProperty HasGlyphMarginProperty { get; }
+ = DependencyProperty.Register(
+ nameof(HasGlyphMargin),
+ typeof(bool),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(
+ false,
+ (d, e) =>
+ {
+ ((CodeEditorCore)d).Options.GlyphMargin = e.NewValue as bool?;
+ ((CodeEditorCore)d).DiffOptions.GlyphMargin = e.NewValue as bool?;
+ }));
+
+ /// <summary>
+ /// Get or Set the CodeEditorCore Text.
+ /// </summary>
+ public bool HasGlyphMargin
+ {
+ get => (bool)GetValue(HasGlyphMarginProperty);
+ set => SetValue(HasGlyphMarginProperty, value);
+ }
+
+ public static DependencyProperty DecorationsProperty { get; }
+ = DependencyProperty.Register(
+ nameof(Decorations),
+ typeof(ModelDeltaDecoration),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(
+ null,
+ async (d, e) =>
+ {
+ if (d is CodeEditorCore editor)
+ {
+ // We only want to do this one at a time per editor.
+ using (await editor._mutexLineDecorations.WaitAsync(CancellationToken.None))
+ {
+ var old = e.OldValue as IObservableVector<ModelDeltaDecoration>;
+ // Clear out the old line decorations if we're replacing them or setting back to null
+ if ((old != null && old.Count > 0) ||
+ e.NewValue == null)
+ {
+ await editor.DeltaDecorationsHelperAsync(null);
+ }
+
+ if (e.NewValue is IObservableVector<ModelDeltaDecoration> value)
+ {
+ if (value.Count > 0)
+ {
+ await editor.DeltaDecorationsHelperAsync(value.ToArray());
+ }
+
+ value.VectorChanged -= editor.Decorations_VectorChanged;
+ value.VectorChanged += editor.Decorations_VectorChanged;
+ }
+ }
+ }
+ }));
+
+ private async void Decorations_VectorChanged(IObservableVector<ModelDeltaDecoration> sender, IVectorChangedEventArgs @event)
+ {
+ if (sender != null)
+ {
+ // Need to recall mutex as this is called from outside of this initial callback setting it up.
+ using (await _mutexLineDecorations.WaitAsync(CancellationToken.None))
+ {
+ await DeltaDecorationsHelperAsync(sender.ToArray());
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets text Decorations.
+ /// </summary>
+ public IObservableVector<ModelDeltaDecoration> Decorations
+ {
+ get => (IObservableVector<ModelDeltaDecoration>)GetValue(DecorationsProperty);
+ set => SetValue(DecorationsProperty, value);
+ }
+
+ public static DependencyProperty MarkersProperty { get; }
+ = DependencyProperty.Register(
+ nameof(Markers),
+ typeof(IMarkerData),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(
+ null,
+ async (d, e) =>
+ {
+ if (d is CodeEditorCore editor)
+ {
+ // We only want to do this one at a time per editor.
+ using (await editor._mutexMarkers.WaitAsync(CancellationToken.None))
+ {
+ var old = e.OldValue as IObservableVector<IMarkerData>;
+ // Clear out the old markers if we're replacing them or setting back to null
+ if ((old != null && old.Count > 0) ||
+ e.NewValue == null)
+ {
+ // TODO: Can I simplify this in this case?
+ await editor.SetModelMarkersAsync("CodeEditorCore", Array.Empty<IMarkerData>());
+ }
+
+ if (e.NewValue is IObservableVector<IMarkerData> value)
+ {
+ if (value.Count > 0)
+ {
+ await editor.SetModelMarkersAsync("CodeEditorCore", value.ToArray());
+ }
+
+ value.VectorChanged -= editor.Markers_VectorChanged;
+ value.VectorChanged += editor.Markers_VectorChanged;
+ }
+ }
+ }
+ }));
+
+ private async void Markers_VectorChanged(IObservableVector<IMarkerData> sender, IVectorChangedEventArgs @event)
+ {
+ if (sender != null)
+ {
+ // Need to recall mutex as this is called from outside of this initial callback setting it up.
+ using (await _mutexMarkers.WaitAsync(CancellationToken.None))
+ {
+ await SetModelMarkersAsync("CodeEditorCore", sender.ToArray());
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the hint Markers.
+ /// Note: This property is a helper for <see cref="SetModelMarkersAsync(string, IMarkerData[])"/>; use this property or the method, not both.
+ /// </summary>
+ public IObservableVector<IMarkerData> Markers
+ {
+ get => (IObservableVector<IMarkerData>)GetValue(MarkersProperty);
+ set => SetValue(MarkersProperty, value);
+ }
+
+ public static DependencyProperty IsDiffViewModeProperty { get; }
+ = DependencyProperty.Register(
+ nameof(IsDiffViewMode),
+ typeof(bool),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(false));
+
+ public bool IsDiffViewMode
+ {
+ get => (bool)GetValue(IsDiffViewModeProperty);
+ set => SetValue(IsDiffViewModeProperty, value);
+ }
+
+ public static DependencyProperty DiffLeftTextProperty { get; }
+ = DependencyProperty.Register(
+ nameof(DiffLeftText),
+ typeof(string),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(
+ string.Empty,
+ (d, e) =>
+ {
+ var codeEditor = (CodeEditorCore)d;
+ if (!codeEditor.IsSettingValue && codeEditor.IsDiffViewMode)
+ {
+ _ = codeEditor.InvokeScriptAsync("updateDiffContent", new object[] { e.NewValue.ToString(), codeEditor.DiffRightText });
+ }
+ }));
+
+ public string DiffLeftText
+ {
+ get => (string)GetValue(DiffLeftTextProperty);
+ set => SetValue(DiffLeftTextProperty, value);
+ }
+
+ public static DependencyProperty DiffRightTextProperty { get; }
+ = DependencyProperty.Register(
+ nameof(DiffRightText),
+ typeof(string),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(
+ string.Empty,
+ (d, e) =>
+ {
+ var codeEditor = (CodeEditorCore)d;
+ if (!codeEditor.IsSettingValue && codeEditor.IsDiffViewMode)
+ {
+ _ = codeEditor.InvokeScriptAsync("updateDiffContent", new object[] { codeEditor.DiffLeftText, e.NewValue.ToString() });
+ }
+ }));
+
+ public string DiffRightText
+ {
+ get => (string)GetValue(DiffRightTextProperty);
+ set => SetValue(DiffRightTextProperty, value);
+ }
+
+ public static DependencyProperty DiffOptionsProperty { get; }
+ = DependencyProperty.Register(
+ nameof(DiffOptions),
+ typeof(DiffEditorConstructionOptions),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(
+ null,
+ (d, e) =>
+ {
+ if (d is CodeEditorCore editor)
+ {
+ if (e.OldValue is DiffEditorConstructionOptions oldValue)
+ {
+ oldValue.PropertyChanged -= editor.DiffOptions_PropertyChanged;
+ }
+
+ if (e.NewValue is DiffEditorConstructionOptions value)
+ {
+ value.PropertyChanged += editor.DiffOptions_PropertyChanged;
+ }
+ }
+ }));
+
+ /// <summary>
+ /// Get or set the CodeEditorCore Options. Node: Will overwrite CodeLanguage.
+ /// </summary>
+ public DiffEditorConstructionOptions DiffOptions
+ {
+ get => (DiffEditorConstructionOptions)GetValue(DiffOptionsProperty);
+ set => SetValue(DiffOptionsProperty, value);
+ }
+
+ /// <summary>
+ /// When Editor is Loading, it is ready to receive commands to the Monaco Engine.
+ /// </summary>
+ public new event RoutedEventHandler? Loading;
+
+ /// <summary>
+ /// When Editor is Loaded, it has been rendered and is ready to be displayed.
+ /// </summary>
+ public new event RoutedEventHandler? Loaded;
+
+ /// <summary>
+ /// Called when a link is Ctrl+Clicked on in the editor, set Handled to true to prevent opening.
+ /// </summary>
+ public event TypedEventHandler<WebView, WebViewNewWindowRequestedEventArgs>? OpenLinkRequested;
+
+ /// <summary>
+ /// Called when an internal exception is encountered while executing a command. (for testing/reporting issues)
+ /// </summary>
+ public event TypedEventHandler<CodeEditorCore, Exception>? InternalException;
+
+ /// <summary>
+ /// Custom Keyboard Handler.
+ /// </summary>
+ public new event WebKeyEventHandler? KeyDown;
+
+ public static DependencyProperty IsEditorLoadedProperty { get; }
+ = DependencyProperty.Register(
+ nameof(IsEditorLoaded),
+ typeof(string),
+ typeof(CodeEditorCore),
+ new PropertyMetadata(false));
+
+ /// <summary>
+ /// Template Property used during loading to prevent blank control visibility when it's still loading WebView.
+ /// </summary>
+ public bool IsEditorLoaded
+ {
+ get => (bool)GetValue(IsEditorLoadedProperty);
+ private set => SetValue(IsEditorLoadedProperty, value);
+ }
+
+ /// <summary>
+ /// Construct a new IStandAloneCodeEditor.
+ /// </summary>
+ public CodeEditorCore()
+ {
+ DefaultStyleKey = typeof(CodeEditorCore);
+
+ Options = new StandaloneEditorConstructionOptions();
+ DiffOptions = new DiffEditorConstructionOptions();
+
+ // Set Pass-Thru Properties
+ Options.GlyphMargin = HasGlyphMargin;
+ DiffOptions.GlyphMargin = HasGlyphMargin;
+
+ // Register for changes
+ Options.PropertyChanged += Options_PropertyChanged;
+ DiffOptions.PropertyChanged += DiffOptions_PropertyChanged;
+
+ // Initialize this here so property changed event will fire and register collection changed event.
+ Decorations = new ObservableVector<ModelDeltaDecoration>();
+ Markers = new ObservableVector<IMarkerData>();
+ _model = new ModelHelper(this);
+
+ base.Loaded += CodeEditor_Loaded;
+ Unloaded += CodeEditor_Unloaded;
+ }
+
+ private async void Options_PropertyChanged(object sender, PropertyChangedEventArgs e)
+ {
+ if (!(sender is StandaloneEditorConstructionOptions options) || IsDiffViewMode)
+ {
+ return;
+ }
+
+ if (e.PropertyName == nameof(StandaloneEditorConstructionOptions.Language))
+ {
+ await InvokeScriptAsync("updateLanguage", options.Language ?? string.Empty);
+ if (CodeLanguage != options.Language)
+ {
+ CodeLanguage = options.Language;
+ }
+ }
+
+ if (e.PropertyName == nameof(StandaloneEditorConstructionOptions.GlyphMargin))
+ {
+ if (HasGlyphMargin != options.GlyphMargin)
+ {
+ options.GlyphMargin = HasGlyphMargin;
+ }
+ }
+
+ if (e.PropertyName == nameof(StandaloneEditorConstructionOptions.ReadOnly))
+ {
+ if (ReadOnly != options.ReadOnly)
+ {
+ options.ReadOnly = ReadOnly;
+ }
+ }
+
+ await InvokeScriptAsync("updateOptions", options);
+ }
+
+ private async void DiffOptions_PropertyChanged(object sender, PropertyChangedEventArgs e)
+ {
+ if (!(sender is DiffEditorConstructionOptions options) || !IsDiffViewMode)
+ {
+ return;
+ }
+
+ if (e.PropertyName == nameof(DiffEditorConstructionOptions.GlyphMargin))
+ {
+ if (HasGlyphMargin != options.GlyphMargin)
+ {
+ options.GlyphMargin = HasGlyphMargin;
+ }
+ }
+
+ if (e.PropertyName == nameof(DiffEditorConstructionOptions.ReadOnly))
+ {
+ if (ReadOnly != options.ReadOnly)
+ {
+ options.ReadOnly = ReadOnly;
+ }
+ }
+
+ await InvokeScriptAsync("updateDiffOptions", options);
+ }
+
+ private void CodeEditor_Loaded(object sender, RoutedEventArgs e)
+ {
+ // Do this the 2nd time around.
+ if (_model == null && _view != null)
+ {
+ _model = new ModelHelper(this);
+
+ Options.PropertyChanged += Options_PropertyChanged;
+ DiffOptions.PropertyChanged += DiffOptions_PropertyChanged;
+
+ Decorations.VectorChanged += Decorations_VectorChanged;
+ Markers.VectorChanged += Markers_VectorChanged;
+
+ _view.NewWindowRequested += WebView_NewWindowRequested;
+
+ _initialized = true;
+
+ Loading?.Invoke(this, new RoutedEventArgs());
+
+ Unloaded += CodeEditor_Unloaded;
+
+ Loaded?.Invoke(this, new RoutedEventArgs());
+ }
+ }
+
+ private void CodeEditor_Unloaded(object sender, RoutedEventArgs e)
+ {
+ Unloaded -= CodeEditor_Unloaded;
+
+ if (_view != null)
+ {
+ _view.NavigationStarting -= WebView_NavigationStarting;
+ _view.DOMContentLoaded -= WebView_DOMContentLoaded;
+ _view.NavigationCompleted -= WebView_NavigationCompleted;
+ _view.NewWindowRequested -= WebView_NewWindowRequested;
+ }
+
+ Decorations.VectorChanged -= Decorations_VectorChanged;
+ Markers.VectorChanged -= Markers_VectorChanged;
+
+ Options.PropertyChanged -= Options_PropertyChanged;
+ DiffOptions.PropertyChanged -= DiffOptions_PropertyChanged;
+
+ UnregisterPropertyChangedCallback(RequestedThemeProperty, _themeToken);
+ _keyboardListener = null;
+ _model = null;
+ }
+
+ protected override void OnApplyTemplate()
+ {
+ if (_view != null)
+ {
+ _view.GotFocus -= View_GotFocus;
+ _view.LostFocus -= View_LostFocus;
+ _view.NavigationStarting -= WebView_NavigationStarting;
+ _view.DOMContentLoaded -= WebView_DOMContentLoaded;
+ _view.NavigationCompleted -= WebView_NavigationCompleted;
+ _view.NewWindowRequested -= WebView_NewWindowRequested;
+ _initialized = false;
+ }
+
+ _view = (WebView)GetTemplateChild("WebViewElement");
+
+ if (_view != null)
+ {
+ _view.GotFocus += View_GotFocus;
+ _view.LostFocus += View_LostFocus;
+ _view.NavigationStarting += WebView_NavigationStarting;
+ _view.DOMContentLoaded += WebView_DOMContentLoaded;
+ _view.NavigationCompleted += WebView_NavigationCompleted;
+ _view.NewWindowRequested += WebView_NewWindowRequested;
+ _view.Source = new System.Uri("ms-appx-web:///DevToys.MonacoEditor/CodeEditorControl/CodeEditorCore.html");
+ }
+
+ base.OnApplyTemplate();
+ }
+
+ private void View_GotFocus(object sender, RoutedEventArgs args)
+ {
+ VisualStateManager.GoToState(this, FocusedState, false);
+ }
+
+ private void View_LostFocus(object sender, RoutedEventArgs args)
+ {
+ VisualStateManager.GoToState(this, NormalState, false);
+ }
+
+ internal async Task SendScriptAsync(string script,
+ [CallerMemberName] string? member = null,
+ [CallerFilePath] string? file = null,
+ [CallerLineNumber] int line = 0)
+ {
+ await SendScriptAsync<object>(script, member, file, line);
+ }
+
+ internal async Task<T?> SendScriptAsync<T>(string script,
+ [CallerMemberName] string? member = null,
+ [CallerFilePath] string? file = null,
+ [CallerLineNumber] int line = 0)
+ {
+ if (_initialized)
+ {
+ try
+ {
+ if (_view is null)
+ {
+ throw new NullReferenceException();
+ }
+ return await _view.RunScriptAsync<T>(script, member, file, line);
+ }
+ catch (Exception e)
+ {
+ InternalException?.Invoke(this, e);
+ }
+ }
+ else
+ {
+#if DEBUG
+ Debug.WriteLine("WARNING: Tried to call '" + script + "' before initialized.");
+#endif
+ }
+
+ return default;
+ }
+
+ internal async Task InvokeScriptAsync(
+ string method,
+ object arg,
+ bool serialize = true,
+ [CallerMemberName] string? member = null,
+ [CallerFilePath] string? file = null,
+ [CallerLineNumber] int line = 0)
+ {
+ await InvokeScriptAsync<object>(method, new object[] { arg }, serialize, member, file, line);
+ }
+
+ internal async Task InvokeScriptAsync(
+ string method,
+ object[] args,
+ bool serialize = true,
+ [CallerMemberName] string? member = null,
+ [CallerFilePath] string? file = null,
+ [CallerLineNumber] int line = 0)
+ {
+ await InvokeScriptAsync<object>(method, args, serialize, member, file, line);
+ }
+
+ internal async Task<T?> InvokeScriptAsync<T>(
+ string method,
+ object arg,
+ bool serialize = true,
+ [CallerMemberName] string? member = null,
+ [CallerFilePath] string? file = null,
+ [CallerLineNumber] int line = 0)
+ {
+ return await InvokeScriptAsync<T>(method, new object[] { arg }, serialize, member, file, line);
+ }
+
+ internal async Task<T?> InvokeScriptAsync<T>(
+ string method,
+ object[] args,
+ bool serialize = true,
+ [CallerMemberName] string? member = null,
+ [CallerFilePath] string? file = null,
+ [CallerLineNumber] int line = 0)
+ {
+ if (_initialized)
+ {
+ try
+ {
+
+ if (_view is null)
+ {
+ throw new NullReferenceException();
+ }
+ return await _view.InvokeScriptAsync<T>(method, args, serialize, member, file, line);
+ }
+ catch (Exception e)
+ {
+ InternalException?.Invoke(this, e);
+ }
+ }
+ else
+ {
+#if DEBUG
+ Debug.WriteLine("WARNING: Tried to call " + method + " before initialized.");
+#endif
+ }
+
+ return default;
+ }
+
+ public void Dispose()
+ {
+ if (_themeListener != null)
+ {
+ _themeListener.ThemeChanged -= ThemeListener_ThemeChanged;
+ }
+
+ _themeListener = null;
+
+ ParentAccessor?.Dispose();
+ ParentAccessor = null;
+ CssStyleBroker.DetachEditor(this);
+ }
+
+ private void WebView_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
+ {
+#if DEBUG
+ Debug.WriteLine("DOM Content Loaded");
+#endif
+ _initialized = true;
+ }
+
+ private async void WebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
+ {
+ IsEditorLoaded = true;
+
+ // Update theme
+ await InvokeScriptAsync("setTheme", args: new string[] { _themeListener!.AccentColorHtmlHex });
+ await InvokeScriptAsync("changeTheme", new string[] { _themeListener.CurrentTheme.ToString(), _themeListener.IsHighContrast.ToString() });
+
+ // If we're supposed to have focus, make sure we try and refocus on our now loaded webview.
+ if (FocusManager.GetFocusedElement() == this)
+ {
+ if (_view is null)
+ {
+ throw new NullReferenceException();
+ }
+ _view.Focus(FocusState.Programmatic);
+ }
+
+ Loaded?.Invoke(this, new RoutedEventArgs());
+ }
+
+ private void WebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
+ {
+#if DEBUG
+ Debug.WriteLine("Navigation Starting");
+#endif
+ ParentAccessor = new ParentAccessor(this);
+ ParentAccessor.AddAssemblyForTypeLookup(typeof(Range).GetTypeInfo().Assembly);
+ ParentAccessor.RegisterAction("Loaded", CodeEditorLoaded);
+
+ _themeListener = new ThemeListener();
+ _themeListener.ThemeChanged += ThemeListener_ThemeChanged;
+ _themeToken = RegisterPropertyChangedCallback(RequestedThemeProperty, RequestedTheme_PropertyChanged);
+
+ _keyboardListener = new KeyboardListener(this);
+
+ if (_view is null)
+ {
+ throw new NullReferenceException();
+ }
+
+ _view.AddWebAllowedObject("Debug", new DebugLogger());
+ _view.AddWebAllowedObject("Parent", ParentAccessor);
+ _view.AddWebAllowedObject("Theme", _themeListener);
+ _view.AddWebAllowedObject("Keyboard", _keyboardListener);
+ }
+
+ private async void CodeEditorLoaded()
+ {
+ if (Decorations != null && Decorations.Count > 0)
+ {
+ // Need to retrigger highlights after load if they were set before load.
+ await DeltaDecorationsHelperAsync(Decorations.ToArray());
+ }
+
+ Options.ReadOnly = ReadOnly;
+ Options.Language = CodeLanguage;
+ DiffOptions.OriginalEditable = !ReadOnly;
+ DiffOptions.ReadOnly = ReadOnly;
+
+ // Now we're done loading
+ Loading?.Invoke(this, new RoutedEventArgs());
+ }
+
+ private void WebView_NewWindowRequested(WebView sender, WebViewNewWindowRequestedEventArgs args)
+ {
+ // TODO: Should probably create own event args here as we don't want to expose the referrer to our internal page?
+ OpenLinkRequested?.Invoke(sender, args);
+ }
+
+ private async void RequestedTheme_PropertyChanged(DependencyObject obj, DependencyProperty property)
+ {
+ var editor = (CodeEditorCore)obj;
+ var theme = editor.RequestedTheme;
+ var tstr = string.Empty;
+
+ if (theme == ElementTheme.Default)
+ {
+ tstr = _themeListener?.CurrentThemeName ?? string.Empty;
+ }
+ else
+ {
+ tstr = theme.ToString();
+ }
+
+ await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
+ {
+ await InvokeScriptAsync("setTheme", args: new string[] { _themeListener!.AccentColorHtmlHex });
+ await InvokeScriptAsync("changeTheme", new string[] { tstr, _themeListener.IsHighContrast.ToString() });
+ });
+ }
+
+ private async void ThemeListener_ThemeChanged(ThemeListener sender)
+ {
+ await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
+ {
+ await InvokeScriptAsync("setTheme", args: new string[] { sender.AccentColorHtmlHex });
+ await InvokeScriptAsync("changeTheme", args: new string[] { sender.CurrentTheme.ToString(), sender.IsHighContrast.ToString() });
+ });
+ }
+
+ public bool TriggerKeyDown(WebKeyEventArgs args)
+ {
+ KeyDown?.Invoke(this, args);
+
+ return args.Handled;
+ }
+
+ protected override void OnGotFocus(RoutedEventArgs e)
+ {
+ base.OnGotFocus(e);
+
+ if (_view != null && FocusManager.GetFocusedElement() == this)
+ {
+ // Forward Focus onto our inner WebView
+ _view.Focus(FocusState.Programmatic);
+ }
+ }
+
+ #region Reveal Methods
+
+ public IAsyncAction RevealLineAsync(uint lineNumber)
+ {
+ return SendScriptAsync("editor.revealLine(" + lineNumber + ")").AsAsyncAction();
+ }
+
+ public IAsyncAction RevealLineInCenterAsync(uint lineNumber)
+ {
+ return SendScriptAsync("editor.revealLineInCenter(" + lineNumber + ")").AsAsyncAction();
+ }
+
+ public IAsyncAction RevealLineInCenterIfOutsideViewportAsync(uint lineNumber)
+ {
+ return SendScriptAsync("editor.revealLineInCenterIfOutsideViewport(" + lineNumber + ")").AsAsyncAction();
+ }
+
+ public IAsyncAction RevealLinesAsync(uint startLineNumber, uint endLineNumber)
+ {
+ return SendScriptAsync("editor.revealLines(" + startLineNumber + ", " + endLineNumber + ")").AsAsyncAction();
+ }
+
+ public IAsyncAction RevealLinesInCenterAsync(uint startLineNumber, uint endLineNumber)
+ {
+ return SendScriptAsync("editor.revealLinesInCenter(" + startLineNumber + ", " + endLineNumber + ")").AsAsyncAction();
+ }
+
+ public IAsyncAction RevealLinesInCenterIfOutsideViewportAsync(uint startLineNumber, uint endLineNumber)
+ {
+ return SendScriptAsync("editor.revealLinesInCenterIfOutsideViewport(" + startLineNumber + ", " + endLineNumber + ")").AsAsyncAction();
+ }
+
+ public IAsyncAction RevealPositionAsync(IPosition position)
+ {
+ return RevealPositionAsync(position, false, false);
+ }
+
+ public IAsyncAction RevealPositionAsync(IPosition position, bool revealVerticalInCenter)
+ {
+ return RevealPositionAsync(position, revealVerticalInCenter, false);
+ }
+
+ public IAsyncAction RevealPositionAsync(IPosition position, bool revealVerticalInCenter, bool revealHorizontal)
+ {
+ return SendScriptAsync("editor.revealPosition(JSON.parse('" + position.ToJson() + "'), " + JsonConvert.ToString(revealVerticalInCenter) + ", " + JsonConvert.ToString(revealHorizontal) + ")").AsAsyncAction();
+ }
+
+ public IAsyncAction RevealPositionInCenterAsync(IPosition position)
+ {
+ return SendScriptAsync("editor.revealPositionInCenter(JSON.parse('" + position.ToJson() + "'))").AsAsyncAction();
+ }
+
+ public IAsyncAction RevealPositionInCenterIfOutsideViewportAsync(IPosition position)
+ {
+ return SendScriptAsync("editor.revealPositionInCenterIfOutsideViewport(JSON.parse('" + position.ToJson() + "'))").AsAsyncAction();
+ }
+
+ public IAsyncAction RevealRangeAsync(IRange range)
+ {
+ return SendScriptAsync("editor.revealRange(JSON.parse('" + range.ToJson() + "'))").AsAsyncAction();
+ }
+
+ public IAsyncAction RevealRangeAtTopAsync(IRange range)
+ {
+ return SendScriptAsync("editor.revealRangeAtTop(JSON.parse('" + range.ToJson() + "'))").AsAsyncAction();
+ }
+
+ public IAsyncAction RevealRangeInCenterAsync(IRange range)
+ {
+ return SendScriptAsync("editor.revealRangeInCenter(JSON.parse('" + range.ToJson() + "'))").AsAsyncAction();
+ }
+
+ public IAsyncAction RevealRangeInCenterIfOutsideViewportAsync(IRange range)
+ {
+ return SendScriptAsync("editor.revealRangeInCenterIfOutsideViewport(JSON.parse('" + range.ToJson() + "'))").AsAsyncAction();
+ }
+ #endregion
+
+ public IAsyncAction AddActionAsync(IActionDescriptor action)
+ {
+ var wref = new WeakReference<CodeEditorCore>(this);
+ ParentAccessor?.RegisterAction(
+ "Action" + action.Id,
+ new Action(() =>
+ {
+ if (wref.TryGetTarget(out CodeEditorCore editor))
+ {
+ action?.Run(editor, null);
+ }
+ }));
+ return InvokeScriptAsync("addAction", action).AsAsyncAction();
+ }
+
+ /// <summary>
+ /// Invoke scripts, return value must be strings
+ /// </summary>
+ /// <param name="script">Script to invoke</param>
+ /// <returns>An async operation result to string</returns>
+ public IAsyncOperation<string> InvokeScriptAsync(string script)
+ {
+ if (_view is null)
+ {
+ throw new NullReferenceException();
+ }
+ return _view.InvokeScriptAsync("eval", new[] { script });
+ }
+
+ public IAsyncOperation<string?> AddCommandAsync(int keybinding, CommandHandler handler)
+ {
+ return AddCommandAsync(keybinding, handler, string.Empty);
+ }
+
+ public IAsyncOperation<string?> AddCommandAsync(int keybinding, CommandHandler handler, string context)
+ {
+ var name = "Command" + keybinding;
+ ParentAccessor?.RegisterAction(name, new Action(() => { handler?.Invoke(); }));
+ return InvokeScriptAsync<string?>("addCommand", new object[] { keybinding, name, context }).AsAsyncOperation();
+ }
+
+ public IAsyncOperation<ContextKey> CreateContextKeyAsync(string key, bool defaultValue)
+ {
+ var ck = new ContextKey(this, key, defaultValue);
+
+ return InvokeScriptAsync("createContext", ck).ContinueWith((noop) =>
+ {
+ return ck;
+ }).AsAsyncOperation();
+ }
+
+ public IModel? GetModel()
+ {
+ return _model;
+ }
+
+ public IAsyncOperation<IEnumerable<Marker>?> GetModelMarkersAsync() // TODO: Filter (string? owner, Uri? resource, int? take)
+ {
+ return SendScriptAsync<IEnumerable<Marker>?>("monaco.editor.getModelMarkers();").AsAsyncOperation();
+ }
+
+ public IAsyncAction SetModelMarkersAsync(string owner, [ReadOnlyArray] IMarkerData[] markers)
+ {
+ return SendScriptAsync("monaco.editor.setModelMarkers(model, " + JsonConvert.ToString(owner) + ", " + JsonConvert.SerializeObject(markers) + ");").AsAsyncAction();
+ }
+
+ public IAsyncOperation<Position?> GetPositionAsync()
+ {
+ return SendScriptAsync<Position?>("editor.getPosition();").AsAsyncOperation();
+ }
+
+ public IAsyncAction SetPositionAsync(IPosition position)
+ {
+ return SendScriptAsync("editor.setPosition(" + JsonConvert.SerializeObject(position) + ");").AsAsyncAction();
+ }
+
+ /// <summary>
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.icommoncodeeditor.html#deltadecorations
+ ///
+ /// Using <see cref="Decorations"/> Property to manipulate decorations instead of calling this directly.
+ /// </summary>
+ /// <param name="newDecorations"></param>
+ /// <returns></returns>
+ private IAsyncAction DeltaDecorationsHelperAsync([ReadOnlyArray] ModelDeltaDecoration[]? newDecorations)
+ {
+ var newDecorationsAdjust = newDecorations ?? Array.Empty<ModelDeltaDecoration>();
+
+ // Update Styles
+ return InvokeScriptAsync("updateStyle", CssStyleBroker.GetInstance(this).GetStyles()).ContinueWith((noop) =>
+ {
+ // Send Command to Modify Decorations
+ // IMPORTANT: Need to cast to object here as we want this to be a single array object passed as a parameter, not a list of parameters to expand.
+ return InvokeScriptAsync("updateDecorations", (object)newDecorationsAdjust);
+ }).AsAsyncAction();
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/CodeEditorControl/CodeEditorCore.html b/src/dev/impl/DevToys.MonacoEditor/CodeEditorControl/CodeEditorCore.html
new file mode 100644
index 000000000..93c9ab235
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/CodeEditorControl/CodeEditorCore.html
@@ -0,0 +1,105 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
+ <style>
+ html, body {
+ height: 100%;
+ margin: 0;
+ }
+ /* Just have Monaco Fill All Available Space within control */
+ #container {
+ height: 100%;
+ width: 100%;
+ }
+ </style>
+ <style id="dynamic">
+ </style>
+</head>
+<body>
+
+ <div id="container" onkeydown="keyDown(event)"></div>
+
+ <script src="ms-appx-web:///DevToys.MonacoEditor/monaco-editor/min/vs/loader.js"></script>
+ <script src="ms-appx-web:///DevToys.MonacoEditor/ts-helpermethods/registerCompletionItemProvider.js"></script>
+ <script src="ms-appx-web:///DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.js"></script>
+ <script src="ms-appx-web:///DevToys.MonacoEditor/ts-helpermethods/updateSelectedContent.js"></script>
+
+ <script>
+ var editor;
+ var model;
+ var contexts = {};
+ var decorations = [];
+ var modifingSelection = false; // Supress updates to selection when making edits.
+
+ Debug.log("Starting Monaco Load");
+ require.config({ paths: { 'vs': 'ms-appx-web:///DevToys.MonacoEditor/monaco-editor/min/vs' } });
+ require(['vs/editor/editor.main'], function () {
+ Debug.log("Grabbing Monaco Options");
+
+ var isDiffView = Parent.getValue("IsDiffViewMode");
+
+ if (isDiffView) {
+ let opt = getDiffOptions();
+ editor = monaco.editor.createDiffEditor(document.getElementById('container'), opt);
+ var originalModel = monaco.editor.createModel("", "text/plain");
+ var modifiedModel = monaco.editor.createModel("", "text/plain");
+ editor.setModel({
+ original: originalModel,
+ modified: modifiedModel
+ });
+ model = editor.getModel();
+ }
+ else {
+ let opt = getOptions();
+ opt["value"] = Parent.getValue("Text");
+ editor = monaco.editor.create(document.getElementById('container'), opt);
+ model = editor.getModel();
+
+ // Listen for Content Changes
+ model.onDidChangeContent((event) => {
+ Parent.setValue("Text", model.getValue());
+ //console.log("buffers: " + JSON.stringify(model._buffer._pieceTree._buffers));
+ //console.log("commandMgr: " + JSON.stringify(model._commandManager));
+ //console.log("viewState:" + JSON.stringify(editor.saveViewState()));
+ });
+
+ // Listen for Selection Changes
+ editor.onDidChangeCursorSelection((event) => {
+ if (!modifingSelection) {
+ console.log(event.source);
+ Parent.setValue("SelectedText", model.getValueInRange(event.selection));
+ Parent.setValue("SelectedRange", JSON.stringify(event.selection), "Selection");
+ }
+ })
+ }
+
+ // Set theme
+ let theme = Parent.getJsonValue("RequestedTheme");
+ theme = {
+ "0": "Default",
+ "1": "Light",
+ "2": "Dark"
+ }[theme];
+ if (theme == "Default") {
+ theme = Theme.currentThemeName.toString();
+ }
+ setTheme(theme, Theme.accentColorHtmlHex.toString());
+ changeTheme(theme, Theme.isHighContrast.toString());
+
+ // Update Monaco Size when we receive a window resize event
+ window.addEventListener("resize", () => {
+ editor.layout();
+ });
+
+ // Disable WebView Scrollbar so Monaco Scrollbar can do heavy lifting
+ document.body.style.overflow = 'hidden';
+
+ // Callback to Parent that we're loaded
+ Debug.log("Loaded Monaco");
+ Parent.callAction("Loaded");
+ });
+ </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/CodeEditorControl/InvertedBooleanConverter.cs b/src/dev/impl/DevToys.MonacoEditor/CodeEditorControl/InvertedBooleanConverter.cs
new file mode 100644
index 000000000..dc8524740
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/CodeEditorControl/InvertedBooleanConverter.cs
@@ -0,0 +1,30 @@
+#nullable enable
+
+using System;
+using Windows.UI.Xaml;
+using Windows.UI.Xaml.Data;
+
+namespace DevToys.MonacoEditor.CodeEditorControl
+{
+ /// <summary>
+ /// Convert a <see cref="bool"/> to a inverted <see cref="bool"/> value.
+ /// </summary>
+ public sealed class InvertedBooleanConverter : IValueConverter
+ {
+ public object Convert(object value, Type targetType, object parameter, string language)
+ {
+ var valueBool = value as bool?;
+ if (valueBool == null)
+ {
+ return DependencyProperty.UnsetValue;
+ }
+
+ return !valueBool.Value;
+ }
+
+ public object ConvertBack(object value, Type targetType, object parameter, string language)
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/DevToys.MonacoEditor.csproj b/src/dev/impl/DevToys.MonacoEditor/DevToys.MonacoEditor.csproj
new file mode 100644
index 000000000..9de4185b1
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/DevToys.MonacoEditor.csproj
@@ -0,0 +1,231 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+ <PropertyGroup>
+ <ProjectGuid>{0FE678BB-9F9B-4495-B777-F9B1E11DA20C}</ProjectGuid>
+ <OutputType>winmdobj</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>DevToys.MonacoEditor</RootNamespace>
+ <AssemblyName>DevToys.MonacoEditor</AssemblyName>
+ <DefaultLanguage>en</DefaultLanguage>
+ <TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
+ <TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">$(Windows10SDKVersion)</TargetPlatformVersion>
+ <TargetPlatformMinVersion>$(Windows10MinSDKVersion)</TargetPlatformMinVersion>
+ <MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
+ <FileAlignment>512</FileAlignment>
+ <ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
+ <AllowCrossPlatformRetargeting>false</AllowCrossPlatformRetargeting>
+ <UseVSHostingProcess>false</UseVSHostingProcess>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)' == 'Debug'">
+ <TypeScriptRemoveComments>false</TypeScriptRemoveComments>
+ <TypeScriptSourceMap>true</TypeScriptSourceMap>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)' == 'Release'">
+ <TypeScriptRemoveComments>true</TypeScriptRemoveComments>
+ <TypeScriptSourceMap>false</TypeScriptSourceMap>
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="..\..\shared\SharedAssemblyInfo.cs">
+ <Link>Properties\SharedAssemblyInfo.cs</Link>
+ </Compile>
+ <Compile Include="CodeEditorControl\CodeEditorCore.cs" />
+ <Compile Include="CodeEditorControl\InvertedBooleanConverter.cs" />
+ <Compile Include="Extensions\JavaScriptExecutionException.cs" />
+ <Compile Include="Extensions\JavaScriptInnerException.cs" />
+ <Compile Include="Extensions\WebViewExtensions.cs" />
+ <Compile Include="Extensions\DispatcherExtensions.cs" />
+ <Compile Include="Extensions\ThreadPriority.cs" />
+ <Compile Include="Helpers\DebugLogger.cs" />
+ <Compile Include="Helpers\DisposableSempahore.cs" />
+ <Compile Include="Helpers\IParentAccessorAcceptor.cs" />
+ <Compile Include="Helpers\KeyboardListener.cs" />
+ <Compile Include="Helpers\ParentAccessor.cs" />
+ <Compile Include="Helpers\ThemeListener.cs" />
+ <Compile Include="Helpers\WebKeyEventArgs.cs" />
+ <Compile Include="Monaco\Editor\AcceptSuggestionOnEnter.cs" />
+ <Compile Include="Monaco\Editor\AccessibilitySupport.cs" />
+ <Compile Include="Monaco\Editor\AccessibilitySupportConverter.cs" />
+ <Compile Include="Monaco\Editor\AutoClosingBrackets.cs" />
+ <Compile Include="Monaco\Editor\AutoClosingBracketsConverter.cs" />
+ <Compile Include="Monaco\Editor\AutoClosingOvertype.cs" />
+ <Compile Include="Monaco\Editor\AcceptSuggestionOnEnterConverter.cs" />
+ <Compile Include="Monaco\Editor\AutoClosingOvertypeConverter.cs" />
+ <Compile Include="Monaco\Editor\AutoClosingQuotes.cs" />
+ <Compile Include="Monaco\Editor\AutoClosingQuotesConverter.cs" />
+ <Compile Include="Monaco\Editor\AutoFindInSelection.cs" />
+ <Compile Include="Monaco\Editor\AutoFindInSelectionConverter.cs" />
+ <Compile Include="Monaco\Editor\AutoIndent.cs" />
+ <Compile Include="Monaco\Editor\AutoIndentConverter.cs" />
+ <Compile Include="Monaco\Editor\AutoSurround.cs" />
+ <Compile Include="Monaco\Editor\AutoSurroundConverter.cs" />
+ <Compile Include="Monaco\Editor\ContextKey.cs" />
+ <Compile Include="Monaco\Editor\CursorBlinking.cs" />
+ <Compile Include="Monaco\Editor\CursorBlinkingConverter.cs" />
+ <Compile Include="Monaco\Editor\CursorStyle.cs" />
+ <Compile Include="Monaco\Editor\CursorStyleConverter.cs" />
+ <Compile Include="Monaco\Editor\CursorSurroundingLinesStyle.cs" />
+ <Compile Include="Monaco\Editor\CursorSurroundingLinesStyleConverter.cs" />
+ <Compile Include="Monaco\Editor\DiffEditorConstructionOptions.cs" />
+ <Compile Include="Monaco\Editor\Dimension.cs" />
+ <Compile Include="Monaco\Editor\EditorFindOptions.cs" />
+ <Compile Include="Monaco\Editor\EditorHoverOptions.cs" />
+ <Compile Include="Monaco\Editor\EditorLightbulbOptions.cs" />
+ <Compile Include="Monaco\Editor\EditorMinimapOptions.cs" />
+ <Compile Include="Monaco\Editor\EndOfLinePreference.cs" />
+ <Compile Include="Monaco\Editor\EndOfLineSequence.cs" />
+ <Compile Include="Monaco\Editor\FoldingStrategy.cs" />
+ <Compile Include="Monaco\Editor\FoldingStrategyConverter.cs" />
+ <Compile Include="Monaco\Editor\GoToLocationOptions.cs" />
+ <Compile Include="Monaco\Editor\IActionDescriptor.cs" />
+ <Compile Include="Monaco\Editor\IContextKey.cs" />
+ <Compile Include="Monaco\Editor\IDiffEditorConstructionOptions.cs" />
+ <Compile Include="Monaco\Editor\IDiffEditorOptions.cs" />
+ <Compile Include="Monaco\Editor\IDimension.cs" />
+ <Compile Include="Monaco\Editor\EditorCommentsOptions.cs" />
+ <Compile Include="Monaco\Editor\IEditorConstructionOptions.cs" />
+ <Compile Include="Monaco\Editor\IEditorOptions.cs" />
+ <Compile Include="Monaco\Editor\EditorParameterHintOptions.cs" />
+ <Compile Include="Monaco\Editor\EditorScrollbarOptions.cs" />
+ <Compile Include="Monaco\Editor\IGlobalEditorOptions.cs" />
+ <Compile Include="Monaco\Editor\IMarker.cs" />
+ <Compile Include="Monaco\Editor\IMarkerData.cs" />
+ <Compile Include="Monaco\Editor\IModel.cs" />
+ <Compile Include="Monaco\Editor\InterfaceToClassConverter.cs" />
+ <Compile Include="Monaco\Editor\ModelDecorationMinimapOptions.cs" />
+ <Compile Include="Monaco\Editor\ModelDecorationOptions.cs" />
+ <Compile Include="Monaco\Editor\ModelDecorationOverviewRulerOptions.cs" />
+ <Compile Include="Monaco\Editor\ModelDeltaDecoration.cs" />
+ <Compile Include="Monaco\Editor\InsertMode.cs" />
+ <Compile Include="Monaco\Editor\InsertModeConverter.cs" />
+ <Compile Include="Monaco\Editor\RelatedInformation.cs" />
+ <Compile Include="Monaco\Editor\SingleEditOperation.cs" />
+ <Compile Include="Monaco\Editor\IStandaloneEditorConstructionOptions.cs" />
+ <Compile Include="Monaco\Editor\SuggestOptions.cs" />
+ <Compile Include="Monaco\Editor\IWordAtPosition.cs" />
+ <Compile Include="Monaco\Editor\LineNumbersType.cs" />
+ <Compile Include="Monaco\Editor\LineNumbersTypeConverter.cs" />
+ <Compile Include="Monaco\Editor\Marker.cs" />
+ <Compile Include="Monaco\Editor\MarkerData.cs" />
+ <Compile Include="Monaco\Editor\MatchBrackets.cs" />
+ <Compile Include="Monaco\Editor\MatchBracketsConverter.cs" />
+ <Compile Include="Monaco\Editor\MouseStyle.cs" />
+ <Compile Include="Monaco\Editor\MouseStyleConverter.cs" />
+ <Compile Include="Monaco\Editor\MultiCursorModifier.cs" />
+ <Compile Include="Monaco\Editor\MultiCursorModifierConverter.cs" />
+ <Compile Include="Monaco\Editor\MultiCursorPaste.cs" />
+ <Compile Include="Monaco\Editor\MultiCursorPasteConverter.cs" />
+ <Compile Include="Monaco\Editor\Multiple.cs" />
+ <Compile Include="Monaco\Editor\MultipleConverter.cs" />
+ <Compile Include="Monaco\Editor\RenderLineHighlight.cs" />
+ <Compile Include="Monaco\Editor\RenderLineHighlightConverter.cs" />
+ <Compile Include="Monaco\Editor\RenderWhitespace.cs" />
+ <Compile Include="Monaco\Editor\RenderWhitespaceConverter.cs" />
+ <Compile Include="Monaco\Editor\ScrollbarBehavior.cs" />
+ <Compile Include="Monaco\Editor\ScrollbarBehaviorConverter.cs" />
+ <Compile Include="Monaco\Editor\Show.cs" />
+ <Compile Include="Monaco\Editor\ShowConverter.cs" />
+ <Compile Include="Monaco\Editor\Side.cs" />
+ <Compile Include="Monaco\Editor\SideConverter.cs" />
+ <Compile Include="Monaco\Editor\SnippetSuggestions.cs" />
+ <Compile Include="Monaco\Editor\SnippetSuggestionsConverter.cs" />
+ <Compile Include="Monaco\Editor\StandaloneEditorConstructionOptions.cs" />
+ <Compile Include="Monaco\Editor\SuggestSelection.cs" />
+ <Compile Include="Monaco\Editor\SuggestSelectionConverter.cs" />
+ <Compile Include="Monaco\Editor\TabCompletion.cs" />
+ <Compile Include="Monaco\Editor\TabCompletionConverter.cs" />
+ <Compile Include="Monaco\Editor\TrackedRangeStickiness.cs" />
+ <Compile Include="Monaco\Editor\WordAtPosition.cs" />
+ <Compile Include="Monaco\Editor\WordWrap.cs" />
+ <Compile Include="Monaco\Editor\WordWrapConverter.cs" />
+ <Compile Include="Monaco\Editor\WrappingIndent.cs" />
+ <Compile Include="Monaco\Editor\WrappingIndentConverter.cs" />
+ <Compile Include="Monaco\Helpers\CssGlyphStyle.cs" />
+ <Compile Include="Monaco\Helpers\CssInlineStyle.cs" />
+ <Compile Include="Monaco\Helpers\CssLineStyle.cs" />
+ <Compile Include="Monaco\Helpers\CssStyleBroker.cs" />
+ <Compile Include="Monaco\Helpers\CssStyleConverter.cs" />
+ <Compile Include="Monaco\Helpers\ICssStyle.cs" />
+ <Compile Include="Monaco\Helpers\Json.cs" />
+ <Compile Include="Monaco\Helpers\TextDecoration.cs" />
+ <Compile Include="Monaco\Helpers\TextDecorationConverter.cs" />
+ <Compile Include="Monaco\LanguagesHelper.cs" />
+ <Compile Include="Monaco\Languages\Command.cs" />
+ <Compile Include="Monaco\Languages\CompletionContext.cs" />
+ <Compile Include="Monaco\Languages\CompletionItem.cs" />
+ <Compile Include="Monaco\Languages\CompletionItemInsertTextRule.cs" />
+ <Compile Include="Monaco\Languages\CompletionItemKind.cs" />
+ <Compile Include="Monaco\Languages\ICompletionItemProvider.cs" />
+ <Compile Include="Monaco\Languages\CompletionList.cs" />
+ <Compile Include="Monaco\Languages\CompletionTriggerKind.cs" />
+ <Compile Include="Monaco\Languages\Hover.cs" />
+ <Compile Include="Monaco\Languages\IHoverProvider.cs" />
+ <Compile Include="Monaco\Languages\LanguageExtensionPoint.cs" />
+ <Compile Include="Monaco\MarkdownString.cs" />
+ <Compile Include="Monaco\IPosition.cs" />
+ <Compile Include="Monaco\IRange.cs" />
+ <Compile Include="Monaco\KeyCode.cs" />
+ <Compile Include="Monaco\KeyMod.cs" />
+ <Compile Include="Monaco\MarkdownStringExtensions.cs" />
+ <Compile Include="Monaco\MarkerSeverity.cs" />
+ <Compile Include="Monaco\MarkerTag.cs" />
+ <Compile Include="Monaco\ModelHelper.cs" />
+ <Compile Include="Monaco\Position.cs" />
+ <Compile Include="Monaco\Range.cs" />
+ <Compile Include="Monaco\Selection.cs" />
+ <Compile Include="Monaco\SelectionDirection.cs" />
+ <Compile Include="Monaco\Uri.cs" />
+ <Compile Include="Monaco\IUriComponents.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <Page Include="Themes\Generic.xaml">
+ <Generator>MSBuild:Compile</Generator>
+ <SubType>Designer</SubType>
+ </Page>
+ <TypeScriptCompile Include="ts-helpermethods\Monaco.Helpers.KeyboardListener.ts">
+ <SubType>Designer</SubType>
+ </TypeScriptCompile>
+ <TypeScriptCompile Include="ts-helpermethods\Monaco.Helpers.ParentAccessor.ts">
+ <SubType>Designer</SubType>
+ </TypeScriptCompile>
+ <TypeScriptCompile Include="ts-helpermethods\updateSelectedContent.ts">
+ <Generator>MSBuild:Compile</Generator>
+ <SubType>Designer</SubType>
+ </TypeScriptCompile>
+ <TypeScriptCompile Include="ts-helpermethods\otherScriptsToBeOrganized.ts">
+ <SubType>Designer</SubType>
+ <Generator>MSBuild:Compile</Generator>
+ </TypeScriptCompile>
+ <TypeScriptCompile Include="ts-helpermethods\registerCompletionItemProvider.ts">
+ <SubType>Designer</SubType>
+ <Generator>MSBuild:Compile</Generator>
+ </TypeScriptCompile>
+ </ItemGroup>
+ <ItemGroup>
+ <Content Include="CodeEditorControl\CodeEditorCore.html" />
+ <Content Include="monaco-editor\*.*" />
+ <Content Include="monaco-editor\min\**\*.*" />
+ <EmbeddedResource Include="Properties\DevToys.rd.xml" />
+ <Content Include="ts-helpermethods\*.js" />
+ </ItemGroup>
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform" Version="$(NuGet_MicrosoftNETCoreUniversalWindowsPlatform)" />
+ <PackageReference Include="Microsoft.Toolkit.Uwp.UI" Version="$(Nuget_MicrosoftToolkitUwpUI)" />
+ <PackageReference Include="Microsoft.TypeScript.MSBuild" Version="$(Nuget_MicrosoftTypeScriptMSBuild)">
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ <PrivateAssets>all</PrivateAssets>
+ </PackageReference>
+ <PackageReference Include="Microsoft.UI.Xaml" Version="$(NuGet_MicrosoftUIXaml)" />
+ <PackageReference Include="Newtonsoft.Json" Version="$(NuGet_NewtonsoftJson)" />
+ <PackageReference Include="ObservableVector" Version="$(Nuget_ObservableVector)" />
+ </ItemGroup>
+ <Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project>
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/Extensions/DispatcherExtensions.cs b/src/dev/impl/DevToys.MonacoEditor/Extensions/DispatcherExtensions.cs
new file mode 100644
index 000000000..f4e7b02da
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Extensions/DispatcherExtensions.cs
@@ -0,0 +1,131 @@
+#nullable enable
+
+using System;
+using System.Threading.Tasks;
+using Windows.UI.Core;
+
+namespace DevToys.MonacoEditor.Extensions
+{
+ internal static class DispatcherExtensions
+ {
+ internal static Task RunOnUIThreadAsync(this CoreDispatcher dispatcher, Action action)
+ {
+ return dispatcher.RunOnUIThreadAsync(ThreadPriority.Normal, action);
+ }
+
+ internal static Task RunOnUIThreadAsync(this CoreDispatcher dispatcher, ThreadPriority priority, Action action)
+ {
+ if (action is null)
+ {
+ return Task.CompletedTask;
+ }
+
+ if (dispatcher.HasThreadAccess)
+ {
+ action();
+ return Task.CompletedTask;
+ }
+ else
+ {
+ return dispatcher.RunAsync(GetDispatcherPriority(priority), () => action()).AsTask();
+ }
+ }
+
+ internal static Task RunOnUIThreadAsync(this CoreDispatcher dispatcher, Func<Task> action)
+ {
+ return dispatcher.RunOnUIThreadAsync(ThreadPriority.Normal, action);
+ }
+
+ internal static async Task RunOnUIThreadAsync(this CoreDispatcher dispatcher, ThreadPriority priority, Func<Task> action)
+ {
+ if (action is null)
+ {
+ return;
+ }
+
+ if (dispatcher.HasThreadAccess)
+ {
+ await action().ConfigureAwait(true);
+ }
+ else
+ {
+ var tcs = new TaskCompletionSource<object>();
+ await dispatcher.RunAsync(
+ GetDispatcherPriority(priority),
+ async () =>
+ {
+ try
+ {
+ await action().ConfigureAwait(true);
+ }
+ catch (Exception ex)
+ {
+ tcs.TrySetException(ex);
+ }
+ finally
+ {
+#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
+ tcs.TrySetResult(null);
+#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
+ }
+ });
+
+ await tcs.Task.ConfigureAwait(false);
+ }
+ }
+
+ internal static Task<T> RunOnUIThreadAsync<T>(this CoreDispatcher dispatcher, Func<Task<T>> action)
+ {
+ return dispatcher.RunOnUIThreadAsync(ThreadPriority.Normal, action);
+ }
+
+ internal static async Task<T> RunOnUIThreadAsync<T>(this CoreDispatcher dispatcher, ThreadPriority priority, Func<Task<T>> action)
+ {
+ if (dispatcher.HasThreadAccess)
+ {
+ return await action().ConfigureAwait(true);
+ }
+ else
+ {
+ T result = default!;
+ var tcs = new TaskCompletionSource<object>();
+ _ = dispatcher.RunAsync(
+ GetDispatcherPriority(priority), async () =>
+ {
+ try
+ {
+ result = await action().ConfigureAwait(true);
+ }
+ catch (Exception ex)
+ {
+ tcs.TrySetException(ex);
+ }
+ finally
+ {
+#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
+ tcs.TrySetResult(null);
+#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
+ }
+ }).AsTask();
+
+ await tcs.Task.ConfigureAwait(false);
+ return result!;
+ }
+ }
+
+ private static CoreDispatcherPriority GetDispatcherPriority(ThreadPriority priority)
+ {
+ switch (priority)
+ {
+ case ThreadPriority.Low:
+ return CoreDispatcherPriority.Low;
+ case ThreadPriority.Normal:
+ return CoreDispatcherPriority.Normal;
+ case ThreadPriority.High:
+ return CoreDispatcherPriority.High;
+ default:
+ throw new NotSupportedException();
+ }
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Extensions/JavaScriptExecutionException.cs b/src/dev/impl/DevToys.MonacoEditor/Extensions/JavaScriptExecutionException.cs
new file mode 100644
index 000000000..daae77197
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Extensions/JavaScriptExecutionException.cs
@@ -0,0 +1,26 @@
+#nullable enable
+
+using System;
+
+namespace DevToys.MonacoEditor.Extensions
+{
+ internal sealed class JavaScriptExecutionException : Exception
+ {
+ public string Script { get; private set; }
+
+ public string? Member { get; private set; }
+
+ public string? FileName { get; private set; }
+
+ public int LineNumber { get; private set; }
+
+ public JavaScriptExecutionException(string? member, string? filename, int line, string script, Exception inner)
+ : base("Error Executing JavaScript Code for " + member + "\nLine " + line + " of " + filename + "\n" + script + "\n", inner)
+ {
+ Member = member;
+ FileName = filename;
+ LineNumber = line;
+ Script = script;
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Extensions/JavaScriptInnerException.cs b/src/dev/impl/DevToys.MonacoEditor/Extensions/JavaScriptInnerException.cs
new file mode 100644
index 000000000..7c5817963
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Extensions/JavaScriptInnerException.cs
@@ -0,0 +1,17 @@
+#nullable enable
+
+using System;
+
+namespace DevToys.MonacoEditor.Extensions
+{
+ internal sealed class JavaScriptInnerException : Exception
+ {
+ public string JavaScriptStackTrace { get; private set; } // TODO Use Enum of JS error types https://www.w3schools.com/js/js_errors.asp
+
+ public JavaScriptInnerException(string message, string stack)
+ : base(message + "\r\n" + stack)
+ {
+ JavaScriptStackTrace = stack;
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Extensions/ThreadPriority.cs b/src/dev/impl/DevToys.MonacoEditor/Extensions/ThreadPriority.cs
new file mode 100644
index 000000000..1c733c3ea
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Extensions/ThreadPriority.cs
@@ -0,0 +1,11 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Extensions
+{
+ internal enum ThreadPriority
+ {
+ Low,
+ Normal,
+ High
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Extensions/WebViewExtensions.cs b/src/dev/impl/DevToys.MonacoEditor/Extensions/WebViewExtensions.cs
new file mode 100644
index 000000000..d6810106f
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Extensions/WebViewExtensions.cs
@@ -0,0 +1,212 @@
+#nullable enable
+
+using DevToys.MonacoEditor.Monaco.Editor;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Serialization;
+using System;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+using Windows.Data.Json;
+using Windows.UI.Xaml.Controls;
+
+namespace DevToys.MonacoEditor.Extensions
+{
+ internal static class WebViewExtensions
+ {
+
+ private static readonly JsonSerializerSettings _settings = new JsonSerializerSettings()
+ {
+ NullValueHandling = NullValueHandling.Ignore,
+ ContractResolver = new CamelCasePropertyNamesContractResolver()
+ };
+
+ static WebViewExtensions()
+ {
+ _settings.Converters.Add(new AcceptSuggestionOnEnterConverter());
+ _settings.Converters.Add(new AccessibilitySupportConverter());
+ _settings.Converters.Add(new AutoClosingBracketsConverter());
+ _settings.Converters.Add(new AutoClosingOvertypeConverter());
+ _settings.Converters.Add(new AutoClosingQuotesConverter());
+ _settings.Converters.Add(new AutoFindInSelectionConverter());
+ _settings.Converters.Add(new AutoIndentConverter());
+ _settings.Converters.Add(new AutoSurroundConverter());
+ _settings.Converters.Add(new CursorBlinkingConverter());
+ _settings.Converters.Add(new CursorStyleConverter());
+ _settings.Converters.Add(new CursorSurroundingLinesStyleConverter());
+ _settings.Converters.Add(new FoldingStrategyConverter());
+ _settings.Converters.Add(new InsertModeConverter());
+ _settings.Converters.Add(new InterfaceToClassConverter<IWordAtPosition, WordAtPosition>());
+ _settings.Converters.Add(new LineNumbersTypeConverter());
+ _settings.Converters.Add(new MatchBracketsConverter());
+ _settings.Converters.Add(new MouseStyleConverter());
+ _settings.Converters.Add(new MultiCursorModifierConverter());
+ _settings.Converters.Add(new MultiCursorPasteConverter());
+ _settings.Converters.Add(new MultipleConverter());
+ _settings.Converters.Add(new RenderLineHighlightConverter());
+ _settings.Converters.Add(new RenderWhitespaceConverter());
+ _settings.Converters.Add(new ScrollbarBehaviorConverter());
+ _settings.Converters.Add(new ShowConverter());
+ _settings.Converters.Add(new SideConverter());
+ _settings.Converters.Add(new SnippetSuggestionsConverter());
+ _settings.Converters.Add(new SuggestSelectionConverter());
+ _settings.Converters.Add(new TabCompletionConverter());
+ _settings.Converters.Add(new WordWrapConverter());
+ _settings.Converters.Add(new WrappingIndentConverter());
+ _settings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter() { NamingStrategy = new CamelCaseNamingStrategy() });
+ }
+
+ public static async Task RunScriptAsync(
+ this WebView _view,
+ string script,
+ [CallerMemberName] string? member = null,
+ [CallerFilePath] string? file = null,
+ [CallerLineNumber] int line = 0)
+ {
+ await _view.RunScriptAsync<object>(script, member, file, line);
+ }
+
+ public static async Task<T?> RunScriptAsync<T>(
+ this WebView _view,
+ string script,
+ [CallerMemberName] string? member = null,
+ [CallerFilePath] string? file = null,
+ [CallerLineNumber] int line = 0)
+ {
+ var start = "try {\n";
+ if (typeof(T) != typeof(object))
+ {
+ script = script.Trim(';');
+ start += "JSON.stringify(" + script + ");";
+ }
+ else
+ {
+ start += script;
+ }
+ var fullscript = start +
+ "\n} catch (err) { JSON.stringify({ wv_internal_error: true, message: err.message, description: err.description, number: err.number, stack: err.stack }); }";
+
+ if (_view.Dispatcher.HasThreadAccess)
+ {
+ try
+ {
+ return await RunScriptHelperAsync<T>(_view, fullscript);
+ }
+ catch (Exception e)
+ {
+ throw new JavaScriptExecutionException(member, file, line, script, e);
+ }
+ }
+ else
+ {
+ return await _view.Dispatcher.RunOnUIThreadAsync(async () =>
+ {
+ try
+ {
+ return await RunScriptHelperAsync<T>(_view, fullscript);
+ }
+ catch (Exception e)
+ {
+ throw new JavaScriptExecutionException(member, file, line, script, e);
+ }
+ });
+ }
+ }
+
+ private static async Task<T?> RunScriptHelperAsync<T>(WebView _view, string script)
+ {
+ var returnstring = await _view.InvokeScriptAsync("eval", new string[] { script });
+
+ if (JsonObject.TryParse(returnstring, out JsonObject result))
+ {
+ if (result.ContainsKey("wv_internal_error") && result["wv_internal_error"].ValueType == JsonValueType.Boolean && result["wv_internal_error"].GetBoolean())
+ {
+ throw new JavaScriptInnerException(result["message"].GetString(), result["stack"].GetString());
+ }
+ }
+
+ if (returnstring != null && returnstring != "null")
+ {
+ return JsonConvert.DeserializeObject<T>(returnstring);
+ }
+
+ return default;
+ }
+
+ public static async Task InvokeScriptAsync(
+ this WebView _view,
+ string method,
+ object arg,
+ bool serialize = true,
+ [CallerMemberName] string? member = null,
+ [CallerFilePath] string? file = null,
+ [CallerLineNumber] int line = 0)
+ {
+ await _view.InvokeScriptAsync<object>(method, arg, serialize, member, file, line);
+ }
+
+ public static async Task InvokeScriptAsync(
+ this WebView _view,
+ string method,
+ object[] args,
+ bool serialize = true,
+ [CallerMemberName] string? member = null,
+ [CallerFilePath] string? file = null,
+ [CallerLineNumber] int line = 0)
+ {
+ await _view.InvokeScriptAsync<object>(method, args, serialize, member, file, line);
+ }
+
+ public static async Task<T?> InvokeScriptAsync<T>(
+ this WebView _view,
+ string method,
+ object arg,
+ bool serialize = true,
+ [CallerMemberName] string? member = null,
+ [CallerFilePath] string? file = null,
+ [CallerLineNumber] int line = 0)
+ {
+ return await _view.InvokeScriptAsync<T>(method, new object[] { arg }, serialize, member, file, line);
+ }
+
+ public static async Task<T?> InvokeScriptAsync<T>(
+ this WebView _view,
+ string method,
+ object[] args,
+ bool serialize = true,
+ [CallerMemberName] string? member = null,
+ [CallerFilePath] string? file = null,
+ [CallerLineNumber] int line = 0)
+ {
+ string[] sanitizedargs;
+
+ if (serialize)
+ {
+ sanitizedargs = args.Select(item =>
+ {
+ if (item is int || item is double)
+ {
+ return item.ToString();
+ }
+ else if (item is string)
+ {
+ return JsonConvert.ToString(item);
+ }
+ else
+ {
+ // TODO: Need JSON.parse?
+ return JsonConvert.SerializeObject(item, _settings);
+ }
+ }).ToArray();
+ }
+ else
+ {
+ sanitizedargs = args.Select(item => item.ToString()).ToArray();
+ }
+
+ var script = method + "(" + string.Join(",", sanitizedargs) + ");";
+
+ return await RunScriptAsync<T>(_view, script, member, file, line);
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Helpers/DebugLogger.cs b/src/dev/impl/DevToys.MonacoEditor/Helpers/DebugLogger.cs
new file mode 100644
index 000000000..b20d0cac1
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Helpers/DebugLogger.cs
@@ -0,0 +1,18 @@
+#nullable enable
+
+using System.Diagnostics;
+using Windows.Foundation.Metadata;
+
+namespace DevToys.MonacoEditor.Helpers
+{
+ [AllowForWeb]
+ public sealed class DebugLogger
+ {
+ public void Log(string message)
+ {
+#if DEBUG
+ Debug.WriteLine(message);
+#endif
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Helpers/DisposableSempahore.cs b/src/dev/impl/DevToys.MonacoEditor/Helpers/DisposableSempahore.cs
new file mode 100644
index 000000000..9cc26860c
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Helpers/DisposableSempahore.cs
@@ -0,0 +1,60 @@
+#nullable enable
+
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace DevToys.MonacoEditor.Helpers
+{
+ /// <summary>
+ /// Represents a semaphore that free other threads when disposing the result of the <see cref="WaitAsync(CancellationToken)"/> method..
+ /// </summary>
+ internal sealed class DisposableSempahore : IDisposable
+ {
+ private readonly object _lockObject = new();
+ private readonly SemaphoreSlim _semaphore;
+
+ internal bool Disposed { get; private set; }
+
+ internal bool IsBusy => _semaphore.CurrentCount == 0;
+
+ internal DisposableSempahore(int maxTasksCount = 1)
+ {
+ _semaphore = new SemaphoreSlim(maxTasksCount, maxTasksCount);
+ }
+
+ public void Dispose()
+ {
+ lock (_lockObject)
+ {
+ if (!Disposed)
+ {
+ Disposed = true;
+ _semaphore.Dispose();
+ }
+ }
+ }
+
+ internal async Task<IDisposable> WaitAsync(CancellationToken cancellationToken)
+ {
+ await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
+
+ return new DummyDisposable(_semaphore);
+ }
+
+ private sealed class DummyDisposable : IDisposable
+ {
+ private readonly SemaphoreSlim _semaphore;
+
+ internal DummyDisposable(SemaphoreSlim semaphore)
+ {
+ _semaphore = semaphore;
+ }
+
+ public void Dispose()
+ {
+ _semaphore.Release();
+ }
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Helpers/IParentAccessorAcceptor.cs b/src/dev/impl/DevToys.MonacoEditor/Helpers/IParentAccessorAcceptor.cs
new file mode 100644
index 000000000..5c5c07909
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Helpers/IParentAccessorAcceptor.cs
@@ -0,0 +1,15 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Helpers
+{
+ /// <summary>
+ /// Interface used on objects to be accessed.
+ /// </summary>
+ public interface IParentAccessorAcceptor
+ {
+ /// <summary>
+ /// Property to tell object the value is being set by ParentAccessor.
+ /// </summary>
+ bool IsSettingValue { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Helpers/KeyboardListener.cs b/src/dev/impl/DevToys.MonacoEditor/Helpers/KeyboardListener.cs
new file mode 100644
index 000000000..cc07d5b9a
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Helpers/KeyboardListener.cs
@@ -0,0 +1,45 @@
+#nullable enable
+
+using DevToys.MonacoEditor.CodeEditorControl;
+using System;
+using Windows.Foundation.Metadata;
+
+namespace DevToys.MonacoEditor.Helpers
+{
+ [AllowForWeb]
+ public sealed class KeyboardListener
+ {
+ private readonly WeakReference<CodeEditorCore> parent;
+
+ public KeyboardListener(CodeEditorCore parent) // TODO: Make Interface for event usage
+ {
+ this.parent = new WeakReference<CodeEditorCore>(parent);
+ }
+
+ /// <summary>
+ /// Called from JavaScript, returns if event was handled or not.
+ /// </summary>
+ /// <param name="keycode"></param>
+ /// <param name="ctrl"></param>
+ /// <param name="shift"></param>
+ /// <param name="alt"></param>
+ /// <param name="meta"></param>
+ /// <returns></returns>
+ public bool KeyDown(int keycode, bool ctrl, bool shift, bool alt, bool meta)
+ {
+ if (parent.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.TriggerKeyDown(new WebKeyEventArgs()
+ {
+ KeyCode = keycode, // TODO: Convert to a virtual key or something?
+ CtrlKey = ctrl,
+ ShiftKey = shift,
+ AltKey = alt,
+ MetaKey = meta
+ });
+ }
+
+ return false;
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Helpers/ParentAccessor.cs b/src/dev/impl/DevToys.MonacoEditor/Helpers/ParentAccessor.cs
new file mode 100644
index 000000000..07d310759
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Helpers/ParentAccessor.cs
@@ -0,0 +1,252 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Runtime.InteropServices.WindowsRuntime;
+using System.Threading.Tasks;
+using Windows.Foundation;
+using Windows.Foundation.Metadata;
+
+namespace DevToys.MonacoEditor.Helpers
+{
+ /// <summary>
+ /// Class to aid in accessing WinRT values from JavaScript.
+ /// Not Thread Safe.
+ /// </summary>
+ [AllowForWeb]
+ public sealed class ParentAccessor : IDisposable
+ {
+ private readonly WeakReference<IParentAccessorAcceptor> parent;
+ private readonly Type typeinfo;
+ private Dictionary<string, Action>? actions;
+ private Dictionary<string, Func<string[], Task<string?>>>? events;
+
+ private List<Assembly> Assemblies { get; set; } = new List<Assembly>();
+
+ /// <summary>
+ /// Constructs a new reflective parent Accessor for the provided object.
+ /// </summary>
+ /// <param name="parent">Object to provide Property Access.</param>
+ public ParentAccessor(IParentAccessorAcceptor parent)
+ {
+ this.parent = new WeakReference<IParentAccessorAcceptor>(parent);
+ typeinfo = parent.GetType();
+ actions = new Dictionary<string, Action>();
+ events = new Dictionary<string, Func<string[], Task<string?>>>();
+ }
+
+ /// <summary>
+ /// Registers an action from the .NET side which can be called from within the JavaScript code.
+ /// </summary>
+ /// <param name="name">String Key.</param>
+ /// <param name="action">Action to perform.</param>
+ internal void RegisterAction(string name, Action action)
+ {
+ if (actions is null)
+ {
+ throw new NullReferenceException();
+ }
+
+ actions[name] = action;
+ }
+
+ /// <summary>
+ /// Registers an event from the .NET side which can be called with the given jsonified string arguments within the JavaScript code.
+ /// </summary>
+ /// <param name="name">String Key.</param>
+ /// <param name="function">Event to call.</param>
+ internal void RegisterEvent(string name, Func<string[], Task<string?>> function)
+ {
+ if (events is null)
+ {
+ throw new NullReferenceException();
+ }
+
+ events[name] = function;
+ }
+
+ /// <summary>
+ /// Calls an Event registered before with the <see cref="RegisterEvent(string, Func{string[], Task{string}})"/>.
+ /// </summary>
+ /// <param name="name">Name of event to call.</param>
+ /// <param name="parameters">JSON string Parameters.</param>
+ /// <returns></returns>
+ public IAsyncOperation<string?>? CallEvent(string name, [ReadOnlyArray] string[] parameters)
+ {
+ if (events is not null && events.ContainsKey(name))
+ {
+ return events[name]?.Invoke(parameters).AsAsyncOperation();
+ }
+
+ return new Task<string?>(() => { return null; }).AsAsyncOperation();
+ }
+
+ /// <summary>
+ /// Adds an Assembly to use for looking up types by name for <see cref="SetValue(string, string, string)"/>.
+ /// </summary>
+ /// <param name="assembly">Assembly to add.</param>
+ internal void AddAssemblyForTypeLookup(Assembly assembly)
+ {
+ Assemblies.Add(assembly);
+ }
+
+ /// <summary>
+ /// Calls an Action registered before with <see cref="RegisterAction(string, Action)"/>.
+ /// </summary>
+ /// <param name="name">String Key.</param>
+ /// <returns>True if method was found in registration.</returns>
+ public bool CallAction(string name)
+ {
+ if (actions is not null && actions.ContainsKey(name))
+ {
+ actions[name]?.Invoke();
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Returns the winrt primative object value for the specified Property.
+ /// </summary>
+ /// <param name="name">Property name on Parent Object.</param>
+ /// <returns>Property Value or null.</returns>
+ public object? GetValue(string name)
+ {
+ if (parent.TryGetTarget(out IParentAccessorAcceptor tobj))
+ {
+ var propinfo = typeinfo.GetProperty(name);
+ return propinfo?.GetValue(tobj);
+ }
+
+ return null;
+ }
+
+ public string GetJsonValue(string name)
+ {
+ if (parent.TryGetTarget(out IParentAccessorAcceptor tobj))
+ {
+ var propinfo = typeinfo.GetProperty(name);
+ var obj = propinfo?.GetValue(tobj);
+
+ return JsonConvert.SerializeObject(obj, new JsonSerializerSettings()
+ {
+ NullValueHandling = NullValueHandling.Ignore
+ });
+ }
+
+ return "{}";
+ }
+
+ /// <summary>
+ /// Returns the winrt primative object value for a child property off of the specified Property.
+ ///
+ /// Useful for providing complex types to users of Parent but still access primatives in JavaScript.
+ /// </summary>
+ /// <param name="name">Parent Property name.</param>
+ /// <param name="child">Property's Property name to retrieve.</param>
+ /// <returns>Value of Child Property or null.</returns>
+ public object? GetChildValue(string name, string child)
+ {
+ if (parent.TryGetTarget(out IParentAccessorAcceptor tobj))
+ {
+ // TODO: Support params for multi-level digging?
+ var propinfo = typeinfo.GetProperty(name);
+ var prop = propinfo?.GetValue(tobj);
+ if (prop != null)
+ {
+ var childinfo = prop.GetType().GetProperty(child);
+ return childinfo?.GetValue(prop);
+ }
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Sets the value for the specified Property.
+ /// </summary>
+ /// <param name="name">Parent Property name.</param>
+ /// <param name="value">Value to set.</param>
+ public void SetValue(string name, object value)
+ {
+ if (parent.TryGetTarget(out IParentAccessorAcceptor tobj))
+ {
+ var propinfo = typeinfo.GetProperty(name); // TODO: Cache these?
+ tobj.IsSettingValue = true;
+ propinfo?.SetValue(tobj, value);
+ tobj.IsSettingValue = false;
+ }
+ }
+
+ /// <summary>
+ /// Sets the value for the specified Property after deserializing the value as the given type name.
+ /// </summary>
+ /// <param name="name"></param>
+ /// <param name="value"></param>
+ /// <param name="type"></param>
+ public void SetValue(string name, string value, string type)
+ {
+ if (parent.TryGetTarget(out IParentAccessorAcceptor tobj))
+ {
+ var propinfo = typeinfo.GetProperty(name);
+ var typeobj = LookForTypeByName(type);
+
+ if (typeobj is null)
+ {
+ throw new Exception("Type not found");
+ }
+
+ var obj = JsonConvert.DeserializeObject(value, typeobj);
+
+ tobj.IsSettingValue = true;
+ propinfo?.SetValue(tobj, obj);
+ tobj.IsSettingValue = false;
+ }
+ }
+
+ private Type? LookForTypeByName(string name)
+ {
+ // First search locally
+ var result = Type.GetType(name);
+
+ if (result != null)
+ {
+ return result;
+ }
+
+ // Search in Other Assemblies
+ foreach (var assembly in Assemblies)
+ {
+ foreach (var typeInfo in assembly.ExportedTypes)
+ {
+ if (typeInfo.Name == name)
+ {
+ return typeInfo;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ public void Dispose()
+ {
+ if (actions != null)
+ {
+ actions.Clear();
+ }
+
+ actions = null;
+
+ if (events != null)
+ {
+ events.Clear();
+ }
+
+ events = null;
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Helpers/ThemeListener.cs b/src/dev/impl/DevToys.MonacoEditor/Helpers/ThemeListener.cs
new file mode 100644
index 000000000..f277f5f85
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Helpers/ThemeListener.cs
@@ -0,0 +1,104 @@
+#nullable enable
+
+using System;
+using Windows.ApplicationModel.Core;
+using Windows.Foundation.Metadata;
+using Windows.UI;
+using Windows.UI.ViewManagement;
+using Windows.UI.Xaml;
+using Windows.UI.Xaml.Media;
+
+namespace DevToys.MonacoEditor.Helpers
+{
+ public delegate void ThemeChangedEvent(ThemeListener sender);
+
+ /// <summary>
+ /// Class which listens for changes to Application Theme or High Contrast Modes
+ /// and Signals an Event when they occur.
+ /// </summary>
+ [AllowForWeb]
+ public sealed class ThemeListener
+ {
+ private readonly AccessibilitySettings _accessible = new AccessibilitySettings();
+ private readonly UISettings _uiSettings = new UISettings();
+
+ public string CurrentThemeName { get { return CurrentTheme.ToString(); } } // For Web Retrieval
+
+ public string AccentColorHtmlHex { get; private set; }
+
+ public ApplicationTheme CurrentTheme { get; set; }
+
+ public bool IsHighContrast { get; set; }
+
+ public event ThemeChangedEvent? ThemeChanged;
+
+ public ThemeListener()
+ {
+ AccentColorHtmlHex = ToHtmlHex(((SolidColorBrush)Application.Current.Resources["TextControlSelectionHighlightColor"]).Color);
+ CurrentTheme = Application.Current.RequestedTheme;
+ IsHighContrast = _accessible.HighContrast;
+
+ _accessible.HighContrastChanged += Accessible_HighContrastChanged;
+ _uiSettings.ColorValuesChanged += UiSettings_ColorValuesChanged;
+
+ if (Window.Current.Content is FrameworkElement frameworkElement)
+ {
+ CurrentTheme = frameworkElement.ActualTheme == ElementTheme.Dark ? ApplicationTheme.Dark : ApplicationTheme.Light;
+ frameworkElement.ActualThemeChanged += Window_ActualThemeChanged;
+ }
+ }
+
+ ~ThemeListener()
+ {
+ _accessible.HighContrastChanged -= Accessible_HighContrastChanged;
+ }
+
+ private void Window_ActualThemeChanged(FrameworkElement sender, object args)
+ {
+ UpdateProperties();
+ }
+
+ private async void UiSettings_ColorValuesChanged(UISettings sender, object args)
+ {
+ // Getting called off thread, so we need to dispatch to request value.
+ await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
+ {
+ UpdateProperties();
+ });
+ }
+
+ private void Accessible_HighContrastChanged(AccessibilitySettings sender, object args)
+ {
+ UpdateProperties();
+ }
+
+ /// <summary>
+ /// Set our current properties and fire a change notification.
+ /// </summary>
+ private void UpdateProperties()
+ {
+ // TODO: Not sure if HighContrastScheme names are localized?
+ if (_accessible.HighContrast && _accessible.HighContrastScheme.IndexOf("white", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ // If our HighContrastScheme is ON & a lighter one, then we should remain in 'Light' theme mode for Monaco Themes Perspective
+ IsHighContrast = false;
+ CurrentTheme = ApplicationTheme.Light;
+ }
+ else
+ {
+ // Otherwise, we just set to what's in the system as we'd expect.
+ IsHighContrast = _accessible.HighContrast;
+ CurrentTheme = ((FrameworkElement)Window.Current.Content).ActualTheme == ElementTheme.Dark ? ApplicationTheme.Dark : ApplicationTheme.Light;
+ }
+
+ AccentColorHtmlHex = ToHtmlHex(((SolidColorBrush)Application.Current.Resources["TextControlSelectionHighlightColor"]).Color);
+
+ ThemeChanged?.Invoke(this);
+ }
+
+ public static string ToHtmlHex(Color color)
+ {
+ return $"#{color.R:X2}{color.G:X2}{color.B:X2}{color.A:X2}";
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Helpers/WebKeyEventArgs.cs b/src/dev/impl/DevToys.MonacoEditor/Helpers/WebKeyEventArgs.cs
new file mode 100644
index 000000000..cf987e6cc
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Helpers/WebKeyEventArgs.cs
@@ -0,0 +1,24 @@
+#nullable enable
+
+using DevToys.MonacoEditor.CodeEditorControl;
+
+namespace DevToys.MonacoEditor.Helpers
+{
+ public delegate void WebKeyEventHandler(CodeEditorCore sender, WebKeyEventArgs args);
+
+ public sealed class WebKeyEventArgs
+ {
+ public int KeyCode { get; set; }
+
+ // TODO: Make these some sort of flagged state enum?
+ public bool CtrlKey { get; set; }
+
+ public bool ShiftKey { get; set; }
+
+ public bool AltKey { get; set; }
+
+ public bool MetaKey { get; set; }
+
+ public bool Handled { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AcceptSuggestionOnEnter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AcceptSuggestionOnEnter.cs
new file mode 100644
index 000000000..a5e66115b
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AcceptSuggestionOnEnter.cs
@@ -0,0 +1,18 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Accept suggestions on ENTER.
+ /// Defaults to 'on'.
+ /// </summary>
+ [JsonConverter(typeof(AcceptSuggestionOnEnterConverter))]
+ public enum AcceptSuggestionOnEnter
+ {
+ Off,
+ On,
+ Smart
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AcceptSuggestionOnEnterConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AcceptSuggestionOnEnterConverter.cs
new file mode 100644
index 000000000..dc44f1f68
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AcceptSuggestionOnEnterConverter.cs
@@ -0,0 +1,59 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class AcceptSuggestionOnEnterConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(AcceptSuggestionOnEnter) || t == typeof(AcceptSuggestionOnEnter?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "off":
+ return AcceptSuggestionOnEnter.Off;
+ case "on":
+ return AcceptSuggestionOnEnter.On;
+ case "smart":
+ return AcceptSuggestionOnEnter.Smart;
+ }
+
+ throw new Exception("Cannot unmarshal type AcceptSuggestionOnEnter");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (AcceptSuggestionOnEnter)untypedValue;
+ switch (value)
+ {
+ case AcceptSuggestionOnEnter.Off:
+ serializer.Serialize(writer, "off");
+ return;
+ case AcceptSuggestionOnEnter.On:
+ serializer.Serialize(writer, "on");
+ return;
+ case AcceptSuggestionOnEnter.Smart:
+ serializer.Serialize(writer, "smart");
+ return;
+ }
+ throw new Exception("Cannot marshal type AcceptSuggestionOnEnter");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AccessibilitySupport.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AccessibilitySupport.cs
new file mode 100644
index 000000000..e8879e462
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AccessibilitySupport.cs
@@ -0,0 +1,18 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Configure the editor's accessibility support.
+ /// Defaults to 'auto'. It is best to leave this to 'auto'.
+ /// </summary>
+ [JsonConverter(typeof(AccessibilitySupportConverter))]
+ public enum AccessibilitySupport
+ {
+ Auto,
+ Off,
+ On
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AccessibilitySupportConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AccessibilitySupportConverter.cs
new file mode 100644
index 000000000..c71b2a9f0
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AccessibilitySupportConverter.cs
@@ -0,0 +1,61 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class AccessibilitySupportConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(AccessibilitySupport) || t == typeof(AccessibilitySupport?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "auto":
+ return AccessibilitySupport.Auto;
+ case "off":
+ return AccessibilitySupport.Off;
+ case "on":
+ return AccessibilitySupport.On;
+ }
+
+ throw new Exception("Cannot unmarshal type AccessibilitySupport");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+
+ var value = (AccessibilitySupport)untypedValue;
+ switch (value)
+ {
+ case AccessibilitySupport.Auto:
+ serializer.Serialize(writer, "auto");
+ return;
+ case AccessibilitySupport.Off:
+ serializer.Serialize(writer, "off");
+ return;
+ case AccessibilitySupport.On:
+ serializer.Serialize(writer, "on");
+ return;
+ }
+
+ throw new Exception("Cannot marshal type AccessibilitySupport");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingBrackets.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingBrackets.cs
new file mode 100644
index 000000000..5ed4a8d9e
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingBrackets.cs
@@ -0,0 +1,19 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Options for auto closing brackets.
+ /// Defaults to language defined behavior.
+ /// </summary>
+ [JsonConverter(typeof(AutoClosingBracketsConverter))]
+ public enum AutoClosingBrackets
+ {
+ Always,
+ BeforeWhitespace,
+ LanguageDefined,
+ Never
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingBracketsConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingBracketsConverter.cs
new file mode 100644
index 000000000..912685724
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingBracketsConverter.cs
@@ -0,0 +1,66 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class AutoClosingBracketsConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(AutoClosingBrackets) || t == typeof(AutoClosingBrackets?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "always":
+ return AutoClosingBrackets.Always;
+ case "beforeWhitespace":
+ return AutoClosingBrackets.BeforeWhitespace;
+ case "languageDefined":
+ return AutoClosingBrackets.LanguageDefined;
+ case "never":
+ return AutoClosingBrackets.Never;
+ }
+
+ throw new Exception("Cannot unmarshal type AutoClosingBrackets");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+
+ var value = (AutoClosingBrackets)untypedValue;
+ switch (value)
+ {
+ case AutoClosingBrackets.Always:
+ serializer.Serialize(writer, "always");
+ return;
+ case AutoClosingBrackets.BeforeWhitespace:
+ serializer.Serialize(writer, "beforeWhitespace");
+ return;
+ case AutoClosingBrackets.LanguageDefined:
+ serializer.Serialize(writer, "languageDefined");
+ return;
+ case AutoClosingBrackets.Never:
+ serializer.Serialize(writer, "never");
+ return;
+ }
+
+ throw new Exception("Cannot marshal type AutoClosingBrackets");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingOvertype.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingOvertype.cs
new file mode 100644
index 000000000..7d48bdd59
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingOvertype.cs
@@ -0,0 +1,16 @@
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Options for typing over closing quotes or brackets.
+ /// </summary>
+ [JsonConverter(typeof(AutoClosingOvertypeConverter))]
+ public enum AutoClosingOvertype
+ {
+ Always,
+ Auto,
+ Never
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingOvertypeConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingOvertypeConverter.cs
new file mode 100644
index 000000000..0a5894e98
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingOvertypeConverter.cs
@@ -0,0 +1,58 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class AutoClosingOvertypeConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(AutoClosingOvertype) || t == typeof(AutoClosingOvertype?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "always":
+ return AutoClosingOvertype.Always;
+ case "auto":
+ return AutoClosingOvertype.Auto;
+ case "never":
+ return AutoClosingOvertype.Never;
+ }
+ throw new Exception("Cannot unmarshal type AutoClosingOvertype");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (AutoClosingOvertype)untypedValue;
+ switch (value)
+ {
+ case AutoClosingOvertype.Always:
+ serializer.Serialize(writer, "always");
+ return;
+ case AutoClosingOvertype.Auto:
+ serializer.Serialize(writer, "auto");
+ return;
+ case AutoClosingOvertype.Never:
+ serializer.Serialize(writer, "never");
+ return;
+ }
+ throw new Exception("Cannot marshal type AutoClosingOvertype");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingQuotes.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingQuotes.cs
new file mode 100644
index 000000000..4e6ca2b53
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingQuotes.cs
@@ -0,0 +1,20 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Options for auto closing quotes.
+ /// Defaults to language defined behavior.
+ /// </summary>
+ [JsonConverter(typeof(AutoClosingQuotesConverter))]
+ public enum AutoClosingQuotes
+ {
+ Always,
+ BeforeWhitespace,
+ LanguageDefined,
+ Never
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingQuotesConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingQuotesConverter.cs
new file mode 100644
index 000000000..ac6fa7445
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoClosingQuotesConverter.cs
@@ -0,0 +1,68 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class AutoClosingQuotesConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(AutoClosingQuotes) || t == typeof(AutoClosingQuotes?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "always":
+ return AutoClosingQuotes.Always;
+ case "beforeWhitespace":
+ return AutoClosingQuotes.BeforeWhitespace;
+ case "languageDefined":
+ return AutoClosingQuotes.LanguageDefined;
+ case "never":
+ return AutoClosingQuotes.Never;
+ }
+
+ throw new Exception("Cannot unmarshal type AutoClosingQuotes");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+
+ var value = (AutoClosingQuotes)untypedValue;
+ switch (value)
+ {
+ case AutoClosingQuotes.Always:
+ serializer.Serialize(writer, "always");
+ return;
+ case AutoClosingQuotes.BeforeWhitespace:
+ serializer.Serialize(writer, "beforeWhitespace");
+ return;
+ case AutoClosingQuotes.LanguageDefined:
+ serializer.Serialize(writer, "languageDefined");
+ return;
+ case AutoClosingQuotes.Never:
+ serializer.Serialize(writer, "never");
+ return;
+ }
+
+ throw new Exception("Cannot marshal type AutoClosingQuotes");
+ }
+
+ public static readonly AutoClosingQuotesConverter Singleton = new AutoClosingQuotesConverter();
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoFindInSelection.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoFindInSelection.cs
new file mode 100644
index 000000000..fa2a6f89e
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoFindInSelection.cs
@@ -0,0 +1,18 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Controls if Find in Selection flag is turned on in the editor.
+ /// </summary>
+ [JsonConverter(typeof(AutoFindInSelectionConverter))]
+ public enum AutoFindInSelection
+ {
+ Always,
+ Multiline,
+ Never
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoFindInSelectionConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoFindInSelectionConverter.cs
new file mode 100644
index 000000000..5fc5010a5
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoFindInSelectionConverter.cs
@@ -0,0 +1,61 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class AutoFindInSelectionConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(AutoFindInSelection) || t == typeof(AutoFindInSelection?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "always":
+ return AutoFindInSelection.Always;
+ case "multiline":
+ return AutoFindInSelection.Multiline;
+ case "never":
+ return AutoFindInSelection.Never;
+ }
+
+ throw new Exception("Cannot unmarshal type AutoFindInSelection");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+
+ var value = (AutoFindInSelection)untypedValue;
+ switch (value)
+ {
+ case AutoFindInSelection.Always:
+ serializer.Serialize(writer, "always");
+ return;
+ case AutoFindInSelection.Multiline:
+ serializer.Serialize(writer, "multiline");
+ return;
+ case AutoFindInSelection.Never:
+ serializer.Serialize(writer, "never");
+ return;
+ }
+
+ throw new Exception("Cannot marshal type AutoFindInSelection");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoIndent.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoIndent.cs
new file mode 100644
index 000000000..45caf8da9
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoIndent.cs
@@ -0,0 +1,20 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Enable auto indentation adjustment.
+ /// Defaults to false.
+ /// </summary>
+ [JsonConverter(typeof(AutoIndentConverter))]
+ public enum AutoIndent
+ {
+ Advanced,
+ Brackets,
+ Full,
+ Keep,
+ None
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoIndentConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoIndentConverter.cs
new file mode 100644
index 000000000..76020a0ac
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoIndentConverter.cs
@@ -0,0 +1,68 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class AutoIndentConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t) => t == typeof(AutoIndent) || t == typeof(AutoIndent?);
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "advanced":
+ return AutoIndent.Advanced;
+ case "brackets":
+ return AutoIndent.Brackets;
+ case "full":
+ return AutoIndent.Full;
+ case "keep":
+ return AutoIndent.Keep;
+ case "none":
+ return AutoIndent.None;
+ }
+
+ throw new Exception("Cannot unmarshal type AutoIndent");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+
+ var value = (AutoIndent)untypedValue;
+ switch (value)
+ {
+ case AutoIndent.Advanced:
+ serializer.Serialize(writer, "advanced");
+ return;
+ case AutoIndent.Brackets:
+ serializer.Serialize(writer, "brackets");
+ return;
+ case AutoIndent.Full:
+ serializer.Serialize(writer, "full");
+ return;
+ case AutoIndent.Keep:
+ serializer.Serialize(writer, "keep");
+ return;
+ case AutoIndent.None:
+ serializer.Serialize(writer, "none");
+ return;
+ }
+
+ throw new Exception("Cannot marshal type AutoIndent");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoSurround.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoSurround.cs
new file mode 100644
index 000000000..6d8788b53
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoSurround.cs
@@ -0,0 +1,19 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Options for auto surrounding.
+ /// Defaults to always allowing auto surrounding.
+ /// </summary>
+ [JsonConverter(typeof(AutoSurroundConverter))]
+ public enum AutoSurround
+ {
+ Brackets,
+ LanguageDefined,
+ Never,
+ Quotes
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoSurroundConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoSurroundConverter.cs
new file mode 100644
index 000000000..1001d8e50
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/AutoSurroundConverter.cs
@@ -0,0 +1,64 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class AutoSurroundConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(AutoSurround) || t == typeof(AutoSurround?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "brackets":
+ return AutoSurround.Brackets;
+ case "languageDefined":
+ return AutoSurround.LanguageDefined;
+ case "never":
+ return AutoSurround.Never;
+ case "quotes":
+ return AutoSurround.Quotes;
+ }
+
+ throw new Exception("Cannot unmarshal type AutoSurround");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (AutoSurround)untypedValue;
+ switch (value)
+ {
+ case AutoSurround.Brackets:
+ serializer.Serialize(writer, "brackets");
+ return;
+ case AutoSurround.LanguageDefined:
+ serializer.Serialize(writer, "languageDefined");
+ return;
+ case AutoSurround.Never:
+ serializer.Serialize(writer, "never");
+ return;
+ case AutoSurround.Quotes:
+ serializer.Serialize(writer, "quotes");
+ return;
+ }
+ throw new Exception("Cannot marshal type AutoSurround");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ContextKey.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ContextKey.cs
new file mode 100644
index 000000000..7548ff4db
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ContextKey.cs
@@ -0,0 +1,56 @@
+#nullable enable
+
+using DevToys.MonacoEditor.CodeEditorControl;
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ public sealed class ContextKey : IContextKey
+ {
+ [JsonIgnore]
+ private readonly WeakReference<CodeEditorCore> _editor;
+
+ [JsonProperty("key")]
+ public string Key { get; private set; }
+ [JsonProperty("defaultValue")]
+ public bool DefaultValue { get; private set; }
+ [JsonProperty("value")]
+ public bool Value { get; private set; }
+
+ internal ContextKey(CodeEditorCore editor, string key, bool defaultValue)
+ {
+ _editor = new WeakReference<CodeEditorCore>(editor);
+
+ Key = key;
+ DefaultValue = defaultValue;
+ }
+
+ private async void UpdateValueAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ await editor.InvokeScriptAsync("updateContext", new object[] { Key, Value });
+ }
+ }
+
+ public bool Get()
+ {
+ return Value;
+ }
+
+ public void Reset()
+ {
+ Value = DefaultValue;
+
+ UpdateValueAsync();
+ }
+
+ public void Set(bool value)
+ {
+ Value = value;
+
+ UpdateValueAsync();
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorBlinking.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorBlinking.cs
new file mode 100644
index 000000000..6b8de4afb
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorBlinking.cs
@@ -0,0 +1,21 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Control the cursor animation style, possible values are 'blink', 'smooth', 'phase',
+ /// 'expand' and 'solid'.
+ /// Defaults to 'blink'.
+ /// </summary>
+ [JsonConverter(typeof(CursorBlinkingConverter))]
+ public enum CursorBlinking
+ {
+ Blink,
+ Expand,
+ Phase,
+ Smooth,
+ Solid
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorBlinkingConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorBlinkingConverter.cs
new file mode 100644
index 000000000..397e93639
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorBlinkingConverter.cs
@@ -0,0 +1,66 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class CursorBlinkingConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t) => t == typeof(CursorBlinking) || t == typeof(CursorBlinking?);
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "blink":
+ return CursorBlinking.Blink;
+ case "expand":
+ return CursorBlinking.Expand;
+ case "phase":
+ return CursorBlinking.Phase;
+ case "smooth":
+ return CursorBlinking.Smooth;
+ case "solid":
+ return CursorBlinking.Solid;
+ }
+
+ throw new Exception("Cannot unmarshal type CursorBlinking");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (CursorBlinking)untypedValue;
+ switch (value)
+ {
+ case CursorBlinking.Blink:
+ serializer.Serialize(writer, "blink");
+ return;
+ case CursorBlinking.Expand:
+ serializer.Serialize(writer, "expand");
+ return;
+ case CursorBlinking.Phase:
+ serializer.Serialize(writer, "phase");
+ return;
+ case CursorBlinking.Smooth:
+ serializer.Serialize(writer, "smooth");
+ return;
+ case CursorBlinking.Solid:
+ serializer.Serialize(writer, "solid");
+ return;
+ }
+ throw new Exception("Cannot marshal type CursorBlinking");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorStyle.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorStyle.cs
new file mode 100644
index 000000000..a5b6097f3
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorStyle.cs
@@ -0,0 +1,21 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Control the cursor style, either 'block' or 'line'.
+ /// Defaults to 'line'.
+ /// </summary>
+ [JsonConverter(typeof(CursorStyleConverter))]
+ public enum CursorStyle
+ {
+ Block,
+ BlockOutline,
+ Line,
+ LineThin,
+ Underline,
+ UnderlineThin
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorStyleConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorStyleConverter.cs
new file mode 100644
index 000000000..44ba79ae7
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorStyleConverter.cs
@@ -0,0 +1,76 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class CursorStyleConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(CursorStyle) || t == typeof(CursorStyle?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "block":
+ return CursorStyle.Block;
+ case "block-outline":
+ return CursorStyle.BlockOutline;
+ case "line":
+ return CursorStyle.Line;
+ case "line-thin":
+ return CursorStyle.LineThin;
+ case "underline":
+ return CursorStyle.Underline;
+ case "underline-thin":
+ return CursorStyle.UnderlineThin;
+ }
+
+ throw new Exception("Cannot unmarshal type CursorStyle");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+
+ var value = (CursorStyle)untypedValue;
+ switch (value)
+ {
+ case CursorStyle.Block:
+ serializer.Serialize(writer, "block");
+ return;
+ case CursorStyle.BlockOutline:
+ serializer.Serialize(writer, "block-outline");
+ return;
+ case CursorStyle.Line:
+ serializer.Serialize(writer, "line");
+ return;
+ case CursorStyle.LineThin:
+ serializer.Serialize(writer, "line-thin");
+ return;
+ case CursorStyle.Underline:
+ serializer.Serialize(writer, "underline");
+ return;
+ case CursorStyle.UnderlineThin:
+ serializer.Serialize(writer, "underline-thin");
+ return;
+ }
+
+ throw new Exception("Cannot marshal type CursorStyle");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorSurroundingLinesStyle.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorSurroundingLinesStyle.cs
new file mode 100644
index 000000000..69eec3ead
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorSurroundingLinesStyle.cs
@@ -0,0 +1,19 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Controls when `cursorSurroundingLines` should be enforced
+ /// Defaults to `default`, `cursorSurroundingLines` is not enforced when cursor position is
+ /// changed
+ /// by mouse.
+ /// </summary>
+ [JsonConverter(typeof(CursorSurroundingLinesStyleConverter))]
+ public enum CursorSurroundingLinesStyle
+ {
+ All,
+ Default
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorSurroundingLinesStyleConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorSurroundingLinesStyleConverter.cs
new file mode 100644
index 000000000..b7fa84f8a
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/CursorSurroundingLinesStyleConverter.cs
@@ -0,0 +1,55 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class CursorSurroundingLinesStyleConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(CursorSurroundingLinesStyle) || t == typeof(CursorSurroundingLinesStyle?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "all":
+ return CursorSurroundingLinesStyle.All;
+ case "default":
+ return CursorSurroundingLinesStyle.Default;
+ }
+
+ throw new Exception("Cannot unmarshal type CursorSurroundingLinesStyle");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+
+ var value = (CursorSurroundingLinesStyle)untypedValue;
+ switch (value)
+ {
+ case CursorSurroundingLinesStyle.All:
+ serializer.Serialize(writer, "all");
+ return;
+ case CursorSurroundingLinesStyle.Default:
+ serializer.Serialize(writer, "default");
+ return;
+ }
+ throw new Exception("Cannot marshal type CursorSurroundingLinesStyle");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/DiffEditorConstructionOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/DiffEditorConstructionOptions.cs
new file mode 100644
index 000000000..702611f1e
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/DiffEditorConstructionOptions.cs
@@ -0,0 +1,823 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Runtime.CompilerServices;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ public sealed class DiffEditorConstructionOptions : IDiffEditorConstructionOptions, INotifyPropertyChanged
+ {
+ public event PropertyChangedEventHandler? PropertyChanged;
+
+ private readonly Dictionary<string, object?> _propertyBackingDictionary = new Dictionary<string, object?>();
+
+ private T? GetPropertyValue<T>([CallerMemberName] string? propertyName = null)
+ {
+ if (propertyName == null)
+ {
+ throw new ArgumentNullException(nameof(propertyName));
+ }
+
+ if (_propertyBackingDictionary.TryGetValue(propertyName, out object? value))
+ {
+ return (T?)value;
+ }
+
+ return default;
+ }
+
+ private bool SetPropertyValue<T>(T newValue, [CallerMemberName] string? propertyName = null)
+ {
+ if (propertyName == null)
+ {
+ throw new ArgumentNullException(nameof(propertyName));
+ }
+
+ if (EqualityComparer<T?>.Default.Equals(newValue, GetPropertyValue<T?>(propertyName)))
+ {
+ return false;
+ }
+
+ if (_propertyBackingDictionary.TryGetValue(propertyName, out object? value)
+ && value is T typedValue
+ && typedValue.Equals(newValue))
+ {
+ return true;
+ }
+
+ _propertyBackingDictionary[propertyName] = newValue;
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ return true;
+ }
+
+ /// <summary>
+ /// Accept suggestions on provider defined characters.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("acceptSuggestionOnCommitCharacter", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? AcceptSuggestionOnCommitCharacter
+ {
+ get => GetPropertyValue<bool?>();
+ set => SetPropertyValue(value);
+ }
+
+ /// <summary>
+ /// Accept suggestions on ENTER.
+ /// Defaults to 'on'.
+ /// </summary>
+ [JsonProperty("acceptSuggestionOnEnter", NullValueHandling = NullValueHandling.Ignore)]
+ public AcceptSuggestionOnEnter? AcceptSuggestionOnEnter
+ {
+ get => GetPropertyValue<AcceptSuggestionOnEnter?>();
+ set => SetPropertyValue(value);
+ }
+
+ /// <summary>
+ /// Controls the number of lines in the editor that can be read out by a screen reader
+ /// </summary>
+ [JsonProperty("accessibilityPageSize", NullValueHandling = NullValueHandling.Ignore)]
+ public int? AccessibilityPageSize { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Configure the editor's accessibility support.
+ /// Defaults to 'auto'. It is best to leave this to 'auto'.
+ /// </summary>
+ [JsonProperty("accessibilitySupport", NullValueHandling = NullValueHandling.Ignore)]
+ public AccessibilitySupport? AccessibilitySupport { get => GetPropertyValue<AccessibilitySupport?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The aria label for the editor's textarea (when it is focused).
+ /// </summary>
+ [JsonProperty("ariaLabel", NullValueHandling = NullValueHandling.Ignore)]
+ public string? AriaLabel { get => GetPropertyValue<string>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Options for auto closing brackets.
+ /// Defaults to language defined behavior.
+ /// </summary>
+ [JsonProperty("autoClosingBrackets", NullValueHandling = NullValueHandling.Ignore)]
+ public AutoClosingBrackets? AutoClosingBrackets { get => GetPropertyValue<AutoClosingBrackets?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Options for typing over closing quotes or brackets.
+ /// </summary>
+ [JsonProperty("autoClosingOvertype", NullValueHandling = NullValueHandling.Ignore)]
+ public AutoClosingOvertype? AutoClosingOvertype { get => GetPropertyValue<AutoClosingOvertype?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Options for auto closing quotes.
+ /// Defaults to language defined behavior.
+ /// </summary>
+ [JsonProperty("autoClosingQuotes", NullValueHandling = NullValueHandling.Ignore)]
+ public AutoClosingQuotes? AutoClosingQuotes { get => GetPropertyValue<AutoClosingQuotes?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable auto indentation adjustment.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("autoIndent", NullValueHandling = NullValueHandling.Ignore)]
+ public AutoIndent? AutoIndent { get => GetPropertyValue<AutoIndent?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable that the editor will install an interval to check if its container dom node size
+ /// has changed.
+ /// Enabling this might have a severe performance impact.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("automaticLayout", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? AutomaticLayout { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Options for auto surrounding.
+ /// Defaults to always allowing auto surrounding.
+ /// </summary>
+ [JsonProperty("autoSurround", NullValueHandling = NullValueHandling.Ignore)]
+ public AutoSurround? AutoSurround { get => GetPropertyValue<AutoSurround?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Timeout for running code actions on save.
+ /// </summary>
+ [JsonProperty("codeActionsOnSaveTimeout", NullValueHandling = NullValueHandling.Ignore)]
+ public int? CodeActionsOnSaveTimeout { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Show code lens
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("codeLens", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? CodeLens { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable inline color decorators and color picker rendering.
+ /// </summary>
+ [JsonProperty("colorDecorators", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ColorDecorators { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the behaviour of comments in the editor.
+ /// </summary>
+ [JsonProperty("comments", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorCommentsOptions? Comments { get => GetPropertyValue<EditorCommentsOptions>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable custom contextmenu.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("contextmenu", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Contextmenu { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Syntax highlighting is copied.
+ /// </summary>
+ [JsonProperty("copyWithSyntaxHighlighting", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? CopyWithSyntaxHighlighting { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the cursor animation style, possible values are 'blink', 'smooth', 'phase',
+ /// 'expand' and 'solid'.
+ /// Defaults to 'blink'.
+ /// </summary>
+ [JsonProperty("cursorBlinking", NullValueHandling = NullValueHandling.Ignore)]
+ public CursorBlinking? CursorBlinking { get => GetPropertyValue<CursorBlinking?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable smooth caret animation.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("cursorSmoothCaretAnimation", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? CursorSmoothCaretAnimation { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the cursor style, either 'block' or 'line'.
+ /// Defaults to 'line'.
+ /// </summary>
+ [JsonProperty("cursorStyle", NullValueHandling = NullValueHandling.Ignore)]
+ public CursorStyle? CursorStyle { get => GetPropertyValue<CursorStyle?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls the minimal number of visible leading and trailing lines surrounding the cursor.
+ /// Defaults to 0.
+ /// </summary>
+ [JsonProperty("cursorSurroundingLines", NullValueHandling = NullValueHandling.Ignore)]
+ public int? CursorSurroundingLines { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls when `cursorSurroundingLines` should be enforced
+ /// Defaults to `default`, `cursorSurroundingLines` is not enforced when cursor position is
+ /// changed
+ /// by mouse.
+ /// </summary>
+ [JsonProperty("cursorSurroundingLinesStyle", NullValueHandling = NullValueHandling.Ignore)]
+ public CursorSurroundingLinesStyle? CursorSurroundingLinesStyle { get => GetPropertyValue<CursorSurroundingLinesStyle?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the width of the cursor when cursorStyle is set to 'line'
+ /// </summary>
+ [JsonProperty("cursorWidth", NullValueHandling = NullValueHandling.Ignore)]
+ public int? CursorWidth { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Disable the use of `transform: translate3d(0px, 0px, 0px)` for the editor margin and
+ /// lines layers.
+ /// The usage of `transform: translate3d(0px, 0px, 0px)` acts as a hint for browsers to
+ /// create an extra layer.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("disableLayerHinting", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? DisableLayerHinting { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Disable the optimizations for monospace fonts.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("disableMonospaceOptimizations", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? DisableMonospaceOptimizations { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls if the editor should allow to move selections via drag and drop.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("dragAndDrop", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? DragAndDrop { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Copying without a selection copies the current line.
+ /// </summary>
+ [JsonProperty("emptySelectionClipboard", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? EmptySelectionClipboard { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Class name to be added to the editor.
+ /// </summary>
+ [JsonProperty("extraEditorClassName", NullValueHandling = NullValueHandling.Ignore)]
+ public string? ExtraEditorClassName { get => GetPropertyValue<string>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// FastScrolling mulitplier speed when pressing `Alt`
+ /// Defaults to 5.
+ /// </summary>
+ [JsonProperty("fastScrollSensitivity", NullValueHandling = NullValueHandling.Ignore)]
+ public int? FastScrollSensitivity { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the behavior of the find widget.
+ /// </summary>
+ [JsonProperty("find", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorFindOptions? Find { get => GetPropertyValue<EditorFindOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Display overflow widgets as `fixed`.
+ /// Defaults to `false`.
+ /// </summary>
+ [JsonProperty("fixedOverflowWidgets", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? FixedOverflowWidgets { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable code folding
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("folding", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Folding { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable highlight for folded regions.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("foldingHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? FoldingHighlight { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Selects the folding strategy. 'auto' uses the strategies contributed for the current
+ /// document, 'indentation' uses the indentation based folding strategy.
+ /// Defaults to 'auto'.
+ /// </summary>
+ [JsonProperty("foldingStrategy", NullValueHandling = NullValueHandling.Ignore)]
+ public FoldingStrategy? FoldingStrategy { get => GetPropertyValue<FoldingStrategy?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The font family
+ /// </summary>
+ [JsonProperty("fontFamily", NullValueHandling = NullValueHandling.Ignore)]
+ public string? FontFamily { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable font ligatures.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("fontLigatures", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? FontLigatures { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The font size
+ /// </summary>
+ [JsonProperty("fontSize", NullValueHandling = NullValueHandling.Ignore)]
+ public int? FontSize { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The font weight
+ /// </summary>
+ [JsonProperty("fontWeight", NullValueHandling = NullValueHandling.Ignore)]
+ public string? FontWeight { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable format on paste.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("formatOnPaste", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? FormatOnPaste { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable format on type.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("formatOnType", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? FormatOnType { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable the rendering of the glyph margin.
+ /// Defaults to true in vscode and to false in monaco-editor.
+ /// </summary>
+ [JsonProperty("glyphMargin", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? GlyphMargin { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Configuration options for go to location
+ /// </summary>
+ [JsonProperty("gotoLocation", NullValueHandling = NullValueHandling.Ignore)]
+ public GoToLocationOptions? GotoLocation { get => GetPropertyValue<GoToLocationOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Should the cursor be hidden in the overview ruler.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("hideCursorInOverviewRuler", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? HideCursorInOverviewRuler { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable highlighting of the active indent guide.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("highlightActiveIndentGuide", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? HighlightActiveIndentGuide { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Configure the editor's hover.
+ /// </summary>
+ [JsonProperty("hover", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorHoverOptions? Hover { get => GetPropertyValue<EditorHoverOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// This editor is used inside a diff editor.
+ /// </summary>
+ [JsonProperty("inDiffEditor", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? InDiffEditor { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The letter spacing
+ /// </summary>
+ [JsonProperty("letterSpacing", NullValueHandling = NullValueHandling.Ignore)]
+ public int? LetterSpacing { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the behavior and rendering of the code action lightbulb.
+ /// </summary>
+ [JsonProperty("lightbulb", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorLightbulbOptions? Lightbulb { get => GetPropertyValue<EditorLightbulbOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The width reserved for line decorations (in px).
+ /// Line decorations are placed between line numbers and the editor content.
+ /// You can pass in a string in the format floating point followed by "ch". e.g. 1.3ch.
+ /// Defaults to 10.
+ /// </summary>
+ [JsonProperty("lineDecorationsWidth", NullValueHandling = NullValueHandling.Ignore)]
+ public uint? LineDecorationsWidth { get => GetPropertyValue<uint?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The line height
+ /// </summary>
+ [JsonProperty("lineHeight", NullValueHandling = NullValueHandling.Ignore)]
+ public int? LineHeight { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the rendering of line numbers.
+ /// If it is a function, it will be invoked when rendering a line number and the return value
+ /// will be rendered.
+ /// Otherwise, if it is a truey, line numbers will be rendered normally (equivalent of using
+ /// an identity function).
+ /// Otherwise, line numbers will not be rendered.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("lineNumbers", NullValueHandling = NullValueHandling.Ignore)]
+ public LineNumbersType? LineNumbers { get => GetPropertyValue<LineNumbersType?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the width of line numbers, by reserving horizontal space for rendering at least
+ /// an amount of digits.
+ /// Defaults to 5.
+ /// </summary>
+ [JsonProperty("lineNumbersMinChars", NullValueHandling = NullValueHandling.Ignore)]
+ public int? LineNumbersMinChars { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable detecting links and making them clickable.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("links", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Links { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable highlighting of matching brackets.
+ /// Defaults to 'always'.
+ /// </summary>
+ [JsonProperty("matchBrackets", NullValueHandling = NullValueHandling.Ignore)]
+ public MatchBrackets? MatchBrackets { get => GetPropertyValue<MatchBrackets?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the behavior and rendering of the minimap.
+ /// </summary>
+ [JsonProperty("minimap", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorMinimapOptions? Minimap { get => GetPropertyValue<EditorMinimapOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the mouse pointer style, either 'text' or 'default' or 'copy'
+ /// Defaults to 'text'
+ /// </summary>
+ [JsonProperty("mouseStyle", NullValueHandling = NullValueHandling.Ignore)]
+ public MouseStyle? MouseStyle { get => GetPropertyValue<MouseStyle?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.
+ /// Defaults to 1.
+ /// </summary>
+ [JsonProperty("mouseWheelScrollSensitivity", NullValueHandling = NullValueHandling.Ignore)]
+ public int? MouseWheelScrollSensitivity { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Zoom the font in the editor when using the mouse wheel in combination with holding Ctrl.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("mouseWheelZoom", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? MouseWheelZoom { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Merge overlapping selections.
+ /// Defaults to true
+ /// </summary>
+ [JsonProperty("multiCursorMergeOverlapping", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? MultiCursorMergeOverlapping { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The modifier to be used to add multiple cursors with the mouse.
+ /// Defaults to 'alt'
+ /// </summary>
+ [JsonProperty("multiCursorModifier", NullValueHandling = NullValueHandling.Ignore)]
+ public MultiCursorModifier? MultiCursorModifier { get => GetPropertyValue<MultiCursorModifier?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Configure the behaviour when pasting a text with the line count equal to the cursor
+ /// count.
+ /// Defaults to 'spread'.
+ /// </summary>
+ [JsonProperty("multiCursorPaste", NullValueHandling = NullValueHandling.Ignore)]
+ public MultiCursorPaste? MultiCursorPaste { get => GetPropertyValue<MultiCursorPaste?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable semantic occurrences highlight.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("occurrencesHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? OccurrencesHighlight { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls if a border should be drawn around the overview ruler.
+ /// Defaults to `true`.
+ /// </summary>
+ [JsonProperty("overviewRulerBorder", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? OverviewRulerBorder { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The number of vertical lanes the overview ruler should render.
+ /// Defaults to 3.
+ /// </summary>
+ [JsonProperty("overviewRulerLanes", NullValueHandling = NullValueHandling.Ignore)]
+ public int? OverviewRulerLanes { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Parameter hint options.
+ /// </summary>
+ [JsonProperty("parameterHints", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorParameterHintOptions? ParameterHints { get => GetPropertyValue<EditorParameterHintOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls whether to focus the inline editor in the peek widget by default.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("peekWidgetDefaultFocus", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? PeekWidgetDefaultFocus { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable quick suggestions (shadow suggestions)
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("quickSuggestions", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? QuickSuggestions { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Quick suggestions show delay (in ms)
+ /// Defaults to 10 (ms)
+ /// </summary>
+ [JsonProperty("quickSuggestionsDelay", NullValueHandling = NullValueHandling.Ignore)]
+ public int? QuickSuggestionsDelay { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Should the editor be read only.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("readOnly", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ReadOnly { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable rendering of control characters.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("renderControlCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? RenderControlCharacters { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Render last line number when the file ends with a newline.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("renderFinalNewline", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? RenderFinalNewline { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable rendering of indent guides.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("renderIndentGuides", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? RenderIndentGuides { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable rendering of current line highlight.
+ /// Defaults to all.
+ /// </summary>
+ [JsonProperty("renderLineHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ public RenderLineHighlight? RenderLineHighlight { get => GetPropertyValue<RenderLineHighlight?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Should the editor render validation decorations.
+ /// Defaults to editable.
+ /// </summary>
+ [JsonProperty("renderValidationDecorations", NullValueHandling = NullValueHandling.Ignore)]
+ public string? RenderValidationDecorations { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable rendering of whitespace.
+ /// Defaults to none.
+ /// </summary>
+ [JsonProperty("renderWhitespace", NullValueHandling = NullValueHandling.Ignore)]
+ public RenderWhitespace? RenderWhitespace { get => GetPropertyValue<RenderWhitespace?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// When revealing the cursor, a virtual padding (px) is added to the cursor, turning it into
+ /// a rectangle.
+ /// This virtual padding ensures that the cursor gets revealed before hitting the edge of the
+ /// viewport.
+ /// Defaults to 30 (px).
+ /// </summary>
+ [JsonProperty("revealHorizontalRightPadding", NullValueHandling = NullValueHandling.Ignore)]
+ public int? RevealHorizontalRightPadding { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Render the editor selection with rounded borders.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("roundedSelection", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? RoundedSelection { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Render vertical lines at the specified columns.
+ /// Defaults to empty array.
+ /// </summary>
+ [JsonProperty("rulers", NullValueHandling = NullValueHandling.Ignore)]
+ public int[]? Rulers { get => GetPropertyValue<int[]>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the behavior and rendering of the scrollbars.
+ /// </summary>
+ [JsonProperty("scrollbar", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorScrollbarOptions? Scrollbar { get => GetPropertyValue<EditorScrollbarOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable that scrolling can go beyond the last column by a number of columns.
+ /// Defaults to 5.
+ /// </summary>
+ [JsonProperty("scrollBeyondLastColumn", NullValueHandling = NullValueHandling.Ignore)]
+ public int? ScrollBeyondLastColumn { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable that scrolling can go one screen size after the last line.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("scrollBeyondLastLine", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ScrollBeyondLastLine { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable Linux primary clipboard.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("selectionClipboard", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SelectionClipboard { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable selection highlight.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("selectionHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SelectionHighlight { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Should the corresponding line be selected when clicking on the line number?
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("selectOnLineNumbers", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SelectOnLineNumbers { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls whether the fold actions in the gutter stay always visible or hide unless the
+ /// mouse is over the gutter.
+ /// Defaults to 'mouseover'.
+ /// </summary>
+ [JsonProperty("showFoldingControls", NullValueHandling = NullValueHandling.Ignore)]
+ public Show? ShowFoldingControls { get => GetPropertyValue<Show?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls fading out of unused variables.
+ /// </summary>
+ [JsonProperty("showUnused", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowUnused { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable that the editor animates scrolling to a position.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("smoothScrolling", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SmoothScrolling { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable snippet suggestions. Default to 'true'.
+ /// </summary>
+ [JsonProperty("snippetSuggestions", NullValueHandling = NullValueHandling.Ignore)]
+ public SnippetSuggestions? SnippetSuggestions { get => GetPropertyValue<SnippetSuggestions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Performance guard: Stop rendering a line after x characters.
+ /// Defaults to 10000.
+ /// Use -1 to never stop rendering
+ /// </summary>
+ [JsonProperty("stopRenderingLineAfter", NullValueHandling = NullValueHandling.Ignore)]
+ public int? StopRenderingLineAfter { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Suggest options.
+ /// </summary>
+ [JsonProperty("suggest", NullValueHandling = NullValueHandling.Ignore)]
+ public SuggestOptions? Suggest { get => GetPropertyValue<SuggestOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The font size for the suggest widget.
+ /// Defaults to the editor font size.
+ /// </summary>
+ [JsonProperty("suggestFontSize", NullValueHandling = NullValueHandling.Ignore)]
+ public int? SuggestFontSize { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The line height for the suggest widget.
+ /// Defaults to the editor line height.
+ /// </summary>
+ [JsonProperty("suggestLineHeight", NullValueHandling = NullValueHandling.Ignore)]
+ public int? SuggestLineHeight { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable the suggestion box to pop-up on trigger characters.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("suggestOnTriggerCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SuggestOnTriggerCharacters { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The history mode for suggestions.
+ /// </summary>
+ [JsonProperty("suggestSelection", NullValueHandling = NullValueHandling.Ignore)]
+ public SuggestSelection? SuggestSelection { get => GetPropertyValue<SuggestSelection?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable tab completion.
+ /// </summary>
+ [JsonProperty("tabCompletion", NullValueHandling = NullValueHandling.Ignore)]
+ public TabCompletion? TabCompletion { get => GetPropertyValue<TabCompletion?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Inserting and deleting whitespace follows tab stops.
+ /// </summary>
+ [JsonProperty("useTabStops", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? UseTabStops { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// A string containing the word separators used when doing word navigation.
+ /// Defaults to `~!@#$%^&amp;*()-=+[{]}\|;:'",.&lt;&gt;/?
+ /// *
+ /// </summary>
+ [JsonProperty("wordSeparators", NullValueHandling = NullValueHandling.Ignore)]
+ public string? WordSeparators { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the wrapping of the editor.
+ /// When `wordWrap` = "off", the lines will never wrap.
+ /// When `wordWrap` = "on", the lines will wrap at the viewport width.
+ /// When `wordWrap` = "wordWrapColumn", the lines will wrap at `wordWrapColumn`.
+ /// When `wordWrap` = "bounded", the lines will wrap at min(viewport width, wordWrapColumn).
+ /// Defaults to "off".
+ /// </summary>
+ [JsonProperty("wordWrap", NullValueHandling = NullValueHandling.Ignore)]
+ public WordWrap? WordWrap { get => GetPropertyValue<WordWrap?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Configure word wrapping characters. A break will be introduced after these characters.
+ /// Defaults to ' \t})]?|&amp;,;'.
+ /// </summary>
+ [JsonProperty("wordWrapBreakAfterCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ public string? WordWrapBreakAfterCharacters { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Configure word wrapping characters. A break will be introduced before these characters.
+ /// Defaults to '{([+'.
+ /// </summary>
+ [JsonProperty("wordWrapBreakBeforeCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ public string? WordWrapBreakBeforeCharacters { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the wrapping of the editor.
+ /// When `wordWrap` = "off", the lines will never wrap.
+ /// When `wordWrap` = "on", the lines will wrap at the viewport width.
+ /// When `wordWrap` = "wordWrapColumn", the lines will wrap at `wordWrapColumn`.
+ /// When `wordWrap` = "bounded", the lines will wrap at min(viewport width, wordWrapColumn).
+ /// Defaults to 80.
+ /// </summary>
+ [JsonProperty("wordWrapColumn", NullValueHandling = NullValueHandling.Ignore)]
+ public int? WordWrapColumn { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Force word wrapping when the text appears to be of a minified/generated file.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("wordWrapMinified", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? WordWrapMinified { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control indentation of wrapped lines. Can be: 'none', 'same', 'indent' or 'deepIndent'.
+ /// Defaults to 'same' in vscode and to 'none' in monaco-editor.
+ /// </summary>
+ [JsonProperty("wrappingIndent", NullValueHandling = NullValueHandling.Ignore)]
+ public WrappingIndent? WrappingIndent { get => GetPropertyValue<WrappingIndent?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls the wrapping strategy to use.
+ /// Defaults to 'simple'.
+ /// </summary>
+ [JsonProperty("wrappingStrategy", NullValueHandling = NullValueHandling.Ignore)]
+ public string? WrappingStrategy { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Initial theme to be used for rendering.
+ /// The current out-of-the-box available themes are: 'vs' (default), 'vs-dark', 'hc-black'.
+ /// You can create custom themes via `monaco.editor.defineTheme`.
+ /// To switch a theme, use `monaco.editor.setTheme`
+ /// </summary>
+ [JsonProperty("theme", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Theme { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ [JsonProperty("enableSplitViewResizing", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? EnableSplitViewResizing { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ [JsonProperty("ignoreTrimWhitespace", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? IgnoreTrimWhitespace { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ [JsonProperty("maxComputationTime", NullValueHandling = NullValueHandling.Ignore)]
+ public uint? MaxComputationTime { get => GetPropertyValue<uint?>(); set => SetPropertyValue(value); }
+
+ [JsonProperty("originalEditable", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? OriginalEditable { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ [JsonProperty("renderIndicators", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? RenderIndicators { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ [JsonProperty("renderSideBySide", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? RenderSideBySide { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+ }
+
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Dimension.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Dimension.cs
new file mode 100644
index 000000000..464b90090
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Dimension.cs
@@ -0,0 +1,18 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// The initial editor dimension (to avoid measuring the container).
+ /// </summary>
+ public sealed class Dimension : IDimension
+ {
+ [JsonProperty("height", NullValueHandling = NullValueHandling.Ignore)]
+ public uint Height { get; set; }
+
+ [JsonProperty("width", NullValueHandling = NullValueHandling.Ignore)]
+ public uint Width { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorCommentsOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorCommentsOptions.cs
new file mode 100644
index 000000000..ced731c9a
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorCommentsOptions.cs
@@ -0,0 +1,19 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Configuration options for editor comments
+ /// </summary>
+ public sealed class EditorCommentsOptions
+ {
+ /// <summary>
+ /// Insert a space after the line comment token and inside the block comments tokens.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("insertSpace", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? InsertSpace { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorFindOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorFindOptions.cs
new file mode 100644
index 000000000..d859b0bd8
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorFindOptions.cs
@@ -0,0 +1,28 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.ieditorfindoptions.html
+ /// </summary>
+ public sealed class EditorFindOptions
+ {
+ [JsonProperty("addExtraSpaceOnTop", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? AddExtraSpaceOnTop { get; set; }
+
+ /// <summary>
+ /// Controls if Find in Selection flag is turned on in the editor.
+ /// </summary>
+ [JsonProperty("autoFindInSelection", NullValueHandling = NullValueHandling.Ignore)]
+ public AutoFindInSelection? AutoFindInSelection { get; set; }
+
+ /// <summary>
+ /// Controls if we seed search string in the Find Widget with editor selection.
+ /// </summary>
+ [JsonProperty("seedSearchStringFromSelection", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SeedSearchStringFromSelection { get; set; }
+ }
+
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorHoverOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorHoverOptions.cs
new file mode 100644
index 000000000..84ad64e75
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorHoverOptions.cs
@@ -0,0 +1,36 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Configure the editor's hover.
+ ///
+ /// Configuration options for editor hover
+ /// </summary>
+ public sealed class EditorHoverOptions
+ {
+ /// <summary>
+ /// Delay for showing the hover.
+ /// Defaults to 300.
+ /// </summary>
+ [JsonProperty("delay", NullValueHandling = NullValueHandling.Ignore)]
+ public int? Delay { get; set; }
+
+ /// <summary>
+ /// Enable the hover.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("enabled", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Enabled { get; set; }
+
+ /// <summary>
+ /// Is the hover sticky such that it can be clicked and its contents selected?
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("sticky", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Sticky { get; set; }
+ }
+
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorLightbulbOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorLightbulbOptions.cs
new file mode 100644
index 000000000..aa8ca2146
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorLightbulbOptions.cs
@@ -0,0 +1,22 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Control the behavior and rendering of the code action lightbulb.
+ ///
+ /// Configuration options for editor lightbulb
+ /// </summary>
+ public sealed class EditorLightbulbOptions
+ {
+ /// <summary>
+ /// Enable the lightbulb code action.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("enabled", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Enabled { get; set; }
+ }
+
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorMinimapOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorMinimapOptions.cs
new file mode 100644
index 000000000..7d6e6e68d
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorMinimapOptions.cs
@@ -0,0 +1,55 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Control the behavior and rendering of the minimap.
+ ///
+ /// Configuration options for editor minimap
+ /// </summary>
+ public sealed class EditorMinimapOptions
+ {
+ /// <summary>
+ /// Enable the rendering of the minimap.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("enabled", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Enabled { get; set; }
+
+ /// <summary>
+ /// Limit the width of the minimap to render at most a certain number of columns.
+ /// Defaults to 120.
+ /// </summary>
+ [JsonProperty("maxColumn", NullValueHandling = NullValueHandling.Ignore)]
+ public uint? MaxColumn { get; set; }
+
+ /// <summary>
+ /// Render the actual text on a line (as opposed to color blocks).
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("renderCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? RenderCharacters { get; set; }
+
+ /// <summary>
+ /// Relative size of the font in the minimap. Defaults to 1.
+ /// </summary>
+ [JsonProperty("scale", NullValueHandling = NullValueHandling.Ignore)]
+ public double? Scale { get; set; }
+
+ /// <summary>
+ /// Control the rendering of the minimap slider.
+ /// Defaults to 'mouseover'.
+ /// </summary>
+ [JsonProperty("showSlider", NullValueHandling = NullValueHandling.Ignore)]
+ public Show? ShowSlider { get; set; }
+
+ /// <summary>
+ /// Control the side of the minimap in editor.
+ /// Defaults to 'right'.
+ /// </summary>
+ [JsonProperty("side", NullValueHandling = NullValueHandling.Ignore)]
+ public Side? Side { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorParameterHintOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorParameterHintOptions.cs
new file mode 100644
index 000000000..98abbd761
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorParameterHintOptions.cs
@@ -0,0 +1,27 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Configuration options for parameter hints
+ /// </summary>
+ public sealed class EditorParameterHintOptions
+ {
+ /// <summary>
+ /// Enable cycling of parameter hints.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("cycle", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Cycle { get; set; }
+
+ /// <summary>
+ /// Enable parameter hints.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("enabled", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Enabled { get; set; }
+ }
+
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorScrollbarOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorScrollbarOptions.cs
new file mode 100644
index 000000000..099e4b68b
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EditorScrollbarOptions.cs
@@ -0,0 +1,95 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ public sealed class EditorScrollbarOptions
+ {
+ /// <summary>
+ /// Always consume mouse wheel events (always call preventDefault() and stopPropagation() on
+ /// the browser events).
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("alwaysConsumeMouseWheel", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? AlwaysConsumeMouseWheel { get; set; }
+
+ /// <summary>
+ /// The size of arrows (if displayed).
+ /// Defaults to 11.
+ /// </summary>
+ [JsonProperty("arrowSize", NullValueHandling = NullValueHandling.Ignore)]
+ public int? ArrowSize { get; set; }
+
+ /// <summary>
+ /// Listen to mouse wheel events and react to them by scrolling.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("handleMouseWheel", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? HandleMouseWheel { get; set; }
+
+ /// <summary>
+ /// Render horizontal scrollbar.
+ /// Defaults to 'auto'.
+ /// </summary>
+ [JsonProperty("horizontal", NullValueHandling = NullValueHandling.Ignore)]
+ public ScrollbarBehavior? Horizontal { get; set; }
+
+ /// <summary>
+ /// Render arrows at the left and right of the horizontal scrollbar.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("horizontalHasArrows", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? HorizontalHasArrows { get; set; }
+
+ /// <summary>
+ /// Height in pixels for the horizontal scrollbar.
+ /// Defaults to 10 (px).
+ /// </summary>
+ [JsonProperty("horizontalScrollbarSize", NullValueHandling = NullValueHandling.Ignore)]
+ public int? HorizontalScrollbarSize { get; set; }
+
+ /// <summary>
+ /// Height in pixels for the horizontal slider.
+ /// Defaults to `horizontalScrollbarSize`.
+ /// </summary>
+ [JsonProperty("horizontalSliderSize", NullValueHandling = NullValueHandling.Ignore)]
+ public int? HorizontalSliderSize { get; set; }
+
+ /// <summary>
+ /// Cast horizontal and vertical shadows when the content is scrolled.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("useShadows", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? UseShadows { get; set; }
+
+ /// <summary>
+ /// Render vertical scrollbar.
+ /// Defaults to 'auto'.
+ /// </summary>
+ [JsonProperty("vertical", NullValueHandling = NullValueHandling.Ignore)]
+ public ScrollbarBehavior? Vertical { get; set; }
+
+ /// <summary>
+ /// Render arrows at the top and bottom of the vertical scrollbar.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("verticalHasArrows", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? VerticalHasArrows { get; set; }
+
+ /// <summary>
+ /// Width in pixels for the vertical scrollbar.
+ /// Defaults to 10 (px).
+ /// </summary>
+ [JsonProperty("verticalScrollbarSize", NullValueHandling = NullValueHandling.Ignore)]
+ public int? VerticalScrollbarSize { get; set; }
+
+ /// <summary>
+ /// Width in pixels for the vertical slider.
+ /// Defaults to `verticalScrollbarSize`.
+ /// </summary>
+ [JsonProperty("verticalSliderSize", NullValueHandling = NullValueHandling.Ignore)]
+ public int? VerticalSliderSize { get; set; }
+ }
+
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EndOfLinePreference.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EndOfLinePreference.cs
new file mode 100644
index 000000000..6c9ceb4c4
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EndOfLinePreference.cs
@@ -0,0 +1,14 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// https://github.com/Microsoft/vscode/blob/master/src/vs/editor/common/editorCommon.ts#L228
+ /// </summary>
+ public enum EndOfLinePreference
+ {
+ TextDefined = 0,
+ LF = 1,
+ CRLF = 2
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EndOfLineSequence.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EndOfLineSequence.cs
new file mode 100644
index 000000000..e0cdc8453
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/EndOfLineSequence.cs
@@ -0,0 +1,13 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// https://github.com/Microsoft/vscode/blob/master/src/vs/editor/common/editorCommon.ts#L260
+ /// </summary>
+ public enum EndOfLineSequence
+ {
+ LF = 0,
+ CRLF = 1
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/FoldingStrategy.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/FoldingStrategy.cs
new file mode 100644
index 000000000..0634e4e32
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/FoldingStrategy.cs
@@ -0,0 +1,18 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Selects the folding strategy. 'auto' uses the strategies contributed for the current
+ /// document, 'indentation' uses the indentation based folding strategy.
+ /// Defaults to 'auto'.
+ /// </summary>
+ [JsonConverter(typeof(FoldingStrategyConverter))]
+ public enum FoldingStrategy
+ {
+ Auto,
+ Indentation
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/FoldingStrategyConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/FoldingStrategyConverter.cs
new file mode 100644
index 000000000..26bd7808e
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/FoldingStrategyConverter.cs
@@ -0,0 +1,56 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class FoldingStrategyConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(FoldingStrategy) || t == typeof(FoldingStrategy?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "auto":
+ return FoldingStrategy.Auto;
+ case "indentation":
+ return FoldingStrategy.Indentation;
+ }
+
+ throw new Exception("Cannot unmarshal type FoldingStrategy");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+
+ var value = (FoldingStrategy)untypedValue;
+ switch (value)
+ {
+ case FoldingStrategy.Auto:
+ serializer.Serialize(writer, "auto");
+ return;
+ case FoldingStrategy.Indentation:
+ serializer.Serialize(writer, "indentation");
+ return;
+ }
+
+ throw new Exception("Cannot marshal type FoldingStrategy");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/GoToLocationOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/GoToLocationOptions.cs
new file mode 100644
index 000000000..83c8711a1
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/GoToLocationOptions.cs
@@ -0,0 +1,46 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Configuration options for go to location
+ /// </summary>
+ public sealed class GoToLocationOptions
+ {
+ [JsonProperty("alternativeDeclarationCommand", NullValueHandling = NullValueHandling.Ignore)]
+ public string? AlternativeDeclarationCommand { get; set; }
+
+ [JsonProperty("alternativeDefinitionCommand", NullValueHandling = NullValueHandling.Ignore)]
+ public string? AlternativeDefinitionCommand { get; set; }
+
+ [JsonProperty("alternativeImplementationCommand", NullValueHandling = NullValueHandling.Ignore)]
+ public string? AlternativeImplementationCommand { get; set; }
+
+ [JsonProperty("alternativeReferenceCommand", NullValueHandling = NullValueHandling.Ignore)]
+ public string? AlternativeReferenceCommand { get; set; }
+
+ [JsonProperty("alternativeTypeDefinitionCommand", NullValueHandling = NullValueHandling.Ignore)]
+ public string? AlternativeTypeDefinitionCommand { get; set; }
+
+ [JsonProperty("multiple", NullValueHandling = NullValueHandling.Ignore)]
+ public Multiple? Multiple { get; set; }
+
+ [JsonProperty("multipleDeclarations", NullValueHandling = NullValueHandling.Ignore)]
+ public Multiple? MultipleDeclarations { get; set; }
+
+ [JsonProperty("multipleDefinitions", NullValueHandling = NullValueHandling.Ignore)]
+ public Multiple? MultipleDefinitions { get; set; }
+
+ [JsonProperty("multipleImplementations", NullValueHandling = NullValueHandling.Ignore)]
+ public Multiple? MultipleImplementations { get; set; }
+
+ [JsonProperty("multipleReferences", NullValueHandling = NullValueHandling.Ignore)]
+ public Multiple? MultipleReferences { get; set; }
+
+ [JsonProperty("multipleTypeDefinitions", NullValueHandling = NullValueHandling.Ignore)]
+ public Multiple? MultipleTypeDefinitions { get; set; }
+ }
+
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IActionDescriptor.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IActionDescriptor.cs
new file mode 100644
index 000000000..00b6f99a5
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IActionDescriptor.cs
@@ -0,0 +1,56 @@
+#nullable enable
+
+using DevToys.MonacoEditor.CodeEditorControl;
+using Newtonsoft.Json;
+using System.Runtime.InteropServices.WindowsRuntime;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Description of an action contribution
+ /// </summary>
+ public interface IActionDescriptor
+ {
+ /**
+ * https://github.com/Microsoft/vscode/blob/master/src/vs/monaco.d.ts#L1907
+ * Control if the action should show up in the context menu and where.
+ * The context menu of the editor has these default:
+ * navigation - The navigation group comes first in all cases.
+ * 1_modification - This group comes next and contains commands that modify your code.
+ * 9_cutcopypaste - The last default group with the basic editing commands.
+ * You can also create your own group.
+ * Defaults to null (don't show in context menu).
+ */
+ [JsonProperty("contextMenuGroupId", NullValueHandling = NullValueHandling.Ignore)]
+ string ContextMenuGroupId { get; }
+
+ [JsonProperty("contextMenuOrder", NullValueHandling = NullValueHandling.Ignore)]
+ float ContextMenuOrder { get; }
+
+ [JsonProperty("id")]
+ string Id { get; }
+
+ /// <summary>
+ /// <see cref="IContextKey"/>
+ /// </summary>
+ [JsonProperty("keybindingContext", NullValueHandling = NullValueHandling.Ignore)]
+ string KeybindingContext { get; }
+
+ /// <summary>
+ /// <see cref="KeyMod"/>, <see cref="KeyCode"/>, and <see cref="KeyMod.Chord(int, int)"/>
+ /// </summary>
+ [JsonProperty("keybindings")]
+ int[] Keybindings { get; }
+
+ [JsonProperty("label")]
+ string Label { get; }
+
+ /// <summary>
+ /// <see cref="IContextKey"/>
+ /// </summary>
+ [JsonProperty("precondition", NullValueHandling = NullValueHandling.Ignore)]
+ string Precondition { get; }
+
+ void Run(CodeEditorCore editor, [ReadOnlyArray] object[]? args);
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IContextKey.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IContextKey.cs
new file mode 100644
index 000000000..ed38430bf
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IContextKey.cs
@@ -0,0 +1,29 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.icontextkey.html
+ ///
+ /// Supports bools only as Windows Runtime Type doesn't support generics.
+ /// </summary>
+ public interface IContextKey
+ {
+ /// <summary>
+ /// Get the current value of the key.
+ /// </summary>
+ /// <returns></returns>
+ bool Get();
+
+ /// <summary>
+ /// Resets the key to the default value.
+ /// </summary>
+ void Reset();
+
+ /// <summary>
+ /// Set the key to the specified value.
+ /// </summary>
+ /// <param name="value"></param>
+ void Set(bool value);
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IDiffEditorConstructionOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IDiffEditorConstructionOptions.cs
new file mode 100644
index 000000000..0fe5f4b82
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IDiffEditorConstructionOptions.cs
@@ -0,0 +1,21 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// The options to create a diff editor.
+ /// </summary>
+ public interface IDiffEditorConstructionOptions : IDiffEditorOptions
+ {
+ /// <summary>
+ /// Initial theme to be used for rendering.
+ /// The current out-of-the-box available themes are: 'vs' (default), 'vs-dark', 'hc-black'.
+ /// You can create custom themes via `monaco.editor.defineTheme`.
+ /// To switch a theme, use `monaco.editor.setTheme`
+ /// </summary>
+ [JsonProperty("theme", NullValueHandling = NullValueHandling.Ignore)]
+ string? Theme { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IDiffEditorOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IDiffEditorOptions.cs
new file mode 100644
index 000000000..c1420ef2b
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IDiffEditorOptions.cs
@@ -0,0 +1,49 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Configuration options for the diff editor.
+ /// </summary>
+ public interface IDiffEditorOptions : IEditorOptions
+ {
+ /// <summary>
+ /// Allow the user to resize the diff editor split view.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("enableSplitViewResizing", NullValueHandling = NullValueHandling.Ignore)]
+ bool? EnableSplitViewResizing { get; set; }
+ /// <summary>
+ /// Compute the diff by ignoring leading/trailing whitespace
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("ignoreTrimWhitespace", NullValueHandling = NullValueHandling.Ignore)]
+ bool? IgnoreTrimWhitespace { get; set; }
+ /// <summary>
+ /// Timeout in milliseconds after which diff computation is cancelled.
+ /// Defaults to 5000.
+ /// </summary>
+ [JsonProperty("maxComputationTime", NullValueHandling = NullValueHandling.Ignore)]
+ uint? MaxComputationTime { get; set; }
+ /// <summary>
+ /// Original model should be editable?
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("originalEditable", NullValueHandling = NullValueHandling.Ignore)]
+ bool? OriginalEditable { get; set; }
+ /// <summary>
+ /// Render +/- indicators for added/deleted changes.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("renderIndicators", NullValueHandling = NullValueHandling.Ignore)]
+ bool? RenderIndicators { get; set; }
+ /// <summary>
+ /// Render the differences in two side-by-side editors.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("renderSideBySide", NullValueHandling = NullValueHandling.Ignore)]
+ bool? RenderSideBySide { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IDimension.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IDimension.cs
new file mode 100644
index 000000000..1e5c142f7
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IDimension.cs
@@ -0,0 +1,18 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// The initial editor dimension (to avoid measuring the container).
+ /// </summary>
+ public interface IDimension
+ {
+ [JsonProperty("height", NullValueHandling = NullValueHandling.Ignore)]
+ uint Height { get; set; }
+
+ [JsonProperty("width", NullValueHandling = NullValueHandling.Ignore)]
+ uint Width { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IEditorConstructionOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IEditorConstructionOptions.cs
new file mode 100644
index 000000000..87c6f6d49
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IEditorConstructionOptions.cs
@@ -0,0 +1,12 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ public interface IEditorConstructionOptions : IEditorOptions
+ {
+ [JsonProperty("dimension", NullValueHandling = NullValueHandling.Ignore)]
+ IDimension? Dimension { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IEditorOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IEditorOptions.cs
new file mode 100644
index 000000000..86d4c2d07
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IEditorOptions.cs
@@ -0,0 +1,743 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Configuration options for the editor.
+ /// </summary>
+ public interface IEditorOptions
+ {
+ /// <summary>
+ /// Accept suggestions on provider defined characters.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("acceptSuggestionOnCommitCharacter", NullValueHandling = NullValueHandling.Ignore)]
+ bool? AcceptSuggestionOnCommitCharacter { get; set; }
+
+ /// <summary>
+ /// Accept suggestions on ENTER.
+ /// Defaults to 'on'.
+ /// </summary>
+ [JsonProperty("acceptSuggestionOnEnter", NullValueHandling = NullValueHandling.Ignore)]
+ AcceptSuggestionOnEnter? AcceptSuggestionOnEnter { get; set; }
+
+ /// <summary>
+ /// Controls the number of lines in the editor that can be read out by a screen reader
+ /// </summary>
+ [JsonProperty("accessibilityPageSize", NullValueHandling = NullValueHandling.Ignore)]
+ int? AccessibilityPageSize { get; set; }
+
+ /// <summary>
+ /// Configure the editor's accessibility support.
+ /// Defaults to 'auto'. It is best to leave this to 'auto'.
+ /// </summary>
+ [JsonProperty("accessibilitySupport", NullValueHandling = NullValueHandling.Ignore)]
+ AccessibilitySupport? AccessibilitySupport { get; set; }
+
+ /// <summary>
+ /// The aria label for the editor's textarea (when it is focused).
+ /// </summary>
+ [JsonProperty("ariaLabel", NullValueHandling = NullValueHandling.Ignore)]
+ string? AriaLabel { get; set; }
+
+ /// <summary>
+ /// Options for auto closing brackets.
+ /// Defaults to language defined behavior.
+ /// </summary>
+ [JsonProperty("autoClosingBrackets", NullValueHandling = NullValueHandling.Ignore)]
+ AutoClosingBrackets? AutoClosingBrackets { get; set; }
+
+ /// <summary>
+ /// Options for typing over closing quotes or brackets.
+ /// </summary>
+ [JsonProperty("autoClosingOvertype", NullValueHandling = NullValueHandling.Ignore)]
+ AutoClosingOvertype? AutoClosingOvertype { get; set; }
+
+ /// <summary>
+ /// Options for auto closing quotes.
+ /// Defaults to language defined behavior.
+ /// </summary>
+ [JsonProperty("autoClosingQuotes", NullValueHandling = NullValueHandling.Ignore)]
+ AutoClosingQuotes? AutoClosingQuotes { get; set; }
+
+ /// <summary>
+ /// Controls whether the editor should automatically adjust the indentation when users type, paste, move or indent lines.
+ /// Defaults to advanced.
+ /// </summary>
+ [JsonProperty("autoIndent", NullValueHandling = NullValueHandling.Ignore)]
+ AutoIndent? AutoIndent { get; set; }
+
+ /// <summary>
+ /// Enable that the editor will install an interval to check if its container dom node size
+ /// has changed.
+ /// Enabling this might have a severe performance impact.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("automaticLayout", NullValueHandling = NullValueHandling.Ignore)]
+ bool? AutomaticLayout { get; set; }
+
+ /// <summary>
+ /// Options for auto surrounding.
+ /// Defaults to always allowing auto surrounding.
+ /// </summary>
+ [JsonProperty("autoSurround", NullValueHandling = NullValueHandling.Ignore)]
+ AutoSurround? AutoSurround { get; set; }
+
+ /// <summary>
+ /// Timeout for running code actions on save.
+ /// </summary>
+ [JsonProperty("codeActionsOnSaveTimeout", NullValueHandling = NullValueHandling.Ignore)]
+ int? CodeActionsOnSaveTimeout { get; set; }
+
+ /// <summary>
+ /// Show code lens
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("codeLens", NullValueHandling = NullValueHandling.Ignore)]
+ bool? CodeLens { get; set; }
+
+ /// <summary>
+ /// Enable inline color decorators and color picker rendering.
+ /// </summary>
+ [JsonProperty("colorDecorators", NullValueHandling = NullValueHandling.Ignore)]
+ bool? ColorDecorators { get; set; }
+
+ /// <summary>
+ /// Control the behaviour of comments in the editor.
+ /// </summary>
+ [JsonProperty("comments", NullValueHandling = NullValueHandling.Ignore)]
+ EditorCommentsOptions? Comments { get; set; }
+ /// <summary>
+ /// Enable custom contextmenu.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("contextmenu", NullValueHandling = NullValueHandling.Ignore)]
+ bool? Contextmenu { get; set; }
+
+ /// <summary>
+ /// Syntax highlighting is copied.
+ /// </summary>
+ [JsonProperty("copyWithSyntaxHighlighting", NullValueHandling = NullValueHandling.Ignore)]
+ bool? CopyWithSyntaxHighlighting { get; set; }
+
+ /// <summary>
+ /// Control the cursor animation style, possible values are 'blink', 'smooth', 'phase',
+ /// 'expand' and 'solid'.
+ /// Defaults to 'blink'.
+ /// </summary>
+ [JsonProperty("cursorBlinking", NullValueHandling = NullValueHandling.Ignore)]
+ CursorBlinking? CursorBlinking { get; set; }
+
+ /// <summary>
+ /// Enable smooth caret animation.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("cursorSmoothCaretAnimation", NullValueHandling = NullValueHandling.Ignore)]
+ bool? CursorSmoothCaretAnimation { get; set; }
+
+ /// <summary>
+ /// Control the cursor style, either 'block' or 'line'.
+ /// Defaults to 'line'.
+ /// </summary>
+ [JsonProperty("cursorStyle", NullValueHandling = NullValueHandling.Ignore)]
+ CursorStyle? CursorStyle { get; set; }
+
+ /// <summary>
+ /// Controls the minimal number of visible leading and trailing lines surrounding the cursor.
+ /// Defaults to 0.
+ /// </summary>
+ [JsonProperty("cursorSurroundingLines", NullValueHandling = NullValueHandling.Ignore)]
+ int? CursorSurroundingLines { get; set; }
+
+ /// <summary>
+ /// Controls when `cursorSurroundingLines` should be enforced
+ /// Defaults to `default`, `cursorSurroundingLines` is not enforced when cursor position is
+ /// changed
+ /// by mouse.
+ /// </summary>
+ [JsonProperty("cursorSurroundingLinesStyle", NullValueHandling = NullValueHandling.Ignore)]
+ CursorSurroundingLinesStyle? CursorSurroundingLinesStyle { get; set; }
+
+ /// <summary>
+ /// Control the width of the cursor when cursorStyle is set to 'line'
+ /// </summary>
+ [JsonProperty("cursorWidth", NullValueHandling = NullValueHandling.Ignore)]
+ int? CursorWidth { get; set; }
+
+ /// <summary>
+ /// Disable the use of `transform: translate3d(0px, 0px, 0px)` for the editor margin and
+ /// lines layers.
+ /// The usage of `transform: translate3d(0px, 0px, 0px)` acts as a hint for browsers to
+ /// create an extra layer.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("disableLayerHinting", NullValueHandling = NullValueHandling.Ignore)]
+ bool? DisableLayerHinting { get; set; }
+
+ /// <summary>
+ /// Disable the optimizations for monospace fonts.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("disableMonospaceOptimizations", NullValueHandling = NullValueHandling.Ignore)]
+ bool? DisableMonospaceOptimizations { get; set; }
+
+ /// <summary>
+ /// Controls if the editor should allow to move selections via drag and drop.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("dragAndDrop", NullValueHandling = NullValueHandling.Ignore)]
+ bool? DragAndDrop { get; set; }
+
+ /// <summary>
+ /// Copying without a selection copies the current line.
+ /// </summary>
+ [JsonProperty("emptySelectionClipboard", NullValueHandling = NullValueHandling.Ignore)]
+ bool? EmptySelectionClipboard { get; set; }
+
+ /// <summary>
+ /// Class name to be added to the editor.
+ /// </summary>
+ [JsonProperty("extraEditorClassName", NullValueHandling = NullValueHandling.Ignore)]
+ string? ExtraEditorClassName { get; set; }
+
+ /// <summary>
+ /// FastScrolling mulitplier speed when pressing `Alt`
+ /// Defaults to 5.
+ /// </summary>
+ [JsonProperty("fastScrollSensitivity", NullValueHandling = NullValueHandling.Ignore)]
+ int? FastScrollSensitivity { get; set; }
+
+ /// <summary>
+ /// Control the behavior of the find widget.
+ /// </summary>
+ [JsonProperty("find", NullValueHandling = NullValueHandling.Ignore)]
+ EditorFindOptions? Find { get; set; }
+
+ /// <summary>
+ /// Display overflow widgets as `fixed`.
+ /// Defaults to `false`.
+ /// </summary>
+ [JsonProperty("fixedOverflowWidgets", NullValueHandling = NullValueHandling.Ignore)]
+ bool? FixedOverflowWidgets { get; set; }
+
+ /// <summary>
+ /// Enable code folding
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("folding", NullValueHandling = NullValueHandling.Ignore)]
+ bool? Folding { get; set; }
+
+ /// <summary>
+ /// Enable highlight for folded regions.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("foldingHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ bool? FoldingHighlight { get; set; }
+
+ /// <summary>
+ /// Selects the folding strategy. 'auto' uses the strategies contributed for the current
+ /// document, 'indentation' uses the indentation based folding strategy.
+ /// Defaults to 'auto'.
+ /// </summary>
+ [JsonProperty("foldingStrategy", NullValueHandling = NullValueHandling.Ignore)]
+ FoldingStrategy? FoldingStrategy { get; set; }
+
+ /// <summary>
+ /// The font family
+ /// </summary>
+ [JsonProperty("fontFamily", NullValueHandling = NullValueHandling.Ignore)]
+ string? FontFamily { get; set; }
+
+ /// <summary>
+ /// Enable font ligatures.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("fontLigatures", NullValueHandling = NullValueHandling.Ignore)]
+ bool? FontLigatures { get; set; }
+
+ /// <summary>
+ /// The font size
+ /// </summary>
+ [JsonProperty("fontSize", NullValueHandling = NullValueHandling.Ignore)]
+ int? FontSize { get; set; }
+
+ /// <summary>
+ /// The font weight
+ /// </summary>
+ [JsonProperty("fontWeight", NullValueHandling = NullValueHandling.Ignore)]
+ string? FontWeight { get; set; }
+
+ /// <summary>
+ /// Enable format on paste.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("formatOnPaste", NullValueHandling = NullValueHandling.Ignore)]
+ bool? FormatOnPaste { get; set; }
+
+ /// <summary>
+ /// Enable format on type.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("formatOnType", NullValueHandling = NullValueHandling.Ignore)]
+ bool? FormatOnType { get; set; }
+
+ /// <summary>
+ /// Enable the rendering of the glyph margin.
+ /// Defaults to true in vscode and to false in monaco-editor.
+ /// </summary>
+ [JsonProperty("glyphMargin", NullValueHandling = NullValueHandling.Ignore)]
+ bool? GlyphMargin { get; set; }
+
+ /// <summary>
+ /// Configuration options for go to location
+ /// </summary>
+ [JsonProperty("gotoLocation", NullValueHandling = NullValueHandling.Ignore)]
+ GoToLocationOptions? GotoLocation { get; set; }
+
+ /// <summary>
+ /// Should the cursor be hidden in the overview ruler.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("hideCursorInOverviewRuler", NullValueHandling = NullValueHandling.Ignore)]
+ bool? HideCursorInOverviewRuler { get; set; }
+
+ /// <summary>
+ /// Enable highlighting of the active indent guide.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("highlightActiveIndentGuide", NullValueHandling = NullValueHandling.Ignore)]
+ bool? HighlightActiveIndentGuide { get; set; }
+
+ /// <summary>
+ /// Configure the editor's hover.
+ /// </summary>
+ [JsonProperty("hover", NullValueHandling = NullValueHandling.Ignore)]
+ EditorHoverOptions? Hover { get; set; }
+
+ /// <summary>
+ /// This editor is used inside a diff editor.
+ /// </summary>
+ [JsonProperty("inDiffEditor", NullValueHandling = NullValueHandling.Ignore)]
+ bool? InDiffEditor { get; set; }
+
+ /// <summary>
+ /// The letter spacing
+ /// </summary>
+ [JsonProperty("letterSpacing", NullValueHandling = NullValueHandling.Ignore)]
+ int? LetterSpacing { get; set; }
+
+ /// <summary>
+ /// Control the behavior and rendering of the code action lightbulb.
+ /// </summary>
+ [JsonProperty("lightbulb", NullValueHandling = NullValueHandling.Ignore)]
+ EditorLightbulbOptions? Lightbulb { get; set; }
+
+ /// <summary>
+ /// The width reserved for line decorations (in px).
+ /// Line decorations are placed between line numbers and the editor content.
+ /// You can pass in a string in the format floating point followed by "ch". e.g. 1.3ch.
+ /// Defaults to 10.
+ /// </summary>
+ [JsonProperty("lineDecorationsWidth", NullValueHandling = NullValueHandling.Ignore)]
+ uint? LineDecorationsWidth { get; set; }
+
+ /// <summary>
+ /// The line height
+ /// </summary>
+ [JsonProperty("lineHeight", NullValueHandling = NullValueHandling.Ignore)]
+ int? LineHeight { get; set; }
+
+ /// <summary>
+ /// Control the rendering of line numbers.
+ /// If it is a function, it will be invoked when rendering a line number and the return value
+ /// will be rendered.
+ /// Otherwise, if it is a truey, line numbers will be rendered normally (equivalent of using
+ /// an identity function).
+ /// Otherwise, line numbers will not be rendered.
+ /// Defaults to `on`.
+ /// </summary>
+ [JsonProperty("lineNumbers", NullValueHandling = NullValueHandling.Ignore)]
+ LineNumbersType? LineNumbers { get; set; }
+
+ /// <summary>
+ /// Control the width of line numbers, by reserving horizontal space for rendering at least
+ /// an amount of digits.
+ /// Defaults to 5.
+ /// </summary>
+ [JsonProperty("lineNumbersMinChars", NullValueHandling = NullValueHandling.Ignore)]
+ int? LineNumbersMinChars { get; set; }
+
+ /// <summary>
+ /// Enable detecting links and making them clickable.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("links", NullValueHandling = NullValueHandling.Ignore)]
+ bool? Links { get; set; }
+
+ /// <summary>
+ /// Enable highlighting of matching brackets.
+ /// Defaults to 'always'.
+ /// </summary>
+ [JsonProperty("matchBrackets", NullValueHandling = NullValueHandling.Ignore)]
+ MatchBrackets? MatchBrackets { get; set; }
+
+ /// <summary>
+ /// Control the behavior and rendering of the minimap.
+ /// </summary>
+ [JsonProperty("minimap", NullValueHandling = NullValueHandling.Ignore)]
+ EditorMinimapOptions? Minimap { get; set; }
+
+ /// <summary>
+ /// Control the mouse pointer style, either 'text' or 'default' or 'copy'
+ /// Defaults to 'text'
+ /// </summary>
+ [JsonProperty("mouseStyle", NullValueHandling = NullValueHandling.Ignore)]
+ MouseStyle? MouseStyle { get; set; }
+
+ /// <summary>
+ /// A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.
+ /// Defaults to 1.
+ /// </summary>
+ [JsonProperty("mouseWheelScrollSensitivity", NullValueHandling = NullValueHandling.Ignore)]
+ int? MouseWheelScrollSensitivity { get; set; }
+
+ /// <summary>
+ /// Zoom the font in the editor when using the mouse wheel in combination with holding Ctrl.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("mouseWheelZoom", NullValueHandling = NullValueHandling.Ignore)]
+ bool? MouseWheelZoom { get; set; }
+
+ /// <summary>
+ /// Merge overlapping selections.
+ /// Defaults to true
+ /// </summary>
+ [JsonProperty("multiCursorMergeOverlapping", NullValueHandling = NullValueHandling.Ignore)]
+ bool? MultiCursorMergeOverlapping { get; set; }
+
+ /// <summary>
+ /// The modifier to be used to add multiple cursors with the mouse.
+ /// Defaults to 'alt'
+ /// </summary>
+ [JsonProperty("multiCursorModifier", NullValueHandling = NullValueHandling.Ignore)]
+ MultiCursorModifier? MultiCursorModifier { get; set; }
+
+ /// <summary>
+ /// Configure the behaviour when pasting a text with the line count equal to the cursor
+ /// count.
+ /// Defaults to 'spread'.
+ /// </summary>
+ [JsonProperty("multiCursorPaste", NullValueHandling = NullValueHandling.Ignore)]
+ MultiCursorPaste? MultiCursorPaste { get; set; }
+
+ /// <summary>
+ /// Enable semantic occurrences highlight.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("occurrencesHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ bool? OccurrencesHighlight { get; set; }
+
+ /// <summary>
+ /// Controls if a border should be drawn around the overview ruler.
+ /// Defaults to `true`.
+ /// </summary>
+ [JsonProperty("overviewRulerBorder", NullValueHandling = NullValueHandling.Ignore)]
+ bool? OverviewRulerBorder { get; set; }
+
+ /// <summary>
+ /// The number of vertical lanes the overview ruler should render.
+ /// Defaults to 3.
+ /// </summary>
+ [JsonProperty("overviewRulerLanes", NullValueHandling = NullValueHandling.Ignore)]
+ int? OverviewRulerLanes { get; set; }
+
+ /// <summary>
+ /// Parameter hint options.
+ /// </summary>
+ [JsonProperty("parameterHints", NullValueHandling = NullValueHandling.Ignore)]
+ EditorParameterHintOptions? ParameterHints { get; set; }
+
+ /// <summary>
+ /// Controls whether to focus the inline editor in the peek widget by default.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("peekWidgetDefaultFocus", NullValueHandling = NullValueHandling.Ignore)]
+ bool? PeekWidgetDefaultFocus { get; set; }
+
+ /// <summary>
+ /// Enable quick suggestions (shadow suggestions)
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("quickSuggestions", NullValueHandling = NullValueHandling.Ignore)]
+ bool? QuickSuggestions { get; set; }
+
+ /// <summary>
+ /// Quick suggestions show delay (in ms)
+ /// Defaults to 10 (ms)
+ /// </summary>
+ [JsonProperty("quickSuggestionsDelay", NullValueHandling = NullValueHandling.Ignore)]
+ int? QuickSuggestionsDelay { get; set; }
+
+ /// <summary>
+ /// Should the editor be read only.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("readOnly", NullValueHandling = NullValueHandling.Ignore)]
+ bool? ReadOnly { get; set; }
+
+ /// <summary>
+ /// Enable rendering of control characters.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("renderControlCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ bool? RenderControlCharacters { get; set; }
+
+ /// <summary>
+ /// Render last line number when the file ends with a newline.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("renderFinalNewline", NullValueHandling = NullValueHandling.Ignore)]
+ bool? RenderFinalNewline { get; set; }
+
+ /// <summary>
+ /// Enable rendering of indent guides.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("renderIndentGuides", NullValueHandling = NullValueHandling.Ignore)]
+ bool? RenderIndentGuides { get; set; }
+
+ /// <summary>
+ /// Enable rendering of current line highlight.
+ /// Defaults to all.
+ /// </summary>
+ [JsonProperty("renderLineHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ RenderLineHighlight? RenderLineHighlight { get; set; }
+
+ /// <summary>
+ /// Should the editor render validation decorations.
+ /// Defaults to editable.
+ /// </summary>
+ [JsonProperty("renderValidationDecorations", NullValueHandling = NullValueHandling.Ignore)]
+ string? RenderValidationDecorations { get; set; }
+
+ /// <summary>
+ /// Enable rendering of whitespace.
+ /// Defaults to none.
+ /// </summary>
+ [JsonProperty("renderWhitespace", NullValueHandling = NullValueHandling.Ignore)]
+ RenderWhitespace? RenderWhitespace { get; set; }
+
+ /// <summary>
+ /// When revealing the cursor, a virtual padding (px) is added to the cursor, turning it into
+ /// a rectangle.
+ /// This virtual padding ensures that the cursor gets revealed before hitting the edge of the
+ /// viewport.
+ /// Defaults to 30 (px).
+ /// </summary>
+ [JsonProperty("revealHorizontalRightPadding", NullValueHandling = NullValueHandling.Ignore)]
+ int? RevealHorizontalRightPadding { get; set; }
+
+ /// <summary>
+ /// Render the editor selection with rounded borders.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("roundedSelection", NullValueHandling = NullValueHandling.Ignore)]
+ bool? RoundedSelection { get; set; }
+
+ /// <summary>
+ /// Render vertical lines at the specified columns.
+ /// Defaults to empty array.
+ /// </summary>
+ [JsonProperty("rulers", NullValueHandling = NullValueHandling.Ignore)]
+ int[]? Rulers { get; set; }
+
+ /// <summary>
+ /// Control the behavior and rendering of the scrollbars.
+ /// </summary>
+ [JsonProperty("scrollbar", NullValueHandling = NullValueHandling.Ignore)]
+ EditorScrollbarOptions? Scrollbar { get; set; }
+
+ /// <summary>
+ /// Enable that scrolling can go beyond the last column by a number of columns.
+ /// Defaults to 5.
+ /// </summary>
+ [JsonProperty("scrollBeyondLastColumn", NullValueHandling = NullValueHandling.Ignore)]
+ int? ScrollBeyondLastColumn { get; set; }
+
+ /// <summary>
+ /// Enable that scrolling can go one screen size after the last line.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("scrollBeyondLastLine", NullValueHandling = NullValueHandling.Ignore)]
+ bool? ScrollBeyondLastLine { get; set; }
+
+ /// <summary>
+ /// Enable Linux primary clipboard.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("selectionClipboard", NullValueHandling = NullValueHandling.Ignore)]
+ bool? SelectionClipboard { get; set; }
+
+ /// <summary>
+ /// Enable selection highlight.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("selectionHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ bool? SelectionHighlight { get; set; }
+
+ /// <summary>
+ /// Should the corresponding line be selected when clicking on the line number?
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("selectOnLineNumbers", NullValueHandling = NullValueHandling.Ignore)]
+ bool? SelectOnLineNumbers { get; set; }
+
+ /// <summary>
+ /// Controls whether the fold actions in the gutter stay always visible or hide unless the
+ /// mouse is over the gutter.
+ /// Defaults to 'mouseover'.
+ /// </summary>
+ [JsonProperty("showFoldingControls", NullValueHandling = NullValueHandling.Ignore)]
+ Show? ShowFoldingControls { get; set; }
+
+ /// <summary>
+ /// Controls fading out of unused variables.
+ /// </summary>
+ [JsonProperty("showUnused", NullValueHandling = NullValueHandling.Ignore)]
+ bool? ShowUnused { get; set; }
+
+ /// <summary>
+ /// Enable that the editor animates scrolling to a position.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("smoothScrolling", NullValueHandling = NullValueHandling.Ignore)]
+ bool? SmoothScrolling { get; set; }
+
+ /// <summary>
+ /// Enable snippet suggestions. Default to 'true'.
+ /// </summary>
+ [JsonProperty("snippetSuggestions", NullValueHandling = NullValueHandling.Ignore)]
+ SnippetSuggestions? SnippetSuggestions { get; set; }
+
+ /// <summary>
+ /// Performance guard: Stop rendering a line after x characters.
+ /// Defaults to 10000.
+ /// Use -1 to never stop rendering
+ /// </summary>
+ [JsonProperty("stopRenderingLineAfter", NullValueHandling = NullValueHandling.Ignore)]
+ int? StopRenderingLineAfter { get; set; }
+
+ /// <summary>
+ /// Suggest options.
+ /// </summary>
+ [JsonProperty("suggest", NullValueHandling = NullValueHandling.Ignore)]
+ SuggestOptions? Suggest { get; set; }
+
+ /// <summary>
+ /// The font size for the suggest widget.
+ /// Defaults to the editor font size.
+ /// </summary>
+ [JsonProperty("suggestFontSize", NullValueHandling = NullValueHandling.Ignore)]
+ int? SuggestFontSize { get; set; }
+
+ /// <summary>
+ /// The line height for the suggest widget.
+ /// Defaults to the editor line height.
+ /// </summary>
+ [JsonProperty("suggestLineHeight", NullValueHandling = NullValueHandling.Ignore)]
+ int? SuggestLineHeight { get; set; }
+
+ /// <summary>
+ /// Enable the suggestion box to pop-up on trigger characters.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("suggestOnTriggerCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ bool? SuggestOnTriggerCharacters { get; set; }
+
+ /// <summary>
+ /// The history mode for suggestions.
+ /// </summary>
+ [JsonProperty("suggestSelection", NullValueHandling = NullValueHandling.Ignore)]
+ SuggestSelection? SuggestSelection { get; set; }
+
+ /// <summary>
+ /// Enable tab completion.
+ /// </summary>
+ [JsonProperty("tabCompletion", NullValueHandling = NullValueHandling.Ignore)]
+ TabCompletion? TabCompletion { get; set; }
+
+ /// <summary>
+ /// Inserting and deleting whitespace follows tab stops.
+ /// </summary>
+ [JsonProperty("useTabStops", NullValueHandling = NullValueHandling.Ignore)]
+ bool? UseTabStops { get; set; }
+
+ /// <summary>
+ /// A string containing the word separators used when doing word navigation.
+ /// Defaults to `~!@#$%^&amp;*()-=+[{]}\|;:'",.&lt;&gt;/?
+ /// *
+ /// </summary>
+ [JsonProperty("wordSeparators", NullValueHandling = NullValueHandling.Ignore)]
+ string? WordSeparators { get; set; }
+
+ /// <summary>
+ /// Control the wrapping of the editor.
+ /// When `wordWrap` = "off", the lines will never wrap.
+ /// When `wordWrap` = "on", the lines will wrap at the viewport width.
+ /// When `wordWrap` = "wordWrapColumn", the lines will wrap at `wordWrapColumn`.
+ /// When `wordWrap` = "bounded", the lines will wrap at min(viewport width, wordWrapColumn).
+ /// Defaults to "off".
+ /// </summary>
+ [JsonProperty("wordWrap", NullValueHandling = NullValueHandling.Ignore)]
+ WordWrap? WordWrap { get; set; }
+
+ /// <summary>
+ /// Configure word wrapping characters. A break will be introduced after these characters.
+ /// Defaults to ' \t})]?|/&amp;.,;¢°′″‰℃、。。、¢,.:;?!%・・ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ァィゥェォャュョッー”〉》」』】〕)]}」'.
+ /// </summary>
+ [JsonProperty("wordWrapBreakAfterCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ string? WordWrapBreakAfterCharacters { get; set; }
+
+ /// <summary>
+ /// Configure word wrapping characters. A break will be introduced before these characters.
+ /// Defaults to '([{‘“〈《「『【〔([{「£¥$£¥++'.
+ /// </summary>
+ [JsonProperty("wordWrapBreakBeforeCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ string? WordWrapBreakBeforeCharacters { get; set; }
+
+ /// <summary>
+ /// Control the wrapping of the editor.
+ /// When `wordWrap` = "off", the lines will never wrap.
+ /// When `wordWrap` = "on", the lines will wrap at the viewport width.
+ /// When `wordWrap` = "wordWrapColumn", the lines will wrap at `wordWrapColumn`.
+ /// When `wordWrap` = "bounded", the lines will wrap at min(viewport width, wordWrapColumn).
+ /// Defaults to 80.
+ /// </summary>
+ [JsonProperty("wordWrapColumn", NullValueHandling = NullValueHandling.Ignore)]
+ int? WordWrapColumn { get; set; }
+
+ /// <summary>
+ /// Force word wrapping when the text appears to be of a minified/generated file.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("wordWrapMinified", NullValueHandling = NullValueHandling.Ignore)]
+ bool? WordWrapMinified { get; set; }
+
+ /// <summary>
+ /// Control indentation of wrapped lines. Can be: 'none', 'same', 'indent' or 'deepIndent'.
+ /// Defaults to 'same' in vscode and to 'none' in monaco-editor.
+ /// </summary>
+ [JsonProperty("wrappingIndent", NullValueHandling = NullValueHandling.Ignore)]
+ WrappingIndent? WrappingIndent { get; set; }
+
+ /// <summary>
+ /// Controls the wrapping strategy to use.
+ /// Defaults to 'simple'.
+ /// </summary>
+ [JsonProperty("wrappingStrategy", NullValueHandling = NullValueHandling.Ignore)]
+ string? WrappingStrategy { get; set; }
+ }
+
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IGlobalEditorOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IGlobalEditorOptions.cs
new file mode 100644
index 000000000..62b947bd0
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IGlobalEditorOptions.cs
@@ -0,0 +1,72 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Options which apply for all editors.
+ /// </summary>
+ public interface IGlobalEditorOptions
+ {
+ /// <summary>
+ /// Controls whether `tabSize` and `insertSpaces` will be automatically detected when a file
+ /// is opened based on the file contents.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("detectIndentation", NullValueHandling = NullValueHandling.Ignore)]
+ bool? DetectIndentation { get; set; }
+
+ /// <summary>
+ /// Insert spaces when pressing `Tab`.
+ /// This setting is overridden based on the file contents when `detectIndentation` is on.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("insertSpaces", NullValueHandling = NullValueHandling.Ignore)]
+ bool? InsertSpaces { get; set; }
+
+ /// <summary>
+ /// Special handling for large files to disable certain memory intensive features.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("largeFileOptimizations", NullValueHandling = NullValueHandling.Ignore)]
+ bool? LargeFileOptimizations { get; set; }
+
+ /// <summary>
+ /// Lines above this length will not be tokenized for performance reasons.
+ /// Defaults to 20000.
+ /// </summary>
+ [JsonProperty("maxTokenizationLineLength", NullValueHandling = NullValueHandling.Ignore)]
+ int? MaxTokenizationLineLength { get; set; }
+
+ /// <summary>
+ /// Keep peek editors open even when int clicking their content or when hitting `Escape`.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("stablePeek", NullValueHandling = NullValueHandling.Ignore)]
+ bool? StablePeek { get; set; }
+
+ /// <summary>
+ /// The number of spaces a tab is equal to.
+ /// This setting is overridden based on the file contents when `detectIndentation` is on.
+ /// Defaults to 4.
+ /// </summary>
+ [JsonProperty("tabSize", NullValueHandling = NullValueHandling.Ignore)]
+ int? TabSize { get; set; }
+
+ /// <summary>
+ /// Remove trailing auto inserted whitespace.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("trimAutoWhitespace", NullValueHandling = NullValueHandling.Ignore)]
+ bool? TrimAutoWhitespace { get; set; }
+
+ /// <summary>
+ /// Controls whether completions should be computed based on words in the document.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("wordBasedSuggestions", NullValueHandling = NullValueHandling.Ignore)]
+ bool? WordBasedSuggestions { get; set; }
+ }
+
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IMarker.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IMarker.cs
new file mode 100644
index 000000000..38ebffda4
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IMarker.cs
@@ -0,0 +1,18 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imarker.html
+ /// </summary>
+ public interface IMarker : IMarkerData
+ {
+ [JsonProperty("owner")]
+ string? Owner { get; set; }
+
+ [JsonProperty("resource")]
+ Uri? Resource { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IMarkerData.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IMarkerData.cs
new file mode 100644
index 000000000..c66d2ca94
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IMarkerData.cs
@@ -0,0 +1,30 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// A structure defining a problem/warning/etc.
+ /// </summary>
+ public interface IMarkerData : IRange
+ {
+ [JsonProperty("code", NullValueHandling = NullValueHandling.Ignore)]
+ string? Code { get; set; }
+
+ [JsonProperty("message")]
+ string? Message { get; set; }
+
+ [JsonProperty("relatedInformation", NullValueHandling = NullValueHandling.Ignore)]
+ RelatedInformation[]? RelatedInformation { get; set; }
+
+ [JsonProperty("severity")]
+ MarkerSeverity Severity { get; set; }
+
+ [JsonProperty("source", NullValueHandling = NullValueHandling.Ignore)]
+ string? Source { get; set; }
+
+ [JsonProperty("tags", NullValueHandling = NullValueHandling.Ignore)]
+ MarkerTag[]? Tags { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IModel.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IModel.cs
new file mode 100644
index 000000000..a825a486c
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IModel.cs
@@ -0,0 +1,74 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System.Collections.Generic;
+using Windows.Foundation;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imodel.html
+ /// </summary>
+ public interface IModel
+ {
+ // TODO: Events
+
+ [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
+ string? Id { get; }
+
+ [JsonProperty("uri", NullValueHandling = NullValueHandling.Ignore)]
+ Uri? Uri { get; }
+
+ //IIdentifiedSingleEditOperation[] ApplyEditsAsync(IIdentifiedSingleEditOperation[] operations)
+ //DeltaDecorationsAsync
+ IAsyncAction? DetectIndentationAsync(bool defaultInsertSpaces, bool defaultTabSize);
+ //FindMatchesAsync(string searchString, bool searchOnlyEditableRange, bool isRegex, ...)
+ //FindNextMatchAsync
+ //FindPreviousMatchAsync
+ //GetAllDecorationsAsync
+ IAsyncOperation<uint>? GetAlternativeVersionIdAsync();
+ //GetDecorationOptionsAsync
+ //GetDecorationRangeAsync
+ //GetDecorationsInRangeAsync
+ IAsyncOperation<string?>? GetEOLAsync();
+ IAsyncOperation<Range?>? GetFullModelRangeAsync();
+ IAsyncOperation<string?>? GetLineContentAsync(uint lineNumber);
+ IAsyncOperation<uint>? GetLineCountAsync();
+ //GetLineDecorationsAsync
+ IAsyncOperation<uint>? GetLineFirstNonWhitespaceColumnAsync(uint lineNumber);
+ IAsyncOperation<uint>? GetLineLastNonWhitespaceColumnAsync(uint lineNumber);
+ IAsyncOperation<uint>? GetLineLengthAsync(uint lineNumber);
+ IAsyncOperation<uint>? GetLineMaxColumnAsync(uint lineNumber);
+ IAsyncOperation<uint>? GetLineMinColumnAsync(uint lineNumber);
+ IAsyncOperation<IEnumerable<string>?>? GetLinesContentAsync();
+ //GetLinesDecorationsAsync
+ IAsyncOperation<string?>? GetModelIdAsync();
+ IAsyncOperation<uint>? GetOffsetAtAsync(IPosition position);
+ IAsyncOperation<string?>? GetOneIndentAsync();
+ //GetOptionsAsync
+ IAsyncOperation<Position?>? GetPositionAtAsync(uint offset);
+ IAsyncOperation<string?>? GetValueAsync();
+ // TextDefined is default eol
+ IAsyncOperation<string?>? GetValueAsync(EndOfLinePreference eol);
+ IAsyncOperation<string?>? GetValueAsync(EndOfLinePreference eol, bool preserveBOM);
+ IAsyncOperation<string?>? GetValueInRangeAsync(IRange range);
+ IAsyncOperation<string?>? GetValueInRangeAsync(IRange range, EndOfLinePreference eol);
+ IAsyncOperation<uint>? GetValueLengthAsync();
+ IAsyncOperation<uint>? GetValueLengthAsync(EndOfLinePreference eol);
+ IAsyncOperation<uint>? GetValueLengthAsync(EndOfLinePreference eol, bool preserveBOM);
+ IAsyncOperation<uint>? GetValueLengthInRangeAsync(IRange range);
+ IAsyncOperation<uint>? GetVersionIdAsync();
+ IAsyncOperation<WordAtPosition?>? GetWordAtPositionAsync(IPosition position);
+ IAsyncOperation<WordAtPosition?>? GetWordUntilPositionAsync(IPosition position);
+ IAsyncOperation<Position?>? ModifyPositionAsync(IPosition position, int number);
+ IAsyncOperation<string?>? NormalizeIndentationAsync(string str);
+ //PushEditOperationsAsync
+ IAsyncAction? PushStackElementAsync();
+ IAsyncAction? SetEOLAsync(EndOfLineSequence eol);
+ IAsyncAction? SetValue(string newValue);
+ //IAsyncAction UpdateOptions(ITextModelUpdateOptions newOpts);
+ IAsyncOperation<Position?>? ValidatePositionAsync(IPosition position);
+ IAsyncOperation<Range?>? ValidateRangeAsync(IRange range);
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IStandaloneEditorConstructionOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IStandaloneEditorConstructionOptions.cs
new file mode 100644
index 000000000..c1c9168ed
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IStandaloneEditorConstructionOptions.cs
@@ -0,0 +1,47 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ public interface IStandaloneEditorConstructionOptions : IEditorConstructionOptions, IGlobalEditorOptions
+ {
+ /// <summary>
+ /// The initial model associated with this code editor.
+ /// </summary>
+ [JsonProperty("model")]
+ IModel? Model { get; set; }
+
+ /// <summary>
+ /// The initial value of the auto created model in the editor.
+ /// To not create automatically a model, use `model: null`.
+ /// </summary>
+ [JsonProperty("value", NullValueHandling = NullValueHandling.Ignore)]
+ string? Value { get; set; }
+
+ /// <summary>
+ /// The initial language of the auto created model in the editor.
+ /// To not create automatically a model, use `model: null`.
+ /// </summary>
+ [JsonProperty("language", NullValueHandling = NullValueHandling.Ignore)]
+ string? Language { get; set; }
+
+ /// <summary>
+ /// Initial theme to be used for rendering.
+ /// The current out-of-the-box available themes are: 'vs' (default), 'vs-dark', 'hc-black'.
+ /// You can create custom themes via `monaco.editor.defineTheme`.
+ /// To switch a theme, use `monaco.editor.setTheme`
+ /// </summary>
+ [JsonProperty("theme", NullValueHandling = NullValueHandling.Ignore)]
+ string? Theme { get; set; }
+
+ /// <summary>
+ /// An URL to open when Ctrl+H (Windows and Linux) or Cmd+H (OSX) is pressed in
+ /// the accessibility help dialog in the editor.
+ ///
+ /// Defaults to "https://go.microsoft.com/fwlink/?linkid=852450"
+ /// </summary>
+ [JsonProperty("accessibilityHelpUrl", NullValueHandling = NullValueHandling.Ignore)]
+ string? AccessibilityHelpUrl { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IWordAtPosition.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IWordAtPosition.cs
new file mode 100644
index 000000000..6a3042dc4
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/IWordAtPosition.cs
@@ -0,0 +1,31 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.iwordatposition.html
+ /// </summary>
+ [JsonConverter(typeof(InterfaceToClassConverter<IWordAtPosition, WordAtPosition>))]
+ public interface IWordAtPosition
+ {
+ /// <summary>
+ /// Column where the word ends.
+ /// </summary>
+ [JsonProperty("endColumn")]
+ uint EndColumn { get; }
+
+ /// <summary>
+ /// Column where the word starts.
+ /// </summary>
+ [JsonProperty("startColumn")]
+ uint StartColumn { get; }
+
+ /// <summary>
+ /// The word.
+ /// </summary>
+ [JsonProperty("word")]
+ string? Word { get; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/InsertMode.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/InsertMode.cs
new file mode 100644
index 000000000..40392b88f
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/InsertMode.cs
@@ -0,0 +1,17 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Overwrite word ends on accept. Default to false.
+ /// </summary>
+ [JsonConverter(typeof(InsertModeConverter))]
+ public enum InsertMode
+ {
+ Insert,
+ Replace
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/InsertModeConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/InsertModeConverter.cs
new file mode 100644
index 000000000..245f70cab
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/InsertModeConverter.cs
@@ -0,0 +1,53 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class InsertModeConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(InsertMode) || t == typeof(InsertMode?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "insert":
+ return InsertMode.Insert;
+ case "replace":
+ return InsertMode.Replace;
+ }
+ throw new Exception("Cannot unmarshal type InsertMode");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (InsertMode)untypedValue;
+ switch (value)
+ {
+ case InsertMode.Insert:
+ serializer.Serialize(writer, "insert");
+ return;
+ case InsertMode.Replace:
+ serializer.Serialize(writer, "replace");
+ return;
+ }
+ throw new Exception("Cannot marshal type InsertMode");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/InterfaceToClassConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/InterfaceToClassConverter.cs
new file mode 100644
index 000000000..6f1180c4e
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/InterfaceToClassConverter.cs
@@ -0,0 +1,36 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Used to upcast an interface to its object type during deserialization of JSON.
+ /// </summary>
+ /// <typeparam name="TInterface">Type of base Interface.</typeparam>
+ /// <typeparam name="TClass">Type of class to use for deserializing object with interface.</typeparam>
+ internal class InterfaceToClassConverter<TInterface, TClass> : JsonConverter where TClass : TInterface, new()
+ {
+ public override bool CanConvert(Type objectType)
+ {
+ // We only want to convert objects that are of the interface.
+ return objectType == typeof(TInterface);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
+ {
+ // Use the implementation type for the deserialization of the interface.
+ var pop = new TClass();
+
+ serializer.Populate(reader, pop);
+
+ return pop;
+ }
+
+ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
+ {
+ serializer.Serialize(writer, value);
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/LineNumbersType.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/LineNumbersType.cs
new file mode 100644
index 000000000..acb267ee4
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/LineNumbersType.cs
@@ -0,0 +1,9 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ [JsonConverter(typeof(LineNumbersTypeConverter))]
+ public enum LineNumbersType { Interval, Off, On, Relative };
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/LineNumbersTypeConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/LineNumbersTypeConverter.cs
new file mode 100644
index 000000000..62f5aa97c
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/LineNumbersTypeConverter.cs
@@ -0,0 +1,60 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class LineNumbersTypeConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t) => t == typeof(LineNumbersType) || t == typeof(LineNumbersType?);
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "interval":
+ return LineNumbersType.Interval;
+ case "off":
+ return LineNumbersType.Off;
+ case "on":
+ return LineNumbersType.On;
+ case "relative":
+ return LineNumbersType.Relative;
+ }
+ throw new Exception("Cannot unmarshal type LineNumbersType");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (LineNumbersType)untypedValue;
+ switch (value)
+ {
+ case LineNumbersType.Interval:
+ serializer.Serialize(writer, "interval");
+ return;
+ case LineNumbersType.Off:
+ serializer.Serialize(writer, "off");
+ return;
+ case LineNumbersType.On:
+ serializer.Serialize(writer, "on");
+ return;
+ case LineNumbersType.Relative:
+ serializer.Serialize(writer, "relative");
+ return;
+ }
+ throw new Exception("Cannot marshal type LineNumbersType");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Marker.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Marker.cs
new file mode 100644
index 000000000..212fbff57
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Marker.cs
@@ -0,0 +1,48 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imarker.html
+ /// </summary>
+ public sealed class Marker : IMarker
+ {
+ [JsonProperty("code", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Code { get; set; }
+
+ [JsonProperty("endColumn")]
+ public uint EndColumn { get; set; }
+
+ [JsonProperty("endLineNumber")]
+ public uint EndLineNumber { get; set; }
+
+ [JsonProperty("message")]
+ public string? Message { get; set; }
+
+ [JsonProperty("owner")]
+ public string? Owner { get; set; }
+
+ [JsonProperty("relatedInformation", NullValueHandling = NullValueHandling.Ignore)]
+ public RelatedInformation[]? RelatedInformation { get; set; }
+
+ [JsonProperty("resource")]
+ public Uri? Resource { get; set; }
+
+ [JsonProperty("severity")]
+ public MarkerSeverity Severity { get; set; }
+
+ [JsonProperty("source", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Source { get; set; }
+
+ [JsonProperty("startColumn")]
+ public uint StartColumn { get; set; }
+
+ [JsonProperty("startLineNumber")]
+ public uint StartLineNumber { get; set; }
+
+ [JsonProperty("tags", NullValueHandling = NullValueHandling.Ignore)]
+ public MarkerTag[]? Tags { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MarkerData.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MarkerData.cs
new file mode 100644
index 000000000..3dfaa3759
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MarkerData.cs
@@ -0,0 +1,42 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imarkerdata.html
+ /// </summary>
+ public sealed class MarkerData : IMarkerData
+ {
+ [JsonProperty("code", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Code { get; set; }
+
+ [JsonProperty("endColumn")]
+ public uint EndColumn { get; set; }
+
+ [JsonProperty("endLineNumber")]
+ public uint EndLineNumber { get; set; }
+
+ [JsonProperty("message")]
+ public string? Message { get; set; }
+
+ [JsonProperty("relatedInformation", NullValueHandling = NullValueHandling.Ignore)]
+ public RelatedInformation[]? RelatedInformation { get; set; }
+
+ [JsonProperty("severity")]
+ public MarkerSeverity Severity { get; set; }
+
+ [JsonProperty("source", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Source { get; set; }
+
+ [JsonProperty("startColumn")]
+ public uint StartColumn { get; set; }
+
+ [JsonProperty("startLineNumber")]
+ public uint StartLineNumber { get; set; }
+
+ [JsonProperty("tags", NullValueHandling = NullValueHandling.Ignore)]
+ public MarkerTag[]? Tags { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MatchBrackets.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MatchBrackets.cs
new file mode 100644
index 000000000..91e1013bd
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MatchBrackets.cs
@@ -0,0 +1,14 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Enable highlighting of matching brackets.
+ /// Defaults to 'always'.
+ /// </summary>
+ [JsonConverter(typeof(MatchBracketsConverter))]
+ public enum MatchBrackets { Always, Near, Never };
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MatchBracketsConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MatchBracketsConverter.cs
new file mode 100644
index 000000000..c95463cf3
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MatchBracketsConverter.cs
@@ -0,0 +1,55 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class MatchBracketsConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t) => t == typeof(MatchBrackets) || t == typeof(MatchBrackets?);
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "always":
+ return MatchBrackets.Always;
+ case "near":
+ return MatchBrackets.Near;
+ case "never":
+ return MatchBrackets.Never;
+ }
+ throw new Exception("Cannot unmarshal type MatchBrackets");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (MatchBrackets)untypedValue;
+ switch (value)
+ {
+ case MatchBrackets.Always:
+ serializer.Serialize(writer, "always");
+ return;
+ case MatchBrackets.Near:
+ serializer.Serialize(writer, "near");
+ return;
+ case MatchBrackets.Never:
+ serializer.Serialize(writer, "never");
+ return;
+ }
+ throw new Exception("Cannot marshal type MatchBrackets");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ModelDecorationMinimapOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ModelDecorationMinimapOptions.cs
new file mode 100644
index 000000000..13817030e
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ModelDecorationMinimapOptions.cs
@@ -0,0 +1,29 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ public sealed class ModelDecorationMinimapOptions
+ {
+ /// <summary>
+ /// CSS color to render.
+ /// e.g.: rgba(100, 100, 100, 0.5) or a color from the color registry
+ /// </summary>
+ [JsonProperty("color", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Color { get; set; }
+
+ /// <summary>
+ /// CSS color to render.
+ /// e.g.: rgba(100, 100, 100, 0.5) or a color from the color registry
+ /// </summary>
+ [JsonProperty("darkColor", NullValueHandling = NullValueHandling.Ignore)]
+ public string? DarkColor { get; set; }
+
+ /// <summary>
+ /// The position in the overview ruler.
+ /// </summary>
+ [JsonProperty("position")]
+ public int Position { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ModelDecorationOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ModelDecorationOptions.cs
new file mode 100644
index 000000000..dd0a4e1db
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ModelDecorationOptions.cs
@@ -0,0 +1,113 @@
+#nullable enable
+
+using DevToys.MonacoEditor.Monaco.Helpers;
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Options for a model decoration.
+ ///
+ /// Options associated with this decoration.
+ /// </summary>
+ public sealed class ModelDecorationOptions
+ {
+ /// <summary>
+ /// If set, the decoration will be rendered after the text with this CSS class name.
+ /// </summary>
+ [JsonProperty("afterContentClassName")]
+ public string? AfterContentClassName { get; set; }
+
+ /// <summary>
+ /// If set, the decoration will be rendered before the text with this CSS class name.
+ /// </summary>
+ [JsonProperty("beforeContentClassName")]
+ public string? BeforeContentClassName { get; set; }
+
+ /// <summary>
+ /// CSS class name describing the decoration.
+ /// </summary>
+ [JsonProperty("className")]
+ public CssLineStyle? ClassName { get; set; }
+
+ /// <summary>
+ /// If set, the decoration will be rendered in the glyph margin with this CSS class name.
+ /// </summary>
+ [JsonProperty("glyphMarginClassName")]
+ public CssGlyphStyle? GlyphMarginClassName { get; set; }
+
+ /// <summary>
+ /// Message to be rendered when hovering over the glyph margin decoration.
+ /// </summary>
+ [JsonProperty("glyphMarginHoverMessage")]
+ public MarkdownString[]? GlyphMarginHoverMessage { get; set; }
+
+ /// <summary>
+ /// Array of MarkdownString to render as the decoration message.
+ /// </summary>
+ [JsonProperty("hoverMessage")]
+ public MarkdownString[]? HoverMessage { get; set; }
+
+ /// <summary>
+ /// If set, the decoration will be rendered inline with the text with this CSS class name.
+ /// Please use this only for CSS rules that must impact the text. For example, use
+ /// `className`
+ /// to have a background color decoration.
+ /// </summary>
+ [JsonProperty("inlineClassName")]
+ public CssInlineStyle? InlineClassName { get; set; }
+
+ /// <summary>
+ /// If there is an `inlineClassName` which affects letter spacing.
+ /// </summary>
+ [JsonProperty("inlineClassNameAffectsLetterSpacing", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? InlineClassNameAffectsLetterSpacing { get; set; }
+
+ /// <summary>
+ /// Should the decoration expand to encompass a whole line.
+ /// </summary>
+ [JsonProperty("isWholeLine", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? IsWholeLine { get; set; }
+
+ /// <summary>
+ /// If set, the decoration will be rendered in the lines decorations with this CSS class name.
+ /// </summary>
+ [JsonProperty("linesDecorationsClassName")]
+ public string? LinesDecorationsClassName { get; set; }
+
+ /// <summary>
+ /// If set, the decoration will be rendered in the margin (covering its full width) with this
+ /// CSS class name.
+ /// </summary>
+ [JsonProperty("marginClassName")]
+ public string? MarginClassName { get; set; }
+
+ /// <summary>
+ /// If set, render this decoration in the minimap.
+ /// </summary>
+ [JsonProperty("minimap")]
+ public ModelDecorationMinimapOptions? Minimap { get; set; }
+
+ /// <summary>
+ /// If set, render this decoration in the overview ruler.
+ /// </summary>
+ [JsonProperty("overviewRuler")]
+ public ModelDecorationOverviewRulerOptions? OverviewRuler { get; set; }
+
+ /// <summary>
+ /// Customize the growing behavior of the decoration when typing at the edges of the
+ /// decoration.
+ /// Defaults to TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges
+ /// </summary>
+ [JsonProperty("stickiness", NullValueHandling = NullValueHandling.Ignore)]
+ public TrackedRangeStickiness? Stickiness { get; set; }
+
+ /// <summary>
+ /// Specifies the stack order of a decoration.
+ /// A decoration with greater stack order is always in front of a decoration with a lower
+ /// stack order.
+ /// </summary>
+ [JsonProperty("zIndex", NullValueHandling = NullValueHandling.Ignore)]
+ public int? ZIndex { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ModelDecorationOverviewRulerOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ModelDecorationOverviewRulerOptions.cs
new file mode 100644
index 000000000..1fba73124
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ModelDecorationOverviewRulerOptions.cs
@@ -0,0 +1,29 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ public sealed class ModelDecorationOverviewRulerOptions
+ {
+ /// <summary>
+ /// CSS color to render.
+ /// e.g.: rgba(100, 100, 100, 0.5) or a color from the color registry
+ /// </summary>
+ [JsonProperty("color", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Color { get; set; }
+
+ /// <summary>
+ /// CSS color to render.
+ /// e.g.: rgba(100, 100, 100, 0.5) or a color from the color registry
+ /// </summary>
+ [JsonProperty("darkColor", NullValueHandling = NullValueHandling.Ignore)]
+ public string? DarkColor { get; set; }
+
+ /// <summary>
+ /// The position in the overview ruler.
+ /// </summary>
+ [JsonProperty("position")]
+ public int Position { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ModelDeltaDecoration.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ModelDeltaDecoration.cs
new file mode 100644
index 000000000..7d5489c5d
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ModelDeltaDecoration.cs
@@ -0,0 +1,24 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// New model decorations.
+ /// </summary>
+ public sealed class ModelDeltaDecoration
+ {
+ [JsonProperty("options")]
+ public ModelDecorationOptions Options { get; private set; }
+
+ [JsonProperty("range")]
+ public IRange Range { get; private set; }
+
+ public ModelDeltaDecoration(IRange range, ModelDecorationOptions options)
+ {
+ Range = range;
+ Options = options;
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MouseStyle.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MouseStyle.cs
new file mode 100644
index 000000000..c7a0b867f
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MouseStyle.cs
@@ -0,0 +1,19 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Control the mouse pointer style, either 'text' or 'default' or 'copy'
+ /// Defaults to 'text'
+ /// </summary>
+ [JsonConverter(typeof(MouseStyleConverter))]
+ public enum MouseStyle
+ {
+ Copy,
+ Default,
+ Text
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MouseStyleConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MouseStyleConverter.cs
new file mode 100644
index 000000000..c51baec1b
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MouseStyleConverter.cs
@@ -0,0 +1,61 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class MouseStyleConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(MouseStyle) || t == typeof(MouseStyle?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "copy":
+ return MouseStyle.Copy;
+ case "default":
+ return MouseStyle.Default;
+ case "text":
+ return MouseStyle.Text;
+ }
+
+ throw new Exception("Cannot unmarshal type MouseStyle");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+
+ var value = (MouseStyle)untypedValue;
+ switch (value)
+ {
+ case MouseStyle.Copy:
+ serializer.Serialize(writer, "copy");
+ return;
+ case MouseStyle.Default:
+ serializer.Serialize(writer, "default");
+ return;
+ case MouseStyle.Text:
+ serializer.Serialize(writer, "text");
+ return;
+ }
+
+ throw new Exception("Cannot marshal type MouseStyle");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultiCursorModifier.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultiCursorModifier.cs
new file mode 100644
index 000000000..5cf99da57
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultiCursorModifier.cs
@@ -0,0 +1,17 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// The modifier to be used to add multiple cursors with the mouse.
+ /// Defaults to 'alt'
+ /// </summary>
+ [JsonConverter(typeof(MultiCursorModifierConverter))]
+ public enum MultiCursorModifier
+ {
+ Alt,
+ CtrlCmd
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultiCursorModifierConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultiCursorModifierConverter.cs
new file mode 100644
index 000000000..c208ebbf6
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultiCursorModifierConverter.cs
@@ -0,0 +1,56 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class MultiCursorModifierConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(MultiCursorModifier) || t == typeof(MultiCursorModifier?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "alt":
+ return MultiCursorModifier.Alt;
+ case "ctrlCmd":
+ return MultiCursorModifier.CtrlCmd;
+ }
+
+ throw new Exception("Cannot unmarshal type MultiCursorModifier");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+
+ var value = (MultiCursorModifier)untypedValue;
+ switch (value)
+ {
+ case MultiCursorModifier.Alt:
+ serializer.Serialize(writer, "alt");
+ return;
+ case MultiCursorModifier.CtrlCmd:
+ serializer.Serialize(writer, "ctrlCmd");
+ return;
+ }
+
+ throw new Exception("Cannot marshal type MultiCursorModifier");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultiCursorPaste.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultiCursorPaste.cs
new file mode 100644
index 000000000..e7e0b5ad5
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultiCursorPaste.cs
@@ -0,0 +1,18 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Configure the behaviour when pasting a text with the line count equal to the cursor
+ /// count.
+ /// Defaults to 'spread'.
+ /// </summary>
+ [JsonConverter(typeof(MultiCursorPasteConverter))]
+ public enum MultiCursorPaste
+ {
+ Full,
+ Spread
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultiCursorPasteConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultiCursorPasteConverter.cs
new file mode 100644
index 000000000..ab0043664
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultiCursorPasteConverter.cs
@@ -0,0 +1,56 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class MultiCursorPasteConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(MultiCursorPaste) || t == typeof(MultiCursorPaste?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "full":
+ return MultiCursorPaste.Full;
+ case "spread":
+ return MultiCursorPaste.Spread;
+ }
+
+ throw new Exception("Cannot unmarshal type MultiCursorPaste");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+
+ var value = (MultiCursorPaste)untypedValue;
+ switch (value)
+ {
+ case MultiCursorPaste.Full:
+ serializer.Serialize(writer, "full");
+ return;
+ case MultiCursorPaste.Spread:
+ serializer.Serialize(writer, "spread");
+ return;
+ }
+
+ throw new Exception("Cannot marshal type MultiCursorPaste");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Multiple.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Multiple.cs
new file mode 100644
index 000000000..8096a7bcc
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Multiple.cs
@@ -0,0 +1,14 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ [JsonConverter(typeof(MultipleConverter))]
+ public enum Multiple
+ {
+ Goto,
+ GotoAndPeek,
+ Peek
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultipleConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultipleConverter.cs
new file mode 100644
index 000000000..1f7ef2832
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/MultipleConverter.cs
@@ -0,0 +1,58 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class MultipleConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(Multiple) || t == typeof(Multiple?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "goto":
+ return Multiple.Goto;
+ case "gotoAndPeek":
+ return Multiple.GotoAndPeek;
+ case "peek":
+ return Multiple.Peek;
+ }
+ throw new Exception("Cannot unmarshal type Multiple");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (Multiple)untypedValue;
+ switch (value)
+ {
+ case Multiple.Goto:
+ serializer.Serialize(writer, "goto");
+ return;
+ case Multiple.GotoAndPeek:
+ serializer.Serialize(writer, "gotoAndPeek");
+ return;
+ case Multiple.Peek:
+ serializer.Serialize(writer, "peek");
+ return;
+ }
+ throw new Exception("Cannot marshal type Multiple");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RelatedInformation.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RelatedInformation.cs
new file mode 100644
index 000000000..244f138b9
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RelatedInformation.cs
@@ -0,0 +1,27 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ public sealed class RelatedInformation
+ {
+ [JsonProperty("endColumn")]
+ public uint EndColumn { get; set; }
+
+ [JsonProperty("endLineNumber")]
+ public uint EndLineNumber { get; set; }
+
+ [JsonProperty("message")]
+ public string? Message { get; set; }
+
+ [JsonProperty("resource")]
+ public Uri? Resource { get; set; }
+
+ [JsonProperty("startColumn")]
+ public uint StartColumn { get; set; }
+
+ [JsonProperty("startLineNumber")]
+ public uint StartLineNumber { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RenderLineHighlight.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RenderLineHighlight.cs
new file mode 100644
index 000000000..b728d820f
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RenderLineHighlight.cs
@@ -0,0 +1,19 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Enable rendering of current line highlight.
+ /// Defaults to all.
+ /// </summary>
+ [JsonConverter(typeof(RenderLineHighlightConverter))]
+ public enum RenderLineHighlight
+ {
+ All,
+ Gutter,
+ Line,
+ None
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RenderLineHighlightConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RenderLineHighlightConverter.cs
new file mode 100644
index 000000000..d51851b85
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RenderLineHighlightConverter.cs
@@ -0,0 +1,63 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class RenderLineHighlightConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(RenderLineHighlight) || t == typeof(RenderLineHighlight?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "all":
+ return RenderLineHighlight.All;
+ case "gutter":
+ return RenderLineHighlight.Gutter;
+ case "line":
+ return RenderLineHighlight.Line;
+ case "none":
+ return RenderLineHighlight.None;
+ }
+ throw new Exception("Cannot unmarshal type RenderLineHighlight");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (RenderLineHighlight)untypedValue;
+ switch (value)
+ {
+ case RenderLineHighlight.All:
+ serializer.Serialize(writer, "all");
+ return;
+ case RenderLineHighlight.Gutter:
+ serializer.Serialize(writer, "gutter");
+ return;
+ case RenderLineHighlight.Line:
+ serializer.Serialize(writer, "line");
+ return;
+ case RenderLineHighlight.None:
+ serializer.Serialize(writer, "none");
+ return;
+ }
+ throw new Exception("Cannot marshal type RenderLineHighlight");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RenderWhitespace.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RenderWhitespace.cs
new file mode 100644
index 000000000..17f30283a
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RenderWhitespace.cs
@@ -0,0 +1,20 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Enable rendering of whitespace.
+ /// Defaults to none.
+ /// </summary>
+ [JsonConverter(typeof(RenderWhitespaceConverter))]
+ public enum RenderWhitespace
+ {
+ All,
+ Boundary,
+ None,
+ Selection
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RenderWhitespaceConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RenderWhitespaceConverter.cs
new file mode 100644
index 000000000..136df56a0
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/RenderWhitespaceConverter.cs
@@ -0,0 +1,63 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class RenderWhitespaceConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(RenderWhitespace) || t == typeof(RenderWhitespace?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "all":
+ return RenderWhitespace.All;
+ case "boundary":
+ return RenderWhitespace.Boundary;
+ case "none":
+ return RenderWhitespace.None;
+ case "selection":
+ return RenderWhitespace.Selection;
+ }
+ throw new Exception("Cannot unmarshal type RenderWhitespace");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (RenderWhitespace)untypedValue;
+ switch (value)
+ {
+ case RenderWhitespace.All:
+ serializer.Serialize(writer, "all");
+ return;
+ case RenderWhitespace.Boundary:
+ serializer.Serialize(writer, "boundary");
+ return;
+ case RenderWhitespace.None:
+ serializer.Serialize(writer, "none");
+ return;
+ case RenderWhitespace.Selection:
+ serializer.Serialize(writer, "selection");
+ return;
+ }
+ throw new Exception("Cannot marshal type RenderWhitespace");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ScrollbarBehavior.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ScrollbarBehavior.cs
new file mode 100644
index 000000000..ef0a4c18c
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ScrollbarBehavior.cs
@@ -0,0 +1,19 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Render horizontal or vertical scrollbar.
+ /// Defaults to 'auto'.
+ /// </summary>
+ [JsonConverter(typeof(ScrollbarBehaviorConverter))]
+ public enum ScrollbarBehavior
+ {
+ Auto,
+ Hidden,
+ Visible
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ScrollbarBehaviorConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ScrollbarBehaviorConverter.cs
new file mode 100644
index 000000000..5cc186e92
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ScrollbarBehaviorConverter.cs
@@ -0,0 +1,58 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class ScrollbarBehaviorConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(ScrollbarBehavior) || t == typeof(ScrollbarBehavior?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "auto":
+ return ScrollbarBehavior.Auto;
+ case "hidden":
+ return ScrollbarBehavior.Hidden;
+ case "visible":
+ return ScrollbarBehavior.Visible;
+ }
+ throw new Exception("Cannot unmarshal type ScrollbarBehavior");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (ScrollbarBehavior)untypedValue;
+ switch (value)
+ {
+ case ScrollbarBehavior.Auto:
+ serializer.Serialize(writer, "auto");
+ return;
+ case ScrollbarBehavior.Hidden:
+ serializer.Serialize(writer, "hidden");
+ return;
+ case ScrollbarBehavior.Visible:
+ serializer.Serialize(writer, "visible");
+ return;
+ }
+ throw new Exception("Cannot marshal type ScrollbarBehavior");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Show.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Show.cs
new file mode 100644
index 000000000..ce8bf2806
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Show.cs
@@ -0,0 +1,22 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Control the rendering of the minimap slider.
+ /// Defaults to 'mouseover'.
+ ///
+ /// Controls whether the fold actions in the gutter stay always visible or hide unless the
+ /// mouse is over the gutter.
+ /// Defaults to 'mouseover'.
+ /// </summary>
+ [JsonConverter(typeof(ShowConverter))]
+ public enum Show
+ {
+ Always,
+ Mouseover
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ShowConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ShowConverter.cs
new file mode 100644
index 000000000..b15091be8
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/ShowConverter.cs
@@ -0,0 +1,53 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class ShowConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(Show) || t == typeof(Show?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "always":
+ return Show.Always;
+ case "mouseover":
+ return Show.Mouseover;
+ }
+ throw new Exception("Cannot unmarshal type Show");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (Show)untypedValue;
+ switch (value)
+ {
+ case Show.Always:
+ serializer.Serialize(writer, "always");
+ return;
+ case Show.Mouseover:
+ serializer.Serialize(writer, "mouseover");
+ return;
+ }
+ throw new Exception("Cannot marshal type Show");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Side.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Side.cs
new file mode 100644
index 000000000..4ee932b9f
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/Side.cs
@@ -0,0 +1,18 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Control the side of the minimap in editor.
+ /// Defaults to 'right'.
+ /// </summary>
+ [JsonConverter(typeof(SideConverter))]
+ public enum Side
+ {
+ Left,
+ Right
+ };
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SideConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SideConverter.cs
new file mode 100644
index 000000000..fc8144ca1
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SideConverter.cs
@@ -0,0 +1,53 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class SideConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(Side) || t == typeof(Side?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "left":
+ return Side.Left;
+ case "right":
+ return Side.Right;
+ }
+ throw new Exception("Cannot unmarshal type Side");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (Side)untypedValue;
+ switch (value)
+ {
+ case Side.Left:
+ serializer.Serialize(writer, "left");
+ return;
+ case Side.Right:
+ serializer.Serialize(writer, "right");
+ return;
+ }
+ throw new Exception("Cannot marshal type Side");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SingleEditOperation.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SingleEditOperation.cs
new file mode 100644
index 000000000..290510739
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SingleEditOperation.cs
@@ -0,0 +1,33 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// A single edit operation, that acts as a simple replace.
+ /// i.e. Replace text at `range` with `text` in model.
+ /// </summary>
+ public sealed class SingleEditOperation
+ {
+ /// <summary>
+ /// This indicates that this operation has "insert" semantics.
+ /// i.e. forceMoveMarkers = true => if `range` is collapsed, all markers at the position will
+ /// be moved.
+ /// </summary>
+ [JsonProperty("forceMoveMarkers", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ForceMoveMarkers { get; set; }
+
+ /// <summary>
+ /// The range to replace. This can be empty to emulate a simple insert.
+ /// </summary>
+ [JsonProperty("range")]
+ public IRange? Range { get; set; }
+
+ /// <summary>
+ /// The text to replace with. This can be null to emulate a simple delete.
+ /// </summary>
+ [JsonProperty("text")]
+ public string? Text { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SnippetSuggestions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SnippetSuggestions.cs
new file mode 100644
index 000000000..555308aba
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SnippetSuggestions.cs
@@ -0,0 +1,19 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Enable snippet suggestions. Default to 'true'.
+ /// </summary>
+ [JsonConverter(typeof(SnippetSuggestionsConverter))]
+ public enum SnippetSuggestions
+ {
+ Bottom,
+ Inline,
+ None,
+ Top
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SnippetSuggestionsConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SnippetSuggestionsConverter.cs
new file mode 100644
index 000000000..2556c0d1a
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SnippetSuggestionsConverter.cs
@@ -0,0 +1,63 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class SnippetSuggestionsConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(SnippetSuggestions) || t == typeof(SnippetSuggestions?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "bottom":
+ return SnippetSuggestions.Bottom;
+ case "inline":
+ return SnippetSuggestions.Inline;
+ case "none":
+ return SnippetSuggestions.None;
+ case "top":
+ return SnippetSuggestions.Top;
+ }
+ throw new Exception("Cannot unmarshal type SnippetSuggestions");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (SnippetSuggestions)untypedValue;
+ switch (value)
+ {
+ case SnippetSuggestions.Bottom:
+ serializer.Serialize(writer, "bottom");
+ return;
+ case SnippetSuggestions.Inline:
+ serializer.Serialize(writer, "inline");
+ return;
+ case SnippetSuggestions.None:
+ serializer.Serialize(writer, "none");
+ return;
+ case SnippetSuggestions.Top:
+ serializer.Serialize(writer, "top");
+ return;
+ }
+ throw new Exception("Cannot marshal type SnippetSuggestions");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/StandaloneEditorConstructionOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/StandaloneEditorConstructionOptions.cs
new file mode 100644
index 000000000..dabf03a87
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/StandaloneEditorConstructionOptions.cs
@@ -0,0 +1,899 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Runtime.CompilerServices;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// The options to create an editor.
+ /// </summary>
+ public sealed class StandaloneEditorConstructionOptions : IStandaloneEditorConstructionOptions, INotifyPropertyChanged
+ {
+ public event PropertyChangedEventHandler? PropertyChanged;
+
+ private readonly Dictionary<string, object?> _propertyBackingDictionary = new Dictionary<string, object?>();
+
+ private T? GetPropertyValue<T>([CallerMemberName] string? propertyName = null)
+ {
+ if (propertyName == null)
+ {
+ throw new ArgumentNullException(nameof(propertyName));
+ }
+
+ if (_propertyBackingDictionary.TryGetValue(propertyName, out object? value))
+ {
+ return (T?)value;
+ }
+
+ return default;
+ }
+
+ private bool SetPropertyValue<T>(T newValue, [CallerMemberName] string? propertyName = null)
+ {
+ if (propertyName == null)
+ {
+ throw new ArgumentNullException(nameof(propertyName));
+ }
+
+ if (EqualityComparer<T?>.Default.Equals(newValue, GetPropertyValue<T?>(propertyName)))
+ {
+ return false;
+ }
+
+ if (_propertyBackingDictionary.TryGetValue(propertyName, out object? value)
+ && value is T typedValue
+ && typedValue.Equals(newValue))
+ {
+ return true;
+ }
+
+ _propertyBackingDictionary[propertyName] = newValue;
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ return true;
+ }
+
+ /// <summary>
+ /// Accept suggestions on provider defined characters.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("acceptSuggestionOnCommitCharacter", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? AcceptSuggestionOnCommitCharacter
+ {
+ get => GetPropertyValue<bool?>();
+ set => SetPropertyValue(value);
+ }
+
+ /// <summary>
+ /// Accept suggestions on ENTER.
+ /// Defaults to 'on'.
+ /// </summary>
+ [JsonProperty("acceptSuggestionOnEnter", NullValueHandling = NullValueHandling.Ignore)]
+ public AcceptSuggestionOnEnter? AcceptSuggestionOnEnter
+ {
+ get => GetPropertyValue<AcceptSuggestionOnEnter?>();
+ set => SetPropertyValue(value);
+ }
+
+ /// <summary>
+ /// Controls the number of lines in the editor that can be read out by a screen reader
+ /// </summary>
+ [JsonProperty("accessibilityPageSize", NullValueHandling = NullValueHandling.Ignore)]
+ public int? AccessibilityPageSize { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Configure the editor's accessibility support.
+ /// Defaults to 'auto'. It is best to leave this to 'auto'.
+ /// </summary>
+ [JsonProperty("accessibilitySupport", NullValueHandling = NullValueHandling.Ignore)]
+ public AccessibilitySupport? AccessibilitySupport { get => GetPropertyValue<AccessibilitySupport?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The aria label for the editor's textarea (when it is focused).
+ /// </summary>
+ [JsonProperty("ariaLabel", NullValueHandling = NullValueHandling.Ignore)]
+ public string? AriaLabel { get => GetPropertyValue<string>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Options for auto closing brackets.
+ /// Defaults to language defined behavior.
+ /// </summary>
+ [JsonProperty("autoClosingBrackets", NullValueHandling = NullValueHandling.Ignore)]
+ public AutoClosingBrackets? AutoClosingBrackets { get => GetPropertyValue<AutoClosingBrackets?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Options for typing over closing quotes or brackets.
+ /// </summary>
+ [JsonProperty("autoClosingOvertype", NullValueHandling = NullValueHandling.Ignore)]
+ public AutoClosingOvertype? AutoClosingOvertype { get => GetPropertyValue<AutoClosingOvertype?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Options for auto closing quotes.
+ /// Defaults to language defined behavior.
+ /// </summary>
+ [JsonProperty("autoClosingQuotes", NullValueHandling = NullValueHandling.Ignore)]
+ public AutoClosingQuotes? AutoClosingQuotes { get => GetPropertyValue<AutoClosingQuotes?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable auto indentation adjustment.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("autoIndent", NullValueHandling = NullValueHandling.Ignore)]
+ public AutoIndent? AutoIndent { get => GetPropertyValue<AutoIndent?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable that the editor will install an interval to check if its container dom node size
+ /// has changed.
+ /// Enabling this might have a severe performance impact.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("automaticLayout", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? AutomaticLayout { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Options for auto surrounding.
+ /// Defaults to always allowing auto surrounding.
+ /// </summary>
+ [JsonProperty("autoSurround", NullValueHandling = NullValueHandling.Ignore)]
+ public AutoSurround? AutoSurround { get => GetPropertyValue<AutoSurround?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Timeout for running code actions on save.
+ /// </summary>
+ [JsonProperty("codeActionsOnSaveTimeout", NullValueHandling = NullValueHandling.Ignore)]
+ public int? CodeActionsOnSaveTimeout { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Show code lens
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("codeLens", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? CodeLens { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable inline color decorators and color picker rendering.
+ /// </summary>
+ [JsonProperty("colorDecorators", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ColorDecorators { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the behaviour of comments in the editor.
+ /// </summary>
+ [JsonProperty("comments", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorCommentsOptions? Comments { get => GetPropertyValue<EditorCommentsOptions>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable custom contextmenu.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("contextmenu", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Contextmenu { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Syntax highlighting is copied.
+ /// </summary>
+ [JsonProperty("copyWithSyntaxHighlighting", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? CopyWithSyntaxHighlighting { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the cursor animation style, possible values are 'blink', 'smooth', 'phase',
+ /// 'expand' and 'solid'.
+ /// Defaults to 'blink'.
+ /// </summary>
+ [JsonProperty("cursorBlinking", NullValueHandling = NullValueHandling.Ignore)]
+ public CursorBlinking? CursorBlinking { get => GetPropertyValue<CursorBlinking?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable smooth caret animation.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("cursorSmoothCaretAnimation", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? CursorSmoothCaretAnimation { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the cursor style, either 'block' or 'line'.
+ /// Defaults to 'line'.
+ /// </summary>
+ [JsonProperty("cursorStyle", NullValueHandling = NullValueHandling.Ignore)]
+ public CursorStyle? CursorStyle { get => GetPropertyValue<CursorStyle?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls the minimal number of visible leading and trailing lines surrounding the cursor.
+ /// Defaults to 0.
+ /// </summary>
+ [JsonProperty("cursorSurroundingLines", NullValueHandling = NullValueHandling.Ignore)]
+ public int? CursorSurroundingLines { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls when `cursorSurroundingLines` should be enforced
+ /// Defaults to `default`, `cursorSurroundingLines` is not enforced when cursor position is
+ /// changed
+ /// by mouse.
+ /// </summary>
+ [JsonProperty("cursorSurroundingLinesStyle", NullValueHandling = NullValueHandling.Ignore)]
+ public CursorSurroundingLinesStyle? CursorSurroundingLinesStyle { get => GetPropertyValue<CursorSurroundingLinesStyle?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the width of the cursor when cursorStyle is set to 'line'
+ /// </summary>
+ [JsonProperty("cursorWidth", NullValueHandling = NullValueHandling.Ignore)]
+ public int? CursorWidth { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Disable the use of `transform: translate3d(0px, 0px, 0px)` for the editor margin and
+ /// lines layers.
+ /// The usage of `transform: translate3d(0px, 0px, 0px)` acts as a hint for browsers to
+ /// create an extra layer.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("disableLayerHinting", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? DisableLayerHinting { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Disable the optimizations for monospace fonts.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("disableMonospaceOptimizations", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? DisableMonospaceOptimizations { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls if the editor should allow to move selections via drag and drop.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("dragAndDrop", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? DragAndDrop { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Copying without a selection copies the current line.
+ /// </summary>
+ [JsonProperty("emptySelectionClipboard", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? EmptySelectionClipboard { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Class name to be added to the editor.
+ /// </summary>
+ [JsonProperty("extraEditorClassName", NullValueHandling = NullValueHandling.Ignore)]
+ public string? ExtraEditorClassName { get => GetPropertyValue<string>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// FastScrolling mulitplier speed when pressing `Alt`
+ /// Defaults to 5.
+ /// </summary>
+ [JsonProperty("fastScrollSensitivity", NullValueHandling = NullValueHandling.Ignore)]
+ public int? FastScrollSensitivity { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the behavior of the find widget.
+ /// </summary>
+ [JsonProperty("find", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorFindOptions? Find { get => GetPropertyValue<EditorFindOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Display overflow widgets as `fixed`.
+ /// Defaults to `false`.
+ /// </summary>
+ [JsonProperty("fixedOverflowWidgets", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? FixedOverflowWidgets { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable code folding
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("folding", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Folding { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable highlight for folded regions.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("foldingHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? FoldingHighlight { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Selects the folding strategy. 'auto' uses the strategies contributed for the current
+ /// document, 'indentation' uses the indentation based folding strategy.
+ /// Defaults to 'auto'.
+ /// </summary>
+ [JsonProperty("foldingStrategy", NullValueHandling = NullValueHandling.Ignore)]
+ public FoldingStrategy? FoldingStrategy { get => GetPropertyValue<FoldingStrategy?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The font family
+ /// </summary>
+ [JsonProperty("fontFamily", NullValueHandling = NullValueHandling.Ignore)]
+ public string? FontFamily { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable font ligatures.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("fontLigatures", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? FontLigatures { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The font size
+ /// </summary>
+ [JsonProperty("fontSize", NullValueHandling = NullValueHandling.Ignore)]
+ public int? FontSize { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The font weight
+ /// </summary>
+ [JsonProperty("fontWeight", NullValueHandling = NullValueHandling.Ignore)]
+ public string? FontWeight { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable format on paste.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("formatOnPaste", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? FormatOnPaste { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable format on type.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("formatOnType", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? FormatOnType { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable the rendering of the glyph margin.
+ /// Defaults to true in vscode and to false in monaco-editor.
+ /// </summary>
+ [JsonProperty("glyphMargin", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? GlyphMargin { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Configuration options for go to location
+ /// </summary>
+ [JsonProperty("gotoLocation", NullValueHandling = NullValueHandling.Ignore)]
+ public GoToLocationOptions? GotoLocation { get => GetPropertyValue<GoToLocationOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Should the cursor be hidden in the overview ruler.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("hideCursorInOverviewRuler", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? HideCursorInOverviewRuler { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable highlighting of the active indent guide.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("highlightActiveIndentGuide", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? HighlightActiveIndentGuide { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Configure the editor's hover.
+ /// </summary>
+ [JsonProperty("hover", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorHoverOptions? Hover { get => GetPropertyValue<EditorHoverOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// This editor is used inside a diff editor.
+ /// </summary>
+ [JsonProperty("inDiffEditor", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? InDiffEditor { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The letter spacing
+ /// </summary>
+ [JsonProperty("letterSpacing", NullValueHandling = NullValueHandling.Ignore)]
+ public int? LetterSpacing { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the behavior and rendering of the code action lightbulb.
+ /// </summary>
+ [JsonProperty("lightbulb", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorLightbulbOptions? Lightbulb { get => GetPropertyValue<EditorLightbulbOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The width reserved for line decorations (in px).
+ /// Line decorations are placed between line numbers and the editor content.
+ /// You can pass in a string in the format floating point followed by "ch". e.g. 1.3ch.
+ /// Defaults to 10.
+ /// </summary>
+ [JsonProperty("lineDecorationsWidth", NullValueHandling = NullValueHandling.Ignore)]
+ public uint? LineDecorationsWidth { get => GetPropertyValue<uint?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The line height
+ /// </summary>
+ [JsonProperty("lineHeight", NullValueHandling = NullValueHandling.Ignore)]
+ public int? LineHeight { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the rendering of line numbers.
+ /// If it is a function, it will be invoked when rendering a line number and the return value
+ /// will be rendered.
+ /// Otherwise, if it is a truey, line numbers will be rendered normally (equivalent of using
+ /// an identity function).
+ /// Otherwise, line numbers will not be rendered.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("lineNumbers", NullValueHandling = NullValueHandling.Ignore)]
+ public LineNumbersType? LineNumbers { get => GetPropertyValue<LineNumbersType?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the width of line numbers, by reserving horizontal space for rendering at least
+ /// an amount of digits.
+ /// Defaults to 5.
+ /// </summary>
+ [JsonProperty("lineNumbersMinChars", NullValueHandling = NullValueHandling.Ignore)]
+ public int? LineNumbersMinChars { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable detecting links and making them clickable.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("links", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Links { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable highlighting of matching brackets.
+ /// Defaults to 'always'.
+ /// </summary>
+ [JsonProperty("matchBrackets", NullValueHandling = NullValueHandling.Ignore)]
+ public MatchBrackets? MatchBrackets { get => GetPropertyValue<MatchBrackets?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the behavior and rendering of the minimap.
+ /// </summary>
+ [JsonProperty("minimap", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorMinimapOptions? Minimap { get => GetPropertyValue<EditorMinimapOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the mouse pointer style, either 'text' or 'default' or 'copy'
+ /// Defaults to 'text'
+ /// </summary>
+ [JsonProperty("mouseStyle", NullValueHandling = NullValueHandling.Ignore)]
+ public MouseStyle? MouseStyle { get => GetPropertyValue<MouseStyle?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.
+ /// Defaults to 1.
+ /// </summary>
+ [JsonProperty("mouseWheelScrollSensitivity", NullValueHandling = NullValueHandling.Ignore)]
+ public int? MouseWheelScrollSensitivity { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Zoom the font in the editor when using the mouse wheel in combination with holding Ctrl.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("mouseWheelZoom", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? MouseWheelZoom { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Merge overlapping selections.
+ /// Defaults to true
+ /// </summary>
+ [JsonProperty("multiCursorMergeOverlapping", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? MultiCursorMergeOverlapping { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The modifier to be used to add multiple cursors with the mouse.
+ /// Defaults to 'alt'
+ /// </summary>
+ [JsonProperty("multiCursorModifier", NullValueHandling = NullValueHandling.Ignore)]
+ public MultiCursorModifier? MultiCursorModifier { get => GetPropertyValue<MultiCursorModifier?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Configure the behaviour when pasting a text with the line count equal to the cursor
+ /// count.
+ /// Defaults to 'spread'.
+ /// </summary>
+ [JsonProperty("multiCursorPaste", NullValueHandling = NullValueHandling.Ignore)]
+ public MultiCursorPaste? MultiCursorPaste { get => GetPropertyValue<MultiCursorPaste?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable semantic occurrences highlight.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("occurrencesHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? OccurrencesHighlight { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls if a border should be drawn around the overview ruler.
+ /// Defaults to `true`.
+ /// </summary>
+ [JsonProperty("overviewRulerBorder", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? OverviewRulerBorder { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The number of vertical lanes the overview ruler should render.
+ /// Defaults to 3.
+ /// </summary>
+ [JsonProperty("overviewRulerLanes", NullValueHandling = NullValueHandling.Ignore)]
+ public int? OverviewRulerLanes { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Parameter hint options.
+ /// </summary>
+ [JsonProperty("parameterHints", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorParameterHintOptions? ParameterHints { get => GetPropertyValue<EditorParameterHintOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls whether to focus the inline editor in the peek widget by default.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("peekWidgetDefaultFocus", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? PeekWidgetDefaultFocus { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable quick suggestions (shadow suggestions)
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("quickSuggestions", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? QuickSuggestions { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Quick suggestions show delay (in ms)
+ /// Defaults to 10 (ms)
+ /// </summary>
+ [JsonProperty("quickSuggestionsDelay", NullValueHandling = NullValueHandling.Ignore)]
+ public int? QuickSuggestionsDelay { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Should the editor be read only.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("readOnly", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ReadOnly { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable rendering of control characters.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("renderControlCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? RenderControlCharacters { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Render last line number when the file ends with a newline.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("renderFinalNewline", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? RenderFinalNewline { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable rendering of indent guides.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("renderIndentGuides", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? RenderIndentGuides { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable rendering of current line highlight.
+ /// Defaults to all.
+ /// </summary>
+ [JsonProperty("renderLineHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ public RenderLineHighlight? RenderLineHighlight { get => GetPropertyValue<RenderLineHighlight?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Should the editor render validation decorations.
+ /// Defaults to editable.
+ /// </summary>
+ [JsonProperty("renderValidationDecorations", NullValueHandling = NullValueHandling.Ignore)]
+ public string? RenderValidationDecorations { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable rendering of whitespace.
+ /// Defaults to none.
+ /// </summary>
+ [JsonProperty("renderWhitespace", NullValueHandling = NullValueHandling.Ignore)]
+ public RenderWhitespace? RenderWhitespace { get => GetPropertyValue<RenderWhitespace?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// When revealing the cursor, a virtual padding (px) is added to the cursor, turning it into
+ /// a rectangle.
+ /// This virtual padding ensures that the cursor gets revealed before hitting the edge of the
+ /// viewport.
+ /// Defaults to 30 (px).
+ /// </summary>
+ [JsonProperty("revealHorizontalRightPadding", NullValueHandling = NullValueHandling.Ignore)]
+ public int? RevealHorizontalRightPadding { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Render the editor selection with rounded borders.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("roundedSelection", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? RoundedSelection { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Render vertical lines at the specified columns.
+ /// Defaults to empty array.
+ /// </summary>
+ [JsonProperty("rulers", NullValueHandling = NullValueHandling.Ignore)]
+ public int[]? Rulers { get => GetPropertyValue<int[]>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the behavior and rendering of the scrollbars.
+ /// </summary>
+ [JsonProperty("scrollbar", NullValueHandling = NullValueHandling.Ignore)]
+ public EditorScrollbarOptions? Scrollbar { get => GetPropertyValue<EditorScrollbarOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable that scrolling can go beyond the last column by a number of columns.
+ /// Defaults to 5.
+ /// </summary>
+ [JsonProperty("scrollBeyondLastColumn", NullValueHandling = NullValueHandling.Ignore)]
+ public int? ScrollBeyondLastColumn { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable that scrolling can go one screen size after the last line.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("scrollBeyondLastLine", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ScrollBeyondLastLine { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable Linux primary clipboard.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("selectionClipboard", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SelectionClipboard { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable selection highlight.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("selectionHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SelectionHighlight { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Should the corresponding line be selected when clicking on the line number?
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("selectOnLineNumbers", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SelectOnLineNumbers { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls whether the fold actions in the gutter stay always visible or hide unless the
+ /// mouse is over the gutter.
+ /// Defaults to 'mouseover'.
+ /// </summary>
+ [JsonProperty("showFoldingControls", NullValueHandling = NullValueHandling.Ignore)]
+ public Show? ShowFoldingControls { get => GetPropertyValue<Show?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls fading out of unused variables.
+ /// </summary>
+ [JsonProperty("showUnused", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowUnused { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable that the editor animates scrolling to a position.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("smoothScrolling", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SmoothScrolling { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable snippet suggestions. Default to 'true'.
+ /// </summary>
+ [JsonProperty("snippetSuggestions", NullValueHandling = NullValueHandling.Ignore)]
+ public SnippetSuggestions? SnippetSuggestions { get => GetPropertyValue<SnippetSuggestions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Performance guard: Stop rendering a line after x characters.
+ /// Defaults to 10000.
+ /// Use -1 to never stop rendering
+ /// </summary>
+ [JsonProperty("stopRenderingLineAfter", NullValueHandling = NullValueHandling.Ignore)]
+ public int? StopRenderingLineAfter { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Suggest options.
+ /// </summary>
+ [JsonProperty("suggest", NullValueHandling = NullValueHandling.Ignore)]
+ public SuggestOptions? Suggest { get => GetPropertyValue<SuggestOptions?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The font size for the suggest widget.
+ /// Defaults to the editor font size.
+ /// </summary>
+ [JsonProperty("suggestFontSize", NullValueHandling = NullValueHandling.Ignore)]
+ public int? SuggestFontSize { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The line height for the suggest widget.
+ /// Defaults to the editor line height.
+ /// </summary>
+ [JsonProperty("suggestLineHeight", NullValueHandling = NullValueHandling.Ignore)]
+ public int? SuggestLineHeight { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable the suggestion box to pop-up on trigger characters.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("suggestOnTriggerCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SuggestOnTriggerCharacters { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The history mode for suggestions.
+ /// </summary>
+ [JsonProperty("suggestSelection", NullValueHandling = NullValueHandling.Ignore)]
+ public SuggestSelection? SuggestSelection { get => GetPropertyValue<SuggestSelection?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Enable tab completion.
+ /// </summary>
+ [JsonProperty("tabCompletion", NullValueHandling = NullValueHandling.Ignore)]
+ public TabCompletion? TabCompletion { get => GetPropertyValue<TabCompletion?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Inserting and deleting whitespace follows tab stops.
+ /// </summary>
+ [JsonProperty("useTabStops", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? UseTabStops { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// A string containing the word separators used when doing word navigation.
+ /// Defaults to `~!@#$%^&amp;*()-=+[{]}\|;:'",.&lt;&gt;/?
+ /// *
+ /// </summary>
+ [JsonProperty("wordSeparators", NullValueHandling = NullValueHandling.Ignore)]
+ public string? WordSeparators { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the wrapping of the editor.
+ /// When `wordWrap` = "off", the lines will never wrap.
+ /// When `wordWrap` = "on", the lines will wrap at the viewport width.
+ /// When `wordWrap` = "wordWrapColumn", the lines will wrap at `wordWrapColumn`.
+ /// When `wordWrap` = "bounded", the lines will wrap at min(viewport width, wordWrapColumn).
+ /// Defaults to "off".
+ /// </summary>
+ [JsonProperty("wordWrap", NullValueHandling = NullValueHandling.Ignore)]
+ public WordWrap? WordWrap { get => GetPropertyValue<WordWrap?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Configure word wrapping characters. A break will be introduced after these characters.
+ /// Defaults to ' \t})]?|&amp;,;'.
+ /// </summary>
+ [JsonProperty("wordWrapBreakAfterCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ public string? WordWrapBreakAfterCharacters { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Configure word wrapping characters. A break will be introduced before these characters.
+ /// Defaults to '{([+'.
+ /// </summary>
+ [JsonProperty("wordWrapBreakBeforeCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ public string? WordWrapBreakBeforeCharacters { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control the wrapping of the editor.
+ /// When `wordWrap` = "off", the lines will never wrap.
+ /// When `wordWrap` = "on", the lines will wrap at the viewport width.
+ /// When `wordWrap` = "wordWrapColumn", the lines will wrap at `wordWrapColumn`.
+ /// When `wordWrap` = "bounded", the lines will wrap at min(viewport width, wordWrapColumn).
+ /// Defaults to 80.
+ /// </summary>
+ [JsonProperty("wordWrapColumn", NullValueHandling = NullValueHandling.Ignore)]
+ public int? WordWrapColumn { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Force word wrapping when the text appears to be of a minified/generated file.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("wordWrapMinified", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? WordWrapMinified { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Control indentation of wrapped lines. Can be: 'none', 'same', 'indent' or 'deepIndent'.
+ /// Defaults to 'same' in vscode and to 'none' in monaco-editor.
+ /// </summary>
+ [JsonProperty("wrappingIndent", NullValueHandling = NullValueHandling.Ignore)]
+ public WrappingIndent? WrappingIndent { get => GetPropertyValue<WrappingIndent?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls the wrapping strategy to use.
+ /// Defaults to 'simple'.
+ /// </summary>
+ [JsonProperty("wrappingStrategy", NullValueHandling = NullValueHandling.Ignore)]
+ public string? WrappingStrategy { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The initial editor dimension (to avoid measuring the container).
+ /// </summary>
+ [JsonProperty("dimension", NullValueHandling = NullValueHandling.Ignore)]
+ public IDimension? Dimension { get => GetPropertyValue<IDimension?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls whether `tabSize` and `insertSpaces` will be automatically detected when a file
+ /// is opened based on the file contents.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("detectIndentation", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? DetectIndentation { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Insert spaces when pressing `Tab`.
+ /// This setting is overridden based on the file contents when detectIndentation` is
+ /// on.
+ /// * Defaults to true.
+ /// *
+ /// </summary>
+ [JsonProperty("insertSpaces", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? InsertSpaces { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Special handling for large files to disable certain memory intensive features.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("largeFileOptimizations", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? LargeFileOptimizations { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Lines above this length will not be tokenized for performance reasons.
+ /// Defaults to 20000.
+ /// </summary>
+ [JsonProperty("maxTokenizationLineLength", NullValueHandling = NullValueHandling.Ignore)]
+ public int? MaxTokenizationLineLength { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Keep peek editors open even when int clicking their content or when hitting `Escape`.
+ /// Defaults to false.
+ /// </summary>
+ [JsonProperty("stablePeek", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? StablePeek { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// The number of spaces a tab is equal to.
+ /// This setting is overridden based on the file contents when `detectIndentation` is on.
+ /// Defaults to 4.
+ /// </summary>
+ [JsonProperty("tabSize", NullValueHandling = NullValueHandling.Ignore)]
+ public int? TabSize { get => GetPropertyValue<int?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Remove trailing auto inserted whitespace.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("trimAutoWhitespace", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? TrimAutoWhitespace { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+
+ /// <summary>
+ /// Controls whether completions should be computed based on words in the document.
+ /// Defaults to true.
+ /// </summary>
+ [JsonProperty("wordBasedSuggestions", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? WordBasedSuggestions { get => GetPropertyValue<bool?>(); set => SetPropertyValue(value); }
+ /// <summary>
+ /// The initial model associated with this code editor.
+ /// </summary>
+ [JsonProperty("model")]
+ public IModel? Model { get => GetPropertyValue<IModel?>(); set => SetPropertyValue(value); }
+ /// <summary>
+ /// The initial value of the auto created model in the editor.
+ /// To not create automatically a model, use `model: null`.
+ /// </summary>
+ [JsonProperty("value", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Value { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+ /// <summary>
+ /// The initial language of the auto created model in the editor.
+ /// To not create automatically a model, use `model: null`.
+ /// </summary>
+ [JsonProperty("language", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Language { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+ /// <summary>
+ /// Initial theme to be used for rendering.
+ /// The current out-of-the-box available themes are: 'vs' (default), 'vs-dark', 'hc-black'.
+ /// You can create custom themes via `monaco.editor.defineTheme`.
+ /// To switch a theme, use `monaco.editor.setTheme`
+ /// </summary>
+ [JsonProperty("theme", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Theme { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+ /// <summary>
+ /// An URL to open when Ctrl+H (Windows and Linux) or Cmd+H (OSX) is pressed in
+ /// the accessibility help dialog in the editor.
+ ///
+ /// Defaults to "https://go.microsoft.com/fwlink/?linkid=852450"
+ /// </summary>
+ [JsonProperty("accessibilityHelpUrl", NullValueHandling = NullValueHandling.Ignore)]
+ public string? AccessibilityHelpUrl { get => GetPropertyValue<string?>(); set => SetPropertyValue(value); }
+ }
+
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SuggestOptions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SuggestOptions.cs
new file mode 100644
index 000000000..1f40ce7cc
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SuggestOptions.cs
@@ -0,0 +1,216 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Configuration options for editor suggest widget
+ /// </summary>
+ public sealed class SuggestOptions
+ {
+ /// <summary>
+ /// Enable graceful matching. Defaults to true.
+ /// </summary>
+ [JsonProperty("filterGraceful", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? FilterGraceful { get; set; }
+
+ /// <summary>
+ /// Controls the visibility of the status bar at the bottom of the suggest widget.
+ /// </summary>
+ [JsonProperty("hideStatusBar", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? HideStatusBar { get; set; }
+
+ /// <summary>
+ /// Show a highlight when suggestion replaces or keep text after the cursor. Defaults to false.
+ /// </summary>
+ [JsonProperty("insertHighlight", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? InsertHighlight { get; set; }
+
+ /// <summary>
+ /// Overwrite word ends on accept. Default to false.
+ /// </summary>
+ [JsonProperty("insertMode", NullValueHandling = NullValueHandling.Ignore)]
+ public InsertMode? InsertMode { get; set; }
+
+ /// <summary>
+ /// Favours words that appear close to the cursor.
+ /// </summary>
+ [JsonProperty("localityBonus", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? LocalityBonus { get; set; }
+
+ /// <summary>
+ /// Max suggestions to show in suggestions. Defaults to 12.
+ /// </summary>
+ [JsonProperty("maxVisibleSuggestions", NullValueHandling = NullValueHandling.Ignore)]
+ public int? MaxVisibleSuggestions { get; set; }
+
+ /// <summary>
+ /// Enable using global storage for remembering suggestions.
+ /// </summary>
+ [JsonProperty("shareSuggestSelections", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShareSuggestSelections { get; set; }
+
+ /// <summary>
+ /// Show class-suggestions.
+ /// </summary>
+ [JsonProperty("showClasses", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowClasses { get; set; }
+
+ /// <summary>
+ /// Show color-suggestions.
+ /// </summary>
+ [JsonProperty("showColors", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowColors { get; set; }
+
+ /// <summary>
+ /// Show constant-suggestions.
+ /// </summary>
+ [JsonProperty("showConstants", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowConstants { get; set; }
+
+ /// <summary>
+ /// Show constructor-suggestions.
+ /// </summary>
+ [JsonProperty("showConstructors", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowConstructors { get; set; }
+
+ /// <summary>
+ /// Show enumMember-suggestions.
+ /// </summary>
+ [JsonProperty("showEnumMembers", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowEnumMembers { get; set; }
+
+ /// <summary>
+ /// Show enum-suggestions.
+ /// </summary>
+ [JsonProperty("showEnums", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowEnums { get; set; }
+
+ /// <summary>
+ /// Show event-suggestions.
+ /// </summary>
+ [JsonProperty("showEvents", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowEvents { get; set; }
+
+ /// <summary>
+ /// Show field-suggestions.
+ /// </summary>
+ [JsonProperty("showFields", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowFields { get; set; }
+
+ /// <summary>
+ /// Show file-suggestions.
+ /// </summary>
+ [JsonProperty("showFiles", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowFiles { get; set; }
+
+ /// <summary>
+ /// Show folder-suggestions.
+ /// </summary>
+ [JsonProperty("showFolders", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowFolders { get; set; }
+
+ /// <summary>
+ /// Show function-suggestions.
+ /// </summary>
+ [JsonProperty("showFunctions", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowFunctions { get; set; }
+
+ /// <summary>
+ /// Enable or disable icons in suggestions. Defaults to true.
+ /// </summary>
+ [JsonProperty("showIcons", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowIcons { get; set; }
+
+ /// <summary>
+ /// Show interface-suggestions.
+ /// </summary>
+ [JsonProperty("showInterfaces", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowInterfaces { get; set; }
+
+ /// <summary>
+ /// Show keyword-suggestions.
+ /// </summary>
+ [JsonProperty("showKeywords", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowKeywords { get; set; }
+
+ /// <summary>
+ /// Show method-suggestions.
+ /// </summary>
+ [JsonProperty("showMethods", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowMethods { get; set; }
+
+ /// <summary>
+ /// Show module-suggestions.
+ /// </summary>
+ [JsonProperty("showModules", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowModules { get; set; }
+
+ /// <summary>
+ /// Show operator-suggestions.
+ /// </summary>
+ [JsonProperty("showOperators", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowOperators { get; set; }
+
+ /// <summary>
+ /// Show property-suggestions.
+ /// </summary>
+ [JsonProperty("showProperties", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowProperties { get; set; }
+
+ /// <summary>
+ /// Show reference-suggestions.
+ /// </summary>
+ [JsonProperty("showReferences", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowReferences { get; set; }
+
+ /// <summary>
+ /// Show snippet-suggestions.
+ /// </summary>
+ [JsonProperty("showSnippets", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowSnippets { get; set; }
+
+ /// <summary>
+ /// Show struct-suggestions.
+ /// </summary>
+ [JsonProperty("showStructs", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowStructs { get; set; }
+
+ /// <summary>
+ /// Show typeParameter-suggestions.
+ /// </summary>
+ [JsonProperty("showTypeParameters", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowTypeParameters { get; set; }
+
+ /// <summary>
+ /// Show unit-suggestions.
+ /// </summary>
+ [JsonProperty("showUnits", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowUnits { get; set; }
+
+ /// <summary>
+ /// Show value-suggestions.
+ /// </summary>
+ [JsonProperty("showValues", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowValues { get; set; }
+
+ /// <summary>
+ /// Show variable-suggestions.
+ /// </summary>
+ [JsonProperty("showVariables", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowVariables { get; set; }
+
+ /// <summary>
+ /// Show text-suggestions.
+ /// </summary>
+ [JsonProperty("showWords", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? ShowWords { get; set; }
+
+ /// <summary>
+ /// Prevent quick suggestions when a snippet is active. Defaults to true.
+ /// </summary>
+ [JsonProperty("snippetsPreventQuickSuggestions", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SnippetsPreventQuickSuggestions { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SuggestSelection.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SuggestSelection.cs
new file mode 100644
index 000000000..6338cfe04
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SuggestSelection.cs
@@ -0,0 +1,17 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// The history mode for suggestions.
+ /// </summary>
+ [JsonConverter(typeof(SuggestSelectionConverter))]
+ public enum SuggestSelection
+ {
+ First,
+ RecentlyUsed,
+ RecentlyUsedByPrefix
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SuggestSelectionConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SuggestSelectionConverter.cs
new file mode 100644
index 000000000..ed8d58dc7
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/SuggestSelectionConverter.cs
@@ -0,0 +1,58 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class SuggestSelectionConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(SuggestSelection) || t == typeof(SuggestSelection?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "first":
+ return SuggestSelection.First;
+ case "recentlyUsed":
+ return SuggestSelection.RecentlyUsed;
+ case "recentlyUsedByPrefix":
+ return SuggestSelection.RecentlyUsedByPrefix;
+ }
+ throw new Exception("Cannot unmarshal type SuggestSelection");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (SuggestSelection)untypedValue;
+ switch (value)
+ {
+ case SuggestSelection.First:
+ serializer.Serialize(writer, "first");
+ return;
+ case SuggestSelection.RecentlyUsed:
+ serializer.Serialize(writer, "recentlyUsed");
+ return;
+ case SuggestSelection.RecentlyUsedByPrefix:
+ serializer.Serialize(writer, "recentlyUsedByPrefix");
+ return;
+ }
+ throw new Exception("Cannot marshal type SuggestSelection");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/TabCompletion.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/TabCompletion.cs
new file mode 100644
index 000000000..81f806166
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/TabCompletion.cs
@@ -0,0 +1,18 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Enable tab completion.
+ /// </summary>
+ [JsonConverter(typeof(TabCompletionConverter))]
+ public enum TabCompletion
+ {
+ Off,
+ On,
+ OnlySnippets
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/TabCompletionConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/TabCompletionConverter.cs
new file mode 100644
index 000000000..3e6d16395
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/TabCompletionConverter.cs
@@ -0,0 +1,58 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class TabCompletionConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(TabCompletion) || t == typeof(TabCompletion?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "off":
+ return TabCompletion.Off;
+ case "on":
+ return TabCompletion.On;
+ case "onlySnippets":
+ return TabCompletion.OnlySnippets;
+ }
+ throw new Exception("Cannot unmarshal type TabCompletion");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (TabCompletion)untypedValue;
+ switch (value)
+ {
+ case TabCompletion.Off:
+ serializer.Serialize(writer, "off");
+ return;
+ case TabCompletion.On:
+ serializer.Serialize(writer, "on");
+ return;
+ case TabCompletion.OnlySnippets:
+ serializer.Serialize(writer, "onlySnippets");
+ return;
+ }
+ throw new Exception("Cannot marshal type TabCompletion");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/TrackedRangeStickiness.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/TrackedRangeStickiness.cs
new file mode 100644
index 000000000..b26d0435f
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/TrackedRangeStickiness.cs
@@ -0,0 +1,16 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// Describes the behavior of decorations when typing/editing near their edges.
+ /// Note: Please do not edit the values, as they very carefully match `DecorationRangeBehavior`
+ /// </summary>
+ public enum TrackedRangeStickiness
+ {
+ AlwaysGrowsWhenTypingAtEdges = 0,
+ GrowsOnlyWhenTypingAfter = 3,
+ GrowsOnlyWhenTypingBefore = 2,
+ NeverGrowsWhenTypingAtEdges = 1
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WordAtPosition.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WordAtPosition.cs
new file mode 100644
index 000000000..dd33201bc
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WordAtPosition.cs
@@ -0,0 +1,30 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ /// <summary>
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.iwordatposition.html
+ /// </summary>
+ public sealed class WordAtPosition : IWordAtPosition
+ {
+ /// <summary>
+ /// Column where the word ends.
+ /// </summary>
+ [JsonProperty("endColumn")]
+ public uint EndColumn { get; private set; }
+
+ /// <summary>
+ /// Column where the word starts.
+ /// </summary>
+ [JsonProperty("startColumn")]
+ public uint StartColumn { get; private set; }
+
+ /// <summary>
+ /// The word.
+ /// </summary>
+ [JsonProperty("word")]
+ public string? Word { get; private set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WordWrap.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WordWrap.cs
new file mode 100644
index 000000000..02da0f2b9
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WordWrap.cs
@@ -0,0 +1,24 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Control the wrapping of the editor.
+ /// When `wordWrap` = "off", the lines will never wrap.
+ /// When `wordWrap` = "on", the lines will wrap at the viewport width.
+ /// When `wordWrap` = "wordWrapColumn", the lines will wrap at `wordWrapColumn`.
+ /// When `wordWrap` = "bounded", the lines will wrap at min(viewport width, wordWrapColumn).
+ /// Defaults to "off".
+ /// </summary>
+ [JsonConverter(typeof(WordWrapConverter))]
+ public enum WordWrap
+ {
+ Bounded,
+ Off,
+ On,
+ WordWrapColumn
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WordWrapConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WordWrapConverter.cs
new file mode 100644
index 000000000..3b5698630
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WordWrapConverter.cs
@@ -0,0 +1,63 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class WordWrapConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(WordWrap) || t == typeof(WordWrap?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "bounded":
+ return WordWrap.Bounded;
+ case "off":
+ return WordWrap.Off;
+ case "on":
+ return WordWrap.On;
+ case "wordWrapColumn":
+ return WordWrap.WordWrapColumn;
+ }
+ throw new Exception("Cannot unmarshal type WordWrap");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (WordWrap)untypedValue;
+ switch (value)
+ {
+ case WordWrap.Bounded:
+ serializer.Serialize(writer, "bounded");
+ return;
+ case WordWrap.Off:
+ serializer.Serialize(writer, "off");
+ return;
+ case WordWrap.On:
+ serializer.Serialize(writer, "on");
+ return;
+ case WordWrap.WordWrapColumn:
+ serializer.Serialize(writer, "wordWrapColumn");
+ return;
+ }
+ throw new Exception("Cannot marshal type WordWrap");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WrappingIndent.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WrappingIndent.cs
new file mode 100644
index 000000000..854456078
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WrappingIndent.cs
@@ -0,0 +1,20 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+
+ /// <summary>
+ /// Control indentation of wrapped lines. Can be: 'none', 'same', 'indent' or 'deepIndent'.
+ /// Defaults to 'same' in vscode and to 'none' in monaco-editor.
+ /// </summary>
+ [JsonConverter(typeof(WrappingIndentConverter))]
+ public enum WrappingIndent
+ {
+ DeepIndent,
+ Indent,
+ None,
+ Same
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WrappingIndentConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WrappingIndentConverter.cs
new file mode 100644
index 000000000..f3ed6ca83
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Editor/WrappingIndentConverter.cs
@@ -0,0 +1,63 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Editor
+{
+ internal class WrappingIndentConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t)
+ {
+ return t == typeof(WrappingIndent) || t == typeof(WrappingIndent?);
+ }
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "deepIndent":
+ return WrappingIndent.DeepIndent;
+ case "indent":
+ return WrappingIndent.Indent;
+ case "none":
+ return WrappingIndent.None;
+ case "same":
+ return WrappingIndent.Same;
+ }
+ throw new Exception("Cannot unmarshal type WrappingIndent");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (WrappingIndent)untypedValue;
+ switch (value)
+ {
+ case WrappingIndent.DeepIndent:
+ serializer.Serialize(writer, "deepIndent");
+ return;
+ case WrappingIndent.Indent:
+ serializer.Serialize(writer, "indent");
+ return;
+ case WrappingIndent.None:
+ serializer.Serialize(writer, "none");
+ return;
+ case WrappingIndent.Same:
+ serializer.Serialize(writer, "same");
+ return;
+ }
+ throw new Exception("Cannot marshal type WrappingIndent");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssGlyphStyle.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssGlyphStyle.cs
new file mode 100644
index 000000000..f7914da19
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssGlyphStyle.cs
@@ -0,0 +1,23 @@
+#nullable enable
+
+using DevToys.MonacoEditor.CodeEditorControl;
+
+namespace DevToys.MonacoEditor.Monaco.Helpers
+{
+ public sealed class CssGlyphStyle : ICssStyle
+ {
+ public System.Uri? GlyphImage { get; set; }
+
+ public string? Name { get; private set; }
+
+ public CssGlyphStyle(CodeEditorCore editor)
+ {
+ Name = CssStyleBroker.GetInstance(editor).Register(this);
+ }
+
+ public string ToCss()
+ {
+ return CssStyleBroker.WrapCssClassName(this, string.Format("background: url(\"{0}\");", GlyphImage?.AbsoluteUri));
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssInlineStyle.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssInlineStyle.cs
new file mode 100644
index 000000000..ccacee83c
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssInlineStyle.cs
@@ -0,0 +1,73 @@
+#nullable enable
+
+using DevToys.MonacoEditor.CodeEditorControl;
+using System.Text;
+using Windows.UI.Text;
+using Windows.UI.Xaml.Media;
+
+namespace DevToys.MonacoEditor.Monaco.Helpers
+{
+ /// <summary>
+ /// Inline styles modify the text style itself and are useful for manipulating the colors and styles of text to indicate conditions.
+ /// </summary>
+ public sealed class CssInlineStyle : ICssStyle
+ {
+ public TextDecoration TextDecoration { get; set; }
+ public FontWeight? FontWeight { get; set; }
+ public FontStyle FontStyle { get; set; }
+
+ // TODO: Provide Cursor: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
+
+ // Setting a background inline will override any CssLineStyle.
+ public SolidColorBrush? BackgroundColor { get; set; }
+ public SolidColorBrush? ForegroundColor { get; set; }
+
+ public string? Name { get; private set; }
+
+ public CssInlineStyle(CodeEditorCore editor)
+ {
+ Name = CssStyleBroker.GetInstance(editor).Register(this);
+ }
+
+ public string ToCss()
+ {
+ StringBuilder output = new StringBuilder(40);
+ if (TextDecoration != TextDecoration.None)
+ {
+ string text = TextDecoration.ToString().ToLower();
+ if (TextDecoration == TextDecoration.LineThrough)
+ {
+ text = "line-through";
+ }
+
+ output.AppendLine(string.Format("text-decoration: {0};", text));
+ }
+
+ if (FontWeight != null && FontWeight.HasValue)
+ {
+ output.AppendLine(string.Format("font-weight: {0};", FontWeight.Value.Weight));
+ }
+
+ if (FontStyle != FontStyle.Normal)
+ {
+ output.AppendLine(string.Format("font-style: {0};", FontStyle.ToString().ToLower()));
+ }
+
+ if (BackgroundColor != null)
+ {
+ output.AppendLine(string.Format("background: #{0:X2}{1:X2}{2:X2};", BackgroundColor.Color.R,
+ BackgroundColor.Color.G,
+ BackgroundColor.Color.B));
+ }
+
+ if (ForegroundColor != null)
+ {
+ output.AppendLine(string.Format("color: #{0:X2}{1:X2}{2:X2} !important;", ForegroundColor.Color.R,
+ ForegroundColor.Color.G,
+ ForegroundColor.Color.B));
+ }
+
+ return CssStyleBroker.WrapCssClassName(this, output.ToString());
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssLineStyle.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssLineStyle.cs
new file mode 100644
index 000000000..e6aabacf2
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssLineStyle.cs
@@ -0,0 +1,49 @@
+#nullable enable
+
+using DevToys.MonacoEditor.CodeEditorControl;
+using System;
+using System.Text;
+using Windows.UI.Xaml.Media;
+
+namespace DevToys.MonacoEditor.Monaco.Helpers
+{
+ /// <summary>
+ /// Simple Proxy to general CSS Line Styles.
+ /// Line styles are overlayed behind text in the editor and are useful for highlighting sections of text efficiently
+ /// </summary>
+ public sealed class CssLineStyle : ICssStyle
+ {
+ public SolidColorBrush? BackgroundColor { get; set; }
+
+ [Obsolete("Use ForegroundColor on CssInlineStyle instead, this is an overlay.")]
+ public SolidColorBrush? ForegroundColor { get; set; }
+
+ public string? Name { get; private set; }
+
+ public CssLineStyle(CodeEditorCore editor)
+ {
+ Name = CssStyleBroker.GetInstance(editor).Register(this);
+ }
+
+ public string ToCss()
+ {
+ StringBuilder output = new StringBuilder(40);
+ if (BackgroundColor != null)
+ {
+ output.AppendLine(string.Format("background: #{0:X2}{1:X2}{2:X2};", BackgroundColor.Color.R,
+ BackgroundColor.Color.G,
+ BackgroundColor.Color.B));
+ }
+#pragma warning disable CS0618 // Type or member is obsolete
+ if (ForegroundColor != null)
+ {
+ output.AppendLine(string.Format("color: #{0:X2}{1:X2}{2:X2} !important;", ForegroundColor.Color.R,
+ ForegroundColor.Color.G,
+ ForegroundColor.Color.B));
+ }
+#pragma warning restore CS0618 // Type or member is obsolete
+
+ return CssStyleBroker.WrapCssClassName(this, output.ToString());
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssStyleBroker.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssStyleBroker.cs
new file mode 100644
index 000000000..de7ca60c5
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssStyleBroker.cs
@@ -0,0 +1,80 @@
+#nullable enable
+
+using DevToys.MonacoEditor.CodeEditorControl;
+using System.Collections.Generic;
+using System.Text;
+
+namespace DevToys.MonacoEditor.Monaco.Helpers
+{
+ /// <summary>
+ /// Singleton Broker to help us manage CSS Styles
+ /// </summary>
+ public sealed class CssStyleBroker
+ {
+ private static uint Id = 0;
+ private readonly Dictionary<string, ICssStyle> _registered = new Dictionary<string, ICssStyle>();
+ private static readonly IDictionary<CodeEditorCore, CssStyleBroker> instances = new Dictionary<CodeEditorCore, CssStyleBroker>();
+
+ // Explicit static constructor to tell C# compiler
+ // not to mark type as beforefieldinit
+ static CssStyleBroker()
+ {
+ }
+
+ private CssStyleBroker()
+ {
+ }
+
+ public static CssStyleBroker GetInstance(CodeEditorCore editor)
+ {
+ if (instances.ContainsKey(editor))
+ {
+ return instances[editor];
+ }
+
+ return instances[editor] = new CssStyleBroker();
+ }
+
+ public static bool DetachEditor(CodeEditorCore editor)
+ {
+ if (instances.ContainsKey(editor))
+ {
+ return instances.Remove(editor);
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Returns the name for a style to use after registered.
+ /// </summary>
+ /// <param name="style"></param>
+ /// <returns></returns>
+ public string Register(ICssStyle style)
+ {
+ Id += 1;
+ var name = "generated-style-" + Id;
+ _registered.Add(name, style);
+ return name;
+ }
+
+ /// <summary>
+ /// Returns the CSS block for all registered styles.
+ /// </summary>
+ /// <returns></returns>
+ public string GetStyles()
+ {
+ StringBuilder rules = new StringBuilder(100);
+ foreach (ICssStyle css in _registered.Values)
+ {
+ rules.AppendLine(css.ToCss());
+ }
+ return rules.ToString();
+ }
+
+ public static string WrapCssClassName(ICssStyle style, string inner)
+ {
+ return string.Format(".{0} {{ {1} }}", style.Name, inner);
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssStyleConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssStyleConverter.cs
new file mode 100644
index 000000000..c389348ba
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/CssStyleConverter.cs
@@ -0,0 +1,24 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+using System.Linq;
+
+namespace DevToys.MonacoEditor.Monaco.Helpers
+{
+ internal class CssStyleConverter : JsonConverter
+ {
+ public override bool CanConvert(Type objectType) =>
+ objectType == typeof(ICssStyle) || objectType.GetInterfaces().Contains(typeof(ICssStyle));
+
+ public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) => new NotSupportedException();
+
+ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
+ {
+ if (value is ICssStyle style)
+ {
+ writer.WriteValue(style.Name);
+ }
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/ICssStyle.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/ICssStyle.cs
new file mode 100644
index 000000000..ba18a776c
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/ICssStyle.cs
@@ -0,0 +1,14 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Helpers
+{
+ [JsonConverter(typeof(CssStyleConverter))]
+ public interface ICssStyle
+ {
+ string? Name { get; }
+
+ string ToCss();
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/Json.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/Json.cs
new file mode 100644
index 000000000..5a63f15ee
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/Json.cs
@@ -0,0 +1,14 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Helpers
+{
+ static class Json
+ {
+ public static string ToJson<T>(this T obj)
+ {
+ return JsonConvert.SerializeObject(obj);
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/TextDecoration.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/TextDecoration.cs
new file mode 100644
index 000000000..1f7a3b440
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/TextDecoration.cs
@@ -0,0 +1,17 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Helpers
+{
+ [JsonConverter(typeof(TextDecorationConverter))]
+ public enum TextDecoration
+ {
+ None,
+ Underline,
+ Overline,
+ LineThrough,
+ Initial,
+ Inherit
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/TextDecorationConverter.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/TextDecorationConverter.cs
new file mode 100644
index 000000000..18aa9ed92
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Helpers/TextDecorationConverter.cs
@@ -0,0 +1,70 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco.Helpers
+{
+ internal class TextDecorationConverter : JsonConverter
+ {
+ public override bool CanConvert(Type t) => t == typeof(TextDecoration) || t == typeof(TextDecoration?);
+
+ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)
+ {
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
+
+ var value = serializer.Deserialize<string>(reader);
+ switch (value)
+ {
+ case "none":
+ return TextDecoration.None;
+ case "underline":
+ return TextDecoration.Underline;
+ case "overline":
+ return TextDecoration.Overline;
+ case "line-through":
+ return TextDecoration.LineThrough;
+ case "initial":
+ return TextDecoration.Initial;
+ case "inherit":
+ return TextDecoration.Inherit;
+ }
+ throw new Exception("Cannot unmarshal type TextDecoration");
+ }
+
+ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)
+ {
+ if (untypedValue == null)
+ {
+ serializer.Serialize(writer, null);
+ return;
+ }
+ var value = (TextDecoration)untypedValue;
+ switch (value)
+ {
+ case TextDecoration.None:
+ serializer.Serialize(writer, "none");
+ return;
+ case TextDecoration.Underline:
+ serializer.Serialize(writer, "underline");
+ return;
+ case TextDecoration.Overline:
+ serializer.Serialize(writer, "overline");
+ return;
+ case TextDecoration.LineThrough:
+ serializer.Serialize(writer, "line-through");
+ return;
+ case TextDecoration.Initial:
+ serializer.Serialize(writer, "initial");
+ return;
+ case TextDecoration.Inherit:
+ serializer.Serialize(writer, "inherit");
+ return;
+ }
+ throw new Exception("Cannot marshal type TextDecoration");
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/IPosition.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/IPosition.cs
new file mode 100644
index 000000000..e79b4ecc0
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/IPosition.cs
@@ -0,0 +1,24 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ /// <summary>
+ /// A position in the editor. This interface is suitable for serialization.
+ /// </summary>
+ public interface IPosition
+ {
+ /// <summary>
+ /// column (the first character in a line is between column 1 and column 2)
+ /// </summary>
+ [JsonProperty("column")]
+ uint Column { get; }
+
+ /// <summary>
+ /// line number (starts at 1)
+ /// </summary>
+ [JsonProperty("lineNumber")]
+ uint LineNumber { get; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/IRange.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/IRange.cs
new file mode 100644
index 000000000..6cfee1529
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/IRange.cs
@@ -0,0 +1,36 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ /// <summary>
+ /// A range in the editor. This interface is suitable for serialization.
+ /// </summary>
+ public interface IRange
+ {
+ /// <summary>
+ /// Line number on which the range starts (starts at 1).
+ /// </summary>
+ [JsonProperty("startLineNumber")]
+ uint StartLineNumber { get; }
+
+ /// <summary>
+ /// Column on which the range starts in line `startLineNumber` (starts at 1).
+ /// </summary>
+ [JsonProperty("startColumn")]
+ uint StartColumn { get; }
+
+ /// <summary>
+ /// Line number on which the range ends.
+ /// </summary>
+ [JsonProperty("endLineNumber")]
+ uint EndLineNumber { get; }
+
+ /// <summary>
+ /// Column on which the range ends in line `endLineNumber`.
+ /// </summary>
+ [JsonProperty("endColumn")]
+ uint EndColumn { get; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/IUriComponents.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/IUriComponents.cs
new file mode 100644
index 000000000..7b5691aa4
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/IUriComponents.cs
@@ -0,0 +1,24 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ public interface IUriComponents
+ {
+ [JsonProperty("authority", NullValueHandling = NullValueHandling.Ignore)]
+ string? Authority { get; set; }
+
+ [JsonProperty("fragment", NullValueHandling = NullValueHandling.Ignore)]
+ string? Fragment { get; set; }
+
+ [JsonProperty("path", NullValueHandling = NullValueHandling.Ignore)]
+ string? Path { get; set; }
+
+ [JsonProperty("query", NullValueHandling = NullValueHandling.Ignore)]
+ string? Query { get; set; }
+
+ [JsonProperty("scheme", NullValueHandling = NullValueHandling.Ignore)]
+ string? Scheme { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/KeyCode.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/KeyCode.cs
new file mode 100644
index 000000000..814f49b6b
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/KeyCode.cs
@@ -0,0 +1,186 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ /// <summary>
+ /// Virtual Key Codes, the value does not hold any inherent meaning.
+ /// Inspired somewhat from https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
+ /// But these are "more general", as they should work across browsers &amp; OS`s.
+ /// </summary>
+ internal static class KeyCode
+ {
+ /**
+ * Placed first to cover the 0 value of the enum.
+ */
+ internal const int Unknown = 0;
+ internal const int Backspace = 1;
+ internal const int Tab = 2;
+ internal const int Enter = 3;
+ internal const int Shift = 4;
+ internal const int Ctrl = 5;
+ internal const int Alt = 6;
+ internal const int PauseBreak = 7;
+ internal const int CapsLock = 8;
+ internal const int Escape = 9;
+ internal const int Space = 10;
+ internal const int PageUp = 11;
+ internal const int PageDown = 12;
+ internal const int End = 13;
+ internal const int Home = 14;
+ internal const int LeftArrow = 15;
+ internal const int UpArrow = 16;
+ internal const int RightArrow = 17;
+ internal const int DownArrow = 18;
+ internal const int Insert = 19;
+ internal const int Delete = 20;
+ internal const int KEY_0 = 21;
+ internal const int KEY_1 = 22;
+ internal const int KEY_2 = 23;
+ internal const int KEY_3 = 24;
+ internal const int KEY_4 = 25;
+ internal const int KEY_5 = 26;
+ internal const int KEY_6 = 27;
+ internal const int KEY_7 = 28;
+ internal const int KEY_8 = 29;
+ internal const int KEY_9 = 30;
+ internal const int KEY_A = 31;
+ internal const int KEY_B = 32;
+ internal const int KEY_C = 33;
+ internal const int KEY_D = 34;
+ internal const int KEY_E = 35;
+ internal const int KEY_F = 36;
+ internal const int KEY_G = 37;
+ internal const int KEY_H = 38;
+ internal const int KEY_I = 39;
+ internal const int KEY_J = 40;
+ internal const int KEY_K = 41;
+ internal const int KEY_L = 42;
+ internal const int KEY_M = 43;
+ internal const int KEY_N = 44;
+ internal const int KEY_O = 45;
+ internal const int KEY_P = 46;
+ internal const int KEY_Q = 47;
+ internal const int KEY_R = 48;
+ internal const int KEY_S = 49;
+ internal const int KEY_T = 50;
+ internal const int KEY_U = 51;
+ internal const int KEY_V = 52;
+ internal const int KEY_W = 53;
+ internal const int KEY_X = 54;
+ internal const int KEY_Y = 55;
+ internal const int KEY_Z = 56;
+ internal const int Meta = 57;
+ internal const int ContextMenu = 58;
+ internal const int F1 = 59;
+ internal const int F2 = 60;
+ internal const int F3 = 61;
+ internal const int F4 = 62;
+ internal const int F5 = 63;
+ internal const int F6 = 64;
+ internal const int F7 = 65;
+ internal const int F8 = 66;
+ internal const int F9 = 67;
+ internal const int F10 = 68;
+ internal const int F11 = 69;
+ internal const int F12 = 70;
+ internal const int F13 = 71;
+ internal const int F14 = 72;
+ internal const int F15 = 73;
+ internal const int F16 = 74;
+ internal const int F17 = 75;
+ internal const int F18 = 76;
+ internal const int F19 = 77;
+ internal const int NumLock = 78;
+ internal const int ScrollLock = 79;
+ /**
+ * Used for miscellaneous characters; it can vary by keyboard.
+ * For the US standard keyboard, the ';:' key
+ */
+ internal const int US_SEMICOLON = 80;
+ /**
+ * For any country/region, the '+' key
+ * For the US standard keyboard, the '=+' key
+ */
+ internal const int US_EQUAL = 81;
+ /**
+ * For any country/region, the ',' key
+ * For the US standard keyboard, the ',&lt;' key
+ */
+ internal const int US_COMMA = 82;
+ /**
+ * For any country/region, the '-' key
+ * For the US standard keyboard, the '-_' key
+ */
+ internal const int US_MINUS = 83;
+ /**
+ * For any country/region, the '.' key
+ * For the US standard keyboard, the '.>' key
+ */
+ internal const int US_DOT = 84;
+ /**
+ * Used for miscellaneous characters; it can vary by keyboard.
+ * For the US standard keyboard, the '/?' key
+ */
+ internal const int US_SLASH = 85;
+ /**
+ * Used for miscellaneous characters; it can vary by keyboard.
+ * For the US standard keyboard, the '`~' key
+ */
+ internal const int US_BACKTICK = 86;
+ /**
+ * Used for miscellaneous characters; it can vary by keyboard.
+ * For the US standard keyboard, the '[{' key
+ */
+ internal const int US_OPEN_SQUARE_BRACKET = 87;
+ /**
+ * Used for miscellaneous characters; it can vary by keyboard.
+ * For the US standard keyboard, the '\|' key
+ */
+ internal const int US_BACKSLASH = 88;
+ /**
+ * Used for miscellaneous characters; it can vary by keyboard.
+ * For the US standard keyboard, the ']}' key
+ */
+ internal const int US_CLOSE_SQUARE_BRACKET = 89;
+ /**
+ * Used for miscellaneous characters; it can vary by keyboard.
+ * For the US standard keyboard, the ''"' key
+ */
+ internal const int US_QUOTE = 90;
+ /**
+ * Used for miscellaneous characters; it can vary by keyboard.
+ */
+ internal const int OEM_8 = 91;
+ /**
+ * Either the angle bracket key or the backslash key on the RT 102-key keyboard.
+ */
+ internal const int OEM_102 = 92;
+ internal const int NUMPAD_0 = 93;
+ internal const int NUMPAD_1 = 94;
+ internal const int NUMPAD_2 = 95;
+ internal const int NUMPAD_3 = 96;
+ internal const int NUMPAD_4 = 97;
+ internal const int NUMPAD_5 = 98;
+ internal const int NUMPAD_6 = 99;
+ internal const int NUMPAD_7 = 100;
+ internal const int NUMPAD_8 = 101;
+ internal const int NUMPAD_9 = 102;
+ internal const int NUMPAD_MULTIPLY = 103;
+ internal const int NUMPAD_ADD = 104;
+ internal const int NUMPAD_SEPARATOR = 105;
+ internal const int NUMPAD_SUBTRACT = 106;
+ internal const int NUMPAD_DECIMAL = 107;
+ internal const int NUMPAD_DIVIDE = 108;
+ /**
+ * Cover all key codes when IME is processing input.
+ */
+ internal const int KEY_IN_COMPOSITION = 109;
+ internal const int ABNT_C1 = 110;
+ internal const int ABNT_C2 = 111;
+ /**
+ * Placed last to cover the length of the enum.
+ * Please do not depend on this value!
+ */
+ internal const int MAX_VALUE = 112;
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/KeyMod.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/KeyMod.cs
new file mode 100644
index 000000000..b7786c1a3
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/KeyMod.cs
@@ -0,0 +1,40 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ /// <summary>
+ /// https://microsoft.github.io/monaco-editor/api/classes/monaco.keymod.html
+ /// </summary>
+ public sealed class KeyMod
+ {
+ internal const int WinCtrl = 256;
+
+ internal const int Alt = 512;
+
+ internal const int Shift = 1024;
+
+ internal const int CtrlCmd = 2048;
+
+ public static int Chord(int firstPart, int secondPart)
+ {
+ // https://github.com/Microsoft/vscode/blob/master/src/vs/base/common/keyCodes.ts#L410
+ var chordPart = ZeroFillRightShift((secondPart & 0x0000ffff) << 16, 0);
+ return ZeroFillRightShift(firstPart | chordPart, 0);
+ }
+
+ // Info on Zero-Fill Right Shift http://www.vanguardsw.com/dphelp4/dph00369.htm
+ // Supported natively by JavaScript, but not C#
+ private static int ZeroFillRightShift(int i, int j)
+ {
+ bool negativemask = i < 0;
+ i >>= j;
+
+ if (negativemask)
+ {
+ i &= 0x7FFFFFFF;
+ }
+
+ return i;
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/Command.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/Command.cs
new file mode 100644
index 000000000..434a8dd7d
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/Command.cs
@@ -0,0 +1,24 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Languages
+{
+ /// <summary>
+ /// A command that should be run upon acceptance of this item.
+ /// </summary>
+ public sealed class Command
+ {
+ [JsonProperty("arguments", NullValueHandling = NullValueHandling.Ignore)]
+ public object[]? Arguments { get; set; }
+
+ [JsonProperty("id")]
+ public string? Id { get; set; }
+
+ [JsonProperty("title")]
+ public string? Title { get; set; }
+
+ [JsonProperty("tooltip", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Tooltip { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionContext.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionContext.cs
new file mode 100644
index 000000000..8767d2333
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionContext.cs
@@ -0,0 +1,27 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Languages
+{
+ /// <summary>
+ /// Contains additional information about the context in which
+ /// [completion provider](#CompletionItemProvider.provideCompletionItems) is triggered.
+ /// </summary>
+ public sealed class CompletionContext
+ {
+ /// <summary>
+ /// Character that triggered the completion item provider.
+ ///
+ /// `undefined` if provider was not triggered by a character.
+ /// </summary>
+ [JsonProperty("triggerCharacter", NullValueHandling = NullValueHandling.Ignore)]
+ public string? TriggerCharacter { get; set; }
+
+ /// <summary>
+ /// How the completion was triggered.
+ /// </summary>
+ [JsonProperty("triggerKind")]
+ public CompletionTriggerKind TriggerKind { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionItem.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionItem.cs
new file mode 100644
index 000000000..6fb945523
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionItem.cs
@@ -0,0 +1,133 @@
+#nullable enable
+
+using DevToys.MonacoEditor.Monaco.Editor;
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Languages
+{
+ /// <summary>
+ /// A completion item represents a text snippet that is
+ /// proposed to complete text that is being typed.
+ /// </summary>
+ public sealed class CompletionItem
+ {
+ /// <summary>
+ /// An optional array of additional text edits that are applied when
+ /// selecting this completion. Edits must not overlap with the main edit
+ /// nor with themselves.
+ /// </summary>
+ [JsonProperty("additionalTextEdits", NullValueHandling = NullValueHandling.Ignore)]
+ public SingleEditOperation[]? AdditionalTextEdits { get; set; }
+
+ /// <summary>
+ /// A command that should be run upon acceptance of this item.
+ /// </summary>
+ [JsonProperty("command", NullValueHandling = NullValueHandling.Ignore)]
+ public Command? Command { get; set; }
+
+ /// <summary>
+ /// An optional set of characters that when pressed while this completion is active will
+ /// accept it first and
+ /// then type that character. *Note* that all commit characters should have `length=1` and
+ /// that superfluous
+ /// characters will be ignored.
+ /// </summary>
+ [JsonProperty("commitCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ public string[]? CommitCharacters { get; set; }
+
+ /// <summary>
+ /// A human-readable string with additional information
+ /// about this item, like type or symbol information.
+ /// </summary>
+ [JsonProperty("detail", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Detail { get; set; }
+
+ /// <summary>
+ /// A human-readable string that represents a doc-comment.
+ /// </summary>
+ [JsonProperty("documentation", NullValueHandling = NullValueHandling.Ignore)]
+ public MarkdownString? Documentation { get; set; }
+
+ /// <summary>
+ /// A string that should be used when filtering a set of
+ /// completion items. When `falsy` the [label](#CompletionItem.label)
+ /// is used.
+ /// </summary>
+ [JsonProperty("filterText", NullValueHandling = NullValueHandling.Ignore)]
+ public string? FilterText { get; set; }
+
+ /// <summary>
+ /// A string or snippet that should be inserted in a document when selecting
+ /// this completion. When `falsy` the [label](#CompletionItem.label)
+ /// is used.
+ /// </summary>
+ [JsonProperty("insertText")]
+ public string? InsertText { get; set; }
+
+ /// <summary>
+ /// Addition rules (as bitmask) that should be applied when inserting
+ /// this completion.
+ /// </summary>
+ [JsonProperty("insertTextRules", NullValueHandling = NullValueHandling.Ignore)]
+ public CompletionItemInsertTextRule? InsertTextRules { get; set; }
+
+ /// <summary>
+ /// The kind of this completion item. Based on the kind
+ /// an icon is chosen by the editor.
+ /// </summary>
+ [JsonProperty("kind")]
+ public CompletionItemKind Kind { get; set; }
+
+ /// <summary>
+ /// The label of this completion item. By default
+ /// this is also the text that is inserted when selecting
+ /// this completion.
+ /// </summary>
+ [JsonProperty("label")]
+ public string? Label { get; set; }
+
+ /// <summary>
+ /// Select this item when showing. *Note* that only one completion item can be selected and
+ /// that the editor decides which item that is. The rule is that the *first* item of those
+ /// that match best is selected.
+ /// </summary>
+ [JsonProperty("preselect", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Preselect { get; set; }
+
+ /// <summary>
+ /// A range of text that should be replaced by this completion item.
+ ///
+ /// Defaults to a range from the start of the [current
+ /// word](#TextDocument.getWordRangeAtPosition) to the
+ /// current position.
+ ///
+ /// *Note:* The range must be a [single line](#Range.isSingleLine) and it must
+ /// [contain](#Range.contains) the position at which completion has been
+ /// [requested](#CompletionItemProvider.provideCompletionItems).
+ /// </summary>
+ [JsonProperty("range")]
+ public Range? Range { get; set; }
+
+ /// <summary>
+ /// A string that should be used when comparing this item
+ /// with other items. When `falsy` the [label](#CompletionItem.label)
+ /// is used.
+ /// </summary>
+ [JsonProperty("sortText", NullValueHandling = NullValueHandling.Ignore)]
+ public string? SortText { get; set; }
+
+ /// <summary>
+ /// A modifier to the `kind` which affect how the item
+ /// is rendered, e.g. Deprecated is rendered with a strikeout
+ /// </summary>
+ [JsonProperty("tags", NullValueHandling = NullValueHandling.Ignore)]
+ public MarkerTag[]? Tags { get; set; }
+
+ public CompletionItem(string label, string insertText, CompletionItemKind kind)
+ {
+ InsertText = insertText;
+ Label = label;
+ Kind = kind;
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionItemInsertTextRule.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionItemInsertTextRule.cs
new file mode 100644
index 000000000..751344a11
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionItemInsertTextRule.cs
@@ -0,0 +1,18 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Monaco.Languages
+{
+ public enum CompletionItemInsertTextRule
+ {
+ /// <summary>
+ /// `insertText` is a snippet.
+ /// </summary>
+ InsertAsSnippet = 4,
+
+ /// <summary>
+ /// Adjust whitespace/indentation of multiline insert texts to
+ /// match the current line indentation.
+ /// </summary>
+ KeepWhitespace = 1
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionItemKind.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionItemKind.cs
new file mode 100644
index 000000000..89a93deda
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionItemKind.cs
@@ -0,0 +1,34 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Monaco.Languages
+{
+ public enum CompletionItemKind
+ {
+ Method = 0,
+ Function = 1,
+ Constructor = 2,
+ Field = 3,
+ Variable = 4,
+ Class = 5,
+ Struct = 6,
+ Interface = 7,
+ Module = 8,
+ Property = 9,
+ Event = 10,
+ Operator = 11,
+ Unit = 12,
+ Value = 13,
+ Constant = 14,
+ Enum = 15,
+ EnumMember = 16,
+ Keyword = 17,
+ Text = 18,
+ Color = 19,
+ File = 20,
+ Reference = 21,
+ Customcolor = 22,
+ Folder = 23,
+ TypeParameter = 24,
+ Snippet = 25
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionList.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionList.cs
new file mode 100644
index 000000000..e02917489
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionList.cs
@@ -0,0 +1,15 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Languages
+{
+ public sealed class CompletionList
+ {
+ [JsonProperty("incomplete", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? Incomplete { get; set; }
+
+ [JsonProperty("suggestions")]
+ public CompletionItem[]? Suggestions { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionTriggerKind.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionTriggerKind.cs
new file mode 100644
index 000000000..5491d4dab
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/CompletionTriggerKind.cs
@@ -0,0 +1,14 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Monaco.Languages
+{
+ /// <summary>
+ /// How a suggest provider was triggered.
+ /// </summary>
+ public enum CompletionTriggerKind
+ {
+ Invoke = 0,
+ TriggerCharacter = 1,
+ TriggerForIncompleteCompletions = 2
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/Hover.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/Hover.cs
new file mode 100644
index 000000000..1044e40d4
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/Hover.cs
@@ -0,0 +1,36 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System.Runtime.InteropServices.WindowsRuntime;
+
+namespace DevToys.MonacoEditor.Monaco.Languages
+{
+ /// <summary>
+ /// A hover represents additional information for a symbol or word. Hovers are
+ /// rendered in a tooltip-like widget.
+ /// </summary>
+ public sealed class Hover
+ {
+ /// <summary>
+ /// The contents of this hover.
+ /// </summary>
+ [JsonProperty("contents")]
+ public MarkdownString[] Contents { get; set; }
+
+ /// <summary>
+ /// The range to which this hover applies. When missing, the
+ /// editor will use the range at the current position or the
+ /// current position itself.
+ /// </summary>
+ [JsonProperty("range", NullValueHandling = NullValueHandling.Ignore)]
+ public IRange Range { get; set; }
+
+ public Hover([ReadOnlyArray] string[] contents, IRange range) : this(contents, range, false) { }
+
+ public Hover([ReadOnlyArray] string[] contents, IRange range, bool isTrusted)
+ {
+ Contents = contents.ToMarkdownString(isTrusted);
+ Range = range;
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/ICompletionItemProvider.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/ICompletionItemProvider.cs
new file mode 100644
index 000000000..38f0a7075
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/ICompletionItemProvider.cs
@@ -0,0 +1,36 @@
+#nullable enable
+
+using DevToys.MonacoEditor.Monaco.Editor;
+using Newtonsoft.Json;
+using Windows.Foundation;
+
+namespace DevToys.MonacoEditor.Monaco.Languages
+{
+ /// <summary>
+ /// The completion item provider interface defines the contract between extensions and
+ /// the [IntelliSense](https://code.visualstudio.com/docs/editor/intellisense)./// When computing *complete* completion items is expensive, providers can optionally implement
+ /// the `resolveCompletionItem`-function. In that case it is enough to return completion
+ /// items with a [label](#CompletionItem.label) from the
+ /// [provideCompletionItems](#CompletionItemProvider.provideCompletionItems)-function. Subsequently,
+ /// when a completion item is shown in the UI and gains focus this provider is asked to resolve
+ /// the item, like adding [doc-comment](#CompletionItem.documentation) or [details](#CompletionItem.detail).
+ ///
+ /// </summary>
+ public interface ICompletionItemProvider
+ {
+ [JsonProperty("triggerCharacters", NullValueHandling = NullValueHandling.Ignore)]
+ string[] TriggerCharacters { get; }
+
+ /// <summary>
+ /// Provide completion items for the given position and document.
+ /// </summary>
+ IAsyncOperation<CompletionList> ProvideCompletionItemsAsync(IModel model, Position position, CompletionContext context);
+
+ /// <summary>
+ /// Given a completion item fill in more data, like [doc-comment](#CompletionItem.documentation)
+ /// or [details](#CompletionItem.detail)./// The editor will only resolve a completion item once.
+ ///
+ /// </summary>
+ IAsyncOperation<CompletionItem> ResolveCompletionItemAsync(IModel model, Position position, CompletionItem item);
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/IHoverProvider.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/IHoverProvider.cs
new file mode 100644
index 000000000..b00953c82
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/IHoverProvider.cs
@@ -0,0 +1,21 @@
+#nullable enable
+
+using DevToys.MonacoEditor.Monaco.Editor;
+using Windows.Foundation;
+
+namespace DevToys.MonacoEditor.Monaco.Languages
+{
+ /// <summary>
+ /// The hover provider interface defines the contract between extensions and
+ /// the [hover](https://code.visualstudio.com/docs/editor/intellisense)-feature.
+ /// </summary>
+ public interface IHoverProvider
+ {
+ /// <summary>
+ /// Provide a hover for the given position and document. Multiple hovers at the same
+ /// position will be merged by the editor. A hover can have a range which defaults
+ /// to the word range at the position when omitted.
+ /// </summary>
+ IAsyncOperation<Hover> ProvideHover(IModel model, Position position);
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/LanguageExtensionPoint.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/LanguageExtensionPoint.cs
new file mode 100644
index 000000000..fc3f6dbaa
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Languages/LanguageExtensionPoint.cs
@@ -0,0 +1,33 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco.Languages
+{
+ public sealed class LanguageExtensionPoint
+ {
+ [JsonProperty("aliases", NullValueHandling = NullValueHandling.Ignore)]
+ public string[]? Aliases { get; set; }
+
+ [JsonProperty("configuration", NullValueHandling = NullValueHandling.Ignore)]
+ public Uri? Configuration { get; set; }
+
+ [JsonProperty("extensions", NullValueHandling = NullValueHandling.Ignore)]
+ public string[]? Extensions { get; set; }
+
+ [JsonProperty("filenamePatterns", NullValueHandling = NullValueHandling.Ignore)]
+ public string[]? FilenamePatterns { get; set; }
+
+ [JsonProperty("filenames", NullValueHandling = NullValueHandling.Ignore)]
+ public string[]? Filenames { get; set; }
+
+ [JsonProperty("firstLine", NullValueHandling = NullValueHandling.Ignore)]
+ public string? FirstLine { get; set; }
+
+ [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Id { get; set; }
+
+ [JsonProperty("mimetypes", NullValueHandling = NullValueHandling.Ignore)]
+ public string[]? Mimetypes { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/LanguagesHelper.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/LanguagesHelper.cs
new file mode 100644
index 000000000..bb5069973
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/LanguagesHelper.cs
@@ -0,0 +1,118 @@
+#nullable enable
+
+using DevToys.MonacoEditor.CodeEditorControl;
+using DevToys.MonacoEditor.Monaco.Languages;
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using Windows.Foundation;
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ /// <summary>
+ /// Helper to static Monaco.Languages Namespace methods.
+ /// https://microsoft.github.io/monaco-editor/api/modules/monaco.languages.html
+ /// </summary>
+ public sealed class LanguagesHelper
+ {
+ private readonly WeakReference<CodeEditorCore> _editor;
+
+ public LanguagesHelper(CodeEditorCore editor)
+ {
+ // We need the editor component in order to execute JavaScript within
+ // the WebView environment to retrieve data (even though this Monaco class is static).
+ _editor = new WeakReference<CodeEditorCore>(editor);
+ }
+
+ public IAsyncOperation<IList<LanguageExtensionPoint>?>? GetLanguagesAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<IList<LanguageExtensionPoint>>("monaco.languages.getLanguages()").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncAction? RegisterAsync(LanguageExtensionPoint language)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.InvokeScriptAsync("monaco.languages.register", language).AsAsyncAction();
+ }
+
+ return null;
+ }
+
+ public IAsyncAction? RegisterCompletionItemProviderAsync(string languageId, ICompletionItemProvider provider)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ // Wrapper around CompletionItem Provider to Monaco editor.
+ // TODO: Add Incremented Id so that we can register multiple providers per language?
+ editor.ParentAccessor?.RegisterEvent("CompletionItemProvider" + languageId, async (args) =>
+ {
+ if (args != null && args.Length >= 2)
+ {
+ var items = await provider.ProvideCompletionItemsAsync(editor.GetModel()!, JsonConvert.DeserializeObject<Position>(args[0]), JsonConvert.DeserializeObject<CompletionContext>(args[1]));
+
+ if (items != null)
+ {
+ return JsonConvert.SerializeObject(items);
+ }
+ }
+
+ return null;
+ });
+
+ editor.ParentAccessor?.RegisterEvent("CompletionItemRequested" + languageId, async (args) =>
+ {
+ if (args != null && args.Length >= 2)
+ {
+ var position = JsonConvert.DeserializeObject<Position>(args[0]);
+ var requestedItem = JsonConvert.DeserializeObject<CompletionItem>(args[1]);
+ var completionItem = await provider.ResolveCompletionItemAsync(editor.GetModel()!, position, requestedItem);
+
+ if (completionItem != null)
+ {
+ return JsonConvert.SerializeObject(completionItem);
+ }
+ }
+
+ return null;
+ });
+
+ return editor.InvokeScriptAsync("registerCompletionItemProvider", new object[] { languageId, provider.TriggerCharacters }).AsAsyncAction();
+ }
+
+ return null;
+ }
+
+ public IAsyncAction? RegisterHoverProviderAsync(string languageId, IHoverProvider provider)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ // Wrapper around Hover Provider to Monaco editor.
+ // TODO: Add Incremented Id so that we can register multiple providers per language?
+ editor.ParentAccessor?.RegisterEvent("HoverProvider" + languageId, async (args) =>
+ {
+ if (args != null && args.Length >= 1)
+ {
+ var hover = await provider.ProvideHover(editor.GetModel()!, JsonConvert.DeserializeObject<Position>(args[0]));
+
+ if (hover != null)
+ {
+ return JsonConvert.SerializeObject(hover);
+ }
+ }
+
+ return string.Empty;
+ });
+
+ return editor.InvokeScriptAsync("registerHoverProvider", languageId).AsAsyncAction();
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/MarkdownString.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/MarkdownString.cs
new file mode 100644
index 000000000..2ee4247d0
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/MarkdownString.cs
@@ -0,0 +1,33 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System.Collections.Generic;
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ public sealed class MarkdownString
+ {
+ [JsonProperty("isTrusted")]
+ public bool IsTrusted { get; set; }
+
+ [JsonProperty("supportThemeIcons", NullValueHandling = NullValueHandling.Ignore)]
+ public bool? SupportThemeIcons { get; set; }
+
+ [JsonProperty("uris", NullValueHandling = NullValueHandling.Ignore)]
+ public IDictionary<string, Uri>? Uris { get; set; }
+
+ [JsonProperty("value")]
+ public string? Value { get; set; }
+
+ public MarkdownString(string svalue)
+ : this(svalue, false)
+ {
+ }
+
+ public MarkdownString(string svalue, bool isTrusted)
+ {
+ Value = svalue;
+ IsTrusted = isTrusted;
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/MarkdownStringExtensions.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/MarkdownStringExtensions.cs
new file mode 100644
index 000000000..0d4891f18
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/MarkdownStringExtensions.cs
@@ -0,0 +1,33 @@
+#nullable enable
+
+using System.Linq;
+using System.Runtime.InteropServices.WindowsRuntime;
+using Windows.Foundation.Metadata;
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ public static class MarkdownStringExtensions
+ {
+ [DefaultOverload]
+ public static MarkdownString ToMarkdownString(this string svalue)
+ {
+ return ToMarkdownString(svalue, false);
+ }
+
+ [DefaultOverload]
+ public static MarkdownString ToMarkdownString(this string svalue, bool isTrusted)
+ {
+ return new MarkdownString(svalue, isTrusted);
+ }
+
+ public static MarkdownString[] ToMarkdownString([ReadOnlyArray] this string[] values)
+ {
+ return ToMarkdownString(values, false);
+ }
+
+ public static MarkdownString[] ToMarkdownString([ReadOnlyArray] this string[] values, bool isTrusted)
+ {
+ return values.Select(value => new MarkdownString(value, isTrusted)).ToArray();
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/MarkerSeverity.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/MarkerSeverity.cs
new file mode 100644
index 000000000..3281999a0
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/MarkerSeverity.cs
@@ -0,0 +1,12 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ public enum MarkerSeverity
+ {
+ Hint = 1,
+ Info = 2,
+ Warning = 4,
+ Error = 8
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/MarkerTag.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/MarkerTag.cs
new file mode 100644
index 000000000..2674bd3b3
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/MarkerTag.cs
@@ -0,0 +1,10 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ public enum MarkerTag
+ {
+ Unnecessary = 1,
+ Deprecated = 2
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/ModelHelper.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/ModelHelper.cs
new file mode 100644
index 000000000..9b2553f3d
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/ModelHelper.cs
@@ -0,0 +1,351 @@
+#nullable enable
+
+using DevToys.MonacoEditor.CodeEditorControl;
+using DevToys.MonacoEditor.Monaco.Editor;
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using Windows.Foundation;
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ /// <summary>
+ /// Helper to access IModel interface methods off of CodeEditorCore object.
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imodel.html
+ /// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.itextmodel.html
+ /// </summary>
+ public sealed class ModelHelper : IModel
+ {
+ private readonly WeakReference<CodeEditorCore> _editor;
+
+ public ModelHelper(CodeEditorCore editor)
+ {
+ _editor = new WeakReference<CodeEditorCore>(editor);
+ }
+
+ public string Id => throw new NotImplementedException();
+
+ public Uri Uri => throw new NotImplementedException();
+
+ public IAsyncAction? DetectIndentationAsync(bool defaultInsertSpaces, bool defaultTabSize)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.InvokeScriptAsync("model.detectIndentationAsync", new object[] { defaultInsertSpaces, defaultTabSize }).AsAsyncAction();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<uint>? GetAlternativeVersionIdAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<uint>("model.getAlternativeVersionId();").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<string?>? GetEOLAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<string>("model.getEOL();").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<Range?>? GetFullModelRangeAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<Range>("model.getFullModelRange();").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<string?>? GetLineContentAsync(uint lineNumber)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<string>("model.getLineContent(" + lineNumber + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<uint>? GetLineCountAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<uint>("model.getLineCount();").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<uint>? GetLineFirstNonWhitespaceColumnAsync(uint lineNumber)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<uint>("model.getLineFirstNonWhitespaceColumn(" + lineNumber + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<uint>? GetLineLastNonWhitespaceColumnAsync(uint lineNumber)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<uint>("model.getLineLastNonWhitespaceColumn(" + lineNumber + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<uint>? GetLineLengthAsync(uint lineNumber)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<uint>("model.getLineLength(" + lineNumber + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<uint>? GetLineMaxColumnAsync(uint lineNumber)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<uint>("model.getLineMaxColumn(" + lineNumber + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<uint>? GetLineMinColumnAsync(uint lineNumber)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<uint>("model.getLineMinColumn(" + lineNumber + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<IEnumerable<string>?>? GetLinesContentAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<IEnumerable<string>>("model.getLinesContent();").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<string?>? GetModelIdAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<string>("model.getModelId();").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<uint>? GetOffsetAtAsync(IPosition position)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<uint>("model.getOffsetAt(" + JsonConvert.SerializeObject(position) + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<string?>? GetOneIndentAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<string>("model.getOneIndent();").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<Position?>? GetPositionAtAsync(uint offset)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<Position>("model.getPositionAt(" + offset + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<string?>? GetValueAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<string>("model.getValue();").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<string?>? GetValueAsync(EndOfLinePreference eol)
+ {
+ throw new NotImplementedException();
+ }
+
+ public IAsyncOperation<string?>? GetValueAsync(EndOfLinePreference eol, bool preserveBOM)
+ {
+ throw new NotImplementedException();
+ }
+
+ public IAsyncOperation<string?>? GetValueInRangeAsync(IRange range)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<string>("model.getValueInRange(" + JsonConvert.SerializeObject(range) + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<string?>? GetValueInRangeAsync(IRange range, EndOfLinePreference eol)
+ {
+ throw new NotImplementedException();
+ }
+
+ public IAsyncOperation<uint>? GetValueLengthAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<uint>("model.getValueLength();").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<uint>? GetValueLengthAsync(EndOfLinePreference eol)
+ {
+ throw new NotImplementedException();
+ }
+
+ public IAsyncOperation<uint>? GetValueLengthAsync(EndOfLinePreference eol, bool preserveBOM)
+ {
+ throw new NotImplementedException();
+ }
+
+ public IAsyncOperation<uint>? GetValueLengthInRangeAsync(IRange range)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<uint>("model.getValueLengthInRange(" + JsonConvert.SerializeObject(range) + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<uint>? GetVersionIdAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<uint>("model.getVersionId();").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ // TODO: Need to investigate why with .NET Native the InterfaceToClassConverter isn't working anymore?
+ public IAsyncOperation<WordAtPosition?>? GetWordAtPositionAsync(IPosition position)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<WordAtPosition>("model.getWordAtPosition(" + JsonConvert.SerializeObject(position) + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<WordAtPosition?>? GetWordUntilPositionAsync(IPosition position)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<WordAtPosition>("model.getWordUntilPosition(" + JsonConvert.SerializeObject(position) + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<Position?>? ModifyPositionAsync(IPosition position, int number)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<Position>("model.modifyPosition(" + JsonConvert.SerializeObject(position) + ", " + number + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<string?>? NormalizeIndentationAsync(string str)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<string>("model.normalizeIndentations(JSON.parse(" + JsonConvert.ToString(str) + "));").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncAction? PushStackElementAsync()
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync("model.pushStackElement();").AsAsyncAction();
+ }
+
+ return null;
+ }
+
+ public IAsyncAction? SetEOLAsync(EndOfLineSequence eol)
+ {
+ throw new NotImplementedException();
+ }
+
+ public IAsyncAction? SetValue(string newValue)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync("model.setValue(JSON.parse(" + JsonConvert.ToString(newValue) + "));").AsAsyncAction();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<Position?>? ValidatePositionAsync(IPosition position)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<Position?>("model.validatePosition(" + JsonConvert.SerializeObject(position) + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+
+ public IAsyncOperation<Range?>? ValidateRangeAsync(IRange range)
+ {
+ if (_editor.TryGetTarget(out CodeEditorCore editor))
+ {
+ return editor.SendScriptAsync<Range?>("model.validateRange(" + JsonConvert.SerializeObject(range) + ");").AsAsyncOperation();
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Position.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Position.cs
new file mode 100644
index 000000000..85212adb7
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Position.cs
@@ -0,0 +1,117 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+using Windows.Foundation;
+using Windows.Foundation.Metadata;
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ /// <summary>
+ /// A position in the editor.
+ /// </summary>
+ public sealed class Position : IPosition
+ {
+ /// <summary>
+ /// column (the first character in a line is between column 1 and column 2)
+ /// </summary>
+ [JsonProperty("column")]
+ public uint Column { get; private set; }
+
+ /// <summary>
+ /// line number (starts at 1)
+ /// </summary>
+ [JsonProperty("lineNumber")]
+ public uint LineNumber { get; private set; }
+
+ public Position(uint lineNumber, uint column)
+ {
+ Column = column;
+ LineNumber = lineNumber;
+ }
+
+ public Position Clone()
+ {
+ return new Position(LineNumber, Column);
+ }
+
+ public override bool Equals(object obj)
+ {
+ if (obj is Position other)
+ {
+ return LineNumber == other.LineNumber && Column == other.Column;
+ }
+
+ return base.Equals(obj);
+ }
+
+ public override int GetHashCode()
+ {
+ return new Point(LineNumber, Column).GetHashCode();
+ }
+
+ public override string ToString()
+ {
+ return string.Format("({0}, {1})", LineNumber, Column);
+ }
+
+ public bool IsBefore(Position other)
+ {
+ // TODO:
+ throw new NotImplementedException();
+ }
+
+ public bool IsBeforeOrEqual(Position other)
+ {
+ // TODO:
+ throw new NotImplementedException();
+ }
+
+ [DefaultOverload]
+ public int CompareTo(Position other)
+ {
+ throw new NotImplementedException();
+ }
+
+ public int CompareTo(object obj)
+ {
+ if (obj is IPosition position)
+ {
+ return CompareTo(Lift(position));
+ }
+
+ throw new NotImplementedException();
+ }
+
+ public static int Compare(Position a, Position b)
+ {
+ return a.CompareTo(b);
+ }
+
+ // Can't Export static Method with same name in Windows Runtime Component
+ /*public static bool Equals(Position a, Position b)
+ {
+ return a.Equals(b);
+ }
+
+ public static bool IsBefore(Position a, Position b)
+ {
+ return a.IsBefore(b);
+ }
+
+ public static bool IsBeforeOrEqual(Position a, Position b)
+ {
+ return a.IsBeforeOrEqual(b);
+ }*/
+
+ public static bool IsIPosition(object a)
+ {
+ return a is Position;
+ }
+
+ public static Position Lift(IPosition pos)
+ {
+ return new Position(pos.LineNumber, pos.Column);
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Range.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Range.cs
new file mode 100644
index 000000000..03c6f0d1c
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Range.cs
@@ -0,0 +1,125 @@
+#nullable enable
+
+using Newtonsoft.Json;
+using System;
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ /// <summary>
+ /// A range in the editor. (startLineNumber,startColumn) is &lt;= (endLineNumber,endColumn)
+ /// </summary>
+ public sealed class Range : IRange
+ {
+ /// <summary>
+ /// Column on which the range ends in line `endLineNumber`.
+ /// </summary>
+ [JsonProperty("endColumn")]
+ public uint EndColumn { get; private set; }
+
+ /// <summary>
+ /// Line number on which the range ends.
+ /// </summary>
+ [JsonProperty("endLineNumber")]
+ public uint EndLineNumber { get; private set; }
+
+ /// <summary>
+ /// Column on which the range starts in line `startLineNumber` (starts at 1).
+ /// </summary>
+ [JsonProperty("startColumn")]
+ public uint StartColumn { get; private set; }
+
+ /// <summary>
+ /// Line number on which the range starts (starts at 1).
+ /// </summary>
+ [JsonProperty("startLineNumber")]
+ public uint StartLineNumber { get; private set; }
+
+ public Range(uint startLineNumber, uint startColumn, uint endLineNumber, uint endColumn)
+ {
+ // TODO: Range Check? Monaco doesn't seem to do it currently...
+ StartLineNumber = startLineNumber;
+ StartColumn = startColumn;
+ EndLineNumber = endLineNumber;
+ EndColumn = endColumn;
+ }
+
+ public Range CloneRange()
+ {
+ return new Range(StartLineNumber, StartColumn, EndLineNumber, EndColumn);
+ }
+
+ public Range CollapseToStart()
+ {
+ return new Range(StartColumn, StartColumn, StartLineNumber, StartColumn);
+ }
+
+ public Range ContainsPosition(IPosition position)
+ {
+ // TODO
+ throw new NotImplementedException();
+ }
+
+ public bool ContainsRange(IRange range)
+ {
+ // TODO
+ throw new NotImplementedException();
+ }
+
+ public bool EqualsRange(Range other)
+ {
+ return StartColumn == other.StartColumn &&
+ StartLineNumber == other.StartLineNumber &&
+ EndColumn == other.EndColumn &&
+ EndLineNumber == other.EndLineNumber;
+ }
+
+ public Position GetEndPosition()
+ {
+ return new Position(EndLineNumber, EndColumn);
+ }
+
+ public Position GetStartPosition()
+ {
+ return new Position(StartLineNumber, StartColumn);
+ }
+
+ public Range IntersectRanges(IRange range)
+ {
+ // TODO
+ throw new NotImplementedException();
+ }
+
+ public bool IsEmpty()
+ {
+ return StartLineNumber == EndLineNumber && StartColumn == EndColumn;
+ }
+
+ public Range PlusRange(IRange range)
+ {
+ // TODO
+ throw new NotImplementedException();
+ }
+
+ public Range SetEndPosition(uint endLineNumber, uint endColumn)
+ {
+ return new Range(StartLineNumber, StartColumn, endLineNumber, endColumn);
+ }
+
+ public Range SetStartPosition(uint startLineNumber, uint startColumn)
+ {
+ return new Range(startLineNumber, startColumn, EndLineNumber, EndColumn);
+ }
+
+ public override string ToString()
+ {
+ return string.Format("[{0}, {1}-> {2}, {3}]", StartLineNumber, StartColumn, EndLineNumber, EndColumn);
+ }
+
+ public static Range Lift(IRange range)
+ {
+ return new Range(range.StartLineNumber, range.StartColumn, range.EndLineNumber, range.EndColumn);
+ }
+
+ // TODO: Weed out unique static method to put here.
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Selection.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Selection.cs
new file mode 100644
index 000000000..8000a7015
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Selection.cs
@@ -0,0 +1,104 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ /// <summary>
+ /// A selection in the editor.
+ /// The selection is a range that has an orientation.
+ /// </summary>
+ public sealed class Selection : IRange
+ {
+ /// <summary>
+ /// Line number on which the range starts (starts at 1).
+ /// </summary>
+ [JsonProperty("startLineNumber")]
+ public uint StartLineNumber { get; private set; }
+
+ /// <summary>
+ /// Column on which the range starts in line `startLineNumber` (starts at 1).
+ /// </summary>
+ [JsonProperty("startColumn")]
+ public uint StartColumn { get; private set; }
+
+ /// <summary>
+ /// Line number on which the range ends.
+ /// </summary>
+ [JsonProperty("endLineNumber")]
+ public uint EndLineNumber { get; private set; }
+
+ /// <summary>
+ /// Column on which the range ends in line `endLineNumber`.
+ /// </summary>
+ [JsonProperty("endColumn")]
+ public uint EndColumn { get; private set; }
+
+ /// <summary>
+ /// The line number on which the selection has ended.
+ /// </summary>
+ [JsonProperty("positionLineNumber")]
+ public uint PositionLineNumber { get; private set; }
+
+ /// <summary>
+ /// The column on `positionLineNumber` where the selection has ended.
+ /// </summary>
+ [JsonProperty("positionColumn")]
+ public uint PositionColumn { get; private set; }
+
+ /// <summary>
+ /// The line number on which the selection has started.
+ /// </summary>
+ [JsonProperty("selectionStartLineNumber")]
+ public uint SelectionStartLineNumber { get; private set; }
+
+ /// <summary>
+ /// The column on `selectionStartLineNumber` where the selection has started.
+ /// </summary>
+ [JsonProperty("selectionStartColumn")]
+ public uint SelectionStartColumn { get; private set; }
+
+ [JsonIgnore]
+ public SelectionDirection Direction { get; private set; }
+
+ public Selection(uint selectionStartLineNumber, uint selectionStartColumn, uint positionLineNumber, uint positionColumn)
+ {
+ SelectionStartLineNumber = selectionStartLineNumber;
+ SelectionStartColumn = selectionStartColumn;
+ PositionLineNumber = positionLineNumber;
+ PositionColumn = positionColumn;
+
+ if (selectionStartLineNumber < positionLineNumber
+ || (selectionStartLineNumber == positionLineNumber && selectionStartColumn <= positionColumn))
+ {
+ // Start is first
+ StartLineNumber = SelectionStartLineNumber;
+ StartColumn = SelectionStartColumn;
+ EndLineNumber = PositionLineNumber;
+ EndColumn = PositionColumn;
+
+ Direction = SelectionDirection.LTR;
+ }
+ else
+ {
+ // Flipped
+ StartLineNumber = PositionLineNumber;
+ StartColumn = PositionColumn;
+ EndLineNumber = SelectionStartLineNumber;
+ EndColumn = SelectionStartColumn;
+
+ Direction = SelectionDirection.RTL;
+ }
+ }
+
+ public SelectionDirection GetDirection()
+ {
+ return Direction;
+ }
+
+ public override string ToString()
+ {
+ return string.Format("[{0}, {1}-> {2}, {3}]", SelectionStartLineNumber, SelectionStartColumn, PositionLineNumber, PositionColumn);
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/SelectionDirection.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/SelectionDirection.cs
new file mode 100644
index 000000000..c66c8a69e
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/SelectionDirection.cs
@@ -0,0 +1,10 @@
+#nullable enable
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ public enum SelectionDirection
+ {
+ LTR,
+ RTL
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Monaco/Uri.cs b/src/dev/impl/DevToys.MonacoEditor/Monaco/Uri.cs
new file mode 100644
index 000000000..adaf26954
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Monaco/Uri.cs
@@ -0,0 +1,54 @@
+#nullable enable
+
+using Newtonsoft.Json;
+
+namespace DevToys.MonacoEditor.Monaco
+{
+ /// <summary>
+ /// Uniform Resource Identifier (Uri) http://tools.ietf.org/html/rfc3986.
+ /// This class is a simple parser which creates the basic component parts
+ /// (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
+ /// and encoding./// foo://example.com:8042/over/there?name=ferret#nose
+ /// \_/ \______________/\_________/ \_________/ \__/
+ /// | | | | |
+ /// scheme authority path query fragment
+ /// | _____________________|__
+ /// / \ / \
+ /// urn:example:animal:ferret:nose
+ ///
+ /// </summary>
+ public sealed class Uri : IUriComponents
+ {
+ /// <summary>
+ /// authority is the 'www.msft.com' part of 'http://www.msft.com/some/path?query#fragment'.
+ /// The part between the first double slashes and the next slash.
+ /// </summary>
+ [JsonProperty("authority", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Authority { get; set; }
+
+ /// <summary>
+ /// fragment is the 'fragment' part of 'http://www.msft.com/some/path?query#fragment'.
+ /// </summary>
+ [JsonProperty("fragment", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Fragment { get; set; }
+
+ /// <summary>
+ /// path is the '/some/path' part of 'http://www.msft.com/some/path?query#fragment'.
+ /// </summary>
+ [JsonProperty("path", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Path { get; set; }
+
+ /// <summary>
+ /// query is the 'query' part of 'http://www.msft.com/some/path?query#fragment'.
+ /// </summary>
+ [JsonProperty("query", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Query { get; set; }
+
+ /// <summary>
+ /// scheme is the 'http' part of 'http://www.msft.com/some/path?query#fragment'.
+ /// The part before the first colon.
+ /// </summary>
+ [JsonProperty("scheme", NullValueHandling = NullValueHandling.Ignore)]
+ public string? Scheme { get; set; }
+ }
+}
diff --git a/src/dev/impl/DevToys.MonacoEditor/Properties/AssemblyInfo.cs b/src/dev/impl/DevToys.MonacoEditor/Properties/AssemblyInfo.cs
new file mode 100644
index 000000000..dfe86f54c
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Properties/AssemblyInfo.cs
@@ -0,0 +1,3 @@
+using System.Reflection;
+
+[assembly: AssemblyTitle("DevToys.MonacoEditor")]
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/Properties/DevToys.rd.xml b/src/dev/impl/DevToys.MonacoEditor/Properties/DevToys.rd.xml
new file mode 100644
index 000000000..6099af3b3
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Properties/DevToys.rd.xml
@@ -0,0 +1,34 @@
+<!--
+ To fully enable reflection for App1.MyClass and all of its public/private members
+ <Type Name="App1.MyClass" Dynamic="Required All"/>
+
+ To enable dynamic creation of the specific instantiation of AppClass<T> over System.Int32
+ <TypeInstantiation Name="App1.AppClass" Arguments="System.Int32" Activate="Required Public" />
+
+ Using the Namespace directive to apply reflection policy to all the types in a particular namespace
+ <Namespace Name="DataClasses.ViewModels" Serialize="All" />
+
+ Runtime Directives are documented at http://go.microsoft.com/fwlink/?LinkID=391919
+-->
+
+<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
+ <Library Name="DevToys.MonacoEditor">
+ <!-- Add your library directives here -->
+ <Namespace Name="DevToys.MonacoEditor.Monaco.Editor" Serialize="All" Dynamic="All"/>
+ <Namespace Name="DevToys.MonacoEditor.Monaco.Helpers" Serialize="All" Dynamic="All"/>
+ <Namespace Name="DevToys.MonacoEditor.Monaco.Languages" Serialize="All" Dynamic="All"/>
+ <Namespace Name="DevToys.MonacoEditor.Monaco" Serialize="All" Dynamic="All"/>
+ <Namespace Name="DevToys.MonacoEditor" Serialize="All" Dynamic="All"/>
+
+ <Type Name="DevToys.MonacoEditor.Monaco.Helpers.InterfaceToClassConverter{TInterface, TClass}">
+ <GenericParameter Name="TInterface" Dynamic="All" />
+ <GenericParameter Name="TClass" Dynamic="All" />
+ </Type>
+
+ <Type Name="Newtonsoft.Json.JsonConvert">
+ <Method Name="SerializeObject">
+ <Parameter Name="value" Serialize="Required All" Dynamic="Required All" />
+ </Method>
+ </Type>
+ </Library>
+</Directives>
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/Themes/generic.xaml b/src/dev/impl/DevToys.MonacoEditor/Themes/generic.xaml
new file mode 100644
index 000000000..4b553e39e
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/Themes/generic.xaml
@@ -0,0 +1,79 @@
+<ResourceDictionary
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:monaco="using:DevToys.MonacoEditor.CodeEditorControl"
+ xmlns:muxc="using:Microsoft.UI.Xaml.Controls">
+
+ <monaco:InvertedBooleanConverter x:Key="InvertedBooleanConverter"/>
+
+ <Style TargetType="monaco:CodeEditorCore" >
+ <Setter Property="Template">
+ <Setter.Value>
+ <ControlTemplate TargetType="monaco:CodeEditorCore">
+ <Grid>
+ <VisualStateManager.VisualStateGroups>
+ <VisualStateGroup x:Name="CommonStates">
+ <VisualState x:Name="Disabled">
+ <Storyboard>
+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">
+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundDisabled}"/>
+ </ObjectAnimationUsingKeyFrames>
+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushDisabled}"/>
+ </ObjectAnimationUsingKeyFrames>
+ </Storyboard>
+ </VisualState>
+ <VisualState x:Name="Normal"/>
+ <VisualState x:Name="PointerOver">
+ <Storyboard>
+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushPointerOver}"/>
+ </ObjectAnimationUsingKeyFrames>
+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">
+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundPointerOver}"/>
+ </ObjectAnimationUsingKeyFrames>
+ </Storyboard>
+ </VisualState>
+ <VisualState x:Name="Focused">
+ <Storyboard>
+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">
+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundFocused}"/>
+ </ObjectAnimationUsingKeyFrames>
+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushFocused}"/>
+ </ObjectAnimationUsingKeyFrames>
+ </Storyboard>
+ </VisualState>
+ </VisualStateGroup>
+ </VisualStateManager.VisualStateGroups>
+ <Border
+ x:Name="BorderElement"
+ Background="{ThemeResource TextControlBackground}"
+ BorderThickness="{ThemeResource TextControlBorderThemeThickness}"
+ BorderBrush="{ThemeResource TextControlBorderBrush}"
+ CornerRadius="4"
+ HorizontalAlignment="Stretch"
+ VerticalAlignment="Stretch"
+ IsHitTestVisible="False">
+ <WebView
+ x:Name="WebViewElement"
+ DefaultBackgroundColor="Transparent"
+ Margin="{TemplateBinding Padding}"
+ Visibility="{Binding IsEditorLoaded,RelativeSource={RelativeSource TemplatedParent}}"
+ HorizontalAlignment="Stretch"
+ VerticalAlignment="Stretch">
+ </WebView>
+ </Border>
+ <muxc:ProgressRing
+ HorizontalAlignment="Center"
+ VerticalAlignment="Center"
+ Height="48"
+ Width="48"
+ IsActive="{Binding IsEditorLoaded, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource InvertedBooleanConverter}}" />
+ </Grid>
+ </ControlTemplate>
+ </Setter.Value>
+ </Setter>
+ </Style>
+
+</ResourceDictionary>
diff --git a/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.KeyboardListener.ts b/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.KeyboardListener.ts
new file mode 100644
index 000000000..0a1aedecb
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.KeyboardListener.ts
@@ -0,0 +1,5 @@
+//namespace DevToys.MonacoEditor.Helpers {
+interface KeyboardListener {
+ keyDown(keycode: number, ctrl: boolean, shift: boolean, alt: boolean, meta: boolean): boolean;
+}
+//}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.ParentAccessor.ts b/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.ParentAccessor.ts
new file mode 100644
index 000000000..b805f55c7
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.ParentAccessor.ts
@@ -0,0 +1,12 @@
+//namespace DevToys.MonacoEditor.Helpers {
+ interface ParentAccessor {
+ callAction(name: string): boolean;
+ callEvent(name: string, parameters: string[]): Promise<string>;
+ close();
+ getChildValue(name: string, child: string): any;
+ getJsonValue(name: string): string;
+ getValue(name: string): any;
+ setValue(name: string, value: any);
+ setValue(name: string, value: string, type: string);
+ }
+//}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.ts b/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.ts
new file mode 100644
index 000000000..47f5a9b01
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.ts
@@ -0,0 +1,185 @@
+///<reference path="../monaco-editor/monaco.d.ts" />
+declare var Parent: ParentAccessor;
+declare var Keyboard: KeyboardListener;
+
+declare var editor: monaco.editor.IStandaloneCodeEditor;
+declare var model: monaco.editor.ITextModel;
+declare var contexts: { [index: string]: monaco.editor.IContextKey<any> };//{};
+declare var decorations: string[];
+declare var modifingSelection:boolean; // Supress updates to selection when making edits.
+
+var registerHoverProvider = function (languageId: string) {
+ return monaco.languages.registerHoverProvider(languageId, {
+ provideHover: function (model, position) {
+ return Parent.callEvent("HoverProvider" + languageId, [JSON.stringify(position)]).then(result => {
+ if (result) {
+ return JSON.parse(result);
+ }
+ });
+ }
+ });
+}
+
+var addAction = function (action: monaco.editor.IActionDescriptor) {
+ action.run = function (ed) {
+ Parent.callAction("Action" + action.id)
+ };
+
+ editor.addAction(action);
+};
+
+var addCommand = function (keybindingStr, handlerName, context) {
+ return editor.addCommand(parseInt(keybindingStr), () => {
+ Parent.callAction(handlerName);
+ }, context);
+};
+
+var createContext = function (context) {
+ if (context) {
+ contexts[context.key] = editor.createContextKey(context.key, context.defaultValue);
+ }
+};
+
+var updateContext = function (key, value) {
+ contexts[key].set(value);
+}
+
+var updateContent = function (content) {
+ // Need to ignore updates from us notifying of a change
+ if (content != model.getValue()) {
+ model.setValue(content);
+ }
+};
+
+var updateDiffContent = function (left, right) {
+ var diffModel = (model as unknown) as monaco.editor.IDiffEditorModel;
+
+ // Need to ignore updates from us notifying of a change
+ if (left != diffModel.original.getValue()) {
+ diffModel.original.setValue(left);
+ }
+
+ if (right != diffModel.modified.getValue()) {
+ diffModel.modified.setValue(right);
+ }
+};
+
+var updateDecorations = function (newHighlights) {
+ if (newHighlights) {
+ decorations = editor.deltaDecorations(decorations, newHighlights);
+ } else {
+ decorations = editor.deltaDecorations(decorations, []);
+ }
+};
+
+var updateStyle = function (innerStyle) {
+ var style = document.getElementById("dynamic");
+ style.innerHTML = innerStyle;
+};
+
+var getOptions = function (): monaco.editor.IEditorOptions {
+ let opt = null;
+ try {
+ opt = JSON.parse(Parent.getJsonValue("Options"));
+ } finally {
+
+ }
+
+ if (opt != null && typeof opt === "object") {
+ return opt;
+ }
+
+ return {};
+};
+
+var getDiffOptions = function (): monaco.editor.IDiffEditorOptions {
+ let opt = null;
+ try {
+ opt = JSON.parse(Parent.getJsonValue("DiffOptions"));
+ } finally {
+
+ }
+
+ if (opt != null && typeof opt === "object") {
+ return opt;
+ }
+
+ return {};
+};
+
+var updateOptions = function (opt: monaco.editor.IEditorOptions) {
+ if (opt != null && typeof opt === "object") {
+ editor.updateOptions(opt);
+ }
+};
+
+var updateDiffOptions = function (opt: monaco.editor.IDiffEditorOptions) {
+ var diffEditor = (editor as unknown) as monaco.editor.IStandaloneDiffEditor;
+ if (opt != null && typeof opt === "object") {
+ diffEditor.updateOptions(opt);
+ }
+};
+
+var updateLanguage = function (language) {
+ monaco.editor.setModelLanguage(model, language);
+};
+
+var changeTheme = function (theme: string, highcontrast) {
+ var newTheme = 'vs';
+ if (highcontrast == "True" || highcontrast == "true") {
+ newTheme = 'hc-black';
+ } else if (theme == "Dark") {
+ newTheme = 'vs-dark';
+ }
+
+ monaco.editor.setTheme(newTheme);
+};
+
+var setTheme = function (accentColor: string) {
+ // Define themes
+ // https://microsoft.github.io/monaco-editor/playground.html#customizing-the-appearence-exposed-colors
+ monaco.editor.defineTheme('vs-dark', {
+ base: 'vs-dark',
+ inherit: true,
+ rules: [],
+ colors: {
+ 'foreground': '#FFFFFF',
+ 'editor.foreground': '#FFFFFF',
+ 'editor.background': '#00000000',
+ 'editor.lineHighlightBackground': '#FFFFFF19',
+ 'editorLineNumber.foreground': '#EEEEEE99',
+ 'editorLineNumber.activeForeground': '#EEEEEE99',
+ 'editor.inactiveSelectionBackground': '#00000000',
+ 'editor.selectionForeground': '#FFFFFF',
+ 'editor.selectionBackground': accentColor,
+ }
+ });
+ monaco.editor.defineTheme('vs', {
+ base: 'vs',
+ inherit: true,
+ rules: [],
+ colors: {
+ 'foreground': '#000000',
+ 'editor.foreground': '#000000',
+ 'editor.background': '#FFFFFF00',
+ 'editor.lineHighlightBackground': '#00000019',
+ 'editorLineNumber.foreground': '#00000099',
+ 'editorLineNumber.activeForeground': '#00000099',
+ 'editor.inactiveSelectionBackground': '#00000000',
+ 'editor.selectionForeground': '#000000',
+ 'editor.selectionBackground': accentColor,
+ }
+ });
+}
+
+var keyDown = function (event) {
+ //Debug.log("Key Down:" + event.keyCode + " " + event.ctrlKey);
+ var result = Keyboard.keyDown(event.keyCode, event.ctrlKey, event.shiftKey, event.altKey, event.metaKey);
+ if (result) {
+ event.cancelBubble = true;
+ event.preventDefault();
+ event.stopPropagation();
+ event.stopImmediatePropagation();
+ return false;
+ }
+};
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/registerCompletionItemProvider.ts b/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/registerCompletionItemProvider.ts
new file mode 100644
index 000000000..25af746ee
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/registerCompletionItemProvider.ts
@@ -0,0 +1,22 @@
+///<reference path="../monaco-editor/monaco.d.ts" />
+declare var Parent: ParentAccessor;
+
+var registerCompletionItemProvider = function (languageId, characters) {
+ return monaco.languages.registerCompletionItemProvider(languageId, {
+ triggerCharacters: characters,
+ provideCompletionItems: function (model, position, context, token) {
+ return Parent.callEvent("CompletionItemProvider" + languageId, [JSON.stringify(position), JSON.stringify(context)]).then(result => {
+ if (result) {
+ return JSON.parse(result);
+ }
+ });
+ },
+ resolveCompletionItem: function (model, position, item, token) {
+ return Parent.callEvent("CompletionItemRequested" + languageId, [JSON.stringify(position), JSON.stringify(item)]).then(result => {
+ if (result) {
+ return JSON.parse(result);
+ }
+ });
+ }
+ });
+}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/tsconfig.json b/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/tsconfig.json
new file mode 100644
index 000000000..6c7547f82
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "compileOnSave": true,
+ "compilerOptions": {
+ "target": "ES2015",
+ "sourceMap": false
+ }
+}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/updateSelectedContent.ts b/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/updateSelectedContent.ts
new file mode 100644
index 000000000..e742a81aa
--- /dev/null
+++ b/src/dev/impl/DevToys.MonacoEditor/ts-helpermethods/updateSelectedContent.ts
@@ -0,0 +1,48 @@
+///<reference path="../monaco-editor/monaco.d.ts" />
+declare var Parent: ParentAccessor;
+declare var Keyboard: KeyboardListener;
+
+declare var editor: monaco.editor.IStandaloneCodeEditor;
+declare var model: monaco.editor.ITextModel;
+declare var contexts: { [index: string]: monaco.editor.IContextKey<any> };//{};
+declare var decorations: string[];
+declare var modifingSelection: boolean; // Supress updates to selection when making edits.
+
+var updateSelectedContent = function (content) {
+ let selection = editor.getSelection();
+
+ // Need to ignore updates from us notifying of a change
+ if (content != model.getValueInRange(selection)) {
+ modifingSelection = true;
+ let range = new monaco.Range(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn);
+ let op = { identifier: { major: 1, minor: 1 }, range, text: content, forceMoveMarkers: true };
+
+ // Make change to selection
+ //TODO how to properly fix this code?
+ //model.pushEditOperations([], [op]);
+ model.pushEditOperations([], [op], null);
+
+ // Update selection to new text.
+ var newEndLineNumber = selection.startLineNumber + content.split('\r').length - 1; // TODO: Not sure if line end is situational/platform specific... investigate more.
+ var newEndColumn = (selection.startLineNumber === selection.endLineNumber)
+ ? selection.startColumn + content.length
+ : content.length - content.lastIndexOf('\r');
+
+ selection = selection.setEndPosition(newEndLineNumber, newEndColumn);
+
+ // Update other selection bound for direction.
+
+ //TODO how to properly fix this code?
+ selection = selection.setEndPosition(selection.endLineNumber, selection.endColumn);
+ //if (selection.getDirection() == monaco.SelectionDirection.LTR) {
+ // selection.positionColumn = selection.endColumn;
+ // selection.positionLineNumber = selection.endLineNumber;
+ //} else {
+ // selection.selectionStartColumn = selection.endColumn;
+ // selection.selectionStartLineNumber = selection.endLineNumber;
+ //}
+
+ modifingSelection = false;
+ editor.setSelection(selection);
+ }
+};
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/App.xaml.cs b/src/dev/impl/DevToys/App.xaml.cs
index ec06b24c8..a8aa0d248 100644
--- a/src/dev/impl/DevToys/App.xaml.cs
+++ b/src/dev/impl/DevToys/App.xaml.cs
@@ -9,6 +9,7 @@ using DevToys.Core;
using DevToys.Core.Settings;
using DevToys.Core.Threading;
using DevToys.Views;
+using Microsoft.Graphics.Canvas.Text;
using System;
using System.Globalization;
using System.Linq;
@@ -31,6 +32,7 @@ namespace DevToys
{
private readonly Task<MefComposer> _mefComposer;
private readonly Lazy<Task<IThemeListener>> _themeListener;
+ private readonly Lazy<Task<ISettingsProvider>> _settingsProvider;
private bool _isDisposed;
@@ -56,6 +58,7 @@ namespace DevToys
// Importing it in a Lazy because we can't import it before a Window is created.
_themeListener = new Lazy<Task<IThemeListener>>(async () => (await _mefComposer).ExportProvider.GetExport<IThemeListener>());
+ _settingsProvider = new Lazy<Task<ISettingsProvider>>(async () => (await _mefComposer).ExportProvider.GetExport<ISettingsProvider>());
InitializeComponent();
Suspending += OnSuspending;
@@ -218,7 +221,31 @@ namespace DevToys
// Apply the app color theme.
(await _themeListener.Value).ApplyDesiredColorTheme();
+ // Change the text editor font if the current font isn't available on the system.
+ ValidateDefaultTextEditorFontAsync().Forget();
+
return rootFrame;
}
+
+ private async Task ValidateDefaultTextEditorFontAsync()
+ {
+ await TaskScheduler.Default;
+
+ ISettingsProvider settingsProvider = await _settingsProvider.Value;
+ string currentFont = settingsProvider.GetSetting(PredefinedSettings.TextEditorFont);
+ string[] systemFonts = CanvasTextFormat.GetSystemFontFamilies();
+
+ if (!systemFonts.Contains(currentFont))
+ {
+ for (int i = 0; i < PredefinedSettings.SupportedFonts.Length; i++)
+ {
+ if (systemFonts.Contains(PredefinedSettings.SupportedFonts[i]))
+ {
+ settingsProvider.SetSetting(PredefinedSettings.TextEditorFont, PredefinedSettings.SupportedFonts[i]);
+ return;
+ }
+ }
+ }
+ }
}
}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/Assets/CascadiaCode.ttf b/src/dev/impl/DevToys/Assets/CascadiaCode.ttf
deleted file mode 100644
index 117b8de3e..000000000
Binary files a/src/dev/impl/DevToys/Assets/CascadiaCode.ttf and /dev/null differ
diff --git a/src/dev/impl/DevToys/Assets/CascadiaMono.ttf b/src/dev/impl/DevToys/Assets/CascadiaMono.ttf
deleted file mode 100644
index 6a66e2b0e..000000000
Binary files a/src/dev/impl/DevToys/Assets/CascadiaMono.ttf and /dev/null differ
diff --git a/src/dev/impl/DevToys/Assets/ReleaseNote.txt b/src/dev/impl/DevToys/Assets/ReleaseNote.txt
index c77d15b39..ef789a259 100644
--- a/src/dev/impl/DevToys/Assets/ReleaseNote.txt
+++ b/src/dev/impl/DevToys/Assets/ReleaseNote.txt
@@ -1,4 +1,8 @@
- • Json <> Yaml converter
+ • Brand new text editor which implies:
+ • Better Text Diff tool
+ • Better Json <> Yaml tool
+ • Better Json Formatter tool
+ • Less UI delay
Upcoming in future updates:
• JWT Decoder
• Json to C#
diff --git a/src/dev/impl/DevToys/Core/Settings/PredefinedSettings.cs b/src/dev/impl/DevToys/Core/Settings/PredefinedSettings.cs
index 238794378..8a0f80257 100644
--- a/src/dev/impl/DevToys/Core/Settings/PredefinedSettings.cs
+++ b/src/dev/impl/DevToys/Core/Settings/PredefinedSettings.cs
@@ -53,6 +53,22 @@ namespace DevToys.Core.Settings
isRoaming: true,
defaultValue: true);
+ public static readonly string[] SupportedFonts
+ = new[]
+ {
+ "Fira Code",
+ "Source Code Pro",
+ "DejaVu Sans Mono",
+ "Menlo",
+ "Hack",
+ "Monaco",
+ "Cascadia Code",
+ "Cascadia Mono",
+ "Consolas",
+ "Courier New",
+ "Segoe UI",
+ };
+
/// <summary>
/// The font family name to use in the text editor.
/// </summary>
@@ -60,7 +76,7 @@ namespace DevToys.Core.Settings
= new(
name: nameof(TextEditorFont),
isRoaming: true,
- defaultValue: "CascadiaMono");
+ defaultValue: "Cascadia Mono");
/// <summary>
/// Whether the text in the text editor should wrap.
@@ -88,5 +104,14 @@ namespace DevToys.Core.Settings
name: nameof(TextEditorHighlightCurrentLine),
isRoaming: true,
defaultValue: true);
+
+ /// <summary>
+ /// Whether white spaces should be rendered in the text editor.
+ /// </summary>
+ public static readonly SettingDefinition<bool> TextEditorRenderWhitespace
+ = new(
+ name: nameof(TextEditorRenderWhitespace),
+ isRoaming: true,
+ defaultValue: false);
}
}
diff --git a/src/dev/impl/DevToys/Core/TitleBar.cs b/src/dev/impl/DevToys/Core/TitleBar.cs
index efc1d228b..e8ed7f775 100644
--- a/src/dev/impl/DevToys/Core/TitleBar.cs
+++ b/src/dev/impl/DevToys/Core/TitleBar.cs
@@ -4,7 +4,6 @@ using DevToys.Api.Core;
using DevToys.Api.Core.Settings;
using DevToys.Api.Core.Theme;
using DevToys.Core.Settings;
-using DevToys.Core.Theme;
using DevToys.Core.Threading;
using System.ComponentModel;
using System.Composition;
diff --git a/src/dev/impl/DevToys/DevToys.csproj b/src/dev/impl/DevToys/DevToys.csproj
index 310400df1..b25d5c820 100644
--- a/src/dev/impl/DevToys/DevToys.csproj
+++ b/src/dev/impl/DevToys/DevToys.csproj
@@ -193,13 +193,15 @@
<Compile Include="Core\Threading\ThreadPriority.cs" />
<Compile Include="Core\TitleBar.cs" />
<Compile Include="Core\ToolProviderFactory.cs" />
+ <Compile Include="UI\Controls\CodeEditor.xaml.cs">
+ <DependentUpon>CodeEditor.xaml</DependentUpon>
+ </Compile>
<Compile Include="UI\Controls\Notification.xaml.cs">
<DependentUpon>Notification.xaml</DependentUpon>
</Compile>
<Compile Include="UI\Converters\NullToVisibilityConverter.cs" />
<Compile Include="Helpers\JsonHelper.cs" />
<Compile Include="Helpers\YamlHelper.cs" />
- <Compile Include="UI\Controls\FormattedTextBlock\Languages\Yaml.cs" />
<Compile Include="ViewModels\Tools\JsonYaml\JsonYamlToolProvider.cs" />
<Compile Include="ViewModels\Tools\JsonYaml\JsonYamlToolViewModel.cs" />
<Compile Include="ViewModels\Tools\ToolProviderBase.cs" />
@@ -226,26 +228,8 @@
<Compile Include="UI\Controls\ExpandableSettingHeaderControl.xaml.cs">
<DependentUpon>ExpandableSettingHeaderControl.xaml</DependentUpon>
</Compile>
- <Compile Include="UI\Controls\FormattedTextBlock\CustomDelimiterChunker.cs" />
- <Compile Include="UI\Controls\FormattedTextBlock\CustomWordChunker.cs" />
- <Compile Include="UI\Controls\FormattedTextBlock\FormattedTextBlock.xaml.cs">
- <DependentUpon>FormattedTextBlock.xaml</DependentUpon>
- </Compile>
- <Compile Include="UI\Controls\FormattedTextBlock\IFormattedTextBlock.cs" />
<Compile Include="UI\Controls\HighlightSpan.cs" />
<Compile Include="UI\Controls\ICustomTextBox.cs" />
- <Compile Include="UI\Controls\TextEditor\CommandHandlerResult.cs" />
- <Compile Include="UI\Controls\TextEditor\ICommandHandler.cs" />
- <Compile Include="UI\Controls\TextEditor\IKeyboardCommand.cs" />
- <Compile Include="UI\Controls\TextEditor\KeyboardCommand.cs" />
- <Compile Include="UI\Controls\TextEditor\KeyboardCommandHandler.cs" />
- <Compile Include="UI\Controls\TextEditor\RtfBuilder.cs" />
- <Compile Include="UI\Controls\TextEditor\RtfFormat.cs" />
- <Compile Include="UI\Controls\TextEditor\TextEditor.xaml.cs">
- <DependentUpon>TextEditor.xaml</DependentUpon>
- </Compile>
- <Compile Include="UI\Controls\TextEditor\TextEditorCore.cs" />
- <Compile Include="UI\Controls\TextEditor\TextFormatter.cs" />
<Compile Include="UI\Converters\BooleanToGridLengthConverter.cs" />
<Compile Include="UI\Converters\BooleanToScrollBarVisibilityConverter.cs" />
<Compile Include="UI\Converters\BooleanToScrollModeConverter.cs" />
@@ -303,8 +287,6 @@
</ItemGroup>
<ItemGroup>
<Content Include="Assets\Icons\Idea.svg" />
- <Content Include="Assets\CascadiaCode.ttf" />
- <Content Include="Assets\CascadiaMono.ttf" />
<Content Include="Assets\FluentSystemIcons-Regular.ttf" />
<None Include="..\..\..\..\LICENSE.md">
<Link>Assets\LICENSE.md</Link>
@@ -340,6 +322,10 @@
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
+ <Page Include="UI\Controls\CodeEditor.xaml">
+ <SubType>Designer</SubType>
+ <Generator>MSBuild:Compile</Generator>
+ </Page>
<Page Include="UI\Controls\CustomTextBox.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
@@ -352,18 +338,10 @@
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
- <Page Include="UI\Controls\FormattedTextBlock\FormattedTextBlock.xaml">
- <Generator>MSBuild:Compile</Generator>
- <SubType>Designer</SubType>
- </Page>
<Page Include="UI\Controls\Notification.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
- <Page Include="UI\Controls\TextEditor\TextEditor.xaml">
- <Generator>MSBuild:Compile</Generator>
- <SubType>Designer</SubType>
- </Page>
<Page Include="Views\MainPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
@@ -418,9 +396,6 @@
<PRIResource Include="Strings\fr\TextDiff.resw" />
</ItemGroup>
<ItemGroup>
- <PackageReference Include="ColorCode.Core" Version="$(Nuget_ColorCodeUwp)" />
- <PackageReference Include="ColorCode.UWP" Version="$(Nuget_ColorCodeUwp)" />
- <PackageReference Include="DiffPlex" Version="$(Nuget_DiffPlex)" />
<PackageReference Include="GitInfo" Version="$(Nuget_GitInfo)" />
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform" Version="$(NuGet_MicrosoftNETCoreUniversalWindowsPlatform)" />
<PackageReference Include="Microsoft.Toolkit.Mvvm" Version="$(NuGet_MicrosoftToolkitMvvm)" />
@@ -430,10 +405,17 @@
<PackageReference Include="Newtonsoft.Json" Version="$(NuGet_NewtonsoftJson)" />
<PackageReference Include="System.Composition" Version="$(NuGet_SystemComposition)" />
<PackageReference Include="YamlDotNet" Version="$(NuGet_YamlDotNet)" />
+ <PackageReference Include="Win2D.uwp" Version="$(Nuget_Win2D)" />
</ItemGroup>
<ItemGroup>
<Service Include="{508349B6-6B84-4DF5-91F0-309BEEBAD82D}" />
</ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DevToys.MonacoEditor\DevToys.MonacoEditor.csproj">
+ <Project>{0fe678bb-9f9b-4495-b777-f9b1e11da20c}</Project>
+ <Name>DevToys.MonacoEditor</Name>
+ </ProjectReference>
+ </ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
diff --git a/src/dev/impl/DevToys/LanguageManager.cs b/src/dev/impl/DevToys/LanguageManager.cs
index 00d3cc608..cf152f221 100644
--- a/src/dev/impl/DevToys/LanguageManager.cs
+++ b/src/dev/impl/DevToys/LanguageManager.cs
@@ -636,6 +636,11 @@ namespace DevToys
/// </summary>
public string RateAndReview => _resources.GetString("RateAndReview");
+ /// <summary>
+ /// Gets the resource RenderWhitespace.
+ /// </summary>
+ public string RenderWhitespace => _resources.GetString("RenderWhitespace");
+
/// <summary>
/// Gets the resource ReportProblem.
/// </summary>
@@ -699,6 +704,11 @@ namespace DevToys
{
private readonly ResourceLoader _resources = ResourceLoader.GetForViewIndependentUse("TextDiff");
+ /// <summary>
+ /// Gets the resource Configuration.
+ /// </summary>
+ public string Configuration => _resources.GetString("Configuration");
+
/// <summary>
/// Gets the resource Difference.
/// </summary>
@@ -709,6 +719,11 @@ namespace DevToys
/// </summary>
public string DisplayName => _resources.GetString("DisplayName");
+ /// <summary>
+ /// Gets the resource InlineDifference.
+ /// </summary>
+ public string InlineDifference => _resources.GetString("InlineDifference");
+
/// <summary>
/// Gets the resource LeftText.
/// </summary>
diff --git a/src/dev/impl/DevToys/Strings/en/Settings.resw b/src/dev/impl/DevToys/Strings/en/Settings.resw
index d2a84c94e..a09cc5886 100644
--- a/src/dev/impl/DevToys/Strings/en/Settings.resw
+++ b/src/dev/impl/DevToys/Strings/en/Settings.resw
@@ -183,6 +183,9 @@
<data name="RateAndReview" xml:space="preserve">
<value>Rate and review on Microsoft Store</value>
</data>
+ <data name="RenderWhitespace" xml:space="preserve">
+ <value>Render white space</value>
+ </data>
<data name="ReportProblem" xml:space="preserve">
<value>Report a problem</value>
</data>
diff --git a/src/dev/impl/DevToys/Strings/en/TextDiff.resw b/src/dev/impl/DevToys/Strings/en/TextDiff.resw
index 36531a163..1fbe4fc4a 100644
--- a/src/dev/impl/DevToys/Strings/en/TextDiff.resw
+++ b/src/dev/impl/DevToys/Strings/en/TextDiff.resw
@@ -117,12 +117,18 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
+ <data name="Configuration" xml:space="preserve">
+ <value>Configuration</value>
+ </data>
<data name="Difference" xml:space="preserve">
<value>Difference</value>
</data>
<data name="DisplayName" xml:space="preserve">
<value>Text Diff</value>
</data>
+ <data name="InlineDifference" xml:space="preserve">
+ <value>Inline mode</value>
+ </data>
<data name="LeftText" xml:space="preserve">
<value>Old text</value>
</data>
diff --git a/src/dev/impl/DevToys/Strings/fr/Settings.resw b/src/dev/impl/DevToys/Strings/fr/Settings.resw
index 6e3b620a5..aa39b8801 100644
--- a/src/dev/impl/DevToys/Strings/fr/Settings.resw
+++ b/src/dev/impl/DevToys/Strings/fr/Settings.resw
@@ -183,6 +183,9 @@
<data name="RateAndReview" xml:space="preserve">
<value>Évaluez et commentez sur Microsoft Store</value>
</data>
+ <data name="RenderWhitespace" xml:space="preserve">
+ <value>Afficher les espaces blanc</value>
+ </data>
<data name="ReportProblem" xml:space="preserve">
<value>Signaler un problème</value>
</data>
diff --git a/src/dev/impl/DevToys/Strings/fr/TextDiff.resw b/src/dev/impl/DevToys/Strings/fr/TextDiff.resw
index b5d6d4889..af0f77f53 100644
--- a/src/dev/impl/DevToys/Strings/fr/TextDiff.resw
+++ b/src/dev/impl/DevToys/Strings/fr/TextDiff.resw
@@ -117,12 +117,18 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
+ <data name="Configuration" xml:space="preserve">
+ <value>Configuration</value>
+ </data>
<data name="Difference" xml:space="preserve">
<value>Différence</value>
</data>
<data name="DisplayName" xml:space="preserve">
<value>Comparateur de texte</value>
</data>
+ <data name="InlineDifference" xml:space="preserve">
+ <value>Mode inline</value>
+ </data>
<data name="LeftText" xml:space="preserve">
<value>Ancien texte</value>
</data>
diff --git a/src/dev/impl/DevToys/Themes/Custom.xaml b/src/dev/impl/DevToys/Themes/Custom.xaml
index 76e2496d8..896d968f1 100644
--- a/src/dev/impl/DevToys/Themes/Custom.xaml
+++ b/src/dev/impl/DevToys/Themes/Custom.xaml
@@ -3,10 +3,6 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<FontFamily x:Key="FluentSystemIcons">ms-appx:///Assets/FluentSystemIcons-Regular.ttf#FluentSystemIcons-Regular</FontFamily>
- <FontFamily x:Key="CascadiaMono">ms-appx:///Assets/CascadiaMono.ttf#Cascadia Mono</FontFamily>
- <FontFamily x:Key="CascadiaCode">ms-appx:///Assets/CascadiaCode.ttf#Cascadia Code</FontFamily>
- <FontFamily x:Key="SegoeUI">Segoe UI</FontFamily>
- <FontFamily x:Key="Consolas">Consolas</FontFamily>
<!-- Icons. Most of them are from https://github.com/microsoft/fluentui-system-icons/blob/master/icons.md -->
<x:String x:Key="EnterCompactOverlayPathIconData">M41.6339 8.13376C42.122 7.64561 42.122 6.85415 41.6339 6.36599C41.1457 5.87784 40.3543 5.87784 39.8661 6.36599L29.5002 16.732V7.25C29.5002 6.55964 28.9405 6 28.2502 6C27.5598 6 27.0002 6.55964 27.0002 7.25V19.75C27.0002 20.4404 27.5598 21 28.2502 21H40.75C41.4404 21 42 20.4404 42 19.75C42 19.0596 41.4404 18.5 40.75 18.5H31.2676L41.6339 8.13376ZM8.5 12.25C8.5 10.1789 10.1789 8.5 12.25 8.5H20.1346C20.825 8.5 21.3846 7.94036 21.3846 7.25C21.3846 6.55964 20.825 6 20.1346 6H12.25C8.79822 6 6 8.79822 6 12.25V35.75C6 39.2018 8.79822 42 12.25 42H35.75C39.2018 42 42 39.2018 42 35.75V27.8654C42 27.175 41.4404 26.6154 40.75 26.6154C40.0596 26.6154 39.5 27.175 39.5 27.8654V35.75C39.5 37.8211 37.8211 39.5 35.75 39.5H24V29.2499C24 26.3504 21.6495 23.9999 18.75 23.9999H8.5V12.25ZM8.5 26.4999H18.75C20.2688 26.4999 21.5 27.7311 21.5 29.2499V39.5H12.25C10.1789 39.5 8.5 37.8211 8.5 35.75V26.4999Z</x:String>
diff --git a/src/dev/impl/DevToys/Themes/Generic.xaml b/src/dev/impl/DevToys/Themes/Generic.xaml
index 76c19c28d..eca3d768b 100644
--- a/src/dev/impl/DevToys/Themes/Generic.xaml
+++ b/src/dev/impl/DevToys/Themes/Generic.xaml
@@ -2,7 +2,6 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:DevToys.UI.Controls"
- xmlns:textEditor="using:DevToys.UI.Controls.TextEditor"
xmlns:DevToys="using:DevToys"
xmlns:toolkit="using:Microsoft.Toolkit.Uwp.UI.Controls">
@@ -66,234 +65,4 @@
</Setter.Value>
</Setter>
</Style>
-
- <Style TargetType="textEditor:TextEditorCore">
- <Setter Property="Foreground" Value="{ThemeResource TextEditorForeground}"/>
- <Setter Property="Background" Value="{ThemeResource TextControlBackground}"/>
- <Setter Property="SelectionHighlightColor" Value="{ThemeResource TextControlSelectionHighlightColor}"/>
- <Setter Property="BorderBrush" Value="{ThemeResource TextControlBorderBrush}"/>
- <Setter Property="BorderThickness" Value="{ThemeResource TextControlBorderThemeThickness}"/>
- <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
- <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
- <Setter Property="ScrollViewer.HorizontalScrollMode" Value="Enabled"/>
- <Setter Property="ScrollViewer.VerticalScrollMode" Value="Enabled"/>
- <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
- <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
- <Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/>
- <Setter Property="TextWrapping" Value="NoWrap"/>
- <Setter Property="Padding" Value="0"/>
- <Setter Property="UseSystemFocusVisuals" Value="{ThemeResource IsApplicationFocusVisualKindReveal}"/>
- <Setter Property="Template">
- <Setter.Value>
- <ControlTemplate TargetType="RichEditBox">
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="*"/>
- <RowDefinition Height="Auto"/>
- </Grid.RowDefinitions>
- <VisualStateManager.VisualStateGroups>
- <VisualStateGroup x:Name="CommonStates">
- <VisualState x:Name="Disabled">
- <Storyboard>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="HeaderContentPresenter" Storyboard.TargetProperty="Foreground">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlHeaderForegroundDisabled}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundDisabled}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushDisabled}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundDisabled}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundDisabled}"/>
- </ObjectAnimationUsingKeyFrames>
- </Storyboard>
- </VisualState>
- <VisualState x:Name="Normal"/>
- <VisualState x:Name="PointerOver">
- <Storyboard>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushPointerOver}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundPointerOver}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundPointerOver}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundPointerOver}"/>
- </ObjectAnimationUsingKeyFrames>
- </Storyboard>
- </VisualState>
- <VisualState x:Name="Focused">
- <Storyboard>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundFocused}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundFocused}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushFocused}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundFocused}"/>
- </ObjectAnimationUsingKeyFrames>
- </Storyboard>
- </VisualState>
- </VisualStateGroup>
- </VisualStateManager.VisualStateGroups>
- <Border
- x:Name="BorderElement"
- Background="{TemplateBinding Background}"
- BorderThickness="{TemplateBinding BorderThickness}"
- BorderBrush="{TemplateBinding BorderBrush}"
- CornerRadius="4"
- MinHeight="{ThemeResource TextControlThemeMinHeight}"
- MinWidth="{ThemeResource TextControlThemeMinWidth}"
- Grid.Row="0"/>
- <Grid x:Name="RootGrid" Grid.Row="0">
- <Grid.ColumnDefinitions>
- <ColumnDefinition x:Name="LineNumberColumnDefinition" Width="Auto"/>
- <ColumnDefinition x:Name="TextEditorColumnDefinition" Width="*"/>
- </Grid.ColumnDefinitions>
- <Canvas x:Name="LineHighlighterAndIndicatorCanvas" Grid.ColumnSpan="2">
- <Border
- x:Name="LineIndicator"
- BorderBrush="{StaticResource SystemControlForegroundAccentBrush}"
- Visibility="Collapsed"/>
- <Grid
- x:Name="LineHighlighter"
- Background="{ThemeResource SystemControlBackgroundListLowBrush}"
- Opacity="0.65"
- BorderThickness="0"
- Visibility="Collapsed"/>
- </Canvas>
- <Grid
- x:Name="LineNumberGrid"
- Grid.Column="0"
- BorderThickness="0,0,0,0"
- BorderBrush="{ThemeResource SystemControlBackgroundTransparentRevealBorderBrush}">
- <Canvas x:Name="LineNumberCanvas"/>
- </Grid>
- <Grid Grid.Column="1">
- <ScrollViewer
- x:Name="ContentElement"
- AutomationProperties.AccessibilityView="Raw"
- HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}"
- HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}"
- IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}"
- IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}"
- IsTabStop="False"
- TabIndex="1"
- IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}"
- Margin="{TemplateBinding BorderThickness}"
- Padding="{TemplateBinding Padding}"
- VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}"
- VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}"
- ZoomMode="Disabled"/>
- </Grid>
- </Grid>
- <TextBlock
- x:Name="PlaceholderTextContentPresenter"
- Foreground="{ThemeResource TextControlPlaceholderForeground}"
- IsHitTestVisible="False"
- Margin="{TemplateBinding BorderThickness}"
- Padding="{TemplateBinding Padding}"
- Grid.Row="0"
- Text="{TemplateBinding PlaceholderText}"
- TextWrapping="{TemplateBinding TextWrapping}"
- TextAlignment="{TemplateBinding TextAlignment}"
- OpticalMarginAlignment="TrimSideBearings"/>
- <ContentPresenter
- x:Name="DescriptionPresenter"
- AutomationProperties.AccessibilityView="Raw"
- Content="{TemplateBinding Description}"
- Foreground="{ThemeResource SystemControlDescriptionTextForegroundBrush}"
- Grid.Row="1"
- x:Load="False"/>
- </Grid>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- <Setter Property="ContextFlyout">
- <Setter.Value>
- <MenuFlyout>
- <MenuFlyoutItem
- Text="{Binding Instance.Common.Cut, Source={StaticResource LanguageManager}}"
- Command="{Binding CutCommand}">
- <MenuFlyoutItem.Icon>
- <FontIcon Glyph="&#xF33A;" />
- </MenuFlyoutItem.Icon>
- <MenuFlyoutItem.KeyboardAccelerators>
- <KeyboardAccelerator Key="X" Modifiers="Control" IsEnabled="False"/>
- </MenuFlyoutItem.KeyboardAccelerators>
- </MenuFlyoutItem>
- <MenuFlyoutItem
- Text="{Binding Instance.Common.Copy, Source={StaticResource LanguageManager}}"
- Command="{Binding CopyCommand}">
- <MenuFlyoutItem.Icon>
- <FontIcon Glyph="&#xF32B;" />
- </MenuFlyoutItem.Icon>
- <MenuFlyoutItem.KeyboardAccelerators>
- <KeyboardAccelerator Key="C" Modifiers="Control" IsEnabled="False"/>
- </MenuFlyoutItem.KeyboardAccelerators>
- </MenuFlyoutItem>
- <MenuFlyoutItem
- Text="{Binding Instance.Common.Paste, Source={StaticResource LanguageManager}}"
- Command="{Binding PasteCommand}">
- <MenuFlyoutItem.Icon>
- <FontIcon Glyph="&#xF2D5;" />
- </MenuFlyoutItem.Icon>
- <MenuFlyoutItem.KeyboardAccelerators>
- <KeyboardAccelerator Key="V" Modifiers="Control" IsEnabled="False"/>
- </MenuFlyoutItem.KeyboardAccelerators>
- </MenuFlyoutItem>
- <MenuFlyoutItem
- Text="{Binding Instance.Common.Delete, Source={StaticResource LanguageManager}}"
- Command="{Binding DeleteCommand}">
- <MenuFlyoutItem.Icon>
- <FontIcon Glyph="&#xF34C;" />
- </MenuFlyoutItem.Icon>
- <MenuFlyoutItem.KeyboardAccelerators>
- <KeyboardAccelerator Key="Delete" IsEnabled="False" />
- </MenuFlyoutItem.KeyboardAccelerators>
- </MenuFlyoutItem>
- <MenuFlyoutSeparator/>
- <MenuFlyoutItem
- Text="{Binding Instance.Common.Undo, Source={StaticResource LanguageManager}}"
- Command="{Binding UndoCommand}">
- <MenuFlyoutItem.Icon>
- <FontIcon Glyph="&#xF199;" />
- </MenuFlyoutItem.Icon>
- <MenuFlyoutItem.KeyboardAccelerators>
- <KeyboardAccelerator Key="Z" Modifiers="Control" IsEnabled="False" />
- </MenuFlyoutItem.KeyboardAccelerators>
- </MenuFlyoutItem>
- <MenuFlyoutItem
- Text="{Binding Instance.Common.Redo, Source={StaticResource LanguageManager}}"
- Command="{Binding RedoCommand}">
- <MenuFlyoutItem.Icon>
- <FontIcon Glyph="&#xF16E;" />
- </MenuFlyoutItem.Icon>
- <MenuFlyoutItem.KeyboardAccelerators>
- <KeyboardAccelerator Key="Y" Modifiers="Control" IsEnabled="False" />
- </MenuFlyoutItem.KeyboardAccelerators>
- </MenuFlyoutItem>
- <MenuFlyoutSeparator/>
- <MenuFlyoutItem
- Text="{Binding Instance.Common.SelectAll, Source={StaticResource LanguageManager}}"
- Command="{Binding SelectAllCommand}">
- <MenuFlyoutItem.KeyboardAccelerators>
- <KeyboardAccelerator Key="A" Modifiers="Control" IsEnabled="False" />
- </MenuFlyoutItem.KeyboardAccelerators>
- </MenuFlyoutItem>
- </MenuFlyout>
- </Setter.Value>
- </Setter>
- </Style>
</ResourceDictionary>
diff --git a/src/dev/impl/DevToys/UI/Controls/CodeEditor.xaml b/src/dev/impl/DevToys/UI/Controls/CodeEditor.xaml
new file mode 100644
index 000000000..7ec6cb046
--- /dev/null
+++ b/src/dev/impl/DevToys/UI/Controls/CodeEditor.xaml
@@ -0,0 +1,111 @@
+<UserControl
+ x:Class="DevToys.UI.Controls.CodeEditor"
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+ xmlns:monaco="using:DevToys.MonacoEditor.CodeEditorControl"
+ xmlns:DevToys="using:DevToys"
+ xmlns:converters="using:DevToys.UI.Converters"
+ mc:Ignorable="d"
+ d:DesignHeight="24"
+ d:DesignWidth="200"
+ SizeChanged="UserControl_SizeChanged">
+ <UserControl.Resources>
+ <DevToys:LanguageManager x:Key="LanguageManager"/>
+
+ <converters:NullToVisibilityConverter x:Key="InvertedNullToVisibilityConverter" IsInverted="True"/>
+ <converters:InvertedBooleanConverter x:Key="InvertedBooleanConverter"/>
+ <converters:BooleanToTextWrappingConverter x:Key="BooleanToTextWrappingConverter" TextWrappingOnTrue="Wrap" TextWrappingOnFalse="NoWrap"/>
+ </UserControl.Resources>
+
+ <Grid>
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto"/>
+ <RowDefinition Height="*"/>
+ </Grid.RowDefinitions>
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="*"/>
+ <ColumnDefinition Width="Auto"/>
+ </Grid.ColumnDefinitions>
+ <TextBlock
+ x:Name="HeaderTextBlock"
+ x:DeferLoadStrategy="Lazy"
+ Grid.Row="0"
+ Grid.Column="0"
+ Text="{x:Bind Header}"
+ Margin="{ThemeResource TextBoxTopHeaderMargin}"
+ Style="{StaticResource SubTitleTextBlock}"
+ TextWrapping="Wrap"
+ VerticalAlignment="Bottom"
+ Visibility="Collapsed">
+ </TextBlock>
+ <StackPanel
+ x:Name="CommandsToolBar"
+ Grid.Row="0"
+ Grid.Column="1"
+ Orientation="Horizontal"
+ HorizontalAlignment="Right"
+ Spacing="8"
+ Margin="0,0,0,8">
+ <Button
+ x:Name="PasteButton"
+ x:DeferLoadStrategy="Lazy"
+ Visibility="Collapsed"
+ TabIndex="0"
+ Click="PasteButton_Click">
+ <StackPanel Orientation="Horizontal" Spacing="4">
+ <FontIcon Glyph="&#xF2D5;"/>
+ <TextBlock VerticalAlignment="Center" Text="{Binding Instance.Common.Paste, Mode=OneTime, Source={StaticResource LanguageManager}}"/>
+ </StackPanel>
+ </Button>
+ <Button
+ x:Name="OpenFileButton"
+ x:DeferLoadStrategy="Lazy"
+ Visibility="Collapsed"
+ TabIndex="0"
+ ToolTipService.ToolTip="{Binding Instance.Common.OpenFile, Mode=OneTime, Source={StaticResource LanguageManager}}"
+ Click="OpenFileButton_Click">
+ <FontIcon Glyph="&#xF378;"/>
+ </Button>
+ <Button
+ x:Name="ClearButton"
+ x:DeferLoadStrategy="Lazy"
+ Visibility="Collapsed"
+ TabIndex="0"
+ ToolTipService.ToolTip="{Binding Instance.Common.Clear, Mode=OneTime, Source={StaticResource LanguageManager}}"
+ Click="ClearButton_Click">
+ <FontIcon Glyph="&#xF369;"/>
+ </Button>
+ <Button
+ x:Name="CopyButton"
+ x:DeferLoadStrategy="Lazy"
+ TabIndex="2"
+ Visibility="Collapsed"
+ Click="CopyButton_Click">
+ <StackPanel Orientation="Horizontal" Spacing="4">
+ <FontIcon Glyph="&#xF32B;"/>
+ <TextBlock VerticalAlignment="Center" Text="{Binding Instance.Common.Copy, Mode=OneTime, Source={StaticResource LanguageManager}}"/>
+ </StackPanel>
+ </Button>
+ </StackPanel>
+ <monaco:CodeEditorCore
+ x:Name="CodeEditorCore"
+ Grid.Row="1"
+ Grid.Column="0"
+ Grid.ColumnSpan="2"
+ TabIndex="1"
+ CodeLanguage="{x:Bind CodeLanguage, Mode=OneWay}"
+ Text="{x:Bind Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
+ IsDiffViewMode="{x:Bind IsDiffViewMode}"
+ DiffLeftText="{x:Bind DiffLeftText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
+ DiffRightText="{x:Bind DiffRightText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
+ <TextBlock
+ Grid.Row="1"
+ Grid.Column="0"
+ Grid.ColumnSpan="2"
+ Text="{x:Bind ErrorMessage, Mode=OneWay}"
+ Visibility="{x:Bind ErrorMessage, Mode=OneWay, Converter={StaticResource InvertedNullToVisibilityConverter}}"
+ IsTextSelectionEnabled="True"/>
+ </Grid>
+</UserControl>
diff --git a/src/dev/impl/DevToys/UI/Controls/CodeEditor.xaml.cs b/src/dev/impl/DevToys/UI/Controls/CodeEditor.xaml.cs
new file mode 100644
index 000000000..226a8e44a
--- /dev/null
+++ b/src/dev/impl/DevToys/UI/Controls/CodeEditor.xaml.cs
@@ -0,0 +1,406 @@
+#nullable enable
+
+using DevToys.Api.Core.Settings;
+using DevToys.Core;
+using DevToys.Core.Settings;
+using DevToys.MonacoEditor.Monaco.Editor;
+using System;
+using Windows.ApplicationModel.DataTransfer;
+using Windows.Storage;
+using Windows.Storage.Pickers;
+using Windows.UI.Xaml;
+using Windows.UI.Xaml.Controls;
+using Clipboard = Windows.ApplicationModel.DataTransfer.Clipboard;
+
+namespace DevToys.UI.Controls
+{
+ public sealed partial class CodeEditor : UserControl
+ {
+ public static readonly DependencyProperty SettingsProviderProperty
+ = DependencyProperty.Register(
+ nameof(SettingsProvider),
+ typeof(ISettingsProvider),
+ typeof(CodeEditor),
+ new PropertyMetadata(
+ null,
+ (d, e) =>
+ {
+ if (e.NewValue is ISettingsProvider settingsProvider)
+ {
+ var codeEditor = (CodeEditor)d;
+ settingsProvider.SettingChanged += codeEditor.SettingsProvider_SettingChanged;
+ }
+ }));
+
+ public ISettingsProvider? SettingsProvider
+ {
+ get => (ISettingsProvider?)GetValue(SettingsProviderProperty);
+ set => SetValue(SettingsProviderProperty, value);
+ }
+
+ public static readonly DependencyProperty HeaderProperty
+ = DependencyProperty.Register(
+ nameof(Header),
+ typeof(object),
+ typeof(CodeEditor),
+ new PropertyMetadata(null, (d, e) => { ((CodeEditor)d).UpdateUI(); }));
+
+ public string? Header
+ {
+ get => (string?)GetValue(HeaderProperty);
+ set => SetValue(HeaderProperty, value);
+ }
+
+ public static readonly DependencyProperty ErrorMessageProperty
+ = DependencyProperty.Register(
+ nameof(ErrorMessage),
+ typeof(string),
+ typeof(CodeEditor),
+ new PropertyMetadata(string.Empty));
+
+ public string ErrorMessage
+ {
+ get => (string)GetValue(ErrorMessageProperty);
+ set => SetValue(ErrorMessageProperty, value);
+ }
+
+ public static readonly DependencyProperty IsReadOnlyProperty
+ = DependencyProperty.Register(
+ nameof(IsReadOnly),
+ typeof(bool),
+ typeof(CodeEditor),
+ new PropertyMetadata(false, OnIsReadOnlyPropertyChangedCalled));
+
+ public bool IsReadOnly
+ {
+ get => (bool)GetValue(IsReadOnlyProperty);
+ set => SetValue(IsReadOnlyProperty, value);
+ }
+
+ public static DependencyProperty CodeLanguageProperty { get; }
+ = DependencyProperty.Register(
+ nameof(CodeLanguage),
+ typeof(string),
+ typeof(CodeEditor),
+ new PropertyMetadata(string.Empty));
+
+ public string? CodeLanguage
+ {
+ get => (string?)GetValue(CodeLanguageProperty);
+ set => SetValue(CodeLanguageProperty, value);
+ }
+
+ public static readonly DependencyProperty TextProperty
+ = DependencyProperty.Register(
+ nameof(Text),
+ typeof(string),
+ typeof(CodeEditor),
+ new PropertyMetadata(string.Empty));
+
+ public string Text
+ {
+ get => (string)GetValue(TextProperty);
+ set => SetValue(TextProperty, value);
+ }
+
+ public static readonly DependencyProperty IsDiffViewModeProperty
+ = DependencyProperty.Register(
+ nameof(IsDiffViewMode),
+ typeof(bool),
+ typeof(CodeEditor),
+ new PropertyMetadata(false));
+
+ public bool IsDiffViewMode
+ {
+ get => (bool)GetValue(IsDiffViewModeProperty);
+ set => SetValue(IsDiffViewModeProperty, value);
+ }
+
+ public static readonly DependencyProperty DiffLeftTextProperty
+ = DependencyProperty.Register(
+ nameof(DiffLeftText),
+ typeof(string),
+ typeof(CodeEditor),
+ new PropertyMetadata(string.Empty));
+
+ public string DiffLeftText
+ {
+ get => (string)GetValue(DiffLeftTextProperty);
+ set => SetValue(DiffLeftTextProperty, value);
+ }
+
+ public static readonly DependencyProperty DiffRightTextProperty
+ = DependencyProperty.Register(
+ nameof(DiffRightText),
+ typeof(string),
+ typeof(CodeEditor),
+ new PropertyMetadata(string.Empty));
+
+ public string DiffRightText
+ {
+ get => (string)GetValue(DiffRightTextProperty);
+ set => SetValue(DiffRightTextProperty, value);
+ }
+
+ public static readonly DependencyProperty InlineDiffViewModeProperty
+ = DependencyProperty.Register(
+ nameof(InlineDiffViewMode),
+ typeof(bool),
+ typeof(CodeEditor),
+ new PropertyMetadata(
+ false,
+ (d, e) =>
+ {
+ ((CodeEditor)d).CodeEditorCore.DiffOptions.RenderSideBySide = !(bool)e.NewValue;
+ }));
+
+ public bool InlineDiffViewMode
+ {
+ get => (bool)GetValue(InlineDiffViewModeProperty);
+ set => SetValue(InlineDiffViewModeProperty, value);
+ }
+
+ public CodeEditor()
+ {
+ InitializeComponent();
+
+ CodeEditorCore.Loading += CodeEditorCore_Loading;
+ CodeEditorCore.InternalException += CodeEditorCore_InternalException;
+
+ UpdateUI();
+ }
+
+ private void CodeEditorCore_InternalException(MonacoEditor.CodeEditorControl.CodeEditorCore sender, Exception args)
+ {
+ ErrorMessage = $"{args.Message}\r\n{args.InnerException?.Message}";
+ }
+
+ private void CodeEditorCore_Loading(object sender, RoutedEventArgs e)
+ {
+ CodeEditorCore.Loading -= CodeEditorCore_Loading;
+
+ CodeEditorCore.HasGlyphMargin = false;
+ CodeEditorCore.Options.GlyphMargin = false;
+ CodeEditorCore.Options.MouseWheelZoom = false;
+ CodeEditorCore.Options.OverviewRulerBorder = false;
+ CodeEditorCore.Options.ScrollBeyondLastLine = false;
+ CodeEditorCore.Options.FontLigatures = true;
+ CodeEditorCore.Options.SnippetSuggestions = SnippetSuggestions.None;
+ CodeEditorCore.Options.CodeLens = false;
+ CodeEditorCore.Options.QuickSuggestions = false;
+ CodeEditorCore.Options.WordBasedSuggestions = false;
+ CodeEditorCore.Options.Minimap = new EditorMinimapOptions()
+ {
+ Enabled = false
+ };
+ CodeEditorCore.Options.Hover = new EditorHoverOptions()
+ {
+ Enabled = false
+ };
+
+ CodeEditorCore.DiffOptions.GlyphMargin = false;
+ CodeEditorCore.DiffOptions.MouseWheelZoom = false;
+ CodeEditorCore.DiffOptions.OverviewRulerBorder = false;
+ CodeEditorCore.DiffOptions.ScrollBeyondLastLine = false;
+ CodeEditorCore.DiffOptions.FontLigatures = true;
+ CodeEditorCore.DiffOptions.SnippetSuggestions = SnippetSuggestions.None;
+ CodeEditorCore.DiffOptions.CodeLens = false;
+ CodeEditorCore.DiffOptions.QuickSuggestions = false;
+ CodeEditorCore.DiffOptions.Minimap = new EditorMinimapOptions()
+ {
+ Enabled = false
+ };
+ CodeEditorCore.DiffOptions.Hover = new EditorHoverOptions()
+ {
+ Enabled = false
+ };
+
+ ApplySettings();
+ }
+
+ private Button GetCopyButton()
+ {
+ return (Button)(CopyButton ?? FindName(nameof(CopyButton)));
+ }
+
+ private Button GetPasteButton()
+ {
+ return (Button)(PasteButton ?? FindName(nameof(PasteButton)));
+ }
+
+ private Button GetOpenFileButton()
+ {
+ return (Button)(OpenFileButton ?? FindName(nameof(OpenFileButton)));
+ }
+
+ private Button GetClearButton()
+ {
+ return (Button)(ClearButton ?? FindName(nameof(ClearButton)));
+ }
+
+ private TextBlock GetHeaderTextBlock()
+ {
+ return (TextBlock)(HeaderTextBlock ?? FindName(nameof(HeaderTextBlock)));
+ }
+
+ private void ApplySettings()
+ {
+ ISettingsProvider? settingsProvider = SettingsProvider;
+ if (settingsProvider is not null)
+ {
+ CodeEditorCore.Options.WordWrapMinified = settingsProvider.GetSetting(PredefinedSettings.TextEditorTextWrapping);
+ CodeEditorCore.Options.WordWrap = settingsProvider.GetSetting(PredefinedSettings.TextEditorTextWrapping) ? WordWrap.On : WordWrap.Off;
+ CodeEditorCore.Options.LineNumbers = settingsProvider.GetSetting(PredefinedSettings.TextEditorLineNumbers) ? LineNumbersType.On : LineNumbersType.Off;
+ CodeEditorCore.Options.RenderLineHighlight = settingsProvider.GetSetting(PredefinedSettings.TextEditorHighlightCurrentLine) ? RenderLineHighlight.All : RenderLineHighlight.None;
+ CodeEditorCore.Options.RenderWhitespace = settingsProvider.GetSetting(PredefinedSettings.TextEditorRenderWhitespace) ? RenderWhitespace.All : RenderWhitespace.None;
+ CodeEditorCore.Options.FontFamily = settingsProvider.GetSetting(PredefinedSettings.TextEditorFont);
+ CodeEditorCore.DiffOptions.WordWrapMinified = settingsProvider.GetSetting(PredefinedSettings.TextEditorTextWrapping);
+ CodeEditorCore.DiffOptions.WordWrap = settingsProvider.GetSetting(PredefinedSettings.TextEditorTextWrapping) ? WordWrap.On : WordWrap.Off;
+ CodeEditorCore.DiffOptions.LineNumbers = settingsProvider.GetSetting(PredefinedSettings.TextEditorLineNumbers) ? LineNumbersType.On : LineNumbersType.Off;
+ CodeEditorCore.DiffOptions.RenderLineHighlight = settingsProvider.GetSetting(PredefinedSettings.TextEditorHighlightCurrentLine) ? RenderLineHighlight.All : RenderLineHighlight.None;
+ CodeEditorCore.DiffOptions.RenderWhitespace = settingsProvider.GetSetting(PredefinedSettings.TextEditorRenderWhitespace) ? RenderWhitespace.All : RenderWhitespace.None;
+ CodeEditorCore.DiffOptions.FontFamily = settingsProvider.GetSetting(PredefinedSettings.TextEditorFont);
+ }
+ }
+
+ private void UpdateUI()
+ {
+ if (Header is not null)
+ {
+ GetHeaderTextBlock().Visibility = Visibility.Visible;
+ }
+
+ if (IsReadOnly)
+ {
+ GetCopyButton().Visibility = Visibility.Visible;
+ if (PasteButton is not null)
+ {
+ PasteButton.Visibility = Visibility.Collapsed;
+ OpenFileButton.Visibility = Visibility.Collapsed;
+ ClearButton.Visibility = Visibility.Collapsed;
+ }
+ }
+ else
+ {
+ if (CopyButton is not null)
+ {
+ CopyButton.Visibility = Visibility.Collapsed;
+ }
+
+ GetPasteButton().Visibility = Visibility.Visible;
+ GetOpenFileButton().Visibility = Visibility.Visible;
+ GetClearButton().Visibility = Visibility.Visible;
+ }
+
+ if (IsDiffViewMode)
+ {
+ if (CopyButton is not null)
+ {
+ CopyButton.Visibility = Visibility.Collapsed;
+ }
+
+ if (PasteButton is not null)
+ {
+ PasteButton.Visibility = Visibility.Collapsed;
+ OpenFileButton.Visibility = Visibility.Collapsed;
+ ClearButton.Visibility = Visibility.Collapsed;
+ }
+ }
+ }
+
+ private async void PasteButton_Click(object sender, RoutedEventArgs e)
+ {
+ try
+ {
+ DataPackageView? dataPackageView = Clipboard.GetContent();
+ if (!dataPackageView.Contains(StandardDataFormats.Text))
+ {
+ return;
+ }
+
+ string? text = await dataPackageView.GetTextAsync();
+
+ CodeEditorCore.SelectedText = text;
+ CodeEditorCore.Focus(FocusState.Programmatic);
+ }
+ catch (Exception ex)
+ {
+ Logger.LogFault("Failed to paste in code editor", ex);
+ }
+ }
+
+ private void CopyButton_Click(object sender, RoutedEventArgs e)
+ {
+ var data = new DataPackage
+ {
+ RequestedOperation = DataPackageOperation.Copy
+ };
+ data.SetText(Text ?? string.Empty);
+
+ Clipboard.SetContent(data);
+ }
+
+ private async void OpenFileButton_Click(object sender, RoutedEventArgs e)
+ {
+ var filePicker = new FileOpenPicker
+ {
+ ViewMode = PickerViewMode.List,
+ SuggestedStartLocation = PickerLocationId.ComputerFolder
+ };
+
+ filePicker.FileTypeFilter.Add("*");
+
+ StorageFile file = await filePicker.PickSingleFileAsync();
+ if (file is not null)
+ {
+ try
+ {
+ string text = await FileIO.ReadTextAsync(file);
+ await Dispatcher.RunAsync(
+ Windows.UI.Core.CoreDispatcherPriority.Normal,
+ () =>
+ {
+ Text = text;
+ });
+ }
+ catch (Exception ex)
+ {
+ Logger.LogFault("Failed to load a file into a code editor", ex);
+ // TODO: Show a modal explaining the user that we can't read the file. Maybe it's not a text file.
+ }
+ }
+ }
+
+ private void ClearButton_Click(object sender, RoutedEventArgs e)
+ {
+ Text = string.Empty;
+ }
+
+ private void SettingsProvider_SettingChanged(object sender, SettingChangedEventArgs e)
+ {
+ if (e.SettingName.Contains("TextEditor"))
+ {
+ ApplySettings();
+ }
+ }
+
+ private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
+ {
+ if (e.NewSize.Width < CommandsToolBar.ActualWidth + 100)
+ {
+ CommandsToolBar.Visibility = Visibility.Collapsed;
+ }
+ else
+ {
+ CommandsToolBar.Visibility = Visibility.Visible;
+ }
+ }
+
+ private static void OnIsReadOnlyPropertyChangedCalled(DependencyObject sender, DependencyPropertyChangedEventArgs eventArgs)
+ {
+ var codeEditor = (CodeEditor)sender;
+ codeEditor.CodeEditorCore.ReadOnly = (bool)eventArgs.NewValue;
+ codeEditor.UpdateUI();
+ }
+ }
+}
diff --git a/src/dev/impl/DevToys/UI/Controls/ExpandableSettingHeaderControl.xaml.cs b/src/dev/impl/DevToys/UI/Controls/ExpandableSettingHeaderControl.xaml.cs
index a29c77988..58b74a58c 100644
--- a/src/dev/impl/DevToys/UI/Controls/ExpandableSettingHeaderControl.xaml.cs
+++ b/src/dev/impl/DevToys/UI/Controls/ExpandableSettingHeaderControl.xaml.cs
@@ -59,7 +59,9 @@ namespace DevToys.UI.Controls
private void MainPanel_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (e.NewSize.Width == e.PreviousSize.Width || ActionableElement == null)
+ {
return;
+ }
if (ActionableElement.ActualWidth > e.NewSize.Width / 3)
{
diff --git a/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/CustomDelimiterChunker.cs b/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/CustomDelimiterChunker.cs
deleted file mode 100644
index 07a736c1f..000000000
--- a/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/CustomDelimiterChunker.cs
+++ /dev/null
@@ -1,81 +0,0 @@
-#nullable enable
-
-using DiffPlex;
-using System;
-using System.Collections.Generic;
-
-namespace DevToys.UI.Controls.FormattedTextBlock
-{
- public class CustomDelimiterChunker : IChunker
- {
- private readonly string[] _delimiters;
-
- public CustomDelimiterChunker(string[] delimiters)
- {
- if (delimiters is null || delimiters.Length == 0)
- {
- throw new ArgumentException($"{nameof(delimiters)} cannot be null or empty.", nameof(delimiters));
- }
-
- _delimiters = delimiters;
- }
-
- public string[] Chunk(string inputString)
- {
- var chunks = new List<string>();
- int begin = 0;
- for (int i = 0; i < inputString.Length; i++)
- {
- int delimiterFound = IndexOfAnySubString(inputString, _delimiters, i, out int delimiterLength);
- if (delimiterFound != -1)
- {
- string word = inputString.Substring(begin, i - begin);
- string delimiter = inputString.Substring(i, delimiterLength);
-
- if (!string.IsNullOrEmpty(word))
- {
- chunks.Add(word);
- }
-
- if (!string.IsNullOrEmpty(delimiter))
- {
- chunks.Add(delimiter);
- }
-
- begin = i + delimiterLength;
- i += delimiterLength - 1;
- }
- else if (i == inputString.Length - 1)
- {
- string lastWord = inputString.Substring(begin, inputString.Length - begin);
-
- if (!string.IsNullOrEmpty(lastWord))
- {
- chunks.Add(lastWord);
- }
- }
- }
-
- return chunks.ToArray();
- }
-
- private int IndexOfAnySubString(string str, string[] delimiters, int startIndex, out int delimiterLength)
- {
- int bestMatch = -1;
- delimiterLength = 0;
-
- for (int i = 0; i < delimiters.Length; i++)
- {
- string delimiter = delimiters[i];
- int index = str.IndexOf(delimiter, startIndex);
- if (index == startIndex && delimiter.Length > delimiterLength)
- {
- bestMatch = index;
- delimiterLength = delimiter.Length;
- }
- }
-
- return bestMatch;
- }
- }
-}
diff --git a/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/CustomWordChunker.cs b/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/CustomWordChunker.cs
deleted file mode 100644
index e3209f87c..000000000
--- a/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/CustomWordChunker.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-#nullable enable
-
-namespace DevToys.UI.Controls.FormattedTextBlock
-{
- internal sealed class CustomWordChunker : CustomDelimiterChunker
- {
- private static string[] WordSeparaters { get; }
- =
- {
- " ",
- "\t",
- "\r\n",
- "\r",
- "\n",
- ".",
- "(",
- ")",
- "{",
- "}",
- ",",
- "!",
- "?",
- ";"
- };
-
- /// <summary>
- /// Gets the default singleton instance of the chunker.
- /// </summary>
- public static CustomWordChunker Instance { get; } = new CustomWordChunker();
-
- public CustomWordChunker() : base(WordSeparaters)
- {
- }
- }
-}
diff --git a/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/FormattedTextBlock.xaml b/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/FormattedTextBlock.xaml
deleted file mode 100644
index 1e6f273a6..000000000
--- a/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/FormattedTextBlock.xaml
+++ /dev/null
@@ -1,165 +0,0 @@
-<UserControl
- x:Class="DevToys.UI.Controls.FormattedTextBlock.FormattedTextBlock"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="using:DevToys.UI.Controls.FormattedTextBlock"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d"
- d:DesignHeight="300"
- d:DesignWidth="400"
- SizeChanged="UserControl_SizeChanged">
-
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="*"/>
- </Grid.RowDefinitions>
-
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="*"/>
- <ColumnDefinition Width="Auto"/>
- </Grid.ColumnDefinitions>
-
- <VisualStateManager.VisualStateGroups>
- <VisualStateGroup x:Name="CommonStates">
- <VisualState x:Name="Disabled">
- <Storyboard>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundDisabled}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushDisabled}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundDisabled}"/>
- </ObjectAnimationUsingKeyFrames>
- </Storyboard>
- </VisualState>
- <VisualState x:Name="Normal"/>
- <VisualState x:Name="PointerOver">
- <Storyboard>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushPointerOver}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundPointerOver}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundPointerOver}"/>
- </ObjectAnimationUsingKeyFrames>
- </Storyboard>
- </VisualState>
- <VisualState x:Name="Focused">
- <Storyboard>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundFocused}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushFocused}"/>
- </ObjectAnimationUsingKeyFrames>
- <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
- <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundFocused}"/>
- </ObjectAnimationUsingKeyFrames>
- </Storyboard>
- </VisualState>
- </VisualStateGroup>
- </VisualStateManager.VisualStateGroups>
-
- <TextBlock
- x:Name="HeaderTextBlock"
- x:DeferLoadStrategy="Lazy"
- Grid.Row="0"
- Grid.Column="0"
- Text="{x:Bind Header}"
- Margin="{ThemeResource TextBoxTopHeaderMargin}"
- Style="{StaticResource SubTitleTextBlock}"
- TextWrapping="Wrap"
- VerticalAlignment="Bottom"
- Visibility="Collapsed">
- </TextBlock>
- <StackPanel
- x:Name="CommandsToolBar"
- Grid.Row="0"
- Grid.Column="1"
- Orientation="Horizontal"
- HorizontalAlignment="Right"
- Spacing="8"
- Margin="0,0,0,8">
- <Button
- x:Name="CopyButton"
- TabIndex="2"
- Click="CopyButton_Click">
- <StackPanel Orientation="Horizontal" Spacing="4">
- <FontIcon Glyph="&#xF32B;"/>
- <TextBlock VerticalAlignment="Center" Text="{Binding Instance.Common.Copy, Mode=OneTime, Source={StaticResource LanguageManager}}"/>
- </StackPanel>
- </Button>
- </StackPanel>
-
- <Border
- x:Name="BorderElement"
- Grid.Row="1"
- Grid.ColumnSpan="2"
- Background="{ThemeResource TextControlBackground}"
- BorderThickness="{ThemeResource TextControlBorderThemeThickness}"
- BorderBrush="{ThemeResource TextControlBorderBrush}"
- CornerRadius="4"
- MinHeight="{ThemeResource TextControlThemeMinHeight}"
- MinWidth="{ThemeResource TextControlThemeMinWidth}"/>
- <ScrollViewer
- x:Name="ContentElement"
- Grid.Row="1"
- Grid.ColumnSpan="2"
- AutomationProperties.AccessibilityView="Raw"
- HorizontalScrollBarVisibility="Auto"
- HorizontalScrollMode="Enabled"
- VerticalScrollBarVisibility="Auto"
- VerticalScrollMode="Enabled"
- IsHorizontalRailEnabled="true"
- IsVerticalRailEnabled="true"
- IsDeferredScrollingEnabled="false"
- IsTabStop="False"
- Margin="{ThemeResource TextControlBorderThemeThickness}"
- Padding="0"
- ZoomMode="Disabled">
- <Grid x:Name="RootGrid">
- <Grid.ColumnDefinitions>
- <ColumnDefinition x:Name="LineNumberColumnDefinition" Width="Auto"/>
- <ColumnDefinition x:Name="TextEditorColumnDefinition" Width="*"/>
- </Grid.ColumnDefinitions>
- <Canvas x:Name="LineHighlighterAndIndicatorCanvas" Grid.ColumnSpan="2">
- <Border
- x:Name="LineIndicator"
- BorderBrush="{StaticResource SystemControlForegroundAccentBrush}"
- Visibility="Collapsed"/>
- <Grid
- x:Name="LineHighlighter"
- Background="{ThemeResource SystemControlBackgroundListLowBrush}"
- Opacity="0.65"
- BorderThickness="0"
- Visibility="Collapsed"/>
- </Canvas>
- <StackPanel
- x:Name="LineNumberGrid"
- Grid.Column="0"
- Orientation="Vertical"
- HorizontalAlignment="Stretch"
- BorderThickness="0,0,0,0"
- BorderBrush="{ThemeResource SystemControlBackgroundTransparentRevealBorderBrush}"
- Margin="0,1,0,0"
- VerticalAlignment="Stretch"
- Spacing="0.6">
- </StackPanel>
- <RichTextBlock
- x:Name="RichTextBlock"
- Grid.Column="1"
- Padding="2,0,0,0"
- LineHeight="18.6"
- ManipulationMode="All"
- HorizontalAlignment="Stretch"
- VerticalAlignment="Stretch"/>
- </Grid>
- </ScrollViewer>
- </Grid>
-</UserControl>
diff --git a/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/FormattedTextBlock.xaml.cs b/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/FormattedTextBlock.xaml.cs
deleted file mode 100644
index aa6343dc1..000000000
--- a/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/FormattedTextBlock.xaml.cs
+++ /dev/null
@@ -1,625 +0,0 @@
-#nullable enable
-
-using ColorCode;
-using DevToys.Api.Core.Settings;
-using DevToys.Core;
-using DevToys.Core.Settings;
-using DiffPlex;
-using DiffPlex.Chunkers;
-using DiffPlex.DiffBuilder;
-using DiffPlex.DiffBuilder.Model;
-using Microsoft.Toolkit.Uwp.Helpers;
-using System;
-using System.Collections.Generic;
-using System.Text;
-using Windows.ApplicationModel.DataTransfer;
-using Windows.Foundation;
-using Windows.UI;
-using Windows.UI.Xaml;
-using Windows.UI.Xaml.Controls;
-using Windows.UI.Xaml.Documents;
-using Windows.UI.Xaml.Input;
-using Windows.UI.Xaml.Media;
-using Clipboard = Windows.ApplicationModel.DataTransfer.Clipboard;
-
-namespace DevToys.UI.Controls.FormattedTextBlock
-{
- public sealed partial class FormattedTextBlock : UserControl, IFormattedTextBlock
- {
- private readonly Dictionary<string, double> _miniRequisiteIntegerTextRenderingWidthCache = new();
- private readonly SolidColorBrush _lineNumberDarkModeForegroundBrush = new("#99EEEEEE".ToColor());
- private readonly SolidColorBrush _lineNumberLightModeForegroundBrush = new("#99000000".ToColor());
-
- private bool _showLineNumbers;
- private bool _highlightCurrentLine;
- private bool _loaded;
- private string? _document;
-
- public static readonly DependencyProperty SettingsProviderProperty
- = DependencyProperty.Register(
- nameof(SettingsProvider),
- typeof(ISettingsProvider),
- typeof(FormattedTextBlock),
- new PropertyMetadata(null, OnSettingsProviderPropertyChangedCallback));
-
- public ISettingsProvider? SettingsProvider
- {
- get => (ISettingsProvider?)GetValue(SettingsProviderProperty);
- set => SetValue(SettingsProviderProperty, value);
- }
-
- public static readonly DependencyProperty HeaderProperty
- = DependencyProperty.Register(
- nameof(Header),
- typeof(string),
- typeof(FormattedTextBlock),
- new PropertyMetadata(null));
-
- public string? Header
- {
- get => (string?)GetValue(HeaderProperty);
- set => SetValue(HeaderProperty, value);
- }
-
- public FormattedTextBlock()
- {
- InitializeComponent();
-
- RichTextBlock.Loaded += OnLoaded;
- RichTextBlock.SelectionChanged += OnSelectionChanged;
- RichTextBlock.SizeChanged += OnSizeChanged;
- RichTextBlock.AddHandler(PointerPressedEvent, new PointerEventHandler(OnPointerPressed), true);
- }
-
- public void SetText(string? text, ILanguage? language = null)
- {
- _document = text;
-
- RichTextBlock.Blocks.Clear();
- RichTextBlock.TextHighlighters.Clear();
-
- if (!string.IsNullOrEmpty(text))
- {
- if (language is not null)
- {
- var formatter = new RichTextBlockFormatter(ActualTheme);
- formatter.FormatRichTextBlock(text, language, RichTextBlock);
- }
- else
- {
- var p = new Paragraph();
- var r = new Run()
- {
- Text = text
- };
- p.Inlines.Add(r);
- RichTextBlock.Blocks.Add(p);
- }
- }
-
- ApplySettings();
- }
-
- public void SetInlineTextDiff(string? oldText, string? newText, bool lineDiff)
- {
- oldText ??= string.Empty;
- newText ??= string.Empty;
-
- var inlineDiffBuilder
- = new InlineDiffBuilder(new Differ());
-
- IChunker chunker;
- if (lineDiff)
- {
- chunker = LineChunker.Instance;
- }
- else
- {
- chunker = CustomWordChunker.Instance;
- }
-
- DiffPaneModel diffPaneModel
- = inlineDiffBuilder.BuildDiffModel(
- oldText,
- newText,
- ignoreWhitespace: false,
- ignoreCase: false,
- chunker);
-
- if (!diffPaneModel.HasDifferences)
- {
- _document = newText;
- var p = new Paragraph();
- var r = new Run()
- {
- Text = _document
- };
- p.Inlines.Add(r);
- RichTextBlock.Blocks.Clear();
- RichTextBlock.TextHighlighters.Clear();
- RichTextBlock.Blocks.Add(p);
- ApplySettings();
- return;
- }
- else
- {
- _document = DiffPaneModelToString(diffPaneModel, lineDiff);
- }
-
- var insertedTextLength = 0;
-
- var deletedHighlighter
- = new TextHighlighter()
- {
- Background = new SolidColorBrush(Colors.Red)
- };
- var insertedHighlighter
- = new TextHighlighter()
- {
- Background = new SolidColorBrush(Colors.Green)
- };
- var modifiedHighlighter
- = new TextHighlighter()
- {
- Background = new SolidColorBrush(Colors.Yellow)
- };
-
- for (int i = 0; i < diffPaneModel.Lines.Count; i++)
- {
- DiffPiece diffPiece = diffPaneModel.Lines[i];
-
- if (diffPiece.Type != ChangeType.Unchanged)
- {
- int startIndex = insertedTextLength;
-
- var textRange
- = new TextRange()
- {
- StartIndex = startIndex,
- Length = diffPiece.Text.Length
- };
-
- if (diffPiece.Type == ChangeType.Inserted)
- {
- insertedHighlighter.Ranges.Add(textRange);
- }
- else if (diffPiece.Type == ChangeType.Deleted)
- {
- deletedHighlighter.Ranges.Add(textRange);
- }
- else if (diffPiece.Type == ChangeType.Modified)
- {
- modifiedHighlighter.Ranges.Add(textRange);
- }
- }
-
- insertedTextLength += diffPiece.Text.Length;
- if (lineDiff)
- {
- insertedTextLength += "\r\n".Length;
- }
- }
-
- var documentParagraph = new Paragraph();
- var run = new Run()
- {
- Text = _document
- };
- documentParagraph.Inlines.Add(run);
- RichTextBlock.Blocks.Clear();
- RichTextBlock.TextHighlighters.Clear();
-
- RichTextBlock.TextHighlighters.Add(deletedHighlighter);
- RichTextBlock.TextHighlighters.Add(insertedHighlighter);
- RichTextBlock.TextHighlighters.Add(modifiedHighlighter);
- RichTextBlock.Blocks.Add(documentParagraph);
-
- ApplySettings();
- }
-
- protected override void OnApplyTemplate()
- {
- base.OnApplyTemplate();
-
- ContentElement.ViewChanged += OnContentScrollViewerViewChanged;
- ContentElement.SizeChanged += OnContentScrollViewerSizeChanged;
- ContentElement.ApplyTemplate();
-
- RootGrid.SizeChanged += OnRootGridSizeChanged;
- }
-
- private void ApplySettings()
- {
- ISettingsProvider? settingsProvider = SettingsProvider;
- if (settingsProvider is not null)
- {
- RichTextBlock.FontFamily = (FontFamily)Application.Current.Resources[settingsProvider.GetSetting(PredefinedSettings.TextEditorFont)];
- RichTextBlock.TextWrapping = settingsProvider.GetSetting(PredefinedSettings.TextEditorTextWrapping) ? TextWrapping.Wrap : TextWrapping.NoWrap;
- _showLineNumbers = settingsProvider.GetSetting(PredefinedSettings.TextEditorLineNumbers);
- _highlightCurrentLine = settingsProvider.GetSetting(PredefinedSettings.TextEditorHighlightCurrentLine);
-
- UpdateLayout();
-
- if (_showLineNumbers)
- {
- ShowLineNumbers();
- }
- else
- {
- HideLineNumbers();
- }
- }
- }
-
- private void ShowLineNumbers()
- {
- if (!_loaded)
- {
- return;
- }
-
- UpdateLineNumbersRendering();
-
- // Call UpdateLineHighlighterAndIndicator to adjust it's state
- UpdateLineHighlighterAndIndicator();
- }
-
- private void HideLineNumbers()
- {
- if (!_loaded)
- {
- return;
- }
-
- LineNumberGrid!.Children.Clear();
- LineNumberGrid.BorderThickness = new Thickness(0, 0, 0, 0);
- LineNumberGrid.Width = .0f;
-
- // Call UpdateLineHighlighterAndIndicator to adjust it's state
- // Since when line highlighter is disabled, we still show the line indicator when line numbers are showing
- UpdateLineHighlighterAndIndicator();
- }
-
- private void UpdateLineNumbersRendering()
- {
- if (!_loaded || !_showLineNumbers)
- {
- return;
- }
-
- LineNumberGrid!.Children.Clear();
-
- int lineCount = LineCount(_document);
-
- double minLineNumberTextRenderingWidth
- = CalculateMinimumRequisiteIntegerTextRenderingWidth(
- RichTextBlock.FontFamily,
- RichTextBlock.FontSize,
- lineCount.ToString().Length);
-
- double padding = RichTextBlock.FontSize / 2;
- Thickness lineNumberPadding = new(padding, 0, padding + 2, 1);
- //double lineHeight = RichTextBlock.LineHeight;
- double lineHeight = GetTextSize(RichTextBlock.FontFamily, RichTextBlock.FontSize, "1").Height;
- double lineNumberTextBlockHeight = lineHeight + RichTextBlock.Padding.Top + lineNumberPadding.Top;
- SolidColorBrush? lineNumberForeground = (ActualTheme == ElementTheme.Dark) ? _lineNumberDarkModeForegroundBrush : _lineNumberLightModeForegroundBrush;
-
- for (int i = 0; i < lineCount; i++)
- {
- int lineNumber = i + 1;
-
- var margin
- = new Thickness(
- lineNumberPadding.Left,
- lineNumberPadding.Top,
- lineNumberPadding.Right,
- lineNumberPadding.Bottom);
-
- var lineNumberBlock = new TextBlock()
- {
- Text = lineNumber.ToString(),
- // Height = lineNumberTextBlockHeight,
- // Width = minLineNumberTextRenderingWidth,
- Margin = margin,
- TextAlignment = TextAlignment.Right,
- HorizontalAlignment = HorizontalAlignment.Right,
- VerticalAlignment = VerticalAlignment.Top,
- HorizontalTextAlignment = TextAlignment.Right,
- Foreground = lineNumberForeground,
- FontFamily = RichTextBlock.FontFamily,
- FontSize = RichTextBlock.FontSize
- };
-
- LineNumberGrid!.Children.Add(lineNumberBlock);
- }
-
- LineNumberGrid!.BorderThickness = new Thickness(0, 0, 0.08 * lineHeight, 0);
- LineNumberGrid.Width = lineNumberPadding.Left + minLineNumberTextRenderingWidth + lineNumberPadding.Right;
- }
-
- private void UpdateLineHighlighterAndIndicator()
- {
- if (!_loaded)
- {
- return;
- }
-
- if (!_showLineNumbers && !_highlightCurrentLine)
- {
- LineHighlighter!.Visibility = Visibility.Collapsed;
- LineIndicator!.Visibility = Visibility.Collapsed;
- return;
- }
-
- TextPointer? anchorPoint = RichTextBlock.SelectionStart;
- if (anchorPoint is null)
- {
- anchorPoint = RichTextBlock.ContentStart!;
- Assumes.NotNull(anchorPoint, nameof(anchorPoint));
- }
-
- Rect selectionRect = anchorPoint.GetCharacterRect(anchorPoint.LogicalDirection);
-
- double singleLineHeight = GetSingleLineHeight();
- Thickness thickness = new Thickness(0.08 * singleLineHeight);
- double height = selectionRect.Height;
- bool selectedMultipleLines = RichTextBlock.SelectedText.IndexOfAny(new[] { '\n', '\r' }) > -1;
-
- // Just to make sure height is a positive number and not smaller than single line height
- if (height < singleLineHeight)
- {
- height = singleLineHeight;
- }
-
- // Show line highlighter rect when it is enabled when selection is single line only
- if (_highlightCurrentLine && !selectedMultipleLines)
- {
- LineHighlighter!.Height = height;
- LineHighlighter.Margin = new Thickness(0, selectionRect.Top, 0, 0);
- LineHighlighter.Width = Math.Clamp(RootGrid!.ActualWidth, 0, double.PositiveInfinity);
-
- LineHighlighter.Visibility = Visibility.Visible;
- }
- else
- {
- LineHighlighter!.Visibility = Visibility.Collapsed;
- }
-
- // Show line indicator when line numbers are enabled and when selection is single line only
- if (_showLineNumbers && !selectedMultipleLines)
- {
- LineIndicator!.Height = height;
- LineIndicator.Margin = new Thickness(0, selectionRect.Top, 0, 0);
- LineIndicator.BorderThickness = thickness;
- LineIndicator.Width = 0.1 * singleLineHeight;
-
- LineIndicator.Visibility = Visibility.Visible;
- }
- else
- {
- LineIndicator!.Visibility = Visibility.Collapsed;
- }
- }
-
- private double GetSingleLineHeight()
- {
- Rect rect = RichTextBlock.ContentStart.GetCharacterRect(LogicalDirection.Forward);
- return rect.Height <= 0 ? 1.35 * FontSize : rect.Height;
- }
-
- private void ResetRootGridClipping()
- {
- if (!_loaded || RootGrid is null)
- {
- return;
- }
-
- //RootGrid!.Clip = new RectangleGeometry
- //{
- // Rect = new Rect(
- // 0,
- // 0,
- // RootGrid.ActualWidth,
- // Math.Clamp(RootGrid.ActualHeight, .0f, double.PositiveInfinity))
- //};
- }
-
- /// <summary>
- /// Get minimum rendering width needed for displaying number text with certain length.
- /// Take length of 3 as example, it is going to iterate thru all possible combinations like:
- /// 111, 222, 333, 444 ... 999 to get minimum rendering length needed to display all of them (the largest width is the min here).
- /// For mono font text, the width is always the same for same length but for non-mono font text, it depends.
- /// Thus we need to calculate here to determine width needed for rendering integer number only text.
- /// </summary>
- /// <param name="fontFamily"></param>
- /// <param name="fontSize"></param>
- /// <param name="numberTextLength"></param>
- /// <returns></returns>
- private double CalculateMinimumRequisiteIntegerTextRenderingWidth(FontFamily fontFamily, double fontSize, int numberTextLength)
- {
- string? cacheKey = $"{fontFamily.Source}-{(int)fontSize}-{numberTextLength}";
-
- if (_miniRequisiteIntegerTextRenderingWidthCache.ContainsKey(cacheKey))
- {
- return _miniRequisiteIntegerTextRenderingWidthCache[cacheKey];
- }
-
- double minRequisiteWidth = 0;
-
- for (int i = 0; i < 10; i++)
- {
- string? str = new((char)('0' + i), numberTextLength);
- double width = GetTextSize(fontFamily, fontSize, str).Width;
- if (width > minRequisiteWidth)
- {
- minRequisiteWidth = width;
- }
- }
-
- _miniRequisiteIntegerTextRenderingWidthCache[cacheKey] = minRequisiteWidth;
- return minRequisiteWidth;
- }
-
- private TextBlock GetHeaderTextBlock()
- {
- return (TextBlock)(HeaderTextBlock ?? FindName(nameof(HeaderTextBlock)));
- }
-
- private void OnLoaded(object sender, RoutedEventArgs e)
- {
- _loaded = true;
-
- if (Header is not null)
- {
- GetHeaderTextBlock().Visibility = Visibility.Visible;
- }
-
- ResetRootGridClipping();
-
- UpdateLineHighlighterAndIndicator();
- if (_showLineNumbers)
- {
- ShowLineNumbers();
- }
- }
-
- private void OnSelectionChanged(object sender, RoutedEventArgs _)
- {
- UpdateLineHighlighterAndIndicator();
- }
-
- private void OnSizeChanged(object sender, SizeChangedEventArgs _)
- {
- UpdateLineHighlighterAndIndicator();
- }
-
- private void OnContentScrollViewerViewChanged(object sender, ScrollViewerViewChangedEventArgs _)
- {
- UpdateLineNumbersRendering();
- }
-
- private void OnContentScrollViewerSizeChanged(object sender, SizeChangedEventArgs _)
- {
- UpdateLineNumbersRendering();
- }
-
- private void OnPointerPressed(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
- {
- var point = RichTextBlock.GetPositionFromPoint(e.GetCurrentPoint(RichTextBlock).Position);
- RichTextBlock.Select(point, point);
- UpdateLineHighlighterAndIndicator();
- }
-
- private void SettingProvider_SettingChanged(object sender, SettingChangedEventArgs e)
- {
- ApplySettings();
- }
-
- private void OnRootGridSizeChanged(object sender, SizeChangedEventArgs _)
- {
- ResetRootGridClipping();
- }
-
- private void CopyButton_Click(object sender, RoutedEventArgs e)
- {
- if (string.IsNullOrWhiteSpace(_document))
- {
- return;
- }
-
- var data = new DataPackage
- {
- RequestedOperation = DataPackageOperation.Copy
- };
- data.SetText(_document);
-
- Clipboard.SetContent(data);
- }
-
- private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
- {
- if (e.NewSize.Width < CommandsToolBar.ActualWidth + 100)
- {
- CommandsToolBar.Visibility = Visibility.Collapsed;
- }
- else
- {
- CommandsToolBar.Visibility = Visibility.Visible;
- }
- }
-
- private static void OnSettingsProviderPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
- {
- ISettingsProvider? settingProvider = e.NewValue as ISettingsProvider;
- if (settingProvider is not null)
- {
- var textEditorCore = (FormattedTextBlock)d;
- settingProvider.SettingChanged += textEditorCore.SettingProvider_SettingChanged;
- textEditorCore.ApplySettings();
- }
- }
-
- private static Size GetTextSize(FontFamily font, double fontSize, string text)
- {
- var textBlock = new TextBlock
- {
- Text = text,
- FontFamily = font,
- FontSize = fontSize
- };
- textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
- return textBlock.DesiredSize;
- }
-
- private static int LineCount(string? text)
- {
- if (string.IsNullOrEmpty(text))
- {
- return 1;
- }
-
- int count = 1;
- int len = text!.Length;
- for (int i = 0; i != len; ++i)
- {
- switch (text[i])
- {
- case '\r':
- ++count;
- if (i + 1 != len && text[i + 1] == '\n')
- {
- ++i;
- }
- break;
-
- case '\n':
- // case '\v':
- // case '\f':
- // case '\u0085':
- // case '\u2028':
- // case '\u2029':
- ++count;
- break;
- }
- }
-
- return count;
- }
-
- private static string DiffPaneModelToString(DiffPaneModel diffPaneModel, bool lineDiff)
- {
- var stringBuilder = new StringBuilder();
-
- for (int i = 0; i < diffPaneModel.Lines.Count; i++)
- {
- stringBuilder.Append(diffPaneModel.Lines[i].Text);
- if (lineDiff)
- {
- stringBuilder.Append("\r\n");
- }
- }
-
- return stringBuilder.ToString();
- }
- }
-}
diff --git a/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/IFormattedTextBlock.cs b/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/IFormattedTextBlock.cs
deleted file mode 100644
index 3ed5b2681..000000000
--- a/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/IFormattedTextBlock.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-#nullable enable
-
-using ColorCode;
-
-namespace DevToys.UI.Controls.FormattedTextBlock
-{
- public interface IFormattedTextBlock
- {
- void SetText(string? text, ILanguage? language = null);
-
- void SetInlineTextDiff(string? oldText, string? newText, bool lineDiff);
- }
-}
diff --git a/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/Languages/Yaml.cs b/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/Languages/Yaml.cs
deleted file mode 100644
index 6328d00e5..000000000
--- a/src/dev/impl/DevToys/UI/Controls/FormattedTextBlock/Languages/Yaml.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-#nullable enable
-
-using ColorCode;
-using ColorCode.Common;
-using System.Collections.Generic;
-
-namespace DevToys.UI.Controls.FormattedTextBlock.Languages
-{
- internal sealed class Yaml : ILanguage
- {
- public string Id
- {
- get { return "yaml"; }
- }
-
- public string Name
- {
- get { return "YAML"; }
- }
-
- public string CssClassName
- {
- get { return "yaml"; }
- }
-
- public string FirstLinePattern
- {
- get
- {
- return null;
- }
- }
-
- public IList<LanguageRule> Rules
- {
- get
- {
- return new List<LanguageRule>
- {
- new LanguageRule(
- @"(#.*?)\r?$",
- new Dictionary<int, string>
- {
- { 1, ScopeName.Comment },
- }),
- new LanguageRule(
- @"'(?>[^\']*)'",
- new Dictionary<int, string>
- {
- { 0, ScopeName.String },
- }),
- new LanguageRule(
- @"""(?>[^\""]*)""",
- new Dictionary<int, string>
- {
- { 0, ScopeName.String },
- }),
- new LanguageRule(
- @"^[^:]+",
- new Dictionary<int, string>
- {
- { 0, ScopeName.Keyword },
- })
- };
- }
- }
-
- public bool HasAlias(string lang)
- {
- return false;
- }
-
- public override string ToString()
- {
- return Name;
- }
- }
-}
diff --git a/src/dev/impl/DevToys/UI/Controls/TextEditor/CommandHandlerResult.cs b/src/dev/impl/DevToys/UI/Controls/TextEditor/CommandHandlerResult.cs
deleted file mode 100644
index e3f32cabb..000000000
--- a/src/dev/impl/DevToys/UI/Controls/TextEditor/CommandHandlerResult.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-#nullable enable
-
-namespace DevToys.UI.Controls.TextEditor
-{
- public class CommandHandlerResult
- {
- public CommandHandlerResult(bool shouldHandle, bool shouldSwallow)
- {
- ShouldHandle = shouldHandle;
- ShouldSwallow = shouldSwallow;
- }
-
- /// <summary>
- /// "ShouldHandle == true" means the keyboard command event should be handled after execution
- /// Meaning you should set KeyRoutedEventArgs.Handled to true after execution
- /// All child OnKeyDown event will not be received and should not be triggered if it is true
- /// </summary>
- public bool ShouldHandle { get; }
-
- /// <summary>
- /// "ShouldSwallow == true" means the keyboard command event should not go to it's children
- /// Meaning you should not call base.OnKeyDown after execution
- /// All parent OnKeyDown event will not be received and should not be triggered if it is true
- /// </summary>
- public bool ShouldSwallow { get; }
- }
-}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/UI/Controls/TextEditor/ICommandHandler.cs b/src/dev/impl/DevToys/UI/Controls/TextEditor/ICommandHandler.cs
deleted file mode 100644
index d402e72cd..000000000
--- a/src/dev/impl/DevToys/UI/Controls/TextEditor/ICommandHandler.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-#nullable enable
-
-namespace DevToys.UI.Controls.TextEditor
-{
- public interface ICommandHandler<in T>
- {
- CommandHandlerResult Handle(T args);
- }
-}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/UI/Controls/TextEditor/IKeyboardCommand.cs b/src/dev/impl/DevToys/UI/Controls/TextEditor/IKeyboardCommand.cs
deleted file mode 100644
index 2f4fa6e8b..000000000
--- a/src/dev/impl/DevToys/UI/Controls/TextEditor/IKeyboardCommand.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-#nullable enable
-
-using Windows.System;
-
-namespace DevToys.UI.Controls.TextEditor
-{
- public interface IKeyboardCommand<T>
- {
- bool Hit(bool ctrlDown, bool altDown, bool shiftDown, VirtualKey key);
-
- bool ShouldExecute(IKeyboardCommand<T>? lastCommand);
-
- bool ShouldHandleAfterExecution();
-
- bool ShouldSwallowAfterExecution();
-
- void Execute(T args);
- }
-}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/UI/Controls/TextEditor/KeyboardCommand.cs b/src/dev/impl/DevToys/UI/Controls/TextEditor/KeyboardCommand.cs
deleted file mode 100644
index 165975d2e..000000000
--- a/src/dev/impl/DevToys/UI/Controls/TextEditor/KeyboardCommand.cs
+++ /dev/null
@@ -1,112 +0,0 @@
-#nullable enable
-
-using System;
-using System.Collections.Generic;
-using Windows.System;
-
-namespace DevToys.UI.Controls.TextEditor
-{
- public class KeyboardCommand<T> : IKeyboardCommand<T>
- {
- private static readonly TimeSpan ConsecutiveHitsInterval = TimeSpan.FromMilliseconds(500);
-
- private readonly bool _ctrl;
- private readonly bool _alt;
- private readonly bool _shift;
- private readonly IList<VirtualKey> _keys;
- private readonly Action<T>? _action;
- private readonly bool _shouldHandle;
- private readonly bool _shouldSwallow;
- private readonly int _requiredHits;
- private int _hits;
- private DateTime _lastHitTimestamp;
-
- public KeyboardCommand(
- VirtualKey key,
- Action<T>? action,
- bool shouldHandle = true,
- bool shouldSwallow = true) :
- this(false, false, false, key, action, shouldHandle, shouldSwallow)
- {
- }
-
- public KeyboardCommand(
- bool ctrlDown,
- bool altDown,
- bool shiftDown,
- VirtualKey key,
- Action<T>? action,
- bool shouldHandle = true,
- bool shouldSwallow = true,
- int requiredHits = 1) :
- this(ctrlDown, altDown, shiftDown, new List<VirtualKey>() { key }, action, shouldHandle, shouldSwallow, requiredHits)
- {
- }
-
- public KeyboardCommand(
- bool ctrlDown,
- bool altDown,
- bool shiftDown,
- IList<VirtualKey> keys,
- Action<T>? action,
- bool shouldHandle,
- bool shouldSwallow,
- int requiredHits = 1)
- {
- _ctrl = ctrlDown;
- _alt = altDown;
- _shift = shiftDown;
- _keys = keys ?? new List<VirtualKey>();
- _action = action;
- _shouldHandle = shouldHandle;
- _shouldSwallow = shouldSwallow;
- _requiredHits = requiredHits;
- _hits = 0;
- _lastHitTimestamp = DateTime.MinValue;
- }
-
- public bool Hit(bool ctrlDown, bool altDown, bool shiftDown, VirtualKey key)
- {
- return _ctrl == ctrlDown && _alt == altDown && _shift == shiftDown && _keys.Contains(key);
- }
-
- public bool ShouldExecute(IKeyboardCommand<T>? lastCommand)
- {
- DateTime now = DateTime.UtcNow;
-
- if (lastCommand == this && now - _lastHitTimestamp < ConsecutiveHitsInterval)
- {
- _hits++;
- }
- else
- {
- _hits = 1;
- }
-
- _lastHitTimestamp = now;
-
- if (_hits >= _requiredHits)
- {
- _hits = 0;
- return true;
- }
-
- return false;
- }
-
- public bool ShouldHandleAfterExecution()
- {
- return _shouldHandle;
- }
-
- public bool ShouldSwallowAfterExecution()
- {
- return _shouldSwallow;
- }
-
- public void Execute(T args)
- {
- _action?.Invoke(args);
- }
- }
-}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/UI/Controls/TextEditor/KeyboardCommandHandler.cs b/src/dev/impl/DevToys/UI/Controls/TextEditor/KeyboardCommandHandler.cs
deleted file mode 100644
index 1477536e9..000000000
--- a/src/dev/impl/DevToys/UI/Controls/TextEditor/KeyboardCommandHandler.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-#nullable enable
-
-using System.Collections.Generic;
-using Windows.System;
-using Windows.UI.Core;
-using Windows.UI.Xaml;
-using Windows.UI.Xaml.Input;
-
-namespace DevToys.UI.Controls.TextEditor
-{
- public class KeyboardCommandHandler : ICommandHandler<KeyRoutedEventArgs>
- {
- public readonly ICollection<IKeyboardCommand<KeyRoutedEventArgs>> Commands;
-
- private IKeyboardCommand<KeyRoutedEventArgs>? _lastCommand;
-
- public KeyboardCommandHandler(ICollection<IKeyboardCommand<KeyRoutedEventArgs>> commands)
- {
- Commands = commands;
- }
-
- public CommandHandlerResult Handle(KeyRoutedEventArgs args)
- {
- var ctrlDown = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
- var altDown = Window.Current.CoreWindow.GetKeyState(VirtualKey.Menu).HasFlag(CoreVirtualKeyStates.Down);
- var shiftDown = Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down);
- var shouldHandle = false;
- var shouldSwallow = false;
-
- foreach (var command in Commands)
- {
- if (command.Hit(ctrlDown, altDown, shiftDown, args.Key))
- {
- if (command.ShouldExecute(_lastCommand))
- {
- command.Execute(args);
- }
-
- if (command.ShouldSwallowAfterExecution())
- {
- shouldSwallow = true;
- }
-
- if (command.ShouldHandleAfterExecution())
- {
- shouldHandle = true;
- }
-
- _lastCommand = command;
- break;
- }
- }
-
- if (!shouldHandle)
- {
- _lastCommand = null;
- }
-
- return new CommandHandlerResult(shouldHandle, shouldSwallow);
- }
- }
-}
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/UI/Controls/TextEditor/RtfBuilder.cs b/src/dev/impl/DevToys/UI/Controls/TextEditor/RtfBuilder.cs
deleted file mode 100644
index 7a07d0460..000000000
--- a/src/dev/impl/DevToys/UI/Controls/TextEditor/RtfBuilder.cs
+++ /dev/null
@@ -1,270 +0,0 @@
-#nullable enable
-
-using System.Collections.Generic;
-using System.Text;
-using Windows.UI;
-using Windows.UI.Xaml;
-
-namespace DevToys.UI.Controls.TextEditor
-{
- internal sealed class RtfBuilder
- {
- private Dictionary<Color, int> colorNbs;
- private Dictionary<string, int> fontNbs;
-
- private StringBuilder sbColorTbl;
- private StringBuilder sbFontTbl;
- private StringBuilder sbText;
-
- private string defaultFontName;
-
- public RtfBuilder(ElementTheme theme, string fontName)
- {
- colorNbs = new Dictionary<Color, int>();
- fontNbs = new Dictionary<string, int>();
-
- sbColorTbl = new StringBuilder();
- sbFontTbl = new StringBuilder();
- sbText = new StringBuilder();
-
- defaultFontName = fontName;
- }
-
- public string DefaultFontName
- {
- get
- {
- return defaultFontName;
- }
-
- set
- {
- defaultFontName = value;
- }
- }
-
- public void Append(string text, RtfFormat format, Color? color, Color? backgroundColor)
- {
- AppendIntern(text, format, color, backgroundColor, true, null, false);
- }
-
- public void Clear()
- {
- colorNbs.Clear();
- fontNbs.Clear();
-
- sbColorTbl.Clear();
- sbFontTbl.Clear();
-
- sbText.Clear();
-
- AddFont(DefaultFontName);
- }
-
- public string GetRtf()
- {
- StringBuilder result = new StringBuilder();
-
- //header
- result.Append(@"{\rtf1\ansi\ansicpg1252\deff0\deflang1031");
-
- //font table
- result.Append(@"{\fonttbl");
- //defaultFont
- result.Append(FontToRtf(defaultFontName, 0));
- //user fonts
- if (fontNbs.Count > 0)
- {
- result.Append(sbFontTbl.ToString());
- }
- result.Append("}");
-
- //color table
- result.Append(@"{\colortbl;");
- //user colors
- if (colorNbs.Count > 0)
- {
- result.Append(sbColorTbl.ToString());
- }
- result.Append("}");
-
- //text
- result.Append(sbText.ToString());
-
- //headerclose
- result.Append("}");
-
- return result.ToString();
- }
-
- public override string ToString()
- {
- return GetRtf();
- }
-
- private string EscapeText(string text)
- {
- if (string.IsNullOrEmpty(text))
- {
- return string.Empty;
- }
- else
- {
- text = text.Replace(@"\", @"\\");
- text = text.Replace(@"{", @"\{");
- text = text.Replace(@"}", @"\}");
- text = text.Replace("\r\n", @"\par ");
-
- return text;
- }
- }
-
- private int AddColor(Color? color)
- {
- if (!color.HasValue)
- {
- //Default Font
- return 0;
- }
- else
- {
- if (colorNbs.ContainsKey(color.Value))
- {
- // Font exists already in Fonttable
- return colorNbs[color.Value];
- }
- else
- {
- //New Font
- int nb = colorNbs.Count + 2;
-
- colorNbs.Add(color.Value, nb);
- sbColorTbl.AppendFormat(ColorToRtf(color.Value));
-
- return nb;
- }
- }
- }
-
- private int AddFont(string font)
- {
- if (defaultFontName == font)
- {
- //Default Font
- return 0;
- }
- else
- {
- if (fontNbs.ContainsKey(font))
- {
- //Font exists alread in font table
- return fontNbs[font];
- }
- else
- {
- //new font
- int fontNb = fontNbs.Count + 1;
-
- sbFontTbl.Append(FontToRtf(font, fontNb));
- fontNbs.Add(font, fontNb);
-
- return fontNb;
- }
- }
- }
-
- private string ColorToRtf(Color color)
- {
- return string.Format(@"\red{0}\green{1}\blue{2};",
- color.R, color.G, color.B);
- }
-
- private string FontToRtf(string font, int nb)
- {
- return string.Format(@"{{\f{1}\fnil\fcharset0 {0}}}", font, nb);
- }
-
- private void AppendIntern(string text, RtfFormat format, Color? color, Color? backgroundColor, bool useColor, string? font, bool newLine)
- {
- //get color nb
- int colorNb = 1;
- if (useColor)
- {
- colorNb = AddColor(color);
- }
-
- int backgroundColorNb = 0;
- if (useColor)
- {
- backgroundColorNb = AddColor(backgroundColor);
- }
-
- //get font
- int fontNb = 0;
- if (font != null)
- {
- fontNb = AddFont(font);
- }
-
- //set formats
- if ((format & RtfFormat.Bold) == RtfFormat.Bold)
- {
- sbText.Append(@"\b");
- }
- if ((format & RtfFormat.Italic) == RtfFormat.Italic)
- {
- sbText.Append(@"\i");
- }
- if ((format & RtfFormat.Underline) == RtfFormat.Underline)
- {
- sbText.Append(@"\ul");
- }
- if ((format & RtfFormat.Strikeout) == RtfFormat.Strikeout)
- {
- sbText.Append(@"\strike");
- }
-
- //set color
- sbText.AppendFormat(@"\cf{0}", colorNb);
-
- //set background color
- sbText.AppendFormat(@"\highlight{0}", backgroundColorNb);
-
- //set font
- sbText.AppendFormat(@"\f{0}", fontNb);
-
- //add text
- sbText.Append(EscapeText(text));
-
- //restore to default color
- sbText.Append(@"\cf1");
-
- //restore to default font
- sbText.Append(@"\f0");
-
- //remove formats
- if ((format & RtfFormat.Bold) == RtfFormat.Bold)
- {
- sbText.Append(@"\b0");
- }
- if ((format & RtfFormat.Italic) == RtfFormat.Italic)
- {
- sbText.Append(@"\i0");
- }
- if ((format & RtfFormat.Underline) == RtfFormat.Underline)
- {
- sbText.Append(@"\ul0");
- }
- if ((format & RtfFormat.Strikeout) == RtfFormat.Strikeout)
- {
- sbText.Append(@"\strike0");
- }
-
- //insert new line
- if (newLine)
- {
- sbText.Append(@"\par ");
- }
- }
- }
-}
diff --git a/src/dev/impl/DevToys/UI/Controls/TextEditor/RtfFormat.cs b/src/dev/impl/DevToys/UI/Controls/TextEditor/RtfFormat.cs
deleted file mode 100644
index 1bacea332..000000000
--- a/src/dev/impl/DevToys/UI/Controls/TextEditor/RtfFormat.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-#nullable enable
-
-using System;
-
-namespace DevToys.UI.Controls.TextEditor
-{
- [Flags]
- public enum RtfFormat
- {
- Normal = 0,
- Bold = 1,
- Italic = 2,
- Underline = 4,
- Strikeout = 8
- }
-}
diff --git a/src/dev/impl/DevToys/UI/Controls/TextEditor/TextEditor.xaml b/src/dev/impl/DevToys/UI/Controls/TextEditor/TextEditor.xaml
deleted file mode 100644
index d8a59e3ca..000000000
--- a/src/dev/impl/DevToys/UI/Controls/TextEditor/TextEditor.xaml
+++ /dev/null
@@ -1,76 +0,0 @@
-<UserControl
- x:Class="DevToys.UI.Controls.TextEditor.TextEditor"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:DevToys="using:DevToys"
- xmlns:local="using:DevToys.UI.Controls.TextEditor"
- mc:Ignorable="d"
- d:DesignHeight="300"
- d:DesignWidth="400"
- SizeChanged="UserControl_SizeChanged">
- <UserControl.Resources>
- <DevToys:LanguageManager x:Key="LanguageManager"/>
- </UserControl.Resources>
-
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="*"/>
- </Grid.RowDefinitions>
-
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="*"/>
- <ColumnDefinition Width="Auto"/>
- </Grid.ColumnDefinitions>
-
- <TextBlock
- x:Name="HeaderTextBlock"
- Grid.Row="0"
- Grid.Column="0"
- Text="{x:Bind Header}"
- Margin="{ThemeResource TextBoxTopHeaderMargin}"
- Style="{StaticResource SubTitleTextBlock}"
- FontFamily="{ThemeResource ContentControlThemeFontFamily}"
- TextWrapping="Wrap"
- VerticalAlignment="Bottom">
- </TextBlock>
- <StackPanel
- x:Name="CommandsToolBar"
- Grid.Row="0"
- Grid.Column="1"
- Orientation="Horizontal"
- HorizontalAlignment="Right"
- Spacing="8"
- Margin="0,0,0,8">
- <Button
- x:Name="PasteButton"
- Click="OnPasteButtonClick">
- <StackPanel Orientation="Horizontal" Spacing="4">
- <FontIcon Glyph="&#xF2D5;"/>
- <TextBlock VerticalAlignment="Center" Text="{Binding Instance.Common.Paste, Mode=OneTime, Source={StaticResource LanguageManager}}"/>
- </StackPanel>
- </Button>
- <Button
- x:Name="OpenFileButton"
- ToolTipService.ToolTip="{Binding Instance.Common.OpenFile, Mode=OneTime, Source={StaticResource LanguageManager}}"
- Click="OnOpenFileButtonClick">
- <FontIcon Glyph="&#xF378;"/>
- </Button>
- <Button
- x:Name="ClearButton"
- ToolTipService.ToolTip="{Binding Instance.Common.Clear, Mode=OneTime, Source={StaticResource LanguageManager}}"
- Click="OnClearButtonClick">
- <FontIcon Glyph="&#xF369;"/>
- </Button>
- </StackPanel>
-
- <local:TextEditorCore
- x:Name="TextEditorCore"
- Grid.Row="1"
- Grid.ColumnSpan="2"
- SettingsProvider="{x:Bind SettingsProvider}"
- Text="{x:Bind Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
- </Grid>
-</UserControl>
diff --git a/src/dev/impl/DevToys/UI/Controls/TextEditor/TextEditor.xaml.cs b/src/dev/impl/DevToys/UI/Controls/TextEditor/TextEditor.xaml.cs
deleted file mode 100644
index 4c5b540ba..000000000
--- a/src/dev/impl/DevToys/UI/Controls/TextEditor/TextEditor.xaml.cs
+++ /dev/null
@@ -1,111 +0,0 @@
-#nullable enable
-
-using DevToys.Api.Core.Settings;
-using System;
-using Windows.Storage;
-using Windows.Storage.Pickers;
-using Windows.UI.Xaml;
-using Windows.UI.Xaml.Controls;
-
-namespace DevToys.UI.Controls.TextEditor
-{
- public sealed partial class TextEditor : UserControl
- {
- public static readonly DependencyProperty SettingsProviderProperty
- = DependencyProperty.Register(
- nameof(SettingsProvider),
- typeof(ISettingsProvider),
- typeof(TextEditor),
- new PropertyMetadata(null));
-
- public ISettingsProvider? SettingsProvider
- {
- get => (ISettingsProvider?)GetValue(SettingsProviderProperty);
- set => SetValue(SettingsProviderProperty, value);
- }
-
- public static readonly DependencyProperty TextProperty
- = DependencyProperty.Register(
- nameof(Text),
- typeof(string),
- typeof(TextEditor),
- new PropertyMetadata(null));
-
- public string? Text
- {
- get => (string?)GetValue(TextProperty);
- set => SetValue(TextProperty, value);
- }
-
- public static readonly DependencyProperty HeaderProperty
- = DependencyProperty.Register(
- nameof(Header),
- typeof(string),
- typeof(TextEditor),
- new PropertyMetadata(null));
-
- public string? Header
- {
- get => (string?)GetValue(HeaderProperty);
- set => SetValue(HeaderProperty, value);
- }
-
- public TextEditor()
- {
- this.InitializeComponent();
- }
-
- private void OnPasteButtonClick(object sender, RoutedEventArgs e)
- {
- TextEditorCore.PasteCommand.Execute(null);
- }
-
- private async void OnOpenFileButtonClick(object sender, RoutedEventArgs e)
- {
- var filePicker = new FileOpenPicker
- {
- ViewMode = PickerViewMode.List,
- SuggestedStartLocation = PickerLocationId.ComputerFolder
- };
-
- filePicker.FileTypeFilter.Add("*");
-
- StorageFile file = await filePicker.PickSingleFileAsync();
- if (file is not null)
- {
- try
- {
- string text = await FileIO.ReadTextAsync(file);
- await Dispatcher.RunAsync(
- Windows.UI.Core.CoreDispatcherPriority.Normal,
- () =>
- {
- Text = text;
- TextEditorCore.Document.Selection.StartPosition = 0;
- });
- }
- catch
- {
- // TODO: Show a modal explaining the user that we can't read the file. Maybe it's not a text file.
- }
- }
- }
-
- private void OnClearButtonClick(object sender, RoutedEventArgs e)
- {
- Text = string.Empty;
- }
-
- private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
- {
- if (e.NewSize.Width < CommandsToolBar.ActualWidth + 100)
- {
- CommandsToolBar.Visibility = Visibility.Collapsed;
- }
- else
- {
- CommandsToolBar.Visibility = Visibility.Visible;
- }
- }
- }
-}
diff --git a/src/dev/impl/DevToys/UI/Controls/TextEditor/TextEditorCore.cs b/src/dev/impl/DevToys/UI/Controls/TextEditor/TextEditorCore.cs
deleted file mode 100644
index 75420ffff..000000000
--- a/src/dev/impl/DevToys/UI/Controls/TextEditor/TextEditorCore.cs
+++ /dev/null
@@ -1,1071 +0,0 @@
-#nullable enable
-
-using DevToys.UI.Extensions;
-using DevToys.Core;
-using DevToys.Core.Settings;
-using DevToys.Core.Threading;
-using DiffPlex.DiffBuilder;
-using Microsoft.Toolkit.Mvvm.Input;
-using Microsoft.Toolkit.Uwp.Helpers;
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Windows.ApplicationModel.DataTransfer;
-using Windows.Foundation;
-using Windows.System;
-using Windows.UI.Text;
-using Windows.UI.Xaml;
-using Windows.UI.Xaml.Controls;
-using Windows.UI.Xaml.Controls.Primitives;
-using Windows.UI.Xaml.Input;
-using Windows.UI.Xaml.Media;
-using DevToys.Api.Core.Settings;
-using Clipboard = Windows.ApplicationModel.DataTransfer.Clipboard;
-
-namespace DevToys.UI.Controls.TextEditor
-{
- [TemplatePart(Name = ContentElementName, Type = typeof(ScrollViewer))]
- [TemplatePart(Name = RootGridName, Type = typeof(Grid))]
- [TemplatePart(Name = LineNumberCanvasName, Type = typeof(Canvas))]
- [TemplatePart(Name = LineNumberGridName, Type = typeof(Grid))]
- [TemplatePart(Name = LineHighlighterAndIndicatorCanvasName, Type = typeof(Canvas))]
- [TemplatePart(Name = LineHighlighterName, Type = typeof(Grid))]
- [TemplatePart(Name = LineIndicatorName, Type = typeof(Border))]
- public sealed class TextEditorCore : RichEditBox
- {
- private const string ContentElementName = "ContentElement";
- private const string RootGridName = "RootGrid";
- private const string LineNumberCanvasName = "LineNumberCanvas";
- private const string LineNumberGridName = "LineNumberGrid";
- private const string ContentScrollViewerVerticalScrollBarName = "VerticalScrollBar";
- private const string LineHighlighterAndIndicatorCanvasName = "LineHighlighterAndIndicatorCanvas";
- private const string LineHighlighterName = "LineHighlighter";
- private const string LineIndicatorName = "LineIndicator";
-
- private const string RichEditBoxDefaultLineEnding = "\r\n";
-
- private readonly InlineDiffBuilder _inlineDiffBuilder = new InlineDiffBuilder();
- private readonly IList<TextBlock> _renderedLineNumberBlocks = new List<TextBlock>();
- private readonly Dictionary<string, double> _miniRequisiteIntegerTextRenderingWidthCache = new();
- private readonly SolidColorBrush _lineNumberDarkModeForegroundBrush = new("#99EEEEEE".ToColor());
- private readonly SolidColorBrush _lineNumberLightModeForegroundBrush = new("#99000000".ToColor());
- private readonly ICommandHandler<KeyRoutedEventArgs> _keyboardCommandHandler;
-
- private CancellationTokenSource _formattingCancellationTokenSource = new CancellationTokenSource();
- private Border? _lineIndicator;
- private Canvas? _lineHighlighterAndIndicatorCanvas;
- private Canvas? _lineNumberCanvas;
- private Grid? _lineHighlighter;
- private Grid? _lineNumberGrid;
- private Grid? _rootGrid;
- private ScrollBar? _contentScrollViewerVerticalScrollBar;
- private ScrollViewer? _contentScrollViewer;
- private bool _showLineNumbers;
- private bool _highlightCurrentLine;
- private bool _loaded;
- private bool _isTextPendingUpdate;
- private bool _isDocumentLinesCachePendingUpdate = true;
- private bool _isSyntaxColorizationPendingUpdate = true;
- private bool _isSyntaxColorizationUpdateInProgress;
- private string[] _documentLinesCache = Array.Empty<string>(); // internal copy of the active document text in array format
- private string _document = string.Empty; // internal copy of the active document text
- private int _textSelectionStartPosition = 0;
- private int _textSelectionEndPosition = 0;
-
- public static readonly DependencyProperty SettingsProviderProperty
- = DependencyProperty.Register(
- nameof(SettingsProvider),
- typeof(ISettingsProvider),
- typeof(TextEditorCore),
- new PropertyMetadata(null, OnSettingsProviderPropertyChangedCallback));
-
- public ISettingsProvider? SettingsProvider
- {
- get => (ISettingsProvider?)GetValue(SettingsProviderProperty);
- set => SetValue(SettingsProviderProperty, value);
- }
-
- public static readonly DependencyProperty TextProperty
- = DependencyProperty.Register(
- nameof(Text),
- typeof(string),
- typeof(TextEditorCore),
- new PropertyMetadata(null, OnTextPropertyChangedCallback));
-
- public string? Text
- {
- get => (string?)GetValue(TextProperty);
- set => SetValue(TextProperty, value);
- }
-
- public TextEditorCore()
- {
- DefaultStyleKey = typeof(TextEditorCore);
-
- DataContext = this;
- IsSpellCheckEnabled = false;
- SelectionFlyout = null;
- HorizontalAlignment = HorizontalAlignment.Stretch;
- VerticalAlignment = VerticalAlignment.Stretch;
- HandwritingView.BorderThickness = new Thickness(0);
-
- Loaded += OnLoaded;
- SelectionChanged += OnSelectionChanged;
- SizeChanged += OnSizeChanged;
- TextChanged += OnTextChanged;
- TextChanging += OnTextChanging;
- SelectionChanging += OnSelectionChanging;
- Paste += OnPaste;
-
- CutCommand = new RelayCommand(ExecuteCutCommand, CanExecuteCutCommand);
- CopyCommand = new RelayCommand(ExecuteCopyCommand, CanExecuteCopyCommand);
- PasteCommand = new AsyncRelayCommand(ExecutePasteCommandAsync, CanExecutePasteCommand);
- DeleteCommand = new RelayCommand(ExecuteDeleteCommand, CanExecuteDeleteCommand);
- UndoCommand = new RelayCommand(ExecuteUndoCommand, CanExecuteUndoCommand);
- RedoCommand = new RelayCommand(ExecuteRedoCommand, CanExecuteRedoCommand);
- SelectAllCommand = new RelayCommand(ExecuteSelectAllCommand, CanExecuteSelectAllCommand);
-
- var swallowedKeys = new List<VirtualKey>()
- {
- VirtualKey.B, VirtualKey.I, VirtualKey.U, VirtualKey.Tab,
- VirtualKey.Number1, VirtualKey.Number2, VirtualKey.Number3,
- VirtualKey.Number4, VirtualKey.Number5, VirtualKey.Number6,
- VirtualKey.Number7, VirtualKey.Number8, VirtualKey.Number9,
- VirtualKey.F3,
- };
-
- _keyboardCommandHandler
- = new KeyboardCommandHandler(new List<IKeyboardCommand<KeyRoutedEventArgs>>
- {
- // By default, RichEditBox insert '\v' when user hit "Shift + Enter"
- // This should be converted to '\r' to match same behaviour as single "Enter"
- new KeyboardCommand<KeyRoutedEventArgs>(false, false, true, VirtualKey.Enter, (args) => EnterWithAutoIndentation()),
- new KeyboardCommand<KeyRoutedEventArgs>(VirtualKey.Enter, (args) => EnterWithAutoIndentation()),
- // Disable RichEditBox default shortcuts (Bold, Underline, Italic)
- // https://docs.microsoft.com/en-us/windows/desktop/controls/about-rich-edit-controls
- new KeyboardCommand<KeyRoutedEventArgs>(true, false, false, swallowedKeys, null, shouldHandle: false, shouldSwallow: true),
- new KeyboardCommand<KeyRoutedEventArgs>(true, false, true, swallowedKeys, null, shouldHandle: false, shouldSwallow: true),
- new KeyboardCommand<KeyRoutedEventArgs>(true, false, true, (VirtualKey)187, null, shouldHandle: false, shouldSwallow: true), // (VirtualKey)187: =
- new KeyboardCommand<KeyRoutedEventArgs>(true, false, true, VirtualKey.L, null, shouldHandle: false, shouldSwallow: true),
- new KeyboardCommand<KeyRoutedEventArgs>(false, false, true, VirtualKey.F3, null, shouldHandle: false, shouldSwallow: true),
- });
- }
-
- #region CutCommand
-
- public static readonly DependencyProperty CutCommandProperty
- = DependencyProperty.Register(
- nameof(CutCommand),
- typeof(IRelayCommand),
- typeof(TextEditorCore),
- new PropertyMetadata(null));
-
- public IRelayCommand CutCommand
- {
- get => (IRelayCommand)GetValue(CutCommandProperty);
- private set => SetValue(CutCommandProperty, value);
- }
-
- private bool CanExecuteCutCommand()
- {
- return Document.Selection.Length != 0 && IsEnabled && Document.CanCopy();
- }
-
- private void ExecuteCutCommand()
- {
- Document.Selection.Cut();
- }
-
- #endregion
-
- #region CopyCommand
-
- public static readonly DependencyProperty CopyCommandProperty
- = DependencyProperty.Register(
- nameof(CopyCommand),
- typeof(IRelayCommand),
- typeof(TextEditorCore),
- new PropertyMetadata(null));
-
- public IRelayCommand CopyCommand
- {
- get => (IRelayCommand)GetValue(CopyCommandProperty);
- private set => SetValue(CopyCommandProperty, value);
- }
-
- private bool CanExecuteCopyCommand()
- {
- return Document.Selection.Length != 0 && IsEnabled && Document.CanCopy();
- }
-
- private void ExecuteCopyCommand()
- {
- Document.Selection.Copy();
- }
-
- #endregion
-
- #region PasteCommand
-
- public static readonly DependencyProperty PasteCommandProperty
- = DependencyProperty.Register(
- nameof(PasteCommand),
- typeof(IAsyncRelayCommand),
- typeof(TextEditorCore),
- new PropertyMetadata(null));
-
- public IAsyncRelayCommand PasteCommand
- {
- get => (IAsyncRelayCommand)GetValue(PasteCommandProperty);
- private set => SetValue(PasteCommandProperty, value);
- }
-
- private bool CanExecutePasteCommand()
- {
- return Document.CanPaste() && IsEnabled;
- }
-
- private async Task ExecutePasteCommandAsync()
- {
- await PastePlainTextFromWindowsClipboardAsync(null);
- }
-
- #endregion
-
- #region DeleteCommand
-
- public static readonly DependencyProperty DeleteCommandProperty
- = DependencyProperty.Register(
- nameof(DeleteCommand),
- typeof(IRelayCommand),
- typeof(TextEditorCore),
- new PropertyMetadata(null));
-
- public IRelayCommand DeleteCommand
- {
- get => (IRelayCommand)GetValue(DeleteCommandProperty);
- private set => SetValue(DeleteCommandProperty, value);
- }
-
- private bool CanExecuteDeleteCommand()
- {
- return Document.Selection.Length != 0 && IsEnabled && !IsReadOnly;
- }
-
- private void ExecuteDeleteCommand()
- {
- Document.BeginUndoGroup();
- Document.Selection.SetText(TextSetOptions.None, string.Empty);
- Document.EndUndoGroup();
- }
-
- #endregion
-
- #region UndoCommand
-
- public static readonly DependencyProperty UndoCommandProperty
- = DependencyProperty.Register(
- nameof(UndoCommand),
- typeof(IRelayCommand),
- typeof(TextEditorCore),
- new PropertyMetadata(null));
-
- public IRelayCommand UndoCommand
- {
- get => (IRelayCommand)GetValue(UndoCommandProperty);
- private set => SetValue(UndoCommandProperty, value);
- }
-
- private bool CanExecuteUndoCommand()
- {
- return Document.CanUndo() && IsEnabled && !IsReadOnly;
- }
-
- private void ExecuteUndoCommand()
- {
- Document.Undo();
- }
-
- #endregion
-
- #region RedoCommand
-
- public static readonly DependencyProperty RedoCommandProperty
- = DependencyProperty.Register(
- nameof(RedoCommand),
- typeof(IRelayCommand),
- typeof(TextEditorCore),
- new PropertyMetadata(null));
-
- public IRelayCommand RedoCommand
- {
- get => (IRelayCommand)GetValue(RedoCommandProperty);
- private set => SetValue(RedoCommandProperty, value);
- }
-
- private bool CanExecuteRedoCommand()
- {
- return Document.CanRedo() && IsEnabled && !IsReadOnly;
- }
-
- private void ExecuteRedoCommand()
- {
- Document.Redo();
- }
-
- #endregion
-
- #region SelectAllCommand
-
- public static readonly DependencyProperty SelectAllCommandProperty
- = DependencyProperty.Register(
- nameof(SelectAllCommand),
- typeof(IRelayCommand),
- typeof(TextEditorCore),
- new PropertyMetadata(null));
-
- public IRelayCommand SelectAllCommand
- {
- get => (IRelayCommand)GetValue(SelectAllCommandProperty);
- private set => SetValue(SelectAllCommandProperty, value);
- }
-
- private bool CanExecuteSelectAllCommand()
- {
- return IsEnabled;
- }
-
- private void ExecuteSelectAllCommand()
- {
- Document.Selection.SetRange(0, int.MaxValue);
- }
-
- #endregion
-
- protected override void OnApplyTemplate()
- {
- base.OnApplyTemplate();
-
- _rootGrid = (Grid)GetTemplateChild(RootGridName);
-
- _lineNumberGrid = (Grid)GetTemplateChild(LineNumberGridName);
- _lineNumberCanvas = (Canvas)GetTemplateChild(LineNumberCanvasName);
-
- _lineHighlighterAndIndicatorCanvas = (Canvas)GetTemplateChild(LineHighlighterAndIndicatorCanvasName);
- _lineHighlighter = (Grid)GetTemplateChild(LineHighlighterName);
- _lineIndicator = (Border)GetTemplateChild(LineIndicatorName);
-
- _contentScrollViewer = (ScrollViewer)GetTemplateChild(ContentElementName);
- _contentScrollViewer.ViewChanged += OnContentScrollViewerViewChanged;
- _contentScrollViewer.SizeChanged += OnContentScrollViewerSizeChanged;
-
- _contentScrollViewer.ApplyTemplate();
- var scrollViewerRoot = (FrameworkElement)VisualTreeHelper.GetChild(_contentScrollViewer, 0);
- _contentScrollViewerVerticalScrollBar = (ScrollBar)scrollViewerRoot.FindName(ContentScrollViewerVerticalScrollBarName);
- _contentScrollViewerVerticalScrollBar.ValueChanged += OnVerticalScrollBarValueChanged;
-
- _lineNumberGrid.SizeChanged += OnLineNumberGridSizeChanged;
- _rootGrid.SizeChanged += OnRootGridSizeChanged;
- }
-
- protected override void OnKeyDown(KeyRoutedEventArgs e)
- {
- var result = _keyboardCommandHandler.Handle(e);
-
- if (result.ShouldHandle)
- {
- e.Handled = true;
- }
-
- if (!result.ShouldSwallow)
- {
- base.OnKeyDown(e);
- }
- }
-
- private void ApplySettings()
- {
- ISettingsProvider? settingsProvider = SettingsProvider;
- if (settingsProvider is not null)
- {
- FontFamily = (FontFamily)Application.Current.Resources[settingsProvider.GetSetting(PredefinedSettings.TextEditorFont)];
- TextWrapping = settingsProvider.GetSetting(PredefinedSettings.TextEditorTextWrapping) ? TextWrapping.Wrap : TextWrapping.NoWrap;
- _showLineNumbers = settingsProvider.GetSetting(PredefinedSettings.TextEditorLineNumbers);
- _highlightCurrentLine = settingsProvider.GetSetting(PredefinedSettings.TextEditorHighlightCurrentLine);
-
- SetDefaultTabStopAndLineSpacing(FontFamily, FontSize);
-
- UpdateLayout();
-
- if (_showLineNumbers)
- {
- ShowLineNumbers();
- }
- else
- {
- HideLineNumbers();
- }
-
- UpdateSyntaxColorization(cancelOnGoingFormattingTask: false);
- }
- }
-
- private void SetDefaultTabStopAndLineSpacing(FontFamily font, double fontSize)
- {
- Document.DefaultTabStop = (float)GetTextSize(font, fontSize, "text").Width;
- ITextParagraphFormat format = Document.GetDefaultParagraphFormat();
- format.SetLineSpacing(LineSpacingRule.Exactly, (float)fontSize);
- Document.SetDefaultParagraphFormat(format);
- }
-
- private void ResetRootGridClipping()
- {
- if (!_loaded || _rootGrid is null)
- {
- return;
- }
-
- _rootGrid!.Clip = new RectangleGeometry
- {
- Rect = new Rect(
- 0,
- 0,
- _rootGrid.ActualWidth,
- Math.Clamp(_rootGrid.ActualHeight, .0f, double.PositiveInfinity))
- };
- }
-
- private void ShowLineNumbers()
- {
- if (!_loaded)
- {
- return;
- }
-
- ResetLineNumberCanvasClipping();
- UpdateLineNumbersRendering();
-
- // Call UpdateLineHighlighterAndIndicator to adjust it's state
- UpdateLineHighlighterAndIndicator();
- }
-
- private void HideLineNumbers()
- {
- if (!_loaded)
- {
- return;
- }
-
- Assumes.NotNull(_lineNumberGrid, nameof(_lineNumberGrid));
-
- foreach (var lineNumberBlock in _renderedLineNumberBlocks)
- {
- lineNumberBlock.Visibility = Visibility.Collapsed;
- }
-
- _lineNumberGrid!.BorderThickness = new Thickness(0, 0, 0, 0);
- _lineNumberGrid.Margin = new Thickness(0, 0, 0, 0);
- _lineNumberGrid.Width = .0f;
-
- // Call UpdateLineHighlighterAndIndicator to adjust it's state
- // Since when line highlighter is disabled, we still show the line indicator when line numbers are showing
- UpdateLineHighlighterAndIndicator();
- }
-
- private void UpdateLineNumbersRendering()
- {
- if (!_loaded || !_showLineNumbers)
- {
- return;
- }
-
- Assumes.NotNull(_contentScrollViewer, nameof(_contentScrollViewer));
-
- ITextRange? startRange
- = Document.GetRangeFromPoint(
- new Point(
- _contentScrollViewer!.HorizontalOffset,
- _contentScrollViewer.VerticalOffset),
- PointOptions.ClientCoordinates);
-
- ITextRange? endRange
- = Document.GetRangeFromPoint(
- new Point(
- _contentScrollViewer.HorizontalOffset + _contentScrollViewer.ViewportWidth,
- _contentScrollViewer.VerticalOffset + _contentScrollViewer.ViewportHeight),
- PointOptions.ClientCoordinates);
-
- string[]? document = GetDocumentLinesCache();
-
- Dictionary<int, Rect> lineNumberTextRenderingPositions = CalculateLineNumberTextRenderingPositions(document, startRange, endRange);
-
- double minLineNumberTextRenderingWidth
- = CalculateMinimumRequisiteIntegerTextRenderingWidth(
- FontFamily,
- FontSize,
- (document.Length - 1).ToString().Length);
-
- RenderLineNumbersInternal(lineNumberTextRenderingPositions, minLineNumberTextRenderingWidth);
- }
-
- private void UpdateSyntaxColorization(bool cancelOnGoingFormattingTask)
- {
- if (!_loaded || (_isSyntaxColorizationUpdateInProgress && !cancelOnGoingFormattingTask))
- {
- return;
- }
-
- // _formattingCancellationTokenSource.Cancel();
- // _formattingCancellationTokenSource.Dispose();
- // _formattingCancellationTokenSource = new CancellationTokenSource();
-
- // Assumes.NotNull(_contentScrollViewer, nameof(_contentScrollViewer));
-
- _isSyntaxColorizationUpdateInProgress = true;
- _isSyntaxColorizationPendingUpdate = false;
-
- // ITextRange? startRange
- // = Document.GetRangeFromPoint(
- // new Point(
- // _contentScrollViewer!.HorizontalOffset - 500,
- // _contentScrollViewer.VerticalOffset - 500),
- // PointOptions.ClientCoordinates);
-
- // ITextRange? endRange
- // = Document.GetRangeFromPoint(
- // new Point(
- // _contentScrollViewer.HorizontalOffset + _contentScrollViewer.ViewportWidth + 500,
- // _contentScrollViewer.VerticalOffset + _contentScrollViewer.ViewportHeight + 500),
- // PointOptions.ClientCoordinates);
-
- // ITextRange visibleSpan = Document.GetRange(startRange.StartPosition, endRange.EndPosition);
-
- // ElementTheme theme = RequestedTheme;
- // if (theme == ElementTheme.Default)
- // {
- // if (Window.Current.Content is FrameworkElement frameworkElement)
- // {
- // theme = frameworkElement.RequestedTheme;
- // }
- // }
-
- // var formatter = new TextFormatter(theme, Document, visibleSpan);
- // formatter.FormatAsync(Languages.CSharp, _formattingCancellationTokenSource.Token)
- // .ContinueWith(_ =>
- // {
- // _isSyntaxColorizationUpdateInProgress = false;
- // });
- }
-
- private string[] GetDocumentLinesCache()
- {
- if (_isDocumentLinesCachePendingUpdate)
- {
- _documentLinesCache = (GetText() + RichEditBoxDefaultLineEnding).Split(RichEditBoxDefaultLineEnding);
- _isDocumentLinesCachePendingUpdate = false;
- }
-
- return _documentLinesCache;
- }
-
- private Dictionary<int, Rect> CalculateLineNumberTextRenderingPositions(string[] lines, ITextRange startRange, ITextRange endRange)
- {
- int offset = 0;
- Dictionary<int, Rect>? lineRects = new(); // 1 - based
-
- for (int i = 0; i < lines.Length - 1; i++)
- {
- string line = lines[i] ?? string.Empty;
-
- ITextRange range = Document.GetRange(offset, offset + line.Length);
-
- // Use "offset + line.Length + 1" instead of just "offset" here is to capture the line right above the viewport
- if (offset + line.Length + 1 >= startRange.StartPosition && offset <= endRange.EndPosition)
- {
- range.GetRect(PointOptions.ClientCoordinates, out Rect rect, out _);
-
- lineRects[i + 1] = rect;
- }
- else if (offset > endRange.EndPosition)
- {
- break;
- }
-
- if (range.Length == 0 && range.Character == '\v')
- {
- offset++;
- }
-
- offset += line.Length + 1; // 1 for line ending: 'RichEditBoxDefaultLineEnding'
- }
-
- return lineRects;
- }
-
- /// <summary>
- /// Get minimum rendering width needed for displaying number text with certain length.
- /// Take length of 3 as example, it is going to iterate thru all possible combinations like:
- /// 111, 222, 333, 444 ... 999 to get minimum rendering length needed to display all of them (the largest width is the min here).
- /// For mono font text, the width is always the same for same length but for non-mono font text, it depends.
- /// Thus we need to calculate here to determine width needed for rendering integer number only text.
- /// </summary>
- /// <param name="fontFamily"></param>
- /// <param name="fontSize"></param>
- /// <param name="numberTextLength"></param>
- /// <returns></returns>
- private double CalculateMinimumRequisiteIntegerTextRenderingWidth(FontFamily fontFamily, double fontSize, int numberTextLength)
- {
- string? cacheKey = $"{fontFamily.Source}-{(int)fontSize}-{numberTextLength}";
-
- if (_miniRequisiteIntegerTextRenderingWidthCache.ContainsKey(cacheKey))
- {
- return _miniRequisiteIntegerTextRenderingWidthCache[cacheKey];
- }
-
- double minRequisiteWidth = 0;
-
- for (int i = 0; i < 10; i++)
- {
- string? str = new((char)('0' + i), numberTextLength);
- double width = GetTextSize(fontFamily, fontSize, str).Width;
- if (width > minRequisiteWidth)
- {
- minRequisiteWidth = width;
- }
- }
-
- _miniRequisiteIntegerTextRenderingWidthCache[cacheKey] = minRequisiteWidth;
- return minRequisiteWidth;
- }
-
- private void RenderLineNumbersInternal(Dictionary<int, Rect> lineNumberTextRenderingPositions, double minLineNumberTextRenderingWidth)
- {
- Assumes.NotNull(_lineNumberCanvas, nameof(_lineNumberCanvas));
- Assumes.NotNull(_lineNumberGrid, nameof(_lineNumberGrid));
-
- double padding = FontSize / 2;
- Thickness lineNumberPadding = new Thickness(padding, 2, padding + 2, 2);
- double lineHeight = GetSingleLineHeight();
- double lineNumberTextBlockHeight = lineHeight + Padding.Top + lineNumberPadding.Top;
- SolidColorBrush? lineNumberForeground = (ActualTheme == ElementTheme.Dark) ? _lineNumberDarkModeForegroundBrush : _lineNumberLightModeForegroundBrush;
-
- int numOfReusableLineNumberBlocks = _renderedLineNumberBlocks.Count;
-
- foreach ((int lineNumber, Rect rect) in lineNumberTextRenderingPositions)
- {
- var margin
- = new Thickness(
- lineNumberPadding.Left,
- rect.Top + lineNumberPadding.Top + Padding.Top,
- lineNumberPadding.Right,
- lineNumberPadding.Bottom);
-
- // Re-use already rendered line number blocks
- if (numOfReusableLineNumberBlocks > 0)
- {
- int index = numOfReusableLineNumberBlocks - 1;
- _renderedLineNumberBlocks[index].Text = lineNumber.ToString();
- _renderedLineNumberBlocks[index].Margin = margin;
- _renderedLineNumberBlocks[index].Height = lineNumberTextBlockHeight;
- _renderedLineNumberBlocks[index].Width = minLineNumberTextRenderingWidth;
- _renderedLineNumberBlocks[index].Visibility = Visibility.Visible;
- _renderedLineNumberBlocks[index].Foreground = lineNumberForeground;
-
- numOfReusableLineNumberBlocks--;
- }
- else // Render new line number block when there is nothing to re-use
- {
- var lineNumberBlock = new TextBlock()
- {
- Text = lineNumber.ToString(),
- Height = lineNumberTextBlockHeight,
- Width = minLineNumberTextRenderingWidth,
- Margin = margin,
- TextAlignment = TextAlignment.Right,
- HorizontalAlignment = HorizontalAlignment.Right,
- VerticalAlignment = VerticalAlignment.Bottom,
- HorizontalTextAlignment = TextAlignment.Right,
- Foreground = lineNumberForeground
- };
-
- _lineNumberCanvas!.Children.Add(lineNumberBlock);
- _renderedLineNumberBlocks.Add(lineNumberBlock);
- }
- }
-
- // Hide all un-used rendered line number block to avoid rendering collision from happening
- for (int i = 0; i < numOfReusableLineNumberBlocks; i++)
- {
- _renderedLineNumberBlocks[i].Visibility = Visibility.Collapsed;
- }
-
- _lineNumberGrid!.BorderThickness = new Thickness(0, 0, 0.08 * lineHeight, 0);
- _lineNumberGrid.Width = lineNumberPadding.Left + minLineNumberTextRenderingWidth + lineNumberPadding.Right;
- }
-
- private void ResetLineNumberCanvasClipping()
- {
- if (!_loaded || !_showLineNumbers)
- {
- return;
- }
-
- Assumes.NotNull(_lineNumberGrid, nameof(_lineNumberGrid));
-
- _lineNumberGrid!.Margin = new Thickness(0, 0, (-1 * Padding.Left) + 1, 0);
- _lineNumberGrid.Clip = new RectangleGeometry
- {
- Rect = new Rect(
- 0,
- Padding.Top,
- _lineNumberGrid.ActualWidth,
- Math.Clamp(_lineNumberGrid.ActualHeight - (Padding.Top + Padding.Bottom), .0f, double.PositiveInfinity))
- };
- }
-
- private void UpdateLineHighlighterAndIndicator()
- {
- if (!_loaded || _lineHighlighter is null || _lineIndicator is null || _rootGrid is null)
- {
- return;
- }
-
- if (!_showLineNumbers && !_highlightCurrentLine)
- {
- _lineHighlighter!.Visibility = Visibility.Collapsed;
- _lineIndicator!.Visibility = Visibility.Collapsed;
- return;
- }
-
- Document.Selection.GetRect(PointOptions.ClientCoordinates, out Rect selectionRect, out var _);
-
- double singleLineHeight = GetSingleLineHeight();
- Thickness thickness = new Thickness(0.08 * singleLineHeight);
- double height = selectionRect.Height;
-
- // Just to make sure height is a positive number and not smaller than single line height
- if (height < singleLineHeight)
- {
- height = singleLineHeight;
- }
-
- // Show line highlighter rect when it is enabled when selection is single line only
- if (_highlightCurrentLine && height < singleLineHeight * 1.5f)
- {
- _lineHighlighter!.Height = height;
- _lineHighlighter.Margin = new Thickness(0, selectionRect.Y + Padding.Top, 0, 0);
- _lineHighlighter.Width = Math.Clamp(_rootGrid!.ActualWidth, 0, double.PositiveInfinity);
-
- _lineHighlighter.Visibility = Visibility.Visible;
- }
- else
- {
- _lineHighlighter!.Visibility = Visibility.Collapsed;
- }
-
- // Show line indicator when line numbers are enabled and when selection is single line only
- if (_showLineNumbers && height < singleLineHeight * 1.5f)
- {
- _lineIndicator!.Height = height;
- _lineIndicator.Margin = new Thickness(0, selectionRect.Y + Padding.Top, 0, 0);
- _lineIndicator.BorderThickness = thickness;
- _lineIndicator.Width = 0.1 * singleLineHeight;
-
- _lineIndicator.Visibility = Visibility.Visible;
- }
- else
- {
- _lineIndicator!.Visibility = Visibility.Collapsed;
- }
- }
-
- /// <summary>
- /// Thread safe way of getting the text in the active story (document)
- /// </summary>
- private string GetText()
- {
- return _document;
- }
-
- private double GetSingleLineHeight()
- {
- Document.GetRange(0, 0).GetRect(PointOptions.ClientCoordinates, out Rect rect, out _);
- return rect.Height <= 0 ? 1.35 * FontSize : rect.Height;
- }
-
- private void EnterWithAutoIndentation()
- {
- // Automatically indent on new lines based on current line's leading spaces/tabs
- GetLineColumnSelection(out var startLineIndex, out _, out var startColumnIndex, out _, out _, out _);
- var lines = GetDocumentLinesCache();
- var leadingSpacesAndTabs = LeadingSpacesAndTabs(lines[startLineIndex - 1].Substring(0, startColumnIndex - 1));
- Document.Selection.SetText(TextSetOptions.None, RichEditBoxDefaultLineEnding + leadingSpacesAndTabs);
- Document.Selection.StartPosition = Document.Selection.EndPosition;
- }
-
- /// <summary>
- /// Returns 1-based indexing values
- /// </summary>
- private void GetLineColumnSelection(
- out int startLineIndex,
- out int endLineIndex,
- out int startColumnIndex,
- out int endColumnIndex,
- out int selectedCount,
- out int lineCount)
- {
- var lines = GetDocumentLinesCache();
- GetTextSelectionPosition(out var start, out var end);
-
- startLineIndex = 1;
- startColumnIndex = 1;
- endLineIndex = 1;
- endColumnIndex = 1;
- selectedCount = 0;
- lineCount = lines.Length - 1;
-
- var length = 0;
- bool startLocated = false;
-
- for (int i = 0; i < lineCount + 1; i++)
- {
- var line = lines[i];
-
- if (line.Length + length >= start && !startLocated)
- {
- startLineIndex = i + 1;
- startColumnIndex = start - length + 1;
- startLocated = true;
- }
-
- if (line.Length + length >= end)
- {
- if (i == startLineIndex - 1)
- {
- selectedCount = end - start;
- }
- else
- {
- selectedCount = end - start + (i - startLineIndex) + 1;
- }
-
- endLineIndex = i + 1;
- endColumnIndex = end - length + 1;
-
- // Reposition end position to previous line's end position if last selected char is RichEditBoxDefaultLineEnding ('\r')
- if (endColumnIndex == 1 && end != start)
- {
- endLineIndex--;
- endColumnIndex = lines[i - 1].Length + 1;
- }
-
- return;
- }
-
- length += line.Length + 1;
- }
- }
-
- /// <summary>
- /// Thread safe way of getting the current document selection position
- /// </summary>
- private void GetTextSelectionPosition(out int startPosition, out int endPosition)
- {
- startPosition = _textSelectionStartPosition;
- endPosition = _textSelectionEndPosition;
- }
-
- private async Task PastePlainTextFromWindowsClipboardAsync(TextControlPasteEventArgs? args)
- {
- if (args != null)
- {
- args.Handled = true;
- }
-
- if (!Document.CanPaste())
- {
- return;
- }
-
- try
- {
- DataPackageView? dataPackageView = Clipboard.GetContent();
- if (!dataPackageView.Contains(StandardDataFormats.Text))
- {
- return;
- }
-
- string? text = await dataPackageView.GetTextAsync();
-
- Document.BeginUndoGroup();
- Document.Selection.SetText(TextSetOptions.None, text);
- Document.Selection.StartPosition = Document.Selection.EndPosition;
- Document.EndUndoGroup();
- }
- catch (Exception ex)
- {
- Logger.LogFault("Failed to paste in text editor core", ex);
- }
- }
-
- private void SettingProvider_SettingChanged(object sender, SettingChangedEventArgs e)
- {
- ApplySettings();
- }
-
- private void OnContentScrollViewerViewChanged(object sender, ScrollViewerViewChangedEventArgs _)
- {
- UpdateLineNumbersRendering();
- UpdateSyntaxColorization(cancelOnGoingFormattingTask: false);
- }
-
- private void OnContentScrollViewerSizeChanged(object sender, SizeChangedEventArgs _)
- {
- UpdateLineNumbersRendering();
- UpdateSyntaxColorization(cancelOnGoingFormattingTask: false);
- }
-
- private void OnVerticalScrollBarValueChanged(object sender, RangeBaseValueChangedEventArgs _)
- {
- Assumes.NotNull(_contentScrollViewer, nameof(_contentScrollViewer));
- Assumes.NotNull(_lineNumberCanvas, nameof(_lineNumberCanvas));
- Assumes.NotNull(_lineHighlighterAndIndicatorCanvas, nameof(_lineHighlighterAndIndicatorCanvas));
-
- // Make sure line number canvas is in sync with editor's ScrollViewer
- _contentScrollViewer!.StartExpressionAnimation(_lineNumberCanvas!, Axis.Y);
-
- // Make sure line highlighter and indicator canvas is in sync with editor's ScrollViewer
- _contentScrollViewer!.StartExpressionAnimation(_lineHighlighterAndIndicatorCanvas!, Axis.Y);
- }
-
- private void OnLineNumberGridSizeChanged(object sender, SizeChangedEventArgs e)
- {
- ResetLineNumberCanvasClipping();
- }
-
- private void OnRootGridSizeChanged(object sender, SizeChangedEventArgs _)
- {
- ResetRootGridClipping();
- }
-
- private void OnPaste(object sender, TextControlPasteEventArgs e)
- {
- PastePlainTextFromWindowsClipboardAsync(e).Forget();
- }
-
- private void OnLoaded(object sender, RoutedEventArgs e)
- {
- _loaded = true;
-
- ResetRootGridClipping();
-
- UpdateLineHighlighterAndIndicator();
- if (_showLineNumbers)
- {
- ShowLineNumbers();
- }
-
- UpdateSyntaxColorization(cancelOnGoingFormattingTask: false);
- }
-
- private void OnSelectionChanging(RichEditBox sender, RichEditBoxSelectionChangingEventArgs args)
- {
- _textSelectionStartPosition = args.SelectionStart;
- _textSelectionEndPosition = args.SelectionStart + args.SelectionLength;
- }
-
- private void OnSelectionChanged(object sender, RoutedEventArgs _)
- {
- UpdateLineHighlighterAndIndicator();
- }
-
- private void OnSizeChanged(object sender, SizeChangedEventArgs _)
- {
- UpdateLineHighlighterAndIndicator();
- }
-
- private void OnTextChanging(RichEditBox sender, RichEditBoxTextChangingEventArgs args)
- {
- if (args.IsContentChanging)
- {
- Document.GetText(TextGetOptions.UseCrlf, out var document);
- _document = document;
-
- if (!_isTextPendingUpdate)
- {
- _isTextPendingUpdate = true;
- Text = document;
- _isTextPendingUpdate = false;
- }
-
- _isDocumentLinesCachePendingUpdate = true;
- _isSyntaxColorizationPendingUpdate = true;
- }
- }
-
- private void OnTextChanged(object sender, RoutedEventArgs _)
- {
- UpdateLineNumbersRendering();
-
- if (_isSyntaxColorizationPendingUpdate)
- {
- UpdateSyntaxColorization(cancelOnGoingFormattingTask: true);
- }
- }
-
- private static void OnSettingsProviderPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
- {
- ISettingsProvider? settingProvider = e.NewValue as ISettingsProvider;
- if (settingProvider is not null)
- {
- var textEditorCore = (TextEditorCore)d;
- settingProvider.SettingChanged += textEditorCore.SettingProvider_SettingChanged;
- textEditorCore.ApplySettings();
- }
- }
-
- private static void OnTextPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
- {
- string? text = e.NewValue as string;
- var textEditorCore = (TextEditorCore)d;
-
-
- if (!textEditorCore._isTextPendingUpdate)
- {
- textEditorCore._isTextPendingUpdate = true;
- bool isReadOnly = textEditorCore.IsReadOnly;
- textEditorCore.IsReadOnly = false;
- textEditorCore.Document.SetText(TextSetOptions.None, text ?? string.Empty);
- textEditorCore.IsReadOnly = isReadOnly;
- textEditorCore._isTextPendingUpdate = false;
- }
- }
-
- private static Size GetTextSize(FontFamily font, double fontSize, string text)
- {
- var textBlock = new TextBlock
- {
- Text = text,
- FontFamily = font,
- FontSize = fontSize
- };
- textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
- return textBlock.DesiredSize;
- }
-
- private static string LeadingSpacesAndTabs(string str)
- {
- int i = 0;
- for (; i < str.Length; i++)
- {
- var ch = str[i];
- if (ch != ' ' && ch != '\t')
- {
- break;
- }
- }
- return str.Substring(0, i);
- }
- }
-}
diff --git a/src/dev/impl/DevToys/UI/Controls/TextEditor/TextFormatter.cs b/src/dev/impl/DevToys/UI/Controls/TextEditor/TextFormatter.cs
deleted file mode 100644
index 81c69c915..000000000
--- a/src/dev/impl/DevToys/UI/Controls/TextEditor/TextFormatter.cs
+++ /dev/null
@@ -1,204 +0,0 @@
-#nullable enable
-
-using ColorCode;
-using ColorCode.Common;
-using ColorCode.Parsing;
-using ColorCode.Styling;
-using DevToys.Core.Threading;
-using Microsoft.Toolkit.Uwp.Helpers;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Windows.ApplicationModel.Core;
-using Windows.UI.Text;
-using Windows.UI.Xaml;
-
-namespace DevToys.UI.Controls.TextEditor
-{
- /// <summary>
- /// Creates a <see cref="TextFormatter"/>, for rendering Syntax Highlighted code to a RichTextBox.
- /// </summary>
- internal sealed class TextFormatter : CodeColorizerBase
- {
- private readonly ITextDocument _textDocument;
- private readonly ITextRange _span;
- private readonly List<(int startPosition, string text, Scope? scope)> _pendingUpdates = new();
- private int _parsedSourceCodePosition;
-
- /// <summary>
- /// Creates a <see cref="TextFormatter"/>, for rendering Syntax Highlighted code to a RichTextBox.
- /// </summary>
- /// <param name="Theme">The Theme to use, determines whether to use Default Light or Default Dark.</param>
- internal TextFormatter(ElementTheme Theme, ITextDocument textDocument, ITextRange span, ILanguageParser? languageParser = null)
- : base(Theme == ElementTheme.Dark ? StyleDictionary.DefaultDark : StyleDictionary.DefaultLight, languageParser)
- {
- _textDocument = textDocument;
- _span = span;
- }
-
- /// <summary>
- /// Adds Syntax Highlighted Source Code to the provided RichTextBox.
- /// </summary>
- /// <param name="language">The language to use to colorize the source code.</param>
- /// <param name="textEditor">The Control to add the Text to.</param>
- internal async Task FormatAsync(ILanguage language, CancellationToken cancellationToken)
- {
- await TaskScheduler.Default;
-
- _span.GetText(TextGetOptions.UseCrlf, out string sourceCode);
- _parsedSourceCodePosition = _span.StartPosition;
-
- languageParser.Parse(
- sourceCode,
- language,
- (parsedSourceCode, captures) =>
- {
- cancellationToken.ThrowIfCancellationRequested();
- Write(parsedSourceCode, captures);
- });
-
- cancellationToken.ThrowIfCancellationRequested();
-
- const int chunkSize = 5;
- int i = 0;
-
- while (i < _pendingUpdates.Count)
- {
- var items = _pendingUpdates.Skip(i).Take(chunkSize);
- i += chunkSize;
-
- cancellationToken.ThrowIfCancellationRequested();
-
- await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
- Windows.UI.Core.CoreDispatcherPriority.Low,
- () =>
- {
- foreach (var item in items)
- {
- if (cancellationToken.IsCancellationRequested)
- {
- break;
- }
-
- ApplyStyle(item.startPosition, item.text, item.scope);
- }
- });
- }
- }
-
- protected override void Write(string parsedSourceCode, IList<Scope> scopes)
- {
- var styleInsertions = new List<TextInsertion>();
-
- foreach (Scope scope in scopes)
- {
- GetStyleInsertionsForCapturedStyle(scope, styleInsertions);
- }
-
- styleInsertions.SortStable((x, y) => x.Index.CompareTo(y.Index));
-
- int parsedSourceCodePosition = _parsedSourceCodePosition;
- int offset = 0;
-
- Scope? previousScope = null;
-
- foreach (TextInsertion? styleinsertion in styleInsertions)
- {
- string text = parsedSourceCode.Substring(offset, styleinsertion.Index - offset);
- if (!string.IsNullOrEmpty(text))
- {
- _pendingUpdates.Add(new(parsedSourceCodePosition + offset, text, previousScope));
- }
-
- if (!string.IsNullOrWhiteSpace(styleinsertion.Text))
- {
- _pendingUpdates.Add(new(parsedSourceCodePosition, text, previousScope));
- }
-
- offset = styleinsertion.Index;
- previousScope = styleinsertion.Scope;
- }
-
- string remaining = parsedSourceCode.Substring(offset);
-
- // Ensures that those loose carriages don't run away!
- if (!string.IsNullOrEmpty(remaining) && remaining != "\r")
- {
- _pendingUpdates.Add(new(parsedSourceCodePosition + offset, remaining, null));
- }
-
- _parsedSourceCodePosition += parsedSourceCode.Length - CountStringOccurrences(parsedSourceCode, "\r");
- }
-
- private void ApplyStyle(int startPosition, string text, Scope? scope)
- {
- ITextRange span = _textDocument.GetRange(startPosition, startPosition + text.Length);
- ColorCode.Styling.Style style;
-
- if (scope is not null && Styles.Contains(scope.Name))
- {
- style = Styles[scope.Name];
- }
- else
- {
- style = Styles["Plain Text"]; // Default
- }
-
- string? foreground = style.Foreground;
- bool italic = style.Italic;
- bool bold = style.Bold;
-
- if (!string.IsNullOrWhiteSpace(foreground))
- {
- span.CharacterFormat.ForegroundColor = foreground!.ToColor();
- }
-
- if (italic)
- {
- span.CharacterFormat.FontStyle = FontStyle.Italic;
- }
-
- if (bold)
- {
- span.CharacterFormat.Bold = FormatEffect.On;
- }
- }
-
- private void GetStyleInsertionsForCapturedStyle(Scope scope, ICollection<TextInsertion> styleInsertions)
- {
- styleInsertions.Add(new TextInsertion
- {
- Index = scope.Index,
- Scope = scope
- });
-
- foreach (Scope childScope in scope.Children)
- {
- GetStyleInsertionsForCapturedStyle(childScope, styleInsertions);
- }
-
- styleInsertions.Add(new TextInsertion
- {
- Index = scope.Index + scope.Length
- });
- }
-
- /// <summary>
- /// Count occurrences of strings.
- /// </summary>
- private static int CountStringOccurrences(string text, string pattern)
- {
- // Loop through all instances of the string 'text'.
- int count = 0;
- int i = 0;
- while ((i = text.IndexOf(pattern, i)) != -1)
- {
- i += pattern.Length;
- count++;
- }
- return count;
- }
- }
-}
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/Base64EncoderDecoder/Base64EncoderDecoderToolProvider.cs b/src/dev/impl/DevToys/ViewModels/Tools/Base64EncoderDecoder/Base64EncoderDecoderToolProvider.cs
index 60f2d3640..0c311f96a 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/Base64EncoderDecoder/Base64EncoderDecoderToolProvider.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/Base64EncoderDecoder/Base64EncoderDecoderToolProvider.cs
@@ -87,7 +87,11 @@ namespace DevToys.ViewModels.Tools.Base64EncoderDecoder
for (int i = 0; i < decoded.Length; i++)
{
current = decoded[i];
- if (current == 65533) return false;
+ if (current == 65533)
+ {
+ return false;
+ }
+
if (!(current == 0x9
|| current == 0xA
|| current == 0xD
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolProvider.cs b/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolProvider.cs
index 0e224ed44..c5ed4b006 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolProvider.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolProvider.cs
@@ -2,11 +2,7 @@
using DevToys.Api.Core.Injection;
using DevToys.Api.Tools;
-using DevToys.Core;
using DevToys.Helpers;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-using System;
using System.Composition;
namespace DevToys.ViewModels.Tools.JsonFormatter
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolViewModel.cs
index 103ba6c91..305b9c0f4 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolViewModel.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/JsonFormatter/JsonFormatterToolViewModel.cs
@@ -1,11 +1,9 @@
#nullable enable
-using ColorCode;
using DevToys.Api.Core.Settings;
using DevToys.Api.Tools;
using DevToys.Core;
using DevToys.Core.Threading;
-using DevToys.UI.Controls.FormattedTextBlock;
using DevToys.Views.Tools.JsonFormatter;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Newtonsoft.Json;
@@ -31,6 +29,7 @@ namespace DevToys.ViewModels.Tools.JsonFormatter
private bool _formattingInProgress;
private string? _inputValue;
+ private string? _outputValue;
private string _indentation = TwoSpaceIndentation;
public Type View { get; } = typeof(JsonFormatterToolPage);
@@ -63,9 +62,14 @@ namespace DevToys.ViewModels.Tools.JsonFormatter
}
}
+ internal string? OutputValue
+ {
+ get => _outputValue;
+ set => SetProperty(ref _outputValue, value);
+ }
+
internal ISettingsProvider SettingsProvider { get; }
- internal IFormattedTextBlock? OutputTextBlock { private get; set; }
[ImportingConstructor]
public JsonFormatterToolViewModel(ISettingsProvider settingsProvider)
@@ -86,8 +90,6 @@ namespace DevToys.ViewModels.Tools.JsonFormatter
return;
}
- Assumes.NotNull(OutputTextBlock, nameof(OutputTextBlock));
-
_formattingInProgress = true;
await TaskScheduler.Default;
@@ -98,14 +100,7 @@ namespace DevToys.ViewModels.Tools.JsonFormatter
ThreadHelper.RunOnUIThreadAsync(ThreadPriority.Low, () =>
{
- if (success)
- {
- OutputTextBlock!.SetText(result, Languages.JavaScript);
- }
- else
- {
- OutputTextBlock!.SetText(result);
- }
+ OutputValue = result;
}).ForgetSafely();
}
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/JsonYaml/JsonYamlToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/JsonYaml/JsonYamlToolViewModel.cs
index 763cba6d9..f9081dcfd 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/JsonYaml/JsonYamlToolViewModel.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/JsonYaml/JsonYamlToolViewModel.cs
@@ -1,13 +1,10 @@
#nullable enable
-using ColorCode;
using DevToys.Api.Core.Settings;
using DevToys.Api.Tools;
using DevToys.Core;
using DevToys.Core.Threading;
using DevToys.Helpers;
-using DevToys.UI.Controls.FormattedTextBlock;
-using DevToys.UI.Controls.FormattedTextBlock.Languages;
using DevToys.Views.Tools.JsonYaml;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Newtonsoft.Json;
@@ -36,7 +33,9 @@ namespace DevToys.ViewModels.Tools.JsonYaml
private bool _conversionInProgress;
private bool _setPropertyInProgress;
private string? _inputValue;
+ private string? _inputValueLanguage;
private string? _outputValue;
+ private string? _outputValueLanguage;
private string _indentation = TwoSpaceIndentation;
private string _conversionMode = JsonToYaml;
@@ -60,17 +59,23 @@ namespace DevToys.ViewModels.Tools.JsonYaml
if (string.Equals(value, JsonToYaml))
{
- if (JsonHelper.IsValidJson(_outputValue))
+ if (JsonHelper.IsValidJson(OutputValue))
{
- InputValue = _outputValue;
+ InputValue = OutputValue;
}
+
+ InputValueLanguage = "json";
+ OutputValueLanguage = "yaml";
}
else
{
- if (YamlHelper.IsValidYaml(_outputValue))
+ if (YamlHelper.IsValidYaml(OutputValue))
{
- InputValue = _outputValue;
+ InputValue = OutputValue;
}
+
+ InputValueLanguage = "yaml";
+ OutputValueLanguage = "json";
}
_setPropertyInProgress = false;
@@ -104,16 +109,41 @@ namespace DevToys.ViewModels.Tools.JsonYaml
}
}
- internal ISettingsProvider SettingsProvider { get; }
+ /// <summary>
+ /// Gets or sets the input code editor's language.
+ /// </summary>
+ internal string? InputValueLanguage
+ {
+ get => _inputValueLanguage;
+ set => SetProperty(ref _inputValueLanguage, value);
+ }
- internal IFormattedTextBlock? OutputTextBlock { private get; set; }
+ /// <summary>
+ /// Gets or sets the output text.
+ /// </summary>
+ internal string? OutputValue
+ {
+ get => _outputValue;
+ set => SetProperty(ref _outputValue, value);
+ }
+
+ /// <summary>
+ /// Gets or sets the output code editor's language.
+ /// </summary>
+ internal string? OutputValueLanguage
+ {
+ get => _outputValueLanguage;
+ set => SetProperty(ref _outputValueLanguage, value);
+ }
+
+ internal ISettingsProvider SettingsProvider { get; }
[ImportingConstructor]
public JsonYamlToolViewModel(ISettingsProvider settingsProvider)
{
SettingsProvider = settingsProvider;
-
- Languages.Load(new Yaml());
+ InputValueLanguage = "json";
+ OutputValueLanguage = "yaml";
}
private void QueueConversion()
@@ -129,8 +159,6 @@ namespace DevToys.ViewModels.Tools.JsonYaml
return;
}
- Assumes.NotNull(OutputTextBlock, nameof(OutputTextBlock));
-
_conversionInProgress = true;
await TaskScheduler.Default;
@@ -139,29 +167,18 @@ namespace DevToys.ViewModels.Tools.JsonYaml
{
bool success;
string result;
- ILanguage language;
if (string.Equals(ConversionMode, JsonToYaml, StringComparison.Ordinal))
{
success = ConvertJsonToYaml(text, out result);
- language = Languages.FindById("yaml");
}
else
{
success = ConvertYamlToJson(text, out result);
- language = Languages.JavaScript;
}
ThreadHelper.RunOnUIThreadAsync(ThreadPriority.Low, () =>
{
- _outputValue = result;
- if (success)
- {
- OutputTextBlock!.SetText(result, language);
- }
- else
- {
- OutputTextBlock!.SetText(result);
- }
+ OutputValue = result;
}).ForgetSafely();
}
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/Settings/SettingsToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/Settings/SettingsToolViewModel.cs
index 67aadb191..6b1405cfe 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/Settings/SettingsToolViewModel.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/Settings/SettingsToolViewModel.cs
@@ -8,11 +8,14 @@ using DevToys.Core;
using DevToys.Core.Settings;
using DevToys.Core.Threading;
using DevToys.Views.Tools.Settings;
+using Microsoft.Graphics.Canvas.Text;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
+using System.Collections.ObjectModel;
using System.Composition;
+using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Windows.ApplicationModel;
@@ -52,6 +55,8 @@ namespace DevToys.ViewModels.Settings
set => _settingsProvider.SetSetting(PredefinedSettings.SmartDetection, value);
}
+ internal ObservableCollection<string> SupportedFonts { get; } = new();
+
internal string TextEditorFont
{
get => _settingsProvider.GetSetting(PredefinedSettings.TextEditorFont);
@@ -76,6 +81,12 @@ namespace DevToys.ViewModels.Settings
set => _settingsProvider.SetSetting(PredefinedSettings.TextEditorHighlightCurrentLine, value);
}
+ internal bool TextEditorRenderWhitespace
+ {
+ get => _settingsProvider.GetSetting(PredefinedSettings.TextEditorRenderWhitespace);
+ set => _settingsProvider.SetSetting(PredefinedSettings.TextEditorRenderWhitespace, value);
+ }
+
/// <summary>
/// Gets the version of the application.
/// </summary>
@@ -113,6 +124,8 @@ namespace DevToys.ViewModels.Settings
LicenseCommand = new AsyncRelayCommand(ExecuteLicenseCommandAsync);
RateAndReviewCommand = new AsyncRelayCommand(ExecuteRateAndReviewCommandAsync);
OpenLogsCommand = new AsyncRelayCommand(ExecuteOpenLogsCommandAsync);
+
+ LoadSupportedFontsAsync().Forget();
}
#region CopyVersionCommand
@@ -203,5 +216,22 @@ namespace DevToys.ViewModels.Settings
}
#endregion
+
+ private async Task LoadSupportedFontsAsync()
+ {
+ await TaskScheduler.Default;
+
+ string[] systemFonts = CanvasTextFormat.GetSystemFontFamilies();
+
+ for (int i = 0; i < PredefinedSettings.SupportedFonts.Length; i++)
+ {
+ if (systemFonts.Contains(PredefinedSettings.SupportedFonts[i]))
+ {
+ SupportedFonts.Add(PredefinedSettings.SupportedFonts[i]);
+ }
+ }
+
+ OnPropertyChanged(nameof(TextEditorFont));
+ }
}
}
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/TextDiff/TextDiffToolProvider.cs b/src/dev/impl/DevToys/ViewModels/Tools/TextDiff/TextDiffToolProvider.cs
index e8b05ad8d..30d02a702 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/TextDiff/TextDiffToolProvider.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/TextDiff/TextDiffToolProvider.cs
@@ -10,6 +10,7 @@ namespace DevToys.ViewModels.Tools.TextDiff
[Name("Text Diff")]
[ProtocolName("diff")]
[Order(0)]
+ [NotScrollable]
internal sealed class TextDiffToolProvider : ToolProviderBase, IToolProvider
{
private readonly IMefProvider _mefProvider;
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/TextDiff/TextDiffToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/TextDiff/TextDiffToolViewModel.cs
index a9f5a5d10..06e4302f4 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/TextDiff/TextDiffToolViewModel.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/TextDiff/TextDiffToolViewModel.cs
@@ -2,24 +2,17 @@
using DevToys.Api.Core.Settings;
using DevToys.Api.Tools;
-using DevToys.Core;
-using DevToys.Core.Threading;
-using DevToys.UI.Controls.FormattedTextBlock;
using DevToys.Views.Tools.TextDiff;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using System;
-using System.Collections.Generic;
using System.Composition;
-using System.Threading.Tasks;
namespace DevToys.ViewModels.Tools.TextDiff
{
[Export(typeof(TextDiffToolViewModel))]
public sealed class TextDiffToolViewModel : ObservableRecipient, IToolViewModel
{
- private readonly Queue<(string? oldText, string? newText)> _comparisonQueue = new();
-
- private bool _comparisonInProgress;
+ private bool _inlineMode;
private string? _oldText;
private string? _newText;
@@ -29,61 +22,28 @@ namespace DevToys.ViewModels.Tools.TextDiff
internal TextDiffStrings Strings => LanguageManager.Instance.TextDiff;
+ internal bool InlineMode
+ {
+ get => _inlineMode;
+ set => SetProperty(ref _inlineMode, value, broadcast: true);
+ }
+
internal string? OldText
{
get => _oldText;
- set
- {
- SetProperty(ref _oldText, value, broadcast: true);
- QueueComparison();
- OutputTextBlock?.SetInlineTextDiff(value, NewText, lineDiff: false);
- }
+ set => SetProperty(ref _oldText, value, broadcast: true);
}
internal string? NewText
{
get => _newText;
- set
- {
- SetProperty(ref _newText, value, broadcast: true);
- QueueComparison();
- OutputTextBlock?.SetInlineTextDiff(OldText, value, lineDiff: false);
- }
+ set => SetProperty(ref _newText, value, broadcast: true);
}
- internal IFormattedTextBlock? OutputTextBlock { private get; set; }
-
[ImportingConstructor]
public TextDiffToolViewModel(ISettingsProvider settingsProvider)
{
SettingsProvider = settingsProvider;
}
-
- private void QueueComparison()
- {
- _comparisonQueue.Enqueue(new(OldText, NewText));
- TreatComparisonQueueAsync().Forget();
- }
-
- private async Task TreatComparisonQueueAsync()
- {
- if (_comparisonInProgress)
- {
- return;
- }
-
- _comparisonInProgress = true;
-
- Assumes.NotNull(OutputTextBlock, nameof(OutputTextBlock));
-
- await TaskScheduler.Default;
-
- while (_comparisonQueue.TryDequeue(out (string? oldText, string? newText) item))
- {
- // await TextEditor!.ShowTextDiffAsync(item.oldText, item.newText);
- }
-
- _comparisonInProgress = false;
- }
}
}
diff --git a/src/dev/impl/DevToys/Views/Tools/JsonFormatter/JsonFormatterToolPage.xaml b/src/dev/impl/DevToys/Views/Tools/JsonFormatter/JsonFormatterToolPage.xaml
index de422fe65..b6a66e445 100644
--- a/src/dev/impl/DevToys/Views/Tools/JsonFormatter/JsonFormatterToolPage.xaml
+++ b/src/dev/impl/DevToys/Views/Tools/JsonFormatter/JsonFormatterToolPage.xaml
@@ -6,7 +6,6 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="using:DevToys.UI.Controls"
xmlns:formattedtextblock="using:DevToys.UI.Controls.FormattedTextBlock"
- xmlns:texteditor="using:DevToys.UI.Controls.TextEditor"
xmlns:toolkit="using:Microsoft.Toolkit.Uwp.UI.Controls"
mc:Ignorable="d"
NavigationCacheMode="Required">
@@ -51,11 +50,13 @@
<ColumnDefinition MinWidth="100"/>
</Grid.ColumnDefinitions>
- <texteditor:TextEditor
+ <controls:CodeEditor
+ x:Name="InputCodeEditor"
Grid.Column="0"
Header="{x:Bind ViewModel.Strings.Input}"
SettingsProvider="{x:Bind ViewModel.SettingsProvider}"
- Text="{x:Bind ViewModel.InputValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
+ Text="{x:Bind ViewModel.InputValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
+ CodeLanguage="json"/>
<toolkit:GridSplitter
Grid.Column="1"
@@ -70,11 +71,14 @@
</toolkit:GridSplitter.Element>
</toolkit:GridSplitter>
- <formattedtextblock:FormattedTextBlock
- x:Name="OutputTextBlock"
+ <controls:CodeEditor
+ x:Name="OutputCodeEditor"
Grid.Column="2"
Header="{x:Bind ViewModel.Strings.Output}"
- SettingsProvider="{x:Bind ViewModel.SettingsProvider}"/>
+ SettingsProvider="{x:Bind ViewModel.SettingsProvider}"
+ Text="{x:Bind ViewModel.OutputValue, Mode=OneWay}"
+ CodeLanguage="json"
+ IsReadOnly="True"/>
</Grid>
</Grid>
</Page>
diff --git a/src/dev/impl/DevToys/Views/Tools/JsonFormatter/JsonFormatterToolPage.xaml.cs b/src/dev/impl/DevToys/Views/Tools/JsonFormatter/JsonFormatterToolPage.xaml.cs
index 92737db02..ed9866e7c 100644
--- a/src/dev/impl/DevToys/Views/Tools/JsonFormatter/JsonFormatterToolPage.xaml.cs
+++ b/src/dev/impl/DevToys/Views/Tools/JsonFormatter/JsonFormatterToolPage.xaml.cs
@@ -42,8 +42,6 @@ namespace DevToys.Views.Tools.JsonFormatter
Assumes.NotNull(parameters.ViewModel, nameof(parameters.ViewModel));
ViewModel = (JsonFormatterToolViewModel)parameters.ViewModel!;
DataContext = ViewModel;
-
- ViewModel.OutputTextBlock = OutputTextBlock;
}
if (!string.IsNullOrWhiteSpace(parameters.ClipBoardContent))
diff --git a/src/dev/impl/DevToys/Views/Tools/JsonYaml/JsonYamlToolPage.xaml b/src/dev/impl/DevToys/Views/Tools/JsonYaml/JsonYamlToolPage.xaml
index 2d7870679..f76937edb 100644
--- a/src/dev/impl/DevToys/Views/Tools/JsonYaml/JsonYamlToolPage.xaml
+++ b/src/dev/impl/DevToys/Views/Tools/JsonYaml/JsonYamlToolPage.xaml
@@ -75,11 +75,12 @@
<ColumnDefinition MinWidth="100"/>
</Grid.ColumnDefinitions>
- <texteditor:TextEditor
+ <controls:CodeEditor
Grid.Column="0"
Header="{x:Bind ViewModel.Strings.Input}"
SettingsProvider="{x:Bind ViewModel.SettingsProvider}"
- Text="{x:Bind ViewModel.InputValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
+ Text="{x:Bind ViewModel.InputValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
+ CodeLanguage="{x:Bind ViewModel.InputValueLanguage, Mode=OneWay}"/>
<toolkit:GridSplitter
Grid.Column="1"
@@ -94,11 +95,13 @@
</toolkit:GridSplitter.Element>
</toolkit:GridSplitter>
- <formattedtextblock:FormattedTextBlock
- x:Name="OutputTextBlock"
+ <controls:CodeEditor
Grid.Column="2"
+ IsReadOnly="True"
Header="{x:Bind ViewModel.Strings.Output}"
- SettingsProvider="{x:Bind ViewModel.SettingsProvider}"/>
+ SettingsProvider="{x:Bind ViewModel.SettingsProvider}"
+ Text="{x:Bind ViewModel.OutputValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
+ CodeLanguage="{x:Bind ViewModel.OutputValueLanguage, Mode=OneWay}"/>
</Grid>
</Grid>
</Page>
diff --git a/src/dev/impl/DevToys/Views/Tools/JsonYaml/JsonYamlToolPage.xaml.cs b/src/dev/impl/DevToys/Views/Tools/JsonYaml/JsonYamlToolPage.xaml.cs
index dbdae29f9..273a875b4 100644
--- a/src/dev/impl/DevToys/Views/Tools/JsonYaml/JsonYamlToolPage.xaml.cs
+++ b/src/dev/impl/DevToys/Views/Tools/JsonYaml/JsonYamlToolPage.xaml.cs
@@ -43,8 +43,6 @@ namespace DevToys.Views.Tools.JsonYaml
Assumes.NotNull(parameters.ViewModel, nameof(parameters.ViewModel));
ViewModel = (JsonYamlToolViewModel)parameters.ViewModel!;
DataContext = ViewModel;
-
- ViewModel.OutputTextBlock = OutputTextBlock;
}
if (!string.IsNullOrWhiteSpace(parameters.ClipBoardContent))
diff --git a/src/dev/impl/DevToys/Views/Tools/Settings/SettingsToolPage.xaml b/src/dev/impl/DevToys/Views/Tools/Settings/SettingsToolPage.xaml
index d9a416d5e..f30d638dd 100644
--- a/src/dev/impl/DevToys/Views/Tools/Settings/SettingsToolPage.xaml
+++ b/src/dev/impl/DevToys/Views/Tools/Settings/SettingsToolPage.xaml
@@ -76,12 +76,8 @@
<FontIcon Glyph="&#xF7E4;" />
</controls:ExpandableSettingControl.Icon>
<ComboBox
- SelectedValuePath="Tag"
+ ItemsSource="{x:Bind ViewModel.SupportedFonts, Mode=OneWay}"
SelectedValue="{x:Bind ViewModel.TextEditorFont, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
- <ComboBoxItem Tag="CascadiaCode" FontFamily="{StaticResource CascadiaCode}" Content="Cascadia Code"/>
- <ComboBoxItem Tag="CascadiaMono" FontFamily="{StaticResource CascadiaMono}" Content="Cascadia Mono"/>
- <ComboBoxItem Tag="Consolas" FontFamily="{StaticResource Consolas}" Content="Consolas"/>
- <ComboBoxItem Tag="SegoeUI" FontFamily="{StaticResource SegoeUI}" Content="Segoe UI"/>
</ComboBox>
</controls:ExpandableSettingControl>
<controls:ExpandableSettingControl
@@ -107,6 +103,13 @@
</controls:ExpandableSettingControl.Icon>
<ToggleSwitch Style="{StaticResource RightAlignedToggleSwitchStyle}" IsOn="{x:Bind ViewModel.TextEditorHighlightCurrentLine, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</controls:ExpandableSettingControl>
+ <controls:ExpandableSettingControl
+ Title="{x:Bind ViewModel.Strings.RenderWhitespace}">
+ <controls:ExpandableSettingControl.Icon>
+ <FontIcon Glyph="&#xF6F8;" />
+ </controls:ExpandableSettingControl.Icon>
+ <ToggleSwitch Style="{StaticResource RightAlignedToggleSwitchStyle}" IsOn="{x:Bind ViewModel.TextEditorRenderWhitespace, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
+ </controls:ExpandableSettingControl>
<TextBlock Style="{StaticResource SubTitleTextBlock}" Text="{x:Bind ViewModel.Strings.About}" />
diff --git a/src/dev/impl/DevToys/Views/Tools/TextDiff/TextDiffToolPage.xaml b/src/dev/impl/DevToys/Views/Tools/TextDiff/TextDiffToolPage.xaml
index e8e2d9766..accece689 100644
--- a/src/dev/impl/DevToys/Views/Tools/TextDiff/TextDiffToolPage.xaml
+++ b/src/dev/impl/DevToys/Views/Tools/TextDiff/TextDiffToolPage.xaml
@@ -4,9 +4,9 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:formattedtextblock="using:DevToys.UI.Controls.FormattedTextBlock"
- xmlns:texteditor="using:DevToys.UI.Controls.TextEditor"
- xmlns:toolkit="using:Microsoft.Toolkit.Uwp.UI.Controls" xmlns:ex="using:DevToys.UI.Extensions"
+ xmlns:controls="using:DevToys.UI.Controls"
+ xmlns:ex="using:DevToys.UI.Extensions"
+ xmlns:toolkit="using:Microsoft.Toolkit.Uwp.UI.Controls"
mc:Ignorable="d"
NavigationCacheMode="Required">
@@ -18,21 +18,17 @@
<ex:IsCompactOverlayModeTrigger TargetElement="{x:Bind}" />
</VisualState.StateTriggers>
<VisualState.Setters>
- <Setter Target="InputGridSplitter.Visibility" Value="Collapsed"/>
<Setter Target="OutputGridSplitter.Visibility" Value="Collapsed"/>
- <Setter Target="HorizontalGridSplitterRow.Height" Value="16" />
- <Setter Target="HorizontalRightTextEditorRow.Height" Value="*" />
- <Setter Target="HorizontalRightTextEditorRow.MinHeight" Value="200" />
- <Setter Target="HorizontalGridSplitterColumn.Width" Value="Auto" />
- <Setter Target="HorizontalRightTextEditorColumn.MinWidth" Value="0" />
- <Setter Target="HorizontalRightTextEditorColumn.Width" Value="Auto" />
- <Setter Target="RightTextEditor.(Grid.Column)" Value="0" />
- <Setter Target="RightTextEditor.(Grid.Row)" Value="2" />
+ <Setter Target="InputGrid.Visibility" Value="Collapsed" />
+ <Setter Target="InputGridRow.MinHeight" Value="0" />
+ <Setter Target="HorizontalGridSplitterRow.Height" Value="0" />
+ <Setter Target="OuputTextEditor.(Grid.Row)" Value="1" />
+ <Setter Target="OuputTextEditor.(Grid.RowSpan)" Value="3" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
-
+
<Grid.ChildrenTransitions>
<TransitionCollection>
<EntranceThemeTransition IsStaggeringEnabled="True" FromVerticalOffset="50"/>
@@ -40,36 +36,46 @@
</Grid.ChildrenTransitions>
<Grid.RowDefinitions>
- <RowDefinition MinHeight="200"/>
- <RowDefinition Height="16"/>
+ <RowDefinition Height="Auto"/>
+ <RowDefinition x:Name="InputGridRow" MinHeight="200"/>
+ <RowDefinition x:Name="HorizontalGridSplitterRow" Height="16"/>
<RowDefinition MinHeight="200"/>
</Grid.RowDefinitions>
- <Grid Grid.Row="0">
+ <StackPanel Grid.Row="0" Spacing="4" Margin="0,0,0,12">
+ <TextBlock Style="{StaticResource SubTitleTextBlock}" Text="{x:Bind ViewModel.Strings.Configuration}" />
+
+ <controls:ExpandableSettingControl
+ VerticalAlignment="Stretch"
+ VerticalContentAlignment="Stretch"
+ Title="{x:Bind ViewModel.Strings.InlineDifference}">
+ <controls:ExpandableSettingControl.Icon>
+ <FontIcon Glyph="&#xFD5E;" />
+ </controls:ExpandableSettingControl.Icon>
+ <ToggleSwitch
+ Style="{StaticResource RightAlignedToggleSwitchStyle}"
+ IsOn="{x:Bind ViewModel.InlineMode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
+ </controls:ExpandableSettingControl>
+ </StackPanel>
+
+ <Grid x:Name="InputGrid" Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="150"/>
- <ColumnDefinition x:Name="HorizontalGridSplitterColumn" Width="16"/>
- <ColumnDefinition x:Name="HorizontalRightTextEditorColumn" MinWidth="150"/>
+ <ColumnDefinition Width="16"/>
+ <ColumnDefinition MinWidth="150"/>
</Grid.ColumnDefinitions>
- <Grid.RowDefinitions>
- <RowDefinition MinHeight="200"/>
- <RowDefinition x:Name="HorizontalGridSplitterRow" Height="0"/>
- <RowDefinition x:Name="HorizontalRightTextEditorRow" Height="0"/>
- </Grid.RowDefinitions>
- <texteditor:TextEditor
+ <controls:CodeEditor
x:Name="LeftTextEditor"
Grid.Column="0"
- Grid.Row="0"
MinHeight="200"
- SettingsProvider="{x:Bind ViewModel.SettingsProvider}"
Header="{x:Bind ViewModel.Strings.LeftText}"
+ SettingsProvider="{x:Bind ViewModel.SettingsProvider}"
Text="{x:Bind ViewModel.OldText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<toolkit:GridSplitter
x:Name="InputGridSplitter"
Grid.Column="1"
- Grid.Row="0"
Width="16"
Margin="0,42,0,0"
ResizeBehavior="BasedOnAlignment"
@@ -81,19 +87,18 @@
</toolkit:GridSplitter.Element>
</toolkit:GridSplitter>
- <texteditor:TextEditor
+ <controls:CodeEditor
x:Name="RightTextEditor"
Grid.Column="2"
- Grid.Row="0"
MinHeight="200"
- SettingsProvider="{x:Bind ViewModel.SettingsProvider}"
Header="{x:Bind ViewModel.Strings.RightText}"
+ SettingsProvider="{x:Bind ViewModel.SettingsProvider}"
Text="{x:Bind ViewModel.NewText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
<toolkit:GridSplitter
x:Name="OutputGridSplitter"
- Grid.Row="1"
+ Grid.Row="2"
Height="16"
ResizeBehavior="BasedOnAlignment"
ResizeDirection="Auto">
@@ -104,11 +109,16 @@
</toolkit:GridSplitter.Element>
</toolkit:GridSplitter>
- <formattedtextblock:FormattedTextBlock
+ <controls:CodeEditor
x:Name="OuputTextEditor"
MinHeight="200"
- Grid.Row="2"
+ Grid.Row="3"
Header="{x:Bind ViewModel.Strings.Difference}"
- SettingsProvider="{x:Bind ViewModel.SettingsProvider}"/>
+ SettingsProvider="{x:Bind ViewModel.SettingsProvider}"
+ IsReadOnly="True"
+ IsDiffViewMode="True"
+ InlineDiffViewMode="{x:Bind ViewModel.InlineMode, Mode=OneWay}"
+ DiffLeftText="{x:Bind ViewModel.OldText, Mode=OneWay}"
+ DiffRightText="{x:Bind ViewModel.NewText, Mode=OneWay}"/>
</Grid>
</Page>
diff --git a/src/dev/impl/DevToys/Views/Tools/TextDiff/TextDiffToolPage.xaml.cs b/src/dev/impl/DevToys/Views/Tools/TextDiff/TextDiffToolPage.xaml.cs
index 61658c34c..d5d77bba6 100644
--- a/src/dev/impl/DevToys/Views/Tools/TextDiff/TextDiffToolPage.xaml.cs
+++ b/src/dev/impl/DevToys/Views/Tools/TextDiff/TextDiffToolPage.xaml.cs
@@ -42,8 +42,6 @@ namespace DevToys.Views.Tools.TextDiff
Assumes.NotNull(parameters.ViewModel, nameof(parameters.ViewModel));
ViewModel = (TextDiffToolViewModel)parameters.ViewModel!;
DataContext = ViewModel;
-
- ViewModel.OutputTextBlock = OuputTextEditor;
}
base.OnNavigatedTo(e);
diff --git a/src/dev/shared/Package.appxmanifest b/src/dev/shared/Package.appxmanifest
index 1110c7c5c..2d218e350 100644
--- a/src/dev/shared/Package.appxmanifest
+++ b/src/dev/shared/Package.appxmanifest
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
@@ -6,73 +6,78 @@
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5"
xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4"
+ xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap mp desktop4">
- <!-- Please DO NOT commit changes on the version number below unless you're about to release a new version of the app on the Store. -->
- <Identity
- Name="DevToysPreview"
- Publisher="CN=etiennebaudoux"
- Version="0.0.0.0" />
+ <!-- Please DO NOT commit changes on the version number below unless you're about to release a new version of the app on the Store. -->
+ <Identity
+ Name="DevToysPreview"
+ Publisher="CN=etiennebaudoux"
+ Version="0.6.0.0" />
- <!-- TODO: maybe we need to remove this when adding runFullTrust capability -->
- <mp:PhoneIdentity PhoneProductId="c12088ee-f979-4809-8039-7851a3aa2b7a" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
+ <!-- TODO: maybe we need to remove this when adding runFullTrust capability -->
+ <mp:PhoneIdentity PhoneProductId="c12088ee-f979-4809-8039-7851a3aa2b7a" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
- <Properties>
- <DisplayName>DevToys - Preview</DisplayName>
- <PublisherDisplayName>etiennebaudoux</PublisherDisplayName>
- <Logo>Assets\Logo\StoreLogo.png</Logo>
- </Properties>
+ <Properties>
+ <DisplayName>DevToys - Preview</DisplayName>
+ <PublisherDisplayName>etiennebaudoux</PublisherDisplayName>
+ <Logo>Assets\Logo\StoreLogo.png</Logo>
+ </Properties>
- <Dependencies>
- <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
- <TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.14393.0" MaxVersionTested="10.0.14393.0" />
- </Dependencies>
+ <Dependencies>
+ <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
+ <TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.14393.0" MaxVersionTested="10.0.14393.0" />
+ </Dependencies>
- <Resources>
- <Resource Language="x-generate"/>
- </Resources>
+ <Resources>
+ <Resource Language="x-generate"/>
+ </Resources>
- <Applications>
- <Application Id="App"
- Executable="$targetnametoken$.exe"
- EntryPoint="$targetentrypoint$"
- desktop4:SupportsMultipleInstances="true">
- <uap:VisualElements
- DisplayName="DevToys - Preview"
- Description="A Swiss-knife for developers."
- BackgroundColor="transparent"
- Square150x150Logo="Assets\Logo\Square150x150Logo.png"
- Square44x44Logo="Assets\Logo\Square44x44Logo.png">
- <uap:DefaultTile Wide310x150Logo="Assets\Logo\Wide310x150Logo.png" ShortName="DevToys" Square310x310Logo="Assets\Logo\LargeTile.png" Square71x71Logo="Assets\Logo\SmallTile.png">
- <uap:ShowNameOnTiles>
- <uap:ShowOn Tile="square150x150Logo"/>
- <uap:ShowOn Tile="wide310x150Logo"/>
- <uap:ShowOn Tile="square310x310Logo"/>
- </uap:ShowNameOnTiles>
- </uap:DefaultTile >
- <uap:SplashScreen Image="Assets\Logo\SplashScreen.png" uap5:Optional="true" />
- <uap:InitialRotationPreference>
- <uap:Rotation Preference="landscape"/>
- <uap:Rotation Preference="portrait"/>
- <uap:Rotation Preference="landscapeFlipped"/>
- <uap:Rotation Preference="portraitFlipped"/>
- </uap:InitialRotationPreference>
- </uap:VisualElements>
- <Extensions>
- <uap:Extension Category="windows.protocol">
- <uap:Protocol ReturnResults="none" Name="devtoys">
- <uap:DisplayName>DevToys URI Scheme</uap:DisplayName>
- <uap:Logo>Assets\Logo\Square512.png</uap:Logo>
- </uap:Protocol>
- </uap:Extension>
- <uap:Extension Category="windows.fileOpenPicker">
- <uap:FileOpenPicker>
- <uap:SupportedFileTypes>
- <uap:SupportsAnyFileType/>
- </uap:SupportedFileTypes>
- </uap:FileOpenPicker>
- </uap:Extension>
- </Extensions>
- </Application>
- </Applications>
+ <Applications>
+ <Application Id="App"
+ Executable="$targetnametoken$.exe"
+ EntryPoint="$targetentrypoint$"
+ desktop4:SupportsMultipleInstances="true">
+ <uap:VisualElements
+ DisplayName="DevToys - Preview"
+ Description="A Swiss-knife for developers."
+ BackgroundColor="transparent"
+ Square150x150Logo="Assets\Logo\Square150x150Logo.png"
+ Square44x44Logo="Assets\Logo\Square44x44Logo.png">
+ <uap:DefaultTile Wide310x150Logo="Assets\Logo\Wide310x150Logo.png" ShortName="DevToys" Square310x310Logo="Assets\Logo\LargeTile.png" Square71x71Logo="Assets\Logo\SmallTile.png">
+ <uap:ShowNameOnTiles>
+ <uap:ShowOn Tile="square150x150Logo"/>
+ <uap:ShowOn Tile="wide310x150Logo"/>
+ <uap:ShowOn Tile="square310x310Logo"/>
+ </uap:ShowNameOnTiles>
+ </uap:DefaultTile >
+ <uap:SplashScreen Image="Assets\Logo\SplashScreen.png" uap5:Optional="true" />
+ <uap:InitialRotationPreference>
+ <uap:Rotation Preference="landscape"/>
+ <uap:Rotation Preference="portrait"/>
+ <uap:Rotation Preference="landscapeFlipped"/>
+ <uap:Rotation Preference="portraitFlipped"/>
+ </uap:InitialRotationPreference>
+ </uap:VisualElements>
+ <Extensions>
+ <uap:Extension Category="windows.protocol">
+ <uap:Protocol ReturnResults="none" Name="devtoys">
+ <uap:DisplayName>DevToys URI Scheme</uap:DisplayName>
+ <uap:Logo>Assets\Logo\Square512.png</uap:Logo>
+ </uap:Protocol>
+ </uap:Extension>
+ <uap:Extension Category="windows.fileOpenPicker">
+ <uap:FileOpenPicker>
+ <uap:SupportedFileTypes>
+ <uap:SupportsAnyFileType/>
+ </uap:SupportedFileTypes>
+ </uap:FileOpenPicker>
+ </uap:Extension>
+ </Extensions>
+ </Application>
+ </Applications>
+
+ <Capabilities>
+ <rescap:Capability Name="inputInjectionBrokered" />
+ </Capabilities>
</Package>
diff --git a/src/dev/shared/SharedAssemblyInfo.cs b/src/dev/shared/SharedAssemblyInfo.cs
index 10b703abb..8c047126e 100644
--- a/src/dev/shared/SharedAssemblyInfo.cs
+++ b/src/dev/shared/SharedAssemblyInfo.cs
@@ -37,7 +37,7 @@ using System.Runtime.CompilerServices;
// Please DO NOT commit changes on the 2 lines below unless
// you're about to release a new version of the app on the Store.
-[assembly: AssemblyVersion("0.0.0.0")]
-[assembly: AssemblyFileVersion("0.0.0.0")]
+[assembly: AssemblyVersion("0.6.0.0")]
+[assembly: AssemblyFileVersion("0.6.0.0")]
[assembly: InternalsVisibleTo("DevToys.Tests")]
diff --git a/src/tests/DevToys.Tests/Properties/AssemblyInfo.cs b/src/tests/DevToys.Tests/Properties/AssemblyInfo.cs
index 2f43efdad..a7fdd8ed6 100644
--- a/src/tests/DevToys.Tests/Properties/AssemblyInfo.cs
+++ b/src/tests/DevToys.Tests/Properties/AssemblyInfo.cs
@@ -1,5 +1,4 @@
using System.Reflection;
-using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DevToys.Tests")]
@@ -10,7 +9,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
-[assembly: AssemblyMetadata("TargetPlatform","UAP")]
+[assembly: AssemblyMetadata("TargetPlatform", "UAP")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
diff --git a/tools/Restore-MonacoEditor.ps1 b/tools/Restore-MonacoEditor.ps1
new file mode 100644
index 000000000..36a4a0467
--- /dev/null
+++ b/tools/Restore-MonacoEditor.ps1
@@ -0,0 +1,63 @@
+# Run this script using PowerShell to download and
+# install dependencies into the project directory before building.
+
+# Reference to Monaco Version to Use in the Package
+$monaco_version = "0.20.0"
+
+# ------------------------
+$monaco_tgz_url = "https://registry.npmjs.org/monaco-editor/-/monaco-editor-$monaco_version.tgz"
+$sharp_zip_lib_url = "https://github.com/icsharpcode/SharpZipLib/releases/download/0.86.0.518/ICSharpCode.SharpZipLib.dll"
+$temp_dir_name = ".temp"
+
+function Get-ScriptDirectory {
+ Split-Path -parent $PSCommandPath
+}
+
+$script_dir = Get-ScriptDirectory
+
+Push-Location $script_dir
+
+function Extract-TGZ {
+ Param([string]$gzArchiveName, [string] $destFolder)
+
+ $inStream = [System.IO.File]::OpenRead($gzArchiveName)
+ $gzipStream = New-Object ICSharpCode.SharpZipLib.GZip.GZipInputStream -ArgumentList $inStream
+
+ $tarArchive = [ICSharpCode.SharpZipLib.Tar.TarArchive]::CreateInputTarArchive($gzipStream);
+ $tarArchive.ExtractContents($destFolder);
+ $tarArchive.Close()
+
+ $gzipStream.Close()
+ $inStream.Close()
+}
+
+# Remove Old Dependency
+Remove-Item "..\src\dev\impl\DevToys.MonacoEditor\monaco-editor" -Force -Recurse -ErrorAction SilentlyContinue
+
+# Create Temp Directory and Output
+New-Item -Name $temp_dir_name -ItemType Directory | Out-Null
+New-Item -Name "..\src\dev\impl\DevToys.MonacoEditor\monaco-editor" -ItemType Directory | Out-Null
+
+Write-Host "Downloading SharpZipLib"
+[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
+Invoke-WebRequest -Uri $sharp_zip_lib_url -OutFile ".\$temp_dir_name\SharpZipLib.dll"
+
+Write-Host "Downloading Monaco"
+
+[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
+Invoke-WebRequest -Uri $monaco_tgz_url -OutFile ".\$temp_dir_name\monaco.tgz"
+
+Write-Host "Extracting..."
+
+# Load Sharp Zip Lib so we can unpack Monaco
+# Load in memory so we can delete the dll after.
+[System.Reflection.Assembly]::Load([IO.File]::ReadAllBytes("$script_dir\$temp_dir_name\SharpZipLib.dll")) | Out-Null
+
+Extract-TGZ "$script_dir\$temp_dir_name\monaco.tgz" "$script_dir\$temp_dir_name\monaco"
+
+Copy-Item -Path ".\$temp_dir_name\monaco\package\*" -Destination "..\src\dev\impl\DevToys.MonacoEditor\monaco-editor" -Recurse
+
+# Clean-up Temp Dir
+Remove-Item $temp_dir_name -Force -Recurse -ErrorAction SilentlyContinue
+
+Pop-Location
\ No newline at end of file
diff --git a/tools/app-version-number.txt b/tools/app-version-number.txt
index 651fa4084..1e43d8f5c 100644
--- a/tools/app-version-number.txt
+++ b/tools/app-version-number.txt
@@ -1 +1 @@
-0.5.2.0
\ No newline at end of file
+0.6.0.0
\ No newline at end of file