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.

10.2 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Controls.Shapes;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform.Storage;
using Microsoft.Extensions.DependencyInjection;
using Nota.Application;
using Nota.Presentation;
using Nota.Application.Localization;

namespace Nota.App;

public partial class MainWindow
{
    // --- browser drag & drop (M7-5) ----------------------------------------

    // Every route a browser item takes onto a track goes through one service (CP-25), so a
    // drop and the command palette put a device in the same place. The service does the
    // engine work as one undo step; ApplyInsertResult does what the views need afterwards.

    private void OnArrangementDrop(BrowserItem item, int trackId, double beat)
    {
        if (_vm is null) return;
        try
        {
            int landed = -1;   // the track the drop ended up on (a new one included) — it becomes the selection
            switch (item.Kind)
            {
                case BrowserItemKind.Sample:
                    // Decodes in the background; the track shows a filling placeholder meanwhile
                    // (and is selected there as soon as it exists).
                    _ = ImportAudioInBackgroundAsync(item.Path, Insertion.TrackIsAudio(trackId) ? trackId : -1, beat);
                    break;
                case BrowserItemKind.MidiFile:
                    landed = ImportMidiFileToArrangement(item, trackId, beat);
                    break;
                default:   // instruments replace / start a track; effects + presets target the track
                    var r = Insertion.DropOnArrangement(item, trackId, beat);
                    ApplyInsertResult(r, revealDevices: item.Kind is not (BrowserItemKind.BuiltinInstrument or BrowserItemKind.PluginInstrument));
                    if (r.Ok) landed = r.TrackId;
                    break;
            }
            Timeline.Refresh();
            _session?.Refresh();
            if (landed > 0) Timeline.Select(landed, -1);
        }
        catch (Exception ex) { _vm.StatusText = Loc.F("main.dnd.drop_failed", ex.Message); }
    }

    private void OnSessionDrop(BrowserItem item, int trackId, int scene, bool instrumentTrack)
    {
        if (_vm is null) return;
        try
        {
            bool landed = false;   // the drop's slot (and so its track) becomes the selection
            // A column header or the empty grid has no slot for a clip.
            if (scene < 0 && item.Kind is BrowserItemKind.Sample or BrowserItemKind.MidiFile)
            {
                _vm.StatusText = Loc.T("main.dnd.drop_samples_and_midi_files");
                return;
            }
            switch (item.Kind)
            {
                case BrowserItemKind.Sample:
                    if (instrumentTrack) { _vm.StatusText = Loc.T("main.dnd.drop_samples_onto_audio_slots"); break; }
                    if (Engine.AddSessionAudioFile(trackId, scene, item.Path))
                    {
                        _vm.StatusText = Loc.F("main.added_to_slot", item.Name);
                        landed = true;
                    }
                    break;
                case BrowserItemKind.MidiFile:
                    landed = instrumentTrack;
                    ImportMidiFileToSlot(item, trackId, scene, instrumentTrack);
                    break;
                case BrowserItemKind.BuiltinEffect:
                case BrowserItemKind.PluginEffect:
                case BrowserItemKind.BuiltinMidiEffect:
                    if (trackId <= 0) { _vm.StatusText = Loc.T("main.dnd.drop_effects_onto_a_column"); break; }
                    var r = Insertion.RouteToTrack(item, trackId); // a session column is a track
                    ApplyInsertResult(r);
                    landed = r.Ok;
                    break;
                default: // instruments and presets (#313): replace, add a chain / pad, or start a track
                {
                    InsertResult ir;
                    Engine.BeginUndoGroup();
                    try
                    {
                        ir = Insertion.DropOnSession(item, trackId);
                        // A new track goes right after the column it was dropped on.
                        if (ir.Ok && ir.CreatedTrack && trackId > 0) Timeline.PlaceNewTrack(ir.TrackId, trackId);
                    }
                    finally { Engine.EndUndoGroup(); }
                    if (ir.ToRackCard)   // an instrument preset on an Instrument Rack: a new chain, from its card
                    {
                        ShowDevices(ir.TrackId);
                        if (_deviceChain?.DropOnInstrumentRack(item) != true) _vm.StatusText = Loc.F("main.dnd.couldnt_add_to_the_rack", item.Name);
                    }
                    else ApplyInsertResult(ir, revealDevices: !ir.CreatedTrack);
                    if (ir.Ok && ir.TrackId > 0) { trackId = ir.TrackId; landed = true; }
                    break;
                }
            }
            _session?.Refresh();
            Timeline.Refresh();
            if (landed && trackId > 0)
            {
                // The drop's slot (and so its track) becomes the selection; a header or the empty
                // grid has no slot, so the track's first scene stands in.
                _session?.SelectSlot(trackId, Math.Max(0, scene));   // the arrangement follows to the same track
                if (Timeline.SelectedTrackId != trackId) Timeline.Select(trackId, -1);
            }
        }
        catch (Exception ex) { _vm.StatusText = Loc.F("main.dnd.drop_failed", ex.Message); }
    }

    // A browser item dropped on the Devices panel of the shown track. An effect lands in
    // the gap it was dropped on, or replaces the card it was dropped on; an instrument
    // replaces the track's instrument (a rack gets a new chain / pad instead). The rest —
    // presets, samples — routes as usual.
    private void OnDevicePanelDrop(BrowserItem item, DeviceDropTarget target)
    {
        int t = _deviceChain?.TrackId ?? -1;
        if (_vm is null) return;
        var placement = target.Mode switch
        {
            DeviceDropMode.Insert => InsertPlacement.Insert,
            DeviceDropMode.Replace => InsertPlacement.Replace,
            _ => InsertPlacement.Default,
        };
        ApplyInsertResult(Insertion.Insert(item, new InsertTarget(t, placement, target.Index, target.Midi)));
    }

    private void OnModularDrop(BrowserItem item) => DropBrowserItem(item, _modular?.TrackId ?? -1);

    // Adds an instrument/effect/MIDI-FX/sample/preset from the browser to a track;
    // shared by the Devices-panel and Modular-view drop targets.
    private void DropBrowserItem(BrowserItem item, int t)
    {
        if (_vm is null) return;
        if (t <= 0) { _vm.StatusText = Loc.T("common.select_a_track_first"); return; }
        ApplyInsertResult(Insertion.Insert(item, new InsertTarget(t)));
    }

    private DeviceInsertService? _insertion;
    private DeviceInsertService Insertion => _insertion ??= NewInsertion();

    private DeviceInsertService NewInsertion()
    {
        var s = new DeviceInsertService(Engine, _factory, _presets, _kits);
        s.InstrumentAdded += OnInstrumentAdded;   // "Add track ▸ Recent" (MainWindow.Recent.cs)
        s.InstrumentPresetApplied += RecordTrackInstrument;
        return s;
    }

    /// <summary>What the views do after the insert service changed a track: card state, the
    /// last-instrument fallback, refreshes, revealing the chain, the status line.</summary>
    private void ApplyInsertResult(InsertResult r, bool revealDevices = true)
    {
        if (_vm is null) return;
        _vm.StatusText = r.Status;
        if (!r.Ok) return;
        int t = r.TrackId;
        if (t > 0 && (r.InstrumentReplaced || r.CreatedTrack) && Insertion.TryTrackInfo(t, out var ti) && ti.IsInstrument)
            _lastInstrumentTrackId = t;
        if (r.InstrumentReplaced) RefreshDeviceChainIfShowing(t);
        if (r.Placed is { } p) _deviceChain?.AdoptPlacement(t, p.Midi, p.Added, p.Final, p.Replaced);
        if (r.PresetLanded is { } pl)
            _deviceChain?.RememberPreset(pl.TrackId, pl.Chain switch
            {
                PresetChain.Instrument => DeviceChainView.ChainKind.Instrument,
                PresetChain.Midi => DeviceChainView.ChainKind.Midi,
                _ => DeviceChainView.ChainKind.Effect,
            }, pl.Index, pl.Name, pl.FactoryId);
        Timeline.Refresh();
        if (r.CreatedTrack && t > 0)
        {
            Timeline.RevealTrack(t);   // a new track lands in view (F1)
            // …and becomes the selected track, as a drop does: the old selection's highlight
            // goes, and arm-on-select hands it the keyboard (#332).
            if (Timeline.SelectedTrackId != t) Timeline.SelectTrackFromOutside(t);
        }
        _session?.Refresh();
        if (_modular?.IsVisible == true) _modular.Refresh();
        if (revealDevices && r.ShowDevices && t > 0) ShowDevices(t);
        else _deviceChain?.Refresh();
        if (r.PluginAdded is { } pa && _vm.Settings.Current.OpenPluginWindowOnInsert) OpenAddedPluginWindow(pa.TrackId, pa.DeviceIndex);
    }

    // A plug-in the user just added opens its window (#250). One without an editor, or whose
    // window fails, just stays closed: the card's Open editor reports the failure if asked.
    private void OpenAddedPluginWindow(int trackId, int deviceIndex)
    {
        try { Engine.OpenPluginEditor(trackId, deviceIndex); }
        catch { /* no editor: nothing to open */ }
    }

    private bool TrackIsAudio(int trackId) => Insertion.TrackIsAudio(trackId);

    // Refresh the device panel after an in-place instrument swap, but only when it's already
    // open on that track (never force it open). The old instrument's preset label is dropped
    // either way so it doesn't reappear on the new one.
    private void RefreshDeviceChainIfShowing(int trackId)
    {
        _deviceChain?.ForgetInstrumentState(trackId);
        if (_deviceChain?.IsVisible == true && _deviceChain.TrackId == trackId) _deviceChain.Show(trackId);
    }
}