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.

15.6 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
// M4.1-A: root view model. Owns the engine lifetime + the playhead clock and
// exposes child VMs. As later sub-steps land, more of the window (arrangement,
// browser, device chain) moves under here; for now the arrangement/toolbar/
// keyboard stay in code-behind but drive the engine via this VM.

using CommunityToolkit.Mvvm.ComponentModel;
using Nota.Application;
using Nota.Application.Localization;

namespace Nota.Presentation;

public sealed partial class MainWindowViewModel : ObservableObject, IDisposable
{
    private readonly IPeriodicTimer _clock;
    private readonly IPeriodicTimer _autosave;
    private readonly ILogSink _log;
    private int _lastXrunCount;
    private readonly DropoutCounter _dropouts = new();

    public IAudioEngine Engine { get; }
    public TransportViewModel Transport { get; }
    public BrowserViewModel Browser { get; }
    public ISettingsService Settings { get; }

    /// <summary>Fired ~30 Hz with the playhead position in beats.</summary>
    public event Action<double>? PlayheadUpdated;
    /// <summary>Fired ~30 Hz only while recording (to refresh captured notes).</summary>
    public event Action? RecordingTick;
    /// <summary>Fired every ~30 s so the window can autosave a crash-recovery snapshot (M7-7).</summary>
    public event Action? AutosaveRequested;
    /// <summary>Version history was just turned off in Settings: the window erases the open
    /// project's history.</summary>
    public event Action? VersionHistoryTurnedOff;
    /// <summary>The audio driver restarted (or fell back) on its own, after a device event, or
    /// the status bar changed the buffer: an open Settings ▸ Audio pane re-reads the driver's
    /// buffer, latency and channels.</summary>
    public event Action? AudioDeviceRestarted;
    /// <summary>The backend restarted through <see cref="ApplyAudioSettings"/>, by any path (Settings,
    /// the buffer menu, a driver event): the device it opened may be another one (a new system
    /// default), so the app re-reads that device's input setup (specs/086).</summary>
    public event Action? AudioApplied;

    /// <summary>Turns version history on or off and persists it. Turning it off (the caller has
    /// confirmed) erases the open project's history; other projects lose theirs on their next save.</summary>
    public void SetKeepVersionHistory(bool on)
    {
        if (Settings.Current.KeepVersionHistory == on) return;
        Settings.Current.KeepVersionHistory = on;
        Settings.Save();
        if (!on) VersionHistoryTurnedOff?.Invoke();
    }

    [ObservableProperty] private string _engineInfo = "";
    /// <summary>The status bar's dropout count (#271): "1 dropout", "3 dropouts".</summary>
    [ObservableProperty] private string _dropoutText = DropoutCounter.Text(0);
    /// <summary>At least one dropout since the device started or the count was reset; the
    /// status bar shows the count only then.</summary>
    [ObservableProperty] private bool _hasDropouts;
    [ObservableProperty] private string _statusText = "";
    [ObservableProperty] private ToolbarSide _toolbarSide = ToolbarSide.Left;

    // Background-operation strip in the status bar (see MainWindow.RunBackgroundAsync).
    // Visible only while BackgroundBusy; Progress is 0..100, or Indeterminate when the
    // phase length isn't known yet.
    [ObservableProperty] private bool _backgroundBusy;
    [ObservableProperty] private string _backgroundLabel = "";
    [ObservableProperty] private double _backgroundProgress;
    [ObservableProperty] private bool _backgroundIndeterminate = true;

    /// <summary>
    /// When true, the playhead clock stops touching the engine. Set during
    /// offline export (M6-4) so the render thread has exclusive engine access
    /// while the audio backend is stopped.
    /// </summary>
    public bool SuspendEnginePolling { get; set; }

    public MainWindowViewModel(IAudioEngine engine, TransportViewModel transport,
                               BrowserViewModel browser, ISettingsService settings,
                               IPeriodicTimerFactory timers, EngineBuildInfo build,
                               ILogSink log)
    {
        Engine = engine;
        Transport = transport;
        Browser = browser;
        Settings = settings;
        _log = log;

        // No output must not stop Nota from opening (#243): the engine falls back to a silent
        // device, and if even that fails the app still starts, with audio off.
        try { Engine.Start(); }
        catch (NotaEngineException ex) { _log.Error("The audio engine couldn't start", ex); }
        Engine.SetBpm(120);
        Engine.SetTimeSignature(4, 4);
        UpdateEngineInfo();
        _log.Info($"Engine started · {Engine.SampleRate:0}\u2009Hz");
        if (NoAudioOutput is { } why) { _log.Warn(why); StatusText = why; }
        else if (AsioFallbackStatus() is { } asio) { _log.Warn(asio); StatusText = asio; }

        Transport.Message += m => { if (m.Length > 0) StatusText = m; };

        ApplyToolbarSide();
        Settings.Changed += ApplyToolbarSide;

        _clock = timers.Create(TimeSpan.FromMilliseconds(33), OnTick);
        _clock.Start();

        // Crash-recovery autosave (M7-7): the window captures + writes a snapshot,
        // gated by a manifest diff so idle sessions don't churn the disk.
        _autosave = timers.Create(TimeSpan.FromSeconds(30), OnAutosaveTick);
        _autosave.Start();
    }

    private void ApplyToolbarSide() => ToolbarSide = Settings.Current.ToolbarSide;

    private void OnTick()
    {
        if (SuspendEnginePolling) return; // export in progress — render thread owns the engine
        Engine.Poll(); // materialise recorded notes
        Transport.Tick();
        PlayheadUpdated?.Invoke(Engine.PositionBeats);
        if (Engine.IsRecording) RecordingTick?.Invoke();
        ReportDropouts();
        if (_applyAfterPanel && !Engine.AsioPanelOpen) { _applyAfterPanel = false; ApplyAudioSettings(); AudioDeviceRestarted?.Invoke(); }
        PollAudioDevice();
    }

    // A settings change made while the ASIO driver's panel was open, applied once it closes.
    private bool _applyAfterPanel;

    /// <summary>The sample rate the ASIO driver refused at the last apply (0 = none).</summary>
    public double RefusedSampleRate { get; private set; }

    // The ASIO driver asked for a restart (its buffer size, rate or latencies changed in its
    // own panel) or stopped calling back (specs/049, FR-009/FR-011). Restart through the one
    // apply path — which falls back to WASAPI if the driver won't start — and carry on
    // playing from the same spot. Never restarted from inside a driver callback.
    private void PollAudioDevice()
    {
        var ev = Engine.PollDeviceEvent();
        if (ev == AudioDeviceEvent.None) return;
        bool wasPlaying = Engine.IsPlaying && !Engine.IsRecording;
        double position = Engine.PositionBeats;
        _log.Info(ev == AudioDeviceEvent.ResetRequested ? "Audio driver asked for a reset" : "Audio driver stopped responding");
        ApplyAudioSettings();
        if (ev == AudioDeviceEvent.ResetRequested && Engine.ActiveAudioSystem == AudioSystem.Asio)
            StatusText = Loc.F("main.audio_driver_settings_changed_frames", Engine.NegotiatedBufferFrames);
        if (wasPlaying && Engine.IsRunning)
        {
            Engine.Seek(position);
            Engine.Play();
        }
        AudioDeviceRestarted?.Invoke();
    }

    private void OnAutosaveTick()
    {
        if (!SuspendEnginePolling && Engine.TrackCount > 0) AutosaveRequested?.Invoke();
    }

    // Surface any new audio dropouts (M7-8): log to stderr, count them in the status bar
    // (#271) and show a non-fatal status message. Playback is never interrupted — the
    // counter is passive.
    private void ReportDropouts()
    {
        int count = Engine.XrunCount;
        if (count <= _lastXrunCount) return;
        _lastXrunCount = count;
        Console.Error.WriteLine($"[xrun] audio dropout #{count} at {DateTime.Now:o}");
        _log.Warn($"Audio dropout #{count}");
        if (!_dropouts.Observe(count)) return;   // all from before the last reset: logged only
        ShowDropouts();
        StatusText = Loc.F("main.audio_dropout", _dropouts.Count);
    }

    /// <summary>Count dropouts from zero again (#271): a click on the status bar's counter,
    /// and every device (re)start — a new device, rate or buffer is a fresh measurement.
    /// The log still gets every dropout.</summary>
    public void ResetDropouts()
    {
        _dropouts.Reset(Engine.XrunCount);
        ShowDropouts();
    }

    private void ShowDropouts()
    {
        DropoutText = DropoutCounter.Text(_dropouts.Count);
        HasDropouts = _dropouts.Count > 0;
    }

    /// <summary>
    /// Applies staged audio-device settings (M7-1): stops the playhead clock
    /// touching the engine, restarts the backend on the new device/rate/buffer,
    /// then resumes. Returns the negotiated status text; sets StatusText too.
    /// </summary>
    public string ApplyAudioSettings()
    {
        // The driver's thread is inside its own (modal) panel: restarting now would wait on it
        // and freeze the UI. Apply when the panel closes; the tick picks it up.
        if (Engine.AsioPanelOpen)
        {
            _applyAfterPanel = true;
            RefusedSampleRate = 0;   // the old refusal no longer answers this new request
            StatusText = Loc.T("main.close_the_drivers_settings_window");
            return StatusText;
        }

        // Don't restart the backend mid-playback.
        if (Engine.IsPlaying) Transport.PlayStopCommand.Execute(null);

        double askedRate = Engine.GetAudioConfig().SampleRate;
        SuspendEnginePolling = true;
        try
        {
            Engine.ApplyAudio();
        }
        catch (NotaEngineException ex)
        {
            _log.Error("Audio device apply failed", ex);
            StatusText = Loc.F("main.audio_device_error", ex.Message);
            return StatusText;
        }
        finally
        {
            SuspendEnginePolling = false;
        }
        AudioApplied?.Invoke();

        // The engine drops a rate the ASIO driver refused (back to device default). Remember
        // it here, so Settings can say why — also when the apply waited for the driver's panel.
        RefusedSampleRate = askedRate > 0 && Engine.ActiveAudioSystem == AudioSystem.Asio
                            && Engine.GetAudioConfig().SampleRate == 0 ? askedRate : 0;
        UpdateEngineInfo();
        ResetDropouts();
        int buf = Engine.NegotiatedBufferFrames;
        _log.Info($"Audio applied · {Engine.NegotiatedSampleRate:0}\u2009Hz · {buf} frames");
        if (NoAudioOutput is { } why)
        {
            _log.Warn(why);
            StatusText = why;
            return StatusText;
        }
        if (AsioFallbackStatus() is { } asio)
        {
            _log.Warn(asio);
            StatusText = asio;
            return StatusText;
        }
        if (Engine.ActiveAudioSystem == AudioSystem.Asio)
        {
            StatusText = Loc.F("main.audio_asio_hz_frames", AsioDriverName(), Engine.NegotiatedSampleRate, buf);
            return StatusText;
        }
        bool fallback = Engine.AudioExclusiveFallback;
        if (fallback)
        {
            _log.Warn("WASAPI exclusive mode refused — fell back to shared");
            StatusText = Loc.T("main.wasapi_exclusive_unavailable_using_shared");
            return StatusText;
        }
        StatusText = buf > 0
            ? Loc.F("main.audio_hz_frames", Engine.NegotiatedSampleRate, buf)
            : Loc.F("main.audio_hz", Engine.NegotiatedSampleRate);
        return StatusText;
    }

    private void UpdateEngineInfo()
    {
        double sr = Engine.NegotiatedSampleRate > 0 ? Engine.NegotiatedSampleRate : Engine.SampleRate;
        // The silent stand-in (no output opened) is "running" but negotiated nothing.
        EngineInfo = AudioFormatStatus.Text(sr, Engine.IsRunning && !Engine.AudioSilentFallback ? Engine.NegotiatedBufferFrames : 0);
    }

    /// <summary>Who sets the running device's buffer: Nota, the ASIO driver, or the device
    /// itself in WASAPI exclusive mode. An ASIO start that fell back to WASAPI is shared mode,
    /// even when exclusive is still saved.</summary>
    public BufferOwner BufferOwner => AudioFormatStatus.Owner(
        Engine.ActiveAudioSystem == AudioSystem.Asio,
        AudioFormatStatus.ExclusiveIsRunning(
            OperatingSystem.IsWindows(),
            Engine.AudioSystem == AudioSystem.Asio,
            Engine.ActiveAudioSystem == AudioSystem.Asio,
            Engine.GetAudioConfig().WasapiExclusive,
            Engine.AudioExclusiveFallback));

    /// <summary>The status bar's buffer menu (#373): stage the size (0 = device default), restart
    /// the backend on it, carry on playing from the same spot, and let an open Settings ▸ Audio
    /// pane re-read it. A no-op while recording — the menu disables the sizes, and this guards a
    /// take that started from elsewhere while the menu stayed open.</summary>
    public void SetAudioBufferFrames(int frames)
    {
        if (Engine.IsRecording) return;
        bool wasPlaying = Engine.IsPlaying;
        double position = Engine.PositionBeats;
        Engine.SetAudioBufferFrames(frames);
        ApplyAudioSettings();
        if (wasPlaying && Engine.IsRunning)
        {
            Engine.Seek(position);
            Engine.Play();
        }
        AudioDeviceRestarted?.Invoke();
    }

    /// <summary>The ASIO driver chosen in Settings couldn't start and WASAPI runs instead
    /// (FR-011): the status line naming the driver and the reason, else null.</summary>
    public string? AsioFallbackStatus()
    {
        if (Engine.AudioSystem != AudioSystem.Asio || Engine.ActiveAudioSystem == AudioSystem.Asio) return null;
        string reason = Engine.AudioFallbackReason;
        if (reason.Length > 0) reason = char.ToUpperInvariant(reason[0]) + reason[1..] + ".";
        return Loc.F("main.asio_driver_couldnt_start_using", AsioDriverName(), reason).TrimEnd();
    }

    /// <summary>Display name of the staged ASIO driver (the first installed when none is staged).</summary>
    public string AsioDriverName()
    {
        var drivers = Engine.AsioDrivers();
        string id = Engine.AsioDriver;
        foreach (var d in drivers)
            if (string.Equals(d.Uid, id, StringComparison.OrdinalIgnoreCase)) return d.Name;
        return id.Length == 0 && drivers.Count > 0 ? drivers[0].Name : "ASIO";
    }

    /// <summary>Why nothing is heard when no output device opened (the engine runs silently
    /// or not at all), else null.</summary>
    public string? NoAudioOutput
        => !Engine.IsRunning ? Loc.T("main.no_audio_output_could_be_opened_outputs")
         : Engine.AudioSilentFallback ? Loc.T("main.no_audio_output_device_opened_outputs")
         : null;

    /// <summary>
    /// Applies staged MIDI-input settings (M7-2). Lighter than audio: only the
    /// CoreMIDI port is reconnected, the audio backend keeps running, so no
    /// polling suspension is needed.
    /// </summary>
    public void ApplyMidiSettings()
    {
        try
        {
            Engine.ApplyMidi();
            _log.Info("MIDI inputs updated");
            StatusText = Loc.T("main.midi_inputs_updated");
        }
        catch (NotaEngineException ex)
        {
            _log.Error("MIDI apply failed", ex);
            StatusText = Loc.F("main.midi_error", ex.Message);
        }
    }

    public void Dispose()
    {
        _clock.Stop();
        _autosave.Stop();
        Engine.Dispose();
    }
}