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