Skip to content

Commit

Permalink
Merge pull request #451 from TheJoeFin/SettingsService
Browse files Browse the repository at this point in the history
Settings service and Modern Settings
  • Loading branch information
TheJoeFin committed Apr 14, 2024
2 parents 89caf9f + 95be674 commit afb735a
Show file tree
Hide file tree
Showing 31 changed files with 571 additions and 206 deletions.
38 changes: 21 additions & 17 deletions Text-Grab/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Microsoft.Toolkit.Uwp.Notifications;
using Microsoft.Win32;
using Microsoft.Windows.Themes;
using RegistryUtils;
using System;
using System.Collections.Generic;
Expand All @@ -18,7 +17,6 @@
using Text_Grab.Views;
using Wpf.Ui;
using Wpf.Ui.Appearance;
using Wpf.Ui.Extensions;

namespace Text_Grab;

Expand All @@ -27,6 +25,12 @@ namespace Text_Grab;
/// </summary>
public partial class App : System.Windows.Application
{
#region Fields

readonly static Settings _defaultSettings = AppUtilities.TextGrabSettings;

#endregion Fields

#region Properties

public List<int> HotKeyIds { get; set; } = new();
Expand All @@ -38,7 +42,7 @@ public partial class App : System.Windows.Application

public static void DefaultLaunch()
{
TextGrabMode defaultLaunchSetting = Enum.Parse<TextGrabMode>(Settings.Default.DefaultLaunch, true);
TextGrabMode defaultLaunchSetting = Enum.Parse<TextGrabMode>(_defaultSettings.DefaultLaunch, true);

switch (defaultLaunchSetting)
{
Expand All @@ -65,7 +69,7 @@ public static void DefaultLaunch()
}
public static void SetTheme(object? sender = null, EventArgs? e = null)
{
bool gotTheme = Enum.TryParse<AppTheme>(Settings.Default.AppTheme.ToString(), true, out AppTheme currentAppTheme);
bool gotTheme = Enum.TryParse(_defaultSettings.AppTheme.ToString(), true, out AppTheme currentAppTheme);

if (!gotTheme)
return;
Expand Down Expand Up @@ -135,8 +139,8 @@ private static async Task<bool> HandleStartupArgs(string[] args)
if (arg == "--windowless")
{
isQuiet = true;
Settings.Default.FirstRun = false;
Settings.Default.Save();
_defaultSettings.FirstRun = false;
_defaultSettings.Save();
}

if (currentArgument.Contains("ToastActivated"))
Expand All @@ -151,7 +155,7 @@ private static async Task<bool> HandleStartupArgs(string[] args)
return true;
}

bool isStandardMode = Enum.TryParse<TextGrabMode>(currentArgument, true, out TextGrabMode launchMode);
bool isStandardMode = Enum.TryParse(currentArgument, true, out TextGrabMode launchMode);

if (isStandardMode)
{
Expand Down Expand Up @@ -195,8 +199,8 @@ private static void ShowAndSetFirstRun()
FirstRunWindow frw = new();
frw.Show();

Settings.Default.FirstRun = false;
Settings.Default.Save();
_defaultSettings.FirstRun = false;
_defaultSettings.Save();
}

private static async Task<bool> TryToOpenFile(string possiblePath, bool isQuiet)
Expand Down Expand Up @@ -253,14 +257,14 @@ async void appStartup(object sender, StartupEventArgs e)
if (handledArgument)
{
// arguments were passed, so don't show firstRun dialog
Settings.Default.FirstRun = false;
Settings.Default.Save();
_defaultSettings.FirstRun = false;
_defaultSettings.Save();
return;
}

if (Settings.Default.FirstRun)
if (_defaultSettings.FirstRun)
{
Settings.Default.CorrectToLatin = LanguageUtilities.IsCurrentLanguageLatinBased();
_defaultSettings.CorrectToLatin = LanguageUtilities.IsCurrentLanguageLatinBased();
ShowAndSetFirstRun();
return;
}
Expand All @@ -277,11 +281,11 @@ private void CurrentDispatcherUnhandledException(object sender, DispatcherUnhand

private bool HandleNotifyIcon()
{
if (Settings.Default.RunInTheBackground && NumberOfRunningInstances < 2)
if (_defaultSettings.RunInTheBackground && NumberOfRunningInstances < 2)
{
NotifyIconUtilities.SetupNotifyIcon();

if (Settings.Default.StartupOnLogin)
if (_defaultSettings.StartupOnLogin)
return true;
}

Expand All @@ -295,11 +299,11 @@ private void LaunchFromToast(ToastNotificationActivatedEventArgsCompat toastArgs
return;

// Need to dispatch to UI thread if performing UI operations
Dispatcher.BeginInvoke((Action)(() =>
Dispatcher.BeginInvoke(() =>
{
EditTextWindow mtw = new(argsInvoked);
mtw.Show();
}));
});
}
#endregion Methods
}
12 changes: 7 additions & 5 deletions Text-Grab/Controls/BottomBarSettings.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ namespace Text_Grab.Controls;

public partial class BottomBarSettings : FluentWindow
{
private readonly Settings DefaultSettings = AppUtilities.TextGrabSettings;

#region Constructors

public BottomBarSettings()
Expand All @@ -30,8 +32,8 @@ public BottomBarSettings()
ButtonsInLeftList = new(allBtns);
LeftListBox.ItemsSource = ButtonsInLeftList;

ShowCursorTextCheckBox.IsChecked = Settings.Default.ShowCursorText;
ShowScrollbarCheckBox.IsChecked = Settings.Default.ScrollBottomBar;
ShowCursorTextCheckBox.IsChecked = DefaultSettings.ShowCursorText;
ShowScrollbarCheckBox.IsChecked = DefaultSettings.ScrollBottomBar;
}

#endregion Constructors
Expand Down Expand Up @@ -115,9 +117,9 @@ private void MoveUpButton_Click(object sender, RoutedEventArgs e)
}
private void SaveBTN_Click(object sender, RoutedEventArgs e)
{
Settings.Default.ShowCursorText = ShowCursorTextCheckBox.IsChecked ?? true;
Settings.Default.ScrollBottomBar = ShowScrollbarCheckBox.IsChecked ?? true;
Settings.Default.Save();
DefaultSettings.ShowCursorText = ShowCursorTextCheckBox.IsChecked ?? true;
DefaultSettings.ScrollBottomBar = ShowScrollbarCheckBox.IsChecked ?? true;
DefaultSettings.Save();

CustomBottomBarUtilities.SaveCustomBottomBarItemsSetting(ButtonsInRightList.ToList());
if (Owner is EditTextWindow etw)
Expand Down
2 changes: 1 addition & 1 deletion Text-Grab/Controls/WordBorder.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ private void WordBorderControl_MouseDoubleClick(object sender, MouseButtonEventA

try { Clipboard.SetDataObject(Word, true); } catch { }

if (Settings.Default.ShowToast
if (AppUtilities.TextGrabSettings.ShowToast
&& !IsFromEditWindow)
NotificationUtilities.ShowToast(Word);

Expand Down
108 changes: 108 additions & 0 deletions Text-Grab/Extensions/SettingsStorageExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;

namespace Text_Grab.Helpers;

// Use these extension methods to store and retrieve local and roaming app data
// More details regarding storing and retrieving app data at https://docs.microsoft.com/windows/apps/design/app-settings/store-and-retrieve-app-data
public static class SettingsStorageExtensions
{
private const string FileExtension = ".json";

public static bool IsRoamingStorageAvailable(this ApplicationData appData)
{
return appData.RoamingStorageQuota == 0;
}

public static async Task SaveAsync<T>(this StorageFolder folder, string name, T content)
{
if (content is null)
return;

StorageFile file = await folder.CreateFileAsync(GetFileName(name), CreationCollisionOption.ReplaceExisting);
string fileContent = await Json.StringifyAsync(content);

await FileIO.WriteTextAsync(file, fileContent);
}

public static async Task<T?> ReadAsync<T>(this StorageFolder folder, string name)
{
if (!File.Exists(Path.Combine(folder.Path, GetFileName(name))))
{
return default;
}

StorageFile file = await folder.GetFileAsync($"{name}.json");
string fileContent = await FileIO.ReadTextAsync(file);

return await Json.ToObjectAsync<T>(fileContent);
}

public static async Task SaveAsync<T>(this ApplicationDataContainer settings, string key, T? value)
{
if (value is null)
return;

settings.SaveString(key, await Json.StringifyAsync(value));
}

public static void SaveString(this ApplicationDataContainer settings, string key, string value)
{
settings.Values[key] = value;
}

public static async Task<T?> ReadAsync<T>(this ApplicationDataContainer settings, string key)
{
if (settings.Values.TryGetValue(key, out object? obj))
return await Json.ToObjectAsync<T>((string)obj);

return default;
}

public static async Task<StorageFile> SaveFileAsync(this StorageFolder folder, byte[] content, string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting)
{
ArgumentNullException.ThrowIfNull(content);

if (string.IsNullOrEmpty(fileName))
throw new ArgumentException("File name is null or empty. Specify a valid file name", nameof(fileName));

StorageFile storageFile = await folder.CreateFileAsync(fileName, options);
await FileIO.WriteBytesAsync(storageFile, content);
return storageFile;
}

public static async Task<byte[]?> ReadFileAsync(this StorageFolder folder, string fileName)
{
IStorageItem item = await folder.TryGetItemAsync(fileName).AsTask().ConfigureAwait(false);

if ((item != null) && item.IsOfType(StorageItemTypes.File))
{
StorageFile storageFile = await folder.GetFileAsync(fileName);
byte[]? content = await storageFile.ReadBytesAsync();
return content;
}

return null;
}

public static async Task<byte[]?> ReadBytesAsync(this StorageFile file)
{
if (file == null)
return null;

using IRandomAccessStream stream = await file.OpenReadAsync();
using DataReader reader = new(stream.GetInputStreamAt(0));
await reader.LoadAsync((uint)stream.Size);
byte[] bytes = new byte[stream.Size];
reader.ReadBytes(bytes);
return bytes;
}

private static string GetFileName(string name)
{
return string.Concat(name, FileExtension);
}
}
2 changes: 1 addition & 1 deletion Text-Grab/Models/OcrOutput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public record OcrOutput

public void CleanOutput()
{
if (Settings.Default is not Settings userSettings
if (AppUtilities.TextGrabSettings is not Settings userSettings
|| Kind == OcrOutputKind.Barcode)
return;

Expand Down
4 changes: 3 additions & 1 deletion Text-Grab/Pages/DangerSettings.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ namespace Text_Grab.Pages;
/// </summary>
public partial class DangerSettings : Page
{
private readonly Settings DefaultSettings = AppUtilities.TextGrabSettings;

public DangerSettings()
{
InitializeComponent();
Expand All @@ -23,7 +25,7 @@ private void ResetSettingsButton_Click(object sender, RoutedEventArgs e)
if (areYouSure != MessageBoxResult.Yes)
return;

Settings.Default.Reset();
DefaultSettings.Reset();
Singleton<HistoryService>.Instance.DeleteHistory();
App.Current.Shutdown();
}
Expand Down
4 changes: 1 addition & 3 deletions Text-Grab/Pages/GeneralSettings.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="GeneralSettings"
d:DesignHeight="450"
d:DesignHeight="1450"
d:DesignWidth="800"
Loaded="Page_Loaded"
mc:Ignorable="d">
Expand Down Expand Up @@ -203,7 +203,6 @@
<ui:ToggleSwitch
Name="ReadBarcodesBarcode"
Checked="ReadBarcodesBarcode_Checked"
IsChecked="True"
Unchecked="ReadBarcodesBarcode_Unchecked">
<TextBlock Style="{StaticResource TextBodyNormal}">
Try to read barcodes
Expand Down Expand Up @@ -299,7 +298,6 @@
<ui:ToggleSwitch
Name="HistorySwitch"
Checked="HistorySwitch_Checked"
IsChecked="True"
Unchecked="HistorySwitch_Unchecked">
<TextBlock Style="{StaticResource TextBodyNormal}">
Keep recent history of Grabs and Edit Text Windows
Expand Down
Loading

0 comments on commit afb735a

Please sign in to comment.