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