fixing client crash if a buffer is deleted during backlog rendering
[quassel.git] / src / client / client.cpp
index 8ee2f39..6ce23d5 100644 (file)
@@ -1,11 +1,11 @@
 /***************************************************************************
- *   Copyright (C) 2005-07 by The Quassel Team                             *
+ *   Copyright (C) 2005-08 by the Quassel Project                          *
  *   devel@quassel-irc.org                                                 *
  *                                                                         *
  *   This program is free software; you can redistribute it and/or modify  *
  *   it under the terms of the GNU General Public License as published by  *
  *   the Free Software Foundation; either version 2 of the License, or     *
- *   (at your option) any later version.                                   *
+ *   (at your option) version 3.                                           *
  *                                                                         *
  *   This program is distributed in the hope that it will be useful,       *
  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 
 #include "client.h"
 
-#include "buffer.h"
-#include "buffertreemodel.h"
+#include "bufferinfo.h"
+#include "buffermodel.h"
+#include "buffersettings.h"
+#include "buffersyncer.h"
+#include "bufferviewmanager.h"
+#include "clientbacklogmanager.h"
+#include "clientirclisthelper.h"
+#include "global.h"
+#include "identity.h"
+#include "ircchannel.h"
+#include "ircuser.h"
+#include "message.h"
+#ifdef SPUTDEV
+# include "messagemodel.h"
+#endif
+#include "network.h"
+#include "networkmodel.h"
 #include "quasselui.h"
 #include "signalproxy.h"
 #include "util.h"
 
-Client * Client::instanceptr = 0;
+QPointer<Client> Client::instanceptr = 0;
+AccountId Client::_currentCoreAccount = 0;
 
-bool Client::connectedToCore = false;
-Client::ClientMode Client::clientMode;
-QVariantMap Client::coreConnectionInfo;
-QHash<BufferId, Buffer *> Client::buffers;
-QHash<uint, BufferId> Client::bufferIds;
-QHash<QString, QHash<QString, QVariantMap> > Client::nicks;
-QHash<QString, bool> Client::netConnected;
-QStringList Client::netsAwaitingInit;
-QHash<QString, QString> Client::ownNick;
+/*** Initialization/destruction ***/
 
 Client *Client::instance() {
-  if(instanceptr) return instanceptr;
-  instanceptr = new Client();
+  if(!instanceptr)
+    instanceptr = new Client();
   return instanceptr;
 }
 
 void Client::destroy() {
-  delete instanceptr;
-  instanceptr = 0;
-}
-
-Client::Client() {
-  _signalProxy = new SignalProxy(SignalProxy::Client, 0, this);
-
-  connectedToCore = false;
-  socket = 0;
+  //delete instanceptr;
+  instanceptr->deleteLater();
 }
 
 void Client::init(AbstractUi *ui) {
@@ -61,36 +62,69 @@ void Client::init(AbstractUi *ui) {
   instance()->init();
 }
 
-void Client::init() {
-  blockSize = 0;
-
-  _bufferModel = new BufferTreeModel(this);
+Client::Client(QObject *parent)
+  : QObject(parent),
+    socket(0),
+    _signalProxy(new SignalProxy(SignalProxy::Client, this)),
+    mainUi(0),
+    _networkModel(0),
+    _bufferModel(0),
+    _bufferSyncer(0),
+    _backlogManager(new ClientBacklogManager(this)),
+    _bufferViewManager(0),
+    _ircListHelper(new ClientIrcListHelper(this)),
+    _messageModel(0),
+    _connectedToCore(false),
+    _syncedToCore(false)
+{
+  _monitorBuffer = new Buffer(BufferInfo(), this);
+  _signalProxy->synchronize(_ircListHelper);
+  
+  connect(_backlogManager, SIGNAL(backlog(BufferId, const QVariantList &)),
+         this, SLOT(receiveBacklog(BufferId, const QVariantList &)));
+}
 
-  connect(this, SIGNAL(bufferSelected(Buffer *)), _bufferModel, SLOT(selectBuffer(Buffer *)));
-  connect(this, SIGNAL(bufferUpdated(Buffer *)), _bufferModel, SLOT(bufferUpdated(Buffer *)));
-  connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)), _bufferModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
+Client::~Client() {
+  disconnectFromCore();
+}
 
+void Client::init() {
+  _currentCoreAccount = 0;
+  _networkModel = new NetworkModel(this);
+
+  connect(this, SIGNAL(bufferUpdated(BufferInfo)),
+          _networkModel, SLOT(bufferUpdated(BufferInfo)));
+  connect(this, SIGNAL(networkRemoved(NetworkId)),
+         _networkModel, SLOT(networkRemoved(NetworkId)));
+
+  _bufferModel = new BufferModel(_networkModel);
+#ifdef SPUTDEV
+  _messageModel = mainUi->createMessageModel(this);
+#endif
   SignalProxy *p = signalProxy();
-  p->attachSignal(this, SIGNAL(sendSessionData(const QString &, const QVariant &)), SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)));
-  p->attachSlot(SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)), this, SLOT(recvSessionData(const QString &, const QVariant &)));
-  p->attachSlot(SIGNAL(coreState(const QVariant &)), this, SLOT(recvCoreState(const QVariant &)));
-  p->attachSlot(SIGNAL(networkState(QString, QVariant)), this, SLOT(recvNetworkState(QString, QVariant)));
-  p->attachSlot(SIGNAL(networkConnected(QString)), this, SLOT(networkConnected(QString)));
-  p->attachSlot(SIGNAL(networkDisconnected(QString)), this, SLOT(networkDisconnected(QString)));
+
   p->attachSlot(SIGNAL(displayMsg(const Message &)), this, SLOT(recvMessage(const Message &)));
   p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
-  p->attachSlot(SIGNAL(topicSet(QString, QString, QString)), this, SLOT(setTopic(QString, QString, QString)));
-  p->attachSlot(SIGNAL(nickAdded(QString, QString, QVariantMap)), this, SLOT(addNick(QString, QString, QVariantMap)));
-  p->attachSlot(SIGNAL(nickRemoved(QString, QString)), this, SLOT(removeNick(QString, QString)));
-  p->attachSlot(SIGNAL(nickRenamed(QString, QString, QString)), this, SLOT(renameNick(QString, QString, QString)));
-  p->attachSlot(SIGNAL(nickUpdated(QString, QString, QVariantMap)), this, SLOT(updateNick(QString, QString, QVariantMap)));
-  p->attachSlot(SIGNAL(ownNickSet(QString, QString)), this, SLOT(setOwnNick(QString, QString)));
-  p->attachSlot(SIGNAL(backlogData(BufferId, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferId, const QVariantList &, bool)));
-  p->attachSlot(SIGNAL(bufferIdUpdated(BufferId)), this, SLOT(updateBufferId(BufferId)));
-  p->attachSignal(this, SIGNAL(sendInput(BufferId, QString)));
+
+  p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), this, SLOT(updateBufferInfo(BufferInfo)));
+  p->attachSignal(this, SIGNAL(sendInput(BufferInfo, QString)));
   p->attachSignal(this, SIGNAL(requestNetworkStates()));
 
-  connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
+  p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &)), SIGNAL(createIdentity(const Identity &)));
+  p->attachSignal(this, SIGNAL(requestUpdateIdentity(const Identity &)), SIGNAL(updateIdentity(const Identity &)));
+  p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
+  p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
+  p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
+
+  p->attachSignal(this, SIGNAL(requestCreateNetwork(const NetworkInfo &)), SIGNAL(createNetwork(const NetworkInfo &)));
+  p->attachSignal(this, SIGNAL(requestUpdateNetwork(const NetworkInfo &)), SIGNAL(updateNetwork(const NetworkInfo &)));
+  p->attachSignal(this, SIGNAL(requestRemoveNetwork(NetworkId)), SIGNAL(removeNetwork(NetworkId)));
+  p->attachSlot(SIGNAL(networkCreated(NetworkId)), this, SLOT(coreNetworkCreated(NetworkId)));
+  p->attachSlot(SIGNAL(networkRemoved(NetworkId)), this, SLOT(coreNetworkRemoved(NetworkId)));
+
+  connect(p, SIGNAL(disconnected()), this, SLOT(disconnectFromCore()));
+
+  //connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
   connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
   connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
   connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
@@ -99,381 +133,546 @@ void Client::init() {
   layoutTimer->setInterval(0);
   layoutTimer->setSingleShot(false);
   connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
+
 }
 
-Client::~Client() {
-  foreach(Buffer *buf, buffers.values()) delete buf; // this is done by disconnectFromCore()! FIXME?
-  Q_ASSERT(!buffers.count());
+/*** public static methods ***/
+
+AccountId Client::currentCoreAccount() {
+  return _currentCoreAccount;
 }
 
-BufferTreeModel *Client::bufferModel() {
-  return instance()->_bufferModel;
+void Client::setCurrentCoreAccount(AccountId id) {
+  _currentCoreAccount = id;
 }
 
-SignalProxy *Client::signalProxy() {
-  return instance()->_signalProxy;
+QList<BufferInfo> Client::allBufferInfos() {
+  QList<BufferInfo> bufferids;
+  foreach(Buffer *buffer, buffers()) {
+    bufferids << buffer->bufferInfo();
+  }
+  return bufferids;
 }
 
-bool Client::isConnected() {
-  return connectedToCore;
+QList<Buffer *> Client::buffers() {
+  return instance()->_buffers.values();
 }
 
-void Client::connectToCore(const QVariantMap &conn) {
-  // TODO implement SSL
-  coreConnectionInfo = conn;
-  if(isConnected()) {
-    emit coreConnectionError(tr("Already connected to Core!"));
-    return;
-  }
-  if(socket != 0) socket->deleteLater();
-  if(conn["Host"].toString().isEmpty()) {
-    clientMode = LocalCore;
-    socket = new QBuffer(this);
-    connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
-    socket->open(QIODevice::ReadWrite);
-    //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
-    //syncToCore(state);
-    coreSocketConnected();
-  } else {
-    clientMode = RemoteCore;
-    emit coreConnectionMsg(tr("Connecting..."));
-    Q_ASSERT(!socket);
-    QTcpSocket *sock = new QTcpSocket(this);
-    socket = sock;
-    connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
-    connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
-    connect(sock, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
-    connect(signalProxy(), SIGNAL(peerDisconnected()), this, SLOT(coreSocketDisconnected()));
-    //connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(coreSocketStateChanged(QAbstractSocket::SocketState)));
-    connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
-    sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
-  }
+
+Buffer *Client::statusBuffer(const NetworkId &networkId) const {
+  if(_statusBuffers.contains(networkId))
+    return _statusBuffers[networkId];
+  else
+    return 0;
 }
 
-void Client::disconnectFromCore() {
-  if(clientMode == RemoteCore) {
-    socket->close();
-    //QAbstractSocket *sock = qobject_cast<QAbstractSocket*>(socket);
-    //Q_ASSERT(sock);
-    //sock->disconnectFromHost();
-  } else {
-    socket->close();
-    //disconnectFromLocalCore();
-    coreSocketDisconnected();
+Buffer *Client::buffer(BufferId bufferId) {
+  if(instance()->_buffers.contains(bufferId))
+    return instance()->_buffers[bufferId];
+  else
+    return 0;
+}
+
+Buffer *Client::buffer(BufferInfo bufferInfo) {
+  Buffer *buff = buffer(bufferInfo.bufferId());
+
+  if(!buff) {
+    Client *client = Client::instance();
+    buff = new Buffer(bufferInfo, client);
+    connect(buff, SIGNAL(destroyed()), client, SLOT(bufferDestroyed()));
+    client->_buffers[bufferInfo.bufferId()] = buff;
+    if(bufferInfo.type() == BufferInfo::StatusBuffer)
+      client->_statusBuffers[bufferInfo.networkId()] = buff;
+
+    emit client->bufferUpdated(bufferInfo);
+
+    // I don't like this: but currently there isn't really a prettier way:
+    if(isSynced()) {  // this slows down syncing a lot, so disable it during sync
+      QModelIndex bufferIdx = networkModel()->bufferIndex(bufferInfo.bufferId());
+      bufferModel()->setCurrentIndex(bufferModel()->mapFromSource(bufferIdx));
+    }
   }
+  Q_ASSERT(buff);
+  return buff;
+}
+
+bool Client::isConnected() {
+  return instance()->_connectedToCore;
 }
 
-void Client::coreSocketConnected() {
-  connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
-  emit coreConnectionMsg(tr("Synchronizing to core..."));
-  QVariantMap clientInit;
-  clientInit["GuiProtocol"] = GUI_PROTOCOL;
-  clientInit["User"] = coreConnectionInfo["User"].toString();
-  clientInit["Password"] = coreConnectionInfo["Password"].toString();
-  writeDataToDevice(socket, clientInit);
+bool Client::isSynced() {
+  return instance()->_syncedToCore;
 }
 
-void Client::coreSocketDisconnected() {
-  connectedToCore = false;
-  emit disconnected();
-  socket->deleteLater();
-  blockSize = 0;
-
-  /* Clear internal data. Hopefully nothing relies on it at this point. */
-  _bufferModel->clear();
-  // Buffers, if deleted, send a signal that causes their removal from buffers and bufferIds.
-  // So we cannot simply go through the array in a loop (or use qDeleteAll) for deletion...
-  while(buffers.count()) { delete buffers.take(buffers.keys()[0]); }
-  Q_ASSERT(!buffers.count());   // should be empty now!
-  Q_ASSERT(!bufferIds.count());
-  coreConnectionInfo.clear();
-  sessionData.clear();
-  nicks.clear();
-  netConnected.clear();
-  netsAwaitingInit.clear();
-  ownNick.clear();
-  layoutQueue.clear();
-  layoutTimer->stop();
+/*** Network handling ***/
+
+QList<NetworkId> Client::networkIds() {
+  return instance()->_networks.keys();
 }
 
-void Client::coreSocketStateChanged(QAbstractSocket::SocketState state) { qDebug() << state;
-  if(state == QAbstractSocket::UnconnectedState) coreSocketDisconnected();
+const Network * Client::network(NetworkId networkid) {
+  if(instance()->_networks.contains(networkid)) return instance()->_networks[networkid];
+  else return 0;
 }
 
-void Client::recvCoreState(const QVariant &state) {
-  disconnect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
-  disconnect(socket, 0, this, 0);  // rest of communication happens through SignalProxy
-  signalProxy()->addPeer(socket);
-  syncToCore(state);
+void Client::createNetwork(const NetworkInfo &info) {
+  emit instance()->requestCreateNetwork(info);
+}
+
+void Client::updateNetwork(const NetworkInfo &info) {
+  emit instance()->requestUpdateNetwork(info);
 }
 
-// TODO: auth errors
-void Client::syncToCore(const QVariant &coreState) {
-  if(!coreState.toMap().contains("SessionState")) {
-    emit coreConnectionError(tr("Invalid data received from core!"));
-    disconnectFromCore();
+void Client::removeNetwork(NetworkId id) {
+  emit instance()->requestRemoveNetwork(id);
+}
+
+void Client::addNetwork(Network *net) {
+  net->setProxy(signalProxy());
+  signalProxy()->synchronize(net);
+  networkModel()->attachNetwork(net);
+  connect(net, SIGNAL(destroyed()), instance(), SLOT(networkDestroyed()));
+  instance()->_networks[net->networkId()] = net;
+  emit instance()->networkCreated(net->networkId());
+}
+
+void Client::coreNetworkCreated(NetworkId id) {
+  if(_networks.contains(id)) {
+    qWarning() << "Creation of already existing network requested!";
     return;
   }
-  QVariantMap sessionState = coreState.toMap()["SessionState"].toMap();
-  QVariantMap sessData = sessionState["SessionData"].toMap();
+  Network *net = new Network(id, this);
+  addNetwork(net);
+}
 
-  foreach(QString key, sessData.keys()) {
-    recvSessionData(key, sessData[key]);
-  }
-  QList<QVariant> coreBuffers = sessionState["Buffers"].toList();
-  /* make lookups by id faster */
-  foreach(QVariant vid, coreBuffers) {
-    BufferId id = vid.value<BufferId>();
-    bufferIds[id.uid()] = id;  // make lookups by id faster
-    buffer(id);                // create all buffers, so we see them in the network views
-  }
-  netsAwaitingInit = sessionState["Networks"].toStringList();
-  connectedToCore = true;
-  if(netsAwaitingInit.count()) {
-    emit coreConnectionMsg(tr("Requesting network states..."));
-    emit coreConnectionProgress(0, netsAwaitingInit.count());
-    emit requestNetworkStates();
-  }
-  else {
-    emit coreConnectionProgress(1, 1);
-    emit connected();
-  }
+void Client::coreNetworkRemoved(NetworkId id) {
+  if(!_networks.contains(id))
+    return;
+  Network *net = _networks.take(id);
+  emit networkRemoved(net->networkId());
+  net->deleteLater();
 }
 
-void Client::recvSessionData(const QString &key, const QVariant &data) {
-  sessionData[key] = data;
-  emit sessionDataChanged(key, data);
-  emit sessionDataChanged(key);
+/*** Identity handling ***/
+
+QList<IdentityId> Client::identityIds() {
+  return instance()->_identities.keys();
 }
 
-void Client::storeSessionData(const QString &key, const QVariant &data) {
-  // Not sure if this is a good idea, but we'll try it anyway:
-  // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
-  // rather than immediately.
-  emit instance()->sendSessionData(key, data);
+const Identity * Client::identity(IdentityId id) {
+  if(instance()->_identities.contains(id)) return instance()->_identities[id];
+  else return 0;
 }
 
-QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
-  if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
-  else return def;
+void Client::createIdentity(const Identity &id) {
+  emit instance()->requestCreateIdentity(id);
 }
 
-QStringList Client::sessionDataKeys() {
-  return instance()->sessionData.keys();
+void Client::updateIdentity(const Identity &id) {
+  emit instance()->requestUpdateIdentity(id);
 }
 
-void Client::coreSocketError(QAbstractSocket::SocketError) {
-  emit coreConnectionError(socket->errorString());
-  socket->deleteLater();
+void Client::removeIdentity(IdentityId id) {
+  emit instance()->requestRemoveIdentity(id);
 }
 
-void Client::coreHasData() {
-  QVariant item;
-  if(readDataFromDevice(socket, blockSize, item)) {
-    emit recvPartialItem(1,1);
-    recvCoreState(item);
-    blockSize = 0;
-    return;
-  }
-  if(blockSize > 0) {
-    emit recvPartialItem(socket->bytesAvailable(), blockSize);
+void Client::coreIdentityCreated(const Identity &other) {
+  if(!_identities.contains(other.id())) {
+    Identity *identity = new Identity(other, this);
+    _identities[other.id()] = identity;
+    identity->setInitialized();
+    signalProxy()->synchronize(identity);
+    emit identityCreated(other.id());
+  } else {
+    qWarning() << tr("Identity already exists in client!");
   }
 }
 
-void Client::networkConnected(QString net) {
-  Q_ASSERT(!netsAwaitingInit.contains(net));
-  netConnected[net] = true;
-  BufferId id = statusBufferId(net);
-  Buffer *b = buffer(id);
-  b->setActive(true);
-  //b->displayMsg(Message(id, Message::Server, tr("Connected.")));
-  // TODO buffersUpdated();
+void Client::coreIdentityRemoved(IdentityId id) {
+  if(_identities.contains(id)) {
+    emit identityRemoved(id);
+    Identity *i = _identities.take(id);
+    i->deleteLater();
+  }
 }
 
-void Client::networkDisconnected(QString net) {
-  foreach(BufferId id, buffers.keys()) {
-    if(id.network() != net) continue;
-    Buffer *b = buffer(id);
-    //b->displayMsg(Message(id, Message::Server, tr("Server disconnected."))); FIXME
-    b->setActive(false);
-  }
-  netConnected[net] = false;
-  if(netsAwaitingInit.contains(net)) {
-    qDebug() << "Network" << net << "disconnected while not yet initialized!";
-    netsAwaitingInit.removeAll(net);
-    emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
-    if(!netsAwaitingInit.count()) emit connected();
-  }
+/***  ***/
+void Client::userInput(BufferInfo bufferInfo, QString message) {
+  emit instance()->sendInput(bufferInfo, message);
 }
 
-void Client::updateBufferId(BufferId id) {
-  bufferIds[id.uid()] = id;  // make lookups by id faster
-  buffer(id);
+/*** core connection stuff ***/
+
+void Client::setConnectedToCore(QIODevice *sock, AccountId id) {
+  socket = sock;
+  signalProxy()->addPeer(socket);
+  _connectedToCore = true;
+  setCurrentCoreAccount(id);
 }
 
-BufferId Client::bufferId(QString net, QString buf) {
-  foreach(BufferId id, buffers.keys()) {
-    if(id.network() == net && id.buffer() == buf) return id;
-  }
-  Q_ASSERT(false);  // should never happen!
-  return BufferId();
+void Client::setSyncedToCore() {
+  // create buffersyncer
+  Q_ASSERT(!_bufferSyncer);
+  _bufferSyncer = new BufferSyncer(this);
+  connect(bufferSyncer(), SIGNAL(lastSeenMsgSet(BufferId, MsgId)), this, SLOT(updateLastSeenMsg(BufferId, MsgId)));
+  connect(bufferSyncer(), SIGNAL(bufferRemoved(BufferId)), this, SLOT(bufferRemoved(BufferId)));
+  connect(bufferSyncer(), SIGNAL(bufferRenamed(BufferId, QString)), this, SLOT(bufferRenamed(BufferId, QString)));
+  signalProxy()->synchronize(bufferSyncer());
+
+  // attach backlog manager
+  signalProxy()->synchronize(backlogManager());
+
+  // create a new BufferViewManager
+  _bufferViewManager = new BufferViewManager(signalProxy(), this);
+  
+  _syncedToCore = true;
+  emit connected();
+  emit coreConnectionStateChanged(true);
 }
 
-BufferId Client::statusBufferId(QString net) {
-  return bufferId(net, "");
+void Client::setSecuredConnection() {
+  emit securedConnection();
 }
 
+void Client::disconnectFromCore() {
+  if(!isConnected())
+    return;
+  _connectedToCore = false;
+  
+  if(socket) {
+    socket->close();
+    socket->deleteLater();
+  }
+  _syncedToCore = false;
+  emit disconnected();
+  emit coreConnectionStateChanged(false);
+
+  // Clear internal data. Hopefully nothing relies on it at this point.
+  setCurrentCoreAccount(0);
+
+  if(_bufferSyncer) {
+    _bufferSyncer->deleteLater();
+    _bufferSyncer = 0;
+  }
+
+  if(_bufferViewManager) {
+    _bufferViewManager->deleteLater();
+    _bufferViewManager = 0;
+  }
+
+  _networkModel->clear();
+
+  QHash<BufferId, Buffer *>::iterator bufferIter =  _buffers.begin();
+  while(bufferIter != _buffers.end()) {
+    Buffer *buffer = bufferIter.value();
+    disconnect(buffer, SIGNAL(destroyed()), this, 0);
+    bufferIter = _buffers.erase(bufferIter);
+    buffer->deleteLater();
+  }
+  Q_ASSERT(_buffers.isEmpty());
+
+  _statusBuffers.clear();
 
-Buffer * Client::buffer(BufferId id) {
-  Client *client = Client::instance();
-  if(!buffers.contains(id)) {
-    Buffer *b = new Buffer(id);
-    b->setOwnNick(ownNick[id.network()]);
-    connect(b, SIGNAL(userInput(BufferId, QString)), client, SLOT(userInput(BufferId, QString)));
-    connect(b, SIGNAL(bufferUpdated(Buffer *)), client, SIGNAL(bufferUpdated(Buffer *)));
-    connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SIGNAL(bufferDestroyed(Buffer *)));
-    connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SLOT(removeBuffer(Buffer *)));
-    buffers[id] = b;
-    emit client->bufferUpdated(b);
+  QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
+  while(netIter != _networks.end()) {
+    Network *net = netIter.value();
+    emit networkRemoved(net->networkId());
+    disconnect(net, SIGNAL(destroyed()), this, 0);
+    netIter = _networks.erase(netIter);
+    net->deleteLater();
+  }
+  Q_ASSERT(_networks.isEmpty());
+
+  QHash<IdentityId, Identity*>::iterator idIter = _identities.begin();
+  while(idIter != _identities.end()) {
+    Identity *id = idIter.value();
+    emit identityRemoved(id->id());
+    idIter = _identities.erase(idIter);
+    id->deleteLater();
   }
-  return buffers[id];
+  Q_ASSERT(_identities.isEmpty());
+
+  layoutQueue.clear();
+  layoutTimer->stop();
 }
 
-QList<BufferId> Client::allBufferIds() {
-  return buffers.keys();
+void Client::setCoreConfiguration(const QVariantMap &settings) {
+  SignalProxy::writeDataToDevice(socket, settings);
 }
 
-void Client::removeBuffer(Buffer *b) {
-  buffers.remove(b->bufferId());
-  bufferIds.remove(b->bufferId().uid());
+/*** ***/
+
+void Client::updateBufferInfo(BufferInfo id) {
+  emit bufferUpdated(id);
 }
 
-void Client::recvNetworkState(QString net, QVariant state) {
-  netsAwaitingInit.removeAll(net);
-  netConnected[net] = true;
-  setOwnNick(net, state.toMap()["OwnNick"].toString());
-  buffer(statusBufferId(net))->setActive(true);
-  QVariantMap t = state.toMap()["Topics"].toMap();
-  QVariantMap n = state.toMap()["Nicks"].toMap();
-  foreach(QVariant v, t.keys()) {
-    QString buf = v.toString();
-    BufferId id = bufferId(net, buf);
-    buffer(id)->setActive(true);
-    setTopic(net, buf, t[buf].toString());
+void Client::bufferDestroyed() {
+  Buffer *buffer = static_cast<Buffer *>(sender());
+  QHash<BufferId, Buffer *>::iterator iter = _buffers.begin();
+  while(iter != _buffers.end()) {
+    if(iter.value() == buffer) {
+      iter = _buffers.erase(iter);
+      break;
+    }
+    iter++;
   }
-  foreach(QString nick, n.keys()) {
-    addNick(net, nick, n[nick].toMap());
+
+  QHash<NetworkId, Buffer *>::iterator statusIter = _statusBuffers.begin();
+  while(statusIter != _statusBuffers.end()) {
+    if(statusIter.value() == buffer) {
+      statusIter = _statusBuffers.erase(statusIter);
+      break;
+    }
+    statusIter++;
   }
-  emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
-  if(!netsAwaitingInit.count()) emit connected();
 }
 
-void Client::recvMessage(const Message &msg) {
-  Buffer *b = buffer(msg.buffer);
+void Client::networkDestroyed() {
+  Network *net = static_cast<Network *>(sender());
+  QHash<NetworkId, Network *>::iterator netIter = _networks.begin();
+  while(netIter != _networks.end()) {
+    if(*netIter == net) {
+      netIter = _networks.erase(netIter);
+      break;
+    } else {
+      netIter++;
+    }
+  }
+}
+
+#ifndef SPUTDEV
+void Client::recvMessage(const Message &message) {
+  Message msg = message;
+  Buffer *b;
+
+  checkForHighlight(msg);
+
+  // FIXME clean up code! (dup)
+
+  // TODO: make redirected messages show up in the correct buffer!
 
-  Buffer::ActivityLevel level = Buffer::OtherActivity;
-  if(msg.type == Message::Plain || msg.type == Message::Notice){
-    level |= Buffer::NewMessage;
+  if(msg.flags() & Message::Redirected) {
+    BufferSettings bufferSettings;
+    bool inStatus = bufferSettings.value("UserMessagesInStatusBuffer", QVariant(true)).toBool();
+    bool inQuery = bufferSettings.value("UserMessagesInQueryBuffer", QVariant(false)).toBool();
+    bool inCurrent = bufferSettings.value("UserMessagesInCurrentBuffer", QVariant(false)).toBool();
+
+    if(inStatus) {
+      b = statusBuffer(msg.bufferInfo().networkId());
+      if(b) {
+        b->appendMsg(msg);
+      } else if(!inQuery && !inCurrent) {      // make sure the message get's shown somewhere
+        b = buffer(msg.bufferInfo());
+        b->appendMsg(msg);
+      }
+    }
+
+    if(inQuery) {
+      b = buffer(msg.bufferInfo().bufferId());
+      if(b) {
+        b->appendMsg(msg);
+      } else if(!inStatus && !inCurrent) { // make sure the message get's shown somewhere
+        b = statusBuffer(msg.bufferInfo().networkId());
+      if(!b) b = buffer(msg.bufferInfo()); // seems like we have to create the buffer anyways...
+      b->appendMsg(msg);
+      }
+    }
+
+    if(inCurrent) {
+      BufferId currentId = bufferModel()->currentIndex().data(NetworkModel::BufferIdRole).value<BufferId>();
+      b = buffer(currentId);
+      if(b && currentId != msg.bufferInfo().bufferId() && !inQuery) {
+        b->appendMsg(msg);
+      } else if(!inStatus && !inQuery) {       // make sure the message get's shown somewhere
+        b = statusBuffer(msg.bufferInfo().networkId());
+        if(!b) b = buffer(msg.bufferInfo()); // seems like we have to create the buffer anyways...
+        b->appendMsg(msg);
+      }
+    }
+  } else {
+    // the regular case: we can deliver where it was supposed to go
+    b = buffer(msg.bufferInfo());
+    b->appendMsg(msg);
   }
-  if(msg.flags & Message::Highlight){
-    level |= Buffer::Highlight;
+  //bufferModel()->updateBufferActivity(msg);
+
+  if(msg.type() == Message::Plain || msg.type() == Message::Notice || msg.type() == Message::Action) {
+    const Network *net = network(msg.bufferInfo().networkId());
+    QString networkName = net != 0
+      ? net->networkName() + ":"
+      : QString();
+    QString sender = networkName + msg.bufferInfo().bufferName() + ":" + msg.sender();
+    Message mmsg = Message(msg.timestamp(), msg.bufferInfo(), msg.type(), msg.contents(), sender, msg.flags());
+    monitorBuffer()->appendMsg(mmsg);
   }
-  emit bufferActivity(level, b);
+  emit messageReceived(msg);
+}
+#else
 
-  b->appendMsg(msg);
+void Client::recvMessage(const Message &msg) {
+  //checkForHighlight(msg);
+  _messageModel->insertMessage(msg);
 }
 
+#endif /* SPUTDEV */
+
 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
-
 }
 
-void Client::recvBacklogData(BufferId id, QVariantList msgs, bool /*done*/) {
-  Buffer *b = buffer(id);
+#ifdef SPUTDEV
+void Client::receiveBacklog(BufferId bufferId, const QVariantList &msgs) {
+  //checkForHighlight(msg);
   foreach(QVariant v, msgs) {
-    Message msg = v.value<Message>();
-    b->prependMsg(msg);
-    if(!layoutQueue.contains(b)) layoutQueue.append(b);
+    _messageModel->insertMessage(v.value<Message>());
   }
-  if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
 }
 
+#else
+
+void Client::receiveBacklog(BufferId bufferId, const QVariantList &msgs) {
+  Buffer *buffer_ = buffer(bufferId);
+  if(!buffer_) {
+    qWarning() << "Client::receiveBacklog(): received Backlog for unknown Buffer:" << bufferId;
+    return;
+  }
+
+  if(msgs.isEmpty())
+    return; // no work to be done...
+  
+  QVariantList::const_iterator msgIter = msgs.constBegin();
+  QVariantList::const_iterator msgIterEnd = msgs.constEnd();
+  Message msg;
+  while(msgIter != msgIterEnd) {
+    msg = (*msgIter).value<Message>();
+    checkForHighlight(msg);
+    buffer_->prependMsg(msg);
+    msgIter++;
+  }
+
+  if(!layoutQueue.contains(buffer_))
+    layoutQueue.append(buffer_);
+
+  if(!layoutTimer->isActive()) {
+    layoutTimer->start();
+  }
+}
+#endif /* SPUTDEV */
+
 void Client::layoutMsg() {
-  if(layoutQueue.count()) {
-    Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
-    if(b->layoutMsg()) layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
+  if(layoutQueue.isEmpty()) {
+    layoutTimer->stop();
+    return;
+  }
+  
+  Buffer *buffer = layoutQueue.takeFirst();
+  if(buffer->layoutMsg()) {
+    layoutQueue.append(buffer);  // Buffer has more messages in its queue --> Round Robin
+    return;
   }
-  if(!layoutQueue.count()) layoutTimer->stop();
+
+  if(layoutQueue.isEmpty())
+    layoutTimer->stop();
 }
 
 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
   return instance()->mainUi->layoutMsg(msg);
 }
 
-void Client::userInput(BufferId id, QString msg) {
-  emit sendInput(id, msg);
+void Client::checkForHighlight(Message &msg) {
+  NotificationSettings notificationSettings;
+  const Network *net = network(msg.bufferInfo().networkId());
+  if(net && !net->myNick().isEmpty()) {
+    QStringList nickList;
+    if(notificationSettings.highlightNick() == NotificationSettings::CurrentNick) {
+      nickList << net->myNick();
+    } else if(notificationSettings.highlightNick() == NotificationSettings::AllNicks) {
+      nickList = identity(net->identity())->nicks();
+    }
+    foreach(QString nickname, nickList) {
+      QRegExp nickRegExp("^(.*\\W)?" + QRegExp::escape(nickname) + "(\\W.*)?$");
+      if((msg.type() & (Message::Plain | Message::Notice | Message::Action))
+          && !(msg.flags() & Message::Self)
+          && nickRegExp.exactMatch(msg.contents())) {
+        msg.setFlags(msg.flags() | Message::Highlight);
+        return;
+      }
+    }
+
+    foreach(QVariant highlight, notificationSettings.highlightList()) {
+      QVariantMap highlightRule = highlight.toMap();
+      if(!highlightRule["enable"].toBool())
+        continue;
+      Qt::CaseSensitivity caseSensitivity = highlightRule["cs"].toBool() ? Qt::CaseSensitive : Qt::CaseInsensitive;
+      QString name = highlightRule["name"].toString();
+      QRegExp userRegExp;
+      if(highlightRule["regex"].toBool()) {
+        userRegExp = QRegExp(name, caseSensitivity);
+      } else {
+        userRegExp = QRegExp("^(.*\\W)?" + QRegExp::escape(name) + "(\\W.*)?$", caseSensitivity);
+      }
+      if((msg.type() & (Message::Plain | Message::Notice | Message::Action))
+          && !(msg.flags() & Message::Self)
+          && userRegExp.exactMatch(msg.contents())) {
+        msg.setFlags(msg.flags() | Message::Highlight);
+        return;
+      }
+    }
+  }
 }
 
-void Client::setTopic(QString net, QString buf, QString topic) {
-  BufferId id = bufferId(net, buf);
-  if(!netConnected[id.network()]) return;
+void Client::updateLastSeenMsg(BufferId id, const MsgId &msgId) {
   Buffer *b = buffer(id);
-  b->setTopic(topic);
-  //if(!b->isActive()) {
-  //  b->setActive(true);
-  //  buffersUpdated();
-  //}
-}
-
-void Client::addNick(QString net, QString nick, QVariantMap props) {
-  if(!netConnected[net]) return;
-  nicks[net][nick] = props;
-  QVariantMap chans = props["Channels"].toMap();
-  QStringList c = chans.keys();
-  foreach(QString bufname, c) {
-    buffer(bufferId(net, bufname))->addNick(nick, props);
+  if(!b) {
+    qWarning() << "Client::updateLastSeen(): Unknown buffer" << id;
+    return;
   }
+  b->setLastSeenMsg(msgId);
 }
 
-void Client::renameNick(QString net, QString oldnick, QString newnick) {
-  if(!netConnected[net]) return;
-  QStringList chans = nicks[net][oldnick]["Channels"].toMap().keys();
-  foreach(QString c, chans) {
-    buffer(bufferId(net, c))->renameNick(oldnick, newnick);
-  }
-  nicks[net][newnick] = nicks[net].take(oldnick);
+void Client::setBufferLastSeenMsg(BufferId id, const MsgId &msgId) {
+  if(!bufferSyncer())
+    return;
+  bufferSyncer()->requestSetLastSeenMsg(id, msgId);
 }
 
-void Client::updateNick(QString net, QString nick, QVariantMap props) {
-  if(!netConnected[net]) return;
-  QStringList oldchans = nicks[net][nick]["Channels"].toMap().keys();
-  QStringList newchans = props["Channels"].toMap().keys();
-  foreach(QString c, newchans) {
-    if(oldchans.contains(c)) buffer(bufferId(net, c))->updateNick(nick, props);
-    else buffer(bufferId(net, c))->addNick(nick, props);
-  }
-  foreach(QString c, oldchans) {
-    if(!newchans.contains(c)) buffer(bufferId(net, c))->removeNick(nick);
-  }
-  nicks[net][nick] = props;
+void Client::removeBuffer(BufferId id) {
+  if(!bufferSyncer()) return;
+  bufferSyncer()->requestRemoveBuffer(id);
 }
 
-void Client::removeNick(QString net, QString nick) {
-  if(!netConnected[net]) return;
-  QVariantMap chans = nicks[net][nick]["Channels"].toMap();
-  foreach(QString bufname, chans.keys()) {
-    buffer(bufferId(net, bufname))->removeNick(nick);
+void Client::bufferRemoved(BufferId bufferId) {
+  // first remove the buffer from hash. this prohibits further lastSeenUpdates
+  Buffer *buff = 0;
+  if(_buffers.contains(bufferId)) {
+    buff = _buffers.take(bufferId);
+    layoutQueue.removeAll(buff);
+    disconnect(buff, 0, this, 0);
   }
-  nicks[net].remove(nick);
-}
 
-void Client::setOwnNick(QString net, QString nick) {
-  if(!netConnected[net]) return;
-  ownNick[net] = nick;
-  foreach(BufferId id, buffers.keys()) {
-    if(id.network() == net) {
-      buffers[id]->setOwnNick(nick);
-    }
+  // then we select a sane buffer (status buffer)
+  /* we have to manually select a buffer because otherwise inconsitent changes
+   * to the model might occur:
+   * the result of a buffer removal triggers a change in the selection model.
+   * the newly selected buffer might be a channel that hasn't been selected yet
+   * and a new nickview would be created (which never heard of the "rowsAboutToBeRemoved").
+   * this new view (and/or) its sort filter will then only receive a "rowsRemoved" signal.
+   */
+  QModelIndex current = bufferModel()->currentIndex();
+  if(current.data(NetworkModel::BufferIdRole).value<BufferId>() == bufferId) {
+    bufferModel()->setCurrentIndex(current.sibling(0,0));
   }
+
+  // and remove it from the model
+  networkModel()->removeBuffer(bufferId);
+
+  if(buff)
+    buff->deleteLater();
 }
 
+void Client::bufferRenamed(BufferId bufferId, const QString &newName) {
+  QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId);
+  if(bufferIndex.isValid()) {
+    networkModel()->setData(bufferIndex, newName, Qt::DisplayRole);
+  }
+}