Still working on the authentification stuff. Technically, now even in the monolithic...
[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 #include "clientproxy.h"
23 #include "buffer.h"
24 #include "buffertreemodel.h"
25 #include "util.h"
26
27 Client * Client::instanceptr = 0;
28
29 bool Client::connectedToCore = false;
30 Client::ClientMode Client::clientMode;
31 QHash<BufferId, Buffer *> Client::buffers;
32 QHash<uint, BufferId> Client::bufferIds;
33 QHash<QString, QHash<QString, VarMap> > Client::nicks;
34 QHash<QString, bool> Client::netConnected;
35 QHash<QString, QString> Client::ownNick;
36 //QList<BufferId> Client::coreBuffers;
37
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     //emit requestBacklog(id, -1, -1);  // TODO: use custom settings for backlog request
184   }
185   connectedToCore = true;
186   emit connected();
187   emit requestNetworkStates();
188 }
189
190 void Client::updateCoreData(UserId, QString key) {
191   if(clientMode == LocalCore) return;
192   QVariant data = Global::data(key);
193   recvProxySignal(GS_UPDATE_GLOBAL_DATA, key, data, QVariant());
194 }
195
196 void Client::updateLocalData(QString key, QVariant data) {
197   Global::updateData(key, data);
198 }
199
200 void Client::recvProxySignal(ClientSignal sig, QVariant arg1, QVariant arg2, QVariant arg3) {
201   if(clientMode == LocalCore) return;
202   QList<QVariant> sigdata;
203   sigdata.append(sig); sigdata.append(arg1); sigdata.append(arg2); sigdata.append(arg3);
204   //qDebug() << "Sending signal: " << sigdata;
205   writeDataToDevice(&socket, QVariant(sigdata));
206 }
207
208 void Client::serverError(QAbstractSocket::SocketError) {
209   emit coreConnectionError(socket.errorString());
210 }
211
212 void Client::serverHasData() {
213   QVariant item;
214   while(readDataFromDevice(&socket, blockSize, item)) {
215     emit recvPartialItem(1,1);
216     QList<QVariant> sigdata = item.toList();
217     Q_ASSERT(sigdata.size() == 4);
218     ClientProxy::instance()->recv((CoreSignal)sigdata[0].toInt(), sigdata[1], sigdata[2], sigdata[3]);
219     blockSize = 0;
220   }
221   if(blockSize > 0) {
222     emit recvPartialItem(socket.bytesAvailable(), blockSize);
223   }
224 }
225
226 void Client::networkConnected(QString net) {
227   netConnected[net] = true;
228   BufferId id = statusBufferId(net);
229   Buffer *b = buffer(id);
230   b->setActive(true);
231   //b->displayMsg(Message(id, Message::Server, tr("Connected.")));
232   // TODO buffersUpdated();
233 }
234
235 void Client::networkDisconnected(QString net) {
236   foreach(BufferId id, buffers.keys()) {
237     if(id.network() != net) continue;
238     Buffer *b = buffer(id);
239     //b->displayMsg(Message(id, Message::Server, tr("Server disconnected."))); FIXME
240     b->setActive(false);
241   }
242   netConnected[net] = false;
243 }
244
245 void Client::updateBufferId(BufferId id) {
246   bufferIds[id.uid()] = id;  // make lookups by id faster
247   buffer(id);
248 }
249
250 BufferId Client::bufferId(QString net, QString buf) {
251   foreach(BufferId id, buffers.keys()) {
252     if(id.network() == net && id.buffer() == buf) return id;
253   }
254   Q_ASSERT(false);  // should never happen!
255   return BufferId();
256 }
257
258 BufferId Client::statusBufferId(QString net) {
259   return bufferId(net, "");
260 }
261
262
263 Buffer * Client::buffer(BufferId id) {
264   Client *client = Client::instance();
265   if(!buffers.contains(id)) {
266     Buffer *b = new Buffer(id);
267     b->setOwnNick(ownNick[id.network()]);
268     connect(b, SIGNAL(userInput(BufferId, QString)), client, SLOT(userInput(BufferId, QString)));
269     connect(b, SIGNAL(bufferUpdated(Buffer *)), client, SIGNAL(bufferUpdated(Buffer *)));
270     connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SIGNAL(bufferDestroyed(Buffer *)));
271     buffers[id] = b;
272     emit client->bufferUpdated(b);
273   }
274   return buffers[id];
275 }
276
277 QList<BufferId> Client::allBufferIds() {
278   return buffers.keys();
279 }
280
281 void Client::recvNetworkState(QString net, QVariant state) {
282   netConnected[net] = true;
283   setOwnNick(net, state.toMap()["OwnNick"].toString());
284   buffer(statusBufferId(net))->setActive(true);
285   VarMap t = state.toMap()["Topics"].toMap();
286   VarMap n = state.toMap()["Nicks"].toMap();
287   foreach(QVariant v, t.keys()) {
288     QString buf = v.toString();
289     BufferId id = bufferId(net, buf);
290     buffer(id)->setActive(true);
291     setTopic(net, buf, t[buf].toString());
292   }
293   foreach(QString nick, n.keys()) {
294     addNick(net, nick, n[nick].toMap());
295   }
296 }
297
298 void Client::recvMessage(const Message &msg) {
299   Buffer *b = buffer(msg.buffer);
300
301   Buffer::ActivityLevel level = Buffer::OtherActivity;
302   if(msg.type == Message::Plain || msg.type == Message::Notice){
303     level |= Buffer::NewMessage;
304   }
305   if(msg.flags & Message::Highlight){
306     level |= Buffer::Highlight;
307   }
308   emit bufferActivity(level, b);
309
310   b->appendMsg(msg);
311 }
312
313 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
314   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
315
316 }
317
318 void Client::recvBacklogData(BufferId id, const QList<QVariant> &msgs, bool /*done*/) {
319   Buffer *b = buffer(id);
320   foreach(QVariant v, msgs) {
321     Message msg = v.value<Message>();
322     b->prependMsg(msg);
323     if(!layoutQueue.contains(b)) layoutQueue.append(b);
324   }
325   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
326 }
327
328 void Client::layoutMsg() {
329   if(layoutQueue.count()) {
330     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
331     if(b->layoutMsg()) layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
332   }
333   if(!layoutQueue.count()) layoutTimer->stop();
334 }
335
336 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
337   return instance()->mainUi->layoutMsg(msg);
338 }
339
340 void Client::userInput(BufferId id, QString msg) {
341   emit sendInput(id, msg);
342 }
343
344 void Client::setTopic(QString net, QString buf, QString topic) {
345   BufferId id = bufferId(net, buf);
346   if(!netConnected[id.network()]) return;
347   Buffer *b = buffer(id);
348   b->setTopic(topic);
349   //if(!b->isActive()) {
350   //  b->setActive(true);
351   //  buffersUpdated();
352   //}
353 }
354
355 void Client::addNick(QString net, QString nick, VarMap props) {
356   if(!netConnected[net]) return;
357   nicks[net][nick] = props;
358   VarMap chans = props["Channels"].toMap();
359   QStringList c = chans.keys();
360   foreach(QString bufname, c) {
361     buffer(bufferId(net, bufname))->addNick(nick, props);
362   }
363 }
364
365 void Client::renameNick(QString net, QString oldnick, QString newnick) {
366   if(!netConnected[net]) return;
367   QStringList chans = nicks[net][oldnick]["Channels"].toMap().keys();
368   foreach(QString c, chans) {
369     buffer(bufferId(net, c))->renameNick(oldnick, newnick);
370   }
371   nicks[net][newnick] = nicks[net].take(oldnick);
372 }
373
374 void Client::updateNick(QString net, QString nick, VarMap props) {
375   if(!netConnected[net]) return;
376   QStringList oldchans = nicks[net][nick]["Channels"].toMap().keys();
377   QStringList newchans = props["Channels"].toMap().keys();
378   foreach(QString c, newchans) {
379     if(oldchans.contains(c)) buffer(bufferId(net, c))->updateNick(nick, props);
380     else buffer(bufferId(net, c))->addNick(nick, props);
381   }
382   foreach(QString c, oldchans) {
383     if(!newchans.contains(c)) buffer(bufferId(net, c))->removeNick(nick);
384   }
385   nicks[net][nick] = props;
386 }
387
388 void Client::removeNick(QString net, QString nick) {
389   if(!netConnected[net]) return;
390   VarMap chans = nicks[net][nick]["Channels"].toMap();
391   foreach(QString bufname, chans.keys()) {
392     buffer(bufferId(net, bufname))->removeNick(nick);
393   }
394   nicks[net].remove(nick);
395 }
396
397 void Client::setOwnNick(QString net, QString nick) {
398   if(!netConnected[net]) return;
399   ownNick[net] = nick;
400   foreach(BufferId id, buffers.keys()) {
401     if(id.network() == net) {
402       buffers[id]->setOwnNick(nick);
403     }
404   }
405 }
406
407