We now have back a real BufferModel. It's basically a ProxyModel to
[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 "networkinfo.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 }
49
50 void Client::init(AbstractUi *ui) {
51   instance()->mainUi = ui;
52   instance()->init();
53 }
54
55 Client::Client(QObject *parent)
56   : QObject(parent),
57     socket(0),
58     _signalProxy(new SignalProxy(SignalProxy::Client, this)),
59     mainUi(0),
60     _networkModel(0),
61     _bufferModel(0),
62     connectedToCore(false)
63 {
64 }
65
66 Client::~Client() {
67 }
68
69 void Client::init() {
70   blockSize = 0;
71
72   _networkModel = new NetworkModel(this);
73   _bufferModel = new BufferModel(_networkModel);
74
75   connect(this, SIGNAL(bufferSelected(Buffer *)),
76           _bufferModel, SLOT(selectBuffer(Buffer *)));
77   
78   connect(this, SIGNAL(bufferUpdated(Buffer *)),
79           _networkModel, SLOT(bufferUpdated(Buffer *)));
80   connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)),
81           _networkModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
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(coreState(const QVariant &)),
89                 this, SLOT(recvCoreState(const QVariant &)));
90   p->attachSlot(SIGNAL(networkConnected(uint)),
91                 this, SLOT(networkConnected(uint)));
92   p->attachSlot(SIGNAL(networkDisconnected(uint)),
93                 this, SLOT(networkDisconnected(uint)));
94   p->attachSlot(SIGNAL(displayMsg(const Message &)),
95                 this, SLOT(recvMessage(const Message &)));
96   p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)),
97                 this, SLOT(recvStatusMsg(QString, QString)));
98
99
100   p->attachSlot(SIGNAL(backlogData(BufferInfo, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferInfo, const QVariantList &, bool)));
101   p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), this, SLOT(updateBufferInfo(BufferInfo)));
102   p->attachSignal(this, SIGNAL(sendInput(BufferInfo, QString)));
103   p->attachSignal(this, SIGNAL(requestNetworkStates()));
104
105   p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &)), SIGNAL(createIdentity(const Identity &)));
106   p->attachSignal(this, SIGNAL(requestUpdateIdentity(const Identity &)), SIGNAL(updateIdentity(const Identity &)));
107   p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
108   p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
109   p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
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<NetworkInfo *> Client::networkInfos() {
127   return instance()->_networkInfo.values();
128 }
129
130 NetworkInfo *Client::networkInfo(uint networkid) {
131   if(instance()->_networkInfo.contains(networkid))
132     return instance()->_networkInfo[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 Buffer *Client::buffer(uint bufferUid) {
150   if(instance()->_buffers.contains(bufferUid))
151     return instance()->_buffers[bufferUid];
152   else
153     return 0;
154 }
155
156 Buffer *Client::buffer(BufferInfo id) {
157   Buffer *buff = buffer(id.uid());
158
159   if(!buff) {
160     Client *client = Client::instance();
161     buff = new Buffer(id, client);
162
163     connect(buff, SIGNAL(userInput(BufferInfo, QString)),
164             client, SLOT(userInput(BufferInfo, QString)));
165     connect(buff, SIGNAL(bufferUpdated(Buffer *)),
166             client, SIGNAL(bufferUpdated(Buffer *)));
167     connect(buff, SIGNAL(destroyed()),
168             client, SLOT(bufferDestroyed()));
169     client->_buffers[id.uid()] = buff;
170     emit client->bufferUpdated(buff);
171   }
172   Q_ASSERT(buff);
173   return buff;
174 }
175
176 // FIXME switch to netids!
177 // WHEN IS THIS NEEDED ANYHOW!?
178 // ...only for finding the Buffer for a channel, I guess...
179 BufferInfo Client::bufferInfo(QString net, QString buf) {
180   foreach(Buffer *buffer_, buffers()) {
181     BufferInfo bufferInfo = buffer_->bufferInfo();
182     if(!bufferInfo.network().compare(net, Qt::CaseInsensitive) && !bufferInfo.buffer().compare(buf, Qt::CaseInsensitive))
183       return bufferInfo;
184   }
185   Q_ASSERT(false);  // should never happen!
186   return BufferInfo();
187 }
188
189 BufferInfo Client::statusBufferInfo(QString net) {
190   return bufferInfo(net, "");
191 }
192
193 NetworkModel *Client::networkModel() {
194   return instance()->_networkModel;
195 }
196
197 BufferModel *Client::bufferModel() {
198   return instance()->_bufferModel;
199 }
200
201
202 SignalProxy *Client::signalProxy() {
203   return instance()->_signalProxy;
204 }
205
206
207 /*** Identity handling ***/
208
209 QList<IdentityId> Client::identityIds() {
210   return instance()->_identities.keys();
211 }
212
213 const Identity * Client::identity(IdentityId id) {
214   if(instance()->_identities.contains(id)) return instance()->_identities[id];
215   else return 0;
216 }
217
218
219 void Client::createIdentity(const Identity &id) {
220   emit instance()->requestCreateIdentity(id);
221 }
222
223 void Client::updateIdentity(const Identity &id) {
224   emit instance()->requestUpdateIdentity(id);
225 }
226
227 void Client::removeIdentity(IdentityId id) {
228   emit instance()->requestRemoveIdentity(id);
229 }
230
231 void Client::coreIdentityCreated(const Identity &other) {
232   if(!_identities.contains(other.id())) {
233     Identity *identity = new Identity(other, this);
234     _identities[other.id()] = identity;
235     identity->setInitialized();
236     signalProxy()->synchronize(identity);
237     emit identityCreated(other.id());
238   } else {
239     qWarning() << tr("Identity already exists in client!");
240   }
241 }
242
243 void Client::coreIdentityRemoved(IdentityId id) {
244   if(_identities.contains(id)) {
245     emit identityRemoved(id);
246     Identity *i = _identities.take(id);
247     i->deleteLater();
248   }
249 }
250
251 /***  ***/
252
253
254 bool Client::isConnected() {
255   return instance()->connectedToCore;
256 }
257
258 void Client::fakeInput(uint bufferUid, QString message) {
259   Buffer *buff = buffer(bufferUid);
260   if(!buff)
261     qWarning() << "No Buffer with uid" << bufferUid << "can't send Input" << message;
262   else
263     emit instance()->sendInput(buff->bufferInfo(), message);
264 }
265
266 void Client::fakeInput(BufferInfo bufferInfo, QString message) {
267   fakeInput(bufferInfo, message);
268 }
269
270 void Client::connectToCore(const QVariantMap &conn) {
271   // TODO implement SSL
272   coreConnectionInfo = conn;
273   if(isConnected()) {
274     emit coreConnectionError(tr("Already connected to Core!"));
275     return;
276   }
277   
278   if(socket != 0)
279     socket->deleteLater();
280   
281   if(conn["Host"].toString().isEmpty()) {
282     clientMode = LocalCore;
283     socket = new QBuffer(this);
284     connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
285     socket->open(QIODevice::ReadWrite);
286     //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
287     //syncToCore(state);
288     coreSocketConnected();
289   } else {
290     clientMode = RemoteCore;
291     emit coreConnectionMsg(tr("Connecting..."));
292     Q_ASSERT(!socket);
293     QTcpSocket *sock = new QTcpSocket(this);
294     socket = sock;
295     connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
296     connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
297     connect(signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
298     connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
299     sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
300   }
301 }
302
303 void Client::disconnectFromCore() {
304   socket->close();
305 }
306
307 void Client::setCoreConfiguration(const QVariantMap &settings) {
308   SignalProxy::writeDataToDevice(socket, settings);
309 }
310
311 void Client::coreSocketConnected() {
312   connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
313   emit coreConnectionMsg(tr("Synchronizing to core..."));
314   QVariantMap clientInit;
315   clientInit["GuiProtocol"] = GUI_PROTOCOL;
316   clientInit["User"] = coreConnectionInfo["User"].toString();
317   clientInit["Password"] = coreConnectionInfo["Password"].toString();
318   SignalProxy::writeDataToDevice(socket, clientInit);
319 }
320
321 void Client::coreSocketDisconnected() {
322   instance()->connectedToCore = false;
323   emit disconnected();
324   emit coreConnectionStateChanged(false);
325   socket->deleteLater();
326   blockSize = 0;
327
328   /* Clear internal data. Hopefully nothing relies on it at this point. */
329   _networkModel->clear();
330
331   QHash<BufferId, Buffer *>::iterator bufferIter =  _buffers.begin();
332   while(bufferIter != _buffers.end()) {
333     Buffer *buffer = bufferIter.value();
334     disconnect(buffer, SIGNAL(destroyed()), this, 0);
335     bufferIter = _buffers.erase(bufferIter);
336     buffer->deleteLater();
337   }
338   Q_ASSERT(_buffers.isEmpty());
339
340
341   QHash<NetworkId, NetworkInfo*>::iterator netIter = _networkInfo.begin();
342   while(netIter != _networkInfo.end()) {
343     NetworkInfo *net = netIter.value();
344     disconnect(net, SIGNAL(destroyed()), this, 0);
345     netIter = _networkInfo.erase(netIter);
346     net->deleteLater();
347   }
348   Q_ASSERT(_networkInfo.isEmpty());
349
350   QHash<IdentityId, Identity*>::iterator idIter = _identities.begin();
351   while(idIter != _identities.end()) {
352     Identity *id = idIter.value();
353     emit identityRemoved(id->id());
354     idIter = _identities.erase(idIter);
355     id->deleteLater();
356   }
357   Q_ASSERT(_identities.isEmpty());
358
359   coreConnectionInfo.clear();
360   sessionData.clear();
361   layoutQueue.clear();
362   layoutTimer->stop();
363 }
364
365 void Client::recvCoreState(const QVariant &state) {
366   disconnect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
367   disconnect(socket, 0, this, 0);  // rest of communication happens through SignalProxy
368   signalProxy()->addPeer(socket);
369   syncToCore(state);
370 }
371
372 // TODO: auth errors
373 void Client::syncToCore(const QVariant &coreState) {
374   if(!coreState.toMap().contains("SessionState")) {
375     emit coreConnectionError(tr("Invalid data received from core!"));
376     disconnectFromCore();
377     return;
378   }
379
380   QVariantMap sessionState = coreState.toMap()["SessionState"].toMap();
381
382   // store sessionData
383   QVariantMap sessData = sessionState["SessionData"].toMap();
384   foreach(QString key, sessData.keys())
385     recvSessionData(key, sessData[key]);
386
387   // create identities
388   foreach(QVariant vid, sessionState["Identities"].toList()) {
389     coreIdentityCreated(vid.value<Identity>());
390     //Identity *id = new Identity(vid.value<Identity>(), this);
391     //_identities[id->id()] = id;
392     //signalProxy()->synchronize(id);
393     //qDebug() << "received identity" << id->identityName();
394   }
395
396   // store Buffer details
397   QVariantList coreBuffers = sessionState["Buffers"].toList();
398   /* make lookups by id faster */
399   foreach(QVariant vid, coreBuffers) {
400     buffer(vid.value<BufferInfo>()); // create all buffers, so we see them in the network views
401   }
402
403   // create networkInfo objects
404   QVariantList networkids = sessionState["Networks"].toList();
405   foreach(QVariant networkid, networkids) {
406     networkConnected(networkid.toUInt());
407   }
408
409   instance()->connectedToCore = true;
410   updateCoreConnectionProgress();
411
412 }
413
414 void Client::updateCoreConnectionProgress() {
415   // we'll do this in three steps:
416   // 1.) networks
417   // 2.) channels
418   // 3.) ircusers
419
420   int numNets = networkInfos().count();
421   int numNetsWaiting = 0;
422
423   int numIrcUsers = 0;
424   int numIrcUsersWaiting = 0;
425
426   int numChannels = 0;
427   int numChannelsWaiting = 0;
428
429   foreach(NetworkInfo *net, networkInfos()) {
430     if(! net->initialized())
431       numNetsWaiting++;
432
433     numIrcUsers += net->ircUsers().count();
434     foreach(IrcUser *user, net->ircUsers()) {
435       if(! user->initialized())
436         numIrcUsersWaiting++;
437     }
438
439     numChannels += net->ircChannels().count();
440     foreach(IrcChannel *channel, net->ircChannels()) {
441       if(! channel->initialized())
442         numChannelsWaiting++;
443     }
444   }
445
446   if(numNetsWaiting > 0) {
447     emit coreConnectionMsg(tr("Requesting network states..."));
448     emit coreConnectionProgress(numNets - numNetsWaiting, numNets);
449     return;
450   }
451
452   if(numIrcUsersWaiting > 0) {
453     emit coreConnectionMsg(tr("Requesting User states..."));
454     emit coreConnectionProgress(numIrcUsers - numIrcUsersWaiting, numIrcUsers);
455     return;
456   }
457
458   if(numChannelsWaiting > 0) {
459     emit coreConnectionMsg(tr("Requesting Channel states..."));
460     emit coreConnectionProgress(numChannels - numChannelsWaiting, numChannels);
461     return;
462   }
463
464   emit coreConnectionProgress(1,1);
465   emit connected();
466   emit coreConnectionStateChanged(true);
467   foreach(NetworkInfo *net, networkInfos()) {
468     disconnect(net, 0, this, SLOT(updateCoreConnectionProgress()));
469   }
470
471   // signalProxy()->dumpProxyStats();
472 }
473
474 void Client::recvSessionData(const QString &key, const QVariant &data) {
475   sessionData[key] = data;
476   emit sessionDataChanged(key, data);
477   emit sessionDataChanged(key);
478 }
479
480 void Client::storeSessionData(const QString &key, const QVariant &data) {
481   // Not sure if this is a good idea, but we'll try it anyway:
482   // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
483   // rather than immediately.
484   emit instance()->sendSessionData(key, data);
485 }
486
487 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
488   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
489   else return def;
490 }
491
492 QStringList Client::sessionDataKeys() {
493   return instance()->sessionData.keys();
494 }
495
496 void Client::coreSocketError(QAbstractSocket::SocketError) {
497   emit coreConnectionError(socket->errorString());
498   socket->deleteLater();
499 }
500
501 void Client::coreHasData() {
502   QVariant item;
503   if(SignalProxy::readDataFromDevice(socket, blockSize, item)) {
504     emit recvPartialItem(1,1);
505     QVariantMap msg = item.toMap();
506     if (!msg["StartWizard"].toBool()) {
507       recvCoreState(msg["Reply"]);
508     } else {
509       qWarning("Core not configured!");
510       qDebug() << "Available storage providers: " << msg["StorageProviders"].toStringList();
511       emit showConfigWizard(msg);
512     }
513     blockSize = 0;
514     return;
515   }
516   if(blockSize > 0) {
517     emit recvPartialItem(socket->bytesAvailable(), blockSize);
518   }
519 }
520
521 void Client::networkConnected(uint netid) {
522   // TODO: create statusBuffer / switch to networkids
523   //BufferInfo id = statusBufferInfo(net);
524   //Buffer *b = buffer(id);
525   //b->setActive(true);
526
527   NetworkInfo *netinfo = new NetworkInfo(netid, this);
528   netinfo->setProxy(signalProxy());
529   networkModel()->attachNetworkInfo(netinfo);
530   
531   if(!isConnected()) {
532     connect(netinfo, SIGNAL(initDone()), this, SLOT(updateCoreConnectionProgress()));
533     connect(netinfo, SIGNAL(ircUserInitDone()), this, SLOT(updateCoreConnectionProgress()));
534     connect(netinfo, SIGNAL(ircChannelInitDone()), this, SLOT(updateCoreConnectionProgress()));
535   }
536   connect(netinfo, SIGNAL(ircChannelAdded(QString)), this, SLOT(ircChannelAdded(QString)));
537   connect(netinfo, SIGNAL(destroyed()), this, SLOT(networkInfoDestroyed()));
538   _networkInfo[netid] = netinfo;
539 }
540
541 void Client::networkDisconnected(uint networkid) {
542   foreach(Buffer *buffer, buffers()) {
543     if(buffer->bufferInfo().networkId() != networkid)
544       continue;
545
546     //buffer->displayMsg(Message(bufferid, Message::Server, tr("Server disconnected."))); FIXME
547     buffer->setActive(false);
548   }
549
550   Q_ASSERT(networkInfo(networkid));
551   if(!networkInfo(networkid)->initialized()) {
552     qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
553     updateCoreConnectionProgress();
554   }
555 }
556
557 void Client::ircChannelAdded(QString chanName) {
558   NetworkInfo *netInfo = qobject_cast<NetworkInfo*>(sender());
559   Q_ASSERT(netInfo);
560   Buffer *buf = buffer(bufferInfo(netInfo->networkName(), chanName));
561   Q_ASSERT(buf);
562   buf->setIrcChannel(netInfo->ircChannel(chanName));
563
564 }
565
566 void Client::updateBufferInfo(BufferInfo id) {
567   buffer(id)->updateBufferInfo(id);
568 }
569
570 void Client::bufferDestroyed() {
571   Buffer *buffer = static_cast<Buffer *>(sender());
572   uint bufferUid = buffer->uid();
573   if(_buffers.contains(bufferUid))
574     _buffers.remove(bufferUid);
575 }
576
577 void Client::networkInfoDestroyed() {
578   NetworkInfo *netinfo = static_cast<NetworkInfo *>(sender());
579   uint networkId = netinfo->networkId();
580   if(_networkInfo.contains(networkId))
581     _networkInfo.remove(networkId);
582 }
583
584 void Client::recvMessage(const Message &msg) {
585   Buffer *b = buffer(msg.buffer());
586
587   Buffer::ActivityLevel level = Buffer::OtherActivity;
588   if(msg.type() == Message::Plain || msg.type() == Message::Notice){
589     level |= Buffer::NewMessage;
590   }
591   if(msg.flags() & Message::Highlight){
592     level |= Buffer::Highlight;
593   }
594   emit bufferActivity(level, b);
595
596   b->appendMsg(msg);
597 }
598
599 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
600   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
601 }
602
603 void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
604   Buffer *b = buffer(id);
605   foreach(QVariant v, msgs) {
606     Message msg = v.value<Message>();
607     b->prependMsg(msg);
608     if(!layoutQueue.contains(b)) layoutQueue.append(b);
609   }
610   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
611 }
612
613 void Client::layoutMsg() {
614   if(layoutQueue.count()) {
615     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
616     if(b->layoutMsg())
617       layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
618   }
619   
620   if(!layoutQueue.count())
621     layoutTimer->stop();
622 }
623
624 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
625   return instance()->mainUi->layoutMsg(msg);
626 }
627
628 void Client::userInput(BufferInfo id, QString msg) {
629   emit sendInput(id, msg);
630 }
631