Skip to content

Commit

Permalink
Transitioned to Json Settings (#6113)
Browse files Browse the repository at this point in the history
  • Loading branch information
d2dyno1 authored Oct 7, 2021
1 parent cda9b7b commit a7fb38f
Show file tree
Hide file tree
Showing 109 changed files with 2,571 additions and 1,382 deletions.
85 changes: 79 additions & 6 deletions Files/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@
using Files.Filesystem;
using Files.Filesystem.FilesystemHistory;
using Files.Helpers;
using Files.Models.Settings;
using Files.SettingsInterfaces;
using Files.Services;
using Files.Services.Implementation;
using Files.UserControls.MultitaskingControl;
using Files.ViewModels;
using Files.Views;
using Microsoft.AppCenter;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Toolkit.Mvvm.DependencyInjection;
using Microsoft.Toolkit.Uwp;
using Microsoft.Toolkit.Uwp.Helpers;
using Microsoft.Toolkit.Uwp.Notifications;
Expand Down Expand Up @@ -41,7 +46,6 @@ sealed partial class App : Application

public static SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1, 1);
public static StorageHistoryWrapper HistoryWrapper = new StorageHistoryWrapper();
public static IBundlesSettings BundlesSettings = new BundlesSettingsModel();
public static SettingsViewModel AppSettings { get; private set; }
public static MainViewModel MainViewModel { get; private set; }
public static JumpListManager JumpList { get; private set; }
Expand All @@ -61,6 +65,10 @@ sealed partial class App : Application
public static OngoingTasksViewModel OngoingTasksViewModel { get; } = new OngoingTasksViewModel();
public static SecondaryTileHelper SecondaryTileHelper { get; private set; } = new SecondaryTileHelper();

public static string AppVersion = $"{Package.Current.Id.Version.Major}.{Package.Current.Id.Version.Minor}.{Package.Current.Id.Version.Build}.{Package.Current.Id.Version.Revision}";

public IServiceProvider Services { get; private set; }

public App()
{
// Initialize logger
Expand All @@ -71,12 +79,52 @@ public App()
InitializeComponent();
Suspending += OnSuspending;
LeavingBackground += OnLeavingBackground;

AppServiceConnectionHelper.Register();

this.Services = ConfigureServices();
Ioc.Default.ConfigureServices(Services);
}

private IServiceProvider ConfigureServices()
{
ServiceCollection services = new ServiceCollection();

services
// TODO: Loggers:

// Settings:
// Base IUserSettingsService as parent settings store (to get ISettingsSharingContext from)
.AddSingleton<IUserSettingsService, UserSettingsService>()
// Children settings (from IUserSettingsService)
.AddSingleton<IFilesAndFoldersSettingsService, FilesAndFoldersSettingsService>((sp) => new FilesAndFoldersSettingsService(sp.GetService<IUserSettingsService>().GetSharingContext()))
.AddSingleton<IStartupSettingsService, StartupSettingsService>((sp) => new StartupSettingsService(sp.GetService<IUserSettingsService>().GetSharingContext()))
.AddSingleton<IMultitaskingSettingsService, MultitaskingSettingsService>((sp) => new MultitaskingSettingsService(sp.GetService<IUserSettingsService>().GetSharingContext()))
.AddSingleton<IWidgetsSettingsService, WidgetsSettingsService>((sp) => new WidgetsSettingsService(sp.GetService<IUserSettingsService>().GetSharingContext()))
.AddSingleton<ISidebarSettingsService, SidebarSettingsService>((sp) => new SidebarSettingsService(sp.GetService<IUserSettingsService>().GetSharingContext()))
.AddSingleton<IPreferencesSettingsService, PreferencesSettingsService>((sp) => new PreferencesSettingsService(sp.GetService<IUserSettingsService>().GetSharingContext()))
.AddSingleton<IAppearanceSettingsService, AppearanceSettingsService>((sp) => new AppearanceSettingsService(sp.GetService<IUserSettingsService>().GetSharingContext()))
.AddSingleton<IPreviewPaneSettingsService, PreviewPaneSettingsService>((sp) => new PreviewPaneSettingsService(sp.GetService<IUserSettingsService>().GetSharingContext()))
.AddSingleton<ILayoutSettingsService, LayoutSettingsService>((sp) => new LayoutSettingsService(sp.GetService<IUserSettingsService>().GetSharingContext()))
// Settings not related to IUserSettingsService:
.AddSingleton<IFileTagsSettingsService, FileTagsSettingsService>()
.AddSingleton<IBundlesSettingsService, BundlesSettingsService>()

// TODO: Dialogs:

// TODO: FileSystem operations:
// (IFilesystemHelpersService, IFilesystemOperationsService)

; // End of service configuration


return services.BuildServiceProvider();
}

private static async Task EnsureSettingsAndConfigurationAreBootstrapped()
{
AppSettings ??= new SettingsViewModel();
RegistryToJsonSettingsMerger.MergeSettings();

ExternalResourcesHelper ??= new ExternalResourcesHelper();
await ExternalResourcesHelper.LoadSelectedTheme();
Expand All @@ -92,6 +140,24 @@ private static async Task EnsureSettingsAndConfigurationAreBootstrapped()
TerminalController ??= new TerminalController();
}

private static async void StartAppCenter()
{
try
{
if (!AppCenter.Configured)
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(@"ms-appx:///Resources/AppCenterKey.txt"));
var lines = await FileIO.ReadTextAsync(file);
var obj = Newtonsoft.Json.Linq.JObject.Parse(lines);
AppCenter.Start((string)obj.SelectToken("key"), typeof(Analytics), typeof(Crashes));
}
}
catch (Exception ex)
{
Logger.Warn(ex, "AppCenter could not be started.");
}
}

public static async Task LoadOtherStuffAsync()
{
// Start off a list of tasks we need to run before we can continue startup
Expand Down Expand Up @@ -437,9 +503,16 @@ await Common.Extensions.IgnoreExceptions(async () =>

public static void SaveSessionTabs() // Enumerates through all tabs and gets the Path property and saves it to AppSettings.LastSessionPages
{
if (AppSettings != null)
IUserSettingsService userSettingsService = Ioc.Default.GetService<IUserSettingsService>();
IBundlesSettingsService bundlesSettingsService = Ioc.Default.GetService<IBundlesSettingsService>();

if (bundlesSettingsService != null)
{
bundlesSettingsService.FlushSettings();
}
if (userSettingsService?.StartupSettingsService != null)
{
AppSettings.LastSessionPages = MainPageViewModel.AppInstances.DefaultIfEmpty().Select(tab =>
userSettingsService.StartupSettingsService.LastSessionTabList = MainPageViewModel.AppInstances.DefaultIfEmpty().Select(tab =>
{
if (tab != null && tab.TabItemArguments != null)
{
Expand All @@ -450,7 +523,7 @@ public static void SaveSessionTabs() // Enumerates through all tabs and gets the
var defaultArg = new TabItemArguments() { InitialPageType = typeof(PaneHolderPage), NavigationArg = "NewTab".GetLocalized() };
return defaultArg.Serialize();
}
}).ToArray();
}).ToList();
}
}

Expand Down
16 changes: 11 additions & 5 deletions Files/BaseLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
using Files.Helpers;
using Files.Helpers.ContextFlyouts;
using Files.Interacts;
using Files.Services;
using Files.UserControls;
using Files.ViewModels;
using Files.ViewModels.Previews;
using Files.Views;
using Microsoft.Toolkit.Mvvm.DependencyInjection;
using Microsoft.Toolkit.Uwp;
using Microsoft.Toolkit.Uwp.UI;
using System;
Expand Down Expand Up @@ -42,6 +44,10 @@ public abstract class BaseLayout : Page, IBaseLayout, INotifyPropertyChanged
{
private readonly DispatcherTimer jumpTimer;

protected IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetService<IUserSettingsService>();

protected IFileTagsSettingsService FileTagsSettingsService { get; } = Ioc.Default.GetService<IFileTagsSettingsService>();

protected Task<NamedPipeAsAppServiceConnection> Connection => AppServiceConnectionHelper.Instance;

public SelectedItemsPropertiesViewModel SelectedItemsPropertiesViewModel { get; }
Expand Down Expand Up @@ -416,7 +422,7 @@ protected override async void OnNavigatedTo(NavigationEventArgs eventArgs)
// pathRoot will be empty on recycle bin path
var workingDir = ParentShellPageInstance.FilesystemViewModel.WorkingDirectory ?? string.Empty;
string pathRoot = GetPathRoot(workingDir);
if (string.IsNullOrEmpty(pathRoot) || workingDir.StartsWith(AppSettings.RecycleBinPath)) // Can't go up from recycle bin
if (string.IsNullOrEmpty(pathRoot) || workingDir.StartsWith(CommonPaths.RecycleBinPath)) // Can't go up from recycle bin
{
ParentShellPageInstance.NavToolbarViewModel.CanNavigateToParent = false;
}
Expand All @@ -425,7 +431,7 @@ protected override async void OnNavigatedTo(NavigationEventArgs eventArgs)
ParentShellPageInstance.NavToolbarViewModel.CanNavigateToParent = true;
}

ParentShellPageInstance.InstanceViewModel.IsPageTypeRecycleBin = workingDir.StartsWith(App.AppSettings.RecycleBinPath);
ParentShellPageInstance.InstanceViewModel.IsPageTypeRecycleBin = workingDir.StartsWith(CommonPaths.RecycleBinPath);
ParentShellPageInstance.InstanceViewModel.IsPageTypeMtpDevice = workingDir.StartsWith("\\\\?\\");
ParentShellPageInstance.InstanceViewModel.IsPageTypeFtp = FtpHelpers.IsFtpPath(workingDir);
ParentShellPageInstance.InstanceViewModel.IsPageTypeZipFolder = ZipStorageFolder.IsZipPath(workingDir);
Expand Down Expand Up @@ -619,7 +625,7 @@ private async Task LoadMenuItemsAsync()
secondaryElements.OfType<FrameworkElement>().ForEach(i => i.MinWidth = 250); // Set menu min width
secondaryElements.ForEach(i => ItemContextMenuFlyout.SecondaryCommands.Add(i));

if (AppSettings.AreFileTagsEnabled && !InstanceViewModel.IsPageTypeSearchResults && !InstanceViewModel.IsPageTypeRecycleBin && !InstanceViewModel.IsPageTypeFtp && !InstanceViewModel.IsPageTypeZipFolder)
if (UserSettingsService.FilesAndFoldersSettingsService.AreFileTagsEnabled && !InstanceViewModel.IsPageTypeSearchResults && !InstanceViewModel.IsPageTypeRecycleBin && !InstanceViewModel.IsPageTypeFtp && !InstanceViewModel.IsPageTypeZipFolder)
{
AddFileTagsItemToMenu(ItemContextMenuFlyout);
}
Expand All @@ -640,7 +646,7 @@ private void AddFileTagsItemToMenu(Microsoft.UI.Xaml.Controls.CommandBarFlyout c
{
var fileTagMenuFlyout = new MenuFlyoutItemFileTag()
{
ItemsSource = AppSettings.FileTagsSettings.FileTagList,
ItemsSource = FileTagsSettingsService.FileTagList,
SelectedItems = SelectedItems
};
var overflowSeparator = contextMenu.SecondaryCommands.FirstOrDefault(x => x is FrameworkElement fe && fe.Tag as string == "OverflowSeparator") as AppBarSeparator;
Expand All @@ -656,7 +662,7 @@ private void AddFileTagsItemToMenu(Microsoft.UI.Xaml.Controls.CommandBarFlyout c
private void AddShellItemsToMenu(List<ContextMenuFlyoutItemViewModel> shellMenuItems, Microsoft.UI.Xaml.Controls.CommandBarFlyout contextMenuFlyout, bool shiftPressed)
{
var openWithSubItems = ItemModelListToContextFlyoutHelper.GetMenuFlyoutItemsFromModel(ShellContextmenuHelper.GetOpenWithItems(shellMenuItems));
var mainShellMenuItems = shellMenuItems.RemoveFrom(!App.AppSettings.MoveOverflowMenuItemsToSubMenu ? int.MaxValue : shiftPressed ? 6 : 4);
var mainShellMenuItems = shellMenuItems.RemoveFrom(!UserSettingsService.AppearanceSettingsService.MoveOverflowMenuItemsToSubMenu ? int.MaxValue : shiftPressed ? 6 : 4);
var overflowShellMenuItems = shellMenuItems.Except(mainShellMenuItems).ToList();

var overflowItems = ItemModelListToContextFlyoutHelper.GetMenuFlyoutItemsFromModel(overflowShellMenuItems);
Expand Down
9 changes: 9 additions & 0 deletions Files/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ public static class AdaptiveLayout
public const float ExtraSmallThreshold = 15.0f;
}

public static class CommonPaths
{
public const string RecycleBinPath = @"Shell:RecycleBinFolder";

public const string NetworkFolderPath = @"Shell:NetworkPlacesFolder";
}

public static class ImageRes
{
// See imageres.dll for more icon indexes to add
Expand Down Expand Up @@ -106,6 +113,8 @@ public static class LocalSettings

public const string BundlesSettingsFileName = "bundles.json";

public const string UserSettingsFileName = "user_settings.json";

public const string FileTagSettingsFileName = "filetags.json";
}

Expand Down
29 changes: 15 additions & 14 deletions Files/DataModels/SidebarPinnedModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
using Files.DataModels.NavigationControlItems;
using Files.Filesystem;
using Files.Helpers;
using Files.Services;
using Files.UserControls;
using Files.ViewModels;
using Microsoft.Toolkit.Mvvm.DependencyInjection;
using Microsoft.Toolkit.Uwp;
using Newtonsoft.Json;
using System;
Expand All @@ -22,13 +24,12 @@ namespace Files.DataModels
{
public class SidebarPinnedModel
{
private IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetService<IUserSettingsService>();

private SidebarPinnedController controller;

private LocationItem favoriteSection, homeSection;

[JsonIgnore]
public SettingsViewModel AppSettings => App.AppSettings;

[JsonIgnore]
public MainViewModel MainViewModel => App.MainViewModel;

Expand All @@ -51,8 +52,8 @@ public void AddDefaultItems()
{
var udp = UserDataPaths.GetDefault();

FavoriteItems.Add(AppSettings.DesktopPath);
FavoriteItems.Add(AppSettings.DownloadsPath);
FavoriteItems.Add(CommonPaths.DesktopPath);
FavoriteItems.Add(CommonPaths.DownloadsPath);
FavoriteItems.Add(udp.Documents);
}

Expand All @@ -61,7 +62,7 @@ private void RemoveFavoritesSideBarSection()
try
{
var item = (from n in SidebarControl.SideBarItems where n.Text.Equals("SidebarFavorites".GetLocalized()) select n).FirstOrDefault();
if (!App.AppSettings.ShowFavoritesSection && item != null)
if (!UserSettingsService.SidebarSettingsService.ShowFavoritesSection && item != null)
{
SidebarControl.SideBarItems.Remove(item);
}
Expand All @@ -72,7 +73,7 @@ private void RemoveFavoritesSideBarSection()

public async void UpdateFavoritesSectionVisibility()
{
if (App.AppSettings.ShowFavoritesSection)
if (UserSettingsService.SidebarSettingsService.ShowFavoritesSection)
{
await AddAllItemsToSidebar();
}
Expand Down Expand Up @@ -113,11 +114,11 @@ public async Task ShowHideRecycleBinItemAsync(bool show)
Text = ApplicationData.Current.LocalSettings.Values.Get("RecycleBin_Title", "Recycle Bin"),
IsDefaultLocation = true,
Icon = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => UIHelpers.GetIconResource(Constants.ImageRes.RecycleBin)),
Path = App.AppSettings.RecycleBinPath
Path = CommonPaths.RecycleBinPath
};
// Add recycle bin to sidebar, title is read from LocalSettings (provided by the fulltrust process)
// TODO: the very first time the app is launched localized name not available
if (!favoriteSection.ChildItems.Any(x => x.Path == App.AppSettings.RecycleBinPath))
if (!favoriteSection.ChildItems.Any(x => x.Path == CommonPaths.RecycleBinPath))
{
await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => favoriteSection.ChildItems.Add(recycleBinItem));
}
Expand All @@ -126,7 +127,7 @@ public async Task ShowHideRecycleBinItemAsync(bool show)
{
foreach (INavigationControlItem item in favoriteSection.ChildItems.ToList())
{
if (item is LocationItem && item.Path == App.AppSettings.RecycleBinPath)
if (item is LocationItem && item.Path == CommonPaths.RecycleBinPath)
{
await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => favoriteSection.ChildItems.Remove(item));
}
Expand Down Expand Up @@ -251,7 +252,7 @@ public async Task AddItemToSidebarAsync(string path)
var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path, item));
if (res || (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path))
{
var lastItem = favoriteSection.ChildItems.LastOrDefault(x => x.ItemType == NavigationControlItemType.Location && !x.Path.Equals(App.AppSettings.RecycleBinPath));
var lastItem = favoriteSection.ChildItems.LastOrDefault(x => x.ItemType == NavigationControlItemType.Location && !x.Path.Equals(CommonPaths.RecycleBinPath));
int insertIndex = lastItem != null ? favoriteSection.ChildItems.IndexOf(lastItem) + 1 : 0;
var locationItem = new LocationItem
{
Expand Down Expand Up @@ -299,7 +300,7 @@ public async Task AddItemToSidebarAsync(string path)
/// <param name="section">The section.</param>
private void AddItemToSidebarAsync(LocationItem section)
{
var lastItem = favoriteSection.ChildItems.LastOrDefault(x => x.ItemType == NavigationControlItemType.Location && !x.Path.Equals(App.AppSettings.RecycleBinPath));
var lastItem = favoriteSection.ChildItems.LastOrDefault(x => x.ItemType == NavigationControlItemType.Location && !x.Path.Equals(CommonPaths.RecycleBinPath));
int insertIndex = lastItem != null ? favoriteSection.ChildItems.IndexOf(lastItem) + 1 : 0;

if (!favoriteSection.ChildItems.Contains(section))
Expand All @@ -313,7 +314,7 @@ private void AddItemToSidebarAsync(LocationItem section)
/// </summary>
public async Task AddAllItemsToSidebar()
{
if (!App.AppSettings.ShowFavoritesSection)
if (!UserSettingsService.SidebarSettingsService.ShowFavoritesSection)
{
return;
}
Expand Down Expand Up @@ -365,7 +366,7 @@ public async Task AddAllItemsToSidebar()
await AddItemToSidebarAsync(path);
}

await ShowHideRecycleBinItemAsync(App.AppSettings.PinRecycleBinToSideBar);
await ShowHideRecycleBinItemAsync(UserSettingsService.SidebarSettingsService.PinRecycleBinToSidebar);
}

/// <summary>
Expand Down
6 changes: 6 additions & 0 deletions Files/Enums/SortOption.cs → Files/Enums/SortOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,10 @@ public enum GroupOption : byte
OriginalFolder,
DateDeleted
}

public enum SortDirection : byte // We cannot use Microsoft.Toolkit.Uwp.UI.SortDirection since it's UI-tied and we need Model-tied
{
Ascending = 0,
Descending = 1
}
}
17 changes: 17 additions & 0 deletions Files/EventArguments/BaseJsonSettingsModelEventArgs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;

namespace Files.EventArguments
{
public sealed class SettingChangedEventArgs : EventArgs
{
public readonly string settingName;

public readonly object newValue;

public SettingChangedEventArgs(string settingName, object newValue)
{
this.settingName = settingName;
this.newValue = newValue;
}
}
}
Loading

0 comments on commit a7fb38f

Please sign in to comment.