Added a function decodeString() to util.{h|cpp} that takes a QByteArray with raw...
[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 QHash<BufferId, Buffer *> Client::buffers;
34 QHash<uint, BufferId> Client::bufferIds;
35 QHash<QString, QHash<QString, VarMap> > Client::nicks;
36 QHash<QString, bool> Client::netConnected;
37 QHash<QString, QString> Client::ownNick;
38
39 Client *Client::instance() {
40   if(instanceptr) return instanceptr;
41   instanceptr = new Client();
42   return instanceptr;
43 }
44
45 void Client::destroy() {
46   delete instanceptr;
47   instanceptr = 0;
48 }
49
50 Client::Client() {
51   clientProxy = ClientProxy::instance();
52
53   _bufferModel = new BufferTreeModel(this);
54
55   connect(this, SIGNAL(bufferSelected(Buffer *)), _bufferModel, SLOT(selectBuffer(Buffer *)));
56   connect(this, SIGNAL(bufferUpdated(Buffer *)), _bufferModel, SLOT(bufferUpdated(Buffer *)));
57   connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)), _bufferModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
58
59     // TODO: make this configurable (allow monolithic client to connect to remote cores)
60   if(Global::runMode == Global::Monolithic) clientMode = LocalCore;
61   else clientMode = RemoteCore;
62   connectedToCore = false;
63 }
64
65 void Client::init(AbstractUi *ui) {
66   instance()->mainUi = ui;
67   instance()->init();
68 }
69
70 void Client::init() {
71   blockSize = 0;
72
73   connect(&socket, SIGNAL(readyRead()), this, SLOT(serverHasData()));
74   connect(&socket, SIGNAL(connected()), this, SLOT(coreConnected()));
75   connect(&socket, SIGNAL(disconnected()), this, SLOT(coreDisconnected()));
76   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(serverError(QAbstractSocket::SocketError)));
77
78   connect(Global::instance(), SIGNAL(dataPutLocally(UserId, QString)), this, SLOT(updateCoreData(UserId, QString)));
79   connect(clientProxy, SIGNAL(csUpdateGlobalData(QString, QVariant)), this, SLOT(updateLocalData(QString, QVariant)));
80
81   connect(clientProxy, SIGNAL(send(ClientSignal, QVariant, QVariant, QVariant)), this, SLOT(recvProxySignal(ClientSignal, QVariant, QVariant, QVariant)));
82   connect(clientProxy, SIGNAL(csServerState(QString, QVariant)), this, SLOT(recvNetworkState(QString, QVariant)));
83   connect(clientProxy, SIGNAL(csServerConnected(QString)), this, SLOT(networkConnected(QString)));
84   connect(clientProxy, SIGNAL(csServerDisconnected(QString)), this, SLOT(networkDisconnected(QString)));
85   connect(clientProxy, SIGNAL(csDisplayMsg(Message)), this, SLOT(recvMessage(const Message &)));
86   connect(clientProxy, SIGNAL(csDisplayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
87   connect(clientProxy, SIGNAL(csTopicSet(QString, QString, QString)), this, SLOT(setTopic(QString, QString, QString)));
88   connect(clientProxy, SIGNAL(csNickAdded(QString, QString, VarMap)), this, SLOT(addNick(QString, QString, VarMap)));
89   connect(clientProxy, SIGNAL(csNickRemoved(QString, QString)), this, SLOT(removeNick(QString, QString)));
90   connect(clientProxy, SIGNAL(csNickRenamed(QString, QString, QString)), this, SLOT(renameNick(QString, QString, QString)));
91   connect(clientProxy, SIGNAL(csNickUpdated(QString, QString, VarMap)), this, SLOT(updateNick(QString, QString, VarMap)));
92   connect(clientProxy, SIGNAL(csOwnNickSet(QString, QString)), this, SLOT(setOwnNick(QString, QString)));
93   connect(clientProxy, SIGNAL(csBacklogData(BufferId, const QList<QVariant> &, bool)), this, SLOT(recvBacklogData(BufferId, QList<QVariant>, bool)));
94   connect(clientProxy, SIGNAL(csUpdateBufferId(BufferId)), this, SLOT(updateBufferId(BufferId)));
95   connect(this, SIGNAL(sendInput(BufferId, QString)), clientProxy, SLOT(gsUserInput(BufferId, QString)));
96   connect(this, SIGNAL(requestBacklog(BufferId, QVariant, QVariant)), clientProxy, SLOT(gsRequestBacklog(BufferId, QVariant, QVariant)));
97   connect(this, SIGNAL(requestNetworkStates()), clientProxy, SLOT(gsRequestNetworkStates()));
98
99   connect(mainUi, SIGNAL(connectToCore(const VarMap &)), this, SLOT(connectToCore(const VarMap &)));
100   connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
101   connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
102   connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
103
104   layoutTimer = new QTimer(this);
105   layoutTimer->setInterval(0);
106   layoutTimer->setSingleShot(false);
107   connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
108
109 }
110
111 Client::~Client() {
112   //delete mainUi;
113   //delete _bufferModel;
114   foreach(Buffer *buf, buffers.values()) delete buf;
115   ClientProxy::destroy();
116
117 }
118
119 BufferTreeModel *Client::bufferModel() {
120   return instance()->_bufferModel;
121 }
122
123 bool Client::isConnected() { return connectedToCore; }
124
125 void Client::connectToCore(const VarMap &conn) {
126   // TODO implement SSL
127   if(isConnected()) {
128     qDebug() << "Already connected to core!";
129     return;
130   }
131   if(conn["Host"].toString().isEmpty()) {
132     clientMode = LocalCore;
133     syncToCore();  // TODO send user and pw from conn info
134   } else {
135     clientMode = RemoteCore;
136     socket.connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
137   }
138 }
139
140 void Client::disconnectFromCore() {
141   if(clientMode == RemoteCore) {
142     socket.close();
143   } else {
144     disconnectFromLocalCore();
145     coreDisconnected();
146   }
147   // TODO clear internal data
148 }
149
150 void Client::coreConnected() {
151   syncToCore();
152
153 }
154
155 void Client::coreDisconnected() {
156   connectedToCore = false;
157   emit disconnected();
158 }
159
160 void Client::syncToCore() {
161   VarMap state;
162   if(clientMode == LocalCore) {
163     state = connectToLocalCore("Default", "password").toMap(); // TODO make this configurable
164   } else {
165
166   }
167
168   VarMap data = state["CoreData"].toMap();
169   foreach(QString key, data.keys()) {
170     Global::updateData(key, data[key]);
171   }
172   //if(!Global::data("CoreReady").toBool()) {
173   //  qFatal("Something is wrong, getting invalid data from core!");
174   //}
175
176   VarMap sessionState = state["SessionState"].toMap();
177   QList<QVariant> coreBuffers = sessionState["Buffers"].toList();
178   /* make lookups by id faster */
179   foreach(QVariant vid, coreBuffers) {
180     BufferId id = vid.value<BufferId>();
181     bufferIds[id.uid()] = id;  // make lookups by id faster
182     buffer(id);                // create all buffers, so we see them in the network views
183   }
184   connectedToCore = true;
185   emit connected();
186   emit requestNetworkStates();
187 }
188
189 void Client::updateCoreData(UserId, QString key) {
190   if(clientMode == LocalCore) return;
191   QVariant data = Global::data(key);
192   recvProxySignal(GS_UPDATE_GLOBAL_DATA, key, data, QVariant());
193 }
194
195 void Client::updateLocalData(QString key, QVariant data) {
196   Global::updateData(key, data);
197 }
198
199 void Client::recvProxySignal(ClientSignal sig, QVariant arg1, QVariant arg2, QVariant arg3) {
200   if(clientMode == LocalCore) return;
201   QList<QVariant> sigdata;
202   sigdata.append(sig); sigdata.append(arg1); sigdata.append(arg2); sigdata.append(arg3);
203   //qDebug() << "Sending signal: " << sigdata;
204   writeDataToDevice(&socket, QVariant(sigdata));
205 }
206
207 void Client::serverError(QAbstractSocket::SocketError) {
208   emit coreConnectionError(socket.errorString());
209 }
210
211 void Client::serverHasData() {
212   QVariant item;
213   while(readDataFromDevice(&socket, blockSize, item)) {
214     emit recvPartialItem(1,1);
215     QList<QVariant> sigdata = item.toList();
216     Q_ASSERT(sigdata.size() == 4);
217     ClientProxy::instance()->recv((CoreSignal)sigdata[0].toInt(), sigdata[1], sigdata[2], sigdata[3]);
218     blockSize = 0;
219   }
220   if(blockSize > 0) {
221     emit recvPartialItem(socket.bytesAvailable(), blockSize);
222   }
223 }
224
225 void Client::networkConnected(QString net) {
226   netConnected[net] = true;
227   BufferId id = statusBufferId(net);
228   Buffer *b = buffer(id);
229   b->setActive(true);
230   //b->displayMsg(Message(id, Message::Server, tr("Connected.")));
231   // TODO buffersUpdated();
232 }
233
234 void Client::networkDisconnected(QString net) {
235   foreach(BufferId id, buffers.keys()) {
236     if(id.network() != net) continue;
237     Buffer *b = buffer(id);
238     //b->displayMsg(Message(id, Message::Server, tr("Server disconnected."))); FIXME
239     b->setActive(false);
240   }
241   netConnected[net] = false;
242 }
243
244 void Client::updateBufferId(BufferId id) {
245   bufferIds[id.uid()] = id;  // make lookups by id faster
246   buffer(id);
247 }
248
249 BufferId Client::bufferId(QString net, QString buf) {
250   foreach(BufferId id, buffers.keys()) {
251     if(id.network() == net && id.buffer() == buf) return id;
252   }
253   Q_ASSERT(false);  // should never happen!
254   return BufferId();
255 }
256
257 BufferId Client::statusBufferId(QString net) {
258   return bufferId(net, "");
259 }
260
261
262 Buffer * Client::buffer(BufferId id) {
263   Client *client = Client::instance();
264   if(!buffers.contains(id)) {
265     Buffer *b = new Buffer(id);
266     b->setOwnNick(ownNick[id.network()]);
267     connect(b, SIGNAL(userInput(BufferId, QString)), client, SLOT(userInput(BufferId, QString)));
268     connect(b, SIGNAL(bufferUpdated(Buffer *)), client, SIGNAL(bufferUpdated(Buffer *)));
269     connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SIGNAL(bufferDestroyed(Buffer *)));
270     buffers[id] = b;
271     emit client->bufferUpdated(b);
272   }
273   return buffers[id];
274 }
275
276 QList<BufferId> Client::allBufferIds() {
277   return buffers.keys();
278 }
279
280 void Client::recvNetworkState(QString net, QVariant state) {
281   netConnected[net] = true;
282   setOwnNick(net, state.toMap()["OwnNick"].toString());
283   buffer(statusBufferId(net))->setActive(true);
284   VarMap t = state.toMap()["Topics"].toMap();
285   VarMap n = state.toMap()["Nicks"].toMap();
286   foreach(QVariant v, t.keys()) {
287     QString buf = v.toString();
288     BufferId id = bufferId(net, buf);
289     buffer(id)->setActive(true);
290     setTopic(net, buf, t[buf].toString());
291   }
292   foreach(QString nick, n.keys()) {
293     addNick(net, nick, n[nick].toMap());
294   }
295 }
296
297 void Client::recvMessage(const Message &msg) {
298   Buffer *b = buffer(msg.buffer);
299
300   Buffer::ActivityLevel level = Buffer::OtherActivity;
301   if(msg.type == Message::Plain || msg.type == Message::Notice){
302     level |= Buffer::NewMessage;
303   }
304   if(msg.flags & Message::Highlight){
305     level |= Buffer::Highlight;
306   }
307   emit bufferActivity(level, b);
308
309   b->appendMsg(msg);
310 }
311
312 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
313   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
314
315 }
316
317 void Client::recvBacklogData(BufferId id, const QList<QVariant> &msgs, bool /*done*/) {
318   Buffer *b = buffer(id);
319   foreach(QVariant v, msgs) {
320     Message msg = v.value<Message>();
321     b->prependMsg(msg);
322     if(!layoutQueue.contains(b)) layoutQueue.append(b);
323   }
324   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
325 }
326
327 void Client::layoutMsg() {
328   if(layoutQueue.count()) {
329     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
330     if(b->layoutMsg()) layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
331   }
332   if(!layoutQueue.count()) layoutTimer->stop();
333 }
334
335 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
336   return instance()->mainUi->layoutMsg(msg);
337 }
338
339 void Client::userInput(BufferId id, QString msg) {
340   emit sendInput(id, msg);
341 }
342
343 void Client::setTopic(QString net, QString buf, QString topic) {
344   BufferId id = bufferId(net, buf);
345   if(!netConnected[id.network()]) return;
346   Buffer *b = buffer(id);
347   b->setTopic(topic);
348   //if(!b->isActive()) {
349   //  b->setActive(true);
350   //  buffersUpdated();
351   //}
352 }
353
354 void Client::addNick(QString net, QString nick, VarMap props) {
355   if(!netConnected[net]) return;
356   nicks[net][nick] = props;
357   VarMap chans = props["Channels"].toMap();
358   QStringList c = chans.keys();
359   foreach(QString bufname, c) {
360     buffer(bufferId(net, bufname))->addNick(nick, props);
361   }
362 }
363
364 void Client::renameNick(QString net, QString oldnick, QString newnick) {
365   if(!netConnected[net]) return;
366   QStringList chans = nicks[net][oldnick]["Channels"].toMap().keys();
367   foreach(QString c, chans) {
368     buffer(bufferId(net, c))->renameNick(oldnick, newnick);
369   }
370   nicks[net][newnick] = nicks[net].take(oldnick);
371 }
372
373 void Client::updateNick(QString net, QString nick, VarMap props) {
374   if(!netConnected[net]) return;
375   QStringList oldchans = nicks[net][nick]["Channels"].toMap().keys();
376   QStringList newchans = props["Channels"].toMap().keys();
377   foreach(QString c, newchans) {
378     if(oldchans.contains(c)) buffer(bufferId(net, c))->updateNick(nick, props);
379     else buffer(bufferId(net, c))->addNick(nick, props);
380   }
381   foreach(QString c, oldchans) {
382     if(!newchans.contains(c)) buffer(bufferId(net, c))->removeNick(nick);
383   }
384   nicks[net][nick] = props;
385 }
386
387 void Client::removeNick(QString net, QString nick) {
388   if(!netConnected[net]) return;
389   VarMap chans = nicks[net][nick]["Channels"].toMap();
390   foreach(QString bufname, chans.keys()) {
391     buffer(bufferId(net, bufname))->removeNick(nick);
392   }
393   nicks[net].remove(nick);
394 }
395
396 void Client::setOwnNick(QString net, QString nick) {
397   if(!netConnected[net]) return;
398   ownNick[net] = nick;
399   foreach(BufferId id, buffers.keys()) {
400     if(id.network() == net) {
401       buffers[id]->setOwnNick(nick);
402     }
403   }
404 }
405