Fixes #682 - Core crashes on client connection
[quassel.git] / src / client / client.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 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 "client.h"
22
23 #include "abstractmessageprocessor.h"
24 #include "abstractui.h"
25 #include "bufferinfo.h"
26 #include "buffermodel.h"
27 #include "buffersettings.h"
28 #include "buffersyncer.h"
29 #include "bufferviewconfig.h"
30 #include "bufferviewoverlay.h"
31 #include "clientaliasmanager.h"
32 #include "clientbacklogmanager.h"
33 #include "clientbufferviewmanager.h"
34 #include "clientirclisthelper.h"
35 #include "clientidentity.h"
36 #include "clientuserinputhandler.h"
37 #include "ircchannel.h"
38 #include "ircuser.h"
39 #include "message.h"
40 #include "messagemodel.h"
41 #include "network.h"
42 #include "networkmodel.h"
43 #include "quassel.h"
44 #include "signalproxy.h"
45 #include "util.h"
46
47 #include <stdio.h>
48 #include <stdlib.h>
49
50 QPointer<Client> Client::instanceptr = 0;
51 AccountId Client::_currentCoreAccount = 0;
52
53 /*** Initialization/destruction ***/
54
55 bool Client::instanceExists()
56 {
57   return instanceptr;
58 }
59
60 Client *Client::instance() {
61   if(!instanceptr)
62     instanceptr = new Client();
63   return instanceptr;
64 }
65
66 void Client::destroy() {
67   if(instanceptr) {
68     delete instanceptr->mainUi();
69     instanceptr->deleteLater();
70     instanceptr = 0;
71   }
72 }
73
74 void Client::init(AbstractUi *ui) {
75   instance()->_mainUi = ui;
76   instance()->init();
77 }
78
79 Client::Client(QObject *parent)
80   : QObject(parent),
81     _signalProxy(new SignalProxy(SignalProxy::Client, this)),
82     _mainUi(0),
83     _networkModel(0),
84     _bufferModel(0),
85     _bufferSyncer(0),
86     _aliasManager(0),
87     _backlogManager(new ClientBacklogManager(this)),
88     _bufferViewManager(0),
89     _bufferViewOverlay(new BufferViewOverlay(this)),
90     _ircListHelper(new ClientIrcListHelper(this)),
91     _inputHandler(0),
92     _messageModel(0),
93     _messageProcessor(0),
94     _connectedToCore(false),
95     _syncedToCore(false),
96     _internalCore(false),
97     _debugLog(&_debugLogBuffer)
98 {
99   _signalProxy->synchronize(_ircListHelper);
100 }
101
102 Client::~Client() {
103   disconnectFromCore();
104 }
105
106 void Client::init() {
107   _currentCoreAccount = 0;
108   _networkModel = new NetworkModel(this);
109
110   connect(this, SIGNAL(networkRemoved(NetworkId)),
111           _networkModel, SLOT(networkRemoved(NetworkId)));
112
113   _bufferModel = new BufferModel(_networkModel);
114   _messageModel = mainUi()->createMessageModel(this);
115   _messageProcessor = mainUi()->createMessageProcessor(this);
116   _inputHandler = new ClientUserInputHandler(this);
117
118   SignalProxy *p = signalProxy();
119
120   p->attachSlot(SIGNAL(displayMsg(const Message &)), this, SLOT(recvMessage(const Message &)));
121   p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)), this, SLOT(recvStatusMsg(QString, QString)));
122
123   p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), _networkModel, SLOT(bufferUpdated(BufferInfo)));
124   p->attachSignal(inputHandler(), SIGNAL(sendInput(BufferInfo, QString)));
125   p->attachSignal(this, SIGNAL(requestNetworkStates()));
126
127   p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &, const QVariantMap &)), SIGNAL(createIdentity(const Identity &, const QVariantMap &)));
128   p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
129   p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
130   p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
131
132   p->attachSignal(this, SIGNAL(requestCreateNetwork(const NetworkInfo &, const QStringList &)), SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)));
133   p->attachSignal(this, SIGNAL(requestRemoveNetwork(NetworkId)), SIGNAL(removeNetwork(NetworkId)));
134   p->attachSlot(SIGNAL(networkCreated(NetworkId)), this, SLOT(coreNetworkCreated(NetworkId)));
135   p->attachSlot(SIGNAL(networkRemoved(NetworkId)), this, SLOT(coreNetworkRemoved(NetworkId)));
136
137   connect(p, SIGNAL(disconnected()), this, SLOT(disconnectedFromCore()));
138
139   //connect(mainUi(), SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
140   connect(mainUi(), SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
141   connect(this, SIGNAL(connected()), mainUi(), SLOT(connectedToCore()));
142   connect(this, SIGNAL(disconnected()), mainUi(), SLOT(disconnectedFromCore()));
143
144   // attach backlog manager
145   p->synchronize(backlogManager());
146   connect(backlogManager(), SIGNAL(messagesReceived(BufferId, int)), _messageModel, SLOT(messagesReceived(BufferId, int)));
147 }
148
149 /*** public static methods ***/
150
151 AbstractUi *Client::mainUi() {
152   return instance()->_mainUi;
153 }
154
155 AccountId Client::currentCoreAccount() {
156   return _currentCoreAccount;
157 }
158
159 void Client::setCurrentCoreAccount(AccountId id) {
160   _currentCoreAccount = id;
161 }
162
163 bool Client::isConnected() {
164   return instance()->_connectedToCore;
165 }
166
167 bool Client::isSynced() {
168   return instance()->_syncedToCore;
169 }
170
171 /*** Network handling ***/
172
173 QList<NetworkId> Client::networkIds() {
174   return instance()->_networks.keys();
175 }
176
177 const Network * Client::network(NetworkId networkid) {
178   if(instance()->_networks.contains(networkid)) return instance()->_networks[networkid];
179   else return 0;
180 }
181
182 void Client::createNetwork(const NetworkInfo &info, const QStringList &persistentChannels) {
183   emit instance()->requestCreateNetwork(info, persistentChannels);
184 }
185
186 void Client::removeNetwork(NetworkId id) {
187   emit instance()->requestRemoveNetwork(id);
188 }
189
190 void Client::updateNetwork(const NetworkInfo &info) {
191   Network *netptr = instance()->_networks.value(info.networkId, 0);
192   if(!netptr) {
193     qWarning() << "Update for unknown network requested:" << info;
194     return;
195   }
196   netptr->requestSetNetworkInfo(info);
197 }
198
199 void Client::addNetwork(Network *net) {
200   net->setProxy(signalProxy());
201   signalProxy()->synchronize(net);
202   networkModel()->attachNetwork(net);
203   connect(net, SIGNAL(destroyed()), instance(), SLOT(networkDestroyed()));
204   instance()->_networks[net->networkId()] = net;
205   emit instance()->networkCreated(net->networkId());
206 }
207
208 void Client::coreNetworkCreated(NetworkId id) {
209   if(_networks.contains(id)) {
210     qWarning() << "Creation of already existing network requested!";
211     return;
212   }
213   Network *net = new Network(id, this);
214   addNetwork(net);
215 }
216
217 void Client::coreNetworkRemoved(NetworkId id) {
218   if(!_networks.contains(id))
219     return;
220   Network *net = _networks.take(id);
221   emit networkRemoved(net->networkId());
222   net->deleteLater();
223 }
224
225 /*** Identity handling ***/
226
227 QList<IdentityId> Client::identityIds() {
228   return instance()->_identities.keys();
229 }
230
231 const Identity *Client::identity(IdentityId id) {
232   if(instance()->_identities.contains(id)) return instance()->_identities[id];
233   else return 0;
234 }
235
236 void Client::createIdentity(const CertIdentity &id) {
237   QVariantMap additional;
238 #ifdef HAVE_SSL
239   additional["KeyPem"] = id.sslKey().toPem();
240   additional["CertPem"] = id.sslCert().toPem();
241 #endif
242   emit instance()->requestCreateIdentity(id, additional);
243 }
244
245 void Client::updateIdentity(IdentityId id, const QVariantMap &ser) {
246   Identity *idptr = instance()->_identities.value(id, 0);
247   if(!idptr) {
248     qWarning() << "Update for unknown identity requested:" << id;
249     return;
250   }
251   idptr->requestUpdate(ser);
252 }
253
254 void Client::removeIdentity(IdentityId id) {
255   emit instance()->requestRemoveIdentity(id);
256 }
257
258 void Client::coreIdentityCreated(const Identity &other) {
259   if(!_identities.contains(other.id())) {
260     Identity *identity = new Identity(other, this);
261     _identities[other.id()] = identity;
262     identity->setInitialized();
263     signalProxy()->synchronize(identity);
264     emit identityCreated(other.id());
265   } else {
266     qWarning() << tr("Identity already exists in client!");
267   }
268 }
269
270 void Client::coreIdentityRemoved(IdentityId id) {
271   if(_identities.contains(id)) {
272     emit identityRemoved(id);
273     Identity *i = _identities.take(id);
274     i->deleteLater();
275   }
276 }
277
278 /*** User input handling ***/
279
280 void Client::userInput(const BufferInfo &bufferInfo, const QString &message) {
281   // we need to make sure that AliasManager is ready before processing input
282   if(aliasManager() && aliasManager()->isInitialized())
283     inputHandler()->handleUserInput(bufferInfo, message);
284   else
285    instance()-> _userInputBuffer.append(qMakePair(bufferInfo, message));
286 }
287
288 void Client::sendBufferedUserInput() {
289   for(int i = 0; i < _userInputBuffer.count(); i++)
290     userInput(_userInputBuffer.at(i).first, _userInputBuffer.at(i).second);
291
292   _userInputBuffer.clear();
293 }
294
295 /*** core connection stuff ***/
296
297 void Client::setConnectedToCore(AccountId id, QIODevice *socket) {
298   if(socket) { // external core
299     // if the socket is an orphan, the signalProxy adopts it.
300     // -> we don't need to care about it anymore
301     socket->setParent(0);
302     signalProxy()->addPeer(socket);
303   }
304   _internalCore = !socket;
305   _connectedToCore = true;
306   setCurrentCoreAccount(id);
307 }
308
309 void Client::setSyncedToCore() {
310   // create buffersyncer
311   Q_ASSERT(!_bufferSyncer);
312   _bufferSyncer = new BufferSyncer(this);
313   connect(bufferSyncer(), SIGNAL(lastSeenMsgSet(BufferId, MsgId)), _networkModel, SLOT(setLastSeenMsgId(BufferId, MsgId)));
314   connect(bufferSyncer(), SIGNAL(bufferRemoved(BufferId)), this, SLOT(bufferRemoved(BufferId)));
315   connect(bufferSyncer(), SIGNAL(bufferRenamed(BufferId, QString)), this, SLOT(bufferRenamed(BufferId, QString)));
316   connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), this, SLOT(buffersPermanentlyMerged(BufferId, BufferId)));
317   connect(bufferSyncer(), SIGNAL(buffersPermanentlyMerged(BufferId, BufferId)), _messageModel, SLOT(buffersPermanentlyMerged(BufferId, BufferId)));
318   connect(networkModel(), SIGNAL(setLastSeenMsg(BufferId, MsgId)), bufferSyncer(), SLOT(requestSetLastSeenMsg(BufferId, const MsgId &)));
319   signalProxy()->synchronize(bufferSyncer());
320
321   // create a new BufferViewManager
322   Q_ASSERT(!_bufferViewManager);
323   _bufferViewManager = new ClientBufferViewManager(signalProxy(), this);
324   connect(bufferViewManager(), SIGNAL(initDone()), this, SLOT(createDefaultBufferView()));
325
326   // create AliasManager
327   Q_ASSERT(!_aliasManager);
328   _aliasManager = new ClientAliasManager(this);
329   connect(aliasManager(), SIGNAL(initDone()), SLOT(sendBufferedUserInput()));
330   signalProxy()->synchronize(aliasManager());
331
332   // trigger backlog request once all active bufferviews are initialized
333   connect(bufferViewOverlay(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
334
335   _syncedToCore = true;
336   emit connected();
337   emit coreConnectionStateChanged(true);
338 }
339
340 void Client::requestInitialBacklog() {
341   // usually it _should_ take longer until the bufferViews are initialized, so that's what
342   // triggers this slot. But we have to make sure that we know all buffers yet.
343   // so we check the BufferSyncer and in case it wasn't initialized we wait for that instead
344   if(!bufferSyncer()->isInitialized()) {
345     connect(bufferViewOverlay(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
346     connect(bufferSyncer(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
347     return;
348   }
349   _backlogManager->requestInitialBacklog();
350 }
351
352 void Client::createDefaultBufferView() {
353   if(bufferViewManager()->bufferViewConfigs().isEmpty()) {
354     BufferViewConfig config(-1);
355     config.setBufferViewName(tr("All Buffers"));
356     config.initSetBufferList(networkModel()->allBufferIdsSorted());
357     bufferViewManager()->requestCreateBufferView(config.toVariantMap());
358   }
359 }
360
361 void Client::disconnectFromCore() {
362   if(!isConnected())
363     return;
364
365   signalProxy()->removeAllPeers();
366 }
367
368 void Client::disconnectedFromCore() {
369   _connectedToCore = false;
370   _syncedToCore = false;
371   emit disconnected();
372   emit coreConnectionStateChanged(false);
373
374   backlogManager()->reset();
375   messageProcessor()->reset();
376
377   // Clear internal data. Hopefully nothing relies on it at this point.
378   setCurrentCoreAccount(0);
379
380   if(_bufferSyncer) {
381     _bufferSyncer->deleteLater();
382     _bufferSyncer = 0;
383   }
384
385   if(_bufferViewManager) {
386     _bufferViewManager->deleteLater();
387     _bufferViewManager = 0;
388   }
389
390   if(_aliasManager) {
391     _aliasManager->deleteLater();
392     _aliasManager = 0;
393   }
394
395   // we probably don't want to save pending input for reconnect
396   _userInputBuffer.clear();
397
398   _messageModel->clear();
399   _networkModel->clear();
400
401   QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
402   while(netIter != _networks.end()) {
403     Network *net = netIter.value();
404     emit networkRemoved(net->networkId());
405     disconnect(net, SIGNAL(destroyed()), this, 0);
406     netIter = _networks.erase(netIter);
407     net->deleteLater();
408   }
409   Q_ASSERT(_networks.isEmpty());
410
411   QHash<IdentityId, Identity *>::iterator idIter = _identities.begin();
412   while(idIter != _identities.end()) {
413     emit identityRemoved(idIter.key());
414     Identity *id = idIter.value();
415     idIter = _identities.erase(idIter);
416     id->deleteLater();
417   }
418   Q_ASSERT(_identities.isEmpty());
419
420 }
421
422 /*** ***/
423
424 void Client::networkDestroyed() {
425   Network *net = static_cast<Network *>(sender());
426   QHash<NetworkId, Network *>::iterator netIter = _networks.begin();
427   while(netIter != _networks.end()) {
428     if(*netIter == net) {
429       netIter = _networks.erase(netIter);
430       break;
431     } else {
432       netIter++;
433     }
434   }
435 }
436
437 // Hmm... we never used this...
438 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
439   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
440 }
441
442 void Client::recvMessage(const Message &msg) {
443   Message msg_ = msg;
444   messageProcessor()->process(msg_);
445 }
446
447 void Client::setBufferLastSeenMsg(BufferId id, const MsgId &msgId) {
448   if(!bufferSyncer())
449     return;
450   bufferSyncer()->requestSetLastSeenMsg(id, msgId);
451 }
452
453 void Client::removeBuffer(BufferId id) {
454   if(!bufferSyncer()) return;
455   bufferSyncer()->requestRemoveBuffer(id);
456 }
457
458 void Client::renameBuffer(BufferId bufferId, const QString &newName) {
459   if(!bufferSyncer())
460     return;
461   bufferSyncer()->requestRenameBuffer(bufferId, newName);
462 }
463
464 void Client::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2) {
465   if(!bufferSyncer())
466     return;
467   bufferSyncer()->requestMergeBuffersPermanently(bufferId1, bufferId2);
468 }
469
470 void Client::purgeKnownBufferIds() {
471   if(!bufferSyncer())
472     return;
473   bufferSyncer()->requestPurgeBufferIds();
474 }
475
476 void Client::bufferRemoved(BufferId bufferId) {
477   // select a sane buffer (status buffer)
478   /* we have to manually select a buffer because otherwise inconsitent changes
479    * to the model might occur:
480    * the result of a buffer removal triggers a change in the selection model.
481    * the newly selected buffer might be a channel that hasn't been selected yet
482    * and a new nickview would be created (which never heard of the "rowsAboutToBeRemoved").
483    * this new view (and/or) its sort filter will then only receive a "rowsRemoved" signal.
484    */
485   QModelIndex current = bufferModel()->currentIndex();
486   if(current.data(NetworkModel::BufferIdRole).value<BufferId>() == bufferId) {
487     bufferModel()->setCurrentIndex(current.sibling(0,0));
488   }
489
490   // and remove it from the model
491   networkModel()->removeBuffer(bufferId);
492 }
493
494 void Client::bufferRenamed(BufferId bufferId, const QString &newName) {
495   QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId);
496   if(bufferIndex.isValid()) {
497     networkModel()->setData(bufferIndex, newName, Qt::DisplayRole);
498   }
499 }
500
501 void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) {
502   QModelIndex idx = networkModel()->bufferIndex(bufferId1);
503   bufferModel()->setCurrentIndex(bufferModel()->mapFromSource(idx));
504   networkModel()->removeBuffer(bufferId2);
505 }
506
507 void Client::logMessage(QtMsgType type, const char *msg) {
508   fprintf(stderr, "%s\n", msg);
509   fflush(stderr);
510   if(type == QtFatalMsg) {
511     Quassel::logFatalMessage(msg);
512   } else {
513     QString msgString = QString("%1\n").arg(msg);
514
515     //Check to see if there is an instance around, else we risk recursions
516     //when calling instance() and creating new ones.
517     if (!instanceExists())
518       return;
519
520     instance()->_debugLog << msgString;
521     emit instance()->logUpdated(msgString);
522   }
523 }
524