938d107218e59bb17724aa333ee1b220a5d84028
[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;
118   ClientProxy::destroy();
119
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   /* 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::coreSocketConnected() {
164   connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
165   emit coreConnectionMsg(tr("Synchronizing to core..."));
166   VarMap clientInit;
167   clientInit["GuiProtocol"] = GUI_PROTOCOL;
168   clientInit["User"] = coreConnectionInfo["User"].toString();
169   clientInit["Password"] = coreConnectionInfo["Password"].toString();
170   writeDataToDevice(&socket, clientInit);
171 }
172
173 void Client::coreSocketDisconnected() {
174   connectedToCore = false;
175   emit disconnected();
176 }
177
178 void Client::recvCoreState(const QVariant &state) {
179   disconnect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
180   syncToCore(state);
181
182 }
183
184 void Client::syncToCore(const QVariant &coreState) {
185   VarMap sessionState = coreState.toMap()["SessionState"].toMap();
186   VarMap sessData = sessionState["SessionData"].toMap();
187
188   foreach(QString key, sessData.keys()) {
189     recvSessionData(key, sessData[key]);
190   }
191   QList<QVariant> coreBuffers = sessionState["Buffers"].toList();
192   /* make lookups by id faster */
193   foreach(QVariant vid, coreBuffers) {
194     BufferId id = vid.value<BufferId>();
195     bufferIds[id.uid()] = id;  // make lookups by id faster
196     buffer(id);                // create all buffers, so we see them in the network views
197   }
198   netsAwaitingInit = sessionState["Networks"].toStringList();
199   connectedToCore = true;
200   if(netsAwaitingInit.count()) {
201     emit coreConnectionMsg(tr("Requesting network states..."));
202     emit coreConnectionProgress(0, netsAwaitingInit.count());
203     emit requestNetworkStates();
204   }
205   else {
206     emit coreConnectionProgress(1, 1);
207     emit connected();
208   }
209 }
210
211 void Client::recvSessionData(const QString &key, const QVariant &data) {
212   sessionData[key] = data;
213   emit sessionDataChanged(key, data);
214   emit sessionDataChanged(key);
215 }
216
217 void Client::storeSessionData(const QString &key, const QVariant &data) {
218   // Not sure if this is a good idea, but we'll try it anyway:
219   // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
220   // rather than immediately.
221   emit instance()->sendSessionData(key, data);
222 }
223
224 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
225   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
226   else return def;
227 }
228
229 QStringList Client::sessionDataKeys() {
230   return instance()->sessionData.keys();
231 }
232
233 void Client::recvProxySignal(ClientSignal sig, QVariant arg1, QVariant arg2, QVariant arg3) {
234   if(clientMode == LocalCore) return;
235   QList<QVariant> sigdata;
236   sigdata.append(sig); sigdata.append(arg1); sigdata.append(arg2); sigdata.append(arg3);
237   //qDebug() << "Sending signal: " << sigdata;
238   writeDataToDevice(&socket, QVariant(sigdata));
239 }
240
241 void Client::serverError(QAbstractSocket::SocketError) {
242   emit coreConnectionError(socket.errorString());
243 }
244
245 void Client::serverHasData() {
246   QVariant item;
247   while(readDataFromDevice(&socket, blockSize, item)) {
248     emit recvPartialItem(1,1);
249     QList<QVariant> sigdata = item.toList();
250     Q_ASSERT(sigdata.size() == 4);
251     ClientProxy::instance()->recv((CoreSignal)sigdata[0].toInt(), sigdata[1], sigdata[2], sigdata[3]);
252     blockSize = 0;
253   }
254   if(blockSize > 0) {
255     emit recvPartialItem(socket.bytesAvailable(), blockSize);
256   }
257 }
258
259 void Client::networkConnected(QString net) {
260   Q_ASSERT(!netsAwaitingInit.contains(net));
261   netConnected[net] = true;
262   BufferId id = statusBufferId(net);
263   Buffer *b = buffer(id);
264   b->setActive(true);
265   //b->displayMsg(Message(id, Message::Server, tr("Connected.")));
266   // TODO buffersUpdated();
267 }
268
269 void Client::networkDisconnected(QString net) {
270   foreach(BufferId id, buffers.keys()) {
271     if(id.network() != net) continue;
272     Buffer *b = buffer(id);
273     //b->displayMsg(Message(id, Message::Server, tr("Server disconnected."))); FIXME
274     b->setActive(false);
275   }
276   netConnected[net] = false;
277   if(netsAwaitingInit.contains(net)) {
278     qDebug() << "Network" << net << "disconnected while not yet initialized!";
279     netsAwaitingInit.removeAll(net);
280     emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
281     if(!netsAwaitingInit.count()) emit connected();
282   }
283 }
284
285 void Client::updateBufferId(BufferId id) {
286   bufferIds[id.uid()] = id;  // make lookups by id faster
287   buffer(id);
288 }
289
290 BufferId Client::bufferId(QString net, QString buf) {
291   foreach(BufferId id, buffers.keys()) {
292     if(id.network() == net && id.buffer() == buf) return id;
293   }
294   Q_ASSERT(false);  // should never happen!
295   return BufferId();
296 }
297
298 BufferId Client::statusBufferId(QString net) {
299   return bufferId(net, "");
300 }
301
302
303 Buffer * Client::buffer(BufferId id) {
304   Client *client = Client::instance();
305   if(!buffers.contains(id)) {
306     Buffer *b = new Buffer(id);
307     b->setOwnNick(ownNick[id.network()]);
308     connect(b, SIGNAL(userInput(BufferId, QString)), client, SLOT(userInput(BufferId, QString)));
309     connect(b, SIGNAL(bufferUpdated(Buffer *)), client, SIGNAL(bufferUpdated(Buffer *)));
310     connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SIGNAL(bufferDestroyed(Buffer *)));
311     buffers[id] = b;
312     emit client->bufferUpdated(b);
313   }
314   return buffers[id];
315 }
316
317 QList<BufferId> Client::allBufferIds() {
318   return buffers.keys();
319 }
320
321 void Client::recvNetworkState(QString net, QVariant state) {
322   netsAwaitingInit.removeAll(net);
323   netConnected[net] = true;
324   setOwnNick(net, state.toMap()["OwnNick"].toString());
325   buffer(statusBufferId(net))->setActive(true);
326   VarMap t = state.toMap()["Topics"].toMap();
327   VarMap n = state.toMap()["Nicks"].toMap();
328   foreach(QVariant v, t.keys()) {
329     QString buf = v.toString();
330     BufferId id = bufferId(net, buf);
331     buffer(id)->setActive(true);
332     setTopic(net, buf, t[buf].toString());
333   }
334   foreach(QString nick, n.keys()) {
335     addNick(net, nick, n[nick].toMap());
336   }
337   emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
338   if(!netsAwaitingInit.count()) emit connected();
339 }
340
341 void Client::recvMessage(const Message &msg) {
342   Buffer *b = buffer(msg.buffer);
343
344   Buffer::ActivityLevel level = Buffer::OtherActivity;
345   if(msg.type == Message::Plain || msg.type == Message::Notice){
346     level |= Buffer::NewMessage;
347   }
348   if(msg.flags & Message::Highlight){
349     level |= Buffer::Highlight;
350   }
351   emit bufferActivity(level, b);
352
353   b->appendMsg(msg);
354 }
355
356 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
357   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
358
359 }
360
361 void Client::recvBacklogData(BufferId id, const QList<QVariant> &msgs, bool /*done*/) {
362   Buffer *b = buffer(id);
363   foreach(QVariant v, msgs) {
364     Message msg = v.value<Message>();
365     b->prependMsg(msg);
366     if(!layoutQueue.contains(b)) layoutQueue.append(b);
367   }
368   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
369 }
370
371 void Client::layoutMsg() {
372   if(layoutQueue.count()) {
373     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
374     if(b->layoutMsg()) layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
375   }
376   if(!layoutQueue.count()) layoutTimer->stop();
377 }
378
379 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
380   return instance()->mainUi->layoutMsg(msg);
381 }
382
383 void Client::userInput(BufferId id, QString msg) {
384   emit sendInput(id, msg);
385 }
386
387 void Client::setTopic(QString net, QString buf, QString topic) {
388   BufferId id = bufferId(net, buf);
389   if(!netConnected[id.network()]) return;
390   Buffer *b = buffer(id);
391   b->setTopic(topic);
392   //if(!b->isActive()) {
393   //  b->setActive(true);
394   //  buffersUpdated();
395   //}
396 }
397
398 void Client::addNick(QString net, QString nick, VarMap props) {
399   if(!netConnected[net]) return;
400   nicks[net][nick] = props;
401   VarMap chans = props["Channels"].toMap();
402   QStringList c = chans.keys();
403   foreach(QString bufname, c) {
404     buffer(bufferId(net, bufname))->addNick(nick, props);
405   }
406 }
407
408 void Client::renameNick(QString net, QString oldnick, QString newnick) {
409   if(!netConnected[net]) return;
410   QStringList chans = nicks[net][oldnick]["Channels"].toMap().keys();
411   foreach(QString c, chans) {
412     buffer(bufferId(net, c))->renameNick(oldnick, newnick);
413   }
414   nicks[net][newnick] = nicks[net].take(oldnick);
415 }
416
417 void Client::updateNick(QString net, QString nick, VarMap props) {
418   if(!netConnected[net]) return;
419   QStringList oldchans = nicks[net][nick]["Channels"].toMap().keys();
420   QStringList newchans = props["Channels"].toMap().keys();
421   foreach(QString c, newchans) {
422     if(oldchans.contains(c)) buffer(bufferId(net, c))->updateNick(nick, props);
423     else buffer(bufferId(net, c))->addNick(nick, props);
424   }
425   foreach(QString c, oldchans) {
426     if(!newchans.contains(c)) buffer(bufferId(net, c))->removeNick(nick);
427   }
428   nicks[net][nick] = props;
429 }
430
431 void Client::removeNick(QString net, QString nick) {
432   if(!netConnected[net]) return;
433   VarMap chans = nicks[net][nick]["Channels"].toMap();
434   foreach(QString bufname, chans.keys()) {
435     buffer(bufferId(net, bufname))->removeNick(nick);
436   }
437   nicks[net].remove(nick);
438 }
439
440 void Client::setOwnNick(QString net, QString nick) {
441   if(!netConnected[net]) return;
442   ownNick[net] = nick;
443   foreach(BufferId id, buffers.keys()) {
444     if(id.network() == net) {
445       buffers[id]->setOwnNick(nick);
446     }
447   }
448 }
449