Syncing my current state, Network settings still not fully functional, so don't use...
[quassel.git] / src / client / client.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
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) version 3.                                           *
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 "bufferinfo.h"
24 #include "global.h"
25 #include "identity.h"
26 #include "ircchannel.h"
27 #include "ircuser.h"
28 #include "message.h"
29 #include "network.h"
30 #include "networkmodel.h"
31 #include "buffermodel.h"
32 #include "nickmodel.h"
33 #include "quasselui.h"
34 #include "signalproxy.h"
35 #include "util.h"
36
37 QPointer<Client> Client::instanceptr = 0;
38
39 /*** Initialization/destruction ***/
40
41 Client *Client::instance() {
42   if(!instanceptr)
43     instanceptr = new Client();
44   return instanceptr;
45 }
46
47 void Client::destroy() {
48   //delete instanceptr;
49   instanceptr->deleteLater();
50 }
51
52 void Client::init(AbstractUi *ui) {
53   instance()->mainUi = ui;
54   instance()->init();
55 }
56
57 Client::Client(QObject *parent)
58   : QObject(parent),
59     socket(0),
60     _signalProxy(new SignalProxy(SignalProxy::Client, this)),
61     mainUi(0),
62     _networkModel(0),
63     _bufferModel(0),
64     _nickModel(0),
65     _connectedToCore(false),
66     _syncedToCore(false)
67 {
68 }
69
70 Client::~Client() {
71   disconnectFromCore();
72 }
73
74 void Client::init() {
75
76   _networkModel = new NetworkModel(this);
77   connect(this, SIGNAL(bufferUpdated(BufferInfo)),
78           _networkModel, SLOT(bufferUpdated(BufferInfo)));
79
80   _bufferModel = new BufferModel(_networkModel);
81   _nickModel = new NickModel(_networkModel);
82
83   SignalProxy *p = signalProxy();
84   p->attachSignal(this, SIGNAL(sendSessionData(const QString &, const QVariant &)),
85                   SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)));
86   p->attachSlot(SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)),
87                 this, SLOT(recvSessionData(const QString &, const QVariant &)));
88   //p->attachSlot(SIGNAL(networkConnected(uint)),
89   //FIXME              this, SLOT(networkConnected(uint)));
90   //p->attachSlot(SIGNAL(networkDisconnected(uint)),
91   //FIXME              this, SLOT(networkDisconnected(uint)));
92   p->attachSlot(SIGNAL(displayMsg(const Message &)),
93                 this, SLOT(recvMessage(const Message &)));
94   p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)),
95                 this, SLOT(recvStatusMsg(QString, QString)));
96
97
98   p->attachSlot(SIGNAL(backlogData(BufferInfo, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferInfo, const QVariantList &, bool)));
99   p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), this, SLOT(updateBufferInfo(BufferInfo)));
100   p->attachSignal(this, SIGNAL(sendInput(BufferInfo, QString)));
101   p->attachSignal(this, SIGNAL(requestNetworkStates()));
102
103   p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &)), SIGNAL(createIdentity(const Identity &)));
104   p->attachSignal(this, SIGNAL(requestUpdateIdentity(const Identity &)), SIGNAL(updateIdentity(const Identity &)));
105   p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
106   p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
107   p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
108
109   p->attachSignal(this, SIGNAL(requestCreateNetwork(const NetworkInfo &)), SIGNAL(createNetwork(const NetworkInfo &)));
110   p->attachSignal(this, SIGNAL(requestUpdateNetwork(const NetworkInfo &)), SIGNAL(updateNetwork(const NetworkInfo &)));
111   p->attachSignal(this, SIGNAL(requestRemoveNetwork(NetworkId)), SIGNAL(removeNetwork(NetworkId)));
112   p->attachSlot(SIGNAL(networkCreated(const NetworkInfo &)), this, SLOT(coreNetworkCreated(const NetworkInfo &)));
113   p->attachSlot(SIGNAL(networkRemoved(NetworkId)), this, SLOT(coreNetworkRemoved(NetworkId)));
114
115   connect(p, SIGNAL(disconnected()), this, SLOT(disconnectFromCore()));
116
117   //connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
118   connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
119   connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
120   connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
121
122   layoutTimer = new QTimer(this);
123   layoutTimer->setInterval(0);
124   layoutTimer->setSingleShot(false);
125   connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
126
127 }
128
129 /*** public static methods ***/
130
131 QList<BufferInfo> Client::allBufferInfos() {
132   QList<BufferInfo> bufferids;
133   foreach(Buffer *buffer, buffers()) {
134     bufferids << buffer->bufferInfo();
135   }
136   return bufferids;
137 }
138
139 QList<Buffer *> Client::buffers() {
140   return instance()->_buffers.values();
141 }
142
143
144 // FIXME remove
145 Buffer *Client::buffer(BufferId bufferUid) {
146   if(instance()->_buffers.contains(bufferUid))
147     return instance()->_buffers[bufferUid];
148   else
149     return 0;
150 }
151
152 // FIXME remove
153 Buffer *Client::buffer(BufferInfo id) {
154   Buffer *buff = buffer(id.uid());
155
156   if(!buff) {
157     Client *client = Client::instance();
158     buff = new Buffer(id, client);
159     connect(buff, SIGNAL(destroyed()),
160             client, SLOT(bufferDestroyed()));
161     client->_buffers[id.uid()] = buff;
162     emit client->bufferUpdated(id);
163   }
164   Q_ASSERT(buff);
165   return buff;
166 }
167
168
169 NetworkModel *Client::networkModel() {
170   return instance()->_networkModel;
171 }
172
173 BufferModel *Client::bufferModel() {
174   return instance()->_bufferModel;
175 }
176
177 NickModel *Client::nickModel() {
178   return instance()->_nickModel;
179 }
180
181
182 SignalProxy *Client::signalProxy() {
183   return instance()->_signalProxy;
184 }
185
186 bool Client::isConnected() {
187   return instance()->_connectedToCore;
188 }
189
190 bool Client::isSynced() {
191   return instance()->_syncedToCore;
192 }
193
194 /*** Network handling ***/
195
196 QList<NetworkId> Client::networkIds() {
197   return instance()->_networks.keys();
198 }
199
200 const Network * Client::network(NetworkId networkid) {
201   if(instance()->_networks.contains(networkid)) return instance()->_networks[networkid];
202   else return 0;
203 }
204
205 /*** Identity handling ***/
206
207 QList<IdentityId> Client::identityIds() {
208   return instance()->_identities.keys();
209 }
210
211 const Identity * Client::identity(IdentityId id) {
212   if(instance()->_identities.contains(id)) return instance()->_identities[id];
213   else return 0;
214 }
215
216 void Client::createIdentity(const Identity &id) {
217   emit instance()->requestCreateIdentity(id);
218 }
219
220 void Client::updateIdentity(const Identity &id) {
221   emit instance()->requestUpdateIdentity(id);
222 }
223
224 void Client::removeIdentity(IdentityId id) {
225   emit instance()->requestRemoveIdentity(id);
226 }
227
228 void Client::coreIdentityCreated(const Identity &other) {
229   if(!_identities.contains(other.id())) {
230     Identity *identity = new Identity(other, this);
231     _identities[other.id()] = identity;
232     identity->setInitialized();
233     signalProxy()->synchronize(identity);
234     emit identityCreated(other.id());
235   } else {
236     qWarning() << tr("Identity already exists in client!");
237   }
238 }
239
240 void Client::coreIdentityRemoved(IdentityId id) {
241   if(_identities.contains(id)) {
242     emit identityRemoved(id);
243     Identity *i = _identities.take(id);
244     i->deleteLater();
245   }
246 }
247
248 /***  ***/
249 void Client::userInput(BufferInfo bufferInfo, QString message) {
250   emit instance()->sendInput(bufferInfo, message);
251 }
252
253 /*** core connection stuff ***/
254
255 void Client::setConnectedToCore(QIODevice *sock) {
256   socket = sock;
257   signalProxy()->addPeer(socket);
258   _connectedToCore = true;
259 }
260
261 void Client::setSyncedToCore() {
262   _syncedToCore = true;
263   emit connected();
264   emit coreConnectionStateChanged(true);
265 }
266
267 void Client::disconnectFromCore() {
268   if(socket) {
269     socket->close();
270     socket->deleteLater();
271   }
272   _connectedToCore = false;
273   _syncedToCore = false;
274   emit disconnected();
275   emit coreConnectionStateChanged(false);
276
277   // Clear internal data. Hopefully nothing relies on it at this point.
278   _networkModel->clear();
279
280   QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
281   while(netIter != _networks.end()) {
282     Network *net = netIter.value();
283     disconnect(net, SIGNAL(destroyed()), this, 0);
284     netIter = _networks.erase(netIter);
285     net->deleteLater();
286   }
287   Q_ASSERT(_networks.isEmpty());
288
289   QHash<BufferId, Buffer *>::iterator bufferIter =  _buffers.begin();
290   while(bufferIter != _buffers.end()) {
291     Buffer *buffer = bufferIter.value();
292     disconnect(buffer, SIGNAL(destroyed()), this, 0);
293     bufferIter = _buffers.erase(bufferIter);
294     buffer->deleteLater();
295   }
296   Q_ASSERT(_buffers.isEmpty());
297
298   QHash<IdentityId, Identity*>::iterator idIter = _identities.begin();
299   while(idIter != _identities.end()) {
300     Identity *id = idIter.value();
301     emit identityRemoved(id->id());
302     idIter = _identities.erase(idIter);
303     id->deleteLater();
304   }
305   Q_ASSERT(_identities.isEmpty());
306
307   sessionData.clear();
308   layoutQueue.clear();
309   layoutTimer->stop();
310 }
311
312 void Client::setCoreConfiguration(const QVariantMap &settings) {
313   SignalProxy::writeDataToDevice(socket, settings);
314 }
315
316 /*** Session data ***/
317
318 void Client::recvSessionData(const QString &key, const QVariant &data) {
319   sessionData[key] = data;
320   emit sessionDataChanged(key, data);
321   emit sessionDataChanged(key);
322 }
323
324 void Client::storeSessionData(const QString &key, const QVariant &data) {
325   // Not sure if this is a good idea, but we'll try it anyway:
326   // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
327   // rather than immediately.
328   emit instance()->sendSessionData(key, data);
329 }
330
331 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
332   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
333   else return def;
334 }
335
336 QStringList Client::sessionDataKeys() {
337   return instance()->sessionData.keys();
338 }
339
340 /*** ***/
341
342 // FIXME
343 void Client::disconnectFromNetwork(NetworkId id) {
344   if(!instance()->_networks.contains(id)) return;
345   Network *net = instance()->_networks[id];
346   net->requestDisconnect();
347 }
348
349 /*
350 void Client::networkConnected(uint netid) {
351   // TODO: create statusBuffer / switch to networkids
352   //BufferInfo id = statusBufferInfo(net);
353   //Buffer *b = buffer(id);
354   //b->setActive(true);
355
356   Network *netinfo = new Network(netid, this);
357   netinfo->setProxy(signalProxy());
358   networkModel()->attachNetwork(netinfo);
359   connect(netinfo, SIGNAL(destroyed()), this, SLOT(networkDestroyed()));
360   _networks[netid] = netinfo;
361 }
362
363 void Client::networkDisconnected(NetworkId networkid) {
364   if(!_networks.contains(networkid)) {
365     qWarning() << "Client::networkDisconnected(uint): unknown Network" << networkid;
366     return;
367   }
368
369   Network *net = _networks.take(networkid);
370   if(!net->isInitialized()) {
371     qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
372     updateCoreConnectionProgress();
373   }
374   net->deleteLater();
375 }
376 */
377
378 void Client::addNetwork(Network *net) {
379   net->setProxy(signalProxy());
380   signalProxy()->synchronize(net);
381   networkModel()->attachNetwork(net);
382   connect(net, SIGNAL(destroyed()), instance(), SLOT(networkDestroyed()));
383   instance()->_networks[net->networkId()] = net;
384   emit instance()->networkCreated(net->networkId());
385 }
386
387 void Client::createNetwork(const NetworkInfo &info) {
388
389
390 }
391
392 /*** ***/
393
394 void Client::updateBufferInfo(BufferInfo id) {
395   emit bufferUpdated(id);
396 }
397
398 void Client::bufferDestroyed() {
399   Buffer *buffer = static_cast<Buffer *>(sender());
400   QHash<BufferId, Buffer *>::iterator iter = _buffers.begin();
401   while(iter != _buffers.end()) {
402     if(iter.value() == buffer) {
403       iter = _buffers.erase(iter);
404       break;
405     }
406     iter++;
407   }
408 }
409
410 void Client::networkDestroyed() {
411   // FIXME this is not gonna work, net is a QObject here already!
412   Network *net = static_cast<Network *>(sender());
413   NetworkId networkId = net->networkId();
414   if(_networks.contains(networkId))
415     _networks.remove(networkId);
416 }
417
418 void Client::recvMessage(const Message &msg) {
419   Buffer *b = buffer(msg.buffer());
420   b->appendMsg(msg);
421   networkModel()->updateBufferActivity(msg);
422 }
423
424 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
425   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
426 }
427
428 void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
429   Buffer *b = buffer(id);
430   foreach(QVariant v, msgs) {
431     Message msg = v.value<Message>();
432     b->prependMsg(msg);
433     // networkModel()->updateBufferActivity(msg);
434     if(!layoutQueue.contains(b)) layoutQueue.append(b);
435   }
436   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
437 }
438
439 void Client::layoutMsg() {
440   if(layoutQueue.count()) {
441     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
442     if(b->layoutMsg())
443       layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
444   }
445   
446   if(!layoutQueue.count())
447     layoutTimer->stop();
448 }
449
450 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
451   return instance()->mainUi->layoutMsg(msg);
452 }
453