#nullable enable
using System;
using System.ComponentModel;
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;
}
/// Autostart: create the window (tray + timer) without showing it.
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)));
}
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();
}
/// TreeView.SelectedItem is read-only – mirror the view model selection onto the container.
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;
}
}
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);
}
/// The window's X keeps the app running in the tray (reminders need it); "Exit" is in the tray menu.
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;
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) =>
{
App.Quit();
});
_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