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