A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Added monaco editor
Etienne Baudoux70f2e33250bd
diff --git a/src/DevToys.sln b/src/DevToys.slnindex 45b2f7ee6..a1a124d1a 100644--- a/src/DevToys.sln+++ b/src/DevToys.sln@@ -63,6 +63,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DevToys.UI", "app\dev\DevToEndProjectProject("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "DevToys.UI.EntryPoint", "app\dev\DevToys.UI.EntryPoint\DevToys.UI.EntryPoint.shproj", "{93E31B7F-903D-4F24-B30D-220489242866}"EndProject+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DevToys.MonacoEditor", "app\dev\DevToys.MonacoEditor\DevToys.MonacoEditor.csproj", "{CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}"+EndProjectGlobalGlobalSection(SolutionConfigurationPlatforms) = preSolutionDebug|AnyCPU = Debug|AnyCPU@@ -211,38 +213,54 @@ Global{A730FA8A-3713-4F7A-915D-79098CA12DF0}.Release|x64.Build.0 = Release|Any CPU{A730FA8A-3713-4F7A-915D-79098CA12DF0}.Release|x86.ActiveCfg = Release|Any CPU{A730FA8A-3713-4F7A-915D-79098CA12DF0}.Release|x86.Build.0 = Release|Any CPU- {723A3D71-2425-49EE-B669-1A0DF3A8B486}.Debug|AnyCPU.ActiveCfg = Debug|Any CPU- {723A3D71-2425-49EE-B669-1A0DF3A8B486}.Debug|AnyCPU.Build.0 = Debug|Any CPU+ {723A3D71-2425-49EE-B669-1A0DF3A8B486}.Debug|AnyCPU.ActiveCfg = Debug|x86+ {723A3D71-2425-49EE-B669-1A0DF3A8B486}.Debug|AnyCPU.Build.0 = Debug|x86{723A3D71-2425-49EE-B669-1A0DF3A8B486}.Debug|ARM64.ActiveCfg = Debug|arm64{723A3D71-2425-49EE-B669-1A0DF3A8B486}.Debug|ARM64.Build.0 = Debug|arm64{723A3D71-2425-49EE-B669-1A0DF3A8B486}.Debug|x64.ActiveCfg = Debug|x64{723A3D71-2425-49EE-B669-1A0DF3A8B486}.Debug|x64.Build.0 = Debug|x64{723A3D71-2425-49EE-B669-1A0DF3A8B486}.Debug|x86.ActiveCfg = Debug|x86{723A3D71-2425-49EE-B669-1A0DF3A8B486}.Debug|x86.Build.0 = Debug|x86- {723A3D71-2425-49EE-B669-1A0DF3A8B486}.Release|AnyCPU.ActiveCfg = Release|Any CPU- {723A3D71-2425-49EE-B669-1A0DF3A8B486}.Release|AnyCPU.Build.0 = Release|Any CPU+ {723A3D71-2425-49EE-B669-1A0DF3A8B486}.Release|AnyCPU.ActiveCfg = Release|x86+ {723A3D71-2425-49EE-B669-1A0DF3A8B486}.Release|AnyCPU.Build.0 = Release|x86{723A3D71-2425-49EE-B669-1A0DF3A8B486}.Release|ARM64.ActiveCfg = Release|arm64{723A3D71-2425-49EE-B669-1A0DF3A8B486}.Release|ARM64.Build.0 = Release|arm64{723A3D71-2425-49EE-B669-1A0DF3A8B486}.Release|x64.ActiveCfg = Release|x64{723A3D71-2425-49EE-B669-1A0DF3A8B486}.Release|x64.Build.0 = Release|x64{723A3D71-2425-49EE-B669-1A0DF3A8B486}.Release|x86.ActiveCfg = Release|x86{723A3D71-2425-49EE-B669-1A0DF3A8B486}.Release|x86.Build.0 = Release|x86- {104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Debug|AnyCPU.ActiveCfg = Debug|Any CPU- {104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Debug|AnyCPU.Build.0 = Debug|Any CPU+ {104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Debug|AnyCPU.ActiveCfg = Debug|x86+ {104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Debug|AnyCPU.Build.0 = Debug|x86{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Debug|ARM64.ActiveCfg = Debug|arm64{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Debug|ARM64.Build.0 = Debug|arm64{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Debug|x64.ActiveCfg = Debug|x64{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Debug|x64.Build.0 = Debug|x64{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Debug|x86.ActiveCfg = Debug|x86{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Debug|x86.Build.0 = Debug|x86- {104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Release|AnyCPU.ActiveCfg = Release|Any CPU- {104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Release|AnyCPU.Build.0 = Release|Any CPU+ {104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Release|AnyCPU.ActiveCfg = Release|x86+ {104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Release|AnyCPU.Build.0 = Release|x86{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Release|ARM64.ActiveCfg = Release|arm64{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Release|ARM64.Build.0 = Release|arm64{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Release|x64.ActiveCfg = Release|x64{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Release|x64.Build.0 = Release|x64{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Release|x86.ActiveCfg = Release|x86{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A}.Release|x86.Build.0 = Release|x86+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Debug|AnyCPU.ActiveCfg = Debug|x86+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Debug|AnyCPU.Build.0 = Debug|x86+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Debug|ARM64.ActiveCfg = Debug|arm64+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Debug|ARM64.Build.0 = Debug|arm64+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Debug|x64.ActiveCfg = Debug|x64+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Debug|x64.Build.0 = Debug|x64+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Debug|x86.ActiveCfg = Debug|x86+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Debug|x86.Build.0 = Debug|x86+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Release|AnyCPU.ActiveCfg = Release|x86+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Release|AnyCPU.Build.0 = Release|x86+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Release|ARM64.ActiveCfg = Release|arm64+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Release|ARM64.Build.0 = Release|arm64+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Release|x64.ActiveCfg = Release|x64+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Release|x64.Build.0 = Release|x64+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Release|x86.ActiveCfg = Release|x86+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8}.Release|x86.Build.0 = Release|x86EndGlobalSectionGlobalSection(SolutionProperties) = preSolutionHideSolutionNode = FALSE@@ -267,6 +285,7 @@ Global{723A3D71-2425-49EE-B669-1A0DF3A8B486} = {B20E4027-0777-4A75-A848-609594E9A6B0}{104F1E4B-E0D3-4D87-9DA0-3FE82FE2573A} = {B20E4027-0777-4A75-A848-609594E9A6B0}{93E31B7F-903D-4F24-B30D-220489242866} = {B20E4027-0777-4A75-A848-609594E9A6B0}+ {CDD8B469-ACA6-4A7D-91A0-66ADB0563AE8} = {B20E4027-0777-4A75-A848-609594E9A6B0}EndGlobalSectionGlobalSection(ExtensibilityGlobals) = postSolutionSolutionGuid = {C2C953F5-F97F-4198-B15C-4947A886050F}diff --git a/src/Directory.Packages.props b/src/Directory.Packages.propsindex 75f56b44d..7655ffe3c 100644--- a/src/Directory.Packages.props+++ b/src/Directory.Packages.props@@ -11,6 +11,7 @@<PolySharpVersion>1.8.1</PolySharpVersion><UnoVersion>4.6.19</UnoVersion><UnoWasmBootstrapVersion>8.0.0-dev.65</UnoWasmBootstrapVersion>+ <WebView2Version>1.0.1264.42</WebView2Version></PropertyGroup><ItemGroup><PackageVersion Include="CommunityToolkit.Common" Version="$(CommunityToolkitVersion)" />@@ -25,21 +26,21 @@<PackageVersion Include="Microsoft.Extensions.Logging.Debug" Version="$(DotNetVersion)" /><PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.1.0" /><PackageVersion Include="Microsoft.TypeScript.MSBuild" Version="4.9.4" />- <PackageVersion Include="Microsoft.UI.Xaml" Version="2.8.1"/>+ <PackageVersion Include="Microsoft.UI.Xaml" Version="2.8.1" />+ <PackageVersion Include="Microsoft.Web.WebView2" Version="$(WebView2Version)" /><PackageVersion Include="Microsoft.Windows.Compatibility" Version="$(DotNetVersion)" /><PackageVersion Include="Microsoft.Windows.SDK.BuildTools" Version="$(MicrosoftWindowsSDKBuildToolsVersion)" /><PackageVersion Include="Moq" Version="4.18.2" /><PackageVersion Include="Newtonsoft.Json" Version="13.0.1" />- <PackageVersion Include="Nito.AsyncEx" Version="5.1.2"/>+ <PackageVersion Include="Nito.AsyncEx" Version="5.1.2" /><PackageVersion Include="Nuke.Common" Version="6.2.1" /><PackageVersion Include="PolySharp" Version="$(PolySharpVersion)" />- <PackageVersion Include="System.CommandLine" Version="2.0.0-beta4.22272.1"/>+ <PackageVersion Include="System.CommandLine" Version="2.0.0-beta4.22272.1" /><PackageVersion Include="System.ComponentModel.Composition" Version="$(DotNetVersion)" /><PackageVersion Include="System.Threading.Tasks.Extensions" Version="4.5.4" /><PackageVersion Include="Uno.Core.Extensions.Logging" Version="4.0.1" /><PackageVersion Include="Uno.Core.Extensions.Logging.Singleton" Version="4.0.1" /><PackageVersion Include="Uno.Extensions.Logging.WebAssembly.Console" Version="1.4.0" />- <PackageVersion Include="Uno.UI" Version="$(UnoVersion)" /><PackageVersion Include="Uno.UI.Adapter.Microsoft.Extensions.Logging" Version="$(UnoVersion)" /><PackageVersion Include="Uno.Wasm.Bootstrap" Version="$(UnoWasmBootstrapVersion)" /><PackageVersion Include="Uno.Wasm.Bootstrap.DevServer" Version="$(UnoWasmBootstrapVersion)" />diff --git a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.Windows.html b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.Windows.htmlnew file mode 100644index 000000000..c555ad0fa--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.Windows.html@@ -0,0 +1,33 @@+<!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>++ <script src="https://devtoys.local/monaco-editor/min/vs/loader.js"></script>+ <script src="https://devtoys.local/ts-helpermethods/editorContext.js"></script>+ <script src="https://devtoys.local/ts-helpermethods/ts-helpermethods-Windows/asyncCallbackHelpers.js"></script>+ <script src="https://devtoys.local/ts-helpermethods/registerCodeLensProvider.js"></script>+ <script src="https://devtoys.local/ts-helpermethods/registerColorProvider.js"></script>+ <script src="https://devtoys.local/ts-helpermethods/registerCompletionItemProvider.js"></script>+ <script src="https://devtoys.local/ts-helpermethods/otherScriptsToBeOrganized.js"></script>+ <script src="https://devtoys.local/ts-helpermethods/updateSelection.js"></script>+ <script src="https://devtoys.local/ts-helpermethods/monacoInitializer.js"></script>+</head>+<body>++ <div id="container" onkeydown="keyDown(event)"></div>+</body>+</html>\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.cs b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.csnew file mode 100644index 000000000..38e2381df--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.cs@@ -0,0 +1,727 @@+using System.Reflection;+using System.Runtime.CompilerServices;+using DevToys.Core.Threading;+using DevToys.MonacoEditor.Extensions;+using DevToys.MonacoEditor.Monaco;+using DevToys.MonacoEditor.Monaco.Editor;+using DevToys.MonacoEditor.WebInterop;+using DevToys.MonacoEditor.WebInterop.Parent;+using DevToys.MonacoEditor.WebInterop.Theme;+using DevToys.UI.Framework.Threading;+using Microsoft.Web.WebView2.Core;+using Windows.Foundation;+using Range = DevToys.MonacoEditor.Monaco.Range;++#if WINDOWS_UWP+using Windows.UI.Xaml;+using Windows.UI.Xaml.Controls;+using DispatcherQueue = Windows.UI.Core.CoreDispatcher;+#else+using Microsoft.UI.Dispatching;+using Microsoft.UI.Xaml;+using Microsoft.UI.Xaml.Controls;+#endif++namespace DevToys.MonacoEditor;++/// <summary>+/// .Net wrapper for the Monaco CodeEditor+/// https://microsoft.github.io/monaco-editor/+/// </summary>+[TemplatePart(Name = "View", Type = typeof(ICodeEditorPresenter))]+[TemplateVisualState(Name = NormalState, GroupName = CommonStates)]+[TemplateVisualState(Name = PointerOverState, GroupName = CommonStates)]+[TemplateVisualState(Name = FocusedState, GroupName = CommonStates)]+[TemplateVisualState(Name = DisabledState, GroupName = CommonStates)]+public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisposable+{+ 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";++#if WINDOWS_UWP+ private DispatcherQueue UIAccess => DispatcherQueueExtensions.DispatcherQueue;+#else+ private DispatcherQueue UIAccess => this.DispatcherQueue;+#endif++ private readonly DebugLogger _debugLogger = new();+ private readonly ThemeListener _themeListener;+ private readonly long _themeToken;++ private ICodeEditorPresenter? _view;+ private bool _initialized;+ private ModelHelper? _model;++ public CodeEditor()+ {+ DefaultStyleKey = typeof(CodeEditor);++ UIAccess.ThrowIfNotOnUIThread();++ ParentAccessor = new ParentAccessor(this);+ ParentAccessor.AddAssemblyForTypeLookup(typeof(Range).GetTypeInfo().Assembly);+ ParentAccessor.RegisterAction("Loaded", OnMonacoEditorLoaded);+ ParentAccessor.RegisterAction("GotFocus", OnMonacoEditorGotFocus);+ ParentAccessor.RegisterAction("LostFocus", OnMonacoEditorLostFocus);++ _themeListener = new ThemeListener(UIAccess);+ _themeListener.ThemeChanged += ThemeListener_ThemeChanged;+ _themeToken = RegisterPropertyChangedCallback(ActualThemeProperty, ActualTheme_PropertyChanged);++ Options = new StandaloneEditorConstructionOptions();+ DiffOptions = new DiffEditorConstructionOptions();++ Options.GlyphMargin = false;+ DiffOptions.GlyphMargin = false;++ Options.PropertyChanged += Options_PropertyChanged;+ DiffOptions.PropertyChanged += DiffOptions_PropertyChanged;++ Unloaded += CodeEditor_Unloaded;+ }++ public static DependencyProperty IsEditorLoadedProperty { get; }+ = DependencyProperty.Register(+ nameof(IsEditorLoaded),+ typeof(string),+ typeof(CodeEditor),+ new PropertyMetadata(false));++ /// <summary>+ /// Gets whether the editor has been loaded or not.+ /// </summary>+ public bool IsEditorLoaded+ {+ get => (bool)GetValue(IsEditorLoadedProperty);+ private set => SetValue(IsEditorLoadedProperty, value);+ }++ public static DependencyProperty IsDiffViewModeProperty { get; }+ = DependencyProperty.Register(+ nameof(IsDiffViewMode),+ typeof(bool),+ typeof(CodeEditor),+ new PropertyMetadata(false));++ /// <summary>+ /// Gets or sets whether the CodeEditor is in Diff View mode.+ /// </summary>+ public bool IsDiffViewMode+ {+ get => (bool)GetValue(IsDiffViewModeProperty);+ set => SetValue(IsDiffViewModeProperty, value);+ }++ public static DependencyProperty TextProperty { get; }+ = DependencyProperty.Register(+ nameof(Text),+ typeof(string),+ typeof(CodeEditor),+ new PropertyMetadata(+ string.Empty,+ async (d, e) =>+ {+ if (d is CodeEditor { IsSettingValue: false } codeEditor && codeEditor._initialized)+ {+ // link:otherScriptsToBeOrganized.ts:updateContent+ await codeEditor.InvokeScriptAsync("updateContent", e.NewValue.ToString() ?? string.Empty);+ }+ }));++ /// <summary>+ /// Gets or sets the CodeEditor 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(CodeEditor),+ new PropertyMetadata(+ string.Empty,+ async (d, e) =>+ {+ if (d is CodeEditor { IsSettingValue: false } codeEditor && codeEditor._initialized)+ {+ // link:updateSelectedContent.ts:updateSelectedContent+ await codeEditor.InvokeScriptAsync("updateSelectedContent", e.NewValue.ToString() ?? string.Empty);+ }+ }));++ /// <summary>+ /// Gets the current Primary Selected CodeEditor Text, or replace the current selection by the given 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(CodeEditor),+ new PropertyMetadata(null));++ /// <summary>+ /// Gets or sets the span to select in the editor+ /// </summary>+ public Selection SelectedRange+ {+ get => (Selection)GetValue(SelectedRangeProperty);+ internal set => SetValue(SelectedRangeProperty, value);+ }++ public static DependencyProperty ReadOnlyProperty { get; }+ = DependencyProperty.Register(+ nameof(ReadOnly),+ typeof(bool),+ typeof(CodeEditor),+ new PropertyMetadata(+ false,+ (d, e) =>+ {+ if (d is not CodeEditor editor)+ {+ return;+ }++ if (editor.Options != null && editor._initialized)+ {+ editor.Options.ReadOnly = bool.Parse(e.NewValue?.ToString() ?? "false");+ }++ if (editor.DiffOptions != null && editor._initialized)+ {+ editor.DiffOptions.OriginalEditable = !bool.Parse(e.NewValue?.ToString() ?? "false");+ editor.DiffOptions.ReadOnly = bool.Parse(e.NewValue?.ToString() ?? "false");+ }+ }));++ /// <summary>+ /// Gets or sets whether the editor is read-only.+ /// </summary>+ public bool ReadOnly+ {+ get => (bool)GetValue(ReadOnlyProperty);+ set => SetValue(ReadOnlyProperty, value);+ }++ public static DependencyProperty CodeLanguageProperty { get; }+ = DependencyProperty.Register(+ nameof(CodeLanguage),+ typeof(string),+ typeof(CodeEditor),+ new PropertyMetadata(+ string.Empty,+ (d, e) =>+ {+ if (d is not CodeEditor editor)+ {+ return;+ }++ if (editor.Options != null && editor._initialized)+ {+ editor.Options.Language = e.NewValue.ToString();+ }+ }));++ /// <summary>+ /// Set the Syntax Language for the editor.+ /// Note: Most likely to change or move location.+ /// </summary>+ public string? CodeLanguage+ {+ get => (string?)GetValue(CodeLanguageProperty);+ set => SetValue(CodeLanguageProperty, value);+ }++ public static DependencyProperty OptionsProperty { get; } = DependencyProperty.Register(+ nameof(Options),+ typeof(StandaloneEditorConstructionOptions),+ typeof(CodeEditor),+ new PropertyMetadata(+ null,+ (d, e) =>+ {+ if (d is CodeEditor editor)+ {+ if (e.OldValue is StandaloneEditorConstructionOptions oldValue)+ {+ oldValue.PropertyChanged -= editor.Options_PropertyChanged;+ }++ if (e.NewValue is StandaloneEditorConstructionOptions value)+ {+ value.PropertyChanged += editor.Options_PropertyChanged;+ }+ }+ }));++ /// <summary>+ /// Gets the CodeEditor Options.+ /// </summary>+ public StandaloneEditorConstructionOptions Options+ {+ get => (StandaloneEditorConstructionOptions)GetValue(OptionsProperty);+ private set => SetValue(OptionsProperty, value);+ }++ public static DependencyProperty DiffLeftTextProperty { get; }+ = DependencyProperty.Register(+ nameof(DiffLeftText),+ typeof(string),+ typeof(CodeEditor),+ new PropertyMetadata(+ string.Empty,+ (d, e) =>+ {+ var codeEditor = (CodeEditor)d;+ if (!codeEditor.IsSettingValue && codeEditor.IsDiffViewMode)+ {+ _ = codeEditor.InvokeScriptAsync("updateDiffContent", new object[] { e.NewValue.ToString() ?? string.Empty, codeEditor.DiffRightText });+ }+ }));++ /// <summary>+ /// Gets or sets the text to display in the left pane of the side-by-side diff view.+ /// </summary>+ public string DiffLeftText+ {+ get => (string)GetValue(DiffLeftTextProperty);+ set => SetValue(DiffLeftTextProperty, value);+ }++ public static DependencyProperty DiffRightTextProperty { get; }+ = DependencyProperty.Register(+ nameof(DiffRightText),+ typeof(string),+ typeof(CodeEditor),+ new PropertyMetadata(+ string.Empty,+ (d, e) =>+ {+ var codeEditor = (CodeEditor)d;+ if (!codeEditor.IsSettingValue && codeEditor.IsDiffViewMode)+ {+ _ = codeEditor.InvokeScriptAsync("updateDiffContent", new object[] { codeEditor.DiffLeftText, e.NewValue.ToString() ?? string.Empty });+ }+ }));++ /// <summary>+ /// Gets or sets the text to display in the right pane of the side-by-side diff view.+ /// </summary>+ public string DiffRightText+ {+ get => (string)GetValue(DiffRightTextProperty);+ set => SetValue(DiffRightTextProperty, value);+ }++ public static DependencyProperty DiffOptionsProperty { get; }+ = DependencyProperty.Register(+ nameof(DiffOptions),+ typeof(DiffEditorConstructionOptions),+ typeof(CodeEditor),+ new PropertyMetadata(+ null,+ (d, e) =>+ {+ if (d is CodeEditor 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.+ /// </summary>+ public DiffEditorConstructionOptions DiffOptions+ {+ get => (DiffEditorConstructionOptions)GetValue(DiffOptionsProperty);+ set => SetValue(DiffOptionsProperty, value);+ }++ public bool IsSettingValue { get; set; }++ internal ParentAccessor ParentAccessor { get; }++ /// <summary>+ /// When Editor is Loaded, it has been rendered and is ready to be displayed.+ /// </summary>+ public event RoutedEventHandler? EditorLoaded;++ /// <summary>+ /// Called when an internal exception is encountered while executing a command. (for testing/reporting issues)+ /// </summary>+ public event TypedEventHandler<CodeEditor, Exception>? InternalException;++ /// <summary>+ /// Called when a link is Ctrl+Clicked on in the editor, set Handled to true to prevent opening.+ /// </summary>+ public event TypedEventHandler<CodeEditor, CoreWebView2NewWindowRequestedEventArgs>? OpenLinkRequested;++#if HAS_UNO+ public new void Dispose()+#else+ public void Dispose()+#endif+ {+ ParentAccessor.Dispose();+ }++ internal IModel GetModel()+ {+ return _model ?? throw new NotSupportedException($"Model is not available");+ }++ 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)+ {+ Guard.IsNotNull(_view);+ try+ {+ 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)+ {+ Guard.IsNotNull(_view);+ try+ {+ 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;+ }++ protected override void OnApplyTemplate()+ {+ if (_view is not null)+ {+ _view.NavigationStarting -= WebView_NavigationStarting;+ _view.DOMContentLoaded -= WebView_DOMContentLoaded;+ _view.NavigationCompleted -= WebView_NavigationCompleted;+ _view.NewWindowRequested -= WebView_NewWindowRequested;+ _view.DotNetObjectInjectionRequested -= WebView_DotNetObjectInjectionRequested;+ _view.GotFocus -= WebView_GotFocus;+ _view.LostFocus -= WebView_LostFocus;+ Debug.WriteLine("Setting initialized - false");+ _initialized = false;+ }++ Guard.IsFalse(_initialized);+ _view = (ICodeEditorPresenter)GetTemplateChild("View");++ if (_view is not null)+ {+ _view.NavigationStarting += WebView_NavigationStarting;+ _view.DOMContentLoaded += WebView_DOMContentLoaded;+ _view.NavigationCompleted += WebView_NavigationCompleted;+ _view.NewWindowRequested += WebView_NewWindowRequested;+ _view.DotNetObjectInjectionRequested += WebView_DotNetObjectInjectionRequested;+ _view.GotFocus += WebView_GotFocus;+ _view.LostFocus += WebView_LostFocus;++ _view.LaunchAsync().Forget();++ base.OnApplyTemplate();+ }+ }++ protected override void OnGotFocus(RoutedEventArgs e)+ {+ base.OnGotFocus(e);++ GiveFocusToInnerEditor();+ }++ private void CodeEditor_Unloaded(object sender, RoutedEventArgs e)+ {+ if (_view != null)+ {+ _view.NavigationStarting -= WebView_NavigationStarting;+ _view.DOMContentLoaded -= WebView_DOMContentLoaded;+ _view.NavigationCompleted -= WebView_NavigationCompleted;+ _view.NewWindowRequested -= WebView_NewWindowRequested;+ _view.DotNetObjectInjectionRequested -= WebView_DotNetObjectInjectionRequested;+ }++ Options.PropertyChanged -= Options_PropertyChanged;+ DiffOptions.PropertyChanged -= DiffOptions_PropertyChanged;+ _themeListener.ThemeChanged -= ThemeListener_ThemeChanged;++ UnregisterPropertyChangedCallback(ActualThemeProperty, _themeToken);++ _initialized = false;+ }++ private void Options_PropertyChanged(object? sender, PropertyChangedEventArgs e)+ {+ if (sender is not StandaloneEditorConstructionOptions options || IsDiffViewMode || !_initialized)+ {+ return;+ }++ if (e.PropertyName == nameof(StandaloneEditorConstructionOptions.Language))+ {+ InvokeScriptAsync("updateLanguage", options.Language ?? string.Empty).Forget();+ if (CodeLanguage != options.Language)+ {+ CodeLanguage = options.Language;+ }+ }++ if (e.PropertyName == nameof(StandaloneEditorConstructionOptions.ReadOnly))+ {+ if (ReadOnly != options.ReadOnly)+ {+ options.ReadOnly = ReadOnly;+ }+ }++ InvokeScriptAsync("updateOptions", options).Forget();+ }++ private void DiffOptions_PropertyChanged(object? sender, PropertyChangedEventArgs e)+ {+ if (sender is not DiffEditorConstructionOptions options || !IsDiffViewMode || !_initialized)+ {+ return;+ }++ if (e.PropertyName == nameof(DiffEditorConstructionOptions.ReadOnly))+ {+ if (ReadOnly != options.ReadOnly)+ {+ options.ReadOnly = ReadOnly;+ }+ }++ InvokeScriptAsync("updateDiffOptions", options).Forget();+ }++ private void ActualTheme_PropertyChanged(DependencyObject obj, DependencyProperty property)+ {+ ElementTheme theme = ActualTheme;+ string themeName = string.Empty;++ if (theme == ElementTheme.Default)+ {+ themeName = _themeListener.CurrentThemeName;+ }+ else+ {+ themeName = theme.ToString();+ }++ UIAccess.RunOnUIThreadAsync(async () =>+ {+ await InvokeScriptAsync("setTheme", args: new string[] { _themeListener!.AccentColorHtmlHex });+ await InvokeScriptAsync("changeTheme", new string[] { themeName, _themeListener.IsHighContrast.ToString() });+ }).Forget();+ }++ private void ThemeListener_ThemeChanged(ThemeListener sender)+ {+ if (RequestedTheme == ElementTheme.Default)+ {+ UIAccess.RunOnUIThreadAsync(async () =>+ {+ await InvokeScriptAsync("setTheme", args: new string[] { sender.AccentColorHtmlHex });+ await InvokeScriptAsync("changeTheme", args: new string[] { sender.CurrentTheme.ToString(), sender.IsHighContrast.ToString() });+ }).Forget();+ }+ }++ private async Task WebView_DotNetObjectInjectionRequested(ICodeEditorPresenter sender, EventArgs args)+ {+ Guard.IsNotNull(_view);+ Guard.IsFalse(_initialized);++ var tasks = new List<Task>+ {+ _view.InjectDotNetObjectToWebPageAsync("Debug", _debugLogger),+ _view.InjectDotNetObjectToWebPageAsync("Accessor", ParentAccessor),+ _view.InjectDotNetObjectToWebPageAsync("Theme", _themeListener)+ };++ await Task.WhenAll(tasks);+ }++ private void WebView_NavigationStarting(ICodeEditorPresenter sender, CoreWebView2NavigationStartingEventArgs args)+ {+ }++ private void WebView_NavigationCompleted(ICodeEditorPresenter sender, CoreWebView2NavigationCompletedEventArgs args)+ {+ }++ private void WebView_DOMContentLoaded(ICodeEditorPresenter sender, CoreWebView2DOMContentLoadedEventArgs args)+ {+ }++ private void WebView_NewWindowRequested(ICodeEditorPresenter sender, CoreWebView2NewWindowRequestedEventArgs args)+ {+ // TODO: Should probably create own event args here as we don't want to expose the referrer to our internal page?+ OpenLinkRequested?.Invoke(this, args);+ }++ private void WebView_GotFocus(ICodeEditorPresenter sender, RoutedEventArgs args)+ {+ OnMonacoEditorGotFocus();+ }++ private void WebView_LostFocus(ICodeEditorPresenter sender, RoutedEventArgs args)+ {+ OnMonacoEditorLostFocus();+ }++ private void OnMonacoEditorGotFocus()+ {+ VisualStateManager.GoToState(this, FocusedState, false);+ }++ private void OnMonacoEditorLostFocus()+ {+ VisualStateManager.GoToState(this, NormalState, false);+ }++ private void OnMonacoEditorLoaded()+ {+ _model = new ModelHelper(this);++ _initialized = true;++ // Update theme+ InvokeScriptAsync(+ "setTheme",+ args: new string[] { _themeListener!.AccentColorHtmlHex })+ .Forget();+ InvokeScriptAsync(+ "changeTheme",+ new string[] { _themeListener.CurrentTheme.ToString(), _themeListener.IsHighContrast.ToString() })+ .Forget();++ // Update options.+ Options.ReadOnly = ReadOnly;+ Options.Language = CodeLanguage;+ DiffOptions.OriginalEditable = !ReadOnly;+ DiffOptions.ReadOnly = ReadOnly;++ // We're done loading Monaco Editor.+ IsEditorLoaded = true;+ EditorLoaded?.Invoke(this, new RoutedEventArgs());++ // Give the focus if necessary.+ GiveFocusToInnerEditor();+ }++ private void GiveFocusToInnerEditor()+ {+ if (_initialized)+ {+ // Make sure inner editor is focused+ Guard.IsNotNull(_view);+ _view.Focus(FocusState.Programmatic);+ SendScriptAsync("editorContext.editor.focus();").Forget();+ }+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Wasm.cs b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Wasm.csnew file mode 100644index 000000000..1cefe5d0a--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Wasm.cs@@ -0,0 +1,193 @@+#if __WASM__++using System.Reflection;+using System.Xml.Linq;+using DevToys.Core.Threading;+using DevToys.UI.Framework.Threading;+using Microsoft.Extensions.Logging;+using Microsoft.UI;+using Microsoft.UI.Dispatching;+using Microsoft.UI.Xaml;+using Microsoft.UI.Xaml.Controls;+using Microsoft.UI.Xaml.Media;+using Microsoft.Web.WebView2.Core;+using Uno.Extensions;+using Uno.Foundation.Interop;+using Uno.Logging;+using Uno.UI.Runtime.WebAssembly;+using Windows.Foundation;++namespace DevToys.MonacoEditor;++/// <summary>+/// Provides a <div> object in the app's web page that will show the Monaco Editor.+/// </summary>+[HtmlElement("div")]+public sealed partial class CodeEditorPresenter : Control, ICodeEditorPresenter, IJSObject+{+ private static readonly string UNO_BOOTSTRAP_APP_BASE = Environment.GetEnvironmentVariable(nameof(UNO_BOOTSTRAP_APP_BASE)) ?? string.Empty;+ private static readonly string UNO_BOOTSTRAP_WEBAPP_BASE_PATH = Environment.GetEnvironmentVariable(nameof(UNO_BOOTSTRAP_WEBAPP_BASE_PATH)) ?? string.Empty;++ private readonly JSObjectHandle _handle;+ private readonly ILogger? _debugLogger;+ private readonly ILogger? _informationLogger;+ private readonly ILogger? _errorLogger;+ private readonly string _htmlId;++ public CodeEditorPresenter()+ {+ Guard.IsNotNullOrEmpty(UNO_BOOTSTRAP_APP_BASE);++ Background = new SolidColorBrush(Colors.Transparent);+ _handle = JSObjectHandle.Create(this);++ _htmlId = this.GetHtmlId();++ ILogger logger = this.Log();+ _debugLogger = logger.IsEnabled(LogLevel.Debug) ? logger : null;+ _informationLogger = logger.IsEnabled(LogLevel.Information) ? logger : null;+ _errorLogger = logger.IsEnabled(LogLevel.Error) ? logger : null;+ }++ /// <inheritdoc />+ JSObjectHandle IJSObject.Handle => _handle;++ /// <inheritdoc />+ public event TypedEventHandler<ICodeEditorPresenter, CoreWebView2NewWindowRequestedEventArgs>? NewWindowRequested;++ /// <inheritdoc />+ public event TypedEventHandler<ICodeEditorPresenter, CoreWebView2NavigationStartingEventArgs>? NavigationStarting;++ /// <inheritdoc />+ public event TypedEventHandler<ICodeEditorPresenter, CoreWebView2DOMContentLoadedEventArgs>? DOMContentLoaded;++ /// <inheritdoc />+ public event TypedEventHandler<ICodeEditorPresenter, CoreWebView2NavigationCompletedEventArgs>? NavigationCompleted;++ /// <inheritdoc />+ public event AsyncTypedEventHandler<ICodeEditorPresenter, EventArgs>? DotNetObjectInjectionRequested;++ /// <inheritdoc />+ public new event TypedEventHandler<ICodeEditorPresenter, RoutedEventArgs>? GotFocus;++ /// <inheritdoc />+ public new event TypedEventHandler<ICodeEditorPresenter, RoutedEventArgs>? LostFocus;++ public async Task LaunchAsync()+ {+ await DispatcherQueue.RunOnUIThreadAsync(+ DispatcherQueuePriority.Low,+ () => NavigationStarting?.Invoke(this, new CoreWebView2NavigationStartingEventArgs()));++ await DispatcherQueue.RunOnUIThreadAsync(+ DispatcherQueuePriority.Low,+ () => DOMContentLoaded?.Invoke(this, new CoreWebView2DOMContentLoadedEventArgs()));++ // Request to inject .Net web object into the web page.+ Guard.IsNotNull(DotNetObjectInjectionRequested);+ await DotNetObjectInjectionRequested.Invoke(this, EventArgs.Empty);++ try+ {+ _informationLogger?.Info($"{nameof(LaunchAsync)}: Creating Monaco Editor");++ string monacoEditorJavaScriptEntryPoint = $@"createMonacoEditor('{UNO_BOOTSTRAP_WEBAPP_BASE_PATH}{UNO_BOOTSTRAP_APP_BASE}/devtoys.monacoeditor', element)";+ this.ExecuteJavascript(monacoEditorJavaScriptEntryPoint);++ _informationLogger?.Info($"{nameof(LaunchAsync)}: Monaco Editor created successfully");+ }+ catch (Exception e)+ {+ _errorLogger?.Error($"{nameof(LaunchAsync)} failed", e);+ }++ await DispatcherQueue.RunOnUIThreadAsync(+ DispatcherQueuePriority.Low,+ () => NavigationCompleted?.Invoke(this, new CoreWebView2NavigationCompletedEventArgs()));+ }++ public Task InjectDotNetObjectToWebPageAsync<T>(string name, T pObject)+ {+ _debugLogger?.Debug($"{nameof(InjectDotNetObjectToWebPageAsync)}: Trying to inject .NET object in web page - {name}");+ if (pObject is IJSObject obj)+ {+ MethodInfo? method = obj.Handle.GetType().GetMethod("GetNativeInstance", BindingFlags.NonPublic | BindingFlags.Instance);+ if (method is null)+ {+ _errorLogger?.Error($"{nameof(InjectDotNetObjectToWebPageAsync)}: GetNativeInstance method doesn't exist.");+ return Task.CompletedTask;+ }++ string? native = method.Invoke(obj.Handle, new object[] { }) as string;+ _debugLogger?.Debug($"{nameof(InjectDotNetObjectToWebPageAsync)}: Native handle {native} - {name}");++ string injectorScript+ = @$"+ var value = {native};+ var frame = Uno.UI.WindowManager.current.getView({_htmlId});+ var editorContext = EditorContext.getEditorForElement(frame);+ editorContext.{name} = value+ ";++ try+ {+ this.ExecuteJavascript(injectorScript);+ _debugLogger?.Debug($"{nameof(InjectDotNetObjectToWebPageAsync)}: '{name}' injected successfully.");+ }+ catch (Exception ex)+ {+ _errorLogger?.Error($"{nameof(InjectDotNetObjectToWebPageAsync)} failed - {name}", ex);+ }+ }+ else+ {+ _errorLogger?.Error($"{nameof(InjectDotNetObjectToWebPageAsync)}: '{name}' is not a JSObject");+ throw new InvalidOperationException($"{nameof(InjectDotNetObjectToWebPageAsync)}: '{name}' is not a JSObject");+ }++ return Task.CompletedTask;+ }++ public Task<string> InvokeScriptAsync(string script)+ {+ script = $@"+ (function() {{+ try {{+ window.__evalMethod = function() {{+ let frame = Uno.UI.WindowManager.current.getView({_htmlId});+ let editorContext = EditorContext.getEditorForElement(frame);+ {script}+ }};++ return window.eval(""__evalMethod()"") || """";+ }}+ catch(err){{+ let frame = Uno.UI.WindowManager.current.getView({_htmlId});+ let editorContext = EditorContext.getEditorForElement(frame);+ editorContext.Debug.log(err);+ }}+ finally {{+ window.__evalMethod = null;+ }}+ }})()";++ _debugLogger?.Debug($"Invoke Script: {script}");++ try+ {+ string result = this.ExecuteJavascript(script);++ _debugLogger?.Debug($"Invoke Script result: {result}");++ return Task.FromResult(result);+ }+ catch (Exception e)+ {+ _errorLogger?.Error("Invoke Script failed", e);++ return Task.FromResult(string.Empty);+ }+ }+}++#endifdiff --git a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Windows.cs b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Windows.csnew file mode 100644index 000000000..f00ead3fd--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Windows.cs@@ -0,0 +1,409 @@+#if WINDOWS_UWP++using System.Reflection;+using System.Text;+using DevToys.UI.Framework.Threading;+using Microsoft.Extensions.Logging;+using Microsoft.UI.Xaml.Controls;+using Microsoft.Web.WebView2.Core;+using Newtonsoft.Json;+using Uno.Extensions;+using Uno.Logging;+using Windows.Foundation;+using Windows.Storage;+using Windows.UI;+using Windows.UI.Core;+using Windows.UI.Xaml;+using Windows.UI.Xaml.Controls;+using DispatcherQueue = Windows.UI.Core.CoreDispatcher;++namespace DevToys.MonacoEditor;++/// <summary>+/// Provides a WebView that displays the Monaco Editor.+/// </summary>+public sealed partial class CodeEditorPresenter : UserControl, ICodeEditorPresenter+{+ private static readonly List<TypedEventHandler<WebView2, CoreWebView2WebMessageReceivedEventArgs>> Handlers = new();++ private enum PropertyAction+ {+ Read = 0,+ Write = 1,+ }++ private struct WebMessage+ {+ public Guid Guid { get; set; }+ }++ private struct MethodWebMessage+ {+ public string Id { get; set; }+ public string Method { get; set; }+ public string Args { get; set; }+ }++ private struct PropertyWebMessage+ {+ public string Id { get; set; }+ public string Property { get; set; }+ public PropertyAction Action { get; set; }+ public string Value { get; set; }+ }++ private readonly ILogger? _debugLogger;+ private readonly ILogger? _informationLogger;+ private readonly ILogger? _errorLogger;++ private readonly WebView2 _webView = new();++ public CodeEditorPresenter()+ {+ // make the WebView2 transparent.+ Environment.SetEnvironmentVariable("WEBVIEW2_DEFAULT_BACKGROUND_COLOR", "00FFFFFF");++ Content = _webView;++ _webView.Visibility = Visibility.Collapsed;+ //_webView.DefaultBackgroundColor = Colors.Transparent;+ _webView.CoreWebView2Initialized += WebView_CoreWebView2Initialized;+ _webView.GotFocus += WebView_GotFocus;+ _webView.LostFocus += WebView_LostFocus;++ ILogger logger = this.Log();+ _debugLogger = logger.IsEnabled(LogLevel.Debug) ? logger : null;+ _informationLogger = logger.IsEnabled(LogLevel.Information) ? logger : null;+ _errorLogger = logger.IsEnabled(LogLevel.Error) ? logger : null;+ }++ /// <inheritdoc />+ public DispatcherQueue DispatcherQueue => DispatcherQueueExtensions.DispatcherQueue;++ /// <inheritdoc />+ public event TypedEventHandler<ICodeEditorPresenter, CoreWebView2NewWindowRequestedEventArgs>? NewWindowRequested;++ /// <inheritdoc />+ public event TypedEventHandler<ICodeEditorPresenter, CoreWebView2NavigationStartingEventArgs>? NavigationStarting;++ /// <inheritdoc />+ public event TypedEventHandler<ICodeEditorPresenter, CoreWebView2DOMContentLoadedEventArgs>? DOMContentLoaded;++ /// <inheritdoc />+ public event TypedEventHandler<ICodeEditorPresenter, CoreWebView2NavigationCompletedEventArgs>? NavigationCompleted;++ /// <inheritdoc />+ public event AsyncTypedEventHandler<ICodeEditorPresenter, EventArgs>? DotNetObjectInjectionRequested;++ /// <inheritdoc />+ public new event TypedEventHandler<ICodeEditorPresenter, RoutedEventArgs>? GotFocus;++ /// <inheritdoc />+ public new event TypedEventHandler<ICodeEditorPresenter, RoutedEventArgs>? LostFocus;++ public async Task LaunchAsync()+ {+ await _webView.EnsureCoreWebView2Async();++ StorageFile storageFile+ = await StorageFile.GetFileFromApplicationUriAsync(+ new Uri("ms-appx:///DevToys.MonacoEditor/CodeEditor/CodeEditor.Windows.html"));++ string rootDirectory = Directory.GetParent(storageFile.Path)!.Parent!.FullName;++ _webView.CoreWebView2.SetVirtualHostNameToFolderMapping(+ hostName: "devtoys.local",+ folderPath: rootDirectory,+ CoreWebView2HostResourceAccessKind.Allow);++ var tcs = new TaskCompletionSource<bool>();+ _webView.CoreWebView2.DOMContentLoaded += OnDOMContentLoaded;+ _webView.Source = new Uri("https://devtoys.local/CodeEditor/CodeEditor.Windows.html");++ await tcs.Task;++ // Request to inject .Net web object into the web page.+ Guard.IsNotNull(DotNetObjectInjectionRequested);+ await DotNetObjectInjectionRequested.Invoke(this, EventArgs.Empty);++ try+ {+ _informationLogger?.Info($"{nameof(LaunchAsync)}: Creating Monaco Editor");++ await _webView.ExecuteScriptAsync("createMonacoEditor(\"https://devtoys.local/\", document.getElementById('container'));");++ _informationLogger?.Info($"{nameof(LaunchAsync)}: Monaco Editor created successfully");+ }+ catch (Exception e)+ {+ _errorLogger?.Error($"{nameof(LaunchAsync)} failed", e);+ }++ _webView.Visibility = Visibility.Visible;++ void OnDOMContentLoaded(CoreWebView2 sender, CoreWebView2DOMContentLoadedEventArgs args)+ {+ _webView.CoreWebView2.DOMContentLoaded -= OnDOMContentLoaded;+ tcs.TrySetResult(true);+ }+ }++ public async Task InjectDotNetObjectToWebPageAsync<T>(string name, T pObject)+ {+ _debugLogger?.Debug($"{nameof(InjectDotNetObjectToWebPageAsync)}: Trying to inject .NET object in web page - {name}");++ var sb = new StringBuilder();+ sb.AppendLine($"EditorContext.getEditorForElement(document.getElementById('container')).{name} = {{");++ var methodsGuid = Guid.NewGuid();+ MethodInfo[] methodInfo = typeof(T).GetMethods(BindingFlags.Public | BindingFlags.Instance);+ var methods = new Dictionary<string, MethodInfo>(methodInfo.Length);+ foreach (MethodInfo method in methodInfo)+ {+ string functionName = $"{char.ToLower(method.Name[0])}{method.Name.Substring(1)}";+ sb.AppendLine($@"{functionName}: function() {{");+ sb.AppendLine($@" let id = this._callbackIndex++;");+ sb.AppendLine($@" window.chrome.webview.postMessage(");+ sb.AppendLine($@" JSON.stringify(");+ sb.AppendLine($@" {{");+ sb.AppendLine($@" guid: ""{methodsGuid}"",");+ sb.AppendLine($@" id: id,");+ sb.AppendLine($@" method: ""{functionName}"",");+ sb.AppendLine($@" args: JSON.stringify([...arguments])");+ sb.AppendLine($@" }}));");+ sb.AppendLine($@" const promise = new Promise((resolve, reject) => this._callbacks.set(id, {{ resolve: resolve, reject: reject }}));");+ sb.AppendLine($@" return promise;");+ sb.AppendLine($@"}},");+ methods.Add($"{functionName}`{method.GetParameters().Length}", method);+ }++ var propertiesGuid = Guid.NewGuid();+ PropertyInfo[] propertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);+ var properties = new Dictionary<string, PropertyInfo>(propertyInfo.Length);+ foreach (PropertyInfo property in propertyInfo)+ {+ string propertyName = $"{char.ToLower(property.Name[0])}{property.Name.Substring(1)}";+ if (property.CanRead)+ {+ sb.AppendLine($@"get {propertyName}() {{");+ sb.AppendLine($@" let id = this._callbackIndex++;");+ sb.AppendLine($@" window.chrome.webview.postMessage(");+ sb.AppendLine($@" JSON.stringify(");+ sb.AppendLine($@" {{");+ sb.AppendLine($@" guid: ""{propertiesGuid}"",");+ sb.AppendLine($@" id: id,");+ sb.AppendLine($@" property: ""{propertyName}"",");+ sb.AppendLine($@" action: ""{(int)PropertyAction.Read}""");+ sb.AppendLine($@" }}));");+ sb.AppendLine($@" const promise = new Promise((resolve, reject) => this._callbacks.set(id, {{ resolve: resolve, reject: reject }}));");+ sb.AppendLine($@" return promise;");+ sb.AppendLine($@"}},");+ }+ if (property.CanWrite)+ {+ sb.AppendLine($@"set {propertyName}(value) {{");+ sb.AppendLine($@" let id = this._callbackIndex++;");+ sb.AppendLine($@" window.chrome.webview.postMessage(");+ sb.AppendLine($@" JSON.stringify(");+ sb.AppendLine($@" {{");+ sb.AppendLine($@" guid: ""{propertiesGuid}"",");+ sb.AppendLine($@" id: id,");+ sb.AppendLine($@" property: ""{propertyName}"",");+ sb.AppendLine($@" action: ""{(int)PropertyAction.Write}"",");+ sb.AppendLine($@" value: JSON.stringify(value)");+ sb.AppendLine($@" }}));");+ sb.AppendLine($@" const promise = new Promise((resolve, reject) => this._callbacks.set(id, {{ resolve: resolve, reject: reject }}));");+ sb.AppendLine($@" return promise;");+ sb.AppendLine($@"}},");+ }+ properties[propertyName] = property;+ }++ // Add a map<int, (promiseAccept, promiseReject)> to the object used to resolve results+ sb.AppendLine($@"_callbacks: new Map(),");++ // And a shared counter to index into that map+ sb.AppendLine($@"_callbackIndex: 0,");++ sb.AppendLine("}");++ try+ {+ await _webView.ExecuteScriptAsync($"{sb}").AsTask();+ _debugLogger?.Debug($"{nameof(InjectDotNetObjectToWebPageAsync)}: '{name}' injected successfully.");+ }+ catch (Exception ex)+ {+ _errorLogger?.Error($"{nameof(InjectDotNetObjectToWebPageAsync)} failed - {name}", ex);+ }++ async void Handler(WebView2 _, CoreWebView2WebMessageReceivedEventArgs e)+ {+ string webMessageAsString = e.TryGetWebMessageAsString();++ WebMessage message = JsonConvert.DeserializeObject<WebMessage>(webMessageAsString);+ if (message.Guid == methodsGuid)+ {+ MethodWebMessage methodMessage = JsonConvert.DeserializeObject<MethodWebMessage>(webMessageAsString);+ object[] arguments = JsonConvert.DeserializeObject<object[]>(methodMessage.Args) ?? Array.Empty<object>();+ MethodInfo method = methods[$"{methodMessage.Method}`{arguments.Length}"];+ try+ {+ object? result = method.Invoke(pObject, arguments);+ if (result is not null)+ {+ Type resultType = result.GetType();+ dynamic? task = null;+ if (resultType.Name.StartsWith("TaskToAsyncOperationAdapter")+ || resultType.IsInstanceOfType(typeof(IAsyncInfo)))+ {+ // Task that needs to be converted to a task first+ if (resultType.GenericTypeArguments.Length > 0)+ {+ MethodInfo asTask = typeof(WindowsRuntimeSystemExtensions)+ .GetMethods(BindingFlags.Public | BindingFlags.Static)+ .Where(method => method.GetParameters().Length == 1+ && method.Name == "AsTask"+ && method.ToString()!.Contains("Windows.Foundation.Task`1[TResult]"))+ .First();++ asTask = asTask.MakeGenericMethod(resultType.GenericTypeArguments[0]);+ task = (Task)asTask.Invoke(null, new[] { result })!;+ }+ else+ {+ task = WindowsRuntimeSystemExtensions.AsTask((dynamic)result);+ }+ }+ else+ {+ MethodInfo? awaiter = resultType.GetMethod(nameof(Task.GetAwaiter));+ if (awaiter is not null)+ {+ task = (Task)result;+ }+ }+ if (task is object)+ {+ result = await task;+ }+ }++ string json = JsonConvert.SerializeObject(result);++ var sb = new StringBuilder();+ sb.AppendLine("(function() {");+ sb.AppendLine($@" let {name} = EditorContext.getEditorForElement(document.getElementById('container')).{name};");+ sb.AppendLine($@" {name}._callbacks.get({methodMessage.Id}).resolve(JSON.parse({json}));");+ sb.AppendLine($@" {name}._callbacks.delete({methodMessage.Id});");+ sb.AppendLine("})();");+ await _webView.ExecuteScriptAsync(sb.ToString());+ }+ catch (Exception ex)+ {+ _errorLogger?.Error($"{nameof(InjectDotNetObjectToWebPageAsync)}-CALLBACK: Exception in {name}.{method.Name}: {ex.Message}");+ string json = JsonConvert.SerializeObject(ex, new JsonSerializerSettings() { Error = (_, e) => e.ErrorContext.Handled = true });+ await _webView.ExecuteScriptAsync($@"EditorContext.getEditorForElement(document.getElementById('container')).{name}._callbacks.get({methodMessage.Id}).reject(JSON.parse({json})); EditorContext.getEditorForElement(document.getElementById('container')).{name}._callbacks.delete({methodMessage.Id});");+ }+ }+ else if (message.Guid == propertiesGuid)+ {+ PropertyWebMessage propertyMessage = JsonConvert.DeserializeObject<PropertyWebMessage>(webMessageAsString);+ PropertyInfo property = properties[propertyMessage.Property];+ try+ {+ object? result;+ if (propertyMessage.Action == PropertyAction.Read)+ {+ result = property.GetValue(pObject);+ }+ else+ {+ object? value = JsonConvert.DeserializeObject(propertyMessage.Value, property.PropertyType);+ property.SetValue(pObject, value);+ result = new object();+ }++ string json = JsonConvert.SerializeObject(result);++ var sb = new StringBuilder();+ sb.AppendLine("(function() {");+ sb.AppendLine($@" let {name} = EditorContext.getEditorForElement(document.getElementById('container')).{name};");+ sb.AppendLine($@" {name}._callbacks.get({propertyMessage.Id}).resolve(JSON.parse({json}));");+ sb.AppendLine($@" {name}._callbacks.delete({propertyMessage.Id});");+ sb.AppendLine("})();");+ await _webView.ExecuteScriptAsync(sb.ToString());+ }+ catch (Exception ex)+ {+ _errorLogger?.Error($"{nameof(InjectDotNetObjectToWebPageAsync)}-CALLBACK: Exception in {name}.{property.Name}: {ex.Message}");+ string json = JsonConvert.SerializeObject(ex, new JsonSerializerSettings() { Error = (_, e) => e.ErrorContext.Handled = true });+ await _webView.ExecuteScriptAsync($@"EditorContext.getEditorForElement(document.getElementById('container')).{name}._callbacks.get({propertyMessage.Id}).reject(JSON.parse({json})); EditorContext.getEditorForElement(document.getElementById('container')).{name}._callbacks.delete({propertyMessage.Id});");+ }+ }+ }++ Handlers.Add(Handler);+ _webView.WebMessageReceived += Handler;+ }++ public async Task<string> InvokeScriptAsync(string script)+ {+ script+ = $@"+ (function()+ {{+ try {{+ let result = (function()+ {{+ let editorContext = EditorContext.getEditorForElement(document.getElementById('container'));+ {script}+ }})();+ return result;+ }}+ catch(err){{+ let editorContext = EditorContext.getEditorForElement(document.getElementById('container'));+ editorContext.Debug.log(err);+ }}+ finally {{+ }}+ }})();";++ _debugLogger?.Debug($"Invoke Script: {script}");++ try+ {+ string result = await _webView.ExecuteScriptAsync(script);++ _debugLogger?.Debug($"Invoke Script result: {result}");++ return result;+ }+ catch (Exception e)+ {+ _errorLogger?.Error("Invoke Script failed", e);++ return string.Empty;+ }+ }++ private void WebView_CoreWebView2Initialized(WebView2 sender, CoreWebView2InitializedEventArgs args)+ {+ _webView.CoreWebView2.NewWindowRequested += (wv, args) => NewWindowRequested?.Invoke(this, args);+ _webView.CoreWebView2.NavigationStarting += (wv, args) => NavigationStarting?.Invoke(this, args);+ _webView.CoreWebView2.DOMContentLoaded += (wv, args) => DOMContentLoaded?.Invoke(this, args);+ _webView.CoreWebView2.NavigationCompleted += (wv, args) => NavigationCompleted?.Invoke(this, args);+ }++ private void WebView_LostFocus(object sender, RoutedEventArgs e)+ {+ LostFocus?.Invoke(this, e);+ }++ private void WebView_GotFocus(object sender, RoutedEventArgs e)+ {+ GotFocus?.Invoke(this, e);+ }+}++#endifdiff --git a/src/app/dev/DevToys.MonacoEditor/CodeEditor/ICodeEditorPresenter.cs b/src/app/dev/DevToys.MonacoEditor/CodeEditor/ICodeEditorPresenter.csnew file mode 100644index 000000000..743ad7b6f--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/CodeEditor/ICodeEditorPresenter.cs@@ -0,0 +1,79 @@+using DevToys.UI.Framework.Threading;+using Microsoft.Web.WebView2.Core;+using Windows.Foundation;++#if WINDOWS_UWP+using Windows.UI.Xaml;+using DispatcherQueue = Windows.UI.Core.CoreDispatcher;+#else+using Microsoft.UI.Dispatching;+using Microsoft.UI.Xaml;+#endif++namespace DevToys.MonacoEditor;++public interface ICodeEditorPresenter+{+ DispatcherQueue DispatcherQueue { get; }++ /// <summary>+ /// Occurs when a user performs an action in a WebView that causes content to be opened in a new window.+ /// </summary>+ event TypedEventHandler<ICodeEditorPresenter, CoreWebView2NewWindowRequestedEventArgs>? NewWindowRequested;++ /// <summary>+ /// Occurs before the WebView navigates to new content.+ /// </summary>+ event TypedEventHandler<ICodeEditorPresenter, CoreWebView2NavigationStartingEventArgs>? NavigationStarting;++ /// <summary>+ /// Occurs when the WebView has finished parsing the current HTML content.+ /// </summary>+ event TypedEventHandler<ICodeEditorPresenter, CoreWebView2DOMContentLoadedEventArgs>? DOMContentLoaded;++ /// <summary>+ /// Occurs when the WebView has finished loading the current content or if navigation has failed.+ /// </summary>+ event TypedEventHandler<ICodeEditorPresenter, CoreWebView2NavigationCompletedEventArgs>? NavigationCompleted;++ /// <summary>+ /// Occurs when the presenter needs to get allowed-web object to be injected in the web page.+ /// </summary>+ event AsyncTypedEventHandler<ICodeEditorPresenter, EventArgs>? DotNetObjectInjectionRequested;++ /// <summary>+ /// Occurs when the WebView or a component inside it (like the Monaco Editor) got focus.+ /// </summary>+ event TypedEventHandler<ICodeEditorPresenter, RoutedEventArgs>? GotFocus;++ /// <summary>+ /// Occurs when the WebView or a component inside it (like the Monaco Editor) lost focus.+ /// </summary>+ event TypedEventHandler<ICodeEditorPresenter, RoutedEventArgs>? LostFocus;++ /// <summary>+ /// Launch the web element of Monaco editor.+ /// </summary>+ Task LaunchAsync();++ /// <summary>+ /// Adds a native .NET object as a global parameter to the top level document inside of a WebView.+ /// This way, the object named by the parameter <paramref name="name"/> can be used directly in JavaScript.+ /// </summary>+ /// <param name="name">The name of the object to expose to the document in the WebView.</param>+ /// <param name="pObject">The object to expose to the document in the WebView.</param>+ Task InjectDotNetObjectToWebPageAsync<T>(string name, T pObject);++ /// <summary>+ /// Execute a JavaScript code on the web page.+ /// </summary>+ /// <returns></returns>+ Task<string> InvokeScriptAsync(string script);++ /// <summary>+ /// Give the focus to the Monaco Editor.+ /// </summary>+ /// <param name="state"></param>+ /// <returns></returns>+ bool Focus(FocusState state);+}diff --git a/src/app/dev/DevToys.MonacoEditor/DevToys.MonacoEditor.csproj b/src/app/dev/DevToys.MonacoEditor/DevToys.MonacoEditor.csprojnew file mode 100644index 000000000..83fff5167--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/DevToys.MonacoEditor.csproj@@ -0,0 +1,119 @@+<Project Sdk="MSBuild.Sdk.Extras/3.0.44">+ <!--+ Adding project references to this project requires some manual adjustments.+ Please see https://github.com/unoplatform/uno/issues/3909 for more details.+ -->+ <PropertyGroup>+ <TargetFrameworks>$(UAP);$(NetCore)</TargetFrameworks>+ <!-- Ensures the .xr.xml files are generated in a proper layout folder -->+ <GenerateLibraryLayout>true</GenerateLibraryLayout>++ <IsUWP>false</IsUWP>+ <IsWasm>false</IsWasm>+ <EnableWindowsTargeting>true</EnableWindowsTargeting>+ </PropertyGroup>++ <PropertyGroup Condition="'$(TargetFramework)' == '$(UAP)'">+ <IsUWP>true</IsUWP>+ </PropertyGroup>++ <PropertyGroup Condition="'$(TargetFramework)' == '$(NetCore)'">+ <IsWasm>true</IsWasm>+ </PropertyGroup>++ <PropertyGroup Condition="'$(IsWasm)' == 'true'">+ <DefineConstants>$(DefineConstants);__WASM__</DefineConstants>+ </PropertyGroup>++ <PropertyGroup Condition="'$(IsUWP)' == 'true'">+ <DefineConstants>$(DefineConstants);WINDOWS_UWP</DefineConstants>+ <TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>+ <TargetPlatformVersion>$(Windows10SDKVersion)</TargetPlatformVersion>+ <TargetPlatformMinVersion>$(Windows10MinSDKVersion)</TargetPlatformMinVersion>+ <WindowsXamlEnableOverview>true</WindowsXamlEnableOverview>+ <Platforms>AnyCPU;x86;x64;arm64</Platforms>+ </PropertyGroup>+ <PropertyGroup Condition="'$(IsUWP)' == 'true' And '$(Configuration)' == 'Release'">+ <UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>+ </PropertyGroup>+ <PropertyGroup Condition="'$(IsUWP)' == 'true' And '$(Platform)' == 'AnyCPU'">+ <PlatformTarget>x86</PlatformTarget>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="Newtonsoft.Json" />+ <PackageReference Include="Nito.AsyncEx" />+ <PackageReference Include="Microsoft.Extensions.Logging" />+ <PackageReference Include="Microsoft.Extensions.Logging.Configuration" />+ <PackageReference Include="Uno.Core.Extensions.Logging" />+ <PackageReference Include="Uno.Core.Extensions.Logging.Singleton" />+ <PackageReference Include="Uno.UI.Adapter.Microsoft.Extensions.Logging" />+ <PackageReference Include="Microsoft.TypeScript.MSBuild">+ <PrivateAssets>all</PrivateAssets>+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>+ </PackageReference>+ </ItemGroup>++ <ItemGroup Condition="'$(IsUWP)' == 'true'">+ <PackageReference Include="Microsoft.UI.Xaml" />+ <PackageReference Include="Microsoft.Web.WebView2" />+ </ItemGroup>++ <ItemGroup Condition="'$(IsWasm)' == 'true'">+ <PackageReference Include="Microsoft.Windows.Compatibility" />+ <PackageReference Include="Uno.Extensions.Logging.WebAssembly.Console" />+ <PackageReference Include="Uno.WinUI" />+ <PackageReference Include="Uno.WinUI.Lottie" />+ <PackageReference Include="Uno.WinUI.Runtime.WebAssembly" />+ <PackageReference Include="Uno.WinUI.RemoteControl" Condition="'$(Configuration)'=='Debug'" />+ </ItemGroup>++ <ItemGroup>+ <None Remove="ts-helpermethods\ts-helpermethods-Wasm\tsconfig.json" />+ <None Remove="ts-helpermethods\ts-helpermethods-Windows\tsconfig.json" />+ <None Remove="WasmScripts\uno-monaco-helpers.js" />+ <None Remove="monaco-editor\**\*.*" />+ <TypeScriptCompile Remove="monaco-editor\**\*.*" />+ <Content Include="monaco-editor\*.*" />+ <Content Include="monaco-editor\min\**\*.*" />+ <Content Include="ts-helpermethods\**\*.js">+ <DependentUpon>%(Filename).ts</DependentUpon>+ </Content>++ <UpToDateCheckInput Include="**\*.xaml" />+ <Page Include="**\*.xaml">+ <SubType>Designer</SubType>+ <Generator>MSBuild:Compile</Generator>+ </Page>+ </ItemGroup>++ <ItemGroup Condition="'$(IsWindows)' == 'true'">+ <Content Include="CodeEditor\CodeEditor.Windows.html" />++ <None Remove="ts-helpermethods\ts-helpermethods-Wasm\**\*.js" />+ <Content Remove="ts-helpermethods\ts-helpermethods-Wasm\**\*.js" />+ <TypeScriptCompile Remove="ts-helpermethods\ts-helpermethods-Wasm\**\*.*" />+ <Content Include="ts-helpermethods\ts-helpermethods-Windows\tsconfig.json" />+ <None Include="ts-helpermethods\ts-helpermethods-Wasm\tsconfig.json" />+ </ItemGroup>++ <ItemGroup Condition="'$(IsWasm)' == 'true'">+ <Content Include="Assets\**" />+ <Compile Update="**\*.xaml.cs">+ <DependentUpon>%(Filename)</DependentUpon>+ </Compile>++ <None Remove="ts-helpermethods\**\*.js" />+ <Content Remove="ts-helpermethods\**\*.js" />+ <TypeScriptCompile Remove="ts-helpermethods\ts-helpermethods-Windows\**\*.js" />+ <Content Include="ts-helpermethods\ts-helpermethods-Wasm\tsconfig.json" />+ <None Include="ts-helpermethods\ts-helpermethods-Windows\tsconfig.json" />+ <EmbeddedResource Include="WasmScripts\uno-monaco-helpers.js" />+ </ItemGroup>++ <ItemGroup>+ <ProjectReference Include="..\DevToys.Core\DevToys.Core.csproj" />+ <ProjectReference Include="..\DevToys.UI.Framework\DevToys.UI.Framework.csproj" />+ </ItemGroup>++</Project>\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/Extensions/ICodeEditorPresenterExtensions.cs b/src/app/dev/DevToys.MonacoEditor/Extensions/ICodeEditorPresenterExtensions.csnew file mode 100644index 000000000..f30fda0a2--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Extensions/ICodeEditorPresenterExtensions.cs@@ -0,0 +1,191 @@+using System.Runtime.CompilerServices;+using DevToys.UI.Framework.Threading;+using Newtonsoft.Json;+using Newtonsoft.Json.Serialization;++namespace DevToys.MonacoEditor.Extensions;++internal static class ICodeEditorPresenterExtensions+{+ public static async Task RunScriptAsync(+ this ICodeEditorPresenter 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 ICodeEditorPresenter view,+ string script,+ [CallerMemberName] string? member = null,+ [CallerFilePath] string? file = null,+ [CallerLineNumber] int line = 0)+ {+ string start = "try {\n";+ if (typeof(T) != typeof(object))+ {+ script = script.Trim(';');+ start += "return JSON.stringify(" + script + ");";+ }+ else+ {+ start += "return " + script;+ }+ string fullscript = start ++ "\n} catch (err) { return JSON.stringify({ wv_internal_error: true, message: err.message, description: err.description, number: err.number, stack: err.stack }); }";++ if (view.DispatcherQueue.HasThreadAccess)+ {+ try+ {+ return await RunScriptHelperAsync<T>(view, fullscript);+ }+ catch (Exception e)+ {+ throw new JavaScriptExecutionException(member, file, line, script, e);+ }+ }+ else+ {+ return await view.DispatcherQueue.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>(ICodeEditorPresenter view, string script)+ {+ string returnstring = await view.InvokeScriptAsync(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());+ // }+ //}++ // TODO: Need to decode the error correctly+ if (!string.IsNullOrEmpty(returnstring))+ {+ if (returnstring.Contains("wv_internal_error"))+ {+ throw new JavaScriptInnerException(returnstring, "");+ }++ if (returnstring != "null")+ {+ return JsonConvert.DeserializeObject<T>(returnstring);+ }+ }++ return default;+ }++ private static readonly JsonSerializerSettings _settings = new()+ {+ NullValueHandling = NullValueHandling.Ignore,+ ContractResolver = new CamelCasePropertyNamesContractResolver()+ };++ public static async Task InvokeScriptAsync(+ this ICodeEditorPresenter 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 ICodeEditorPresenter 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 ICodeEditorPresenter 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 ICodeEditorPresenter view,+ string method,+ object[] args,+ bool serialize = true,+ [CallerMemberName] string? member = null,+ [CallerFilePath] string? file = null,+ [CallerLineNumber] int line = 0)+ {+ string?[] sanitizedargs;++ try+ {+ Debug.WriteLine($"Begin invoke script (serialize - {serialize})");+ 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();+ }++ string script = method + "(editorContext, " + string.Join(", ", sanitizedargs) + ");";++ Debug.WriteLine($"Script {script})");++ return await RunScriptAsync<T>(view, script, member, file, line);+ }+ catch (Exception ex)+ {+ Debug.WriteLine($"Error {ex.Message} {ex.StackTrace} {ex.InnerException?.Message})");+ return default(T);+ }+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Extensions/UriExtensions.cs b/src/app/dev/DevToys.MonacoEditor/Extensions/UriExtensions.csnew file mode 100644index 000000000..c5e731611--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Extensions/UriExtensions.cs@@ -0,0 +1,40 @@+namespace DevToys.MonacoEditor.Extensions;++internal static class UriExtensions+{+ private static readonly string UNO_BOOTSTRAP_APP_BASE = Environment.GetEnvironmentVariable(nameof(UNO_BOOTSTRAP_APP_BASE)) ?? string.Empty;+ private static readonly string UNO_BOOTSTRAP_WEBAPP_BASE_PATH = Environment.GetEnvironmentVariable(nameof(UNO_BOOTSTRAP_WEBAPP_BASE_PATH)) ?? "";++ internal static string AbsoluteUriString(this Uri uri)+ {+ string target;+ if (uri.IsAbsoluteUri)+ {+#if __WASM__+ Debugger.Launch(); // TODO+ if (uri.Scheme == "file" || uri.Scheme == "ms-appx-web")+ {+ // Local files are assumed as coming from the remoter server+ target+ = UNO_BOOTSTRAP_APP_BASE is null+ ? uri.PathAndQuery+ : UNO_BOOTSTRAP_WEBAPP_BASE_PATH + UNO_BOOTSTRAP_APP_BASE + uri.PathAndQuery;+ }+ else+ {+ target = uri.AbsoluteUri;+ }+#else+ target = uri.AbsoluteUri;+#endif+ }+ else+ {+ target+ = UNO_BOOTSTRAP_APP_BASE is null+ ? uri.OriginalString+ : UNO_BOOTSTRAP_WEBAPP_BASE_PATH + UNO_BOOTSTRAP_APP_BASE + "/" + uri.OriginalString;+ }+ return target;+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/JavaScriptExecutionException.cs b/src/app/dev/DevToys.MonacoEditor/JavaScriptExecutionException.csnew file mode 100644index 000000000..0f74408bd--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/JavaScriptExecutionException.cs@@ -0,0 +1,21 @@+namespace DevToys.MonacoEditor;++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/app/dev/DevToys.MonacoEditor/JavaScriptInnerException.cs b/src/app/dev/DevToys.MonacoEditor/JavaScriptInnerException.csnew file mode 100644index 000000000..f0ae2f223--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/JavaScriptInnerException.cs@@ -0,0 +1,12 @@+namespace DevToys.MonacoEditor;++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)+ {+ JavaScriptStackTrace = stack;+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/JsonConverters/InterfaceToClassConverter.cs b/src/app/dev/DevToys.MonacoEditor/JsonConverters/InterfaceToClassConverter.csnew file mode 100644index 000000000..1e7c236d9--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/JsonConverters/InterfaceToClassConverter.cs@@ -0,0 +1,32 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.JsonConverters;++/// <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/app/dev/DevToys.MonacoEditor/Monaco/Editor/AcceptSuggestionOnEnter.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AcceptSuggestionOnEnter.csnew file mode 100644index 000000000..fff76a2a4--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AcceptSuggestionOnEnter.cs@@ -0,0 +1,55 @@+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 };++internal class AcceptSuggestionOnEnterConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "off" => AcceptSuggestionOnEnter.Off,+ "on" => AcceptSuggestionOnEnter.On,+ "smart" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/AccessibilitySupport.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AccessibilitySupport.csnew file mode 100644index 000000000..ccbd0c53e--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AccessibilitySupport.cs@@ -0,0 +1,53 @@+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 };+internal class AccessibilitySupportConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "auto" => AccessibilitySupport.Auto,+ "off" => AccessibilitySupport.Off,+ "on" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoClosingBrackets.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoClosingBrackets.csnew file mode 100644index 000000000..6416359d2--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoClosingBrackets.cs@@ -0,0 +1,58 @@+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 };++internal class AutoClosingBracketsConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "always" => AutoClosingBrackets.Always,+ "beforeWhitespace" => AutoClosingBrackets.BeforeWhitespace,+ "languageDefined" => AutoClosingBrackets.LanguageDefined,+ "never" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoClosingOvertype.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoClosingOvertype.csnew file mode 100644index 000000000..6abde2360--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoClosingOvertype.cs@@ -0,0 +1,52 @@+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 };+internal class AutoClosingOvertypeConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "always" => AutoClosingOvertype.Always,+ "auto" => AutoClosingOvertype.Auto,+ "never" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoClosingQuotes.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoClosingQuotes.csnew file mode 100644index 000000000..bb1813240--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoClosingQuotes.cs@@ -0,0 +1,60 @@+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 };++internal class AutoClosingQuotesConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "always" => AutoClosingQuotes.Always,+ "beforeWhitespace" => AutoClosingQuotes.BeforeWhitespace,+ "languageDefined" => AutoClosingQuotes.LanguageDefined,+ "never" => (object)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();+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoFindInSelection.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoFindInSelection.csnew file mode 100644index 000000000..d1da8679d--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoFindInSelection.cs@@ -0,0 +1,53 @@+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 };++internal class AutoFindInSelectionConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "always" => AutoFindInSelection.Always,+ "multiline" => AutoFindInSelection.Multiline,+ "never" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoIndent.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoIndent.csnew file mode 100644index 000000000..893a2aa57--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoIndent.cs@@ -0,0 +1,62 @@+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 };++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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "advanced" => AutoIndent.Advanced,+ "brackets" => AutoIndent.Brackets,+ "full" => AutoIndent.Full,+ "keep" => AutoIndent.Keep,+ "none" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoSurround.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoSurround.csnew file mode 100644index 000000000..0996b996c--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/AutoSurround.cs@@ -0,0 +1,58 @@+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 };++internal class AutoSurroundConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "brackets" => AutoSurround.Brackets,+ "languageDefined" => AutoSurround.LanguageDefined,+ "never" => AutoSurround.Never,+ "quotes" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/ContextKey.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/ContextKey.csnew file mode 100644index 000000000..6d398da75--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/ContextKey.cs@@ -0,0 +1,51 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++public sealed class ContextKey : IContextKey+{+ [JsonIgnore]+ private readonly WeakReference<CodeEditor> _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(CodeEditor editor, string key, bool defaultValue)+ {+ _editor = new WeakReference<CodeEditor>(editor);++ Key = key;+ DefaultValue = defaultValue;+ }++ private async void UpdateValueAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? 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/app/dev/DevToys.MonacoEditor/Monaco/Editor/CursorBlinking.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/CursorBlinking.csnew file mode 100644index 000000000..1732aa330--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/CursorBlinking.cs@@ -0,0 +1,63 @@+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 };++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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "blink" => CursorBlinking.Blink,+ "expand" => CursorBlinking.Expand,+ "phase" => CursorBlinking.Phase,+ "smooth" => CursorBlinking.Smooth,+ "solid" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/CursorStyle.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/CursorStyle.csnew file mode 100644index 000000000..d83997733--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/CursorStyle.cs@@ -0,0 +1,66 @@+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 };++internal class CursorStyleConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "block" => CursorStyle.Block,+ "block-outline" => CursorStyle.BlockOutline,+ "line" => CursorStyle.Line,+ "line-thin" => CursorStyle.LineThin,+ "underline" => CursorStyle.Underline,+ "underline-thin" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/CursorSurroundingLinesStyle.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/CursorSurroundingLinesStyle.csnew file mode 100644index 000000000..1357eeaba--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/CursorSurroundingLinesStyle.cs@@ -0,0 +1,52 @@+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 };++internal class CursorSurroundingLinesStyleConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "all" => CursorSurroundingLinesStyle.All,+ "default" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/DiffEditorConstructionOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/DiffEditorConstructionOptions.csnew file mode 100644index 000000000..66d297350--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/DiffEditorConstructionOptions.cs@@ -0,0 +1,816 @@+using System.Runtime.CompilerServices;+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++public sealed class DiffEditorConstructionOptions : IDiffEditorConstructionOptions, INotifyPropertyChanged+{+ public event PropertyChangedEventHandler? PropertyChanged;++ private readonly Dictionary<string, object?> _propertyBackingDictionary = new();++ 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 IEditorCommentsOptions? Comments { get => GetPropertyValue<IEditorCommentsOptions>(); 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 IEditorParameterHintOptions? ParameterHints { get => GetPropertyValue<IEditorParameterHintOptions?>(); 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 IEditorScrollbarOptions? Scrollbar { get => GetPropertyValue<IEditorScrollbarOptions?>(); 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 ISuggestOptions? Suggest { get => GetPropertyValue<ISuggestOptions?>(); 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 `~!@#$%^&*()-=+[{]}\|;:'",.<>/?+ /// *+ /// </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})]?|&,;'.+ /// </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/app/dev/DevToys.MonacoEditor/Monaco/Editor/Dimension.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/Dimension.csnew file mode 100644index 000000000..06929b0ac--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/Dimension.cs@@ -0,0 +1,15 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/EditorFindOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EditorFindOptions.csnew file mode 100644index 000000000..85cb21419--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EditorFindOptions.cs@@ -0,0 +1,21 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++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/app/dev/DevToys.MonacoEditor/Monaco/Editor/EditorHoverOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EditorHoverOptions.csnew file mode 100644index 000000000..2ec68c74a--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EditorHoverOptions.cs@@ -0,0 +1,32 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/EditorLightbulbOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EditorLightbulbOptions.csnew file mode 100644index 000000000..f5c92ebb1--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EditorLightbulbOptions.cs@@ -0,0 +1,18 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/EditorMinimapOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EditorMinimapOptions.csnew file mode 100644index 000000000..81b3a7c04--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EditorMinimapOptions.cs@@ -0,0 +1,52 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/EndOfLinePreference.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EndOfLinePreference.csnew file mode 100644index 000000000..5d908eb68--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EndOfLinePreference.cs@@ -0,0 +1,21 @@+namespace DevToys.MonacoEditor.Monaco.Editor;++/// <summary>+/// End of line character preference.+/// </summary>+public enum EndOfLinePreference+{+ /// <summary>+ /// Use carriage return and line feed (\r\n) as the end of line character.+ /// </summary>+ CRLF = 2,+ /// <summary>+ /// Use line feed (\n) as the end of line character.+ /// </summary>+ LF = 1,+ /// <summary>+ /// Use the end of line character identified in the text buffer.+ /// </summary>+ TextDefined = 0+}+diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EndOfLineSequence.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EndOfLineSequence.csnew file mode 100644index 000000000..40cac8c5e--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/EndOfLineSequence.cs@@ -0,0 +1,17 @@+namespace DevToys.MonacoEditor.Monaco.Editor;++/// <summary>+/// End of line character preference.+/// </summary>+public enum EndOfLineSequence+{+ /// <summary>+ /// Use carriage return and line feed (\r\n) as the end of line character.+ /// </summary>+ CRLF = 1,+ /// <summary>+ /// Use line feed (\n) as the end of line character.+ /// </summary>+ LF = 0+}+diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/FindMatch.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/FindMatch.csnew file mode 100644index 000000000..e4a1f2f1f--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/FindMatch.cs@@ -0,0 +1,15 @@+using DevToys.MonacoEditor.JsonConverters;+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++public sealed class FindMatch+{+ [JsonProperty("matches", NullValueHandling = NullValueHandling.Ignore)]+ public string[]? Matches { get; set; }++ [JsonProperty("range", NullValueHandling = NullValueHandling.Ignore)]+ [JsonConverter(typeof(InterfaceToClassConverter<IRange, Range>))]+ public IRange? Range { get; set; }+}+diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/FoldingStrategy.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/FoldingStrategy.csnew file mode 100644index 000000000..f1880411a--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/FoldingStrategy.cs@@ -0,0 +1,51 @@+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 };++internal class FoldingStrategyConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "auto" => FoldingStrategy.Auto,+ "indentation" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/GoToLocationOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/GoToLocationOptions.csnew file mode 100644index 000000000..7179ab4fc--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/GoToLocationOptions.cs@@ -0,0 +1,42 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IActionDescriptor.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IActionDescriptor.csnew file mode 100644index 000000000..b5c449163--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IActionDescriptor.cs@@ -0,0 +1,57 @@+using Newtonsoft.Json;++#if !NETSTANDARD2_0+using System.Runtime.InteropServices.WindowsRuntime;+#else+using ReadOnlyArrayAttribute = Monaco.Helpers.Stubs.ReadOnlyArrayAttribute;+#endif++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(CodeEditor editor, [ReadOnlyArray] object[] args);+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IContextKey.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IContextKey.csnew file mode 100644index 000000000..2022056e3--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IContextKey.cs@@ -0,0 +1,26 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IDiffEditorConstructionOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IDiffEditorConstructionOptions.csnew file mode 100644index 000000000..611326254--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IDiffEditorConstructionOptions.cs@@ -0,0 +1,18 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IDiffEditorOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IDiffEditorOptions.csnew file mode 100644index 000000000..6f1354101--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IDiffEditorOptions.cs@@ -0,0 +1,46 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IDimension.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IDimension.csnew file mode 100644index 000000000..32966fd02--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IDimension.cs@@ -0,0 +1,15 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorCommentsOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorCommentsOptions.csnew file mode 100644index 000000000..1c691b1a0--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorCommentsOptions.cs@@ -0,0 +1,16 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++/// <summary>+/// Configuration options for editor comments+/// </summary>+public sealed class IEditorCommentsOptions+{+ /// <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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorConstructionOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorConstructionOptions.csnew file mode 100644index 000000000..ef410126b--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorConstructionOptions.cs@@ -0,0 +1,9 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorFindOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorFindOptions.csnew file mode 100644index 000000000..a9c2f933e--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorFindOptions.cs@@ -0,0 +1,14 @@+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 IEditorFindOptions+{+ [JsonProperty("autoFindInSelection")]+ public bool AutoFindInSelection { get; set; }+ [JsonProperty("seedSearchStringFromSelection")]+ public bool SeedSearchStringFromSelection { get; set; } //= true;+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorOptions.csnew file mode 100644index 000000000..2e8b59e6c--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorOptions.cs@@ -0,0 +1,739 @@+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)]+ IEditorCommentsOptions? 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)]+ IEditorParameterHintOptions? 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)]+ IEditorScrollbarOptions? 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)]+ ISuggestOptions? 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 `~!@#$%^&*()-=+[{]}\|;:'",.<>/?+ /// *+ /// </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})]?|/&.,;¢°′″‰℃、。。、¢,.:;?!%・・ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ァィゥェォャュョッー”〉》」』】〕)]}」'.+ /// </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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorParameterHintOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorParameterHintOptions.csnew file mode 100644index 000000000..5ddc34e9b--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorParameterHintOptions.cs@@ -0,0 +1,23 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++/// <summary>+/// Configuration options for parameter hints+/// </summary>+public sealed class IEditorParameterHintOptions+{+ /// <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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorScrollbarOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorScrollbarOptions.csnew file mode 100644index 000000000..9ffbd47d9--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IEditorScrollbarOptions.cs@@ -0,0 +1,91 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++public sealed class IEditorScrollbarOptions+{+ /// <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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IGlobalEditorOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IGlobalEditorOptions.csnew file mode 100644index 000000000..e2c96feea--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IGlobalEditorOptions.cs@@ -0,0 +1,68 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IMarker.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IMarker.csnew file mode 100644index 000000000..035524162--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IMarker.cs@@ -0,0 +1,15 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IMarkerData.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IMarkerData.csnew file mode 100644index 000000000..3dbd6080b--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IMarkerData.cs@@ -0,0 +1,27 @@+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)]+ IRelatedInformation[]? 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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModel.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModel.csnew file mode 100644index 000000000..8791a2a00--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModel.cs@@ -0,0 +1,110 @@+using Newtonsoft.Json;+using Windows.Foundation;+using Windows.Foundation.Metadata;++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+ Task DetectIndentationAsync(bool defaultInsertSpaces, bool defaultTabSize);++ /// <summary>+ /// Search the model.+ /// </summary>+ /// <returns>+ /// The ranges where the matches are. It is empty if not matches have been found.+ ///+ /// </returns>+ [DefaultOverload]+ Task<IEnumerable<FindMatch>?> FindMatchesAsync(string searchString, bool searchOnlyEditableRange, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches);++ [DefaultOverload]+ Task<IEnumerable<FindMatch>?> FindMatchesAsync(string searchString, bool searchOnlyEditableRange, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches, double limitResultCount);++ /// <summary>+ /// Search the model.+ /// </summary>+ /// <returns>+ /// The ranges where the matches are. It is empty if no matches have been found.+ ///+ /// </returns>+ Task<IEnumerable<FindMatch>?> FindMatchesAsync(string searchString, IRange searchScope, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches);++ Task<IEnumerable<FindMatch>?> FindMatchesAsync(string searchString, IRange searchScope, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches, double limitResultCount);++ /// <summary>+ /// Search the model for the next match. Loops to the beginning of the model if needed.+ /// </summary>+ /// <returns>+ /// The range where the next match is. It is null if no next match has been found.+ ///+ /// </returns>+ Task<FindMatch?> FindNextMatchAsync(string searchString, IPosition searchStart, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches);++ /// <summary>+ /// Search the model for the previous match. Loops to the end of the model if needed.+ /// </summary>+ /// <returns>+ /// The range where the previous match is. It is null if no previous match has been found.+ ///+ /// </returns>+ Task<FindMatch?> FindPreviousMatchAsync(string searchString, IPosition searchStart, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches);++ //GetAllDecorationsAsync+ Task<uint> GetAlternativeVersionIdAsync();+ //GetDecorationOptionsAsync+ //GetDecorationRangeAsync+ //GetDecorationsInRangeAsync+ Task<string?> GetEOLAsync();+ Task<Range?> GetFullModelRangeAsync();+ Task<string?> GetLineContentAsync(uint lineNumber);+ Task<uint> GetLineCountAsync();+ //GetLineDecorationsAsync+ Task<uint> GetLineFirstNonWhitespaceColumnAsync(uint lineNumber);+ Task<uint> GetLineLastNonWhitespaceColumnAsync(uint lineNumber);+ Task<uint> GetLineLengthAsync(uint lineNumber);+ Task<uint> GetLineMaxColumnAsync(uint lineNumber);+ Task<uint> GetLineMinColumnAsync(uint lineNumber);+ Task<IEnumerable<string>?> GetLinesContentAsync();+ //GetLinesDecorationsAsync+ Task<string?> GetModelIdAsync();+ Task<uint> GetOffsetAtAsync(IPosition position);+ Task<string?> GetOneIndentAsync();+ //GetOptionsAsync+ Task<Position?> GetPositionAtAsync(uint offset);+ Task<string?> GetValueAsync();+ // TextDefined is default eol+ Task<string?> GetValueAsync(EndOfLinePreference eol);+ Task<string?> GetValueAsync(EndOfLinePreference eol, bool preserveBOM);+ Task<string?> GetValueInRangeAsync(IRange range);+ Task<string?> GetValueInRangeAsync(IRange range, EndOfLinePreference eol);+ Task<uint> GetValueLengthAsync();+ Task<uint> GetValueLengthAsync(EndOfLinePreference eol);+ Task<uint> GetValueLengthAsync(EndOfLinePreference eol, bool preserveBOM);+ Task<uint> GetValueLengthInRangeAsync(IRange range);+ Task<uint> GetVersionIdAsync();+ Task<WordAtPosition?> GetWordAtPositionAsync(IPosition position);+ Task<WordAtPosition?> GetWordUntilPositionAsync(IPosition position);+ Task<Position?> ModifyPositionAsync(IPosition position, int number);+ Task<string?> NormalizeIndentationAsync(string str);+ //PushEditOperationsAsync+ Task PushStackElementAsync();+ Task SetEOLAsync(EndOfLineSequence eol);+ Task SetValue(string newValue);+ //Task UpdateOptions(ITextModelUpdateOptions newOpts);+ Task<Position?> ValidatePositionAsync(IPosition position);+ Task<Range?> ValidateRangeAsync(IRange range);+}+diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModelDecorationMinimapOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModelDecorationMinimapOptions.csnew file mode 100644index 000000000..05b0b0de6--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModelDecorationMinimapOptions.cs@@ -0,0 +1,26 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++public sealed class IModelDecorationMinimapOptions+{+ /// <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; }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModelDecorationOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModelDecorationOptions.csnew file mode 100644index 000000000..279f0bd65--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModelDecorationOptions.cs@@ -0,0 +1,113 @@+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 IModelDecorationOptions+{+ /// <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")]+ [JsonConverter(typeof(CssStyleConverter))]+ 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")]+ [JsonConverter(typeof(CssStyleConverter))]+ public CssGlyphStyle? GlyphMarginClassName { get; set; }++ /// <summary>+ /// Message to be rendered when hovering over the glyph margin decoration.+ /// </summary>+ [JsonProperty("glyphMarginHoverMessage")]+ public IMarkdownString[]? GlyphMarginHoverMessage { get; set; }++ /// <summary>+ /// Array of MarkdownString to render as the decoration message.+ /// </summary>+ [JsonProperty("hoverMessage")]+ public IMarkdownString[]? 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")]+ [JsonConverter(typeof(CssStyleConverter))]+ 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 IModelDecorationMinimapOptions? Minimap { get; set; }++ /// <summary>+ /// If set, render this decoration in the overview ruler.+ /// </summary>+ [JsonProperty("overviewRuler")]+ public IModelDecorationOverviewRulerOptions? 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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModelDecorationOverviewRulerOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModelDecorationOverviewRulerOptions.csnew file mode 100644index 000000000..898f00b03--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModelDecorationOverviewRulerOptions.cs@@ -0,0 +1,26 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++public sealed class IModelDecorationOverviewRulerOptions+{+ /// <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; }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModelDeltaDecoration.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModelDeltaDecoration.csnew file mode 100644index 000000000..d2042439a--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IModelDeltaDecoration.cs@@ -0,0 +1,22 @@+using DevToys.MonacoEditor.JsonConverters;+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++/// <summary>+/// New model decorations.+/// </summary>+public sealed class IModelDeltaDecoration+{+ [JsonProperty("options")]+ public IModelDecorationOptions Options { get; private set; }++ [JsonProperty("range"), JsonConverter(typeof(InterfaceToClassConverter<IRange, Range>))]+ public IRange Range { get; private set; }++ public IModelDeltaDecoration(IRange range, IModelDecorationOptions options)+ {+ Range = range;+ Options = options;+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IRelatedInformation.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IRelatedInformation.csnew file mode 100644index 000000000..c92f8012b--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IRelatedInformation.cs@@ -0,0 +1,24 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++public sealed class IRelatedInformation+{+ [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; }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/ISingleEditOperation.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/ISingleEditOperation.csnew file mode 100644index 000000000..4e808c44c--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/ISingleEditOperation.cs@@ -0,0 +1,30 @@+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 ISingleEditOperation+{+ /// <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; }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IStandaloneEditorConstructionOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IStandaloneEditorConstructionOptions.csnew file mode 100644index 000000000..849971f0f--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IStandaloneEditorConstructionOptions.cs@@ -0,0 +1,40 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/ISuggestOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/ISuggestOptions.csnew file mode 100644index 000000000..80ee5013d--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/ISuggestOptions.cs@@ -0,0 +1,213 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++/// <summary>+/// Configuration options for editor suggest widget+/// </summary>+public sealed class ISuggestOptions+{+ /// <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/app/dev/DevToys.MonacoEditor/Monaco/Editor/IWordAtPosition.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IWordAtPosition.csnew file mode 100644index 000000000..d139e826b--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/IWordAtPosition.cs@@ -0,0 +1,29 @@+using Newtonsoft.Json;+using DevToys.MonacoEditor.JsonConverters;++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/app/dev/DevToys.MonacoEditor/Monaco/Editor/InsertMode.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/InsertMode.csnew file mode 100644index 000000000..55b3470e1--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/InsertMode.cs@@ -0,0 +1,47 @@+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 };++internal class InsertModeConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "insert" => InsertMode.Insert,+ "replace" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/LineNumbersType.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/LineNumbersType.csnew file mode 100644index 000000000..e4e606089--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/LineNumbersType.cs@@ -0,0 +1,54 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++[JsonConverter(typeof(LineNumbersTypeConverter))]+public enum LineNumbersType { Interval, Off, On, Relative };++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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "interval" => LineNumbersType.Interval,+ "off" => LineNumbersType.Off,+ "on" => LineNumbersType.On,+ "relative" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/Marker.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/Marker.csnew file mode 100644index 000000000..1d5ced1d8--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/Marker.cs@@ -0,0 +1,45 @@+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 IRelatedInformation[]? 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/app/dev/DevToys.MonacoEditor/Monaco/Editor/MarkerData.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/MarkerData.csnew file mode 100644index 000000000..4f78b30cb--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/MarkerData.cs@@ -0,0 +1,53 @@+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 IRelatedInformation[]? 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; }++ public MarkerData() { }++ /// <summary>+ /// Initializes a new <see cref="MarkerData"/> instance in the specified <see cref="Range"/>. Provided as a helper.+ /// </summary>+ /// <param name="range"><see cref="Range"/> to scope Marker on.</param>+ public MarkerData(Range range)+ {+ StartLineNumber = range.StartLineNumber;+ StartColumn = range.StartColumn;+ EndLineNumber = range.EndLineNumber;+ EndColumn = range.EndColumn;+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/MatchBrackets.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/MatchBrackets.csnew file mode 100644index 000000000..4dcc429a8--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/MatchBrackets.cs@@ -0,0 +1,54 @@+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 };++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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "always" => MatchBrackets.Always,+ "near" => MatchBrackets.Near,+ "never" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/MouseStyle.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/MouseStyle.csnew file mode 100644index 000000000..d15a6576a--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/MouseStyle.cs@@ -0,0 +1,54 @@+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 };++internal class MouseStyleConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "copy" => MouseStyle.Copy,+ "default" => MouseStyle.Default,+ "text" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/MultiCursorModifier.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/MultiCursorModifier.csnew file mode 100644index 000000000..3d4dcfc7e--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/MultiCursorModifier.cs@@ -0,0 +1,50 @@+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 };++internal class MultiCursorModifierConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "alt" => MultiCursorModifier.Alt,+ "ctrlCmd" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/MultiCursorPaste.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/MultiCursorPaste.csnew file mode 100644index 000000000..18f1c5c26--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/MultiCursorPaste.cs@@ -0,0 +1,51 @@+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 };++internal class MultiCursorPasteConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "full" => MultiCursorPaste.Full,+ "spread" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/Multiple.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/Multiple.csnew file mode 100644index 000000000..df27d6a3d--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/Multiple.cs@@ -0,0 +1,50 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++[JsonConverter(typeof(MultipleConverter))]+public enum Multiple { Goto, GotoAndPeek, Peek };++internal class MultipleConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "goto" => Multiple.Goto,+ "gotoAndPeek" => Multiple.GotoAndPeek,+ "peek" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/RenderLineHighlight.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/RenderLineHighlight.csnew file mode 100644index 000000000..cd3d90eaf--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/RenderLineHighlight.cs@@ -0,0 +1,58 @@+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 };++internal class RenderLineHighlightConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "all" => RenderLineHighlight.All,+ "gutter" => RenderLineHighlight.Gutter,+ "line" => RenderLineHighlight.Line,+ "none" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/RenderWhitespace.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/RenderWhitespace.csnew file mode 100644index 000000000..7d290bc7d--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/RenderWhitespace.cs@@ -0,0 +1,58 @@+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 };++internal class RenderWhitespaceConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "all" => RenderWhitespace.All,+ "boundary" => RenderWhitespace.Boundary,+ "none" => RenderWhitespace.None,+ "selection" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/ScrollbarBehavior.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/ScrollbarBehavior.csnew file mode 100644index 000000000..38f4ba19a--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/ScrollbarBehavior.cs@@ -0,0 +1,54 @@+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 };++internal class ScrollbarBehaviorConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "auto" => ScrollbarBehavior.Auto,+ "hidden" => ScrollbarBehavior.Hidden,+ "visible" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/Show.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/Show.csnew file mode 100644index 000000000..4bda6acab--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/Show.cs@@ -0,0 +1,54 @@+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 };++internal class ShowConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "always" => Show.Always,+ "mouseover" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/Side.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/Side.csnew file mode 100644index 000000000..7d2f20b6d--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/Side.cs@@ -0,0 +1,50 @@+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 };++internal class SideConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "left" => Side.Left,+ "right" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/SnippetSuggestions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/SnippetSuggestions.csnew file mode 100644index 000000000..c03ccf11f--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/SnippetSuggestions.cs@@ -0,0 +1,57 @@+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 };++internal class SnippetSuggestionsConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "bottom" => SnippetSuggestions.Bottom,+ "inline" => SnippetSuggestions.Inline,+ "none" => SnippetSuggestions.None,+ "top" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/StandaloneEditorConstructionOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/StandaloneEditorConstructionOptions.csnew file mode 100644index 000000000..f3b7e5376--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/StandaloneEditorConstructionOptions.cs@@ -0,0 +1,895 @@+using Newtonsoft.Json;+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();++ private T? GetPropertyValue<T>([CallerMemberName] string? propertyName = null)+ {+ if (propertyName == null)+ throw new ArgumentNullException(nameof(propertyName));++ if (_propertyBackingDictionary.TryGetValue(propertyName, out object? value) && value is not null)+ {+ 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;++ _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)]+ [JsonConverter(typeof(AcceptSuggestionOnEnterConverter))]+ 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)]+ [JsonConverter(typeof(AccessibilitySupportConverter))]+ 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)]+ [JsonConverter(typeof(AutoClosingBracketsConverter))]+ public AutoClosingBrackets? AutoClosingBrackets { get => GetPropertyValue<AutoClosingBrackets?>(); set => SetPropertyValue(value); }++ /// <summary>+ /// Options for typing over closing quotes or brackets.+ /// </summary>+ [JsonProperty("autoClosingOvertype", NullValueHandling = NullValueHandling.Ignore)]+ [JsonConverter(typeof(AutoClosingOvertypeConverter))]+ 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)]+ [JsonConverter(typeof(AutoClosingQuotesConverter))]+ public AutoClosingQuotes? AutoClosingQuotes { get => GetPropertyValue<AutoClosingQuotes?>(); set => SetPropertyValue(value); }++ /// <summary>+ /// Enable auto indentation adjustment.+ /// Defaults to false.+ /// </summary>+ [JsonProperty("autoIndent", NullValueHandling = NullValueHandling.Ignore)]+ [JsonConverter(typeof(AutoIndentConverter))]+ 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)]+ [JsonConverter(typeof(AutoSurroundConverter))]+ 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 IEditorCommentsOptions? Comments { get => GetPropertyValue<IEditorCommentsOptions>(); 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)]+ [JsonConverter(typeof(CursorBlinkingConverter))]+ 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)]+ [JsonConverter(typeof(CursorStyleConverter))]+ 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)]+ [JsonConverter(typeof(CursorSurroundingLinesStyleConverter))]+ 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)]+ [JsonConverter(typeof(FoldingStrategyConverter))]+ 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)]+ [JsonConverter(typeof(LineNumbersTypeConverter))]+ 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)]+ [JsonConverter(typeof(MatchBracketsConverter))]+ 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)]+ [JsonConverter(typeof(MouseStyleConverter))]+ 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)]+ [JsonConverter(typeof(MultiCursorModifierConverter))]+ 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)]+ [JsonConverter(typeof(MultiCursorPasteConverter))]+ 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 IEditorParameterHintOptions? ParameterHints { get => GetPropertyValue<IEditorParameterHintOptions>(); 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)]+ [JsonConverter(typeof(RenderLineHighlightConverter))]+ 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)]+ [JsonConverter(typeof(RenderWhitespaceConverter))]+ 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 IEditorScrollbarOptions? Scrollbar { get => GetPropertyValue<IEditorScrollbarOptions>(); 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)]+ [JsonConverter(typeof(ShowConverter))]+ 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)]+ [JsonConverter(typeof(SnippetSuggestionsConverter))]+ 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 ISuggestOptions? Suggest { get => GetPropertyValue<ISuggestOptions>(); 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)]+ [JsonConverter(typeof(SuggestSelectionConverter))]+ public SuggestSelection? SuggestSelection { get => GetPropertyValue<SuggestSelection?>(); set => SetPropertyValue(value); }++ /// <summary>+ /// Enable tab completion.+ /// </summary>+ [JsonProperty("tabCompletion", NullValueHandling = NullValueHandling.Ignore)]+ [JsonConverter(typeof(TabCompletionConverter))]+ 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 `~!@#$%^&*()-=+[{]}\|;:'",.<>/?+ /// *+ /// </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)]+ [JsonConverter(typeof(WordWrapConverter))]+ 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})]?|&,;'.+ /// </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)]+ [JsonConverter(typeof(WrappingIndentConverter))]+ 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/app/dev/DevToys.MonacoEditor/Monaco/Editor/SuggestSelection.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/SuggestSelection.csnew file mode 100644index 000000000..3119474cd--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/SuggestSelection.cs@@ -0,0 +1,53 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++/// <summary>+/// The history mode for suggestions.+/// </summary>+[JsonConverter(typeof(SuggestSelectionConverter))]+public enum SuggestSelection { First, RecentlyUsed, RecentlyUsedByPrefix };++internal class SuggestSelectionConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "first" => SuggestSelection.First,+ "recentlyUsed" => SuggestSelection.RecentlyUsed,+ "recentlyUsedByPrefix" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/TabCompletion.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/TabCompletion.csnew file mode 100644index 000000000..13ccc319d--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/TabCompletion.cs@@ -0,0 +1,53 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++/// <summary>+/// Enable tab completion.+/// </summary>+[JsonConverter(typeof(TabCompletionConverter))]+public enum TabCompletion { Off, On, OnlySnippets };++internal class TabCompletionConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "off" => TabCompletion.Off,+ "on" => TabCompletion.On,+ "onlySnippets" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/TrackedRangeStickiness.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/TrackedRangeStickiness.csnew file mode 100644index 000000000..d977f457a--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/TrackedRangeStickiness.cs@@ -0,0 +1,13 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/WordAtPosition.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/WordAtPosition.csnew file mode 100644index 000000000..497ebe8c9--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/WordAtPosition.cs@@ -0,0 +1,27 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Editor/WordWrap.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/WordWrap.csnew file mode 100644index 000000000..876b01cba--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/WordWrap.cs@@ -0,0 +1,62 @@+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 };++internal class WordWrapConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "bounded" => WordWrap.Bounded,+ "off" => WordWrap.Off,+ "on" => WordWrap.On,+ "wordWrapColumn" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Editor/WrappingIndent.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/WrappingIndent.csnew file mode 100644index 000000000..aa1455c0f--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Editor/WrappingIndent.cs@@ -0,0 +1,58 @@+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 };++internal class WrappingIndentConverter : JsonConverter+{+ public override bool CanConvert(Type t) => 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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "deepIndent" => WrappingIndent.DeepIndent,+ "indent" => WrappingIndent.Indent,+ "none" => WrappingIndent.None,+ "same" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssGlyphStyle.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssGlyphStyle.csnew file mode 100644index 000000000..13fce6e70--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssGlyphStyle.cs@@ -0,0 +1,26 @@+using DevToys.MonacoEditor.Extensions;+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Helpers;++[JsonConverter(typeof(CssStyleConverter))]+public sealed class CssGlyphStyle : ICssStyle+{+ [JsonIgnore]+ public System.Uri? GlyphImage { get; set; }++ public uint Id { get; }++ public string Name { get; }++ public CssGlyphStyle()+ {+ Id = CssStyleBroker.Register(this);+ Name = "generated-style-" + Id;+ }++ public string ToCss()+ {+ return this.WrapCssClassName(string.Format("background: url(\"{0}\");", GlyphImage?.AbsoluteUriString() ?? string.Empty));+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssInlineStyle.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssInlineStyle.csnew file mode 100644index 000000000..930f848fd--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssInlineStyle.cs@@ -0,0 +1,79 @@+using Newtonsoft.Json;+using System.Text;+using Windows.UI;+using Windows.UI.Text;++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>+[JsonConverter(typeof(CssStyleConverter))]+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 Color? BackgroundColor { get; set; }++ public Color? ForegroundColor { get; set; }++ public uint Id { get; }++ public string Name { get; }++ public CssInlineStyle()+ {+ Id = CssStyleBroker.Register(this);+ Name = "generated-style-" + Id;+ }++ public string ToCss()+ {+ var 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.HasValue)+ {+ output.AppendLine(string.Format("background: rgba({0:d},{1:d},{2:d},{3:f});", BackgroundColor.Value.R,+ BackgroundColor.Value.G,+ BackgroundColor.Value.B,+ BackgroundColor.Value.A / 255f));+ }++ if (ForegroundColor.HasValue)+ {+ output.AppendLine(string.Format("color: rgba({0:d},{1:d},{2:d},{3:f}) !important;", ForegroundColor.Value.R,+ ForegroundColor.Value.G,+ ForegroundColor.Value.B,+ ForegroundColor.Value.A / 255f));+ }++ return this.WrapCssClassName(output.ToString());+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssLineStyle.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssLineStyle.csnew file mode 100644index 000000000..dd19e91b1--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssLineStyle.cs@@ -0,0 +1,54 @@+using Newtonsoft.Json;+using System.Text;+using Windows.UI;++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>+[JsonConverter(typeof(CssStyleConverter))]+public sealed class CssLineStyle : ICssStyle+{+ [JsonIgnore]+ public Color? BackgroundColor { get; set; }++ [Obsolete("Use ForegroundColor on CssInlineStyle instead, this is an overlay.")]+ [JsonIgnore]+ public Color? ForegroundColor { get; set; }++ public uint Id { get; }++ public string Name { get; }++ public CssLineStyle()+ {+ Id = CssStyleBroker.Register(this);+ Name = "generated-style-" + Id;+ }++ public string ToCss()+ {+ var output = new StringBuilder(40);+ if (BackgroundColor.HasValue)+ {+ //// we need to use rgba function like this due to EdgeHTML, otherwise we could use #RRGGBBAA which would be easier using #{n:X2}...+ output.AppendLine(string.Format("background: rgba({0:d},{1:d},{2:d},{3:f});", BackgroundColor.Value.R,+ BackgroundColor.Value.G,+ BackgroundColor.Value.B,+ BackgroundColor.Value.A / 255f));+ }+#pragma warning disable CS0618 // Type or member is obsolete+ if (ForegroundColor.HasValue)+ {+ output.AppendLine(string.Format("color: rgba({0:d},{1:d},{2:d},{3:f}) !important;", ForegroundColor.Value.R,+ ForegroundColor.Value.G,+ ForegroundColor.Value.B,+ ForegroundColor.Value.A / 255f));+ }+#pragma warning restore CS0618 // Type or member is obsolete++ return this.WrapCssClassName(output.ToString());+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssStyleBroker.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssStyleBroker.csnew file mode 100644index 000000000..7ac1a21c6--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssStyleBroker.cs@@ -0,0 +1,110 @@+using DevToys.MonacoEditor.Monaco.Editor;+using System.Text;++namespace DevToys.MonacoEditor.Monaco.Helpers;++/// <summary>+/// Broker to help manage CSS Styles and their usage within each CodeEditor. Lifetime managed by CodeEditor.+/// </summary>+internal sealed class CssStyleBroker : IDisposable+{+ private static uint Id = 0;++ // Track styles registered to this particular editor.+ private static readonly Dictionary<uint, WeakReference<ICssStyle>> registry = new();++ private static readonly Dictionary<WeakReference<CodeEditor>, HashSet<uint>> knownStyles = new();++ private static readonly Dictionary<WeakReference<CodeEditor>, bool> isDirty = new();++ private readonly WeakReference<CodeEditor> _parent;++ public CssStyleBroker(CodeEditor codeEditor)+ {+ _parent = new WeakReference<CodeEditor>(codeEditor);+ knownStyles.Add(_parent, new HashSet<uint>());+ isDirty.Add(_parent, false);+ }++ public void Dispose()+ {+ knownStyles.Remove(_parent);+ isDirty.Remove(_parent);+ }++ /// <summary>+ /// Returns the name for a style to use after registered. Generates a unique style name.+ /// </summary>+ /// <param name="style"></param>+ /// <returns></returns>+ public static uint Register(ICssStyle style)+ {+ uint id = Id++;+ registry.Add(id, new WeakReference<ICssStyle>(style));+ return id;+ }++ public bool AssociateStyles(IModelDeltaDecoration[] decorations)+ {+ /// By construction we assume that decorations will not be null from the call in <see cref="CodeEditor.DeltaDecorationsHelperAsync"/>+ bool newStyle = isDirty[_parent]; /// Can be set in <see cref="GetStyles"/>.++ isDirty[_parent] = false; // Reset++ foreach (IModelDeltaDecoration decoration in decorations)+ {+ // Add (or ignore) elements to the collection.+ // If any Adds are new, we flag our boolean to return+ if (decoration.Options.ClassName != null)+ {+ newStyle |= knownStyles[_parent].Add(decoration.Options.ClassName.Id);+ }+ if (decoration.Options.GlyphMarginClassName != null)+ {+ newStyle |= knownStyles[_parent].Add(decoration.Options.GlyphMarginClassName.Id);+ }+ if (decoration.Options.InlineClassName != null)+ {+ newStyle |= knownStyles[_parent].Add(decoration.Options.InlineClassName.Id);+ }+ }++ return newStyle;+ }++ /// <summary>+ /// Returns the CSS block for all registered styles.+ /// </summary>+ /// <returns></returns>+ public string GetStyles()+ {+ var rules = new StringBuilder(100);+ knownStyles[_parent].RemoveWhere(id =>+ {+ if (registry[id].TryGetTarget(out ICssStyle? style))+ {+ rules.AppendLine(style.ToCss());+ }+ else+ {+ // Clean-up from disposed style objects+ foreach (KeyValuePair<WeakReference<CodeEditor>, HashSet<uint>> entry in knownStyles)+ {+ if (entry.Key == _parent)+ {+ break; // Skip our current editor, as we can't remove from within the loop. Thus the return true below in this RemoveWhere clause.+ }+ entry.Value.Remove(id); // Remove from Style set+ isDirty[entry.Key] = true; // Mark that editor as dirty+ }+ registry.Remove(id); // Remove the style completely from our known world as it's gone.++ return true; // Also remove this entry from our own set.+ }++ return false; // Default, we're just using this as a dumb loop, but that we can remove from when needed above.+ });++ return rules.ToString();+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/ICssStyle.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/ICssStyle.csnew file mode 100644index 000000000..4287e0c7c--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/ICssStyle.cs@@ -0,0 +1,35 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Helpers;++public interface ICssStyle+{+ uint Id { get; }++ string Name { get; }++ string ToCss();+}++public static class ICssStyleExtensions+{+ public static string WrapCssClassName(this ICssStyle style, string inner)+ {+ return string.Format(".{0} {{ {1} }}", style.Name, inner);+ }+}++internal class CssStyleConverter : JsonConverter+{+ public override bool CanConvert(Type objectType) => typeof(ICssStyle).IsAssignableFrom(objectType);++ 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/app/dev/DevToys.MonacoEditor/Monaco/Helpers/TextDecoration.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/TextDecoration.csnew file mode 100644index 000000000..193baf21a--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/TextDecoration.cs@@ -0,0 +1,69 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Helpers;++[JsonConverter(typeof(TextDecorationConverter))]+public enum TextDecoration+{+ None,+ Underline,+ Overline,+ LineThrough,+ Initial,+ Inherit+}+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;+ }+ string? value = serializer.Deserialize<string>(reader);+ return value switch+ {+ "none" => TextDecoration.None,+ "underline" => TextDecoration.Underline,+ "overline" => TextDecoration.Overline,+ "line-through" => TextDecoration.LineThrough,+ "initial" => TextDecoration.Initial,+ "inherit" => (object)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/app/dev/DevToys.MonacoEditor/Monaco/IMarkdownString.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/IMarkdownString.csnew file mode 100644index 000000000..c9a00b975--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/IMarkdownString.cs@@ -0,0 +1,52 @@+using Newtonsoft.Json;+using Windows.Foundation.Metadata;+using System.Runtime.InteropServices.WindowsRuntime;++namespace DevToys.MonacoEditor.Monaco;++public sealed class IMarkdownString+{+ [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 IMarkdownString(string svalue) : this(svalue, false) { }++ public IMarkdownString(string svalue, bool isTrusted)+ {+ Value = svalue;+ IsTrusted = isTrusted;+ }+}++public static class MarkdownStringExtensions+{+ [DefaultOverload]+ public static IMarkdownString ToMarkdownString(this string svalue)+ {+ return ToMarkdownString(svalue, false);+ }++ [DefaultOverload]+ public static IMarkdownString ToMarkdownString(this string svalue, bool isTrusted)+ {+ return new IMarkdownString(svalue, isTrusted);+ }++ public static IMarkdownString[] ToMarkdownString([ReadOnlyArray] this string[] values)+ {+ return ToMarkdownString(values, false);+ }++ public static IMarkdownString[] ToMarkdownString([ReadOnlyArray] this string[] values, bool isTrusted)+ {+ return values.Select(value => new IMarkdownString(value, isTrusted)).ToArray();+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/IPosition.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/IPosition.csnew file mode 100644index 000000000..65cb843a6--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/IPosition.cs@@ -0,0 +1,21 @@+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/app/dev/DevToys.MonacoEditor/Monaco/IRange.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/IRange.csnew file mode 100644index 000000000..623aaa9a0--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/IRange.cs@@ -0,0 +1,33 @@+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/app/dev/DevToys.MonacoEditor/Monaco/KeyCode.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/KeyCode.csnew file mode 100644index 000000000..d7a10b050--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/KeyCode.cs@@ -0,0 +1,183 @@+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 & OS`s.+/// </summary>+public static class KeyCode+{+ /**+ * Placed first to cover the 0 value of the enum.+ */+ public static int Unknown => 0;+ public static int Backspace => 1;+ public static int Tab => 2;+ public static int Enter => 3;+ public static int Shift => 4;+ public static int Ctrl => 5;+ public static int Alt => 6;+ public static int PauseBreak => 7;+ public static int CapsLock => 8;+ public static int Escape => 9;+ public static int Space => 10;+ public static int PageUp => 11;+ public static int PageDown => 12;+ public static int End => 13;+ public static int Home => 14;+ public static int LeftArrow => 15;+ public static int UpArrow => 16;+ public static int RightArrow => 17;+ public static int DownArrow => 18;+ public static int Insert => 19;+ public static int Delete => 20;+ public static int KEY_0 => 21;+ public static int KEY_1 => 22;+ public static int KEY_2 => 23;+ public static int KEY_3 => 24;+ public static int KEY_4 => 25;+ public static int KEY_5 => 26;+ public static int KEY_6 => 27;+ public static int KEY_7 => 28;+ public static int KEY_8 => 29;+ public static int KEY_9 => 30;+ public static int KEY_A => 31;+ public static int KEY_B => 32;+ public static int KEY_C => 33;+ public static int KEY_D => 34;+ public static int KEY_E => 35;+ public static int KEY_F => 36;+ public static int KEY_G => 37;+ public static int KEY_H => 38;+ public static int KEY_I => 39;+ public static int KEY_J => 40;+ public static int KEY_K => 41;+ public static int KEY_L => 42;+ public static int KEY_M => 43;+ public static int KEY_N => 44;+ public static int KEY_O => 45;+ public static int KEY_P => 46;+ public static int KEY_Q => 47;+ public static int KEY_R => 48;+ public static int KEY_S => 49;+ public static int KEY_T => 50;+ public static int KEY_U => 51;+ public static int KEY_V => 52;+ public static int KEY_W => 53;+ public static int KEY_X => 54;+ public static int KEY_Y => 55;+ public static int KEY_Z => 56;+ public static int Meta => 57;+ public static int ContextMenu => 58;+ public static int F1 => 59;+ public static int F2 => 60;+ public static int F3 => 61;+ public static int F4 => 62;+ public static int F5 => 63;+ public static int F6 => 64;+ public static int F7 => 65;+ public static int F8 => 66;+ public static int F9 => 67;+ public static int F10 => 68;+ public static int F11 => 69;+ public static int F12 => 70;+ public static int F13 => 71;+ public static int F14 => 72;+ public static int F15 => 73;+ public static int F16 => 74;+ public static int F17 => 75;+ public static int F18 => 76;+ public static int F19 => 77;+ public static int NumLock => 78;+ public static int ScrollLock => 79;+ /**+ * Used for miscellaneous characters; it can vary by keyboard.+ * For the US standard keyboard, the ';:' key+ */+ public static int US_SEMICOLON => 80;+ /**+ * For any country/region, the '+' key+ * For the US standard keyboard, the '=+' key+ */+ public static int US_EQUAL => 81;+ /**+ * For any country/region, the ',' key+ * For the US standard keyboard, the ',<' key+ */+ public static int US_COMMA => 82;+ /**+ * For any country/region, the '-' key+ * For the US standard keyboard, the '-_' key+ */+ public static int US_MINUS => 83;+ /**+ * For any country/region, the '.' key+ * For the US standard keyboard, the '.>' key+ */+ public static int US_DOT => 84;+ /**+ * Used for miscellaneous characters; it can vary by keyboard.+ * For the US standard keyboard, the '/?' key+ */+ public static int US_SLASH => 85;+ /**+ * Used for miscellaneous characters; it can vary by keyboard.+ * For the US standard keyboard, the '`~' key+ */+ public static int US_BACKTICK => 86;+ /**+ * Used for miscellaneous characters; it can vary by keyboard.+ * For the US standard keyboard, the '[{' key+ */+ public static int US_OPEN_SQUARE_BRACKET => 87;+ /**+ * Used for miscellaneous characters; it can vary by keyboard.+ * For the US standard keyboard, the '\|' key+ */+ public static int US_BACKSLASH => 88;+ /**+ * Used for miscellaneous characters; it can vary by keyboard.+ * For the US standard keyboard, the ']}' key+ */+ public static int US_CLOSE_SQUARE_BRACKET => 89;+ /**+ * Used for miscellaneous characters; it can vary by keyboard.+ * For the US standard keyboard, the ''"' key+ */+ public static int US_QUOTE => 90;+ /**+ * Used for miscellaneous characters; it can vary by keyboard.+ */+ public static int OEM_8 => 91;+ /**+ * Either the angle bracket key or the backslash key on the RT 102-key keyboard.+ */+ public static int OEM_102 => 92;+ public static int NUMPAD_0 => 93;+ public static int NUMPAD_1 => 94;+ public static int NUMPAD_2 => 95;+ public static int NUMPAD_3 => 96;+ public static int NUMPAD_4 => 97;+ public static int NUMPAD_5 => 98;+ public static int NUMPAD_6 => 99;+ public static int NUMPAD_7 => 100;+ public static int NUMPAD_8 => 101;+ public static int NUMPAD_9 => 102;+ public static int NUMPAD_MULTIPLY => 103;+ public static int NUMPAD_ADD => 104;+ public static int NUMPAD_SEPARATOR => 105;+ public static int NUMPAD_SUBTRACT => 106;+ public static int NUMPAD_DECIMAL => 107;+ public static int NUMPAD_DIVIDE => 108;+ /**+ * Cover all key codes when IME is processing input.+ */+ public static int KEY_IN_COMPOSITION => 109;+ public static int ABNT_C1 => 110;+ public static int ABNT_C2 => 111;+ /**+ * Placed last to cover the length of the enum.+ * Please do not depend on this value!+ */+ public static int MAX_VALUE => 112;+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/KeyMod.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/KeyMod.csnew file mode 100644index 000000000..ccc933508--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/KeyMod.cs@@ -0,0 +1,33 @@+namespace DevToys.MonacoEditor.Monaco;++/// <summary>+/// https://microsoft.github.io/monaco-editor/api/classes/monaco.keymod.html+/// </summary>+public sealed class KeyMod+{+ public static int WinCtrl => 256;+ public static int Alt => 512;+ public static int Shift => 1024;+ public static 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+ int 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/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeAction.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeAction.csnew file mode 100644index 000000000..1359d2204--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeAction.cs@@ -0,0 +1,29 @@+using DevToys.MonacoEditor.Monaco.Editor;+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Languages;++public sealed class CodeAction+{+ [JsonProperty("command", NullValueHandling = NullValueHandling.Ignore)]+ public Command? Command { get; set; }++ [JsonProperty("diagnostics", NullValueHandling = NullValueHandling.Ignore)]+ public IMarkerData[]? Diagnostics { get; set; }++ [JsonProperty("disabled", NullValueHandling = NullValueHandling.Ignore)]+ public string? Disabled { get; set; }++ [JsonProperty("edit", NullValueHandling = NullValueHandling.Ignore)]+ public WorkspaceEdit? Edit { get; set; }++ [JsonProperty("isPreferred", NullValueHandling = NullValueHandling.Ignore)]+ public bool IsPreferred { get; set; }++ [JsonProperty("kind", NullValueHandling = NullValueHandling.Ignore)]+ public string? Kind { get; set; }++ [JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)]+ public string? Title { get; set; }+}+diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeActionContext.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeActionContext.csnew file mode 100644index 000000000..2ef87eecf--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeActionContext.cs@@ -0,0 +1,24 @@+using DevToys.MonacoEditor.Monaco.Editor;+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Languages;++/// <summary>+/// Contains additional diagnostic information about the context in which+/// a [code action](#CodeActionProvider.provideCodeActions) is run.+/// </summary>+public sealed class CodeActionContext+{+ /// <summary>+ /// An array of diagnostics.+ /// </summary>+ [JsonProperty("markers", NullValueHandling = NullValueHandling.Ignore)]+ public MarkerData[]? Markers { get; set; } // TODO: Should setup the serialization mappings between interfaces to leave interfaces here...++ /// <summary>+ /// Requested kind of actions to return.+ /// </summary>+ [JsonProperty("only", NullValueHandling = NullValueHandling.Ignore)]+ public string? Only { get; set; }+}+diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeActionList.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeActionList.csnew file mode 100644index 000000000..4c0eddf8e--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeActionList.cs@@ -0,0 +1,8 @@+namespace DevToys.MonacoEditor.Monaco.Languages;++public sealed class CodeActionList // IDisposable??+{+ [Newtonsoft.Json.JsonProperty("actions", NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]+ public CodeAction[]? Actions { get; set; }+}+diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeActionProvider.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeActionProvider.csnew file mode 100644index 000000000..b4f68e727--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeActionProvider.cs@@ -0,0 +1,17 @@+using DevToys.MonacoEditor.Monaco.Editor;+using Windows.Foundation;++namespace DevToys.MonacoEditor.Monaco.Languages;++/// <summary>+/// The code action interface defines the contract between extensions and+/// the [light bulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) feature.+/// </summary>+public interface CodeActionProvider+{+ /// <summary>+ /// Provide commands for the given document and range.+ /// </summary>+ Task<CodeActionList> ProvideCodeActionsAsync(IModel model, Range range, CodeActionContext context);+}+diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeLens.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeLens.csnew file mode 100644index 000000000..f38e4a61f--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeLens.cs@@ -0,0 +1,16 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Languages;++public sealed class CodeLens+{+ [JsonProperty("command", NullValueHandling = NullValueHandling.Ignore)]+ public Command? Command { get; set; }++ [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]+ public string? Id { get; set; }++ [JsonProperty("range", NullValueHandling = NullValueHandling.Ignore)]+ public IRange? Range { get; set; }+}+diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeLensList.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeLensList.csnew file mode 100644index 000000000..3c3159a84--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeLensList.cs@@ -0,0 +1,10 @@+namespace DevToys.MonacoEditor.Monaco.Languages;++using Newtonsoft.Json;++public sealed class CodeLensList // IDisposible?+{+ [JsonProperty("lenses", NullValueHandling = NullValueHandling.Ignore)]+ public CodeLens[]? Lenses { get; set; }+}+diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeLensProvider.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeLensProvider.csnew file mode 100644index 000000000..2a1d39eea--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CodeLensProvider.cs@@ -0,0 +1,11 @@+using DevToys.MonacoEditor.Monaco.Editor;++namespace DevToys.MonacoEditor.Monaco.Languages;++public interface CodeLensProvider+{+ Task<CodeLensList> ProvideCodeLensesAsync(IModel model);++ Task<CodeLens> ResolveCodeLensAsync(IModel model, CodeLens codeLens);+}+diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/ColorInformation.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/ColorInformation.csnew file mode 100644index 000000000..772fa126b--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/ColorInformation.cs@@ -0,0 +1,85 @@+using DevToys.MonacoEditor.JsonConverters;+using Newtonsoft.Json;+using Windows.UI;++namespace DevToys.MonacoEditor.Monaco.Languages;++/// <summary>+/// A color range is a range in a text model which represents a color.+/// </summary>+public sealed class ColorInformation+{+ [JsonProperty("color")]+ [JsonConverter(typeof(ColorConverter))]+ public Color Color { get; set; }++ [JsonProperty("range")]+ [JsonConverter(typeof(InterfaceToClassConverter<IRange, Range>))]+ public IRange Range { get; set; }++ public ColorInformation(Color color, IRange range)+ {+ Color = color;+ Range = range;+ }+}++/// <summary>+/// Helper to convert between <see cref="Windows.UI.Color"/> and Monaco <see href="https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.icolor.html">IColor</see>.+/// </summary>+internal class ColorConverter : JsonConverter+{+ public override bool CanConvert(Type t) => t == typeof(Color) || t == typeof(Color?);++ public override object? ReadJson(JsonReader reader, Type t, object? existingValue, JsonSerializer serializer)+ {+ var color = new Color();++ if (reader.Read())+ {+ while (reader.TokenType != JsonToken.EndObject)+ {+ switch (reader.Value)+ {+ case "alpha":+ color.A = (byte)(reader.ReadAsDouble().GetValueOrDefault(0) * 255);+ break;+ case "red":+ color.R = (byte)(reader.ReadAsDouble().GetValueOrDefault(0) * 255);+ break;+ case "green":+ color.G = (byte)(reader.ReadAsDouble().GetValueOrDefault(0) * 255);+ break;+ case "blue":+ color.B = (byte)(reader.ReadAsDouble().GetValueOrDefault(0) * 255);+ break;+ }++ reader.Read(); // Advance past Number Token read above to next property+ }+ }++ return color;+ }++ public override void WriteJson(JsonWriter writer, object? untypedValue, JsonSerializer serializer)+ {+ if (untypedValue == null)+ {+ serializer.Serialize(writer, null);+ return;+ }+ var value = (Color)untypedValue;++ writer.WriteStartObject();+ writer.WritePropertyName("alpha");+ writer.WriteValue(value.A / 255F);+ writer.WritePropertyName("red");+ writer.WriteValue(value.R / 255F);+ writer.WritePropertyName("green");+ writer.WriteValue(value.G / 255F);+ writer.WritePropertyName("blue");+ writer.WriteValue(value.B / 255F);+ writer.WriteEndObject();+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/ColorPresentation.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/ColorPresentation.csnew file mode 100644index 000000000..7f6005248--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/ColorPresentation.cs@@ -0,0 +1,34 @@+using DevToys.MonacoEditor.Monaco.Editor;+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Languages;++/// <summary>+/// String representations for a color.+/// <seealso href="https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.icolorpresentation.html">monaco.languages.IColorPresentation</seealso>+/// </summary>+public sealed class ColorPresentation+{+ /// <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 ISingleEditOperation[]? AdditionalTextEdits { get; set; }++ /// <summary>+ /// The label of this color presentation. It will be shown on the color picker header.+ /// By default this is also the text that is inserted when selecting this color presentation.+ /// </summary>+ [JsonProperty("label")]+ public string? Label { get; set; }++ [JsonProperty("textEdit", NullValueHandling = NullValueHandling.Ignore)]+ public ISingleEditOperation? TextEdit { get; set; }++ public ColorPresentation(string label)+ {+ Label = label;+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/Command.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/Command.csnew file mode 100644index 000000000..1f321d7dc--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/Command.cs@@ -0,0 +1,21 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionContext.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionContext.csnew file mode 100644index 000000000..52e42e9a4--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionContext.cs@@ -0,0 +1,24 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionItem.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionItem.csnew file mode 100644index 000000000..17de0a4e5--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionItem.cs@@ -0,0 +1,130 @@+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 ISingleEditOperation[]? 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 IMarkdownString? 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/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionItemInsertTextRule.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionItemInsertTextRule.csnew file mode 100644index 000000000..05ee98831--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionItemInsertTextRule.cs@@ -0,0 +1,14 @@+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+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionItemKind.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionItemKind.csnew file mode 100644index 000000000..b42658362--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionItemKind.cs@@ -0,0 +1,31 @@+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+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionItemProvider.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionItemProvider.csnew file mode 100644index 000000000..05063b5ab--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionItemProvider.cs@@ -0,0 +1,30 @@+using DevToys.MonacoEditor.Monaco.Editor;+using Newtonsoft.Json;++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 CompletionItemProvider+{+ [JsonProperty("triggerCharacters", NullValueHandling = NullValueHandling.Ignore)]+ string[] TriggerCharacters { get; }+ /// <summary>+ /// Provide completion items for the given position and document.+ /// </summary>+ Task<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>+ Task<CompletionItem> ResolveCompletionItemAsync(IModel model, CompletionItem item);+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionList.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionList.csnew file mode 100644index 000000000..1097c8ae3--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/CompletionList.cs@@ -0,0 +1,12 @@+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/app/dev/DevToys.MonacoEditor/Monaco/Languages/DocumentColorProvider.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/DocumentColorProvider.csnew file mode 100644index 000000000..87c734fbb--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/DocumentColorProvider.cs@@ -0,0 +1,20 @@+using DevToys.MonacoEditor.Monaco.Editor;++namespace DevToys.MonacoEditor.Monaco.Languages;++/// <summary>+/// A provider of colors for editor models.+/// <seealso href="https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.documentcolorprovider.html">monaco.languages.DocumentColorProvider</seealso>+/// </summary>+public interface DocumentColorProvider+{+ /// <summary>+ /// Provide the string representations for a color.+ /// </summary>+ Task<IEnumerable<ColorPresentation>> ProvideColorPresentationsAsync(IModel model, ColorInformation colorInfo);++ /// <summary>+ /// Provides the color ranges for a specific model.+ /// </summary>+ Task<IEnumerable<ColorInformation>> ProvideDocumentColorsAsync(IModel model);+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/Hover.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/Hover.csnew file mode 100644index 000000000..aaae148e7--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/Hover.cs@@ -0,0 +1,38 @@+using Newtonsoft.Json;++#if !NETSTANDARD2_0+using System.Runtime.InteropServices.WindowsRuntime;+#else+using ReadOnlyArrayAttribute = Monaco.Helpers.Stubs.ReadOnlyArrayAttribute;+#endif++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 IMarkdownString[] 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/app/dev/DevToys.MonacoEditor/Monaco/Languages/HoverProvider.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/HoverProvider.csnew file mode 100644index 000000000..57dc2b844--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/HoverProvider.cs@@ -0,0 +1,17 @@+using DevToys.MonacoEditor.Monaco.Editor;++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 HoverProvider+{+ /// <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>+ Task<Hover> ProvideHover(IModel model, Position position);+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/ILanguageExtensionPoint.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/ILanguageExtensionPoint.csnew file mode 100644index 000000000..abaadd207--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/ILanguageExtensionPoint.cs@@ -0,0 +1,23 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Languages;++public sealed class ILanguageExtensionPoint+{+ [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/app/dev/DevToys.MonacoEditor/Monaco/Languages/SuggestTriggerKind.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/SuggestTriggerKind.csnew file mode 100644index 000000000..a3fe4be9b--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/SuggestTriggerKind.cs@@ -0,0 +1,11 @@+namespace DevToys.MonacoEditor.Monaco.Languages;++/// <summary>+/// How a suggest provider was triggered.+/// </summary>+public enum CompletionTriggerKind+{+ Invoke = 0,+ TriggerCharacter = 1,+ TriggerForIncompleteCompletions = 2+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/TextEdit.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/TextEdit.csnew file mode 100644index 000000000..6099de76c--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/TextEdit.cs@@ -0,0 +1,16 @@+using DevToys.MonacoEditor.Monaco.Editor;+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Languages;++public sealed class TextEdit+{+ [JsonProperty("range", NullValueHandling = NullValueHandling.Ignore)]+ public IRange? Range { get; set; }++ [JsonProperty("text", NullValueHandling = NullValueHandling.Ignore)]+ public string? Text { get; set; }++ [JsonProperty("eol", NullValueHandling = NullValueHandling.Ignore)]+ public EndOfLineSequence Eol { get; set; }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceEdit.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceEdit.csnew file mode 100644index 000000000..2b9b5b028--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceEdit.cs@@ -0,0 +1,9 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Languages;++public sealed class WorkspaceEdit+{+ [JsonProperty("edits", NullValueHandling = NullValueHandling.Ignore)]+ public WorkspaceTextEdit[]? Edits { get; set; } // TODO: This could also be of type 'WorkspaceFileEdit'+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceEditMetadata.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceEditMetadata.csnew file mode 100644index 000000000..be54517bb--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceEditMetadata.cs@@ -0,0 +1,15 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Languages;++public interface WorkspaceEditMetadata+{+ [JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)]+ string Description { get; set; }++ [JsonProperty("label", NullValueHandling = NullValueHandling.Ignore)]+ string Label { get; set; }++ [JsonProperty("needsConfirmation", NullValueHandling = NullValueHandling.Ignore)]+ bool NeedsConfirmation { get; set; }+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceFileEdit.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceFileEdit.csnew file mode 100644index 000000000..60816c898--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceFileEdit.cs@@ -0,0 +1,18 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Languages;++public interface WorkspaceFileEdit+{+ [JsonProperty("metadata", NullValueHandling = NullValueHandling.Ignore)]+ WorkspaceEditMetadata Metadata { get; set; }++ [JsonProperty("newUri", NullValueHandling = NullValueHandling.Ignore)]+ Uri NewUri { get; set; }++ [JsonProperty("oldUri", NullValueHandling = NullValueHandling.Ignore)]+ Uri OldUri { get; set; }++ [JsonProperty("options", NullValueHandling = NullValueHandling.Ignore)]+ WorkspaceFileEditOptions Options { get; set; }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceFileEditOptions.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceFileEditOptions.csnew file mode 100644index 000000000..cfc00a187--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceFileEditOptions.cs@@ -0,0 +1,30 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Languages;++public interface WorkspaceFileEditOptions+{+ [JsonProperty("copy", NullValueHandling = NullValueHandling.Ignore)]+ bool Copy { get; set; }++ [JsonProperty("folder", NullValueHandling = NullValueHandling.Ignore)]+ bool Folder { get; set; }++ [JsonProperty("ignoreIfExists", NullValueHandling = NullValueHandling.Ignore)]+ bool IgnoreIfExists { get; set; }++ [JsonProperty("ignoreIfNotExists", NullValueHandling = NullValueHandling.Ignore)]+ bool IgnoreIfNotExists { get; set; }++ [JsonProperty("maxSize", NullValueHandling = NullValueHandling.Ignore)]+ double MaxSize { get; set; }++ [JsonProperty("overwrite", NullValueHandling = NullValueHandling.Ignore)]+ bool Overwrite { get; set; }++ [JsonProperty("recursive", NullValueHandling = NullValueHandling.Ignore)]+ bool Recursive { get; set; }++ [JsonProperty("skipTrashBin", NullValueHandling = NullValueHandling.Ignore)]+ bool SkipTrashBin { get; set; }+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceTextEdit.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceTextEdit.csnew file mode 100644index 000000000..627ffe2dd--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Languages/WorkspaceTextEdit.cs@@ -0,0 +1,18 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Languages;++public sealed class WorkspaceTextEdit+{+ [JsonProperty("edit", NullValueHandling = NullValueHandling.Ignore)]+ public TextEdit? Edit { get; set; }++ [JsonProperty("metadata", NullValueHandling = NullValueHandling.Ignore)]+ public WorkspaceEditMetadata? Metadata { get; set; }++ [JsonProperty("modelVersionId", NullValueHandling = NullValueHandling.Ignore)]+ public double? ModelVersionId { get; set; } //// Important for this to be nullable here, as otherwise it still serializes as '0' which throws a 'bad state - model changed in the meantime' as version will mismatch++ [JsonProperty("resource", NullValueHandling = NullValueHandling.Ignore)]+ public Uri? Resource { get; set; }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/LanguagesHelper.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/LanguagesHelper.csnew file mode 100644index 000000000..873eca8d2--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/LanguagesHelper.cs@@ -0,0 +1,233 @@+using DevToys.MonacoEditor.Monaco.Languages;+using Newtonsoft.Json;+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<CodeEditor> _editor;++ [Obsolete("Use <Editor Instance>.Languages.* instead of constructing your own LanguagesHelper.")]+ [EditorBrowsable(EditorBrowsableState.Never)]+ public LanguagesHelper(CodeEditor editor) // TODO: Make Internal later.+ {+ // 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<CodeEditor>(editor);+ }++ public Task<IList<ILanguageExtensionPoint>?> GetLanguagesAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<IList<ILanguageExtensionPoint>>("monaco.languages.getLanguages()");+ }++ return Task.FromResult<IList<ILanguageExtensionPoint>?>(null);+ }++ public Task RegisterAsync(ILanguageExtensionPoint language)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.InvokeScriptAsync("monaco.languages.register", language);+ }++ return Task.CompletedTask;+ }++ public Task RegisterCodeActionProviderAsync(string languageId, CodeActionProvider provider)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ // link:registerCodeActionProvider.ts:ProvideCodeActions+ editor.ParentAccessor.RegisterEvent("ProvideCodeActions" + languageId, async (args) =>+ {+ if (args != null && args.Length >= 2)+ {+ Range? range = JsonConvert.DeserializeObject<Range>(args[0]);+ CodeActionContext? context = JsonConvert.DeserializeObject<CodeActionContext>(args[1]);+ Guard.IsNotNull(context);+ Guard.IsNotNull(range);++ CodeActionList list = await provider.ProvideCodeActionsAsync(editor.GetModel(), range, context);++ if (list != null)+ {+ return JsonConvert.SerializeObject(list);+ }+ }++ return string.Empty;+ });++ // link:registerCodeActionProvider.ts:registerCodeActionProvider+ return editor.InvokeScriptAsync("registerCodeActionProvider", new object[] { languageId });+ }++ return Task.CompletedTask;+ }++ public Task RegisterCodeLensProviderAsync(string languageId, CodeLensProvider provider)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ // link:registerCodeLensProvider.ts:ProvideCodeLenses+ editor.ParentAccessor.RegisterEvent("ProvideCodeLenses" + languageId, async (args) =>+ {+ CodeLensList list = await provider.ProvideCodeLensesAsync(editor.GetModel());++ if (list != null)+ {+ return JsonConvert.SerializeObject(list);+ }++ return string.Empty;+ });++ // link:registerCodeLensProvider.ts:ResolveCodeLens+ editor.ParentAccessor.RegisterEvent("ResolveCodeLens" + languageId, async (args) =>+ {+ if (args != null && args.Length >= 1)+ {+ CodeLens lens = await provider.ResolveCodeLensAsync(editor.GetModel(), JsonConvert.DeserializeObject<CodeLens>(args[0])!);++ if (lens != null)+ {+ return JsonConvert.SerializeObject(lens);+ }+ }++ return string.Empty;+ });++ // link:registerCodeLensProvider.ts:registerCodeLensProvider+ return editor.InvokeScriptAsync("registerCodeLensProvider", new object[] { languageId });+ }++ return Task.CompletedTask;+ }++ public Task RegisterColorProviderAsync(string languageId, DocumentColorProvider provider)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ // link:registerColorProvider.ts:ProvideColorPresentations+ editor.ParentAccessor.RegisterEvent("ProvideColorPresentations" + languageId, async (args) =>+ {+ if (args != null && args.Length >= 1)+ {+ IEnumerable<ColorPresentation> items = await provider.ProvideColorPresentationsAsync(editor.GetModel(), JsonConvert.DeserializeObject<ColorInformation>(args[0])!);++ if (items != null)+ {+ return JsonConvert.SerializeObject(items);+ }+ }++ return string.Empty;+ });++ // link:registerColorProvider.ts:ProvideDocumentColors+ editor.ParentAccessor.RegisterEvent("ProvideDocumentColors" + languageId, async (args) =>+ {+ IEnumerable<ColorInformation> items = await provider.ProvideDocumentColorsAsync(editor.GetModel());++ if (items != null)+ {+ return JsonConvert.SerializeObject(items);+ }++ return string.Empty;+ });++ // link:registerColorProvider.ts:registerColorProvider+ return editor.InvokeScriptAsync("registerColorProvider", new object[] { languageId });+ }++ return Task.CompletedTask;+ }++ public Task RegisterCompletionItemProviderAsync(string languageId, CompletionItemProvider provider)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ // TODO: Add Incremented Id so that we can register multiple providers per language?+ // link:registerCompletionItemProvider.ts:CompletionItemProvider+ editor.ParentAccessor.RegisterEvent("CompletionItemProvider" + languageId, async (args) =>+ {+ if (args != null && args.Length >= 2)+ {+ CompletionList items = await provider.ProvideCompletionItemsAsync(editor.GetModel(), JsonConvert.DeserializeObject<Position>(args[0])!, JsonConvert.DeserializeObject<CompletionContext>(args[1])!);++ if (items != null)+ {+ Debug.WriteLine("Items: " + items);+ string serialized = JsonConvert.SerializeObject(items);+ Debug.WriteLine("Items in JSON: " + serialized);+ return serialized;+ }+ }++ return string.Empty;+ });++ // link:registerCompletionItemProvider.ts:CompletionItemRequested+ editor.ParentAccessor.RegisterEvent("CompletionItemRequested" + languageId, async (args) =>+ {+ if (args != null && args.Length >= 1)+ {+ CompletionItem? requestedItem = JsonConvert.DeserializeObject<CompletionItem>(args[0]);+ Guard.IsNotNull(requestedItem);+ CompletionItem completionItem = await provider.ResolveCompletionItemAsync(editor.GetModel(), requestedItem);++ if (completionItem != null)+ {+ return JsonConvert.SerializeObject(completionItem);+ }+ }++ return string.Empty;+ });++ // link:registerCompletionItemProvider.ts:registerCompletionItemProvider+ return editor.InvokeScriptAsync("registerCompletionItemProvider", new object[] { languageId, provider.TriggerCharacters });+ }++ return Task.CompletedTask;+ }++ public Task RegisterHoverProviderAsync(string languageId, HoverProvider provider)+ {+ if (_editor.TryGetTarget(out CodeEditor? 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) =>+ {+ Debug.WriteLine($"Hover provider.......... {args != null}");+ if (args != null && args.Length >= 1)+ {+ Hover hover = await provider.ProvideHover(editor.GetModel(), JsonConvert.DeserializeObject<Position>(args[0])!);++ if (hover != null)+ {+ return JsonConvert.SerializeObject(hover);+ }+ }++ return string.Empty;+ });++ // link:otherScriptsToBeOrganized.ts:registerHoverProvider+ return editor.InvokeScriptAsync("registerHoverProvider", languageId);+ }++ return Task.CompletedTask;+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/MarkerSeverity.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/MarkerSeverity.csnew file mode 100644index 000000000..b0cbdc55d--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/MarkerSeverity.cs@@ -0,0 +1,9 @@+namespace DevToys.MonacoEditor.Monaco;++public enum MarkerSeverity+{+ Hint = 1,+ Info = 2,+ Warning = 4,+ Error = 8+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/MarkerTag.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/MarkerTag.csnew file mode 100644index 000000000..4756d4c76--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/MarkerTag.cs@@ -0,0 +1,7 @@+namespace DevToys.MonacoEditor.Monaco;++public enum MarkerTag+{+ Unnecessary = 1,+ Deprecated = 2+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/ModelHelper.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/ModelHelper.csnew file mode 100644index 000000000..40e7fe0d6--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/ModelHelper.cs@@ -0,0 +1,396 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco.Editor;++/// <summary>+/// Helper to access IModel interface methods off of CodeEditor 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<CodeEditor> _editor;++ public ModelHelper(CodeEditor editor)+ {+ _editor = new WeakReference<CodeEditor>(editor);+ }++ public string Id => throw new NotImplementedException();++ public Uri Uri => throw new NotImplementedException();++ public Task DetectIndentationAsync(bool defaultInsertSpaces, bool defaultTabSize)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.InvokeScriptAsync("editorContext.model.detectIndentationAsync", new object[] { defaultInsertSpaces, defaultTabSize });+ }++ return Task.CompletedTask;+ }++ public Task<IEnumerable<FindMatch>?> FindMatchesAsync(string searchString, bool searchOnlyEditableRange, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches)+ {+ // Default limit results: https://github.com/microsoft/vscode/blob/b2d0292a20c4a012005c94975019a5b572ce6a63/src/vs/editor/common/model/textModel.ts#L117+ return FindMatchesAsync(searchString, searchOnlyEditableRange, isRegex, matchCase, wordSeparators, captureMatches, 999);+ }++ public Task<IEnumerable<FindMatch>?> FindMatchesAsync(string searchString, IRange searchScope, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches)+ {+ // Default limit results: https://github.com/microsoft/vscode/blob/b2d0292a20c4a012005c94975019a5b572ce6a63/src/vs/editor/common/model/textModel.ts#L117+ return FindMatchesAsync(searchString, searchScope, isRegex, matchCase, wordSeparators, captureMatches, 999);+ }++ public Task<IEnumerable<FindMatch>?> FindMatchesAsync(string searchString, bool searchOnlyEditableRange, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches, double limitResultCount)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.InvokeScriptAsync<IEnumerable<FindMatch>>("editorContext.model.findMatches", new object[] { searchString, searchOnlyEditableRange, isRegex, matchCase, wordSeparators, captureMatches, limitResultCount });+ }++ return Task.FromResult<IEnumerable<FindMatch>?>(null);+ }++ public Task<IEnumerable<FindMatch>?> FindMatchesAsync(string searchString, IRange searchScope, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches, double limitResultCount)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.InvokeScriptAsync<IEnumerable<FindMatch>>("editorContext.model.findMatches", new object[] { searchString, searchScope, isRegex, matchCase, wordSeparators, captureMatches, limitResultCount });+ }++ return Task.FromResult<IEnumerable<FindMatch>?>(null);+ }++ public Task<FindMatch?> FindNextMatchAsync(string searchString, IPosition searchStart, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.InvokeScriptAsync<FindMatch>("editorContext.model.findNextMatch", new object[] { searchString, searchString, isRegex, matchCase, wordSeparators, captureMatches });+ }++ return Task.FromResult<FindMatch?>(null);+ }++ public Task<FindMatch?> FindPreviousMatchAsync(string searchString, IPosition searchStart, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.InvokeScriptAsync<FindMatch>("editorContext.model.findPreviousMatch", new object[] { searchString, searchString, isRegex, matchCase, wordSeparators, captureMatches });+ }++ return Task.FromResult<FindMatch?>(null);+ }++ public Task<uint> GetAlternativeVersionIdAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<uint>("editorContext.model.getAlternativeVersionId();");+ }++ return Task.FromResult<uint>(0);+ }++ public Task<string?> GetEOLAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<string>("editorContext.model.getEOL();");+ }++ return Task.FromResult<string?>(null);+ }++ public Task<Range?> GetFullModelRangeAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<Range>("editorContext.model.getFullModelRange();");+ }++ return Task.FromResult<Range?>(null);+ }++ public Task<string?> GetLineContentAsync(uint lineNumber)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<string>("editorContext.model.getLineContent(" + lineNumber + ");");+ }++ return Task.FromResult<string?>(null);+ }++ public Task<uint> GetLineCountAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<uint>("editorContext.model.getLineCount();");+ }++ return Task.FromResult<uint>(0);+ }++ public Task<uint> GetLineFirstNonWhitespaceColumnAsync(uint lineNumber)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<uint>("editorContext.model.getLineFirstNonWhitespaceColumn(" + lineNumber + ");");+ }++ return Task.FromResult<uint>(0);+ }++ public Task<uint> GetLineLastNonWhitespaceColumnAsync(uint lineNumber)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<uint>("editorContext.model.getLineLastNonWhitespaceColumn(" + lineNumber + ");");+ }++ return Task.FromResult<uint>(0);+ }++ public Task<uint> GetLineLengthAsync(uint lineNumber)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<uint>("editorContext.model.getLineLength(" + lineNumber + ");");+ }++ return Task.FromResult<uint>(0);+ }++ public Task<uint> GetLineMaxColumnAsync(uint lineNumber)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<uint>("editorContext.model.getLineMaxColumn(" + lineNumber + ");");+ }++ return Task.FromResult<uint>(0);+ }++ public Task<uint> GetLineMinColumnAsync(uint lineNumber)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<uint>("editorContext.model.getLineMinColumn(" + lineNumber + ");");+ }++ return Task.FromResult<uint>(0);+ }++ public Task<IEnumerable<string>?> GetLinesContentAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<IEnumerable<string>>("editorContext.model.getLinesContent();");+ }++ return Task.FromResult<IEnumerable<string>?>(null);+ }++ public Task<string?> GetModelIdAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<string>("editorContext.model.getModelId();");+ }++ return Task.FromResult<string?>(null);+ }++ public Task<uint> GetOffsetAtAsync(IPosition position)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<uint>("editorContext.model.getOffsetAt(" + JsonConvert.SerializeObject(position) + ");");+ }++ return Task.FromResult<uint>(0);+ }++ public Task<string?> GetOneIndentAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<string>("editorContext.model.getOneIndent();");+ }++ return Task.FromResult<string?>(null);+ }++ public Task<Position?> GetPositionAtAsync(uint offset)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<Position>("editorContext.model.getPositionAt(" + offset + ");");+ }++ return Task.FromResult<Position?>(null);+ }++ public Task<string?> GetValueAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<string>("editorContext.model.getValue();");+ }++ return Task.FromResult<string?>(null);+ }++ public Task<string?> GetValueAsync(EndOfLinePreference eol)+ {+ throw new NotImplementedException();+ }++ public Task<string?> GetValueAsync(EndOfLinePreference eol, bool preserveBOM)+ {+ throw new NotImplementedException();+ }++ public Task<string?> GetValueInRangeAsync(IRange range)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<string>("editorContext.model.getValueInRange(" + JsonConvert.SerializeObject(range) + ");");+ }++ return Task.FromResult<string?>(null);+ }++ public Task<string?> GetValueInRangeAsync(IRange range, EndOfLinePreference eol)+ {+ throw new NotImplementedException();+ }++ public Task<uint> GetValueLengthAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<uint>("editorContext.model.getValueLength();");+ }++ return Task.FromResult<uint>(0);+ }++ public Task<uint> GetValueLengthAsync(EndOfLinePreference eol)+ {+ throw new NotImplementedException();+ }++ public Task<uint> GetValueLengthAsync(EndOfLinePreference eol, bool preserveBOM)+ {+ throw new NotImplementedException();+ }++ public Task<uint> GetValueLengthInRangeAsync(IRange range)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<uint>("editorContext.model.getValueLengthInRange(" + JsonConvert.SerializeObject(range) + ");");+ }++ return Task.FromResult<uint>(0);+ }++ public Task<uint> GetVersionIdAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<uint>("editorContext.model.getVersionId();");+ }++ return Task.FromResult<uint>(0);+ }++ // TODO: Need to investigate why with .NET Native the InterfaceToClassConverter isn't working anymore?+ public Task<WordAtPosition?> GetWordAtPositionAsync(IPosition position)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<WordAtPosition>("editorContext.model.getWordAtPosition(" + JsonConvert.SerializeObject(position) + ");");+ }++ return Task.FromResult<WordAtPosition?>(null);+ }++ public Task<WordAtPosition?> GetWordUntilPositionAsync(IPosition position)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<WordAtPosition>("editorContext.model.getWordUntilPosition(" + JsonConvert.SerializeObject(position) + ");");+ }++ return Task.FromResult<WordAtPosition?>(null);+ }++ public Task<Position?> ModifyPositionAsync(IPosition position, int number)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<Position>("editorContext.model.modifyPosition(" + JsonConvert.SerializeObject(position) + ", " + number + ");");+ }++ return Task.FromResult<Position?>(null);+ }++ public Task<string?> NormalizeIndentationAsync(string str)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<string>("editorContext.model.normalizeIndentations(JSON.parse(" + JsonConvert.ToString(str) + "));");+ }++ return Task.FromResult<string?>(null);+ }++ public Task PushStackElementAsync()+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync("editorContext.model.pushStackElement();");+ }++ return Task.CompletedTask;+ }++ public Task SetEOLAsync(EndOfLineSequence eol)+ {+ throw new NotImplementedException();+ }++ public Task SetValue(string newValue)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync("editorContext.model.setValue(JSON.parse(" + JsonConvert.ToString(newValue) + "));");+ }++ return Task.CompletedTask;+ }++ public Task<Position?> ValidatePositionAsync(IPosition position)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<Position>("editorContext.model.validatePosition(" + JsonConvert.SerializeObject(position) + ");");+ }++ return Task.FromResult<Position?>(null);+ }++ public Task<Range?> ValidateRangeAsync(IRange range)+ {+ if (_editor.TryGetTarget(out CodeEditor? editor))+ {+ return editor.SendScriptAsync<Range>("editorContext.model.validateRange(" + JsonConvert.SerializeObject(range) + ");");+ }++ return Task.FromResult<Range?>(null);+ }+}+diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Position.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Position.csnew file mode 100644index 000000000..1d818e466--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Position.cs@@ -0,0 +1,113 @@+using Newtonsoft.Json;+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 position)+ {+ return LineNumber == position.LineNumber && Column == position.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/app/dev/DevToys.MonacoEditor/Monaco/Range.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Range.csnew file mode 100644index 000000000..180f06165--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Range.cs@@ -0,0 +1,138 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco;++/// <summary>+/// A range in the editor. (startLineNumber,startColumn) is <= (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() // For Serialization+ {+ }++ 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 bool ContainsPosition(IPosition position)+ {+ if (StartLineNumber == position.LineNumber && position.LineNumber == EndLineNumber)+ {+ return StartColumn <= position.Column && position.Column <= EndColumn;+ }+ else if (StartLineNumber == position.LineNumber)+ {+ return StartColumn <= position.Column;+ }+ else if (EndLineNumber == position.LineNumber)+ {+ return position.Column <= EndColumn;+ }++ return StartLineNumber < position.LineNumber && EndLineNumber > position.LineNumber;+ }++ public bool ContainsRange(IRange range)+ {+ bool isStart = StartLineNumber <= range.StartLineNumber;+ bool isStartColumn = (StartLineNumber == range.StartLineNumber) ? StartColumn <= range.StartColumn : true;+ bool isEnd = EndLineNumber >= range.EndLineNumber;+ bool isEndColumn = (EndLineNumber == range.EndLineNumber) ? EndColumn >= range.EndColumn : true;++ return isStart && isStartColumn && isEnd && isEndColumn;+ }++ 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/app/dev/DevToys.MonacoEditor/Monaco/Selection.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Selection.csnew file mode 100644index 000000000..d143bd44d--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Selection.cs@@ -0,0 +1,100 @@+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/app/dev/DevToys.MonacoEditor/Monaco/SelectionDirection.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/SelectionDirection.csnew file mode 100644index 000000000..0dc7d029f--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/SelectionDirection.cs@@ -0,0 +1,7 @@+namespace DevToys.MonacoEditor.Monaco;++public enum SelectionDirection+{+ LTR,+ RTL+}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Uri.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Uri.csnew file mode 100644index 000000000..391c41870--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Uri.cs@@ -0,0 +1,48 @@+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 : UriComponents+{+ /// <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/app/dev/DevToys.MonacoEditor/Monaco/UriComponents.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/UriComponents.csnew file mode 100644index 000000000..7b048a530--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/UriComponents.cs@@ -0,0 +1,17 @@+using Newtonsoft.Json;++namespace DevToys.MonacoEditor.Monaco;++public interface UriComponents+{+ [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/app/dev/DevToys.MonacoEditor/Themes/generic.xaml b/src/app/dev/DevToys.MonacoEditor/Themes/generic.xamlnew file mode 100644index 000000000..38020026a--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/Themes/generic.xaml@@ -0,0 +1,80 @@+<ResourceDictionary+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:monaco="using:DevToys.MonacoEditor"+ xmlns:muxc="using:Microsoft.UI.Xaml.Controls"+ xmlns:converters="using:DevToys.UI.Framework.Converters">++ <converters:NegateBooleanConverter x:Key="NegateBooleanConverter"/>++ <Style TargetType="monaco:CodeEditor" >+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="monaco:CodeEditor">+ <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">+ <Grid>+ <Button Content="Hello world"/>+ <monaco:CodeEditorPresenter+ x:Name="View"+ Margin="{TemplateBinding Padding}"+ HorizontalAlignment="Stretch"+ VerticalAlignment="Stretch"/>+ </Grid>+ </Border>+ <muxc:ProgressRing+ HorizontalAlignment="Center"+ VerticalAlignment="Center"+ Height="48"+ Width="48"+ IsActive="{Binding IsEditorLoaded, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource NegateBooleanConverter}}" />+ </Grid>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++</ResourceDictionary>diff --git a/src/app/dev/DevToys.MonacoEditor/WebInterop/Logger/DebugLogger.Wasm.cs b/src/app/dev/DevToys.MonacoEditor/WebInterop/Logger/DebugLogger.Wasm.csnew file mode 100644index 000000000..b6bcfd287--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/WebInterop/Logger/DebugLogger.Wasm.cs@@ -0,0 +1,28 @@+#if __WASM__++using Uno;+using Uno.Foundation.Interop;++namespace DevToys.MonacoEditor.WebInterop;++internal partial class DebugLogger : IJSObject+{+ private JSObjectHandle? _handle;++ /// <inheritdoc />+ public JSObjectHandle Handle+ {+ get+ {+ return _handle ??= JSObjectHandle.Create(this);+ }+ }++ [Preserve]+ public void log(string message)+ {+ Log(message);+ }+}++#endifdiff --git a/src/app/dev/DevToys.MonacoEditor/WebInterop/Logger/DebugLogger.cs b/src/app/dev/DevToys.MonacoEditor/WebInterop/Logger/DebugLogger.csnew file mode 100644index 000000000..3637121f7--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/WebInterop/Logger/DebugLogger.cs@@ -0,0 +1,22 @@+using Microsoft.Extensions.Logging;+using Uno.Extensions;+using Windows.Foundation.Metadata;++namespace DevToys.MonacoEditor.WebInterop;++[AllowForWeb]+internal sealed partial class DebugLogger+{+ private readonly ILogger? _debugLogger;++ public DebugLogger()+ {+ ILogger logger = this.Log();+ _debugLogger = logger.IsEnabled(LogLevel.Debug) ? logger : null;+ }++ public void Log(string message)+ {+ _debugLogger?.LogDebug(message);+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/WebInterop/Parent/IParentAccessorAcceptor.cs b/src/app/dev/DevToys.MonacoEditor/WebInterop/Parent/IParentAccessorAcceptor.csnew file mode 100644index 000000000..075a59358--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/WebInterop/Parent/IParentAccessorAcceptor.cs@@ -0,0 +1,13 @@+namespace DevToys.MonacoEditor.WebInterop.Parent;++//// TODO: Find better approach than this.+/// <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/app/dev/DevToys.MonacoEditor/WebInterop/Parent/ParentAccessor.cs b/src/app/dev/DevToys.MonacoEditor/WebInterop/Parent/ParentAccessor.csnew file mode 100644index 000000000..7e0591b0b--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/WebInterop/Parent/ParentAccessor.cs@@ -0,0 +1,288 @@+using System.Reflection;+using System.Runtime.InteropServices.WindowsRuntime;+using Newtonsoft.Json;+using Windows.Foundation;+using Windows.Foundation.Metadata;++namespace DevToys.MonacoEditor.WebInterop.Parent;++/// <summary>+/// Class to help in accessing .NET values from JavaScript.+/// Not Thread Safe.+/// </summary>+[AllowForWeb]+internal sealed partial class ParentAccessor : IDisposable+{+ private readonly WeakReference<IParentAccessorAcceptor> _parent;+ private readonly Type _typeinfo;+ private readonly Dictionary<string, Action<string[]>> _actionParameters;+ private readonly Dictionary<string, Action> _actions = new();+ private readonly Dictionary<string, Func<string[], Task<string>>> _events = new();++ private List<Assembly> Assemblies { get; } = new List<Assembly>();++ /// <summary>+ /// Constructs a new reflective parent Accessor for the provided object.+ /// </summary>+ /// <param name="parent">Object to provide Property Access.</param>+ internal ParentAccessor(IParentAccessorAcceptor parent)+ {+ this._parent = new WeakReference<IParentAccessorAcceptor>(parent);+ _typeinfo = parent.GetType();+ _actionParameters = new Dictionary<string, Action<string[]>>();++ PartialCtor();+ }++ partial void PartialCtor();++ public void Dispose()+ {+ _actions.Clear();+ _events.Clear();+ }++ /// <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)+ {+ _actions[name] = action;+ }++ internal void RegisterActionWithParameters(string name, Action<string[]> action)+ {+ _actionParameters[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)+ {+ _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 Task<string> CallEvent(string name, [ReadOnlyArray] string[] parameters)+ {+ Debug.WriteLine($"Event {name}");+ if (_events.ContainsKey(name))+ {+ Debug.WriteLine($"Parameters: {parameters != null} - {parameters?.Length.ToString() ?? "N/A"}");+ parameters ??= Array.Empty<string>();+ return _events[name].Invoke(parameters);+ }++ return Task.FromResult(string.Empty);+ }++ /// <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.ContainsKey(name))+ {+ _actions[name]?.Invoke();+ return true;+ }++ return false;+ }++ /// <summary>+ /// Calls an Action registered before with <see cref="RegisterActionWithParameters(string, Action{string[]})"/>.+ /// </summary>+ /// <param name="name">String Key.</param>+ /// <param name="parameters">Parameters to be passed to Action.</param>+ /// <returns>True if method was found in registration.</returns>+ public bool CallActionWithParameters(string name, [ReadOnlyArray] string[] parameters)+ {+ if (_actionParameters.ContainsKey(name))+ {+ _actionParameters[name]?.Invoke(parameters);+ 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? target) && target is not null)+ {+ PropertyInfo? propinfo = _typeinfo.GetProperty(name);+ Guard.IsNotNull(propinfo);+ return propinfo.GetValue(target);+ }++ return null;+ }++ public string GetJsonValue(string name)+ {+ if (_parent.TryGetTarget(out IParentAccessorAcceptor? target) && target is not null)+ {+ PropertyInfo? propinfo = _typeinfo.GetProperty(name);+ Guard.IsNotNull(propinfo);+ object? obj = propinfo.GetValue(target);++ if (obj is not null)+ {+ string json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings()+ {+ NullValueHandling = NullValueHandling.Ignore+ });++ // Serialize the json to sanitize it and pass it as a string to the web page.+ return JsonConvert.SerializeObject(json);+ }+ }++ 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? target) && target is not null)+ {+ // TODO: Support params for multi-level digging?+ PropertyInfo? propinfo = _typeinfo.GetProperty(name);+ Guard.IsNotNull(propinfo);+ object? prop = propinfo.GetValue(target);+ if (prop is not null)+ {+ PropertyInfo? childinfo = prop.GetType().GetProperty(child);+ Guard.IsNotNull(childinfo);+ 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? target) && target is not null)+ {+ PropertyInfo? propinfo = _typeinfo.GetProperty(name); // TODO: Cache these?+ Guard.IsNotNull(propinfo);+ target.IsSettingValue = true;+ propinfo.SetValue(target, value);+ target.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 SetValueWithType(string name, string value, string type)+ {+ if (_parent.TryGetTarget(out IParentAccessorAcceptor? target) && target is not null)+ {+ PropertyInfo? propinfo = _typeinfo.GetProperty(name);+ Guard.IsNotNull(propinfo);+ Type typeobj = LookForTypeByName(type);++ // TODO: this allocates a lot of string. Check if we can do better.+ string json = Desanitize(value);+ json = json.Replace(@"\\", @"\");+ json = json.Trim('"', ' ');+ json = json.Replace(@"\r\n", Environment.NewLine);+ json = json.Replace(@"\t", "\t");++ object? obj = JsonConvert.DeserializeObject(json, typeobj);++ target.IsSettingValue = true;+ propinfo.SetValue(target, obj);+ target.IsSettingValue = false;+ }+ }++ private Type LookForTypeByName(string name)+ {+ // First search locally+ var result = Type.GetType(name);++ if (result is not null)+ {+ return result;+ }++ // Search in Other Assemblies+ foreach (Assembly assembly in Assemblies)+ {+ foreach (Type typeInfo in assembly.ExportedTypes)+ {+ if (typeInfo.Name == name)+ {+ return typeInfo;+ }+ }+ }++ throw new Exception($"Unable to solve the type '{name}'");+ }++ private static string Desanitize(string parameter)+ {+ if (parameter is null)+ {+ return string.Empty;+ }++ // TODO: this allocates a lot of string. Check if we can do better.+ string replacements = @"&\""'{}:,%";++ for (int i = 0; i < replacements.Length; i++)+ {+ parameter = parameter.Replace($"%{(int)replacements[i]}", (char)replacements[i] + "");+ }++ parameter = parameter.Replace(@"\\""", @"""");++ return parameter;+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/WebInterop/Parent/ParentAccessor.wasm.cs b/src/app/dev/DevToys.MonacoEditor/WebInterop/Parent/ParentAccessor.wasm.csnew file mode 100644index 000000000..40e1f6344--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/WebInterop/Parent/ParentAccessor.wasm.cs@@ -0,0 +1,198 @@+#if __WASM__++using Uno;+using Uno.Extensions.Specialized;+using Uno.Foundation;+using Uno.Foundation.Interop;++namespace DevToys.MonacoEditor.WebInterop.Parent;++internal partial class ParentAccessor : IJSObject+{+ private JSObjectHandle? _handle;+ private bool _initialized;++ partial void PartialCtor()+ {+ // TODO: Remove???+ //getValue(null!);+ //setValue(null!, null!);+ //setValueWithType(null!, null!, null!);+ //getJsonValue(null!, null!);+ //callAction(null!);+ //callActionWithParameters(null!, null!, null!);+ //callEvent(null!, null!, null!, null!);+ //close();++ _initialized = true;+ }++ /// <inheritdoc />+ public JSObjectHandle? Handle+ {+ get+ {+ return _initialized ? (_handle ??= JSObjectHandle.Create(this)) : null;+ }+ }++ [Preserve]+ public object? getValue(string name)+ {+ if (Handle is null)+ {+ return null;+ }++ object? obj = GetValue(name);+ return obj;+ }++ [Preserve]+ public void setValue(string name, string value)+ {+ if (Handle is null)+ {+ return;+ }++ // TODO: this allocates a lot of string. Check if we can do better.+ string json = Desanitize(value);+ json = json.Replace(@"\\", @"\");+ json = json.Trim('"');+ json = json.Replace(@"\r\n", Environment.NewLine);+ json = json.Replace(@"\t", "\t");++ SetValue(name, json);+ }++ [Preserve]+ public void setValueWithType(string name, string value, string type)+ {+ if (Handle is null)+ {+ return;+ }++ SetValueWithType(name, value, type);+ }++ [Preserve]+ public void getJsonValue(string name, string returnId)+ {+ if (Handle is null)+ {+ return;+ }++ string json = GetJsonValue(name);++ try+ {+ string callbackMethod = $"returnValueCallback('{returnId}', {json});";+ string result = WebAssemblyRuntime.InvokeJS(callbackMethod);+ }+ catch (Exception e)+ {+ Console.WriteLine($"Result Callback - error {e.Message}");+ }+ }++ [Preserve]+ public bool callAction(string name)+ {+ if (Handle is null)+ {+ return false;+ }++ bool result = CallAction(name);++ return result;+ }++ [Preserve]+ public bool callActionWithParameters(string name, string parameter1, string parameter2)+ {+ if (Handle is null)+ {+ return false;+ }++ string[] parameters+ = new[]+ {+ Desanitize(parameter1),+ Desanitize(parameter2)+ }+ .Where(x => x is not null)+ .ToArray();++ bool result = CallActionWithParameters(name, parameters);++ return result;+ }++ [Preserve]+ public async void callEvent(string name, string promiseId, string parameter1, string parameter2)+ {+ if (Handle is null)+ {+ return;+ }++ string[] parameters+ = new[]+ {+ Desanitize(parameter1),+ Desanitize(parameter2)+ }+ .Where(x => x is not null)+ .ToArray();++ string resultString = await CallEvent(name, parameters);++ try+ {+ string sanitized = Santize(resultString);++ string callbackMethod = $"asyncCallback('{promiseId}','{sanitized}');";++ string result = WebAssemblyRuntime.InvokeJS(callbackMethod);+ }+ catch (Exception e)+ {+ Console.WriteLine($"Event Callback - error {e.Message}");+ }++ return;+ }++ [Preserve]+ public void close()+ {+ if (Handle is not null)+ {+ Dispose();+ }+ }++ internal static string Santize(string jsonString)+ {+ if (jsonString is null)+ {+ return string.Empty;+ }++ // TODO: this allocates a lot of string. Check if we can do better.+ string replacements = @"%&\""'{}:,";+ for (int i = 0; i < replacements.Length; i++)+ {+ jsonString = jsonString.Replace(replacements[i] + "", "%" + (int)replacements[i]);+ }++ return jsonString;+ }+}++#endifdiff --git a/src/app/dev/DevToys.MonacoEditor/WebInterop/Theme/ThemeListener.cs b/src/app/dev/DevToys.MonacoEditor/WebInterop/Theme/ThemeListener.csnew file mode 100644index 000000000..1ee5d44c3--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/WebInterop/Theme/ThemeListener.cs@@ -0,0 +1,150 @@+using Windows.Foundation.Metadata;+using Windows.UI.ViewManagement;+using Newtonsoft.Json;+using Windows.UI;++#if WINDOWS_UWP+using Windows.UI.Xaml;+using Windows.UI.Xaml.Media;+using DispatcherQueue = Windows.UI.Core.CoreDispatcher;+#else+using Microsoft.UI.Dispatching;+using Microsoft.UI.Xaml;+using Microsoft.UI.Xaml.Media;+#endif++namespace DevToys.MonacoEditor.WebInterop.Theme;++internal 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]+internal sealed partial class ThemeListener // This is a copy of the Toolkit ThemeListener, for some reason if we try and use it directly it's not read by the WebView+{+ private readonly DispatcherQueue _dispatcher;++ public string CurrentThemeName => JsonConvert.SerializeObject(CurrentTheme.ToString()); // For Web Retrieval++ public ApplicationTheme CurrentTheme { get; set; }++ public bool IsHighContrast { get; set; }++ public string AccentColorHtmlHex { get; private set; }++ public event ThemeChangedEvent? ThemeChanged;++ private readonly AccessibilitySettings _accessible = new();+ private readonly UISettings _settings = new();++ internal ThemeListener(DispatcherQueue queue)+ {+ Guard.IsNotNull(queue);+ _dispatcher = queue;++ AccentColorHtmlHex = ToHtmlHex(((SolidColorBrush)Application.Current.Resources["TextControlSelectionHighlightColor"]).Color);+ CurrentTheme = Application.Current.RequestedTheme;+#if !__WASM__+ IsHighContrast = _accessible.HighContrast;+#endif++ // TODO+ //_accessible.HighContrastChanged += _accessible_HighContrastChanged;+ //_settings.ColorValuesChanged += _settings_ColorValuesChanged;++ //// Fallback in case either of the above fail, we'll check when we get activated next.+ //Window.Current.CoreWindow.Activated += CoreWindow_Activated;++ PartialCtor();+ UpdateProperties();+ }++ partial void PartialCtor();++ ~ThemeListener()+ {+ // TODO+ //_accessible.HighContrastChanged -= _accessible_HighContrastChanged;+ //_settings.ColorValuesChanged -= _settings_ColorValuesChanged;++ //Window.Current.CoreWindow.Activated -= CoreWindow_Activated;+ }++ // TODO+ // private void _accessible_HighContrastChanged(AccessibilitySettings sender, object args)+ // {+ //#if DEBUG+ // Debug.WriteLine("HighContrast Changed");+ //#endif++ // UpdateProperties();+ // }++ // // Note: This can get called multiple times during HighContrast switch, do we care?+ // private void _settings_ColorValuesChanged(UISettings sender, object args)+ // {+ // // Getting called off thread, so we need to dispatch to request value.+ // _dispatcher.RunOnUIThreadAsync(() =>+ // {+ // // TODO: This doesn't stop the multiple calls if we're in our faked 'White' HighContrast Mode below.+ // if (CurrentTheme != Application.Current.RequestedTheme ||+ // IsHighContrast != _accessible.HighContrast)+ // {+ //#if DEBUG+ // Debug.WriteLine("Color Values Changed");+ //#endif++ // UpdateProperties();+ // }+ // }).Forget();+ // }++ private bool IsSystemHighContrast() =>+ ApiInformation.IsPropertyPresent("Windows.UI.ViewManagement.HighContrast", "HighContrast")+ && _accessible.HighContrast;++ // TODO+ // private void CoreWindow_Activated(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.WindowActivatedEventArgs args)+ // {+ // if (CurrentTheme != Application.Current.RequestedTheme ||+ // IsHighContrast != IsSystemHighContrast())+ // {+ //#if DEBUG+ // Debug.WriteLine("CoreWindow Activated Changed");+ //#endif++ // UpdateProperties();+ // }+ // }++ /// <summary>+ /// Set our current properties and fire a change notification.+ /// </summary>+ private void UpdateProperties()+ {+ // TODO: Not sure if HighContrastScheme names are localized?+ if (IsSystemHighContrast() && _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 = Application.Current.RequestedTheme;+ }++ AccentColorHtmlHex = ToHtmlHex(((SolidColorBrush)Application.Current.Resources["TextControlSelectionHighlightColor"]).Color);++ ThemeChanged?.Invoke(this);+ }++ public static string ToHtmlHex(Color color)+ {+ return JsonConvert.SerializeObject($"#{color.R:X2}{color.G:X2}{color.B:X2}{color.A:X2}");+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/WebInterop/Theme/ThemeListener.wasm.cs b/src/app/dev/DevToys.MonacoEditor/WebInterop/Theme/ThemeListener.wasm.csnew file mode 100644index 000000000..08564fd8f--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/WebInterop/Theme/ThemeListener.wasm.cs@@ -0,0 +1,72 @@+#if __WASM__++using DevToys.MonacoEditor.WebInterop.Parent;+using Newtonsoft.Json;+using Uno;+using Uno.Foundation;+using Uno.Foundation.Interop;++namespace DevToys.MonacoEditor.WebInterop.Theme;++internal partial class ThemeListener : IJSObject+{+ partial void PartialCtor()+ {+ Handle = JSObjectHandle.Create(this);++ // TODO: Remove?+ // getCurrentThemeName(null);+ // getIsHighContrast(null);+ }++ public JSObjectHandle Handle { get; private set; }++ [Preserve]+ public void getAccentColorHtmlHex(string returnId)+ {+ getJsonValue(returnId, AccentColorHtmlHex);+ }++ [Preserve]+ public void getCurrentThemeName(string returnId)+ {+ getJsonValue(returnId, CurrentThemeName);+ }++ [Preserve]+ public void getIsHighContrast(string returnId)+ {+ getJsonValue(returnId, IsHighContrast);+ }++ private void getJsonValue<T>(string returnId, T obj)+ {+ if (Handle == null)+ {+ return;+ }++ string returnJson = "";+ if (obj != null)+ {+ returnJson = JsonConvert.SerializeObject(obj, new JsonSerializerSettings()+ {+ NullValueHandling = NullValueHandling.Ignore+ });+ // System.Diagnostics.Debug.WriteLine($"Json Object - {returnJson}");+ }+ returnJson = ParentAccessor.Santize(returnJson);++ try+ {+ string callbackMethod = $"returnValueCallback('{returnId}','{returnJson}');";+ string result = WebAssemblyRuntime.InvokeJS(callbackMethod);+ }+ catch (Exception e)+ {+ Console.WriteLine($"Result Callback - error {e.Message}");+ }+ }+}++#endifdiff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.DebugLogger.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.DebugLogger.tsnew file mode 100644index 000000000..4b492be5b--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.DebugLogger.ts@@ -0,0 +1,5 @@+//namespace DevToys.MonacoEditor.Monaco.Helpers {+ interface DebugLogger {+ log(message: string);+ }+//}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.KeyboardListener.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.KeyboardListener.tsnew file mode 100644index 000000000..beea49aec--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.KeyboardListener.ts@@ -0,0 +1,5 @@+//namespace DevToys.MonacoEditor.Monaco.Helpers {+interface KeyboardListener {+ keyDown(keycode: number, ctrl: boolean, shift: boolean, alt: boolean, meta: boolean): boolean;+}+//}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.ParentAccessor.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.ParentAccessor.tsnew file mode 100644index 000000000..7959afa21--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/Monaco.Helpers.ParentAccessor.ts@@ -0,0 +1,17 @@+//namespace DevToys.MonacoEditor.Monaco.Helpers {+interface ParentAccessor {+ callAction(name: string): boolean;+ callActionWithParameters(name: string, parameters: string[]): boolean;+ callEvent(name: string, parameters: string[]): Promise<string>+ close();+ getChildValue(name: string, child: string): Promise<any>;+ getJsonValue(name: string): Promise<string>;+ getValue(name: string): Promise<any>;+ setValue(name: string, value: any): Promise<undefined>;+ setValueWithType(name: string, value: string, type: string): Promise<undefined>;+ callActionWithParameters(name: string, parameter1: string, parameter2: string): boolean;+ callEvent(name: string, callbackMethod: string, parameter1: string, parameter2: string);+ getJsonValue(name: string, returnId: string);+}++//}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/editorContext.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/editorContext.tsnew file mode 100644index 000000000..b97722c40--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/editorContext.ts@@ -0,0 +1,43 @@+///<reference path="../monaco-editor/monaco.d.ts" />++class EditorContext {+ static _editors: Map<any, EditorContext> = new Map<any, EditorContext>();++ public static registerEditorForElement(element: any, editor: monaco.editor.IEditor): EditorContext {+ var value = EditorContext.getEditorForElement(element);+ value.editor = editor;+ return value;+ }++ public static getEditorForElement(element: any): EditorContext {+ var context = EditorContext._editors.get(element);++ if (!context) {+ context = new EditorContext();+ context.htmlElement = element;+ EditorContext._editors.set(element, context);+ }++ return context;+ }++ constructor() {+ this.modifingSelection = false;+ this.contexts = {};+ this.decorations = [];+ }++ public Accessor: ParentAccessor;+ public Keyboard: KeyboardListener;+ public Theme: ThemeAccessor;+ public Debug: DebugLogger;++ public editor: monaco.editor.IEditor;+ public standaloneEditor: monaco.editor.IStandaloneCodeEditor;+ public diffEditor: monaco.editor.IStandaloneDiffEditor;+ public model: monaco.editor.ITextModel;+ public contexts: { [index: string]: monaco.editor.IContextKey<any> };+ public decorations: string[];+ public modifingSelection: boolean; // Supress updates to selection when making edits.+ public htmlElement: any;+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/monacoInitializer.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/monacoInitializer.tsnew file mode 100644index 000000000..b5f0e4c0c--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/monacoInitializer.ts@@ -0,0 +1,179 @@+///<reference path="../monaco-editor/monaco.d.ts" />++const createMonacoEditor = (basePath: string, element: any) => {+ let editorContext = EditorContext.getEditorForElement(element);+ let debug = editorContext.Debug;+ debug.log("Create dynamic style element");++ var head = document.head || document.getElementsByTagName('head')[0];+ var style = document.createElement('style');+ style.id = 'dynamic';+ head.appendChild(style);++ debug.log("Starting Monaco Load");++ (<any>window).require.config({ paths: { 'vs': `${basePath}/monaco-editor/min/vs` } });+ (<any>window).require(['vs/editor/editor.main'], async function () {+ await initializeMonacoEditorAsync(editorContext);+ });+}++const initializeMonacoEditorAsync = async (editorContext: EditorContext) => {+ let debug = editorContext.Debug;+ let accessor = editorContext.Accessor;++ debug.log("Determining if a standard editor or diff view editor should be created.");+ let isDiffView = await getParentValue(editorContext, "IsDiffViewMode");+ isDiffView = (isDiffView === "true" || isDiffView == true);++ if (isDiffView) {+ await initializeDiffModeMonacoEditorAsync(editorContext);+ }+ else {+ await initializeStandardMonacoEditorAsync(editorContext);+ }++ //// Set theme+ debug.log("Getting accessor theme value");+ let theme = await getParentJsonValue(editorContext, "ActualTheme");+ switch (theme) {+ case "0":+ theme = "Default";+ break;+ case "1":+ theme = "Light";+ break;+ case "2":+ theme = "Dark";+ break;+ default:+ debug.log("Unknown theme");+ }++ debug.log("Current theme value - " + theme);+ if (theme == "Default")+ {+ debug.log("Loading default theme");+ theme = await getThemeCurrentThemeName(editorContext);+ }++ debug.log("Changing theme");+ setTheme(editorContext, await getAccentColorHtmlHex(editorContext));+ changeTheme(editorContext, theme, await getThemeIsHighContrast(editorContext));++ // Update Monaco Size when we receive a window resize event+ debug.log("Listen for resize events on the window and resize the editor");+ window.addEventListener(+ "resize",+ () => {+ editorContext.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");+ accessor.callAction("Loaded");++ debug.log("Ending Monaco Load");+}++const initializeStandardMonacoEditorAsync = async (editorContext: EditorContext) => {+ let debug = editorContext.Debug;+ let accessor = editorContext.Accessor;+ debug.log("Grabbing Monaco Options");++ // link:CodeEditor.Options+ let opt = await getOptions(editorContext);++ debug.log("Getting Parent Text value");++ // link:CodeEditor.Text+ opt["value"] = await getParentValue(editorContext, "Text");++ debug.log("Creating Editor");+ const editor = monaco.editor.create(editorContext.htmlElement, opt);+ EditorContext.registerEditorForElement(editorContext.htmlElement, editor);+ editorContext.standaloneEditor = editor;++ debug.log("Getting & Configuring Editor model");+ let model = editor.getModel();+ model.updateOptions({+ bracketColorizationOptions: { enabled: true }+ });+ editorContext.model = model;++ // Listen for Content Changes+ debug.log("Listening for changes in the editor model - " + (!model));+ model.onDidChangeContent(+ async (event) => {+ // link:CodeEditor.Text+ await accessor.setValue("Text", stringifyForMarshalling(model.getValue()));+ });++ // Listen for Selection Changes+ debug.log("Listening for changes in the editor selection");+ editor.onDidChangeCursorSelection(+ async (event) => {+ if (!editorContext.modifingSelection) {+ // link:CodeEditor.SelectedText+ await accessor.setValue("SelectedText", stringifyForMarshalling(model.getValueInRange(event.selection)));++ // link:CodeEditor.SelectedRange of type Selection+ await accessor.setValueWithType("SelectedRange", stringifyForMarshalling(JSON.stringify(event.selection)), "Selection");+ }+ });++ // Listen for focus changes.+ debug.log("Listen for focus events");+ editorContext.standaloneEditor.onDidFocusEditorWidget(+ async (event) => {+ accessor.callAction("GotFocus");+ });+ editorContext.standaloneEditor.onDidBlurEditorWidget(+ async (event) => {+ accessor.callAction("LostFocus");+ });+}++const initializeDiffModeMonacoEditorAsync = async (editorContext: EditorContext) => {+ let debug = editorContext.Debug;+ let accessor = editorContext.Accessor;+ debug.log("Grabbing Monaco Options");++ // link:CodeEditor.DiffOptions+ let opt = await getDiffOptions(editorContext);++ debug.log("Creating Diff Editor");+ const editor = monaco.editor.createDiffEditor(editorContext.htmlElement, opt);+ EditorContext.registerEditorForElement(editorContext.htmlElement, editor);+ editorContext.diffEditor = editor;++ debug.log("Getting & Configuring Diff Editor model");+ let originalModel = monaco.editor.createModel("", "text/plain");+ let modifiedModel = monaco.editor.createModel("", "text/plain");+ editor.setModel({+ original: originalModel,+ modified: modifiedModel+ });++ // Listen for focus changes.+ debug.log("Listen for focus events");+ editorContext.diffEditor.getOriginalEditor().onDidFocusEditorWidget(+ async (event) => {+ accessor.callAction("GotFocus");+ });+ editorContext.diffEditor.getModifiedEditor().onDidFocusEditorWidget(+ async (event) => {+ accessor.callAction("GotFocus");+ });+ editorContext.diffEditor.getOriginalEditor().onDidBlurEditorWidget(+ async (event) => {+ accessor.callAction("LostFocus");+ });+ editorContext.diffEditor.getModifiedEditor().onDidBlurEditorWidget(+ async (event) => {+ accessor.callAction("LostFocus");+ });+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.tsnew file mode 100644index 000000000..d602b6abe--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.ts@@ -0,0 +1,230 @@+///<reference path="../monaco-editor/monaco.d.ts" />++const registerHoverProvider = function (editorContext: EditorContext, languageId: string) {+ return monaco.languages.registerHoverProvider(languageId, {+ provideHover: function (model, position) {+ return callParentEventAsync(editorContext, "HoverProvider" + languageId, [JSON.stringify(position)]).then(result => {+ if (result) {+ return JSON.parse(result);+ }+ });+ }+ });+};++const addAction = function (editorContext: EditorContext, action: monaco.editor.IActionDescriptor) {+ action.run = function (ed) {+ editorContext.Accessor.callAction("Action" + action.id)+ };++ if (editorContext.standaloneEditor != null) {+ editorContext.standaloneEditor.addAction(action);+ }+ else {+ editorContext.diffEditor.addAction(action);+ }+};++const addCommand = function (editorContext: EditorContext, keybindingStr, handlerName, context) {+ if (editorContext.standaloneEditor != null) {+ return editorContext.standaloneEditor.addCommand(parseInt(keybindingStr), function () {+ const objs = [];+ if (arguments) { // Use arguments as Monaco will pass each as it's own parameter, so we don't know how many that may be.+ for (let i = 1; i < arguments.length; i++) { // Skip first one as that's the sender?+ objs.push(JSON.stringify(arguments[i]));+ }+ }+ editorContext.Accessor.callActionWithParameters(handlerName, objs);+ }, context);+ }+ else {+ return editorContext.diffEditor.addCommand(parseInt(keybindingStr), function () {+ const objs = [];+ if (arguments) { // Use arguments as Monaco will pass each as it's own parameter, so we don't know how many that may be.+ for (let i = 1; i < arguments.length; i++) { // Skip first one as that's the sender?+ objs.push(JSON.stringify(arguments[i]));+ }+ }+ editorContext.Accessor.callActionWithParameters(handlerName, objs);+ }, context);+ }+};++const createContext = function (editorContext: EditorContext, context) {+ if (context) {+ if (editorContext.standaloneEditor != null) {+ editorContext.contexts[context.key] = editorContext.standaloneEditor.createContextKey(context.key, context.defaultValue);+ }+ else {+ editorContext.contexts[context.key] = editorContext.diffEditor.createContextKey(context.key, context.defaultValue);+ }+ }+};++const updateContext = function (editorContext: EditorContext, key, value) {+ editorContext.contexts[key].set(value);+}++// link:CodeEditor.cs:updateContent+const updateContent = function (editorContext: EditorContext, content) {+ // Need to ignore updates from us notifying of a change+ if (content !== editorContext.model.getValue()) {+ editorContext.model.setValue(content);+ }+};++// link:CodeEditor.cs:updateDiffContent+var updateDiffContent = function (editorContext: EditorContext, left, right) {+ var diffModel = (editorContext.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);+ }+};++const updateDecorations = function (editorContext: EditorContext, newHighlights) {+ if (editorContext.standaloneEditor != null) {+ if (newHighlights) {+ editorContext.decorations = editorContext.standaloneEditor.deltaDecorations(editorContext.decorations, newHighlights);+ } else {+ editorContext.decorations = editorContext.standaloneEditor.deltaDecorations(editorContext.decorations, []);+ }+ }+};++const updateStyle = function (innerStyle) {+ var style = document.getElementById("dynamic");+ style.innerHTML = innerStyle;+};++const getOptions = function (editorContext: EditorContext): Promise<monaco.editor.IEditorOptions> {+ let opt = null;+ try {+ opt = getParentValue(editorContext, "Options");+ } finally {++ }++ return opt;+};++var getDiffOptions = function (editorContext: EditorContext): monaco.editor.IDiffEditorOptions {+ let opt = null;+ try {+ opt = getParentValue(editorContext, "DiffOptions");+ } finally {++ }++ return opt;+};++const updateOptions = function (editorContext: EditorContext, opt: monaco.editor.IEditorOptions) {+ if (opt !== null && typeof opt === "object") {+ editorContext.editor.updateOptions(opt);+ }+};++var updateDiffOptions = function (editorContext: EditorContext, opt: monaco.editor.IDiffEditorOptions) {+ if (opt !== null && typeof opt === "object") {+ editorContext.diffEditor.updateOptions(opt);+ }+};++const updateLanguage = function (editorContext: EditorContext, language: string) {+ monaco.editor.setModelLanguage(editorContext.model, language);+};++const changeTheme = function (editorContext: EditorContext, theme: string, highcontrast) {+ let newTheme = 'devtoys';+ if (highcontrast == "True" || highcontrast == "true") {+ newTheme = 'hc-black';+ } else if (theme == "Dark") {+ newTheme = 'devtoys-dark';+ }++ monaco.editor.setTheme(newTheme);+};++var setTheme = function (editorContext: EditorContext, accentColor: string) {+ // Define themes+ // https://microsoft.github.io/monaco-editor/playground.html#customizing-the-appearence-exposed-colors++ accentColor = accentColor.replace('\"', '');++ monaco.editor.defineTheme('devtoys-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,+ 'editorWidget.background': '#252526'+ }+ });+ monaco.editor.defineTheme('devtoys', {+ 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,+ 'editorWidget.background': '#F3F3F3'+ }+ });+}++const keyDown = async function (element: any, event) {+ //Debug.log("Key Down:" + event.keyCode + " " + event.ctrlKey);+ //const result = await editorContext.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;+ //}+};+++const stringifyForMarshalling = (value: any): string => sanitize(value)++const sanitize = (jsonString: string): string => {+ if (jsonString == null) {+ //console.log('Sanitized is null');+ return null;+ }++ const replacements = "%&\\\"'{}:,";+ for (let i = 0; i < replacements.length; i++) {+ jsonString = replaceAll(jsonString, replacements.charAt(i), `%${replacements.charCodeAt(i)}`);+ }+ //console.log('Sanitized: ' + jsonString);+ return jsonString;+}++const replaceAll = (str: string, find: string, rep: string): string => {+ if (find == "\\") {+ find = "\\\\";+ }+ return (`${str}`).replace(new RegExp(find, "g"), rep);+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/registerCodeActionProvider.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/registerCodeActionProvider.tsnew file mode 100644index 000000000..f3d7e51ab--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/registerCodeActionProvider.ts@@ -0,0 +1,38 @@+///<reference path="../monaco-editor/monaco.d.ts" />++function isTextEdit(edit: monaco.languages.WorkspaceTextEdit | monaco.languages.WorkspaceFileEdit): edit is monaco.languages.WorkspaceTextEdit {+ return (edit as monaco.languages.WorkspaceTextEdit).edit !== undefined;+}++const registerCodeActionProvider = function (editorContext: EditorContext, languageId) {+ return monaco.languages.registerCodeActionProvider(languageId, {+ provideCodeActions: function (model, range, context, token) {+ return callParentEventAsync(editorContext, "ProvideCodeActions" + languageId, [JSON.stringify(range), JSON.stringify(context)]).then(result => {+ if (result) {+ const list: monaco.languages.CodeActionList = JSON.parse(result);++ // Need to add in the model.uri to any edits to connect the dots+ if (list.actions &&+ list.actions.length > 0) {+ list.actions.forEach((action) => {+ if (action.edit &&+ action.edit.edits &&+ action.edit.edits.length > 0) {+ action.edit.edits.forEach((inneredit) => {+ if (isTextEdit(inneredit)) {+ inneredit.resource = model.uri;+ }+ });+ }+ });+ }++ // Add dispose method for IDisposable that Monaco is looking for.+ list.dispose = () => { };++ return list;+ }+ });+ },+ });+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/registerCodeLensProvider.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/registerCodeLensProvider.tsnew file mode 100644index 000000000..87165c6d6--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/registerCodeLensProvider.ts@@ -0,0 +1,29 @@+///<reference path="../monaco-editor/monaco.d.ts" />++const registerCodeLensProvider = function (editorContext: EditorContext, any, languageId) {+ return monaco.languages.registerCodeLensProvider(languageId, {+ provideCodeLenses: function (model, token) {+ return callParentEventAsync(editorContext, "ProvideCodeLenses" + languageId, []).then(result => {+ if (result) {+ const list: monaco.languages.CodeLensList = JSON.parse(result);++ // Add dispose method for IDisposable that Monaco is looking for.+ list.dispose = () => {};++ return list;+ }+ return null;++ });+ },+ resolveCodeLens: function (model, codeLens, token) {+ return callParentEventAsync(editorContext, "ResolveCodeLens" + languageId, [JSON.stringify(codeLens)]).then(result => {+ if (result) {+ return JSON.parse(result);+ }+ return null;+ });+ }+ // TODO: onDidChange, don't know what this does.+ });+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/registerColorProvider.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/registerColorProvider.tsnew file mode 100644index 000000000..db9bf8ef4--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/registerColorProvider.ts@@ -0,0 +1,20 @@+///<reference path="../monaco-editor/monaco.d.ts" />++const registerColorProvider = function (editorContext: EditorContext, languageId) {+ return monaco.languages.registerColorProvider(languageId, {+ provideColorPresentations: function (model, colorInfo, token) {+ return callParentEventAsync(editorContext, "ProvideColorPresentations" + languageId, [JSON.stringify(colorInfo)]).then(result => {+ if (result) {+ return JSON.parse(result);+ }+ });+ },+ provideDocumentColors: function (model, token) {+ return callParentEventAsync(editorContext, "ProvideDocumentColors" + languageId, []).then(result => {+ if (result) {+ return JSON.parse(result);+ }+ });+ }+ });+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/registerCompletionItemProvider.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/registerCompletionItemProvider.tsnew file mode 100644index 000000000..564683ced--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/registerCompletionItemProvider.ts@@ -0,0 +1,26 @@+///<reference path="../monaco-editor/monaco.d.ts" />++const registerCompletionItemProvider = function (editorContext: EditorContext, languageId, characters) {+ return monaco.languages.registerCompletionItemProvider(languageId, {+ triggerCharacters: characters,+ provideCompletionItems: function (model, position, context, token) {+ return callParentEventAsync(editorContext, "CompletionItemProvider" + languageId, [JSON.stringify(position), JSON.stringify(context)]).then(result => {+ if (result) {+ const list: monaco.languages.CompletionList = JSON.parse(result);++ // Add dispose method for IDisposable that Monaco is looking for.+ list.dispose = () => { };++ return list;+ }+ });+ },+ resolveCompletionItem: function (item, token) {+ return callParentEventAsync(editorContext, "CompletionItemRequested" + languageId, [JSON.stringify(item)]).then(result => {+ if (result) {+ return JSON.parse(result);+ }+ });+ }+ });+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Wasm/Monaco.Helpers.ThemeAccessor.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Wasm/Monaco.Helpers.ThemeAccessor.tsnew file mode 100644index 000000000..173ad7d4c--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Wasm/Monaco.Helpers.ThemeAccessor.ts@@ -0,0 +1,7 @@+//namespace DevToys.MonacoEditor.Monaco.Helpers {+interface ThemeAccessor {+ getAccentColorHtmlHex(returnId: string);+ getCurrentThemeName(returnId: string);+ getIsHighContrast(returnId: string);+}+//}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Wasm/asyncCallbackHelpers.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Wasm/asyncCallbackHelpers.tsnew file mode 100644index 000000000..a6edd06a1--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Wasm/asyncCallbackHelpers.ts@@ -0,0 +1,122 @@+declare var Parent: ParentAccessor;+declare var Theme: ThemeAccessor;++type MethodWithReturnId = (parameter: string) => void;+type NumberCallback = (parameter: any) => void;+declare var asyncCallbackMap: { [promiseId: string]: NumberCallback };+declare var nextAsync: number;++nextAsync = 1;+asyncCallbackMap = {};++declare var returnValueCallbackMap: { [returnId: string]: string };+declare var nextReturn: number;++nextReturn = 1;+returnValueCallbackMap = {};++const asyncCallback = (promiseId: string, parameter: string) => {+ const promise = asyncCallbackMap[promiseId];+ if (promise) {+ //console.log('Async response: ' + parameter);+ promise(parameter);+ }+}++const returnValueCallback = (returnId: string, returnValue: string) => {+ //console.log('Return value for id ' + returnId + ' is ' + returnValue);+ returnValueCallbackMap[returnId] = returnValue;+}++const invokeAsyncMethod = <T>(syncMethod: NumberCallback): Promise<T> => {+ if (nextAsync == null) {+ nextAsync = 0;+ }+ if (asyncCallbackMap == null) {+ asyncCallbackMap = {};+ }+ const promise = new Promise<T>((resolve, reject) => {+ var nextId = nextAsync++;+ asyncCallbackMap[nextId] = resolve;+ syncMethod(`${nextId}`);+ });+ return promise;+}++const desantize = (parameter: string): string => {+ //System.Diagnostics.Debug.WriteLine($"Encoded String: {parameter}");+ if (parameter == null) return parameter;+ const replacements = "&\\\"'{}:,%";+ //System.Diagnostics.Debug.WriteLine($"Replacements: >{replacements}<");+ for (let i = 0; i < replacements.length; i++) {+ //console.log("Replacing: >%" + replacements.charCodeAt(i) + "< with >" + replacements.charAt(i) + "< ");+ parameter = replaceAll(parameter, "%" + replacements.charCodeAt(i), replacements.charAt(i));+ }++ //console.log("Decoded String: " + parameter );+ return parameter;+}++const invokeWithReturnValue = (methodToInvoke: MethodWithReturnId): string => {+ const nextId = nextReturn++;+ methodToInvoke(nextId + '');+ var json = returnValueCallbackMap[nextId];+ //console.log('Return json ' + json);+ json = desantize(json);+ return json;+}++const getParentValue = (editorContext: EditorContext, name: string): Promise<any> => {+ return new Promise((resolve, reject) => {+ const jsonString = invokeWithReturnValue((returnId) => editorContext.Accessor.getJsonValue(name, returnId));+ const obj = JSON.parse(jsonString);+ resolve(obj);+ });+}++const getParentJsonValue = function (editorContext: EditorContext, name: string): Promise<string> {+ return new Promise((resolve, reject) => {+ const json = invokeWithReturnValue((returnId) => editorContext.Accessor.getJsonValue(name, returnId));+ resolve(json);+ });+}++const callParentEventAsync = (editorContext: EditorContext, name: string, parameters: string[]): Promise<string> =>+ invokeAsyncMethod<string>(async (promiseId) => {+ let result = await editorContext.Accessor.callEvent(name,+ promiseId,+ parameters != null && parameters.length > 0 ? stringifyForMarshalling(parameters[0]) : null,+ parameters != null && parameters.length > 1 ? stringifyForMarshalling(parameters[1]) : null);+ if (result) {+ console.log('Parent event result: ' + name + ' - ' + result);+ result = desantize(result);+ console.log('Desanitized: ' + name + ' - ' + result);+ } else {+ console.log('No Parent event result for ' + name);+ }++ return result;+ });++const callParentActionWithParameters = (name: string, parameters: string[]): boolean =>+ Parent.callActionWithParameters(name,+ parameters != null && parameters.length > 0 ? stringifyForMarshalling(parameters[0]) : null,+ parameters != null && parameters.length > 1 ? stringifyForMarshalling(parameters[1]) : null);++const getAccentColorHtmlHex = function (editorContext: EditorContext): Promise<string> {+ return new Promise((resolve, reject) => {+ resolve(invokeWithReturnValue((returnId) => editorContext.Theme.getAccentColorHtmlHex(returnId)));+ });+}++const getThemeCurrentThemeName = function (editorContext: EditorContext): Promise<string> {+ return new Promise((resolve, reject) => {+ resolve(invokeWithReturnValue((returnId) => editorContext.Theme.getCurrentThemeName(returnId)));+ });+}++const getThemeIsHighContrast = function (editorContext: EditorContext): Promise<boolean> {+ return new Promise((resolve, reject) => {+ resolve(invokeWithReturnValue((returnId) => editorContext.Theme.getIsHighContrast(returnId)) == "true");+ });+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Wasm/tsconfig.json b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Wasm/tsconfig.jsonnew file mode 100644index 000000000..ba7a481f7--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Wasm/tsconfig.json@@ -0,0 +1,17 @@+{+ "compileOnSave": true,+ "compilerOptions": {+ "emitBOM": false,+ "target": "ES2015",+ "lib": [ "ES2015", "DOM" ],+ "sourceMap": false,+ "outFile": "..\\..\\WasmScripts\\uno-monaco-helpers.js"+ },+ "include": [+ ".\\",+ "..\\..\\ts-helpermethods"+ ],+ "exclude": [+ "..\\..\\ts-helpermethods\\ts-helpermethods-Windows"+ ]+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Windows/Monaco.Helpers.ThemeAccessor.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Windows/Monaco.Helpers.ThemeAccessor.tsnew file mode 100644index 000000000..ab67ab57c--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Windows/Monaco.Helpers.ThemeAccessor.ts@@ -0,0 +1,7 @@+//namespace DevToys.MonacoEditor.Monaco.Helpers {+interface ThemeAccessor {+ accentColorHtmlHex: Promise<string>;+ currentThemeName: Promise<string>;+ isHighContrast: Promise<boolean>;+}+//}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Windows/asyncCallbackHelpers.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Windows/asyncCallbackHelpers.tsnew file mode 100644index 000000000..bea681166--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Windows/asyncCallbackHelpers.ts@@ -0,0 +1,29 @@+var callParentEventAsync = function (editorContext: EditorContext, name: string, parameters: string[]): Promise<string> {+ return editorContext.Accessor.callEvent(name, parameters);+}++var callParentActionWithParameters = function (editorContext: EditorContext, name: string, parameters: string[]): boolean {+ return editorContext.Accessor.callActionWithParameters(name, parameters);+}++var getParentJsonValue = function (editorContext: EditorContext, name: string): Promise<string> {+ return editorContext.Accessor.getJsonValue(name);+}++var getParentValue = async function (editorContext: EditorContext, name: string): Promise<any> {+ var jsonString = await editorContext.Accessor.getJsonValue(name);+ var obj = JSON.parse(jsonString);+ return obj;+}++const getAccentColorHtmlHex = function (editorContext: EditorContext): Promise<string> {+ return editorContext.Theme.accentColorHtmlHex;+}++const getThemeCurrentThemeName = function (editorContext: EditorContext): Promise<string> {+ return editorContext.Theme.currentThemeName;+}++const getThemeIsHighContrast = function (editorContext: EditorContext): Promise<boolean> {+ return editorContext.Theme.isHighContrast;+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Windows/tsconfig.json b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Windows/tsconfig.jsonnew file mode 100644index 000000000..8de032db5--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/ts-helpermethods-Windows/tsconfig.json@@ -0,0 +1,14 @@+{+ "compileOnSave": true,+ "compilerOptions": {+ "target": "ES2015",+ "sourceMap": false+ },+ "include": [+ ".\\",+ "..\\..\\ts-helpermethods"+ ],+ "exclude": [+ "..\\..\\ts-helpermethods\\ts-helpermethods-Wasm"+ ]+}\ No newline at end of filediff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/updateSelection.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/updateSelection.tsnew file mode 100644index 000000000..8635d8174--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/updateSelection.ts@@ -0,0 +1,43 @@+///<reference path="../monaco-editor/monaco.d.ts" />++// link:CodeEditor.Properties.cs:updateSelectedContent+const updateSelectedContent = function (element: any, content) {+ var editorContext = EditorContext.getEditorForElement(element);++ let selection = editorContext.editor.getSelection();++ // Need to ignore updates from us notifying of a change+ if (content != editorContext.model.getValueInRange(selection)) {+ editorContext.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]);+ editorContext.model.pushEditOperations([], [op], null);++ // Update selection to new text.+ const newEndLineNumber = selection.startLineNumber + content.split('\r').length - 1; // TODO: Not sure if line end is situational/platform specific... investigate more.+ const 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;+ //}++ editorContext.modifingSelection = false;+ editorContext.editor.setSelection(selection);+ }+};\ No newline at end of filediff --git a/src/app/dev/DevToys.UI.EntryPoint/App.xaml.cs b/src/app/dev/DevToys.UI.EntryPoint/App.xaml.csindex 9ed006a8b..3ffcf9025 100644--- a/src/app/dev/DevToys.UI.EntryPoint/App.xaml.cs+++ b/src/app/dev/DevToys.UI.EntryPoint/App.xaml.cs@@ -63,7 +63,7 @@ public sealed partial class App : Application#if WINDOWS_UWPLaunchActivatedEventArgs uwpArgs = args;#else- var uwpArgs = args.UWPLaunchActivatedEventArgs;+ Windows.ApplicationModel.Activation.LaunchActivatedEventArgs uwpArgs = args.UWPLaunchActivatedEventArgs;#endif// Do not repeat app initialization when the Window already has content,diff --git a/src/app/dev/DevToys.UI.Framework/Threading/DispatcherQueueExtensions.cs b/src/app/dev/DevToys.UI.Framework/Threading/DispatcherQueueExtensions.csindex c05dc3393..316314c53 100644--- a/src/app/dev/DevToys.UI.Framework/Threading/DispatcherQueueExtensions.cs+++ b/src/app/dev/DevToys.UI.Framework/Threading/DispatcherQueueExtensions.cs@@ -1,4 +1,6 @@#if WINDOWS_UWP+using Windows.ApplicationModel.Core;+using Windows.UI.Core;using DispatcherQueue = Windows.UI.Core.CoreDispatcher;using DispatcherQueuePriority = Windows.UI.Core.CoreDispatcherPriority;#else@@ -9,6 +11,10 @@ namespace DevToys.UI.Framework.Threading;public static class DispatcherQueueExtensions{+#if WINDOWS_UWP+ public static readonly DispatcherQueue DispatcherQueue = CoreApplication.MainView.CoreWindow.Dispatcher;+#endif+public static void ThrowIfNotOnUIThread(this DispatcherQueue dispatcherQueue){if (!dispatcherQueue.HasThreadAccess)diff --git a/src/app/dev/DevToys.UI/DevToys.UI.csproj b/src/app/dev/DevToys.UI/DevToys.UI.csprojindex 9c541a49a..542372f70 100644--- a/src/app/dev/DevToys.UI/DevToys.UI.csproj+++ b/src/app/dev/DevToys.UI/DevToys.UI.csproj@@ -77,7 +77,7 @@</ItemGroup><ItemGroup>- <!--<ProjectReference Include="..\DevToys.MonacoEditor\DevToys.MonacoEditor.csproj" />-->+ <ProjectReference Include="..\DevToys.MonacoEditor\DevToys.MonacoEditor.csproj" /><ProjectReference Include="..\DevToys.UI.Framework\DevToys.UI.Framework.csproj" /></ItemGroup></Project>\ No newline at end of filediff --git a/src/app/dev/DevToys.UI/Views/MainPage.xaml b/src/app/dev/DevToys.UI/Views/MainPage.xamlindex 900fd0f6a..6ec101b60 100644--- a/src/app/dev/DevToys.UI/Views/MainPage.xaml+++ b/src/app/dev/DevToys.UI/Views/MainPage.xaml@@ -4,6 +4,7 @@xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"+ xmlns:monaco="using:DevToys.MonacoEditor"mc:Ignorable="d"Background="Transparent">@@ -19,14 +20,14 @@<RowDefinition Height="Auto"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>- <!--<monaco:CodeEditor x:Name="Editor"+ <monaco:CodeEditor x:Name="Editor"Grid.Row="0"- Grid.Column="0"/>-->+ Grid.Column="0"/>- <!--<monaco:CodeEditor x:Name="Editor2"+ <monaco:CodeEditor x:Name="Editor2"Grid.Row="0"Grid.Column="1"ReadOnly="True"- IsDiffViewMode="True"/>-->+ IsDiffViewMode="True"/></Grid></Page>diff --git a/src/app/dev/platforms/desktop/windows/DevToys.Windows.Core/DevToys.Windows.Core.csproj b/src/app/dev/platforms/desktop/windows/DevToys.Windows.Core/DevToys.Windows.Core.csprojindex 13f4c8f90..4f726b300 100644--- a/src/app/dev/platforms/desktop/windows/DevToys.Windows.Core/DevToys.Windows.Core.csproj+++ b/src/app/dev/platforms/desktop/windows/DevToys.Windows.Core/DevToys.Windows.Core.csproj@@ -61,6 +61,7 @@<PackageReference Include="CommunityToolkit.Common" Version="$(CommunityToolkitVersion)" /><PackageReference Include="CommunityToolkit.Diagnostics" Version="$(CommunityToolkitVersion)" /><PackageReference Include="System.ComponentModel.Composition" Version="$(DotNetVersion)" />+ <PackageReference Include="Microsoft.Web.WebView2" Version="$(WebView2Version)" /><PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="$(DotNetVersion)" /><PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform" Version="$(MicrosoftNETCoreUniversalWindowsPlatformVersion)" /><PackageReference Include="PolySharp" Version="$(PolySharpVersion)">@@ -77,6 +78,10 @@<Project>{a730fa8a-3713-4f7a-915d-79098ca12df0}</Project><Name>DevToys.Core</Name></ProjectReference>+ <ProjectReference Include="..\..\..\..\DevToys.MonacoEditor\DevToys.MonacoEditor.csproj">+ <Project>{cdd8b469-aca6-4a7d-91a0-66adb0563ae8}</Project>+ <Name>DevToys.MonacoEditor</Name>+ </ProjectReference><ProjectReference Include="..\..\..\..\DevToys.Tools\DevToys.Tools.csproj"><Project>{b6d48157-5257-4b60-b065-3b231b610a54}</Project><Name>DevToys.Tools</Name>