Moved BufferView and BufferViewFilter to uisupport, since I intend
[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 "synchronizer.h"
34 #include "util.h"
35
36 QPointer<Client> Client::instanceptr = 0;
37
38 // ==============================
39 //  public Static Methods
40 // ==============================
41 Client *Client::instance() {
42   if(!instanceptr)
43     instanceptr = new Client();
44   return instanceptr;
45 }
46
47 void Client::destroy() {
48   delete instanceptr;
49 }
50
51 void Client::init(AbstractUi *ui) {
52   instance()->mainUi = ui;
53   instance()->init();
54 }
55
56 QList<NetworkInfo *> Client::networkInfos() {
57   return instance()->_networkInfo.values();
58 }
59
60 NetworkInfo *Client::networkInfo(uint networkid) {
61   if(instance()->_networkInfo.contains(networkid))
62     return instance()->_networkInfo[networkid];
63   else
64     return 0;
65 }
66
67 QList<BufferInfo> Client::allBufferInfos() {
68   QList<BufferInfo> bufferids;
69   foreach(Buffer *buffer, buffers()) {
70     bufferids << buffer->bufferInfo();
71   }
72   return bufferids;
73 }
74
75 QList<Buffer *> Client::buffers() {
76   return instance()->_buffers.values();
77 }
78
79 Buffer *Client::buffer(uint bufferUid) {
80   if(instance()->_buffers.contains(bufferUid))
81     return instance()->_buffers[bufferUid];
82   else
83     return 0;
84 }
85
86 Buffer *Client::buffer(BufferInfo id) {
87   Buffer *buff = buffer(id.uid());
88
89   if(!buff) {
90     Client *client = Client::instance();
91     buff = new Buffer(id, client);
92
93     connect(buff, SIGNAL(userInput(BufferInfo, QString)),
94             client, SLOT(userInput(BufferInfo, QString)));
95     connect(buff, SIGNAL(bufferUpdated(Buffer *)),
96             client, SIGNAL(bufferUpdated(Buffer *)));
97     connect(buff, SIGNAL(destroyed()),
98             client, SLOT(bufferDestroyed()));
99     client->_buffers[id.uid()] = buff;
100     emit client->bufferUpdated(buff);
101   }
102   Q_ASSERT(buff);
103   return buff;
104 }
105
106 // FIXME switch to netids!
107 // WHEN IS THIS NEEDED ANYHOW!?
108 BufferInfo Client::bufferInfo(QString net, QString buf) {
109   foreach(Buffer *buffer_, buffers()) {
110     BufferInfo bufferInfo = buffer_->bufferInfo();
111     if(bufferInfo.network() == net && bufferInfo.buffer() == buf)
112       return bufferInfo;
113   }
114   Q_ASSERT(false);  // should never happen!
115   return BufferInfo();
116 }
117
118 BufferInfo Client::statusBufferInfo(QString net) {
119   return bufferInfo(net, "");
120 }
121
122 BufferTreeModel *Client::bufferModel() {
123   return instance()->_bufferModel;
124 }
125
126 SignalProxy *Client::signalProxy() {
127   return instance()->_signalProxy;
128 }
129
130 // ==============================
131 //  Constructor / Decon
132 // ==============================
133 Client::Client(QObject *parent)
134   : QObject(parent),
135     socket(0),
136     _signalProxy(new SignalProxy(SignalProxy::Client, this)),
137     mainUi(0),
138     _bufferModel(0),
139     connectedToCore(false)
140 {
141 }
142
143 Client::~Client() {
144 }
145
146 void Client::init() {
147   blockSize = 0;
148
149   _bufferModel = new BufferTreeModel(this);
150
151   connect(this, SIGNAL(bufferSelected(Buffer *)),
152           _bufferModel, SLOT(selectBuffer(Buffer *)));
153   connect(this, SIGNAL(bufferUpdated(Buffer *)),
154           _bufferModel, SLOT(bufferUpdated(Buffer *)));
155   connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)),
156           _bufferModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
157
158   SignalProxy *p = signalProxy();
159   p->attachSignal(this, SIGNAL(sendSessionData(const QString &, const QVariant &)),
160                   SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)));
161   p->attachSlot(SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)),
162                 this, SLOT(recvSessionData(const QString &, const QVariant &)));
163   p->attachSlot(SIGNAL(coreState(const QVariant &)),
164                 this, SLOT(recvCoreState(const QVariant &)));
165   p->attachSlot(SIGNAL(networkConnected(uint)),
166                 this, SLOT(networkConnected(uint)));
167   p->attachSlot(SIGNAL(networkDisconnected(uint)),
168                 this, SLOT(networkDisconnected(uint)));
169   p->attachSlot(SIGNAL(displayMsg(const Message &)),
170                 this, SLOT(recvMessage(const Message &)));
171   p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)),
172                 this, SLOT(recvStatusMsg(QString, QString)));
173
174
175   p->attachSlot(SIGNAL(backlogData(BufferInfo, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferInfo, const QVariantList &, bool)));
176   p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), this, SLOT(updateBufferInfo(BufferInfo)));
177   p->attachSignal(this, SIGNAL(sendInput(BufferInfo, QString)));
178   p->attachSignal(this, SIGNAL(requestNetworkStates()));
179
180   connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
181   connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
182   connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
183   connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
184
185   layoutTimer = new QTimer(this);
186   layoutTimer->setInterval(0);
187   layoutTimer->setSingleShot(false);
188   connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
189
190 }
191
192 bool Client::isConnected() {
193   return instance()->connectedToCore;
194 }
195
196 void Client::fakeInput(uint bufferUid, QString message) {
197   Buffer *buff = buffer(bufferUid);
198   if(!buff)
199     qWarning() << "No Buffer with uid" << bufferUid << "can't send Input" << message;
200   else
201     emit instance()->sendInput(buff->bufferInfo(), message);
202 }
203
204 void Client::fakeInput(BufferInfo bufferInfo, QString message) {
205   fakeInput(bufferInfo, message);
206 }
207
208 void Client::connectToCore(const QVariantMap &conn) {
209   // TODO implement SSL
210   coreConnectionInfo = conn;
211   if(isConnected()) {
212     emit coreConnectionError(tr("Already connected to Core!"));
213     return;
214   }
215   
216   if(socket != 0)
217     socket->deleteLater();
218   
219   if(conn["Host"].toString().isEmpty()) {
220     clientMode = LocalCore;
221     socket = new QBuffer(this);
222     connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
223     socket->open(QIODevice::ReadWrite);
224     //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
225     //syncToCore(state);
226     coreSocketConnected();
227   } else {
228     clientMode = RemoteCore;
229     emit coreConnectionMsg(tr("Connecting..."));
230     Q_ASSERT(!socket);
231     QTcpSocket *sock = new QTcpSocket(this);
232     socket = sock;
233     connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
234     connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
235     connect(sock, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
236     connect(signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
237     //connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(coreSocketStateChanged(QAbstractSocket::SocketState)));
238     connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
239     sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
240   }
241 }
242
243 void Client::disconnectFromCore() {
244   socket->close();
245   if(clientMode == LocalCore) {
246     coreSocketDisconnected();
247   }
248 }
249
250 void Client::setCoreConfiguration(const QVariantMap &settings) {
251   writeDataToDevice(socket, settings);
252 }
253
254 void Client::coreSocketConnected() {
255   connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
256   emit coreConnectionMsg(tr("Synchronizing to core..."));
257   QVariantMap clientInit;
258   clientInit["GuiProtocol"] = GUI_PROTOCOL;
259   clientInit["User"] = coreConnectionInfo["User"].toString();
260   clientInit["Password"] = coreConnectionInfo["Password"].toString();
261   writeDataToDevice(socket, clientInit);
262 }
263
264 void Client::coreSocketDisconnected() {
265   instance()->connectedToCore = false;
266   emit disconnected();
267   socket->deleteLater();
268   blockSize = 0;
269
270   /* Clear internal data. Hopefully nothing relies on it at this point. */
271   _bufferModel->clear();
272   foreach(Buffer *buffer, _buffers.values()) {
273     buffer->deleteLater();
274   }
275   _buffers.clear();
276
277   foreach(NetworkInfo *networkinfo, _networkInfo.values()) {
278     networkinfo->deleteLater();
279   }
280   _networkInfo.clear();
281
282   coreConnectionInfo.clear();
283   sessionData.clear();
284   layoutQueue.clear();
285   layoutTimer->stop();
286 }
287
288 void Client::coreSocketStateChanged(QAbstractSocket::SocketState state) {
289   if(state == QAbstractSocket::UnconnectedState) coreSocketDisconnected();
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(); // FIXME EgS: This caused the double backlog... but... we shouldn't be calling this whole function all the time...
384
385   foreach(NetworkInfo *net, networkInfos()) {
386     disconnect(net, 0, this, SLOT(updateCoreConnectionProgress()));
387   }
388
389   // signalProxy()->dumpProxyStats();
390 }
391
392 void Client::recvSessionData(const QString &key, const QVariant &data) {
393   sessionData[key] = data;
394   emit sessionDataChanged(key, data);
395   emit sessionDataChanged(key);
396 }
397
398 void Client::storeSessionData(const QString &key, const QVariant &data) {
399   // Not sure if this is a good idea, but we'll try it anyway:
400   // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
401   // rather than immediately.
402   emit instance()->sendSessionData(key, data);
403 }
404
405 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
406   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
407   else return def;
408 }
409
410 QStringList Client::sessionDataKeys() {
411   return instance()->sessionData.keys();
412 }
413
414 void Client::coreSocketError(QAbstractSocket::SocketError) {
415   emit coreConnectionError(socket->errorString());
416   socket->deleteLater();
417 }
418
419 void Client::coreHasData() {
420   QVariant item;
421   if(readDataFromDevice(socket, blockSize, item)) {
422     emit recvPartialItem(1,1);
423     QVariantMap msg = item.toMap();
424     if (!msg["StartWizard"].toBool()) {
425       recvCoreState(msg["Reply"]);
426     } else {
427       qWarning("Core not configured!");
428       qDebug() << "Available storage providers: " << msg["StorageProviders"].toStringList();
429       emit showConfigWizard(msg);
430     }
431     blockSize = 0;
432     return;
433   }
434   if(blockSize > 0) {
435     emit recvPartialItem(socket->bytesAvailable(), blockSize);
436   }
437 }
438
439 void Client::networkConnected(uint netid) {
440   // TODO: create statusBuffer / switch to networkids
441   //BufferInfo id = statusBufferInfo(net);
442   //Buffer *b = buffer(id);
443   //b->setActive(true);
444
445   // FIXME EgS: do we really need to call updateCoreConnectionProgress whenever a new network is connected?
446   NetworkInfo *netinfo = new NetworkInfo(netid, signalProxy(), this);
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