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