Since we're going for one grand unified model to store all the stuff
[quassel.git] / src / client / networkmodel.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-07 by the Quassel IRC Team                         *
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 <QColor>  // FIXME Dependency on QtGui!
22
23 #include "networkmodel.h"
24
25 #include "mappedselectionmodel.h"
26 #include <QAbstractItemView>
27
28 #include "bufferinfo.h"
29 #include "client.h"
30 #include "signalproxy.h"
31 #include "networkinfo.h"
32 #include "ircchannel.h"
33 #include "ircuser.h"
34
35 /*****************************************
36 *  Fancy Buffer Items
37 *****************************************/
38 BufferItem::BufferItem(Buffer *buffer, AbstractTreeItem *parent)
39   : PropertyMapItem(QStringList() << "bufferName" << "topic" << "nickCount", parent),
40     buf(buffer),
41     activity(Buffer::NoActivity)
42 {
43   Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;
44   if(buf->bufferType() == Buffer::QueryType)
45     flags |= Qt::ItemIsDropEnabled;
46   setFlags(flags);
47 }
48
49 quint64 BufferItem::id() const {
50   return buf->bufferInfo().uid();
51 }
52
53 void BufferItem::setActivity(const Buffer::ActivityLevel &level) {
54   activity = level;
55 }
56
57 QColor BufferItem::foreground(int column) const {
58   Q_UNUSED(column)
59   // for the time beeing we ignore the column :)
60   if(activity & Buffer::Highlight) {
61     return QColor(Qt::red);
62   } else if(activity & Buffer::NewMessage) {
63     return QColor(Qt::darkYellow);
64   } else if(activity & Buffer::OtherActivity) {
65     return QColor(Qt::darkGreen);
66   } else {
67     if(buf->isActive())
68       return QColor(Qt::black);
69     else
70       return QColor(Qt::gray);
71   }
72 }
73
74 QVariant BufferItem::data(int column, int role) const {
75   switch(role) {
76   case NetworkModel::ItemTypeRole:
77     return NetworkModel::BufferItemType;
78   case NetworkModel::BufferUidRole:
79     return buf->bufferInfo().uid();
80   case NetworkModel::NetworkIdRole:
81     return buf->bufferInfo().networkId();
82   case NetworkModel::BufferTypeRole:
83     return int(buf->bufferType());
84   case NetworkModel::BufferActiveRole:
85     return buf->isActive();
86   case Qt::ForegroundRole:
87     return foreground(column);
88   default:
89     return PropertyMapItem::data(column, role);
90   }
91 }
92
93 void BufferItem::attachIrcChannel(IrcChannel *ircChannel) {
94   if(!ircChannel)
95     return;
96   
97   _ircChannel = ircChannel;
98
99   connect(ircChannel, SIGNAL(topicSet(QString)),
100           this, SLOT(setTopic(QString)));
101   connect(ircChannel, SIGNAL(ircUserJoined(IrcUser *)),
102           this, SLOT(join(IrcUser *)));
103   connect(ircChannel, SIGNAL(ircUserParted(IrcUser *)),
104           this, SLOT(part(IrcUser *)));
105 }
106
107 QString BufferItem::bufferName() const {
108   return buf->name();
109 }
110
111 QString BufferItem::topic() const {
112   if(_ircChannel)
113     return _ircChannel->topic();
114   else
115     return QString();
116 }
117
118 int BufferItem::nickCount() const {
119   if(_ircChannel)
120     return _ircChannel->ircUsers().count();
121   else
122     return 0;
123 }
124
125 void BufferItem::setTopic(const QString &topic) {
126   Q_UNUSED(topic);
127   emit dataChanged(1);
128 }
129
130 void BufferItem::join(IrcUser *ircUser) {
131 //   emit newChild(new IrcUserItem(ircUser, this));
132 //   emit dataChanged(2);
133 }
134
135 void BufferItem::part(IrcUser *ircUser) {
136   Q_UNUSED(ircUser);
137   emit dataChanged(2);
138 }
139
140 /*****************************************
141 *  Network Items
142 *****************************************/
143 NetworkItem::NetworkItem(const uint &netid, const QString &network, AbstractTreeItem *parent)
144   : PropertyMapItem(QList<QString>() << "networkName" << "currentServer" << "nickCount", parent),
145     _networkId(netid),
146     _networkName(network)
147 {
148   setFlags(Qt::ItemIsEnabled);
149 }
150
151 QVariant NetworkItem::data(int column, int role) const {
152   switch(role) {
153   case NetworkModel::NetworkIdRole:
154     return _networkId;
155   case NetworkModel::ItemTypeRole:
156     return NetworkModel::NetworkItemType;
157   default:
158     return PropertyMapItem::data(column, role);
159   }
160 }
161
162 quint64 NetworkItem::id() const {
163   return _networkId;
164 }
165
166 QString NetworkItem::networkName() const {
167   if(_networkInfo)
168     return _networkInfo->networkName();
169   else
170     return _networkName;
171 }
172
173 QString NetworkItem::currentServer() const {
174   if(_networkInfo)
175     return _networkInfo->currentServer();
176   else
177     return QString();
178 }
179
180 int NetworkItem::nickCount() const {
181   BufferItem *bufferItem;
182   int count = 0;
183   for(int i = 0; i < childCount(); i++) {
184     bufferItem = qobject_cast<BufferItem *>(child(i));
185     if(!bufferItem)
186       continue;
187     count += bufferItem->nickCount();
188   }
189   return count;
190 }
191
192 void NetworkItem::attachNetworkInfo(NetworkInfo *networkInfo) {
193   if(!networkInfo)
194     return;
195   
196   _networkInfo = networkInfo;
197
198   connect(networkInfo, SIGNAL(networkNameSet(QString)),
199           this, SLOT(setNetworkName(QString)));
200   connect(networkInfo, SIGNAL(currentServerSet(QString)),
201           this, SLOT(setCurrentServer(QString)));
202   connect(networkInfo, SIGNAL(ircChannelAdded(QString)),
203           this, SLOT(attachIrcChannel(QString)));
204   // FIXME: connect this and that...
205 }
206
207 void NetworkItem::attachIrcChannel(const QString &channelName) {
208   IrcChannel *ircChannel = _networkInfo->ircChannel(channelName);
209   if(!ircChannel) {
210     qWarning() << "NetworkItem::attachIrcChannel(): unkown Channel" << channelName;
211     return;
212   }
213   
214   BufferItem *bufferItem;
215   for(int i = 0; i < childCount(); i++) {
216     bufferItem = qobject_cast<BufferItem *>(child(i));
217     if(bufferItem->bufferName() == ircChannel->name()) {
218       bufferItem->attachIrcChannel(ircChannel);
219       break;
220     }
221   }
222 }
223
224 void NetworkItem::setNetworkName(const QString &networkName) {
225   Q_UNUSED(networkName);
226   emit dataChanged(0);
227 }
228
229 void NetworkItem::setCurrentServer(const QString &serverName) {
230   Q_UNUSED(serverName);
231   emit dataChanged(1);
232 }
233
234 /*****************************************
235 *  Irc User Items
236 *****************************************/
237 IrcUserItem::IrcUserItem(IrcUser *ircUser, AbstractTreeItem *parent)
238   : PropertyMapItem(QStringList() << "nickName", parent),
239     _ircUser(ircUser)
240 {
241   connect(ircUser, SIGNAL(destroyed()),
242           this, SLOT(ircUserDestroyed()));
243   
244   connect(ircUser, SIGNAL(nickSet(QString)),
245           this, SLOT(setNick(QString)));
246 }
247
248 QString IrcUserItem::nickName() {
249   return _ircUser->nick();
250 }
251
252 void IrcUserItem::setNick(QString newNick) {
253   Q_UNUSED(newNick);
254   emit dataChanged(0);
255 }
256 void IrcUserItem::ircUserDestroyed() {
257   deleteLater();
258 }
259
260
261 /*****************************************
262  * NetworkModel
263  *****************************************/
264 NetworkModel::NetworkModel(QObject *parent)
265   : TreeModel(NetworkModel::defaultHeader(), parent),
266     _selectionModelSynchronizer(new SelectionModelSynchronizer(this)),
267     _propertyMapper(new ModelPropertyMapper(this))
268 {
269   // initialize the Property Mapper
270   _propertyMapper->setModel(this);
271   delete _propertyMapper->selectionModel();
272   MappedSelectionModel *mappedSelectionModel = new MappedSelectionModel(this);
273   _propertyMapper->setSelectionModel(mappedSelectionModel);
274   synchronizeSelectionModel(mappedSelectionModel);
275   
276   connect(_selectionModelSynchronizer, SIGNAL(setCurrentIndex(QModelIndex, QItemSelectionModel::SelectionFlags)),
277           this, SLOT(setCurrentIndex(QModelIndex, QItemSelectionModel::SelectionFlags)));
278 }
279
280 QList<QVariant >NetworkModel::defaultHeader() {
281   QList<QVariant> data;
282   data << tr("Buffer") << tr("Topic") << tr("Nick Count");
283   return data;
284 }
285
286 void NetworkModel::synchronizeSelectionModel(MappedSelectionModel *selectionModel) {
287   selectionModelSynchronizer()->addSelectionModel(selectionModel);
288 }
289
290 void NetworkModel::synchronizeView(QAbstractItemView *view) {
291   MappedSelectionModel *mappedSelectionModel = new MappedSelectionModel(view->model());
292   selectionModelSynchronizer()->addSelectionModel(mappedSelectionModel);
293   Q_ASSERT(mappedSelectionModel);
294   delete view->selectionModel();
295   view->setSelectionModel(mappedSelectionModel);
296 }
297
298 void NetworkModel::mapProperty(int column, int role, QObject *target, const QByteArray &property) {
299   propertyMapper()->addMapping(column, role, target, property);
300 }
301
302 bool NetworkModel::isBufferIndex(const QModelIndex &index) const {
303   return index.data(NetworkModel::ItemTypeRole) == NetworkModel::BufferItemType;
304 }
305
306 Buffer *NetworkModel::getBufferByIndex(const QModelIndex &index) const {
307   BufferItem *item = static_cast<BufferItem *>(index.internalPointer());
308   // FIXME get rid of this
309   Q_ASSERT(item->buffer() == Client::instance()->buffer(item->id()));
310   return item->buffer();
311 }
312
313
314 // experimental stuff :)
315 QModelIndex NetworkModel::networkIndex(uint networkId) {
316   return indexById(networkId);
317 }
318
319 NetworkItem *NetworkModel::network(uint networkId) {
320   return qobject_cast<NetworkItem *>(rootItem->childById(networkId));
321 }
322
323 NetworkItem *NetworkModel::newNetwork(uint networkId, const QString &networkName) {
324   NetworkItem *networkItem = network(networkId);
325
326   if(networkItem == 0) {
327     networkItem = new NetworkItem(networkId, networkName, rootItem);
328     appendChild(rootItem, networkItem);
329   }
330
331   Q_ASSERT(networkItem);
332   return networkItem;
333 }
334
335 QModelIndex NetworkModel::bufferIndex(BufferInfo bufferInfo) {
336   QModelIndex networkIdx = networkIndex(bufferInfo.networkId());
337   if(!networkIdx.isValid())
338     return QModelIndex();
339   else
340     return indexById(bufferInfo.uid(), networkIdx);
341 }
342
343 BufferItem *NetworkModel::buffer(BufferInfo bufferInfo) {
344   QModelIndex bufferIdx = bufferIndex(bufferInfo);
345   if(bufferIdx.isValid())
346     return static_cast<BufferItem *>(bufferIdx.internalPointer());
347   else
348     return 0;
349 }
350
351 BufferItem *NetworkModel::newBuffer(BufferInfo bufferInfo) {
352   BufferItem *bufferItem = buffer(bufferInfo);
353   if(bufferItem == 0) {
354     NetworkItem *networkItem = newNetwork(bufferInfo.networkId(), bufferInfo.network());
355
356     // FIXME: get rid of the buffer pointer
357     Buffer *buffer = Client::instance()->buffer(bufferInfo.uid());
358     bufferItem = new BufferItem(buffer, networkItem);
359     appendChild(networkItem, bufferItem);
360   }
361
362   Q_ASSERT(bufferItem);
363   return bufferItem;
364 }
365
366 QStringList NetworkModel::mimeTypes() const {
367   // mimetypes we accept for drops
368   QStringList types;
369   // comma separated list of colon separated pairs of networkid and bufferid
370   // example: 0:1,0:2,1:4
371   types << "application/Quassel/BufferItemList";
372   return types;
373 }
374
375 bool NetworkModel::mimeContainsBufferList(const QMimeData *mimeData) {
376   return mimeData->hasFormat("application/Quassel/BufferItemList");
377 }
378
379 QList< QPair<uint, uint> > NetworkModel::mimeDataToBufferList(const QMimeData *mimeData) {
380   QList< QPair<uint, uint> > bufferList;
381
382   if(!mimeContainsBufferList(mimeData))
383     return bufferList;
384
385   QStringList rawBufferList = QString::fromAscii(mimeData->data("application/Quassel/BufferItemList")).split(",");
386   uint networkId, bufferUid;
387   foreach(QString rawBuffer, rawBufferList) {
388     if(!rawBuffer.contains(":"))
389       continue;
390     networkId = rawBuffer.section(":", 0, 0).toUInt();
391     bufferUid = rawBuffer.section(":", 1, 1).toUInt();
392     bufferList.append(qMakePair(networkId, bufferUid));
393   }
394   return bufferList;
395 }
396
397
398 QMimeData *NetworkModel::mimeData(const QModelIndexList &indexes) const {
399   QMimeData *mimeData = new QMimeData();
400
401   QStringList bufferlist;
402   QString netid, uid, bufferid;
403   foreach(QModelIndex index, indexes) {
404     netid = QString::number(index.data(NetworkIdRole).toUInt());
405     uid = QString::number(index.data(BufferUidRole).toUInt());
406     bufferid = QString("%1:%2").arg(netid).arg(uid);
407     if(!bufferlist.contains(bufferid))
408       bufferlist << bufferid;
409   }
410
411   mimeData->setData("application/Quassel/BufferItemList", bufferlist.join(",").toAscii());
412
413   return mimeData;
414 }
415
416 bool NetworkModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) {
417   Q_UNUSED(action)
418   Q_UNUSED(row)
419   Q_UNUSED(column)
420
421   if(!mimeContainsBufferList(data))
422     return false;
423
424   // target must be a query
425   Buffer::Type targetType = (Buffer::Type)parent.data(NetworkModel::BufferTypeRole).toInt();
426   if(targetType != Buffer::QueryType)
427     return false;
428
429   QList< QPair<uint, uint> > bufferList = mimeDataToBufferList(data);
430
431   // exactly one buffer has to be dropped
432   if(bufferList.count() != 1)
433     return false;
434
435   uint netId = bufferList.first().first;
436   uint bufferId = bufferList.first().second;
437
438   // no self merges (would kill us)
439   if(bufferId == parent.data(BufferUidRole).toUInt())
440     return false; 
441   
442   Q_ASSERT(rootItem->childById(netId));
443   Q_ASSERT(rootItem->childById(netId)->childById(bufferId));
444
445   // source must be a query too
446   Buffer::Type sourceType = (Buffer::Type)rootItem->childById(netId)->childById(bufferId)->data(0, BufferTypeRole).toInt();
447   if(sourceType != Buffer::QueryType)
448     return false;
449     
450   // TODO: warn user about buffermerge!
451   qDebug() << "merging" << bufferId << parent.data(BufferUidRole).toInt();
452   removeRow(parent.row(), parent.parent());
453   
454   return true;
455 }
456
457 void NetworkModel::attachNetworkInfo(NetworkInfo *networkInfo) {
458   NetworkItem *networkItem = network(networkInfo->networkId());
459   if(!networkItem) {
460     qWarning() << "NetworkModel::attachNetworkInfo(): network is unknown!";
461     return;
462   }
463   networkItem->attachNetworkInfo(networkInfo);
464 }
465
466 void NetworkModel::bufferUpdated(Buffer *buffer) {
467   BufferItem *bufferItem = newBuffer(buffer->bufferInfo());
468   QModelIndex itemindex = indexByItem(bufferItem);
469   emit dataChanged(itemindex, itemindex);
470 }
471
472 // This Slot indicates that the user has selected a different buffer in the gui
473 void NetworkModel::setCurrentIndex(const QModelIndex &index, QItemSelectionModel::SelectionFlags command) {
474   Q_UNUSED(command)
475   Buffer *newCurrentBuffer;
476   if(isBufferIndex(index) && currentBuffer != (newCurrentBuffer = getBufferByIndex(index))) {
477     currentBuffer = newCurrentBuffer;
478     bufferActivity(Buffer::NoActivity, currentBuffer);
479     emit bufferSelected(currentBuffer);
480     emit selectionChanged(index);
481   }
482 }
483
484 void NetworkModel::bufferActivity(Buffer::ActivityLevel level, Buffer *buf) {
485   BufferItem *bufferItem = buffer(buf->bufferInfo());
486   if(!bufferItem) {
487     qWarning() << "NetworkModel::bufferActivity(): received Activity Info for uknown Buffer";
488     return;
489   }
490   
491   if(buf != currentBuffer)
492     bufferItem->setActivity(level);
493   else
494     bufferItem->setActivity(Buffer::NoActivity);
495   bufferUpdated(buf);
496 }
497
498 void NetworkModel::selectBuffer(Buffer *buffer) {
499   QModelIndex index = bufferIndex(buffer->bufferInfo());
500   if(!index.isValid()) {
501     qWarning() << "NetworkModel::selectBuffer(): unknown Buffer has been selected.";
502     return;
503   }
504   // SUPER UGLY!
505   setCurrentIndex(index, 0);
506 }