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