Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
// 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.Diagnostics;
using System.IO;
using System.Linq;
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.Infrastructure;
using Nota.Presentation;
using Nota.Application.Localization;
namespace Nota.App;
public partial class MainWindow
{
private int _lastInstrumentTrackId;
private const double BrowserDefaultWidth = 344; // MainWindow.axaml's column width
// The browser column's width before it was folded to its rail, restored on unfold.
private GridLength _browserWidth = new(BrowserDefaultWidth);
// Double-clicking the splitter puts the column back at its default width.
private void ResetBrowserWidth()
{
_browserWidth = new GridLength(BrowserDefaultWidth);
BrowserGrid.ColumnDefinitions[0].Width = _browserWidth;
}
// Folded, the column hugs the rail and the splitter goes away — there's nothing to resize.
private void OnBrowserCollapsedChanged(bool collapsed)
{
var column = BrowserGrid.ColumnDefinitions[0];
if (collapsed)
{
if (column.Width.IsAbsolute) _browserWidth = column.Width;
column.MinWidth = 0;
column.Width = GridLength.Auto;
}
else
{
column.MinWidth = 160;
column.Width = _browserWidth;
}
BrowserSplitter.IsVisible = !collapsed;
}
/// <summary>The fallback target when nothing is selected: the last instrument track added,
/// but only while it still exists — it may have been deleted, cut or undone since, and
/// acting on a dead track id silently edits nothing (or re-shows its stale device chain).</summary>
private int LastInstrumentTrack()
{
if (_lastInstrumentTrackId > 0 && TrackIndexOf(_lastInstrumentTrackId) < 0) _lastInstrumentTrackId = 0;
return _lastInstrumentTrackId;
}
// Effects target the selected track, else the last instrument track added.
private int EffectTarget() => Timeline.SelectedTrackId > 0 ? Timeline.SelectedTrackId : LastInstrumentTrack();
private HashSet<int> TrackIds()
{
var ids = new HashSet<int>();
for (int i = 0; i < Engine.TrackCount; i++)
if (Engine.TryGetTrackInfo(i, out var ti)) ids.Add(ti.Id);
return ids;
}
// Double-click on a browser row: an instrument replaces the selected instrument track's
// instrument (clips and effects stay) — else, or with ⌥ held, it starts a track; effects
// go to the selected track (else the last instrument track, else a new audio track),
// presets apply — through the
// same insert service as drag & drop and the command palette.
private void OnBrowserItemActivated(BrowserItem item, KeyModifiers mods)
{
if (_vm is null) return;
if (item.Kind == BrowserItemKind.ModularNode) { AddModularNode(item); return; }
try
{
RecordUse(PaletteIdOf(item), fromPalette: false);
switch (item.Kind)
{
case BrowserItemKind.BuiltinInstrument:
case BrowserItemKind.PluginInstrument:
{
var r = Insertion.Insert(item, Insertion.ActivationTarget(Timeline.SelectedTrackId, (mods & KeyModifiers.Alt) != 0));
ApplyInsertResult(r, revealDevices: item.BuiltinKind is 1 or 3 or 4 && item.Kind == BrowserItemKind.BuiltinInstrument);
break;
}
case BrowserItemKind.BuiltinEffect:
case BrowserItemKind.BuiltinMidiEffect:
case BrowserItemKind.PluginEffect:
{
int tgt = EffectTarget();
ApplyInsertResult(tgt > 0 ? Insertion.RouteToTrack(item, tgt) : Insertion.EffectOnNewTrack(item));
break;
}
case BrowserItemKind.Sample:
_ = ImportAudioInBackgroundAsync(item.Path, -1, 0.0);
break;
case BrowserItemKind.MidiFile:
ImportMidiFileToArrangement(item, -1, 0.0);
Timeline.Refresh();
break;
case BrowserItemKind.Project:
_ = OpenProjectConfirmedAsync(item.Path);
return; // OpenProject rebuilds everything itself
case BrowserItemKind.Preset:
ApplyInsertResult(Insertion.ApplyPreset(item, new InsertTarget(Timeline.SelectedTrackId)));
break;
}
_session?.Refresh();
}
catch (Exception ex)
{
_vm.StatusText = Loc.F("main.browser.load_failed", ex.Message);
}
}
// --- Locate (spec 092, #581) ------------------------------------------------------------
// The arrangement and Session clip menus' Locate submenu, and the Files-tab highlight of
// the selected clip's source file.
private void InitLocate()
{
var hooks = new LocateHooks
{
Source = id => ClipFiles.Source(Engine, id),
BundleCopy = id => ClipFiles.BundleCopy(Engine, id, _projectPath),
InBrowser = path => Browser.RevealFile(path),
InFileManager = path =>
{
try { RevealInFileManager(path); }
catch (Exception ex) { if (_vm is not null) _vm.StatusText = Loc.F("main.browser.reveal_failed", ex.Message); }
},
};
Timeline.Locate = hooks;
if (_session is not null)
{
_session.Locate = hooks;
_session.SlotSelected += (t, s) => MarkLocated(SessionSource(t, s));
}
Timeline.ClipSelectionChanged += () => MarkLocated(ArrangementSource());
}
private void MarkLocated(string? path) => _vm?.Browser.SetLocatedPath(path);
// The selected arrangement clip's source file, when it is one audio clip with a known source.
private string? ArrangementSource()
=> SelectedClip(out int t, out int c, out bool midi) && !midi && Engine.TryGetAudioClipInfo(t, c, out var ai)
? ClipFiles.Source(Engine, ai.SampleId) : null;
private string? SessionSource(int trackId, int scene)
=> trackId > 0 && scene >= 0 && Engine.TryGetSessionAudioSlot(trackId, scene, out var sa)
? ClipFiles.Source(Engine, sa.SampleId) : null;
// Reveal a sample / folder / project in the OS file manager (Finder / Explorer / files).
private void OnBrowserReveal(BrowserItem item)
{
if (_vm is null || string.IsNullOrEmpty(item.Path)) return;
try { RevealInFileManager(item.Path); }
catch (Exception ex) { _vm.StatusText = Loc.F("main.browser.reveal_failed", ex.Message); }
}
/// <summary>Open a folder itself in the OS file manager (not its parent with it selected).</summary>
internal static void OpenFolderInFileManager(string dir)
{
if (OperatingSystem.IsMacOS()) Process.Start("open", new[] { dir });
else if (OperatingSystem.IsWindows()) Process.Start("explorer.exe", $"\"{dir}\"");
else Process.Start("xdg-open", new[] { dir });
}
internal static void RevealInFileManager(string path)
{
if (OperatingSystem.IsMacOS()) Process.Start("open", new[] { "-R", path });
else if (OperatingSystem.IsWindows()) Process.Start("explorer.exe", $"/select,\"{path}\"");
else Process.Start("xdg-open", new[] { System.IO.Path.GetDirectoryName(path) ?? path });
}
// Delete a project bundle: confirm, then move it to the Trash (recoverable). Falls back
// to a permanent delete on platforms without a scriptable trash.
private async void OnBrowserDeleteProject(BrowserItem item)
{
if (_vm is null) return;
bool ok = await new ConfirmWindow(Loc.T("main.browser.delete_project"),
Loc.F("main.browser.move_to_the_trash", item.Name), Loc.T("common.delete"), Loc.T("common.cancel")).ShowDialog<bool>(this);
if (!ok) return;
bool done = await Task.Run(() => MoveToTrash(item.Path));
_vm.Browser.RebuildProjects();
_vm.StatusText = done ? Loc.F("main.browser.moved_to_trash", item.Name) : Loc.F("main.browser.couldnt_delete", item.Name);
}
// Delete a saved preset (#234): confirm, then to the Trash, like a project.
private async void OnBrowserDeletePreset(BrowserItem item)
{
if (_vm is null) return;
bool ok = await new ConfirmWindow(Loc.T("main.browser.delete_preset"),
Loc.F("main.browser.move_to_the_trash", item.Name), Loc.T("common.delete"), Loc.T("common.cancel")).ShowDialog<bool>(this);
if (!ok) return;
bool done = await Task.Run(() => MoveToTrash(item.Path));
_vm.Browser.RebuildPresets();
_vm.StatusText = done ? Loc.F("main.browser.moved_to_trash", item.Name) : Loc.F("main.browser.couldnt_delete", item.Name);
}
// Open the user presets folder itself (not its parent with it selected).
private void OnBrowserOpenPresetsFolder()
{
if (_vm is null) return;
try
{
string dir = _vm.Settings.PresetsFolder();
Directory.CreateDirectory(dir); // nothing saved yet: open it empty rather than fail
OpenFolderInFileManager(dir);
}
catch (Exception ex) { _vm.StatusText = Loc.F("main.browser.reveal_failed", ex.Message); }
}
private static bool MoveToTrash(string path)
{
try
{
if (OperatingSystem.IsMacOS())
{
var psi = new ProcessStartInfo("osascript") { UseShellExecute = false };
psi.ArgumentList.Add("-e");
psi.ArgumentList.Add($"tell application \"Finder\" to delete POSIX file \"{path}\"");
Process.Start(psi)?.WaitForExit();
return !Directory.Exists(path) && !File.Exists(path);
}
// Fallback: permanent delete (Windows/Linux — no portable trash API here).
if (Directory.Exists(path)) Directory.Delete(path, true);
else if (File.Exists(path)) File.Delete(path);
return !Directory.Exists(path) && !File.Exists(path);
}
catch { return false; }
}
// Open the tag manager. item == null → manage all tags; a device item → create a tag
// already assigned to that device.
private async void OnBrowserEditTags(BrowserItem? item)
{
var lib = App.Services.GetService<IBrowserLibrary>();
if (lib is null) return;
string? key = item is not null && item.LibraryKey.Length > 0 ? item.LibraryKey : null;
await new TagEditorWindow(lib, key).ShowDialog(this);
}
private async void OnSavePreset(int deviceIndex)
{
if (_vm is null || _deviceChain is null) return;
int trackId = _deviceChain.TrackId;
if (trackId <= 0) { _vm.StatusText = Loc.T("common.select_a_track_first"); return; }
string label = deviceIndex <= PresetService.MidiEffectBase
? Engine.MidiEffectName(trackId, PresetService.MidiEffectBase - deviceIndex)
: Engine.DeviceName(trackId, deviceIndex);
if (string.IsNullOrEmpty(label)) label = Loc.T("common.instrument");
// The preset it was loaded from is the likelier name to start from (specs/048).
var (surface, index) = deviceIndex <= PresetService.MidiEffectBase ? (PresetSurface.MidiEffect, PresetService.MidiEffectBase - deviceIndex)
: deviceIndex < 0 ? (PresetSurface.Instrument, -1) : (PresetSurface.Effect, deviceIndex);
if (Nota.Application.Editing.PresetEdit.Name(Engine, trackId, surface, index) is { Length: > 0 } loaded) label = loaded;
var name = await new TextPromptWindow(Loc.T("common.save_preset"), Loc.T("main.browser.preset_name"), label).ShowDialog<string?>(this);
if (string.IsNullOrEmpty(name)) return;
try
{
if (!_presets.Save(Engine, trackId, deviceIndex, name, _vm.Settings.PresetsFolder()))
{ _vm.StatusText = Loc.T("main.browser.nothing_to_save_built_in"); return; }
// The device now holds that preset: its name, no " *".
Engine.SetDevicePresetTag(trackId, surface, index, "user:" + name, name);
_deviceChain.Refresh();
_vm.Browser.RebuildPresets();
_vm.StatusText = Loc.F("main.browser.saved_preset", name);
}
catch (Exception ex)
{
_vm.StatusText = Loc.F("main.browser.save_preset_failed", ex.Message);
}
}
// Save a rack chain's instrument (hosted plugins only) as a preset.
private async void OnSaveRackChainPreset(int chain)
{
if (_vm is null || _deviceChain is null) return;
int trackId = _deviceChain.TrackId;
if (trackId <= 0) return;
string label = Engine.RackChainInstrumentName(trackId, chain);
if (string.IsNullOrEmpty(label)) label = Loc.T("common.instrument");
var name = await new TextPromptWindow(Loc.T("common.save_preset"), Loc.T("main.browser.preset_name"), label).ShowDialog<string?>(this);
if (string.IsNullOrEmpty(name)) return;
try
{
if (!_presets.SaveRackChainInstrument(Engine, trackId, chain, name, _vm.Settings.PresetsFolder()))
{ _vm.StatusText = Loc.T("main.browser.only_plug_in_chain_instruments"); return; }
_vm.Browser.RebuildPresets();
_vm.StatusText = Loc.F("main.browser.saved_preset", name);
}
catch (Exception ex)
{
_vm.StatusText = Loc.F("main.browser.save_preset_failed", ex.Message);
}
}
// A Modular node double-clicked (or Enter) in the browser's Modular tab (specs/095): onto
// the shown track's canvas, unconnected, in the middle of the view — as the palette does.
private void AddModularNode(BrowserItem item)
{
if (_vm is null || _modular is null) return;
if (!_modular.IsVisible || !_modular.CanAddNodes) { _vm.StatusText = Loc.T("modular.open_a_track_to_add_nodes"); return; }
if (_modular.AddModulatorAt(item.BuiltinKind) < 0) { _vm.StatusText = Loc.F("main.palette.couldnt_add", item.Name); return; }
Timeline.Refresh();
_vm.StatusText = Loc.F("modular.node_added", item.Name);
}
}