Files
ReminderOrganizer/MainWindow.xaml.cs
Michi 00e9990feb Anniversary categories (wedding, jubilee, own) and month grouping
- Birthday becomes "anniversary" with a category: birthday, wedding
  anniversary (with Silver/Gold/... names), jubilee, memorial day
- Own categories: Settings > Categories (icon, color, text with {0}/{o})
- Sidebar "Categories" lists anniversaries across folders with counts
- Group by month (any view), groups fold with a click
- Folders named Hochzeit/Wedding migrate yearly tasks once
- Old files keep working (JSON "IsBirthday" maps to IsAnniversary)
- 74 tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 15:06:19 +01:00

440 lines
17 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#nullable enable
using System;
using System.ComponentModel;
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) => ApplyTheme(dark, animate: true);
_viewModel.EditTaskRequested += OnEditTaskRequested;
_viewModel.PropertyChanged += OnViewModelPropertyChanged;
TrySetWindowIcon();
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();
ApplyTheme(_viewModel.IsDarkMode, animate: false);
SyncTreeSelection();
}
public void OnAppExit()
{
if (!_initialized) return;
_viewModel.Cleanup();
_viewModel.FlushSave();
}
private void TrySetWindowIcon()
{
try
{
Icon = System.Windows.Media.Imaging.BitmapFrame.Create(new Uri(IconUri));
}
catch
{
// no Assets\app.ico yet – 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 UpcomingEntry_Click(object sender, MouseButtonEventArgs e)
{
_viewModel.ShowUpcomingCommand.Execute(null);
}
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
bool ctrl = (Keyboard.Modifiers & ModifierKeys.Control) != 0;
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 (e.Key == Key.Escape && (SearchBox.IsKeyboardFocusWithin || _viewModel.SearchText.Length > 0))
{
_viewModel.ClearSearchCommand.Execute(null);
FolderTree.Focus();
e.Handled = true;
}
else if (ctrl && e.Key == Key.Z && _viewModel.IsUndoVisible)
{
_viewModel.UndoCommand.Execute(null);
e.Handled = true;
}
else if (e.Key == Key.Delete && !SearchBox.IsKeyboardFocusWithin && _viewModel.SelectedTask != null)
{
_viewModel.DeleteTaskCommand.Execute(_viewModel.SelectedTask);
_viewModel.SelectedTask = null;
e.Handled = true;
}
}
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();
}
}
private void ApplyTheme(bool isDarkMode, bool animate)
{
Theme.Apply(Resources, isDarkMode);
if (!animate || ThemeTransitionOverlay == null) return;
var overlay = ThemeTransitionOverlay;
overlay.Background = new SolidColorBrush(isDarkMode ? Color.FromRgb(0x12, 0x12, 0x18) : Color.FromRgb(0xF1, 0xF5, 0xF9));
var fadeIn = new DoubleAnimation(0, 0.3, TimeSpan.FromMilliseconds(100));
var fadeOut = new DoubleAnimation(0.3, 0, TimeSpan.FromMilliseconds(200));
fadeIn.Completed += (s, args) => overlay.BeginAnimation(OpacityProperty, fadeOut);
overlay.BeginAnimation(OpacityProperty, fadeIn);
}
private void MainWindow_StateChanged(object? sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
HideToTray();
}
}
private void HideToTray()
{
Hide();
if (!_trayHintShown && _notifyIcon != null)
{
_trayHintShown = true;
_notifyIcon.ShowBalloonTip(3000, _viewModel.L("AppTitle"), _viewModel.L("MinimizedToTray"), System.Windows.Forms.ToolTipIcon.Info);
}
}
private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
MaximizeRestore();
}
else if (e.LeftButton == MouseButtonState.Pressed)
{
DragMove();
}
}
private void MinimizeButton_Click(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
}
private void MaximizeButton_Click(object sender, RoutedEventArgs e)
{
MaximizeRestore();
}
private void MaximizeRestore()
{
if (WindowState == WindowState.Maximized)
{
WindowState = WindowState.Normal;
MaximizeButton.Content = "";
}
else
{
// WindowStyle=None would cover the taskbar – limit to the work area.
MaxHeight = SystemParameters.WorkArea.Height + 8;
MaxWidth = SystemParameters.WorkArea.Width + 8;
WindowState = WindowState.Maximized;
MaximizeButton.Content = "";
}
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
HideToTray();
}
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;
var menu = new System.Windows.Forms.ContextMenuStrip();
menu.Items.Add(_viewModel.L("Open"), null, (s, e) => ShowMainWindow());
menu.Items.Add(_viewModel.L("Exit"), null, (s, e) =>
{
_viewModel.Cleanup();
Application.Current.Shutdown();
});
_notifyIcon.ContextMenuStrip = menu;
_notifyIcon.DoubleClick += (s, e) => ShowMainWindow();
_notifyIcon.BalloonTipClicked += (s, e) => 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_MouseEnter(object sender, MouseEventArgs e)
{
if (sender is Border border)
{
if (border.RenderTransform is ScaleTransform scaleTransform)
{
scaleTransform.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(1, 1.01, TimeSpan.FromMilliseconds(150)));
scaleTransform.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(1, 1.01, TimeSpan.FromMilliseconds(150)));
}
if (border.Effect is System.Windows.Media.Effects.DropShadowEffect effect)
{
effect.BeginAnimation(System.Windows.Media.Effects.DropShadowEffect.BlurRadiusProperty, new DoubleAnimation(15, TimeSpan.FromMilliseconds(200)));
effect.BeginAnimation(System.Windows.Media.Effects.DropShadowEffect.OpacityProperty, new DoubleAnimation(0.35, TimeSpan.FromMilliseconds(200)));
}
border.SetResourceReference(Border.BackgroundProperty, "HoverBrush");
}
}
private void TaskItem_MouseLeave(object sender, MouseEventArgs e)
{
if (sender is Border border)
{
if (border.RenderTransform is ScaleTransform scaleTransform)
{
scaleTransform.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(150)));
scaleTransform.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(150)));
}
if (border.Effect is System.Windows.Media.Effects.DropShadowEffect effect)
{
effect.BeginAnimation(System.Windows.Media.Effects.DropShadowEffect.BlurRadiusProperty, new DoubleAnimation(0, TimeSpan.FromMilliseconds(150)));
effect.BeginAnimation(System.Windows.Media.Effects.DropShadowEffect.OpacityProperty, new DoubleAnimation(0, TimeSpan.FromMilliseconds(150)));
}
border.Background = Brushes.Transparent;
}
}
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);
}
// kept for styles that still reference them
private void SecondaryButton_MouseEnter(object sender, MouseEventArgs e)
{
if (sender is Border border) border.SetResourceReference(Border.BackgroundProperty, "HoverBrush");
}
private void SecondaryButton_MouseLeave(object sender, MouseEventArgs e)
{
if (sender is Border border) border.Background = Brushes.Transparent;
}
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;
}
}
}