Who stole the ! from main.cpp?
[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 "networkinfo.h"
30 #include "networkmodel.h"
31 #include "quasselui.h"
32 #include "signalproxy.h"
33 #include "util.h"
34
35 QPointer<Client> Client::instanceptr = 0;
36
37 /*** Initialization/destruction ***/
38
39 Client *Client::instance() {
40   if(!instanceptr)
41     instanceptr = new Client();
42   return instanceptr;
43 }
44
45 void Client::destroy() {
46   delete instanceptr;
47 }
48
49 void Client::init(AbstractUi *ui) {
50   instance()->mainUi = ui;
51   instance()->init();
52 }
53
54 Client::Client(QObject *parent)
55     : QObject(parent),
56     socket(0),
57     _signalProxy(new SignalProxy(SignalProxy::Client, this)),
58     mainUi(0),
59     _networkModel(0),
60     connectedToCore(false)
61 {
62
63 }
64
65 Client::~Client() {
66
67 }
68
69 void Client::init() {
70   blockSize = 0;
71
72   _networkModel = new NetworkModel(this);
73
74   connect(this, SIGNAL(bufferSelected(Buffer *)),
75           _networkModel, SLOT(selectBuffer(Buffer *)));
76   connect(this, SIGNAL(bufferUpdated(Buffer *)),
77           _networkModel, SLOT(bufferUpdated(Buffer *)));
78   connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)),
79           _networkModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
80
81   SignalProxy *p = signalProxy();
82   p->attachSignal(this, SIGNAL(sendSessionData(const QString &, const QVariant &)),
83                   SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)));
84   p->attachSlot(SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)),
85                 this, SLOT(recvSessionData(const QString &, const QVariant &)));
86   p->attachSlot(SIGNAL(coreState(const QVariant &)),
87                 this, SLOT(recvCoreState(const QVariant &)));
88   p->attachSlot(SIGNAL(networkConnected(uint)),
89                 this, SLOT(networkConnected(uint)));
90   p->attachSlot(SIGNAL(networkDisconnected(uint)),
91                 this, SLOT(networkDisconnected(uint)));
92   p->attachSlot(SIGNAL(displayMsg(const Message &)),
93                 this, SLOT(recvMessage(const Message &)));
94   p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)),
95                 this, SLOT(recvStatusMsg(QString, QString)));
96
97
98   p->attachSlot(SIGNAL(backlogData(BufferInfo, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferInfo, const QVariantList &, bool)));
99   p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), this, SLOT(updateBufferInfo(BufferInfo)));
100   p->attachSignal(this, SIGNAL(sendInput(BufferInfo, QString)));
101   p->attachSignal(this, SIGNAL(requestNetworkStates()));
102
103   p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &)), SIGNAL(createIdentity(const Identity &)));
104   p->attachSignal(this, SIGNAL(requestUpdateIdentity(const Identity &)), SIGNAL(updateIdentity(const Identity &)));
105   p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
106   p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
107   p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
108
109   connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
110   connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
111   connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
112   connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
113
114   layoutTimer = new QTimer(this);
115   layoutTimer->setInterval(0);
116   layoutTimer->setSingleShot(false);
117   connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
118
119 }
120
121 /*** public static methods ***/
122
123
124 QList<NetworkInfo *> Client::networkInfos() {
125   return instance()->_networkInfo.values();
126 }
127
128 NetworkInfo *Client::networkInfo(uint networkid) {
129   if(instance()->_networkInfo.contains(networkid))
130     return instance()->_networkInfo[networkid];
131   else
132     return 0;
133 }
134
135 QList<BufferInfo> Client::allBufferInfos() {
136   QList<BufferInfo> bufferids;
137   foreach(Buffer *buffer, buffers()) {
138     bufferids << buffer->bufferInfo();
139   }
140   return bufferids;
141 }
142
143 QList<Buffer *> Client::buffers() {
144   return instance()->_buffers.values();
145 }
146
147 Buffer *Client::buffer(uint bufferUid) {
148   if(instance()->_buffers.contains(bufferUid))
149     return instance()->_buffers[bufferUid];
150   else
151     return 0;
152 }
153
154 Buffer *Client::buffer(BufferInfo id) {
155   Buffer *buff = buffer(id.uid());
156
157   if(!buff) {
158     Client *client = Client::instance();
159     buff = new Buffer(id, client);
160
161     connect(buff, SIGNAL(userInput(BufferInfo, QString)),
162             client, SLOT(userInput(BufferInfo, QString)));
163     connect(buff, SIGNAL(bufferUpdated(Buffer *)),
164             client, SIGNAL(bufferUpdated(Buffer *)));
165     connect(buff, SIGNAL(destroyed()),
166             client, SLOT(bufferDestroyed()));
167     client->_buffers[id.uid()] = buff;
168     emit client->bufferUpdated(buff);
169   }
170   Q_ASSERT(buff);
171   return buff;
172 }
173
174 // FIXME switch to netids!
175 // WHEN IS THIS NEEDED ANYHOW!?
176 // ...only for finding the Buffer for a channel, I guess...
177 BufferInfo Client::bufferInfo(QString net, QString buf) {
178   foreach(Buffer *buffer_, buffers()) {
179     BufferInfo bufferInfo = buffer_->bufferInfo();
180     if(!bufferInfo.network().compare(net, Qt::CaseInsensitive) && !bufferInfo.buffer().compare(buf, Qt::CaseInsensitive))
181       return bufferInfo;
182   }
183   Q_ASSERT(false);  // should never happen!
184   return BufferInfo();
185 }
186
187 BufferInfo Client::statusBufferInfo(QString net) {
188   return bufferInfo(net, "");
189 }
190
191 NetworkModel *Client::networkModel() {
192   return instance()->_networkModel;
193 }
194
195 SignalProxy *Client::signalProxy() {
196   return instance()->_signalProxy;
197 }
198
199
200 /*** Identity handling ***/
201
202 QList<IdentityId> Client::identityIds() {
203   return instance()->_identities.keys();
204 }
205
206 const Identity * Client::identity(IdentityId id) {
207   if(instance()->_identities.contains(id)) return instance()->_identities[id];
208   else return 0;
209 }
210
211
212 void Client::createIdentity(const Identity &id) {
213   emit instance()->requestCreateIdentity(id);
214 }
215
216 void Client::updateIdentity(const Identity &id) {
217   emit instance()->requestUpdateIdentity(id);
218 }
219
220 void Client::removeIdentity(IdentityId id) {
221   emit instance()->requestRemoveIdentity(id);
222 }
223
224 void Client::coreIdentityCreated(const Identity &other) {
225   if(!_identities.contains(other.id())) {
226     Identity *identity = new Identity(other, this);
227     _identities[other.id()] = identity;
228     identity->setInitialized();
229     signalProxy()->synchronize(identity);
230     emit identityCreated(other.id());
231   } else {
232     qWarning() << tr("Identity already exists in client!");
233   }
234 }
235
236 void Client::coreIdentityRemoved(IdentityId id) {
237   if(_identities.contains(id)) {
238     emit identityRemoved(id);
239     Identity *i = _identities.take(id);
240     i->deleteLater();
241   }
242 }
243
244 /***  ***/
245
246
247 bool Client::isConnected() {
248   return instance()->connectedToCore;
249 }
250
251 void Client::fakeInput(uint bufferUid, QString message) {
252   Buffer *buff = buffer(bufferUid);
253   if(!buff)
254     qWarning() << "No Buffer with uid" << bufferUid << "can't send Input" << message;
255   else
256     emit instance()->sendInput(buff->bufferInfo(), message);
257 }
258
259 void Client::fakeInput(BufferInfo bufferInfo, QString message) {
260   fakeInput(bufferInfo, message);
261 }
262
263 void Client::connectToCore(const QVariantMap &conn) {
264   // TODO implement SSL
265   coreConnectionInfo = conn;
266   if(isConnected()) {
267     emit coreConnectionError(tr("Already connected to Core!"));
268     return;
269   }
270   
271   if(socket != 0)
272     socket->deleteLater();
273   
274   if(conn["Host"].toString().isEmpty()) {
275     clientMode = LocalCore;
276     socket = new QBuffer(this);
277     connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
278     socket->open(QIODevice::ReadWrite);
279     //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
280     //syncToCore(state);
281     coreSocketConnected();
282   } else {
283     clientMode = RemoteCore;
284     emit coreConnectionMsg(tr("Connecting..."));
285     Q_ASSERT(!socket);
286     QTcpSocket *sock = new QTcpSocket(this);
287     socket = sock;
288     connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
289     connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
290     connect(signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
291     connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
292     sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
293   }
294 }
295
296 void Client::disconnectFromCore() {
297   socket->close();
298 }
299
300 void Client::setCoreConfiguration(const QVariantMap &settings) {
301   SignalProxy::writeDataToDevice(socket, settings);
302 }
303
304 void Client::coreSocketConnected() {
305   connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
306   emit coreConnectionMsg(tr("Synchronizing to core..."));
307   QVariantMap clientInit;
308   clientInit["GuiProtocol"] = GUI_PROTOCOL;
309   clientInit["User"] = coreConnectionInfo["User"].toString();
310   clientInit["Password"] = coreConnectionInfo["Password"].toString();
311   SignalProxy::writeDataToDevice(socket, clientInit);
312 }
313
314 void Client::coreSocketDisconnected() {
315   instance()->connectedToCore = false;
316   emit disconnected();
317   emit coreConnectionStateChanged(false);
318   socket->deleteLater();
319   blockSize = 0;
320
321   /* Clear internal data. Hopefully nothing relies on it at this point. */
322   _networkModel->clear();
323
324   QHash<BufferId, Buffer *>::iterator bufferIter =  _buffers.begin();
325   while(bufferIter != _buffers.end()) {
326     Buffer *buffer = bufferIter.value();
327     disconnect(buffer, SIGNAL(destroyed()), this, 0);
328     bufferIter = _buffers.erase(bufferIter);
329     buffer->deleteLater();
330   }
331   Q_ASSERT(_buffers.isEmpty());
332
333
334   QHash<NetworkId, NetworkInfo*>::iterator netIter = _networkInfo.begin();
335   while(netIter != _networkInfo.end()) {
336     NetworkInfo *net = netIter.value();
337     disconnect(net, SIGNAL(destroyed()), this, 0);
338     netIter = _networkInfo.erase(netIter);
339     net->deleteLater();
340   }
341   Q_ASSERT(_networkInfo.isEmpty());
342
343   QHash<IdentityId, Identity*>::iterator idIter = _identities.begin();
344   while(idIter != _identities.end()) {
345     Identity *id = idIter.value();
346     emit identityRemoved(id->id());
347     idIter = _identities.erase(idIter);
348     id->deleteLater();
349   }
350   Q_ASSERT(_identities.isEmpty());
351
352   coreConnectionInfo.clear();
353   sessionData.clear();
354   layoutQueue.clear();
355   layoutTimer->stop();
356 }
357
358 void Client::recvCoreState(const QVariant &state) {
359   disconnect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
360   disconnect(socket, 0, this, 0);  // rest of communication happens through SignalProxy
361   signalProxy()->addPeer(socket);
362   syncToCore(state);
363 }
364
365 // TODO: auth errors
366 void Client::syncToCore(const QVariant &coreState) {
367   if(!coreState.toMap().contains("SessionState")) {
368     emit coreConnectionError(tr("Invalid data received from core!"));
369     disconnectFromCore();
370     return;
371   }
372
373   QVariantMap sessionState = coreState.toMap()["SessionState"].toMap();
374
375   // store sessionData
376   QVariantMap sessData = sessionState["SessionData"].toMap();
377   foreach(QString key, sessData.keys())
378     recvSessionData(key, sessData[key]);
379
380   // create identities
381   foreach(QVariant vid, sessionState["Identities"].toList()) {
382     coreIdentityCreated(vid.value<Identity>());
383     //Identity *id = new Identity(vid.value<Identity>(), this);
384     //_identities[id->id()] = id;
385     //signalProxy()->synchronize(id);
386     //qDebug() << "received identity" << id->identityName();
387   }
388
389   // store Buffer details
390   QVariantList coreBuffers = sessionState["Buffers"].toList();
391   /* make lookups by id faster */
392   foreach(QVariant vid, coreBuffers) {
393     buffer(vid.value<BufferInfo>()); // create all buffers, so we see them in the network views
394   }
395
396   // create networkInfo objects
397   QVariantList networkids = sessionState["Networks"].toList();
398   foreach(QVariant networkid, networkids) {
399     networkConnected(networkid.toUInt());
400   }
401
402   instance()->connectedToCore = true;
403   updateCoreConnectionProgress();
404
405 }
406
407 void Client::updateCoreConnectionProgress() {
408   // we'll do this in three steps:
409   // 1.) networks
410   // 2.) channels
411   // 3.) ircusers
412
413   int numNets = networkInfos().count();
414   int numNetsWaiting = 0;
415
416   int numIrcUsers = 0;
417   int numIrcUsersWaiting = 0;
418
419   int numChannels = 0;
420   int numChannelsWaiting = 0;
421
422   foreach(NetworkInfo *net, networkInfos()) {
423     if(! net->initialized())
424       numNetsWaiting++;
425
426     numIrcUsers += net->ircUsers().count();
427     foreach(IrcUser *user, net->ircUsers()) {
428       if(! user->initialized())
429         numIrcUsersWaiting++;
430     }
431
432     numChannels += net->ircChannels().count();
433     foreach(IrcChannel *channel, net->ircChannels()) {
434       if(! channel->initialized())
435         numChannelsWaiting++;
436     }
437   }
438
439   if(numNetsWaiting > 0) {
440     emit coreConnectionMsg(tr("Requesting network states..."));
441     emit coreConnectionProgress(numNets - numNetsWaiting, numNets);
442     return;
443   }
444
445   if(numIrcUsersWaiting > 0) {
446     emit coreConnectionMsg(tr("Requesting User states..."));
447     emit coreConnectionProgress(numIrcUsers - numIrcUsersWaiting, numIrcUsers);
448     return;
449   }
450
451   if(numChannelsWaiting > 0) {
452     emit coreConnectionMsg(tr("Requesting Channel states..."));
453     emit coreConnectionProgress(numChannels - numChannelsWaiting, numChannels);
454     return;
455   }
456
457   emit coreConnectionProgress(1,1);
458   emit connected();
459   emit coreConnectionStateChanged(true);
460   foreach(NetworkInfo *net, networkInfos()) {
461     disconnect(net, 0, this, SLOT(updateCoreConnectionProgress()));
462   }
463
464   // signalProxy()->dumpProxyStats();
465 }
466
467 void Client::recvSessionData(const QString &key, const QVariant &data) {
468   sessionData[key] = data;
469   emit sessionDataChanged(key, data);
470   emit sessionDataChanged(key);
471 }
472
473 void Client::storeSessionData(const QString &key, const QVariant &data) {
474   // Not sure if this is a good idea, but we'll try it anyway:
475   // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
476   // rather than immediately.
477   emit instance()->sendSessionData(key, data);
478 }
479
480 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
481   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
482   else return def;
483 }
484
485 QStringList Client::sessionDataKeys() {
486   return instance()->sessionData.keys();
487 }
488
489 void Client::coreSocketError(QAbstractSocket::SocketError) {
490   emit coreConnectionError(socket->errorString());
491   socket->deleteLater();
492 }
493
494 void Client::coreHasData() {
495   QVariant item;
496   if(SignalProxy::readDataFromDevice(socket, blockSize, item)) {
497     emit recvPartialItem(1,1);
498     QVariantMap msg = item.toMap();
499     if (!msg["StartWizard"].toBool()) {
500       recvCoreState(msg["Reply"]);
501     } else {
502       qWarning("Core not configured!");
503       qDebug() << "Available storage providers: " << msg["StorageProviders"].toStringList();
504       emit showConfigWizard(msg);
505     }
506     blockSize = 0;
507     return;
508   }
509   if(blockSize > 0) {
510     emit recvPartialItem(socket->bytesAvailable(), blockSize);
511   }
512 }
513
514 void Client::networkConnected(uint netid) {
515   // TODO: create statusBuffer / switch to networkids
516   //BufferInfo id = statusBufferInfo(net);
517   //Buffer *b = buffer(id);
518   //b->setActive(true);
519
520   NetworkInfo *netinfo = new NetworkInfo(netid, this);
521   netinfo->setProxy(signalProxy());
522   networkModel()->attachNetworkInfo(netinfo);
523   
524   if(!isConnected()) {
525     connect(netinfo, SIGNAL(initDone()), this, SLOT(updateCoreConnectionProgress()));
526     connect(netinfo, SIGNAL(ircUserInitDone()), this, SLOT(updateCoreConnectionProgress()));
527     connect(netinfo, SIGNAL(ircChannelInitDone()), this, SLOT(updateCoreConnectionProgress()));
528   }
529   connect(netinfo, SIGNAL(ircChannelAdded(QString)), this, SLOT(ircChannelAdded(QString)));
530   connect(netinfo, SIGNAL(destroyed()), this, SLOT(networkInfoDestroyed()));
531   _networkInfo[netid] = netinfo;
532 }
533
534 void Client::networkDisconnected(uint networkid) {
535   foreach(Buffer *buffer, buffers()) {
536     if(buffer->bufferInfo().networkId() != networkid)
537       continue;
538
539     //buffer->displayMsg(Message(bufferid, Message::Server, tr("Server disconnected."))); FIXME
540     buffer->setActive(false);
541   }
542
543   Q_ASSERT(networkInfo(networkid));
544   if(!networkInfo(networkid)->initialized()) {
545     qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
546     updateCoreConnectionProgress();
547   }
548 }
549
550 void Client::ircChannelAdded(QString chanName) {
551   NetworkInfo *netInfo = qobject_cast<NetworkInfo*>(sender());
552   Q_ASSERT(netInfo);
553   Buffer *buf = buffer(bufferInfo(netInfo->networkName(), chanName));
554   Q_ASSERT(buf);
555   buf->setIrcChannel(netInfo->ircChannel(chanName));
556
557 }
558
559 void Client::updateBufferInfo(BufferInfo id) {
560   buffer(id)->updateBufferInfo(id);
561 }
562
563 void Client::bufferDestroyed() {
564   Buffer *buffer = static_cast<Buffer *>(sender());
565   uint bufferUid = buffer->uid();
566   if(_buffers.contains(bufferUid))
567     _buffers.remove(bufferUid);
568 }
569
570 void Client::networkInfoDestroyed() {
571   NetworkInfo *netinfo = static_cast<NetworkInfo *>(sender());
572   uint networkId = netinfo->networkId();
573   if(_networkInfo.contains(networkId))
574     _networkInfo.remove(networkId);
575 }
576
577 void Client::recvMessage(const Message &msg) {
578   Buffer *b = buffer(msg.buffer());
579
580   Buffer::ActivityLevel level = Buffer::OtherActivity;
581   if(msg.type() == Message::Plain || msg.type() == Message::Notice){
582     level |= Buffer::NewMessage;
583   }
584   if(msg.flags() & Message::Highlight){
585     level |= Buffer::Highlight;
586   }
587   emit bufferActivity(level, b);
588
589   b->appendMsg(msg);
590 }
591
592 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
593   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
594 }
595
596 void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
597   Buffer *b = buffer(id);
598   foreach(QVariant v, msgs) {
599     Message msg = v.value<Message>();
600     b->prependMsg(msg);
601     if(!layoutQueue.contains(b)) layoutQueue.append(b);
602   }
603   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
604 }
605
606 void Client::layoutMsg() {
607   if(layoutQueue.count()) {
608     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
609     if(b->layoutMsg())
610       layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
611   }
612   
613   if(!layoutQueue.count())
614     layoutTimer->stop();
615 }
616
617 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
618   return instance()->mainUi->layoutMsg(msg);
619 }
620
621 void Client::userInput(BufferInfo id, QString msg) {
622   emit sendInput(id, msg);
623 }
624