Features come and features go...
[quassel.git] / src / client / client.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "client.h"
22
23 #include "bufferinfo.h"
24 #include "global.h"
25 #include "identity.h"
26 #include "ircchannel.h"
27 #include "ircuser.h"
28 #include "message.h"
29 #include "network.h"
30 #include "networkmodel.h"
31 #include "buffermodel.h"
32 #include "quasselui.h"
33 #include "signalproxy.h"
34 #include "util.h"
35
36 QPointer<Client> Client::instanceptr = 0;
37
38 /*** Initialization/destruction ***/
39
40 Client *Client::instance() {
41   if(!instanceptr)
42     instanceptr = new Client();
43   return instanceptr;
44 }
45
46 void Client::destroy() {
47   delete instanceptr;
48 }
49
50 void Client::init(AbstractUi *ui) {
51   instance()->mainUi = ui;
52   instance()->init();
53 }
54
55 Client::Client(QObject *parent)
56   : QObject(parent),
57     socket(0),
58     _signalProxy(new SignalProxy(SignalProxy::Client, this)),
59     mainUi(0),
60     _networkModel(0),
61     _bufferModel(0),
62     connectedToCore(false)
63 {
64 }
65
66 Client::~Client() {
67 }
68
69 void Client::init() {
70   blockSize = 0;
71
72   _networkModel = new NetworkModel(this);
73   connect(this, SIGNAL(bufferUpdated(BufferInfo)),
74           _networkModel, SLOT(bufferUpdated(BufferInfo)));
75
76   _bufferModel = new BufferModel(_networkModel);
77
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)));
93
94
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()));
99
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)));
105
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()));
110
111   layoutTimer = new QTimer(this);
112   layoutTimer->setInterval(0);
113   layoutTimer->setSingleShot(false);
114   connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
115
116 }
117
118 /*** public static methods ***/
119
120
121 QList<Network *> Client::networks() {
122   return instance()->_network.values();
123 }
124
125 Network *Client::network(uint networkid) {
126   if(instance()->_network.contains(networkid))
127     return instance()->_network[networkid];
128   else
129     return 0;
130 }
131
132 QList<BufferInfo> Client::allBufferInfos() {
133   QList<BufferInfo> bufferids;
134   foreach(Buffer *buffer, buffers()) {
135     bufferids << buffer->bufferInfo();
136   }
137   return bufferids;
138 }
139
140 QList<Buffer *> Client::buffers() {
141   return instance()->_buffers.values();
142 }
143
144 Buffer *Client::buffer(uint bufferUid) {
145   if(instance()->_buffers.contains(bufferUid))
146     return instance()->_buffers[bufferUid];
147   else
148     return 0;
149 }
150
151 Buffer *Client::buffer(BufferInfo id) {
152   Buffer *buff = buffer(id.uid());
153
154   if(!buff) {
155     Client *client = Client::instance();
156     buff = new Buffer(id, client);
157
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);
164   }
165   Q_ASSERT(buff);
166   return buff;
167 }
168
169 NetworkModel *Client::networkModel() {
170   return instance()->_networkModel;
171 }
172
173 BufferModel *Client::bufferModel() {
174   return instance()->_bufferModel;
175 }
176
177
178 SignalProxy *Client::signalProxy() {
179   return instance()->_signalProxy;
180 }
181
182
183 /*** Identity handling ***/
184
185 QList<IdentityId> Client::identityIds() {
186   return instance()->_identities.keys();
187 }
188
189 const Identity * Client::identity(IdentityId id) {
190   if(instance()->_identities.contains(id)) return instance()->_identities[id];
191   else return 0;
192 }
193
194
195 void Client::createIdentity(const Identity &id) {
196   emit instance()->requestCreateIdentity(id);
197 }
198
199 void Client::updateIdentity(const Identity &id) {
200   emit instance()->requestUpdateIdentity(id);
201 }
202
203 void Client::removeIdentity(IdentityId id) {
204   emit instance()->requestRemoveIdentity(id);
205 }
206
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());
214   } else {
215     qWarning() << tr("Identity already exists in client!");
216   }
217 }
218
219 void Client::coreIdentityRemoved(IdentityId id) {
220   if(_identities.contains(id)) {
221     emit identityRemoved(id);
222     Identity *i = _identities.take(id);
223     i->deleteLater();
224   }
225 }
226
227 /***  ***/
228
229
230 bool Client::isConnected() {
231   return instance()->connectedToCore;
232 }
233
234 void Client::fakeInput(uint bufferUid, QString message) {
235   Buffer *buff = buffer(bufferUid);
236   if(!buff)
237     qWarning() << "No Buffer with uid" << bufferUid << "can't send Input" << message;
238   else
239     emit instance()->sendInput(buff->bufferInfo(), message);
240 }
241
242 void Client::fakeInput(BufferInfo bufferInfo, QString message) {
243   fakeInput(bufferInfo, message);
244 }
245
246 void Client::connectToCore(const QVariantMap &conn) {
247   // TODO implement SSL
248   coreConnectionInfo = conn;
249   if(isConnected()) {
250     emit coreConnectionError(tr("Already connected to Core!"));
251     return;
252   }
253   
254   if(socket != 0)
255     socket->deleteLater();
256   
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());
263     //syncToCore(state);
264     coreSocketConnected();
265   } else {
266     clientMode = RemoteCore;
267     emit coreConnectionMsg(tr("Connecting..."));
268     Q_ASSERT(!socket);
269     QTcpSocket *sock = new QTcpSocket(this);
270     socket = sock;
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());
276   }
277 }
278
279 void Client::disconnectFromCore() {
280   socket->close();
281 }
282
283 void Client::setCoreConfiguration(const QVariantMap &settings) {
284   SignalProxy::writeDataToDevice(socket, settings);
285 }
286
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);
295 }
296
297 void Client::coreSocketDisconnected() {
298   instance()->connectedToCore = false;
299   emit disconnected();
300   emit coreConnectionStateChanged(false);
301   socket->deleteLater();
302   blockSize = 0;
303
304   /* Clear internal data. Hopefully nothing relies on it at this point. */
305   _networkModel->clear();
306
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();
313   }
314   Q_ASSERT(_buffers.isEmpty());
315
316
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);
322     net->deleteLater();
323   }
324   Q_ASSERT(_network.isEmpty());
325
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);
331     id->deleteLater();
332   }
333   Q_ASSERT(_identities.isEmpty());
334
335   coreConnectionInfo.clear();
336   sessionData.clear();
337   layoutQueue.clear();
338   layoutTimer->stop();
339 }
340
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);
345   syncToCore(state);
346 }
347
348 // TODO: auth errors
349 void Client::syncToCore(const QVariant &coreState) {
350   if(!coreState.toMap().contains("SessionState")) {
351     emit coreConnectionError(tr("Invalid data received from core!"));
352     disconnectFromCore();
353     return;
354   }
355
356   QVariantMap sessionState = coreState.toMap()["SessionState"].toMap();
357
358   // store sessionData
359   QVariantMap sessData = sessionState["SessionData"].toMap();
360   foreach(QString key, sessData.keys())
361     recvSessionData(key, sessData[key]);
362
363   // create identities
364   foreach(QVariant vid, sessionState["Identities"].toList()) {
365     coreIdentityCreated(vid.value<Identity>());
366   }
367
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
373   }
374
375   // create network objects
376   QVariantList networkids = sessionState["Networks"].toList();
377   foreach(QVariant networkid, networkids) {
378     networkConnected(networkid.toUInt());
379   }
380
381   instance()->connectedToCore = true;
382   updateCoreConnectionProgress();
383
384 }
385
386 void Client::updateCoreConnectionProgress() {
387   // we'll do this in three steps:
388   // 1.) networks
389   // 2.) channels
390   // 3.) ircusers
391
392   int numNets = networks().count();
393   int numNetsWaiting = 0;
394
395   int numIrcUsers = 0;
396   int numIrcUsersWaiting = 0;
397
398   int numChannels = 0;
399   int numChannelsWaiting = 0;
400
401   foreach(Network *net, networks()) {
402     if(! net->initialized())
403       numNetsWaiting++;
404
405     numIrcUsers += net->ircUsers().count();
406     foreach(IrcUser *user, net->ircUsers()) {
407       if(! user->initialized())
408         numIrcUsersWaiting++;
409     }
410
411     numChannels += net->ircChannels().count();
412     foreach(IrcChannel *channel, net->ircChannels()) {
413       if(! channel->initialized())
414         numChannelsWaiting++;
415     }
416   }
417
418   if(numNetsWaiting > 0) {
419     emit coreConnectionMsg(tr("Requesting network states..."));
420     emit coreConnectionProgress(numNets - numNetsWaiting, numNets);
421     return;
422   }
423
424   if(numIrcUsersWaiting > 0) {
425     emit coreConnectionMsg(tr("Requesting User states..."));
426     emit coreConnectionProgress(numIrcUsers - numIrcUsersWaiting, numIrcUsers);
427     return;
428   }
429
430   if(numChannelsWaiting > 0) {
431     emit coreConnectionMsg(tr("Requesting Channel states..."));
432     emit coreConnectionProgress(numChannels - numChannelsWaiting, numChannels);
433     return;
434   }
435
436   emit coreConnectionProgress(1,1);
437   emit connected();
438   emit coreConnectionStateChanged(true);
439   foreach(Network *net, networks()) {
440     disconnect(net, 0, this, SLOT(updateCoreConnectionProgress()));
441   }
442
443   // signalProxy()->dumpProxyStats();
444 }
445
446 void Client::recvSessionData(const QString &key, const QVariant &data) {
447   sessionData[key] = data;
448   emit sessionDataChanged(key, data);
449   emit sessionDataChanged(key);
450 }
451
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);
457 }
458
459 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
460   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
461   else return def;
462 }
463
464 QStringList Client::sessionDataKeys() {
465   return instance()->sessionData.keys();
466 }
467
468 void Client::coreSocketError(QAbstractSocket::SocketError) {
469   emit coreConnectionError(socket->errorString());
470   socket->deleteLater();
471 }
472
473 void Client::coreHasData() {
474   QVariant item;
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"]);
480     } else {
481       qWarning("Core not configured!");
482       qDebug() << "Available storage providers: " << msg["StorageProviders"].toStringList();
483       emit showConfigWizard(msg);
484     }
485     blockSize = 0;
486     return;
487   }
488   if(blockSize > 0) {
489     emit recvPartialItem(socket->bytesAvailable(), blockSize);
490   }
491 }
492
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);
498
499   Network *netinfo = new Network(netid, this);
500   netinfo->setProxy(signalProxy());
501   networkModel()->attachNetwork(netinfo);
502   
503   if(!isConnected()) {
504     connect(netinfo, SIGNAL(initDone()), this, SLOT(updateCoreConnectionProgress()));
505     connect(netinfo, SIGNAL(ircUserInitDone()), this, SLOT(updateCoreConnectionProgress()));
506     connect(netinfo, SIGNAL(ircChannelInitDone()), this, SLOT(updateCoreConnectionProgress()));
507   }
508   connect(netinfo, SIGNAL(destroyed()), this, SLOT(networkDestroyed()));
509   _network[netid] = netinfo;
510 }
511
512 void Client::networkDisconnected(uint networkid) {
513   if(!_network.contains(networkid)) {
514     qWarning() << "Client::networkDisconnected(uint): unknown Network" << networkid;
515     return;
516   }
517
518   Network *net = _network.take(networkid);
519   if(!net->initialized()) {
520     qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
521     updateCoreConnectionProgress();
522   }
523   net->deleteLater();
524 }
525
526 void Client::updateBufferInfo(BufferInfo id) {
527   emit bufferUpdated(id);
528 }
529
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);
536       break;
537     }
538     iter++;
539   }
540 }
541
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);
547 }
548
549 void Client::recvMessage(const Message &msg) {
550   Buffer *b = buffer(msg.buffer());
551
552 //   Buffer::ActivityLevel level = Buffer::OtherActivity;
553 //   if(msg.type() == Message::Plain || msg.type() == Message::Notice){
554 //     level |= Buffer::NewMessage;
555 //   }
556 //   if(msg.flags() & Message::Highlight){
557 //     level |= Buffer::Highlight;
558 //   }
559 //   emit bufferActivity(level, b);
560
561   b->appendMsg(msg);
562 }
563
564 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
565   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
566 }
567
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>();
572     b->prependMsg(msg);
573     if(!layoutQueue.contains(b)) layoutQueue.append(b);
574   }
575   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
576 }
577
578 void Client::layoutMsg() {
579   if(layoutQueue.count()) {
580     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
581     if(b->layoutMsg())
582       layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
583   }
584   
585   if(!layoutQueue.count())
586     layoutTimer->stop();
587 }
588
589 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
590   return instance()->mainUi->layoutMsg(msg);
591 }
592
593 void Client::userInput(BufferInfo id, QString msg) {
594   emit sendInput(id, msg);
595 }
596