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(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(csServerState(QString, QVariant)), this, SLOT(recvNetworkState(QString, QVariant)));
85 connect(clientProxy, SIGNAL(csServerConnected(QString)), this, SLOT(networkConnected(QString)));
86 connect(clientProxy, SIGNAL(csServerDisconnected(QString)), this, SLOT(networkDisconnected(QString)));
87 connect(clientProxy, SIGNAL(csDisplayMsg(Message)), this, SLOT(recvMessage(const Message &)));
88 connect(clientProxy, SIGNAL(csDisplayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
89 connect(clientProxy, SIGNAL(csTopicSet(QString, QString, QString)), this, SLOT(setTopic(QString, QString, QString)));
90 connect(clientProxy, SIGNAL(csNickAdded(QString, QString, VarMap)), this, SLOT(addNick(QString, QString, VarMap)));
91 connect(clientProxy, SIGNAL(csNickRemoved(QString, QString)), this, SLOT(removeNick(QString, QString)));
92 connect(clientProxy, SIGNAL(csNickRenamed(QString, QString, QString)), this, SLOT(renameNick(QString, QString, QString)));
93 connect(clientProxy, SIGNAL(csNickUpdated(QString, QString, VarMap)), this, SLOT(updateNick(QString, QString, VarMap)));
94 connect(clientProxy, SIGNAL(csOwnNickSet(QString, QString)), this, SLOT(setOwnNick(QString, QString)));
95 connect(clientProxy, SIGNAL(csBacklogData(BufferId, const QList<QVariant> &, bool)), this, SLOT(recvBacklogData(BufferId, QList<QVariant>, bool)));
96 connect(clientProxy, SIGNAL(csUpdateBufferId(BufferId)), this, SLOT(updateBufferId(BufferId)));
97 connect(this, SIGNAL(sendInput(BufferId, QString)), clientProxy, SLOT(gsUserInput(BufferId, QString)));
98 connect(this, SIGNAL(requestBacklog(BufferId, QVariant, QVariant)), clientProxy, SLOT(gsRequestBacklog(BufferId, QVariant, QVariant)));
99 connect(this, SIGNAL(requestNetworkStates()), clientProxy, SLOT(gsRequestNetworkStates()));
101 connect(mainUi, SIGNAL(connectToCore(const VarMap &)), this, SLOT(connectToCore(const VarMap &)));
102 connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
103 connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
104 connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
106 layoutTimer = new QTimer(this);
107 layoutTimer->setInterval(0);
108 layoutTimer->setSingleShot(false);
109 connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
115 //delete _bufferModel;
116 foreach(Buffer *buf, buffers.values()) delete buf;
117 ClientProxy::destroy();
121 BufferTreeModel *Client::bufferModel() {
122 return instance()->_bufferModel;
125 bool Client::isConnected() { return connectedToCore; }
127 void Client::connectToCore(const VarMap &conn) {
128 // TODO implement SSL
129 coreConnectionInfo = conn;
131 emit coreConnectionError(tr("Already connected to Core!"));
134 if(conn["Host"].toString().isEmpty()) {
135 clientMode = LocalCore;
138 clientMode = RemoteCore;
139 emit coreConnectionMsg(tr("Connecting..."));
140 socket.connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
144 void Client::disconnectFromCore() {
145 if(clientMode == RemoteCore) {
148 disconnectFromLocalCore();
151 /* Clear internal data. Hopefully nothing relies on it at this point. */
152 coreConnectionInfo.clear();
154 //foreach(Buffer *buf, buffers.values()) delete buf;
155 qDebug() << "barfoo";
156 _bufferModel->clear();
157 //qDeleteAll(buffers);
158 qDebug() << "foobar";
161 void Client::coreConnected() {
166 void Client::coreDisconnected() {
167 connectedToCore = false;
171 void Client::syncToCore() {
173 if(clientMode == LocalCore) {
174 state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString()).toMap();
176 // TODO connect to remote cores
179 VarMap sessionState = state["SessionState"].toMap();
180 VarMap sessData = sessionState["SessionData"].toMap();
181 foreach(QString key, sessData.keys()) {
182 recvSessionData(key, sessData[key]);
184 QList<QVariant> coreBuffers = sessionState["Buffers"].toList();
185 /* make lookups by id faster */
186 foreach(QVariant vid, coreBuffers) {
187 BufferId id = vid.value<BufferId>();
188 bufferIds[id.uid()] = id; // make lookups by id faster
189 buffer(id); // create all buffers, so we see them in the network views
191 netsAwaitingInit = sessionState["Networks"].toStringList();
192 connectedToCore = true;
193 if(netsAwaitingInit.count()) {
194 emit coreConnectionMsg(tr("Requesting network states..."));
195 emit coreConnectionProgress(0, netsAwaitingInit.count());
196 emit requestNetworkStates();
199 emit coreConnectionProgress(1, 1);
204 void Client::recvSessionData(const QString &key, const QVariant &data) {
205 sessionData[key] = data;
206 emit sessionDataChanged(key, data);
207 emit sessionDataChanged(key);
210 void Client::storeSessionData(const QString &key, const QVariant &data) {
211 // Not sure if this is a good idea, but we'll try it anyway:
212 // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
213 // rather than immediately.
214 emit instance()->sendSessionData(key, data);
217 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
218 if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
222 QStringList Client::sessionDataKeys() {
223 return instance()->sessionData.keys();
226 void Client::recvProxySignal(ClientSignal sig, QVariant arg1, QVariant arg2, QVariant arg3) {
227 if(clientMode == LocalCore) return;
228 QList<QVariant> sigdata;
229 sigdata.append(sig); sigdata.append(arg1); sigdata.append(arg2); sigdata.append(arg3);
230 //qDebug() << "Sending signal: " << sigdata;
231 writeDataToDevice(&socket, QVariant(sigdata));
234 void Client::serverError(QAbstractSocket::SocketError) {
235 emit coreConnectionError(socket.errorString());
238 void Client::serverHasData() {
240 while(readDataFromDevice(&socket, blockSize, item)) {
241 emit recvPartialItem(1,1);
242 QList<QVariant> sigdata = item.toList();
243 Q_ASSERT(sigdata.size() == 4);
244 ClientProxy::instance()->recv((CoreSignal)sigdata[0].toInt(), sigdata[1], sigdata[2], sigdata[3]);
248 emit recvPartialItem(socket.bytesAvailable(), blockSize);
252 void Client::networkConnected(QString net) {
253 Q_ASSERT(!netsAwaitingInit.contains(net));
254 netConnected[net] = true;
255 BufferId id = statusBufferId(net);
256 Buffer *b = buffer(id);
258 //b->displayMsg(Message(id, Message::Server, tr("Connected.")));
259 // TODO buffersUpdated();
262 void Client::networkDisconnected(QString net) {
263 foreach(BufferId id, buffers.keys()) {
264 if(id.network() != net) continue;
265 Buffer *b = buffer(id);
266 //b->displayMsg(Message(id, Message::Server, tr("Server disconnected."))); FIXME
269 netConnected[net] = false;
270 if(netsAwaitingInit.contains(net)) {
271 qDebug() << "Network" << net << "disconnected while not yet initialized!";
272 netsAwaitingInit.removeAll(net);
273 emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
274 if(!netsAwaitingInit.count()) emit connected();
278 void Client::updateBufferId(BufferId id) {
279 bufferIds[id.uid()] = id; // make lookups by id faster
283 BufferId Client::bufferId(QString net, QString buf) {
284 foreach(BufferId id, buffers.keys()) {
285 if(id.network() == net && id.buffer() == buf) return id;
287 Q_ASSERT(false); // should never happen!
291 BufferId Client::statusBufferId(QString net) {
292 return bufferId(net, "");
296 Buffer * Client::buffer(BufferId id) {
297 Client *client = Client::instance();
298 if(!buffers.contains(id)) {
299 Buffer *b = new Buffer(id);
300 b->setOwnNick(ownNick[id.network()]);
301 connect(b, SIGNAL(userInput(BufferId, QString)), client, SLOT(userInput(BufferId, QString)));
302 connect(b, SIGNAL(bufferUpdated(Buffer *)), client, SIGNAL(bufferUpdated(Buffer *)));
303 connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SIGNAL(bufferDestroyed(Buffer *)));
305 emit client->bufferUpdated(b);
310 QList<BufferId> Client::allBufferIds() {
311 return buffers.keys();
314 void Client::recvNetworkState(QString net, QVariant state) {
315 netsAwaitingInit.removeAll(net);
316 netConnected[net] = true;
317 setOwnNick(net, state.toMap()["OwnNick"].toString());
318 buffer(statusBufferId(net))->setActive(true);
319 VarMap t = state.toMap()["Topics"].toMap();
320 VarMap n = state.toMap()["Nicks"].toMap();
321 foreach(QVariant v, t.keys()) {
322 QString buf = v.toString();
323 BufferId id = bufferId(net, buf);
324 buffer(id)->setActive(true);
325 setTopic(net, buf, t[buf].toString());
327 foreach(QString nick, n.keys()) {
328 addNick(net, nick, n[nick].toMap());
330 emit coreConnectionProgress(netConnected.count(), netConnected.count() + netsAwaitingInit.count());
331 if(!netsAwaitingInit.count()) emit connected();
334 void Client::recvMessage(const Message &msg) {
335 Buffer *b = buffer(msg.buffer);
337 Buffer::ActivityLevel level = Buffer::OtherActivity;
338 if(msg.type == Message::Plain || msg.type == Message::Notice){
339 level |= Buffer::NewMessage;
341 if(msg.flags & Message::Highlight){
342 level |= Buffer::Highlight;
344 emit bufferActivity(level, b);
349 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
350 //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
354 void Client::recvBacklogData(BufferId id, const QList<QVariant> &msgs, bool /*done*/) {
355 Buffer *b = buffer(id);
356 foreach(QVariant v, msgs) {
357 Message msg = v.value<Message>();
359 if(!layoutQueue.contains(b)) layoutQueue.append(b);
361 if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
364 void Client::layoutMsg() {
365 if(layoutQueue.count()) {
366 Buffer *b = layoutQueue.takeFirst(); // TODO make this the current buffer
367 if(b->layoutMsg()) layoutQueue.append(b); // Buffer has more messages in its queue --> Round Robin
369 if(!layoutQueue.count()) layoutTimer->stop();
372 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
373 return instance()->mainUi->layoutMsg(msg);
376 void Client::userInput(BufferId id, QString msg) {
377 emit sendInput(id, msg);
380 void Client::setTopic(QString net, QString buf, QString topic) {
381 BufferId id = bufferId(net, buf);
382 if(!netConnected[id.network()]) return;
383 Buffer *b = buffer(id);
385 //if(!b->isActive()) {
386 // b->setActive(true);
391 void Client::addNick(QString net, QString nick, VarMap props) {
392 if(!netConnected[net]) return;
393 nicks[net][nick] = props;
394 VarMap chans = props["Channels"].toMap();
395 QStringList c = chans.keys();
396 foreach(QString bufname, c) {
397 buffer(bufferId(net, bufname))->addNick(nick, props);
401 void Client::renameNick(QString net, QString oldnick, QString newnick) {
402 if(!netConnected[net]) return;
403 QStringList chans = nicks[net][oldnick]["Channels"].toMap().keys();
404 foreach(QString c, chans) {
405 buffer(bufferId(net, c))->renameNick(oldnick, newnick);
407 nicks[net][newnick] = nicks[net].take(oldnick);
410 void Client::updateNick(QString net, QString nick, VarMap props) {
411 if(!netConnected[net]) return;
412 QStringList oldchans = nicks[net][nick]["Channels"].toMap().keys();
413 QStringList newchans = props["Channels"].toMap().keys();
414 foreach(QString c, newchans) {
415 if(oldchans.contains(c)) buffer(bufferId(net, c))->updateNick(nick, props);
416 else buffer(bufferId(net, c))->addNick(nick, props);
418 foreach(QString c, oldchans) {
419 if(!newchans.contains(c)) buffer(bufferId(net, c))->removeNick(nick);
421 nicks[net][nick] = props;
424 void Client::removeNick(QString net, QString nick) {
425 if(!netConnected[net]) return;
426 VarMap chans = nicks[net][nick]["Channels"].toMap();
427 foreach(QString bufname, chans.keys()) {
428 buffer(bufferId(net, bufname))->removeNick(nick);
430 nicks[net].remove(nick);
433 void Client::setOwnNick(QString net, QString nick) {
434 if(!netConnected[net]) return;
436 foreach(BufferId id, buffers.keys()) {
437 if(id.network() == net) {
438 buffers[id]->setOwnNick(nick);