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