瀏覽代碼

Projeto modificado (*) no título, 'salvar alterações?' antes de novo/abrir/sair e autosave a cada 2 min

Kauan 1 月之前
父節點
當前提交
8ea0e92bb1
共有 5 個文件被更改,包括 97 次插入 和 9 次删除
  1. 10 2
      src/Main.cpp
  2. 6 0
      src/engine/AudioEngine.cpp
  3. 5 0
      src/engine/AudioEngine.h
  4. 69 7
      src/ui/MainComponent.cpp
  5. 7 0
      src/ui/MainComponent.h

+ 10 - 2
src/Main.cpp

@@ -107,7 +107,13 @@ public:
         juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
     }
 
-    void systemRequestedQuit() override { quit(); }
+    void systemRequestedQuit() override
+    {
+        if (mainWindow != nullptr)
+            mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
+        else
+            quit();
+    }
 
 private:
     // LYNX.exe --selftest relatorio.txt: renderiza 2 s sem placa de som e grava o resultado.
@@ -164,7 +170,8 @@ private:
         offline.undo();
         const auto afterUndo = offline.getSong().bpm;
         offline.redo();
-        const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo();
+        const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
+                            && offline.isModified();
 
         // gravação pelo teclado do PC: uma nota de um tempo entra na pattern, num passo de desfazer
         const auto notesBefore = offline.getSong().patterns[0].notes.size();
@@ -489,6 +496,7 @@ private:
         }
 
         void openFile (const juce::File& file) { content->openFile (file); }
+        void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
 
         void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
 

+ 6 - 0
src/engine/AudioEngine.cpp

@@ -501,6 +501,7 @@ void AudioEngine::setSong (Song newSong)
     redoStack.clear();
     song = std::move (newSong);
     selectedChannel = 0;
+    modified = false;
     publishSong();
 }
 
@@ -532,6 +533,9 @@ void AudioEngine::editSong (const std::function<void (Song&)>& edit, bool undoab
         }
     }
 
+    if (undoable)
+        modified = true;
+
     edit (song);
     publishSong();
 }
@@ -544,6 +548,7 @@ void AudioEngine::undo()
     redoStack.push_back (std::move (song));
     song = std::move (undoStack.back());
     undoStack.pop_back();
+    modified = true;
     lastUndoPress = {};
     publishSong();
 }
@@ -556,6 +561,7 @@ void AudioEngine::redo()
     undoStack.push_back (std::move (song));
     song = std::move (redoStack.back());
     redoStack.pop_back();
+    modified = true;
     lastUndoPress = {};
     publishSong();
 }

+ 5 - 0
src/engine/AudioEngine.h

@@ -78,6 +78,10 @@ public:
     // (arrastar uma nota, girar um knob) viram um passo só.
     void editSong (const std::function<void (Song&)>& edit, bool undoable = true);
 
+    // Alterações desde o último salvar/abrir (para o "*" no título e o "salvar alterações?").
+    bool isModified() const noexcept { return modified; }
+    void markSaved() noexcept { modified = false; sendChangeMessage(); }
+
     bool canUndo() const noexcept { return ! undoStack.empty(); }
     bool canRedo() const noexcept { return ! redoStack.empty(); }
     void undo();
@@ -176,6 +180,7 @@ private:
 
     Song song;
     int selectedChannel = 0;
+    bool modified = false;
     std::unique_ptr<StreamPrefetcher> prefetcher; // só com dispositivo de áudio (tocando ao vivo)
 
     static constexpr std::size_t maxUndoSteps = 100;

+ 69 - 7
src/ui/MainComponent.cpp

@@ -511,6 +511,21 @@ void MainComponent::changeListenerCallback (juce::ChangeBroadcaster*)
 
 void MainComponent::timerCallback()
 {
+    if (engine.isModified() != lastModified)
+    {
+        lastModified = engine.isModified();
+        updateTitle();
+    }
+
+    // autosave a cada 2 minutos com alterações
+    if (++autosaveTicks >= 30 * 120)
+    {
+        autosaveTicks = 0;
+
+        if (engine.isModified())
+            autosave();
+    }
+
     auto& transport = engine.getTransport();
     const auto& song = engine.getSong();
     const auto loop = song.mode == PlayMode::song ? song.songLength()
@@ -535,20 +550,66 @@ void MainComponent::timerCallback()
 void MainComponent::updateTitle()
 {
     if (auto* window = getTopLevelComponent())
-        window->setName (currentFile.exists() ? "LYNX - " + currentFile.getFileNameWithoutExtension() : juce::String ("LYNX"));
+        window->setName ((engine.isModified() ? "* " : "")
+                         + (projectName.isNotEmpty() ? "LYNX - " + projectName : juce::String ("LYNX")));
+}
+
+void MainComponent::confirmDiscard (std::function<void()> then)
+{
+    if (! engine.isModified())
+    {
+        then();
+        return;
+    }
+
+    auto* window = new juce::AlertWindow (utf8 ("Salvar alterações?"),
+                                          utf8 ("O projeto tem alterações que não foram salvas."),
+                                          juce::MessageBoxIconType::QuestionIcon);
+    window->addButton ("Salvar", 1, juce::KeyPress (juce::KeyPress::returnKey));
+    window->addButton ("Descartar", 2);
+    window->addButton ("Cancelar", 0, juce::KeyPress (juce::KeyPress::escapeKey));
+    window->enterModalState (true, juce::ModalCallbackFunction::create ([this, then] (int result) {
+                                 if (result == 1)
+                                 {
+                                     save (false);
+                                     if (! engine.isModified()) // salvou (não cancelou o "salvar como")
+                                         then();
+                                 }
+                                 else if (result == 2)
+                                     then();
+                             }),
+                             true);
+}
+
+void MainComponent::autosave()
+{
+    // cópia de segurança do projeto aberto, para não perder trabalho se algo travar
+    const auto folder = juce::File::getSpecialLocation (juce::File::userApplicationDataDirectory).getChildFile ("LYNX/autosave");
+    folder.createDirectory();
+    const auto name = projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("sem nome");
+    juce::String error;
+    engine.capturePluginStates();
+    ProjectFile::save (engine.getSong(), folder.getChildFile (name + ProjectFile::extension), error);
 }
 
 void MainComponent::newProject()
 {
-    engine.stop();
-    engine.rewind();
-    engine.setSong (Song::makeDefault());
-    currentFile = juce::File();
-    projectName = {};
-    updateTitle();
+    confirmDiscard ([this] {
+        engine.stop();
+        engine.rewind();
+        engine.setSong (Song::makeDefault());
+        currentFile = juce::File();
+        projectName = {};
+        updateTitle();
+    });
 }
 
 void MainComponent::chooseFileToOpen()
+{
+    confirmDiscard ([this] { chooseFileToOpenNow(); });
+}
+
+void MainComponent::chooseFileToOpenNow()
 {
     fileChooser = std::make_unique<juce::FileChooser> ("Abrir projeto", currentFile.getParentDirectory(),
                                                        juce::String ("*") + ProjectFile::extension + ";*.dawproj;*.flp;*.mid;*.midi");
@@ -632,6 +693,7 @@ void MainComponent::save (bool askForFile)
 
         if (ProjectFile::save (engine.getSong(), file, error))
         {
+            engine.markSaved();
             currentFile = file;
             projectName = file.getFileNameWithoutExtension();
             updateTitle();

+ 7 - 0
src/ui/MainComponent.h

@@ -29,6 +29,9 @@ public:
     // Abre .lynx ou .flp (também usado pela linha de comando).
     void openFile (const juce::File& file);
 
+    // Pergunta "salvar alterações?" se houver; `then` roda se o usuário não cancelar.
+    void confirmDiscard (std::function<void()> then);
+
     // Para o modo --snapshot: 0 = Channel Rack, 1 = Piano Roll (no canal com mais notas), 2 = Playlist, 3 = Mixer.
     void selectTabForSnapshot (int tab);
 
@@ -39,10 +42,14 @@ private:
     void showAudioSettings();
     void newProject();
     void chooseFileToOpen();
+    void chooseFileToOpenNow();
     void save (bool askForFile);
     void exportAudio();
     void refreshToolbar();
     void updateTitle();
+    void autosave();
+    int autosaveTicks = 0;
+    bool lastModified = false;
     void openPianoRoll();
     void toggleMode();
     void refreshModeButton();