clean++
[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 "buffer.h"
24 #include "buffertreemodel.h"
25 #include "quasselui.h"
26 #include "signalproxy.h"
27 #include "util.h"
28
29 Client * Client::instanceptr = 0;
30
31 bool Client::connectedToCore = false;
32 Client::ClientMode Client::clientMode;
33 QVariantMap Client::coreConnectionInfo;
34 QHash<BufferId, Buffer *> Client::buffers;
35 QHash<uint, BufferId> Client::bufferIds;
36 QHash<QString, QHash<QString, QVariantMap> > Client::nicks;
37 QHash<QString, bool> Client::netConnected;
38 QStringList Client::netsAwaitingInit;
39 QHash<QString, QString> Client::ownNick;
40
41 Client *Client::instance() {
42   if(instanceptr) return instanceptr;
43   instanceptr = new Client();
44   return instanceptr;
45 }
46
47 void Client::destroy() {
48   delete instanceptr;
49   instanceptr = 0;
50 }
51
52 Client::Client() {
53   _signalProxy = new SignalProxy(SignalProxy::Client, 0, this);
54
55   connectedToCore = false;
56   socket = 0;
57 }
58
59 void Client::init(AbstractUi *ui) {
60   instance()->mainUi = ui;
61   instance()->init();
62 }
63
64 void Client::init() {
65   blockSize = 0;
66
67   _bufferModel = new BufferTreeModel(this);
68
69   connect(this, SIGNAL(bufferSelected(Buffer *)), _bufferModel, SLOT(selectBuffer(Buffer *)));
70   connect(this, SIGNAL(bufferUpdated(Buffer *)), _bufferModel, SLOT(bufferUpdated(Buffer *)));
71   connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)), _bufferModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
72
73   SignalProxy *p = signalProxy();
74   p->attachSignal(this, SIGNAL(sendSessionData(const QString &, const QVariant &)), SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)));
75   p->attachSlot(SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)), this, SLOT(recvSessionData(const QString &, const QVariant &)));
76   p->attachSlot(SIGNAL(coreState(const QVariant &)), this, SLOT(recvCoreState(const QVariant &)));
77   p->attachSlot(SIGNAL(networkState(QString, QVariant)), this, SLOT(recvNetworkState(QString, QVariant)));
78   p->attachSlot(SIGNAL(networkConnected(QString)), this, SLOT(networkConnected(QString)));
79   p->attachSlot(SIGNAL(networkDisconnected(QString)), this, SLOT(networkDisconnected(QString)));
80   p->attachSlot(SIGNAL(displayMsg(const Message &)), this, SLOT(recvMessage(const Message &)));
81   p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
82   p->attachSlot(SIGNAL(topicSet(QString, QString, QString)), this, SLOT(setTopic(QString, QString, QString)));
83   p->attachSlot(SIGNAL(nickAdded(QString, QString, QVariantMap)), this, SLOT(addNick(QString, QString, QVariantMap)));
84   p->attachSlot(SIGNAL(nickRemoved(QString, QString)), this, SLOT(removeNick(QString, QString)));
85   p->attachSlot(SIGNAL(nickRenamed(QString, QString, QString)), this, SLOT(renameNick(QString, QString, QString)));
86   p->attachSlot(SIGNAL(nickUpdated(QString, QString, QVariantMap)), this, SLOT(updateNick(QString, QString, QVariantMap)));
87   p->attachSlot(SIGNAL(ownNickSet(QString, QString)), this, SLOT(setOwnNick(QString, QString)));
88   p->attachSlot(SIGNAL(backlogData(BufferId, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferId, const QVariantList &, bool)));
89   p->attachSlot(SIGNAL(bufferIdUpdated(BufferId)), this, SLOT(updateBufferId(BufferId)));
90   p->attachSignal(this, SIGNAL(sendInput(BufferId, QString)));
91   p->attachSignal(this, SIGNAL(requestNetworkStates()));
92
93   connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
94   connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
95   connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
96   connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
97
98   layoutTimer = new QTimer(this);
99   layoutTimer->setInterval(0);
100   layoutTimer->setSingleShot(false);
101   connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
102
103 }
104
105 Client::~Client() {
106   foreach(Buffer *buf, buffers.values()) delete buf; // this is done by disconnectFromCore()! FIXME?
107   Q_ASSERT(!buffers.count());
108 }
109
110 BufferTreeModel *Client::bufferModel() {
111   return instance()->_bufferModel;
112 }
113
114 SignalProxy *Client::signalProxy() {
115   return instance()->_signalProxy;
116 }
117
118 bool Client::isConnected() {
119   return connectedToCore;
120 }
121
122 void Client::connectToCore(const QVariantMap &conn) {
123   // TODO implement SSL
124   coreConnectionInfo = conn;
125   if(isConnected() || socket != 0) {
126     emit coreConnectionError(tr("Already connected to Core!"));
127     return;
128   }
129   if(conn["Host"].toString().isEmpty()) {
130     clientMode = LocalCore;
131     socket = new QBuffer(this);
132     connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
133     socket->open(QIODevice::ReadWrite);
134     //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
135     //syncToCore(state);
136     coreSocketConnected();
137   } else {
138     clientMode = RemoteCore;
139     emit coreConnectionMsg(tr("Connecting..."));
140     Q_ASSERT(!socket);
141     QTcpSocket *sock = new QTcpSocket(this);
142     socket = sock;
143     connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
144     connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
145     connect(sock, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
146     connect(signalProxy(), SIGNAL(peerDisconnected()), this, SLOT(coreSocketDisconnected()));
147     //connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(coreSocketStateChanged(QAbstractSocket::SocketState)));
148     connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
149     sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
150   }
151 }
152
153 void Client::disconnectFromCore() {
154   if(clientMode == RemoteCore) {
155     socket->close();
156     //QAbstractSocket *sock = qobject_cast<QAbstractSocket*>(socket);
157     //Q_ASSERT(sock);
158     //sock->disconnectFromHost();
159   } else {
160     socket->close();
161     //disconnectFromLocalCore();
162     coreSocketDisconnected();
163   }
164 }
165
166 void Client::coreSocketConnected() {
167   connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
168   emit coreConnectionMsg(tr("Synchronizing to core..."));
169   QVariantMap clientInit;
170   clientInit["GuiProtocol"] = GUI_PROTOCOL;
171   clientInit["User"] = coreConnectionInfo["User"].toString();
172   clientInit["Password"] = coreConnectionInfo["Password"].toString();
173   writeDataToDevice(socket, clientInit);
174 }
175
176 void Client::coreSocketDisconnected() {
177   connectedToCore = false;
178   emit disconnected();
179   socket->deleteLater();
180
181   /* Clear internal data. Hopefully nothing relies on it at this point. */
182   _bufferModel->clear();
183   // Buffers, if deleted, send a signal that causes their removal from buffers and bufferIds.
184   // So we cannot simply go through the array in a loop (or use qDeleteAll) for deletion...
185   while(buffers.count()) { delete buffers.take(buffers.keys()[0]); }
186   Q_ASSERT(!buffers.count());   // should be empty now!
187   Q_ASSERT(!bufferIds.count());
188   coreConnectionInfo.clear();
189   sessionData.clear();
190   nicks.clear();
191   netConnected.clear();
192   netsAwaitingInit.clear();
193   ownNick.clear();
194   layoutQueue.clear();
195   layoutTimer->stop();
196 }
197
198 void Client::coreSocketStateChanged(QAbstractSocket::SocketState state) { qDebug() << state;
199   if(state == QAbstractSocket::UnconnectedState) coreSocketDisconnected();
200 }
201
202 void Client::recvCoreState(const QVariant &state) {
203   disconnect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
204   disconnect(socket, 0, this, 0);  // rest of communication happens through SignalProxy
205   signalProxy()->addPeer(socket);
206   syncToCore(state);
207 }
208
209 void Client::syncToCore(const QVariant &coreState) {
210   if(!coreState.toMap().contains("SessionState")) {
211     emit coreConnectionError(tr("Invalid data received from core!"));
212     disconnectFromCore();
213     return;
214   }
215   QVariantMap sessionState = coreState.toMap()["SessionState"].toMap();
216   QVariantMap sessData = sessionState["SessionData"].toMap();
217
218   foreach(QString key, sessData.keys()) {
219     recvSessionData(key, sessData[key]);
220   }
221   QList<QVariant> coreBuffers = sessionState["Buffers"].toList();
222   /* make lookups by id faster */
223   foreach(QVariant vid, coreBuffers) {
224     BufferId id = vid.value<BufferId>();
225     bufferIds[id.uid()] = id;  // make lookups by id faster
226     buffer(id);                // create all buffers, so we see them in the network views
227   }
228   netsAwaitingInit = sessionState["Networks"].toStringList();
229   connectedToCore = true;
230   if(netsAwaitingInit.count()) {
231     emit coreConnectionMsg(tr("Requesting network states..."));
232     emit coreConnectionProgress(0, netsAwaitingInit.count());
233     emit requestNetworkStates();
234   }
235   else {
236     emit coreConnectionProgress(1, 1);
237     emit connected();
238   }
239 }
240
241 void Client::recvSessionData(const QString &key, const QVariant &data) {
242   sessionData[key] = data;
243   emit sessionDataChanged(key, data);
244   emit sessionDataChanged(key);
245 }
246
247 void Client::storeSessionData(const QString &key, const QVariant &data) {
248   // Not sure if this is a good idea, but we'll try it anyway:
249   // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
250   // rather than immediately.
251   emit instance()->sendSessionData(key, data);
252 }
253
254 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
255   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
256   else return def;
257 }
258
259 QStringList Client::sessionDataKeys() {
260   return instance()->sessionData.keys();
261 }
262
263 void Client::coreSocketError(QAbstractSocket::SocketError) {
264   emit coreConnectionError(socket->errorString());
265 }
266
267 void Client::coreHasData() {
268   QVariant item;
269   if(readDataFromDevice(socket, blockSize, item)) {
270     emit recvPartialItem(1,1);
271     recvCoreState(item);
272     blockSize = 0;
273     return;
274   }
275   if(blockSize > 0) {
276     emit recvPartialItem(socket->bytesAvailable(), blockSize);
277   }
278 }
279
280 void Client::networkConnected(QString net) {
281   Q_ASSERT(!netsAwaitingInit.contains(net));
282   netConnected[net] = true;
283   BufferId id = statusBufferId(net);
284   Buffer *b = buffer(id);
285   b->setActive(true);
286   //b->displayMsg(Message(id, Message::Server, tr("Connected.")));
287   // TODO buffersUpdated();
288 }
289
290 void Client::networkDisconnected(QString net) {
291   foreach(BufferId id, buffers.keys()) {
292     if(id.network() != net) continue;
293     Buffer *b = buffer(id);
294     //b->displayMsg(Message(id, Message::Server, tr("Server disconnected."))); FIXME
295     b->setActive(false);
296   }
297   netConnected[net] = false;
298   if(netsAwaitingInit.contains(net)) {
299     qDebug() << "Network" << net << "disconnected while not yet initialized!";
300     netsAwaitingInit.removeAll(net);
301     emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
302     if(!netsAwaitingInit.count()) emit connected();
303   }
304 }
305
306 void Client::updateBufferId(BufferId id) {
307   bufferIds[id.uid()] = id;  // make lookups by id faster
308   buffer(id);
309 }
310
311 BufferId Client::bufferId(QString net, QString buf) {
312   foreach(BufferId id, buffers.keys()) {
313     if(id.network() == net && id.buffer() == buf) return id;
314   }
315   Q_ASSERT(false);  // should never happen!
316   return BufferId();
317 }
318
319 BufferId Client::statusBufferId(QString net) {
320   return bufferId(net, "");
321 }
322
323
324 Buffer * Client::buffer(BufferId id) {
325   Client *client = Client::instance();
326   if(!buffers.contains(id)) {
327     Buffer *b = new Buffer(id);
328     b->setOwnNick(ownNick[id.network()]);
329     connect(b, SIGNAL(userInput(BufferId, QString)), client, SLOT(userInput(BufferId, QString)));
330     connect(b, SIGNAL(bufferUpdated(Buffer *)), client, SIGNAL(bufferUpdated(Buffer *)));
331     connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SIGNAL(bufferDestroyed(Buffer *)));
332     connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SLOT(removeBuffer(Buffer *)));
333     buffers[id] = b;
334     emit client->bufferUpdated(b);
335   }
336   return buffers[id];
337 }
338
339 QList<BufferId> Client::allBufferIds() {
340   return buffers.keys();
341 }
342
343 void Client::removeBuffer(Buffer *b) {
344   buffers.remove(b->bufferId());
345   bufferIds.remove(b->bufferId().uid());
346 }
347
348 void Client::recvNetworkState(QString net, QVariant state) {
349   netsAwaitingInit.removeAll(net);
350   netConnected[net] = true;
351   setOwnNick(net, state.toMap()["OwnNick"].toString());
352   buffer(statusBufferId(net))->setActive(true);
353   QVariantMap t = state.toMap()["Topics"].toMap();
354   QVariantMap n = state.toMap()["Nicks"].toMap();
355   foreach(QVariant v, t.keys()) {
356     QString buf = v.toString();
357     BufferId id = bufferId(net, buf);
358     buffer(id)->setActive(true);
359     setTopic(net, buf, t[buf].toString());
360   }
361   foreach(QString nick, n.keys()) {
362     addNick(net, nick, n[nick].toMap());
363   }
364   emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
365   if(!netsAwaitingInit.count()) emit connected();
366 }
367
368 void Client::recvMessage(const Message &msg) {
369   Buffer *b = buffer(msg.buffer);
370
371   Buffer::ActivityLevel level = Buffer::OtherActivity;
372   if(msg.type == Message::Plain || msg.type == Message::Notice){
373     level |= Buffer::NewMessage;
374   }
375   if(msg.flags & Message::Highlight){
376     level |= Buffer::Highlight;
377   }
378   emit bufferActivity(level, b);
379
380   b->appendMsg(msg);
381 }
382
383 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
384   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
385
386 }
387
388 void Client::recvBacklogData(BufferId id, QVariantList msgs, bool /*done*/) {
389   Buffer *b = buffer(id);
390   foreach(QVariant v, msgs) {
391     Message msg = v.value<Message>();
392     b->prependMsg(msg);
393     if(!layoutQueue.contains(b)) layoutQueue.append(b);
394   }
395   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
396 }
397
398 void Client::layoutMsg() {
399   if(layoutQueue.count()) {
400     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
401     if(b->layoutMsg()) layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
402   }
403   if(!layoutQueue.count()) layoutTimer->stop();
404 }
405
406 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
407   return instance()->mainUi->layoutMsg(msg);
408 }
409
410 void Client::userInput(BufferId id, QString msg) {
411   emit sendInput(id, msg);
412 }
413
414 void Client::setTopic(QString net, QString buf, QString topic) {
415   BufferId id = bufferId(net, buf);
416   if(!netConnected[id.network()]) return;
417   Buffer *b = buffer(id);
418   b->setTopic(topic);
419   //if(!b->isActive()) {
420   //  b->setActive(true);
421   //  buffersUpdated();
422   //}
423 }
424
425 void Client::addNick(QString net, QString nick, QVariantMap props) {
426   if(!netConnected[net]) return;
427   nicks[net][nick] = props;
428   QVariantMap chans = props["Channels"].toMap();
429   QStringList c = chans.keys();
430   foreach(QString bufname, c) {
431     buffer(bufferId(net, bufname))->addNick(nick, props);
432   }
433 }
434
435 void Client::renameNick(QString net, QString oldnick, QString newnick) {
436   if(!netConnected[net]) return;
437   QStringList chans = nicks[net][oldnick]["Channels"].toMap().keys();
438   foreach(QString c, chans) {
439     buffer(bufferId(net, c))->renameNick(oldnick, newnick);
440   }
441   nicks[net][newnick] = nicks[net].take(oldnick);
442 }
443
444 void Client::updateNick(QString net, QString nick, QVariantMap props) {
445   if(!netConnected[net]) return;
446   QStringList oldchans = nicks[net][nick]["Channels"].toMap().keys();
447   QStringList newchans = props["Channels"].toMap().keys();
448   foreach(QString c, newchans) {
449     if(oldchans.contains(c)) buffer(bufferId(net, c))->updateNick(nick, props);
450     else buffer(bufferId(net, c))->addNick(nick, props);
451   }
452   foreach(QString c, oldchans) {
453     if(!newchans.contains(c)) buffer(bufferId(net, c))->removeNick(nick);
454   }
455   nicks[net][nick] = props;
456 }
457
458 void Client::removeNick(QString net, QString nick) {
459   if(!netConnected[net]) return;
460   QVariantMap chans = nicks[net][nick]["Channels"].toMap();
461   foreach(QString bufname, chans.keys()) {
462     buffer(bufferId(net, bufname))->removeNick(nick);
463   }
464   nicks[net].remove(nick);
465 }
466
467 void Client::setOwnNick(QString net, QString nick) {
468   if(!netConnected[net]) return;
469   ownNick[net] = nick;
470   foreach(BufferId id, buffers.keys()) {
471     if(id.network() == net) {
472       buffers[id]->setOwnNick(nick);
473     }
474   }
475 }
476