Snooze notifications, morning summary, ICS import, data folder sync
- 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>
This commit is contained in:
18
App.xaml.cs
18
App.xaml.cs
@@ -1,4 +1,4 @@
|
||||
#nullable enable
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
@@ -30,10 +30,18 @@ namespace ReminderOrganizer
|
||||
SetupExceptionHandling();
|
||||
ServiceLocator.Initialize();
|
||||
|
||||
// Buttons in Windows notifications (snooze / done / open) – also when Windows started us for it.
|
||||
Microsoft.Toolkit.Uwp.Notifications.ToastNotificationManagerCompat.OnActivated += args =>
|
||||
{
|
||||
var toastArgs = Microsoft.Toolkit.Uwp.Notifications.ToastArguments.Parse(args.Argument);
|
||||
Current.Dispatcher.BeginInvoke(new Action(() => (Current.MainWindow as MainWindow)?.HandleToast(toastArgs)));
|
||||
};
|
||||
bool fromToast = Microsoft.Toolkit.Uwp.Notifications.ToastNotificationManagerCompat.WasCurrentProcessToastActivated();
|
||||
|
||||
var main = new MainWindow();
|
||||
MainWindow = main;
|
||||
// Autostart passes --minimized: start straight into the tray.
|
||||
if (Array.IndexOf(e.Args, "--minimized") >= 0)
|
||||
// Autostart passes --minimized: start straight into the tray. A toast button decides itself.
|
||||
if (Array.IndexOf(e.Args, "--minimized") >= 0 || fromToast)
|
||||
main.StartHidden();
|
||||
else
|
||||
main.Show();
|
||||
@@ -84,8 +92,8 @@ namespace ReminderOrganizer
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(DataService.DefaultDataDirectory);
|
||||
var logPath = Path.Combine(DataService.DefaultDataDirectory, "error.log");
|
||||
Directory.CreateDirectory(DataService.AppDirectory);
|
||||
var logPath = Path.Combine(DataService.AppDirectory, "error.log");
|
||||
var logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{source}]\n{ex}\n\n";
|
||||
File.AppendAllText(logPath, logEntry);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,10 @@ services through `ServiceLocator` (Microsoft.Extensions.DependencyInjection).
|
||||
`ProcessDue`) is pure and tested.
|
||||
- `Services/`: `DataService` (JSON in %APPDATA%, atomic + serialized), `LocalizationService` (Locales are
|
||||
**EmbeddedResource** `Locales.<lang>.json`), `TaskCsv` + `Core/Csv` (import/export), `AutostartService`
|
||||
(HKCU Run, `"exe" --minimized`), `NotificationService` (tray balloon).
|
||||
(HKCU Run, `"exe" --minimized`), `NotificationService` (Windows toasts via Microsoft.Toolkit.Uwp.Notifications with snooze/done buttons → `App` `OnActivated` → `MainWindow.HandleToast` → `MainViewModel.HandleToastAction`; tray balloon as fallback), `IcsImport`/`IcsExport`.
|
||||
- Data folder: `DataService.AppDirectory` (pointer `location.json`, error.log, toast logo) vs. `DefaultDataDirectory` (tasks.json,
|
||||
may be OneDrive). `FileSystemWatcher` + `LastWriteUtc` → `MainViewModel.ReloadFromDiskAsync` when another PC changed the file.
|
||||
- Morning summary: `Core/DailySummary.cs` (pure), shown from `CheckReminders`.
|
||||
- Anniversaries: `ReminderTask.IsAnniversary` (stored as JSON `"IsBirthday"` for older files) + `CategoryId`
|
||||
→ `Models/Category.cs` (presets birthday/wedding/jubilee/memorial + own ones, text with `{0}`/`{o}`).
|
||||
Filter/sort/group rules are in `Core/TaskQuery.cs` (pure, tested).
|
||||
|
||||
35
Core/DailySummary.cs
Normal file
35
Core/DailySummary.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using ReminderOrganizer.Models;
|
||||
|
||||
namespace ReminderOrganizer.Core
|
||||
{
|
||||
/// <summary>Content of the morning summary. Null when there is nothing worth showing.</summary>
|
||||
public sealed record DailySummaryData(
|
||||
IReadOnlyList<ReminderTask> Today,
|
||||
IReadOnlyList<ReminderTask> Overdue,
|
||||
IReadOnlyList<ReminderTask> AnniversariesSoon);
|
||||
|
||||
public static class DailySummary
|
||||
{
|
||||
/// <summary>Days ahead in which anniversaries are announced (tomorrow … in 3 days).</summary>
|
||||
public const int AnniversaryDays = 3;
|
||||
|
||||
public static DailySummaryData? Build(IEnumerable<ReminderTask> tasks, DateTime now)
|
||||
{
|
||||
var open = tasks.Where(t => !t.IsNotified).ToList();
|
||||
var today = open.Where(t => t.ReminderDate.Date == now.Date).OrderBy(t => t.ReminderDate).ToList();
|
||||
var overdue = open.Where(t => !t.IsRecurring && t.ReminderDate.Date < now.Date).OrderBy(t => t.ReminderDate).ToList();
|
||||
var soon = open.Where(t => t.IsAnniversary)
|
||||
.Where(t => (t.ReminderDate.Date - now.Date).Days is > 0 and <= AnniversaryDays)
|
||||
.OrderBy(t => t.ReminderDate).ToList();
|
||||
return today.Count + overdue.Count + soon.Count == 0 ? null : new DailySummaryData(today, overdue, soon);
|
||||
}
|
||||
|
||||
/// <summary>Should the summary be shown now? Once per day, from <paramref name="hour"/> on.</summary>
|
||||
public static bool IsDue(DateTime now, int hour, DateTime? lastShown) =>
|
||||
now.Hour >= hour && (lastShown == null || lastShown.Value.Date < now.Date);
|
||||
}
|
||||
}
|
||||
@@ -196,5 +196,22 @@
|
||||
"CatPlaceholderYears": "Anzahl der Jahre",
|
||||
"CatPlaceholderOrdinal": "Ordnungszahl (25.)",
|
||||
"CatChangeLook": "Symbol und Farbe ändern",
|
||||
"AddCategoryShort": "Kategorie"
|
||||
"AddCategoryShort": "Kategorie",
|
||||
"Snooze10": "10 Min",
|
||||
"Snooze60": "1 Std",
|
||||
"SnoozeTomorrow": "Morgen",
|
||||
"ToastDone": "Erledigt",
|
||||
"SummarySetting": "Tagesübersicht",
|
||||
"SummarySettingHint": "Einmal am Tag: heutige Einträge, nahe Geburtstage und Überfälliges.",
|
||||
"SummaryTitle": "Dein Tag",
|
||||
"SummaryToday": "Heute:",
|
||||
"SummaryOverdue": "{0} überfällig",
|
||||
"DataFolderHint": "Für mehrere PCs einen synchronisierten Ordner wählen, z. B. in OneDrive.",
|
||||
"ChangeFolder": "Ändern…",
|
||||
"ChooseDataFolder": "Datenordner wählen",
|
||||
"DataFolderHasData": "In diesem Ordner liegen schon Erinnerungen.\n\nJa = die Erinnerungen dort verwenden\nNein = sie durch meine ersetzen",
|
||||
"ImportIcs": "Kalender importieren (.ics)",
|
||||
"IcsImported": "{0} Einträge importiert, {1} übersprungen",
|
||||
"IcsNothingNew": "Keine neuen Einträge gefunden ({0} übersprungen – schon vorhanden oder vergangen).",
|
||||
"FolderBirthdays": "Geburtstage"
|
||||
}
|
||||
|
||||
@@ -196,5 +196,22 @@
|
||||
"CatPlaceholderYears": "number of years",
|
||||
"CatPlaceholderOrdinal": "ordinal (25th)",
|
||||
"CatChangeLook": "Change icon and color",
|
||||
"AddCategoryShort": "Category"
|
||||
"AddCategoryShort": "Category",
|
||||
"Snooze10": "10 min",
|
||||
"Snooze60": "1 hour",
|
||||
"SnoozeTomorrow": "Tomorrow",
|
||||
"ToastDone": "Done",
|
||||
"SummarySetting": "Morning summary",
|
||||
"SummarySettingHint": "Once a day: today's entries, upcoming birthdays and anything overdue.",
|
||||
"SummaryTitle": "Your day",
|
||||
"SummaryToday": "Today:",
|
||||
"SummaryOverdue": "{0} overdue",
|
||||
"DataFolderHint": "For several PCs choose a synced folder, e.g. in OneDrive.",
|
||||
"ChangeFolder": "Change…",
|
||||
"ChooseDataFolder": "Choose data folder",
|
||||
"DataFolderHasData": "This folder already contains reminders.\n\nYes = use the reminders in that folder\nNo = replace them with mine",
|
||||
"ImportIcs": "Import calendar (.ics)",
|
||||
"IcsImported": "{0} entries imported, {1} skipped",
|
||||
"IcsNothingNew": "No new entries found ({0} skipped – already there or in the past).",
|
||||
"FolderBirthdays": "Birthdays"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
@@ -62,6 +63,10 @@ namespace ReminderOrganizer
|
||||
|
||||
// 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()
|
||||
@@ -207,6 +212,48 @@ namespace ReminderOrganizer
|
||||
_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)
|
||||
@@ -284,17 +331,71 @@ namespace ReminderOrganizer
|
||||
|
||||
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) =>
|
||||
// WPF menu instead of the WinForms one, so it uses the app's theme styles.
|
||||
_notifyIcon.MouseUp += (s, e) =>
|
||||
{
|
||||
App.Quit();
|
||||
});
|
||||
_notifyIcon.ContextMenuStrip = menu;
|
||||
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();
|
||||
|
||||
@@ -59,6 +59,33 @@ namespace ReminderOrganizer.Models
|
||||
set { if (SetProperty(ref _recurrenceType, value)) OnPropertyChanged(nameof(AgeText)); }
|
||||
}
|
||||
|
||||
private DateTime? _snoozedUntil;
|
||||
/// <summary>Snoozed reminder for recurring entries (the real date stays unchanged).</summary>
|
||||
public DateTime? SnoozedUntil
|
||||
{
|
||||
get => _snoozedUntil;
|
||||
set => SetProperty(ref _snoozedUntil, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Remind me again later": one-off tasks move their date; recurring tasks and anniversaries keep their
|
||||
/// date (it already moved to the next occurrence) and get an extra reminder at <c>now + delay</c>.
|
||||
/// </summary>
|
||||
/// <param name="keepDate">true for a lead ("in 2 days") reminder: the real date must not move.</param>
|
||||
public void Snooze(DateTime until, bool keepDate = false)
|
||||
{
|
||||
if (IsRecurring || keepDate)
|
||||
{
|
||||
SnoozedUntil = until;
|
||||
}
|
||||
else
|
||||
{
|
||||
ReminderDate = until;
|
||||
IsNotified = false;
|
||||
IsPreNotified = true; // the lead reminder is long past
|
||||
}
|
||||
}
|
||||
|
||||
private int _leadDays;
|
||||
/// <summary>Extra reminder this many days before the date (0 = none).</summary>
|
||||
public int LeadDays
|
||||
@@ -242,6 +269,13 @@ namespace ReminderOrganizer.Models
|
||||
foreach (var task in folder.Tasks)
|
||||
{
|
||||
if (task.IsNotified) continue;
|
||||
// snoozed reminder of a recurring entry: fire once, keep the real date
|
||||
if (task.SnoozedUntil is DateTime snoozed && snoozed <= now)
|
||||
{
|
||||
due.Add(new DueReminder(task, task.ReminderDate, false, task.UpcomingAge));
|
||||
task.SnoozedUntil = null;
|
||||
continue;
|
||||
}
|
||||
if (task.ReminderDate <= now)
|
||||
{
|
||||
due.Add(new DueReminder(task, task.ReminderDate, false, task.UpcomingAge));
|
||||
@@ -344,6 +378,11 @@ namespace ReminderOrganizer.Models
|
||||
public double? WindowHeight { get; set; }
|
||||
public bool WindowMaximized { get; set; }
|
||||
|
||||
/// <summary>Morning summary: on/off, hour, last day it was shown.</summary>
|
||||
public bool DailySummary { get; set; } = true;
|
||||
public int SummaryHour { get; set; } = 8;
|
||||
public DateTime? LastSummaryDate { get; set; }
|
||||
|
||||
/// <summary>"list", "compact" or "cards".</summary>
|
||||
public string ViewMode { get; set; } = "list";
|
||||
/// <summary>Group the list by month (collapsible).</summary>
|
||||
|
||||
@@ -16,17 +16,20 @@ It runs in the system tray (notification area).
|
||||
("25th anniversary · Silver"), Jubilee, Memorial day, plus your own (Settings → Categories: icon, color, text)
|
||||
- Sidebar **Categories** shows every birthday / wedding … across all folders
|
||||
- Views **list / compact / cards**; **group by month** (click a month to fold it)
|
||||
- Reminders missed while the app was closed are shown at the next start, with a reminder sound (can be turned off)
|
||||
- Windows notifications with **snooze** (10 min, 1 hour, tomorrow) and **Done**; missed reminders are shown at the next start, with a reminder sound (can be turned off)
|
||||
- **Morning summary** once a day (time adjustable): today's entries, birthdays in the next 3 days, overdue items
|
||||
- **Folder colors** and order (drag or context menu); drag a task onto a folder to move it
|
||||
- **Undo** after deleting (Ctrl+Z), shortcuts Ctrl+N (new task), Del, Esc
|
||||
- CSV import/export (`Folder;Name;Description;Date;IsRecurring;RecurrenceType`, date `yyyy-MM-dd HH:mm`)
|
||||
- **Calendar export (.ics)** for Outlook, Google and Apple Calendar (recurrence + advance reminder included)
|
||||
- **Calendar import and export (.ics)** for Outlook, Google and Apple Calendar (recurrence, advance reminder, birthdays incl. Google's birthday calendar; re-importing skips existing entries)
|
||||
- **Data folder selectable** (e.g. OneDrive) – several PCs share the same reminders; changes from another PC are loaded automatically
|
||||
- Keyboard: arrow keys / Home / End move through the list, Space marks done
|
||||
- Dark/light theme, German/English; the first start follows the Windows settings
|
||||
- Autostart with Windows, starting hidden in the tray (`--minimized`)
|
||||
|
||||
## Data
|
||||
|
||||
Tasks are stored in `%APPDATA%\ReminderOrganizer\tasks.json`. The app keeps `tasks.json.bak` as a backup
|
||||
Tasks are stored in `%APPDATA%\ReminderOrganizer\tasks.json`, or in the folder chosen under Settings → Data (pointer file `location.json`). The app keeps `tasks.json.bak` as a backup
|
||||
of the previous save, and saves a broken file as `tasks.json.corrupt-<time>` instead of overwriting it.
|
||||
`error.log` is in the same folder.
|
||||
On first start, an older `tasks.json` next to the exe is copied over automatically.
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -23,14 +23,56 @@ namespace ReminderOrganizer.Services
|
||||
|
||||
private readonly SemaphoreSlim _writeLock = new(1, 1);
|
||||
|
||||
public string DataFilePath { get; }
|
||||
public string DataFilePath { get; private set; }
|
||||
public string DataDirectory => Path.GetDirectoryName(DataFilePath)!;
|
||||
|
||||
/// <summary>%APPDATA%\ReminderOrganizer – or REMINDER_ORGANIZER_DATA (for tests/screenshots).</summary>
|
||||
public static string DefaultDataDirectory =>
|
||||
/// <summary>Time stamp of our own last write – a different one means another PC (sync) changed the file.</summary>
|
||||
public DateTime LastWriteUtc { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// App folder (pointer file, error log): %APPDATA%\ReminderOrganizer – or REMINDER_ORGANIZER_DATA (tests/screenshots).
|
||||
/// </summary>
|
||||
public static string AppDirectory =>
|
||||
Environment.GetEnvironmentVariable("REMINDER_ORGANIZER_DATA") is { Length: > 0 } custom
|
||||
? custom
|
||||
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ReminderOrganizer");
|
||||
|
||||
/// <summary>Where tasks.json lives: the folder chosen in Settings (e.g. OneDrive), otherwise the app folder.</summary>
|
||||
public static string DefaultDataDirectory => ReadPointer(AppDirectory) ?? AppDirectory;
|
||||
|
||||
private const string PointerFile = "location.json";
|
||||
|
||||
/// <summary>Chosen data folder from location.json, or null (none / folder gone).</summary>
|
||||
public static string? ReadPointer(string appDirectory)
|
||||
{
|
||||
try
|
||||
{
|
||||
var file = Path.Combine(appDirectory, PointerFile);
|
||||
if (!File.Exists(file)) return null;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file));
|
||||
var folder = doc.RootElement.TryGetProperty("DataFolder", out var p) ? p.GetString() : null;
|
||||
return !string.IsNullOrWhiteSpace(folder) && Directory.Exists(folder) ? folder : null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stores the data folder; null or the app folder itself removes the pointer.</summary>
|
||||
public static void WritePointer(string appDirectory, string? folder)
|
||||
{
|
||||
Directory.CreateDirectory(appDirectory);
|
||||
var file = Path.Combine(appDirectory, PointerFile);
|
||||
if (string.IsNullOrWhiteSpace(folder) ||
|
||||
string.Equals(Path.GetFullPath(folder).TrimEnd('\\'), Path.GetFullPath(appDirectory).TrimEnd('\\'), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (File.Exists(file)) File.Delete(file);
|
||||
return;
|
||||
}
|
||||
File.WriteAllText(file, JsonSerializer.Serialize(new { DataFolder = folder }, _jsonOptions));
|
||||
}
|
||||
|
||||
public DataService() : this(DefaultDataDirectory) { }
|
||||
|
||||
public DataService(string dataDirectory)
|
||||
@@ -39,6 +81,62 @@ namespace ReminderOrganizer.Services
|
||||
DataFilePath = Path.Combine(dataDirectory, "tasks.json");
|
||||
}
|
||||
|
||||
/// <summary>Use another folder from now on (after moving or adopting its tasks.json).</summary>
|
||||
public void SwitchTo(string dataDirectory)
|
||||
{
|
||||
StopWatching();
|
||||
Directory.CreateDirectory(dataDirectory);
|
||||
DataFilePath = Path.Combine(dataDirectory, "tasks.json");
|
||||
LastWriteUtc = File.Exists(DataFilePath) ? File.GetLastWriteTimeUtc(DataFilePath) : default;
|
||||
}
|
||||
|
||||
// ---------- sync: notice changes made by another PC ----------
|
||||
|
||||
private FileSystemWatcher? _watcher;
|
||||
private Timer? _debounce;
|
||||
|
||||
/// <summary>Calls <paramref name="onExternalChange"/> (thread pool) when tasks.json changes and it wasn't us.</summary>
|
||||
public void StartWatching(Action onExternalChange)
|
||||
{
|
||||
StopWatching();
|
||||
if (File.Exists(DataFilePath)) LastWriteUtc = File.GetLastWriteTimeUtc(DataFilePath);
|
||||
_debounce = new Timer(_ =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (IsExternalChange()) onExternalChange();
|
||||
}
|
||||
catch { /* file busy – next event */ }
|
||||
});
|
||||
_watcher = new FileSystemWatcher(DataDirectory, "tasks.json")
|
||||
{
|
||||
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size,
|
||||
EnableRaisingEvents = true
|
||||
};
|
||||
FileSystemEventHandler h = (_, _) => _debounce?.Change(1000, Timeout.Infinite); // sync tools write in bursts
|
||||
_watcher.Changed += h;
|
||||
_watcher.Created += h;
|
||||
_watcher.Renamed += (_, _) => _debounce?.Change(1000, Timeout.Infinite);
|
||||
}
|
||||
|
||||
public void StopWatching()
|
||||
{
|
||||
_watcher?.Dispose();
|
||||
_watcher = null;
|
||||
_debounce?.Dispose();
|
||||
_debounce = null;
|
||||
}
|
||||
|
||||
/// <summary>True if the file on disk is newer than our own last write.</summary>
|
||||
public bool IsExternalChange()
|
||||
{
|
||||
if (!File.Exists(DataFilePath)) return false;
|
||||
var stamp = File.GetLastWriteTimeUtc(DataFilePath);
|
||||
if (Math.Abs((stamp - LastWriteUtc).TotalMilliseconds) < 50) return false;
|
||||
LastWriteUtc = stamp;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Copies tasks.json from an old location (next to the exe) if no data exists yet.</summary>
|
||||
public void MigrateFrom(string? legacyDirectory)
|
||||
{
|
||||
@@ -105,6 +203,7 @@ namespace ReminderOrganizer.Services
|
||||
File.Replace(tmp, DataFilePath, DataFilePath + ".bak");
|
||||
else
|
||||
File.Move(tmp, DataFilePath);
|
||||
LastWriteUtc = File.GetLastWriteTimeUtc(DataFilePath); // our own write is not a "sync change"
|
||||
}
|
||||
|
||||
public async Task SaveAsync(AppData data)
|
||||
|
||||
189
Services/IcsImport.cs
Normal file
189
Services/IcsImport.cs
Normal file
@@ -0,0 +1,189 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using ReminderOrganizer.Models;
|
||||
|
||||
namespace ReminderOrganizer.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// iCalendar (.ics) import – counterpart of <see cref="IcsExport"/>. Reads Outlook, Google (incl. the birthday
|
||||
/// calendar) and Apple exports. All-day yearly events become anniversaries.
|
||||
/// </summary>
|
||||
public static class IcsImport
|
||||
{
|
||||
public sealed record Result(List<ReminderTask> Tasks, int Skipped);
|
||||
|
||||
/// <param name="existingIds">Ids already in the app – events with the same UID are skipped (safe re-import).</param>
|
||||
public static Result Parse(string ics, ISet<string> existingIds, DateTime now)
|
||||
{
|
||||
var tasks = new List<ReminderTask>();
|
||||
int skipped = 0;
|
||||
Dictionary<string, (string Params, string Value)>? ev = null;
|
||||
bool inAlarm = false;
|
||||
string? trigger = null;
|
||||
|
||||
foreach (var line in Unfold(ics))
|
||||
{
|
||||
if (line.Equals("BEGIN:VEVENT", StringComparison.OrdinalIgnoreCase)) { ev = new(StringComparer.OrdinalIgnoreCase); trigger = null; continue; }
|
||||
if (ev == null) continue;
|
||||
if (line.Equals("BEGIN:VALARM", StringComparison.OrdinalIgnoreCase)) { inAlarm = true; continue; }
|
||||
if (line.Equals("END:VALARM", StringComparison.OrdinalIgnoreCase)) { inAlarm = false; continue; }
|
||||
if (line.Equals("END:VEVENT", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var task = ToTask(ev, trigger, existingIds, now);
|
||||
if (task == null) skipped++;
|
||||
else { tasks.Add(task); existingIds.Add(task.Id); }
|
||||
ev = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
int colon = line.IndexOf(':');
|
||||
if (colon <= 0) continue;
|
||||
var head = line[..colon];
|
||||
var value = line[(colon + 1)..];
|
||||
int semi = head.IndexOf(';');
|
||||
var name = semi < 0 ? head : head[..semi];
|
||||
var parameters = semi < 0 ? "" : head[(semi + 1)..];
|
||||
|
||||
if (inAlarm)
|
||||
{
|
||||
if (name.Equals("TRIGGER", StringComparison.OrdinalIgnoreCase)) trigger ??= value;
|
||||
continue;
|
||||
}
|
||||
ev.TryAdd(name, (parameters, value));
|
||||
}
|
||||
return new Result(tasks, skipped);
|
||||
}
|
||||
|
||||
private static ReminderTask? ToTask(Dictionary<string, (string Params, string Value)> ev, string? trigger,
|
||||
ISet<string> existingIds, DateTime now)
|
||||
{
|
||||
if (!ev.TryGetValue("SUMMARY", out var summary) || string.IsNullOrWhiteSpace(summary.Value)) return null;
|
||||
if (!ev.TryGetValue("DTSTART", out var start) || !TryParseDate(start.Params, start.Value, out var date, out bool allDay)) return null;
|
||||
|
||||
var uid = ev.TryGetValue("UID", out var u) && !string.IsNullOrWhiteSpace(u.Value) ? u.Value.Trim() : null;
|
||||
if (uid != null && existingIds.Contains(uid)) return null;
|
||||
|
||||
var freq = ev.TryGetValue("RRULE", out var rrule) ? Regex.Match(rrule.Value, @"FREQ=(\w+)", RegexOptions.IgnoreCase).Groups[1].Value.ToUpperInvariant() : "";
|
||||
var name = Unescape(summary.Value).Trim();
|
||||
var description = ev.TryGetValue("DESCRIPTION", out var d) ? Unescape(d.Value).Trim() : "";
|
||||
|
||||
var task = new ReminderTask { Name = name, Description = description };
|
||||
if (uid != null) task.Id = uid;
|
||||
task.LeadDays = LeadDaysFrom(trigger, allDay);
|
||||
|
||||
if (allDay && freq == "YEARLY")
|
||||
{
|
||||
// anniversary: birthday, wedding, …
|
||||
task.IsAnniversary = true;
|
||||
task.IsRecurring = true;
|
||||
task.RecurrenceType = RecurrenceType.Yearly;
|
||||
task.CategoryId = GuessCategory(name + " " + description);
|
||||
if (date.Year < now.Year && date.Year >= 1900) task.BirthYear = date.Year;
|
||||
// our own export writes "Oma (86)" with the date of the next occurrence → year = date year − age
|
||||
var age = Regex.Match(name, @"\s*\((\d{1,3})\)\s*$");
|
||||
if (age.Success)
|
||||
{
|
||||
int y = date.Year - int.Parse(age.Groups[1].Value, CultureInfo.InvariantCulture);
|
||||
if (y >= 1900 && y <= now.Year) task.BirthYear = y;
|
||||
name = name[..age.Index];
|
||||
}
|
||||
task.ReminderDate = ReminderTask.NextBirthday(date.Day, date.Month, now.Date);
|
||||
task.Name = StripCategoryWords(name);
|
||||
return task;
|
||||
}
|
||||
|
||||
if (allDay) date = date.Date.AddHours(ReminderTask.BirthdayHour);
|
||||
task.ReminderDate = date;
|
||||
if (freq is "DAILY" or "WEEKLY" or "MONTHLY" or "YEARLY")
|
||||
{
|
||||
task.IsRecurring = true;
|
||||
task.RecurrenceType = freq switch
|
||||
{
|
||||
"DAILY" => RecurrenceType.Daily,
|
||||
"WEEKLY" => RecurrenceType.Weekly,
|
||||
"MONTHLY" => RecurrenceType.Monthly,
|
||||
_ => RecurrenceType.Yearly
|
||||
};
|
||||
if (task.ReminderDate <= now) task.ReminderDate = task.GetNextOccurrence(now);
|
||||
}
|
||||
else if (date <= now)
|
||||
{
|
||||
return null; // past one-off events are not imported
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
/// <summary>Google's birthday calendar writes "Anna's birthday" / "Geburtstag von Anna" – keep just the name.</summary>
|
||||
private static string StripCategoryWords(string name)
|
||||
{
|
||||
var n = Regex.Replace(name, @"^(Geburtstag von|Geburtstag:)\s*", "", RegexOptions.IgnoreCase);
|
||||
n = Regex.Replace(n, @"(['’]s)?\s+(birthday|Geburtstag)$", "", RegexOptions.IgnoreCase);
|
||||
return string.IsNullOrWhiteSpace(n) ? name : n.Trim();
|
||||
}
|
||||
|
||||
public static string GuessCategory(string text)
|
||||
{
|
||||
var t = text.ToLowerInvariant();
|
||||
if (t.Contains("hochzeit") || t.Contains("wedding") || t.Contains("anniversary") || t.Contains("jahrestag")) return Category.WeddingId;
|
||||
if (t.Contains("jubiläum") || t.Contains("jubilaeum") || t.Contains("jubilee")) return Category.JubileeId;
|
||||
if (t.Contains("todestag") || t.Contains("gedenk") || t.Contains("memorial")) return Category.MemorialId;
|
||||
return Category.BirthdayId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "-P2D", "-PT24H", "-P1W" → days before (0 when none or after the start). All-day events start at
|
||||
/// midnight, so "-PT15H" means "the day before at 09:00" → rounded up; timed events round down.
|
||||
/// </summary>
|
||||
public static int LeadDaysFrom(string? trigger, bool allDay = false)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(trigger) || !trigger.TrimStart().StartsWith("-")) return 0;
|
||||
var m = Regex.Match(trigger, @"P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?)?", RegexOptions.IgnoreCase);
|
||||
if (!m.Success) return 0;
|
||||
int Val(int g) => m.Groups[g].Success ? int.Parse(m.Groups[g].Value, CultureInfo.InvariantCulture) : 0;
|
||||
int hours = (Val(1) * 7 + Val(2)) * 24 + Val(3);
|
||||
int days = allDay ? (hours + 23) / 24 : hours / 24;
|
||||
return days switch { <= 0 => 0, 1 => 1, 2 => 2, <= 4 => 3, _ => 7 }; // nearest option of the app
|
||||
}
|
||||
|
||||
public static bool TryParseDate(string parameters, string value, out DateTime date, out bool allDay)
|
||||
{
|
||||
value = value.Trim();
|
||||
allDay = parameters.Contains("VALUE=DATE", StringComparison.OrdinalIgnoreCase) && !parameters.Contains("VALUE=DATE-TIME", StringComparison.OrdinalIgnoreCase)
|
||||
|| value.Length == 8;
|
||||
if (allDay)
|
||||
return DateTime.TryParseExact(value[..Math.Min(8, value.Length)], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
|
||||
|
||||
bool utc = value.EndsWith("Z", StringComparison.OrdinalIgnoreCase);
|
||||
if (!DateTime.TryParseExact(value.TrimEnd('Z', 'z'), new[] { "yyyyMMdd'T'HHmmss", "yyyyMMdd'T'HHmm" },
|
||||
CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
|
||||
return false;
|
||||
if (utc) date = DateTime.SpecifyKind(date, DateTimeKind.Utc).ToLocalTime();
|
||||
date = DateTime.SpecifyKind(date, DateTimeKind.Unspecified); // TZID / floating: treat as local time
|
||||
return true;
|
||||
}
|
||||
|
||||
public static IEnumerable<string> Unfold(string ics)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
foreach (var raw in ics.Replace("\r\n", "\n").Split('\n'))
|
||||
{
|
||||
if (raw.Length > 0 && (raw[0] == ' ' || raw[0] == '\t'))
|
||||
{
|
||||
sb.Append(raw, 1, raw.Length - 1);
|
||||
continue;
|
||||
}
|
||||
if (sb.Length > 0) yield return sb.ToString();
|
||||
sb.Clear().Append(raw.TrimEnd('\r'));
|
||||
}
|
||||
if (sb.Length > 0) yield return sb.ToString();
|
||||
}
|
||||
|
||||
public static string Unescape(string s) =>
|
||||
Regex.Replace(s, @"\\([\\;,nN])", m => m.Groups[1].Value is "n" or "N" ? "\n" : m.Groups[1].Value);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
#nullable enable
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
@@ -12,11 +12,17 @@ namespace ReminderOrganizer.Services
|
||||
Task SaveAsync(AppData data);
|
||||
void Save(AppData data);
|
||||
string DataFilePath { get; }
|
||||
string DataDirectory { get; }
|
||||
void SwitchTo(string dataDirectory);
|
||||
void StartWatching(Action onExternalChange);
|
||||
void StopWatching();
|
||||
}
|
||||
|
||||
public interface INotificationService
|
||||
{
|
||||
void ShowNotification(string title, string message);
|
||||
/// <summary>Reminder with snooze/done buttons for one task.</summary>
|
||||
void ShowReminder(string title, string message, string taskId, bool isLead);
|
||||
}
|
||||
|
||||
public interface ILocalizationService
|
||||
|
||||
@@ -1,51 +1,117 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Toolkit.Uwp.Notifications;
|
||||
|
||||
namespace ReminderOrganizer.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Windows toast notifications (Action Center) with snooze buttons. Falls back to the tray balloon if toasts
|
||||
/// are not available (e.g. notifications turned off or an old Windows build).
|
||||
/// </summary>
|
||||
public class NotificationService : INotificationService
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
private readonly ILocalizationService _loc;
|
||||
private string? _logoPath;
|
||||
|
||||
public static NotifyIcon? SharedTrayIcon { get; set; }
|
||||
|
||||
public NotificationService(ILocalizationService localizationService)
|
||||
{
|
||||
_loc = localizationService;
|
||||
}
|
||||
|
||||
public void ShowNotification(string title, string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"[NotificationService] ShowNotification: {title} - {message}");
|
||||
System.Diagnostics.Debug.WriteLine($"[NotificationService] SharedTrayIcon is null: {SharedTrayIcon == null}");
|
||||
ShowBalloonTip(title, message);
|
||||
Builder(title, message).AddArgument("action", "open").Show();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"[NotificationService] Error: {ex.Message}");
|
||||
System.Diagnostics.Debug.WriteLine($"[Toast] {ex.Message}");
|
||||
ShowBalloon(title, message);
|
||||
}
|
||||
}
|
||||
|
||||
private void ShowBalloonTip(string title, string message)
|
||||
public void ShowReminder(string title, string message, string taskId, bool isLead)
|
||||
{
|
||||
lock (_lock)
|
||||
try
|
||||
{
|
||||
if (SharedTrayIcon != null)
|
||||
{
|
||||
// ShowBalloonTip throws on empty text – tasks without description would never notify.
|
||||
SharedTrayIcon.BalloonTipTitle = string.IsNullOrWhiteSpace(title) ? "Reminder Organizer" : title;
|
||||
SharedTrayIcon.BalloonTipText = string.IsNullOrWhiteSpace(message) ? " " : message;
|
||||
SharedTrayIcon.BalloonTipIcon = ToolTipIcon.Info;
|
||||
SharedTrayIcon.ShowBalloonTip(5000);
|
||||
System.Diagnostics.Debug.WriteLine("[NotificationService] BalloonTip shown!");
|
||||
}
|
||||
else
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine("[NotificationService] SharedTrayIcon is null, cannot show balloon tip!");
|
||||
}
|
||||
string lead = isLead ? "1" : "0";
|
||||
ToastButton Snooze(string label, string minutes) => new ToastButton()
|
||||
.SetContent(label)
|
||||
.AddArgument("action", "snooze").AddArgument("min", minutes)
|
||||
.AddArgument("id", taskId).AddArgument("lead", lead)
|
||||
.SetBackgroundActivation();
|
||||
|
||||
Builder(title, message)
|
||||
.AddArgument("action", "open").AddArgument("id", taskId)
|
||||
.AddButton(Snooze(_loc.GetString("Snooze10"), "10"))
|
||||
.AddButton(Snooze(_loc.GetString("Snooze60"), "60"))
|
||||
.AddButton(Snooze(_loc.GetString("SnoozeTomorrow"), "tomorrow"))
|
||||
.AddButton(new ToastButton()
|
||||
.SetContent(_loc.GetString("ToastDone"))
|
||||
.AddArgument("action", "done").AddArgument("id", taskId).AddArgument("lead", lead)
|
||||
.SetBackgroundActivation())
|
||||
.Show();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"[Toast] {ex.Message}");
|
||||
ShowBalloon(title, message);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
private ToastContentBuilder Builder(string title, string message)
|
||||
{
|
||||
var b = new ToastContentBuilder()
|
||||
.AddText(string.IsNullOrWhiteSpace(title) ? "Reminder Organizer" : title);
|
||||
if (!string.IsNullOrWhiteSpace(message)) b.AddText(message);
|
||||
if (LogoPath() is { } logo) b.AddAppLogoOverride(new Uri(logo), ToastGenericAppLogoCrop.Default);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Toasts need the logo as a file – extract it once to the app folder.</summary>
|
||||
private string? LogoPath()
|
||||
{
|
||||
if (_logoPath != null) return _logoPath;
|
||||
try
|
||||
{
|
||||
var path = Path.Combine(DataService.AppDirectory, "toast-logo.png");
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
var res = System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/Assets/app.png"));
|
||||
if (res == null) return null;
|
||||
Directory.CreateDirectory(DataService.AppDirectory);
|
||||
using var fs = File.Create(path);
|
||||
res.Stream.CopyTo(fs);
|
||||
}
|
||||
return _logoPath = path;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void ShowBalloon(string title, string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (SharedTrayIcon == null) return;
|
||||
// ShowBalloonTip throws on empty text – tasks without description would never notify.
|
||||
SharedTrayIcon.BalloonTipTitle = string.IsNullOrWhiteSpace(title) ? "Reminder Organizer" : title;
|
||||
SharedTrayIcon.BalloonTipText = string.IsNullOrWhiteSpace(message) ? " " : message;
|
||||
SharedTrayIcon.BalloonTipIcon = ToolTipIcon.Info;
|
||||
SharedTrayIcon.ShowBalloonTip(5000);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"[Balloon] {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +117,23 @@
|
||||
<CheckBox DockPanel.Dock="Right" Style="{StaticResource ToggleSwitch}" IsChecked="{Binding IsAutostartEnabled}" VerticalAlignment="Center"/>
|
||||
</DockPanel>
|
||||
<Border Style="{StaticResource Divider}"/>
|
||||
<DockPanel Style="{StaticResource Row}">
|
||||
<StackPanel DockPanel.Dock="Left" MaxWidth="300">
|
||||
<TextBlock Text="{Binding [SummarySetting]}"/>
|
||||
<TextBlock Text="{Binding [SummarySettingHint]}" Style="{StaticResource RowHint}"/>
|
||||
</StackPanel>
|
||||
<CheckBox DockPanel.Dock="Right" Style="{StaticResource ToggleSwitch}" IsChecked="{Binding DailySummaryEnabled}" VerticalAlignment="Center"/>
|
||||
<ComboBox DockPanel.Dock="Right" Width="92" Margin="0,0,16,0" VerticalAlignment="Center"
|
||||
ItemsSource="{Binding SummaryHours}" SelectedItem="{Binding SummaryHour}"
|
||||
IsEnabled="{Binding DailySummaryEnabled}">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding StringFormat={}{0}:00}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
</DockPanel>
|
||||
<Border Style="{StaticResource Divider}"/>
|
||||
<DockPanel Style="{StaticResource Row}">
|
||||
<TextBlock Text="{Binding [TestNotificationHint]}" Style="{StaticResource RowLabel}"/>
|
||||
<Button DockPanel.Dock="Right" Content="{Binding [TestNow]}" Style="{StaticResource SubtleButton}" Command="{Binding TestNotificationCommand}"/>
|
||||
@@ -157,12 +174,16 @@
|
||||
<Border Style="{StaticResource Group}">
|
||||
<StackPanel>
|
||||
<DockPanel Style="{StaticResource Row}">
|
||||
<StackPanel DockPanel.Dock="Left" MaxWidth="330">
|
||||
<StackPanel DockPanel.Dock="Left" MaxWidth="300">
|
||||
<TextBlock Text="{Binding [SetDataFolder]}"/>
|
||||
<TextBlock Text="{Binding DataFolder}" Style="{StaticResource RowHint}" TextTrimming="CharacterEllipsis" TextWrapping="NoWrap"
|
||||
ToolTip="{Binding DataFolder}"/>
|
||||
<TextBlock Text="{Binding [DataFolderHint]}" Style="{StaticResource RowHint}"/>
|
||||
</StackPanel>
|
||||
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal" VerticalAlignment="Top">
|
||||
<Button Content="{Binding [OpenFolder]}" Style="{StaticResource SubtleButton}" Command="{Binding OpenDataFolderCommand}" Margin="0,0,8,0"/>
|
||||
<Button Content="{Binding [ChangeFolder]}" Style="{StaticResource SubtleButton}" Command="{Binding ChangeDataFolderCommand}"/>
|
||||
</StackPanel>
|
||||
<Button DockPanel.Dock="Right" Content="{Binding [OpenFolder]}" Style="{StaticResource SubtleButton}" Command="{Binding OpenDataFolderCommand}"/>
|
||||
</DockPanel>
|
||||
<Border Style="{StaticResource Divider}"/>
|
||||
<DockPanel Style="{StaticResource Row}">
|
||||
@@ -178,7 +199,10 @@
|
||||
<TextBlock Text="{Binding [SetCalendar]}"/>
|
||||
<TextBlock Text="{Binding [SetCalendarHint]}" Style="{StaticResource RowHint}"/>
|
||||
</StackPanel>
|
||||
<Button DockPanel.Dock="Right" Content="{Binding [Export]}" Style="{StaticResource SubtleButton}" Command="{Binding ExportIcsCommand}"/>
|
||||
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
|
||||
<Button Content="{Binding [Import]}" Style="{StaticResource SubtleButton}" Command="{Binding ImportIcsCommand}" Margin="0,0,8,0"/>
|
||||
<Button Content="{Binding [Export]}" Style="{StaticResource SubtleButton}" Command="{Binding ExportIcsCommand}"/>
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
159
Tests/ImportSnoozeTests.cs
Normal file
159
Tests/ImportSnoozeTests.cs
Normal file
@@ -0,0 +1,159 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using ReminderOrganizer.Core;
|
||||
using ReminderOrganizer.Models;
|
||||
using ReminderOrganizer.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ReminderOrganizer.Tests
|
||||
{
|
||||
public class SnoozeTests
|
||||
{
|
||||
private static readonly DateTime Now = new(2026, 11, 29, 10, 0, 0);
|
||||
|
||||
[Fact]
|
||||
public void One_off_task_moves_its_date()
|
||||
{
|
||||
var t = new ReminderTask("Call", "", Now.AddMinutes(-1)) { IsNotified = true };
|
||||
t.Snooze(Now.AddMinutes(10));
|
||||
Assert.False(t.IsNotified);
|
||||
Assert.Equal(Now.AddMinutes(10), t.ReminderDate);
|
||||
Assert.Null(t.SnoozedUntil);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Recurring_task_keeps_date_and_fires_once_more()
|
||||
{
|
||||
var next = new DateTime(2027, 11, 29, 9, 0, 0);
|
||||
var t = new ReminderTask("Oma", "", next) { IsRecurring = true, RecurrenceType = RecurrenceType.Yearly, IsAnniversary = true };
|
||||
var f = new Folder("f");
|
||||
f.Tasks.Add(t);
|
||||
|
||||
t.Snooze(Now.AddHours(1));
|
||||
Assert.Equal(next, t.ReminderDate);
|
||||
|
||||
Assert.Empty(ReminderTask.ProcessDue(new[] { f }, Now.AddMinutes(30)));
|
||||
var due = ReminderTask.ProcessDue(new[] { f }, Now.AddHours(1));
|
||||
Assert.Single(due);
|
||||
Assert.Null(t.SnoozedUntil);
|
||||
Assert.Equal(next, t.ReminderDate);
|
||||
Assert.Empty(ReminderTask.ProcessDue(new[] { f }, Now.AddHours(2)));
|
||||
}
|
||||
}
|
||||
|
||||
public class DailySummaryTests
|
||||
{
|
||||
private static readonly DateTime Now = new(2026, 11, 29, 8, 0, 0);
|
||||
|
||||
[Fact]
|
||||
public void Collects_today_overdue_and_upcoming_anniversaries()
|
||||
{
|
||||
var tasks = new[]
|
||||
{
|
||||
new ReminderTask("Dentist", "", Now.Date.AddHours(10)),
|
||||
new ReminderTask("Tax", "", Now.AddDays(-2)),
|
||||
new ReminderTask("Done", "", Now.AddDays(-2)) { IsNotified = true },
|
||||
new ReminderTask("Oma", "", Now.Date.AddDays(1).AddHours(9)) { IsAnniversary = true, IsRecurring = true },
|
||||
new ReminderTask("Later", "", Now.Date.AddDays(10).AddHours(9)) { IsAnniversary = true, IsRecurring = true },
|
||||
};
|
||||
var s = DailySummary.Build(tasks, Now)!;
|
||||
Assert.Equal(new[] { "Dentist" }, s.Today.Select(t => t.Name));
|
||||
Assert.Equal(new[] { "Tax" }, s.Overdue.Select(t => t.Name));
|
||||
Assert.Equal(new[] { "Oma" }, s.AnniversariesSoon.Select(t => t.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Nothing_to_say_is_null()
|
||||
{
|
||||
Assert.Null(DailySummary.Build(new[] { new ReminderTask("x", "", Now.AddDays(20)) }, Now));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Once_per_day_from_the_hour()
|
||||
{
|
||||
Assert.False(DailySummary.IsDue(Now.Date.AddHours(7), 8, null));
|
||||
Assert.True(DailySummary.IsDue(Now.Date.AddHours(8), 8, null));
|
||||
Assert.False(DailySummary.IsDue(Now.Date.AddHours(9), 8, Now.Date.AddHours(8)));
|
||||
Assert.True(DailySummary.IsDue(Now.Date.AddDays(1).AddHours(9), 8, Now.Date.AddHours(8)));
|
||||
}
|
||||
}
|
||||
|
||||
public class IcsImportTests
|
||||
{
|
||||
private static readonly DateTime Now = new(2026, 11, 29, 10, 0, 0);
|
||||
|
||||
[Fact]
|
||||
public void Round_trip_with_own_export()
|
||||
{
|
||||
var data = new AppData();
|
||||
var f = new Folder("F");
|
||||
f.Tasks.Add(new ReminderTask("Oma", "Kuchen; Blumen", new DateTime(2027, 1, 27, 9, 0, 0))
|
||||
{ IsAnniversary = true, IsRecurring = true, RecurrenceType = RecurrenceType.Yearly, BirthYear = 1941, LeadDays = 1 });
|
||||
f.Tasks.Add(new ReminderTask("Team", "", new DateTime(2026, 12, 7, 9, 30, 0))
|
||||
{ IsRecurring = true, RecurrenceType = RecurrenceType.Weekly, LeadDays = 2 });
|
||||
data.Folders.Add(f);
|
||||
var ics = IcsExport.Build(data, DateTime.UtcNow);
|
||||
|
||||
var r = IcsImport.Parse(ics, new HashSet<string>(), Now);
|
||||
Assert.Equal(0, r.Skipped);
|
||||
var oma = r.Tasks.Single(t => t.Name == "Oma");
|
||||
Assert.True(oma.IsAnniversary);
|
||||
Assert.Equal(1941, oma.BirthYear);
|
||||
Assert.Equal(1, oma.LeadDays);
|
||||
Assert.Equal("Kuchen; Blumen", oma.Description);
|
||||
Assert.Equal(new DateTime(2027, 1, 27, 9, 0, 0), oma.ReminderDate);
|
||||
var team = r.Tasks.Single(t => t.Name == "Team");
|
||||
Assert.Equal(RecurrenceType.Weekly, team.RecurrenceType);
|
||||
Assert.Equal(new DateTime(2026, 12, 7, 9, 30, 0), team.ReminderDate);
|
||||
Assert.Equal(2, team.LeadDays);
|
||||
|
||||
// importing the same file again changes nothing
|
||||
var ids = new HashSet<string>(r.Tasks.Select(t => t.Id));
|
||||
var again = IcsImport.Parse(ics, ids, Now);
|
||||
Assert.Empty(again.Tasks);
|
||||
Assert.Equal(2, again.Skipped);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Google_birthday_calendar()
|
||||
{
|
||||
var ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART;VALUE=DATE:19860319\r\nRRULE:FREQ=YEARLY\r\n" +
|
||||
"SUMMARY:Michael's birthday\r\nUID:abc@google.com\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
|
||||
var t = IcsImport.Parse(ics, new HashSet<string>(), Now).Tasks.Single();
|
||||
Assert.Equal("Michael", t.Name);
|
||||
Assert.True(t.IsAnniversary);
|
||||
Assert.Equal(Category.BirthdayId, t.CategoryId);
|
||||
Assert.Equal(1986, t.BirthYear);
|
||||
Assert.Equal(new DateTime(2027, 3, 19, 9, 0, 0), t.ReminderDate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wedding_folded_lines_utc_and_past_events()
|
||||
{
|
||||
var ics = string.Join("\r\n",
|
||||
"BEGIN:VCALENDAR",
|
||||
"BEGIN:VEVENT", "DTSTART;VALUE=DATE:20010812", "RRULE:FREQ=YEARLY", "SUMMARY:Hochzeitstag Lea + Max", "END:VEVENT",
|
||||
"BEGIN:VEVENT", "DTSTART:20261215T130000Z", "SUMMARY:Arzt mit einem sehr langen", " Namen", "END:VEVENT",
|
||||
"BEGIN:VEVENT", "DTSTART:20200101T100000", "SUMMARY:Alt", "END:VEVENT",
|
||||
"END:VCALENDAR", "");
|
||||
var r = IcsImport.Parse(ics, new HashSet<string>(), Now);
|
||||
Assert.Equal(1, r.Skipped);
|
||||
Assert.Equal(Category.WeddingId, r.Tasks[0].CategoryId);
|
||||
Assert.Equal(2001, r.Tasks[0].BirthYear);
|
||||
// RFC 5545: the continuation's single leading space is removed
|
||||
Assert.Equal("Arzt mit einem sehr langenNamen", r.Tasks[1].Name);
|
||||
Assert.Equal(DateTimeKind.Unspecified, r.Tasks[1].ReminderDate.Kind);
|
||||
Assert.Equal(new DateTime(2026, 12, 15, 13, 0, 0, DateTimeKind.Utc).ToLocalTime().Hour, r.Tasks[1].ReminderDate.Hour);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("-P1D", false, 1)]
|
||||
[InlineData("-PT15H", true, 1)]
|
||||
[InlineData("-PT15H", false, 0)]
|
||||
[InlineData("-P1W", false, 7)]
|
||||
[InlineData("PT9H", true, 0)]
|
||||
public void Lead_days(string trigger, bool allDay, int expected) =>
|
||||
Assert.Equal(expected, IcsImport.LeadDaysFrom(trigger, allDay));
|
||||
}
|
||||
}
|
||||
66
Tests/SyncTests.cs
Normal file
66
Tests/SyncTests.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using ReminderOrganizer.Models;
|
||||
using ReminderOrganizer.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ReminderOrganizer.Tests
|
||||
{
|
||||
public class SyncTests : IDisposable
|
||||
{
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "ro-sync-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(_root, true); } catch { }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pointer_file_round_trip()
|
||||
{
|
||||
var app = Path.Combine(_root, "app");
|
||||
var cloud = Path.Combine(_root, "OneDrive", "Reminders");
|
||||
Directory.CreateDirectory(cloud);
|
||||
|
||||
Assert.Null(DataService.ReadPointer(app));
|
||||
DataService.WritePointer(app, cloud);
|
||||
Assert.Equal(cloud, DataService.ReadPointer(app));
|
||||
|
||||
DataService.WritePointer(app, app); // back to the app folder = no pointer
|
||||
Assert.Null(DataService.ReadPointer(app));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pointer_to_missing_folder_is_ignored()
|
||||
{
|
||||
var app = Path.Combine(_root, "app");
|
||||
DataService.WritePointer(app, Path.Combine(_root, "gone"));
|
||||
Directory.CreateDirectory(Path.Combine(_root, "gone"));
|
||||
Directory.Delete(Path.Combine(_root, "gone"));
|
||||
Assert.Null(DataService.ReadPointer(app));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Own_writes_are_not_external_but_other_writes_are()
|
||||
{
|
||||
var ds = new DataService(Path.Combine(_root, "data"));
|
||||
await ds.SaveAsync(new AppData());
|
||||
Assert.False(ds.IsExternalChange());
|
||||
|
||||
await Task.Delay(30);
|
||||
File.WriteAllText(ds.DataFilePath, "{\"Folders\":[]}"); // "another PC"
|
||||
File.SetLastWriteTimeUtc(ds.DataFilePath, DateTime.UtcNow.AddSeconds(2));
|
||||
Assert.True(ds.IsExternalChange());
|
||||
Assert.False(ds.IsExternalChange()); // reported once
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Switching_folder_uses_new_file()
|
||||
{
|
||||
var ds = new DataService(Path.Combine(_root, "a"));
|
||||
ds.SwitchTo(Path.Combine(_root, "b"));
|
||||
Assert.Equal(Path.Combine(_root, "b", "tasks.json"), ds.DataFilePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
|
||||
<!--
|
||||
Shared control styles. Colors are DynamicResources set by Core/Theme.cs on Application.Resources,
|
||||
@@ -601,6 +601,179 @@
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- ========== calendar (popup of the date picker) ========== -->
|
||||
<Style x:Key="CalendarNavButton" TargetType="Button" BasedOn="{StaticResource IconButton}">
|
||||
<Setter Property="FontSize" Value="10"/>
|
||||
<Setter Property="Width" Value="28"/>
|
||||
<Setter Property="Height" Value="28"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="CalendarHeaderButton" TargetType="Button">
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
<Setter Property="FontFamily" Value="{StaticResource UiFont}"/>
|
||||
<Setter Property="FontSize" Value="13"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border x:Name="Bd" Background="Transparent" CornerRadius="6" Padding="10,4">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource HoverBrush}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="AppCalendarDayButton" TargetType="CalendarDayButton">
|
||||
<Setter Property="FontFamily" Value="{StaticResource UiFont}"/>
|
||||
<Setter Property="FontSize" Value="12.5"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="CalendarDayButton">
|
||||
<Border x:Name="Bd" Width="32" Height="30" Margin="1" CornerRadius="6" BorderThickness="1"
|
||||
Background="Transparent" BorderBrush="Transparent">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsInactive" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextTertiaryBrush}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource HoverBrush}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsToday" Value="True">
|
||||
<Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource PrimaryBrush}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource PrimaryBrush}"/>
|
||||
<Setter Property="Foreground" Value="White"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsBlackedOut" Value="True">
|
||||
<Setter Property="Opacity" Value="0.35"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="AppCalendarButton" TargetType="CalendarButton">
|
||||
<Setter Property="FontFamily" Value="{StaticResource UiFont}"/>
|
||||
<Setter Property="FontSize" Value="12.5"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="CalendarButton">
|
||||
<Border x:Name="Bd" Width="52" Height="44" Margin="2" CornerRadius="6" Background="Transparent">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsInactive" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextTertiaryBrush}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource HoverBrush}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="HasSelectedDays" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource AccentSubtleBrush}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="AppCalendarItem" TargetType="CalendarItem">
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="CalendarItem">
|
||||
<ControlTemplate.Resources>
|
||||
<DataTemplate x:Key="{x:Static CalendarItem.DayTitleTemplateResourceKey}">
|
||||
<TextBlock Text="{Binding}" FontFamily="{StaticResource UiFont}" FontSize="11" FontWeight="SemiBold"
|
||||
HorizontalAlignment="Center" Margin="0,2,0,6" Foreground="{DynamicResource TextTertiaryBrush}"/>
|
||||
</DataTemplate>
|
||||
</ControlTemplate.Resources>
|
||||
<Grid x:Name="PART_Root">
|
||||
<Border Background="{DynamicResource MenuBackgroundBrush}" BorderBrush="{DynamicResource BorderBrush}" BorderThickness="1"
|
||||
CornerRadius="8" Padding="10" Margin="6,2,6,10">
|
||||
<Border.Effect>
|
||||
<DropShadowEffect BlurRadius="14" ShadowDepth="3" Opacity="0.22" Color="Black"/>
|
||||
</Border.Effect>
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
<Grid Margin="0,0,0,6">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button x:Name="PART_PreviousButton" Content="" Style="{StaticResource CalendarNavButton}" Focusable="False"/>
|
||||
<Button x:Name="PART_HeaderButton" Grid.Column="1" Style="{StaticResource CalendarHeaderButton}" Focusable="False"/>
|
||||
<Button x:Name="PART_NextButton" Grid.Column="2" Content="" Style="{StaticResource CalendarNavButton}" Focusable="False"/>
|
||||
</Grid>
|
||||
<Grid x:Name="PART_MonthView" Grid.Row="1" Visibility="Visible">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/>
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition/><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/>
|
||||
</Grid.ColumnDefinitions>
|
||||
</Grid>
|
||||
<Grid x:Name="PART_YearView" Grid.Row="1" Visibility="Hidden">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition/><RowDefinition/><RowDefinition/>
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition/><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/>
|
||||
</Grid.ColumnDefinitions>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Border>
|
||||
<Rectangle x:Name="PART_DisabledVisual" Fill="Transparent" Visibility="Collapsed"/>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding DisplayMode, RelativeSource={RelativeSource AncestorType=Calendar}}" Value="Year">
|
||||
<Setter TargetName="PART_MonthView" Property="Visibility" Value="Hidden"/>
|
||||
<Setter TargetName="PART_YearView" Property="Visibility" Value="Visible"/>
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding DisplayMode, RelativeSource={RelativeSource AncestorType=Calendar}}" Value="Decade">
|
||||
<Setter TargetName="PART_MonthView" Property="Visibility" Value="Hidden"/>
|
||||
<Setter TargetName="PART_YearView" Property="Visibility" Value="Visible"/>
|
||||
</DataTrigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="AppCalendar" TargetType="Calendar">
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
<Setter Property="CalendarItemStyle" Value="{StaticResource AppCalendarItem}"/>
|
||||
<Setter Property="CalendarDayButtonStyle" Value="{StaticResource AppCalendarDayButton}"/>
|
||||
<Setter Property="CalendarButtonStyle" Value="{StaticResource AppCalendarButton}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Calendar">
|
||||
<StackPanel x:Name="PART_Root" HorizontalAlignment="Center">
|
||||
<CalendarItem x:Name="PART_CalendarItem" Style="{TemplateBinding CalendarItemStyle}"/>
|
||||
</StackPanel>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- ========== date picker (text field + calendar button) ========== -->
|
||||
<Style TargetType="DatePickerTextBox">
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
@@ -617,8 +790,11 @@
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="Calendar" BasedOn="{StaticResource AppCalendar}"/>
|
||||
|
||||
<Style TargetType="DatePicker">
|
||||
<Setter Property="FontFamily" Value="{StaticResource UiFont}"/>
|
||||
<Setter Property="CalendarStyle" Value="{StaticResource AppCalendar}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
<Setter Property="MinHeight" Value="32"/>
|
||||
<Setter Property="Template">
|
||||
|
||||
@@ -221,7 +221,8 @@ namespace ReminderOrganizer.ViewModels
|
||||
if (ThemeMode == "system") ApplyThemeMode();
|
||||
}
|
||||
|
||||
public string DataFolder => DataService.DefaultDataDirectory;
|
||||
private string _dataFolder = DataService.DefaultDataDirectory;
|
||||
public string DataFolder { get => _dataFolder; private set => SetProperty(ref _dataFolder, value); }
|
||||
|
||||
// ---------- window placement ----------
|
||||
|
||||
@@ -446,6 +447,8 @@ namespace ReminderOrganizer.ViewModels
|
||||
public ICommand ImportCsvCommand { get; }
|
||||
public ICommand ExportCsvCommand { get; }
|
||||
public ICommand ExportIcsCommand { get; }
|
||||
public ICommand ImportIcsCommand { get; }
|
||||
public ICommand ChangeDataFolderCommand { get; }
|
||||
public ICommand OpenDiscordCommand { get; }
|
||||
public ICommand ShowUpcomingCommand { get; }
|
||||
public ICommand UndoCommand { get; }
|
||||
@@ -507,6 +510,8 @@ namespace ReminderOrganizer.ViewModels
|
||||
ImportCsvCommand = new RelayCommand(ImportCsv);
|
||||
ExportCsvCommand = new RelayCommand(ExportCsv);
|
||||
ExportIcsCommand = new RelayCommand(ExportIcs);
|
||||
ImportIcsCommand = new RelayCommand(ImportIcs);
|
||||
ChangeDataFolderCommand = new RelayCommand(ChangeDataFolder);
|
||||
OpenDiscordCommand = new RelayCommand(OpenDiscord);
|
||||
ShowUpcomingCommand = new RelayCommand(() => ShowCategory(null));
|
||||
ShowCategoryCommand = new RelayCommand<string>(ShowCategory);
|
||||
@@ -548,7 +553,7 @@ namespace ReminderOrganizer.ViewModels
|
||||
_appData.ThemeMode = firstRun ? "system" : (_appData.IsDarkMode.Value ? "dark" : "light");
|
||||
_isDarkMode = ThemeMode switch { "light" => false, "dark" => true, _ => SystemPrefs.IsDarkMode() };
|
||||
_appData.IsDarkMode = _isDarkMode;
|
||||
_appData.Folders.CollectionChanged += (s, e) => { HookFolders(); ReindexTasks(); };
|
||||
_appData.Folders.CollectionChanged += OnFoldersChanged;
|
||||
HookFolders();
|
||||
ReindexTasks();
|
||||
|
||||
@@ -557,6 +562,7 @@ namespace ReminderOrganizer.ViewModels
|
||||
|
||||
CheckReminders(); // catch up on reminders missed while the app was closed
|
||||
_reminderTimer.Start();
|
||||
_dataService.StartWatching(OnDataFileChangedExternally); // another PC (OneDrive …) changed the file
|
||||
IsLoading = false;
|
||||
}
|
||||
|
||||
@@ -841,31 +847,36 @@ namespace ReminderOrganizer.ViewModels
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Most single reminders (with snooze buttons) per check; more are combined into one message.</summary>
|
||||
private const int MaxSingleToasts = 3;
|
||||
|
||||
private void CheckReminders()
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
var due = ReminderTask.ProcessDue(_appData.Folders, now);
|
||||
|
||||
if (due.Count == 1)
|
||||
if (due.Count is > 0 and <= MaxSingleToasts)
|
||||
{
|
||||
var d = due[0];
|
||||
var title = d.IsLead ? $"⏰ {d.Task.Name} · {WhenText(d.Date, now)}" : $"🔔 {d.Task.Name}";
|
||||
var parts = new List<string>();
|
||||
if (d.Age is int age) parts.Add(string.Format(L("TurnsAge"), age));
|
||||
if (!string.IsNullOrWhiteSpace(d.Task.Description)) parts.Add(d.Task.Description);
|
||||
if (parts.Count == 0) parts.Add(d.IsLead ? d.Date.ToString("dd.MM.yyyy HH:mm") : L("Reminder"));
|
||||
_notificationService.ShowNotification(title, string.Join(" · ", parts));
|
||||
foreach (var d in due)
|
||||
{
|
||||
var title = d.IsLead ? $"{d.Task.Name} · {WhenText(d.Date, now)}" : d.Task.Name;
|
||||
var parts = new List<string>();
|
||||
if (d.Age is int age) parts.Add(d.Task.AgeText ?? string.Format(L("TurnsAge"), age));
|
||||
if (!string.IsNullOrWhiteSpace(d.Task.Description)) parts.Add(d.Task.Description);
|
||||
if (parts.Count == 0) parts.Add(d.Task.IsAnniversary ? d.Task.DisplayDate : d.Date.ToString("dd.MM.yyyy HH:mm"));
|
||||
_notificationService.ShowReminder(title, string.Join(" · ", parts), d.Task.Id, d.IsLead);
|
||||
}
|
||||
}
|
||||
else if (due.Count > 1)
|
||||
else if (due.Count > MaxSingleToasts)
|
||||
{
|
||||
// A balloon replaces the previous one – show one summary instead of losing reminders.
|
||||
var lines = due.Take(6).Select(d => (d.IsLead ? "⏰ " : "🔔 ") + d.Task.Name +
|
||||
(d.IsLead ? $" ({WhenText(d.Date, now)})" : ""));
|
||||
var lines = due.Take(6).Select(d => d.Task.Name + (d.IsLead ? $" ({WhenText(d.Date, now)})" : ""));
|
||||
var body = string.Join("\n", lines) + (due.Count > 6 ? "\n…" : "");
|
||||
_notificationService.ShowNotification(string.Format(L("RemindersCount"), due.Count), body);
|
||||
}
|
||||
|
||||
if (due.Count > 0)
|
||||
bool summaryShown = ShowDailySummaryIfDue(now);
|
||||
|
||||
if (due.Count > 0 || summaryShown)
|
||||
{
|
||||
if (PlaySound) SoundService.PlayReminder();
|
||||
_ = SaveAsync();
|
||||
@@ -876,6 +887,225 @@ namespace ReminderOrganizer.ViewModels
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- morning summary ----------
|
||||
|
||||
public bool DailySummaryEnabled
|
||||
{
|
||||
get => _appData.DailySummary;
|
||||
set { if (_appData.DailySummary == value) return; _appData.DailySummary = value; OnPropertyChanged(); _ = SaveAsync(); }
|
||||
}
|
||||
|
||||
public IReadOnlyList<int> SummaryHours { get; } = new[] { 6, 7, 8, 9, 10, 11 };
|
||||
|
||||
public int SummaryHour
|
||||
{
|
||||
get => _appData.SummaryHour;
|
||||
set { if (_appData.SummaryHour == value) return; _appData.SummaryHour = value; OnPropertyChanged(); _ = SaveAsync(); }
|
||||
}
|
||||
|
||||
private bool ShowDailySummaryIfDue(DateTime now)
|
||||
{
|
||||
if (!_appData.DailySummary || !DailySummary.IsDue(now, _appData.SummaryHour, _appData.LastSummaryDate)) return false;
|
||||
_appData.LastSummaryDate = now.Date;
|
||||
var s = DailySummary.Build(_allTasks, now);
|
||||
if (s == null) return true; // nothing today – remember the day, but stay quiet
|
||||
|
||||
var parts = new List<string>();
|
||||
if (s.Today.Count > 0)
|
||||
parts.Add(L("SummaryToday") + " " + string.Join(", ", s.Today.Select(t =>
|
||||
t.IsAnniversary ? t.Name + (t.AgeText is { } a ? $" ({a})" : "") : $"{t.Name} {t.ReminderDate:HH:mm}")));
|
||||
if (s.AnniversariesSoon.Count > 0)
|
||||
parts.Add(string.Join(", ", s.AnniversariesSoon.Select(t =>
|
||||
$"{RelativeText(t.ReminderDate, now)}: {t.Name}" + (t.AgeText is { } a ? $" ({a})" : ""))));
|
||||
if (s.Overdue.Count > 0)
|
||||
parts.Add(string.Format(L("SummaryOverdue"), s.Overdue.Count));
|
||||
_notificationService.ShowNotification(L("SummaryTitle"), string.Join("\n", parts));
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------- toast buttons ----------
|
||||
|
||||
public ReminderTask? FindTask(string? id) =>
|
||||
string.IsNullOrEmpty(id) ? null : _allTasks.FirstOrDefault(t => t.Id == id);
|
||||
|
||||
/// <summary>Snooze / done / open from a Windows notification.</summary>
|
||||
public void HandleToastAction(string action, string? id, string? minutes, bool isLead)
|
||||
{
|
||||
var task = FindTask(id);
|
||||
switch (action)
|
||||
{
|
||||
case "snooze" when task != null:
|
||||
var now = DateTime.Now;
|
||||
var until = minutes == "tomorrow"
|
||||
? now.Date.AddDays(1).AddHours(ReminderTask.BirthdayHour)
|
||||
: now.AddMinutes(int.TryParse(minutes, out var m) ? m : 10);
|
||||
task.Snooze(until, keepDate: isLead);
|
||||
_ = SaveAsync();
|
||||
break;
|
||||
|
||||
case "done" when task != null:
|
||||
task.SnoozedUntil = null;
|
||||
if (isLead)
|
||||
{
|
||||
// done before the date: no main reminder (recurring → next occurrence)
|
||||
task.IsNotified = true;
|
||||
ToggleDone(task);
|
||||
}
|
||||
_ = SaveAsync();
|
||||
break;
|
||||
|
||||
case "open":
|
||||
if (task != null)
|
||||
{
|
||||
if (IsUpcomingMode || SelectedFolder?.Tasks.Contains(task) != true)
|
||||
ShowCategory(null);
|
||||
SelectedTask = task;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- data folder (sync) ----------
|
||||
|
||||
private void ChangeDataFolder()
|
||||
{
|
||||
var dialog = new Microsoft.Win32.OpenFolderDialog { Title = L("ChooseDataFolder"), InitialDirectory = DataFolder };
|
||||
if (dialog.ShowDialog(ActiveOwner!) != true) return;
|
||||
var target = dialog.FolderName;
|
||||
if (string.Equals(System.IO.Path.GetFullPath(target).TrimEnd('\\'), System.IO.Path.GetFullPath(DataFolder).TrimEnd('\\'),
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
return;
|
||||
|
||||
var targetFile = System.IO.Path.Combine(target, "tasks.json");
|
||||
bool useExisting = false;
|
||||
if (System.IO.File.Exists(targetFile))
|
||||
{
|
||||
var answer = MessageBox.Show(ActiveOwner!, L("DataFolderHasData"), L("AppTitle"),
|
||||
MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
|
||||
if (answer == MessageBoxResult.Cancel) return;
|
||||
useExisting = answer == MessageBoxResult.Yes;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_dataService.Save(_appData);
|
||||
if (!useExisting) System.IO.File.Copy(_dataService.DataFilePath, targetFile, overwrite: true);
|
||||
DataService.WritePointer(DataService.AppDirectory, target);
|
||||
_dataService.SwitchTo(target);
|
||||
_dataService.StartWatching(OnDataFileChangedExternally);
|
||||
DataFolder = _dataService.DataDirectory;
|
||||
if (useExisting) _ = ReloadFromDiskAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(string.Format(L("ExportError"), ex.Message), L("AppTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Called from the file watcher (thread pool) when another PC changed tasks.json.</summary>
|
||||
private void OnDataFileChangedExternally() =>
|
||||
Application.Current?.Dispatcher.BeginInvoke(new Action(() => _ = ReloadFromDiskAsync()));
|
||||
|
||||
/// <summary>Replaces the data with the file on disk (sync), keeping this PC's view and window.</summary>
|
||||
private async Task ReloadFromDiskAsync()
|
||||
{
|
||||
var fresh = await _dataService.LoadAsync();
|
||||
if (fresh.Folders.Count == 0) return; // half-synced or broken file: keep what we have
|
||||
|
||||
fresh.WindowLeft = _appData.WindowLeft;
|
||||
fresh.WindowTop = _appData.WindowTop;
|
||||
fresh.WindowWidth = _appData.WindowWidth;
|
||||
fresh.WindowHeight = _appData.WindowHeight;
|
||||
fresh.WindowMaximized = _appData.WindowMaximized;
|
||||
|
||||
var selectedId = SelectedFolder?.Id;
|
||||
bool upcoming = IsUpcomingMode;
|
||||
var category = CategoryFilter;
|
||||
|
||||
_appData.Folders.CollectionChanged -= OnFoldersChanged;
|
||||
foreach (var f in _hooked)
|
||||
{
|
||||
f.Tasks.CollectionChanged -= OnFolderTasksChanged;
|
||||
f.PropertyChanged -= OnFolderPropertyChanged;
|
||||
}
|
||||
_hooked.Clear();
|
||||
|
||||
_appData = fresh;
|
||||
_appData.EnsureDefaultCategories(L);
|
||||
_appData.IsDarkMode ??= _isDarkMode;
|
||||
_localizationService.Initialize(_appData);
|
||||
_appData.Folders.CollectionChanged += OnFoldersChanged;
|
||||
HookFolders();
|
||||
ReindexTasks();
|
||||
ApplyThemeMode();
|
||||
|
||||
_selectedFolder = null;
|
||||
OnPropertyChanged(string.Empty);
|
||||
if (upcoming) ShowCategory(category);
|
||||
else SelectFolder(_appData.Folders.FirstOrDefault(f => f.Id == selectedId) ?? _appData.Folders.FirstOrDefault());
|
||||
}
|
||||
|
||||
private void OnFoldersChanged(object? sender, NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
HookFolders();
|
||||
ReindexTasks();
|
||||
}
|
||||
|
||||
// ---------- calendar import ----------
|
||||
|
||||
private void ImportIcs()
|
||||
{
|
||||
var dialog = new Microsoft.Win32.OpenFileDialog { Filter = "iCalendar (*.ics)|*.ics", Title = L("ImportIcs") };
|
||||
if (dialog.ShowDialog(ActiveOwner!) != true) return;
|
||||
|
||||
try
|
||||
{
|
||||
var ids = new HashSet<string>(_allTasks.Select(t => t.Id));
|
||||
var result = IcsImport.Parse(System.IO.File.ReadAllText(dialog.FileName), ids, DateTime.Now);
|
||||
if (result.Tasks.Count == 0)
|
||||
{
|
||||
MessageBox.Show(ActiveOwner!, string.Format(L("IcsNothingNew"), result.Skipped), L("AppTitle"));
|
||||
return;
|
||||
}
|
||||
|
||||
// anniversaries go to a matching folder ("Birthdays", "Weddings" …), appointments to the current folder
|
||||
var added = new List<(Folder Folder, ReminderTask Task)>();
|
||||
var createdFolders = new List<Folder>();
|
||||
foreach (var task in result.Tasks)
|
||||
{
|
||||
var folder = task.IsAnniversary ? FolderForCategory(task.CategoryId, createdFolders) : (SelectedFolder ?? Folders.First());
|
||||
folder.Tasks.Add(task);
|
||||
added.Add((folder, task));
|
||||
}
|
||||
_ = SaveAsync();
|
||||
|
||||
OfferUndo(string.Format(L("IcsImported"), added.Count, result.Skipped), () =>
|
||||
{
|
||||
foreach (var (folder, task) in added) folder.Tasks.Remove(task);
|
||||
foreach (var f in createdFolders) if (f.Tasks.Count == 0) _appData.Folders.Remove(f);
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(string.Format(L("ImportError"), ex.Message), L("AppTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private Folder FolderForCategory(string? categoryId, List<Folder> created)
|
||||
{
|
||||
var id = categoryId ?? Category.BirthdayId;
|
||||
var existing = Folders.FirstOrDefault(f => AppData.CategoryHintForFolder(f.Name) == id)
|
||||
?? Folders.FirstOrDefault(f => f.Tasks.Count > 0 && f.Tasks.All(t => t.IsAnniversary && (t.CategoryId ?? Category.BirthdayId) == id));
|
||||
if (existing != null) return existing;
|
||||
|
||||
var cat = _appData.Categories.FirstOrDefault(c => c.Id == id);
|
||||
var folder = new Folder(id == Category.BirthdayId ? L("FolderBirthdays") : cat?.Name ?? L("FolderBirthdays"))
|
||||
{ Color = cat?.Color ?? Folder.DefaultColor };
|
||||
_appData.Folders.Add(folder);
|
||||
created.Add(folder);
|
||||
return folder;
|
||||
}
|
||||
|
||||
private void TestNotification()
|
||||
{
|
||||
_notificationService.ShowNotification(L("TestNotificationTitle"), L("TestNotificationMessage"));
|
||||
|
||||
Reference in New Issue
Block a user