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