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