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(coreSocketConnected()));
77 connect(&socket, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
78 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(serverError(QAbstractSocket::SocketError)));
80 connect(this, SIGNAL(sendSessionData(const QString &, const QVariant &)), clientProxy, SLOT(gsSessionDataChanged(const QString &, const QVariant &)));
81 connect(clientProxy, SIGNAL(csSessionDataChanged(const QString &, const QVariant &)), this, SLOT(recvSessionData(const QString &, const QVariant &)));
83 connect(clientProxy, SIGNAL(send(ClientSignal, QVariant, QVariant, QVariant)), this, SLOT(recvProxySignal(ClientSignal, QVariant, QVariant, QVariant)));
84 connect(clientProxy, SIGNAL(csCoreState(QVariant)), this, SLOT(recvCoreState(const QVariant &)));
85 connect(clientProxy, SIGNAL(csServerState(QString, QVariant)), this, SLOT(recvNetworkState(QString, QVariant)));
86 connect(clientProxy, SIGNAL(csServerConnected(QString)), this, SLOT(networkConnected(QString)));
87 connect(clientProxy, SIGNAL(csServerDisconnected(QString)), this, SLOT(networkDisconnected(QString)));
88 connect(clientProxy, SIGNAL(csDisplayMsg(Message)), this, SLOT(recvMessage(const Message &)));
89 connect(clientProxy, SIGNAL(csDisplayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
90 connect(clientProxy, SIGNAL(csTopicSet(QString, QString, QString)), this, SLOT(setTopic(QString, QString, QString)));
91 connect(clientProxy, SIGNAL(csNickAdded(QString, QString, VarMap)), this, SLOT(addNick(QString, QString, VarMap)));
92 connect(clientProxy, SIGNAL(csNickRemoved(QString, QString)), this, SLOT(removeNick(QString, QString)));
93 connect(clientProxy, SIGNAL(csNickRenamed(QString, QString, QString)), this, SLOT(renameNick(QString, QString, QString)));
94 connect(clientProxy, SIGNAL(csNickUpdated(QString, QString, VarMap)), this, SLOT(updateNick(QString, QString, VarMap)));
95 connect(clientProxy, SIGNAL(csOwnNickSet(QString, QString)), this, SLOT(setOwnNick(QString, QString)));
96 connect(clientProxy, SIGNAL(csBacklogData(BufferId, const QList<QVariant> &, bool)), this, SLOT(recvBacklogData(BufferId, QList<QVariant>, bool)));
97 connect(clientProxy, SIGNAL(csUpdateBufferId(BufferId)), this, SLOT(updateBufferId(BufferId)));
98 connect(this, SIGNAL(sendInput(BufferId, QString)), clientProxy, SLOT(gsUserInput(BufferId, QString)));
99 connect(this, SIGNAL(requestBacklog(BufferId, QVariant, QVariant)), clientProxy, SLOT(gsRequestBacklog(BufferId, QVariant, QVariant)));
100 connect(this, SIGNAL(requestNetworkStates()), clientProxy, SLOT(gsRequestNetworkStates()));
102 connect(mainUi, SIGNAL(connectToCore(const VarMap &)), this, SLOT(connectToCore(const VarMap &)));
103 connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
104 connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
105 connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
107 layoutTimer = new QTimer(this);
108 layoutTimer->setInterval(0);
109 layoutTimer->setSingleShot(false);
110 connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
116 //delete _bufferModel;
117 foreach(Buffer *buf, buffers.values()) delete buf;
118 ClientProxy::destroy();
122 BufferTreeModel *Client::bufferModel() {
123 return instance()->_bufferModel;
126 bool Client::isConnected() { return connectedToCore; }
128 void Client::connectToCore(const VarMap &conn) {
129 // TODO implement SSL
130 coreConnectionInfo = conn;
132 emit coreConnectionError(tr("Already connected to Core!"));
135 if(conn["Host"].toString().isEmpty()) {
136 clientMode = LocalCore;
137 QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
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();
151 coreSocketDisconnected();
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::coreSocketConnected() {
164 connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
165 emit coreConnectionMsg(tr("Synchronizing to core..."));
167 clientInit["GuiProtocol"] = GUI_PROTOCOL;
168 clientInit["User"] = coreConnectionInfo["User"].toString();
169 clientInit["Password"] = coreConnectionInfo["Password"].toString();
170 writeDataToDevice(&socket, clientInit);
173 void Client::coreSocketDisconnected() {
174 connectedToCore = false;
178 void Client::recvCoreState(const QVariant &state) {
179 disconnect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
184 void Client::syncToCore(const QVariant &coreState) {
185 VarMap sessionState = coreState.toMap()["SessionState"].toMap();
186 VarMap sessData = sessionState["SessionData"].toMap();
188 foreach(QString key, sessData.keys()) {
189 recvSessionData(key, sessData[key]);
191 QList<QVariant> coreBuffers = sessionState["Buffers"].toList();
192 /* make lookups by id faster */
193 foreach(QVariant vid, coreBuffers) {
194 BufferId id = vid.value<BufferId>();
195 bufferIds[id.uid()] = id; // make lookups by id faster
196 buffer(id); // create all buffers, so we see them in the network views
198 netsAwaitingInit = sessionState["Networks"].toStringList();
199 connectedToCore = true;
200 if(netsAwaitingInit.count()) {
201 emit coreConnectionMsg(tr("Requesting network states..."));
202 emit coreConnectionProgress(0, netsAwaitingInit.count());
203 emit requestNetworkStates();
206 emit coreConnectionProgress(1, 1);
211 void Client::recvSessionData(const QString &key, const QVariant &data) {
212 sessionData[key] = data;
213 emit sessionDataChanged(key, data);
214 emit sessionDataChanged(key);
217 void Client::storeSessionData(const QString &key, const QVariant &data) {
218 // Not sure if this is a good idea, but we'll try it anyway:
219 // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
220 // rather than immediately.
221 emit instance()->sendSessionData(key, data);
224 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
225 if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
229 QStringList Client::sessionDataKeys() {
230 return instance()->sessionData.keys();
233 void Client::recvProxySignal(ClientSignal sig, QVariant arg1, QVariant arg2, QVariant arg3) {
234 if(clientMode == LocalCore) return;
235 QList<QVariant> sigdata;
236 sigdata.append(sig); sigdata.append(arg1); sigdata.append(arg2); sigdata.append(arg3);
237 //qDebug() << "Sending signal: " << sigdata;
238 writeDataToDevice(&socket, QVariant(sigdata));
241 void Client::serverError(QAbstractSocket::SocketError) {
242 emit coreConnectionError(socket.errorString());
245 void Client::serverHasData() {
247 while(readDataFromDevice(&socket, blockSize, item)) {
248 emit recvPartialItem(1,1);
249 QList<QVariant> sigdata = item.toList();
250 Q_ASSERT(sigdata.size() == 4);
251 ClientProxy::instance()->recv((CoreSignal)sigdata[0].toInt(), sigdata[1], sigdata[2], sigdata[3]);
255 emit recvPartialItem(socket.bytesAvailable(), blockSize);
259 void Client::networkConnected(QString net) {
260 Q_ASSERT(!netsAwaitingInit.contains(net));
261 netConnected[net] = true;
262 BufferId id = statusBufferId(net);
263 Buffer *b = buffer(id);
265 //b->displayMsg(Message(id, Message::Server, tr("Connected.")));
266 // TODO buffersUpdated();
269 void Client::networkDisconnected(QString net) {
270 foreach(BufferId id, buffers.keys()) {
271 if(id.network() != net) continue;
272 Buffer *b = buffer(id);
273 //b->displayMsg(Message(id, Message::Server, tr("Server disconnected."))); FIXME
276 netConnected[net] = false;
277 if(netsAwaitingInit.contains(net)) {
278 qDebug() << "Network" << net << "disconnected while not yet initialized!";
279 netsAwaitingInit.removeAll(net);
280 emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
281 if(!netsAwaitingInit.count()) emit connected();
285 void Client::updateBufferId(BufferId id) {
286 bufferIds[id.uid()] = id; // make lookups by id faster
290 BufferId Client::bufferId(QString net, QString buf) {
291 foreach(BufferId id, buffers.keys()) {
292 if(id.network() == net && id.buffer() == buf) return id;
294 Q_ASSERT(false); // should never happen!
298 BufferId Client::statusBufferId(QString net) {
299 return bufferId(net, "");
303 Buffer * Client::buffer(BufferId id) {
304 Client *client = Client::instance();
305 if(!buffers.contains(id)) {
306 Buffer *b = new Buffer(id);
307 b->setOwnNick(ownNick[id.network()]);
308 connect(b, SIGNAL(userInput(BufferId, QString)), client, SLOT(userInput(BufferId, QString)));
309 connect(b, SIGNAL(bufferUpdated(Buffer *)), client, SIGNAL(bufferUpdated(Buffer *)));
310 connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SIGNAL(bufferDestroyed(Buffer *)));
312 emit client->bufferUpdated(b);
317 QList<BufferId> Client::allBufferIds() {
318 return buffers.keys();
321 void Client::recvNetworkState(QString net, QVariant state) {
322 netsAwaitingInit.removeAll(net);
323 netConnected[net] = true;
324 setOwnNick(net, state.toMap()["OwnNick"].toString());
325 buffer(statusBufferId(net))->setActive(true);
326 VarMap t = state.toMap()["Topics"].toMap();
327 VarMap n = state.toMap()["Nicks"].toMap();
328 foreach(QVariant v, t.keys()) {
329 QString buf = v.toString();
330 BufferId id = bufferId(net, buf);
331 buffer(id)->setActive(true);
332 setTopic(net, buf, t[buf].toString());
334 foreach(QString nick, n.keys()) {
335 addNick(net, nick, n[nick].toMap());
337 emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
338 if(!netsAwaitingInit.count()) emit connected();
341 void Client::recvMessage(const Message &msg) {
342 Buffer *b = buffer(msg.buffer);
344 Buffer::ActivityLevel level = Buffer::OtherActivity;
345 if(msg.type == Message::Plain || msg.type == Message::Notice){
346 level |= Buffer::NewMessage;
348 if(msg.flags & Message::Highlight){
349 level |= Buffer::Highlight;
351 emit bufferActivity(level, b);
356 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
357 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
361 void Client::recvBacklogData(BufferId id, const QList<QVariant> &msgs, bool /*done*/) {
362 Buffer *b = buffer(id);
363 foreach(QVariant v, msgs) {
364 Message msg = v.value<Message>();
366 if(!layoutQueue.contains(b)) layoutQueue.append(b);
368 if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
371 void Client::layoutMsg() {
372 if(layoutQueue.count()) {
373 Buffer *b = layoutQueue.takeFirst(); // TODO make this the current buffer
374 if(b->layoutMsg()) layoutQueue.append(b); // Buffer has more messages in its queue --> Round Robin
376 if(!layoutQueue.count()) layoutTimer->stop();
379 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
380 return instance()->mainUi->layoutMsg(msg);
383 void Client::userInput(BufferId id, QString msg) {
384 emit sendInput(id, msg);
387 void Client::setTopic(QString net, QString buf, QString topic) {
388 BufferId id = bufferId(net, buf);
389 if(!netConnected[id.network()]) return;
390 Buffer *b = buffer(id);
392 //if(!b->isActive()) {
393 // b->setActive(true);
398 void Client::addNick(QString net, QString nick, VarMap props) {
399 if(!netConnected[net]) return;
400 nicks[net][nick] = props;
401 VarMap chans = props["Channels"].toMap();
402 QStringList c = chans.keys();
403 foreach(QString bufname, c) {
404 buffer(bufferId(net, bufname))->addNick(nick, props);
408 void Client::renameNick(QString net, QString oldnick, QString newnick) {
409 if(!netConnected[net]) return;
410 QStringList chans = nicks[net][oldnick]["Channels"].toMap().keys();
411 foreach(QString c, chans) {
412 buffer(bufferId(net, c))->renameNick(oldnick, newnick);
414 nicks[net][newnick] = nicks[net].take(oldnick);
417 void Client::updateNick(QString net, QString nick, VarMap props) {
418 if(!netConnected[net]) return;
419 QStringList oldchans = nicks[net][nick]["Channels"].toMap().keys();
420 QStringList newchans = props["Channels"].toMap().keys();
421 foreach(QString c, newchans) {
422 if(oldchans.contains(c)) buffer(bufferId(net, c))->updateNick(nick, props);
423 else buffer(bufferId(net, c))->addNick(nick, props);
425 foreach(QString c, oldchans) {
426 if(!newchans.contains(c)) buffer(bufferId(net, c))->removeNick(nick);
428 nicks[net][nick] = props;
431 void Client::removeNick(QString net, QString nick) {
432 if(!netConnected[net]) return;
433 VarMap chans = nicks[net][nick]["Channels"].toMap();
434 foreach(QString bufname, chans.keys()) {
435 buffer(bufferId(net, bufname))->removeNick(nick);
437 nicks[net].remove(nick);
440 void Client::setOwnNick(QString net, QString nick) {
441 if(!netConnected[net]) return;
443 foreach(BufferId id, buffers.keys()) {
444 if(id.network() == net) {
445 buffers[id]->setOwnNick(nick);