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