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