1 /***************************************************************************
2 * Copyright (C) 2005-07 by The Quassel Team *
3 * devel@quassel-irc.org *
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) any later version. *
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. *
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 ***************************************************************************/
23 #include "networkinfo.h"
25 #include "ircchannel.h"
29 #include "bufferinfo.h"
30 #include "buffertreemodel.h"
31 #include "quasselui.h"
32 #include "signalproxy.h"
33 #include "synchronizer.h"
36 QPointer<Client> Client::instanceptr = 0;
38 // ==============================
39 // public Static Methods
40 // ==============================
41 Client *Client::instance() {
43 instanceptr = new Client();
47 void Client::destroy() {
51 void Client::init(AbstractUi *ui) {
52 instance()->mainUi = ui;
56 QList<NetworkInfo *> Client::networkInfos() {
57 return instance()->_networkInfo.values();
60 NetworkInfo *Client::networkInfo(uint networkid) {
61 if(instance()->_networkInfo.contains(networkid))
62 return instance()->_networkInfo[networkid];
67 QList<BufferInfo> Client::allBufferInfos() {
68 QList<BufferInfo> bufferids;
69 foreach(Buffer *buffer, buffers()) {
70 bufferids << buffer->bufferInfo();
75 QList<Buffer *> Client::buffers() {
76 return instance()->_buffers.values();
79 Buffer *Client::buffer(uint bufferUid) {
80 if(instance()->_buffers.contains(bufferUid))
81 return instance()->_buffers[bufferUid];
86 Buffer *Client::buffer(BufferInfo id) {
87 Buffer *buff = buffer(id.uid());
90 Client *client = Client::instance();
91 buff = new Buffer(id, client);
93 connect(buff, SIGNAL(userInput(BufferInfo, QString)),
94 client, SLOT(userInput(BufferInfo, QString)));
95 connect(buff, SIGNAL(bufferUpdated(Buffer *)),
96 client, SIGNAL(bufferUpdated(Buffer *)));
97 connect(buff, SIGNAL(bufferDestroyed(Buffer *)),
98 client, SIGNAL(bufferDestroyed(Buffer *)));
99 connect(buff, SIGNAL(bufferDestroyed(Buffer *)),
100 client, SLOT(removeBuffer(Buffer *)));
102 client->_buffers[id.uid()] = buff;
103 emit client->bufferUpdated(buff);
109 // FIXME switch to netids!
110 // WHEN IS THIS NEEDED ANYHOW!?
111 BufferInfo Client::bufferInfo(QString net, QString buf) {
112 foreach(Buffer *buffer_, buffers()) {
113 BufferInfo bufferInfo = buffer_->bufferInfo();
114 if(bufferInfo.network() == net && bufferInfo.buffer() == buf)
117 Q_ASSERT(false); // should never happen!
121 BufferInfo Client::statusBufferInfo(QString net) {
122 return bufferInfo(net, "");
125 BufferTreeModel *Client::bufferModel() {
126 return instance()->_bufferModel;
129 SignalProxy *Client::signalProxy() {
130 return instance()->_signalProxy;
133 // ==============================
134 // Constructor / Decon
135 // ==============================
136 Client::Client(QObject *parent)
139 _signalProxy(new SignalProxy(SignalProxy::Client, 0, this)),
142 connectedToCore(false)
149 void Client::init() {
152 _bufferModel = new BufferTreeModel(this);
154 connect(this, SIGNAL(bufferSelected(Buffer *)),
155 _bufferModel, SLOT(selectBuffer(Buffer *)));
156 connect(this, SIGNAL(bufferUpdated(Buffer *)),
157 _bufferModel, SLOT(bufferUpdated(Buffer *)));
158 connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)),
159 _bufferModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
161 SignalProxy *p = signalProxy();
162 p->attachSignal(this, SIGNAL(sendSessionData(const QString &, const QVariant &)),
163 SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)));
164 p->attachSlot(SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)),
165 this, SLOT(recvSessionData(const QString &, const QVariant &)));
166 p->attachSlot(SIGNAL(coreState(const QVariant &)),
167 this, SLOT(recvCoreState(const QVariant &)));
168 p->attachSlot(SIGNAL(networkConnected(uint)),
169 this, SLOT(networkConnected(uint)));
170 p->attachSlot(SIGNAL(networkDisconnected(uint)),
171 this, SLOT(networkDisconnected(uint)));
172 p->attachSlot(SIGNAL(displayMsg(const Message &)),
173 this, SLOT(recvMessage(const Message &)));
174 p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)),
175 this, SLOT(recvStatusMsg(QString, QString)));
178 p->attachSlot(SIGNAL(backlogData(BufferInfo, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferInfo, const QVariantList &, bool)));
179 p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), this, SLOT(updateBufferInfo(BufferInfo)));
180 p->attachSignal(this, SIGNAL(sendInput(BufferInfo, QString)));
181 p->attachSignal(this, SIGNAL(requestNetworkStates()));
183 connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
184 connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
185 connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
186 connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
188 layoutTimer = new QTimer(this);
189 layoutTimer->setInterval(0);
190 layoutTimer->setSingleShot(false);
191 connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
195 bool Client::isConnected() {
196 return instance()->connectedToCore;
199 void Client::connectToCore(const QVariantMap &conn) {
200 // TODO implement SSL
201 coreConnectionInfo = conn;
203 emit coreConnectionError(tr("Already connected to Core!"));
208 socket->deleteLater();
210 if(conn["Host"].toString().isEmpty()) {
211 clientMode = LocalCore;
212 socket = new QBuffer(this);
213 connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
214 socket->open(QIODevice::ReadWrite);
215 //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
217 coreSocketConnected();
219 clientMode = RemoteCore;
220 emit coreConnectionMsg(tr("Connecting..."));
222 QTcpSocket *sock = new QTcpSocket(this);
224 connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
225 connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
226 connect(sock, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
227 connect(signalProxy(), SIGNAL(peerDisconnected()), this, SLOT(coreSocketDisconnected()));
228 //connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(coreSocketStateChanged(QAbstractSocket::SocketState)));
229 connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
230 sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
234 void Client::disconnectFromCore() {
236 if(clientMode == LocalCore)
237 coreSocketDisconnected();
240 void Client::coreSocketConnected() {
241 connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
242 emit coreConnectionMsg(tr("Synchronizing to core..."));
243 QVariantMap clientInit;
244 clientInit["GuiProtocol"] = GUI_PROTOCOL;
245 clientInit["User"] = coreConnectionInfo["User"].toString();
246 clientInit["Password"] = coreConnectionInfo["Password"].toString();
247 writeDataToDevice(socket, clientInit);
250 void Client::coreSocketDisconnected() {
251 instance()->connectedToCore = false;
253 socket->deleteLater();
256 /* Clear internal data. Hopefully nothing relies on it at this point. */
257 _bufferModel->clear();
259 foreach(Buffer *buffer, _buffers.values()) {
262 Q_ASSERT(_buffers.empty());
264 foreach(NetworkInfo *networkinfo, _networkInfo.values()) {
267 Q_ASSERT(_networkInfo.empty());
269 coreConnectionInfo.clear();
275 void Client::coreSocketStateChanged(QAbstractSocket::SocketState state) {
276 if(state == QAbstractSocket::UnconnectedState) coreSocketDisconnected();
279 void Client::recvCoreState(const QVariant &state) {
280 disconnect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
281 disconnect(socket, 0, this, 0); // rest of communication happens through SignalProxy
282 signalProxy()->addPeer(socket);
287 void Client::syncToCore(const QVariant &coreState) {
288 if(!coreState.toMap().contains("SessionState")) {
289 emit coreConnectionError(tr("Invalid data received from core!"));
290 disconnectFromCore();
294 QVariantMap sessionState = coreState.toMap()["SessionState"].toMap();
297 QVariantMap sessData = sessionState["SessionData"].toMap();
298 foreach(QString key, sessData.keys())
299 recvSessionData(key, sessData[key]);
301 // store Buffer details
302 QVariantList coreBuffers = sessionState["Buffers"].toList();
303 /* make lookups by id faster */
304 foreach(QVariant vid, coreBuffers) {
305 buffer(vid.value<BufferInfo>()); // create all buffers, so we see them in the network views
308 // create networkInfo objects
309 QVariantList networkids = sessionState["Networks"].toList();
310 foreach(QVariant networkid, networkids) {
311 networkConnected(networkid.toUInt());
314 instance()->connectedToCore = true;
315 updateCoreConnectionProgress();
318 void Client::updateCoreConnectionProgress() {
319 // we'll do this in three steps:
324 int numNets = networkInfos().count();
325 int numNetsWaiting = 0;
328 int numIrcUsersWaiting = 0;
331 int numChannelsWaiting = 0;
333 foreach(NetworkInfo *net, networkInfos()) {
334 if(! net->initialized())
337 numIrcUsers += net->ircUsers().count();
338 foreach(IrcUser *user, net->ircUsers()) {
339 if(! user->initialized())
340 numIrcUsersWaiting++;
343 numChannels += net->ircChannels().count();
344 foreach(IrcChannel *channel, net->ircChannels()) {
345 if(! channel->initialized())
346 numChannelsWaiting++;
351 if(numNetsWaiting > 0) {
352 emit coreConnectionMsg(tr("Requesting network states..."));
353 emit coreConnectionProgress(numNets - numNetsWaiting, numNets);
357 if(numIrcUsersWaiting > 0) {
358 emit coreConnectionMsg(tr("Requesting User states..."));
359 emit coreConnectionProgress(numIrcUsers - numIrcUsersWaiting, numIrcUsers);
363 if(numChannelsWaiting > 0) {
364 emit coreConnectionMsg(tr("Requesting Channel states..."));
365 emit coreConnectionProgress(numChannels - numChannelsWaiting, numChannels);
369 emit coreConnectionProgress(1,1);
373 void Client::recvSessionData(const QString &key, const QVariant &data) {
374 sessionData[key] = data;
375 emit sessionDataChanged(key, data);
376 emit sessionDataChanged(key);
379 void Client::storeSessionData(const QString &key, const QVariant &data) {
380 // Not sure if this is a good idea, but we'll try it anyway:
381 // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
382 // rather than immediately.
383 emit instance()->sendSessionData(key, data);
386 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
387 if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
391 QStringList Client::sessionDataKeys() {
392 return instance()->sessionData.keys();
395 void Client::coreSocketError(QAbstractSocket::SocketError) {
396 emit coreConnectionError(socket->errorString());
397 socket->deleteLater();
400 void Client::coreHasData() {
402 if(readDataFromDevice(socket, blockSize, item)) {
403 emit recvPartialItem(1,1);
409 emit recvPartialItem(socket->bytesAvailable(), blockSize);
413 void Client::networkConnected(uint netid) {
414 // TODO: create statusBuffer / switch to networkids
415 //BufferInfo id = statusBufferInfo(net);
416 //Buffer *b = buffer(id);
417 //b->setActive(true);
419 NetworkInfo *netinfo = new NetworkInfo(netid, signalProxy(), this);
420 connect(netinfo, SIGNAL(initDone()), this, SLOT(updateCoreConnectionProgress()));
421 connect(netinfo, SIGNAL(ircUserInitDone()), this, SLOT(updateCoreConnectionProgress()));
422 connect(netinfo, SIGNAL(ircChannelInitDone()), this, SLOT(updateCoreConnectionProgress()));
423 _networkInfo[netid] = netinfo;
426 void Client::networkDisconnected(uint networkid) {
427 foreach(Buffer *buffer, buffers()) {
428 if(buffer->bufferInfo().networkId() != networkid)
431 //buffer->displayMsg(Message(bufferid, Message::Server, tr("Server disconnected."))); FIXME
432 buffer->setActive(false);
435 Q_ASSERT(networkInfo(networkid));
436 if(!networkInfo(networkid)->initialized()) {
437 qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
438 updateCoreConnectionProgress();
442 void Client::updateBufferInfo(BufferInfo id) {
443 buffer(id)->updateBufferInfo(id);
447 void Client::removeBuffer(Buffer *b) {
448 _buffers.remove(b->bufferInfo().uid());
451 void Client::recvMessage(const Message &msg) {
452 Buffer *b = buffer(msg.buffer());
454 Buffer::ActivityLevel level = Buffer::OtherActivity;
455 if(msg.type() == Message::Plain || msg.type() == Message::Notice){
456 level |= Buffer::NewMessage;
458 if(msg.flags() & Message::Highlight){
459 level |= Buffer::Highlight;
461 emit bufferActivity(level, b);
466 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
467 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
470 void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
471 Buffer *b = buffer(id);
472 foreach(QVariant v, msgs) {
473 Message msg = v.value<Message>();
475 if(!layoutQueue.contains(b)) layoutQueue.append(b);
477 if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
480 void Client::layoutMsg() {
481 if(layoutQueue.count()) {
482 Buffer *b = layoutQueue.takeFirst(); // TODO make this the current buffer
484 layoutQueue.append(b); // Buffer has more messages in its queue --> Round Robin
487 if(!layoutQueue.count())
491 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
492 return instance()->mainUi->layoutMsg(msg);
495 void Client::userInput(BufferInfo id, QString msg) {
496 emit sendInput(id, msg);