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