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