A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Added theme support, thread helpers and titlebar customization
Etienne Baudoux2231f8780254
diff --git a/src/Directory.Build.props b/src/Directory.Build.propsindex 707f51e77..08ffb3b4d 100644--- a/src/Directory.Build.props+++ b/src/Directory.Build.props@@ -5,7 +5,7 @@<Platform Condition=" '$(Platform)' == '' ">x64</Platform><Windows10SDKVersion>10.0.19041.0</Windows10SDKVersion>- <Windows10MinSDKVersion>10.0.16299.0</Windows10MinSDKVersion>+ <Windows10MinSDKVersion>10.0.18362.0</Windows10MinSDKVersion><LangVersion>latest</LangVersion><Nullable>enable</Nullable>diff --git a/src/dev/def/DevTools.Core/Arguments.cs b/src/dev/def/DevTools.Core/Arguments.csnew file mode 100644index 000000000..b1b865c58--- /dev/null+++ b/src/dev/def/DevTools.Core/Arguments.cs@@ -0,0 +1,37 @@+using System;++namespace DevTools.Core+{+ public static class Arguments+ {+ public static T NotNull<T>(T? value, string argumentName)+ {+ if (value == null)+ {+ throw new ArgumentNullException(argumentName);+ }++ return value;+ }++ public static string NotNullOrEmpty(string? value, string argumentName)+ {+ if (string.IsNullOrEmpty(value))+ {+ throw new ArgumentNullException(argumentName);+ }++ return value!;+ }++ public static string NotNullOrWhiteSpace(string? value, string argumentName)+ {+ if (string.IsNullOrWhiteSpace(value))+ {+ throw new ArgumentNullException(argumentName);+ }++ return value!;+ }+ }+}diff --git a/src/dev/def/DevTools.Core/ITitleBar.cs b/src/dev/def/DevTools.Core/ITitleBar.csnew file mode 100644index 000000000..51fe09d3f--- /dev/null+++ b/src/dev/def/DevTools.Core/ITitleBar.cs@@ -0,0 +1,15 @@+using System.Threading.Tasks;++namespace DevTools.Core+{+ /// <summary>+ /// Provides a service designed to manager the window title bar.+ /// </summary>+ public interface ITitleBar+ {+ /// <summary>+ /// Initialize the states of the title bar.+ /// </summary>+ Task SetupTitleBarAsync();+ }+}diff --git a/src/dev/def/DevTools.Core/Settings/PredefinedSettings.cs b/src/dev/def/DevTools.Core/Settings/PredefinedSettings.csnew file mode 100644index 000000000..1dc949704--- /dev/null+++ b/src/dev/def/DevTools.Core/Settings/PredefinedSettings.cs@@ -0,0 +1,16 @@+using DevTools.Core.Theme;++namespace DevTools.Core.Settings+{+ public static class PredefinedSettings+ {+ /// <summary>+ /// The color theme of the application.+ /// </summary>+ public static readonly SettingDefinition<AppTheme> Theme+ = new(+ name: nameof(Theme),+ isRoaming: false,+ defaultValue: AppTheme.Default);+ }+}diff --git a/src/dev/def/DevTools.Core/Theme/AppTheme.cs b/src/dev/def/DevTools.Core/Theme/AppTheme.csnew file mode 100644index 000000000..25690d3b9--- /dev/null+++ b/src/dev/def/DevTools.Core/Theme/AppTheme.cs@@ -0,0 +1,23 @@+namespace DevTools.Core.Theme+{+ /// <summary>+ /// Specifies a UI theme that should be used for individual UIElement parts of an app UI.+ /// </summary>+ public enum AppTheme+ {+ /// <summary>+ /// Use the Application.RequestedTheme value for the element. This is the default.+ /// </summary>+ Default,++ /// <summary>+ /// Use the **Light** default theme.+ /// </summary>+ Light,++ /// <summary>+ /// Use the **Dark** default theme.+ /// </summary>+ Dark+ }+}diff --git a/src/dev/def/DevTools.Core/Theme/IThemeListener.cs b/src/dev/def/DevTools.Core/Theme/IThemeListener.csnew file mode 100644index 000000000..3917c9723--- /dev/null+++ b/src/dev/def/DevTools.Core/Theme/IThemeListener.cs@@ -0,0 +1,22 @@+using System;++namespace DevTools.Core.Theme+{+ public interface IThemeListener+ {+ /// <summary>+ /// Gets the current theme.+ /// </summary>+ AppTheme CurrentTheme { get; }++ /// <summary>+ /// Gets or sets a value indicating whether the current theme is high contrast.+ /// </summary>+ bool IsHighContrast { get; }++ /// <summary>+ /// Raised when the theme has changed.+ /// </summary>+ event EventHandler? ThemeChanged;+ }+}diff --git a/src/dev/def/DevTools.Core/Threading/DisposableSempahore.cs b/src/dev/def/DevTools.Core/Threading/DisposableSempahore.csnew file mode 100644index 000000000..4327ef545--- /dev/null+++ b/src/dev/def/DevTools.Core/Threading/DisposableSempahore.cs@@ -0,0 +1,58 @@+using System;+using System.Threading;+using System.Threading.Tasks;++namespace DevTools.Core.Threading+{+ /// <summary>+ /// Represents a semaphore that free other threads when disposing the result of the <see cref="WaitAsync(CancellationToken)"/> method..+ /// </summary>+ public sealed class DisposableSempahore : IDisposable+ {+ private readonly object _lockObject = new();+ private readonly SemaphoreSlim _semaphore;++ public bool Disposed { get; private set; }++ public bool IsBusy => _semaphore.CurrentCount == 0;++ public DisposableSempahore(int maxTasksCount = 1)+ {+ _semaphore = new SemaphoreSlim(maxTasksCount, maxTasksCount);+ }++ public void Dispose()+ {+ lock (_lockObject)+ {+ if (!Disposed)+ {+ Disposed = true;+ _semaphore.Dispose();+ }+ }+ }++ public async Task<IDisposable> WaitAsync(CancellationToken cancellationToken)+ {+ await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);++ return new DummyDisposable(_semaphore);+ }++ private sealed class DummyDisposable : IDisposable+ {+ private readonly SemaphoreSlim _semaphore;++ public DummyDisposable(SemaphoreSlim semaphore)+ {+ _semaphore = semaphore;+ }++ public void Dispose()+ {+ _semaphore.Release();+ }+ }+ }+}diff --git a/src/dev/def/DevTools.Core/Threading/IThread.cs b/src/dev/def/DevTools.Core/Threading/IThread.csnew file mode 100644index 000000000..3b16205dc--- /dev/null+++ b/src/dev/def/DevTools.Core/Threading/IThread.cs@@ -0,0 +1,42 @@+using System;+using System.Threading.Tasks;++namespace DevTools.Core.Threading+{+ /// <summary>+ /// Provides a set of methods to play around with threads.+ /// </summary>+ public interface IThread+ {+ /// <summary>+ /// Throws an exception if the current thread isn't the UI thread.+ /// </summary>+ void ThrowIfNotOnUIThread();++ /// <summary>+ /// Throws an exception if the current thread is the UI thread.+ /// </summary>+ void ThrowIfOnUIThread();++ /// <summary>+ /// Runs a given action on the UI thread and wait for its result asynchronously.+ /// </summary>+ /// <param name="action">Action to run on the UI thread.</param>+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>+ Task RunOnUIThreadAsync(Action action);++ /// <summary>+ /// Runs a given action on the UI thread and wait for its result asynchronously.+ /// </summary>+ /// <param name="action">Action to run on the UI thread.</param>+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>+ Task RunOnUIThreadAsync(Func<Task> action);++ /// <summary>+ /// Runs a given action on the UI thread and wait for its result asynchronously.+ /// </summary>+ /// <param name="action">Action to run on the UI thread.</param>+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>+ Task<T> RunOnUIThreadAsync<T>(Func<Task<T>> action);+ }+}diff --git a/src/dev/def/DevTools.Core/Threading/TaskCompletionNotifier.cs b/src/dev/def/DevTools.Core/Threading/TaskCompletionNotifier.csnew file mode 100644index 000000000..3c9136da1--- /dev/null+++ b/src/dev/def/DevTools.Core/Threading/TaskCompletionNotifier.cs@@ -0,0 +1,96 @@+using System.ComponentModel;+using System.Threading;+using System.Threading.Tasks;++namespace DevTools.Core.Threading+{+ /// <summary>+ /// Watches a task and raises property-changed notifications when the task completes.+ /// </summary>+ /// <typeparam name="TResult">The type of the result of the task.</typeparam>+ public sealed class TaskCompletionNotifier<TResult> : INotifyPropertyChanged+ {+ /// <summary>+ /// Gets the task being watched. This property never changes and is never <c>null</c>.+ /// </summary>+ public Task<TResult?>? Task { get; private set; }++ /// <summary>+ /// Gets the result of the task. Returns the default value of TResult if the task has not completed successfully.+ /// </summary>+ public TResult? Result => (Task != null && Task.Status == TaskStatus.RanToCompletion) ? Task.Result : default(TResult);++ /// <summary>+ /// Gets whether the task has completed.+ /// </summary>+ public bool IsCompleted => Task == null || Task.IsCompleted;++ /// <summary>+ /// Gets whether the task has completed successfully.+ /// </summary>+ public bool IsSuccessfullyCompleted => Task == null || Task.Status == TaskStatus.RanToCompletion;++ /// <summary>+ /// Gets whether the task has been canceled.+ /// </summary>+ public bool IsCanceled => Task != null && Task.IsCanceled;++ /// <summary>+ /// Gets whether the task has faulted.+ /// </summary>+ public bool IsFaulted => Task != null && Task.IsFaulted;++ /// <summary>+ /// Occurs when a property value changes.+ /// </summary>+ public event PropertyChangedEventHandler? PropertyChanged;++ /// <summary>+ /// Initialize a new instance of the <see cref="TaskCompletionNotifier{TResult}"/> class.+ /// </summary>+ /// <param name="task">The <see cref="Task"/> to run.</param>+ public TaskCompletionNotifier(Task<TResult?>? task)+ {+ try+ {+ Task = task;+ if (task != null && !task.IsCompleted)+ {+ var scheduler = (SynchronizationContext.Current == null) ? TaskScheduler.Current : TaskScheduler.FromCurrentSynchronizationContext();++ task+ .ContinueWith(+ t =>+ {+ var propertyChanged = PropertyChanged;+ if (propertyChanged != null)+ {+ propertyChanged(this, new PropertyChangedEventArgs(nameof(IsCompleted)));+ if (t.IsCanceled)+ {+ propertyChanged(this, new PropertyChangedEventArgs(nameof(IsCanceled)));+ }+ else if (t.IsFaulted)+ {+ propertyChanged(this, new PropertyChangedEventArgs(nameof(IsFaulted)));+ }+ else+ {+ propertyChanged(this, new PropertyChangedEventArgs(nameof(IsSuccessfullyCompleted)));+ propertyChanged(this, new PropertyChangedEventArgs(nameof(Result)));+ }+ }+ },+ CancellationToken.None,+ TaskContinuationOptions.ExecuteSynchronously,+ scheduler)+ .Forget();+ }+ }+ catch+ {+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsFaulted)));+ }+ }+ }+}diff --git a/src/dev/def/DevTools.Core/Threading/TaskExtension.cs b/src/dev/def/DevTools.Core/Threading/TaskExtension.csnew file mode 100644index 000000000..d6ba7b2c4--- /dev/null+++ b/src/dev/def/DevTools.Core/Threading/TaskExtension.cs@@ -0,0 +1,56 @@+using System;+using System.Diagnostics;+using System.Threading.Tasks;++namespace DevTools.Core.Threading+{+ /// <summary>+ /// Provides a set of helper method to play around with threads.+ /// </summary>+ public static class TaskExtension+ {+ /// <summary>+ /// Runs a task without waiting for its result.+ /// </summary>+ public static void Forget(this Task _)+ {+ }++ /// <summary>+ /// Runs a task without waiting for its result.+ /// </summary>+ public static void Forget<T>(this Task<T> _)+ {+ }++ /// <summary>+ /// Runs a task without waiting for its result. Swallows or handle any exception caused by the task.+ /// </summary>+ /// <param name="errorHandler">The action to run when an exception is caught.</param>+ public static async void ForgetSafely(this Task task, Action<Exception>? errorHandler = null)+ {+ try+ {+ await task.ConfigureAwait(true);+ }+ catch (Exception ex)+ {+ errorHandler?.Invoke(ex);+#if DEBUG+ Debugger.Launch();+#endif+ }+ }++ /// <summary>+ /// Gets an awaiter that schedules continuations on the specified scheduler.+ /// </summary>+ /// <param name="scheduler">The task scheduler used to execute continuations.</param>+ /// <returns>An awaitable.</returns>+ public static TaskSchedulerAwaiter GetAwaiter(this TaskScheduler scheduler)+ {+ Arguments.NotNull(scheduler, nameof(scheduler));+ return new TaskSchedulerAwaiter(scheduler);+ }+ }+}diff --git a/src/dev/def/DevTools.Core/Threading/TaskSchedulerAwaiter.cs b/src/dev/def/DevTools.Core/Threading/TaskSchedulerAwaiter.csnew file mode 100644index 000000000..ecd98f085--- /dev/null+++ b/src/dev/def/DevTools.Core/Threading/TaskSchedulerAwaiter.cs@@ -0,0 +1,100 @@+using System;+using System.Runtime.CompilerServices;+using System.Threading;+using System.Threading.Tasks;++namespace DevTools.Core.Threading+{+ /// <summary>+ /// An awaiter returned from <see cref="GetAwaiter(TaskScheduler)"/>.+ /// </summary>+ public readonly struct TaskSchedulerAwaiter : ICriticalNotifyCompletion+ {+ /// <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;++ /// <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, bool alwaysYield = false)+ {+ _scheduler = scheduler;+ _alwaysYield = alwaysYield;+ }++ /// <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()+ {+ }+ }+}diff --git a/src/dev/impl/DevTools.Core.Impl/DevTools.Core.Impl.csproj b/src/dev/impl/DevTools.Core.Impl/DevTools.Core.Impl.csprojindex 46fd99e9c..4165ef7ac 100644--- a/src/dev/impl/DevTools.Core.Impl/DevTools.Core.Impl.csproj+++ b/src/dev/impl/DevTools.Core.Impl/DevTools.Core.Impl.csproj@@ -7,7 +7,7 @@<AppDesignerFolder>Properties</AppDesignerFolder><RootNamespace>DevTools.Core.Impl</RootNamespace><AssemblyName>DevTools.Core.Impl</AssemblyName>- <DefaultLanguage>en-US</DefaultLanguage>+ <DefaultLanguage>en</DefaultLanguage><TargetPlatformIdentifier>UAP</TargetPlatformIdentifier><TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">$(Windows10SDKVersion)</TargetPlatformVersion><TargetPlatformMinVersion>$(Windows10MinSDKVersion)</TargetPlatformMinVersion>@@ -77,6 +77,9 @@<Compile Include="Injection\MefProvider.cs" /><Compile Include="Properties\AssemblyInfo.cs" /><Compile Include="Settings\SettingsProvider.cs" />+ <Compile Include="Theme\ThemeListener.cs" />+ <Compile Include="Threading\Thread.cs" />+ <Compile Include="TitleBar.cs" /></ItemGroup><ItemGroup><PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform" Version="$(NuGet_MicrosoftNETCoreUniversalWindowsPlatform)" />diff --git a/src/dev/impl/DevTools.Core.Impl/Theme/ThemeListener.cs b/src/dev/impl/DevTools.Core.Impl/Theme/ThemeListener.csnew file mode 100644index 000000000..e95cb2d6b--- /dev/null+++ b/src/dev/impl/DevTools.Core.Impl/Theme/ThemeListener.cs@@ -0,0 +1,96 @@+#nullable enable++using DevTools.Core.Theme;+using DevTools.Core.Threading;+using System;+using System.Composition;+using Windows.UI.ViewManagement;+using Windows.UI.Xaml;++namespace DevTools.Core.Impl.Theme+{+ [Export(typeof(IThemeListener))]+ [Shared]+ internal sealed class ThemeListener : IThemeListener+ {+ private readonly AccessibilitySettings _accessible = new();+ private readonly UISettings _uiSettings = new();+ private readonly IThread _thread;++ public AppTheme CurrentTheme { get; private set; }++ public bool IsHighContrast { get; private set; }++ public event EventHandler? ThemeChanged;++ [ImportingConstructor]+ public ThemeListener(IThread thread)+ {+ _thread = thread;++ CurrentTheme = Application.Current.RequestedTheme == ApplicationTheme.Dark ? AppTheme.Dark : AppTheme.Light;+ IsHighContrast = _accessible.HighContrast;++ _accessible.HighContrastChanged += Accessible_HighContrastChanged;+ _uiSettings.ColorValuesChanged += UiSettings_ColorValuesChanged;++ if (Window.Current != null)+ {+ Window.Current.CoreWindow.Activated += CoreWindow_Activated;+ }+ }++ private void Accessible_HighContrastChanged(AccessibilitySettings sender, object args)+ {+ _thread.RunOnUIThreadAsync(UpdateProperties).Forget();+ }++ private void UiSettings_ColorValuesChanged(UISettings sender, object args)+ {+ // Note: This can get called multiple times during HighContrast switch, do we care?+ _thread.RunOnUIThreadAsync(+ () =>+ {+ // TODO: This doesn't stop the multiple calls if we're in our faked 'White' HighContrast Mode below.+ AppTheme currentAppTheme = Application.Current.RequestedTheme == ApplicationTheme.Dark ? AppTheme.Dark : AppTheme.Light;+ if (CurrentTheme != currentAppTheme || IsHighContrast != _accessible.HighContrast)+ {+ UpdateProperties();+ }+ }).Forget();+ }++ private void CoreWindow_Activated(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.WindowActivatedEventArgs args)+ {+ AppTheme currentAppTheme = Application.Current.RequestedTheme == ApplicationTheme.Dark ? AppTheme.Dark : AppTheme.Light;+ if (CurrentTheme != currentAppTheme || IsHighContrast != _accessible.HighContrast)+ {+ UpdateProperties();+ }+ }++ /// <summary>+ /// Set our current properties and fire a change notification.+ /// </summary>+ private void UpdateProperties()+ {+ _thread.ThrowIfNotOnUIThread();++ // TODO: Not sure if HighContrastScheme names are localized?+ if (_accessible.HighContrast && _accessible.HighContrastScheme.IndexOf("white", StringComparison.OrdinalIgnoreCase) != -1)+ {+ IsHighContrast = false;+ CurrentTheme = AppTheme.Light;+ }+ else+ {+ // Otherwise, we just set to what's in the system as we'd expect.+ IsHighContrast = _accessible.HighContrast;+ AppTheme currentAppTheme = Application.Current.RequestedTheme == ApplicationTheme.Dark ? AppTheme.Dark : AppTheme.Light;+ CurrentTheme = currentAppTheme;+ }++ ThemeChanged?.Invoke(this, EventArgs.Empty);+ }+ }+}\ No newline at end of filediff --git a/src/dev/impl/DevTools.Core.Impl/Threading/Thread.cs b/src/dev/impl/DevTools.Core.Impl/Threading/Thread.csnew file mode 100644index 000000000..4cf8fd202--- /dev/null+++ b/src/dev/impl/DevTools.Core.Impl/Threading/Thread.cs@@ -0,0 +1,126 @@+#nullable enable++using DevTools.Core.Threading;+using System;+using System.Composition;+using System.Threading.Tasks;+using Windows.ApplicationModel.Core;+using Windows.UI.Core;++namespace DevTools.Core.Impl.Threading+{+ [Export(typeof(IThread))]+ [Shared]+ internal sealed class Thread : IThread+ {+ private readonly static CoreDispatcher _uiDispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;++ public void ThrowIfNotOnUIThread()+ {+ if (!_uiDispatcher.HasThreadAccess)+ {+ throw new Exception("The UI thread is expected, but the current call stack is running on another thread.");+ }+ }++ public void ThrowIfOnUIThread()+ {+ if (_uiDispatcher.HasThreadAccess)+ {+ throw new Exception("The UI thread is not expected, but the current call stack is running on UI thread.");+ }+ }++ public Task RunOnUIThreadAsync(Action action)+ {+ if (action is null)+ {+ return Task.CompletedTask;+ }++ if (_uiDispatcher.HasThreadAccess)+ {+ action();+ return Task.CompletedTask;+ }+ else+ {+ return _uiDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action()).AsTask();+ }+ }++ public async Task RunOnUIThreadAsync(Func<Task> action)+ {+ if (action is null)+ {+ return;+ }++ if (_uiDispatcher.HasThreadAccess)+ {+ await action().ConfigureAwait(true);+ }+ else+ {+ var tcs = new TaskCompletionSource<object>();+ await _uiDispatcher.RunAsync(+ CoreDispatcherPriority.Normal,+ async() =>+ {+ try+ {+ await action().ConfigureAwait(true);+ }+ catch (Exception ex)+ {+ tcs.TrySetException(ex);+ }+ finally+ {+ #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.+ tcs.TrySetResult(null);+ #pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.+ }+ });++ await tcs.Task.ConfigureAwait(false);+ }+ }++ public async Task<T> RunOnUIThreadAsync<T>(Func<Task<T>> action)+ {+ Arguments.NotNull(action, nameof(action));++ if (_uiDispatcher.HasThreadAccess)+ {+ return await action().ConfigureAwait(true);+ }+ else+ {+ T result = default!;+ var tcs = new TaskCompletionSource<object>();+ _uiDispatcher.RunAsync(+ CoreDispatcherPriority.Normal, async () =>+ {+ try+ {+ result = await action().ConfigureAwait(true);+ }+ catch (Exception ex)+ {+ tcs.TrySetException(ex);+ }+ finally+ {+ #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.+ tcs.TrySetResult(null);+ #pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.+ }+ }).AsTask().ForgetSafely();++ await tcs.Task.ConfigureAwait(false);+ return result!;+ }+ }+ }+}diff --git a/src/dev/impl/DevTools.Core.Impl/TitleBar.cs b/src/dev/impl/DevTools.Core.Impl/TitleBar.csnew file mode 100644index 000000000..825582eb6--- /dev/null+++ b/src/dev/impl/DevTools.Core.Impl/TitleBar.cs@@ -0,0 +1,108 @@+#nullable enable++using DevTools.Core.Settings;+using DevTools.Core.Theme;+using DevTools.Core.Threading;+using System.Composition;+using System.Threading.Tasks;+using Windows.ApplicationModel.Core;+using Windows.UI;+using Windows.UI.Core;+using Windows.UI.ViewManagement;++namespace DevTools.Core.Impl+{+ [Export(typeof(ITitleBar))]+ [Shared]+ internal sealed class TitleBar : ITitleBar+ {+ private readonly IThread _thread;+ private readonly ISettingsProvider _settingsProvider;+ private readonly IThemeListener _themeListener;++ [ImportingConstructor]+ public TitleBar(IThread thread, ISettingsProvider settingsProvider, IThemeListener themeListener)+ {+ _thread = thread;+ _settingsProvider = settingsProvider;+ _themeListener = themeListener;+ }++ public Task SetupTitleBarAsync()+ {+ return _thread.RunOnUIThreadAsync(() =>+ {+ SetupTitleBar(CoreApplication.GetCurrentView().TitleBar);+ });+ }++ private void SetupTitleBar(CoreApplicationViewTitleBar coreTitleBar)+ {+ _thread.ThrowIfNotOnUIThread();+ Arguments.NotNull(coreTitleBar, nameof(coreTitleBar));++ coreTitleBar.ExtendViewIntoTitleBar = true;++ // Register a handler for when the size of the overlaid caption control changes.+ // For example, when the app moves to a screen with a different DPI.+ coreTitleBar.LayoutMetricsChanged += TitleBar_LayoutMetricsChanged;++ SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;++ ApplyThemeForTitleBarButtons();+ }++ private void ApplyThemeForTitleBarButtons()+ {+ ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar;++ AppTheme theme = _settingsProvider.GetSetting(PredefinedSettings.Theme);+ if (theme == AppTheme.Default)+ {+ theme = _themeListener.CurrentTheme;+ }++ if (theme == AppTheme.Dark)+ {+ // Set active window colors+ titleBar.ButtonForegroundColor = Colors.White;+ titleBar.ButtonBackgroundColor = Colors.Transparent;+ titleBar.ButtonHoverForegroundColor = Colors.White;+ titleBar.ButtonHoverBackgroundColor = Color.FromArgb(255, 90, 90, 90);+ titleBar.ButtonPressedForegroundColor = Colors.White;+ titleBar.ButtonPressedBackgroundColor = Color.FromArgb(255, 120, 120, 120);++ // Set inactive window colors+ titleBar.InactiveForegroundColor = Colors.Gray;+ titleBar.InactiveBackgroundColor = Colors.Transparent;+ titleBar.ButtonInactiveForegroundColor = Colors.Gray;+ titleBar.ButtonInactiveBackgroundColor = Colors.Transparent;++ titleBar.BackgroundColor = Color.FromArgb(255, 45, 45, 45);+ }+ else if (theme == AppTheme.Light)+ {+ // Set active window colors+ titleBar.ButtonForegroundColor = Colors.Black;+ titleBar.ButtonBackgroundColor = Colors.Transparent;+ titleBar.ButtonHoverForegroundColor = Colors.Black;+ titleBar.ButtonHoverBackgroundColor = Color.FromArgb(255, 180, 180, 180);+ titleBar.ButtonPressedForegroundColor = Colors.Black;+ titleBar.ButtonPressedBackgroundColor = Color.FromArgb(255, 150, 150, 150);++ // Set inactive window colors+ titleBar.InactiveForegroundColor = Colors.DimGray;+ titleBar.InactiveBackgroundColor = Colors.Transparent;+ titleBar.ButtonInactiveForegroundColor = Colors.DimGray;+ titleBar.ButtonInactiveBackgroundColor = Colors.Transparent;++ titleBar.BackgroundColor = Color.FromArgb(255, 210, 210, 210);+ }+ }++ private void TitleBar_LayoutMetricsChanged(CoreApplicationViewTitleBar sender, object args)+ {+ SetupTitleBar(sender);+ }+ }+}diff --git a/src/dev/impl/DevTools.Impl/DevTools.Impl.csproj b/src/dev/impl/DevTools.Impl/DevTools.Impl.csprojindex 6b9dc5f48..becf9c5fb 100644--- a/src/dev/impl/DevTools.Impl/DevTools.Impl.csproj+++ b/src/dev/impl/DevTools.Impl/DevTools.Impl.csproj@@ -9,7 +9,7 @@<AppDesignerFolder>Properties</AppDesignerFolder><RootNamespace>DevTools.Impl</RootNamespace><AssemblyName>DevTools.Impl</AssemblyName>- <DefaultLanguage>en-US</DefaultLanguage>+ <DefaultLanguage>en</DefaultLanguage><TargetPlatformIdentifier>UAP</TargetPlatformIdentifier><TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">$(Windows10SDKVersion)</TargetPlatformVersion><TargetPlatformMinVersion>$(Windows10MinSDKVersion)</TargetPlatformMinVersion>diff --git a/src/dev/impl/DevTools.Impl/Views/MainPage.xaml b/src/dev/impl/DevTools.Impl/Views/MainPage.xamlindex 65234d7b3..132fcaa23 100644--- a/src/dev/impl/DevTools.Impl/Views/MainPage.xaml+++ b/src/dev/impl/DevTools.Impl/Views/MainPage.xaml@@ -14,9 +14,12 @@<Thickness x:Key="NavigationViewContentMargin">0,48,0,0</Thickness></Page.Resources>- <Grid>+ <Grid Background="Transparent">+ <Grid.BackgroundTransition>+ <BrushTransition />+ </Grid.BackgroundTransition>+<Border- IsHitTestVisible="False"VerticalAlignment="Top"Height="48"Margin="48,0,0,0">@@ -35,9 +38,16 @@Style="{StaticResource CaptionTextBlockStyle}" /></StackPanel></Border>+ <Border+ x:Name="AppTitleBar"+ Background="Transparent"+ VerticalAlignment="Top"+ Height="32"+ Margin="48,0,0,0"+ Canvas.ZIndex="1"/><muxc:NavigationViewx:Name="nvSample"- IsTitleBarAutoPaddingEnabled="True"+ IsTitleBarAutoPaddingEnabled="False"IsSettingsVisible="False"IsBackButtonVisible="Collapsed"IsBackEnabled="False"diff --git a/src/dev/impl/DevTools.Impl/Views/MainPage.xaml.cs b/src/dev/impl/DevTools.Impl/Views/MainPage.xaml.csindex c1630b155..4beea0bf1 100644--- a/src/dev/impl/DevTools.Impl/Views/MainPage.xaml.cs+++ b/src/dev/impl/DevTools.Impl/Views/MainPage.xaml.cs@@ -1,4 +1,7 @@-using Windows.UI.Xaml.Controls;+#nullable enable++using Windows.UI.Xaml;+using Windows.UI.Xaml.Controls;// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238@@ -11,7 +14,10 @@ namespace DevTools.Impl.Views{public MainPage(){- this.InitializeComponent();+ InitializeComponent();++ // Set custom title bar dragging area+ Window.Current.SetTitleBar(AppTitleBar);}}}diff --git a/src/dev/impl/DevTools.Providers.Impl/DevTools.Providers.Impl.csproj b/src/dev/impl/DevTools.Providers.Impl/DevTools.Providers.Impl.csprojindex bd0b2ac94..724236043 100644--- a/src/dev/impl/DevTools.Providers.Impl/DevTools.Providers.Impl.csproj+++ b/src/dev/impl/DevTools.Providers.Impl/DevTools.Providers.Impl.csproj@@ -7,7 +7,7 @@<AppDesignerFolder>Properties</AppDesignerFolder><RootNamespace>DevTools.Providers.Impl</RootNamespace><AssemblyName>DevTools.Providers.Impl</AssemblyName>- <DefaultLanguage>en-US</DefaultLanguage>+ <DefaultLanguage>en</DefaultLanguage><TargetPlatformIdentifier>UAP</TargetPlatformIdentifier><TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">$(Windows10SDKVersion)</TargetPlatformVersion><TargetPlatformMinVersion>$(Windows10MinSDKVersion)</TargetPlatformMinVersion>diff --git a/src/dev/startup/DevTools/App.xaml.cs b/src/dev/startup/DevTools/App.xaml.csindex 4d0e46727..5feeecd87 100644--- a/src/dev/startup/DevTools/App.xaml.cs+++ b/src/dev/startup/DevTools/App.xaml.cs@@ -1,5 +1,7 @@#nullable enable+using DevTools.Core;+using DevTools.Core.Threading;using DevTools.Core.Impl.Injection;using DevTools.Impl.Views;using DevTools.Localization;@@ -8,10 +10,12 @@ using System.Globalization;using Windows.ApplicationModel;using Windows.ApplicationModel.Activation;using Windows.UI.ViewManagement;-using Windows.UI.WindowManagement.Preview;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Navigation;+using Windows.ApplicationModel.Core;+using DevTools.Core.Theme;+using DevTools.Core.Settings;namespace DevTools{@@ -21,6 +25,8 @@ namespace DevToolssealed partial class App : Application, IDisposable{private readonly MefComposer _mefComposer;+ private readonly ISettingsProvider _settingsProvider;+ private readonly Lazy<IThemeListener> _themeListener;private bool _isDisposed;@@ -40,6 +46,9 @@ namespace DevToolstypeof(Providers.Impl.Dummy).Assembly,typeof(Impl.Dummy).Assembly);+ _settingsProvider = _mefComposer.ExportProvider.GetExport<ISettingsProvider>();+ _themeListener = new Lazy<IThemeListener>(() => _mefComposer.ExportProvider.GetExport<IThemeListener>());+InitializeComponent();Suspending += OnSuspending;}@@ -98,8 +107,14 @@ namespace DevToolsWindow.Current.Content = rootFrame;}+ _themeListener.Value.ThemeChanged += ThemeListener_ThemeChanged;+ UpdateColorTheme();+if (e.PrelaunchActivated == false){+ // On Windows 10 version 1607 or later, this code signals that this app wants to participate in prelaunch+ CoreApplication.EnablePrelaunch(true);+if (rootFrame.Content == null){// When the navigation stack isn't restored navigate to the first page,@@ -135,5 +150,28 @@ namespace DevTools//TODO: Save application state and stop any background activitydeferral.Complete();}++ private void ThemeListener_ThemeChanged(object sender, EventArgs e)+ {+ UpdateColorTheme();+ }++ private void UpdateColorTheme()+ {+ AppTheme theme = _settingsProvider.GetSetting(PredefinedSettings.Theme);++ if (theme == AppTheme.Default)+ {+ theme = _themeListener.Value.CurrentTheme;+ }++ // Set theme for window root.+ if (Window.Current.Content is FrameworkElement frameworkElement)+ {+ frameworkElement.RequestedTheme = theme == AppTheme.Light ? ElementTheme.Light : ElementTheme.Dark;+ }++ _mefComposer.ExportProvider.GetExport<ITitleBar>().SetupTitleBarAsync().Forget();+ }}-}+}\ No newline at end of file