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"
29 Client * Client::instanceptr = 0;
31 bool Client::connectedToCore = false;
32 Client::ClientMode Client::clientMode;
33 VarMap Client::coreConnectionInfo;
34 QHash<BufferId, Buffer *> Client::buffers;
35 QHash<uint, BufferId> Client::bufferIds;
36 QHash<QString, QHash<QString, VarMap> > Client::nicks;
37 QHash<QString, bool> Client::netConnected;
38 QStringList Client::netsAwaitingInit;
39 QHash<QString, QString> Client::ownNick;
41 Client *Client::instance() {
42 if(instanceptr) return instanceptr;
43 instanceptr = new Client();
47 void Client::destroy() {
53 clientProxy = ClientProxy::instance();
55 _bufferModel = new BufferTreeModel(this);
57 connect(this, SIGNAL(bufferSelected(Buffer *)), _bufferModel, SLOT(selectBuffer(Buffer *)));
58 connect(this, SIGNAL(bufferUpdated(Buffer *)), _bufferModel, SLOT(bufferUpdated(Buffer *)));
59 connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)), _bufferModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
61 // TODO: make this configurable (allow monolithic client to connect to remote cores)
62 if(Global::runMode == Global::Monolithic) clientMode = LocalCore;
63 else clientMode = RemoteCore;
64 connectedToCore = false;
67 void Client::init(AbstractUi *ui) {
68 instance()->mainUi = ui;
75 connect(&socket, SIGNAL(readyRead()), this, SLOT(serverHasData()));
76 connect(&socket, SIGNAL(connected()), this, SLOT(coreConnected()));
77 connect(&socket, SIGNAL(disconnected()), this, SLOT(coreDisconnected()));
78 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(serverError(QAbstractSocket::SocketError)));
80 connect(Global::instance(), SIGNAL(dataPutLocally(UserId, QString)), this, SLOT(updateCoreData(UserId, QString)));
81 connect(clientProxy, SIGNAL(csUpdateGlobalData(QString, QVariant)), this, SLOT(updateLocalData(QString, QVariant)));
82 connect(this, SIGNAL(sendSessionData(const QString &, const QVariant &)), clientProxy, SLOT(gsSessionDataChanged(const QString &, const QVariant &)));
83 connect(clientProxy, SIGNAL(csSessionDataChanged(const QString &, const QVariant &)), this, SLOT(recvSessionData(const QString &, const QVariant &)));
85 connect(clientProxy, SIGNAL(send(ClientSignal, QVariant, QVariant, QVariant)), this, SLOT(recvProxySignal(ClientSignal, QVariant, QVariant, QVariant)));
86 connect(clientProxy, SIGNAL(csServerState(QString, QVariant)), this, SLOT(recvNetworkState(QString, QVariant)));
87 connect(clientProxy, SIGNAL(csServerConnected(QString)), this, SLOT(networkConnected(QString)));
88 connect(clientProxy, SIGNAL(csServerDisconnected(QString)), this, SLOT(networkDisconnected(QString)));
89 connect(clientProxy, SIGNAL(csDisplayMsg(Message)), this, SLOT(recvMessage(const Message &)));
90 connect(clientProxy, SIGNAL(csDisplayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
91 connect(clientProxy, SIGNAL(csTopicSet(QString, QString, QString)), this, SLOT(setTopic(QString, QString, QString)));
92 connect(clientProxy, SIGNAL(csNickAdded(QString, QString, VarMap)), this, SLOT(addNick(QString, QString, VarMap)));
93 connect(clientProxy, SIGNAL(csNickRemoved(QString, QString)), this, SLOT(removeNick(QString, QString)));
94 connect(clientProxy, SIGNAL(csNickRenamed(QString, QString, QString)), this, SLOT(renameNick(QString, QString, QString)));
95 connect(clientProxy, SIGNAL(csNickUpdated(QString, QString, VarMap)), this, SLOT(updateNick(QString, QString, VarMap)));
96 connect(clientProxy, SIGNAL(csOwnNickSet(QString, QString)), this, SLOT(setOwnNick(QString, QString)));
97 connect(clientProxy, SIGNAL(csBacklogData(BufferId, const QList<QVariant> &, bool)), this, SLOT(recvBacklogData(BufferId, QList<QVariant>, bool)));
98 connect(clientProxy, SIGNAL(csUpdateBufferId(BufferId)), this, SLOT(updateBufferId(BufferId)));
99 connect(this, SIGNAL(sendInput(BufferId, QString)), clientProxy, SLOT(gsUserInput(BufferId, QString)));
100 connect(this, SIGNAL(requestBacklog(BufferId, QVariant, QVariant)), clientProxy, SLOT(gsRequestBacklog(BufferId, QVariant, QVariant)));
101 connect(this, SIGNAL(requestNetworkStates()), clientProxy, SLOT(gsRequestNetworkStates()));
103 connect(mainUi, SIGNAL(connectToCore(const VarMap &)), this, SLOT(connectToCore(const VarMap &)));
104 connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
105 connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
106 connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
108 layoutTimer = new QTimer(this);
109 layoutTimer->setInterval(0);
110 layoutTimer->setSingleShot(false);
111 connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
117 //delete _bufferModel;
118 foreach(Buffer *buf, buffers.values()) delete buf;
119 ClientProxy::destroy();
123 BufferTreeModel *Client::bufferModel() {
124 return instance()->_bufferModel;
127 bool Client::isConnected() { return connectedToCore; }
129 void Client::connectToCore(const VarMap &conn) {
130 // TODO implement SSL
131 coreConnectionInfo = conn;
133 emit coreConnectionError(tr("Already connected to Core!"));
136 if(conn["Host"].toString().isEmpty()) {
137 clientMode = LocalCore;
140 clientMode = RemoteCore;
141 emit coreConnectionMsg(tr("Connecting..."));
142 socket.connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
146 void Client::disconnectFromCore() {
147 if(clientMode == RemoteCore) {
150 disconnectFromLocalCore();
153 /* Clear internal data. Hopefully nothing relies on it at this point. */
154 coreConnectionInfo.clear();
156 //foreach(Buffer *buf, buffers.values()) delete buf;
157 qDebug() << "barfoo";
158 _bufferModel->clear();
159 //qDeleteAll(buffers);
160 qDebug() << "foobar";
163 void Client::coreConnected() {
168 void Client::coreDisconnected() {
169 connectedToCore = false;
173 void Client::syncToCore() {
175 if(clientMode == LocalCore) {
176 state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString()).toMap();
178 // TODO connect to remote cores
181 VarMap data = state["CoreData"].toMap();
182 foreach(QString key, data.keys()) {
183 Global::updateData(key, data[key]);
185 //if(!Global::data("CoreReady").toBool()) {
186 // qFatal("Something is wrong, getting invalid data from core!");
189 VarMap sessionState = state["SessionState"].toMap();
190 VarMap sessData = sessionState["SessionData"].toMap();
191 foreach(QString key, sessData.keys()) {
192 recvSessionData(key, sessData[key]);
194 QList<QVariant> coreBuffers = sessionState["Buffers"].toList();
195 /* make lookups by id faster */
196 foreach(QVariant vid, coreBuffers) {
197 BufferId id = vid.value<BufferId>();
198 bufferIds[id.uid()] = id; // make lookups by id faster
199 buffer(id); // create all buffers, so we see them in the network views
201 netsAwaitingInit = sessionState["Networks"].toStringList();
202 connectedToCore = true;
203 if(netsAwaitingInit.count()) {
204 emit coreConnectionMsg(tr("Requesting network states..."));
205 emit coreConnectionProgress(0, netsAwaitingInit.count());
206 emit requestNetworkStates();
209 emit coreConnectionProgress(1, 1);
214 void Client::updateCoreData(UserId, QString key) {
215 if(clientMode == LocalCore) return;
216 QVariant data = Global::data(key);
217 recvProxySignal(GS_UPDATE_GLOBAL_DATA, key, data, QVariant());
220 void Client::updateLocalData(QString key, QVariant data) {
221 Global::updateData(key, data);
224 void Client::recvSessionData(const QString &key, const QVariant &data) {
225 sessionData[key] = data;
226 emit sessionDataChanged(key, data);
227 emit sessionDataChanged(key);
230 void Client::storeSessionData(const QString &key, const QVariant &data) {
231 // Not sure if this is a good idea, but we'll try it anyway:
232 // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
233 // rather than immediately.
234 emit instance()->sendSessionData(key, data);
237 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
238 if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
242 QStringList Client::sessionDataKeys() {
243 return instance()->sessionData.keys();
246 void Client::recvProxySignal(ClientSignal sig, QVariant arg1, QVariant arg2, QVariant arg3) {
247 if(clientMode == LocalCore) return;
248 QList<QVariant> sigdata;
249 sigdata.append(sig); sigdata.append(arg1); sigdata.append(arg2); sigdata.append(arg3);
250 //qDebug() << "Sending signal: " << sigdata;
251 writeDataToDevice(&socket, QVariant(sigdata));
254 void Client::serverError(QAbstractSocket::SocketError) {
255 emit coreConnectionError(socket.errorString());
258 void Client::serverHasData() {
260 while(readDataFromDevice(&socket, blockSize, item)) {
261 emit recvPartialItem(1,1);
262 QList<QVariant> sigdata = item.toList();
263 Q_ASSERT(sigdata.size() == 4);
264 ClientProxy::instance()->recv((CoreSignal)sigdata[0].toInt(), sigdata[1], sigdata[2], sigdata[3]);
268 emit recvPartialItem(socket.bytesAvailable(), blockSize);
272 void Client::networkConnected(QString net) {
273 Q_ASSERT(!netsAwaitingInit.contains(net));
274 netConnected[net] = true;
275 BufferId id = statusBufferId(net);
276 Buffer *b = buffer(id);
278 //b->displayMsg(Message(id, Message::Server, tr("Connected.")));
279 // TODO buffersUpdated();
282 void Client::networkDisconnected(QString net) {
283 foreach(BufferId id, buffers.keys()) {
284 if(id.network() != net) continue;
285 Buffer *b = buffer(id);
286 //b->displayMsg(Message(id, Message::Server, tr("Server disconnected."))); FIXME
289 netConnected[net] = false;
290 if(netsAwaitingInit.contains(net)) {
291 qDebug() << "Network" << net << "disconnected while not yet initialized!";
292 netsAwaitingInit.removeAll(net);
293 emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
294 if(!netsAwaitingInit.count()) emit connected();
298 void Client::updateBufferId(BufferId id) {
299 bufferIds[id.uid()] = id; // make lookups by id faster
303 BufferId Client::bufferId(QString net, QString buf) {
304 foreach(BufferId id, buffers.keys()) {
305 if(id.network() == net && id.buffer() == buf) return id;
307 Q_ASSERT(false); // should never happen!
311 BufferId Client::statusBufferId(QString net) {
312 return bufferId(net, "");
316 Buffer * Client::buffer(BufferId id) {
317 Client *client = Client::instance();
318 if(!buffers.contains(id)) {
319 Buffer *b = new Buffer(id);
320 b->setOwnNick(ownNick[id.network()]);
321 connect(b, SIGNAL(userInput(BufferId, QString)), client, SLOT(userInput(BufferId, QString)));
322 connect(b, SIGNAL(bufferUpdated(Buffer *)), client, SIGNAL(bufferUpdated(Buffer *)));
323 connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SIGNAL(bufferDestroyed(Buffer *)));
325 emit client->bufferUpdated(b);
330 QList<BufferId> Client::allBufferIds() {
331 return buffers.keys();
334 void Client::recvNetworkState(QString net, QVariant state) {
335 netsAwaitingInit.removeAll(net);
336 netConnected[net] = true;
337 setOwnNick(net, state.toMap()["OwnNick"].toString());
338 buffer(statusBufferId(net))->setActive(true);
339 VarMap t = state.toMap()["Topics"].toMap();
340 VarMap n = state.toMap()["Nicks"].toMap();
341 foreach(QVariant v, t.keys()) {
342 QString buf = v.toString();
343 BufferId id = bufferId(net, buf);
344 buffer(id)->setActive(true);
345 setTopic(net, buf, t[buf].toString());
347 foreach(QString nick, n.keys()) {
348 addNick(net, nick, n[nick].toMap());
350 emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
351 if(!netsAwaitingInit.count()) emit connected();
354 void Client::recvMessage(const Message &msg) {
355 Buffer *b = buffer(msg.buffer);
357 Buffer::ActivityLevel level = Buffer::OtherActivity;
358 if(msg.type == Message::Plain || msg.type == Message::Notice){
359 level |= Buffer::NewMessage;
361 if(msg.flags & Message::Highlight){
362 level |= Buffer::Highlight;
364 emit bufferActivity(level, b);
369 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
370 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
374 void Client::recvBacklogData(BufferId id, const QList<QVariant> &msgs, bool /*done*/) {
375 Buffer *b = buffer(id);
376 foreach(QVariant v, msgs) {
377 Message msg = v.value<Message>();
379 if(!layoutQueue.contains(b)) layoutQueue.append(b);
381 if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
384 void Client::layoutMsg() {
385 if(layoutQueue.count()) {
386 Buffer *b = layoutQueue.takeFirst(); // TODO make this the current buffer
387 if(b->layoutMsg()) layoutQueue.append(b); // Buffer has more messages in its queue --> Round Robin
389 if(!layoutQueue.count()) layoutTimer->stop();
392 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
393 return instance()->mainUi->layoutMsg(msg);
396 void Client::userInput(BufferId id, QString msg) {
397 emit sendInput(id, msg);
400 void Client::setTopic(QString net, QString buf, QString topic) {
401 BufferId id = bufferId(net, buf);
402 if(!netConnected[id.network()]) return;
403 Buffer *b = buffer(id);
405 //if(!b->isActive()) {
406 // b->setActive(true);
411 void Client::addNick(QString net, QString nick, VarMap props) {
412 if(!netConnected[net]) return;
413 nicks[net][nick] = props;
414 VarMap chans = props["Channels"].toMap();
415 QStringList c = chans.keys();
416 foreach(QString bufname, c) {
417 buffer(bufferId(net, bufname))->addNick(nick, props);
421 void Client::renameNick(QString net, QString oldnick, QString newnick) {
422 if(!netConnected[net]) return;
423 QStringList chans = nicks[net][oldnick]["Channels"].toMap().keys();
424 foreach(QString c, chans) {
425 buffer(bufferId(net, c))->renameNick(oldnick, newnick);
427 nicks[net][newnick] = nicks[net].take(oldnick);
430 void Client::updateNick(QString net, QString nick, VarMap props) {
431 if(!netConnected[net]) return;
432 QStringList oldchans = nicks[net][nick]["Channels"].toMap().keys();
433 QStringList newchans = props["Channels"].toMap().keys();
434 foreach(QString c, newchans) {
435 if(oldchans.contains(c)) buffer(bufferId(net, c))->updateNick(nick, props);
436 else buffer(bufferId(net, c))->addNick(nick, props);
438 foreach(QString c, oldchans) {
439 if(!newchans.contains(c)) buffer(bufferId(net, c))->removeNick(nick);
441 nicks[net][nick] = props;
444 void Client::removeNick(QString net, QString nick) {
445 if(!netConnected[net]) return;
446 VarMap chans = nicks[net][nick]["Channels"].toMap();
447 foreach(QString bufname, chans.keys()) {
448 buffer(bufferId(net, bufname))->removeNick(nick);
450 nicks[net].remove(nick);
453 void Client::setOwnNick(QString net, QString nick) {
454 if(!netConnected[net]) return;
456 foreach(BufferId id, buffers.keys()) {
457 if(id.network() == net) {
458 buffers[id]->setOwnNick(nick);