0fa57cd7cfadddbb88ecf8b65cceda6b3a1c05d4
[quassel.git] / src / uisupport / bufferviewfilter.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 "bufferviewfilter.h"
22
23 #include <QCoreApplication>
24
25 #include "buffermodel.h"
26 #include "client.h"
27 #include "networkmodel.h"
28
29 #include "uisettings.h"
30
31 class CheckRemovalEvent : public QEvent {
32 public:
33   CheckRemovalEvent(const QModelIndex &source_index) : QEvent(QEvent::User), index(source_index) {};
34   QPersistentModelIndex index;
35 };
36
37 /*****************************************
38 * The Filter for the Tree View
39 *****************************************/
40 BufferViewFilter::BufferViewFilter(QAbstractItemModel *model, BufferViewConfig *config)
41   : QSortFilterProxyModel(model),
42     _config(0),
43     _sortOrder(Qt::AscendingOrder)
44 {
45   setConfig(config);
46   setSourceModel(model);
47                         
48   setDynamicSortFilter(true);
49
50   loadColors();
51
52   connect(this, SIGNAL(_dataChanged(const QModelIndex &, const QModelIndex &)),
53           this, SLOT(_q_sourceDataChanged(QModelIndex,QModelIndex)));
54 }
55
56 void BufferViewFilter::loadColors() {
57   UiSettings s("QtUi/Colors");
58   _FgColorInactiveActivity = s.value("inactiveActivityFG", QVariant(QColor(Qt::gray))).value<QColor>();
59   _FgColorNoActivity = s.value("noActivityFG", QVariant(QColor(Qt::black))).value<QColor>();
60   _FgColorHighlightActivity = s.value("highlightActivityFG", QVariant(QColor(Qt::magenta))).value<QColor>();
61   _FgColorNewMessageActivity = s.value("newMessageActivityFG", QVariant(QColor(Qt::green))).value<QColor>();
62   _FgColorOtherActivity = s.value("otherActivityFG", QVariant(QColor(Qt::darkGreen))).value<QColor>();
63 }
64
65 void BufferViewFilter::setConfig(BufferViewConfig *config) {
66   if(_config == config)
67     return;
68   
69   if(_config) {
70     disconnect(_config, 0, this, 0);
71   }
72
73   _config = config;
74
75   if(!config) {
76     invalidate();
77     return;
78   }
79
80   if(config->isInitialized()) {
81     configInitialized();
82   } else {
83     connect(config, SIGNAL(initDone()), this, SLOT(configInitialized()));
84     invalidate();
85   }
86 }
87
88 void BufferViewFilter::configInitialized() {
89   if(!config())
90     return;
91     
92   connect(config(), SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(invalidate()));
93   connect(config(), SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(invalidate()));
94   connect(config(), SIGNAL(addNewBuffersAutomaticallySet(bool)), this, SLOT(invalidate()));
95   connect(config(), SIGNAL(sortAlphabeticallySet(bool)), this, SLOT(invalidate()));
96   connect(config(), SIGNAL(hideInactiveBuffersSet(bool)), this, SLOT(invalidate()));
97   connect(config(), SIGNAL(allowedBufferTypesSet(int)), this, SLOT(invalidate()));
98   connect(config(), SIGNAL(minimumActivitySet(int)), this, SLOT(invalidate()));
99   connect(config(), SIGNAL(bufferListSet()), this, SLOT(invalidate()));
100   connect(config(), SIGNAL(bufferAdded(const BufferId &, int)), this, SLOT(invalidate()));
101   connect(config(), SIGNAL(bufferMoved(const BufferId &, int)), this, SLOT(invalidate()));
102   connect(config(), SIGNAL(bufferRemoved(const BufferId &)), this, SLOT(invalidate()));
103   connect(config(), SIGNAL(bufferPermanentlyRemoved(const BufferId &)), this, SLOT(invalidate()));
104
105   disconnect(config(), SIGNAL(initDone()), this, SLOT(configInitialized()));
106
107   invalidate();
108 }
109
110 Qt::ItemFlags BufferViewFilter::flags(const QModelIndex &index) const {
111   Qt::ItemFlags flags = mapToSource(index).flags();
112   if(_config && (index == QModelIndex() || index.parent() == QModelIndex()))
113     flags |= Qt::ItemIsDropEnabled;
114   return flags;
115 }
116
117 bool BufferViewFilter::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) {
118   if(!config() || !NetworkModel::mimeContainsBufferList(data))
119     return QSortFilterProxyModel::dropMimeData(data, action, row, column, parent);
120
121   NetworkId droppedNetworkId;
122   if(parent.data(NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType)
123     droppedNetworkId = parent.data(NetworkModel::NetworkIdRole).value<NetworkId>();
124
125   QList< QPair<NetworkId, BufferId> > bufferList = NetworkModel::mimeDataToBufferList(data);
126   BufferId bufferId;
127   NetworkId networkId;
128   int pos;
129   for(int i = 0; i < bufferList.count(); i++) {
130     networkId = bufferList[i].first;
131     bufferId = bufferList[i].second;
132     if(droppedNetworkId == networkId) {
133       if(row < 0)
134         row = 0;
135
136       if(row < rowCount(parent)) {
137         BufferId beforeBufferId = parent.child(row, 0).data(NetworkModel::BufferIdRole).value<BufferId>();
138         pos = config()->bufferList().indexOf(beforeBufferId);
139         if(_sortOrder == Qt::DescendingOrder)
140           pos++;
141       } else {
142         if(_sortOrder == Qt::AscendingOrder)
143           pos = config()->bufferList().count();
144         else
145           pos = 0;
146       }
147
148       if(config()->bufferList().contains(bufferId)) {
149         if(config()->bufferList().indexOf(bufferId) < pos)
150           pos--;
151         config()->requestMoveBuffer(bufferId, pos);
152       } else {
153         config()->requestAddBuffer(bufferId, pos);
154       }
155
156     } else {
157       addBuffer(bufferId);
158     }
159   }
160   return true;
161 }
162
163 void BufferViewFilter::sort(int column, Qt::SortOrder order) {
164   _sortOrder = order;
165   QSortFilterProxyModel::sort(column, order);
166 }
167
168 void BufferViewFilter::addBuffer(const BufferId &bufferId) const {
169   if(!config() || config()->bufferList().contains(bufferId))
170     return;
171   
172   int pos = config()->bufferList().count();
173   bool lt;
174   for(int i = 0; i < config()->bufferList().count(); i++) {
175     if(config() && config()->sortAlphabetically())
176       lt = bufferIdLessThan(bufferId, config()->bufferList()[i]);
177     else
178       lt = bufferId < config()->bufferList()[i];
179     
180     if(lt) {
181       pos = i;
182       break;
183     }
184   }
185   config()->requestAddBuffer(bufferId, pos);
186 }
187
188 bool BufferViewFilter::filterAcceptBuffer(const QModelIndex &source_bufferIndex) const {
189   // no config -> "all buffers" -> accept everything
190   if(!config())
191     return true;
192
193   BufferId bufferId = sourceModel()->data(source_bufferIndex, NetworkModel::BufferIdRole).value<BufferId>();
194   Q_ASSERT(bufferId.isValid());
195
196   int activityLevel = source_bufferIndex.data(NetworkModel::BufferActivityRole).toInt();
197
198   if(!config()->bufferList().contains(bufferId)) {
199     // add the buffer if...
200     if(config()->isInitialized() && !config()->removedBuffers().contains(bufferId) // it hasn't been manually removed and either
201        && ((config()->addNewBuffersAutomatically() && !config()->temporarilyRemovedBuffers().contains(bufferId)) // is totally unknown to us (a new buffer)...
202            || (config()->temporarilyRemovedBuffers().contains(bufferId) && activityLevel > Buffer::OtherActivity))) { // or was just temporarily hidden and has a new message waiting for us.
203       addBuffer(bufferId);
204     }
205     // note: adding the buffer to the valid list does not temper with the following filters ("show only channels" and stuff)
206     return false;
207   }
208   
209   if(config()->networkId().isValid() && config()->networkId() != sourceModel()->data(source_bufferIndex, NetworkModel::NetworkIdRole).value<NetworkId>())
210     return false;
211
212   if(!(config()->allowedBufferTypes() & (BufferInfo::Type)source_bufferIndex.data(NetworkModel::BufferTypeRole).toInt()))
213     return false;
214
215   if(config()->hideInactiveBuffers() && !source_bufferIndex.data(NetworkModel::ItemActiveRole).toBool())
216     return false;
217
218   if(config()->minimumActivity() > activityLevel) {
219     if(bufferId != Client::bufferModel()->standardSelectionModel()->currentIndex().data(NetworkModel::BufferIdRole).value<BufferId>())
220       return false;
221   }
222
223   return true;
224 }
225
226 bool BufferViewFilter::filterAcceptNetwork(const QModelIndex &source_index) const {
227   if(!config())
228     return true;
229
230   if(!config()->networkId().isValid()) {
231     return true;
232   } else {
233     return config()->networkId() == sourceModel()->data(source_index, NetworkModel::NetworkIdRole).value<NetworkId>();
234   }
235 }
236
237 bool BufferViewFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const {
238   QModelIndex child = sourceModel()->index(source_row, 0, source_parent);
239   
240   if(!child.isValid()) {
241     qWarning() << "filterAcceptsRow has been called with an invalid Child";
242     return false;
243   }
244
245   if(!source_parent.isValid())
246     return filterAcceptNetwork(child);
247   else
248     return filterAcceptBuffer(child);
249 }
250
251 bool BufferViewFilter::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
252   int itemType = sourceModel()->data(source_left, NetworkModel::ItemTypeRole).toInt();
253   switch(itemType) {
254   case NetworkModel::NetworkItemType:
255     return networkLessThan(source_left, source_right);
256   case NetworkModel::BufferItemType:
257     return bufferLessThan(source_left, source_right);
258   default:
259     return QSortFilterProxyModel::lessThan(source_left, source_right);    
260   }
261 }
262
263 bool BufferViewFilter::bufferLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
264   BufferId leftBufferId = sourceModel()->data(source_left, NetworkModel::BufferIdRole).value<BufferId>();
265   BufferId rightBufferId = sourceModel()->data(source_right, NetworkModel::BufferIdRole).value<BufferId>();
266   if(config()) {
267     return config()->bufferList().indexOf(leftBufferId) < config()->bufferList().indexOf(rightBufferId);
268   } else
269     return bufferIdLessThan(leftBufferId, rightBufferId);
270 }
271
272 bool BufferViewFilter::networkLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {
273   NetworkId leftNetworkId = sourceModel()->data(source_left, NetworkModel::NetworkIdRole).value<NetworkId>();
274   NetworkId rightNetworkId = sourceModel()->data(source_right, NetworkModel::NetworkIdRole).value<NetworkId>();
275
276   if(config() && config()->sortAlphabetically())
277     return QSortFilterProxyModel::lessThan(source_left, source_right);
278   else
279     return leftNetworkId < rightNetworkId;
280 }
281
282 QVariant BufferViewFilter::data(const QModelIndex &index, int role) const {
283   if(role == Qt::ForegroundRole)
284     return foreground(index);
285   else
286     return QSortFilterProxyModel::data(index, role);
287 }
288
289 QVariant BufferViewFilter::foreground(const QModelIndex &index) const {
290   if(!index.data(NetworkModel::ItemActiveRole).toBool())
291     return _FgColorInactiveActivity;
292
293   Buffer::ActivityLevel activity = (Buffer::ActivityLevel)index.data(NetworkModel::BufferActivityRole).toInt();
294
295   if(activity & Buffer::Highlight)
296     return _FgColorHighlightActivity;
297   if(activity & Buffer::NewMessage)
298     return _FgColorNewMessageActivity;
299   if(activity & Buffer::OtherActivity)
300     return _FgColorOtherActivity;
301
302   return _FgColorNoActivity;
303 }
304
305 void BufferViewFilter::checkPreviousCurrentForRemoval(const QModelIndex &current, const QModelIndex &previous) {
306   Q_UNUSED(current);
307   if(previous.isValid())
308     QCoreApplication::postEvent(this, new CheckRemovalEvent(previous));
309 }
310
311 void BufferViewFilter::customEvent(QEvent *event) {
312   if(event->type() != QEvent::User)
313     return;
314   
315   CheckRemovalEvent *removalEvent = static_cast<CheckRemovalEvent *>(event);
316   checkItemForRemoval(removalEvent->index);
317   
318   event->accept();
319 }
320
321 void BufferViewFilter::checkItemsForRemoval(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
322   QModelIndex source_topLeft = mapToSource(topLeft);
323   QModelIndex source_bottomRight = mapToSource(bottomRight);
324   emit _dataChanged(source_topLeft, source_bottomRight);
325 }
326
327 // ******************************
328 //  Helper
329 // ******************************
330 bool bufferIdLessThan(const BufferId &left, const BufferId &right) {
331   Q_CHECK_PTR(Client::networkModel());
332   if(!Client::networkModel())
333     return true;
334   
335   QModelIndex leftIndex = Client::networkModel()->bufferIndex(left);
336   QModelIndex rightIndex = Client::networkModel()->bufferIndex(right);
337
338   int leftType = Client::networkModel()->data(leftIndex, NetworkModel::BufferTypeRole).toInt();
339   int rightType = Client::networkModel()->data(rightIndex, NetworkModel::BufferTypeRole).toInt();
340
341   if(leftType != rightType)
342     return leftType < rightType;
343   else
344     return QString::compare(Client::networkModel()->data(leftIndex, Qt::DisplayRole).toString(), Client::networkModel()->data(rightIndex, Qt::DisplayRole).toString(), Qt::CaseInsensitive) < 0;
345 }
346