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