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