/ src / modules / cmdpal / Microsoft.CmdPal.UI.ViewModels / CommandSettingsViewModel.cs
CommandSettingsViewModel.cs
 1  // Copyright (c) Microsoft Corporation
 2  // The Microsoft Corporation licenses this file to you under the MIT license.
 3  // See the LICENSE file in the project root for more information.
 4  
 5  using Microsoft.CmdPal.Core.Common;
 6  using Microsoft.CmdPal.Core.ViewModels;
 7  using Microsoft.CmdPal.Core.ViewModels.Models;
 8  using Microsoft.CommandPalette.Extensions;
 9  
10  namespace Microsoft.CmdPal.UI.ViewModels;
11  
12  public partial class CommandSettingsViewModel(ICommandSettings? _unsafeSettings, CommandProviderWrapper provider, TaskScheduler mainThread)
13  {
14      private readonly ExtensionObject<ICommandSettings> _model = new(_unsafeSettings);
15  
16      public ContentPageViewModel? SettingsPage { get; private set; }
17  
18      public bool Initialized { get; private set; }
19  
20      public bool HasSettings =>
21          _model.Unsafe is not null && // We have a settings model AND
22          (!Initialized || SettingsPage is not null); // we weren't initialized, OR we were, and we do have a settings page
23  
24      private void UnsafeInitializeProperties()
25      {
26          var model = _model.Unsafe;
27          if (model is null)
28          {
29              return;
30          }
31  
32          if (model.SettingsPage is not null)
33          {
34              SettingsPage = new CommandPaletteContentPageViewModel(model.SettingsPage, mainThread, provider.ExtensionHost);
35              SettingsPage.InitializeProperties();
36          }
37      }
38  
39      public void SafeInitializeProperties()
40      {
41          try
42          {
43              UnsafeInitializeProperties();
44          }
45          catch (Exception ex)
46          {
47              CoreLogger.LogError($"Failed to load settings page", ex: ex);
48          }
49  
50          Initialized = true;
51      }
52  
53      public void DoOnUiThread(Action action)
54      {
55          Task.Factory.StartNew(
56              action,
57              CancellationToken.None,
58              TaskCreationOptions.None,
59              mainThread);
60      }
61  }