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