瀏覽代碼

Som funcionando, sampler, Piano Roll, projetos .dawproj e teclado do PC

- Corrige o silêncio: o grafo era montado antes de ter canais de saída e
  o JUCE recusava as conexões; coberto por Daw.exe --selftest
- Sampler com cache; lê os WAV com Ogg Vorbis do FL e Ogg com extensão .wav
- Projetos .flp importados usam os samples reais da instalação do FL
- Piano Roll: criar, mover, redimensionar, apagar, snap, zoom, preview,
  ghost notes
- Channel Rack: pan/volume, seleção, menu do canal, renomear, arrastar
  arquivos de áudio
- Formato próprio .dawproj (JSON), Novo/Abrir/Salvar, atalhos
- Teclado do PC como piano (layout do FL), fila lock-free para notas ao vivo
- Exportação para WAV (--render), snapshots da UI (--snapshot), soft clip
  no master, tema escuro
Kauan 1 月之前
父節點
當前提交
6f26167fe3

+ 5 - 1
CMakeLists.txt

@@ -52,14 +52,18 @@ if(DAW_BUILD_APP)
         src/engine/AudioEngine.cpp
         src/engine/ChannelRackProcessor.cpp
         src/engine/Metronome.cpp
+        src/engine/SampleLibrary.cpp
+        src/engine/ProjectFile.cpp
         src/ui/MainComponent.cpp
-        src/ui/ChannelRackComponent.cpp)
+        src/ui/ChannelRackComponent.cpp
+        src/ui/PianoRollComponent.cpp)
 
     target_compile_definitions(Daw PRIVATE
         JUCE_WEB_BROWSER=0
         JUCE_USE_CURL=0
         JUCE_PLUGINHOST_VST3=1
         JUCE_ASIO=0                      # ligar quando o ASIO SDK estiver disponível
+        JUCE_USE_MP3AUDIOFORMAT=1
         JUCE_APPLICATION_NAME_STRING="$<TARGET_PROPERTY:Daw,JUCE_PRODUCT_NAME>"
         JUCE_APPLICATION_VERSION_STRING="$<TARGET_PROPERTY:Daw,JUCE_VERSION>")
 

+ 16 - 1
docs/ESTADO.md

@@ -3,6 +3,11 @@
 Atualizado em 2026-10-12.
 
 ## Funcionando e verificado
+- Áudio no app: o grafo estava sem conexões (os nós eram conectados antes de o grafo ter
+  canais de saída). Corrigido e coberto pelo `Daw.exe --selftest`.
+- `Daw.exe --render projeto.flp saida.wav 20` exporta um demo do FL com 17/17 samples reais.
+- `Daw.exe --snapshot prefixo projeto.flp` desenha a UI fora da tela em PNG: é assim que
+  confiro a interface sem mexer na tela do usuário.
 - `Daw.exe` compila de forma cruzada do WSL com Zig 0.14.1 + JUCE 8.0.4, abre no Windows 11
   e mostra o Channel Rack (verificado por captura de tela da janela).
 - Testes do núcleo: 75 mil verificações passando, incluindo leitura dos 165 `.flp` instalados
@@ -25,5 +30,15 @@ Confirmadas empiricamente nos demos:
 - Nome de canal: 0xCB; arquivos ≤ 11 usam 0xC0. Nome interno do plugin: 0xC9.
 - A string de versão (0xC7) é sempre ASCII; os outros textos são UTF-16LE a partir da 11.5.4.
 
+## Descobertas sobre os samples do FL
+- Muitos samples de fábrica são WAV com format tag 0x674F/0x6750 e um stream Ogg Vorbis no
+  chunk `data`; outros são arquivos Ogg puros com extensão `.wav`. `SampleLibrary` trata os dois.
+- Caminhos usam `%FLStudioFactoryData%` (= pasta de instalação), `%FLStudioData%`
+  (= instalação\Data) e `%FLStudioUserData%` (= Documentos\Image-Line\FL Studio).
+
+## Ainda não verificado por um humano
+- Ouvir o app tocando (o autoteste prova que o grafo gera áudio; falta confirmar na placa do usuário).
+- Interações de mouse/teclado (arrastar notas, knobs, teclado do PC): conferidas só por leitura do código.
+
 ## Próximo passo
-Fase 2 do roadmap: sampler (para os projetos importados soarem com os samples reais) e Piano Roll.
+Fase 3: Playlist (arranjo) com importação da playlist do `.flp`, depois mixer.

+ 9 - 4
docs/ROADMAP.md

@@ -13,11 +13,16 @@ Ordem pensada para ter algo usável o quanto antes e nunca quebrar a regra do mo
 - [x] Build Windows sem Visual Studio (Zig) e testes do núcleo
 
 ## Fase 2: compor de verdade
-- [ ] Sampler: carregar `.wav`/`.flac`/`.mp3` por canal (usa o `samplePath` do `.flp` quando existir)
-- [ ] Piano Roll (editar notas com duração, velocity, arrastar, quantizar)
-- [ ] Salvar/abrir projeto no formato próprio (JSON versionado + blobs)
-- [ ] Volume, pan e mute/solo por canal na UI; teclado do PC como teclado MIDI
+- [x] Sampler: `.wav`/`.flac`/`.ogg`/`.mp3`/`.aiff` por canal, inclusive os WAV-com-Ogg do FL
+- [x] Projetos `.flp` importados tocam com os samples reais da instalação do FL
+- [x] Piano Roll (criar, mover, redimensionar, apagar, snap, zoom, preview, ghost notes)
+- [x] Salvar/abrir projeto no formato próprio (`.dawproj`, JSON versionado)
+- [x] Volume, pan e mute por canal; teclado do PC como teclado musical
+- [x] Exportar para WAV (`Daw.exe --render`)
+- [ ] Velocity no Piano Roll, seleção múltipla, copiar/colar, desfazer/refazer
+- [ ] Solo por canal, renomear/colorir patterns
 - [ ] Entrada MIDI e gravação de notas
+- [ ] Exportar pela interface (hoje só pela linha de comando)
 
 ## Fase 3: arranjo
 - [ ] Playlist: clips de pattern no tempo, trilhas, loop region

+ 3 - 1
scripts/build-windows-zig.sh

@@ -29,6 +29,7 @@ MODULES=(juce_core juce_data_structures juce_events juce_graphics juce_gui_basic
     echo '#define JUCE_USE_WINDOWS_MEDIA_FORMAT 0'
     echo '#define JUCE_PLUGINHOST_VST3 0'
     echo '#define JUCE_ASIO 0'
+    echo '#define JUCE_USE_MP3AUDIOFORMAT 1'
     echo '#define JUCE_APPLICATION_NAME_STRING "Daw"'
     echo '#define JUCE_APPLICATION_VERSION_STRING "0.1.0"'
     for m in "${MODULES[@]}"; do echo "#define JUCE_MODULE_AVAILABLE_$m 1"; done
@@ -67,7 +68,8 @@ fi
 
 APP_SOURCES=(src/Main.cpp
              src/engine/AudioEngine.cpp src/engine/ChannelRackProcessor.cpp src/engine/Metronome.cpp
-             src/ui/MainComponent.cpp src/ui/ChannelRackComponent.cpp
+             src/engine/SampleLibrary.cpp src/engine/ProjectFile.cpp
+             src/ui/MainComponent.cpp src/ui/ChannelRackComponent.cpp src/ui/PianoRollComponent.cpp
              src/core/Song.cpp src/core/Scheduler.cpp src/core/Instruments.cpp src/core/RackRenderer.cpp
              src/core/FlpImport.cpp src/flp/Flp.cpp
              src/platform/MingwFixes.cpp)

+ 163 - 6
src/Main.cpp

@@ -1,7 +1,10 @@
 #include <juce_gui_basics/juce_gui_basics.h>
 
 #include "engine/AudioEngine.h"
+#include "engine/ProjectFile.h"
+#include "engine/Text.h"
 #include "ui/MainComponent.h"
+#include "ui/Theme.h"
 
 class DawApplication final : public juce::JUCEApplication
 {
@@ -10,43 +13,197 @@ public:
     const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
     bool moreThanOneInstanceAllowed() override { return false; }
 
-    void initialise (const juce::String&) override
+    void initialise (const juce::String& commandLine) override
     {
+        const auto args = juce::StringArray::fromTokens (commandLine, true);
+
+        if (args.contains ("--selftest"))
+        {
+            runSelfTest (args[args.indexOf ("--selftest") + 1].unquoted());
+            return;
+        }
+
+        if (args.contains ("--snapshot"))
+        {
+            const auto i = args.indexOf ("--snapshot");
+            runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
+            return;
+        }
+
+        if (args.contains ("--render"))
+        {
+            const auto i = args.indexOf ("--render");
+            runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
+            return;
+        }
+
+        juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
         engine = std::make_unique<daw::AudioEngine>();
         mainWindow = std::make_unique<MainWindow> (getApplicationName(), *engine);
+
+        // Duplo clique num .dawproj/.flp abre a DAW com o arquivo como argumento.
+        if (args.size() > 0 && juce::File::isAbsolutePath (args[0].unquoted()))
+            mainWindow->openFile (juce::File (args[0].unquoted()));
     }
 
     void shutdown() override
     {
         mainWindow = nullptr; // a UI sai antes do engine
         engine = nullptr;
+        juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
     }
 
     void systemRequestedQuit() override { quit(); }
 
 private:
+    // Daw.exe --selftest relatorio.txt: renderiza 2 s sem placa de som e grava o resultado.
+    // Código de saída 0 = saiu áudio, 1 = silêncio.
+    void runSelfTest (const juce::String& reportPath)
+    {
+        daw::AudioEngine offline (false);
+        const auto peak = offline.renderOffline (2.0, 48000.0);
+        const auto audioOk = peak > 0.01f && peak < 10.0f;
+
+        // ida e volta do formato de projeto, com acentos no nome
+        auto original = daw::Song::makeDefault();
+        original.channels[0].name = "Bumbo ação";
+        juce::String error;
+        const auto reloaded = daw::ProjectFile::fromJson (daw::ProjectFile::toJson (original), error);
+        const auto projectOk = reloaded && reloaded->channels.size() == original.channels.size()
+                               && reloaded->channels[0].name == original.channels[0].name
+                               && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
+                               && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start;
+        const auto ok = audioOk && projectOk;
+
+        juce::String report;
+        report << "conexoes=" << offline.getNumGraphConnections() << "\n"
+               << "pico=" << peak << "\n"
+               << "projeto=" << (projectOk ? "OK" : "ERRO " + error) << "\n"
+               << "resultado=" << (ok ? "OK" : "FALHOU") << "\n";
+
+        if (reportPath.isNotEmpty())
+            juce::File (reportPath).replaceWithText (report);
+
+        setApplicationReturnValue (ok ? 0 : 1);
+        quit();
+    }
+
+    // Daw.exe --render projeto.(flp|dawproj) saida.wav [segundos]
+    // Exporta a pattern atual para WAV 24 bits (num .flp importado, a que tem mais notas).
+    void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
+    {
+        daw::AudioEngine offline (false);
+        const juce::File input (inputPath);
+        juce::String error, report;
+        bool ok = false;
+
+        if (input.hasFileExtension ("flp"))
+            ok = offline.importFlpFile (input, error);
+        else if (auto song = daw::ProjectFile::load (input, error))
+        {
+            offline.setSong (std::move (*song));
+            ok = true;
+        }
+
+        int samplers = 0, samplersLoaded = 0;
+
+        if (ok)
+        {
+            for (const auto& c : offline.getSong().channels)
+                if (c.instrument == daw::InstrumentKind::sampler)
+                {
+                    ++samplers;
+                    samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
+                }
+
+            const juce::File output (outputPath);
+            output.deleteFile();
+            juce::WavAudioFormat wav;
+            std::unique_ptr<juce::AudioFormatWriter> writer (
+                wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
+
+            if (writer == nullptr)
+            {
+                ok = false;
+                error = daw::utf8 ("não foi possível criar ") + outputPath;
+            }
+            else
+            {
+                const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
+                report << "pico=" << peak << "\n";
+                ok = peak > 0.001f;
+            }
+        }
+
+        report << "samplers=" << samplersLoaded << "/" << samplers << "\n"
+               << "resultado=" << (ok ? "OK" : "ERRO " + error) << "\n";
+        juce::File (outputPath + ".txt").replaceWithText (report);
+
+        setApplicationReturnValue (ok ? 0 : 1);
+        quit();
+    }
+
+    // Daw.exe --snapshot prefixo [projeto]: desenha a janela fora da tela e grava
+    // prefixo-rack.png e prefixo-pianoroll.png (usado para conferir a UI sem mexer na tela).
+    void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
+    {
+        juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
+        {
+            daw::AudioEngine offline (false);
+            daw::MainComponent ui (offline);
+            ui.setSize (1280, 720);
+
+            if (projectPath.isNotEmpty())
+                ui.openFile (juce::File (projectPath));
+
+            offline.dispatchPendingMessages(); // as notificações de mudança são assíncronas
+
+            ui.selectTabForSnapshot (0);
+            saveSnapshot (ui, prefix + "-rack.png");
+            ui.selectTabForSnapshot (1);
+            saveSnapshot (ui, prefix + "-pianoroll.png");
+        }
+        juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
+        quit();
+    }
+
+    static void saveSnapshot (juce::Component& c, const juce::String& path)
+    {
+        const juce::File file (path);
+        file.deleteFile();
+        juce::PNGImageFormat png;
+
+        if (auto out = file.createOutputStream())
+            png.writeImageToStream (c.createComponentSnapshot (c.getLocalBounds()), *out);
+    }
+
     class MainWindow final : public juce::DocumentWindow
     {
     public:
         MainWindow (const juce::String& name, daw::AudioEngine& engine)
-            : DocumentWindow (name,
-                              juce::Desktop::getInstance().getDefaultLookAndFeel()
-                                  .findColour (juce::ResizableWindow::backgroundColourId),
-                              DocumentWindow::allButtons)
+            : DocumentWindow (name, daw::theme::window, DocumentWindow::allButtons)
         {
             setUsingNativeTitleBar (true);
-            setContentOwned (new daw::MainComponent (engine), true);
+            content = new daw::MainComponent (engine);
+            setContentOwned (content, true);
             setResizable (true, true);
+            setResizeLimits (800, 400, 10000, 10000);
             centreWithSize (getWidth(), getHeight());
             setVisible (true);
+            content->grabKeyboardFocus();
         }
 
+        void openFile (const juce::File& file) { content->openFile (file); }
+
         void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
 
     private:
+        daw::MainComponent* content = nullptr; // pertence à janela
+
         JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
     };
 
+    daw::theme::LookAndFeel lookAndFeel;
     std::unique_ptr<daw::AudioEngine> engine;
     std::unique_ptr<MainWindow> mainWindow;
 };

+ 37 - 1
src/core/FlpImport.cpp

@@ -40,7 +40,26 @@ InstrumentKind guessInstrument (const std::string& channelName, flp::ChannelType
     return InstrumentKind::synth;
 }
 
-Song importFlp (const flp::Project& project)
+std::string resolveFlPath (const std::string& flPath, const FlPathRoots& roots)
+{
+    const std::pair<const char*, const std::string*> variables[] = {
+        { "%FLStudioFactoryData%", &roots.factoryData },
+        { "%FLStudioUserData%", &roots.userData },
+        { "%FLStudioData%", &roots.data },
+    };
+
+    for (const auto& [name, root] : variables)
+    {
+        const std::string variable (name);
+
+        if (flPath.compare (0, variable.size(), variable) == 0)
+            return root->empty() ? std::string() : *root + flPath.substr (variable.size());
+    }
+
+    return flPath;
+}
+
+Song importFlp (const flp::Project& project, const FlpImportOptions& options)
 {
     Song song;
     song.bpm = project.tempo > 0.0 ? project.tempo : 140.0;
@@ -59,6 +78,18 @@ Song importFlp (const flp::Project& project)
         ChannelDef def;
         def.name = c.name.empty() ? "Canal " + std::to_string (c.index + 1) : c.name;
         def.instrument = guessInstrument (def.name, c.type);
+
+        if (c.type == flp::ChannelType::sampler && ! c.samplePath.empty() && options.fileExists)
+        {
+            const auto path = resolveFlPath (c.samplePath, options.roots);
+
+            if (! path.empty() && options.fileExists (path))
+            {
+                def.instrument = InstrumentKind::sampler;
+                def.samplePath = path;
+            }
+        }
+
         song.channels.push_back (std::move (def));
     }
 
@@ -96,6 +127,11 @@ Song importFlp (const flp::Project& project)
     if (song.patterns.empty())
         song.patterns.emplace_back().name = "Pattern 1";
 
+    // O .flp não diz qual pattern estava aberta; a mais cheia é o melhor ponto de partida.
+    for (int i = 0; i < (int) song.patterns.size(); ++i)
+        if (song.patterns[(std::size_t) i].notes.size() > song.patterns[(std::size_t) song.currentPattern].notes.size())
+            song.currentPattern = i;
+
     return song;
 }
 } // namespace daw

+ 23 - 4
src/core/FlpImport.h

@@ -1,14 +1,33 @@
 #pragma once
 
+#include <functional>
+#include <string>
+
 #include "core/Song.h"
 #include "flp/Flp.h"
 
 namespace daw
 {
-// Converte um projeto do FL Studio para o nosso modelo: canais viram canais
-// com instrumento interno escolhido pelo nome/tipo, patterns são reescaladas
-// para o nosso PPQ. Plugins e samples ainda não são carregados.
-Song importFlp (const flp::Project& project);
+// Pastas para onde apontam as variáveis que o FL grava nos caminhos de sample.
+struct FlPathRoots
+{
+    std::string factoryData; // %FLStudioFactoryData%  ex.: C:\Program Files\Image-Line\FL Studio 2026
+    std::string data;        // %FLStudioData%         ex.: ...\FL Studio 2026\Data
+    std::string userData;    // %FLStudioUserData%     ex.: Documentos\Image-Line\FL Studio
+};
+
+std::string resolveFlPath (const std::string& flPath, const FlPathRoots& roots);
+
+struct FlpImportOptions
+{
+    FlPathRoots roots;
+    std::function<bool (const std::string& path)> fileExists; // sem isto, nenhum sample é usado
+};
+
+// Converte um projeto do FL Studio para o nosso modelo. Canais sampler cujo
+// arquivo existe viram samplers; os demais usam um instrumento interno escolhido
+// pelo nome. Patterns são reescaladas para o nosso PPQ. Plugins ainda não.
+Song importFlp (const flp::Project& project, const FlpImportOptions& options = {});
 
 InstrumentKind guessInstrument (const std::string& channelName, flp::ChannelType type);
 } // namespace daw

+ 116 - 1
src/core/Instruments.cpp

@@ -142,6 +142,7 @@ private:
             }
 
             case InstrumentKind::synth:
+            case InstrumentKind::sampler:
                 break;
         }
 
@@ -278,10 +279,124 @@ private:
     float filterCoeff = 0.3f;
     std::array<SynthVoice, 16> voices {};
 };
+// ---------------------------------------------------------------------------
+// Sampler: toca o sample inteiro a cada nota (one-shot, como um step do FL),
+// transposto pela tecla (60 = altura original), com interpolação linear.
+
+struct SamplerVoice
+{
+    bool active = false;
+    double position = 0.0;
+    double rate = 1.0;
+    float velocity = 0.0f;
+    float fade = 1.0f;     // < 1 quando a voz foi roubada (declick)
+    bool stolen = false;
+    int age = 0;
+};
+
+class SamplerInstrument final : public Instrument
+{
+public:
+    explicit SamplerInstrument (std::shared_ptr<const SampleData> s) : sample (std::move (s)) {}
+
+    void prepare (double sr) noexcept override
+    {
+        sampleRate = sr;
+        fadeStep = (float) (1.0 / (0.003 * sr)); // 3 ms
+        allNotesOff();
+    }
+
+    void noteOn (int key, float velocity) noexcept override
+    {
+        if (sample == nullptr || sample->frames() < 2)
+            return;
+
+        SamplerVoice* target = nullptr;
+
+        for (auto& v : voices)
+            if (! v.active)
+            {
+                target = &v;
+                break;
+            }
+
+        if (target == nullptr)
+        {
+            // Sem voz livre: rouba a mais antiga.
+            target = &voices[0];
+            for (auto& v : voices)
+                if (v.age > target->age)
+                    target = &v;
+        }
+
+        *target = {};
+        target->active = true;
+        target->velocity = velocity;
+        target->rate = sample->sampleRate / sampleRate * std::pow (2.0, (key - 60) / 12.0);
+    }
+
+    void noteOff (int) noexcept override {}
+
+    void allNotesOff() noexcept override
+    {
+        for (auto& v : voices)
+            if (v.active)
+                v.stolen = true; // some com fade em vez de cortar seco
+    }
+
+    void render (float* left, float* right, int n, float gl, float gr) noexcept override
+    {
+        if (sample == nullptr)
+            return;
+
+        const auto& l = sample->left;
+        const auto& r = sample->right.empty() ? sample->left : sample->right;
+        const auto last = (double) (sample->frames() - 1);
+
+        for (auto& v : voices)
+        {
+            if (! v.active)
+                continue;
+
+            for (int i = 0; i < n; ++i)
+            {
+                if (v.position >= last || (v.stolen && v.fade <= 0.0f))
+                {
+                    v.active = false;
+                    break;
+                }
+
+                const auto index = (std::size_t) v.position;
+                const auto frac = (float) (v.position - (double) index);
+                const auto sl = l[index] + frac * (l[index + 1] - l[index]);
+                const auto sr = r[index] + frac * (r[index + 1] - r[index]);
+                const auto gain = v.velocity * v.fade;
+
+                left[i] += sl * gain * gl;
+                right[i] += sr * gain * gr;
+
+                v.position += v.rate;
+                ++v.age;
+
+                if (v.stolen)
+                    v.fade -= fadeStep;
+            }
+        }
+    }
+
+private:
+    std::shared_ptr<const SampleData> sample;
+    double sampleRate = 44100.0;
+    float fadeStep = 0.01f;
+    std::array<SamplerVoice, 16> voices {};
+};
 } // namespace
 
-std::unique_ptr<Instrument> makeInstrument (InstrumentKind kind)
+std::unique_ptr<Instrument> makeInstrument (InstrumentKind kind, std::shared_ptr<const SampleData> sample)
 {
+    if (kind == InstrumentKind::sampler)
+        return std::make_unique<SamplerInstrument> (std::move (sample));
+
     if (kind == InstrumentKind::synth)
         return std::make_unique<SynthInstrument>();
 

+ 14 - 3
src/core/Instruments.h

@@ -1,12 +1,13 @@
 #pragma once
 
-// Instrumentos internos sintetizados (sem samples). Servem para a DAW fazer som
-// antes de existir hosting de plugins e para tocar projetos importados.
+// Instrumentos internos: bateria e synth sintetizados, e um sampler. Servem para a
+// DAW fazer som antes de existir hosting de plugins e para tocar projetos importados.
 // Tudo com capacidade fixa: noteOn/render nunca alocam.
 
 #include <array>
 #include <cstdint>
 #include <memory>
+#include <vector>
 
 #include "core/Song.h"
 
@@ -26,7 +27,17 @@ public:
     virtual void render (float* left, float* right, int n, float gainLeft, float gainRight) noexcept = 0;
 };
 
-std::unique_ptr<Instrument> makeInstrument (InstrumentKind kind);
+// Áudio de um sample já decodificado (carregado fora da thread de áudio).
+struct SampleData
+{
+    std::vector<float> left, right; // right vazio = mono
+    double sampleRate = 44100.0;
+
+    std::size_t frames() const noexcept { return left.size(); }
+};
+
+// `sample` só é usado pelo sampler; sem sample o sampler fica mudo.
+std::unique_ptr<Instrument> makeInstrument (InstrumentKind kind, std::shared_ptr<const SampleData> sample = nullptr);
 
 // Ruído branco barato e determinístico (xorshift), igual em toda plataforma.
 struct Noise

+ 51 - 0
src/core/LiveEventQueue.h

@@ -0,0 +1,51 @@
+#pragma once
+
+// Fila lock-free de uma thread produtora (UI) para uma consumidora (áudio),
+// para notas tocadas ao vivo: teclado do PC, preview do Piano Roll, MIDI.
+
+#include <array>
+#include <atomic>
+#include <cstddef>
+
+#include "core/Scheduler.h"
+
+namespace daw
+{
+class LiveEventQueue
+{
+public:
+    static constexpr std::size_t capacity = 256; // potência de 2
+
+    // UI. Retorna false se a fila estiver cheia (o evento é descartado).
+    bool push (const NoteEvent& e) noexcept
+    {
+        const auto w = writeIndex.load (std::memory_order_relaxed);
+        const auto next = (w + 1) & (capacity - 1);
+
+        if (next == readIndex.load (std::memory_order_acquire))
+            return false;
+
+        events[w] = e;
+        writeIndex.store (next, std::memory_order_release);
+        return true;
+    }
+
+    // Áudio.
+    bool pop (NoteEvent& out) noexcept
+    {
+        const auto r = readIndex.load (std::memory_order_relaxed);
+
+        if (r == writeIndex.load (std::memory_order_acquire))
+            return false;
+
+        out = events[r];
+        readIndex.store ((r + 1) & (capacity - 1), std::memory_order_release);
+        return true;
+    }
+
+private:
+    std::array<NoteEvent, capacity> events {};
+    std::atomic<std::size_t> writeIndex { 0 };
+    std::atomic<std::size_t> readIndex { 0 };
+};
+} // namespace daw

+ 41 - 5
src/core/RackRenderer.cpp

@@ -6,28 +6,39 @@
 
 namespace daw
 {
-std::unique_ptr<const RackState> RackState::build (Song song, const RackState* previous, double sampleRate)
+std::unique_ptr<const RackState> RackState::build (Song song,
+                                                   const RackState* previous,
+                                                   double sampleRate,
+                                                   const SampleProvider& samples)
 {
     auto state = std::make_unique<RackState>();
     state->instruments.reserve (song.channels.size());
 
     for (std::size_t i = 0; i < song.channels.size(); ++i)
     {
-        const auto kind = song.channels[i].instrument;
+        const auto& channel = song.channels[i];
+        const auto kind = channel.instrument;
 
         if (previous != nullptr && i < previous->song.channels.size() && i < previous->instruments.size()
-            && previous->song.channels[i].instrument == kind)
+            && previous->song.channels[i].instrument == kind
+            && (kind != InstrumentKind::sampler || previous->song.channels[i].samplePath == channel.samplePath))
         {
             state->instruments.push_back (previous->instruments[i]);
             continue;
         }
 
-        std::shared_ptr<Instrument> instrument = makeInstrument (kind);
+        std::shared_ptr<const SampleData> sample;
+
+        if (kind == InstrumentKind::sampler && samples && ! channel.samplePath.empty())
+            sample = samples (channel.samplePath);
+
+        std::shared_ptr<Instrument> instrument = makeInstrument (kind, std::move (sample));
         instrument->prepare (sampleRate);
         state->instruments.push_back (std::move (instrument));
     }
 
     state->song = std::move (song);
+    state->sampleRate = sampleRate;
     return state;
 }
 
@@ -59,7 +70,8 @@ void RackRenderer::process (const RackState* state,
                             double startTick,
                             int numSamples,
                             float* left,
-                            float* right) noexcept
+                            float* right,
+                            LiveEventQueue* live) noexcept
 {
     std::memset (left, 0, sizeof (float) * (std::size_t) numSamples);
     std::memset (right, 0, sizeof (float) * (std::size_t) numSamples);
@@ -68,6 +80,12 @@ void RackRenderer::process (const RackState* state,
     if (state == nullptr)
         return;
 
+    // Um snapshot montado antes de o dispositivo abrir pode ter outra taxa. prepare()
+    // não aloca, então pode rodar aqui.
+    if (state != lastState && state->sampleRate != sampleRate)
+        for (auto& instrument : state->instruments)
+            instrument->prepare (sampleRate);
+
     lastState = state; // para prepare() saber quais instrumentos reconfigurar
 
     if (wasPlaying && ! playing)
@@ -76,6 +94,24 @@ void RackRenderer::process (const RackState* state,
 
     wasPlaying = playing;
 
+    if (live != nullptr)
+    {
+        NoteEvent e;
+
+        while (live->pop (e))
+        {
+            if (e.channel < 0 || e.channel >= (int) state->instruments.size())
+                continue;
+
+            auto& instrument = *state->instruments[(std::size_t) e.channel];
+
+            if (e.type == NoteEvent::Type::on)
+                instrument.noteOn (e.key, e.velocity);
+            else
+                instrument.noteOff (e.key);
+        }
+    }
+
     const auto& song = state->song;
 
     if (playing && ! song.patterns.empty())

+ 16 - 4
src/core/RackRenderer.h

@@ -3,10 +3,13 @@
 // Junta Song + instrumentos + scheduler: dado o estado do transporte, gera o
 // áudio estéreo de um bloco com as notas disparadas no sample exato.
 
+#include <functional>
 #include <memory>
+#include <string>
 #include <vector>
 
 #include "core/Instruments.h"
+#include "core/LiveEventQueue.h"
 #include "core/Scheduler.h"
 #include "core/Song.h"
 
@@ -18,10 +21,17 @@ struct RackState
 {
     Song song;
     std::vector<std::shared_ptr<Instrument>> instruments; // um por canal
+    double sampleRate = 44100.0; // taxa com que os instrumentos novos foram preparados
+
+    // Carrega (ou pega do cache) o áudio de um arquivo; nullptr se não conseguir.
+    using SampleProvider = std::function<std::shared_ptr<const SampleData> (const std::string& path)>;
 
     // Monta o próximo estado reaproveitando os instrumentos de `previous` quando o
-    // tipo do canal não mudou. Roda na thread da UI (aloca).
-    static std::unique_ptr<const RackState> build (Song song, const RackState* previous, double sampleRate);
+    // canal não mudou de instrumento nem de sample. Roda na thread da UI (aloca).
+    static std::unique_ptr<const RackState> build (Song song,
+                                                   const RackState* previous,
+                                                   double sampleRate,
+                                                   const SampleProvider& samples = {});
 };
 
 class RackRenderer
@@ -29,13 +39,15 @@ class RackRenderer
 public:
     void prepare (double sampleRate) noexcept;
 
-    // Thread de áudio. left/right são sobrescritos.
+    // Thread de áudio. left/right são sobrescritos. `live` (opcional) traz notas
+    // tocadas ao vivo, aplicadas no início do bloco.
     void process (const RackState* state,
                   bool playing,
                   double startTick,
                   int numSamples,
                   float* left,
-                  float* right) noexcept;
+                  float* right,
+                  LiveEventQueue* live = nullptr) noexcept;
 
     // Eventos do último bloco (para testes e diagnóstico).
     const EventBuffer& lastEvents() const noexcept { return events; }

+ 23 - 0
src/core/SoftClip.h

@@ -0,0 +1,23 @@
+#pragma once
+
+#include <cmath>
+
+namespace daw
+{
+// Proteção do master até existir um limiter de verdade no mixer: linear até 0,9 e
+// depois uma curva suave que nunca passa de 1,0 (evita a distorção dura do clipping).
+inline void softClip (float* samples, int n) noexcept
+{
+    constexpr float knee = 0.9f;
+    constexpr float headroom = 1.0f - knee;
+
+    for (int i = 0; i < n; ++i)
+    {
+        const auto x = samples[i];
+        const auto a = std::abs (x);
+
+        if (a > knee)
+            samples[i] = std::copysign (knee + headroom * std::tanh ((a - knee) / headroom), x);
+    }
+}
+} // namespace daw

+ 5 - 5
src/core/Song.cpp

@@ -53,11 +53,11 @@ Song Song::makeDefault()
 {
     Song song;
     song.channels = {
-        { "Kick", InstrumentKind::kick, 0.9f, 0.0f, false },
-        { "Clap", InstrumentKind::clap, 0.7f, 0.0f, false },
-        { "Hat", InstrumentKind::hat, 0.5f, 0.1f, false },
-        { "Snare", InstrumentKind::snare, 0.7f, 0.0f, false },
-        { "Synth", InstrumentKind::synth, 0.5f, 0.0f, false },
+        { "Kick", InstrumentKind::kick, 0.9f, 0.0f, false, {} },
+        { "Clap", InstrumentKind::clap, 0.7f, 0.0f, false, {} },
+        { "Hat", InstrumentKind::hat, 0.5f, 0.1f, false, {} },
+        { "Snare", InstrumentKind::snare, 0.7f, 0.0f, false, {} },
+        { "Synth", InstrumentKind::synth, 0.5f, 0.0f, false, {} },
     };
 
     auto& p = song.patterns.emplace_back();

+ 3 - 1
src/core/Song.h

@@ -20,7 +20,8 @@ enum class InstrumentKind : std::uint8_t
     snare,
     hat,
     clap,
-    synth
+    synth,
+    sampler
 };
 
 struct ChannelDef
@@ -30,6 +31,7 @@ struct ChannelDef
     float volume = 0.8f;   // 0..1
     float pan = 0.0f;      // -1..1
     bool muted = false;
+    std::string samplePath; // usado quando instrument == sampler
 };
 
 struct Note

+ 141 - 7
src/engine/AudioEngine.cpp

@@ -1,22 +1,59 @@
 #include "engine/AudioEngine.h"
 
+#include "engine/Text.h"
+
+#include "core/FlpImport.h"
+#include "core/SoftClip.h"
 #include "engine/ChannelRackProcessor.h"
 #include "engine/Metronome.h"
+#include "flp/Flp.h"
 
 namespace daw
 {
 using IONode = juce::AudioProcessorGraph::AudioGraphIOProcessor;
 
-AudioEngine::AudioEngine()
+namespace
+{
+// Procura a instalação mais recente do FL Studio para resolver %FLStudio...%.
+FlPathRoots findFlStudioRoots()
+{
+    FlPathRoots roots;
+    const auto imageLine = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory).getChildFile ("Image-Line");
+    juce::File best;
+
+    for (const auto& dir : imageLine.findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
+        if (dir.getChildFile ("Data").isDirectory() && dir.getFileName() > best.getFileName())
+            best = dir;
+
+    if (best.exists())
+    {
+        roots.factoryData = best.getFullPathName().toStdString();
+        roots.data = best.getChildFile ("Data").getFullPathName().toStdString();
+    }
+
+    const auto user = juce::File::getSpecialLocation (juce::File::userDocumentsDirectory).getChildFile ("Image-Line/FL Studio");
+
+    if (user.isDirectory())
+        roots.userData = user.getFullPathName().toStdString();
+
+    return roots;
+}
+} // namespace
+
+AudioEngine::AudioEngine (bool openAudioDevice)
     : song (Song::makeDefault())
 {
     publishSong();
     buildInitialGraph();
-    player.setProcessor (&graph);
 
-    // 0 entradas, 2 saídas, sem estado salvo ainda, usa o dispositivo padrão.
-    deviceManager.initialise (0, 2, nullptr, true);
-    deviceManager.addAudioCallback (this);
+    if (openAudioDevice)
+    {
+        player.setProcessor (&graph);
+
+        // 0 entradas, 2 saídas, sem estado salvo ainda, usa o dispositivo padrão.
+        deviceManager.initialise (0, 2, nullptr, true);
+        deviceManager.addAudioCallback (this);
+    }
 
     startTimerHz (10); // coleta de snapshots aposentados
 }
@@ -31,8 +68,12 @@ AudioEngine::~AudioEngine()
 
 void AudioEngine::buildInitialGraph()
 {
+    // O nó de saída herda o número de canais do grafo no momento em que é criado.
+    // Sem isto o grafo ainda tem 0 saídas e o JUCE recusa as conexões em silêncio.
+    graph.setPlayConfigDetails (0, 2, transport.sampleRate.load(), 512);
+
     auto output = graph.addNode (std::make_unique<IONode> (IONode::audioOutputNode));
-    auto rack = graph.addNode (std::make_unique<ChannelRackProcessor> (transport, rackExchange));
+    auto rack = graph.addNode (std::make_unique<ChannelRackProcessor> (transport, rackExchange, liveEvents));
     auto metronome = graph.addNode (std::make_unique<Metronome> (transport));
 
     for (int channel = 0; channel < 2; ++channel)
@@ -40,15 +81,61 @@ void AudioEngine::buildInitialGraph()
         graph.addConnection ({ { rack->nodeID, channel }, { output->nodeID, channel } });
         graph.addConnection ({ { metronome->nodeID, channel }, { output->nodeID, channel } });
     }
+
+    jassert (graph.getConnections().size() == 4);
+}
+
+float AudioEngine::renderOffline (double seconds, double sampleRate, juce::AudioFormatWriter* output)
+{
+    constexpr int blockSize = 512;
+    transport.sampleRate.store (sampleRate);
+    graph.setPlayConfigDetails (0, 2, sampleRate, blockSize);
+    graph.prepareToPlay (sampleRate, blockSize);
+    play();
+
+    juce::AudioBuffer<float> buffer (2, blockSize);
+    juce::MidiBuffer midi;
+    float peak = 0.0f;
+
+    for (int done = 0; done < (int) (seconds * sampleRate); done += blockSize)
+    {
+        buffer.clear();
+        graph.processBlock (buffer, midi);
+
+        for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
+            softClip (buffer.getWritePointer (ch), blockSize);
+
+        peak = juce::jmax (peak, buffer.getMagnitude (0, blockSize));
+
+        if (output != nullptr)
+            output->writeFromAudioSampleBuffer (buffer, 0, blockSize);
+
+        transport.positionTicks.store (transport.positionTicks.load() + blockSize * transport.ticksPerSample());
+    }
+
+    stop();
+    graph.releaseResources();
+    return peak;
 }
 
 void AudioEngine::play() noexcept { transport.playing.store (true); }
 void AudioEngine::stop() noexcept { transport.playing.store (false); }
 void AudioEngine::rewind() noexcept { transport.rewindRequested.store (true); }
 
+void AudioEngine::sendLiveNote (int channel, int key, float velocity, bool on)
+{
+    NoteEvent e;
+    e.type = on ? NoteEvent::Type::on : NoteEvent::Type::off;
+    e.channel = channel;
+    e.key = key;
+    e.velocity = velocity;
+    liveEvents.push (e);
+}
+
 void AudioEngine::setSong (Song newSong)
 {
     song = std::move (newSong);
+    selectedChannel = 0;
     publishSong();
 }
 
@@ -58,13 +145,56 @@ void AudioEngine::editSong (const std::function<void (Song&)>& edit)
     publishSong();
 }
 
+void AudioEngine::setSelectedChannel (int channel)
+{
+    channel = juce::jlimit (0, juce::jmax (0, (int) song.channels.size() - 1), channel);
+
+    if (channel != selectedChannel)
+    {
+        selectedChannel = channel;
+        sendChangeMessage();
+    }
+}
+
+bool AudioEngine::importFlpFile (const juce::File& file, juce::String& error)
+{
+    juce::MemoryBlock data;
+
+    if (! file.loadFileAsData (data))
+    {
+        error = utf8 ("não foi possível ler o arquivo");
+        return false;
+    }
+
+    try
+    {
+        const auto project = flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() });
+
+        FlpImportOptions options;
+        options.roots = findFlStudioRoots();
+        options.fileExists = [] (const std::string& path) { return juce::File (juce::String::fromUTF8 (path.c_str())).existsAsFile(); };
+
+        stop();
+        rewind();
+        setSong (importFlp (project, options));
+        return true;
+    }
+    catch (const flp::Error& e)
+    {
+        error = juce::String::fromUTF8 (e.what());
+        return false;
+    }
+}
+
 void AudioEngine::publishSong()
 {
     song.currentPattern = juce::jlimit (0, juce::jmax (0, (int) song.patterns.size() - 1), song.currentPattern);
+    selectedChannel = juce::jlimit (0, juce::jmax (0, (int) song.channels.size() - 1), selectedChannel);
     transport.bpm.store (song.bpm);
     transport.beatsPerBar.store (song.beatsPerBar);
 
-    auto state = RackState::build (song, &lastPublishedShape, transport.sampleRate.load());
+    auto state = RackState::build (song, &lastPublishedShape, transport.sampleRate.load(),
+                                   [this] (const std::string& path) { return samples.load (juce::String::fromUTF8 (path.c_str())); });
 
     lastPublishedShape.song.channels = song.channels;
     lastPublishedShape.instruments = state->instruments;
@@ -92,6 +222,10 @@ void AudioEngine::audioDeviceIOCallbackWithContext (const float* const* inputCha
                                              outputChannelData, numOutputChannels,
                                              numSamples, context);
 
+    for (int ch = 0; ch < numOutputChannels; ++ch)
+        if (outputChannelData[ch] != nullptr)
+            softClip (outputChannelData[ch], numSamples);
+
     if (transport.playing.load (std::memory_order_relaxed))
         transport.positionTicks.store (transport.positionTicks.load (std::memory_order_relaxed)
                                            + numSamples * transport.ticksPerSample(),

+ 24 - 1
src/engine/AudioEngine.h

@@ -4,9 +4,11 @@
 
 #include <juce_audio_utils/juce_audio_utils.h>
 
+#include "core/LiveEventQueue.h"
 #include "core/RackRenderer.h"
 #include "core/SnapshotExchange.h"
 #include "core/Song.h"
+#include "engine/SampleLibrary.h"
 #include "engine/Transport.h"
 
 namespace daw
@@ -22,21 +24,39 @@ class AudioEngine final : private juce::AudioIODeviceCallback,
                           private juce::Timer
 {
 public:
-    AudioEngine();
+    explicit AudioEngine (bool openAudioDevice = true);
     ~AudioEngine() override;
 
     juce::AudioDeviceManager& getDeviceManager() noexcept { return deviceManager; }
     Transport& getTransport() noexcept { return transport; }
+    SampleLibrary& getSampleLibrary() noexcept { return samples; }
 
     void play() noexcept;
     void stop() noexcept;
     void rewind() noexcept;
 
+    // Nota tocada ao vivo (teclado do PC, preview). Thread da UI.
+    void sendLiveNote (int channel, int key, float velocity, bool on);
+
     // Documento (thread da UI)
     const Song& getSong() const noexcept { return song; }
     void setSong (Song newSong);
     void editSong (const std::function<void (Song&)>& edit);
 
+    // Canal selecionado no Channel Rack (alvo do Piano Roll e do teclado). Thread da UI.
+    int getSelectedChannel() const noexcept { return selectedChannel; }
+    void setSelectedChannel (int channel);
+
+    // Importa um .flp localizando a instalação do FL para achar os samples.
+    // Retorna false e preenche `error` se não conseguir.
+    bool importFlpFile (const juce::File& file, juce::String& error);
+
+    // Renderiza sem dispositivo de áudio. Grava em `output` se não for nullptr.
+    // Retorna o pico (usado pelo autoteste).
+    float renderOffline (double seconds, double sampleRate, juce::AudioFormatWriter* output = nullptr);
+
+    int getNumGraphConnections() const { return (int) graph.getConnections().size(); }
+
 private:
     void audioDeviceIOCallbackWithContext (const float* const* inputChannelData,
                                            int numInputChannels,
@@ -55,8 +75,11 @@ private:
     juce::AudioProcessorGraph graph;
     juce::AudioProcessorPlayer player;
     Transport transport;
+    SampleLibrary samples;
+    LiveEventQueue liveEvents;
 
     Song song;
+    int selectedChannel = 0;
     SnapshotExchange<RackState> rackExchange;
     RackState lastPublishedShape; // canais + instrumentos do último snapshot, para reaproveitar vozes
 

+ 5 - 4
src/engine/ChannelRackProcessor.cpp

@@ -2,10 +2,11 @@
 
 namespace daw
 {
-ChannelRackProcessor::ChannelRackProcessor (const Transport& t, SnapshotExchange<RackState>& x)
+ChannelRackProcessor::ChannelRackProcessor (const Transport& t, SnapshotExchange<RackState>& x, LiveEventQueue& l)
     : AudioProcessor (BusesProperties().withOutput ("Output", juce::AudioChannelSet::stereo(), true)),
       transport (t),
-      exchange (x)
+      exchange (x),
+      live (l)
 {
 }
 
@@ -24,11 +25,11 @@ void ChannelRackProcessor::processBlock (juce::AudioBuffer<float>& buffer, juce:
 
     if (buffer.getNumChannels() >= 2)
     {
-        renderer.process (state, playing, startTick, numSamples, buffer.getWritePointer (0), buffer.getWritePointer (1));
+        renderer.process (state, playing, startTick, numSamples, buffer.getWritePointer (0), buffer.getWritePointer (1), &live);
     }
     else if (numSamples <= scratch.getNumSamples())
     {
-        renderer.process (state, playing, startTick, numSamples, scratch.getWritePointer (0), scratch.getWritePointer (1));
+        renderer.process (state, playing, startTick, numSamples, scratch.getWritePointer (0), scratch.getWritePointer (1), &live);
 
         if (buffer.getNumChannels() == 1)
         {

+ 3 - 1
src/engine/ChannelRackProcessor.h

@@ -2,6 +2,7 @@
 
 #include <juce_audio_processors/juce_audio_processors.h>
 
+#include "core/LiveEventQueue.h"
 #include "core/RackRenderer.h"
 #include "core/SnapshotExchange.h"
 #include "engine/Transport.h"
@@ -13,7 +14,7 @@ namespace daw
 class ChannelRackProcessor final : public juce::AudioProcessor
 {
 public:
-    ChannelRackProcessor (const Transport& transport, SnapshotExchange<RackState>& exchange);
+    ChannelRackProcessor (const Transport& transport, SnapshotExchange<RackState>& exchange, LiveEventQueue& live);
 
     const juce::String getName() const override { return "Channel Rack"; }
 
@@ -40,6 +41,7 @@ public:
 private:
     const Transport& transport;
     SnapshotExchange<RackState>& exchange;
+    LiveEventQueue& live;
     RackRenderer renderer;
     juce::AudioBuffer<float> scratch; // para saída mono
 

+ 188 - 0
src/engine/ProjectFile.cpp

@@ -0,0 +1,188 @@
+#include "engine/ProjectFile.h"
+
+#include "engine/Text.h"
+
+namespace daw::ProjectFile
+{
+namespace
+{
+const char* instrumentId (InstrumentKind k)
+{
+    switch (k)
+    {
+        case InstrumentKind::kick: return "kick";
+        case InstrumentKind::snare: return "snare";
+        case InstrumentKind::hat: return "hat";
+        case InstrumentKind::clap: return "clap";
+        case InstrumentKind::synth: return "synth";
+        case InstrumentKind::sampler: return "sampler";
+    }
+    return "synth";
+}
+
+InstrumentKind instrumentFromId (const juce::String& id)
+{
+    for (auto k : { InstrumentKind::kick, InstrumentKind::snare, InstrumentKind::hat, InstrumentKind::clap,
+                    InstrumentKind::synth, InstrumentKind::sampler })
+        if (id == instrumentId (k))
+            return k;
+
+    return InstrumentKind::synth;
+}
+
+juce::String str (const std::string& s) { return juce::String::fromUTF8 (s.c_str()); }
+} // namespace
+
+juce::String toJson (const Song& song)
+{
+    auto root = std::make_unique<juce::DynamicObject>();
+    root->setProperty ("format", "daw-project");
+    root->setProperty ("version", currentVersion);
+    root->setProperty ("bpm", song.bpm);
+    root->setProperty ("beatsPerBar", song.beatsPerBar);
+    root->setProperty ("currentPattern", song.currentPattern);
+
+    juce::Array<juce::var> channels;
+
+    for (const auto& c : song.channels)
+    {
+        auto o = std::make_unique<juce::DynamicObject>();
+        o->setProperty ("name", str (c.name));
+        o->setProperty ("instrument", instrumentId (c.instrument));
+        o->setProperty ("volume", c.volume);
+        o->setProperty ("pan", c.pan);
+        o->setProperty ("muted", c.muted);
+
+        if (! c.samplePath.empty())
+            o->setProperty ("sample", str (c.samplePath));
+
+        channels.add (juce::var (o.release()));
+    }
+
+    root->setProperty ("channels", channels);
+
+    juce::Array<juce::var> patterns;
+
+    for (const auto& p : song.patterns)
+    {
+        auto o = std::make_unique<juce::DynamicObject>();
+        o->setProperty ("name", str (p.name));
+
+        if (p.lengthTicks > 0)
+            o->setProperty ("length", (juce::int64) p.lengthTicks);
+
+        juce::Array<juce::var> notes;
+
+        for (const auto& n : p.notes)
+            notes.add (juce::Array<juce::var> { (juce::int64) n.start, (juce::int64) n.length, n.channel, n.key,
+                                                juce::roundToInt (n.velocity * 1000.0f) / 1000.0 });
+
+        o->setProperty ("notes", notes);
+        patterns.add (juce::var (o.release()));
+    }
+
+    root->setProperty ("patterns", patterns);
+    return juce::JSON::toString (juce::var (root.release()), false);
+}
+
+std::optional<Song> fromJson (const juce::String& json, juce::String& error)
+{
+    juce::var root;
+    const auto parsed = juce::JSON::parse (json, root);
+
+    if (parsed.failed())
+    {
+        error = utf8 ("JSON inválido: ") + parsed.getErrorMessage();
+        return std::nullopt;
+    }
+
+    if (root["format"].toString() != "daw-project")
+    {
+        error = utf8 ("não é um projeto desta DAW");
+        return std::nullopt;
+    }
+
+    if ((int) root["version"] > currentVersion)
+    {
+        error = utf8 ("projeto salvo por uma versão mais nova da DAW");
+        return std::nullopt;
+    }
+
+    Song song;
+    song.bpm = juce::jlimit (10.0, 999.0, (double) root.getProperty ("bpm", 130.0));
+    song.beatsPerBar = juce::jlimit (1, 32, (int) root.getProperty ("beatsPerBar", 4));
+    song.currentPattern = (int) root.getProperty ("currentPattern", 0);
+
+    if (auto* channels = root["channels"].getArray())
+        for (const auto& c : *channels)
+        {
+            ChannelDef def;
+            def.name = c["name"].toString().toStdString();
+            def.instrument = instrumentFromId (c["instrument"].toString());
+            def.volume = juce::jlimit (0.0f, 1.0f, (float) c.getProperty ("volume", 0.8));
+            def.pan = juce::jlimit (-1.0f, 1.0f, (float) c.getProperty ("pan", 0.0));
+            def.muted = (bool) c.getProperty ("muted", false);
+            def.samplePath = c["sample"].toString().toStdString();
+            song.channels.push_back (std::move (def));
+        }
+
+    if (auto* patterns = root["patterns"].getArray())
+        for (const auto& p : *patterns)
+        {
+            Pattern pattern;
+            pattern.name = p["name"].toString().toStdString();
+            pattern.lengthTicks = (juce::int64) p.getProperty ("length", 0);
+
+            if (auto* notes = p["notes"].getArray())
+                for (const auto& n : *notes)
+                {
+                    if (! n.isArray() || n.size() < 5)
+                        continue;
+
+                    Note note;
+                    note.start = (juce::int64) n[0];
+                    note.length = juce::jmax<juce::int64> (1, (juce::int64) n[1]);
+                    note.channel = (int) n[2];
+                    note.key = juce::jlimit (0, 127, (int) n[3]);
+                    note.velocity = juce::jlimit (0.0f, 1.0f, (float) (double) n[4]);
+
+                    if (note.channel >= 0 && note.channel < (int) song.channels.size())
+                        pattern.notes.push_back (note);
+                }
+
+            pattern.sortNotes();
+            song.patterns.push_back (std::move (pattern));
+        }
+
+    if (song.patterns.empty())
+        song.patterns.emplace_back().name = "Pattern 1";
+
+    song.currentPattern = juce::jlimit (0, (int) song.patterns.size() - 1, song.currentPattern);
+    return song;
+}
+
+bool save (const Song& song, const juce::File& file, juce::String& error)
+{
+    // Grava num temporário e troca, para um erro no meio não destruir o projeto anterior.
+    juce::TemporaryFile temp (file);
+
+    if (! temp.getFile().replaceWithText (toJson (song)) || ! temp.overwriteTargetFileWithTemporary())
+    {
+        error = utf8 ("não foi possível gravar ") + file.getFullPathName();
+        return false;
+    }
+
+    return true;
+}
+
+std::optional<Song> load (const juce::File& file, juce::String& error)
+{
+    if (! file.existsAsFile())
+    {
+        error = utf8 ("arquivo não encontrado");
+        return std::nullopt;
+    }
+
+    return fromJson (file.loadFileAsString(), error);
+}
+} // namespace daw::ProjectFile

+ 24 - 0
src/engine/ProjectFile.h

@@ -0,0 +1,24 @@
+#pragma once
+
+#include <optional>
+
+#include <juce_core/juce_core.h>
+
+#include "core/Song.h"
+
+namespace daw
+{
+// Formato próprio de projeto: JSON versionado (.dawproj).
+// Notas vão como arrays compactos [start, length, channel, key, velocity].
+namespace ProjectFile
+{
+constexpr const char* extension = ".dawproj";
+constexpr int currentVersion = 1;
+
+juce::String toJson (const Song& song);
+std::optional<Song> fromJson (const juce::String& json, juce::String& error);
+
+bool save (const Song& song, const juce::File& file, juce::String& error);
+std::optional<Song> load (const juce::File& file, juce::String& error);
+} // namespace ProjectFile
+} // namespace daw

+ 109 - 0
src/engine/SampleLibrary.cpp

@@ -0,0 +1,109 @@
+#include "engine/SampleLibrary.h"
+
+namespace daw
+{
+namespace
+{
+// O FL guarda muitos samples de fábrica como WAV cujo "data" é um stream Ogg Vorbis
+// (format tag 0x674F/0x6750/0x6751, "Og"). O leitor de WAV do JUCE não entende isso.
+std::unique_ptr<juce::MemoryBlock> extractOggFromWav (const juce::File& file)
+{
+    juce::MemoryBlock bytes;
+
+    if (! file.loadFileAsData (bytes) || bytes.getSize() < 12)
+        return nullptr;
+
+    const auto* d = static_cast<const juce::uint8*> (bytes.getData());
+
+    if (std::memcmp (d, "RIFF", 4) != 0 || std::memcmp (d + 8, "WAVE", 4) != 0)
+        return nullptr;
+
+    bool isOgg = false;
+
+    for (size_t pos = 12; pos + 8 <= bytes.getSize();)
+    {
+        const auto size = (size_t) juce::ByteOrder::littleEndianInt (d + pos + 4);
+        const auto body = pos + 8;
+
+        if (std::memcmp (d + pos, "fmt ", 4) == 0 && body + 2 <= bytes.getSize())
+        {
+            const auto tag = juce::ByteOrder::littleEndianShort (d + body);
+            isOgg = tag == 0x674F || tag == 0x6750 || tag == 0x6751;
+        }
+        else if (std::memcmp (d + pos, "data", 4) == 0 && isOgg)
+        {
+            const auto available = juce::jmin (size, bytes.getSize() - body);
+            return std::make_unique<juce::MemoryBlock> (d + body, available);
+        }
+
+        pos = body + size + (size & 1);
+    }
+
+    return nullptr;
+}
+} // namespace
+
+SampleLibrary::SampleLibrary()
+{
+    formats.registerBasicFormats();
+}
+
+juce::String SampleLibrary::wildcard() const
+{
+    return formats.getWildcardForAllFormats();
+}
+
+std::unique_ptr<juce::AudioFormatReader> SampleLibrary::createReader (const juce::File& file)
+{
+    if (auto reader = std::unique_ptr<juce::AudioFormatReader> (formats.createReaderFor (file)))
+        return reader;
+
+    // Extensão mentirosa (ex.: um Ogg salvo como .wav): testa todos os formatos pelo conteúdo.
+    if (auto* reader = formats.createReaderFor (file.createInputStream()))
+        return std::unique_ptr<juce::AudioFormatReader> (reader);
+
+    if (auto ogg = extractOggFromWav (file))
+    {
+        juce::OggVorbisAudioFormat vorbis;
+
+        // O reader fica dono do stream; se falhar, o próprio JUCE apaga o stream.
+        if (auto* reader = vorbis.createReaderFor (new juce::MemoryInputStream (std::move (*ogg)), true))
+            return std::unique_ptr<juce::AudioFormatReader> (reader);
+    }
+
+    return nullptr;
+}
+
+std::shared_ptr<const SampleData> SampleLibrary::load (const juce::String& path)
+{
+    if (auto cached = cache[path].lock())
+        return cached;
+
+    const juce::File file (path);
+
+    if (! file.existsAsFile())
+        return nullptr;
+
+    auto reader = createReader (file);
+
+    if (reader == nullptr || reader->lengthInSamples <= 0 || reader->numChannels == 0)
+        return nullptr;
+
+    // Limite de segurança: 10 minutos. Samples maiores vão precisar de streaming do disco.
+    const auto frames = (int) juce::jmin<juce::int64> (reader->lengthInSamples, (juce::int64) (reader->sampleRate * 600.0));
+    const auto channels = juce::jmin (2, (int) reader->numChannels);
+
+    juce::AudioBuffer<float> buffer (channels, frames);
+    reader->read (&buffer, 0, frames, 0, true, channels > 1);
+
+    auto data = std::make_shared<SampleData>();
+    data->sampleRate = reader->sampleRate;
+    data->left.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + frames);
+
+    if (channels > 1)
+        data->right.assign (buffer.getReadPointer (1), buffer.getReadPointer (1) + frames);
+
+    cache[path] = data;
+    return data;
+}
+} // namespace daw

+ 30 - 0
src/engine/SampleLibrary.h

@@ -0,0 +1,30 @@
+#pragma once
+
+#include <map>
+#include <memory>
+
+#include <juce_audio_formats/juce_audio_formats.h>
+
+#include "core/Instruments.h"
+
+namespace daw
+{
+// Decodifica arquivos de áudio para SampleData, com cache por caminho.
+// Thread da UI (decodificar aloca e faz I/O).
+class SampleLibrary
+{
+public:
+    SampleLibrary();
+
+    std::shared_ptr<const SampleData> load (const juce::String& path);
+
+    // Filtro para FileChooser ("*.wav;*.flac;...")
+    juce::String wildcard() const;
+
+private:
+    std::unique_ptr<juce::AudioFormatReader> createReader (const juce::File& file);
+
+    juce::AudioFormatManager formats;
+    std::map<juce::String, std::weak_ptr<const SampleData>> cache;
+};
+} // namespace daw

+ 12 - 0
src/engine/Text.h

@@ -0,0 +1,12 @@
+#pragma once
+
+#include <juce_core/juce_core.h>
+
+namespace daw
+{
+// O JUCE trata literais char* como ASCII. Todo texto com acento passa por aqui.
+inline juce::String utf8 (const char* text)
+{
+    return juce::String::fromUTF8 (text);
+}
+} // namespace daw

+ 288 - 74
src/ui/ChannelRackComponent.cpp

@@ -1,19 +1,13 @@
 #include "ui/ChannelRackComponent.h"
 
+#include "engine/Text.h"
+
+#include "ui/Theme.h"
+
 namespace daw
 {
 namespace
 {
-const juce::Colour background { 0xff2b3036 };
-const juce::Colour rowColour { 0xff353b42 };
-const juce::Colour stepOffA { 0xff4a525b };  // grupos de 4 steps alternados, como no FL
-const juce::Colour stepOffB { 0xff5b4f4f };
-const juce::Colour stepOn { 0xffe8e8e8 };
-const juce::Colour stepOnImported { 0xff9fd3ff }; // nota fora da grade (veio do piano roll)
-const juce::Colour playheadColour { 0x5530c0ff };
-const juce::Colour muteOn { 0xff6fe36f };
-const juce::Colour muteOff { 0xff505050 };
-
 const char* instrumentName (InstrumentKind k)
 {
     switch (k)
@@ -23,20 +17,66 @@ const char* instrumentName (InstrumentKind k)
         case InstrumentKind::hat: return "Hat";
         case InstrumentKind::clap: return "Clap";
         case InstrumentKind::synth: return "Synth";
+        case InstrumentKind::sampler: return "Sampler";
     }
     return "?";
 }
 
+constexpr InstrumentKind builtInKinds[] = { InstrumentKind::kick, InstrumentKind::snare, InstrumentKind::hat,
+                                            InstrumentKind::clap, InstrumentKind::synth };
+
 void setStep (Pattern& p, int channel, int step, bool on)
 {
     if (p.hasStep (channel, step) != on)
         p.toggleStep (channel, step);
 }
+
+void removeChannelNotes (Song& s, int channel, bool shiftOthers)
+{
+    for (auto& p : s.patterns)
+    {
+        auto& notes = p.notes;
+        notes.erase (std::remove_if (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }),
+                     notes.end());
+
+        if (shiftOthers)
+            for (auto& n : notes)
+                if (n.channel > channel)
+                    --n.channel;
+    }
+}
+
+void drawKnob (juce::Graphics& g, juce::Rectangle<float> r, float value01, bool bipolar, juce::Colour colour)
+{
+    const auto size = juce::jmin (r.getWidth(), r.getHeight()) - 6.0f;
+    const auto area = r.withSizeKeepingCentre (size, size);
+    const auto centre = area.getCentre();
+    const auto radius = size / 2.0f;
+    constexpr auto start = juce::MathConstants<float>::pi * 1.25f;
+    constexpr auto range = juce::MathConstants<float>::pi * 1.5f;
+
+    g.setColour (theme::knobBackground);
+    g.fillEllipse (area);
+
+    const auto from = bipolar ? start + range * 0.5f : start;
+    const auto to = start + range * value01;
+    juce::Path arc;
+    arc.addCentredArc (centre.x, centre.y, radius - 1.5f, radius - 1.5f, 0.0f, juce::jmin (from, to), juce::jmax (from, to), true);
+    g.setColour (colour);
+    g.strokePath (arc, juce::PathStrokeType (2.5f));
+
+    // ângulos do JUCE: 0 = meio-dia, sentido horário
+    const auto length = radius - 3.0f;
+    g.setColour (juce::Colours::white);
+    g.drawLine (centre.x, centre.y, centre.x + std::sin (to) * length, centre.y - std::cos (to) * length, 1.5f);
+}
 } // namespace
 
 ChannelRackComponent::ChannelRackComponent (AudioEngine& e)
     : engine (e)
 {
+    setWantsKeyboardFocus (false);
+    setMouseClickGrabsKeyboardFocus (false);
     engine.addChangeListener (this);
     updateSize();
     startTimerHz (30);
@@ -56,7 +96,7 @@ int ChannelRackComponent::numSteps() const
 
     const auto& p = song.patterns[(std::size_t) song.currentPattern];
     const auto steps = (int) (p.effectiveLength (song.beatsPerBar) / ticksPerStep);
-    return juce::jlimit (16, 256, steps);
+    return juce::jlimit (16, 512, steps);
 }
 
 void ChannelRackComponent::updateSize()
@@ -65,9 +105,37 @@ void ChannelRackComponent::updateSize()
     setSize (gridLeft() + numSteps() * stepWidth + 8, rows * rowHeight + 8);
 }
 
+juce::Rectangle<int> ChannelRackComponent::rowBounds (int row) const
+{
+    return { 0, 4 + row * rowHeight, getWidth(), rowHeight };
+}
+
 juce::Rectangle<int> ChannelRackComponent::stepBounds (int row, int step) const
 {
-    return { gridLeft() + step * stepWidth + 1, 4 + row * rowHeight + 3, stepWidth - 3, rowHeight - 6 };
+    return { gridLeft() + step * stepWidth + 1, 4 + row * rowHeight + 4, stepWidth - 3, rowHeight - 8 };
+}
+
+ChannelRackComponent::Area ChannelRackComponent::areaAt (int x, int y, int& row) const
+{
+    const auto channels = (int) engine.getSong().channels.size();
+    row = (y - 4) / rowHeight;
+
+    if (y < 4 || row > channels)
+        return Area::none;
+
+    if (row == channels)
+        return x < gridLeft() ? Area::addRow : Area::none;
+
+    if (x < muteWidth)
+        return Area::mute;
+    if (x < muteWidth + knobWidth)
+        return Area::pan;
+    if (x < muteWidth + 2 * knobWidth)
+        return Area::volume;
+    if (x < gridLeft())
+        return Area::name;
+
+    return Area::grid;
 }
 
 bool ChannelRackComponent::cellHasNote (int channel, int step) const
@@ -78,20 +146,15 @@ bool ChannelRackComponent::cellHasNote (int channel, int step) const
     const auto to = from + ticksPerStep;
 
     for (const auto& n : p.notes)
-    {
-        if (n.start >= to)
-            break; // notas ordenadas
-
-        if (n.channel == channel && n.start >= from)
+        if (n.channel == channel && n.start >= from && n.start < to)
             return true;
-    }
 
     return false;
 }
 
 void ChannelRackComponent::paint (juce::Graphics& g)
 {
-    g.fillAll (background);
+    g.fillAll (theme::panel);
 
     const auto& song = engine.getSong();
 
@@ -101,6 +164,7 @@ void ChannelRackComponent::paint (juce::Graphics& g)
     const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
     const auto steps = numSteps();
     const auto clip = g.getClipBounds();
+    const auto selected = engine.getSelectedChannel();
     g.setFont (juce::FontOptions (14.0f));
 
     for (int row = 0; row < (int) song.channels.size(); ++row)
@@ -111,15 +175,28 @@ void ChannelRackComponent::paint (juce::Graphics& g)
             continue;
 
         const auto& channel = song.channels[(std::size_t) row];
+        const auto nameArea = juce::Rectangle<float> ((float) muteWidth + 2 * knobWidth + 2, (float) y + 3,
+                                                      (float) nameWidth, (float) rowHeight - 6);
 
-        g.setColour (rowColour);
-        g.fillRoundedRectangle ({ 4.0f, (float) y + 2, (float) (muteWidth + nameWidth), (float) rowHeight - 4 }, 4.0f);
+        g.setColour (theme::muteLed (channel.muted));
+        g.fillEllipse ((float) 9, (float) y + rowHeight / 2.0f - 5, 10, 10);
 
-        g.setColour (channel.muted ? muteOff : muteOn);
-        g.fillEllipse ((float) 10, (float) y + rowHeight / 2.0f - 5, 10, 10);
+        drawKnob (g, { (float) muteWidth, (float) y, (float) knobWidth, (float) rowHeight }, (channel.pan + 1.0f) / 2.0f,
+                  true, theme::accentBlue);
+        drawKnob (g, { (float) muteWidth + knobWidth, (float) y, (float) knobWidth, (float) rowHeight }, channel.volume,
+                  false, theme::accentGreen);
+
+        g.setColour (row == selected ? theme::channelButtonSelected : theme::channelButton);
+        g.fillRoundedRectangle (nameArea, 4.0f);
+
+        if (row == selected)
+        {
+            g.setColour (theme::accentOrange);
+            g.fillRoundedRectangle (nameArea.withWidth (4.0f), 2.0f);
+        }
 
         g.setColour (channel.muted ? juce::Colours::grey : juce::Colours::white);
-        g.drawText (juce::String::fromUTF8 (channel.name.c_str()), muteWidth + 4, y, nameWidth - 8, rowHeight,
+        g.drawText (juce::String::fromUTF8 (channel.name.c_str()), nameArea.reduced (10, 0).toNearestInt(),
                     juce::Justification::centredLeft, true);
 
         for (int step = 0; step < steps; ++step)
@@ -132,71 +209,121 @@ void ChannelRackComponent::paint (juce::Graphics& g)
             const auto onGrid = pattern.hasStep (row, step);
             const auto any = onGrid || cellHasNote (row, step);
 
-            g.setColour (any ? (onGrid ? stepOn : stepOnImported) : ((step / 4) % 2 == 0 ? stepOffA : stepOffB));
+            g.setColour (any ? (onGrid ? theme::stepOn : theme::stepOnOffGrid) : theme::stepOff (step));
             g.fillRoundedRectangle (r.toFloat(), 3.0f);
         }
     }
 
-    // linha "adicionar canal"
     const auto addY = 4 + (int) song.channels.size() * rowHeight;
     g.setColour (juce::Colours::white.withAlpha (0.5f));
-    g.drawText ("+ adicionar canal", muteWidth + 4, addY, nameWidth, rowHeight, juce::Justification::centredLeft);
+    g.drawText (utf8 ("+ adicionar canal (ou arraste um arquivo de áudio)"), muteWidth + 2 * knobWidth + 4, addY,
+                400, rowHeight, juce::Justification::centredLeft);
 
     if (playheadStep >= 0 && playheadStep < steps)
     {
-        g.setColour (playheadColour);
+        g.setColour (theme::playhead.withAlpha (0.35f));
         g.fillRect (gridLeft() + playheadStep * stepWidth, 0, stepWidth - 2, addY);
     }
 }
 
 void ChannelRackComponent::mouseDown (const juce::MouseEvent& e)
 {
+    int row = 0;
+    const auto area = areaAt (e.x, e.y, row);
     const auto& song = engine.getSong();
-    const auto row = (e.y - 4) / rowHeight;
-
-    if (e.y < 4 || row > (int) song.channels.size())
-        return;
 
-    if (row == (int) song.channels.size())
+    switch (area)
     {
-        if (e.x < gridLeft())
-            addChannel();
-        return;
-    }
+        case Area::none:
+            return;
+
+        case Area::addRow:
+            showAddChannelMenu();
+            return;
+
+        case Area::mute:
+            engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].muted = ! s.channels[(std::size_t) row].muted; });
+            return;
+
+        case Area::pan:
+        case Area::volume:
+            knobDrag = area;
+            knobRow = row;
+            knobStartValue = area == Area::pan ? song.channels[(std::size_t) row].pan : song.channels[(std::size_t) row].volume;
+            return;
+
+        case Area::name:
+            engine.setSelectedChannel (row);
+
+            if (e.mods.isPopupMenu())
+                showChannelMenu (row);
+            else
+                engine.sendLiveNote (row, 60, 0.8f, true);
+            return;
+
+        case Area::grid:
+        {
+            const auto step = (e.x - gridLeft()) / stepWidth;
+            const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
 
-    if (e.x < muteWidth + 4)
-    {
-        engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].muted = ! s.channels[(std::size_t) row].muted; });
-        return;
-    }
+            if (e.mods.isRightButtonDown())
+                paintMode = PaintMode::remove;
+            else
+                paintMode = pattern.hasStep (row, step) ? PaintMode::remove : PaintMode::add;
 
-    if (e.x < gridLeft())
-    {
-        showChannelMenu (row);
-        return;
+            lastPaintedRow = lastPaintedStep = -1;
+            applyPaint (e);
+            return;
+        }
     }
-
-    const auto step = (e.x - gridLeft()) / stepWidth;
-    const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
-
-    if (e.mods.isRightButtonDown())
-        paintMode = PaintMode::remove;
-    else
-        paintMode = pattern.hasStep (row, step) ? PaintMode::remove : PaintMode::add;
-
-    lastPaintedRow = lastPaintedStep = -1;
-    applyPaint (e);
 }
 
 void ChannelRackComponent::mouseDrag (const juce::MouseEvent& e)
 {
+    if (knobDrag != Area::none)
+    {
+        const auto delta = (float) -e.getDistanceFromDragStartY() / 150.0f;
+        const auto row = knobRow;
+
+        if (knobDrag == Area::pan)
+        {
+            const auto value = juce::jlimit (-1.0f, 1.0f, knobStartValue + delta * 2.0f);
+            engine.editSong ([row, value] (Song& s) { s.channels[(std::size_t) row].pan = value; });
+        }
+        else
+        {
+            const auto value = juce::jlimit (0.0f, 1.0f, knobStartValue + delta);
+            engine.editSong ([row, value] (Song& s) { s.channels[(std::size_t) row].volume = value; });
+        }
+        return;
+    }
+
     if (paintMode != PaintMode::none)
         applyPaint (e);
 }
 
-void ChannelRackComponent::mouseUp (const juce::MouseEvent&)
+void ChannelRackComponent::mouseUp (const juce::MouseEvent& e)
 {
+    int row = 0;
+
+    if (areaAt (e.getMouseDownX(), e.getMouseDownY(), row) == Area::name && ! e.mods.isPopupMenu())
+        engine.sendLiveNote (row, 60, 0.0f, false);
+
     paintMode = PaintMode::none;
+    knobDrag = Area::none;
+}
+
+void ChannelRackComponent::mouseDoubleClick (const juce::MouseEvent& e)
+{
+    int row = 0;
+    const auto area = areaAt (e.x, e.y, row);
+
+    if (area == Area::pan)
+        engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].pan = 0.0f; });
+    else if (area == Area::volume)
+        engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].volume = 0.8f; });
+    else if (area == Area::name && onOpenPianoRoll)
+        onOpenPianoRoll();
 }
 
 void ChannelRackComponent::applyPaint (const juce::MouseEvent& e)
@@ -216,6 +343,9 @@ void ChannelRackComponent::applyPaint (const juce::MouseEvent& e)
     const auto on = paintMode == PaintMode::add;
 
     engine.editSong ([row, step, on] (Song& s) { setStep (s.patterns[(std::size_t) s.currentPattern], row, step, on); });
+
+    if (on)
+        engine.sendLiveNote (row, 60, 0.78f, true);
 }
 
 void ChannelRackComponent::showChannelMenu (int channel)
@@ -223,47 +353,50 @@ void ChannelRackComponent::showChannelMenu (int channel)
     const auto& c = engine.getSong().channels[(std::size_t) channel];
     juce::PopupMenu instruments;
 
-    for (auto kind : { InstrumentKind::kick, InstrumentKind::snare, InstrumentKind::hat, InstrumentKind::clap,
-                       InstrumentKind::synth })
+    for (auto kind : builtInKinds)
         instruments.addItem (instrumentName (kind), true, c.instrument == kind, [this, channel, kind] {
             engine.editSong ([channel, kind] (Song& s) { s.channels[(std::size_t) channel].instrument = kind; });
         });
 
+    instruments.addSeparator();
+    instruments.addItem ("Sampler (escolher arquivo)...", [this, channel] { chooseSample (channel); });
+
     juce::PopupMenu menu;
     menu.addSectionHeader (juce::String::fromUTF8 (c.name.c_str()));
+
+    if (c.instrument == InstrumentKind::sampler)
+        menu.addItem (juce::String ("Sample: ") + juce::File (juce::String::fromUTF8 (c.samplePath.c_str())).getFileName(),
+                      false, false, [] {});
+
+    menu.addItem ("Piano Roll", [this] {
+        if (onOpenPianoRoll)
+            onOpenPianoRoll();
+    });
     menu.addSubMenu ("Instrumento", instruments);
-    menu.addItem ("Limpar steps", [this, channel] {
+    menu.addItem ("Renomear...", [this, channel] { rename (channel); });
+    menu.addItem ("Limpar notas desta pattern", [this, channel] {
         engine.editSong ([channel] (Song& s) {
             auto& notes = s.patterns[(std::size_t) s.currentPattern].notes;
             notes.erase (std::remove_if (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }),
                          notes.end());
         });
     });
+    menu.addSeparator();
     menu.addItem ("Remover canal", engine.getSong().channels.size() > 1, false, [this, channel] {
         engine.editSong ([channel] (Song& s) {
             s.channels.erase (s.channels.begin() + channel);
-
-            for (auto& p : s.patterns)
-            {
-                auto& notes = p.notes;
-                notes.erase (std::remove_if (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }),
-                             notes.end());
-                for (auto& n : notes)
-                    if (n.channel > channel)
-                        --n.channel;
-            }
+            removeChannelNotes (s, channel, true);
         });
     });
 
     menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
 }
 
-void ChannelRackComponent::addChannel()
+void ChannelRackComponent::showAddChannelMenu()
 {
     juce::PopupMenu menu;
 
-    for (auto kind : { InstrumentKind::kick, InstrumentKind::snare, InstrumentKind::hat, InstrumentKind::clap,
-                       InstrumentKind::synth })
+    for (auto kind : builtInKinds)
         menu.addItem (instrumentName (kind), [this, kind] {
             engine.editSong ([kind] (Song& s) {
                 ChannelDef c;
@@ -271,11 +404,92 @@ void ChannelRackComponent::addChannel()
                 c.instrument = kind;
                 s.channels.push_back (c);
             });
+            engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
         });
 
+    menu.addSeparator();
+    menu.addItem ("Sampler (escolher arquivo)...", [this] { chooseSample (-1); });
+
     menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
 }
 
+void ChannelRackComponent::chooseSample (int channel)
+{
+    fileChooser = std::make_unique<juce::FileChooser> ("Escolher sample", juce::File(), engine.getSampleLibrary().wildcard());
+    fileChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
+                              [this, channel] (const juce::FileChooser& chooser) {
+                                  if (chooser.getResult().existsAsFile())
+                                      assignSample (channel, chooser.getResult());
+                              });
+}
+
+void ChannelRackComponent::assignSample (int channel, const juce::File& file)
+{
+    if (engine.getSampleLibrary().load (file.getFullPathName()) == nullptr)
+    {
+        juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "Sample",
+                                                utf8 ("Não consegui ler ") + file.getFileName());
+        return;
+    }
+
+    const auto path = file.getFullPathName().toStdString();
+    const auto name = file.getFileNameWithoutExtension().toStdString();
+
+    engine.editSong ([channel, path, name] (Song& s) {
+        const auto isNew = channel < 0 || channel >= (int) s.channels.size();
+        auto& c = isNew ? s.channels.emplace_back() : s.channels[(std::size_t) channel];
+        c.instrument = InstrumentKind::sampler;
+        c.samplePath = path;
+        c.name = name;
+    });
+
+    if (channel < 0)
+        engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
+}
+
+void ChannelRackComponent::rename (int channel)
+{
+    auto* window = new juce::AlertWindow ("Renomear canal", {}, juce::MessageBoxIconType::NoIcon);
+    window->addTextEditor ("name", juce::String::fromUTF8 (engine.getSong().channels[(std::size_t) channel].name.c_str()));
+    window->addButton ("OK", 1, juce::KeyPress (juce::KeyPress::returnKey));
+    window->addButton ("Cancelar", 0, juce::KeyPress (juce::KeyPress::escapeKey));
+
+    window->enterModalState (true, juce::ModalCallbackFunction::create ([this, channel, window] (int result) {
+                                 const auto name = window->getTextEditorContents ("name").trim().toStdString();
+
+                                 if (result == 1 && ! name.empty() && channel < (int) engine.getSong().channels.size())
+                                     engine.editSong ([channel, name] (Song& s) { s.channels[(std::size_t) channel].name = name; });
+                             }),
+                             true);
+}
+
+bool ChannelRackComponent::isInterestedInFileDrag (const juce::StringArray& files)
+{
+    for (const auto& f : files)
+        if (juce::File (f).hasFileExtension ("wav;aif;aiff;flac;ogg;mp3"))
+            return true;
+
+    return false;
+}
+
+void ChannelRackComponent::filesDropped (const juce::StringArray& files, int x, int y)
+{
+    int row = 0;
+    const auto area = areaAt (x, y, row);
+    auto target = (area == Area::none || area == Area::addRow) ? -1 : row;
+
+    for (const auto& f : files)
+    {
+        const juce::File file (f);
+
+        if (! file.hasFileExtension ("wav;aif;aiff;flac;ogg;mp3"))
+            continue;
+
+        assignSample (target, file);
+        target = -1; // os próximos arquivos viram canais novos
+    }
+}
+
 void ChannelRackComponent::changeListenerCallback (juce::ChangeBroadcaster*)
 {
     updateSize();

+ 33 - 7
src/ui/ChannelRackComponent.h

@@ -1,15 +1,22 @@
 #pragma once
 
+#include <functional>
+
 #include <juce_gui_basics/juce_gui_basics.h>
 
 #include "engine/AudioEngine.h"
 
 namespace daw
 {
-// Channel Rack no estilo do FL: uma linha por canal com mute, nome e a grade
-// de steps da pattern atual. Clique esquerdo liga steps (arrastar pinta),
-// clique direito apaga. Clique no nome abre o menu do canal.
+// Channel Rack no estilo do FL: uma linha por canal com mute, pan, volume, nome
+// e a grade de steps da pattern atual.
+//  - steps: clique esquerdo liga (arrastar pinta), clique direito apaga
+//  - nome: clique seleciona e toca um preview, duplo clique abre o Piano Roll,
+//    clique direito abre o menu do canal
+//  - knobs: arrastar na vertical, duplo clique volta ao padrão
+//  - arrastar um arquivo de áudio para uma linha transforma o canal em sampler
 class ChannelRackComponent final : public juce::Component,
+                                   public juce::FileDragAndDropTarget,
                                    private juce::ChangeListener,
                                    private juce::Timer
 {
@@ -17,30 +24,43 @@ public:
     explicit ChannelRackComponent (AudioEngine& engine);
     ~ChannelRackComponent() override;
 
+    std::function<void()> onOpenPianoRoll;
+
     void paint (juce::Graphics& g) override;
     void mouseDown (const juce::MouseEvent& e) override;
     void mouseDrag (const juce::MouseEvent& e) override;
     void mouseUp (const juce::MouseEvent& e) override;
+    void mouseDoubleClick (const juce::MouseEvent& e) override;
+
+    bool isInterestedInFileDrag (const juce::StringArray& files) override;
+    void filesDropped (const juce::StringArray& files, int x, int y) override;
 
-    // Tamanho que o conteúdo precisa (o pai coloca isto num Viewport).
     void updateSize();
 
-    static constexpr int rowHeight = 28;
+    static constexpr int rowHeight = 30;
     static constexpr int muteWidth = 26;
+    static constexpr int knobWidth = 28;
     static constexpr int nameWidth = 150;
     static constexpr int stepWidth = 22;
 
 private:
+    enum class Area { none, mute, pan, volume, name, grid, addRow };
+
     void changeListenerCallback (juce::ChangeBroadcaster*) override;
     void timerCallback() override;
 
+    Area areaAt (int x, int y, int& row) const;
     int numSteps() const;
-    int gridLeft() const noexcept { return muteWidth + nameWidth + 8; }
+    int gridLeft() const noexcept { return muteWidth + 2 * knobWidth + nameWidth + 12; }
+    juce::Rectangle<int> rowBounds (int row) const;
     juce::Rectangle<int> stepBounds (int row, int step) const;
     bool cellHasNote (int channel, int step) const;
     void applyPaint (const juce::MouseEvent& e);
     void showChannelMenu (int channel);
-    void addChannel();
+    void showAddChannelMenu();
+    void chooseSample (int channel); // channel < 0 = novo canal
+    void assignSample (int channel, const juce::File& file);
+    void rename (int channel);
 
     AudioEngine& engine;
     int playheadStep = -1;
@@ -48,6 +68,12 @@ private:
     enum class PaintMode { none, add, remove } paintMode = PaintMode::none;
     int lastPaintedRow = -1, lastPaintedStep = -1;
 
+    Area knobDrag = Area::none;
+    int knobRow = -1;
+    float knobStartValue = 0.0f;
+
+    std::unique_ptr<juce::FileChooser> fileChooser;
+
     JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelRackComponent)
 };
 } // namespace daw

+ 265 - 62
src/ui/MainComponent.cpp

@@ -1,14 +1,45 @@
 #include "ui/MainComponent.h"
 
-#include "core/FlpImport.h"
-#include "flp/Flp.h"
+#include "engine/Text.h"
+
+#include "engine/ProjectFile.h"
+#include "ui/Theme.h"
 
 namespace daw
 {
+namespace
+{
+// Teclado do PC como piano, no layout do FL: Z S X D C V G B H N J M = C5..B5,
+// Q 2 W 3 E R 5 T 6 Y 7 U I 9 O 0 P = C6..E7.
+int keyCodeToNote (int keyCode)
+{
+    static const char lower[] = "ZSXDCVGBHNJM";
+    static const char upper[] = "Q2W3ER5T6Y7UI9O0P";
+    const auto c = (char) juce::CharacterFunctions::toUpperCase ((juce::juce_wchar) keyCode);
+
+    for (int i = 0; lower[i] != 0; ++i)
+        if (lower[i] == c)
+            return 60 + i;
+
+    for (int i = 0; upper[i] != 0; ++i)
+        if (upper[i] == c)
+            return 72 + i;
+
+    return -1;
+}
+
+constexpr int rackTab = 0;
+constexpr int pianoRollTab = 1;
+} // namespace
+
 MainComponent::MainComponent (AudioEngine& e)
     : engine (e),
-      rack (e)
+      rack (e),
+      pianoRoll (e)
 {
+    newButton.onClick = [this] { newProject(); };
+    openButton.onClick = [this] { chooseFileToOpen(); };
+    saveButton.onClick = [this] { save (false); };
     playButton.onClick = [this] { togglePlay(); };
     stopButton.onClick = [this]
     {
@@ -17,7 +48,6 @@ MainComponent::MainComponent (AudioEngine& e)
     };
     metronomeButton.onClick = [this] { engine.getTransport().metronome.store (metronomeButton.getToggleState()); };
     settingsButton.onClick = [this] { showAudioSettings(); };
-    openButton.onClick = [this] { openFlp(); };
 
     bpmSlider.setRange (20.0, 999.0, 0.1);
     bpmSlider.setValue (engine.getSong().bpm, juce::dontSendNotification);
@@ -44,20 +74,37 @@ MainComponent::MainComponent (AudioEngine& e)
     positionLabel.setFont (juce::FontOptions (20.0f));
     positionLabel.setJustificationType (juce::Justification::centred);
     cpuLabel.setJustificationType (juce::Justification::centredRight);
+    hintLabel.setFont (juce::FontOptions (12.0f));
+    hintLabel.setColour (juce::Label::textColourId, juce::Colours::white.withAlpha (0.5f));
+    hintLabel.setText (utf8 ("Espaço: play/pause   Z..M / Q..P: tocar o canal selecionado   F6 rack   F7 piano roll   Ctrl+S salvar   Ctrl+O abrir"),
+                       juce::dontSendNotification);
 
+    rack.onOpenPianoRoll = [this] { openPianoRoll(); };
     rackViewport.setViewedComponent (&rack, false);
     rackViewport.setScrollBarsShown (true, true);
 
-    for (auto* c : std::initializer_list<juce::Component*> { &playButton, &stopButton, &metronomeButton, &bpmSlider,
-                                                             &patternBox, &newPatternButton, &openButton,
-                                                             &settingsButton, &positionLabel, &cpuLabel, &rackViewport })
+    tabs.setTabBarDepth (28);
+    tabs.setOutline (0);
+    tabs.addTab ("Channel Rack", theme::toolbar, &rackViewport, false);
+    tabs.addTab ("Piano Roll", theme::toolbar, &pianoRoll, false);
+
+    for (auto* c : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &playButton, &stopButton,
+                                                             &metronomeButton, &bpmSlider, &patternBox, &newPatternButton,
+                                                             &settingsButton, &positionLabel, &cpuLabel, &hintLabel, &tabs })
+    {
         addAndMakeVisible (c);
+        c->setMouseClickGrabsKeyboardFocus (false); // o teclado do PC fica com a janela principal
+    }
+
+    for (auto* b : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &playButton, &stopButton,
+                                                             &metronomeButton, &newPatternButton, &settingsButton })
+        b->setWantsKeyboardFocus (false);
 
     engine.addChangeListener (this);
-    refreshPatternList();
+    refreshToolbar();
 
     setWantsKeyboardFocus (true);
-    setSize (1000, 420);
+    setSize (1180, 620);
     startTimerHz (30);
 }
 
@@ -69,43 +116,108 @@ MainComponent::~MainComponent()
 
 void MainComponent::paint (juce::Graphics& g)
 {
-    g.fillAll (juce::Colour (0xff23272c));
+    g.fillAll (theme::window);
+    g.setColour (theme::toolbar);
+    g.fillRect (0, 0, getWidth(), 46);
 }
 
 void MainComponent::resized()
 {
-    auto area = getLocalBounds().reduced (8);
-    auto toolbar = area.removeFromTop (30);
-
-    playButton.setBounds (toolbar.removeFromLeft (64));
-    toolbar.removeFromLeft (4);
-    stopButton.setBounds (toolbar.removeFromLeft (64));
-    toolbar.removeFromLeft (8);
-    metronomeButton.setBounds (toolbar.removeFromLeft (70));
-    bpmSlider.setBounds (toolbar.removeFromLeft (150));
-    toolbar.removeFromLeft (8);
-    patternBox.setBounds (toolbar.removeFromLeft (160));
-    toolbar.removeFromLeft (4);
-    newPatternButton.setBounds (toolbar.removeFromLeft (30));
-    toolbar.removeFromLeft (8);
-    openButton.setBounds (toolbar.removeFromLeft (90));
+    auto area = getLocalBounds();
+    auto toolbar = area.removeFromTop (46).reduced (8);
+
+    auto place = [&toolbar] (juce::Component& c, int width, int gapAfter = 4) {
+        c.setBounds (toolbar.removeFromLeft (width));
+        toolbar.removeFromLeft (gapAfter);
+    };
+
+    place (newButton, 56);
+    place (openButton, 56);
+    place (saveButton, 60, 16);
+    place (playButton, 60);
+    place (stopButton, 60, 8);
+    place (metronomeButton, 70);
+    place (bpmSlider, 150, 12);
+    place (patternBox, 170);
+    place (newPatternButton, 30);
 
     settingsButton.setBounds (toolbar.removeFromRight (80));
     cpuLabel.setBounds (toolbar.removeFromRight (90));
     positionLabel.setBounds (toolbar);
 
-    area.removeFromTop (8);
-    rackViewport.setBounds (area);
+    hintLabel.setBounds (area.removeFromBottom (20).reduced (8, 0));
+    tabs.setBounds (area.reduced (6, 4));
 }
 
 bool MainComponent::keyPressed (const juce::KeyPress& key)
 {
+    const auto cmd = key.getModifiers().isCommandDown();
+
     if (key == juce::KeyPress::spaceKey)
     {
         togglePlay();
         return true;
     }
 
+    if (cmd && key.getKeyCode() == 'S')
+    {
+        save (key.getModifiers().isShiftDown());
+        return true;
+    }
+
+    if (cmd && key.getKeyCode() == 'O')
+    {
+        chooseFileToOpen();
+        return true;
+    }
+
+    if (cmd && key.getKeyCode() == 'N')
+    {
+        newProject();
+        return true;
+    }
+
+    if (key.getKeyCode() == juce::KeyPress::F6Key)
+    {
+        tabs.setCurrentTabIndex (rackTab);
+        return true;
+    }
+
+    if (key.getKeyCode() == juce::KeyPress::F7Key)
+    {
+        openPianoRoll();
+        return true;
+    }
+
+    if (! cmd && ! key.getModifiers().isAltDown())
+    {
+        const auto note = keyCodeToNote (key.getKeyCode());
+
+        if (note >= 0)
+        {
+            if (heldKeys.insert (key.getKeyCode()).second)
+                engine.sendLiveNote (engine.getSelectedChannel(), note, 0.8f, true);
+            return true;
+        }
+    }
+
+    return false;
+}
+
+bool MainComponent::keyStateChanged (bool)
+{
+    // O JUCE não tem "keyReleased" por tecla; conferimos quais teclas presas foram soltas.
+    for (auto it = heldKeys.begin(); it != heldKeys.end();)
+    {
+        if (! juce::KeyPress::isKeyCurrentlyDown (*it))
+        {
+            engine.sendLiveNote (engine.getSelectedChannel(), keyCodeToNote (*it), 0.0f, false);
+            it = heldKeys.erase (it);
+        }
+        else
+            ++it;
+    }
+
     return false;
 }
 
@@ -114,7 +226,33 @@ void MainComponent::togglePlay()
     engine.getTransport().playing.load() ? engine.stop() : engine.play();
 }
 
-void MainComponent::refreshPatternList()
+void MainComponent::openPianoRoll()
+{
+    tabs.setCurrentTabIndex (pianoRollTab);
+    pianoRoll.scrollToNotes();
+}
+
+void MainComponent::selectTabForSnapshot (int tab)
+{
+    if (tab == pianoRollTab)
+    {
+        const auto& song = engine.getSong();
+        std::vector<int> counts (song.channels.size(), 0);
+
+        for (const auto& n : song.patterns[(std::size_t) song.currentPattern].notes)
+            if (n.channel >= 0 && n.channel < (int) counts.size())
+                ++counts[(std::size_t) n.channel];
+
+        if (! counts.empty())
+            engine.setSelectedChannel ((int) (std::max_element (counts.begin(), counts.end()) - counts.begin()));
+
+        openPianoRoll();
+    }
+    else
+        tabs.setCurrentTabIndex (tab);
+}
+
+void MainComponent::refreshToolbar()
 {
     const auto& song = engine.getSong();
     patternBox.clear (juce::dontSendNotification);
@@ -129,10 +267,13 @@ void MainComponent::refreshPatternList()
 void MainComponent::changeListenerCallback (juce::ChangeBroadcaster*)
 {
     const auto& song = engine.getSong();
+    bool namesChanged = patternBox.getNumItems() != (int) song.patterns.size();
 
-    if (patternBox.getNumItems() != (int) song.patterns.size() || patternBox.getSelectedItemIndex() != song.currentPattern
-        || std::abs (bpmSlider.getValue() - song.bpm) > 1e-9)
-        refreshPatternList();
+    for (int i = 0; ! namesChanged && i < patternBox.getNumItems(); ++i)
+        namesChanged = patternBox.getItemText (i) != juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str());
+
+    if (namesChanged || patternBox.getSelectedItemIndex() != song.currentPattern || std::abs (bpmSlider.getValue() - song.bpm) > 1e-9)
+        refreshToolbar();
 }
 
 void MainComponent::timerCallback()
@@ -148,41 +289,103 @@ void MainComponent::timerCallback()
     playButton.setButtonText (transport.playing.load() ? "Pause" : "Play");
     cpuLabel.setText ("CPU " + juce::String (engine.getDeviceManager().getCpuUsage() * 100.0, 1) + "%",
                       juce::dontSendNotification);
+
+    // Se um diálogo roubou o foco, devolve para o teclado do PC continuar tocando.
+    if (! hasKeyboardFocus (true) && isShowing() && juce::Process::isForegroundProcess()
+        && juce::Component::getCurrentlyModalComponent() == nullptr)
+        grabKeyboardFocus();
+}
+
+void MainComponent::updateTitle()
+{
+    if (auto* window = getTopLevelComponent())
+        window->setName (currentFile.exists() ? "Daw - " + currentFile.getFileNameWithoutExtension() : juce::String ("Daw"));
+}
+
+void MainComponent::newProject()
+{
+    engine.stop();
+    engine.rewind();
+    engine.setSong (Song::makeDefault());
+    currentFile = juce::File();
+    updateTitle();
 }
 
-void MainComponent::openFlp()
+void MainComponent::chooseFileToOpen()
 {
-    fileChooser = std::make_unique<juce::FileChooser> ("Abrir projeto do FL Studio", juce::File(), "*.flp");
+    fileChooser = std::make_unique<juce::FileChooser> ("Abrir projeto", currentFile.getParentDirectory(),
+                                                       juce::String ("*") + ProjectFile::extension + ";*.flp");
 
     fileChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
-                              [this] (const juce::FileChooser& chooser)
-                              {
-                                  const auto file = chooser.getResult();
-
-                                  if (! file.existsAsFile())
-                                      return;
-
-                                  juce::MemoryBlock data;
-
-                                  if (! file.loadFileAsData (data))
-                                      return;
-
-                                  try
-                                  {
-                                      const auto project = flp::parseProject (
-                                          { static_cast<const std::uint8_t*> (data.getData()), data.getSize() });
-
-                                      engine.stop();
-                                      engine.rewind();
-                                      engine.setSong (importFlp (project));
-                                      getTopLevelComponent()->setName ("Daw - " + file.getFileNameWithoutExtension());
-                                  }
-                                  catch (const flp::Error& e)
-                                  {
-                                      juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon,
-                                                                              "Não foi possível abrir",
-                                                                              juce::String::fromUTF8 (e.what()));
-                                  }
+                              [this] (const juce::FileChooser& chooser) {
+                                  if (chooser.getResult().existsAsFile())
+                                      openFile (chooser.getResult());
+                              });
+}
+
+void MainComponent::openFile (const juce::File& file)
+{
+    juce::String error;
+
+    if (file.hasFileExtension ("flp"))
+    {
+        if (! engine.importFlpFile (file, error))
+        {
+            juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, utf8 ("Não foi possível abrir"), error);
+            return;
+        }
+
+        currentFile = juce::File(); // importado: "Salvar" pergunta onde gravar o .dawproj
+        if (auto* window = getTopLevelComponent())
+            window->setName ("Daw - " + file.getFileNameWithoutExtension() + " (importado do FL)");
+        return;
+    }
+
+    auto song = ProjectFile::load (file, error);
+
+    if (! song)
+    {
+        juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, utf8 ("Não foi possível abrir"), error);
+        return;
+    }
+
+    engine.stop();
+    engine.rewind();
+    engine.setSong (std::move (*song));
+    currentFile = file;
+    updateTitle();
+}
+
+void MainComponent::save (bool askForFile)
+{
+    auto write = [this] (juce::File file) {
+        if (! file.hasFileExtension (ProjectFile::extension))
+            file = file.withFileExtension (ProjectFile::extension);
+
+        juce::String error;
+
+        if (ProjectFile::save (engine.getSong(), file, error))
+        {
+            currentFile = file;
+            updateTitle();
+        }
+        else
+            juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, utf8 ("Não foi possível salvar"), error);
+    };
+
+    if (! askForFile && currentFile != juce::File())
+    {
+        write (currentFile);
+        return;
+    }
+
+    fileChooser = std::make_unique<juce::FileChooser> ("Salvar projeto", currentFile.getParentDirectory(),
+                                                       juce::String ("*") + ProjectFile::extension);
+
+    fileChooser->launchAsync (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
+                              [write] (const juce::FileChooser& chooser) {
+                                  if (chooser.getResult() != juce::File())
+                                      write (chooser.getResult());
                               });
 }
 
@@ -194,7 +397,7 @@ void MainComponent::showAudioSettings()
 
     juce::DialogWindow::LaunchOptions options;
     options.content.setOwned (selector.release());
-    options.dialogTitle = "Configurações de áudio";
+    options.dialogTitle = utf8 ("Configurações de áudio");
     options.useNativeTitleBar = true;
     options.resizable = false;
     options.launchAsync();

+ 23 - 3
src/ui/MainComponent.h

@@ -1,9 +1,12 @@
 #pragma once
 
+#include <set>
+
 #include <juce_gui_basics/juce_gui_basics.h>
 
 #include "engine/AudioEngine.h"
 #include "ui/ChannelRackComponent.h"
+#include "ui/PianoRollComponent.h"
 
 namespace daw
 {
@@ -18,31 +21,48 @@ public:
     void paint (juce::Graphics& g) override;
     void resized() override;
     bool keyPressed (const juce::KeyPress& key) override;
+    bool keyStateChanged (bool isKeyDown) override;
+
+    // Abre .dawproj ou .flp (também usado pela linha de comando).
+    void openFile (const juce::File& file);
+
+    // Para o modo --snapshot: 0 = Channel Rack, 1 = Piano Roll (no canal com mais notas).
+    void selectTabForSnapshot (int tab);
 
 private:
     void timerCallback() override;
     void changeListenerCallback (juce::ChangeBroadcaster*) override;
     void togglePlay();
     void showAudioSettings();
-    void openFlp();
-    void refreshPatternList();
+    void newProject();
+    void chooseFileToOpen();
+    void save (bool askForFile);
+    void refreshToolbar();
+    void updateTitle();
+    void openPianoRoll();
 
     AudioEngine& engine;
 
+    juce::TextButton newButton { "Novo" }, openButton { "Abrir" }, saveButton { "Salvar" };
     juce::TextButton playButton { "Play" };
     juce::TextButton stopButton { "Stop" };
     juce::ToggleButton metronomeButton { "Metro" };
     juce::Slider bpmSlider { juce::Slider::IncDecButtons, juce::Slider::TextBoxLeft };
     juce::ComboBox patternBox;
     juce::TextButton newPatternButton { "+" };
-    juce::TextButton openButton { "Abrir .flp" };
     juce::TextButton settingsButton { "Audio..." };
     juce::Label positionLabel;
     juce::Label cpuLabel;
+    juce::Label hintLabel;
 
     ChannelRackComponent rack;
     juce::Viewport rackViewport;
+    PianoRollComponent pianoRoll;
+    juce::TabbedComponent tabs { juce::TabbedButtonBar::TabsAtTop };
+
     std::unique_ptr<juce::FileChooser> fileChooser;
+    juce::File currentFile;
+    std::set<int> heldKeys; // teclas do teclado do PC tocando notas agora (keyCode)
 
     JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainComponent)
 };

+ 534 - 0
src/ui/PianoRollComponent.cpp

@@ -0,0 +1,534 @@
+#include "ui/PianoRollComponent.h"
+
+#include "ui/Theme.h"
+
+namespace daw
+{
+namespace
+{
+bool isBlackKey (int key)
+{
+    const auto n = key % 12;
+    return n == 1 || n == 3 || n == 6 || n == 8 || n == 10;
+}
+
+// Nome no padrão do FL: tecla 60 = C5.
+juce::String keyName (int key)
+{
+    static const char* names[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
+    return juce::String (names[key % 12]) + juce::String (key / 12);
+}
+
+const Pattern& currentPattern (const Song& s)
+{
+    return s.patterns[(std::size_t) s.currentPattern];
+}
+} // namespace
+
+PianoRollComponent::PianoRollComponent (AudioEngine& e)
+    : engine (e)
+{
+    setWantsKeyboardFocus (false);
+    setMouseClickGrabsKeyboardFocus (false);
+
+    for (auto* bar : { &hBar, &vBar })
+    {
+        bar->addListener (this);
+        bar->setAutoHide (false);
+        addAndMakeVisible (bar);
+    }
+
+    engine.addChangeListener (this);
+    startTimerHz (30);
+}
+
+PianoRollComponent::~PianoRollComponent()
+{
+    engine.removeChangeListener (this);
+}
+
+juce::Rectangle<int> PianoRollComponent::gridArea() const
+{
+    return getLocalBounds().withTrimmedLeft (keyboardWidth).withTrimmedTop (timelineHeight)
+        .withTrimmedRight (scrollBarSize).withTrimmedBottom (scrollBarSize);
+}
+
+double PianoRollComponent::tickToX (double tick) const
+{
+    return keyboardWidth + (tick - scrollTicks) * pixelsPerTick;
+}
+
+double PianoRollComponent::xToTick (int x) const
+{
+    return (x - keyboardWidth) / pixelsPerTick + scrollTicks;
+}
+
+int PianoRollComponent::keyToY (int key) const
+{
+    return timelineHeight + (127 - key) * rowHeight - scrollY;
+}
+
+int PianoRollComponent::yToKey (int y) const
+{
+    return juce::jlimit (0, 127, 127 - (y - timelineHeight + scrollY) / rowHeight);
+}
+
+std::int64_t PianoRollComponent::snap (double tick, bool enabled) const
+{
+    if (! enabled)
+        return (std::int64_t) std::floor (tick);
+
+    return (std::int64_t) std::floor (tick / ticksPerStep) * ticksPerStep;
+}
+
+std::int64_t PianoRollComponent::viewLengthTicks() const
+{
+    const auto& song = engine.getSong();
+    const auto bar = (std::int64_t) ppq * song.beatsPerBar;
+    // pattern + 4 compassos de folga para crescer
+    return currentPattern (song).effectiveLength (song.beatsPerBar) + 4 * bar;
+}
+
+void PianoRollComponent::updateScrollBars()
+{
+    const auto grid = gridArea();
+    const auto total = (double) viewLengthTicks();
+    hBar.setRangeLimits (0.0, total, juce::dontSendNotification);
+    hBar.setCurrentRange (scrollTicks, grid.getWidth() / pixelsPerTick, juce::dontSendNotification);
+    vBar.setRangeLimits (0.0, 128.0 * rowHeight, juce::dontSendNotification);
+    vBar.setCurrentRange (scrollY, grid.getHeight(), juce::dontSendNotification);
+    scrollTicks = hBar.getCurrentRangeStart();
+    scrollY = (int) vBar.getCurrentRangeStart();
+}
+
+void PianoRollComponent::resized()
+{
+    hBar.setBounds (keyboardWidth, getHeight() - scrollBarSize, getWidth() - keyboardWidth - scrollBarSize, scrollBarSize);
+    vBar.setBounds (getWidth() - scrollBarSize, timelineHeight, scrollBarSize, getHeight() - timelineHeight - scrollBarSize);
+    updateScrollBars();
+}
+
+void PianoRollComponent::scrollToNotes()
+{
+    const auto& song = engine.getSong();
+    const auto channel = engine.getSelectedChannel();
+    int low = 128, high = -1;
+
+    for (const auto& n : currentPattern (song).notes)
+        if (n.channel == channel)
+        {
+            low = juce::jmin (low, n.key);
+            high = juce::jmax (high, n.key);
+        }
+
+    const auto centreKey = high >= 0 ? (low + high) / 2 : 66;
+    scrollY = (127 - centreKey) * rowHeight - gridArea().getHeight() / 2;
+    scrollTicks = 0.0;
+    updateScrollBars();
+    repaint();
+}
+
+void PianoRollComponent::paint (juce::Graphics& g)
+{
+    const auto& song = engine.getSong();
+    const auto& pattern = currentPattern (song);
+    const auto channel = engine.getSelectedChannel();
+    const auto grid = gridArea();
+    const auto patternLength = pattern.effectiveLength (song.beatsPerBar);
+    const auto bar = (std::int64_t) ppq * song.beatsPerBar;
+
+    g.fillAll (theme::window);
+
+    // --- grade -----------------------------------------------------------
+    {
+        juce::Graphics::ScopedSaveState state (g);
+        g.reduceClipRegion (grid);
+
+        for (int key = 0; key < 128; ++key)
+        {
+            const auto y = keyToY (key);
+
+            if (y > grid.getBottom() || y + rowHeight < grid.getY())
+                continue;
+
+            g.setColour (isBlackKey (key) ? juce::Colour (0xff262b30) : juce::Colour (0xff30363d));
+            g.fillRect (grid.getX(), y, grid.getWidth(), rowHeight);
+
+            if (key % 12 == 0)
+            {
+                g.setColour (juce::Colour (0xff1a1d21));
+                g.drawHorizontalLine (y + rowHeight - 1, (float) grid.getX(), (float) grid.getRight());
+            }
+        }
+
+        const auto firstStep = (std::int64_t) std::floor (scrollTicks / ticksPerStep);
+        const auto lastStep = (std::int64_t) std::ceil (xToTick (grid.getRight()) / ticksPerStep);
+
+        for (auto step = firstStep; step <= lastStep; ++step)
+        {
+            const auto tick = step * ticksPerStep;
+            const auto x = (float) tickToX ((double) tick);
+            g.setColour (tick % bar == 0 ? juce::Colour (0xff15181b) : tick % ppq == 0 ? juce::Colour (0xff22272c) : juce::Colour (0xff2a2f35));
+            g.drawVerticalLine ((int) x, (float) grid.getY(), (float) grid.getBottom());
+        }
+
+        // fora da pattern fica escurecido
+        const auto endX = (float) tickToX ((double) patternLength);
+        g.setColour (juce::Colours::black.withAlpha (0.35f));
+        g.fillRect (juce::Rectangle<float> (endX, (float) grid.getY(), (float) grid.getRight() - endX, (float) grid.getHeight()));
+
+        // ghost notes
+        for (const auto& n : pattern.notes)
+        {
+            if (n.channel == channel)
+                continue;
+
+            const auto r = juce::Rectangle<float> ((float) tickToX ((double) n.start), (float) keyToY (n.key) + 1,
+                                                   (float) (n.length * pixelsPerTick), (float) rowHeight - 2);
+            g.setColour (juce::Colours::white.withAlpha (0.08f));
+            g.fillRoundedRectangle (r, 2.0f);
+        }
+
+        for (const auto& n : pattern.notes)
+        {
+            if (n.channel != channel)
+                continue;
+
+            const auto r = juce::Rectangle<float> ((float) tickToX ((double) n.start), (float) keyToY (n.key) + 1,
+                                                   juce::jmax (4.0f, (float) (n.length * pixelsPerTick) - 1.0f), (float) rowHeight - 2);
+            g.setColour (theme::noteColour (n.velocity));
+            g.fillRoundedRectangle (r, 2.5f);
+            g.setColour (juce::Colours::black.withAlpha (0.5f));
+            g.drawRoundedRectangle (r, 2.5f, 1.0f);
+
+            if (r.getWidth() > 30)
+            {
+                g.setColour (juce::Colours::black.withAlpha (0.7f));
+                g.setFont (juce::FontOptions (10.0f));
+                g.drawText (keyName (n.key), r.reduced (3, 0), juce::Justification::centredLeft, false);
+            }
+        }
+
+        if (playheadTick >= 0.0)
+        {
+            g.setColour (theme::playhead);
+            g.drawVerticalLine ((int) tickToX (playheadTick), (float) grid.getY(), (float) grid.getBottom());
+        }
+    }
+
+    // --- régua de tempo ----------------------------------------------------
+    {
+        const auto ruler = juce::Rectangle<int> (keyboardWidth, 0, grid.getWidth(), timelineHeight);
+        g.setColour (theme::toolbar);
+        g.fillRect (ruler);
+        juce::Graphics::ScopedSaveState state (g);
+        g.reduceClipRegion (ruler);
+        g.setFont (juce::FontOptions (12.0f));
+
+        const auto firstBar = (std::int64_t) std::floor (scrollTicks / (double) bar);
+        const auto lastBar = (std::int64_t) std::ceil (xToTick (grid.getRight()) / (double) bar);
+
+        for (auto b = firstBar; b <= lastBar; ++b)
+        {
+            const auto x = (int) tickToX ((double) (b * bar));
+            g.setColour (theme::text.withAlpha (0.7f));
+            g.drawVerticalLine (x, 10.0f, (float) timelineHeight);
+            g.drawText (juce::String (b + 1), x + 3, 2, 40, timelineHeight - 4, juce::Justification::centredLeft);
+        }
+
+        if (playheadTick >= 0.0)
+        {
+            const auto x = (float) tickToX (playheadTick);
+            juce::Path tri;
+            tri.addTriangle (x - 5, 0, x + 5, 0, x, 8);
+            g.setColour (theme::playhead);
+            g.fillPath (tri);
+        }
+    }
+
+    // --- teclado -------------------------------------------------------------
+    {
+        const auto keys = juce::Rectangle<int> (0, timelineHeight, keyboardWidth, grid.getHeight());
+        juce::Graphics::ScopedSaveState state (g);
+        g.reduceClipRegion (keys);
+        g.setFont (juce::FontOptions (10.0f));
+
+        for (int key = 0; key < 128; ++key)
+        {
+            const auto y = keyToY (key);
+
+            if (y > keys.getBottom() || y + rowHeight < keys.getY())
+                continue;
+
+            const auto black = isBlackKey (key);
+            const auto pressed = key == previewKey;
+            g.setColour (pressed ? theme::accentOrange : black ? juce::Colour (0xff1c1c1c) : juce::Colour (0xffdedede));
+            g.fillRect (0, y, black ? keyboardWidth * 2 / 3 : keyboardWidth, rowHeight);
+            g.setColour (juce::Colour (0xff888888));
+            g.drawHorizontalLine (y + rowHeight - 1, 0.0f, (float) keyboardWidth);
+
+            if (key % 12 == 0)
+            {
+                g.setColour (juce::Colours::black);
+                g.drawText (keyName (key), keyboardWidth - 30, y, 28, rowHeight, juce::Justification::centredRight);
+            }
+        }
+    }
+
+    // canto superior esquerdo: nome do canal
+    g.setColour (theme::toolbar);
+    g.fillRect (0, 0, keyboardWidth, timelineHeight);
+
+    if (channel < (int) song.channels.size())
+    {
+        g.setColour (theme::accentOrange);
+        g.setFont (juce::FontOptions (11.0f));
+        g.drawText (juce::String::fromUTF8 (song.channels[(std::size_t) channel].name.c_str()), 4, 0, keyboardWidth - 6,
+                    timelineHeight, juce::Justification::centredLeft, true);
+    }
+}
+
+int PianoRollComponent::noteAt (int x, int y, bool& onRightEdge) const
+{
+    const auto& notes = currentPattern (engine.getSong()).notes;
+    const auto channel = engine.getSelectedChannel();
+    const auto key = yToKey (y);
+
+    // de trás para frente: a nota desenhada por cima ganha
+    for (int i = (int) notes.size() - 1; i >= 0; --i)
+    {
+        const auto& n = notes[(std::size_t) i];
+
+        if (n.channel != channel || n.key != key)
+            continue;
+
+        const auto x0 = tickToX ((double) n.start);
+        const auto x1 = tickToX ((double) (n.start + n.length));
+
+        if (x >= x0 && x < juce::jmax (x1, x0 + 4.0))
+        {
+            onRightEdge = x >= x1 - 6.0;
+            return i;
+        }
+    }
+
+    return -1;
+}
+
+void PianoRollComponent::previewOn (int key, float velocity)
+{
+    previewOff();
+    previewKey = key;
+    engine.sendLiveNote (engine.getSelectedChannel(), key, velocity, true);
+    repaint (0, timelineHeight, keyboardWidth, getHeight());
+}
+
+void PianoRollComponent::previewOff()
+{
+    if (previewKey >= 0)
+    {
+        engine.sendLiveNote (engine.getSelectedChannel(), previewKey, 0.0f, false);
+        previewKey = -1;
+        repaint (0, timelineHeight, keyboardWidth, getHeight());
+    }
+}
+
+void PianoRollComponent::mouseDown (const juce::MouseEvent& e)
+{
+    if (engine.getSong().channels.empty())
+        return;
+
+    if (e.x < keyboardWidth && e.y >= timelineHeight)
+    {
+        drag = Drag::keyboard;
+        previewOn (yToKey (e.y), 0.8f);
+        return;
+    }
+
+    if (! gridArea().contains (e.getPosition()))
+        return;
+
+    bool rightEdge = false;
+    const auto hit = noteAt (e.x, e.y, rightEdge);
+
+    if (e.mods.isRightButtonDown())
+    {
+        drag = Drag::erase;
+
+        if (hit >= 0)
+            engine.editSong ([hit] (Song& s) {
+                auto& notes = s.patterns[(std::size_t) s.currentPattern].notes;
+                notes.erase (notes.begin() + hit);
+            });
+        return;
+    }
+
+    const auto snapOn = ! e.mods.isAltDown();
+
+    if (hit >= 0)
+    {
+        const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) hit];
+        dragNote = hit;
+        drag = rightEdge ? Drag::resize : Drag::move;
+        grabOffset = n.start - snap (xToTick (e.x), snapOn);
+        lastLength = n.length;
+        previewOn (n.key, n.velocity);
+        return;
+    }
+
+    // nota nova
+    Note n;
+    n.start = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
+    n.length = lastLength;
+    n.key = yToKey (e.y);
+    n.channel = engine.getSelectedChannel();
+
+    engine.editSong ([n] (Song& s) { s.patterns[(std::size_t) s.currentPattern].notes.push_back (n); });
+    dragNote = (int) currentPattern (engine.getSong()).notes.size() - 1;
+    drag = Drag::move;
+    grabOffset = 0;
+    previewOn (n.key, n.velocity);
+}
+
+void PianoRollComponent::mouseDrag (const juce::MouseEvent& e)
+{
+    const auto snapOn = ! e.mods.isAltDown();
+
+    switch (drag)
+    {
+        case Drag::none:
+            return;
+
+        case Drag::keyboard:
+        {
+            const auto key = yToKey (e.y);
+            if (key != previewKey)
+                previewOn (key, 0.8f);
+            return;
+        }
+
+        case Drag::erase:
+        {
+            bool edge = false;
+            const auto hit = noteAt (e.x, e.y, edge);
+
+            if (hit >= 0)
+                engine.editSong ([hit] (Song& s) {
+                    auto& notes = s.patterns[(std::size_t) s.currentPattern].notes;
+                    notes.erase (notes.begin() + hit);
+                });
+            return;
+        }
+
+        case Drag::move:
+        {
+            const auto start = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn) + grabOffset);
+            const auto key = yToKey (e.y);
+            const auto index = dragNote;
+            const auto& current = currentPattern (engine.getSong()).notes[(std::size_t) index];
+
+            if (current.start == start && current.key == key)
+                return;
+
+            if (current.key != key)
+                previewOn (key, current.velocity);
+
+            // sem reordenar durante o arraste, para o índice continuar válido
+            engine.editSong ([index, start, key] (Song& s) {
+                auto& n = s.patterns[(std::size_t) s.currentPattern].notes[(std::size_t) index];
+                n.start = start;
+                n.key = key;
+            });
+            return;
+        }
+
+        case Drag::resize:
+        {
+            const auto index = dragNote;
+            const auto& current = currentPattern (engine.getSong()).notes[(std::size_t) index];
+            const auto minimum = snapOn ? (std::int64_t) ticksPerStep : (std::int64_t) 10;
+            auto end = snapOn ? snap (xToTick (e.x) + ticksPerStep / 2.0, true) : (std::int64_t) xToTick (e.x);
+            const auto length = juce::jmax (minimum, end - current.start);
+
+            if (length == current.length)
+                return;
+
+            lastLength = length;
+            engine.editSong ([index, length] (Song& s) {
+                s.patterns[(std::size_t) s.currentPattern].notes[(std::size_t) index].length = length;
+            });
+            return;
+        }
+    }
+}
+
+void PianoRollComponent::mouseUp (const juce::MouseEvent&)
+{
+    if (drag == Drag::move || drag == Drag::resize)
+        engine.editSong ([] (Song& s) { s.patterns[(std::size_t) s.currentPattern].sortNotes(); });
+
+    previewOff();
+    drag = Drag::none;
+    dragNote = -1;
+}
+
+void PianoRollComponent::mouseMove (const juce::MouseEvent& e)
+{
+    bool rightEdge = false;
+    const auto hit = gridArea().contains (e.getPosition()) ? noteAt (e.x, e.y, rightEdge) : -1;
+    setMouseCursor (hit >= 0 ? (rightEdge ? juce::MouseCursor::LeftRightResizeCursor : juce::MouseCursor::DraggingHandCursor)
+                             : juce::MouseCursor::NormalCursor);
+}
+
+void PianoRollComponent::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
+{
+    if (e.mods.isCtrlDown())
+    {
+        // zoom mantendo o tick sob o mouse no lugar
+        const auto anchor = xToTick (e.x);
+        pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick * (wheel.deltaY > 0 ? 1.2 : 1.0 / 1.2));
+        scrollTicks = juce::jmax (0.0, anchor - (e.x - keyboardWidth) / pixelsPerTick);
+    }
+    else if (e.mods.isShiftDown())
+        scrollTicks = juce::jmax (0.0, scrollTicks - wheel.deltaY * 400.0 / pixelsPerTick * 0.25);
+    else
+        scrollY = juce::jlimit (0, 128 * rowHeight, scrollY - (int) (wheel.deltaY * 200.0f));
+
+    updateScrollBars();
+    repaint();
+}
+
+void PianoRollComponent::scrollBarMoved (juce::ScrollBar* bar, double start)
+{
+    if (bar == &hBar)
+        scrollTicks = start;
+    else
+        scrollY = (int) start;
+
+    repaint();
+}
+
+void PianoRollComponent::changeListenerCallback (juce::ChangeBroadcaster*)
+{
+    updateScrollBars();
+    repaint();
+}
+
+void PianoRollComponent::timerCallback()
+{
+    auto& transport = engine.getTransport();
+    auto tick = -1.0;
+
+    if (transport.playing.load() && isShowing())
+    {
+        const auto& song = engine.getSong();
+        tick = std::fmod (transport.positionTicks.load(), (double) currentPattern (song).effectiveLength (song.beatsPerBar));
+    }
+
+    if (tick != playheadTick)
+    {
+        playheadTick = tick;
+        repaint();
+    }
+}
+} // namespace daw

+ 76 - 0
src/ui/PianoRollComponent.h

@@ -0,0 +1,76 @@
+#pragma once
+
+#include <juce_gui_basics/juce_gui_basics.h>
+
+#include "engine/AudioEngine.h"
+
+namespace daw
+{
+// Piano Roll do canal selecionado na pattern atual.
+//  - clique esquerdo no vazio cria uma nota (com a última duração usada) e já permite arrastar
+//  - arrastar o corpo move; arrastar a borda direita muda a duração
+//  - clique direito apaga (arrastar apaga várias)
+//  - Alt desliga o snap; roda do mouse rola, Shift+roda rola na horizontal, Ctrl+roda dá zoom
+//  - teclado à esquerda toca a nota
+// Notas de outros canais aparecem apagadas ao fundo, como "ghost notes" no FL.
+class PianoRollComponent final : public juce::Component,
+                                 private juce::ChangeListener,
+                                 private juce::Timer,
+                                 private juce::ScrollBar::Listener
+{
+public:
+    explicit PianoRollComponent (AudioEngine& engine);
+    ~PianoRollComponent() override;
+
+    void paint (juce::Graphics& g) override;
+    void resized() override;
+    void mouseDown (const juce::MouseEvent& e) override;
+    void mouseDrag (const juce::MouseEvent& e) override;
+    void mouseUp (const juce::MouseEvent& e) override;
+    void mouseMove (const juce::MouseEvent& e) override;
+    void mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel) override;
+
+    // Centraliza a vista nas notas do canal (chamado ao abrir).
+    void scrollToNotes();
+
+    static constexpr int keyboardWidth = 64;
+    static constexpr int timelineHeight = 22;
+    static constexpr int rowHeight = 14;
+    static constexpr int scrollBarSize = 12;
+
+private:
+    enum class Drag { none, move, resize, erase, keyboard };
+
+    void changeListenerCallback (juce::ChangeBroadcaster*) override;
+    void timerCallback() override;
+    void scrollBarMoved (juce::ScrollBar*, double) override;
+
+    juce::Rectangle<int> gridArea() const;
+    double tickToX (double tick) const;
+    double xToTick (int x) const;
+    int keyToY (int key) const;
+    int yToKey (int y) const;
+    std::int64_t snap (double tick, bool enabled) const;
+    std::int64_t viewLengthTicks() const;
+    int noteAt (int x, int y, bool& onRightEdge) const;
+    void updateScrollBars();
+    void previewOn (int key, float velocity);
+    void previewOff();
+
+    AudioEngine& engine;
+    juce::ScrollBar hBar { false }, vBar { true };
+
+    double pixelsPerTick = 24.0 / ticksPerStep; // 24 px por step
+    double scrollTicks = 0.0;
+    int scrollY = (127 - 84) * rowHeight;       // começa mostrando por volta do C6..C3
+
+    Drag drag = Drag::none;
+    int dragNote = -1;
+    std::int64_t grabOffset = 0;  // tick da nota - tick do mouse no início do arraste
+    std::int64_t lastLength = ticksPerStep * 2;
+    int previewKey = -1;
+    double playheadTick = -1.0;
+
+    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PianoRollComponent)
+};
+} // namespace daw

+ 56 - 0
src/ui/Theme.h

@@ -0,0 +1,56 @@
+#pragma once
+
+#include <juce_gui_basics/juce_gui_basics.h>
+
+// Paleta e LookAndFeel: tons de cinza-azulado escuros, destaques em laranja,
+// verde e azul, no espírito do FL Studio.
+namespace daw::theme
+{
+inline const juce::Colour window { 0xff1e2226 };
+inline const juce::Colour panel { 0xff2b3036 };
+inline const juce::Colour toolbar { 0xff32383f };
+inline const juce::Colour channelButton { 0xff434a52 };
+inline const juce::Colour channelButtonSelected { 0xff56606b };
+inline const juce::Colour knobBackground { 0xff1b1e22 };
+inline const juce::Colour stepOn { 0xffe8e8e8 };
+inline const juce::Colour stepOnOffGrid { 0xff9fd3ff };
+inline const juce::Colour accentOrange { 0xffff9a3c };
+inline const juce::Colour accentGreen { 0xff7ed957 };
+inline const juce::Colour accentBlue { 0xff58b7ff };
+inline const juce::Colour playhead { 0xff30c0ff };
+inline const juce::Colour text { 0xffe6e6e6 };
+
+inline juce::Colour stepOff (int step)
+{
+    return (step / 4) % 2 == 0 ? juce::Colour (0xff4a525b) : juce::Colour (0xff5b4f4f); // grupos de 4 alternados
+}
+
+inline juce::Colour muteLed (bool muted)
+{
+    return muted ? juce::Colour (0xff505050) : accentGreen;
+}
+
+// Cor de nota no Piano Roll pela velocity (fraca = esverdeada, forte = laranja).
+inline juce::Colour noteColour (float velocity)
+{
+    return juce::Colour (0xff7ed957).interpolatedWith (accentOrange, juce::jlimit (0.0f, 1.0f, velocity));
+}
+
+class LookAndFeel final : public juce::LookAndFeel_V4
+{
+public:
+    LookAndFeel()
+        : juce::LookAndFeel_V4 (juce::LookAndFeel_V4::ColourScheme {
+              window, panel, toolbar, juce::Colour (0xff4d5560), text, toolbar, juce::Colours::white, accentOrange,
+              text })
+    {
+        setColour (juce::TextButton::buttonOnColourId, accentOrange.darker (0.3f));
+        setColour (juce::ComboBox::backgroundColourId, panel);
+        setColour (juce::TabbedButtonBar::tabOutlineColourId, juce::Colours::transparentBlack);
+        setColour (juce::TabbedButtonBar::frontOutlineColourId, juce::Colours::transparentBlack);
+        setColour (juce::TabbedComponent::outlineColourId, juce::Colours::transparentBlack);
+        setColour (juce::TabbedButtonBar::tabTextColourId, text.withAlpha (0.6f));
+        setColour (juce::TabbedButtonBar::frontTextColourId, accentOrange);
+    }
+};
+} // namespace daw::theme

+ 135 - 0
tests/tests.cpp

@@ -11,9 +11,11 @@
 #include <vector>
 
 #include "core/FlpImport.h"
+#include "core/LiveEventQueue.h"
 #include "core/RackRenderer.h"
 #include "core/Scheduler.h"
 #include "core/SnapshotExchange.h"
+#include "core/SoftClip.h"
 #include "core/Song.h"
 #include "flp/Flp.h"
 
@@ -474,6 +476,139 @@ TEST (flp_import_maps_channels_and_rescales)
     CHECK (std::abs (s.patterns[0].notes[0].velocity - 0.5f) < 1e-6f);
 }
 
+TEST (live_queue_is_fifo_and_bounded)
+{
+    daw::LiveEventQueue q;
+    daw::NoteEvent e;
+    CHECK (! q.pop (e));
+
+    for (int i = 0; i < 10; ++i)
+    {
+        daw::NoteEvent in;
+        in.key = i;
+        CHECK (q.push (in));
+    }
+
+    for (int i = 0; i < 10; ++i)
+        CHECK (q.pop (e) && e.key == i);
+
+    int pushed = 0;
+    while (q.push (e))
+        ++pushed;
+    CHECK (pushed == (int) daw::LiveEventQueue::capacity - 1); // uma vaga fica livre para distinguir cheio de vazio
+}
+
+TEST (sampler_plays_pitched_one_shot)
+{
+    // sample de 1000 frames com rampa: dá para medir a posição pela amplitude
+    auto data = std::make_shared<daw::SampleData>();
+    data->sampleRate = 48000.0;
+    for (int i = 0; i < 1000; ++i)
+        data->left.push_back (1.0f);
+
+    auto sampler = daw::makeInstrument (daw::InstrumentKind::sampler, data);
+    sampler->prepare (48000.0);
+    std::vector<float> l (2048, 0.0f), r (2048, 0.0f);
+
+    sampler->noteOn (60, 1.0f);
+    sampler->noteOff (60); // one-shot: noteOff não corta
+    sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
+    int sounding = 0;
+    for (auto s : l)
+        sounding += s > 0.5f;
+    CHECK (sounding >= 995 && sounding <= 1000); // toca o sample inteiro na altura original
+
+    std::fill (l.begin(), l.end(), 0.0f);
+    sampler->noteOn (72, 1.0f); // uma oitava acima: metade da duração
+    sampler->render (l.data(), r.data(), 2048, 1.0f, 1.0f);
+    sounding = 0;
+    for (auto s : l)
+        sounding += s > 0.5f;
+    CHECK (sounding >= 495 && sounding <= 500);
+    CHECK (r[10] > 0.5f); // mono vai para os dois lados
+
+    auto silent = daw::makeInstrument (daw::InstrumentKind::sampler, nullptr);
+    silent->prepare (48000.0);
+    silent->noteOn (60, 1.0f);
+    std::fill (l.begin(), l.end(), 0.0f);
+    silent->render (l.data(), r.data(), 64, 1.0f, 1.0f);
+    CHECK (l[0] == 0.0f);
+}
+
+TEST (rack_live_notes_and_sample_provider)
+{
+    daw::Song song;
+    daw::ChannelDef c;
+    c.name = "Smp";
+    c.instrument = daw::InstrumentKind::sampler;
+    c.samplePath = "a.wav";
+    song.channels.push_back (c);
+    song.patterns.emplace_back();
+
+    int loads = 0;
+    auto provider = [&] (const std::string& path) -> std::shared_ptr<const daw::SampleData> {
+        ++loads;
+        CHECK (path == "a.wav");
+        auto d = std::make_shared<daw::SampleData>();
+        d->left.assign (4800, 0.5f);
+        return d;
+    };
+
+    auto state = daw::RackState::build (song, nullptr, 48000.0, provider);
+    CHECK (loads == 1);
+
+    daw::RackRenderer renderer;
+    renderer.prepare (48000.0);
+    daw::LiveEventQueue live;
+    daw::NoteEvent on;
+    on.channel = 0;
+    on.velocity = 1.0f;
+    live.push (on);
+
+    std::vector<float> l (256), r (256);
+    renderer.process (state.get(), false, 0.0, 256, l.data(), r.data(), &live); // parado, mas a nota ao vivo toca
+    CHECK (l[0] > 0.1f);
+
+    // mesmo sample: reaproveita; sample diferente: recarrega
+    auto same = daw::RackState::build (song, state.get(), 48000.0, provider);
+    CHECK (loads == 1 && same->instruments[0] == state->instruments[0]);
+    song.channels[0].samplePath = "b.wav";
+    auto other = daw::RackState::build (song, state.get(), 48000.0, [&] (const std::string&) { ++loads; return nullptr; });
+    CHECK (loads == 2 && other->instruments[0] != state->instruments[0]);
+}
+
+TEST (flp_paths_resolve_and_samplers_import)
+{
+    daw::FlPathRoots roots { "C:\\FL", "C:\\FL\\Data", "D:\\User" };
+    CHECK (daw::resolveFlPath ("%FLStudioFactoryData%\\Data\\x.wav", roots) == "C:\\FL\\Data\\x.wav");
+    CHECK (daw::resolveFlPath ("%FLStudioData%\\Patches\\y.wav", roots) == "C:\\FL\\Data\\Patches\\y.wav");
+    CHECK (daw::resolveFlPath ("%FLStudioUserData%\\z.wav", roots) == "D:\\User\\z.wav");
+    CHECK (daw::resolveFlPath ("E:\\abs.wav", roots) == "E:\\abs.wav");
+    CHECK (daw::resolveFlPath ("%FLStudioUserData%\\z.wav", {}) == "");
+
+    flp::Project p;
+    p.channels = { { 0, flp::ChannelType::sampler, "Kick", "", "%FLStudioData%\\k.wav", 1 },
+                   { 1, flp::ChannelType::sampler, "Hat", "", "%FLStudioData%\\missing.wav", 1 } };
+    daw::FlpImportOptions options;
+    options.roots = roots;
+    options.fileExists = [] (const std::string& path) { return path == "C:\\FL\\Data\\k.wav"; };
+
+    const auto s = daw::importFlp (p, options);
+    CHECK (s.channels[0].instrument == daw::InstrumentKind::sampler);
+    CHECK (s.channels[0].samplePath == "C:\\FL\\Data\\k.wav");
+    CHECK (s.channels[1].instrument == daw::InstrumentKind::hat); // sem arquivo: instrumento interno
+}
+
+TEST (soft_clip_is_transparent_below_knee_and_bounded)
+{
+    float s[] = { 0.5f, -0.89f, 1.5f, -3.0f, 0.95f };
+    daw::softClip (s, 5);
+    CHECK (s[0] == 0.5f && s[1] == -0.89f);
+    CHECK (s[2] > 0.9f && s[2] <= 1.0f);
+    CHECK (s[3] < -0.9f && s[3] >= -1.0f);
+    CHECK (s[4] > 0.9f && s[4] < 0.95f);
+}
+
 int main (int argc, char** argv)
 {
     if (argc > 1)

+ 103 - 0
tools/WavReader.h

@@ -0,0 +1,103 @@
+#pragma once
+
+// Leitor mínimo de WAV (PCM 8/16/24/32 e float 32) para as ferramentas e testes.
+// O app usa os leitores do JUCE, que cobrem bem mais formatos.
+
+#include <cstdint>
+#include <cstring>
+#include <fstream>
+#include <iterator>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "core/Instruments.h"
+
+namespace daw::tools
+{
+inline std::shared_ptr<const SampleData> readWav (const std::string& path)
+{
+    std::ifstream in (path, std::ios::binary);
+
+    if (! in)
+        return nullptr;
+
+    std::vector<std::uint8_t> d ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
+
+    if (d.size() < 12 || std::memcmp (d.data(), "RIFF", 4) != 0 || std::memcmp (d.data() + 8, "WAVE", 4) != 0)
+        return nullptr;
+
+    auto u16 = [&] (std::size_t o) { return (std::uint16_t) (d[o] | (d[o + 1] << 8)); };
+    auto u32 = [&] (std::size_t o) { return (std::uint32_t) (u16 (o) | ((std::uint32_t) u16 (o + 2) << 16)); };
+
+    std::uint16_t format = 0, channels = 0, bits = 0;
+    std::uint32_t rate = 0;
+    const std::uint8_t* data = nullptr;
+    std::size_t dataSize = 0;
+
+    for (std::size_t pos = 12; pos + 8 <= d.size();)
+    {
+        const auto size = u32 (pos + 4);
+        const auto body = pos + 8;
+
+        if (std::memcmp (&d[pos], "fmt ", 4) == 0 && body + 16 <= d.size())
+        {
+            format = u16 (body);
+            channels = u16 (body + 2);
+            rate = u32 (body + 4);
+            bits = u16 (body + 14);
+
+            if (format == 0xFFFE && size >= 26) // WAVE_FORMAT_EXTENSIBLE: subformato nos 2 primeiros bytes do GUID
+                format = u16 (body + 24);
+        }
+        else if (std::memcmp (&d[pos], "data", 4) == 0)
+        {
+            data = &d[body];
+            dataSize = std::min<std::size_t> (size, d.size() - body);
+        }
+
+        pos = body + size + (size & 1);
+    }
+
+    if (data == nullptr || channels == 0 || rate == 0 || bits == 0 || (format != 1 && format != 3))
+        return nullptr;
+
+    const auto bytesPerSample = bits / 8u;
+    const auto frames = dataSize / (bytesPerSample * channels);
+    auto sample = std::make_shared<SampleData>();
+    sample->sampleRate = rate;
+    sample->left.resize (frames);
+
+    if (channels > 1)
+        sample->right.resize (frames);
+
+    auto read = [&] (const std::uint8_t* p) -> float {
+        if (format == 3 && bits == 32)
+        {
+            float f;
+            std::memcpy (&f, p, 4);
+            return f;
+        }
+
+        switch (bits)
+        {
+            case 8: return (p[0] - 128) / 128.0f;
+            case 16: return (std::int16_t) (p[0] | (p[1] << 8)) / 32768.0f;
+            case 24: return (std::int32_t) ((p[0] << 8) | (p[1] << 16) | ((std::uint32_t) p[2] << 24)) / 2147483648.0f;
+            case 32: return (std::int32_t) (p[0] | (p[1] << 8) | (p[2] << 16) | ((std::uint32_t) p[3] << 24)) / 2147483648.0f;
+            default: return 0.0f;
+        }
+    };
+
+    for (std::size_t i = 0; i < frames; ++i)
+    {
+        const auto* frame = data + i * bytesPerSample * channels;
+        sample->left[i] = read (frame);
+
+        if (channels > 1)
+            sample->right[i] = read (frame + bytesPerSample);
+    }
+
+    return sample;
+}
+} // namespace daw::tools

+ 28 - 3
tools/renderwav.cpp

@@ -8,6 +8,11 @@
 #include <iterator>
 #include <vector>
 
+#include <algorithm>
+#include <filesystem>
+#include <map>
+
+#include "WavReader.h"
 #include "core/FlpImport.h"
 #include "core/RackRenderer.h"
 
@@ -56,9 +61,21 @@ int main (int argc, char** argv)
 
     daw::Song song;
 
+    // No Linux/WSL o FL fica em /mnt/c; os caminhos do .flp usam barras invertidas.
+    const std::string flRoot = std::getenv ("FL_ROOT") ? std::getenv ("FL_ROOT")
+                                                       : "/mnt/c/Program Files/Image-Line/FL Studio 2026";
+    auto toLocal = [] (std::string p) {
+        std::replace (p.begin(), p.end(), '\\', '/');
+        return p;
+    };
+
+    daw::FlpImportOptions options;
+    options.roots = { flRoot, flRoot + "/Data", "" };
+    options.fileExists = [&] (const std::string& p) { return std::filesystem::exists (toLocal (p)); };
+
     try
     {
-        song = daw::importFlp (flp::parseProject (bytes));
+        song = daw::importFlp (flp::parseProject (bytes), options);
     }
     catch (const flp::Error& e)
     {
@@ -92,11 +109,19 @@ int main (int argc, char** argv)
 
     for (std::size_t i = 0; i < song.channels.size(); ++i)
     {
-        static const char* kinds[] = { "kick", "snare", "hat", "clap", "synth" };
+        static const char* kinds[] = { "kick", "snare", "hat", "clap", "synth", "sampler" };
         std::printf ("  %2zu %-28s -> %s\n", i, song.channels[i].name.c_str(), kinds[(int) song.channels[i].instrument]);
     }
 
-    auto state = daw::RackState::build (song, nullptr, sampleRate);
+    std::map<std::string, std::shared_ptr<const daw::SampleData>> cache;
+    auto state = daw::RackState::build (song, nullptr, sampleRate, [&] (const std::string& p) {
+        auto& entry = cache[p];
+        if (entry == nullptr)
+            entry = daw::tools::readWav (toLocal (p));
+        if (entry == nullptr)
+            std::printf ("  (não consegui ler %s)\n", p.c_str());
+        return entry;
+    });
     daw::RackRenderer renderer;
     renderer.prepare (sampleRate);