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.

16.6 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
// 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 (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.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Layout;
using Avalonia.Media;
using Microsoft.Extensions.DependencyInjection;
using Nota.Application;
using Nota.Application.Localization;

namespace Nota.App;

public sealed partial class PreferencesWindow
{
    private static readonly string[] PackFilters = { Loc.T("preferences.all"), Loc.T("preferences.samples.one_shots"), Loc.T("common.instruments"), Loc.T("preferences.installed") };

    private readonly ISampleStore _samples = App.Services.GetRequiredService<ISampleStore>();
    private IReadOnlyList<StorePack>? _packs;
    private int _packFilter;
    private string _packSearch = "";
    private string? _packMessage;                    // registry loading / error, shown under the toolbar
    private Task? _packLoad;
    private bool _packLoading;
    private ContentControl? _packList;               // null while another pane is showing
    private ItemsControl? _packItems;
    private TextBlock[]? _packCounts;
    private TextBlock? _packStatus;
    private Button? _packRefresh;
    private ProgressBar? _packLoadBar;

    private sealed record PackEntry(StorePack Pack, InstalledStorePack? Installed, bool First);

    private static string PackKey(string id) => "pack:" + id;

    private static readonly string PacksIntro = Loc.T("preferences.samples.free_sample_packs_from_the");

    // The Sample Packs half of Downloads (PreferencesWindow.Downloads.cs).
    private (Control Toolbar, Control Body) PackParts()
    {
        var strip = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2 };
        var segs = new List<ToggleButton>();
        _packCounts = new TextBlock[PackFilters.Length];
        for (int i = 0; i < PackFilters.Length; i++)
        {
            int idx = i;
            var count = new TextBlock { FontSize = 8.5, FontFamily = NotaFonts.ValuesFamily, VerticalAlignment = VerticalAlignment.Center };
            _packCounts[i] = count;
            var b = new ToggleButton
            {
                Classes = { "seg" }, FontSize = 11, IsChecked = i == _packFilter,
                Content = new StackPanel
                {
                    Orientation = Orientation.Horizontal, Spacing = 6,
                    Children = { new TextBlock { Text = PackFilters[i], VerticalAlignment = VerticalAlignment.Center }, count },
                },
            };
            b.Click += (_, _) =>
            {
                for (int k = 0; k < segs.Count; k++) segs[k].IsChecked = k == idx;
                _packFilter = idx;
                RenderPackList();
            };
            segs.Add(b);
            strip.Children.Add(b);
        }
        var search = new TextBox { PlaceholderText = Loc.T("preferences.search"), Text = _packSearch, Classes = { "search" }, FontSize = 11 };
        search.TextChanged += (_, _) => { _packSearch = search.Text ?? ""; RenderPackList(); };
        var refresh = new Button { Content = Loc.T("preferences.refresh"), Classes = { "ghost" }, Height = 30, FontSize = 11, Padding = new Thickness(12, 0), Foreground = TextSecondary };
        ToolTip.SetTip(refresh, Loc.T("preferences.reload_the_registry"));
        refresh.Click += (_, _) => { if (!_packLoading) _packLoad = LoadPacksAsync(refresh: true); };
        _packRefresh = refresh;

        var toolbar = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 10 };
        toolbar.Children.Add(new Border { Classes = { "segmented" }, Child = strip });
        var searchField = SearchField(search, double.PositiveInfinity);
        searchField.MinWidth = 140;
        Grid.SetColumn(searchField, 1); toolbar.Children.Add(searchField);
        Grid.SetColumn(refresh, 2); toolbar.Children.Add(refresh);

        var list = _packList = new ContentControl();
        _packStatus = Caption("");
        _packLoadBar = new ProgressBar { IsIndeterminate = true, Height = 3, MinWidth = 0, IsVisible = false };
        _packItems = PackItems();

        var body = new StackPanel
        {
            Spacing = 14,
            Children =
            {
                _packStatus,
                new StackPanel { Spacing = 6, Children = { _packLoadBar, _packList } },
                Caption(Loc.F("preferences.installed_to", _samples.InstallDir)),
            },
        };
        body.DetachedFromVisualTree += (_, _) =>
        {
            if (_packList != list) return;
            _packList = null; _packItems = null; _packStatus = null; _packCounts = null; _packRefresh = null; _packLoadBar = null;
        };
        if (_packs is null && _packLoad is not { IsCompleted: false }) _packLoad = LoadPacksAsync(refresh: false);
        RenderPackList();
        return (toolbar, body);
    }

    private async Task LoadPacksAsync(bool refresh)
    {
        _packLoading = true;
        _packMessage = null;
        RenderPackList();
        try
        {
            _packs = await _samples.FetchAsync(refresh);
        }
        catch (StoreException e)
        {
            _packMessage = e.Message;
        }
        finally { _packLoading = false; }
        RenderPackList();
    }

    private ItemsControl PackItems() => new()
    {
        ItemsPanel = new FuncTemplate<Panel?>(() => new VirtualizingStackPanel()),
        Margin = new Thickness(0, 0, 0, -1),
        DataTemplates =
        {
            new FuncDataTemplate<PackEntry>((e, _) => e is null ? new Panel() : new Border
            {
                Background = RowBg, BorderBrush = Hairline, BorderThickness = new Thickness(0, e.First ? 0 : 1, 0, 0),
                Child = PackRow(e.Pack, e.Installed),
            }),
        },
    };

    private void RenderPackList()
    {
        if (_packList is null || _packItems is null) return;
        if (_packStatus is not null)
        {
            _packStatus.Text = _packMessage ?? "";
            _packStatus.IsVisible = _packStatus.Text.Length > 0;
        }
        if (_packRefresh is not null)
        {
            _packRefresh.IsEnabled = !_packLoading;
            _packRefresh.Content = _packLoading && _packs is not null ? Loc.T("preferences.refreshing") : Loc.T("preferences.refresh");
        }
        if (_packLoadBar is not null) _packLoadBar.IsVisible = _packLoading && _packs is not null;
        if (_packs is null)
        {
            _packList.Content = _packLoading ? PackLoadingBlock() : null;
            UpdatePackCounts(null);
            return;
        }

        var installed = _samples.Installed.ToDictionary(i => i.Id);
        UpdatePackCounts(installed);
        var q = _packSearch.Trim();
        var shown = _packs.Where(p => MatchesPackFilter(p, _packFilter, installed))
            .Where(p => q.Length == 0
                        || p.Name.Contains(q, StringComparison.OrdinalIgnoreCase)
                        || p.Author.Contains(q, StringComparison.OrdinalIgnoreCase)
                        || p.Description.Contains(q, StringComparison.OrdinalIgnoreCase)
                        || p.Tags.Any(t => t.Contains(q, StringComparison.OrdinalIgnoreCase)))
            .ToList();

        if (shown.Count == 0)
        {
            var empty = new TextBlock
            {
                Text = _packFilter == 3 && q.Length == 0 ? Loc.T("preferences.samples.no_sample_packs_installed_from") : Loc.T("preferences.nothing_matches"),
                FontSize = 11, Foreground = TextTertiary, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(28),
            };
            _packList.Content = Table(new List<Control> { empty });
            return;
        }

        _packItems.ItemsSource = shown.Select((p, i) => new PackEntry(p, installed.GetValueOrDefault(p.Id), First: i == 0)).ToList();
        if (_packList.Content is not Border { Tag: "pack-table" })
            _packList.Content = new Border
            {
                Tag = "pack-table", BorderBrush = Divider, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Group,
                ClipToBounds = true, Child = _packItems,
            };
    }

    private Control PackLoadingBlock() => Table(new List<Control>
    {
        new StackPanel
        {
            Spacing = 10, Margin = new Thickness(28, 36), HorizontalAlignment = HorizontalAlignment.Center,
            Children =
            {
                new ProgressBar { IsIndeterminate = true, Width = 180, Height = 4, MinWidth = 0 },
                new TextBlock { Text = Loc.T("preferences.samples.loading_the_sample_registry"), FontSize = 11, Foreground = TextTertiary, HorizontalAlignment = HorizontalAlignment.Center },
            },
        },
    });

    private static bool MatchesPackFilter(StorePack p, int filter, IReadOnlyDictionary<string, InstalledStorePack> installed) => filter switch
    {
        1 => p.Kind is "one-shots" or "loops" or "mixed",
        2 => p.Kind is "multisample",
        3 => installed.ContainsKey(p.Id),
        _ => true,
    };

    private void UpdatePackCounts(IReadOnlyDictionary<string, InstalledStorePack>? installed)
    {
        if (_packCounts is null) return;
        for (int i = 0; i < _packCounts.Length; i++)
        {
            _packCounts[i].Text = _packs is null || installed is null ? "" : _packs.Count(p => MatchesPackFilter(p, i, installed)).ToString();
            _packCounts[i].Foreground = i == _packFilter ? NotaPalette.TextPrimary : TextDisabled;
        }
    }

    private static string PackKindLabel(string kind) => kind switch
    {
        "one-shots" => Loc.T("preferences.samples.one_shots"),
        "loops" => Loc.T("preferences.samples.loops"),
        "multisample" => Loc.T("common.instrument"),
        "mixed" => Loc.T("preferences.samples.mixed"),
        _ => NotaText.Label(kind.ToUpperInvariant()),
    };

    private static string Megabytes(long bytes)
        => bytes >= 1L << 30 ? NotaNum.Unit(bytes / (double)(1L << 30), "0.0", "GB") : NotaNum.Unit(bytes / 1048576.0, "0.0", "MB");

    private Control PackRow(StorePack p, InstalledStorePack? inst)
    {
        var text = new StackPanel
        {
            Spacing = 4,
            Children =
            {
                new WrapPanel
                {
                    Children =
                    {
                        new TextBlock { Text = p.Name, FontSize = 12, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary, Margin = new Thickness(0, 0, 8, 0), VerticalAlignment = VerticalAlignment.Center },
                        new TextBlock { Text = PackKindLabel(p.Kind), FontSize = 8.5, FontFamily = NotaFonts.ValuesFamily, Foreground = TextMuted, VerticalAlignment = VerticalAlignment.Center },
                    },
                },
                new TextBlock { Text = $"{p.Author} · {p.Version} · {p.License}", FontSize = 9, FontFamily = NotaFonts.ValuesFamily, Foreground = TextTertiary },
                new TextBlock { Text = p.Description, FontSize = 11, LineHeight = 18, Foreground = TextSecondary, TextWrapping = TextWrapping.Wrap },
            },
        };
        if (p.Attribution is { Length: > 0 } credit)
            text.Children.Add(new TextBlock { Text = Loc.F("preferences.samples.credit", credit), FontSize = 10, LineHeight = 16, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap });
        if (p.Notes is { Length: > 0 } notes)
            text.Children.Add(new TextBlock { Text = notes, FontSize = 10, LineHeight = 16, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap });

        var actions = new StackPanel { Spacing = 8, MinWidth = 96, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top };
        bool busy = Jobs.BusyId is not null;
        if (Jobs.BusyId == PackKey(p.Id))
        {
            actions.Children.Add(StoreButton(inst is null ? Loc.T("preferences.installing") : Loc.T("preferences.working"), enabled: false, () => { }));
        }
        else if (inst is null)
        {
            actions.Children.Add(StoreButton(Loc.T("preferences.install"), enabled: !busy, () => InstallPack(p)));
        }
        else
        {
            if (inst.Version != p.Version)
                actions.Children.Add(StoreButton(Loc.F("preferences.update_to", p.Version), enabled: !busy, () => InstallPack(p)));
            else
                actions.Children.Add(new StackPanel
                {
                    Orientation = Orientation.Horizontal, Spacing = 6, Height = 26, HorizontalAlignment = HorizontalAlignment.Right,
                    Children = { Dot(Brass), new TextBlock { Text = Loc.T("preferences.installed"), FontSize = 10, FontWeight = FontWeight.Medium, Foreground = Brass, VerticalAlignment = VerticalAlignment.Center } },
                });
            var show = StoreLink(Loc.T("common.show"), null, () => { try { MainWindow.RevealInFileManager(inst.Path); } catch { /* no file manager */ } });
            ToolTip.SetTip(show, Loc.T("preferences.samples.show_the_packs_folder"));
            actions.Children.Add(show);
            actions.Children.Add(StoreLink(Loc.T("preferences.remove"), null, busy ? null : () => RemovePack(p, inst)));
        }
        actions.Children.Add(new TextBlock
        {
            Text = inst is null ? Loc.F("preferences.samples.samples_n", Megabytes(p.Asset.Size), p.Asset.Files) : Loc.Plural("preferences.samples.samples", inst.Files),
            FontSize = 9, FontFamily = NotaFonts.UiFamily, Foreground = TextTertiary, HorizontalAlignment = HorizontalAlignment.Right,
        });
        if (inst is null)
            ToolTip.SetTip(actions.Children[^1], Loc.F("preferences.samples.download_samples_on_disk", Megabytes(p.Asset.Size), p.Asset.Files, Megabytes(p.Asset.UnpackedSize), string.Join(", ", p.Asset.Formats)));
        var source = StoreLink(Loc.T("preferences.source"), GlyphKind.PopOut, () => _ = Launcher.LaunchUriAsync(new Uri(p.Source)));
        ToolTip.SetTip(source, Loc.T("preferences.samples.open_the_packs_page"));
        actions.Children.Add(source);

        var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 16, Margin = new Thickness(16, 14, 14, 14) };
        grid.Children.Add(text);
        Grid.SetColumn(actions, 1);
        grid.Children.Add(actions);
        return grid;
    }

    private void InstallPack(StorePack p)
    {
        var main = _main;
        Jobs.Install(PackKey(p.Id), source: 1, p.Name, p.Asset.Size, new StoreProgress(0, Loc.F("preferences.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();
                // Its instruments become Nota Mosaic presets (Packs → the pack) in the background.
                _ = App.Services.GetService<IMosaicPacks>()?.ScanAsync();
                return Task.FromResult(Loc.F("preferences.samples.is_installed_find_it_under", p.Name));
            });
    }

    private async void RemovePack(StorePack p, InstalledStorePack inst)
    {
        if (Jobs.Busy) return;
        var ok = await new ConfirmWindow(Loc.T("preferences.samples.remove_sample_pack"),
            Loc.F("preferences.samples.remove_its_folder_is_deleted", p.Name, inst.Path),
            Loc.T("preferences.remove"), Loc.T("common.cancel")).ShowDialog<bool>(this);
        if (!ok) return;
        var main = _main;
        Jobs.Remove(PackKey(p.Id), source: 1, Loc.F("preferences.removing", p.Name), async () =>
        {
            await Task.Run(() => _samples.Uninstall(p.Id));
            main?.Browser.RebuildSamples();
            return Loc.F("preferences.was_removed", p.Name);
        });
    }

    // Every list, since a job in one disables the Install buttons of the others.
    private void RenderStoreLists()
    {
        RenderStoreList();
        RenderPackList();
        RenderModelList();
        UpdateDock();   // RenderStoreList only reaches the dock while the Downloads pane is showing
    }
}