OK Folks, my first commit after quite a while, and while Quassel looks the same as...
[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(coreConnected()));
77   connect(&socket, SIGNAL(disconnected()), this, SLOT(coreDisconnected()));
78   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(serverError(QAbstractSocket::SocketError)));
79
80   connect(Global::instance(), SIGNAL(dataPutLocally(UserId, QString)), this, SLOT(updateCoreData(UserId, QString)));
81   connect(clientProxy, SIGNAL(csUpdateGlobalData(QString, QVariant)), this, SLOT(updateLocalData(QString, QVariant)));
82   connect(this, SIGNAL(sendSessionData(const QString &, const QVariant &)), clientProxy, SLOT(gsSessionDataChanged(const QString &, const QVariant &)));
83   connect(clientProxy, SIGNAL(csSessionDataChanged(const QString &, const QVariant &)), this, SLOT(recvSessionData(const QString &, const QVariant &)));
84
85   connect(clientProxy, SIGNAL(send(ClientSignal, QVariant, QVariant, QVariant)), this, SLOT(recvProxySignal(ClientSignal, QVariant, QVariant, QVariant)));
86   connect(clientProxy, SIGNAL(csServerState(QString, QVariant)), this, SLOT(recvNetworkState(QString, QVariant)));
87   connect(clientProxy, SIGNAL(csServerConnected(QString)), this, SLOT(networkConnected(QString)));
88   connect(clientProxy, SIGNAL(csServerDisconnected(QString)), this, SLOT(networkDisconnected(QString)));
89   connect(clientProxy, SIGNAL(csDisplayMsg(Message)), this, SLOT(recvMessage(const Message &)));
90   connect(clientProxy, SIGNAL(csDisplayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
91   connect(clientProxy, SIGNAL(csTopicSet(QString, QString, QString)), this, SLOT(setTopic(QString, QString, QString)));
92   connect(clientProxy, SIGNAL(csNickAdded(QString, QString, VarMap)), this, SLOT(addNick(QString, QString, VarMap)));
93   connect(clientProxy, SIGNAL(csNickRemoved(QString, QString)), this, SLOT(removeNick(QString, QString)));
94   connect(clientProxy, SIGNAL(csNickRenamed(QString, QString, QString)), this, SLOT(renameNick(QString, QString, QString)));
95   connect(clientProxy, SIGNAL(csNickUpdated(QString, QString, VarMap)), this, SLOT(updateNick(QString, QString, VarMap)));
96   connect(clientProxy, SIGNAL(csOwnNickSet(QString, QString)), this, SLOT(setOwnNick(QString, QString)));
97   connect(clientProxy, SIGNAL(csBacklogData(BufferId, const QList<QVariant> &, bool)), this, SLOT(recvBacklogData(BufferId, QList<QVariant>, bool)));
98   connect(clientProxy, SIGNAL(csUpdateBufferId(BufferId)), this, SLOT(updateBufferId(BufferId)));
99   connect(this, SIGNAL(sendInput(BufferId, QString)), clientProxy, SLOT(gsUserInput(BufferId, QString)));
100   connect(this, SIGNAL(requestBacklog(BufferId, QVariant, QVariant)), clientProxy, SLOT(gsRequestBacklog(BufferId, QVariant, QVariant)));
101   connect(this, SIGNAL(requestNetworkStates()), clientProxy, SLOT(gsRequestNetworkStates()));
102
103   connect(mainUi, SIGNAL(connectToCore(const VarMap &)), this, SLOT(connectToCore(const VarMap &)));
104   connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
105   connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
106   connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
107
108   layoutTimer = new QTimer(this);
109   layoutTimer->setInterval(0);
110   layoutTimer->setSingleShot(false);
111   connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
112
113 }
114
115 Client::~Client() {
116   //delete mainUi;
117   //delete _bufferModel;
118   foreach(Buffer *buf, buffers.values()) delete buf;
119   ClientProxy::destroy();
120
121 }
122
123 BufferTreeModel *Client::bufferModel() {
124   return instance()->_bufferModel;
125 }
126
127 bool Client::isConnected() { return connectedToCore; }
128
129 void Client::connectToCore(const VarMap &conn) {
130   // TODO implement SSL
131   coreConnectionInfo = conn;
132   if(isConnected()) {
133     emit coreConnectionError(tr("Already connected to Core!"));
134     return;
135   }
136   if(conn["Host"].toString().isEmpty()) {
137     clientMode = LocalCore;
138     syncToCore();
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     coreDisconnected();
152   }
153   /* Clear internal data. Hopefully nothing relies on it at this point. */
154   coreConnectionInfo.clear();
155   sessionData.clear();
156   //foreach(Buffer *buf, buffers.values()) delete buf;
157   qDebug() << "barfoo";
158   _bufferModel->clear();
159   //qDeleteAll(buffers);
160   qDebug() << "foobar";
161 }
162
163 void Client::coreConnected() {
164   syncToCore();
165
166 }
167
168 void Client::coreDisconnected() {
169   connectedToCore = false;
170   emit disconnected();
171 }
172
173 void Client::syncToCore() {
174   VarMap state;
175   if(clientMode == LocalCore) {
176     state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString()).toMap();
177   } else {
178     // TODO connect to remote cores
179   }
180
181   VarMap data = state["CoreData"].toMap();
182   foreach(QString key, data.keys()) {
183     Global::updateData(key, data[key]);
184   }
185   //if(!Global::data("CoreReady").toBool()) {
186   //  qFatal("Something is wrong, getting invalid data from core!");
187   //}
188
189   VarMap sessionState = state["SessionState"].toMap();
190   VarMap sessData = sessionState["SessionData"].toMap();
191   foreach(QString key, sessData.keys()) {
192     recvSessionData(key, sessData[key]);
193   }
194   QList<QVariant> coreBuffers = sessionState["Buffers"].toList();
195   /* make lookups by id faster */
196   foreach(QVariant vid, coreBuffers) {
197     BufferId id = vid.value<BufferId>();
198     bufferIds[id.uid()] = id;  // make lookups by id faster
199     buffer(id);                // create all buffers, so we see them in the network views
200   }
201   netsAwaitingInit = sessionState["Networks"].toStringList();
202   connectedToCore = true;
203   if(netsAwaitingInit.count()) {
204     emit coreConnectionMsg(tr("Requesting network states..."));
205     emit coreConnectionProgress(0, netsAwaitingInit.count());
206     emit requestNetworkStates();
207   }
208   else {
209     emit coreConnectionProgress(1, 1);
210     emit connected();
211   }
212 }
213
214 void Client::updateCoreData(UserId, QString key) {
215   if(clientMode == LocalCore) return;
216   QVariant data = Global::data(key);
217   recvProxySignal(GS_UPDATE_GLOBAL_DATA, key, data, QVariant());
218 }
219
220 void Client::updateLocalData(QString key, QVariant data) {
221   Global::updateData(key, data);
222 }
223
224 void Client::recvSessionData(const QString &key, const QVariant &data) {
225   sessionData[key] = data;
226   emit sessionDataChanged(key, data);
227   emit sessionDataChanged(key);
228 }
229
230 void Client::storeSessionData(const QString &key, const QVariant &data) {
231   // Not sure if this is a good idea, but we'll try it anyway:
232   // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
233   // rather than immediately.
234   emit instance()->sendSessionData(key, data);
235 }
236
237 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
238   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
239   else return def;
240 }
241
242 QStringList Client::sessionDataKeys() {
243   return instance()->sessionData.keys();
244 }
245
246 void Client::recvProxySignal(ClientSignal sig, QVariant arg1, QVariant arg2, QVariant arg3) {
247   if(clientMode == LocalCore) return;
248   QList<QVariant> sigdata;
249   sigdata.append(sig); sigdata.append(arg1); sigdata.append(arg2); sigdata.append(arg3);
250   //qDebug() << "Sending signal: " << sigdata;
251   writeDataToDevice(&socket, QVariant(sigdata));
252 }
253
254 void Client::serverError(QAbstractSocket::SocketError) {
255   emit coreConnectionError(socket.errorString());
256 }
257
258 void Client::serverHasData() {
259   QVariant item;
260   while(readDataFromDevice(&socket, blockSize, item)) {
261     emit recvPartialItem(1,1);
262     QList<QVariant> sigdata = item.toList();
263     Q_ASSERT(sigdata.size() == 4);
264     ClientProxy::instance()->recv((CoreSignal)sigdata[0].toInt(), sigdata[1], sigdata[2], sigdata[3]);
265     blockSize = 0;
266   }
267   if(blockSize > 0) {
268     emit recvPartialItem(socket.bytesAvailable(), blockSize);
269   }
270 }
271
272 void Client::networkConnected(QString net) {
273   Q_ASSERT(!netsAwaitingInit.contains(net));
274   netConnected[net] = true;
275   BufferId id = statusBufferId(net);
276   Buffer *b = buffer(id);
277   b->setActive(true);
278   //b->displayMsg(Message(id, Message::Server, tr("Connected.")));
279   // TODO buffersUpdated();
280 }
281
282 void Client::networkDisconnected(QString net) {
283   foreach(BufferId id, buffers.keys()) {
284     if(id.network() != net) continue;
285     Buffer *b = buffer(id);
286     //b->displayMsg(Message(id, Message::Server, tr("Server disconnected."))); FIXME
287     b->setActive(false);
288   }
289   netConnected[net] = false;
290   if(netsAwaitingInit.contains(net)) {
291     qDebug() << "Network" << net << "disconnected while not yet initialized!";
292     netsAwaitingInit.removeAll(net);
293     emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
294     if(!netsAwaitingInit.count()) emit connected();
295   }
296 }
297
298 void Client::updateBufferId(BufferId id) {
299   bufferIds[id.uid()] = id;  // make lookups by id faster
300   buffer(id);
301 }
302
303 BufferId Client::bufferId(QString net, QString buf) {
304   foreach(BufferId id, buffers.keys()) {
305     if(id.network() == net && id.buffer() == buf) return id;
306   }
307   Q_ASSERT(false);  // should never happen!
308   return BufferId();
309 }
310
311 BufferId Client::statusBufferId(QString net) {
312   return bufferId(net, "");
313 }
314
315
316 Buffer * Client::buffer(BufferId id) {
317   Client *client = Client::instance();
318   if(!buffers.contains(id)) {
319     Buffer *b = new Buffer(id);
320     b->setOwnNick(ownNick[id.network()]);
321     connect(b, SIGNAL(userInput(BufferId, QString)), client, SLOT(userInput(BufferId, QString)));
322     connect(b, SIGNAL(bufferUpdated(Buffer *)), client, SIGNAL(bufferUpdated(Buffer *)));
323     connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SIGNAL(bufferDestroyed(Buffer *)));
324     buffers[id] = b;
325     emit client->bufferUpdated(b);
326   }
327   return buffers[id];
328 }
329
330 QList<BufferId> Client::allBufferIds() {
331   return buffers.keys();
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