Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(feat) Background download

Egor Khindikaynen9ab385687ea3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14dbf171..9b7058f8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -86,6 +86,9 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
imports instead of every sample again, and the same audio used in several places is
stored once. Background autosave no longer rewrites the project's audio either. Older
projects are converted on their next save.
+- **Downloads keep going after Settings closes.** Press Install, close Settings, and the
+ download carries on, with its progress in the main window's status bar, a cross to cancel
+ it and the outcome when it's done. Click it to open Settings → Downloads again.
### Fixed
- **One-shots dropped on the arrangement are no longer warped:** a short hit used to be
diff --git a/src/managed/Nota.App/App.axaml.cs b/src/managed/Nota.App/App.axaml.cs
index 6ba475fd..31b03522 100644
--- a/src/managed/Nota.App/App.axaml.cs
+++ b/src/managed/Nota.App/App.axaml.cs
@@ -98,6 +98,8 @@ public partial class App : Avalonia.Application
{
// A downloaded update installs once the app is gone (see AppUpdater).
desktop.Exit += (_, _) => Services.GetRequiredService<IAppUpdater>().RunPendingInstall();
+ // A Settings → Downloads install still running when the app quits is abandoned.
+ desktop.Exit += (_, _) => DownloadJobs.Shared.CancelAll();
// Show the splash immediately, then defer the heavy engine spin-up to a
// background dispatcher tick so the splash actually paints before the audio
diff --git a/src/managed/Nota.App/DownloadJobs.cs b/src/managed/Nota.App/DownloadJobs.cs
new file mode 100644
index 00000000..40082acc
--- /dev/null
+++ b/src/managed/Nota.App/DownloadJobs.cs
@@ -0,0 +1,167 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The one running Downloads job (a plug-in, sample pack or AI model install / removal) and the
+// outcome of the last one. It lives for the app, not for Preferences: closing the window leaves
+// the download running, and the main window's status bar keeps showing it (MainWindow.Downloads.cs).
+// Preferences → Downloads starts the jobs and shows the same state in its dock. Quitting the
+// app cancels a running download.
+
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Avalonia.Threading;
+using Microsoft.Extensions.DependencyInjection;
+using Nota.Application;
+
+namespace Nota.App;
+
+internal sealed class DownloadJobs
+{
+ public static DownloadJobs Shared { get; } = new();
+
+ /// <summary>Key of the item being installed / removed ("pack:<id>", "model:<id>", a plug-in
+ /// id); null when idle.</summary>
+ public string? BusyId { get; private set; }
+
+ /// <summary>Which Downloads source the job belongs to: 0 plug-ins, 1 sample packs, 2 AI models.</summary>
+ public int Source { get; private set; }
+
+ public StoreProgress Progress { get; private set; }
+
+ /// <summary>Bytes of the download in progress, 0 when unknown or past the download stage.</summary>
+ public long Size { get; private set; }
+
+ /// <summary>The last job's outcome; a success clears itself after a while, an error stays.</summary>
+ public string? Result { get; private set; }
+
+ public bool Busy => BusyId is not null;
+
+ /// <summary>A Cancel is possible (the download stage of an install).</summary>
+ public bool Cancellable => _job is not null;
+ public bool Cancelling => _job is { IsCancellationRequested: true };
+
+ /// <summary>A job started or ended, or the result changed: lists need re-rendering.</summary>
+ public event Action? Changed;
+
+ /// <summary>The running job reported progress.</summary>
+ public event Action? ProgressChanged;
+
+ private readonly CancellationTokenSource _app = new(); // app lifetime
+ private CancellationTokenSource? _job; // the running download; null when it can't be cancelled
+ private int _resultSeq;
+
+ /// <summary>Install: <paramref name="download"/> runs cancellable, then <paramref name="finish"/>
+ /// (no cancel) returns the line to show.</summary>
+ public async void Install(string key, int source, string name, long size, StoreProgress first,
+ Func<IProgress<StoreProgress>, CancellationToken, Task> download, Func<Task<string>> finish)
+ {
+ if (Busy) return;
+ Begin(key, source, size, first);
+ var job = _job = CancellationTokenSource.CreateLinkedTokenSource(_app.Token);
+ // A report queued before Cancel must not overwrite "Cancelling…". Only the download has
+ // a known byte count; a later stage's fraction is of something else.
+ var progress = new Progress<StoreProgress>(r =>
+ {
+ if (job.IsCancellationRequested || BusyId != key) return;
+ if (!r.Message.StartsWith("Downloading", StringComparison.Ordinal)) Size = 0;
+ Progress = r;
+ ProgressChanged?.Invoke();
+ });
+ string? result = null;
+ bool sticky = false;
+ try
+ {
+ await download(progress, job.Token);
+ _job = null; // the files are in place — too late to cancel
+ Changed?.Invoke();
+ result = await finish();
+ }
+ catch (OperationCanceledException)
+ {
+ // Quitting: nothing to show. Otherwise the user pressed Cancel.
+ if (!_app.IsCancellationRequested) result = $"Installing {name} was cancelled.";
+ }
+ catch (StoreException e) { result = e.Message; sticky = true; }
+ catch (Exception e)
+ {
+ App.Services.GetRequiredService<ILogSink>().Error($"Installing {key} failed", e);
+ result = $"Installing {name} failed: {e.Message}";
+ sticky = true;
+ }
+ finally
+ {
+ _job = null;
+ job.Dispose();
+ }
+ End(result, sticky);
+ }
+
+ /// <summary>Removal: not cancellable; <paramref name="remove"/> returns the line to show.</summary>
+ public async void Remove(string key, int source, string message, Func<Task<string>> remove)
+ {
+ if (Busy) return;
+ Begin(key, source, 0, new StoreProgress(-1, message));
+ string? result;
+ bool sticky = false;
+ try { result = await remove(); }
+ catch (StoreException e) { result = e.Message; sticky = true; }
+ catch (Exception e)
+ {
+ App.Services.GetRequiredService<ILogSink>().Error($"Removing {key} failed", e);
+ result = e.Message;
+ sticky = true;
+ }
+ End(result, sticky);
+ }
+
+ /// <summary>Progress from a job's own later stage (its finish step).</summary>
+ public void Report(StoreProgress r)
+ {
+ if (!Busy) return;
+ Size = 0;
+ Progress = r;
+ ProgressChanged?.Invoke();
+ }
+
+ public void Cancel()
+ {
+ if (_job is not { IsCancellationRequested: false } job) return;
+ job.Cancel();
+ Progress = Progress with { Message = "Cancelling…" };
+ ProgressChanged?.Invoke();
+ Changed?.Invoke();
+ }
+
+ /// <summary>Hide the last outcome (the dock's / status bar's close button).</summary>
+ public void Dismiss()
+ {
+ if (Result is null) return;
+ Result = null;
+ Changed?.Invoke();
+ }
+
+ /// <summary>App exit: stop a running download.</summary>
+ public void CancelAll() => _app.Cancel();
+
+ private void Begin(string key, int source, long size, StoreProgress first)
+ {
+ BusyId = key;
+ Source = source;
+ Size = size;
+ Progress = first;
+ Result = null;
+ _resultSeq++;
+ Changed?.Invoke();
+ }
+
+ private void End(string? result, bool sticky)
+ {
+ BusyId = null;
+ Result = result;
+ int seq = ++_resultSeq;
+ if (result is not null && !sticky)
+ DispatcherTimer.RunOnce(() => { if (seq == _resultSeq && !Busy) { Result = null; Changed?.Invoke(); } }, TimeSpan.FromSeconds(8));
+ Changed?.Invoke();
+ }
+}
diff --git a/src/managed/Nota.App/MainWindow.Downloads.cs b/src/managed/Nota.App/MainWindow.Downloads.cs
new file mode 100644
index 00000000..9e0acf5b
--- /dev/null
+++ b/src/managed/Nota.App/MainWindow.Downloads.cs
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The status bar's Downloads indicator: a plug-in / sample pack / AI model install started in
+// Settings → Downloads keeps running after Settings closes (DownloadJobs), and shows here — its
+// message, a thin bar, the percentage and a Cancel cross; then its outcome until it fades or is
+// closed. Clicking the message opens Settings on the job's Downloads source.
+
+using System;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Microsoft.Extensions.DependencyInjection;
+using Nota.Application;
+using Nota.Presentation;
+
+namespace Nota.App;
+
+public partial class MainWindow
+{
+ private TextBlock _dlText = null!, _dlDetail = null!;
+ private ProgressBar _dlBar = null!;
+ private Button _dlCancel = null!;
+
+ private void BuildDownloadIndicator()
+ {
+ _dlText = new TextBlock { Classes = { "Caption" }, VerticalAlignment = VerticalAlignment.Center, MaxWidth = 360, TextTrimming = TextTrimming.CharacterEllipsis };
+ var open = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = _dlText };
+ ToolTip.SetTip(open, "Open Settings → Downloads");
+ open.PointerEntered += (_, _) => _dlText.TextDecorations = TextDecorations.Underline;
+ open.PointerExited += (_, _) => _dlText.TextDecorations = null;
+ open.PointerPressed += (_, e) =>
+ {
+ if (e.GetCurrentPoint(open).Properties.IsLeftButtonPressed) ShowPreferences(downloads: DownloadJobs.Shared.Source);
+ };
+
+ _dlBar = new ProgressBar { Width = 90, Height = 4, MinWidth = 0, Minimum = 0, Maximum = 1, VerticalAlignment = VerticalAlignment.Center };
+ _dlBar.BindResource(ProgressBar.ForegroundProperty, "Brush.Accent");
+ _dlBar.BindResource(ProgressBar.BackgroundProperty, "Brush.BorderDefault");
+ _dlDetail = new TextBlock { Classes = { "Caption", "Mono" }, VerticalAlignment = VerticalAlignment.Center };
+
+ // One cross: Cancel while the download runs, close once there's only the outcome.
+ _dlCancel = new Button
+ {
+ Classes = { "ghost" }, Width = 18, Height = 18, Padding = new Thickness(0), MinHeight = 0, MinWidth = 0,
+ VerticalAlignment = VerticalAlignment.Center, Content = new Glyph(GlyphKind.Close, 8),
+ };
+ _dlCancel.BindResource(Button.ForegroundProperty, "Brush.TextTertiary");
+ _dlCancel.Click += (_, _) =>
+ {
+ var jobs = DownloadJobs.Shared;
+ if (jobs.Busy) jobs.Cancel(); else jobs.Dismiss();
+ };
+
+ DownloadHost.Children.Add(new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 8, Margin = new Thickness(0, 0, 14, 0),
+ Children = { open, _dlBar, _dlDetail, _dlCancel },
+ });
+
+ DownloadJobs.Shared.Changed += UpdateDownloadIndicator;
+ DownloadJobs.Shared.ProgressChanged += UpdateDownloadIndicator;
+ Closed += (_, _) =>
+ {
+ DownloadJobs.Shared.Changed -= UpdateDownloadIndicator;
+ DownloadJobs.Shared.ProgressChanged -= UpdateDownloadIndicator;
+ };
+ UpdateDownloadIndicator();
+ }
+
+ private void UpdateDownloadIndicator()
+ {
+ var jobs = DownloadJobs.Shared;
+ bool busy = jobs.Busy;
+ DownloadHost.IsVisible = busy || jobs.Result is not null;
+ if (!DownloadHost.IsVisible) return;
+
+ var pr = jobs.Progress;
+ _dlText.Text = busy ? pr.Message : jobs.Result;
+ _dlBar.IsVisible = busy;
+ _dlBar.IsIndeterminate = busy && pr.Fraction < 0;
+ if (busy && pr.Fraction >= 0) _dlBar.Value = pr.Fraction;
+ _dlDetail.Text = busy && pr.Fraction >= 0 ? NotaNum.Unit(pr.Fraction * 100, "0", "%") : "";
+ _dlDetail.IsVisible = _dlDetail.Text.Length > 0;
+ // Past the download stage (unpacking, scanning, removing) there's nothing to cancel.
+ _dlCancel.IsVisible = !busy || jobs.Cancellable;
+ _dlCancel.IsEnabled = !jobs.Cancelling;
+ ToolTip.SetTip(_dlCancel, busy ? "Cancel the download" : "Dismiss");
+ }
+
+ /// <summary>Settings → Downloads, on the given source; reuses an open Settings window.</summary>
+ private void ShowPreferences(int downloads)
+ {
+ foreach (var w in OwnedWindows)
+ if (w is PreferencesWindow open)
+ {
+ open.ShowDownloads(downloads);
+ open.Activate();
+ return;
+ }
+ var settings = App.Services.GetRequiredService<ISettingsService>();
+ var win = new PreferencesWindow(new SettingsViewModel(settings), _vm);
+ win.ShowDownloads(downloads);
+ win.Show(this);
+ }
+}
diff --git a/src/managed/Nota.App/MainWindow.Stems.cs b/src/managed/Nota.App/MainWindow.Stems.cs
index 06063e14..e766f657 100644
--- a/src/managed/Nota.App/MainWindow.Stems.cs
+++ b/src/managed/Nota.App/MainWindow.Stems.cs
@@ -69,6 +69,12 @@ public partial class MainWindow
return false;
}
+ if (DownloadJobs.Shared.BusyId == "model:" + id)
+ {
+ _vm.StatusText = $"{feature} is waiting for its model — it's downloading (see the status bar).";
+ return false;
+ }
+
var model = store.Models.First(m => m.Id == id);
bool withRuntime = store.RuntimePath is null;
string what = withRuntime ? $"the {model.Name} model and the AI runtime it runs on" : $"the {model.Name} model";
diff --git a/src/managed/Nota.App/MainWindow.axaml b/src/managed/Nota.App/MainWindow.axaml
index e42f5b11..031c18d8 100644
--- a/src/managed/Nota.App/MainWindow.axaml
+++ b/src/managed/Nota.App/MainWindow.axaml
@@ -354,10 +354,12 @@
<Border DockPanel.Dock="Bottom" Background="{DynamicResource Brush.ChromeBg}"
BorderBrush="{DynamicResource Brush.BorderDefault}" BorderThickness="0,1,0,0"
Height="22" Padding="12,0">
- <Grid ColumnDefinitions="*,Auto,Auto">
+ <Grid ColumnDefinitions="*,Auto,Auto,Auto">
<TextBlock Classes="Caption" VerticalAlignment="Center" Text="{Binding StatusText}"/>
+ <!-- Settings → Downloads job (MainWindow.Downloads.cs): it keeps running after Settings closes. -->
+ <Panel x:Name="DownloadHost" Grid.Column="1" VerticalAlignment="Center"/>
<!-- Background-operation strip: label + thin bar, shown only while a background op runs. -->
- <StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="8"
+ <StackPanel Grid.Column="2" Orientation="Horizontal" Spacing="8"
VerticalAlignment="Center" Margin="0,0,14,0"
IsVisible="{Binding BackgroundBusy}">
<TextBlock Classes="Caption" VerticalAlignment="Center" Text="{Binding BackgroundLabel}"/>
@@ -368,7 +370,7 @@
Foreground="{DynamicResource Brush.Accent}"
Background="{DynamicResource Brush.BorderDefault}"/>
</StackPanel>
- <TextBlock Grid.Column="2" Classes="Caption Mono"
+ <TextBlock Grid.Column="3" Classes="Caption Mono"
VerticalAlignment="Center" Text="{Binding EngineInfo}"/>
</Grid>
</Border>
diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.cs
index 6fabdce5..bc7c576b 100644
--- a/src/managed/Nota.App/MainWindow.axaml.cs
+++ b/src/managed/Nota.App/MainWindow.axaml.cs
@@ -100,6 +100,7 @@ public partial class MainWindow : Window
ExtendClientAreaTitleBarHeightHint = 36;
}
DataContextChanged += OnDataContextChanged;
+ BuildDownloadIndicator();
// Platform-specific window icon: Windows/Linux get the .ico bundle from
// assets/icons/windows so the taskbar / alt-tab shows the brand mark. macOS
// uses the .icns produced by scripts/bundle-mac.sh for the dock/Finder.
diff --git a/src/managed/Nota.App/PreferencesWindow.Models.cs b/src/managed/Nota.App/PreferencesWindow.Models.cs
index 977b24d7..0a06cd5c 100644
--- a/src/managed/Nota.App/PreferencesWindow.Models.cs
+++ b/src/managed/Nota.App/PreferencesWindow.Models.cs
@@ -3,13 +3,12 @@
//
// Preferences → Downloads → AI Models: install / remove the models behind Separate Stems and
// Convert to MIDI (IModelStore), and see the ONNX Runtime they share, which comes with the first
-// model and goes with the last. Shares the store's job state with Plug-ins and Sample Packs: one
-// download at a time, shown in the same dock. A model's busy key is "model:<id>".
+// model and goes with the last. Shares the job state (DownloadJobs) with Plug-ins and Sample Packs:
+// one download at a time, shown in the same dock. A model's busy key is "model:<id>".
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
@@ -75,8 +74,8 @@ public sealed partial class PreferencesWindow
};
var actions = new StackPanel { Spacing = 8, MinWidth = 96, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top };
- bool busy = _storeBusyId is not null;
- if (_storeBusyId == ModelKey(m.Id))
+ bool busy = Jobs.BusyId is not null;
+ if (Jobs.BusyId == ModelKey(m.Id))
actions.Children.Add(StoreButton(installed ? "Removing…" : "Installing…", enabled: false, () => { }));
else if (installed)
{
@@ -113,70 +112,29 @@ public sealed partial class PreferencesWindow
return grid;
}
- private async void InstallModel(StoreModel m)
+ private void InstallModel(StoreModel m)
{
- if (_storeBusyId is not null) return;
- _storeBusyId = ModelKey(m.Id);
- _storeBusySize = _models.DownloadSize(m.Id);
- _storeProgress = new StoreProgress(0, "Downloading…");
- SetStoreResult(null, sticky: true);
- _storeCts ??= new CancellationTokenSource();
- var job = _storeJobCts = CancellationTokenSource.CreateLinkedTokenSource(_storeCts.Token);
- RenderStoreLists();
- var progress = new Progress<StoreProgress>(r =>
- {
- if (job.IsCancellationRequested) return;
- // Each download reports its own fraction; the dock's byte count would mix two files.
- _storeBusySize = 0;
- _storeProgress = r;
- UpdateDock();
- });
- try
- {
- await _models.InstallAsync(m.Id, progress, job.Token);
- SetStoreResult(m.Id == AiModels.Stems
+ // Size 0: the model and the runtime download one after the other, each reporting its own
+ // fraction, so a byte count would mix two files.
+ Jobs.Install(ModelKey(m.Id), source: 2, m.Name, 0, new StoreProgress(0, $"Downloading {m.Name}…"),
+ (progress, ct) => _models.InstallAsync(m.Id, progress, ct),
+ () => Task.FromResult(m.Id == AiModels.Stems
? $"{m.Name} is installed — right-click an audio clip and choose Separate Stems."
- : $"{m.Name} is installed — Convert Melody and Convert Harmony now use it.", sticky: false);
- }
- catch (OperationCanceledException)
- {
- if (_storeCts is { IsCancellationRequested: false }) SetStoreResult($"Installing {m.Name} was cancelled.", sticky: false);
- }
- catch (StoreException e) { SetStoreResult(e.Message, sticky: true); }
- catch (Exception e)
- {
- App.Services.GetRequiredService<ILogSink>().Error($"Installing model {m.Id} failed", e);
- SetStoreResult($"Installing {m.Name} failed: {e.Message}", sticky: true);
- }
- finally
- {
- _storeBusyId = null;
- _storeJobCts = null;
- job.Dispose();
- }
- RenderStoreLists();
+ : $"{m.Name} is installed — Convert Melody and Convert Harmony now use it."));
}
private async void RemoveModel(StoreModel m)
{
- if (_storeBusyId is not null) return;
+ if (Jobs.Busy) return;
bool last = _models.Models.Count(x => _models.IsInstalled(x.Id)) == 1;
var ok = await new ConfirmWindow("Remove AI model",
$"Remove {m.Name}? {m.Feature} will offer to download it again." + (last ? " The AI runtime goes too." : ""),
"Remove", "Cancel").ShowDialog<bool>(this);
if (!ok) return;
- _storeBusyId = ModelKey(m.Id);
- _storeBusySize = 0;
- _storeProgress = new StoreProgress(-1, $"Removing {m.Name}…");
- SetStoreResult(null, sticky: true);
- RenderStoreLists();
- try
+ Jobs.Remove(ModelKey(m.Id), source: 2, $"Removing {m.Name}…", async () =>
{
await Task.Run(() => _models.Uninstall(m.Id));
- SetStoreResult($"{m.Name} was removed.", sticky: false);
- }
- catch (StoreException e) { SetStoreResult(e.Message, sticky: true); }
- finally { _storeBusyId = null; }
- RenderStoreLists();
+ return $"{m.Name} was removed.";
+ });
}
}
diff --git a/src/managed/Nota.App/PreferencesWindow.Samples.cs b/src/managed/Nota.App/PreferencesWindow.Samples.cs
index 89045bba..88a6066d 100644
--- a/src/managed/Nota.App/PreferencesWindow.Samples.cs
+++ b/src/managed/Nota.App/PreferencesWindow.Samples.cs
@@ -3,14 +3,13 @@
//
// Preferences → Downloads → Sample Packs: browse the Nota sample registry and install /
// update / remove free sample packs (ISampleStore) into the Samples folder. Built like Get Plug-ins
-// (PreferencesWindow.Store.cs) and sharing its job state: one download at a time across both
-// stores, shown in the same dock. A pack's busy key is "pack:<id>" so it can't collide with a
+// (PreferencesWindow.Store.cs) and sharing its job state (DownloadJobs): one download at a time
+// across all of Downloads, shown in the same dock. A pack's busy key is "pack:<id>" so it can't collide with a
// plugin id. After every change the browser's Files tab is rescanned.
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
@@ -266,8 +265,8 @@ public sealed partial class PreferencesWindow
text.Children.Add(new TextBlock { Text = notes, FontSize = 11, LineHeight = 16, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap });
var actions = new StackPanel { Spacing = 8, MinWidth = 96, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top };
- bool busy = _storeBusyId is not null;
- if (_storeBusyId == PackKey(p.Id))
+ bool busy = Jobs.BusyId is not null;
+ if (Jobs.BusyId == PackKey(p.Id))
{
actions.Children.Add(StoreButton(inst is null ? "Installing…" : "Working…", enabled: false, () => { }));
}
@@ -308,73 +307,35 @@ public sealed partial class PreferencesWindow
return grid;
}
- private async void InstallPack(StorePack p)
+ private void InstallPack(StorePack p)
{
- if (_storeBusyId is not null) return;
- _storeBusyId = PackKey(p.Id);
- _storeBusySize = p.Asset.Size;
- _storeProgress = new StoreProgress(0, $"Downloading {p.Name}…");
- SetStoreResult(null, sticky: true);
- _storeCts ??= new CancellationTokenSource();
- var job = _storeJobCts = CancellationTokenSource.CreateLinkedTokenSource(_storeCts.Token);
- RenderStoreLists();
- var progress = new Progress<StoreProgress>(r =>
- {
- if (job.IsCancellationRequested) return;
- // Only the download has a known byte count; the copy stage's fraction is of the unpacked size.
- if (!r.Message.StartsWith("Downloading", StringComparison.Ordinal)) _storeBusySize = 0;
- _storeProgress = r;
- UpdateDock();
- });
- try
- {
- await _samples.InstallAsync(p, progress, job.Token);
- // Analyse the new pack first, so its tempo / key tags and filters work at once.
- if (_samples.Installed.FirstOrDefault(i => i.Id == p.Id) is { } installed)
- App.Services.GetRequiredService<ISampleIndex>().Prioritize(installed.Path);
- _main?.Browser.RebuildSamples();
- SetStoreResult($"{p.Name} is installed — find it under Downloaded in the browser's Files tab, where it is being analysed for tempo and key.", sticky: false);
- }
- catch (OperationCanceledException)
- {
- if (_storeCts is { IsCancellationRequested: false }) SetStoreResult($"Installing {p.Name} was cancelled.", sticky: false);
- }
- catch (StoreException e) { SetStoreResult(e.Message, sticky: true); }
- catch (Exception e)
- {
- App.Services.GetRequiredService<ILogSink>().Error($"Installing pack {p.Id} failed", e);
- SetStoreResult($"Installing {p.Name} failed: {e.Message}", sticky: true);
- }
- finally
- {
- _storeBusyId = null;
- _storeJobCts = null;
- job.Dispose();
- }
- RenderStoreLists();
+ var main = _main;
+ Jobs.Install(PackKey(p.Id), source: 1, p.Name, p.Asset.Size, new StoreProgress(0, $"Downloading {p.Name}…"),
+ (progress, ct) => _samples.InstallAsync(p, progress, ct),
+ () =>
+ {
+ // Analyse the new pack first, so its tempo / key tags and filters work at once.
+ if (_samples.Installed.FirstOrDefault(i => i.Id == p.Id) is { } installed)
+ App.Services.GetRequiredService<ISampleIndex>().Prioritize(installed.Path);
+ main?.Browser.RebuildSamples();
+ return Task.FromResult($"{p.Name} is installed — find it under Downloaded in the browser's Files tab, where it is being analysed for tempo and key.");
+ });
}
private async void RemovePack(StorePack p, InstalledStorePack inst)
{
- if (_storeBusyId is not null) return;
+ if (Jobs.Busy) return;
var ok = await new ConfirmWindow("Remove sample pack",
$"Remove {p.Name}? Its folder ({inst.Path}) is deleted.",
"Remove", "Cancel").ShowDialog<bool>(this);
if (!ok) return;
- _storeBusyId = PackKey(p.Id);
- _storeBusySize = 0;
- _storeProgress = new StoreProgress(-1, $"Removing {p.Name}…");
- SetStoreResult(null, sticky: true);
- RenderStoreLists();
- try
+ var main = _main;
+ Jobs.Remove(PackKey(p.Id), source: 1, $"Removing {p.Name}…", async () =>
{
await Task.Run(() => _samples.Uninstall(p.Id));
- _main?.Browser.RebuildSamples();
- SetStoreResult($"{p.Name} was removed.", sticky: false);
- }
- catch (StoreException e) { SetStoreResult(e.Message, sticky: true); }
- finally { _storeBusyId = null; }
- RenderStoreLists();
+ main?.Browser.RebuildSamples();
+ return $"{p.Name} was removed.";
+ });
}
// Every list, since a job in one disables the Install buttons of the others.
diff --git a/src/managed/Nota.App/PreferencesWindow.Store.cs b/src/managed/Nota.App/PreferencesWindow.Store.cs
index becee0b6..c22829a3 100644
--- a/src/managed/Nota.App/PreferencesWindow.Store.cs
+++ b/src/managed/Nota.App/PreferencesWindow.Store.cs
@@ -2,11 +2,11 @@
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
// Preferences → Downloads → Plug-ins: browse the Nota plugin registry and install / update /
-// remove open-source VST3 plugins (IPluginStore). One install at a time; it keeps
-// running when the user switches panes and is cancelled when the window closes. Its
-// progress and outcome show in a dock at the bottom of the window (visible from every
-// pane), which also cancels it; Sample Packs (PreferencesWindow.Samples.cs) shares that
-// job state and dock. After every change the catalog is rescanned so the browser lists the
+// remove open-source VST3 plugins (IPluginStore). One install at a time across all of Downloads
+// (DownloadJobs); it keeps running when the user switches panes or closes the window, and then
+// shows in the main window's status bar. Here its progress and outcome show in a dock at the
+// bottom of the window (visible from every pane), which also cancels it; Sample Packs and AI
+// Models share that dock. After every change the catalog is rescanned so the browser lists the
// new plugins.
//
// The list is virtualized (only the rows in view exist), so filtering and searching the
@@ -16,7 +16,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
@@ -26,9 +25,9 @@ using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
-using Avalonia.Threading;
using Microsoft.Extensions.DependencyInjection;
using Nota.Application;
+using Nota.Presentation;
namespace Nota.App;
@@ -40,14 +39,8 @@ public sealed partial class PreferencesWindow
private IReadOnlyList<StorePlugin>? _storePlugins;
private int _storeFilter;
private string _storeSearch = "";
- private string? _storeBusyId; // plugin being installed / removed
- private StoreProgress _storeProgress;
- private long _storeBusySize; // download size in bytes, 0 = unknown
+ private static DownloadJobs Jobs => DownloadJobs.Shared; // the running install / removal, app-wide
private string? _storeMessage; // registry loading / error, shown under the toolbar
- private string? _storeResult; // last install / remove outcome, shown in the dock
- private int _storeResultSeq; // guards the auto-hide of an older result
- private CancellationTokenSource? _storeCts; // window lifetime
- private CancellationTokenSource? _storeJobCts; // the running install; null when it can't be cancelled
private Task? _storeLoad;
private bool _storeLoading; // fetching the registry index
private ContentControl? _storeList; // null while another pane is showing
@@ -316,7 +309,7 @@ public sealed partial class PreferencesWindow
_dockTitle = new TextBlock { FontSize = 12, FontWeight = FontWeight.Medium, Foreground = TextPrimary, TextWrapping = TextWrapping.Wrap, VerticalAlignment = VerticalAlignment.Center };
_dockDetail = new TextBlock { FontSize = 10, FontFamily = NotaFonts.MonoFamily, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center };
_dockBar = new ProgressBar { Minimum = 0, Maximum = 1, Height = 4, MinWidth = 0 };
- _dockCancel = StoreButton("Cancel", enabled: true, CancelStoreInstall);
+ _dockCancel = StoreButton("Cancel", enabled: true, Jobs.Cancel);
_dockCancel.VerticalAlignment = VerticalAlignment.Center;
ToolTip.SetTip(_dockCancel, "Stop the download — nothing is changed");
_dockClose = new Button
@@ -324,7 +317,7 @@ public sealed partial class PreferencesWindow
Content = new Glyph(GlyphKind.Close, 10), Classes = { "ghost" }, Width = 26, Height = 26, Padding = new Thickness(0),
Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center,
};
- ((Button)_dockClose).Click += (_, _) => { _storeResult = null; UpdateDock(); };
+ ((Button)_dockClose).Click += (_, _) => Jobs.Dismiss();
var head = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 12 };
head.Children.Add(_dockTitle);
@@ -346,43 +339,30 @@ public sealed partial class PreferencesWindow
private void UpdateDock()
{
- bool busy = _storeBusyId is not null;
- _dock.IsVisible = busy || _storeResult is not null;
+ bool busy = Jobs.Busy;
+ _dock.IsVisible = busy || Jobs.Result is not null;
if (!_dock.IsVisible) return;
- var pr = _storeProgress;
- _dockTitle.Text = busy ? pr.Message : _storeResult;
+ var pr = Jobs.Progress;
+ _dockTitle.Text = busy ? pr.Message : Jobs.Result;
_dockTitle.Foreground = busy ? TextPrimary : TextSecondary;
_dockBar.IsVisible = busy;
_dockBar.IsIndeterminate = busy && pr.Fraction < 0;
if (busy && pr.Fraction >= 0) _dockBar.Value = pr.Fraction;
- _dockDetail.Text = !busy || pr.Fraction < 0 ? ""
- : _storeBusySize > 0
- ? $"{(pr.Fraction * _storeBusySize / 1048576.0).ToString("0.0", NotaNum.Culture)} / {NotaNum.Unit(_storeBusySize / 1048576.0, "0.0", "MB")} · {NotaNum.Unit(pr.Fraction * 100, "0", "%")}"
- : NotaNum.Unit(pr.Fraction * 100, "0", "%");
+ _dockDetail.Text = busy ? ProgressDetail(pr, Jobs.Size) : "";
_dockDetail.IsVisible = _dockDetail.Text.Length > 0;
- _dockCancel.IsVisible = busy && _storeJobCts is not null;
- _dockCancel.IsEnabled = _storeJobCts is { IsCancellationRequested: false };
+ _dockCancel.IsVisible = busy && Jobs.Cancellable;
+ _dockCancel.IsEnabled = !Jobs.Cancelling;
_dockClose.IsVisible = !busy;
}
- private void CancelStoreInstall()
- {
- if (_storeJobCts is not { IsCancellationRequested: false } cts) return;
- cts.Cancel();
- _storeProgress = _storeProgress with { Message = "Cancelling…" };
- UpdateDock();
- }
-
- // Shows an install / remove outcome in the dock; a success fades out on its own, an error
- // stays until it's closed.
- private void SetStoreResult(string? text, bool sticky)
- {
- _storeResult = text;
- int seq = ++_storeResultSeq;
- if (text is not null && !sticky)
- DispatcherTimer.RunOnce(() => { if (seq == _storeResultSeq && _storeBusyId is null) { _storeResult = null; UpdateDock(); } }, TimeSpan.FromSeconds(8));
- }
+ /// <summary>"12.3 / 40.0 MB · 31 %" while the size is known, else just the percentage; empty
+ /// for an indeterminate stage.</summary>
+ internal static string ProgressDetail(StoreProgress pr, long size)
+ => pr.Fraction < 0 ? ""
+ : size > 0
+ ? $"{(pr.Fraction * size / 1048576.0).ToString("0.0", NotaNum.Culture)} / {NotaNum.Unit(size / 1048576.0, "0.0", "MB")} · {NotaNum.Unit(pr.Fraction * 100, "0", "%")}"
+ : NotaNum.Unit(pr.Fraction * 100, "0", "%");
private Control StoreRow(StorePlugin p, InstalledStorePlugin? inst)
{
@@ -410,8 +390,8 @@ public sealed partial class PreferencesWindow
text.Children.Add(new TextBlock { Text = notes, FontSize = 11, LineHeight = 16, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap });
var actions = new StackPanel { Spacing = 8, MinWidth = 96, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top };
- bool busy = _storeBusyId is not null;
- if (_storeBusyId == p.Id)
+ bool busy = Jobs.BusyId is not null;
+ if (Jobs.BusyId == p.Id)
{
actions.Children.Add(StoreButton(inst is null ? "Installing…" : "Working…", enabled: false, () => { }));
}
@@ -537,80 +517,40 @@ public sealed partial class PreferencesWindow
_ => kind.ToUpperInvariant(),
};
- private async void InstallFromStore(StorePlugin p)
+ private void InstallFromStore(StorePlugin p)
{
- if (_storeBusyId is not null) return;
- _storeBusyId = p.Id;
- _storeBusySize = p.Asset?.Size ?? 0;
- _storeProgress = new StoreProgress(0, $"Downloading {p.Name}…");
- SetStoreResult(null, sticky: true);
- _storeCts ??= new CancellationTokenSource();
- var job = _storeJobCts = CancellationTokenSource.CreateLinkedTokenSource(_storeCts.Token);
- RenderStoreLists();
- // A report queued before Cancel must not overwrite "Cancelling…".
- var progress = new Progress<StoreProgress>(r => { if (job.IsCancellationRequested) return; _storeProgress = r; UpdateDock(); });
- try
- {
- await _store.InstallAsync(p, progress, job.Token);
- _storeJobCts = null; // the files are in place — too late to cancel
- _storeProgress = new StoreProgress(-1, $"Scanning {p.Name}…");
- UpdateDock();
- SetStoreResult(await RescanAfterStoreChange() ? $"{p.Name} {p.Version} is installed — find it in the browser." : $"{p.Name} is installed. Rescan plugins to use it.", sticky: false);
- }
- catch (OperationCanceledException)
- {
- // Window closing: nothing to show. Otherwise the user pressed Cancel.
- if (_storeCts is { IsCancellationRequested: false }) SetStoreResult($"Installing {p.Name} was cancelled.", sticky: false);
- }
- catch (StoreException e) { SetStoreResult(e.Message, sticky: true); }
- catch (Exception e)
- {
- App.Services.GetRequiredService<ILogSink>().Error($"Installing {p.Id} failed", e);
- SetStoreResult($"Installing {p.Name} failed: {e.Message}", sticky: true);
- }
- finally
- {
- _storeBusyId = null;
- _storeJobCts = null;
- job.Dispose();
- }
- RenderStoreLists();
+ var main = _main;
+ Jobs.Install(p.Id, source: 0, p.Name, p.Asset?.Size ?? 0, new StoreProgress(0, $"Downloading {p.Name}…"),
+ (progress, ct) => _store.InstallAsync(p, progress, ct),
+ async () =>
+ {
+ Jobs.Report(new StoreProgress(-1, $"Scanning {p.Name}…"));
+ return await RescanAfterStoreChange(main)
+ ? $"{p.Name} {p.Version} is installed — find it in the browser."
+ : $"{p.Name} is installed. Rescan plugins to use it.";
+ });
}
private async void RemoveFromStore(StorePlugin p)
{
- if (_storeBusyId is not null) return;
+ if (Jobs.Busy) return;
var ok = await new ConfirmWindow("Remove plugin",
$"Remove {p.Name}? Projects that use it will load without it until it's installed again.",
"Remove", "Cancel").ShowDialog<bool>(this);
if (!ok) return;
- _storeBusyId = p.Id;
- _storeBusySize = 0;
- _storeProgress = new StoreProgress(-1, $"Removing {p.Name}…");
- SetStoreResult(null, sticky: true);
- RenderStoreLists();
- try
+ var main = _main;
+ Jobs.Remove(p.Id, source: 0, $"Removing {p.Name}…", async () =>
{
_store.Uninstall(p.Id);
- await RescanAfterStoreChange();
- SetStoreResult($"{p.Name} was removed.", sticky: false);
- }
- catch (StoreException e) { SetStoreResult(e.Message, sticky: true); }
- finally { _storeBusyId = null; }
- RenderStoreLists();
- }
-
- private async Task<bool> RescanAfterStoreChange()
- {
- if (_main is null) return false;
- return await PluginScan.RescanAsync(_main) is not null;
+ await RescanAfterStoreChange(main);
+ return $"{p.Name} was removed.";
+ });
}
- // Called from the constructor's Closed handler chain: stop a running download.
- private void CancelStoreWork()
+ // Static: the job can outlive this window.
+ private static async Task<bool> RescanAfterStoreChange(MainWindowViewModel? main)
{
- _storeCts?.Cancel();
- _storeCts?.Dispose();
- _storeCts = null;
+ if (main is null) return false;
+ return await PluginScan.RescanAsync(main) is not null;
}
}
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index 479ce008..46b7338d 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -155,9 +155,20 @@ public sealed partial class PreferencesWindow : NotaWindow
grid.Children.Add(column);
SetBody(grid);
- Closed += (_, _) => { StopTests(); CancelStoreWork(); };
+ // A running download outlives the window (DownloadJobs); only stop listening to it.
+ Jobs.Changed += RenderStoreLists;
+ Jobs.ProgressChanged += UpdateDock;
+ Closed += (_, _) => { StopTests(); Jobs.Changed -= RenderStoreLists; Jobs.ProgressChanged -= UpdateDock; };
Select(0);
EnsureStoreLoading();
+ UpdateDock();
+ }
+
+ /// <summary>Switch to Downloads, on the given source (0 plug-ins, 1 sample packs, 2 AI models).</summary>
+ public void ShowDownloads(int source)
+ {
+ _downloadSource = Math.Clamp(source, 0, DownloadSources.Length - 1);
+ Select(DownloadsIndex);
}
private static IEnumerable<Page> Pages => Nav.SelectMany(g => g.Pages);