Fix default button behavior in CoreConnectDlg.
[quassel.git] / src / core / coresession.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
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) version 3.                                           *
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 "core.h"
22 #include "coresession.h"
23 #include "networkconnection.h"
24
25 #include "signalproxy.h"
26 #include "storage.h"
27
28 #include "network.h"
29 #include "ircuser.h"
30 #include "ircchannel.h"
31 #include "identity.h"
32
33 #include "util.h"
34 #include "coreusersettings.h"
35
36 #include <QtScript>
37
38 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent) : QObject(parent),
39     _user(uid),
40     _signalProxy(new SignalProxy(SignalProxy::Server, 0, this)),
41     scriptEngine(new QScriptEngine(this))
42 {
43
44   SignalProxy *p = signalProxy();
45
46   p->attachSlot(SIGNAL(requestConnect(QString)), this, SLOT(connectToNetwork(QString)));
47   p->attachSlot(SIGNAL(disconnectFromNetwork(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId))); // FIXME
48   p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
49   p->attachSlot(SIGNAL(requestBacklog(BufferInfo, QVariant, QVariant)), this, SLOT(sendBacklog(BufferInfo, QVariant, QVariant)));
50   p->attachSignal(this, SIGNAL(displayMsg(Message)));
51   p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
52   p->attachSignal(this, SIGNAL(backlogData(BufferInfo, QVariantList, bool)));
53   p->attachSignal(this, SIGNAL(bufferInfoUpdated(BufferInfo)));
54
55   p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
56   p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
57   p->attachSlot(SIGNAL(createIdentity(const Identity &)), this, SLOT(createIdentity(const Identity &)));
58   p->attachSlot(SIGNAL(updateIdentity(const Identity &)), this, SLOT(updateIdentity(const Identity &)));
59   p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
60
61   p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
62   p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
63   p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &)), this, SLOT(createNetwork(const NetworkInfo &)));
64   p->attachSlot(SIGNAL(updateNetwork(const NetworkInfo &)), this, SLOT(updateNetwork(const NetworkInfo &)));
65   p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
66
67   loadSettings();
68   initScriptEngine();
69
70   // Restore session state
71   if(restoreState) restoreSessionState();
72
73   emit initialized();
74 }
75
76 CoreSession::~CoreSession() {
77   saveSessionState();
78   foreach(NetworkConnection *conn, _connections.values()) {
79     delete conn;
80   }
81   foreach(Network *net, _networks.values()) {
82     delete net;
83   }
84 }
85
86 UserId CoreSession::user() const {
87   return _user;
88 }
89
90 Network *CoreSession::network(NetworkId id) const {
91   if(_networks.contains(id)) return _networks[id];
92   return 0;
93 }
94
95 NetworkConnection *CoreSession::networkConnection(NetworkId id) const {
96   if(_connections.contains(id)) return _connections[id];
97   return 0;
98 }
99
100 Identity *CoreSession::identity(IdentityId id) const {
101   if(_identities.contains(id)) return _identities[id];
102   return 0;
103 }
104
105 void CoreSession::loadSettings() {
106   CoreUserSettings s(user());
107
108   foreach(IdentityId id, s.identityIds()) {
109     Identity *i = new Identity(s.identity(id), this);
110     if(!i->isValid()) {
111       qWarning() << QString("Invalid identity! Removing...");
112       s.removeIdentity(id);
113       delete i;
114       continue;
115     }
116     if(_identities.contains(i->id())) {
117       qWarning() << "Duplicate identity, ignoring!";
118       delete i;
119       continue;
120     }
121     _identities[i->id()] = i;
122     signalProxy()->synchronize(i);
123   }
124   if(!_identities.count()) {
125     Identity i(1);
126     i.setToDefaults();
127     i.setIdentityName(tr("Default Identity"));
128     createIdentity(i);
129   }
130
131   // FIXME switch to a pure DB storage
132   foreach(NetworkId id, s.networkIds()) {
133     NetworkInfo info = s.networkInfo(id);
134     createNetwork(info);
135   }
136
137   // FIXME Migrate old settings if available...
138   if(!_networks.count()) {
139     QVariantMap networks = s.sessionValue("Networks").toMap();
140     if(networks.keys().count()) {
141       qWarning() << "Migrating your old network settings to the new format!";
142       foreach(QString netname, networks.keys()) {
143         QVariantMap network = networks[netname].toMap();
144         NetworkId netid = Core::networkId(user(), netname);
145         NetworkInfo info;
146         info.networkId = netid;
147         info.networkName = netname;
148         info.identity = 1;
149         info.codecForEncoding = "ISO-8859-15";
150         info.codecForDecoding = "ISO-8859-15";
151         QVariantList slist;
152         foreach(QVariant v, network["Servers"].toList()) {
153           QVariantMap server;
154           server["Host"] = v.toMap()["Address"];
155           server["Port"] = v.toMap()["Port"];
156           slist << server;
157         }
158         info.serverList = slist;
159         createNetwork(info);
160       }
161     }
162   }
163 }
164
165 void CoreSession::saveSessionState() const {
166   QVariantMap res;
167   QVariantList conn;
168   foreach(NetworkConnection *net, _connections.values()) {
169     QVariantMap m;
170     m["NetworkId"] = QVariant::fromValue<NetworkId>(net->networkId());
171     m["State"] = net->state();
172     conn << m;
173   }
174   res["CoreBuild"] = Global::quasselBuild;
175   res["ConnectedNetworks"] = conn;
176   CoreUserSettings s(user());
177   s.setSessionState(res);
178 }
179
180 void CoreSession::restoreSessionState() {
181   CoreUserSettings s(user());
182   uint build = s.sessionState().toMap()["CoreBuild"].toUInt();
183   if(build < 362) {
184     qWarning() << qPrintable(tr("Session state does not exist or is too old!"));
185     return;
186   }
187   QVariantList conn = s.sessionState().toMap()["ConnectedNetworks"].toList();
188   foreach(QVariant v, conn) {
189     NetworkId id = v.toMap()["NetworkId"].value<NetworkId>();
190     if(_networks.keys().contains(id)) connectToNetwork(id, v.toMap()["State"]);
191   }
192 }
193
194 void CoreSession::updateBufferInfo(UserId uid, const BufferInfo &bufinfo) {
195   if(uid == user()) emit bufferInfoUpdated(bufinfo);
196 }
197
198 // FIXME remove
199 void CoreSession::connectToNetwork(QString netname, const QVariant &previousState) {
200   Network *net = 0;
201   foreach(Network *n, _networks.values()) {
202     if(n->networkName() == netname) {
203       net = n; break;
204     }
205   }
206   if(!net) {
207     qWarning() << "Connect to unknown network requested, ignoring!";
208     return;
209   }
210   connectToNetwork(net->networkId(), previousState);
211 }
212
213 void CoreSession::connectToNetwork(NetworkId id, const QVariant &previousState) {
214   Network *net = network(id);
215   if(!net) {
216     qWarning() << "Connect to unknown network requested! net:" << id << "user:" << user();
217     return;
218   }
219
220   NetworkConnection *conn = networkConnection(id);
221   if(!conn) {
222     conn = new NetworkConnection(net, this, previousState);
223     _connections[id] = conn;
224     attachNetworkConnection(conn);
225   }
226   conn->connectToIrc();
227 }
228
229 void CoreSession::attachNetworkConnection(NetworkConnection *conn) {
230   connect(conn, SIGNAL(connected(NetworkId)), this, SLOT(networkConnected(NetworkId)));
231   connect(conn, SIGNAL(disconnected(NetworkId)), this, SLOT(networkDisconnected(NetworkId)));
232
233   // I guess we don't need these anymore, client-side can just connect the network's signals directly
234   //signalProxy()->attachSignal(conn, SIGNAL(connected(NetworkId)), SIGNAL(networkConnected(NetworkId)));
235   //signalProxy()->attachSignal(conn, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
236
237   connect(conn, SIGNAL(displayMsg(Message::Type, QString, QString, QString, quint8)), this, SLOT(recvMessageFromServer(Message::Type, QString, QString, QString, quint8)));
238   connect(conn, SIGNAL(displayStatusMsg(QString)), this, SLOT(recvStatusMsgFromServer(QString)));
239
240 }
241
242 void CoreSession::disconnectFromNetwork(NetworkId id) {
243   if(!_connections.contains(id)) return;
244   _connections[id]->disconnectFromIrc();
245 }
246
247 void CoreSession::networkStateRequested() {
248 }
249
250 void CoreSession::addClient(QObject *dev) { // this is QObject* so we can use it in signal connections
251   QIODevice *device = qobject_cast<QIODevice *>(dev);
252   if(!device) {
253     qWarning() << "Invoking CoreSession::addClient with a QObject that is not a QIODevice!";
254   } else {
255     signalProxy()->addPeer(device);
256     QVariantMap reply;
257     reply["MsgType"] = "SessionInit";
258     reply["SessionState"] = sessionState();
259     SignalProxy::writeDataToDevice(device, reply);
260   }
261 }
262
263 SignalProxy *CoreSession::signalProxy() const {
264   return _signalProxy;
265 }
266
267 // FIXME we need a sane way for creating buffers!
268 void CoreSession::networkConnected(NetworkId networkid) {
269   Core::bufferInfo(user(), networkid); // create status buffer
270 }
271
272 void CoreSession::networkDisconnected(NetworkId networkid) {
273   // FIXME
274   // connection should only go away on explicit /part, and handle reconnections etcpp internally otherwise
275
276   Q_ASSERT(_connections.contains(networkid));
277   _connections.take(networkid)->deleteLater();
278 }
279
280 // FIXME switch to BufferId
281 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg) {
282   NetworkConnection *conn = networkConnection(bufinfo.networkId());
283   if(conn) {
284     conn->userInput(bufinfo.bufferName(), msg);
285   } else {
286     qWarning() << "Trying to send to unconnected network!";
287   }
288 }
289
290 // ALL messages coming pass through these functions before going to the GUI.
291 // So this is the perfect place for storing the backlog and log stuff.
292 void CoreSession::recvMessageFromServer(Message::Type type, QString target, QString text, QString sender, quint8 flags) {
293   NetworkConnection *netCon = qobject_cast<NetworkConnection*>(this->sender());
294   Q_ASSERT(netCon);
295   
296   BufferInfo bufferInfo = Core::bufferInfo(user(), netCon->networkId(), target);
297   Message msg(bufferInfo, type, text, sender, flags);
298   msg.setMsgId(Core::storeMessage(msg));
299   Q_ASSERT(msg.msgId() != 0);
300   emit displayMsg(msg);
301 }
302
303 void CoreSession::recvStatusMsgFromServer(QString msg) {
304   NetworkConnection *s = qobject_cast<NetworkConnection*>(sender());
305   Q_ASSERT(s);
306   emit displayStatusMsg(s->networkName(), msg);
307 }
308
309 QList<BufferInfo> CoreSession::buffers() const {
310   return Core::requestBuffers(user());
311 }
312
313
314 QVariant CoreSession::sessionState() {
315   QVariantMap v;
316
317   QVariantList bufs;
318   foreach(BufferInfo id, buffers()) bufs << qVariantFromValue(id);
319   v["BufferInfos"] = bufs;
320   QVariantList networkids;
321   foreach(NetworkId id, _networks.keys()) networkids << qVariantFromValue(id);
322   v["NetworkIds"] = networkids;
323
324   quint32 ircusercount = 0;
325   quint32 ircchannelcount = 0;
326   foreach(Network *net, _networks.values()) {
327     ircusercount += net->ircUserCount();
328     ircchannelcount += net->ircChannelCount();
329   }
330   v["IrcUserCount"] = ircusercount;
331   v["IrcChannelCount"] = ircchannelcount;
332
333   QList<QVariant> idlist;
334   foreach(Identity *i, _identities.values()) idlist << qVariantFromValue(*i);
335   v["Identities"] = idlist;
336
337   //v["Payload"] = QByteArray(100000000, 'a');  // for testing purposes
338   return v;
339 }
340
341 void CoreSession::sendBacklog(BufferInfo id, QVariant v1, QVariant v2) {
342   QList<QVariant> log;
343   QList<Message> msglist;
344   if(v1.type() == QVariant::DateTime) {
345
346
347   } else {
348     msglist = Core::requestMsgs(id, v1.toInt(), v2.toInt());
349   }
350
351   // Send messages out in smaller packages - we don't want to make the signal data too large!
352   for(int i = 0; i < msglist.count(); i++) {
353     log.append(qVariantFromValue(msglist[i]));
354     if(log.count() >= 5) {
355       emit backlogData(id, log, i >= msglist.count() - 1);
356       log.clear();
357     }
358   }
359   if(log.count() > 0) emit backlogData(id, log, true);
360 }
361
362
363 void CoreSession::initScriptEngine() {
364   signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
365   signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
366
367   // FIXME
368   //QScriptValue storage_ = scriptEngine->newQObject(storage);
369   //scriptEngine->globalObject().setProperty("storage", storage_);
370 }
371
372 void CoreSession::scriptRequest(QString script) {
373   emit scriptResult(scriptEngine->evaluate(script).toString());
374 }
375
376 /*** Identity Handling ***/
377
378 void CoreSession::createIdentity(const Identity &id) {
379   // find free ID
380   int i;
381   for(i = 1; i <= _identities.count(); i++) {
382     if(!_identities.keys().contains(i)) break;
383   }
384   //qDebug() << "found free id" << i;
385   Identity *newId = new Identity(id, this);
386   newId->setId(i);
387   _identities[i] = newId;
388   signalProxy()->synchronize(newId);
389   CoreUserSettings s(user());
390   s.storeIdentity(*newId);
391   emit identityCreated(*newId);
392 }
393
394 void CoreSession::updateIdentity(const Identity &id) {
395   if(!_identities.contains(id.id())) {
396     qWarning() << "Update request for unknown identity received!";
397     return;
398   }
399   _identities[id.id()]->update(id);
400
401   CoreUserSettings s(user());
402   s.storeIdentity(id);
403 }
404
405 void CoreSession::removeIdentity(IdentityId id) {
406   Identity *i = _identities.take(id);
407   if(i) {
408     emit identityRemoved(id);
409     CoreUserSettings s(user());
410     s.removeIdentity(id);
411     i->deleteLater();
412   }
413 }
414
415 /*** Network Handling ***/
416
417 void CoreSession::createNetwork(const NetworkInfo &info_) {
418   NetworkInfo info = info_;
419   int id;
420
421   if(!info.networkId.isValid())
422     Core::createNetworkId(user(), info);
423
424   Q_ASSERT(info.networkId.isValid());
425
426   id = info.networkId.toInt();
427   Q_ASSERT(!_networks.contains(id));
428   
429   Network *net = new Network(id, this);
430   connect(net, SIGNAL(connectRequested(NetworkId)), this, SLOT(connectToNetwork(NetworkId)));
431   connect(net, SIGNAL(disconnectRequested(NetworkId)), this, SLOT(disconnectFromNetwork(NetworkId)));
432   net->setNetworkInfo(info);
433   net->setProxy(signalProxy());
434   _networks[id] = net;
435   signalProxy()->synchronize(net);
436   CoreUserSettings s(user());
437   s.storeNetworkInfo(info);
438   emit networkCreated(id);
439 }
440
441 void CoreSession::updateNetwork(const NetworkInfo &info) {
442   if(!_networks.contains(info.networkId)) {
443     qWarning() << "Update request for unknown network received!";
444     return;
445   }
446   _networks[info.networkId]->setNetworkInfo(info);
447   CoreUserSettings s(user());
448   s.storeNetworkInfo(info);
449 }
450
451 void CoreSession::removeNetwork(NetworkId id) {
452   Network *net = _networks.take(id);
453   if(net) {
454     emit networkRemoved(id);
455     CoreUserSettings s(user());
456     s.removeNetworkInfo(id);
457     net->deleteLater();
458   }
459 }