5211214caec8d6a6640f2d323b2839a43e37897c
[quassel.git] / src / client / client.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-07 by The Quassel Team                             *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                   *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "client.h"
22 #include "clientproxy.h"
23 #include "mainwin.h"
24 #include "buffer.h"
25 #include "bufferviewwidget.h"
26 #include "util.h"
27
28 Client * Client::instanceptr = 0;
29
30 Client::ClientMode Client::clientMode;
31 QHash<BufferId, Buffer *> Client::buffers;
32 QHash<uint, BufferId> Client::bufferIds;
33 QHash<QString, QHash<QString, VarMap> > Client::nicks;
34 QHash<QString, bool> Client::connected;
35 QHash<QString, QString> Client::ownNick;
36 QList<BufferId> Client::coreBuffers;
37
38
39 Client *Client::instance() {
40   if(instanceptr) return instanceptr;
41   instanceptr = new Client();
42   instanceptr->init();
43   return instanceptr;
44 }
45
46 void Client::destroy() {
47   delete instanceptr;
48   instanceptr = 0;
49 }
50
51 Client::Client() {
52   clientProxy = ClientProxy::instance();
53
54   //mainWin = new MainWin();
55
56   _bufferModel = new BufferTreeModel(0);  // FIXME
57
58   connect(this, SIGNAL(bufferSelected(Buffer *)), _bufferModel, SLOT(selectBuffer(Buffer *)));
59   connect(this, SIGNAL(bufferUpdated(Buffer *)), _bufferModel, SLOT(bufferUpdated(Buffer *)));
60   connect(this, SIGNAL(bufferActivity(Buffer::ActivityLevel, Buffer *)), _bufferModel, SLOT(bufferActivity(Buffer::ActivityLevel, Buffer *)));
61
62     // TODO: make this configurable (allow monolithic client to connect to remote cores)
63   if(Global::runMode == Global::Monolithic) clientMode = LocalCore;
64   else clientMode = RemoteCore;
65 }
66
67 void Client::init() {
68   blockSize = 0;
69
70   connect(&socket, SIGNAL(readyRead()), this, SLOT(serverHasData()));
71   connect(&socket, SIGNAL(connected()), this, SLOT(coreConnected()));
72   connect(&socket, SIGNAL(disconnected()), this, SLOT(coreDisconnected()));
73   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(serverError(QAbstractSocket::SocketError)));
74
75   connect(Global::instance(), SIGNAL(dataPutLocally(UserId, QString)), this, SLOT(updateCoreData(UserId, QString)));
76   connect(clientProxy, SIGNAL(csUpdateGlobalData(QString, QVariant)), this, SLOT(updateLocalData(QString, QVariant)));
77
78   connect(clientProxy, SIGNAL(send(ClientSignal, QVariant, QVariant, QVariant)), this, SLOT(recvProxySignal(ClientSignal, QVariant, QVariant, QVariant)));
79   connect(clientProxy, SIGNAL(csServerState(QString, QVariant)), this, SLOT(recvNetworkState(QString, QVariant)));
80   connect(clientProxy, SIGNAL(csServerConnected(QString)), this, SLOT(networkConnected(QString)));
81   connect(clientProxy, SIGNAL(csServerDisconnected(QString)), this, SLOT(networkDisconnected(QString)));
82   connect(clientProxy, SIGNAL(csDisplayMsg(Message)), this, SLOT(recvMessage(Message)));
83   connect(clientProxy, SIGNAL(csDisplayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
84   connect(clientProxy, SIGNAL(csTopicSet(QString, QString, QString)), this, SLOT(setTopic(QString, QString, QString)));
85   connect(clientProxy, SIGNAL(csNickAdded(QString, QString, VarMap)), this, SLOT(addNick(QString, QString, VarMap)));
86   connect(clientProxy, SIGNAL(csNickRemoved(QString, QString)), this, SLOT(removeNick(QString, QString)));
87   connect(clientProxy, SIGNAL(csNickRenamed(QString, QString, QString)), this, SLOT(renameNick(QString, QString, QString)));
88   connect(clientProxy, SIGNAL(csNickUpdated(QString, QString, VarMap)), this, SLOT(updateNick(QString, QString, VarMap)));
89   connect(clientProxy, SIGNAL(csOwnNickSet(QString, QString)), this, SLOT(setOwnNick(QString, QString)));
90   connect(clientProxy, SIGNAL(csBacklogData(BufferId, QList<QVariant>, bool)), this, SLOT(recvBacklogData(BufferId, QList<QVariant>, bool)));
91   connect(clientProxy, SIGNAL(csUpdateBufferId(BufferId)), this, SLOT(updateBufferId(BufferId)));
92   connect(this, SIGNAL(sendInput(BufferId, QString)), clientProxy, SLOT(gsUserInput(BufferId, QString)));
93   connect(this, SIGNAL(requestBacklog(BufferId, QVariant, QVariant)), clientProxy, SLOT(gsRequestBacklog(BufferId, QVariant, QVariant)));
94
95   syncToCore();
96
97   layoutTimer = new QTimer(this);
98   layoutTimer->setInterval(0);
99   layoutTimer->setSingleShot(false);
100   connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
101
102   /* make lookups by id faster */
103   foreach(BufferId id, coreBuffers) {
104     bufferIds[id.uid()] = id;  // make lookups by id faster
105     buffer(id);                // create all buffers, so we see them in the network views
106     emit requestBacklog(id, -1, -1);  // TODO: use custom settings for backlog request
107   }
108
109   mainWin = new MainWin();
110   mainWin->init();
111
112 }
113
114 Client::~Client() {
115   delete mainWin;
116   delete _bufferModel;
117   foreach(Buffer *buf, buffers.values()) delete buf;
118   ClientProxy::destroy();
119
120 }
121
122 BufferTreeModel *Client::bufferModel() {
123   return instance()->_bufferModel;
124 }
125
126 void Client::coreConnected() {
127
128 }
129
130 void Client::coreDisconnected() {
131
132 }
133
134 void Client::updateCoreData(UserId, QString key) {
135   if(clientMode == LocalCore) return;
136   QVariant data = Global::data(key);
137   recvProxySignal(GS_UPDATE_GLOBAL_DATA, key, data, QVariant());
138 }
139
140 void Client::updateLocalData(QString key, QVariant data) {
141   Global::updateData(key, data);
142 }
143
144 void Client::recvProxySignal(ClientSignal sig, QVariant arg1, QVariant arg2, QVariant arg3) {
145   if(clientMode == LocalCore) return;
146   QList<QVariant> sigdata;
147   sigdata.append(sig); sigdata.append(arg1); sigdata.append(arg2); sigdata.append(arg3);
148   //qDebug() << "Sending signal: " << sigdata;
149   writeDataToDevice(&socket, QVariant(sigdata));
150 }
151
152 void Client::connectToCore(QString host, quint16 port) {
153   // TODO implement SSL
154   socket.connectToHost(host, port);
155 }
156
157 void Client::disconnectFromCore() {
158   socket.close();
159 }
160
161 void Client::serverError(QAbstractSocket::SocketError) {
162   emit coreConnectionError(socket.errorString());
163 }
164
165 void Client::serverHasData() {
166   QVariant item;
167   while(readDataFromDevice(&socket, blockSize, item)) {
168     emit recvPartialItem(1,1);
169     QList<QVariant> sigdata = item.toList();
170     Q_ASSERT(sigdata.size() == 4);
171     ClientProxy::instance()->recv((CoreSignal)sigdata[0].toInt(), sigdata[1], sigdata[2], sigdata[3]);
172     blockSize = 0;
173   }
174   if(blockSize > 0) {
175     emit recvPartialItem(socket.bytesAvailable(), blockSize);
176   }
177 }
178
179 /*******************************************************************************************************************/
180
181 void Client::networkConnected(QString net) {
182   connected[net] = true;
183   BufferId id = statusBufferId(net);
184   Buffer *b = buffer(id);
185   b->setActive(true);
186   //b->displayMsg(Message(id, Message::Server, tr("Connected.")));
187   // TODO buffersUpdated();
188 }
189
190 void Client::networkDisconnected(QString net) {
191   foreach(BufferId id, buffers.keys()) {
192     if(id.network() != net) continue;
193     Buffer *b = buffer(id);
194     //b->displayMsg(Message(id, Message::Server, tr("Server disconnected."))); FIXME
195     b->setActive(false);
196   }
197   connected[net] = false;
198 }
199
200 void Client::updateBufferId(BufferId id) {
201   bufferIds[id.uid()] = id;  // make lookups by id faster
202   buffer(id);
203 }
204
205 BufferId Client::bufferId(QString net, QString buf) {
206   foreach(BufferId id, buffers.keys()) {
207     if(id.network() == net && id.buffer() == buf) return id;
208   }
209   Q_ASSERT(false);  // should never happen!
210   return BufferId();
211 }
212
213 BufferId Client::statusBufferId(QString net) {
214   return bufferId(net, "");
215 }
216
217
218 Buffer * Client::buffer(BufferId id) {
219   Client *client = Client::instance();
220   if(!buffers.contains(id)) {
221     Buffer *b = new Buffer(id);
222     b->setOwnNick(ownNick[id.network()]);
223     connect(b, SIGNAL(userInput(BufferId, QString)), client, SLOT(userInput(BufferId, QString)));
224     connect(b, SIGNAL(bufferUpdated(Buffer *)), client, SIGNAL(bufferUpdated(Buffer *)));
225     connect(b, SIGNAL(bufferDestroyed(Buffer *)), client, SIGNAL(bufferDestroyed(Buffer *)));
226     buffers[id] = b;
227     emit client->bufferUpdated(b);
228   }
229   return buffers[id];
230 }
231
232 void Client::recvNetworkState(QString net, QVariant state) {
233   connected[net] = true;
234   setOwnNick(net, state.toMap()["OwnNick"].toString());
235   buffer(statusBufferId(net))->setActive(true);
236   VarMap t = state.toMap()["Topics"].toMap();
237   VarMap n = state.toMap()["Nicks"].toMap();
238   foreach(QVariant v, t.keys()) {
239     QString buf = v.toString();
240     BufferId id = bufferId(net, buf);
241     buffer(id)->setActive(true);
242     setTopic(net, buf, t[buf].toString());
243   }
244   foreach(QString nick, n.keys()) {
245     addNick(net, nick, n[nick].toMap());
246   }
247 }
248
249 void Client::recvMessage(Message msg) {
250   Buffer *b = buffer(msg.buffer);
251
252   Buffer::ActivityLevel level = Buffer::OtherActivity;
253   if(msg.type == Message::Plain || msg.type == Message::Notice){
254     level |= Buffer::NewMessage;
255   }
256   if(msg.flags & Message::Highlight){
257     level |= Buffer::Highlight;
258   }
259   emit bufferActivity(level, b);
260
261   //b->displayMsg(msg);
262   b->appendChatLine(new ChatLine(msg));
263 }
264
265 void Client::recvStatusMsg(QString net, QString msg) {
266   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
267
268 }
269
270 void Client::recvBacklogData(BufferId id, QList<QVariant> msgs, bool done) {
271   foreach(QVariant v, msgs) {
272     layoutQueue.append(v.value<Message>());
273   }
274   if(!layoutTimer->isActive()) layoutTimer->start();
275 }
276
277
278 void Client::layoutMsg() {
279   if(layoutQueue.count()) {
280     ChatLine *line = new ChatLine(layoutQueue.takeFirst());
281     buffer(line->bufferId())->prependChatLine(line);
282   }
283   if(!layoutQueue.count()) layoutTimer->stop();
284 }
285
286 void Client::userInput(BufferId id, QString msg) {
287   emit sendInput(id, msg);
288 }
289
290 void Client::setTopic(QString net, QString buf, QString topic) {
291   BufferId id = bufferId(net, buf);
292   if(!connected[id.network()]) return;
293   Buffer *b = buffer(id);
294   b->setTopic(topic);
295   //if(!b->isActive()) {
296   //  b->setActive(true);
297   //  buffersUpdated();
298   //}
299 }
300
301 void Client::addNick(QString net, QString nick, VarMap props) {
302   if(!connected[net]) return;
303   nicks[net][nick] = props;
304   VarMap chans = props["Channels"].toMap();
305   QStringList c = chans.keys();
306   foreach(QString bufname, c) {
307     buffer(bufferId(net, bufname))->addNick(nick, props);
308   }
309 }
310
311 void Client::renameNick(QString net, QString oldnick, QString newnick) {
312   if(!connected[net]) return;
313   QStringList chans = nicks[net][oldnick]["Channels"].toMap().keys();
314   foreach(QString c, chans) {
315     buffer(bufferId(net, c))->renameNick(oldnick, newnick);
316   }
317   nicks[net][newnick] = nicks[net].take(oldnick);
318 }
319
320 void Client::updateNick(QString net, QString nick, VarMap props) {
321   if(!connected[net]) return;
322   QStringList oldchans = nicks[net][nick]["Channels"].toMap().keys();
323   QStringList newchans = props["Channels"].toMap().keys();
324   foreach(QString c, newchans) {
325     if(oldchans.contains(c)) buffer(bufferId(net, c))->updateNick(nick, props);
326     else buffer(bufferId(net, c))->addNick(nick, props);
327   }
328   foreach(QString c, oldchans) {
329     if(!newchans.contains(c)) buffer(bufferId(net, c))->removeNick(nick);
330   }
331   nicks[net][nick] = props;
332 }
333
334 void Client::removeNick(QString net, QString nick) {
335   if(!connected[net]) return;
336   VarMap chans = nicks[net][nick]["Channels"].toMap();
337   foreach(QString bufname, chans.keys()) {
338     buffer(bufferId(net, bufname))->removeNick(nick);
339   }
340   nicks[net].remove(nick);
341 }
342
343 void Client::setOwnNick(QString net, QString nick) {
344   if(!connected[net]) return;
345   ownNick[net] = nick;
346   foreach(BufferId id, buffers.keys()) {
347     if(id.network() == net) {
348       buffers[id]->setOwnNick(nick);
349     }
350   }
351 }
352
353