Ok, the long awaited config wizard is here (at least in a very basic state). There...
[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 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
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, signalProxy(), this);
445   connect(netinfo, SIGNAL(initDone()), this, SLOT(updateCoreConnectionProgress()));
446   connect(netinfo, SIGNAL(ircUserInitDone()), this, SLOT(updateCoreConnectionProgress()));
447   connect(netinfo, SIGNAL(ircChannelInitDone()), this, SLOT(updateCoreConnectionProgress()));
448   connect(netinfo, SIGNAL(destroyed()), this, SLOT(networkInfoDestroyed()));
449   _networkInfo[netid] = netinfo;
450 }
451
452 void Client::networkDisconnected(uint networkid) {
453   foreach(Buffer *buffer, buffers()) {
454     if(buffer->bufferInfo().networkId() != networkid)
455       continue;
456
457     //buffer->displayMsg(Message(bufferid, Message::Server, tr("Server disconnected."))); FIXME
458     buffer->setActive(false);
459   }
460   
461   Q_ASSERT(networkInfo(networkid));
462   if(!networkInfo(networkid)->initialized()) {
463     qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
464     updateCoreConnectionProgress();
465   }
466 }
467
468 void Client::updateBufferInfo(BufferInfo id) {
469   buffer(id)->updateBufferInfo(id);
470 }
471
472 void Client::bufferDestroyed() {
473   Buffer *buffer = static_cast<Buffer *>(sender());
474   uint bufferUid = buffer->uid();
475   if(_buffers.contains(bufferUid))
476     _buffers.remove(bufferUid);
477 }
478
479 void Client::networkInfoDestroyed() {
480   NetworkInfo *netinfo = static_cast<NetworkInfo *>(sender());
481   uint networkId = netinfo->networkId();
482   if(_networkInfo.contains(networkId))
483     _networkInfo.remove(networkId);
484 }
485
486 void Client::recvMessage(const Message &msg) {
487   Buffer *b = buffer(msg.buffer());
488
489   Buffer::ActivityLevel level = Buffer::OtherActivity;
490   if(msg.type() == Message::Plain || msg.type() == Message::Notice){
491     level |= Buffer::NewMessage;
492   }
493   if(msg.flags() & Message::Highlight){
494     level |= Buffer::Highlight;
495   }
496   emit bufferActivity(level, b);
497
498   b->appendMsg(msg);
499 }
500
501 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
502   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
503 }
504
505 void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
506   Buffer *b = buffer(id);
507   foreach(QVariant v, msgs) {
508     Message msg = v.value<Message>();
509     b->prependMsg(msg);
510     if(!layoutQueue.contains(b)) layoutQueue.append(b);
511   }
512   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
513 }
514
515 void Client::layoutMsg() {
516   if(layoutQueue.count()) {
517     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
518     if(b->layoutMsg())
519       layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
520   }
521   
522   if(!layoutQueue.count())
523     layoutTimer->stop();
524 }
525
526 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
527   return instance()->mainUi->layoutMsg(msg);
528 }
529
530 void Client::userInput(BufferInfo id, QString msg) {
531   emit sendInput(id, msg);
532 }
533