Added a context menu to users
[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 "bufferinfo.h"
24 #include "global.h"
25 #include "identity.h"
26 #include "ircchannel.h"
27 #include "ircuser.h"
28 #include "message.h"
29 #include "network.h"
30 #include "networkmodel.h"
31 #include "buffermodel.h"
32 #include "nickmodel.h"
33 #include "quasselui.h"
34 #include "signalproxy.h"
35 #include "util.h"
36
37 QPointer<Client> Client::instanceptr = 0;
38
39 /*** Initialization/destruction ***/
40
41 Client *Client::instance() {
42   if(!instanceptr)
43     instanceptr = new Client();
44   return instanceptr;
45 }
46
47 void Client::destroy() {
48   //delete instanceptr;
49   instanceptr->deleteLater();
50 }
51
52 void Client::init(AbstractUi *ui) {
53   instance()->mainUi = ui;
54   instance()->init();
55 }
56
57 Client::Client(QObject *parent)
58   : QObject(parent),
59     socket(0),
60     _signalProxy(new SignalProxy(SignalProxy::Client, this)),
61     mainUi(0),
62     _networkModel(0),
63     _bufferModel(0),
64     _nickModel(0),
65     _connectedToCore(false),
66     _syncedToCore(false)
67 {
68 }
69
70 Client::~Client() {
71   disconnectFromCore();
72 }
73
74 void Client::init() {
75
76   _networkModel = new NetworkModel(this);
77   connect(this, SIGNAL(bufferUpdated(BufferInfo)),
78           _networkModel, SLOT(bufferUpdated(BufferInfo)));
79
80   _bufferModel = new BufferModel(_networkModel);
81   _nickModel = new NickModel(_networkModel);
82
83   SignalProxy *p = signalProxy();
84   p->attachSignal(this, SIGNAL(sendSessionData(const QString &, const QVariant &)),
85                   SIGNAL(clientSessionDataChanged(const QString &, const QVariant &)));
86   p->attachSlot(SIGNAL(coreSessionDataChanged(const QString &, const QVariant &)),
87                 this, SLOT(recvSessionData(const QString &, const QVariant &)));
88   //p->attachSlot(SIGNAL(networkConnected(uint)),
89   //FIXME              this, SLOT(networkConnected(uint)));
90   //p->attachSlot(SIGNAL(networkDisconnected(uint)),
91   //FIXME              this, SLOT(networkDisconnected(uint)));
92   p->attachSlot(SIGNAL(displayMsg(const Message &)),
93                 this, SLOT(recvMessage(const Message &)));
94   p->attachSlot(SIGNAL(displayStatusMsg(QString, QString)),
95                 this, SLOT(recvStatusMsg(QString, QString)));
96
97
98   p->attachSlot(SIGNAL(backlogData(BufferInfo, const QVariantList &, bool)), this, SLOT(recvBacklogData(BufferInfo, const QVariantList &, bool)));
99   p->attachSlot(SIGNAL(bufferInfoUpdated(BufferInfo)), this, SLOT(updateBufferInfo(BufferInfo)));
100   p->attachSignal(this, SIGNAL(sendInput(BufferInfo, QString)));
101   p->attachSignal(this, SIGNAL(requestNetworkStates()));
102
103   p->attachSignal(this, SIGNAL(requestCreateIdentity(const Identity &)), SIGNAL(createIdentity(const Identity &)));
104   p->attachSignal(this, SIGNAL(requestUpdateIdentity(const Identity &)), SIGNAL(updateIdentity(const Identity &)));
105   p->attachSignal(this, SIGNAL(requestRemoveIdentity(IdentityId)), SIGNAL(removeIdentity(IdentityId)));
106   p->attachSlot(SIGNAL(identityCreated(const Identity &)), this, SLOT(coreIdentityCreated(const Identity &)));
107   p->attachSlot(SIGNAL(identityRemoved(IdentityId)), this, SLOT(coreIdentityRemoved(IdentityId)));
108
109   connect(p, SIGNAL(disconnected()), this, SLOT(disconnectFromCore()));
110
111   //connect(mainUi, SIGNAL(connectToCore(const QVariantMap &)), this, SLOT(connectToCore(const QVariantMap &)));
112   connect(mainUi, SIGNAL(disconnectFromCore()), this, SLOT(disconnectFromCore()));
113   connect(this, SIGNAL(connected()), mainUi, SLOT(connectedToCore()));
114   connect(this, SIGNAL(disconnected()), mainUi, SLOT(disconnectedFromCore()));
115
116   layoutTimer = new QTimer(this);
117   layoutTimer->setInterval(0);
118   layoutTimer->setSingleShot(false);
119   connect(layoutTimer, SIGNAL(timeout()), this, SLOT(layoutMsg()));
120
121 }
122
123 /*** public static methods ***/
124
125 QList<BufferInfo> Client::allBufferInfos() {
126   QList<BufferInfo> bufferids;
127   foreach(Buffer *buffer, buffers()) {
128     bufferids << buffer->bufferInfo();
129   }
130   return bufferids;
131 }
132
133 QList<Buffer *> Client::buffers() {
134   return instance()->_buffers.values();
135 }
136
137
138 // FIXME remove
139 Buffer *Client::buffer(BufferId bufferUid) {
140   if(instance()->_buffers.contains(bufferUid))
141     return instance()->_buffers[bufferUid];
142   else
143     return 0;
144 }
145
146 // FIXME remove
147 Buffer *Client::buffer(BufferInfo id) {
148   Buffer *buff = buffer(id.uid());
149
150   if(!buff) {
151     Client *client = Client::instance();
152     buff = new Buffer(id, client);
153
154     connect(buff, SIGNAL(userInput(BufferInfo, QString)),
155             client, SLOT(userInput(BufferInfo, QString)));
156     connect(buff, SIGNAL(destroyed()),
157             client, SLOT(bufferDestroyed()));
158     client->_buffers[id.uid()] = buff;
159     emit client->bufferUpdated(id);
160   }
161   Q_ASSERT(buff);
162   return buff;
163 }
164
165
166 NetworkModel *Client::networkModel() {
167   return instance()->_networkModel;
168 }
169
170 BufferModel *Client::bufferModel() {
171   return instance()->_bufferModel;
172 }
173
174 NickModel *Client::nickModel() {
175   return instance()->_nickModel;
176 }
177
178
179 SignalProxy *Client::signalProxy() {
180   return instance()->_signalProxy;
181 }
182
183 bool Client::isConnected() {
184   return instance()->_connectedToCore;
185 }
186
187 bool Client::isSynced() {
188   return instance()->_syncedToCore;
189 }
190
191 /*** Network handling ***/
192
193 QList<NetworkId> Client::networkIds() {
194   return instance()->_networks.keys();
195 }
196
197 const Network * Client::network(NetworkId networkid) {
198   if(instance()->_networks.contains(networkid)) return instance()->_networks[networkid];
199   else return 0;
200 }
201
202 /*** Identity handling ***/
203
204 QList<IdentityId> Client::identityIds() {
205   return instance()->_identities.keys();
206 }
207
208 const Identity * Client::identity(IdentityId id) {
209   if(instance()->_identities.contains(id)) return instance()->_identities[id];
210   else return 0;
211 }
212
213 void Client::createIdentity(const Identity &id) {
214   emit instance()->requestCreateIdentity(id);
215 }
216
217 void Client::updateIdentity(const Identity &id) {
218   emit instance()->requestUpdateIdentity(id);
219 }
220
221 void Client::removeIdentity(IdentityId id) {
222   emit instance()->requestRemoveIdentity(id);
223 }
224
225 void Client::coreIdentityCreated(const Identity &other) {
226   if(!_identities.contains(other.id())) {
227     Identity *identity = new Identity(other, this);
228     _identities[other.id()] = identity;
229     identity->setInitialized();
230     signalProxy()->synchronize(identity);
231     emit identityCreated(other.id());
232   } else {
233     qWarning() << tr("Identity already exists in client!");
234   }
235 }
236
237 void Client::coreIdentityRemoved(IdentityId id) {
238   if(_identities.contains(id)) {
239     emit identityRemoved(id);
240     Identity *i = _identities.take(id);
241     i->deleteLater();
242   }
243 }
244
245 /***  ***/
246
247 void Client::fakeInput(BufferId bufferUid, QString message) {
248   Buffer *buff = buffer(bufferUid);
249   if(!buff)
250     qWarning() << "No Buffer with uid" << bufferUid << "can't send Input" << message;
251   else
252     instance()->userInput(buff->bufferInfo(), message);
253 }
254
255 /*** core connection stuff ***/
256
257 void Client::setConnectedToCore(QIODevice *sock) {
258   socket = sock;
259   signalProxy()->addPeer(socket);
260   _connectedToCore = true;
261 }
262
263 void Client::setSyncedToCore() {
264   _syncedToCore = true;
265   emit connected();
266   emit coreConnectionStateChanged(true);
267 }
268
269 void Client::disconnectFromCore() {
270   if(socket) {
271     socket->close();
272     socket->deleteLater();
273   }
274   _connectedToCore = false;
275   _syncedToCore = false;
276   emit disconnected();
277   emit coreConnectionStateChanged(false);
278
279   // Clear internal data. Hopefully nothing relies on it at this point.
280   _networkModel->clear();
281
282   QHash<NetworkId, Network*>::iterator netIter = _networks.begin();
283   while(netIter != _networks.end()) {
284     Network *net = netIter.value();
285     disconnect(net, SIGNAL(destroyed()), this, 0);
286     netIter = _networks.erase(netIter);
287     net->deleteLater();
288   }
289   Q_ASSERT(_networks.isEmpty());
290
291   QHash<BufferId, Buffer *>::iterator bufferIter =  _buffers.begin();
292   while(bufferIter != _buffers.end()) {
293     Buffer *buffer = bufferIter.value();
294     disconnect(buffer, SIGNAL(destroyed()), this, 0);
295     bufferIter = _buffers.erase(bufferIter);
296     buffer->deleteLater();
297   }
298   Q_ASSERT(_buffers.isEmpty());
299
300   QHash<IdentityId, Identity*>::iterator idIter = _identities.begin();
301   while(idIter != _identities.end()) {
302     Identity *id = idIter.value();
303     emit identityRemoved(id->id());
304     idIter = _identities.erase(idIter);
305     id->deleteLater();
306   }
307   Q_ASSERT(_identities.isEmpty());
308
309   sessionData.clear();
310   layoutQueue.clear();
311   layoutTimer->stop();
312 }
313
314 void Client::setCoreConfiguration(const QVariantMap &settings) {
315   SignalProxy::writeDataToDevice(socket, settings);
316 }
317
318 /*** Session data ***/
319
320 void Client::recvSessionData(const QString &key, const QVariant &data) {
321   sessionData[key] = data;
322   emit sessionDataChanged(key, data);
323   emit sessionDataChanged(key);
324 }
325
326 void Client::storeSessionData(const QString &key, const QVariant &data) {
327   // Not sure if this is a good idea, but we'll try it anyway:
328   // Calling this function only sends a signal to core. Data is stored upon reception of the update signal,
329   // rather than immediately.
330   emit instance()->sendSessionData(key, data);
331 }
332
333 QVariant Client::retrieveSessionData(const QString &key, const QVariant &def) {
334   if(instance()->sessionData.contains(key)) return instance()->sessionData[key];
335   else return def;
336 }
337
338 QStringList Client::sessionDataKeys() {
339   return instance()->sessionData.keys();
340 }
341
342 /*** ***/
343
344 /*
345 void Client::networkConnected(uint netid) {
346   // TODO: create statusBuffer / switch to networkids
347   //BufferInfo id = statusBufferInfo(net);
348   //Buffer *b = buffer(id);
349   //b->setActive(true);
350
351   Network *netinfo = new Network(netid, this);
352   netinfo->setProxy(signalProxy());
353   networkModel()->attachNetwork(netinfo);
354   connect(netinfo, SIGNAL(destroyed()), this, SLOT(networkDestroyed()));
355   _networks[netid] = netinfo;
356 }
357
358 void Client::networkDisconnected(NetworkId networkid) {
359   if(!_networks.contains(networkid)) {
360     qWarning() << "Client::networkDisconnected(uint): unknown Network" << networkid;
361     return;
362   }
363
364   Network *net = _networks.take(networkid);
365   if(!net->isInitialized()) {
366     qDebug() << "Network" << networkid << "disconnected while not yet initialized!";
367     updateCoreConnectionProgress();
368   }
369   net->deleteLater();
370 }
371 */
372
373 void Client::addNetwork(NetworkId netid) {
374   Network *net = new Network(netid, instance());
375   addNetwork(net);
376 }
377
378 void Client::addNetwork(Network *net) {
379   net->setProxy(signalProxy());
380   signalProxy()->synchronize(net);
381   networkModel()->attachNetwork(net);
382   connect(net, SIGNAL(destroyed()), instance(), SLOT(networkDestroyed()));
383   instance()->_networks[net->networkId()] = net;
384   emit instance()->networkAdded(net->networkId());
385   //if(net->networkId() == 1) net->requestConnect(); // FIXME
386 }
387
388 /*** ***/
389
390 void Client::updateBufferInfo(BufferInfo id) {
391   emit bufferUpdated(id);
392 }
393
394 void Client::bufferDestroyed() {
395   Buffer *buffer = static_cast<Buffer *>(sender());
396   QHash<BufferId, Buffer *>::iterator iter = _buffers.begin();
397   while(iter != _buffers.end()) {
398     if(iter.value() == buffer) {
399       iter = _buffers.erase(iter);
400       break;
401     }
402     iter++;
403   }
404 }
405
406 void Client::networkDestroyed() {
407   Network *netinfo = static_cast<Network *>(sender());
408   NetworkId networkId = netinfo->networkId();
409   if(_networks.contains(networkId))
410     _networks.remove(networkId);
411 }
412
413 void Client::recvMessage(const Message &msg) {
414   Buffer *b = buffer(msg.buffer());
415
416 //   Buffer::ActivityLevel level = Buffer::OtherActivity;
417 //   if(msg.type() == Message::Plain || msg.type() == Message::Notice){
418 //     level |= Buffer::NewMessage;
419 //   }
420 //   if(msg.flags() & Message::Highlight){
421 //     level |= Buffer::Highlight;
422 //   }
423 //   emit bufferActivity(level, b);
424
425   b->appendMsg(msg);
426 }
427
428 void Client::recvStatusMsg(QString /*net*/, QString /*msg*/) {
429   //recvMessage(net, Message::server("", QString("[STATUS] %1").arg(msg)));
430 }
431
432 void Client::recvBacklogData(BufferInfo id, QVariantList msgs, bool /*done*/) {
433   Buffer *b = buffer(id);
434   foreach(QVariant v, msgs) {
435     Message msg = v.value<Message>();
436     b->prependMsg(msg);
437     if(!layoutQueue.contains(b)) layoutQueue.append(b);
438   }
439   if(layoutQueue.count() && !layoutTimer->isActive()) layoutTimer->start();
440 }
441
442 void Client::layoutMsg() {
443   if(layoutQueue.count()) {
444     Buffer *b = layoutQueue.takeFirst();  // TODO make this the current buffer
445     if(b->layoutMsg())
446       layoutQueue.append(b);  // Buffer has more messages in its queue --> Round Robin
447   }
448   
449   if(!layoutQueue.count())
450     layoutTimer->stop();
451 }
452
453 AbstractUiMsg *Client::layoutMsg(const Message &msg) {
454   return instance()->mainUi->layoutMsg(msg);
455 }
456
457 void Client::userInput(BufferInfo id, QString msg) {
458   emit sendInput(id, msg);
459 }
460