A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Added a multiline-line text input (#780)
Etienne BAUDOUX41a487471352
diff --git a/src/Directory.Packages.props b/src/Directory.Packages.propsindex fb8d1517e..29b7671d1 100644--- a/src/Directory.Packages.props+++ b/src/Directory.Packages.props@@ -8,14 +8,10 @@<CommunityToolkitWinUINuGetVersion>7.1.2</CommunityToolkitWinUINuGetVersion><DotNetVersion>7.0.0</DotNetVersion><MicrosoftFastComponentsFluentUIVersion>2.0.1</MicrosoftFastComponentsFluentUIVersion>- <MicrosoftNETCoreUniversalWindowsPlatformVersion>6.2.14</MicrosoftNETCoreUniversalWindowsPlatformVersion>- <MicrosoftWindowsSDKBuildToolsVersion>10.0.22621.755</MicrosoftWindowsSDKBuildToolsVersion><UnoVersion>4.7.37</UnoVersion><UnoCommunityToolkitWinUINuGetVersion>7.1.100</UnoCommunityToolkitWinUINuGetVersion><UnoWasmBootstrapVersion>8.0.0-dev.65</UnoWasmBootstrapVersion>- <WebView2Version>1.0.1462.37</WebView2Version><MicrosoftTypeScriptMSBuildVersion>4.9.4</MicrosoftTypeScriptMSBuildVersion>- <WpfGridLayoutBlazorVersion>1.2.0</WpfGridLayoutBlazorVersion></PropertyGroup><ItemGroup><PackageVersion Include="CommunityToolkit.Common" Version="$(CommunityToolkitVersion)" />@@ -34,14 +30,15 @@<PackageVersion Include="Microsoft.Extensions.Logging.Console" Version="$(DotNetVersion)" /><PackageVersion Include="Microsoft.Extensions.Logging.Debug" Version="$(DotNetVersion)" /><PackageVersion Include="Microsoft.Fast.Components.FluentUI" Version="$(MicrosoftFastComponentsFluentUIVersion)" />+ <PackageVersion Include="Microsoft.Graphics.Win2D" Version="1.0.4" /><PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.1.0" /><PackageVersion Include="Microsoft.TypeScript.MSBuild" Version="$(MicrosoftTypeScriptMSBuildVersion)" /><PackageVersion Include="Microsoft.UI.Xaml" Version="2.8.1" />- <PackageVersion Include="Microsoft.Web.WebView2" Version="$(WebView2Version)" />+ <PackageVersion Include="Microsoft.Web.WebView2" Version="1.0.1462.37" /><PackageVersion Include="Microsoft.Windows.Compatibility" Version="$(DotNetVersion)" /><PackageVersion Include="Microsoft.Windows.CsWin32" Version="0.2.188-beta" />- <PackageVersion Include="Microsoft.Windows.SDK.BuildTools" Version="$(MicrosoftWindowsSDKBuildToolsVersion)" />- <PackageVersion Include="Microsoft.WindowsAppSDK" Version="1.2.230118.102" />+ <PackageVersion Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.22621.756" />+ <PackageVersion Include="Microsoft.WindowsAppSDK" Version="1.2.230313.1" /><PackageVersion Include="Microsoft.Xaml.Behaviors.WinUI.Managed" Version="2.0.9"/><PackageVersion Include="Moq" Version="4.18.2" /><PackageVersion Include="Newtonsoft.Json" Version="13.0.1" />diff --git a/src/app/dev/DevToys.Api/Core/IFontProvider.cs b/src/app/dev/DevToys.Api/Core/IFontProvider.csnew file mode 100644index 000000000..6ba923d9c--- /dev/null+++ b/src/app/dev/DevToys.Api/Core/IFontProvider.cs@@ -0,0 +1,12 @@+namespace DevToys.Api.Core;++/// <summary>+/// Provides a platform agnostic way to retrieve information about fonts installed on the operating system.+/// </summary>+public interface IFontProvider+{+ /// <summary>+ /// Retrieves the list of font families available on the operating system.+ /// </summary>+ string[] GetFontFamilies();+}diff --git a/src/app/dev/DevToys.Api/Settings/PredefinedSettings.cs b/src/app/dev/DevToys.Api/Settings/PredefinedSettings.csindex 9807653b0..b791b64c4 100644--- a/src/app/dev/DevToys.Api/Settings/PredefinedSettings.cs+++ b/src/app/dev/DevToys.Api/Settings/PredefinedSettings.cs@@ -10,6 +10,76 @@ public static class PredefinedSettingsname: nameof(CompactMode),defaultValue: false);+ /// <summary>+ /// Preferred default fonts. The app will the first font in this list that is available on the system.+ /// </summary>+ public static readonly string[] DefaultFonts+ = new[]+ {+ // Popular fonts developers install. If it's on the system, users likely want to use it.+ "Fira Code",+ "Source Code Pro",+ "DejaVu Sans Mono",+ "Hack",++ // Default Visual Studio fonts.+ "Cascadia Mono",+ "Cascadia Code",++ // Fonts included on MacOS.+ "Menlo",+ "Monaco",+ "SF Mono",+ "SF Pro",++ // Fonts included on Windows and MacOS.+ "Consolas",+ "Courier New",++ // Fonts included on Windows.+ "Segoe UI",+ };++ /// <summary>+ /// The font family name to use in the text editor.+ /// </summary>+ public static readonly SettingDefinition<string> TextEditorFont+ = new(+ name: nameof(TextEditorFont),+ defaultValue: string.Empty); // Default value will be defined by the app depending on the operating system.++ /// <summary>+ /// Whether the text in the text editor should wrap.+ /// </summary>+ public static readonly SettingDefinition<bool> TextEditorTextWrapping+ = new(+ name: nameof(TextEditorTextWrapping),+ defaultValue: false);++ /// <summary>+ /// Whether the line numbers should be displayed in the text editor.+ /// </summary>+ public static readonly SettingDefinition<bool> TextEditorLineNumbers+ = new(+ name: nameof(TextEditorLineNumbers),+ defaultValue: true);++ /// <summary>+ /// Whether the line where the caret is should be highlighted in the text editor.+ /// </summary>+ public static readonly SettingDefinition<bool> TextEditorHighlightCurrentLine+ = new(+ name: nameof(TextEditorHighlightCurrentLine),+ defaultValue: true);++ /// <summary>+ /// Whether white spaces should be rendered in the text editor.+ /// </summary>+ public static readonly SettingDefinition<bool> TextEditorRenderWhitespace+ = new(+ name: nameof(TextEditorRenderWhitespace),+ defaultValue: false);+/// <summary>/// Whether when using the Paste command, the text in the editor should be replaced or appended./// </summary>diff --git a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIButton.cs b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIButton.csindex a7aa8f6dc..42c3f4fe4 100644--- a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIButton.cs+++ b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIButton.cs@@ -49,7 +49,7 @@ internal sealed class UIButton : UIElement, IUIButtonpublic static partial class GUI{/// <summary>- /// Create component that represents a button, which reacts when clicking on it.+ /// Create a component that represents a button, which reacts when clicking on it./// </summary>public static IUIButton Button(){@@ -57,7 +57,7 @@ public static partial class GUI}/// <summary>- /// Create component that represents a button, which reacts when clicking on it.+ /// Create a component that represents a button, which reacts when clicking on it./// </summary>/// <param name="id">An optional unique identifier for this UI element.</param>public static IUIButton Button(string? id)@@ -66,7 +66,7 @@ public static partial class GUI}/// <summary>- /// Create component that represents a button, which reacts when clicking on it.+ /// Create a component that represents a button, which reacts when clicking on it./// </summary>/// <param name="id">An optional unique identifier for this UI element.</param>/// <param name="text">The text to display in the button.</param>diff --git a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIMultilineLineTextInput.cs b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIMultilineLineTextInput.csindex abfd3e7db..6f22a198b 100644--- a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIMultilineLineTextInput.cs+++ b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIMultilineLineTextInput.cs@@ -108,7 +108,7 @@ public static partial class GUI/// <summary>/// Sets the list of spans to highlight in the text document./// </summary>- public static IUIMultilineLineTextInput Hihglight(this IUIMultilineLineTextInput element, params TextSpan[] spans)+ public static IUIMultilineLineTextInput Highlight(this IUIMultilineLineTextInput element, params TextSpan[] spans){((UIMultilineTextInput)element).HighlightedSpans = spans;return element;diff --git a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISetting.cs b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISetting.csindex 231d1f59f..12524b123 100644--- a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISetting.cs+++ b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISetting.cs@@ -1,6 +1,4 @@-using System;--namespace DevToys.Api;+namespace DevToys.Api;/// <summary>/// A component that represents a setting, with a title, description, icon and <see cref="IUIElement"/> for the option value.diff --git a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISinglelineTextInput.cs b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISinglelineTextInput.csindex cf3bf6efd..8fc2e4469 100644--- a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISinglelineTextInput.cs+++ b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISinglelineTextInput.cs@@ -142,7 +142,7 @@ public static partial class GUI/// <summary>/// Sets the text input control as read-only./// </summary>- public static T ReadOnly<T>(this T element) where T : IUITitledElement+ public static T ReadOnly<T>(this T element) where T : IUISinglelineTextInput{if (element is UISinglelineTextInput strongElement){@@ -154,7 +154,7 @@ public static partial class GUI/// <summary>/// Sets the text input control as editable./// </summary>- public static T Editable<T>(this T element) where T : IUITitledElement+ public static T Editable<T>(this T element) where T : IUISinglelineTextInput{if (element is UISinglelineTextInput strongElement){@@ -166,7 +166,7 @@ public static partial class GUI/// <summary>/// Shows the "copy" button when the editor is editable./// </summary>- public static T CanCopyWhenEditable<T>(this T element) where T : IUITitledElement+ public static T CanCopyWhenEditable<T>(this T element) where T : IUISinglelineTextInput{if (element is UISinglelineTextInput strongElement){@@ -178,7 +178,7 @@ public static partial class GUI/// <summary>/// Hides the "copy" button when the editor is editable./// </summary>- public static T CannotCopyWhenEditable<T>(this T element) where T : IUITitledElement+ public static T CannotCopyWhenEditable<T>(this T element) where T : IUISinglelineTextInput{if (element is UISinglelineTextInput strongElement){@@ -190,7 +190,7 @@ public static partial class GUI/// <summary>/// Sets the unformatted text of the control./// </summary>- public static T Text<T>(this T element, string text) where T : IUITitledElement+ public static T Text<T>(this T element, string text) where T : IUISinglelineTextInput{if (element is UISinglelineTextInput strongElement){@@ -202,7 +202,7 @@ public static partial class GUI/// <summary>/// Selects the given span in the text document./// </summary>- public static T Select<T>(this T element, TextSpan span) where T : IUITitledElement+ public static T Select<T>(this T element, TextSpan span) where T : IUISinglelineTextInput{if (element is UISinglelineTextInput strongElement){@@ -214,7 +214,7 @@ public static partial class GUI/// <summary>/// Selects the given span in the text document./// </summary>- public static T Select<T>(this T element, int start, int length) where T : IUITitledElement+ public static T Select<T>(this T element, int start, int length) where T : IUISinglelineTextInput{if (element is UISinglelineTextInput strongElement){diff --git a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.cs b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.csindex 040693757..178f398f2 100644--- a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.cs+++ b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.cs@@ -4,14 +4,19 @@ using DevToys.Api;using DevToys.MonacoEditor.Extensions;using DevToys.MonacoEditor.Monaco;using DevToys.MonacoEditor.Monaco.Editor;+using DevToys.MonacoEditor.Monaco.Helpers;using DevToys.MonacoEditor.WebInterop;-using DevToys.UI.Framework.Threading;+using DevToys.UI.Framework.Controls;+using DevToys.UI.Framework.Helpers;+using Microsoft.Extensions.Logging;+using Microsoft.UI.Xaml;+using Microsoft.UI.Xaml.Controls;using Microsoft.Web.WebView2.Core;+using Uno.Extensions;using Windows.Foundation;+using Windows.UI;+using static System.Net.Mime.MediaTypeNames;using Range = DevToys.MonacoEditor.Monaco.Range;-using Microsoft.UI.Dispatching;-using Microsoft.UI.Xaml;-using Microsoft.UI.Xaml.Controls;namespace DevToys.MonacoEditor;@@ -24,7 +29,7 @@ namespace DevToys.MonacoEditor;[TemplateVisualState(Name = PointerOverState, GroupName = CommonStates)][TemplateVisualState(Name = FocusedState, GroupName = CommonStates)][TemplateVisualState(Name = DisabledState, GroupName = CommonStates)]-public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisposable+public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisposable, IMonacoEditor{internal const string CommonStates = "CommonStates";internal const string NormalState = "Normal";@@ -32,12 +37,22 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDispinternal const string FocusedState = "Focused";internal const string DisabledState = "Disabled";- private DispatcherQueue UIAccess => this.DispatcherQueue;+ private static readonly IModelDecorationOptions HighlightedSpanStyle+ = new IModelDecorationOptions()+ {+ ClassName = new CssLineStyle()+ {+ BackgroundColor = Color.FromArgb(85, 234, 92, 0) // #55EA5C00+ }+ };+ private readonly ILogger _logger;+ private readonly ISettingsProvider _settingsProvider = Parts.SettingsProvider;private readonly DebugLogger _debugLogger = new();- private readonly ThemeListener _themeListener;- private readonly long _themeToken;+ private readonly ThemeListener _themeListener = new();+ private readonly CssStyleBroker _cssBroker;+ private IReadOnlyList<TextSpan>? _spansToHighlight;private ICodeEditorPresenter? _view;private int _focusCount;private bool _initialized;@@ -46,17 +61,19 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisppublic CodeEditor(){+ _logger = this.Log();DefaultStyleKey = typeof(CodeEditor);ParentAccessor = new ParentAccessor(this);ParentAccessor.AddAssemblyForTypeLookup(typeof(Range).GetTypeInfo().Assembly);+ ParentAccessor.AddAssemblyForTypeLookup(typeof(TextSpan).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);++ _cssBroker = new CssStyleBroker(this);Options = new StandaloneEditorConstructionOptions();DiffOptions = new DiffEditorConstructionOptions();@@ -66,8 +83,7 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDispOptions.PropertyChanged += Options_PropertyChanged;DiffOptions.PropertyChanged += DiffOptions_PropertyChanged;-- Unloaded += CodeEditor_Unloaded;+ _settingsProvider.SettingChanged += SettingsProvider_SettingChanged;}public static DependencyProperty IsEditorLoadedProperty { get; }@@ -111,10 +127,17 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDispstring.Empty,async (d, e) =>{- if (d is CodeEditor { IsSettingValue: false } codeEditor && codeEditor._initialized)+ if (d is CodeEditor codeEditor && codeEditor._initialized){- // link:otherScriptsToBeOrganized.ts:updateContent- await codeEditor.InvokeScriptAsync("updateContent", e.NewValue.ToString() ?? string.Empty);+ if (!codeEditor.IsSettingValue)+ {+ // link:otherScriptsToBeOrganized.ts:updateContent+ await codeEditor.InvokeScriptAsync("updateContent", e.NewValue.ToString() ?? string.Empty);+ }+ else+ {+ codeEditor.TextChanged?.Invoke(d, EventArgs.Empty);+ }}}));@@ -127,47 +150,6 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDispset => 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),@@ -194,6 +176,38 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisp}}));+ public static DependencyProperty SelectedSpanProperty { get; }+ = DependencyProperty.Register(+ nameof(SelectedSpan),+ typeof(TextSpan),+ typeof(CodeEditor),+ new PropertyMetadata(+ new TextSpan(0, 0),+ async (d, e) =>+ {+ if (d is CodeEditor codeEditor && codeEditor._initialized)+ {+ if (!codeEditor.IsSettingValue)+ {+ // link:updateSelection.ts:updateSelectedSpan+ await codeEditor.InvokeScriptAsync("updateSelectedSpan", e.NewValue ?? new TextSpan(0, 0));+ }+ else+ {+ codeEditor.SelectedSpanChanged?.Invoke(d, EventArgs.Empty);+ }+ }+ }));++ /// <summary>+ /// Gets the current selection in the editor, or replace the current selection by the given span.+ /// </summary>+ public TextSpan SelectedSpan+ {+ get => (TextSpan)GetValue(SelectedSpanProperty);+ set => SetValue(SelectedSpanProperty, value);+ }+/// <summary>/// Gets or sets whether the editor is read-only./// </summary>@@ -220,6 +234,7 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDispif (editor.Options != null && editor._initialized){editor.Options.Language = e.NewValue.ToString();+ editor.Options.Folding = !string.IsNullOrWhiteSpace(editor.Options.Language) && !string.Equals("text", editor.Options.Language, StringComparison.OrdinalIgnoreCase);}}));@@ -348,6 +363,8 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisppublic bool IsSettingValue { get; set; }+ public Control UIHost => this;+internal ParentAccessor ParentAccessor { get; }/// <summary>@@ -365,6 +382,10 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisp/// </summary>public event TypedEventHandler<CodeEditor, CoreWebView2NewWindowRequestedEventArgs>? OpenLinkRequested;+ public event EventHandler? TextChanged;++ public event EventHandler? SelectedSpanChanged;+#if HAS_UNOpublic new void Dispose()#else@@ -372,6 +393,52 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisp#endif{ParentAccessor.Dispose();+ _cssBroker.Dispose();+ }++ public async Task HighlightSpansAsync(IReadOnlyList<TextSpan>? spans)+ {+ if (!_initialized)+ {+ _spansToHighlight = spans;+ return;+ }++ var newDecorationsAdjust = new List<IModelDeltaDecoration>();++ if (spans is not null)+ {+ for (int i = 0; i < spans.Count; i++)+ {+ TextSpan span = spans[i];+ if (span.StartPosition + span.Length < Text.Length)+ {+ Position? startPosition = await GetModel().GetPositionAtAsync((uint)span.StartPosition);+ Position? endPosition = await GetModel().GetPositionAtAsync((uint)(span.StartPosition + span.Length));+ if (startPosition is not null && endPosition is not null)+ {+ newDecorationsAdjust.Add(+ new IModelDeltaDecoration(+ new Range(+ startPosition.LineNumber,+ startPosition.Column,+ endPosition.LineNumber,+ endPosition.Column),+ HighlightedSpanStyle));+ }+ }+ }+ }++ if (_cssBroker.AssociateStyles(newDecorationsAdjust))+ {+ // Update Styles First+ await InvokeScriptAsync("updateStyle", _cssBroker.GetStyles());+ }++ // Send Command to Modify Decorations+ // IMPORTANT: Need to cast to object here as we want this to be a single array object passed as a parameter, not a list of parameters to expand.+ await InvokeScriptAsync("updateDecorations", (object)newDecorationsAdjust);}internal IModel GetModel()@@ -399,18 +466,20 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDispGuard.IsNotNull(_view);try{- return await _view.RunScriptAsync<T>(script, member, file, line);+ return await _view.RunScriptAsync<T>(script, serializeResult: false, member, file, line);}catch (Exception e){+ LogInternalError(e);InternalException?.Invoke(this, e);}}else{-#if DEBUG- Debug.WriteLine("WARNING: Tried to call '" + script + "' before initialized.");-#endif+ if (Debugger.IsAttached)+ {+ Debug.WriteLine("WARNING: Tried to call '" + script + "' before initialized.");+ }}return default;@@ -466,14 +535,16 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisp}catch (Exception e){+ LogInternalError(e);InternalException?.Invoke(this, e);}}else{-#if DEBUG- Debug.WriteLine("WARNING: Tried to call '" + method + "' before initialized.");-#endif+ if (Debugger.IsAttached)+ {+ Debug.WriteLine("WARNING: Tried to call '" + method + "' before initialized.");+ }}return default;@@ -516,26 +587,6 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDispGiveFocusToInnerEditor();}- 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)@@ -587,29 +638,23 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisp}}- private void ActualTheme_PropertyChanged(DependencyObject obj, DependencyProperty property)+ private void ThemeListener_ThemeChanged(ThemeListener sender){- ElementTheme theme = ActualTheme;- string themeName;- if (theme == ElementTheme.Default)- {- themeName = _themeListener.CurrentThemeName;- }- else- {- themeName = theme.ToString();- }-- InvokeScriptAsync("setTheme", args: new string[] { _themeListener!.AccentColorHtmlHex }).Forget();- InvokeScriptAsync("changeTheme", new string[] { themeName, _themeListener.IsHighContrast.ToString() }).Forget();+ InvokeScriptAsync(+ "setTheme",+ args: new string[] { sender.AccentColorHtmlHex })+ .Forget();+ InvokeScriptAsync(+ "changeTheme",+ args: new object[] { sender.CurrentTheme.ToString(), sender.IsHighContrast, IsFocusEngaged })+ .Forget();}- private void ThemeListener_ThemeChanged(ThemeListener sender)+ private void SettingsProvider_SettingChanged(object? sender, SettingChangedEventArgs e){- if (RequestedTheme == ElementTheme.Default)+ if (e.SettingName.Contains("TextEditor")){- InvokeScriptAsync("setTheme", args: new string[] { sender.AccentColorHtmlHex }).Forget();- InvokeScriptAsync("changeTheme", args: new string[] { sender.CurrentTheme.ToString(), sender.IsHighContrast.ToString() }).Forget();+ ApplySettings();}}@@ -651,6 +696,10 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisp_focusCount++;if (_focusCount > 0){+ InvokeScriptAsync(+ "changeTheme",+ args: new object[] { _themeListener.CurrentTheme.ToString(), _themeListener.IsHighContrast, true })+ .Forget();VisualStateManager.GoToState(this, FocusedState, false);}}@@ -660,6 +709,10 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisp_focusCount = Math.Max(0, _focusCount - 1);if (_focusCount == 0){+ InvokeScriptAsync(+ "changeTheme",+ args: new object[] { _themeListener.CurrentTheme.ToString(), _themeListener.IsHighContrast, false })+ .Forget();VisualStateManager.GoToState(this, NormalState, false);}}@@ -677,19 +730,42 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisp.Forget();InvokeScriptAsync("changeTheme",- new string[] { _themeListener.CurrentTheme.ToString(), _themeListener.IsHighContrast.ToString() })+ new object[] { _themeListener.CurrentTheme.ToString(), _themeListener.IsHighContrast, IsFocusEngaged }).Forget();// Update options._refrainFromUpdatingOptionsInternally = true;Options.SmoothScrolling = true;+ Options.GlyphMargin = false;+ Options.MouseWheelZoom = false;+ Options.OverviewRulerBorder = false;+ Options.ScrollBeyondLastLine = false;+ Options.FontLigatures = false;+ Options.SnippetSuggestions = SnippetSuggestions.None;+ Options.CodeLens = true;+ Options.QuickSuggestions = false;+ Options.WordBasedSuggestions = false;Options.Minimap = new EditorMinimapOptions() { Enabled = false };+ Options.ShowFoldingControls = Show.Always;Options.ReadOnly = ReadOnly;Options.Language = CodeLanguage;+ Options.Folding = !string.IsNullOrWhiteSpace(CodeLanguage) && !string.Equals("text", CodeLanguage, StringComparison.OrdinalIgnoreCase);+ DiffOptions.SmoothScrolling = true;+ DiffOptions.GlyphMargin = false;+ DiffOptions.MouseWheelZoom = false;+ DiffOptions.OverviewRulerBorder = false;+ DiffOptions.ScrollBeyondLastLine = false;+ DiffOptions.FontLigatures = false;+ DiffOptions.SnippetSuggestions = SnippetSuggestions.None;+ DiffOptions.CodeLens = true;+ DiffOptions.QuickSuggestions = false;+ DiffOptions.ShowFoldingControls = Show.Always;DiffOptions.OriginalEditable = !ReadOnly;DiffOptions.ReadOnly = ReadOnly;+ ApplySettings();+_refrainFromUpdatingOptionsInternally = false;if (IsDiffViewMode){@@ -700,11 +776,32 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDispInvokeScriptAsync("updateOptions", Options).Forget();}+ // Set text, selection, highlighted spans that may have been set but not sent to the editor yet.+ InvokeScriptAsync("updateContent", Text ?? string.Empty).Forget();+ InvokeScriptAsync("updateSelectedSpan", SelectedSpan).Forget();+ HighlightSpansAsync(_spansToHighlight).Forget();+// We're done loading Monaco Editor.IsEditorLoaded = true;EditorLoaded?.Invoke(this, new RoutedEventArgs());}+ private void ApplySettings()+ {+ Options.WordWrapMinified = _settingsProvider.GetSetting(PredefinedSettings.TextEditorTextWrapping);+ Options.WordWrap = _settingsProvider.GetSetting(PredefinedSettings.TextEditorTextWrapping) ? WordWrap.On : WordWrap.Off;+ Options.LineNumbers = _settingsProvider.GetSetting(PredefinedSettings.TextEditorLineNumbers) ? LineNumbersType.On : LineNumbersType.Off;+ Options.RenderLineHighlight = _settingsProvider.GetSetting(PredefinedSettings.TextEditorHighlightCurrentLine) ? RenderLineHighlight.All : RenderLineHighlight.None;+ Options.RenderWhitespace = _settingsProvider.GetSetting(PredefinedSettings.TextEditorRenderWhitespace) ? RenderWhitespace.All : RenderWhitespace.None;+ Options.FontFamily = _settingsProvider.GetSetting(PredefinedSettings.TextEditorFont);+ DiffOptions.WordWrapMinified = _settingsProvider.GetSetting(PredefinedSettings.TextEditorTextWrapping);+ DiffOptions.WordWrap = _settingsProvider.GetSetting(PredefinedSettings.TextEditorTextWrapping) ? WordWrap.On : WordWrap.Off;+ DiffOptions.LineNumbers = _settingsProvider.GetSetting(PredefinedSettings.TextEditorLineNumbers) ? LineNumbersType.On : LineNumbersType.Off;+ DiffOptions.RenderLineHighlight = _settingsProvider.GetSetting(PredefinedSettings.TextEditorHighlightCurrentLine) ? RenderLineHighlight.All : RenderLineHighlight.None;+ DiffOptions.RenderWhitespace = _settingsProvider.GetSetting(PredefinedSettings.TextEditorRenderWhitespace) ? RenderWhitespace.All : RenderWhitespace.None;+ DiffOptions.FontFamily = _settingsProvider.GetSetting(PredefinedSettings.TextEditorFont);+ }+private void GiveFocusToInnerEditor(){if (_initialized)@@ -715,4 +812,7 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDispSendScriptAsync("editorContext.editor.focus();").Forget();}}++ [LoggerMessage(2, LogLevel.Error, "An error occured related to the Monaco Editor.")]+ partial void LogInternalError(Exception ex);}diff --git a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Wasm.cs b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Wasm.csindex 96c5d51f6..7e8390d23 100644--- a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Wasm.cs+++ b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Wasm.cs@@ -168,7 +168,7 @@ public sealed partial class CodeEditorPresenter : Control, ICodeEditorPresenter,}}}})()";- _debugLogger?.Debug($"Invoke Script: {script}");+ _debugLogger?.Debug($"Invoking script");try{diff --git a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Windows.cs b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Windows.csindex 4bce657f3..bad366f38 100644--- a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Windows.cs+++ b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Windows.cs@@ -13,6 +13,7 @@ using Windows.Foundation;using Microsoft.UI.Dispatching;using Microsoft.UI.Xaml;using System.Runtime.CompilerServices;+using Microsoft.UI.Xaml.Media;namespace DevToys.MonacoEditor;@@ -57,8 +58,9 @@ public sealed partial class CodeEditorPresenter : UserControl, ICodeEditorPresen{_logger = this.Log();- // make the WebView2 transparent.- Environment.SetEnvironmentVariable("WEBVIEW2_DEFAULT_BACKGROUND_COLOR", "00FFFFFF");+ // Fill the WebView2 with ControlFillColorInputActive.+ var controlFillColorInputActive = (Windows.UI.Color)Application.Current.Resources["ControlFillColorInputActive"];+ Environment.SetEnvironmentVariable("WEBVIEW2_DEFAULT_BACKGROUND_COLOR", $"{controlFillColorInputActive.R:X2}{controlFillColorInputActive.G:X2}{controlFillColorInputActive.B:X2}");Content = _webView;@@ -92,6 +94,18 @@ public sealed partial class CodeEditorPresenter : UserControl, ICodeEditorPresen{await _webView.EnsureCoreWebView2Async();+ _webView.CoreWebView2.Settings.IsZoomControlEnabled = false;+ _webView.CoreWebView2.Settings.IsPinchZoomEnabled = false;+ _webView.CoreWebView2.Settings.IsSwipeNavigationEnabled = false;+ _webView.CoreWebView2.Settings.IsStatusBarEnabled = false;+ _webView.CoreWebView2.Settings.IsPasswordAutosaveEnabled = false;+ _webView.CoreWebView2.Settings.IsGeneralAutofillEnabled = false;+ _webView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;+#if !DEBUG+ _webView.CoreWebView2.Settings.AreBrowserAcceleratorKeysEnabled = false;+ _webView.CoreWebView2.Settings.AreDevToolsEnabled = false;+#endif+string path = Path.Combine(AppContext.BaseDirectory, "DevToys.MonacoEditor", "CodeEditor", "CodeEditor.Windows.html");if (!File.Exists(path)){@@ -359,7 +373,7 @@ public sealed partial class CodeEditorPresenter : UserControl, ICodeEditorPresen}}}})();";- LogInvokingJavaScript(script);+ LogInvokingJavaScript();try{@@ -415,8 +429,8 @@ public sealed partial class CodeEditorPresenter : UserControl, ICodeEditorPresen[LoggerMessage(7, LogLevel.Error, "{caller}-CALLBACK: Exception in {name}.{propertyName}.")]partial void LogDotNetObjectInjectionCallbackPropertyFailed(string name, string propertyName, Exception exception, [CallerMemberName] string? caller = null);- [LoggerMessage(8, LogLevel.Debug, "{caller}: Invoking JavaScript: {script}")]- partial void LogInvokingJavaScript(string script, [CallerMemberName] string? caller = null);+ [LoggerMessage(8, LogLevel.Debug, "{caller}: Invoking JavaScript...")]+ partial void LogInvokingJavaScript([CallerMemberName] string? caller = null);[LoggerMessage(9, LogLevel.Debug, "{caller}: JavaScript invoked successfully: {result}")]partial void LogInvokedJavaScriptSuccessfully(string result, [CallerMemberName] string? caller = null);diff --git a/src/app/dev/DevToys.MonacoEditor/Extensions/ICodeEditorPresenterExtensions.cs b/src/app/dev/DevToys.MonacoEditor/Extensions/ICodeEditorPresenterExtensions.csindex de7e5da04..1617efd93 100644--- a/src/app/dev/DevToys.MonacoEditor/Extensions/ICodeEditorPresenterExtensions.cs+++ b/src/app/dev/DevToys.MonacoEditor/Extensions/ICodeEditorPresenterExtensions.cs@@ -14,18 +14,19 @@ internal static class ICodeEditorPresenterExtensions[CallerFilePath] string? file = null,[CallerLineNumber] int line = 0){- await view.RunScriptAsync<object>(script, member, file, line);+ await view.RunScriptAsync<object>(script, serializeResult: false, member, file, line);}public static async Task<T?> RunScriptAsync<T>(this ICodeEditorPresenter view,string script,+ bool serializeResult = true,[CallerMemberName] string? member = null,[CallerFilePath] string? file = null,[CallerLineNumber] int line = 0){string start = "try {\n";- if (typeof(T) != typeof(object))+ if (typeof(T) != typeof(object) && serializeResult){script = script.Trim(';');start += "return JSON.stringify(" + script + ");";@@ -51,14 +52,6 @@ internal static class ICodeEditorPresenterExtensions{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 correctlyif (!string.IsNullOrEmpty(returnstring)){@@ -131,7 +124,11 @@ internal static class ICodeEditorPresenterExtensionstry{- Debug.WriteLine($"Begin invoke script (serialize - {serialize})");+ if (Debugger.IsAttached)+ {+ Debug.WriteLine($"Begin invoke script (serialize - {serialize})");+ }+if (serialize){sanitizedargs@@ -161,13 +158,14 @@ internal static class ICodeEditorPresenterExtensionsstring script = method + "(editorContext, " + string.Join(", ", sanitizedargs) + ");";- Debug.WriteLine($"Script {script})");-- return await RunScriptAsync<T>(view, script, member, file, line);+ return await RunScriptAsync<T>(view, script, serialize, member, file, line);}catch (Exception ex){- Debug.WriteLine($"Error {ex.Message} {ex.StackTrace} {ex.InnerException?.Message})");+ if (Debugger.IsAttached)+ {+ Debug.WriteLine($"Error {ex.Message} {ex.StackTrace} {ex.InnerException?.Message})");+ }return default;}}diff --git a/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssStyleBroker.cs b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssStyleBroker.csindex ffb6cb283..a7c98c620 100644--- a/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssStyleBroker.cs+++ b/src/app/dev/DevToys.MonacoEditor/Monaco/Helpers/CssStyleBroker.cs@@ -44,15 +44,17 @@ internal sealed class CssStyleBroker : IDisposablereturn id;}- public bool AssociateStyles(IModelDeltaDecoration[] decorations)+ public bool AssociateStyles(IReadOnlyList<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)+ for (int i = 0; i < decorations.Count; i++){+ IModelDeltaDecoration decoration = decorations[i];+// Add (or ignore) elements to the collection.// If any Adds are new, we flag our boolean to returnif (decoration.Options.ClassName != null)diff --git a/src/app/dev/DevToys.MonacoEditor/MonacoEditorFactory.cs b/src/app/dev/DevToys.MonacoEditor/MonacoEditorFactory.csnew file mode 100644index 000000000..47c3bb132--- /dev/null+++ b/src/app/dev/DevToys.MonacoEditor/MonacoEditorFactory.cs@@ -0,0 +1,12 @@+using DevToys.UI.Framework.Controls;++namespace DevToys.MonacoEditor;++[Export(typeof(IMonacoEditorFactory))]+internal sealed class MonacoEditorFactory : IMonacoEditorFactory+{+ public IMonacoEditor CreateMonacoEditorInstance()+ {+ return new CodeEditor();+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/Themes/generic.xaml b/src/app/dev/DevToys.MonacoEditor/Themes/generic.xamlindex 476b7ac95..d5f73a99b 100644--- a/src/app/dev/DevToys.MonacoEditor/Themes/generic.xaml+++ b/src/app/dev/DevToys.MonacoEditor/Themes/generic.xaml@@ -5,6 +5,26 @@xmlns:muxc="using:Microsoft.UI.Xaml.Controls"xmlns:converters="using:DevToys.UI.Framework.Converters">+ <ResourceDictionary.ThemeDictionaries>+ <ResourceDictionary x:Key="Light">+ <SolidColorBrush x:Key="TextControlBackground" Color="#FDFDFD"/>+ <SolidColorBrush x:Key="TextControlBackgroundFocused" Color="#FFFFFF"/>+ <SolidColorBrush x:Key="TextControlBackgroundDisabled" Color="RED"/> <!-- TODO -->+ <SolidColorBrush x:Key="TextControlBackgroundPointerOver" Color="RED"/>+ </ResourceDictionary>+ <ResourceDictionary x:Key="Dark">+ <SolidColorBrush x:Key="TextControlBackground" Color="#343434"/>+ <SolidColorBrush x:Key="TextControlBackgroundFocused" Color="#202123"/>+ <SolidColorBrush x:Key="TextControlBackgroundDisabled" Color="RED"/> <!-- TODO -->+ <SolidColorBrush x:Key="TextControlBackgroundPointerOver" Color="#393939"/>+ </ResourceDictionary>+ <ResourceDictionary x:Key="HighContrast">+ <SolidColorBrush x:Key="TextControlBackground" Color="#FFFFFF"/>+ <SolidColorBrush x:Key="TextControlBackgroundDisabled" Color="RED"/> <!-- TODO -->+ <SolidColorBrush x:Key="TextControlBackgroundPointerOver" Color="RED"/>+ </ResourceDictionary>+ </ResourceDictionary.ThemeDictionaries>+<converters:NegateBooleanConverter x:Key="NegateBooleanConverter"/><Style TargetType="monaco:CodeEditor" >diff --git a/src/app/dev/DevToys.MonacoEditor/WebInterop/Parent/ParentAccessor.cs b/src/app/dev/DevToys.MonacoEditor/WebInterop/Parent/ParentAccessor.csindex eb4a7c8bf..bd3880592 100644--- a/src/app/dev/DevToys.MonacoEditor/WebInterop/Parent/ParentAccessor.cs+++ b/src/app/dev/DevToys.MonacoEditor/WebInterop/Parent/ParentAccessor.cs@@ -73,10 +73,18 @@ internal sealed partial class ParentAccessor : IDisposable/// <returns></returns>public Task<string> CallEvent(string name, string[] parameters){- Debug.WriteLine($"Event {name}");+ if (Debugger.IsAttached)+ {+ Debug.WriteLine($"Event {name}");+ }+if (_events.TryGetValue(name, out Func<string[], Task<string>>? @event)){- Debug.WriteLine($"Parameters: {parameters != null} - {parameters?.Length.ToString() ?? "N/A"}");+ if (Debugger.IsAttached)+ {+ Debug.WriteLine($"Parameters: {parameters != null} - {parameters?.Length.ToString() ?? "N/A"}");+ }+parameters ??= Array.Empty<string>();return @event.Invoke(parameters);}diff --git a/src/app/dev/DevToys.MonacoEditor/WebInterop/Theme/ThemeListener.cs b/src/app/dev/DevToys.MonacoEditor/WebInterop/Theme/ThemeListener.csindex 0d3cc0db6..5d5e93146 100644--- a/src/app/dev/DevToys.MonacoEditor/WebInterop/Theme/ThemeListener.cs+++ b/src/app/dev/DevToys.MonacoEditor/WebInterop/Theme/ThemeListener.cs@@ -1,10 +1,9 @@-using Windows.Foundation.Metadata;-using Windows.UI.ViewManagement;-using Newtonsoft.Json;-using Windows.UI;-using Microsoft.UI.Dispatching;+using DevToys.UI.Framework.Helpers;using Microsoft.UI.Xaml;using Microsoft.UI.Xaml.Media;+using Newtonsoft.Json;+using Windows.Foundation.Metadata;+using Windows.UI;namespace DevToys.MonacoEditor.WebInterop;@@ -15,128 +14,36 @@ internal delegate void ThemeChangedEvent(ThemeListener sender);/// 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+internal sealed partial class ThemeListener{- 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)+ internal ThemeListener(){- Guard.IsNotNull(queue);- _dispatcher = queue;+ Parts.ThemeListener.ThemeChanged += ThemeListener_ThemeChanged;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+ public string CurrentThemeName => JsonConvert.SerializeObject(Parts.ThemeListener.ActualAppTheme.ToString()); // For Web Retrieval- // UpdateProperties();- // }+ public Api.Core.Theme.ApplicationTheme CurrentTheme => Parts.ThemeListener.ActualAppTheme;- // // 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+ public bool IsHighContrast => Parts.ThemeListener.IsHighContrast;- // UpdateProperties();- // }- // }).Forget();- // }-- private bool IsSystemHighContrast() =>- ApiInformation.IsPropertyPresent("Windows.UI.ViewManagement.HighContrast", "HighContrast")- && _accessible.HighContrast;+ public string AccentColorHtmlHex { get; private set; }- // 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+ public event ThemeChangedEvent? ThemeChanged;- // UpdateProperties();- // }- // }+ partial void PartialCtor();- /// <summary>- /// Set our current properties and fire a change notification.- /// </summary>- private void UpdateProperties()+ private void ThemeListener_ThemeChanged(object? sender, EventArgs e){- // 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)+ private 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/ts-helpermethods/editorContext.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/editorContext.tsindex b97722c40..f08f5602e 100644--- a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/editorContext.ts+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/editorContext.ts@@ -40,4 +40,9 @@ class EditorContext {public decorations: string[];public modifingSelection: boolean; // Supress updates to selection when making edits.public htmlElement: any;+}++class TextSpan {+ public StartPosition: number;+ public Length: number;}\ 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.tsindex b5f0e4c0c..257d9e9fd 100644--- a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/monacoInitializer.ts+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/monacoInitializer.ts@@ -59,7 +59,7 @@ const initializeMonacoEditorAsync = async (editorContext: EditorContext) => {debug.log("Changing theme");setTheme(editorContext, await getAccentColorHtmlHex(editorContext));- changeTheme(editorContext, theme, await getThemeIsHighContrast(editorContext));+ changeTheme(editorContext, theme, await getThemeIsHighContrast(editorContext), false);// Update Monaco Size when we receive a window resize eventdebug.log("Listen for resize events on the window and resize the editor");@@ -109,7 +109,7 @@ const initializeStandardMonacoEditorAsync = async (editorContext: EditorContext)model.onDidChangeContent(async (event) => {// link:CodeEditor.Text- await accessor.setValue("Text", stringifyForMarshalling(model.getValue()));+ await accessor.setValue("Text", model.getValue());});// Listen for Selection Changes@@ -117,11 +117,16 @@ const initializeStandardMonacoEditorAsync = async (editorContext: EditorContext)editor.onDidChangeCursorSelection(async (event) => {if (!editorContext.modifingSelection) {- // link:CodeEditor.SelectedText- await accessor.setValue("SelectedText", stringifyForMarshalling(model.getValueInRange(event.selection)));+ var primarySelection = editor.getSelection();+ var start = model.getOffsetAt(primarySelection.getStartPosition());+ var end = model.getOffsetAt(primarySelection.getEndPosition());- // link:CodeEditor.SelectedRange of type Selection- await accessor.setValueWithType("SelectedRange", stringifyForMarshalling(JSON.stringify(event.selection)), "Selection");+ var selectedSpan = new TextSpan();+ selectedSpan.StartPosition = start;+ selectedSpan.Length = end - start;++ // link:CodeEditor.SelectedSpan of type TextSpan+ await accessor.setValueWithType("SelectedSpan", stringifyForMarshalling(JSON.stringify(selectedSpan)), "TextSpan");}});diff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.tsindex 8850f2eb7..ed2359cb4 100644--- a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.ts+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.ts@@ -97,7 +97,7 @@ const updateDecorations = function (editorContext: EditorContext, newHighlights)}};-const updateStyle = function (innerStyle) {+const updateStyle = function (editorContext: EditorContext, innerStyle) {var style = document.getElementById("dynamic");style.innerHTML = innerStyle;};@@ -140,14 +140,30 @@ 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") {+var _theme = "Dark";+var _highContrast = false;++const changeTheme = function (editorContext: EditorContext, theme: string, highContrast: boolean, hasFocus: boolean) {+ if (theme == undefined) {+ theme = _theme;+ }++ if (highContrast == undefined) {+ highContrast = _highContrast;+ }++ let state = hasFocus ? "active" : "inactive";+ let newTheme = 'devtoys-' + state;++ if (highContrast) {newTheme = 'hc-black';} else if (theme == "Dark") {- newTheme = 'devtoys-dark';+ newTheme = 'devtoys-dark-' + state;}+ _theme = theme;+ _highContrast = highContrast;+monaco.editor.setTheme(newTheme);};@@ -158,14 +174,33 @@ var setTheme = function (editorContext: EditorContext, accentColor: string) {// remove quotes.accentColor = accentColor.replace(/"/g, '');- monaco.editor.defineTheme('devtoys-dark', {+ monaco.editor.defineTheme('devtoys-dark-active', {+ base: 'vs-dark',+ inherit: true,+ rules: [],+ colors: {+ 'foreground': '#FFFFFF',+ 'editor.foreground': '#FFFFFF',+ 'editor.background': '#202123',+ 'editor.lineHighlightBackground': '#FFFFFF00',+ 'editor.lineHighlightBorder': '#FFFFFF19',+ 'editorLineNumber.foreground': '#EEEEEE99',+ 'editorLineNumber.activeForeground': '#EEEEEEFF',+ 'editor.inactiveSelectionBackground': '#00000000',+ 'editor.selectionForeground': '#FFFFFF',+ 'editor.selectionBackground': accentColor,+ 'editorWidget.background': '#252526'+ }+ });++ monaco.editor.defineTheme('devtoys-dark-inactive', {base: 'vs-dark',inherit: true,rules: [],colors: {'foreground': '#FFFFFF','editor.foreground': '#FFFFFF',- 'editor.background': '#00000000',+ 'editor.background': '#343434','editor.lineHighlightBackground': '#FFFFFF00','editor.lineHighlightBorder': '#FFFFFF19','editorLineNumber.foreground': '#EEEEEE99',@@ -176,14 +211,34 @@ var setTheme = function (editorContext: EditorContext, accentColor: string) {'editorWidget.background': '#252526'}});- monaco.editor.defineTheme('devtoys', {++ monaco.editor.defineTheme('devtoys-active', {+ base: 'vs',+ inherit: true,+ rules: [],+ colors: {+ 'foreground': '#000000',+ 'editor.foreground': '#000000',+ 'editor.background': '#FFFFFF',+ 'editor.lineHighlightBackground': '#00000000',+ 'editor.lineHighlightBorder': '#00000019',+ 'editorLineNumber.foreground': '#00000099',+ 'editorLineNumber.activeForeground': '#000000FF',+ 'editor.inactiveSelectionBackground': '#00000000',+ 'editor.selectionForeground': '#000000',+ 'editor.selectionBackground': accentColor,+ 'editorWidget.background': '#F3F3F3'+ }+ });++ monaco.editor.defineTheme('devtoys-inactive', {base: 'vs',inherit: true,rules: [],colors: {'foreground': '#000000','editor.foreground': '#000000',- 'editor.background': '#FFFFFF00',+ 'editor.background': '#FDFDFD','editor.lineHighlightBackground': '#00000000','editor.lineHighlightBorder': '#00000019','editorLineNumber.foreground': '#00000099',diff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/updateSelection.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/updateSelection.tsindex 8635d8174..b2af8d561 100644--- a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/updateSelection.ts+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/updateSelection.ts@@ -1,43 +1,12 @@///<reference path="../monaco-editor/monaco.d.ts" />-// link:CodeEditor.Properties.cs:updateSelectedContent-const updateSelectedContent = function (element: any, content) {- var editorContext = EditorContext.getEditorForElement(element);+// link:CodeEditor.Properties.cs:updateSelectedSpan+const updateSelectedSpan = function (element: any, span: any) {+ var editorContext = EditorContext.getEditorForElement(element).htmlElement;- let selection = editorContext.editor.getSelection();+ var startPosition = editorContext.model.getPositionAt(span.startPosition);+ var endPosition = editorContext.model.getPositionAt(span.startPosition + span.length);+ var newSelection = monaco.Selection.fromPositions(startPosition, endPosition);- // 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);- }+ editorContext.editor.setSelection(newSelection);};\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/Sample/SampleToolFactory.cs b/src/app/dev/DevToys.Tools/Tools/Sample/SampleToolFactory.csindex 8953c67c0..84d7df7e5 100644--- a/src/app/dev/DevToys.Tools/Tools/Sample/SampleToolFactory.cs+++ b/src/app/dev/DevToys.Tools/Tools/Sample/SampleToolFactory.cs@@ -1,4 +1,5 @@using Microsoft.Extensions.Logging;+using Newtonsoft.Json.Linq;namespace DevToys.Tools.Tools.Sample;@@ -48,21 +49,21 @@ internal sealed class SampleCommandLineTool : ICommandLineToolAccessibleNameResourceName = nameof(Sample.CommandDescription),SearchKeywordsResourceName = nameof(Sample.CommandDescription))][AcceptedDataTypeName(PredefinedCommonDataTypeNames.Json)]-[TargetPlatform(Platform.Windows)] // Optional. Not putting any attribute means every platforms are supported.-[TargetPlatform(Platform.Linux)]-[TargetPlatform(Platform.MacCatalyst)]-[TargetPlatform(Platform.WASM)]internal sealed class SampleGuiTool : IGuiTool{+ private readonly IUIMultilineLineTextInput _editor = MultilineTextInput().Language("json").CanCopyWhenEditable();+public IUIElement View- => Stack()- .Vertical()- .WithChildren(- SinglelineTextInput().Title("Read-write text control"),- SinglelineTextInput().Title("Read-only text control").ReadOnly(),- SinglelineTextInput().Title("Read-write text input with copy").CanCopyWhenEditable());+ => _editor;- public void OnDataReceived(string dataTypeName, object? parsedData) { }+ public void OnDataReceived(string dataTypeName, object? parsedData)+ {+ if (dataTypeName == PredefinedCommonDataTypeNames.Json && parsedData is Tuple<JToken, string> strongTypedParsedData)+ {+ _editor.Text(strongTypedParsedData.Item2);+ _editor.Highlight(new TextSpan(3, 6));+ }+ }}[Export(typeof(IGuiTool))]@@ -84,9 +85,14 @@ internal sealed class SampleGuiTool : IGuiTool[TargetPlatform(Platform.WASM)]internal sealed class SampleGuiTool2 : IGuiTool{- public IUIElement View => null!;+ private readonly IUIMultilineLineTextInput _editor = MultilineTextInput().CanCopyWhenEditable();- public void OnDataReceived(string dataTypeName, object? parsedData) { }+ public IUIElement View+ => _editor;++ public void OnDataReceived(string dataTypeName, object? parsedData)+ {+ }}[Export(typeof(IGuiTool))]diff --git a/src/app/dev/DevToys.Tools/Tools/Settings/SettingsGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Settings/SettingsGuiTool.csindex ab942fdcd..2ef34e9d4 100644--- a/src/app/dev/DevToys.Tools/Tools/Settings/SettingsGuiTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/Settings/SettingsGuiTool.cs@@ -67,10 +67,8 @@ internal sealed class SettingsGuiTool : IGuiTool.Title("Compact mode").Handle(_settingsProvider, PredefinedSettings.CompactMode),Setting()- .Title("Title")- .Description("Description")- .InteractiveElement(- Switch()),+ .Title("Line numbers")+ .Handle(_settingsProvider, PredefinedSettings.TextEditorLineNumbers),Setting().Title("Title").Description("Description")@@ -93,7 +91,8 @@ internal sealed class SettingsGuiTool : IGuiTool.WithChildren(Button().Text("Bottom Left button"),Button().Text("Bottom Center button").OnClick(OnBottomCenterButtonClickAsync),- Button().Text("Bottom Right button")));+ Button().Text("Bottom Right button")),+ SinglelineTextInput().CanCopyWhenEditable());public void OnDataReceived(string dataTypeName, object? parsedData){diff --git a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/IDetachable.cs b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/IDetachable.csnew file mode 100644index 000000000..e829d658c--- /dev/null+++ b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/IDetachable.cs@@ -0,0 +1,6 @@+namespace DevToys.UI.Framework.Controls.GuiTool;++internal interface IDetachable+{+ void Detach();+}diff --git a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIElementPresenter.xaml b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIElementPresenter.xamlindex 8ac01cfb1..cad33a91b 100644--- a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIElementPresenter.xaml+++ b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIElementPresenter.xaml@@ -86,6 +86,7 @@<Control.Template><ControlTemplate TargetType="local:UIElementPresenter"><ContentControl+ x:Name="RootContentControl"ContentTemplateSelector="{StaticResource UIElementTemplateSelector}"Content="{x:Bind UIElement, Mode=OneWay}"HorizontalContentAlignment="Stretch"diff --git a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIElementPresenter.xaml.cs b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIElementPresenter.xaml.csindex 8b008f8a2..bf207310a 100644--- a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIElementPresenter.xaml.cs+++ b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIElementPresenter.xaml.cs@@ -4,7 +4,7 @@ using Microsoft.UI.Xaml.Controls;namespace DevToys.UI.Framework.Controls.GuiTool;-public sealed partial class UIElementPresenter : Control+public sealed partial class UIElementPresenter : Control, IDetachable{internal static UIElementPresenter Create(IUIElement element){@@ -31,4 +31,16 @@ public sealed partial class UIElementPresenter : Controlget => (IUIElement)GetValue(UIElementProperty);set => SetValue(UIElementProperty, value);}++ public void Detach()+ {+ if (IsLoaded)+ {+ var rootContentControl = GetTemplateChild("RootContentControl") as ContentControl;+ if (rootContentControl is not null && rootContentControl.ContentTemplateRoot is IDetachable detachableChild)+ {+ detachableChild.Detach();+ }+ }+ }}diff --git a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIMultilineTextInputPresenter.xaml b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIMultilineTextInputPresenter.xamlindex aa1877cca..9e1fa7ba7 100644--- a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIMultilineTextInputPresenter.xaml+++ b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIMultilineTextInputPresenter.xaml@@ -6,7 +6,5 @@xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable="d">- <local:UITextInputHeader>- <!-- TODO: Monaco Editor -->- </local:UITextInputHeader>+ <local:UITextInputHeader x:Name="UITextInputHeader"/></UserControl>\ No newline at end of filediff --git a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIMultilineTextInputPresenter.xaml.cs b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIMultilineTextInputPresenter.xaml.csindex b62210f80..45939da18 100644--- a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIMultilineTextInputPresenter.xaml.cs+++ b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIMultilineTextInputPresenter.xaml.cs@@ -3,25 +3,151 @@ using Microsoft.UI.Xaml.Controls;namespace DevToys.UI.Framework.Controls.GuiTool;-public sealed partial class UIMultilineTextInputPresenter : UserControl+public sealed partial class UIMultilineTextInputPresenter : UserControl, IDetachable{+ private static readonly MonacoEditorPool MonacoEditorPool = new();++ private readonly IMonacoEditor _monacoEditor;++ private bool _isDetached;+ private bool _textChangedByUser;+public UIMultilineTextInputPresenter(){this.InitializeComponent();Loaded += UIMultilineTextInputPresenter_Loaded;Unloaded += UIMultilineTextInputPresenter_Unloaded;++ _monacoEditor = MonacoEditorPool.Get();+ _monacoEditor.UIHost.HorizontalAlignment = Microsoft.UI.Xaml.HorizontalAlignment.Stretch;+ _monacoEditor.UIHost.VerticalAlignment = Microsoft.UI.Xaml.VerticalAlignment.Stretch;+ _monacoEditor.TextChanged += MonacoEditor_TextChanged;+ _monacoEditor.SelectedSpanChanged += MonacoEditor_SelectedSpanChanged;+ UITextInputHeader.InnerEditor = _monacoEditor.UIHost;}internal IUIMultilineLineTextInput UIMultilineLineTextInput => (IUIMultilineLineTextInput)DataContext;+ public void Detach()+ {+ // Recycling the Monaco Editor when we don't need it anymore (i.e navigating to another tool) so it can+ // be reused in another tool without having to create a new editor instance (which is slow and consumes a lot of memory).+ _isDetached = true;+ _monacoEditor.TextChanged -= MonacoEditor_TextChanged;+ _monacoEditor.SelectedSpanChanged -= MonacoEditor_SelectedSpanChanged;+ UITextInputHeader.InnerEditor = null;+ MonacoEditorPool.Recycle(_monacoEditor);+ }+private void UIMultilineTextInputPresenter_Loaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e){+ UIMultilineLineTextInput.IsReadOnlyChanged += UIMultilineLineTextInput_IsReadOnlyChanged;+ UIMultilineLineTextInput.TextChanged += UIMultilineLineTextInput_TextChanged;+ UIMultilineLineTextInput.SelectionChanged += UIMultilineLineTextInput_SelectionChanged;+ UIMultilineLineTextInput.SyntaxColorizationLanguageNameChanged += UIMultilineLineTextInput_SyntaxColorizationLanguageNameChanged;+ UIMultilineLineTextInput.HighlightedSpansChanged += UIMultilineLineTextInput_HighlightedSpansChanged;+ _monacoEditor.ReadOnly = UIMultilineLineTextInput.IsReadOnly;+ _monacoEditor.Text = UIMultilineLineTextInput.Text;+ _monacoEditor.CodeLanguage = UIMultilineLineTextInput.SyntaxColorizationLanguageName;+ _monacoEditor.HighlightSpansAsync(UIMultilineLineTextInput.HighlightedSpans).ForgetSafely();+ if (UIMultilineLineTextInput.Selection is not null)+ {+ _monacoEditor.SelectedSpan = UIMultilineLineTextInput.Selection;+ }}private void UIMultilineTextInputPresenter_Unloaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e){+ _monacoEditor.TextChanged -= MonacoEditor_TextChanged;+ _monacoEditor.SelectedSpanChanged -= MonacoEditor_SelectedSpanChanged;+ UIMultilineLineTextInput.IsReadOnlyChanged -= UIMultilineLineTextInput_IsReadOnlyChanged;+ UIMultilineLineTextInput.TextChanged -= UIMultilineLineTextInput_TextChanged;+ UIMultilineLineTextInput.SelectionChanged -= UIMultilineLineTextInput_SelectionChanged;+ UIMultilineLineTextInput.SyntaxColorizationLanguageNameChanged -= UIMultilineLineTextInput_SyntaxColorizationLanguageNameChanged;Loaded -= UIMultilineTextInputPresenter_Loaded;Unloaded -= UIMultilineTextInputPresenter_Unloaded;}++ private void UIMultilineLineTextInput_SelectionChanged(object? sender, EventArgs e)+ {+ if (_isDetached)+ {+ return;+ }++ if (UIMultilineLineTextInput.Selection is not null)+ {+ if (_monacoEditor.SelectedSpan.StartPosition != UIMultilineLineTextInput.Selection.StartPosition+ && _monacoEditor.SelectedSpan.Length != UIMultilineLineTextInput.Selection.Length)+ {+ _monacoEditor.SelectedSpan = UIMultilineLineTextInput.Selection;+ }+ }+ else+ {+ _monacoEditor.SelectedSpan = new TextSpan(0, 0);+ }+ }++ private void UIMultilineLineTextInput_TextChanged(object? sender, EventArgs e)+ {+ if (!_isDetached)+ {+ if (!_textChangedByUser)+ {+ _monacoEditor.Text = UIMultilineLineTextInput.Text;+ }+ }+ }++ private void UIMultilineLineTextInput_IsReadOnlyChanged(object? sender, EventArgs e)+ {+ if (!_isDetached)+ {+ _monacoEditor.ReadOnly = UIMultilineLineTextInput.IsReadOnly;+ }+ }++ private void UIMultilineLineTextInput_SyntaxColorizationLanguageNameChanged(object? sender, EventArgs e)+ {+ if (!_isDetached)+ {+ _monacoEditor.CodeLanguage = UIMultilineLineTextInput.SyntaxColorizationLanguageName;+ }+ }++ private void UIMultilineLineTextInput_HighlightedSpansChanged(object? sender, EventArgs e)+ {+ if (!_isDetached)+ {+ _monacoEditor.HighlightSpansAsync(UIMultilineLineTextInput.HighlightedSpans).ForgetSafely();+ }+ }++ private void MonacoEditor_TextChanged(object? sender, EventArgs e)+ {+ _textChangedByUser = true;+ if (!_isDetached)+ {+ UIMultilineLineTextInput.Text(_monacoEditor.Text);+ }+ _textChangedByUser = false;+ }++ private void MonacoEditor_SelectedSpanChanged(object? sender, EventArgs e)+ {+ if (!_isDetached)+ {+ if (_monacoEditor.SelectedSpan.StartPosition > UIMultilineLineTextInput.Text.Length)+ {+ // Looks like the text isn't in sync.+ _textChangedByUser = true;+ UIMultilineLineTextInput.Text(_monacoEditor.Text);+ _textChangedByUser = false;+ }++ UIMultilineLineTextInput.Select(_monacoEditor.SelectedSpan);+ }+ }}diff --git a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISettingGroupPresenter.xaml.cs b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISettingGroupPresenter.xaml.csindex 0b4184a88..f37ed762d 100644--- a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISettingGroupPresenter.xaml.cs+++ b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISettingGroupPresenter.xaml.cs@@ -5,7 +5,7 @@ using Microsoft.UI.Xaml.Controls;namespace DevToys.UI.Framework.Controls.GuiTool;-public sealed partial class UISettingGroupPresenter : Expander+public sealed partial class UISettingGroupPresenter : Expander, IDetachable{public UISettingGroupPresenter(){@@ -19,6 +19,12 @@ public sealed partial class UISettingGroupPresenter : Expanderinternal IUISettingGroup UISettingGroup => (IUISettingGroup)DataContext;+ public void Detach()+ {+ UISettingHeaderControl.Detach();+ DetachContentStackPanel();+ }+private void UISettingGroupPresenter_Loaded(object sender, RoutedEventArgs e){UISettingGroup.IsEnabledChanged += UISettingGroup_IsEnabledChanged;@@ -100,6 +106,7 @@ public sealed partial class UISettingGroupPresenter : Expanderprivate void SetChildren(){+ DetachContentStackPanel();ContentStackPanel.Children.Clear();if (UISettingGroup.Children is not null){@@ -149,4 +156,15 @@ public sealed partial class UISettingGroupPresenter : Expander}}}++ private void DetachContentStackPanel()+ {+ for (int i = 0; i < ContentStackPanel.Children.Count; i++)+ {+ if (ContentStackPanel.Children[i] is IDetachable detachable)+ {+ detachable.Detach();+ }+ }+ }}diff --git a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISettingHeaderControl.xaml.cs b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISettingHeaderControl.xaml.csindex fda2c7b7a..74048105d 100644--- a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISettingHeaderControl.xaml.cs+++ b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISettingHeaderControl.xaml.cs@@ -7,7 +7,7 @@ using Microsoft.UI.Xaml.Markup;namespace DevToys.UI.Framework.Controls.GuiTool;[ContentProperty(Name = nameof(SettingActionableElement))]-public sealed partial class UISettingHeaderControl : UserControl+public sealed partial class UISettingHeaderControl : UserControl, IDetachable{public static readonly DependencyProperty SettingActionableElementProperty= DependencyProperty.Register(@@ -77,6 +77,12 @@ public sealed partial class UISettingHeaderControl : UserControlVisualStateManager.GoToState(this, "NormalState", false);}+ public void Detach()+ {+ SettingIconElement.Detach();+ ActionableElement.Detach();+ }+private void MainPanel_SizeChanged(object sender, SizeChangedEventArgs e){if (e.NewSize.Width == e.PreviousSize.Width || ActionableElement == null)diff --git a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISettingPresenter.xaml.cs b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISettingPresenter.xaml.csindex 409c059f2..1c25f519b 100644--- a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISettingPresenter.xaml.cs+++ b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISettingPresenter.xaml.cs@@ -4,7 +4,7 @@ using Microsoft.UI.Xaml.Controls;namespace DevToys.UI.Framework.Controls.GuiTool;-public sealed partial class UISettingPresenter : UserControl+public sealed partial class UISettingPresenter : UserControl, IDetachable{public UISettingPresenter(){@@ -18,6 +18,11 @@ public sealed partial class UISettingPresenter : UserControlinternal IUISetting UISetting => (IUISetting)DataContext;+ public void Detach()+ {+ UISettingHeaderControl.Detach();+ }+internal void ClearBackground(){NonExpanderGrid.Background = null;diff --git a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISinglelineTextInputPresenter.xaml.cs b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISinglelineTextInputPresenter.xaml.csindex 31a824552..26ac10545 100644--- a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISinglelineTextInputPresenter.xaml.cs+++ b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UISinglelineTextInputPresenter.xaml.cs@@ -1,4 +1,5 @@using DevToys.Api;+using DevToys.UI.Framework.Helpers;using Microsoft.UI.Xaml.Controls;namespace DevToys.UI.Framework.Controls.GuiTool;@@ -22,12 +23,15 @@ public sealed partial class UISinglelineTextInputPresenter : UserControlUISinglelineTextInput.IsReadOnlyChanged += UISinglelineTextInput_IsReadOnlyChanged;UISinglelineTextInput.TextChanged += UISinglelineTextInput_TextChanged;UISinglelineTextInput.SelectionChanged += UISinglelineTextInput_SelectionChanged;+ TextBox.FontFamily = new Microsoft.UI.Xaml.Media.FontFamily(Parts.SettingsProvider.GetSetting(PredefinedSettings.TextEditorFont));TextBox.IsReadOnly = UISinglelineTextInput.IsReadOnly;TextBox.Text = UISinglelineTextInput.Text;if (UISinglelineTextInput.Selection is not null){TextBox.Select(UISinglelineTextInput.Selection.StartPosition, UISinglelineTextInput.Selection.Length);}++ Parts.SettingsProvider.SettingChanged += SettingsProvider_SettingChanged;}private void UISinglelineTextInputPresenter_Unloaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)@@ -37,6 +41,8 @@ public sealed partial class UISinglelineTextInputPresenter : UserControlUISinglelineTextInput.SelectionChanged -= UISinglelineTextInput_SelectionChanged;Loaded -= UISinglelineTextInputPresenter_Loaded;Unloaded -= UISinglelineTextInputPresenter_Unloaded;++ Parts.SettingsProvider.SettingChanged -= SettingsProvider_SettingChanged;}private void UISinglelineTextInput_SelectionChanged(object? sender, EventArgs e)@@ -87,4 +93,12 @@ public sealed partial class UISinglelineTextInputPresenter : UserControlUISinglelineTextInput.Select(TextBox.SelectionStart, TextBox.SelectionLength);}++ private void SettingsProvider_SettingChanged(object? sender, SettingChangedEventArgs e)+ {+ if (string.Equals(e.SettingName, PredefinedSettings.TextEditorFont.Name, StringComparison.Ordinal))+ {+ TextBox.FontFamily = new Microsoft.UI.Xaml.Media.FontFamily(e.NewValue as string);+ }+ }}diff --git a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIStackPresenter.xaml.cs b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIStackPresenter.xaml.csindex 1b18d0b96..a3091bb34 100644--- a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIStackPresenter.xaml.cs+++ b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UIStackPresenter.xaml.cs@@ -3,7 +3,7 @@ using Microsoft.UI.Xaml.Controls;namespace DevToys.UI.Framework.Controls.GuiTool;-public sealed partial class UIStackPresenter : ContentControl+public sealed partial class UIStackPresenter : ContentControl, IDetachable{public UIStackPresenter(){@@ -15,6 +15,17 @@ public sealed partial class UIStackPresenter : ContentControlinternal IUIStack UIStack => (IUIStack)DataContext;+ public void Detach()+ {+ for (int i = 0; i < StackPanel.Children.Count; i++)+ {+ if (StackPanel.Children[i] is IDetachable detachable)+ {+ detachable.Detach();+ }+ }+ }+private void UIStackPresenter_Loaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e){UIStack.IsEnabledChanged += UIStack_IsEnabledChanged;@@ -60,7 +71,9 @@ public sealed partial class UIStackPresenter : ContentControlprivate void SetChildren(){+ Detach();StackPanel.Children.Clear();+if (UIStack.Children is not null){for (int i = 0; i < UIStack.Children.Length; i++)diff --git a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UITextInputHeader.xaml b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UITextInputHeader.xamlindex 2c6d2af67..a0a5c437f 100644--- a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UITextInputHeader.xaml+++ b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UITextInputHeader.xaml@@ -31,7 +31,13 @@<Style TargetType="Button" BasedOn="{StaticResource CustomButtonStyle}"/></UserControl.Resources>- <Grid>+ <Grid+ x:Name="MainPanel"+ AllowDrop="True"+ Background="Transparent"+ DragOver="MainPanel_DragOver"+ DragLeave="MainPanel_DragLeave"+ Drop="MainPanel_Drop"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/>@@ -63,6 +69,7 @@<Buttonx:Name="PasteButton"x:Load="{x:Bind IsReadOnly, Mode=OneWay, Converter={StaticResource NegateBooleanConverter}}"+ IsEnabled="{x:Bind IsLoadingFile, Mode=OneWay, Converter={StaticResource NegateBooleanConverter}}"ToolTipService.ToolTip="{str:StringsExtension Key=Paste}"AutomationProperties.Name="{str:StringsExtension Key=Paste}"Click="PasteButton_Click">@@ -74,6 +81,7 @@<Buttonx:Name="OpenFileButton"x:Load="{x:Bind IsReadOnly, Mode=OneWay, Converter={StaticResource NegateBooleanConverter}}"+ IsEnabled="{x:Bind IsLoadingFile, Mode=OneWay, Converter={StaticResource NegateBooleanConverter}}"ToolTipService.ToolTip="{str:StringsExtension Key=OpenFile}"AutomationProperties.Name="{str:StringsExtension Key=OpenFile}"Click="OpenFileButton_Click">@@ -82,6 +90,7 @@<Buttonx:Name="ClearButton"x:Load="{x:Bind IsReadOnly, Mode=OneWay, Converter={StaticResource NegateBooleanConverter}}"+ IsEnabled="{x:Bind IsLoadingFile, Mode=OneWay, Converter={StaticResource NegateBooleanConverter}}"ToolTipService.ToolTip="{str:StringsExtension Key=Clear}"AutomationProperties.Name="{str:StringsExtension Key=Clear}"Click="ClearButton_Click">@@ -94,6 +103,7 @@<Buttonx:Name="SaveAsButton"x:Load="{x:Bind IsReadOnlyOrCanCopyWhenEditable, Mode=OneWay}"+ IsEnabled="{x:Bind IsLoadingFile, Mode=OneWay, Converter={StaticResource NegateBooleanConverter}}"ToolTipService.ToolTip="{str:StringsExtension Key=SaveAs}"AutomationProperties.Name="{str:StringsExtension Key=SaveAs}"Click="SaveAsButton_Click">@@ -102,6 +112,7 @@<Buttonx:Name="CopyButton"x:Load="{x:Bind IsReadOnlyOrCanCopyWhenEditable, Mode=OneWay}"+ IsEnabled="{x:Bind IsLoadingFile, Mode=OneWay, Converter={StaticResource NegateBooleanConverter}}"ToolTipService.ToolTip="{str:StringsExtension Key=Copy}"AutomationProperties.Name="{str:StringsExtension Key=Copy}"Click="CopyButton_Click">@@ -117,6 +128,7 @@<DropDownButtonx:Name="SmartDetectionDropDownButton"x:Load="{x:Bind IsReadOnlyOrCanCopyWhenEditable, Mode=OneWay}"+ IsEnabled="{x:Bind IsLoadingFile, Mode=OneWay, Converter={StaticResource NegateBooleanConverter}}"Padding="{ThemeResource ButtonPadding}"ToolTipService.ToolTip="{str:StringsExtension Key=SendToSmartDetection}"AutomationProperties.Name="{str:StringsExtension Key=SendToSmartDetection}">@@ -148,13 +160,36 @@</DropDownButton></StackPanel>+ <!-- OneWay binding mode on Content property is important so MonacoEditor can be removed from the visual tree when being reclycled --><ContentControl+ x:Name="EditorControl"Grid.Row="1"Grid.ColumnSpan="2"HorizontalAlignment="Stretch"VerticalAlignment="Stretch"HorizontalContentAlignment="Stretch"VerticalContentAlignment="Stretch"- Content="{Binding InnerEditor, ElementName=Root, Mode=OneTime}"/>+ Content="{Binding InnerEditor, ElementName=Root, Mode=OneWay}"+ IsEnabled="{x:Bind IsLoadingFile, Mode=OneWay, Converter={StaticResource NegateBooleanConverter}}"/>++ <Rectangle+ x:Name="DragDropAreaRectangle"+ x:Load="{x:Bind IsDraggingHover, Mode=OneWay}"+ Grid.RowSpan="2"+ Grid.ColumnSpan="2"+ Stroke="{ThemeResource TextControlHeaderForeground}"+ StrokeDashArray="4 4"+ StrokeThickness="2"+ Fill="{ThemeResource ButtonBackgroundPointerOver}"/>++ <ProgressBar+ x:Name="LoadingFileProgressRing"+ x:Load="{x:Bind IsLoadingFile, Mode=OneWay}"+ Grid.Row="1"+ Grid.ColumnSpan="2"+ HorizontalAlignment="Stretch"+ VerticalAlignment="Center"+ Margin="24,0,24,0"+ IsIndeterminate="{x:Bind IsLoadingFile, Mode=OneWay}" /></Grid></UserControl>\ No newline at end of filediff --git a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UITextInputHeader.xaml.cs b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UITextInputHeader.xaml.csindex d9cff6c6c..a7db26721 100644--- a/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UITextInputHeader.xaml.cs+++ b/src/app/dev/DevToys.UI.Framework/Controls/GuiTool/UITextInputHeader.xaml.cs@@ -8,6 +8,7 @@ using Microsoft.UI.Xaml.Automation;using Microsoft.UI.Xaml.Controls;using Microsoft.UI.Xaml.Markup;using Uno.Extensions;+using Windows.ApplicationModel.DataTransfer;using Windows.Storage;using Windows.Storage.Pickers;using Windows.Storage.Provider;@@ -101,6 +102,32 @@ public sealed partial class UITextInputHeader : UserControlset => SetValue(InnerEditorProperty, value);}+ public static readonly DependencyProperty IsDraggingHoverProperty+ = DependencyProperty.Register(+ nameof(IsDraggingHover),+ typeof(bool),+ typeof(UITextInputHeader),+ new PropertyMetadata(false));++ public bool IsDraggingHover+ {+ get => (bool)GetValue(IsDraggingHoverProperty);+ set => SetValue(IsDraggingHoverProperty, value);+ }++ public static readonly DependencyProperty IsLoadingFileProperty+ = DependencyProperty.Register(+ nameof(IsLoadingFile),+ typeof(bool),+ typeof(UITextInputHeader),+ new PropertyMetadata(false));++ public bool IsLoadingFile+ {+ get => (bool)GetValue(IsLoadingFileProperty);+ set => SetValue(IsLoadingFileProperty, value);+ }+private void UITextInputHeader_Loaded(object sender, RoutedEventArgs e){UITextInput.TitleChanged += UITextInput_TitleChanged;@@ -237,37 +264,7 @@ public sealed partial class UITextInputHeader : UserControlStorageFile file = await filePicker.PickSingleFileAsync();if (file is not null){- try- {- await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(CancellationToken.None);-- string? text = await FileIO.ReadTextAsync(file);-- await this.DispatcherQueue.RunOnUIThreadAsync(() =>- {- UITextInput.Text(text);- });- }- catch (Exception ex)- {- LogErrorOpeningFile(ex);-- await this.DispatcherQueue.RunOnUIThreadAsync(async () =>- {- var dialog = new ContentDialog- {- // XamlRoot must be set in the case of a ContentDialog running in a Desktop app- XamlRoot = this.XamlRoot,- Title = ToolPage.UnableOpenFile,- Content = string.Format(ToolPage.UnableOpenFileDescription, file.Name),- CloseButtonText = ToolPage.Ok,- DefaultButton = ContentDialogButton.Close- };-- await dialog.ShowAsync();- });-- }+ await LoadFileAsync(file);}}).ForgetSafely();}@@ -349,9 +346,100 @@ public sealed partial class UITextInputHeader : UserControlParts.Clipboard.SetClipboardTextAsync(UITextInput.Text).ForgetSafely();}- [LoggerMessage(1, LogLevel.Warning, "Unable to open a file in a text input control.")]+ private async void MainPanel_DragOver(object sender, DragEventArgs e)+ {+ DragOperationDeferral? deferral = e.GetDeferral();+ if (e!.DataView.Contains(StandardDataFormats.StorageItems))+ {+ // This line may cause a hang, but we have no choice since we can't afford to make this method async+ // since the parent caller won't be able to see what changed in DragEventArgs since it won't+ // wait for the execution to end.+ IReadOnlyList<IStorageItem>? storageItems = await e.DataView.GetStorageItemsAsync();+ if (storageItems is not null && storageItems.Count == 1 && storageItems[0] is StorageFile)+ {+ e.AcceptedOperation = DataPackageOperation.Copy;+ e.Handled = false;+ }+ }++ IsDraggingHover = true;+ deferral?.Complete();+ }++ private void MainPanel_DragLeave(object sender, DragEventArgs e)+ {+ IsDraggingHover = false;+ }++ private async void MainPanel_Drop(object sender, DragEventArgs e)+ {+ DragOperationDeferral? deferral = e.GetDeferral();+ IsDraggingHover = false;+ if (!e!.DataView.Contains(StandardDataFormats.StorageItems))+ {+ return;+ }++ IReadOnlyList<IStorageItem>? storageItems = await e.DataView.GetStorageItemsAsync();+ if (storageItems is not null && storageItems.Count == 1 && storageItems[0] is StorageFile file)+ {+ LoadFileAsync(file).Forget();+ }+ deferral?.Complete();+ }++ private async Task LoadFileAsync(StorageFile file)+ {+ IsLoadingFile = true;++ try+ {+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(CancellationToken.None);++ LogOpeningFile(new FileInfo(file.Path).Length);++ string? text = await FileIO.ReadTextAsync(file);++ await this.DispatcherQueue.RunOnUIThreadAsync(() =>+ {+ UITextInput.Text(text);++ IsLoadingFile = false;++ if (EditorControl.Content is Control control)+ {+ control.Focus(FocusState.Programmatic);+ }+ });+ }+ catch (Exception ex)+ {+ LogErrorOpeningFile(ex);++ await this.DispatcherQueue.RunOnUIThreadAsync(async () =>+ {+ IsLoadingFile = false;+ var dialog = new ContentDialog+ {+ // XamlRoot must be set in the case of a ContentDialog running in a Desktop app+ XamlRoot = this.XamlRoot,+ Title = ToolPage.UnableOpenFile,+ Content = string.Format(ToolPage.UnableOpenFileDescription, file.Name),+ CloseButtonText = ToolPage.Ok,+ DefaultButton = ContentDialogButton.Close+ };++ await dialog.ShowAsync();+ });+ }+ }++ [LoggerMessage(1, LogLevel.Information, "Loading a file into a text input control. The file size is {fileSize} byte(s).")]+ partial void LogOpeningFile(long fileSize);++ [LoggerMessage(2, LogLevel.Warning, "Unable to open a file in a text input control.")]partial void LogErrorOpeningFile(Exception ex);- [LoggerMessage(2, LogLevel.Warning, "Unable to save a file from a text input control.")]+ [LoggerMessage(3, LogLevel.Warning, "Unable to save a file from a text input control.")]partial void LogErrorSavingFile(Exception ex);}diff --git a/src/app/dev/DevToys.UI.Framework/Controls/IMonacoEditor.cs b/src/app/dev/DevToys.UI.Framework/Controls/IMonacoEditor.csnew file mode 100644index 000000000..9cd956fcd--- /dev/null+++ b/src/app/dev/DevToys.UI.Framework/Controls/IMonacoEditor.cs@@ -0,0 +1,26 @@+using DevToys.Api;+using Microsoft.UI.Xaml.Controls;++namespace DevToys.UI.Framework.Controls;++/// <summary>+/// Represents an instance of the Monaco Editor.+/// </summary>+public interface IMonacoEditor+{+ bool ReadOnly { get; set; }++ string Text { get; set; }++ string? CodeLanguage { get; set; }++ TextSpan SelectedSpan { get; set; }++ Control UIHost { get; }++ event EventHandler TextChanged;++ event EventHandler SelectedSpanChanged;++ Task HighlightSpansAsync(IReadOnlyList<TextSpan> spans);+}diff --git a/src/app/dev/DevToys.UI.Framework/Controls/IMonacoEditorFactory.cs b/src/app/dev/DevToys.UI.Framework/Controls/IMonacoEditorFactory.csnew file mode 100644index 000000000..ce97d66f5--- /dev/null+++ b/src/app/dev/DevToys.UI.Framework/Controls/IMonacoEditorFactory.cs@@ -0,0 +1,9 @@+namespace DevToys.UI.Framework.Controls;++/// <summary>+/// Represents a factory to create an instance of the Monaco Editor.+/// </summary>+public interface IMonacoEditorFactory+{+ IMonacoEditor CreateMonacoEditorInstance();+}diff --git a/src/app/dev/DevToys.UI.Framework/Controls/MonacoEditorPool.cs b/src/app/dev/DevToys.UI.Framework/Controls/MonacoEditorPool.csnew file mode 100644index 000000000..cc0db1c6f--- /dev/null+++ b/src/app/dev/DevToys.UI.Framework/Controls/MonacoEditorPool.cs@@ -0,0 +1,30 @@+using System.Collections.Concurrent;+using DevToys.UI.Framework.Helpers;++namespace DevToys.UI.Framework.Controls;++/// <summary>+/// A pool of <see cref="IMonacoEditor"/>. You can use this class to get a new instance of the Monaco Editor, or a recycled one.+/// </summary>+internal sealed class MonacoEditorPool+{+ private readonly IMonacoEditorFactory _monacoEditorFactory = Parts.MefProvider.Import<IMonacoEditorFactory>();+ private readonly ConcurrentBag<IMonacoEditor> _instances = new ConcurrentBag<IMonacoEditor>();++ public void Recycle(IMonacoEditor item)+ {+ _instances.Add(item);+ }++ public IMonacoEditor Get()+ {+ if (_instances.TryTake(out IMonacoEditor? item) && item is not null)+ {+ return item;+ }+ else+ {+ return _monacoEditorFactory.CreateMonacoEditorInstance();+ }+ }+}diff --git a/src/app/dev/DevToys.UI.Framework/Helpers/Parts.cs b/src/app/dev/DevToys.UI.Framework/Helpers/Parts.csindex 63710985a..b04a59a8b 100644--- a/src/app/dev/DevToys.UI.Framework/Helpers/Parts.cs+++ b/src/app/dev/DevToys.UI.Framework/Helpers/Parts.cs@@ -1,11 +1,16 @@using DevToys.Api;using DevToys.Api.Core;+using DevToys.Api.Core.Theme;namespace DevToys.UI.Framework.Helpers;public static class Parts{- public static ISettingsProvider SettingsProvider { internal get; set; } = null!;+ public static IMefProvider MefProvider { internal get; set; } = null!;- public static IClipboard Clipboard { internal get; set; } = null!;+ public static IThemeListener ThemeListener => MefProvider!.Import<IThemeListener>();++ public static ISettingsProvider SettingsProvider => MefProvider!.Import<ISettingsProvider>();++ public static IClipboard Clipboard => MefProvider!.Import<IClipboard>();}diff --git a/src/app/dev/DevToys.UI/Views/ToolPage.xaml b/src/app/dev/DevToys.UI/Views/ToolPage.xamlindex 57fe10839..0d49a1026 100644--- a/src/app/dev/DevToys.UI/Views/ToolPage.xaml+++ b/src/app/dev/DevToys.UI/Views/ToolPage.xaml@@ -93,6 +93,7 @@</Border><guiTool:UIElementPresenter+ x:Name="RootUIElementPresenter"Grid.Row="1"Grid.Column="0"Grid.ColumnSpan="2"diff --git a/src/app/dev/DevToys.UI/Views/ToolPage.xaml.cs b/src/app/dev/DevToys.UI/Views/ToolPage.xaml.csindex 2daa2259d..3caa42029 100644--- a/src/app/dev/DevToys.UI/Views/ToolPage.xaml.cs+++ b/src/app/dev/DevToys.UI/Views/ToolPage.xaml.cs@@ -23,6 +23,12 @@ public sealed partial class ToolPage : Page, IVisualStateListener/// </summary>internal ToolPageViewModel ViewModel => (ToolPageViewModel)DataContext;+ protected override void OnNavigatedFrom(NavigationEventArgs e)+ {+ base.OnNavigatedFrom(e);+ RootUIElementPresenter.Detach();+ }+protected override void OnNavigatedTo(NavigationEventArgs e){base.OnNavigatedTo(e);diff --git a/src/app/dev/platforms/desktop/DevToys.MauiBlazor/Core/FontProvider/FontProvider.cs b/src/app/dev/platforms/desktop/DevToys.MauiBlazor/Core/FontProvider/FontProvider.csnew file mode 100644index 000000000..d608e8559--- /dev/null+++ b/src/app/dev/platforms/desktop/DevToys.MauiBlazor/Core/FontProvider/FontProvider.cs@@ -0,0 +1,38 @@+using DevToys.Api.Core;+using Microsoft.Extensions.Logging;+using Uno.Extensions;++namespace DevToys.MauiBlazor.Core.FontProvider;++[Export(typeof(IFontProvider))]+internal sealed partial class FontProvider : IFontProvider+{+ private readonly ILogger _logger;++ [ImportingConstructor]+ public FontProvider()+ {+ _logger = this.Log();+ }++ public string[] GetFontFamilies()+ {+ try+ {+#if __MACCATALYST__+ return UIKit.UIFont.FamilyNames;+#else+ return Microsoft.Graphics.Canvas.Text.CanvasTextFormat.GetSystemFontFamilies();+#endif+ }+ catch (Exception ex)+ {+ LogGetFontFamiliesFailed(ex);+ }++ return Array.Empty<string>();+ }++ [LoggerMessage(1, LogLevel.Error, "Failed to retrieve the list of fonts installed on the system.")]+ partial void LogGetFontFamiliesFailed(Exception ex);+}diff --git a/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/Core/FontProvider/FontProvider.cs b/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/Core/FontProvider/FontProvider.csnew file mode 100644index 000000000..c0a8e96b3--- /dev/null+++ b/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/Core/FontProvider/FontProvider.cs@@ -0,0 +1,35 @@+using DevToys.Api.Core;+using Microsoft.Extensions.Logging;+using Microsoft.Graphics.Canvas.Text;+using Uno.Extensions;++namespace DevToys.Wasdk.Core.FontProvider;++[Export(typeof(IFontProvider))]+internal sealed partial class FontProvider : IFontProvider+{+ private readonly ILogger _logger;++ [ImportingConstructor]+ public FontProvider()+ {+ _logger = this.Log();+ }++ public string[] GetFontFamilies()+ {+ try+ {+ return CanvasTextFormat.GetSystemFontFamilies();+ }+ catch (Exception ex)+ {+ LogGetFontFamiliesFailed(ex);+ }++ return Array.Empty<string>();+ }++ [LoggerMessage(1, LogLevel.Error, "Failed to retrieve the list of fonts installed on the system.")]+ partial void LogGetFontFamiliesFailed(Exception ex);+}diff --git a/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/DevToys.Wasdk.csproj b/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/DevToys.Wasdk.csprojindex f19ba3b09..7b48731e6 100644--- a/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/DevToys.Wasdk.csproj+++ b/src/app/dev/platforms/desktop/windows/DevToys.Wasdk/DevToys.Wasdk.csproj@@ -58,6 +58,7 @@<PackageReference Include="Microsoft.Extensions.Logging" /><PackageReference Include="Microsoft.Extensions.Logging.Console" /><PackageReference Include="Microsoft.Extensions.Logging.Debug" />+ <PackageReference Include="Microsoft.Graphics.Win2D" /><PackageReference Include="Microsoft.WindowsAppSDK" /><PackageReference Include="Microsoft.Windows.SDK.BuildTools" /><PackageReference Include="SixLabors.ImageSharp" />diff --git a/src/app/dev/platforms/web/DevToys.Wasm/Core/FontProvider/FontProvider.cs b/src/app/dev/platforms/web/DevToys.Wasm/Core/FontProvider/FontProvider.csnew file mode 100644index 000000000..3e461ce5d--- /dev/null+++ b/src/app/dev/platforms/web/DevToys.Wasm/Core/FontProvider/FontProvider.cs@@ -0,0 +1,13 @@+using DevToys.Api.Core;++namespace DevToys.Wasm.Core.FontProvider;++[Export(typeof(IFontProvider))]+internal sealed class FontProvider : IFontProvider+{+ public string[] GetFontFamilies()+ {+ // TODO+ throw new NotImplementedException();+ }+}diff --git a/src/app/dev/platforms/web/DevToys.Wasm/DevToys.Wasm.csproj b/src/app/dev/platforms/web/DevToys.Wasm/DevToys.Wasm.csprojindex 3368a7455..fa011f05b 100644--- a/src/app/dev/platforms/web/DevToys.Wasm/DevToys.Wasm.csproj+++ b/src/app/dev/platforms/web/DevToys.Wasm/DevToys.Wasm.csproj@@ -29,6 +29,9 @@<ItemGroup><Compile Include="..\..\desktop\windows\DevToys.Wasdk\Core\**\*" Link="Core\%(RecursiveDir)/%(Filename)%(Extension)" /></ItemGroup>+ <ItemGroup>+ <Compile Remove="..\..\desktop\windows\DevToys.Wasdk\Core\FontProvider\FontProvider.cs" />+ </ItemGroup><ItemGroup><EmbeddedResource Include="WasmCSS\Fonts.css" /><EmbeddedResource Include="WasmScripts\AppManifest.js" />@@ -68,22 +71,5 @@<ProjectReference Include="..\..\..\DevToys.UI\DevToys.UI.csproj" /></ItemGroup>- <ItemGroup>- <Compile Update="..\..\desktop\windows\DevToys.Wasdk\Core\Settings\SettingsStorage.cs">- <Link>Core\Settings\\SettingsStorage.cs</Link>- </Compile>- <Compile Update="..\..\desktop\windows\DevToys.Wasdk\Core\Theme\ThemeListener.cs">- <Link>Core\Theme\\ThemeListener.cs</Link>- </Compile>- <Compile Update="..\..\desktop\windows\DevToys.Wasdk\Core\Settings\SettingsStorage.Unpackaged.cs">- <Link>Core\Settings\\SettingsStorage.Unpackaged.cs</Link>- </Compile>- <Compile Update="..\..\desktop\windows\DevToys.Wasdk\Core\Settings\SettingsStorage.Packaged.cs">- <Link>Core\Settings\\SettingsStorage.Packaged.cs</Link>- </Compile>- <Compile Update="..\..\desktop\windows\DevToys.Wasdk\Core\FileStorage\FileStorage.cs">- <Link>Core\FileStorage\\FileStorage.cs</Link>- </Compile>- </ItemGroup><Import Project="$(RepoRoot)\src\app\dev\shared\App.props" /></Project>\ No newline at end of filediff --git a/src/app/dev/shared/App.xaml.cs b/src/app/dev/shared/App.xaml.csindex 45b1199b7..16a632d65 100644--- a/src/app/dev/shared/App.xaml.cs+++ b/src/app/dev/shared/App.xaml.cs@@ -64,7 +64,8 @@ public sealed partial class App : Application{typeof(DevToysToolsResourceManagerAssemblyIdentifier).Assembly,typeof(MainWindow).Assembly,- typeof(MainWindowViewModel).Assembly+ typeof(MainWindowViewModel).Assembly,+ typeof(MonacoEditor.CodeEditor).Assembly});_mefProvider = _mefComposer.Provider;@@ -98,8 +99,9 @@ public sealed partial class App : ApplicationIThemeListener themeListener = _themeListener.Value;- Parts.SettingsProvider = _settingsProvider.Value;- Parts.Clipboard = _mefProvider.Import<IClipboard>();+ Parts.MefProvider = _mefProvider;++ SetDefaultTextEditorFont();#if __WINDOWS__// On Windows 10 version 1607 or later, this code signals that this app wants to participate in prelaunch@@ -178,6 +180,23 @@ public sealed partial class App : Application// Also, use IMarketingService to NotifyAppEncounteredAProblemAsync ?}+ private void SetDefaultTextEditorFont()+ {+ string? currentFontName = _settingsProvider.Value.GetSetting(Api.PredefinedSettings.TextEditorFont); // By default, the value is null.+ string[] systemFontFamilies = _mefProvider.Import<IFontProvider>().GetFontFamilies();+ if (!systemFontFamilies.Contains(currentFontName))+ {+ for (int i = 0; i < Api.PredefinedSettings.DefaultFonts.Length; i++)+ {+ if (systemFontFamilies.Contains(Api.PredefinedSettings.DefaultFonts[i]))+ {+ _settingsProvider.Value.SetSetting(Api.PredefinedSettings.TextEditorFont, Api.PredefinedSettings.DefaultFonts[i]);+ return;+ }+ }+ }+ }+/// <summary>/// Configures global Uno Platform logging/// </summary>