A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Improved Monaco editor loading time
Etienne Baudouxac1c1b2e102d
diff --git a/src/app/dev/DevToys.Core/Threading/DisposableSemaphore.cs b/src/app/dev/DevToys.Api/Core/Threading/DisposableSemaphore.cssimilarity index 97%rename from src/app/dev/DevToys.Core/Threading/DisposableSemaphore.csrename to src/app/dev/DevToys.Api/Core/Threading/DisposableSemaphore.csindex e4ee9d839..b9aaac4a6 100644--- a/src/app/dev/DevToys.Core/Threading/DisposableSemaphore.cs+++ b/src/app/dev/DevToys.Api/Core/Threading/DisposableSemaphore.cs@@ -1,4 +1,4 @@-namespace DevToys.Core.Threading;+namespace DevToys.Api;/// <summary>/// Represents a semaphore that free other threads when disposing the result of the <see cref="WaitAsync(CancellationToken)"/> method..diff --git a/src/app/dev/DevToys.Core/Threading/TaskExtensions.cs b/src/app/dev/DevToys.Api/Core/Threading/TaskExtensions.cssimilarity index 96%rename from src/app/dev/DevToys.Core/Threading/TaskExtensions.csrename to src/app/dev/DevToys.Api/Core/Threading/TaskExtensions.csindex 4831d6fcb..d5147362e 100644--- a/src/app/dev/DevToys.Core/Threading/TaskExtensions.cs+++ b/src/app/dev/DevToys.Api/Core/Threading/TaskExtensions.cs@@ -1,4 +1,6 @@-namespace DevToys.Core.Threading;+using System.Threading;++namespace DevToys.Api;/// <summary>/// Provides a set of helper method to play around with threads.diff --git a/src/app/dev/DevToys.Api/Core/Threading/TaskSchedulerAwaiter.cs b/src/app/dev/DevToys.Api/Core/Threading/TaskSchedulerAwaiter.csnew file mode 100644index 000000000..4c23a4a50--- /dev/null+++ b/src/app/dev/DevToys.Api/Core/Threading/TaskSchedulerAwaiter.cs@@ -0,0 +1,119 @@+using System.Runtime.CompilerServices;++namespace DevToys.Api;++/// <summary>+/// An awaiter returned from <see cref="GetAwaiter(TaskScheduler)"/>.+/// </summary>+public readonly struct TaskSchedulerAwaiter : ICriticalNotifyCompletion+{+ public static TaskSchedulerAwaiter SwitchOffMainThreadAsync(CancellationToken cancellationToken)+ {+ cancellationToken.ThrowIfCancellationRequested();+ return new TaskSchedulerAwaiter(+ SynchronizationContext.Current != null ? TaskScheduler.Default : TaskScheduler.Current,+ cancellationToken);+ }++ /// <summary>+ /// The scheduler for continuations.+ /// </summary>+ private readonly TaskScheduler _scheduler;++ /// <summary>+ /// A value indicating whether <see cref="IsCompleted"/>+ /// should always return false.+ /// </summary>+ private readonly bool _alwaysYield;++ private readonly CancellationToken _cancellationToken;++ /// <summary>+ /// Initializes a new instance of the <see cref="TaskSchedulerAwaiter"/> struct.+ /// </summary>+ /// <param name="scheduler">The scheduler for continuations.</param>+ /// <param name="alwaysYield">A value indicating whether the caller should yield even if+ /// already executing on the desired task scheduler.</param>+ public TaskSchedulerAwaiter(TaskScheduler scheduler, CancellationToken cancellationToken, bool alwaysYield = false)+ {+ _scheduler = scheduler;+ _cancellationToken = cancellationToken;+ _alwaysYield = alwaysYield;+ }++ /// <summary>+ /// Gets the <see cref="TaskSchedulerAwaiter"/>.+ /// </summary>+ /// <returns>+ /// Returns this instance.+ /// </returns>+ public TaskSchedulerAwaiter GetAwaiter()+ {+ return this;+ }++ /// <summary>+ /// Gets a value indicating whether no yield is necessary.+ /// </summary>+ /// <value><c>true</c> if the caller is already running on that TaskScheduler.</value>+ public bool IsCompleted+ {+ get+ {+ if (_alwaysYield)+ {+ return false;+ }++ // We special case the TaskScheduler.Default since that is semantically equivalent to being+ // on a ThreadPool thread, and there are various ways to get on those threads.+ // TaskScheduler.Current is never null. Even if no scheduler is really active and the current+ // thread is not a threadpool thread, TaskScheduler.Current == TaskScheduler.Default, so we have+ // to protect against that case too.+ bool isThreadPoolThread = Thread.CurrentThread.IsThreadPoolThread;+ return (_scheduler == TaskScheduler.Default && isThreadPoolThread)+ || (_scheduler == TaskScheduler.Current && TaskScheduler.Current != TaskScheduler.Default);+ }+ }++ /// <summary>+ /// Schedules a continuation to execute using the specified task scheduler.+ /// </summary>+ /// <param name="continuation">The delegate to invoke.</param>+ public void OnCompleted(Action continuation)+ {+ if (_scheduler == TaskScheduler.Default)+ {+ ThreadPool.QueueUserWorkItem(state => ((Action)state!)(), continuation);+ }+ else+ {+ Task.Factory.StartNew(continuation, CancellationToken.None, TaskCreationOptions.None, _scheduler).Forget();+ }+ }++ /// <summary>+ /// Schedules a continuation to execute using the specified task scheduler+ /// without capturing the ExecutionContext.+ /// </summary>+ /// <param name="continuation">The action.</param>+ public void UnsafeOnCompleted(Action continuation)+ {+ if (_scheduler == TaskScheduler.Default)+ {+ ThreadPool.UnsafeQueueUserWorkItem(state => ((Action)state!)(), continuation);+ }+ else+ {+ Task.Factory.StartNew(continuation, CancellationToken.None, TaskCreationOptions.None, _scheduler).Forget();+ }+ }++ /// <summary>+ /// Does nothing.+ /// </summary>+ public void GetResult()+ {+ _cancellationToken.ThrowIfCancellationRequested();+ }+}diff --git a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.cs b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.csindex d7d0df5c4..2efafd5c8 100644--- a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.cs+++ b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditor.cs@@ -1,6 +1,6 @@using System.Reflection;using System.Runtime.CompilerServices;-using DevToys.Core.Threading;+using DevToys.Api;using DevToys.MonacoEditor.Extensions;using DevToys.MonacoEditor.Monaco;using DevToys.MonacoEditor.Monaco.Editor;@@ -52,6 +52,7 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDispprivate ICodeEditorPresenter? _view;private int _focusCount;private bool _initialized;+ private bool _refrainFromUpdatingOptionsInternally;private ModelHelper? _model;public CodeEditor()@@ -572,7 +573,10 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisp}}- InvokeScriptAsync("updateOptions", options).Forget();+ if (!_refrainFromUpdatingOptionsInternally)+ {+ InvokeScriptAsync("updateOptions", options).Forget();+ }}private void DiffOptions_PropertyChanged(object? sender, PropertyChangedEventArgs e)@@ -590,14 +594,16 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisp}}- InvokeScriptAsync("updateDiffOptions", options).Forget();+ if (!_refrainFromUpdatingOptionsInternally)+ {+ InvokeScriptAsync("updateDiffOptions", options).Forget();+ }}private void ActualTheme_PropertyChanged(DependencyObject obj, DependencyProperty property){ElementTheme theme = ActualTheme;- string themeName = string.Empty;-+ string themeName;if (theme == ElementTheme.Default){themeName = _themeListener.CurrentThemeName;@@ -607,22 +613,16 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDispthemeName = theme.ToString();}- UIAccess.RunOnUIThreadAsync(async () =>- {- await InvokeScriptAsync("setTheme", args: new string[] { _themeListener!.AccentColorHtmlHex });- await InvokeScriptAsync("changeTheme", new string[] { themeName, _themeListener.IsHighContrast.ToString() });- }).Forget();+ InvokeScriptAsync("setTheme", args: new string[] { _themeListener!.AccentColorHtmlHex }).Forget();+ InvokeScriptAsync("changeTheme", new string[] { themeName, _themeListener.IsHighContrast.ToString() }).Forget();}private void ThemeListener_ThemeChanged(ThemeListener sender){if (RequestedTheme == ElementTheme.Default){- UIAccess.RunOnUIThreadAsync(async () =>- {- await InvokeScriptAsync("setTheme", args: new string[] { sender.AccentColorHtmlHex });- await InvokeScriptAsync("changeTheme", args: new string[] { sender.CurrentTheme.ToString(), sender.IsHighContrast.ToString() });- }).Forget();+ InvokeScriptAsync("setTheme", args: new string[] { sender.AccentColorHtmlHex }).Forget();+ InvokeScriptAsync("changeTheme", args: new string[] { sender.CurrentTheme.ToString(), sender.IsHighContrast.ToString() }).Forget();}}@@ -694,6 +694,8 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDisp.Forget();// Update options.+ _refrainFromUpdatingOptionsInternally = true;+Options.SmoothScrolling = true;Options.Minimap = new EditorMinimapOptions() { Enabled = false };Options.ReadOnly = ReadOnly;@@ -701,6 +703,16 @@ public sealed partial class CodeEditor : Control, IParentAccessorAcceptor, IDispDiffOptions.OriginalEditable = !ReadOnly;DiffOptions.ReadOnly = ReadOnly;+ _refrainFromUpdatingOptionsInternally = false;+ if (IsDiffViewMode)+ {+ InvokeScriptAsync("updateDiffOptions", DiffOptions).Forget();+ }+ else+ {+ InvokeScriptAsync("updateOptions", Options).Forget();+ }+// We're done loading Monaco Editor.IsEditorLoaded = true;EditorLoaded?.Invoke(this, new RoutedEventArgs());diff --git a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Wasm.cs b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Wasm.csindex 65dc1ca35..96c5d51f6 100644--- a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Wasm.cs+++ b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Wasm.cs@@ -1,12 +1,10 @@#if __WASM__using System.Reflection;-using System.Xml.Linq;-using DevToys.Core.Threading;+using DevToys.Api;using DevToys.UI.Framework.Threading;using Microsoft.Extensions.Logging;using Microsoft.UI;-using Microsoft.UI.Dispatching;using Microsoft.UI.Xaml;using Microsoft.UI.Xaml.Controls;using Microsoft.UI.Xaml.Media;@@ -75,13 +73,12 @@ public sealed partial class CodeEditorPresenter : Control, ICodeEditorPresenter,public async Task LaunchAsync(){- await DispatcherQueue.RunOnUIThreadAsync(- DispatcherQueuePriority.Low,- () => NavigationStarting?.Invoke(this, new CoreWebView2NavigationStartingEventArgs()));+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(CancellationToken.None);- await DispatcherQueue.RunOnUIThreadAsync(- DispatcherQueuePriority.Low,- () => DOMContentLoaded?.Invoke(this, new CoreWebView2DOMContentLoadedEventArgs()));+ _informationLogger?.Info($"{nameof(LaunchAsync)}: Startup");++ NavigationStarting?.Invoke(this, new CoreWebView2NavigationStartingEventArgs());+ DOMContentLoaded?.Invoke(this, new CoreWebView2DOMContentLoadedEventArgs());// Request to inject .NET web object into the web page.Guard.IsNotNull(DotNetObjectInjectionRequested);@@ -101,13 +98,13 @@ public sealed partial class CodeEditorPresenter : Control, ICodeEditorPresenter,_errorLogger?.Error($"{nameof(LaunchAsync)} failed", e);}- await DispatcherQueue.RunOnUIThreadAsync(- DispatcherQueuePriority.Low,- () => NavigationCompleted?.Invoke(this, new CoreWebView2NavigationCompletedEventArgs()));+ NavigationCompleted?.Invoke(this, new CoreWebView2NavigationCompletedEventArgs());}- public Task InjectDotNetObjectToWebPageAsync<T>(string name, T pObject)+ public async Task InjectDotNetObjectToWebPageAsync<T>(string name, T pObject){+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(CancellationToken.None);+_debugLogger?.Debug($"{nameof(InjectDotNetObjectToWebPageAsync)}: Trying to inject .NET object in web page - {name}");if (pObject is IJSObject obj){@@ -115,7 +112,7 @@ public sealed partial class CodeEditorPresenter : Control, ICodeEditorPresenter,if (method is null){_errorLogger?.Error($"{nameof(InjectDotNetObjectToWebPageAsync)}: GetNativeInstance method doesn't exist.");- return Task.CompletedTask;+ return;}string? native = method.Invoke(obj.Handle, Array.Empty<object>()) as string;@@ -144,12 +141,12 @@ public sealed partial class CodeEditorPresenter : Control, ICodeEditorPresenter,_errorLogger?.Error($"{nameof(InjectDotNetObjectToWebPageAsync)}: '{name}' is not a JSObject");throw new InvalidOperationException($"{nameof(InjectDotNetObjectToWebPageAsync)}: '{name}' is not a JSObject");}-- return Task.CompletedTask;}- public Task<string> InvokeScriptAsync(string script)+ public async Task<string> InvokeScriptAsync(string script){+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(CancellationToken.None);+script = $@"(function() {{try {{@@ -179,13 +176,13 @@ public sealed partial class CodeEditorPresenter : Control, ICodeEditorPresenter,_debugLogger?.Debug($"Invoke Script result: {result}");- return Task.FromResult(result);+ return result;}catch (Exception e){_errorLogger?.Error("Invoke Script failed", e);- return Task.FromResult(string.Empty);+ return string.Empty;}}}diff --git a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Windows.cs b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Windows.csindex 5d88215d1..aeee1f01b 100644--- a/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Windows.cs+++ b/src/app/dev/DevToys.MonacoEditor/CodeEditor/CodeEditorPresenter.Windows.cs@@ -11,7 +11,6 @@ using Uno.Extensions;using Uno.Logging;using Windows.Foundation;using Windows.Storage;-using Windows.UI;using Windows.UI.Core;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;@@ -372,7 +371,13 @@ public sealed partial class CodeEditorPresenter : UserControl, ICodeEditorPresentry{- string result = await _webView.ExecuteScriptAsync(script);+ string result+ = await DispatcherQueue.RunOnUIThreadAsync(+ CoreDispatcherPriority.High,+ async () =>+ {+ return await _webView.ExecuteScriptAsync(script);+ });_debugLogger?.Debug($"Invoke Script result: {result}");@@ -382,7 +387,7 @@ public sealed partial class CodeEditorPresenter : UserControl, ICodeEditorPresen{_errorLogger?.Error("Invoke Script failed", e);- return string.Empty;+ throw;}}diff --git a/src/app/dev/DevToys.MonacoEditor/DevToys.MonacoEditor.csproj b/src/app/dev/DevToys.MonacoEditor/DevToys.MonacoEditor.csprojindex 8527c32fa..280248bc1 100644--- a/src/app/dev/DevToys.MonacoEditor/DevToys.MonacoEditor.csproj+++ b/src/app/dev/DevToys.MonacoEditor/DevToys.MonacoEditor.csproj@@ -143,6 +143,7 @@</Choose><ItemGroup>+ <ProjectReference Include="..\DevToys.Api\DevToys.Api.csproj" /><ProjectReference Include="..\DevToys.Core\DevToys.Core.csproj" /><ProjectReference Include="..\DevToys.UI.Framework\DevToys.UI.Framework.csproj" /></ItemGroup>diff --git a/src/app/dev/DevToys.MonacoEditor/Extensions/ICodeEditorPresenterExtensions.cs b/src/app/dev/DevToys.MonacoEditor/Extensions/ICodeEditorPresenterExtensions.csindex f30fda0a2..7331c858f 100644--- a/src/app/dev/DevToys.MonacoEditor/Extensions/ICodeEditorPresenterExtensions.cs+++ b/src/app/dev/DevToys.MonacoEditor/Extensions/ICodeEditorPresenterExtensions.cs@@ -37,30 +37,13 @@ internal static class ICodeEditorPresenterExtensionsstring fullscript = start +"\n} catch (err) { return JSON.stringify({ wv_internal_error: true, message: err.message, description: err.description, number: err.number, stack: err.stack }); }";- if (view.DispatcherQueue.HasThreadAccess)+ try{- try- {- return await RunScriptHelperAsync<T>(view, fullscript);- }- catch (Exception e)- {- throw new JavaScriptExecutionException(member, file, line, script, e);- }+ return await RunScriptHelperAsync<T>(view, fullscript);}- else+ catch (Exception e){- return await view.DispatcherQueue.RunOnUIThreadAsync(async () =>- {- try- {- return await RunScriptHelperAsync<T>(view, fullscript);- }- catch (Exception e)- {- throw new JavaScriptExecutionException(member, file, line, script, e);- }- });+ throw new JavaScriptExecutionException(member, file, line, script, e);}}diff --git a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.ts b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.tsindex f84fbc9a2..8850f2eb7 100644--- a/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.ts+++ b/src/app/dev/DevToys.MonacoEditor/ts-helpermethods/otherScriptsToBeOrganized.ts@@ -158,8 +158,6 @@ var setTheme = function (editorContext: EditorContext, accentColor: string) {// remove quotes.accentColor = accentColor.replace(/"/g, '');- editorContext.Debug.log(accentColor);-monaco.editor.defineTheme('devtoys-dark', {base: 'vs-dark',inherit: true,diff --git a/src/app/dev/DevToys.UI.EntryPoint/App.xaml.cs b/src/app/dev/DevToys.UI.EntryPoint/App.xaml.csindex 9b0ffc30c..c911e9a74 100644--- a/src/app/dev/DevToys.UI.EntryPoint/App.xaml.cs+++ b/src/app/dev/DevToys.UI.EntryPoint/App.xaml.cs@@ -144,7 +144,7 @@ public sealed partial class App : Application//// For more performance documentation: https://platform.uno/docs/articles/Uno-UI-Performance.html- ILoggerFactory factory = LoggerFactory.Create(builder =>+ ILoggerFactory factory = LoggerFactory.Create((ILoggingBuilder builder) =>{#if __WASM__builder.AddProvider(new global::Uno.Extensions.Logging.WebAssembly.WebAssemblyConsoleLoggerProvider());