X-Git-Url: https://git.quassel-irc.org/?p=quassel.git;a=blobdiff_plain;f=src%2Fclient%2Fclient.cpp;h=8d6068912e140401086a7e0a30e5e06aae9c01a5;hp=f98fe7266ab01759e9583696d217dbd7f9c33b3d;hb=7cd3ad607186b3a14989075968daa4f1e2ea265b;hpb=de9a7ec6b70c796182e0a7992aa380a58b954b94 diff --git a/src/client/client.cpp b/src/client/client.cpp index f98fe726..d8dbcbf5 100644 --- a/src/client/client.cpp +++ b/src/client/client.cpp @@ -1,11 +1,11 @@ /*************************************************************************** - * Copyright (C) 2005-07 by The Quassel Team * + * Copyright (C) 2005-2015 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 * @@ -15,461 +15,693 @@ * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * - * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "client.h" -#include "buffer.h" -#include "buffertreemodel.h" -#include "quasselui.h" +#include "abstractmessageprocessor.h" +#include "abstractui.h" +#include "bufferinfo.h" +#include "buffermodel.h" +#include "buffersettings.h" +#include "buffersyncer.h" +#include "bufferviewconfig.h" +#include "bufferviewoverlay.h" +#include "clientaliasmanager.h" +#include "clientbacklogmanager.h" +#include "clientbufferviewmanager.h" +#include "clientirclisthelper.h" +#include "clientidentity.h" +#include "clientignorelistmanager.h" +#include "clienttransfermanager.h" +#include "clientuserinputhandler.h" +#include "coreaccountmodel.h" +#include "coreconnection.h" +#include "ircchannel.h" +#include "ircuser.h" +#include "message.h" +#include "messagemodel.h" +#include "network.h" +#include "networkconfig.h" +#include "networkmodel.h" +#include "quassel.h" #include "signalproxy.h" #include "util.h" +#include "clientauthhandler.h" -Client * Client::instanceptr = 0; +#include +#include -bool Client::connectedToCore = false; -Client::ClientMode Client::clientMode; -QVariantMap Client::coreConnectionInfo; -QHash Client::buffers; -QHash Client::bufferIds; -QHash > Client::nicks; -QHash Client::netConnected; -QStringList Client::netsAwaitingInit; -QHash Client::ownNick; - -Client *Client::instance() { - if(instanceptr) return 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) { - instance()->mainUi = ui; - instance()->init(); -} - -void Client::init() { - blockSize = 0; - - _bufferModel = new BufferTreeModel(this); - - 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 *))); - - 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(requestNetworkStates())); - - 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())); - - layoutTimer = new QTimer(this); - 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()); -} - -BufferTreeModel *Client::bufferModel() { - return instance()->_bufferModel; -} - -SignalProxy *Client::signalProxy() { - return instance()->_signalProxy; -} - -bool Client::isConnected() { - return connectedToCore; -} - -void Client::connectToCore(const QVariantMap &conn) { - // TODO implement SSL - coreConnectionInfo = conn; - if(isConnected() || socket != 0) { - emit coreConnectionError(tr("Already connected to Core!")); - return; - } - 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()); - } -} - -void Client::disconnectFromCore() { - if(clientMode == RemoteCore) { - socket->close(); - //QAbstractSocket *sock = qobject_cast(socket); - //Q_ASSERT(sock); - //sock->disconnectFromHost(); - } else { - socket->close(); - //disconnectFromLocalCore(); - coreSocketDisconnected(); - } -} - -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); -} - -void Client::coreSocketDisconnected() { - connectedToCore = false; - emit disconnected(); - socket->deleteLater(); - - /* 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(); -} - -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 - signalProxy()->addPeer(socket); - syncToCore(state); -} - -void Client::syncToCore(const QVariant &coreState) { - if(!coreState.toMap().contains("SessionState")) { - emit coreConnectionError(tr("Invalid data received from core!")); +QPointer Client::instanceptr = 0; +Quassel::Features Client::_coreFeatures = 0; + +/*** Initialization/destruction ***/ + +bool Client::instanceExists() +{ + return instanceptr; +} + + +Client *Client::instance() +{ + if (!instanceptr) + instanceptr = new Client(); + return instanceptr; +} + + +void Client::destroy() +{ + if (instanceptr) { + delete instanceptr->mainUi(); + instanceptr->deleteLater(); + instanceptr = 0; + } +} + + +void Client::init(AbstractUi *ui) +{ + instance()->_mainUi = ui; + instance()->init(); +} + + +Client::Client(QObject *parent) + : QObject(parent), + _signalProxy(new SignalProxy(SignalProxy::Client, this)), + _mainUi(0), + _networkModel(0), + _bufferModel(0), + _bufferSyncer(0), + _aliasManager(0), + _backlogManager(new ClientBacklogManager(this)), + _bufferViewManager(0), + _bufferViewOverlay(new BufferViewOverlay(this)), + _ircListHelper(new ClientIrcListHelper(this)), + _inputHandler(0), + _networkConfig(0), + _ignoreListManager(0), + _transferManager(0), + _messageModel(0), + _messageProcessor(0), + _coreAccountModel(new CoreAccountModel(this)), + _coreConnection(new CoreConnection(this)), + _connected(false), + _debugLog(&_debugLogBuffer) +{ + _signalProxy->synchronize(_ircListHelper); +} + + +Client::~Client() +{ disconnectFromCore(); - return; - } - QVariantMap sessionState = coreState.toMap()["SessionState"].toMap(); - QVariantMap sessData = sessionState["SessionData"].toMap(); - - foreach(QString key, sessData.keys()) { - recvSessionData(key, sessData[key]); - } - QList coreBuffers = sessionState["Buffers"].toList(); - /* make lookups by id faster */ - foreach(QVariant vid, coreBuffers) { - BufferId id = vid.value(); - 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); +} + + +void Client::init() +{ + _networkModel = new NetworkModel(this); + + connect(this, SIGNAL(networkRemoved(NetworkId)), + _networkModel, SLOT(networkRemoved(NetworkId))); + + _bufferModel = new BufferModel(_networkModel); + _messageModel = mainUi()->createMessageModel(this); + _messageProcessor = mainUi()->createMessageProcessor(this); + _inputHandler = new ClientUserInputHandler(this); + + SignalProxy *p = signalProxy(); + + 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(bufferInfoUpdated(BufferInfo)), _networkModel, SLOT(bufferUpdated(BufferInfo))); + p->attachSignal(inputHandler(), SIGNAL(sendInput(BufferInfo, QString))); + p->attachSignal(this, SIGNAL(requestNetworkStates())); + + p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &, const QVariantMap &)), SIGNAL(createIdentity(const Identity &, const QVariantMap &))); + 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 &, const QStringList &)), SIGNAL(createNetwork(const NetworkInfo &, const QStringList &))); + 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(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())); + + // attach backlog manager + p->synchronize(backlogManager()); + connect(backlogManager(), SIGNAL(messagesReceived(BufferId, int)), _messageModel, SLOT(messagesReceived(BufferId, int))); + + coreAccountModel()->load(); + + connect(coreConnection(), SIGNAL(stateChanged(CoreConnection::ConnectionState)), SLOT(connectionStateChanged(CoreConnection::ConnectionState))); + coreConnection()->init(); +} + + +/*** public static methods ***/ + +AbstractUi *Client::mainUi() +{ + return instance()->_mainUi; +} + + +void Client::setCoreFeatures(Quassel::Features features) +{ + _coreFeatures = features; +} + + +bool Client::isConnected() +{ + return instance()->_connected; +} + + +bool Client::internalCore() +{ + return currentCoreAccount().isInternal(); +} + + +/*** Network handling ***/ + +QList Client::networkIds() +{ + return instance()->_networks.keys(); +} + + +const Network *Client::network(NetworkId networkid) +{ + if (instance()->_networks.contains(networkid)) return instance()->_networks[networkid]; + else return 0; +} + + +void Client::createNetwork(const NetworkInfo &info, const QStringList &persistentChannels) +{ + emit instance()->requestCreateNetwork(info, persistentChannels); +} + + +void Client::removeNetwork(NetworkId id) +{ + emit instance()->requestRemoveNetwork(id); +} + + +void Client::updateNetwork(const NetworkInfo &info) +{ + Network *netptr = instance()->_networks.value(info.networkId, 0); + if (!netptr) { + qWarning() << "Update for unknown network requested:" << info; + return; + } + netptr->requestSetNetworkInfo(info); +} + + +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; + } + Network *net = new Network(id, this); + addNetwork(net); +} + + +void Client::coreNetworkRemoved(NetworkId id) +{ + if (!_networks.contains(id)) + return; + Network *net = _networks.take(id); + emit networkRemoved(net->networkId()); + net->deleteLater(); +} + + +/*** Identity handling ***/ + +QList 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 CertIdentity &id) +{ + QVariantMap additional; +#ifdef HAVE_SSL + additional["KeyPem"] = id.sslKey().toPem(); + additional["CertPem"] = id.sslCert().toPem(); +#endif + emit instance()->requestCreateIdentity(id, additional); +} + + +void Client::updateIdentity(IdentityId id, const QVariantMap &ser) +{ + Identity *idptr = instance()->_identities.value(id, 0); + if (!idptr) { + qWarning() << "Update for unknown identity requested:" << id; + return; + } + idptr->requestUpdate(ser); +} + + +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(); + } +} + + +/*** User input handling ***/ + +void Client::userInput(const BufferInfo &bufferInfo, const QString &message) +{ + // we need to make sure that AliasManager is ready before processing input + if (aliasManager() && aliasManager()->isInitialized()) + inputHandler()->handleUserInput(bufferInfo, message); + else + instance()->_userInputBuffer.append(qMakePair(bufferInfo, message)); +} + + +void Client::sendBufferedUserInput() +{ + for (int i = 0; i < _userInputBuffer.count(); i++) + userInput(_userInputBuffer.at(i).first, _userInputBuffer.at(i).second); + + _userInputBuffer.clear(); +} + + +/*** core connection stuff ***/ + +void Client::connectionStateChanged(CoreConnection::ConnectionState state) +{ + switch (state) { + case CoreConnection::Disconnected: + setDisconnectedFromCore(); + break; + case CoreConnection::Synchronized: + setSyncedToCore(); + break; + default: + break; + } +} + + +void Client::setSyncedToCore() +{ + // create buffersyncer + Q_ASSERT(!_bufferSyncer); + _bufferSyncer = new BufferSyncer(this); + connect(bufferSyncer(), SIGNAL(lastSeenMsgSet(BufferId, MsgId)), _networkModel, SLOT(setLastSeenMsgId(BufferId, MsgId))); + connect(bufferSyncer(), SIGNAL(markerLineSet(BufferId, MsgId)), _networkModel, SLOT(setMarkerLineMsgId(BufferId, MsgId))); + connect(bufferSyncer(), SIGNAL(bufferRemoved(BufferId)), this, SLOT(bufferRemoved(BufferId))); + connect(bufferSyncer(), SIGNAL(bufferRenamed(BufferId, QString)), this, SLOT(bufferRenamed(BufferId, QString))); + connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), this, SLOT(buffersPermanentlyMerged(BufferId, BufferId))); + connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), _messageModel, SLOT(buffersPermanentlyMerged(BufferId, BufferId))); + connect(bufferSyncer(), SIGNAL(bufferMarkedAsRead(BufferId)), SIGNAL(bufferMarkedAsRead(BufferId))); + connect(networkModel(), SIGNAL(requestSetLastSeenMsg(BufferId, MsgId)), bufferSyncer(), SLOT(requestSetLastSeenMsg(BufferId, const MsgId &))); + + SignalProxy *p = signalProxy(); + + if ((Client::coreFeatures() & Quassel::PasswordChange)) { + p->attachSignal(this, SIGNAL(clientChangePassword(QString))); + } + + p->synchronize(bufferSyncer()); + + // create a new BufferViewManager + Q_ASSERT(!_bufferViewManager); + _bufferViewManager = new ClientBufferViewManager(p, this); + connect(_bufferViewManager, SIGNAL(initDone()), _bufferViewOverlay, SLOT(restore())); + + // create AliasManager + Q_ASSERT(!_aliasManager); + _aliasManager = new ClientAliasManager(this); + connect(aliasManager(), SIGNAL(initDone()), SLOT(sendBufferedUserInput())); + p->synchronize(aliasManager()); + + // create NetworkConfig + Q_ASSERT(!_networkConfig); + _networkConfig = new NetworkConfig("GlobalNetworkConfig", this); + p->synchronize(networkConfig()); + + // create IgnoreListManager + Q_ASSERT(!_ignoreListManager); + _ignoreListManager = new ClientIgnoreListManager(this); + p->synchronize(ignoreListManager()); + + Q_ASSERT(!_transferManager); + _transferManager = new ClientTransferManager(this); + p->synchronize(transferManager()); + + // trigger backlog request once all active bufferviews are initialized + connect(bufferViewOverlay(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog())); + + _connected = true; emit connected(); - } + emit coreConnectionStateChanged(true); } -void Client::recvSessionData(const QString &key, const QVariant &data) { - sessionData[key] = data; - emit sessionDataChanged(key, data); - emit sessionDataChanged(key); + +void Client::requestInitialBacklog() +{ + // usually it _should_ take longer until the bufferViews are initialized, so that's what + // triggers this slot. But we have to make sure that we know all buffers yet. + // so we check the BufferSyncer and in case it wasn't initialized we wait for that instead + if (!bufferSyncer()->isInitialized()) { + disconnect(bufferViewOverlay(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog())); + connect(bufferSyncer(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog())); + return; + } + disconnect(bufferViewOverlay(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog())); + disconnect(bufferSyncer(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog())); + + _backlogManager->requestInitialBacklog(); } -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); + +void Client::disconnectFromCore() +{ + if (!coreConnection()->isConnected()) + return; + + coreConnection()->disconnectFromCore(); } -QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) { - if(instance()->sessionData.contains(key)) return instance()->sessionData[key]; - else return def; + +void Client::setDisconnectedFromCore() +{ + _connected = false; + _coreFeatures = 0; + + emit disconnected(); + emit coreConnectionStateChanged(false); + + backlogManager()->reset(); + messageProcessor()->reset(); + + // Clear internal data. Hopefully nothing relies on it at this point. + + if (_bufferSyncer) { + _bufferSyncer->deleteLater(); + _bufferSyncer = 0; + } + + if (_bufferViewManager) { + _bufferViewManager->deleteLater(); + _bufferViewManager = 0; + } + + _bufferViewOverlay->reset(); + + if (_aliasManager) { + _aliasManager->deleteLater(); + _aliasManager = 0; + } + + if (_ignoreListManager) { + _ignoreListManager->deleteLater(); + _ignoreListManager = 0; + } + + if (_transferManager) { + _transferManager->deleteLater(); + _transferManager = 0; + } + + // we probably don't want to save pending input for reconnect + _userInputBuffer.clear(); + + _messageModel->clear(); + _networkModel->clear(); + + QHash::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::iterator idIter = _identities.begin(); + while (idIter != _identities.end()) { + emit identityRemoved(idIter.key()); + Identity *id = idIter.value(); + idIter = _identities.erase(idIter); + id->deleteLater(); + } + Q_ASSERT(_identities.isEmpty()); + + if (_networkConfig) { + _networkConfig->deleteLater(); + _networkConfig = 0; + } +} + + +/*** ***/ + +void Client::networkDestroyed() +{ + Network *net = static_cast(sender()); + QHash::iterator netIter = _networks.begin(); + while (netIter != _networks.end()) { + if (*netIter == net) { + netIter = _networks.erase(netIter); + break; + } + else { + netIter++; + } + } +} + + +// Hmm... we never used this... +void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) +{ + //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg))); +} + + +void Client::recvMessage(const Message &msg) +{ + Message msg_ = msg; + messageProcessor()->process(msg_); } -QStringList Client::sessionDataKeys() { - return instance()->sessionData.keys(); + +void Client::setBufferLastSeenMsg(BufferId id, const MsgId &msgId) +{ + if (bufferSyncer()) + bufferSyncer()->requestSetLastSeenMsg(id, msgId); } -void Client::coreSocketError(QAbstractSocket::SocketError) { - emit coreConnectionError(socket->errorString()); -} -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::setMarkerLine(BufferId id, const MsgId &msgId) +{ + if (bufferSyncer()) + bufferSyncer()->requestSetMarkerLine(id, msgId); +} + -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(); +MsgId Client::markerLine(BufferId id) +{ + if (id.isValid() && networkModel()) + return networkModel()->markerLineMsgId(id); + return MsgId(); } -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::removeBuffer(BufferId id) +{ + if (!bufferSyncer()) return; + bufferSyncer()->requestRemoveBuffer(id); } -void Client::updateBufferId(BufferId id) { - bufferIds[id.uid()] = id; // make lookups by id faster - buffer(id); + +void Client::renameBuffer(BufferId bufferId, const QString &newName) +{ + if (!bufferSyncer()) + return; + bufferSyncer()->requestRenameBuffer(bufferId, newName); } -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::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2) +{ + if (!bufferSyncer()) + return; + bufferSyncer()->requestMergeBuffersPermanently(bufferId1, bufferId2); } -BufferId Client::statusBufferId(QString net) { - return bufferId(net, ""); + +void Client::purgeKnownBufferIds() +{ + if (!bufferSyncer()) + return; + bufferSyncer()->requestPurgeBufferIds(); } -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]; +void Client::bufferRemoved(BufferId bufferId) +{ + // 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) { + bufferModel()->setCurrentIndex(current.sibling(0, 0)); + } + + // and remove it from the model + networkModel()->removeBuffer(bufferId); } -QList Client::allBufferIds() { - return buffers.keys(); + +void Client::bufferRenamed(BufferId bufferId, const QString &newName) +{ + QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId); + if (bufferIndex.isValid()) { + networkModel()->setData(bufferIndex, newName, Qt::DisplayRole); + } } -void Client::removeBuffer(Buffer *b) { - buffers.remove(b->bufferId()); - bufferIds.remove(b->bufferId().uid()); + +void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) +{ + QModelIndex idx = networkModel()->bufferIndex(bufferId1); + bufferModel()->setCurrentIndex(bufferModel()->mapFromSource(idx)); + networkModel()->removeBuffer(bufferId2); } -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::recvMessage(const Message &msg) { - Buffer *b = buffer(msg.buffer); - - Buffer::ActivityLevel level = Buffer::OtherActivity; - if(msg.type == Message::Plain || msg.type == Message::Notice){ - level |= Buffer::NewMessage; - } - if(msg.flags & Message::Highlight){ - level |= Buffer::Highlight; - } - emit bufferActivity(level, b); - - b->appendMsg(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*/) { - Buffer *b = buffer(id); - foreach(QVariant v, msgs) { - Message msg = v.value(); - b->prependMsg(msg); - if(!layoutQueue.contains(b)) layoutQueue.append(b); - } - if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start(); -} - -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.count()) layoutTimer->stop(); + +void Client::markBufferAsRead(BufferId id) +{ + if (bufferSyncer() && id.isValid()) + bufferSyncer()->requestMarkBufferAsRead(id); } - -AbstractUiMsg *Client::layoutMsg(const Message &msg) { - return instance()->mainUi->layoutMsg(msg); -} - -void Client::userInput(BufferId 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::changePassword(QString newPassword) { + CoreAccount account = currentCoreAccount(); + account.setPassword(newPassword); + coreAccountModel()->createOrUpdateAccount(account); + coreAccountModel()->save(); + emit clientChangePassword(newPassword); } -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); + +#if QT_VERSION < 0x050000 +void Client::logMessage(QtMsgType type, const char *msg) +{ + fprintf(stderr, "%s\n", msg); + fflush(stderr); + if (type == QtFatalMsg) { + Quassel::logFatalMessage(msg); + } + else { + QString msgString = QString("%1\n").arg(msg); + + //Check to see if there is an instance around, else we risk recursions + //when calling instance() and creating new ones. + if (!instanceExists()) + return; + + instance()->_debugLog << msgString; + emit instance()->logUpdated(msgString); } - } } +#else +void Client::logMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg) +{ + Q_UNUSED(context); + fprintf(stderr, "%s\n", msg.toLocal8Bit().constData()); + fflush(stderr); + if (type == QtFatalMsg) { + Quassel::logFatalMessage(msg.toLocal8Bit().constData()); + } + else { + QString msgString = QString("%1\n").arg(msg); + + //Check to see if there is an instance around, else we risk recursions + //when calling instance() and creating new ones. + if (!instanceExists()) + return; + + instance()->_debugLog << msgString; + emit instance()->logUpdated(msgString); + } +} +#endif