MainWindow.xaml.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. using System;
  2. using System.ComponentModel;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Input;
  8. using CommunityToolkit.Mvvm.ComponentModel;
  9. using CommunityToolkit.Mvvm.Input;
  10. using DesktopClock.Properties;
  11. using H.NotifyIcon;
  12. using Humanizer;
  13. using WpfWindowPlacement;
  14. namespace DesktopClock;
  15. /// <summary>
  16. /// Interaction logic for MainWindow.xaml
  17. /// </summary>
  18. [ObservableObject]
  19. public partial class MainWindow : Window
  20. {
  21. private readonly SystemClockTimer _systemClockTimer;
  22. private TaskbarIcon _trayIcon;
  23. private TimeZoneInfo _timeZone;
  24. public MainWindow()
  25. {
  26. InitializeComponent();
  27. DataContext = this;
  28. _timeZone = App.GetTimeZone();
  29. Settings.Default.PropertyChanged += Settings_PropertyChanged;
  30. _systemClockTimer = new();
  31. _systemClockTimer.SecondChanged += SystemClockTimer_SecondChanged;
  32. _systemClockTimer.Start();
  33. ContextMenu = Resources["MainContextMenu"] as ContextMenu;
  34. CreateOrDestroyTrayIcon(!Settings.Default.ShowInTaskbar, true);
  35. }
  36. /// <summary>
  37. /// The current date and time in the selected time zone.
  38. /// </summary>
  39. private DateTimeOffset CurrentTimeInSelectedTimeZone => TimeZoneInfo.ConvertTime(DateTimeOffset.Now, _timeZone);
  40. /// <summary>
  41. /// Should the clock be a countdown?
  42. /// </summary>
  43. private bool IsCountdown => Settings.Default.CountdownTo > DateTimeOffset.MinValue;
  44. /// <summary>
  45. /// The current date and time in the selected time zone or countdown as a formatted string.
  46. /// </summary>
  47. public string CurrentTimeOrCountdownString =>
  48. IsCountdown ?
  49. Settings.Default.CountdownTo.Humanize(CurrentTimeInSelectedTimeZone) :
  50. CurrentTimeInSelectedTimeZone.ToString(Settings.Default.Format);
  51. [RelayCommand]
  52. public void CopyToClipboard() =>
  53. Clipboard.SetText(TimeTextBlock.Text);
  54. /// <summary>
  55. /// Sets app theme to parameter's value.
  56. /// </summary>
  57. [RelayCommand]
  58. public void SetTheme(Theme theme) => Settings.Default.Theme = theme;
  59. /// <summary>
  60. /// Sets format string in settings to parameter's string.
  61. /// </summary>
  62. [RelayCommand]
  63. public void SetFormat(string format) => Settings.Default.Format = format;
  64. /// <summary>
  65. /// Sets time zone ID in settings to parameter's time zone ID.
  66. /// </summary>
  67. [RelayCommand]
  68. public void SetTimeZone(TimeZoneInfo tzi) => App.SetTimeZone(tzi);
  69. /// <summary>
  70. /// Creates a new clock.
  71. /// </summary>
  72. [RelayCommand]
  73. public void NewClock()
  74. {
  75. var result = MessageBox.Show(this,
  76. $"This will copy the executable and start it with new settings.\n\n" +
  77. $"Continue?",
  78. Title, MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.OK);
  79. if (result != MessageBoxResult.OK)
  80. return;
  81. var exeInfo = new FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location);
  82. var newExePath = Path.Combine(exeInfo.DirectoryName, Guid.NewGuid().ToString() + exeInfo.Name);
  83. File.Copy(exeInfo.FullName, newExePath);
  84. Process.Start(newExePath);
  85. }
  86. /// <summary>
  87. /// Explains how to enable countdown mode.
  88. /// </summary>
  89. [RelayCommand]
  90. public void CountdownTo()
  91. {
  92. var result = MessageBox.Show(this,
  93. $"In advanced settings: change {nameof(Settings.Default.CountdownTo)}, then save.\n" +
  94. "Go back by replacing it with \"0001-01-01T00:00:00+00:00\".\n\n" +
  95. "Open advanced settings now?",
  96. Title, MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.OK);
  97. if (result == MessageBoxResult.OK)
  98. OpenSettings();
  99. }
  100. /// <summary>
  101. /// Opens the settings file in Notepad.
  102. /// </summary>
  103. [RelayCommand]
  104. public void OpenSettings()
  105. {
  106. Settings.Default.Save();
  107. // Re-create the settings file if it got deleted.
  108. if (!File.Exists(Settings.FilePath))
  109. Settings.Default.Save();
  110. // Open settings file in notepad.
  111. try
  112. {
  113. Process.Start("notepad", Settings.FilePath);
  114. }
  115. catch (Exception ex)
  116. {
  117. // Lazy scammers on the Microsoft Store may reupload without realizing it's sandboxed, which makes it unable to start the Notepad process.
  118. MessageBox.Show(this,
  119. "Couldn't open settings file.\n\n" +
  120. "This app may have be reuploaded without permission. If you paid for it, ask for a refund and download it for free from the original source: https://github.com/danielchalmers/DesktopClock.\n\n" +
  121. $"If it still doesn't work, report it as an issue at that link with details on what happened and include this error: \"{ex.Message}\"");
  122. }
  123. }
  124. /// <summary>
  125. /// Checks for updates.
  126. /// </summary>
  127. [RelayCommand]
  128. public void CheckForUpdates()
  129. {
  130. Process.Start("https://github.com/danielchalmers/DesktopClock/releases");
  131. }
  132. /// <summary>
  133. /// Exits the program.
  134. /// </summary>
  135. [RelayCommand]
  136. public void Exit() => Close();
  137. private void CreateOrDestroyTrayIcon(bool showTrayIcon, bool firstLaunch)
  138. {
  139. if (showTrayIcon)
  140. {
  141. if (_trayIcon == null)
  142. {
  143. _trayIcon = Resources["TrayIcon"] as TaskbarIcon;
  144. _trayIcon.ContextMenu = Resources["MainContextMenu"] as ContextMenu;
  145. _trayIcon.ContextMenu.DataContext = this;
  146. _trayIcon.ForceCreate();
  147. }
  148. if (!firstLaunch)
  149. _trayIcon.ShowNotification("Hidden from taskbar", "Icon was moved to the tray");
  150. }
  151. else
  152. {
  153. _trayIcon?.Dispose();
  154. _trayIcon = null;
  155. }
  156. }
  157. private void Settings_PropertyChanged(object sender, PropertyChangedEventArgs e)
  158. {
  159. switch (e.PropertyName)
  160. {
  161. case nameof(Settings.Default.TimeZone):
  162. _timeZone = App.GetTimeZone();
  163. UpdateTimeString();
  164. break;
  165. case nameof(Settings.Default.Format):
  166. UpdateTimeString();
  167. break;
  168. case nameof(Settings.Default.ShowInTaskbar):
  169. CreateOrDestroyTrayIcon(!Settings.Default.ShowInTaskbar, false);
  170. break;
  171. }
  172. }
  173. private void SystemClockTimer_SecondChanged(object sender, EventArgs e)
  174. {
  175. UpdateTimeString();
  176. }
  177. private void UpdateTimeString() => OnPropertyChanged(nameof(CurrentTimeOrCountdownString));
  178. private void Window_MouseDown(object sender, MouseButtonEventArgs e)
  179. {
  180. if (e.ChangedButton == MouseButton.Left)
  181. {
  182. DragMove();
  183. }
  184. }
  185. private void Window_MouseDoubleClick(object sender, MouseButtonEventArgs e)
  186. {
  187. CopyToClipboard();
  188. }
  189. private void Window_MouseWheel(object sender, MouseWheelEventArgs e)
  190. {
  191. if (Keyboard.Modifiers == ModifierKeys.Control)
  192. {
  193. // Scale size based on scroll amount, with one notch on a default PC mouse being a change of 15%.
  194. var steps = e.Delta / (double)Mouse.MouseWheelDeltaForOneLine;
  195. var change = Settings.Default.Height * steps * 0.15;
  196. Settings.Default.Height = (int)Math.Min(Math.Max(Settings.Default.Height + change, 16), 160);
  197. }
  198. }
  199. private void Window_SourceInitialized(object sender, EventArgs e)
  200. {
  201. WindowPlacementFunctions.SetPlacement(this, Settings.Default.Placement);
  202. }
  203. private void Window_Closing(object sender, CancelEventArgs e)
  204. {
  205. Settings.Default.Placement = WindowPlacementFunctions.GetPlacement(this);
  206. Settings.Default.SaveIfNotModifiedExternally();
  207. App.SetRunOnStartup(Settings.Default.RunOnStartup);
  208. Settings.Default.Dispose();
  209. }
  210. }