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