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