core: Allow clean shutdown of the core
[quassel.git] / src / qtui / monoapplication.cpp
index 1a8822d..128ab97 100644 (file)
@@ -38,10 +38,9 @@ MonolithicApplication::MonolithicApplication(int &argc, char **argv)
 }
 
 
-bool MonolithicApplication::init()
+void MonolithicApplication::init()
 {
-    if (!QtUiApplication::init())
-        return false;
+    QtUiApplication::init();
 
     connect(Client::coreConnection(), SIGNAL(connectToInternalCore(QPointer<InternalPeer>)), this, SLOT(onConnectionRequest(QPointer<InternalPeer>)));
 
@@ -51,18 +50,40 @@ bool MonolithicApplication::init()
     if (Quassel::isOptionSet("port")) {
         startInternalCore();
     }
+}
+
 
-    return true;
+Quassel::QuitHandler MonolithicApplication::quitHandler()
+{
+    return [this]() {
+        connect(_client.get(), SIGNAL(destroyed()), this, SLOT(onClientDestroyed()));
+        _client.release()->deleteLater();
+    };
+}
+
+
+void MonolithicApplication::onClientDestroyed()
+{
+    if (_core) {
+        connect(_core, SIGNAL(shutdownComplete()), this, SLOT(onCoreShutdown()));
+        _core->shutdown();
+    }
+    else {
+        QCoreApplication::quit();
+    }
 }
 
 
-MonolithicApplication::~MonolithicApplication()
+void MonolithicApplication::onCoreShutdown()
 {
-    // Client needs to be destroyed first
-    Client::destroy();
-    _coreThread.quit();
-    _coreThread.wait();
-    Quassel::destroy();
+    if (_core) {
+        connect(_core, SIGNAL(destroyed()), QCoreApplication::instance(), SLOT(quit()));
+        _coreThread.quit();
+        _coreThread.wait();
+    }
+    else {
+        QCoreApplication::quit();
+    }
 }
 
 
@@ -76,12 +97,15 @@ void MonolithicApplication::startInternalCore()
     // Start internal core in a separate thread, so it doesn't block the UI
     _core = new Core{};
     _core->moveToThread(&_coreThread);
-    connect(&_coreThread, SIGNAL(started()), _core, SLOT(init()));
+    connect(&_coreThread, SIGNAL(started()), _core, SLOT(initAsync()));
     connect(&_coreThread, SIGNAL(finished()), _core, SLOT(deleteLater()));
 
     connect(this, SIGNAL(connectInternalPeer(QPointer<InternalPeer>)), _core, SLOT(connectInternalPeer(QPointer<InternalPeer>)));
     connect(_core, SIGNAL(sessionState(Protocol::SessionState)), Client::coreConnection(), SLOT(internalSessionStateReceived(Protocol::SessionState)));
 
+    connect(_core, SIGNAL(dbUpgradeInProgress(bool)), Client::instance(), SLOT(onDbUpgradeInProgress(bool)));
+    connect(_core, SIGNAL(exitRequested(int,QString)), Client::instance(), SLOT(onExitRequested(int,QString)));
+
     _coreThread.start();
 }