This is it, the long-awaited huge commit with the new Network handling.
[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(NetworkId)), this, SLOT(coreNetworkCreated(NetworkId)));
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 /*
203 void Client::networkConnected(uint netid) {
204   // TODO: create statusBuffer / switch to networkids
205   //BufferInfo id = statusBufferInfo(net);
206   //Buffer *b = buffer(id);
207   //b->setActive(true);
208
209   Network *netinfo = new Network(netid, this);
210   netinfo->setProxy(signalProxy());
211   networkModel()->attachNetwork(netinfo);
212   connect(netinfo, SIGNAL(destroyed()), this, SLOT(networkDestroyed()));
213   _networks[netid] = netinfo;
214 }
215
216 void Client::networkDisconnected(NetworkId networkid) {
217   if(!_networks.contains(networkid)) {
218     qWarning() << "Client::networkDisconnected(uint): unknown Network" << networkid;
219     return;
220 }
221
222   Network *net = _networks.take(networkid);
223   if(!net->isInitialized()) {
224     qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
225     updateCoreConnectionProgress();
226 }
227   net->deleteLater();
228 }
229 */
230
231 void Client::createNetwork(const NetworkInfo &info) {
232   emit instance()->requestCreateNetwork(info);
233 }
234
235 void Client::updateNetwork(const NetworkInfo &info) {
236   emit instance()->requestUpdateNetwork(info);
237 }
238
239 void Client::removeNetwork(NetworkId id) {
240   emit instance()->requestRemoveNetwork(id);
241 }
242
243 void Client::addNetwork(Network *net) {
244   net->setProxy(signalProxy());
245   signalProxy()->synchronize(net);
246   networkModel()->attachNetwork(net);
247   connect(net, SIGNAL(destroyed()), instance(), SLOT(networkDestroyed()));
248   instance()->_networks[net->networkId()] = net;
249   emit instance()->networkCreated(net->networkId());
250 }
251
252 void Client::coreNetworkCreated(NetworkId id) {
253   if(_networks.contains(id)) {
254     qWarning() << "Creation of already existing network requested!";
255     return;
256   }
257   Network *net = new Network(id, this);
258   addNetwork(net);
259 }
260
261 void Client::coreNetworkRemoved(NetworkId id) {
262   if(!_networks.contains(id)) return;
263   Network *net = _networks.take(id);
264   emit networkRemoved(net->networkId());
265   net->deleteLater();
266 }
267
268 /*** Identity handling ***/
269
270 QList<IdentityId> Client::identityIds() {
271   return instance()->_identities.keys();
272 }
273
274 const Identity * Client::identity(IdentityId id) {
275   if(instance()->_identities.contains(id)) return instance()->_identities[id];
276   else return 0;
277 }
278
279 void Client::createIdentity(const Identity &id) {
280   emit instance()->requestCreateIdentity(id);
281 }
282
283 void Client::updateIdentity(const Identity &id) {
284   emit instance()->requestUpdateIdentity(id);
285 }
286
287 void Client::removeIdentity(IdentityId id) {
288   emit instance()->requestRemoveIdentity(id);
289 }
290
291 void Client::coreIdentityCreated(const Identity &other) {
292   if(!_identities.contains(other.id())) {
293     Identity *identity = new Identity(other, this);
294     _identities[other.id()] = identity;
295     identity->setInitialized();
296     signalProxy()->synchronize(identity);
297     emit identityCreated(other.id());
298   } else {
299     qWarning() << tr("Identity already exists in client!");
300   }
301 }
302
303 void Client::coreIdentityRemoved(IdentityId id) {
304   if(_identities.contains(id)) {
305     emit identityRemoved(id);
306     Identity *i = _identities.take(id);
307     i->deleteLater();
308   }
309 }
310
311 /***  ***/
312 void Client::userInput(BufferInfo bufferInfo, QString message) {
313   emit instance()->sendInput(bufferInfo, message);
314 }
315
316 /*** core connection stuff ***/
317
318 void Client::setConnectedToCore(QIODevice *sock) {
319   socket = sock;
320   signalProxy()->addPeer(socket);
321   _connectedToCore = true;
322 }
323
324 void Client::setSyncedToCore() {
325   _syncedToCore = true;
326   emit connected();
327   emit coreConnectionStateChanged(true);
328 }
329
330 void Client::disconnectFromCore() {
331   if(socket) {
332     socket->close();
333     socket->deleteLater();
334   }
335   _connectedToCore = false;
336   _syncedToCore = false;
337   emit disconnected();
338   emit coreConnectionStateChanged(false);
339
340   // Clear internal data. Hopefully nothing relies on it at this point.
341   _networkModel->clear();
342
343   QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
344   while(netIter != _networks.end()) {
345     Network *net = netIter.value();
346     disconnect(net, SIGNAL(destroyed()), this, 0);
347     netIter = _networks.erase(netIter);
348     net->deleteLater();
349   }
350   Q_ASSERT(_networks.isEmpty());
351
352   QHash<BufferId, Buffer *>::iterator bufferIter =  _buffers.begin();
353   while(bufferIter != _buffers.end()) {
354     Buffer *buffer = bufferIter.value();
355     disconnect(buffer, SIGNAL(destroyed()), this, 0);
356     bufferIter = _buffers.erase(bufferIter);
357     buffer->deleteLater();
358   }
359   Q_ASSERT(_buffers.isEmpty());
360
361   QHash<IdentityId, Identity*>::iterator idIter = _identities.begin();
362   while(idIter != _identities.end()) {
363     Identity *id = idIter.value();
364     emit identityRemoved(id->id());
365     idIter = _identities.erase(idIter);
366     id->deleteLater();
367   }
368   Q_ASSERT(_identities.isEmpty());
369
370   sessionData.clear();
371   layoutQueue.clear();
372   layoutTimer->stop();
373 }
374
375 void Client::setCoreConfiguration(const QVariantMap &settings) {
376   SignalProxy::writeDataToDevice(socket, settings);
377 }
378
379 /*** Session data ***/
380
381 void Client::recvSessionData(const QString &key, const QVariant &data) {
382   sessionData[key] = data;
383   emit sessionDataChanged(key, data);
384   emit sessionDataChanged(key);
385 }
386
387 void Client::storeSessionData(const QString &key, const QVariant &data) {
388   // Not sure if this is a good idea, but we'll try it anyway:
389   // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
390   // rather than immediately.
391   emit instance()->sendSessionData(key, data);
392 }
393
394 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
395   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
396   else return def;
397 }
398
399 QStringList Client::sessionDataKeys() {
400   return instance()->sessionData.keys();
401 }
402
403 /*** ***/
404
405
406 /*** ***/
407
408 void Client::updateBufferInfo(BufferInfo id) {
409   emit bufferUpdated(id);
410 }
411
412 void Client::bufferDestroyed() {
413   Buffer *buffer = static_cast<Buffer *>(sender());
414   QHash<BufferId, Buffer *>::iterator iter = _buffers.begin();
415   while(iter != _buffers.end()) {
416     if(iter.value() == buffer) {
417       iter = _buffers.erase(iter);
418       break;
419     }
420     iter++;
421   }
422 }
423
424 void Client::networkDestroyed() {
425   // FIXME this is not gonna work, net is a QObject here already!
426   Network *net = static_cast<Network *>(sender());
427   NetworkId networkId = net->networkId();
428   if(_networks.contains(networkId))
429     _networks.remove(networkId);
430 }
431
432 void Client::recvMessage(const Message &msg) {
433   Buffer *b = buffer(msg.buffer());
434   b->appendMsg(msg);
435   networkModel()->updateBufferActivity(msg);
436
437   if(msg.type() == Message::Plain || msg.type() == Message::Notice || msg.type() == Message::Action) {
438     QString sender = msg.buffer().network() + ":" + msg.buffer().buffer() + ":" + msg.sender();
439     Message mmsg = Message(msg.timestamp(), msg.buffer(), msg.type(), msg.text(), sender, msg.flags());
440     monitorBuffer()->appendMsg(mmsg);
441   }
442
443 }
444
445 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
446   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
447 }
448
449 void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
450   Buffer *b = buffer(id);
451   foreach(QVariant v, msgs) {
452     Message msg = v.value<Message>();
453     b->prependMsg(msg);
454     // networkModel()->updateBufferActivity(msg);
455     if(!layoutQueue.contains(b)) layoutQueue.append(b);
456   }
457   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
458 }
459
460 void Client::layoutMsg() {
461   if(layoutQueue.count()) {
462     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
463     if(b->layoutMsg())
464       layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
465   }
466   
467   if(!layoutQueue.count())
468     layoutTimer->stop();
469 }
470
471 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
472   return instance()->mainUi->layoutMsg(msg);
473 }
474