Merge branch 'fix/shell-notify': taskbar progress, OS notifications, shortcuts, job notices, badges, General settings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 11:13:04 +00:00
commit 979a27e3d3
117 files changed
+1807 -190

No files matched your search

@@ -64,7 +64,13 @@ public sealed class AppSettings
public string? Language { get; set; }
public AppTheme Theme { get; set; } = AppTheme.Dark;
public bool RailCollapsed { get; set; }
/// <summary>The first-run consent of BRIEF §21; offered only by builds with <see cref="ProductFeatures.AdsEnabled"/>.</summary>
public bool AnonymousUsageCounts { get; set; }
/// <summary>Toasts also appear as Windows notifications while the window is minimised or in the background (BRIEF §12.1).</summary>
public bool OsNotifications { get; set; } = true;
public WindowPlacement? Window { get; set; }
/// <summary>The first-run choice (local archive, adopted folder or server) was made.</summary>
@@ -0,0 +1,17 @@
using System.Reflection;
namespace Titano.App.Infrastructure;
/// <summary>Features a build switches on through MSBuild properties (Directory.Build.props), read from the assembly metadata.</summary>
public static class ProductFeatures
{
/// <summary>
/// Monetization (BRIEF §21: ads, the anonymous usage counts consent, the licence) ships disabled until a build sets
/// <c>TitanoAdsEnabled=true</c>; until then nothing of it shows.
/// </summary>
public static bool AdsEnabled { get; } = Flag("TitanoAdsEnabled");
private static bool Flag(string key) =>
typeof(ProductFeatures).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>().FirstOrDefault(a => a.Key == key)?.Value is { } value
&& bool.TryParse(value, out var on) && on;
}
@@ -0,0 +1,92 @@
using System.IO;
using System.Security;
using Microsoft.Win32;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
namespace Titano.App.Infrastructure;
/// <summary>Settings › General › Startup: Titano starts when the user signs in to Windows.</summary>
public interface IStartWithWindows
{
bool IsEnabled { get; }
void SetEnabled(bool enabled);
/// <summary>Points this copy's entry at the current executable (after an update renamed it).</summary>
void Refresh();
}
/// <summary>
/// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> value that starts Titano minimised at sign-in, so inserted
/// cards are noticed (BRIEF §12.4) without a window in the way. The registry stays the source of truth because Task
/// Manager can turn it off. There is one value for every copy of Titano: a copy shows it as on only when it starts
/// that copy, and never takes it over or removes it unless the user ticks or unticks the box there. The uninstaller
/// removes it with the Uploader's when it starts a program of the folder it removes.
/// </summary>
public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWithWindows
{
/// <summary>Starts the main window minimised on the taskbar.</summary>
public const string MinimizedOption = "--minimized";
private readonly string? _executable = executable ?? Environment.ProcessPath;
public bool IsEnabled => StartupCommand.Starts(Read(), _executable);
public void SetEnabled(bool enabled)
{
if (_executable is null) return;
try
{
using var key = Registry.CurrentUser.CreateSubKey(StartupCommand.RunKey, writable: true);
if (enabled) key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(_executable, MinimizedOption), RegistryValueKind.String);
else if (StartupCommand.Starts(key.GetValue(StartupCommand.ClientValue) as string, _executable)) key.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false);
}
catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException)
{
Log.Warning("startup", "Run key not updated", ex);
}
}
public void Refresh()
{
if (Follows(Read(), _executable, File.Exists)) SetEnabled(true);
}
/// <summary>
/// The entry should now start <paramref name="current"/>: the program it names is gone from the folder
/// <paramref name="current"/> runs from (an update renamed it). An entry of another copy, still on disk or
/// elsewhere (a second install, a portable copy, a development build), is left alone.
/// </summary>
internal static bool Follows(string? command, string? current, Func<string, bool> exists)
{
if (current is null || StartupCommand.Executable(command) is not { } stored || StartupCommand.Starts(command, current)) return false;
return !exists(stored) && StartupCommand.FolderOf(current) is { } folder
&& string.Equals(StartupCommand.Folder(command), folder, StringComparison.OrdinalIgnoreCase);
}
private static string? Read()
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey);
return key?.GetValue(StartupCommand.ClientValue) as string;
}
catch (Exception ex) when (ex is SecurityException or IOException)
{
return null;
}
}
}
/// <summary>Screenshots, tests and portable copies (which leave nothing in the registry) never touch the user's sign-in programs.</summary>
public sealed class MemoryStartWithWindows : IStartWithWindows
{
public bool IsEnabled { get; private set; }
public void SetEnabled(bool enabled) => IsEnabled = enabled;
public void Refresh()
{
}
}
+7
View File
@@ -137,6 +137,13 @@ public sealed class JobListModel
public int QueuedCount => _entries.Values.Count(e => e.State == JobState.Queued);
/// <summary>
/// A job of <paramref name="kind"/> that the user waits for (not background work) is queued or running. Paused jobs
/// do not count: they wait for the user, or for an unmetered network, not for the queue.
/// </summary>
public bool IsBusy(JobKind kind) =>
_entries.Values.Any(e => e.Job.Kind == kind && e.Job.Priority != JobPriority.Background && e.State is JobState.Queued or JobState.Running);
/// <summary>Same order as <c>JobRepository.ClaimNextAsync</c>: priority descending, then creation time and id.</summary>
public static bool ClaimsBefore(Job a, Job b) =>
a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0;
+98
View File
@@ -0,0 +1,98 @@
using Titano.Core.Model;
namespace Titano.App.Jobs;
/// <summary>What the shell says when a job of this PC ends.</summary>
public enum JobNotice
{
None,
Done,
Failed,
}
/// <summary>
/// Which job endings raise a toast (BRIEF §12.1 "toasts for job completion"): the long operations the user asked for
/// end with one toast, whichever screen started them. Background work (thumbnails, proxies, light analysis, the
/// analysis queued after an import) and scans (the archive is rescanned every 10 minutes) end silently; an import
/// has its own toast when it ends well, and a download shows on its Library card and Server row. Every other failure
/// is said. Cancelled jobs were stopped on purpose.
/// </summary>
public static class JobNotices
{
/// <summary>
/// The notice for <paramref name="job"/> after a change from <paramref name="before"/> (null: not seen before).
/// A job already finished before the change (a repeated event, a page read again) says nothing.
/// </summary>
public static JobNotice For(JobState? before, Job job)
{
ArgumentNullException.ThrowIfNull(job);
if (before is JobState.Done or JobState.Failed or JobState.Cancelled || job.Priority == JobPriority.Background) return JobNotice.None;
return job.State switch
{
JobState.Done when Announces(job.Kind) => JobNotice.Done,
JobState.Failed when !IsUpkeep(job.Kind) => JobNotice.Failed,
_ => JobNotice.None,
};
}
private static bool Announces(JobKind kind) =>
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
or JobKind.Move or JobKind.Adopt;
/// <summary>Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.</summary>
private static bool IsUpkeep(JobKind kind) =>
kind is JobKind.Scan or JobKind.Thumbs or JobKind.Proxies or JobKind.LightAnalyse;
}
/// <summary>Endings said in one toast: one job, or several of a batch.</summary>
public sealed record JobEnding(JobNotice Notice, IReadOnlyList<Job> Jobs);
/// <summary>
/// Job endings waiting for their toast, so that a batch speaks once (Server › Upload all queues one upload per
/// sequence): finished jobs of one kind wait until no job of that kind the user waits for is queued or running, then
/// one toast says how many finished; failures are said at the end of the update that brought them, together when
/// several failed at once. WPF-free; feed it on the UI thread.
/// </summary>
public sealed class JobEndings
{
private readonly SortedDictionary<JobKind, List<Job>> _done = [];
private readonly List<Job> _failed = [];
/// <summary>Finished jobs still waiting for the rest of their kind (tests).</summary>
public int Waiting => _done.Values.Sum(l => l.Count);
public void Add(JobNotice notice, Job job)
{
ArgumentNullException.ThrowIfNull(job);
if (notice == JobNotice.Failed)
{
_failed.Add(job);
}
else if (notice == JobNotice.Done)
{
if (!_done.TryGetValue(job.Kind, out var jobs)) _done[job.Kind] = jobs = [];
jobs.Add(job);
}
}
/// <summary>
/// The toasts due now: the failures added since the last call, then each finished kind that <paramref name="busy"/>
/// no longer reports as queued or running. What is returned is forgotten.
/// </summary>
public IReadOnlyList<JobEnding> Take(Func<JobKind, bool> busy)
{
ArgumentNullException.ThrowIfNull(busy);
var due = new List<JobEnding>();
if (_failed.Count > 0)
{
due.Add(new JobEnding(JobNotice.Failed, [.. _failed]));
_failed.Clear();
}
foreach (var kind in _done.Keys.Where(k => !busy(k)).ToList())
{
due.Add(new JobEnding(JobNotice.Done, _done[kind]));
_done.Remove(kind);
}
return due;
}
}
@@ -493,6 +493,8 @@ public sealed class ArchiveViewModel : SectionViewModel
_ => null,
})),
];
// The rail badge counts the health lines that need attention (BRIEF §12.1 "badge counts (warnings, …)").
Badge = Health.Count(h => !h.IsOk);
}
private static IReadOnlyList<ChartItem> Bars(IReadOnlyList<BarValue> values) =>
+3 -1
View File
@@ -1399,7 +1399,7 @@ public sealed class ImportViewModel : SectionViewModel
if (_phase == ImportPhase.Failed && _jobId is not null && _jobSourceKey == device.Identity)
{
Shell.Notify(Loc.L("Import.Toast.Inserted", source.Title), Loc.L("Import.Toast.ResumeMessage"), Loc.L("Import.Toast.Resume"),
Loc.L("Tooltips.Import.Resume"), () => RetryCommand.Execute(null));
Loc.L("Tooltips.Import.Resume"), () => RetryCommand.Execute(null), runsFromNotification: true);
return;
}
if (_phase == ImportPhase.Running) return;
@@ -1425,6 +1425,8 @@ public sealed class ImportViewModel : SectionViewModel
SelectSource(device.Identity);
Shell.Navigate(SectionKey.Import);
}),
// BRIEF §12.4: the Windows notification "Card X detected — Import" opens the card on Import.
RunsFromNotification = true,
});
}
+101 -5
View File
@@ -10,6 +10,7 @@ using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Jobs;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
@@ -49,7 +50,8 @@ public sealed class JobFilterChip(JobFilter filter, Action<JobFilter> select) :
/// <summary>
/// Jobs (BRIEF §12.6, Jobs.html): queue and history with live progress from the engine (batched to about 10
/// updates a second), filters, queue order, an expandable log tail per job, and the row actions. Also feeds the
/// shell's job bar, the status strip and the rail badge.
/// shell's job bar, the status strip and the rail badge (running jobs, and failures not seen on this screen yet), and
/// raises the toast of a long operation that ends (<see cref="JobNotices"/>), whichever screen started it.
/// </summary>
public sealed class JobsViewModel : SectionViewModel
{
@@ -59,6 +61,8 @@ public sealed class JobsViewModel : SectionViewModel
private readonly JobListModel _model = new();
private readonly JobUpdateBuffer _buffer = new();
private readonly Dictionary<Guid, JobRowViewModel> _rows = [];
private readonly HashSet<Guid> _unseenFailures = [];
private readonly JobEndings _endings = new();
private readonly JobActions _actions;
private CoalescingThrottle? _throttle;
private IJobQueue? _queue;
@@ -217,13 +221,103 @@ public sealed class JobsViewModel : SectionViewModel
internal void Flush()
{
var (jobs, progress) = _buffer.Drain();
foreach (var job in jobs) _model.Apply(job);
foreach (var job in jobs)
{
var before = _model[job.Id]?.State;
_model.Apply(job);
Follow(before, job);
}
foreach (var p in progress) _model.Apply(p);
foreach (var ending in _endings.Take(_model.IsBusy)) Shell.ShowToast(ToastFor(ending));
SyncRows();
UpdateShell();
}
private void OnJobChanged(Job job)
/// <summary>Failures seen on this screen no longer count on the rail.</summary>
protected override void OnActivated()
{
if (_unseenFailures.Count == 0) return;
_unseenFailures.Clear();
UpdateShell();
}
/// <summary>
/// A change the engine reported (these are live, never pages read again): a failure counts on the rail until this
/// screen is opened, and a long operation that ends is announced at the end of the flush (<see cref="JobEndings"/>).
/// </summary>
private void Follow(JobState? before, Job job)
{
if (job.State != JobState.Failed) _unseenFailures.Remove(job.Id);
else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id);
var notice = JobNotices.For(before, job);
if (notice == JobNotice.Done && EditorAnnounces(job)) return;
_endings.Add(notice, job);
}
/// <summary>
/// The toast of a job that ended, with one action (BRIEF §12.1, §0.2 rule 6). Several endings at once (a batch
/// finished, or failed together) say how many and lead to this screen. Clicking the Windows notification of a
/// toast opens what it names; a retry waits until the user has seen why the job failed.
/// </summary>
private Toast ToastFor(JobEnding ending)
{
var job = ending.Jobs[0];
var failed = ending.Notice == JobNotice.Failed;
if (ending.Jobs.Count > 1)
{
return new Toast
{
Title = Loc.Plural(failed ? "Shell.Job.FailedPlural" : "Shell.Job.DonePlural", ending.Jobs.Count),
Message = ending.Jobs.All(j => j.Kind == job.Kind) ? JobText.Kind(job.Kind) : null,
ActionText = Loc.L("Shell.Nav.Jobs"),
ActionToolTip = Loc.L("Tooltips.Nav.Jobs"),
ActionCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Jobs)),
IsError = failed,
RunsFromNotification = true,
};
}
if (!failed)
{
return new Toast
{
Title = Loc.L("Shell.Job.Done"),
Message = JobText.Name(job),
ActionText = Loc.L("Jobs.Action.Open"),
ActionToolTip = Loc.L("Tooltips.Jobs.Open"),
ActionCommand = new AsyncRelayCommand(() => OpenTargetAsync(job)),
RunsFromNotification = true,
};
}
return job.Kind == JobKind.Import
// The Import screen resumes an import with its plan and card; it holds the retry.
? new Toast
{
Title = Loc.L("Shell.Job.Failed"),
Message = JobText.Name(job),
ActionText = Loc.L("Shell.Nav.Import"),
ActionToolTip = Loc.L("Tooltips.Nav.Import"),
ActionCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import)),
IsError = true,
RunsFromNotification = true,
}
: new Toast
{
Title = Loc.L("Shell.Job.Failed"),
Message = JobText.Name(job),
ActionText = Loc.L("Jobs.Action.Retry"),
ActionToolTip = Loc.L("Tooltips.Jobs.Retry"),
ActionCommand = new AsyncRelayCommand(() => _queue?.ResumeAsync(job.Id) ?? Task.CompletedTask),
IsError = true,
};
}
/// <summary>A finished render of the sequence open in the editor: the editor says it, with its output file.</summary>
private bool EditorAnnounces(Job job) =>
job is { Kind: JobKind.Render, State: JobState.Done } && Shell.Sequence.Editor is { IsRemote: false } editor
&& job.TargetIds.Contains(editor.Session.Content.Sequence.Id);
/// <summary>A job changed state (any thread; tests feed it too): buffered until the next flush.</summary>
internal void OnJobChanged(Job job)
{
_buffer.Post(job);
_throttle?.Signal();
@@ -274,10 +368,12 @@ public sealed class JobsViewModel : SectionViewModel
Shell.SetJob(JobText.Bar(current), current.Fraction ?? 0, indeterminate: current.Fraction is null, name: JobText.Name(current.Job));
else
Shell.SetJob(null, 0);
// The rail badge, the status strip and the Running chip count the same jobs: running or paused (Jobs.html).
// The status strip and the Running chip count the same jobs: running or paused (Jobs.html). The rail badge adds the
// failures not seen here yet, which also turn the taskbar button red while no job runs.
var active = _model.CountOf(JobFilter.Running);
Shell.SetJobCount(active, _model.QueuedCount);
Badge = active;
Shell.SetUnseenFailures(_unseenFailures.Count);
Badge = active + _unseenFailures.Count;
OnPropertyChanged(nameof(WorkersText));
OnPropertyChanged(nameof(HasWorkers));
CommandManager.InvalidateRequerySuggested();
@@ -700,6 +700,7 @@ public sealed class LibraryViewModel : SectionViewModel
_hasArchive = (await _db.Archives.ListAsync()).Count > 0;
Shell.SetLibraryTotals(stats.Sequences, stats.Photos, stats.Bytes);
_localStats = stats;
await CountWarningsAsync();
_suppressReload = true;
var tag = _tag.Value;
@@ -1025,6 +1026,8 @@ public sealed class LibraryViewModel : SectionViewModel
if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit
|| SyncService.TransferKind(job) is SyncTransferKind.DownloadOriginals or SyncTransferKind.GetExports)
await RefreshAsync();
else if (job.Kind is JobKind.LightAnalyse or JobKind.DeepAnalyse)
await CountWarningsAsync();
}
catch (DatabaseException ex)
{
@@ -1032,6 +1035,15 @@ public sealed class LibraryViewModel : SectionViewModel
}
}
/// <summary>
/// The rail badge counts the sequences of this PC with warnings (BRIEF §12.1 "badge counts (warnings, …)"), the
/// ones the Warnings filter shows; analyses change it.
/// </summary>
private async Task CountWarningsAsync()
{
if (_db is not null) Badge = await _db.Sequences.CountAsync(new SequenceQuery { WithStatus = SequenceStatus.HasWarnings });
}
/// <summary>Open: the editor for a sequence here; for a remote card, with proxies (fetched first when this PC has none).</summary>
private async Task OpenAsync(SequenceItem item)
{
+2 -2
View File
@@ -27,7 +27,7 @@
<KeyBinding Key="Z" Modifiers="Control" Command="{Binding UndoCommand}" />
<KeyBinding Key="Y" Modifiers="Control" Command="{Binding RedoCommand}" />
<KeyBinding Key="D0" Modifiers="Control" Command="{Binding FitCommand}" />
<KeyBinding Key="D1" Modifiers="Control" Command="{Binding ActualSizeCommand}" />
<KeyBinding Key="D1" Modifiers="Control+Shift" Command="{Binding ActualSizeCommand}" />
<KeyBinding Key="R" Modifiers="Control" Command="{Binding RenderCommand}" />
<KeyBinding Key="A" Modifiers="Control+Shift" Command="{Binding AnalyseCommand}" />
</Grid.InputBindings>
@@ -141,7 +141,7 @@
IsChecked="{Binding IsCropResult}" ui:ButtonIcon.Glyph="{StaticResource Icon.Eye}" ToolTip="{Binding CropModeToolTip}"
AutomationProperties.Name="{l:Loc Editor.Preview.CropResult}" />
<ToggleButton Visibility="{Binding IsExportTab, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" Style="{StaticResource ToggleButton.PreviewTool}"
IsChecked="{Binding IsActualSize}" Content="{l:Loc Editor.Preview.ActualSize}" ToolTip="{l:Loc Tooltips.Editor.Preview.ActualSize}" />
IsChecked="{Binding IsActualSize}" Content="{l:Loc Editor.Preview.ActualSize}" ToolTip="{l:Loc Tooltips.Editor.Preview.OneToOne}" />
<Button Visibility="{Binding IsExportTab, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" Style="{StaticResource Button.PreviewToolIcon}"
ui:ButtonIcon.Glyph="{StaticResource Icon.Fullscreen}" Click="OnFullScreen" ToolTip="{l:Loc Tooltips.Editor.Preview.FullScreen}"
AutomationProperties.Name="{l:Loc Editor.Preview.FullScreen}" />
@@ -15,9 +15,11 @@ namespace Titano.App.Sections;
/// Server (BRIEF §12.7, Server.html): address with LAN-discovered servers, connect with trust-on-first-use and login,
/// status (name, version, latency, certificate), account and quota, sign out, the options of this PC (render node,
/// proxies kept offline, automatic project sync, uploads paused on metered networks) and the sync table (<see cref="Sync"/>).
/// The rail badge counts the settings conflicts waiting for a choice.
/// </summary>
public sealed class ServerViewModel : SectionViewModel
{
private readonly SyncFilterChip _conflicts;
private string _address;
private string? _errorText;
private ServerSession? _session;
@@ -37,6 +39,8 @@ public sealed class ServerViewModel : SectionViewModel
});
CertificateCommand = new RelayCommand(ShowCertificate, () => Fingerprint is not null);
Sync = new SyncTableViewModel(shell);
_conflicts = Sync.Chips.Single(c => c.Filter == SyncFilter.Conflicts);
_conflicts.PropertyChanged += OnConflictsChanged;
}
/// <summary>Sequences of this PC and of the server, where they stand and what can be done.</summary>
@@ -213,6 +217,7 @@ public sealed class ServerViewModel : SectionViewModel
public override void Dispose()
{
_conflicts.PropertyChanged -= OnConflictsChanged;
if (_session is not null) _session.PropertyChanged -= OnSessionChanged;
Shell.Settings.Encoders.CollectionChanged -= OnEncodersChanged;
Sync.Dispose();
@@ -225,6 +230,11 @@ public sealed class ServerViewModel : SectionViewModel
if (Shell.Settings.Encoders.Count == 0 && !Shell.Settings.IsDetecting) _ = Shell.Settings.DetectEncodersAsync();
}
private void OnConflictsChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName is nameof(SyncFilterChip.Count) or "" or null) Badge = _conflicts.Count;
}
private void SetSyncOption(bool value, bool current, Action<bool> store, [System.Runtime.CompilerServices.CallerMemberName] string? name = null)
{
if (value == current) return;
+10 -1
View File
@@ -134,7 +134,16 @@
<RadioButton Content="{l:Loc Settings.General.Theme.System}" IsChecked="{Binding IsSystemTheme}" ToolTip="{l:Loc Tooltips.Settings.ThemeSystem}" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Usage}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Startup}"
Visibility="{Binding ShowsStartup, Converter={StaticResource BoolToVisibility}}">
<CheckBox Content="{l:Loc Settings.General.StartWithWindows}" IsChecked="{Binding StartWithWindows}" ToolTip="{l:Loc Tooltips.Settings.StartWithWindows}" Margin="0,4,0,0" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Notifications}">
<CheckBox Content="{l:Loc Settings.General.OsNotifications}" IsChecked="{Binding OsNotifications}" ToolTip="{l:Loc Tooltips.Settings.OsNotifications}" Margin="0,4,0,0" />
</HeaderedContentControl>
<!-- Monetization consent (BRIEF §21): only in builds made with TitanoAdsEnabled=true. -->
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.General.Usage}"
Visibility="{Binding ShowsUsageCounts, Converter={StaticResource BoolToVisibility}}">
<CheckBox Content="{l:Loc Settings.General.UsageCounts}" IsChecked="{Binding UsageCounts}" ToolTip="{l:Loc Tooltips.Settings.UsageCounts}" Margin="0,4,0,0" />
</HeaderedContentControl>
</StackPanel>
+40 -1
View File
@@ -56,9 +56,11 @@ public sealed class SettingsViewModel : SectionViewModel
{
Shell = shell;
_s = shell.Services.Settings;
Startup = shell.Services.Environment is { IsCapture: false, IsPortable: false } ? new RunKeyStartWithWindows() : new MemoryStartWithWindows();
AllPages =
[
new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", "Settings.General.Usage"]),
new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", .. ShowsStartup ? (string[])["Settings.General.Startup"] : [],
"Settings.General.Notifications", .. ProductFeatures.AdsEnabled ? (string[])["Settings.General.Usage"] : []]),
new(SettingsPage.Archive, ["Settings.Archive.Root", "Settings.Archive.Folders", "Settings.Archive.Files", "Settings.Archive.Proxies",
"Settings.Archive.Thumbnails", "Settings.Archive.Polling"]),
new(SettingsPage.Import, ["Import.Scan.Sessions", "Import.Label.Scan", "Import.Scan.Subfolders", "Import.Scan.Verify", "Import.Label.Duplicates",
@@ -302,6 +304,40 @@ public sealed class SettingsViewModel : SectionViewModel
}
}
/// <summary>Where "Start with Windows" is kept (the Run key); screenshots, tests and portable copies keep it in memory.</summary>
internal IStartWithWindows Startup { get; set; }
/// <summary>A portable copy leaves nothing in the registry (BRIEF §6.2): it offers no Startup row.</summary>
public bool ShowsStartup => !Shell.Services.Environment.IsPortable;
/// <summary>Titano starts minimised when the user signs in to Windows.</summary>
public bool StartWithWindows
{
get => Startup.IsEnabled;
set
{
if (Startup.IsEnabled == value) return;
Startup.SetEnabled(value);
OnPropertyChanged();
}
}
/// <summary>Toasts also appear as Windows notifications while the window is minimised or in the background.</summary>
public bool OsNotifications
{
get => _s.OsNotifications;
set
{
if (_s.OsNotifications == value) return;
_s.OsNotifications = value;
Save();
OnPropertyChanged();
}
}
/// <summary>The usage counts consent belongs to monetization (BRIEF §21): only builds with it enabled offer it.</summary>
public bool ShowsUsageCounts => ProductFeatures.AdsEnabled;
public bool UsageCounts
{
get => _s.AnonymousUsageCounts;
@@ -762,6 +798,7 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Settings.Advanced.RestoreFailed"), Loc.L("Errors.Backup.Deferred"), isError: true);
break;
}
Startup.Refresh();
}
public override void Dispose()
@@ -1262,6 +1299,8 @@ public sealed class SettingsViewModel : SectionViewModel
{
case SettingsPage.General:
_s.AnonymousUsageCounts = defaults.AnonymousUsageCounts;
_s.OsNotifications = defaults.OsNotifications;
Startup.SetEnabled(false);
ApplyTheme(defaults.Theme);
_s.Language = null;
UiLanguage.Apply(null);
+4 -2
View File
@@ -106,14 +106,16 @@
</RadioButton>
</StackPanel>
<!-- Consent, then Continue (visual and Tab order); the consent has the same label as in Settings. -->
<!-- Consent, then Continue (visual and Tab order); the consent has the same label as in Settings and, like all of
monetization (BRIEF §21), shows only in builds made with TitanoAdsEnabled=true. -->
<Grid Margin="0,20,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<CheckBox Content="{l:Loc Settings.General.UsageCounts}" IsChecked="{Binding UsageCounts}" ToolTip="{l:Loc Tooltips.Settings.UsageCounts}" VerticalAlignment="Center"
HorizontalAlignment="Left" Foreground="{DynamicResource Brush.TextMuted}" />
HorizontalAlignment="Left" Foreground="{DynamicResource Brush.TextMuted}"
Visibility="{Binding ShowsUsageCounts, Converter={StaticResource BoolToVisibility}}" />
<Button Grid.Column="1" Style="{StaticResource Button.Primary}" Height="36" Padding="22,0" Margin="12,0,0,0" Content="{l:Loc Shell.Welcome.Continue}"
Command="{Binding ContinueCommand}" ToolTip="{l:Loc Tooltips.Welcome.Continue}" IsDefault="True" />
</Grid>
@@ -139,6 +139,9 @@ public sealed class WelcomeViewModel : LocalizedViewModel
}
}
/// <summary>The usage counts consent belongs to monetization (BRIEF §21): only builds with it enabled offer it.</summary>
public bool ShowsUsageCounts => ProductFeatures.AdsEnabled;
public bool UsageCounts
{
get => _shell.Services.Settings.AnonymousUsageCounts;
+9 -4
View File
@@ -131,23 +131,28 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) :
return await IdentifyAsync(ct);
}
/// <summary>Sends the credentials; only possible once the server is identified and trusted.</summary>
/// <summary>
/// Sends the credentials; only possible once the server is identified and trusted. An answer that arrives after the
/// flow moved on (disconnected, or connecting elsewhere) changes nothing.
/// </summary>
public async Task<ConnectStep> SignInAsync(string username, string password, CancellationToken ct = default)
{
if (Step is not (ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) || _api is null) return Step;
if (Step is not (ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) || _api is not { } api) return Step;
if (string.IsNullOrWhiteSpace(username)) return Retry(ConnectError.BadCredentials);
Set(ConnectStep.SigningIn, ConnectError.None);
try
{
var login = await _api.LoginAsync(username.Trim(), password, ct);
var login = await api.LoginAsync(username.Trim(), password, ct);
if (!ReferenceEquals(api, _api)) return Step;
if (login.Token is null) return Retry(ConnectError.BadCredentials);
// TitanoClient keeps the token itself; set it explicitly so every IServerApi behaves the same.
_api.Token = login.Token;
api.Token = login.Token;
User = login.User;
return Set(ConnectStep.Connected, ConnectError.None);
}
catch (Exception ex) when (Classify(ex, ct) is { } error)
{
if (!ReferenceEquals(api, _api)) return Step;
return error is ConnectError.BadCredentials ? Retry(error) : Fail(error);
}
}
+9 -3
View File
@@ -144,17 +144,23 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
if (step != ConnectStep.AwaitingCredentials) return false;
}
// The form may be cancelled while the server is still answering: that answer must not sign this PC in.
using var attempt = CancellationTokenSource.CreateLinkedTokenSource(ct);
var signedIn = dialogs.SignIn(display, _settings.ServerUsername, async (user, password) =>
{
var result = await _flow.SignInAsync(user, password, ct);
return result == ConnectStep.Connected ? null : ErrorText(_flow.Error);
var result = await _flow.SignInAsync(user, password, attempt.Token);
// An answer the flow dropped (the form was cancelled meanwhile) carries no error of its own.
return result == ConnectStep.Connected ? null : ErrorText(_flow.Error is ConnectError.None ? ConnectError.Failed : _flow.Error);
});
if (signedIn && IsConnected)
{
Remember();
return true;
}
if (!IsConnected && _flow.Step == ConnectStep.AwaitingCredentials) _flow.Disconnect();
await attempt.CancelAsync();
// Signed in just before the cancel was handled: the session the user turned down ends on the server too.
if (IsConnected) await _flow.SignOutAsync();
else if (_flow.Step is ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) _flow.Disconnect();
return false;
}
finally
+25 -14
View File
@@ -29,7 +29,7 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
private Task _switch = Task.CompletedTask;
private Credentials? _credentials;
private (SyncAgent Agent, ISyncRemote Remote, Credentials Credentials)? _running;
private Running? _running;
private JobEngine? _renders;
/// <summary>Connections over <see cref="TitanoClient"/>; screenshots substitute a fake server.</summary>
@@ -44,10 +44,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
public SyncService? Service { get; private set; }
/// <summary>The background comparison of the signed-in server; null while signed out.</summary>
public SyncAgent? Agent => _running?.Agent;
public SyncAgent? Agent => Volatile.Read(ref _running)?.Agent;
/// <summary>The agent's connection, for the table's own calls (conflict resolution); null while signed out.</summary>
public ISyncRemote? Remote => _running?.Remote;
public ISyncRemote? Remote => Volatile.Read(ref _running)?.Remote;
/// <summary>Key of the signed-in server (<see cref="SyncService.ServerKey"/>); null while signed out.</summary>
public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
@@ -103,8 +103,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// <summary>Compares now, once the session switch in progress settled; null while signed out.</summary>
public async Task<SyncSnapshot?> RefreshAsync(CancellationToken ct = default)
{
await _switch;
return Agent is { } agent ? await agent.RefreshAsync(ct) : null;
await _switch.ConfigureAwait(false);
return Agent is { } agent ? await agent.RefreshAsync(ct).ConfigureAwait(false) : null;
}
/// <summary>Compares again soon (an option changed, an edit on this PC).</summary>
@@ -135,13 +135,17 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
return RemoteFactory(c.Address, c.Token, c.Fingerprints);
}
/// <summary>
/// Stops the agent once the session switch in progress settled. The app's exit waits for this on the UI thread, so
/// nothing here, in the switch or in the stop continues on it.
/// </summary>
public async ValueTask DisposeAsync()
{
Volatile.Write(ref _credentials, null);
Uploads.Dispose();
if (_renders is not null) _renders.JobChanged -= OnJobChanged;
await _switch;
await StopAsync();
await _switch.ConfigureAwait(false);
await StopAsync().ConfigureAwait(false);
}
private bool Allows(Permissions permission) => services.Server.User is { } user && (user.Permissions & (long)permission) != 0;
@@ -183,11 +187,16 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
}
}
/// <summary>
/// Switches are chained (each waits for the previous one) and continue on the thread pool: a switch still stopping
/// the old agent when the app exits must not need the UI thread its exit blocks.
/// </summary>
private async Task SwitchAsync(Task previous, Credentials? wanted)
{
await previous;
if (_running is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token) return;
await StopAsync();
await previous.ConfigureAwait(false);
if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token)
return;
await StopAsync().ConfigureAwait(false);
if (wanted is not { } start || Service is not { } service)
{
Changed?.Invoke();
@@ -197,19 +206,21 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
agent.Changed += () => Changed?.Invoke();
agent.Start();
_running = (agent, remote, start);
Volatile.Write(ref _running, new Running(agent, remote, start));
Log.Info("sync", $"Comparing with {remote.Server}");
Changed?.Invoke();
}
private async Task StopAsync()
{
if (_running is not { } running) return;
_running = null;
await running.Agent.DisposeAsync();
if (Interlocked.Exchange(ref _running, null) is not { } running) return;
await running.Agent.DisposeAsync().ConfigureAwait(false);
running.Remote.Dispose();
Changed?.Invoke();
}
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints);
/// <summary>The agent of the signed-in session: one reference, so the UI thread never reads half of a switch.</summary>
private sealed record Running(SyncAgent Agent, ISyncRemote Remote, Credentials Credentials);
}
+32 -14
View File
@@ -1,6 +1,7 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using Titano.Core.Diagnostics;
using Titano.Ui.Controls;
namespace Titano.App.Shell;
@@ -9,16 +10,20 @@ namespace Titano.App.Shell;
/// The login form (BRIEF §12.7). It calls back the connection with the credentials and stays open with the
/// error sentence until the sign-in succeeds or the user cancels. The password never leaves the PasswordBox
/// except for that call. A failed sign-in is announced to screen readers and marks the password box (error border,
/// sentence as its help text) until the next attempt.
/// sentence as its help text) until the next attempt. Cancel stays available while the server answers: the form
/// closes at once and the connection drops the answer.
/// </summary>
public sealed partial class LoginDialog : TitanoWindow
{
private readonly Func<string, string, Task<string?>> _signIn;
private bool _pending;
private bool _closed;
private LoginDialog(string server, string? username, Func<string, string, Task<string?>> signIn)
{
_signIn = signIn;
InitializeComponent();
Closed += (_, _) => _closed = true;
ServerText.Text = server;
User.Text = username ?? string.Empty;
Loaded += (_, _) =>
@@ -41,28 +46,41 @@ public sealed partial class LoginDialog : TitanoWindow
private async void OnSignIn(object sender, RoutedEventArgs e)
{
if (_pending) return;
_pending = true;
SignIn.IsEnabled = false;
Error.Visibility = Visibility.Collapsed;
Field.SetError(Password, null);
string? error;
try
{
var error = await _signIn(User.Text, Password.Password);
if (error is null)
{
DialogResult = true;
return;
}
Error.Text = error;
Error.Visibility = Visibility.Visible;
Field.SetError(Password, error);
Password.Clear();
Password.Focus();
UIElementAutomationPeer.CreatePeerForElement(this)?.RaiseNotificationEvent(
AutomationNotificationKind.ActionCompleted, AutomationNotificationProcessing.ImportantMostRecent, error, "Titano.SignIn");
error = await _signIn(User.Text, Password.Password);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Cancel ended the request: nobody waits for this answer any more.
if (_closed && ex is OperationCanceledException) return;
Log.Warning("server", "Sign-in failed", ex);
error = ErrorText.For(ex);
}
finally
{
_pending = false;
SignIn.IsEnabled = true;
}
// The form was cancelled or closed while the server answered: a result can no longer be set on it.
if (_closed) return;
if (error is null)
{
DialogResult = true;
return;
}
Error.Text = error;
Error.Visibility = Visibility.Visible;
Field.SetError(Password, error);
Password.Clear();
Password.Focus();
UIElementAutomationPeer.CreatePeerForElement(this)?.RaiseNotificationEvent(
AutomationNotificationKind.ActionCompleted, AutomationNotificationProcessing.ImportantMostRecent, error, "Titano.SignIn");
}
}
+20
View File
@@ -9,6 +9,26 @@
Title="{Binding WindowTitle}"
Width="1440" Height="900" MinWidth="1200" MinHeight="760"
WindowStartupLocation="CenterScreen">
<!-- The taskbar button mirrors the job bar (BRIEF §11.5); red while a failure waits on the Jobs screen. -->
<ui:TitanoWindow.TaskbarItemInfo>
<TaskbarItemInfo ProgressState="{Binding TaskbarState}" ProgressValue="{Binding TaskbarProgress}" />
</ui:TitanoWindow.TaskbarItemInfo>
<!-- Sections by keyboard, as the rail tooltips list them (BRIEF §12.1): Ctrl+1…6 down the rail, Ctrl+, for Settings. -->
<ui:TitanoWindow.InputBindings>
<KeyBinding Key="D1" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Library}" />
<KeyBinding Key="D2" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Import}" />
<KeyBinding Key="D3" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Sequence}" />
<KeyBinding Key="D4" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Archive}" />
<KeyBinding Key="D5" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Jobs}" />
<KeyBinding Key="D6" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Server}" />
<KeyBinding Key="NumPad1" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Library}" />
<KeyBinding Key="NumPad2" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Import}" />
<KeyBinding Key="NumPad3" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Sequence}" />
<KeyBinding Key="NumPad4" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Archive}" />
<KeyBinding Key="NumPad5" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Jobs}" />
<KeyBinding Key="NumPad6" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Server}" />
<KeyBinding Key="OemComma" Modifiers="Control" Command="{Binding NavigateCommand}" CommandParameter="{x:Static shell:SectionKey.Settings}" />
</ui:TitanoWindow.InputBindings>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
+44 -4
View File
@@ -9,9 +9,15 @@ using Titano.Ui.Controls;
namespace Titano.App.Shell;
/// <summary>
/// The client's window (BRIEF §12.1): rail, job bar, section, status strip, the first-run dialog and the toasts, which
/// also become Windows notifications while nobody sees the window (<see cref="OsNotifications"/>).
/// </summary>
public partial class MainWindow : TitanoWindow
{
private readonly ShellViewModel _shell;
private readonly OsNotifications _notifications;
private WindowState? _restoreTo;
public MainWindow(ShellViewModel shell)
{
@@ -24,10 +30,37 @@ public partial class MainWindow : TitanoWindow
if (e.PropertyName is nameof(ShellViewModel.IsConnected) or "") UpdateConnection();
if (e.PropertyName is nameof(ShellViewModel.IsWelcomeOpen) or "") FocusWelcome();
};
// Screenshots and tests run off screen and never activated: they must not reach the notification area.
_notifications = new OsNotifications(this, () => shell.Services.Settings.OsNotifications && !shell.Services.Environment.IsCapture, t => Toasts.Dismiss(t));
shell.PendingToasts.CollectionChanged += OnToastRequested;
Loaded += (_, _) => FocusWelcome();
RestorePlacement();
Closing += (_, _) => SavePlacement();
Closed += (_, _) => _notifications.Dispose();
}
/// <summary>Started at sign-in (Settings › General › Startup): the window waits minimised on the taskbar.</summary>
internal static bool StartsMinimized(IReadOnlyList<string> arguments) =>
arguments.Any(a => a.Equals(RunKeyStartWithWindows.MinimizedOption, StringComparison.OrdinalIgnoreCase));
/// <summary>Minimised until the user opens it; that first restore brings back the saved state (maximised or not).</summary>
internal void WaitMinimized(bool maximized)
{
WindowState = WindowState.Minimized;
_restoreTo = maximized ? WindowState.Maximized : WindowState.Normal;
}
/// <summary>The maximised flag to save: a window started minimised and never opened keeps the state it would come back to.</summary>
internal static bool SavesMaximized(WindowState state, WindowState? restoreTo) =>
state == WindowState.Maximized || (state == WindowState.Minimized && restoreTo == WindowState.Maximized);
/// <summary>The first restore of a window started minimised brings back the saved maximised state.</summary>
protected override void OnStateChanged(EventArgs e)
{
base.OnStateChanged(e);
if (_restoreTo is not { } state || WindowState == WindowState.Minimized) return;
_restoreTo = null;
if (WindowState != state) WindowState = state;
}
/// <summary>F6 moves the keyboard to the newest notification (as in Windows apps), Esc there dismisses it.</summary>
@@ -66,14 +99,21 @@ public partial class MainWindow : TitanoWindow
private void OnToastRequested(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action != NotifyCollectionChangedAction.Add || e.NewItems is null) return;
foreach (Toast t in e.NewItems) Toasts.Show(t);
foreach (Toast t in e.NewItems)
{
Toasts.Show(t);
_notifications.Show(t);
}
Dispatcher.BeginInvoke(() => _shell.PendingToasts.Clear());
}
private void RestorePlacement()
{
if (_shell.Services.Environment.IsCapture) return;
var p = _shell.Services.Settings.Window;
if (p is null || p.Width < MinWidth || p.Height < MinHeight || _shell.Services.Environment.IsCapture) return;
var maximized = p?.Maximized == true;
if (StartsMinimized(Environment.GetCommandLineArgs())) WaitMinimized(maximized);
if (p is null || p.Width < MinWidth || p.Height < MinHeight) return;
var virtualScreen = new Rect(SystemParameters.VirtualScreenLeft, SystemParameters.VirtualScreenTop, SystemParameters.VirtualScreenWidth, SystemParameters.VirtualScreenHeight);
var rect = new Rect(p.Left, p.Top, p.Width, p.Height);
if (!virtualScreen.IntersectsWith(rect)) return;
@@ -82,7 +122,7 @@ public partial class MainWindow : TitanoWindow
Top = p.Top;
Width = p.Width;
Height = p.Height;
if (p.Maximized) WindowState = WindowState.Maximized;
if (maximized && _restoreTo is null) WindowState = WindowState.Maximized;
}
private void SavePlacement()
@@ -95,7 +135,7 @@ public partial class MainWindow : TitanoWindow
Top = b.Top,
Width = b.Width,
Height = b.Height,
Maximized = WindowState == WindowState.Maximized,
Maximized = SavesMaximized(WindowState, _restoreTo),
};
}
}
+129
View File
@@ -0,0 +1,129 @@
using System.Windows;
using Titano.Core.Localization;
using Titano.Ui.Controls;
using Titano.Ui.Interop;
namespace Titano.App.Shell;
/// <summary>
/// Windows notifications for the toasts nobody would see (BRIEF §12.1 "optional OS toast when minimised", §12.4 "Card
/// X detected — Import"): while the main window is minimised, hidden or behind another program, every toast also goes
/// to a tray balloon, which Windows 10/11 shows as a notification, when Settings › General allows it. Clicking it
/// brings the window back; it also runs the toast's action when the toast allows it
/// (<see cref="Toast.RunsFromNotification"/>) and it is the only notification shown, since Windows does not say which
/// of several was clicked. The tray icon exists only while such a notification can be clicked: it goes once a window
/// of Titano is active again. Create, use and dispose it on the UI thread.
/// </summary>
public sealed class OsNotifications : IDisposable
{
private const int MenuShow = 1;
private readonly Window _window;
private readonly Func<bool> _enabled;
private readonly Action<Toast> _dismiss;
private TrayIcon? _tray;
private Toast? _latest;
private int _shown;
private bool _disposed;
/// <param name="window">The main window, restored by a click.</param>
/// <param name="enabled">Settings › General › Notifications (never during screenshots and tests).</param>
/// <param name="dismiss">Closes the in-window toast whose action a click ran.</param>
public OsNotifications(Window window, Func<bool> enabled, Action<Toast> dismiss)
{
_window = window;
_enabled = enabled;
_dismiss = dismiss;
_window.Activated += OnActivated;
}
/// <summary>The tray icon is in the notification area (tests).</summary>
internal bool HasTrayIcon => _tray is not null;
/// <summary>Mirrors <paramref name="toast"/> as a Windows notification when nobody sees the window; true when it did.</summary>
public bool Show(Toast toast)
{
// A toast raised while the app closes (the window is hidden by then) needs no icon that would outlive it.
if (_disposed || !_enabled() || !IsUnseen(_window.WindowState, _window.IsVisible, AnyWindowActive())) return false;
_tray ??= new TrayIcon(Loc.L("Shell.AppName"), Menu, OnMenu, Restore, OnBalloonClicked);
_latest = toast;
_shown++;
_tray.ShowBalloon(toast.Title, BalloonText(toast), toast.IsError);
return true;
}
public void Dispose()
{
_disposed = true;
_window.Activated -= OnActivated;
RemoveIcon();
}
/// <summary>Nobody sees the main window: minimised, hidden, or no window of Titano has the foreground.</summary>
public static bool IsUnseen(WindowState state, bool isVisible, bool anyWindowActive) =>
state == WindowState.Minimized || !isVisible || !anyWindowActive;
/// <summary>
/// The notification's text: the toast's message, then the action a click on it runs ("Import"); the title alone
/// when there is neither (Windows needs a text to show a notification at all). An action a click does not run
/// waits in the window and is not offered here.
/// </summary>
public static string BalloonText(Toast toast)
{
ArgumentNullException.ThrowIfNull(toast);
var lines = new[] { toast.Message, toast.RunsFromNotification ? toast.ActionText : null }.Where(l => !string.IsNullOrWhiteSpace(l));
return string.Join(Environment.NewLine, lines) is { Length: > 0 } text ? text : toast.Title;
}
/// <summary>
/// A notification was clicked: the window comes back, and the toast's action runs when the toast allows it and
/// no other notification was shown since the icon appeared (Windows does not say which one was clicked).
/// </summary>
internal void OnBalloonClicked()
{
var toast = _shown == 1 ? _latest : null;
_latest = null;
Restore();
if (toast is not { RunsFromNotification: true, ActionCommand: { } command } || !command.CanExecute(null)) return;
command.Execute(null);
_dismiss(toast);
}
private static bool AnyWindowActive() => Application.Current?.Windows.OfType<Window>().Any(w => w.IsActive) ?? false;
private IReadOnlyList<TrayMenuItem> Menu() => [new(MenuShow, Loc.L("Shell.Tray.Show"))];
private void OnMenu(int id)
{
if (id == MenuShow) Restore();
}
/// <summary>The window as it was before it was minimised (maximised stays maximised), in front.</summary>
private void Restore()
{
_window.Show();
if (_window.WindowState == WindowState.Minimized) SystemCommands.RestoreWindow(_window);
_window.Activate();
}
/// <summary>
/// Back in front: the notifications have done their job. The icon goes after the current message, since activation
/// may come from a click the icon's own window is still handling, unless the window went to the background again.
/// </summary>
private void OnActivated(object? sender, EventArgs e)
{
if (_tray is null) return;
_window.Dispatcher.BeginInvoke(() =>
{
if (!IsUnseen(_window.WindowState, _window.IsVisible, AnyWindowActive())) RemoveIcon();
});
}
private void RemoveIcon()
{
_latest = null;
_shown = 0;
_tray?.Dispose();
_tray = null;
}
}
+36 -4
View File
@@ -1,5 +1,6 @@
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.Windows.Shell;
using Titano.App.Infrastructure;
using Titano.App.Sections;
using Titano.Core.Diagnostics;
@@ -26,6 +27,7 @@ public sealed class ShellViewModel : LocalizedViewModel
private string? _serverName;
private int _jobCount;
private int _queuedCount;
private int _unseenFailures;
private WelcomeViewModel? _welcome;
private Guid? _currentSequenceId;
@@ -48,12 +50,13 @@ public sealed class ShellViewModel : LocalizedViewModel
Library.IsSelected = true;
Library.PropertyChanged += OnCurrentChanged;
// The rail and its shortcuts (Ctrl+1…6, Ctrl+,) navigate only while no first-run dialog covers the shell.
NavigateCommand = new RelayCommand(p =>
{
if (p is SectionViewModel s) Navigate(s.Key);
else if (p is SectionKey k) Navigate(k);
else if (p is string name && Enum.TryParse<SectionKey>(name, out var key)) Navigate(key);
});
}, _ => IsShellEnabled);
ToggleRailCommand = new RelayCommand(() => IsRailCollapsed = !IsRailCollapsed);
services.Server.PropertyChanged += (_, _) => SetConnection(services.Server.ServerName);
if (!_settings.FirstRunCompleted) _welcome = new WelcomeViewModel(this);
@@ -89,6 +92,7 @@ public sealed class ShellViewModel : LocalizedViewModel
if (!Set(ref _welcome, value)) return;
OnPropertyChanged(nameof(IsWelcomeOpen));
OnPropertyChanged(nameof(IsShellEnabled));
CommandManager.InvalidateRequerySuggested();
}
}
@@ -196,8 +200,20 @@ public sealed class ShellViewModel : LocalizedViewModel
public string JobAnnouncement => _jobActive && _jobName is not null ? _jobName : JobText;
/// <summary>
/// Updates the global job bar (and the taskbar progress through the window). <paramref name="name"/> says which job
/// it is without its progress ("Render: Harbour sunset"); null reads <paramref name="text"/>.
/// The taskbar button mirrors the job bar (BRIEF §11.5): the running job's progress, sliding while its total is
/// unknown; red while no job runs and a failure waits on the Jobs screen; nothing otherwise.
/// </summary>
public TaskbarItemProgressState TaskbarState =>
_jobActive ? _jobIndeterminate ? TaskbarItemProgressState.Indeterminate : TaskbarItemProgressState.Normal
: _unseenFailures > 0 ? TaskbarItemProgressState.Error
: TaskbarItemProgressState.None;
/// <summary>0…1 for <see cref="TaskbarState"/>; a waiting failure fills the button.</summary>
public double TaskbarProgress => _jobActive ? _jobProgress : _unseenFailures > 0 ? 1 : 0;
/// <summary>
/// Updates the global job bar and the taskbar button. <paramref name="name"/> says which job it is without its
/// progress ("Render: Harbour sunset"); null reads <paramref name="text"/>.
/// </summary>
public void SetJob(string? text, double progress, bool indeterminate = false, string? name = null)
{
@@ -208,6 +224,17 @@ public sealed class ShellViewModel : LocalizedViewModel
IsJobIndeterminate = indeterminate;
OnPropertyChanged(nameof(JobText));
OnPropertyChanged(nameof(JobAnnouncement));
OnPropertyChanged(nameof(TaskbarState));
OnPropertyChanged(nameof(TaskbarProgress));
}
/// <summary>Failed jobs not seen on the Jobs screen yet (the taskbar button turns red while no job runs).</summary>
public void SetUnseenFailures(int count)
{
if (_unseenFailures == count) return;
_unseenFailures = count;
OnPropertyChanged(nameof(TaskbarState));
OnPropertyChanged(nameof(TaskbarProgress));
}
// ---- Status strip ----
@@ -264,8 +291,10 @@ public sealed class ShellViewModel : LocalizedViewModel
/// <summary>
/// A one-line notice with one action (job done, update available). <paramref name="isError"/> marks something that
/// did not happen or failed: screen readers then say it at once instead of after what they are reading.
/// <paramref name="runsFromNotification"/>: a click on its Windows notification also runs the action (<see cref="Toast.RunsFromNotification"/>).
/// </summary>
public void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false) =>
public void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false,
bool runsFromNotification = false) =>
ShowToast(new Toast
{
Title = title,
@@ -274,6 +303,7 @@ public sealed class ShellViewModel : LocalizedViewModel
ActionToolTip = actionToolTip,
ActionCommand = action is null ? null : new RelayCommand(action),
IsError = isError,
RunsFromNotification = runsFromNotification,
});
/// <summary>Errors are one sentence saying what happened plus one action (BRIEF §0.2 rule 6); the details go to the log.</summary>
@@ -292,6 +322,8 @@ public sealed class ShellViewModel : LocalizedViewModel
public override void Dispose()
{
// The editor first: it stops its runners and closes its source before the engine and the index under it go.
Sequence.Dispose();
Jobs.Dispose();
Library.Dispose();
Import.Dispose();
+61
View File
@@ -0,0 +1,61 @@
namespace Titano.Core.IO;
/// <summary>
/// The sign-in entries of Titano's programs: <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> values whose
/// command starts one executable with one option (<c>"C:\…\Titano.exe" --minimized</c>). Shared by the programs that
/// write them and the uninstaller that removes them; the paths are Windows paths, compared ignoring case.
/// </summary>
public static class StartupCommand
{
public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
/// <summary>The client's value (Settings › General › Startup).</summary>
public const string ClientValue = "Titano";
/// <summary>The Uploader's value (its "Start with Windows").</summary>
public const string UploaderValue = "Titano Uploader";
/// <summary>The command that starts <paramref name="executable"/> with <paramref name="option"/>.</summary>
public static string Format(string executable, string option) => $"\"{executable}\" {option}";
/// <summary>
/// The program <paramref name="command"/> starts: its quoted first part, or the text up to the first space when it
/// is not quoted; null for an empty or malformed command.
/// </summary>
public static string? Executable(string? command)
{
var text = command?.Trim();
if (string.IsNullOrEmpty(text)) return null;
if (text[0] == '"')
{
var end = text.IndexOf('"', 1);
return end > 1 ? text[1..end] : null;
}
var space = text.IndexOf(' ', StringComparison.Ordinal);
return space < 0 ? text : text[..space];
}
/// <summary><paramref name="command"/> starts <paramref name="executable"/>, not another copy of the program.</summary>
public static bool Starts(string? command, string? executable) =>
executable is { Length: > 0 } && string.Equals(Executable(command), executable, StringComparison.OrdinalIgnoreCase);
/// <summary>The program <paramref name="command"/> starts lies in <paramref name="directory"/> or one of its folders.</summary>
public static bool StartsFrom(string? command, string directory)
{
ArgumentNullException.ThrowIfNull(directory);
var folder = directory.TrimEnd('\\', '/');
return Executable(command) is { } exe && folder.Length > 0 && exe.Length > folder.Length + 1
&& exe.StartsWith(folder, StringComparison.OrdinalIgnoreCase) && exe[folder.Length] is '\\' or '/';
}
/// <summary>The folder of the program <paramref name="command"/> starts; null when it names none.</summary>
public static string? Folder(string? command) => Executable(command) is { } exe ? FolderOf(exe) : null;
/// <summary>The folder part of a Windows path (on any platform); null when it has none.</summary>
public static string? FolderOf(string path)
{
ArgumentNullException.ThrowIfNull(path);
var slash = path.LastIndexOfAny(['\\', '/']);
return slash > 0 ? path[..slash] : null;
}
}
+15
View File
@@ -2,6 +2,7 @@ using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using Titano.Core.IO;
namespace Titano.Setup.Engine;
@@ -56,6 +57,20 @@ internal static partial class SetupRegistry
public static void DeleteUninstallEntry(InstallScope scope, string productKey) =>
Hive(scope).DeleteSubKeyTree(UninstallRoot + productKey, throwOnMissingSubKey: false);
/// <summary>
/// Removes the sign-in entries of the client and the Uploader (<c>HKCU\…\Run</c>, written by the programs
/// themselves) that start a program of <paramref name="directory"/>; another copy's entries stay.
/// </summary>
public static void DeleteStartupEntries(string directory)
{
using var run = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey, writable: true);
if (run is null) return;
foreach (var name in (ReadOnlySpan<string>)[StartupCommand.ClientValue, StartupCommand.UploaderValue])
{
if (StartupCommand.StartsFrom(run.GetValue(name) as string, directory)) run.DeleteValue(name, throwOnMissingValue: false);
}
}
/// <summary>Registers <paramref name="extension"/> to open with <c>"program" "%1"</c> under <paramref name="progId"/>.</summary>
public static void RegisterFileType(InstallScope scope, string extension, string progId, string description, string program)
{
+11 -2
View File
@@ -10,8 +10,8 @@ namespace Titano.Setup.Engine;
internal sealed record InstalledProduct(string Directory, InstallLog Log);
/// <summary>
/// Removes an installation using only its log: shortcuts, file types, logged files, the log and the Add/Remove
/// Programs entry, then the uninstaller itself. Files the log does not list are left alone; the user data folder
/// Removes an installation using only its log: shortcuts, file types, logged files, the log, the Add/Remove
/// Programs entry and the programs' sign-in entries, then the uninstaller itself. Files the log does not list are left alone; the user data folder
/// is deleted only when <c>removeUserData</c> is set by an explicit choice in the window.
/// </summary>
internal static class UninstallEngine
@@ -60,6 +60,15 @@ internal static class UninstallEngine
}
SetupRegistry.DeleteUninstallEntry(log.Scope, log.ProductKey);
try
{
SetupRegistry.DeleteStartupEntries(directory);
}
catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException)
{
// Windows skips a sign-in entry whose program is gone; not worth failing the removal.
Log.Warning("setup", "Sign-in entries not removed", ex);
}
File.Delete(Path.Combine(directory, InstallLog.FileName));
var uninstaller = Path.Combine(directory, log.UninstallerName);
try
+7
View File
@@ -22,6 +22,13 @@ public sealed class Toast : ObservableObject
/// <summary>Something failed: screen readers say it at once, ahead of other notices (assertive, not polite).</summary>
public bool IsError { get; init; }
/// <summary>
/// A click on the toast's Windows notification also runs its action (it opens what the toast names). Off by
/// default: people click a notification to bring the window back, so a Cancel, Undo or Retry there would act
/// before they have read why.
/// </summary>
public bool RunsFromNotification { get; init; }
}
/// <summary>
@@ -3,14 +3,16 @@ using System.Windows.Interop;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
namespace Titano.Uploader.Interop;
namespace Titano.Ui.Interop;
/// <summary>One entry of the tray menu; an id of 0 is a separator.</summary>
public readonly record struct TrayMenuItem(int Id, string? Text);
/// <summary>
/// Notification-area icon through <c>Shell_NotifyIconW</c>: the program icon from the executable's resources, a tooltip,
/// a native context menu and balloons. A hidden window receives the callbacks and re-adds the icon after Explorer restarts.
/// a native context menu and balloons (Windows notifications on Windows 10/11). A hidden window receives the callbacks
/// and re-adds the icon after Explorer restarts. Used by the Uploader (tray) and the client (notifications while
/// minimised); create, use and dispose it on the UI thread.
/// </summary>
public sealed unsafe partial class TrayIcon : IDisposable
{
@@ -21,6 +23,7 @@ public sealed unsafe partial class TrayIcon : IDisposable
private const uint NifIcon = 0x2;
private const uint NifTip = 0x4;
private const uint NifInfo = 0x10;
private const uint NiifError = 0x3;
private const uint NiifUser = 0x4;
private const int CallbackMessage = 0x8000 + 1; // WM_APP + 1
private const int WmContextMenu = 0x007B;
@@ -42,21 +45,24 @@ public sealed unsafe partial class TrayIcon : IDisposable
private readonly Func<IReadOnlyList<TrayMenuItem>> _menu;
private readonly Action<int> _command;
private readonly Action _show;
private readonly Action? _balloonClicked;
private string _toolTip;
private bool _added;
/// <param name="toolTip">Hover text (up to 127 characters).</param>
/// <param name="menu">Builds the context menu when it opens.</param>
/// <param name="command">Runs a chosen menu id.</param>
/// <param name="show">Left click or balloon click.</param>
public TrayIcon(string toolTip, Func<IReadOnlyList<TrayMenuItem>> menu, Action<int> command, Action show)
/// <param name="show">Left click, and balloon click when <paramref name="balloonClicked"/> is null.</param>
/// <param name="balloonClicked">Click on the last balloon (or its Windows notification).</param>
public TrayIcon(string toolTip, Func<IReadOnlyList<TrayMenuItem>> menu, Action<int> command, Action show, Action? balloonClicked = null)
{
_toolTip = toolTip;
_menu = menu;
_command = command;
_show = show;
_balloonClicked = balloonClicked;
// A hidden top-level window: message-only windows miss the TaskbarCreated broadcast.
_window = new HwndSource(new HwndSourceParameters("TitanoUploaderTray") { Width = 0, Height = 0, WindowStyle = 0 });
_window = new HwndSource(new HwndSourceParameters("TitanoTray") { Width = 0, Height = 0, WindowStyle = 0 });
_window.AddHook(WndProc);
_taskbarCreated = RegisterWindowMessageW("TaskbarCreated");
(_icon, _ownsIcon) = LoadProgramIcon();
@@ -71,13 +77,16 @@ public sealed unsafe partial class TrayIcon : IDisposable
Notify(NimModify, &data);
}
/// <summary>Shows a balloon (a toast on Windows 10/11) with the program icon.</summary>
public void ShowBalloon(string title, string text)
/// <summary>
/// Shows a balloon (a Windows notification on Windows 10/11) with the program icon, or the error icon when
/// <paramref name="isError"/>. <paramref name="text"/> must not be empty: an empty text removes the balloon.
/// </summary>
public void ShowBalloon(string title, string text, bool isError = false)
{
var data = NewData(NifInfo);
Copy(title, data.InfoTitle, 64);
Copy(text, data.Info, 256);
data.InfoFlags = NiifUser;
data.InfoFlags = isError ? NiifError : NiifUser;
Notify(NimModify, &data);
}
@@ -108,9 +117,12 @@ public sealed unsafe partial class TrayIcon : IDisposable
{
switch ((int)(lParam.ToInt64() & 0xFFFF))
{
case WmLButtonUp or WmLButtonDblClk or NinBalloonUserClick:
case WmLButtonUp or WmLButtonDblClk:
_show();
break;
case NinBalloonUserClick:
(_balloonClicked ?? _show)();
break;
case WmRButtonUp or WmContextMenu:
ShowMenu();
break;
@@ -172,7 +184,7 @@ public sealed unsafe partial class TrayIcon : IDisposable
destination[length] = '\0';
}
/// <summary>The generated titano-uploader icon embedded in the executable; the stock icon if it cannot be read.</summary>
/// <summary>The program's generated icon embedded in its executable; the stock icon if it cannot be read.</summary>
private static (IntPtr Icon, bool Owned) LoadProgramIcon()
{
if (Environment.ProcessPath is { } exe)
+4 -3
View File
@@ -42,8 +42,9 @@ public readonly record struct MotionVector(float X, float Y, float Dx, float Dy)
/// polyline) and a crop mask (normalised <see cref="CropRect"/>; dims or hides what the output loses). Tools go
/// bottom-left (<see cref="ToolsContent"/>), the shot data pill bottom-right (<see cref="InfoText"/>). Images and
/// overlays are retained visuals under one shared transform, so panning re-renders nothing. Double-click toggles
/// Fit and 1:1; Ctrl+0 fits, Ctrl+1 shows 1:1. Screen readers see an image (named by AutomationProperties.Name)
/// whose status is the zoom and whose help text is the shot data, holding the tools.
/// Fit and 1:1; Ctrl+0 fits, Ctrl+Shift+1 shows 1:1 (Ctrl+1 to Ctrl+6 switch the client's sections). Screen readers
/// see an image (named by AutomationProperties.Name) whose status is the zoom and whose help text is the shot data,
/// holding the tools.
/// </summary>
[TemplatePart(Name = PartSurface, Type = typeof(FrameworkElement))]
[TemplatePart(Name = PartTools, Type = typeof(FrameworkElement))]
@@ -55,7 +56,7 @@ public class PreviewViewport : Control
public const string PartInfo = "PART_Info";
public static readonly RoutedCommand FitCommand = new(nameof(FitCommand), typeof(PreviewViewport), [new KeyGesture(Key.D0, ModifierKeys.Control)]);
public static readonly RoutedCommand ActualSizeCommand = new(nameof(ActualSizeCommand), typeof(PreviewViewport), [new KeyGesture(Key.D1, ModifierKeys.Control)]);
public static readonly RoutedCommand ActualSizeCommand = new(nameof(ActualSizeCommand), typeof(PreviewViewport), [new KeyGesture(Key.D1, ModifierKeys.Control | ModifierKeys.Shift)]);
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
nameof(Source), typeof(ImageSource), typeof(PreviewViewport), new PropertyMetadata(null, OnImagesChanged));
+1 -1
View File
@@ -5,10 +5,10 @@ using System.Windows;
using System.Windows.Threading;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Ui.Interop;
using Titano.Ui.Mvvm;
using Titano.Ui.Theming;
using Titano.Uploader.Infrastructure;
using Titano.Uploader.Interop;
using Titano.Uploader.Server;
using Titano.Uploader.Shell;
using Titano.Uploader.Uploads;