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