- Windows toast notifications with snooze (10 min / 1 h / tomorrow) and done buttons; balloon fallback; works when Windows starts the app - Recurring entries snooze via SnoozedUntil without moving their date; lead reminders keep the real date - Morning summary once a day from a chosen hour (pure DailySummary) - iCalendar import incl. Google birthday calendar, folded lines, UTC, alarms, own export round trip, duplicates skipped by UID, undo - Data folder selectable (location.json pointer), file watcher reloads changes from another PC (own writes ignored) - Themed date picker calendar, WPF tray menu, arrow/Home/End/Space keys - 90 tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
530 lines
21 KiB
C#
530 lines
21 KiB
C#
#nullable enable
|
||
using System;
|
||
using System.ComponentModel;
|
||
using System.Linq;
|
||
using System.Runtime.InteropServices;
|
||
using System.Windows;
|
||
using System.Windows.Controls;
|
||
using System.Windows.Input;
|
||
using System.Windows.Interop;
|
||
using System.Windows.Media;
|
||
using System.Windows.Media.Animation;
|
||
using ReminderOrganizer.Core;
|
||
using ReminderOrganizer.Models;
|
||
using ReminderOrganizer.ViewModels;
|
||
|
||
namespace ReminderOrganizer
|
||
{
|
||
public partial class MainWindow : Window
|
||
{
|
||
private const string IconUri = "pack://application:,,,/Assets/app.ico";
|
||
|
||
private readonly MainViewModel _viewModel;
|
||
private System.Windows.Forms.NotifyIcon? _notifyIcon;
|
||
private bool _initialized;
|
||
private bool _trayHintShown;
|
||
private Point _dragStart;
|
||
|
||
public MainWindow()
|
||
{
|
||
InitializeComponent();
|
||
|
||
_viewModel = ServiceLocator.Services.GetService(typeof(MainViewModel)) as MainViewModel
|
||
?? throw new InvalidOperationException("MainViewModel not found");
|
||
DataContext = _viewModel;
|
||
|
||
_viewModel.ThemeChanged += (_, dark) => Theme.Apply(Application.Current.Resources, dark);
|
||
_viewModel.EditTaskRequested += OnEditTaskRequested;
|
||
_viewModel.PropertyChanged += OnViewModelPropertyChanged;
|
||
Microsoft.Win32.SystemEvents.UserPreferenceChanged += OnUserPreferenceChanged;
|
||
|
||
TrySetWindowIcon();
|
||
SourceInitialized += (_, _) => UseRoundedCorners();
|
||
Loaded += async (_, _) => await InitializeOnceAsync();
|
||
StateChanged += MainWindow_StateChanged;
|
||
}
|
||
|
||
/// <summary>Autostart: create the window (tray + timer) without showing it.</summary>
|
||
public async void StartHidden()
|
||
{
|
||
new WindowInteropHelper(this).EnsureHandle();
|
||
await InitializeOnceAsync();
|
||
}
|
||
|
||
private async System.Threading.Tasks.Task InitializeOnceAsync()
|
||
{
|
||
if (_initialized) return;
|
||
_initialized = true;
|
||
SetupTrayIcon();
|
||
await _viewModel.InitializeAsync();
|
||
Theme.Apply(Application.Current.Resources, _viewModel.IsDarkMode);
|
||
RestoreWindowPlacement();
|
||
SyncTreeSelection();
|
||
|
||
// The window starts invisible so the user never sees the default theme flash.
|
||
BeginAnimation(OpacityProperty, new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(160)));
|
||
|
||
_ready = true;
|
||
foreach (var pending in _pendingToasts.ToArray()) HandleToast(pending);
|
||
_pendingToasts.Clear();
|
||
}
|
||
|
||
public void OnAppExit()
|
||
{
|
||
if (!_initialized) return;
|
||
RememberWindowPlacement();
|
||
Microsoft.Win32.SystemEvents.UserPreferenceChanged -= OnUserPreferenceChanged;
|
||
_viewModel.Cleanup();
|
||
_viewModel.FlushSave();
|
||
}
|
||
|
||
private void OnUserPreferenceChanged(object? sender, Microsoft.Win32.UserPreferenceChangedEventArgs e)
|
||
{
|
||
if (e.Category == Microsoft.Win32.UserPreferenceCategory.General)
|
||
Dispatcher.BeginInvoke(_viewModel.OnSystemThemeChanged);
|
||
}
|
||
|
||
// ---------- window placement ----------
|
||
|
||
private void RestoreWindowPlacement()
|
||
{
|
||
if (_viewModel.SavedWindowBounds is Rect r)
|
||
{
|
||
// only if the saved rectangle is still (mostly) on a screen
|
||
var screen = new Rect(SystemParameters.VirtualScreenLeft, SystemParameters.VirtualScreenTop,
|
||
SystemParameters.VirtualScreenWidth, SystemParameters.VirtualScreenHeight);
|
||
if (screen.IntersectsWith(new Rect(r.Left + 40, r.Top, Math.Max(1, r.Width - 80), 40)))
|
||
{
|
||
WindowStartupLocation = WindowStartupLocation.Manual;
|
||
Left = r.Left;
|
||
Top = r.Top;
|
||
Width = Math.Max(MinWidth, r.Width);
|
||
Height = Math.Max(MinHeight, r.Height);
|
||
}
|
||
}
|
||
if (_viewModel.SavedWindowMaximized) WindowState = WindowState.Maximized;
|
||
}
|
||
|
||
private void RememberWindowPlacement()
|
||
{
|
||
var bounds = WindowState == WindowState.Normal ? new Rect(Left, Top, Width, Height) : RestoreBounds;
|
||
if (bounds.Width > 0 && bounds.Height > 0)
|
||
_viewModel.RememberWindow(bounds, WindowState == WindowState.Maximized);
|
||
}
|
||
|
||
// Windows 11: native rounded corners for our custom-chrome window.
|
||
[DllImport("dwmapi.dll")]
|
||
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int value, int size);
|
||
|
||
private void UseRoundedCorners()
|
||
{
|
||
try
|
||
{
|
||
int round = 2; // DWMWCP_ROUND
|
||
DwmSetWindowAttribute(new WindowInteropHelper(this).Handle, 33, ref round, sizeof(int));
|
||
}
|
||
catch { /* older Windows */ }
|
||
}
|
||
|
||
private void TrySetWindowIcon()
|
||
{
|
||
try
|
||
{
|
||
Icon = System.Windows.Media.Imaging.BitmapFrame.Create(new Uri(IconUri));
|
||
}
|
||
catch
|
||
{
|
||
// no Assets\app.ico – Windows default icon
|
||
}
|
||
}
|
||
|
||
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
|
||
{
|
||
if (e.PropertyName is nameof(MainViewModel.SelectedFolder) or nameof(MainViewModel.IsUpcomingMode))
|
||
SyncTreeSelection();
|
||
}
|
||
|
||
/// <summary>TreeView.SelectedItem is read-only – mirror the view model selection onto the container.</summary>
|
||
private void SyncTreeSelection()
|
||
{
|
||
Dispatcher.BeginInvoke(() =>
|
||
{
|
||
if (_viewModel.IsUpcomingMode)
|
||
{
|
||
if (FolderTree.SelectedItem != null &&
|
||
FolderTree.ItemContainerGenerator.ContainerFromItem(FolderTree.SelectedItem) is TreeViewItem sel)
|
||
sel.IsSelected = false;
|
||
return;
|
||
}
|
||
var folder = _viewModel.SelectedFolder;
|
||
if (folder != null && FolderTree.ItemContainerGenerator.ContainerFromItem(folder) is TreeViewItem item && !item.IsSelected)
|
||
{
|
||
item.IsSelected = true;
|
||
item.BringIntoView();
|
||
}
|
||
}, System.Windows.Threading.DispatcherPriority.Loaded);
|
||
}
|
||
|
||
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
|
||
{
|
||
bool ctrl = (Keyboard.Modifiers & ModifierKeys.Control) != 0;
|
||
bool typing = Keyboard.FocusedElement is TextBox;
|
||
if (ctrl && e.Key == Key.N)
|
||
{
|
||
if (_viewModel.AddTaskCommand.CanExecute(null)) _viewModel.AddTaskCommand.Execute(null);
|
||
e.Handled = true;
|
||
}
|
||
else if (ctrl && e.Key == Key.F)
|
||
{
|
||
SearchBox.Focus();
|
||
SearchBox.SelectAll();
|
||
e.Handled = true;
|
||
}
|
||
else if (ctrl && e.Key == Key.OemComma)
|
||
{
|
||
_viewModel.OpenSettingsCommand.Execute(null);
|
||
e.Handled = true;
|
||
}
|
||
else if (e.Key == Key.Escape && (SearchBox.IsKeyboardFocusWithin || _viewModel.SearchText.Length > 0))
|
||
{
|
||
_viewModel.ClearSearchCommand.Execute(null);
|
||
FolderTree.Focus();
|
||
e.Handled = true;
|
||
}
|
||
else if (e.Key == Key.Escape && _viewModel.SelectedTask != null)
|
||
{
|
||
_viewModel.SelectedTask = null;
|
||
e.Handled = true;
|
||
}
|
||
else if (ctrl && e.Key == Key.Z && _viewModel.IsUndoVisible && !typing)
|
||
{
|
||
_viewModel.UndoCommand.Execute(null);
|
||
e.Handled = true;
|
||
}
|
||
else if (e.Key == Key.Delete && !typing && _viewModel.SelectedTask != null)
|
||
{
|
||
_viewModel.DeleteTaskCommand.Execute(_viewModel.SelectedTask);
|
||
_viewModel.SelectedTask = null;
|
||
e.Handled = true;
|
||
}
|
||
else if (e.Key == Key.Enter && !typing && _viewModel.SelectedTask != null)
|
||
{
|
||
_viewModel.EditTaskCommand.Execute(_viewModel.SelectedTask);
|
||
e.Handled = true;
|
||
}
|
||
// list navigation (the folder tree keeps its own arrow keys)
|
||
else if (!typing && !FolderTree.IsKeyboardFocusWithin && e.Key is Key.Down or Key.Up or Key.Home or Key.End)
|
||
{
|
||
MoveSelection(e.Key);
|
||
e.Handled = true;
|
||
}
|
||
else if (!typing && e.Key == Key.Space && _viewModel.SelectedTask is { } sel)
|
||
{
|
||
sel.IsNotified = !sel.IsNotified;
|
||
_viewModel.ToggleDoneCommand.Execute(sel);
|
||
e.Handled = true;
|
||
}
|
||
}
|
||
|
||
/// <summary>Arrow keys move the selection in display order (across groups) and keep it visible.</summary>
|
||
private void MoveSelection(Key key)
|
||
{
|
||
var items = _viewModel.TasksView?.Cast<ReminderTask>().ToList();
|
||
if (items == null || items.Count == 0) return;
|
||
int idx = _viewModel.SelectedTask is { } cur ? items.IndexOf(cur) : -1;
|
||
int next = key switch
|
||
{
|
||
Key.Home => 0,
|
||
Key.End => items.Count - 1,
|
||
Key.Down => idx < 0 ? 0 : Math.Min(items.Count - 1, idx + 1),
|
||
_ => idx < 0 ? items.Count - 1 : Math.Max(0, idx - 1)
|
||
};
|
||
_viewModel.SelectedTask = items[next];
|
||
Dispatcher.BeginInvoke(() => FindContainer(ListScroll, items[next])?.BringIntoView(),
|
||
System.Windows.Threading.DispatcherPriority.Loaded);
|
||
}
|
||
|
||
/// <summary>Rows sit inside group containers, so ItemContainerGenerator can't find them – search the tree.</summary>
|
||
private static FrameworkElement? FindContainer(DependencyObject root, object item)
|
||
{
|
||
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
|
||
{
|
||
var child = VisualTreeHelper.GetChild(root, i);
|
||
if (child is ContentPresenter cp && ReferenceEquals(cp.Content, item)) return cp;
|
||
if (FindContainer(child, item) is { } found) return found;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
private void OnEditTaskRequested(object? sender, ReminderTask? task)
|
||
{
|
||
if (task == null) return;
|
||
|
||
var taskWindow = new TaskWindow(task, _viewModel.IsDarkMode, _viewModel.Categories) { Owner = this };
|
||
if (taskWindow.ShowDialog() == true)
|
||
{
|
||
_ = _viewModel.SaveAsync();
|
||
}
|
||
}
|
||
|
||
// ---------- caption ----------
|
||
|
||
private void MainWindow_StateChanged(object? sender, EventArgs e)
|
||
{
|
||
// With WindowChrome a maximized window reaches past the screen edge by the resize border.
|
||
RootGrid.Margin = WindowState == WindowState.Maximized ? new Thickness(7) : new Thickness(0);
|
||
MaximizeButton.Content = WindowState == WindowState.Maximized ? "\uE923" : "\uE922";
|
||
MaximizeButton.ToolTip = _viewModel.L(WindowState == WindowState.Maximized ? "Restore" : "Maximize");
|
||
}
|
||
|
||
private void HideToTray()
|
||
{
|
||
RememberWindowPlacement();
|
||
Hide();
|
||
if (!_trayHintShown && _notifyIcon != null)
|
||
{
|
||
_trayHintShown = true;
|
||
_notifyIcon.ShowBalloonTip(3000, _viewModel.L("AppTitle"), _viewModel.L("MinimizedToTray"), System.Windows.Forms.ToolTipIcon.Info);
|
||
}
|
||
}
|
||
|
||
private void MinimizeButton_Click(object sender, RoutedEventArgs e) => SystemCommands.MinimizeWindow(this);
|
||
|
||
private void MaximizeButton_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
if (WindowState == WindowState.Maximized) SystemCommands.RestoreWindow(this);
|
||
else SystemCommands.MaximizeWindow(this);
|
||
}
|
||
|
||
/// <summary>The window's X keeps the app running in the tray (reminders need it); "Exit" is in the tray menu.</summary>
|
||
private void CloseButton_Click(object sender, RoutedEventArgs e) => HideToTray();
|
||
|
||
protected override void OnClosing(CancelEventArgs e)
|
||
{
|
||
// Alt+F4 / taskbar "close window": same as the X button unless the app is shutting down.
|
||
if (!_shuttingDown)
|
||
{
|
||
e.Cancel = true;
|
||
HideToTray();
|
||
}
|
||
base.OnClosing(e);
|
||
}
|
||
|
||
private bool _shuttingDown;
|
||
public void AllowClose() => _shuttingDown = true;
|
||
private void SetupTrayIcon()
|
||
{
|
||
System.Drawing.Icon icon = System.Drawing.SystemIcons.Information;
|
||
try
|
||
{
|
||
var res = Application.GetResourceStream(new Uri(IconUri));
|
||
if (res != null) icon = new System.Drawing.Icon(res.Stream);
|
||
}
|
||
catch { }
|
||
|
||
_notifyIcon = new System.Windows.Forms.NotifyIcon
|
||
{
|
||
Icon = icon,
|
||
Visible = true,
|
||
Text = "Reminder Organizer"
|
||
};
|
||
|
||
Services.NotificationService.SharedTrayIcon = _notifyIcon;
|
||
|
||
// WPF menu instead of the WinForms one, so it uses the app's theme styles.
|
||
_notifyIcon.MouseUp += (s, e) =>
|
||
{
|
||
if (e.Button == System.Windows.Forms.MouseButtons.Right) ShowTrayMenu();
|
||
};
|
||
_notifyIcon.DoubleClick += (s, e) => ShowMainWindow();
|
||
_notifyIcon.BalloonTipClicked += (s, e) => ShowMainWindow();
|
||
}
|
||
|
||
[DllImport("user32.dll")]
|
||
private static extern bool SetForegroundWindow(IntPtr hWnd);
|
||
|
||
private void ShowTrayMenu()
|
||
{
|
||
MenuItem Item(string key, string glyph, Action onClick)
|
||
{
|
||
var mi = new MenuItem
|
||
{
|
||
Header = _viewModel.L(key),
|
||
Icon = new TextBlock { Text = glyph, FontFamily = (FontFamily)FindResource("IconFont"), FontSize = 12 }
|
||
};
|
||
mi.Click += (_, _) => onClick();
|
||
return mi;
|
||
}
|
||
|
||
var menu = new ContextMenu { Placement = System.Windows.Controls.Primitives.PlacementMode.MousePoint };
|
||
menu.Items.Add(Item("Open", "", ShowMainWindow));
|
||
menu.Items.Add(Item("NewEntry", "", () =>
|
||
{
|
||
ShowMainWindow();
|
||
if (_viewModel.AddTaskCommand.CanExecute(null)) _viewModel.AddTaskCommand.Execute(null);
|
||
}));
|
||
var sound = Item("PlaySound", "", () => _viewModel.PlaySound = !_viewModel.PlaySound);
|
||
sound.IsChecked = _viewModel.PlaySound;
|
||
sound.Icon = null; // the check mark shows the state
|
||
menu.Items.Add(sound);
|
||
menu.Items.Add(new Separator());
|
||
menu.Items.Add(Item("Exit", "", App.Quit));
|
||
|
||
menu.IsOpen = true;
|
||
// A popup from the tray only closes on outside clicks if it owns the foreground.
|
||
if (PresentationSource.FromVisual(menu) is HwndSource src) SetForegroundWindow(src.Handle);
|
||
}
|
||
|
||
// ---------- Windows notification buttons ----------
|
||
|
||
private readonly System.Collections.Generic.List<Microsoft.Toolkit.Uwp.Notifications.ToastArguments> _pendingToasts = new();
|
||
private bool _ready;
|
||
|
||
/// <summary>Snooze / done / open from a toast. Waits until the data is loaded.</summary>
|
||
public void HandleToast(Microsoft.Toolkit.Uwp.Notifications.ToastArguments args)
|
||
{
|
||
if (!_ready)
|
||
{
|
||
_pendingToasts.Add(args);
|
||
return;
|
||
}
|
||
args.TryGetValue("action", out string? action);
|
||
args.TryGetValue("id", out string? id);
|
||
args.TryGetValue("min", out string? minutes);
|
||
args.TryGetValue("lead", out string? lead);
|
||
_viewModel.HandleToastAction(action ?? "open", id, minutes, lead == "1");
|
||
if ((action ?? "open") == "open") ShowMainWindow();
|
||
}
|
||
|
||
private void ShowMainWindow()
|
||
{
|
||
Show();
|
||
if (WindowState == WindowState.Minimized) WindowState = WindowState.Normal;
|
||
Activate();
|
||
}
|
||
|
||
private void FolderTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
|
||
{
|
||
if (e.NewValue is Folder folder)
|
||
_viewModel.SelectFolder(folder);
|
||
}
|
||
|
||
private void TreeViewItem_RightClick(object sender, MouseButtonEventArgs e)
|
||
{
|
||
if (sender is TreeViewItem treeViewItem && treeViewItem.DataContext is Folder folder)
|
||
{
|
||
_viewModel.SelectFolder(folder);
|
||
treeViewItem.IsSelected = true;
|
||
}
|
||
}
|
||
|
||
// A click on an already selected folder (e.g. coming back from "Upcoming") must switch too.
|
||
private Point _folderDragStart;
|
||
private Folder? _folderDragCandidate;
|
||
|
||
private void TreeViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
|
||
{
|
||
if (sender is TreeViewItem item && item.DataContext is Folder folder)
|
||
{
|
||
_folderDragStart = e.GetPosition(this);
|
||
_folderDragCandidate = folder;
|
||
if (item.IsSelected) _viewModel.SelectFolder(folder);
|
||
}
|
||
}
|
||
|
||
private void TreeViewItem_PreviewMouseMove(object sender, MouseEventArgs e)
|
||
{
|
||
if (e.LeftButton != MouseButtonState.Pressed || _folderDragCandidate == null || sender is not TreeViewItem item) return;
|
||
var delta = e.GetPosition(this) - _folderDragStart;
|
||
if (Math.Abs(delta.Y) < SystemParameters.MinimumVerticalDragDistance * 2 &&
|
||
Math.Abs(delta.X) < SystemParameters.MinimumHorizontalDragDistance * 2) return;
|
||
var folder = _folderDragCandidate;
|
||
_folderDragCandidate = null;
|
||
DragDrop.DoDragDrop(item, folder, DragDropEffects.Move);
|
||
}
|
||
|
||
private void AddTaskToFolder_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
if (_viewModel.SelectedFolder != null)
|
||
{
|
||
_viewModel.AddTaskToFolderCommand.Execute(_viewModel.SelectedFolder);
|
||
}
|
||
}
|
||
|
||
private void TaskItem_Click(object sender, MouseButtonEventArgs e)
|
||
{
|
||
if (sender is FrameworkElement element && element.DataContext is ReminderTask task)
|
||
{
|
||
_viewModel.SelectedTask = task;
|
||
_dragStart = e.GetPosition(this);
|
||
|
||
if (e.ClickCount == 2)
|
||
{
|
||
_viewModel.EditTaskCommand.Execute(task);
|
||
}
|
||
}
|
||
}
|
||
|
||
private void TaskItem_MouseMove(object sender, MouseEventArgs e)
|
||
{
|
||
if (e.LeftButton != MouseButtonState.Pressed || sender is not FrameworkElement element || element.DataContext is not ReminderTask task)
|
||
return;
|
||
// Only start dragging after a real move – otherwise clicks/double-clicks get swallowed.
|
||
if (e.OriginalSource is System.Windows.Controls.Primitives.ButtonBase || e.OriginalSource is CheckBox) return;
|
||
var delta = e.GetPosition(this) - _dragStart;
|
||
if (Math.Abs(delta.X) < SystemParameters.MinimumHorizontalDragDistance &&
|
||
Math.Abs(delta.Y) < SystemParameters.MinimumVerticalDragDistance)
|
||
return;
|
||
DragDrop.DoDragDrop(element, task, DragDropEffects.Move);
|
||
}
|
||
|
||
private void TreeView_DragOver(object sender, DragEventArgs e)
|
||
{
|
||
e.Effects = e.Data.GetDataPresent(typeof(ReminderTask)) ? DragDropEffects.Move : DragDropEffects.None;
|
||
e.Handled = true;
|
||
}
|
||
|
||
private void TreeView_Drop(object sender, DragEventArgs e)
|
||
{
|
||
// Drops on a folder are handled by TreeViewItem_Drop; empty space does nothing.
|
||
}
|
||
|
||
private static bool IsOurDrag(DragEventArgs e) =>
|
||
e.Data.GetDataPresent(typeof(ReminderTask)) || e.Data.GetDataPresent(typeof(Folder));
|
||
|
||
private void TreeViewItem_DragOver(object sender, DragEventArgs e)
|
||
{
|
||
e.Effects = IsOurDrag(e) ? DragDropEffects.Move : DragDropEffects.None;
|
||
e.Handled = true;
|
||
}
|
||
|
||
private void TreeViewItem_DragEnter(object sender, DragEventArgs e)
|
||
{
|
||
if (sender is TreeViewItem item && IsOurDrag(e)) item.Tag = "DropTarget";
|
||
}
|
||
|
||
private void TreeViewItem_DragLeave(object sender, DragEventArgs e)
|
||
{
|
||
if (sender is TreeViewItem item) item.Tag = null;
|
||
}
|
||
|
||
private void TreeViewItem_Drop(object sender, DragEventArgs e)
|
||
{
|
||
if (sender is TreeViewItem treeViewItem)
|
||
{
|
||
treeViewItem.Tag = null;
|
||
if (treeViewItem.DataContext is not Folder targetFolder) return;
|
||
if (e.Data.GetData(typeof(ReminderTask)) is ReminderTask task)
|
||
{
|
||
_viewModel.MoveTaskToFolderCommand.Execute((task, targetFolder));
|
||
}
|
||
else if (e.Data.GetData(typeof(Folder)) is Folder dragged && dragged != targetFolder)
|
||
{
|
||
_viewModel.MoveFolder(dragged, _viewModel.Folders.IndexOf(targetFolder));
|
||
_viewModel.SelectFolder(dragged);
|
||
}
|
||
}
|
||
e.Handled = true;
|
||
}
|
||
}
|
||
} |