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