Daniel Chalmers 1 year ago
parent
commit
ba26f09567

+ 12 - 27
DesktopClock/App.xaml.cs

@@ -1,5 +1,4 @@
 using System;
-using System.Collections.Generic;
 using System.Diagnostics;
 using System.IO;
 using System.Windows;
@@ -15,25 +14,11 @@ public partial class App : Application
 {
     public static FileInfo MainFileInfo = new(Process.GetCurrentProcess().MainModule.FileName);
 
-    // https://www.materialui.co/colors - A100, A700.
-    public static IReadOnlyList<Theme> Themes { get; } = new Theme[]
-    {
-        new("Light Text", "#F5F5F5", "#212121"),
-        new("Dark Text", "#212121", "#F5F5F5"),
-        new("Red", "#D50000", "#FF8A80"),
-        new("Pink", "#C51162", "#FF80AB"),
-        new("Purple", "#AA00FF", "#EA80FC"),
-        new("Blue", "#2962FF", "#82B1FF"),
-        new("Cyan", "#00B8D4", "#84FFFF"),
-        new("Green", "#00C853", "#B9F6CA"),
-        new("Orange", "#FF6D00", "#FFD180"),
-    };
-
     /// <summary>
     /// Gets the time zone selected in settings, or local by default.
     /// </summary>
     public static TimeZoneInfo GetTimeZone() =>
-        DateTimeUtil.TryGetTimeZoneById(Settings.Default.TimeZone, out var timeZoneInfo) ? timeZoneInfo : TimeZoneInfo.Local;
+        DateTimeUtil.TryFindSystemTimeZoneById(Settings.Default.TimeZone, out var timeZoneInfo) ? timeZoneInfo : TimeZoneInfo.Local;
 
     /// <summary>
     /// Sets the time zone to be used.
@@ -46,6 +31,17 @@ public partial class App : Application
     /// </summary>
     public static void SetRunOnStartup(bool runOnStartup)
     {
+        static string GetSha256Hash(string text)
+        {
+            if (string.IsNullOrEmpty(text))
+                return string.Empty;
+
+            using var sha = new System.Security.Cryptography.SHA256Managed();
+            var textData = System.Text.Encoding.UTF8.GetBytes(text);
+            var hash = sha.ComputeHash(textData);
+            return BitConverter.ToString(hash).Replace("-", string.Empty);
+        }
+
         var keyName = GetSha256Hash(MainFileInfo.FullName);
         using var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
 
@@ -54,15 +50,4 @@ public partial class App : Application
         else
             key?.DeleteValue(keyName, false);
     }
-
-    internal static string GetSha256Hash(string text)
-    {
-        if (string.IsNullOrEmpty(text))
-            return string.Empty;
-
-        using var sha = new System.Security.Cryptography.SHA256Managed();
-        var textData = System.Text.Encoding.UTF8.GetBytes(text);
-        var hash = sha.ComputeHash(textData);
-        return BitConverter.ToString(hash).Replace("-", string.Empty);
-    }
 }

+ 1 - 1
DesktopClock/DateTimeUtil.cs

@@ -7,7 +7,7 @@ public static class DateTimeUtil
 {
     public static IReadOnlyCollection<TimeZoneInfo> TimeZones { get; } = TimeZoneInfo.GetSystemTimeZones();
 
-    public static bool TryGetTimeZoneById(string timeZoneId, out TimeZoneInfo timeZoneInfo)
+    public static bool TryFindSystemTimeZoneById(string timeZoneId, out TimeZoneInfo timeZoneInfo)
     {
         try
         {

+ 1 - 1
DesktopClock/DesktopClock.csproj

@@ -18,7 +18,7 @@
   <ItemGroup>
     <PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
     <PackageReference Include="Costura.Fody" Version="5.7.0" PrivateAssets="All" />
-    <PackageReference Include="H.NotifyIcon.Wpf" Version="2.0.118" />
+    <PackageReference Include="H.NotifyIcon.Wpf" Version="2.0.123" />
     <PackageReference Include="Humanizer.Core" Version="2.14.1" />
     <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
     <PackageReference Include="PropertyChanged.Fody" Version="4.1.0" PrivateAssets="All" />

+ 2 - 2
DesktopClock/MainWindow.xaml

@@ -28,7 +28,7 @@
 	<Window.Resources>
 		<ContextMenu x:Key="MainContextMenu" x:Shared="False">
 			<MenuItem Command="{Binding CopyToClipboardCommand}" Header="_Copy" />
-			
+
 			<MenuItem Command="{Binding HideForNowCommand}" Header="_Hide for now" />
 
 			<Separator />
@@ -68,7 +68,7 @@
 				</MenuItem.Header>
 			</MenuItem>
 
-			<MenuItem Header="The_me" ItemsSource="{x:Static local:App.Themes}">
+			<MenuItem Header="The_me" ItemsSource="{x:Static local:Theme.DefaultThemes}">
 				<MenuItem.Resources>
 					<Style TargetType="MenuItem">
 						<Setter Property="Command" Value="{Binding DataContext.SetThemeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" />

+ 8 - 7
DesktopClock/MainWindow.xaml.cs

@@ -70,7 +70,8 @@ public partial class MainWindow : Window
     {
         if (!Settings.Default.TipsShown.HasFlag(TeachingTips.HideForNow))
         {
-            MessageBox.Show(this, "Clock will be minimized and can be opened again from the taskbar or system tray (if enabled).", Title);
+            MessageBox.Show(this, "Clock will be minimized and can be opened again from the taskbar or system tray (if enabled).",
+                Title, MessageBoxButton.OK, MessageBoxImage.Information);
 
             Settings.Default.TipsShown |= TeachingTips.HideForNow;
         }
@@ -123,8 +124,8 @@ public partial class MainWindow : Window
         if (!Settings.Default.TipsShown.HasFlag(TeachingTips.NewClock))
         {
             var result = MessageBox.Show(this,
-                $"This will copy the executable and start it with new settings.\n\n" +
-                $"Continue?",
+                "This will copy the executable and start it with new settings.\n\n" +
+                "Continue?",
                 Title, MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.OK);
 
             if (result != MessageBoxResult.OK)
@@ -170,8 +171,8 @@ public partial class MainWindow : Window
         if (!Settings.Default.TipsShown.HasFlag(TeachingTips.AdvancedSettings))
         {
             MessageBox.Show(this,
-                "Settings are stored in JSON format and will be opened in Notepad. Simply save the file to see your changes instantly appear on the clock. To start fresh, delete your '.settings' file.",
-                Title);
+                "Settings are stored in JSON format and will be opened in Notepad. Simply save the file to see your changes appear on the clock. To start fresh, delete your '.settings' file.",
+                Title, MessageBoxButton.OK, MessageBoxImage.Information);
 
             Settings.Default.TipsShown |= TeachingTips.AdvancedSettings;
         }
@@ -201,8 +202,8 @@ public partial class MainWindow : Window
         if (!Settings.Default.TipsShown.HasFlag(TeachingTips.CheckForUpdates))
         {
             var result = MessageBox.Show(this,
-                $"This will take you to a website to view the latest release.\n\n" +
-                $"Continue?",
+                "This will take you to a website to view the latest release.\n\n" +
+                "Continue?",
                 Title, MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.OK);
 
             if (result != MessageBoxResult.OK)

+ 14 - 9
DesktopClock/Properties/Settings.cs

@@ -16,10 +16,7 @@ public sealed class Settings : INotifyPropertyChanged, IDisposable
     private static readonly JsonSerializerSettings _jsonSerializerSettings = new()
     {
         Formatting = Formatting.Indented,
-        Error = (_, e) =>
-        {
-            e.ErrorContext.Handled = true;
-        },
+        Error = (_, e) => e.ErrorContext.Handled = true,
     };
 
     private Settings()
@@ -31,13 +28,12 @@ public sealed class Settings : INotifyPropertyChanged, IDisposable
         // Watch for changes.
         _watcher = new(App.MainFileInfo.DirectoryName, settingsFileName)
         {
-            EnableRaisingEvents = true
+            EnableRaisingEvents = true,
         };
         _watcher.Changed += FileChanged;
 
-        // Random default theme.
-        var random = new Random();
-        Theme = App.Themes[random.Next(0, App.Themes.Count)];
+        // Random default theme before getting overwritten.
+        Theme = Theme.GetRandomDefaultTheme();
     }
 
 #pragma warning disable CS0067 // The event 'Settings.PropertyChanged' is never used
@@ -92,7 +88,7 @@ public sealed class Settings : INotifyPropertyChanged, IDisposable
     {
         var json = JsonConvert.SerializeObject(this, _jsonSerializerSettings);
 
-        // Attempt to save up to 4 times.
+        // Attempt to save multiple times.
         for (var i = 0; i < 4; i++)
         {
             try
@@ -122,6 +118,9 @@ public sealed class Settings : INotifyPropertyChanged, IDisposable
         JsonSerializer.Create(_jsonSerializerSettings).Populate(jsonReader, settings);
     }
 
+    /// <summary>
+    /// Loads from the default path in JSON format.
+    /// </summary>
     private static Settings LoadFromFile()
     {
         try
@@ -136,6 +135,9 @@ public sealed class Settings : INotifyPropertyChanged, IDisposable
         }
     }
 
+    /// <summary>
+    /// Loads from the default path in JSON format then attempts to save in order to check if it can be done.
+    /// </summary>
     private static Settings LoadAndAttemptSave()
     {
         var settings = LoadFromFile();
@@ -145,6 +147,9 @@ public sealed class Settings : INotifyPropertyChanged, IDisposable
         return settings;
     }
 
+    /// <summary>
+    /// Occurs after the watcher detects a change in the settings file.
+    /// </summary>
     private void FileChanged(object sender, FileSystemEventArgs e)
     {
         try

+ 24 - 1
DesktopClock/Theme.cs

@@ -1,4 +1,7 @@
-namespace DesktopClock;
+using System;
+using System.Collections.Generic;
+
+namespace DesktopClock;
 
 public readonly record struct Theme
 {
@@ -12,4 +15,24 @@ public readonly record struct Theme
         PrimaryColor = primaryColor;
         SecondaryColor = secondaryColor;
     }
+
+    // https://www.materialui.co/colors - A100, A700.
+    public static IReadOnlyList<Theme> DefaultThemes { get; } = new Theme[]
+    {
+        new("Light Text", "#F5F5F5", "#212121"),
+        new("Dark Text", "#212121", "#F5F5F5"),
+        new("Red", "#D50000", "#FF8A80"),
+        new("Pink", "#C51162", "#FF80AB"),
+        new("Purple", "#AA00FF", "#EA80FC"),
+        new("Blue", "#2962FF", "#82B1FF"),
+        new("Cyan", "#00B8D4", "#84FFFF"),
+        new("Green", "#00C853", "#B9F6CA"),
+        new("Orange", "#FF6D00", "#FFD180"),
+    };
+
+    public static Theme GetRandomDefaultTheme()
+    {
+        var random = new Random();
+        return DefaultThemes[random.Next(0, DefaultThemes.Count)];
+    }
 }

+ 2 - 3
DesktopClock/Tokenizer.cs

@@ -8,13 +8,12 @@ public static class Tokenizer
     private static readonly Regex _tokenizerRegex = new("{([^{}]+)}", RegexOptions.Compiled);
 
     /// <summary>
-    /// Formats with a tokenized format in mind, or treats it as a regular formatting string.
-    /// Falls back to the default format on any exception.
+    /// <para>Returns a string formatted using a tokenized format or the default formatting method.</para>
+    /// <para>Falls back to the default format on any exception.</para>
     /// </summary>
     /// <param name="formattable">The object to format.</param>
     /// <param name="format">The format to use.</param>
     /// <param name="formatProvider">The format provider.</param>
-    /// <returns></returns>
     public static string FormatWithTokenizerOrFallBack(IFormattable formattable, string format, IFormatProvider formatProvider)
     {
         try