Actually... I have nearly no clue what the changes in this revision are. Since most...
[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, 0, 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(peerDisconnected()), 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 void Client::coreSocketConnected() {
250   connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
251   emit coreConnectionMsg(tr("Synchronizing to core..."));
252   QVariantMap clientInit;
253   clientInit["GuiProtocol"] = GUI_PROTOCOL;
254   clientInit["User"] = coreConnectionInfo["User"].toString();
255   clientInit["Password"] = coreConnectionInfo["Password"].toString();
256   writeDataToDevice(socket, clientInit);
257 }
258
259 void Client::coreSocketDisconnected() {
260   instance()->connectedToCore = false;
261   emit disconnected();
262   socket->deleteLater();
263   blockSize = 0;
264
265   /* Clear internal data. Hopefully nothing relies on it at this point. */
266   _bufferModel->clear();
267
268   foreach(Buffer *buffer, _buffers.values()) {
269     buffer->deleteLater();
270   }
271
272   foreach(NetworkInfo *networkinfo, _networkInfo.values()) {
273     networkinfo->deleteLater();
274   }
275
276   coreConnectionInfo.clear();
277   sessionData.clear();
278   layoutQueue.clear();
279   layoutTimer->stop();
280 }
281
282 void Client::coreSocketStateChanged(QAbstractSocket::SocketState state) {
283   if(state == QAbstractSocket::UnconnectedState) coreSocketDisconnected();
284 }
285
286 void Client::recvCoreState(const QVariant &state) {
287   disconnect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
288   disconnect(socket, 0, this, 0);  // rest of communication happens through SignalProxy
289   signalProxy()->addPeer(socket);
290   syncToCore(state);
291 }
292
293 // TODO: auth errors
294 void Client::syncToCore(const QVariant &coreState) {
295   if(!coreState.toMap().contains("SessionState")) {
296     emit coreConnectionError(tr("Invalid data received from core!"));
297     disconnectFromCore();
298     return;
299   }
300
301   QVariantMap sessionState = coreState.toMap()["SessionState"].toMap();
302
303   // store sessionData
304   QVariantMap sessData = sessionState["SessionData"].toMap();
305   foreach(QString key, sessData.keys())
306     recvSessionData(key, sessData[key]);
307
308   // store Buffer details
309   QVariantList coreBuffers = sessionState["Buffers"].toList();
310   /* make lookups by id faster */
311   foreach(QVariant vid, coreBuffers) {
312     buffer(vid.value<BufferInfo>()); // create all buffers, so we see them in the network views
313   }
314
315   // create networkInfo objects
316   QVariantList networkids = sessionState["Networks"].toList();
317   foreach(QVariant networkid, networkids) {
318     networkConnected(networkid.toUInt());
319   }
320   
321   instance()->connectedToCore = true;
322   updateCoreConnectionProgress();
323 }
324
325 void Client::updateCoreConnectionProgress() {
326   // we'll do this in three steps:
327   // 1.) networks
328   // 2.) channels
329   // 3.) ircusers
330
331   int numNets = networkInfos().count();
332   int numNetsWaiting = 0;
333
334   int numIrcUsers = 0;
335   int numIrcUsersWaiting = 0;
336
337   int numChannels = 0;
338   int numChannelsWaiting = 0;
339
340   foreach(NetworkInfo *net, networkInfos()) {
341     if(! net->initialized())
342       numNetsWaiting++;
343
344     numIrcUsers += net->ircUsers().count();
345     foreach(IrcUser *user, net->ircUsers()) {
346       if(! user->initialized())
347         numIrcUsersWaiting++;
348     }
349
350     numChannels += net->ircChannels().count();
351     foreach(IrcChannel *channel, net->ircChannels()) {
352       if(! channel->initialized())
353         numChannelsWaiting++;
354     }
355
356   }
357
358   if(numNetsWaiting > 0) {
359     emit coreConnectionMsg(tr("Requesting network states..."));
360     emit coreConnectionProgress(numNets - numNetsWaiting, numNets);
361     return;
362   }
363
364   if(numIrcUsersWaiting > 0) {
365     emit coreConnectionMsg(tr("Requesting User states..."));
366     emit coreConnectionProgress(numIrcUsers - numIrcUsersWaiting, numIrcUsers);
367     return;
368   }
369
370   if(numChannelsWaiting > 0) {
371     emit coreConnectionMsg(tr("Requesting Channel states..."));
372     emit coreConnectionProgress(numChannels - numChannelsWaiting, numChannels);
373     return;
374   }
375
376   emit coreConnectionProgress(1,1);
377   emit connected();
378 }
379
380 void Client::recvSessionData(const QString &key, const QVariant &data) {
381   sessionData[key] = data;
382   emit sessionDataChanged(key, data);
383   emit sessionDataChanged(key);
384 }
385
386 void Client::storeSessionData(const QString &key, const QVariant &data) {
387   // Not sure if this is a good idea, but we'll try it anyway:
388   // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
389   // rather than immediately.
390   emit instance()->sendSessionData(key, data);
391 }
392
393 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
394   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
395   else return def;
396 }
397
398 QStringList Client::sessionDataKeys() {
399   return instance()->sessionData.keys();
400 }
401
402 void Client::coreSocketError(QAbstractSocket::SocketError) {
403   emit coreConnectionError(socket->errorString());
404   socket->deleteLater();
405 }
406
407 void Client::coreHasData() {
408   QVariant item;
409   if(readDataFromDevice(socket, blockSize, item)) {
410     emit recvPartialItem(1,1);
411     recvCoreState(item);
412     blockSize = 0;
413     return;
414   }
415   if(blockSize > 0) {
416     emit recvPartialItem(socket->bytesAvailable(), blockSize);
417   }
418 }
419
420 void Client::networkConnected(uint netid) {
421   // TODO: create statusBuffer / switch to networkids
422   //BufferInfo id = statusBufferInfo(net);
423   //Buffer *b = buffer(id);
424   //b->setActive(true);
425
426   NetworkInfo *netinfo = new NetworkInfo(netid, signalProxy(), this);
427   connect(netinfo, SIGNAL(initDone()), this, SLOT(updateCoreConnectionProgress()));
428   connect(netinfo, SIGNAL(ircUserInitDone()), this, SLOT(updateCoreConnectionProgress()));
429   connect(netinfo, SIGNAL(ircChannelInitDone()), this, SLOT(updateCoreConnectionProgress()));
430   _networkInfo[netid] = netinfo;
431 }
432
433 void Client::networkDisconnected(uint networkid) {
434   foreach(Buffer *buffer, buffers()) {
435     if(buffer->bufferInfo().networkId() != networkid)
436       continue;
437
438     //buffer->displayMsg(Message(bufferid, Message::Server, tr("Server disconnected."))); FIXME
439     buffer->setActive(false);
440   }
441   
442   Q_ASSERT(networkInfo(networkid));
443   if(!networkInfo(networkid)->initialized()) {
444     qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
445     updateCoreConnectionProgress();
446   }
447 }
448
449 void Client::updateBufferInfo(BufferInfo id) {
450   buffer(id)->updateBufferInfo(id);
451 }
452
453 void Client::bufferDestroyed() {
454   Buffer *buffer = static_cast<Buffer *>(sender());
455   _buffers.remove(_buffers.key(buffer));
456 }
457
458 void Client::recvMessage(const Message &msg) {
459   Buffer *b = buffer(msg.buffer());
460
461   Buffer::ActivityLevel level = Buffer::OtherActivity;
462   if(msg.type() == Message::Plain || msg.type() == Message::Notice){
463     level |= Buffer::NewMessage;
464   }
465   if(msg.flags() & Message::Highlight){
466     level |= Buffer::Highlight;
467   }
468   emit bufferActivity(level, b);
469
470   b->appendMsg(msg);
471 }
472
473 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
474   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
475 }
476
477 void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
478   Buffer *b = buffer(id);
479   foreach(QVariant v, msgs) {
480     Message msg = v.value<Message>();
481     b->prependMsg(msg);
482     if(!layoutQueue.contains(b)) layoutQueue.append(b);
483   }
484   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
485 }
486
487 void Client::layoutMsg() {
488   if(layoutQueue.count()) {
489     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
490     if(b->layoutMsg())
491       layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
492   }
493   
494   if(!layoutQueue.count())
495     layoutTimer->stop();
496 }
497
498 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
499   return instance()->mainUi->layoutMsg(msg);
500 }
501
502 void Client::userInput(BufferInfo id, QString msg) {
503   emit sendInput(id, msg);
504 }
505