We now have back a real BufferModel. It's basically a ProxyModel to
[quassel.git] / src / client / client.cpp
index f98fe72..55fccf2 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 "global.h"
+#include "identity.h"
+#include "ircchannel.h"
+#include "ircuser.h"
+#include "message.h"
+#include "networkinfo.h"
+#include "networkmodel.h"
+#include "buffermodel.h"
 #include "quasselui.h"
 #include "signalproxy.h"
 #include "util.h"
 
-Client * Client::instanceptr = 0;
+QPointer<Client> Client::instanceptr = 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;
 }
 
 void Client::init(AbstractUi *ui) {
@@ -61,35 +52,62 @@ void Client::init(AbstractUi *ui) {
   instance()->init();
 }
 
+Client::Client(QObject *parent)
+  : QObject(parent),
+    socket(0),
+    _signalProxy(new SignalProxy(SignalProxy::Client, this)),
+    mainUi(0),
+    _networkModel(0),
+    _bufferModel(0),
+    connectedToCore(false)
+{
+}
+
+Client::~Client() {
+}
+
 void Client::init() {
   blockSize = 0;
 
-  _bufferModel = new BufferTreeModel(this);
+  _networkModel = new NetworkModel(this);
+  _bufferModel = new BufferModel(_networkModel);
 
-  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 *)));
+  connect(this, SIGNAL(bufferSelected(Buffer *)),
+          _bufferModel, SLOT(selectBuffer(Buffer *)));
+  
+  connect(this, SIGNAL(bufferUpdated(Buffer *)),
+          _networkModel, SLOT(bufferUpdated(Buffer *)));
+  connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)),
+          _networkModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
 
   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->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(networkConnected(uint)),
+                this, SLOT(networkConnected(uint)));
+  p->attachSlot(SIGNAL(networkDisconnected(uint)),
+                this, SLOT(networkDisconnected(uint)));
+  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(backlogData(BufferInfo, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferInfo, const QVariantList &, bool)));
+  p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), this, SLOT(updateBufferInfo(BufferInfo)));
+  p->attachSignal(this, SIGNAL(sendInput(BufferInfo, QString)));
   p->attachSignal(this, SIGNAL(requestNetworkStates()));
 
+  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)));
+
   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()));
@@ -99,32 +117,167 @@ 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 ***/
+
+
+QList<NetworkInfo *> Client::networkInfos() {
+  return instance()->_networkInfo.values();
+}
+
+NetworkInfo *Client::networkInfo(uint networkid) {
+  if(instance()->_networkInfo.contains(networkid))
+    return instance()->_networkInfo[networkid];
+  else
+    return 0;
+}
+
+QList<BufferInfo> Client::allBufferInfos() {
+  QList<BufferInfo> bufferids;
+  foreach(Buffer *buffer, buffers()) {
+    bufferids << buffer->bufferInfo();
+  }
+  return bufferids;
+}
+
+QList<Buffer *> Client::buffers() {
+  return instance()->_buffers.values();
+}
+
+Buffer *Client::buffer(uint bufferUid) {
+  if(instance()->_buffers.contains(bufferUid))
+    return instance()->_buffers[bufferUid];
+  else
+    return 0;
 }
 
-BufferTreeModel *Client::bufferModel() {
+Buffer *Client::buffer(BufferInfo id) {
+  Buffer *buff = buffer(id.uid());
+
+  if(!buff) {
+    Client *client = Client::instance();
+    buff = new Buffer(id, client);
+
+    connect(buff, SIGNAL(userInput(BufferInfo, QString)),
+           client, SLOT(userInput(BufferInfo, QString)));
+    connect(buff, SIGNAL(bufferUpdated(Buffer *)),
+           client, SIGNAL(bufferUpdated(Buffer *)));
+    connect(buff, SIGNAL(destroyed()),
+           client, SLOT(bufferDestroyed()));
+    client->_buffers[id.uid()] = buff;
+    emit client->bufferUpdated(buff);
+  }
+  Q_ASSERT(buff);
+  return buff;
+}
+
+// FIXME switch to netids!
+// WHEN IS THIS NEEDED ANYHOW!?
+// ...only for finding the Buffer for a channel, I guess...
+BufferInfo Client::bufferInfo(QString net, QString buf) {
+  foreach(Buffer *buffer_, buffers()) {
+    BufferInfo bufferInfo = buffer_->bufferInfo();
+    if(!bufferInfo.network().compare(net, Qt::CaseInsensitive) && !bufferInfo.buffer().compare(buf, Qt::CaseInsensitive))
+      return bufferInfo;
+  }
+  Q_ASSERT(false);  // should never happen!
+  return BufferInfo();
+}
+
+BufferInfo Client::statusBufferInfo(QString net) {
+  return bufferInfo(net, "");
+}
+
+NetworkModel *Client::networkModel() {
+  return instance()->_networkModel;
+}
+
+BufferModel *Client::bufferModel() {
   return instance()->_bufferModel;
 }
 
+
 SignalProxy *Client::signalProxy() {
   return instance()->_signalProxy;
 }
 
+
+/*** Identity handling ***/
+
+QList<IdentityId> Client::identityIds() {
+  return instance()->_identities.keys();
+}
+
+const Identity * Client::identity(IdentityId id) {
+  if(instance()->_identities.contains(id)) return instance()->_identities[id];
+  else return 0;
+}
+
+
+void Client::createIdentity(const Identity &id) {
+  emit instance()->requestCreateIdentity(id);
+}
+
+void Client::updateIdentity(const Identity &id) {
+  emit instance()->requestUpdateIdentity(id);
+}
+
+void Client::removeIdentity(IdentityId id) {
+  emit instance()->requestRemoveIdentity(id);
+}
+
+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::coreIdentityRemoved(IdentityId id) {
+  if(_identities.contains(id)) {
+    emit identityRemoved(id);
+    Identity *i = _identities.take(id);
+    i->deleteLater();
+  }
+}
+
+/***  ***/
+
+
 bool Client::isConnected() {
-  return connectedToCore;
+  return instance()->connectedToCore;
+}
+
+void Client::fakeInput(uint bufferUid, QString message) {
+  Buffer *buff = buffer(bufferUid);
+  if(!buff)
+    qWarning() << "No Buffer with uid" << bufferUid << "can't send Input" << message;
+  else
+    emit instance()->sendInput(buff->bufferInfo(), message);
+}
+
+void Client::fakeInput(BufferInfo bufferInfo, QString message) {
+  fakeInput(bufferInfo, message);
 }
 
 void Client::connectToCore(const QVariantMap &conn) {
   // TODO implement SSL
   coreConnectionInfo = conn;
-  if(isConnected() || socket != 0) {
+  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);
@@ -141,25 +294,18 @@ void Client::connectToCore(const QVariantMap &conn) {
     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(signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
     connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
     sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
   }
 }
 
 void Client::disconnectFromCore() {
-  if(clientMode == RemoteCore) {
-    socket->close();
-    //QAbstractSocket *sock = qobject_cast<QAbstractSocket*>(socket);
-    //Q_ASSERT(sock);
-    //sock->disconnectFromHost();
-  } else {
-    socket->close();
-    //disconnectFromLocalCore();
-    coreSocketDisconnected();
-  }
+  socket->close();
+}
+
+void Client::setCoreConfiguration(const QVariantMap &settings) {
+  SignalProxy::writeDataToDevice(socket, settings);
 }
 
 void Client::coreSocketConnected() {
@@ -169,35 +315,53 @@ void Client::coreSocketConnected() {
   clientInit["GuiProtocol"] = GUI_PROTOCOL;
   clientInit["User"] = coreConnectionInfo["User"].toString();
   clientInit["Password"] = coreConnectionInfo["Password"].toString();
-  writeDataToDevice(socket, clientInit);
+  SignalProxy::writeDataToDevice(socket, clientInit);
 }
 
 void Client::coreSocketDisconnected() {
-  connectedToCore = false;
+  instance()->connectedToCore = false;
   emit disconnected();
+  emit coreConnectionStateChanged(false);
   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());
+  _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());
+
+
+  QHash<NetworkId, NetworkInfo*>::iterator netIter = _networkInfo.begin();
+  while(netIter != _networkInfo.end()) {
+    NetworkInfo *net = netIter.value();
+    disconnect(net, SIGNAL(destroyed()), this, 0);
+    netIter = _networkInfo.erase(netIter);
+    net->deleteLater();
+  }
+  Q_ASSERT(_networkInfo.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();
+  }
+  Q_ASSERT(_identities.isEmpty());
+
   coreConnectionInfo.clear();
   sessionData.clear();
-  nicks.clear();
-  netConnected.clear();
-  netsAwaitingInit.clear();
-  ownNick.clear();
   layoutQueue.clear();
   layoutTimer->stop();
 }
 
-void Client::coreSocketStateChanged(QAbstractSocket::SocketState state) { qDebug() << state;
-  if(state == QAbstractSocket::UnconnectedState) coreSocketDisconnected();
-}
-
 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
@@ -205,36 +369,106 @@ void Client::recvCoreState(const QVariant &state) {
   syncToCore(state);
 }
 
+// TODO: auth errors
 void Client::syncToCore(const QVariant &coreState) {
   if(!coreState.toMap().contains("SessionState")) {
     emit coreConnectionError(tr("Invalid data received from core!"));
     disconnectFromCore();
     return;
   }
+
   QVariantMap sessionState = coreState.toMap()["SessionState"].toMap();
-  QVariantMap sessData = sessionState["SessionData"].toMap();
 
-  foreach(QString key, sessData.keys()) {
+  // store sessionData
+  QVariantMap sessData = sessionState["SessionData"].toMap();
+  foreach(QString key, sessData.keys())
     recvSessionData(key, sessData[key]);
+
+  // create identities
+  foreach(QVariant vid, sessionState["Identities"].toList()) {
+    coreIdentityCreated(vid.value<Identity>());
+    //Identity *id = new Identity(vid.value<Identity>(), this);
+    //_identities[id->id()] = id;
+    //signalProxy()->synchronize(id);
+    //qDebug() << "received identity" << id->identityName();
   }
-  QList<QVariant> coreBuffers = sessionState["Buffers"].toList();
+
+  // store Buffer details
+  QVariantList 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
+    buffer(vid.value<BufferInfo>()); // create all buffers, so we see them in the network views
+  }
+
+  // create networkInfo objects
+  QVariantList networkids = sessionState["Networks"].toList();
+  foreach(QVariant networkid, networkids) {
+    networkConnected(networkid.toUInt());
+  }
+
+  instance()->connectedToCore = true;
+  updateCoreConnectionProgress();
+
+}
+
+void Client::updateCoreConnectionProgress() {
+  // we'll do this in three steps:
+  // 1.) networks
+  // 2.) channels
+  // 3.) ircusers
+
+  int numNets = networkInfos().count();
+  int numNetsWaiting = 0;
+
+  int numIrcUsers = 0;
+  int numIrcUsersWaiting = 0;
+
+  int numChannels = 0;
+  int numChannelsWaiting = 0;
+
+  foreach(NetworkInfo *net, networkInfos()) {
+    if(! net->initialized())
+      numNetsWaiting++;
+
+    numIrcUsers += net->ircUsers().count();
+    foreach(IrcUser *user, net->ircUsers()) {
+      if(! user->initialized())
+       numIrcUsersWaiting++;
+    }
+
+    numChannels += net->ircChannels().count();
+    foreach(IrcChannel *channel, net->ircChannels()) {
+      if(! channel->initialized())
+       numChannelsWaiting++;
+    }
   }
-  netsAwaitingInit = sessionState["Networks"].toStringList();
-  connectedToCore = true;
-  if(netsAwaitingInit.count()) {
+
+  if(numNetsWaiting > 0) {
     emit coreConnectionMsg(tr("Requesting network states..."));
-    emit coreConnectionProgress(0, netsAwaitingInit.count());
-    emit requestNetworkStates();
+    emit coreConnectionProgress(numNets - numNetsWaiting, numNets);
+    return;
+  }
+
+  if(numIrcUsersWaiting > 0) {
+    emit coreConnectionMsg(tr("Requesting User states..."));
+    emit coreConnectionProgress(numIrcUsers - numIrcUsersWaiting, numIrcUsers);
+    return;
   }
-  else {
-    emit coreConnectionProgress(1, 1);
-    emit connected();
+
+  if(numChannelsWaiting > 0) {
+    emit coreConnectionMsg(tr("Requesting Channel states..."));
+    emit coreConnectionProgress(numChannels - numChannelsWaiting, numChannels);
+    return;
+  }
+
+  emit coreConnectionProgress(1,1);
+  emit connected();
+  emit coreConnectionStateChanged(true);
+  foreach(NetworkInfo *net, networkInfos()) {
+    disconnect(net, 0, this, SLOT(updateCoreConnectionProgress()));
   }
+
+  // signalProxy()->dumpProxyStats();
 }
 
 void Client::recvSessionData(const QString &key, const QVariant &data) {
@@ -261,13 +495,21 @@ QStringList Client::sessionDataKeys() {
 
 void Client::coreSocketError(QAbstractSocket::SocketError) {
   emit coreConnectionError(socket->errorString());
+  socket->deleteLater();
 }
 
 void Client::coreHasData() {
   QVariant item;
-  if(readDataFromDevice(socket, blockSize, item)) {
+  if(SignalProxy::readDataFromDevice(socket, blockSize, item)) {
     emit recvPartialItem(1,1);
-    recvCoreState(item);
+    QVariantMap msg = item.toMap();
+    if (!msg["StartWizard"].toBool()) {
+      recvCoreState(msg["Reply"]);
+    } else {
+      qWarning("Core not configured!");
+      qDebug() << "Available storage providers: " << msg["StorageProviders"].toStringList();
+      emit showConfigWizard(msg);
+    }
     blockSize = 0;
     return;
   }
@@ -276,102 +518,77 @@ void Client::coreHasData() {
   }
 }
 
-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::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::networkConnected(uint netid) {
+  // TODO: create statusBuffer / switch to networkids
+  //BufferInfo id = statusBufferInfo(net);
+  //Buffer *b = buffer(id);
+  //b->setActive(true);
+
+  NetworkInfo *netinfo = new NetworkInfo(netid, this);
+  netinfo->setProxy(signalProxy());
+  networkModel()->attachNetworkInfo(netinfo);
+  
+  if(!isConnected()) {
+    connect(netinfo, SIGNAL(initDone()), this, SLOT(updateCoreConnectionProgress()));
+    connect(netinfo, SIGNAL(ircUserInitDone()), this, SLOT(updateCoreConnectionProgress()));
+    connect(netinfo, SIGNAL(ircChannelInitDone()), this, SLOT(updateCoreConnectionProgress()));
   }
+  connect(netinfo, SIGNAL(ircChannelAdded(QString)), this, SLOT(ircChannelAdded(QString)));
+  connect(netinfo, SIGNAL(destroyed()), this, SLOT(networkInfoDestroyed()));
+  _networkInfo[netid] = netinfo;
 }
 
-void Client::updateBufferId(BufferId id) {
-  bufferIds[id.uid()] = id;  // make lookups by id faster
-  buffer(id);
-}
+void Client::networkDisconnected(uint networkid) {
+  foreach(Buffer *buffer, buffers()) {
+    if(buffer->bufferInfo().networkId() != networkid)
+      continue;
 
-BufferId Client::bufferId(QString net, QString buf) {
-  foreach(BufferId id, buffers.keys()) {
-    if(id.network() == net && id.buffer() == buf) return id;
+    //buffer->displayMsg(Message(bufferid, Message::Server, tr("Server disconnected."))); FIXME
+    buffer->setActive(false);
   }
-  Q_ASSERT(false);  // should never happen!
-  return BufferId();
-}
 
-BufferId Client::statusBufferId(QString net) {
-  return bufferId(net, "");
+  Q_ASSERT(networkInfo(networkid));
+  if(!networkInfo(networkid)->initialized()) {
+    qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
+    updateCoreConnectionProgress();
+  }
 }
 
+void Client::ircChannelAdded(QString chanName) {
+  NetworkInfo *netInfo = qobject_cast<NetworkInfo*>(sender());
+  Q_ASSERT(netInfo);
+  Buffer *buf = buffer(bufferInfo(netInfo->networkName(), chanName));
+  Q_ASSERT(buf);
+  buf->setIrcChannel(netInfo->ircChannel(chanName));
 
-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);
-  }
-  return buffers[id];
 }
 
-QList<BufferId> Client::allBufferIds() {
-  return buffers.keys();
+void Client::updateBufferInfo(BufferInfo id) {
+  buffer(id)->updateBufferInfo(id);
 }
 
-void Client::removeBuffer(Buffer *b) {
-  buffers.remove(b->bufferId());
-  bufferIds.remove(b->bufferId().uid());
+void Client::bufferDestroyed() {
+  Buffer *buffer = static_cast<Buffer *>(sender());
+  uint bufferUid = buffer->uid();
+  if(_buffers.contains(bufferUid))
+    _buffers.remove(bufferUid);
 }
 
-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());
-  }
-  foreach(QString nick, n.keys()) {
-    addNick(net, nick, n[nick].toMap());
-  }
-  emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
-  if(!netsAwaitingInit.count()) emit connected();
+void Client::networkInfoDestroyed() {
+  NetworkInfo *netinfo = static_cast<NetworkInfo *>(sender());
+  uint networkId = netinfo->networkId();
+  if(_networkInfo.contains(networkId))
+    _networkInfo.remove(networkId);
 }
 
 void Client::recvMessage(const Message &msg) {
-  Buffer *b = buffer(msg.buffer);
+  Buffer *b = buffer(msg.buffer());
 
   Buffer::ActivityLevel level = Buffer::OtherActivity;
-  if(msg.type == Message::Plain || msg.type == Message::Notice){
+  if(msg.type() == Message::Plain || msg.type() == Message::Notice){
     level |= Buffer::NewMessage;
   }
-  if(msg.flags & Message::Highlight){
+  if(msg.flags() & Message::Highlight){
     level |= Buffer::Highlight;
   }
   emit bufferActivity(level, b);
@@ -381,10 +598,9 @@ void Client::recvMessage(const Message &msg) {
 
 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*/) {
+void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
   Buffer *b = buffer(id);
   foreach(QVariant v, msgs) {
     Message msg = v.value<Message>();
@@ -397,79 +613,19 @@ void Client::recvBacklogData(BufferId id, QVariantList msgs, bool /*done*/) {
 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(b->layoutMsg())
+      layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
   }
-  if(!layoutQueue.count()) layoutTimer->stop();
+  
+  if(!layoutQueue.count())
+    layoutTimer->stop();
 }
 
 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
   return instance()->mainUi->layoutMsg(msg);
 }
 
-void Client::userInput(BufferId id, QString msg) {
+void Client::userInput(BufferInfo id, QString msg) {
   emit sendInput(id, msg);
 }
 
-void Client::setTopic(QString net, QString buf, QString topic) {
-  BufferId id = bufferId(net, buf);
-  if(!netConnected[id.network()]) return;
-  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);
-  }
-}
-
-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::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::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);
-  }
-  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);
-    }
-  }
-}
-