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 ***************************************************************************/
24 #include "buffertreemodel.h"
25 //#include "clientproxy.h"
26 #include "quasselui.h"
27 #include "signalproxy.h"
30 Client * Client::instanceptr = 0;
32 bool Client::connectedToCore = false;
33 Client::ClientMode Client::clientMode;
34 QVariantMap Client::coreConnectionInfo;
35 QHash<BufferId, Buffer *> Client::buffers;
36 QHash<uint, BufferId> Client::bufferIds;
37 QHash<QString, QHash<QString, QVariantMap> > Client::nicks;
38 QHash<QString, bool> Client::netConnected;
39 QStringList Client::netsAwaitingInit;
40 QHash<QString, QString> Client::ownNick;
42 Client *Client::instance() {
43 if(instanceptr) return instanceptr;
44 instanceptr = new Client();
48 void Client::destroy() {
54 //clientProxy = ClientProxy::instance();
55 _signalProxy = new SignalProxy(SignalProxy::Client, 0, this);
57 // TODO: make this configurable (allow monolithic client to connect to remote cores)
58 //if(Global::runMode == Global::Monolithic) clientMode = LocalCore;
59 //else clientMode = RemoteCore;
60 connectedToCore = false;
64 void Client::init(AbstractUi *ui) {
65 instance()->mainUi = ui;
72 _bufferModel = new BufferTreeModel(this);
74 connect(this, SIGNAL(bufferSelected(Buffer *)), _bufferModel, SLOT(selectBuffer(Buffer *)));
75 connect(this, SIGNAL(bufferUpdated(Buffer *)), _bufferModel, SLOT(bufferUpdated(Buffer *)));
76 connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)), _bufferModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
78 //connect(&socket, SIGNAL(readyRead()), this, SLOT(serverHasData()));
79 //connect(&socket, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
80 //connect(&socket, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
81 //connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(serverError(QAbstractSocket::SocketError)));
83 //connect(this, SIGNAL(sendSessionData(const QString &, const QVariant &)), clientProxy, SLOT(gsSessionDataChanged(const QString &, const QVariant &)));
84 //connect(clientProxy, SIGNAL(csSessionDataChanged(const QString &, const QVariant &)), this, SLOT(recvSessionData(const QString &, const QVariant &)));
86 //connect(clientProxy, SIGNAL(send(ClientSignal, QVariant, QVariant, QVariant)), this, SLOT(recvProxySignal(ClientSignal, QVariant, QVariant, QVariant)));
87 //connect(clientProxy, SIGNAL(csCoreState(QVariant)), this, SLOT(recvCoreState(const QVariant &)));
88 //connect(clientProxy, SIGNAL(csServerState(QString, QVariant)), this, SLOT(recvNetworkState(QString, QVariant)));
89 //connect(clientProxy, SIGNAL(csServerConnected(QString)), this, SLOT(networkConnected(QString)));
90 //connect(clientProxy, SIGNAL(csServerDisconnected(QString)), this, SLOT(networkDisconnected(QString)));
91 //connect(clientProxy, SIGNAL(csDisplayMsg(Message)), this, SLOT(recvMessage(const Message &)));
92 //connect(clientProxy, SIGNAL(csDisplayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
93 //connect(clientProxy, SIGNAL(csTopicSet(QString, QString, QString)), this, SLOT(setTopic(QString, QString, QString)));
94 //connect(clientProxy, SIGNAL(csNickAdded(QString, QString, QVariantMap)), this, SLOT(addNick(QString, QString, QVariantMap)));
95 //connect(clientProxy, SIGNAL(csNickRemoved(QString, QString)), this, SLOT(removeNick(QString, QString)));
96 //connect(clientProxy, SIGNAL(csNickRenamed(QString, QString, QString)), this, SLOT(renameNick(QString, QString, QString)));
97 //connect(clientProxy, SIGNAL(csNickUpdated(QString, QString, QVariantMap)), this, SLOT(updateNick(QString, QString, QVariantMap)));
98 //connect(clientProxy, SIGNAL(csOwnNickSet(QString, QString)), this, SLOT(setOwnNick(QString, QString)));
99 //connect(clientProxy, SIGNAL(csBacklogData(BufferId, const QList<QVariant> &, bool)), this, SLOT(recvBacklogData(BufferId, QList<QVariant>, bool)));
100 //connect(clientProxy, SIGNAL(csUpdateBufferId(BufferId)), this, SLOT(updateBufferId(BufferId)));
101 //connect(this, SIGNAL(sendInput(BufferId, QString)), clientProxy, SLOT(gsUserInput(BufferId, QString)));
102 //connect(this, SIGNAL(requestBacklog(BufferId, QVariant, QVariant)), clientProxy, SLOT(gsRequestBacklog(BufferId, QVariant, QVariant)));
103 //connect(this, SIGNAL(requestNetworkStates()), clientProxy, SLOT(gsRequestNetworkStates()));
105 SignalProxy *p = signalProxy();
106 p->attachSignal(this, SIGNAL(sendSessionData(const QString &, const QVariant &)), SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)));
107 p->attachSlot(SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)), this, SLOT(recvSessionData(const QString &, const QVariant &)));
108 p->attachSlot(SIGNAL(coreState(const QVariant &)), this, SLOT(recvCoreState(const QVariant &)));
109 p->attachSlot(SIGNAL(networkState(QString, QVariant)), this, SLOT(recvNetworkState(QString, QVariant)));
110 p->attachSlot(SIGNAL(networkConnected(QString)), this, SLOT(networkConnected(QString)));
111 p->attachSlot(SIGNAL(networkDisconnected(QString)), this, SLOT(networkDisconnected(QString)));
112 p->attachSlot(SIGNAL(displayMsg(const Message &)), this, SLOT(recvMessage(const Message &)));
113 p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
114 p->attachSlot(SIGNAL(topicSet(QString, QString, QString)), this, SLOT(setTopic(QString, QString, QString)));
115 p->attachSlot(SIGNAL(nickAdded(QString, QString, QVariantMap)), this, SLOT(addNick(QString, QString, QVariantMap)));
116 p->attachSlot(SIGNAL(nickRemoved(QString, QString)), this, SLOT(removeNick(QString, QString)));
117 p->attachSlot(SIGNAL(nickRenamed(QString, QString, QString)), this, SLOT(renameNick(QString, QString, QString)));
118 p->attachSlot(SIGNAL(nickUpdated(QString, QString, QVariantMap)), this, SLOT(updateNick(QString, QString, QVariantMap)));
119 p->attachSlot(SIGNAL(ownNickSet(QString, QString)), this, SLOT(setOwnNick(QString, QString)));
120 p->attachSlot(SIGNAL(backlogData(BufferId, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferId, const QVariantList &, bool)));
121 p->attachSlot(SIGNAL(bufferIdUpdated(BufferId)), this, SLOT(updateBufferId(BufferId)));
122 p->attachSignal(this, SIGNAL(sendInput(BufferId, QString)));
123 //p->attachSignal(this, SIGNAL(requestBacklog(BufferId, QVariant, QVariant)), "requestBacklog");
124 p->attachSignal(this, SIGNAL(requestNetworkStates()));
126 connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
127 connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
128 connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
129 connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
131 layoutTimer = new QTimer(this);
132 layoutTimer->setInterval(0);
133 layoutTimer->setSingleShot(false);
134 connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
140 //delete _bufferModel;
141 foreach(Buffer *buf, buffers.values()) delete buf; // this is done by disconnectFromCore()! FIXME?
142 //ClientProxy::destroy();
143 Q_ASSERT(!buffers.count());
146 BufferTreeModel *Client::bufferModel() {
147 return instance()->_bufferModel;
150 SignalProxy *Client::signalProxy() {
151 return instance()->_signalProxy;
154 bool Client::isConnected() {
155 return connectedToCore;
158 void Client::connectToCore(const QVariantMap &conn) {
159 // TODO implement SSL
160 coreConnectionInfo = conn;
161 if(isConnected() || socket != 0) {
162 emit coreConnectionError(tr("Already connected to Core!"));
165 if(conn["Host"].toString().isEmpty()) {
166 clientMode = LocalCore;
167 socket = new QBuffer(this);
168 connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
169 socket->open(QIODevice::ReadWrite);
170 //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
172 coreSocketConnected();
174 clientMode = RemoteCore;
175 emit coreConnectionMsg(tr("Connecting..."));
177 QTcpSocket *sock = new QTcpSocket(this);
179 connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
180 connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
181 connect(sock, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
182 connect(signalProxy(), SIGNAL(peerDisconnected()), this, SLOT(coreSocketDisconnected()));
183 //connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(coreSocketStateChanged(QAbstractSocket::SocketState)));
184 connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
185 sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
189 void Client::disconnectFromCore() {
190 if(clientMode == RemoteCore) {
192 //QAbstractSocket *sock = qobject_cast<QAbstractSocket*>(socket);
194 //sock->disconnectFromHost();
197 //disconnectFromLocalCore();
198 coreSocketDisconnected();
202 void Client::coreSocketConnected() {
203 connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
204 emit coreConnectionMsg(tr("Synchronizing to core..."));
205 QVariantMap clientInit;
206 clientInit["GuiProtocol"] = GUI_PROTOCOL;
207 clientInit["User"] = coreConnectionInfo["User"].toString();
208 clientInit["Password"] = coreConnectionInfo["Password"].toString();
209 writeDataToDevice(socket, clientInit);
212 void Client::coreSocketDisconnected() {
213 connectedToCore = false;
215 socket->deleteLater();
217 /* Clear internal data. Hopefully nothing relies on it at this point. */
218 _bufferModel->clear();
219 // Buffers, if deleted, send a signal that causes their removal from buffers and bufferIds.
220 // So we cannot simply go through the array in a loop (or use qDeleteAll) for deletion...
221 while(buffers.count()) { delete buffers.take(buffers.keys()[0]); }
222 Q_ASSERT(!buffers.count()); // should be empty now!
223 Q_ASSERT(!bufferIds.count());
224 coreConnectionInfo.clear();
227 netConnected.clear();
228 netsAwaitingInit.clear();
234 void Client::coreSocketStateChanged(QAbstractSocket::SocketState state) { qDebug() << state;
235 if(state == QAbstractSocket::UnconnectedState) coreSocketDisconnected();
238 void Client::recvCoreState(const QVariant &state) {
239 disconnect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
240 disconnect(socket, 0, this, 0); // rest of communication happens through SignalProxy
241 signalProxy()->addPeer(socket);
245 void Client::syncToCore(const QVariant &coreState) {
246 if(!coreState.toMap().contains("SessionState")) {
247 emit coreConnectionError(tr("Invalid data received from core!"));
248 disconnectFromCore();
251 QVariantMap sessionState = coreState.toMap()["SessionState"].toMap();
252 QVariantMap sessData = sessionState["SessionData"].toMap();
254 foreach(QString key, sessData.keys()) {
255 recvSessionData(key, sessData[key]);
257 QList<QVariant> coreBuffers = sessionState["Buffers"].toList();
258 /* make lookups by id faster */
259 foreach(QVariant vid, coreBuffers) {
260 BufferId id = vid.value<BufferId>();
261 bufferIds[id.uid()] = id; // make lookups by id faster
262 buffer(id); // create all buffers, so we see them in the network views
264 netsAwaitingInit = sessionState["Networks"].toStringList();
265 connectedToCore = true;
266 if(netsAwaitingInit.count()) {
267 emit coreConnectionMsg(tr("Requesting network states..."));
268 emit coreConnectionProgress(0, netsAwaitingInit.count());
269 emit requestNetworkStates();
272 emit coreConnectionProgress(1, 1);
277 void Client::recvSessionData(const QString &key, const QVariant &data) {
278 sessionData[key] = data;
279 emit sessionDataChanged(key, data);
280 emit sessionDataChanged(key);
283 void Client::storeSessionData(const QString &key, const QVariant &data) {
284 // Not sure if this is a good idea, but we'll try it anyway:
285 // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
286 // rather than immediately.
287 emit instance()->sendSessionData(key, data);
290 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
291 if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
295 QStringList Client::sessionDataKeys() {
296 return instance()->sessionData.keys();
299 void Client::recvProxySignal(ClientSignal sig, QVariant arg1, QVariant arg2, QVariant arg3) {
300 if(clientMode == LocalCore) return;
301 QList<QVariant> sigdata;
302 sigdata.append(sig); sigdata.append(arg1); sigdata.append(arg2); sigdata.append(arg3);
303 //qDebug() << "Sending signal: " << sigdata;
304 writeDataToDevice(socket, QVariant(sigdata));
307 void Client::coreSocketError(QAbstractSocket::SocketError) {
308 emit coreConnectionError(socket->errorString());
311 void Client::coreHasData() {
313 if(readDataFromDevice(socket, blockSize, item)) {
314 emit recvPartialItem(1,1);
315 //QList<QVariant> sigdata = item.toList();
316 //Q_ASSERT(sigdata.size() == 4);
317 //ClientProxy::instance()->recv((CoreSignal)sigdata[0].toInt(), sigdata[1], sigdata[2], sigdata[3]);
323 emit recvPartialItem(socket->bytesAvailable(), blockSize);
327 void Client::networkConnected(QString net) {
328 Q_ASSERT(!netsAwaitingInit.contains(net));
329 netConnected[net] = true;
330 BufferId id = statusBufferId(net);
331 Buffer *b = buffer(id);
333 //b->displayMsg(Message(id, Message::Server, tr("Connected.")));
334 // TODO buffersUpdated();
337 void Client::networkDisconnected(QString net) {
338 foreach(BufferId id, buffers.keys()) {
339 if(id.network() != net) continue;
340 Buffer *b = buffer(id);
341 //b->displayMsg(Message(id, Message::Server, tr("Server disconnected."))); FIXME
344 netConnected[net] = false;
345 if(netsAwaitingInit.contains(net)) {
346 qDebug() << "Network" << net << "disconnected while not yet initialized!";
347 netsAwaitingInit.removeAll(net);
348 emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
349 if(!netsAwaitingInit.count()) emit connected();
353 void Client::updateBufferId(BufferId id) {
354 bufferIds[id.uid()] = id; // make lookups by id faster
358 BufferId Client::bufferId(QString net, QString buf) {
359 foreach(BufferId id, buffers.keys()) {
360 if(id.network() == net && id.buffer() == buf) return id;
362 Q_ASSERT(false); // should never happen!
366 BufferId Client::statusBufferId(QString net) {
367 return bufferId(net, "");
371 Buffer * Client::buffer(BufferId id) {
372 Client *client = Client::instance();
373 if(!buffers.contains(id)) {
374 Buffer *b = new Buffer(id);
375 b->setOwnNick(ownNick[id.network()]);
376 connect(b, SIGNAL(userInput(BufferId, QString)), client, SLOT(userInput(BufferId, QString)));
377 connect(b, SIGNAL(bufferUpdated(Buffer *)), client, SIGNAL(bufferUpdated(Buffer *)));
378 connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SIGNAL(bufferDestroyed(Buffer *)));
379 connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SLOT(removeBuffer(Buffer *)));
381 emit client->bufferUpdated(b);
386 QList<BufferId> Client::allBufferIds() {
387 return buffers.keys();
390 void Client::removeBuffer(Buffer *b) {
391 buffers.remove(b->bufferId());
392 bufferIds.remove(b->bufferId().uid());
395 void Client::recvNetworkState(QString net, QVariant state) {
396 netsAwaitingInit.removeAll(net);
397 netConnected[net] = true;
398 setOwnNick(net, state.toMap()["OwnNick"].toString());
399 buffer(statusBufferId(net))->setActive(true);
400 QVariantMap t = state.toMap()["Topics"].toMap();
401 QVariantMap n = state.toMap()["Nicks"].toMap();
402 foreach(QVariant v, t.keys()) {
403 QString buf = v.toString();
404 BufferId id = bufferId(net, buf);
405 buffer(id)->setActive(true);
406 setTopic(net, buf, t[buf].toString());
408 foreach(QString nick, n.keys()) {
409 addNick(net, nick, n[nick].toMap());
411 emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
412 if(!netsAwaitingInit.count()) emit connected();
415 void Client::recvMessage(const Message &msg) {
416 Buffer *b = buffer(msg.buffer);
418 Buffer::ActivityLevel level = Buffer::OtherActivity;
419 if(msg.type == Message::Plain || msg.type == Message::Notice){
420 level |= Buffer::NewMessage;
422 if(msg.flags & Message::Highlight){
423 level |= Buffer::Highlight;
425 emit bufferActivity(level, b);
430 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
431 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
435 void Client::recvBacklogData(BufferId id, QVariantList msgs, bool /*done*/) {
436 Buffer *b = buffer(id);
437 foreach(QVariant v, msgs) {
438 Message msg = v.value<Message>();
440 if(!layoutQueue.contains(b)) layoutQueue.append(b);
442 if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
445 void Client::layoutMsg() {
446 if(layoutQueue.count()) {
447 Buffer *b = layoutQueue.takeFirst(); // TODO make this the current buffer
448 if(b->layoutMsg()) layoutQueue.append(b); // Buffer has more messages in its queue --> Round Robin
450 if(!layoutQueue.count()) layoutTimer->stop();
453 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
454 return instance()->mainUi->layoutMsg(msg);
457 void Client::userInput(BufferId id, QString msg) {
458 emit sendInput(id, msg);
461 void Client::setTopic(QString net, QString buf, QString topic) {
462 BufferId id = bufferId(net, buf);
463 if(!netConnected[id.network()]) return;
464 Buffer *b = buffer(id);
466 //if(!b->isActive()) {
467 // b->setActive(true);
472 void Client::addNick(QString net, QString nick, QVariantMap props) {
473 if(!netConnected[net]) return;
474 nicks[net][nick] = props;
475 QVariantMap chans = props["Channels"].toMap();
476 QStringList c = chans.keys();
477 foreach(QString bufname, c) {
478 buffer(bufferId(net, bufname))->addNick(nick, props);
482 void Client::renameNick(QString net, QString oldnick, QString newnick) {
483 if(!netConnected[net]) return;
484 QStringList chans = nicks[net][oldnick]["Channels"].toMap().keys();
485 foreach(QString c, chans) {
486 buffer(bufferId(net, c))->renameNick(oldnick, newnick);
488 nicks[net][newnick] = nicks[net].take(oldnick);
491 void Client::updateNick(QString net, QString nick, QVariantMap props) {
492 if(!netConnected[net]) return;
493 QStringList oldchans = nicks[net][nick]["Channels"].toMap().keys();
494 QStringList newchans = props["Channels"].toMap().keys();
495 foreach(QString c, newchans) {
496 if(oldchans.contains(c)) buffer(bufferId(net, c))->updateNick(nick, props);
497 else buffer(bufferId(net, c))->addNick(nick, props);
499 foreach(QString c, oldchans) {
500 if(!newchans.contains(c)) buffer(bufferId(net, c))->removeNick(nick);
502 nicks[net][nick] = props;
505 void Client::removeNick(QString net, QString nick) {
506 if(!netConnected[net]) return;
507 QVariantMap chans = nicks[net][nick]["Channels"].toMap();
508 foreach(QString bufname, chans.keys()) {
509 buffer(bufferId(net, bufname))->removeNick(nick);
511 nicks[net].remove(nick);
514 void Client::setOwnNick(QString net, QString nick) {
515 if(!netConnected[net]) return;
517 foreach(BufferId id, buffers.keys()) {
518 if(id.network() == net) {
519 buffers[id]->setOwnNick(nick);