de43a0b6b55d39244bc8ed04d46836035e124bc7
[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   connect(p, SIGNAL(disconnected()), this, SLOT(disconnectFromCore()));
110
111   //connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
112   connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
113   connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
114   connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
115
116   layoutTimer = new QTimer(this);
117   layoutTimer->setInterval(0);
118   layoutTimer->setSingleShot(false);
119   connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
120
121 }
122
123 /*** public static methods ***/
124
125 QList<BufferInfo> Client::allBufferInfos() {
126   QList<BufferInfo> bufferids;
127   foreach(Buffer *buffer, buffers()) {
128     bufferids << buffer->bufferInfo();
129   }
130   return bufferids;
131 }
132
133 QList<Buffer *> Client::buffers() {
134   return instance()->_buffers.values();
135 }
136
137
138 // FIXME remove
139 Buffer *Client::buffer(BufferId bufferUid) {
140   if(instance()->_buffers.contains(bufferUid))
141     return instance()->_buffers[bufferUid];
142   else
143     return 0;
144 }
145
146 // FIXME remove
147 Buffer *Client::buffer(BufferInfo id) {
148   Buffer *buff = buffer(id.uid());
149
150   if(!buff) {
151     Client *client = Client::instance();
152     buff = new Buffer(id, client);
153     connect(buff, SIGNAL(destroyed()),
154             client, SLOT(bufferDestroyed()));
155     client->_buffers[id.uid()] = buff;
156     emit client->bufferUpdated(id);
157   }
158   Q_ASSERT(buff);
159   return buff;
160 }
161
162
163 NetworkModel *Client::networkModel() {
164   return instance()->_networkModel;
165 }
166
167 BufferModel *Client::bufferModel() {
168   return instance()->_bufferModel;
169 }
170
171 NickModel *Client::nickModel() {
172   return instance()->_nickModel;
173 }
174
175
176 SignalProxy *Client::signalProxy() {
177   return instance()->_signalProxy;
178 }
179
180 bool Client::isConnected() {
181   return instance()->_connectedToCore;
182 }
183
184 bool Client::isSynced() {
185   return instance()->_syncedToCore;
186 }
187
188 /*** Network handling ***/
189
190 QList<NetworkId> Client::networkIds() {
191   return instance()->_networks.keys();
192 }
193
194 const Network * Client::network(NetworkId networkid) {
195   if(instance()->_networks.contains(networkid)) return instance()->_networks[networkid];
196   else return 0;
197 }
198
199 /*** Identity handling ***/
200
201 QList<IdentityId> Client::identityIds() {
202   return instance()->_identities.keys();
203 }
204
205 const Identity * Client::identity(IdentityId id) {
206   if(instance()->_identities.contains(id)) return instance()->_identities[id];
207   else return 0;
208 }
209
210 void Client::createIdentity(const Identity &id) {
211   emit instance()->requestCreateIdentity(id);
212 }
213
214 void Client::updateIdentity(const Identity &id) {
215   emit instance()->requestUpdateIdentity(id);
216 }
217
218 void Client::removeIdentity(IdentityId id) {
219   emit instance()->requestRemoveIdentity(id);
220 }
221
222 void Client::coreIdentityCreated(const Identity &other) {
223   if(!_identities.contains(other.id())) {
224     Identity *identity = new Identity(other, this);
225     _identities[other.id()] = identity;
226     identity->setInitialized();
227     signalProxy()->synchronize(identity);
228     emit identityCreated(other.id());
229   } else {
230     qWarning() << tr("Identity already exists in client!");
231   }
232 }
233
234 void Client::coreIdentityRemoved(IdentityId id) {
235   if(_identities.contains(id)) {
236     emit identityRemoved(id);
237     Identity *i = _identities.take(id);
238     i->deleteLater();
239   }
240 }
241
242 /***  ***/
243 void Client::userInput(BufferInfo bufferInfo, QString message) {
244   emit instance()->sendInput(bufferInfo, message);
245 }
246
247 /*** core connection stuff ***/
248
249 void Client::setConnectedToCore(QIODevice *sock) {
250   socket = sock;
251   signalProxy()->addPeer(socket);
252   _connectedToCore = true;
253 }
254
255 void Client::setSyncedToCore() {
256   _syncedToCore = true;
257   emit connected();
258   emit coreConnectionStateChanged(true);
259 }
260
261 void Client::disconnectFromCore() {
262   if(socket) {
263     socket->close();
264     socket->deleteLater();
265   }
266   _connectedToCore = false;
267   _syncedToCore = false;
268   emit disconnected();
269   emit coreConnectionStateChanged(false);
270
271   // Clear internal data. Hopefully nothing relies on it at this point.
272   _networkModel->clear();
273
274   QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
275   while(netIter != _networks.end()) {
276     Network *net = netIter.value();
277     disconnect(net, SIGNAL(destroyed()), this, 0);
278     netIter = _networks.erase(netIter);
279     net->deleteLater();
280   }
281   Q_ASSERT(_networks.isEmpty());
282
283   QHash<BufferId, Buffer *>::iterator bufferIter =  _buffers.begin();
284   while(bufferIter != _buffers.end()) {
285     Buffer *buffer = bufferIter.value();
286     disconnect(buffer, SIGNAL(destroyed()), this, 0);
287     bufferIter = _buffers.erase(bufferIter);
288     buffer->deleteLater();
289   }
290   Q_ASSERT(_buffers.isEmpty());
291
292   QHash<IdentityId, Identity*>::iterator idIter = _identities.begin();
293   while(idIter != _identities.end()) {
294     Identity *id = idIter.value();
295     emit identityRemoved(id->id());
296     idIter = _identities.erase(idIter);
297     id->deleteLater();
298   }
299   Q_ASSERT(_identities.isEmpty());
300
301   sessionData.clear();
302   layoutQueue.clear();
303   layoutTimer->stop();
304 }
305
306 void Client::setCoreConfiguration(const QVariantMap &settings) {
307   SignalProxy::writeDataToDevice(socket, settings);
308 }
309
310 /*** Session data ***/
311
312 void Client::recvSessionData(const QString &key, const QVariant &data) {
313   sessionData[key] = data;
314   emit sessionDataChanged(key, data);
315   emit sessionDataChanged(key);
316 }
317
318 void Client::storeSessionData(const QString &key, const QVariant &data) {
319   // Not sure if this is a good idea, but we'll try it anyway:
320   // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
321   // rather than immediately.
322   emit instance()->sendSessionData(key, data);
323 }
324
325 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
326   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
327   else return def;
328 }
329
330 QStringList Client::sessionDataKeys() {
331   return instance()->sessionData.keys();
332 }
333
334 /*** ***/
335
336 /*
337 void Client::networkConnected(uint netid) {
338   // TODO: create statusBuffer / switch to networkids
339   //BufferInfo id = statusBufferInfo(net);
340   //Buffer *b = buffer(id);
341   //b->setActive(true);
342
343   Network *netinfo = new Network(netid, this);
344   netinfo->setProxy(signalProxy());
345   networkModel()->attachNetwork(netinfo);
346   connect(netinfo, SIGNAL(destroyed()), this, SLOT(networkDestroyed()));
347   _networks[netid] = netinfo;
348 }
349
350 void Client::networkDisconnected(NetworkId networkid) {
351   if(!_networks.contains(networkid)) {
352     qWarning() << "Client::networkDisconnected(uint): unknown Network" << networkid;
353     return;
354   }
355
356   Network *net = _networks.take(networkid);
357   if(!net->isInitialized()) {
358     qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
359     updateCoreConnectionProgress();
360   }
361   net->deleteLater();
362 }
363 */
364
365 void Client::addNetwork(NetworkId netid) {
366   Network *net = new Network(netid, instance());
367   addNetwork(net);
368 }
369
370 void Client::addNetwork(Network *net) {
371   net->setProxy(signalProxy());
372   signalProxy()->synchronize(net);
373   networkModel()->attachNetwork(net);
374   connect(net, SIGNAL(destroyed()), instance(), SLOT(networkDestroyed()));
375   instance()->_networks[net->networkId()] = net;
376   emit instance()->networkAdded(net->networkId());
377   //if(net->networkId() == 1) net->requestConnect(); // FIXME
378 }
379
380 /*** ***/
381
382 void Client::updateBufferInfo(BufferInfo id) {
383   emit bufferUpdated(id);
384 }
385
386 void Client::bufferDestroyed() {
387   Buffer *buffer = static_cast<Buffer *>(sender());
388   QHash<BufferId, Buffer *>::iterator iter = _buffers.begin();
389   while(iter != _buffers.end()) {
390     if(iter.value() == buffer) {
391       iter = _buffers.erase(iter);
392       break;
393     }
394     iter++;
395   }
396 }
397
398 void Client::networkDestroyed() {
399   Network *netinfo = static_cast<Network *>(sender());
400   NetworkId networkId = netinfo->networkId();
401   if(_networks.contains(networkId))
402     _networks.remove(networkId);
403 }
404
405 void Client::recvMessage(const Message &msg) {
406   Buffer *b = buffer(msg.buffer());
407   b->appendMsg(msg);
408   networkModel()->updateBufferActivity(msg);
409 }
410
411 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
412   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
413 }
414
415 void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
416   Buffer *b = buffer(id);
417   foreach(QVariant v, msgs) {
418     Message msg = v.value<Message>();
419     b->prependMsg(msg);
420     // networkModel()->updateBufferActivity(msg);
421     if(!layoutQueue.contains(b)) layoutQueue.append(b);
422   }
423   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
424 }
425
426 void Client::layoutMsg() {
427   if(layoutQueue.count()) {
428     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
429     if(b->layoutMsg())
430       layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
431   }
432   
433   if(!layoutQueue.count())
434     layoutTimer->stop();
435 }
436
437 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
438   return instance()->mainUi->layoutMsg(msg);
439 }
440