From 09691d557e35bcc6f44e9639ff190e75c0b570dd Mon Sep 17 00:00:00 2001
From: Kubat <mael.martin31@gmail.com>
Date: Mon, 28 Jun 2021 17:43:32 +0200
Subject: [PATCH] WINDOW: On new/open document, the first untouched document is
 replaced by the new document

---
 src/MainWindow.cc | 31 ++++++++++++++++++++++++++++++-
 src/MainWindow.hh |  2 ++
 2 files changed, 32 insertions(+), 1 deletion(-)

diff --git a/src/MainWindow.cc b/src/MainWindow.cc
index 421a0124..10d54bba 100644
--- a/src/MainWindow.cc
+++ b/src/MainWindow.cc
@@ -272,7 +272,15 @@ MainWindow::loadSubDocumentAudio() noexcept
 void
 MainWindow::addTab(VivyDocumentView *tab)
 {
-    const int index = documents->addTab(tab, QIcon(":/icons/vivy.png"), tab->getDocumentTabName());
+    int index = -1;
+    if (const int untouched_index = findFirstUntouchedDocument(); untouched_index >= 0) {
+        closeDocument(untouched_index);
+        index = documents->insertTab(untouched_index, tab, QIcon(":/icons/vivy.png"),
+                                     tab->getDocumentTabName());
+    } else {
+        index = documents->addTab(tab, QIcon(":/icons/vivy.png"), tab->getDocumentTabName());
+    }
+
     documents->setTabToolTip(index, tab->getDocumentTabToolTip());
     qDebug() << "View constructed successfully";
 }
@@ -289,3 +297,24 @@ MainWindow::getCurrentDocumentView() const
         throw std::runtime_error("no current document");
     }
 }
+
+VivyDocumentView *
+MainWindow::getTab(const int index) const noexcept
+{
+    if (index > documents->count())
+        return nullptr;
+    return reinterpret_cast<VivyDocumentView *>(documents->widget(index));
+}
+
+int
+MainWindow::findFirstUntouchedDocument() const noexcept
+{
+    const int count = documents->count();
+    for (int index = 0; index < count; ++index) {
+        if (getTab(index)->getDocument().lock()->checkDocumentOption(
+                VivyDocument::UntouchedByDefault))
+            return index;
+    }
+
+    return -1;
+}
diff --git a/src/MainWindow.hh b/src/MainWindow.hh
index 1dab565b..9beb5785 100644
--- a/src/MainWindow.hh
+++ b/src/MainWindow.hh
@@ -26,7 +26,9 @@ public:
 
 private:
     void addTab(VivyDocumentView *);
+    VivyDocumentView *getTab(const int) const noexcept;
     VivyDocumentView *getCurrentDocumentView() const;
+    int findFirstUntouchedDocument() const noexcept;
 
 private slots:
     void newDocument() noexcept;
-- 
GitLab