From bcfcba8c6c9fd1e74b3948909a88e21f5676e016 Mon Sep 17 00:00:00 2001
From: Kubat <mael.martin31@gmail.com>
Date: Fri, 19 Nov 2021 13:10:47 +0100
Subject: [PATCH] FIX: Dead lock with MPV on exit

When closing the window before closing the document where MPV is
initialized, don't close MPV and let the memory leak.

This is OK because the application will close imediatly after that.
---
 src/UI/DocumentViews/MpvContainer.cc | 13 ++++++++++++-
 src/UI/MainWindow.cc                 |  7 +++++++
 src/UI/MainWindow.hh                 |  4 ++++
 3 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/src/UI/DocumentViews/MpvContainer.cc b/src/UI/DocumentViews/MpvContainer.cc
index c0e3c49b..b6350953 100644
--- a/src/UI/DocumentViews/MpvContainer.cc
+++ b/src/UI/DocumentViews/MpvContainer.cc
@@ -1,5 +1,6 @@
 #include "PreCompiledHeaders.hh"
 #include "UI/DocumentViews/MpvContainer.hh"
+#include "UI/MainWindow.hh"
 
 using namespace Vivy;
 using namespace std::string_literals;
@@ -97,7 +98,17 @@ MpvContainer::closeMpv() noexcept
     }
 }
 
-MpvContainer::~MpvContainer() noexcept { closeMpv(); }
+MpvContainer::~MpvContainer() noexcept
+{
+    if (!(vivyApp->getMainWindow()->isBeingClosed()))
+        closeMpv();
+
+    else {
+        logWarning() << "The main window was already destroyed, "
+                        "don't destroy MPV and let it leak, "
+                        "the OS will collect the garbage.";
+    }
+}
 
 void
 MpvContainer::handleMpvEvent(const mpv_event *const event) noexcept
diff --git a/src/UI/MainWindow.cc b/src/UI/MainWindow.cc
index 6c564ae4..d83a4b49 100644
--- a/src/UI/MainWindow.cc
+++ b/src/UI/MainWindow.cc
@@ -161,10 +161,17 @@ MainWindow::MainWindow() noexcept
     newDocument();
 }
 
+bool
+MainWindow::isBeingClosed() const noexcept
+{
+    return privateIsBeingClosed;
+}
+
 void
 MainWindow::closeEvent(QCloseEvent *event) noexcept
 {
     logDebug() << "Closing the main window!";
+    privateIsBeingClosed = true;
     forEachViews<VivyDocumentView>([](VivyDocumentView *view, int) { view->closeDocument(); });
     QMainWindow::closeEvent(event);
 }
diff --git a/src/UI/MainWindow.hh b/src/UI/MainWindow.hh
index 71dea3cd..c462d7f9 100644
--- a/src/UI/MainWindow.hh
+++ b/src/UI/MainWindow.hh
@@ -28,9 +28,13 @@ class MainWindow final : public QMainWindow {
     QMutex aboutWindowMutex;
     AboutWindow *aboutWindow{ nullptr };
 
+    bool privateIsBeingClosed{ false };
+
 public:
     explicit MainWindow() noexcept;
 
+    bool isBeingClosed() const noexcept;
+
     AbstractDocument *getCurrentDocument() const;
     template <class Document> Document *getCurrentDocument() const
     {
-- 
GitLab