Fixing backlog timestamps when merging from sqlite.
[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   connect(bufferViewManager(), SIGNAL(viewsInitialized()), this, SLOT(requestInitialBacklog()));
326
327   // create AliasManager
328   Q_ASSERT(!_aliasManager);
329   _aliasManager = new ClientAliasManager(this);
330   connect(aliasManager(), SIGNAL(initDone()), SLOT(sendBufferedUserInput()));
331   signalProxy()->synchronize(aliasManager());
332
333   _syncedToCore = true;
334   emit connected();
335   emit coreConnectionStateChanged(true);
336 }
337
338 void Client::requestInitialBacklog() {
339   // usually it _should_ take longer until the bufferViews are initialized, so that's what
340   // triggers this slot. But we have to make sure that we know all buffers yet.
341   // so we check the BufferSyncer and in case it wasn't initialized we wait for that instead
342   if(!bufferSyncer()->isInitialized()) {
343     disconnect(bufferViewManager(), SIGNAL(viewsInitialized()), this, SLOT(requestInitialBacklog()));
344     connect(bufferSyncer(), SIGNAL(initDone()), this, SLOT(requestInitialBacklog()));
345     return;
346   }
347   _backlogManager->requestInitialBacklog();
348 }
349
350 void Client::createDefaultBufferView() {
351   if(bufferViewManager()->bufferViewConfigs().isEmpty()) {
352     BufferViewConfig config(-1);
353     config.setBufferViewName(tr("All Buffers"));
354     config.initSetBufferList(networkModel()->allBufferIdsSorted());
355     bufferViewManager()->requestCreateBufferView(config.toVariantMap());
356   }
357 }
358
359 void Client::disconnectFromCore() {
360   if(!isConnected())
361     return;
362
363   signalProxy()->removeAllPeers();
364 }
365
366 void Client::disconnectedFromCore() {
367   _connectedToCore = false;
368   _syncedToCore = false;
369   emit disconnected();
370   emit coreConnectionStateChanged(false);
371
372   backlogManager()->reset();
373   messageProcessor()->reset();
374
375   // Clear internal data. Hopefully nothing relies on it at this point.
376   setCurrentCoreAccount(0);
377
378   if(_bufferSyncer) {
379     _bufferSyncer->deleteLater();
380     _bufferSyncer = 0;
381   }
382
383   if(_bufferViewManager) {
384     _bufferViewManager->deleteLater();
385     _bufferViewManager = 0;
386   }
387
388   if(_aliasManager) {
389     _aliasManager->deleteLater();
390     _aliasManager = 0;
391   }
392
393   // we probably don't want to save pending input for reconnect
394   _userInputBuffer.clear();
395
396   _messageModel->clear();
397   _networkModel->clear();
398
399   QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
400   while(netIter != _networks.end()) {
401     Network *net = netIter.value();
402     emit networkRemoved(net->networkId());
403     disconnect(net, SIGNAL(destroyed()), this, 0);
404     netIter = _networks.erase(netIter);
405     net->deleteLater();
406   }
407   Q_ASSERT(_networks.isEmpty());
408
409   QHash<IdentityId, Identity *>::iterator idIter = _identities.begin();
410   while(idIter != _identities.end()) {
411     emit identityRemoved(idIter.key());
412     Identity *id = idIter.value();
413     idIter = _identities.erase(idIter);
414     id->deleteLater();
415   }
416   Q_ASSERT(_identities.isEmpty());
417
418 }
419
420 /*** ***/
421
422 void Client::networkDestroyed() {
423   Network *net = static_cast<Network *>(sender());
424   QHash<NetworkId, Network *>::iterator netIter = _networks.begin();
425   while(netIter != _networks.end()) {
426     if(*netIter == net) {
427       netIter = _networks.erase(netIter);
428       break;
429     } else {
430       netIter++;
431     }
432   }
433 }
434
435 // Hmm... we never used this...
436 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
437   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
438 }
439
440 void Client::recvMessage(const Message &msg) {
441   Message msg_ = msg;
442   messageProcessor()->process(msg_);
443 }
444
445 void Client::setBufferLastSeenMsg(BufferId id, const MsgId &msgId) {
446   if(!bufferSyncer())
447     return;
448   bufferSyncer()->requestSetLastSeenMsg(id, msgId);
449 }
450
451 void Client::removeBuffer(BufferId id) {
452   if(!bufferSyncer()) return;
453   bufferSyncer()->requestRemoveBuffer(id);
454 }
455
456 void Client::renameBuffer(BufferId bufferId, const QString &newName) {
457   if(!bufferSyncer())
458     return;
459   bufferSyncer()->requestRenameBuffer(bufferId, newName);
460 }
461
462 void Client::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2) {
463   if(!bufferSyncer())
464     return;
465   bufferSyncer()->requestMergeBuffersPermanently(bufferId1, bufferId2);
466 }
467
468 void Client::purgeKnownBufferIds() {
469   if(!bufferSyncer())
470     return;
471   bufferSyncer()->requestPurgeBufferIds();
472 }
473
474 void Client::bufferRemoved(BufferId bufferId) {
475   // select a sane buffer (status buffer)
476   /* we have to manually select a buffer because otherwise inconsitent changes
477    * to the model might occur:
478    * the result of a buffer removal triggers a change in the selection model.
479    * the newly selected buffer might be a channel that hasn't been selected yet
480    * and a new nickview would be created (which never heard of the "rowsAboutToBeRemoved").
481    * this new view (and/or) its sort filter will then only receive a "rowsRemoved" signal.
482    */
483   QModelIndex current = bufferModel()->currentIndex();
484   if(current.data(NetworkModel::BufferIdRole).value<BufferId>() == bufferId) {
485     bufferModel()->setCurrentIndex(current.sibling(0,0));
486   }
487
488   // and remove it from the model
489   networkModel()->removeBuffer(bufferId);
490 }
491
492 void Client::bufferRenamed(BufferId bufferId, const QString &newName) {
493   QModelIndex bufferIndex = networkModel()->bufferIndex(bufferId);
494   if(bufferIndex.isValid()) {
495     networkModel()->setData(bufferIndex, newName, Qt::DisplayRole);
496   }
497 }
498
499 void Client::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) {
500   QModelIndex idx = networkModel()->bufferIndex(bufferId1);
501   bufferModel()->setCurrentIndex(bufferModel()->mapFromSource(idx));
502   networkModel()->removeBuffer(bufferId2);
503 }
504
505 void Client::logMessage(QtMsgType type, const char *msg) {
506   fprintf(stderr, "%s\n", msg);
507   fflush(stderr);
508   if(type == QtFatalMsg) {
509     Quassel::logFatalMessage(msg);
510   } else {
511     QString msgString = QString("%1\n").arg(msg);
512
513     //Check to see if there is an instance around, else we risk recursions
514     //when calling instance() and creating new ones.
515     if (!instanceExists())
516       return;
517
518     instance()->_debugLog << msgString;
519     emit instance()->logUpdated(msgString);
520   }
521 }
522