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