1 /***************************************************************************
2 * Copyright (C) 2005-08 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
23 #include "bufferinfo.h"
26 #include "ircchannel.h"
30 #include "networkmodel.h"
31 #include "buffermodel.h"
32 #include "quasselui.h"
33 #include "signalproxy.h"
36 QPointer<Client> Client::instanceptr = 0;
38 /*** Initialization/destruction ***/
40 Client *Client::instance() {
42 instanceptr = new Client();
46 void Client::destroy() {
50 void Client::init(AbstractUi *ui) {
51 instance()->mainUi = ui;
55 Client::Client(QObject *parent)
58 _signalProxy(new SignalProxy(SignalProxy::Client, this)),
62 connectedToCore(false)
72 _networkModel = new NetworkModel(this);
73 connect(this, SIGNAL(bufferUpdated(BufferInfo)),
74 _networkModel, SLOT(bufferUpdated(BufferInfo)));
76 _bufferModel = new BufferModel(_networkModel);
78 SignalProxy *p = signalProxy();
79 p->attachSignal(this, SIGNAL(sendSessionData(const QString &, const QVariant &)),
80 SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)));
81 p->attachSlot(SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)),
82 this, SLOT(recvSessionData(const QString &, const QVariant &)));
83 p->attachSlot(SIGNAL(coreState(const QVariant &)),
84 this, SLOT(recvCoreState(const QVariant &)));
85 p->attachSlot(SIGNAL(networkConnected(uint)),
86 this, SLOT(networkConnected(uint)));
87 p->attachSlot(SIGNAL(networkDisconnected(uint)),
88 this, SLOT(networkDisconnected(uint)));
89 p->attachSlot(SIGNAL(displayMsg(const Message &)),
90 this, SLOT(recvMessage(const Message &)));
91 p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)),
92 this, SLOT(recvStatusMsg(QString, QString)));
95 p->attachSlot(SIGNAL(backlogData(BufferInfo, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferInfo, const QVariantList &, bool)));
96 p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), this, SLOT(updateBufferInfo(BufferInfo)));
97 p->attachSignal(this, SIGNAL(sendInput(BufferInfo, QString)));
98 p->attachSignal(this, SIGNAL(requestNetworkStates()));
100 p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &)), SIGNAL(createIdentity(const Identity &)));
101 p->attachSignal(this, SIGNAL(requestUpdateIdentity(const Identity &)), SIGNAL(updateIdentity(const Identity &)));
102 p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
103 p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
104 p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
106 connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
107 connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
108 connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
109 connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
111 layoutTimer = new QTimer(this);
112 layoutTimer->setInterval(0);
113 layoutTimer->setSingleShot(false);
114 connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
118 /*** public static methods ***/
121 QList<Network *> Client::networks() {
122 return instance()->_network.values();
125 Network *Client::network(uint networkid) {
126 if(instance()->_network.contains(networkid))
127 return instance()->_network[networkid];
132 QList<BufferInfo> Client::allBufferInfos() {
133 QList<BufferInfo> bufferids;
134 foreach(Buffer *buffer, buffers()) {
135 bufferids << buffer->bufferInfo();
140 QList<Buffer *> Client::buffers() {
141 return instance()->_buffers.values();
144 Buffer *Client::buffer(uint bufferUid) {
145 if(instance()->_buffers.contains(bufferUid))
146 return instance()->_buffers[bufferUid];
151 Buffer *Client::buffer(BufferInfo id) {
152 Buffer *buff = buffer(id.uid());
155 Client *client = Client::instance();
156 buff = new Buffer(id, client);
158 connect(buff, SIGNAL(userInput(BufferInfo, QString)),
159 client, SLOT(userInput(BufferInfo, QString)));
160 connect(buff, SIGNAL(destroyed()),
161 client, SLOT(bufferDestroyed()));
162 client->_buffers[id.uid()] = buff;
163 emit client->bufferUpdated(id);
169 NetworkModel *Client::networkModel() {
170 return instance()->_networkModel;
173 BufferModel *Client::bufferModel() {
174 return instance()->_bufferModel;
178 SignalProxy *Client::signalProxy() {
179 return instance()->_signalProxy;
183 /*** Identity handling ***/
185 QList<IdentityId> Client::identityIds() {
186 return instance()->_identities.keys();
189 const Identity * Client::identity(IdentityId id) {
190 if(instance()->_identities.contains(id)) return instance()->_identities[id];
195 void Client::createIdentity(const Identity &id) {
196 emit instance()->requestCreateIdentity(id);
199 void Client::updateIdentity(const Identity &id) {
200 emit instance()->requestUpdateIdentity(id);
203 void Client::removeIdentity(IdentityId id) {
204 emit instance()->requestRemoveIdentity(id);
207 void Client::coreIdentityCreated(const Identity &other) {
208 if(!_identities.contains(other.id())) {
209 Identity *identity = new Identity(other, this);
210 _identities[other.id()] = identity;
211 identity->setInitialized();
212 signalProxy()->synchronize(identity);
213 emit identityCreated(other.id());
215 qWarning() << tr("Identity already exists in client!");
219 void Client::coreIdentityRemoved(IdentityId id) {
220 if(_identities.contains(id)) {
221 emit identityRemoved(id);
222 Identity *i = _identities.take(id);
230 bool Client::isConnected() {
231 return instance()->connectedToCore;
234 void Client::fakeInput(uint bufferUid, QString message) {
235 Buffer *buff = buffer(bufferUid);
237 qWarning() << "No Buffer with uid" << bufferUid << "can't send Input" << message;
239 emit instance()->sendInput(buff->bufferInfo(), message);
242 void Client::fakeInput(BufferInfo bufferInfo, QString message) {
243 fakeInput(bufferInfo, message);
246 void Client::connectToCore(const QVariantMap &conn) {
247 // TODO implement SSL
248 coreConnectionInfo = conn;
250 emit coreConnectionError(tr("Already connected to Core!"));
255 socket->deleteLater();
257 if(conn["Host"].toString().isEmpty()) {
258 clientMode = LocalCore;
259 socket = new QBuffer(this);
260 connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
261 socket->open(QIODevice::ReadWrite);
262 //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
264 coreSocketConnected();
266 clientMode = RemoteCore;
267 emit coreConnectionMsg(tr("Connecting..."));
269 QTcpSocket *sock = new QTcpSocket(this);
271 connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
272 connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
273 connect(signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
274 connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
275 sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
279 void Client::disconnectFromCore() {
283 void Client::setCoreConfiguration(const QVariantMap &settings) {
284 SignalProxy::writeDataToDevice(socket, settings);
287 void Client::coreSocketConnected() {
288 connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
289 emit coreConnectionMsg(tr("Synchronizing to core..."));
290 QVariantMap clientInit;
291 clientInit["GuiProtocol"] = GUI_PROTOCOL;
292 clientInit["User"] = coreConnectionInfo["User"].toString();
293 clientInit["Password"] = coreConnectionInfo["Password"].toString();
294 SignalProxy::writeDataToDevice(socket, clientInit);
297 void Client::coreSocketDisconnected() {
298 instance()->connectedToCore = false;
300 emit coreConnectionStateChanged(false);
301 socket->deleteLater();
304 /* Clear internal data. Hopefully nothing relies on it at this point. */
305 _networkModel->clear();
307 QHash<BufferId, Buffer *>::iterator bufferIter = _buffers.begin();
308 while(bufferIter != _buffers.end()) {
309 Buffer *buffer = bufferIter.value();
310 disconnect(buffer, SIGNAL(destroyed()), this, 0);
311 bufferIter = _buffers.erase(bufferIter);
312 buffer->deleteLater();
314 Q_ASSERT(_buffers.isEmpty());
317 QHash<NetworkId, Network*>::iterator netIter = _network.begin();
318 while(netIter != _network.end()) {
319 Network *net = netIter.value();
320 disconnect(net, SIGNAL(destroyed()), this, 0);
321 netIter = _network.erase(netIter);
324 Q_ASSERT(_network.isEmpty());
326 QHash<IdentityId, Identity*>::iterator idIter = _identities.begin();
327 while(idIter != _identities.end()) {
328 Identity *id = idIter.value();
329 emit identityRemoved(id->id());
330 idIter = _identities.erase(idIter);
333 Q_ASSERT(_identities.isEmpty());
335 coreConnectionInfo.clear();
341 void Client::recvCoreState(const QVariant &state) {
342 disconnect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
343 disconnect(socket, 0, this, 0); // rest of communication happens through SignalProxy
344 signalProxy()->addPeer(socket);
349 void Client::syncToCore(const QVariant &coreState) {
350 if(!coreState.toMap().contains("SessionState")) {
351 emit coreConnectionError(tr("Invalid data received from core!"));
352 disconnectFromCore();
356 QVariantMap sessionState = coreState.toMap()["SessionState"].toMap();
359 QVariantMap sessData = sessionState["SessionData"].toMap();
360 foreach(QString key, sessData.keys())
361 recvSessionData(key, sessData[key]);
364 foreach(QVariant vid, sessionState["Identities"].toList()) {
365 coreIdentityCreated(vid.value<Identity>());
368 // store Buffer details
369 QVariantList coreBuffers = sessionState["Buffers"].toList();
370 /* make lookups by id faster */
371 foreach(QVariant vid, coreBuffers) {
372 buffer(vid.value<BufferInfo>()); // create all buffers, so we see them in the network views
375 // create network objects
376 QVariantList networkids = sessionState["Networks"].toList();
377 foreach(QVariant networkid, networkids) {
378 networkConnected(networkid.toUInt());
381 instance()->connectedToCore = true;
382 updateCoreConnectionProgress();
386 void Client::updateCoreConnectionProgress() {
387 // we'll do this in three steps:
392 int numNets = networks().count();
393 int numNetsWaiting = 0;
396 int numIrcUsersWaiting = 0;
399 int numChannelsWaiting = 0;
401 foreach(Network *net, networks()) {
402 if(! net->initialized())
405 numIrcUsers += net->ircUsers().count();
406 foreach(IrcUser *user, net->ircUsers()) {
407 if(! user->initialized())
408 numIrcUsersWaiting++;
411 numChannels += net->ircChannels().count();
412 foreach(IrcChannel *channel, net->ircChannels()) {
413 if(! channel->initialized())
414 numChannelsWaiting++;
418 if(numNetsWaiting > 0) {
419 emit coreConnectionMsg(tr("Requesting network states..."));
420 emit coreConnectionProgress(numNets - numNetsWaiting, numNets);
424 if(numIrcUsersWaiting > 0) {
425 emit coreConnectionMsg(tr("Requesting User states..."));
426 emit coreConnectionProgress(numIrcUsers - numIrcUsersWaiting, numIrcUsers);
430 if(numChannelsWaiting > 0) {
431 emit coreConnectionMsg(tr("Requesting Channel states..."));
432 emit coreConnectionProgress(numChannels - numChannelsWaiting, numChannels);
436 emit coreConnectionProgress(1,1);
438 emit coreConnectionStateChanged(true);
439 foreach(Network *net, networks()) {
440 disconnect(net, 0, this, SLOT(updateCoreConnectionProgress()));
443 // signalProxy()->dumpProxyStats();
446 void Client::recvSessionData(const QString &key, const QVariant &data) {
447 sessionData[key] = data;
448 emit sessionDataChanged(key, data);
449 emit sessionDataChanged(key);
452 void Client::storeSessionData(const QString &key, const QVariant &data) {
453 // Not sure if this is a good idea, but we'll try it anyway:
454 // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
455 // rather than immediately.
456 emit instance()->sendSessionData(key, data);
459 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
460 if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
464 QStringList Client::sessionDataKeys() {
465 return instance()->sessionData.keys();
468 void Client::coreSocketError(QAbstractSocket::SocketError) {
469 emit coreConnectionError(socket->errorString());
470 socket->deleteLater();
473 void Client::coreHasData() {
475 if(SignalProxy::readDataFromDevice(socket, blockSize, item)) {
476 emit recvPartialItem(1,1);
477 QVariantMap msg = item.toMap();
478 if (!msg["StartWizard"].toBool()) {
479 recvCoreState(msg["Reply"]);
481 qWarning("Core not configured!");
482 qDebug() << "Available storage providers: " << msg["StorageProviders"].toStringList();
483 emit showConfigWizard(msg);
489 emit recvPartialItem(socket->bytesAvailable(), blockSize);
493 void Client::networkConnected(uint netid) {
494 // TODO: create statusBuffer / switch to networkids
495 //BufferInfo id = statusBufferInfo(net);
496 //Buffer *b = buffer(id);
497 //b->setActive(true);
499 Network *netinfo = new Network(netid, this);
500 netinfo->setProxy(signalProxy());
501 networkModel()->attachNetwork(netinfo);
504 connect(netinfo, SIGNAL(initDone()), this, SLOT(updateCoreConnectionProgress()));
505 connect(netinfo, SIGNAL(ircUserInitDone()), this, SLOT(updateCoreConnectionProgress()));
506 connect(netinfo, SIGNAL(ircChannelInitDone()), this, SLOT(updateCoreConnectionProgress()));
508 connect(netinfo, SIGNAL(destroyed()), this, SLOT(networkDestroyed()));
509 _network[netid] = netinfo;
512 void Client::networkDisconnected(uint networkid) {
513 if(!_network.contains(networkid)) {
514 qWarning() << "Client::networkDisconnected(uint): unknown Network" << networkid;
518 Network *net = _network.take(networkid);
519 if(!net->initialized()) {
520 qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
521 updateCoreConnectionProgress();
526 void Client::updateBufferInfo(BufferInfo id) {
527 emit bufferUpdated(id);
530 void Client::bufferDestroyed() {
531 Buffer *buffer = static_cast<Buffer *>(sender());
532 QHash<BufferId, Buffer *>::iterator iter = _buffers.begin();
533 while(iter != _buffers.end()) {
534 if(iter.value() == buffer) {
535 iter = _buffers.erase(iter);
542 void Client::networkDestroyed() {
543 Network *netinfo = static_cast<Network *>(sender());
544 uint networkId = netinfo->networkId();
545 if(_network.contains(networkId))
546 _network.remove(networkId);
549 void Client::recvMessage(const Message &msg) {
550 Buffer *b = buffer(msg.buffer());
552 // Buffer::ActivityLevel level = Buffer::OtherActivity;
553 // if(msg.type() == Message::Plain || msg.type() == Message::Notice){
554 // level |= Buffer::NewMessage;
556 // if(msg.flags() & Message::Highlight){
557 // level |= Buffer::Highlight;
559 // emit bufferActivity(level, b);
564 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
565 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
568 void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
569 Buffer *b = buffer(id);
570 foreach(QVariant v, msgs) {
571 Message msg = v.value<Message>();
573 if(!layoutQueue.contains(b)) layoutQueue.append(b);
575 if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
578 void Client::layoutMsg() {
579 if(layoutQueue.count()) {
580 Buffer *b = layoutQueue.takeFirst(); // TODO make this the current buffer
582 layoutQueue.append(b); // Buffer has more messages in its queue --> Round Robin
585 if(!layoutQueue.count())
589 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
590 return instance()->mainUi->layoutMsg(msg);
593 void Client::userInput(BufferInfo id, QString msg) {
594 emit sendInput(id, msg);