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