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