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