Quassel IRC  Pre-Release
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros
bufferview.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  * Copyright (C) 2005-2015 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  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19  ***************************************************************************/
20 
21 #include "bufferview.h"
22 
23 #include <QApplication>
24 #include <QAction>
25 #include <QFlags>
26 #include <QHeaderView>
27 #include <QLineEdit>
28 #include <QMenu>
29 #include <QMessageBox>
30 #include <QSet>
31 
32 #include "action.h"
33 #include "buffermodel.h"
34 #include "bufferviewfilter.h"
35 #include "buffersettings.h"
36 #include "buffersyncer.h"
37 #include "client.h"
39 #include "graphicalui.h"
40 #include "network.h"
41 #include "networkmodel.h"
43 
44 /*****************************************
45 * The TreeView showing the Buffers
46 *****************************************/
47 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
48 // to be on the safe side: call QTreeView's method aswell
49 BufferView::BufferView(QWidget *parent)
50  : QTreeView(parent)
51 {
52  connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
53  connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(storeExpandedState(const QModelIndex &)));
54 
55  setSelectionMode(QAbstractItemView::ExtendedSelection);
56 
57  QAbstractItemDelegate *oldDelegate = itemDelegate();
58  BufferViewDelegate *tristateDelegate = new BufferViewDelegate(this);
59  setItemDelegate(tristateDelegate);
60  delete oldDelegate;
61 }
62 
63 
65 {
66  header()->setContextMenuPolicy(Qt::ActionsContextMenu);
67  hideColumn(1);
68  hideColumn(2);
69  setIndentation(10);
70 
71  expandAll();
72 
73  header()->hide(); // nobody seems to use this anyway
74 
75  // breaks with Qt 4.8
76  if (QString("4.8.0") > qVersion()) // FIXME breaks with Qt versions >= 4.10!
77  setAnimated(true);
78 
79  // FIXME This is to workaround bug #663
80  setUniformRowHeights(true);
81 
82 #ifndef QT_NO_DRAGANDDROP
83  setDragEnabled(true);
84  setAcceptDrops(true);
85  setDropIndicatorShown(true);
86 #endif
87 
88  setSortingEnabled(true);
89  sortByColumn(0, Qt::AscendingOrder);
90 
91  // activated() fails on X11 and Qtopia at least
92 #if defined Q_WS_QWS || defined Q_WS_X11
93  disconnect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
94  connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(joinChannel(QModelIndex)));
95 #else
96  // afaik this is better on Mac and Windows
97  disconnect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
98  connect(this, SIGNAL(activated(QModelIndex)), SLOT(joinChannel(QModelIndex)));
99 #endif
100 }
101 
102 
103 void BufferView::setModel(QAbstractItemModel *model)
104 {
105  delete selectionModel();
106 
107  QTreeView::setModel(model);
108  init();
109  // remove old Actions
110  QList<QAction *> oldactions = header()->actions();
111  foreach(QAction *action, oldactions) {
112  header()->removeAction(action);
113  action->deleteLater();
114  }
115 
116  if (!model)
117  return;
118 
119  QString sectionName;
120  QAction *showSection;
121  for (int i = 1; i < model->columnCount(); i++) {
122  sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
123  showSection = new QAction(sectionName, header());
124  showSection->setCheckable(true);
125  showSection->setChecked(!isColumnHidden(i));
126  showSection->setProperty("column", i);
127  connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
128  header()->addAction(showSection);
129  }
130 
131  connect(model, SIGNAL(layoutChanged()), this, SLOT(on_layoutChanged()));
132 }
133 
134 
135 void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config)
136 {
137  BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
138  if (filter) {
139  filter->setConfig(config);
140  setConfig(config);
141  return;
142  }
143 
144  if (model()) {
145  disconnect(this, 0, model(), 0);
146  disconnect(model(), 0, this, 0);
147  }
148 
149  if (!model_) {
150  setModel(model_);
151  }
152  else {
153  BufferViewFilter *filter = new BufferViewFilter(model_, config);
154  setModel(filter);
155  connect(filter, SIGNAL(configChanged()), this, SLOT(on_configChanged()));
156  }
157  setConfig(config);
158 }
159 
160 
161 void BufferView::setSelectionModel(QItemSelectionModel *selectionModel)
162 {
163  if (QTreeView::selectionModel())
164  disconnect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
165  model(), SIGNAL(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
166 
167  QTreeView::setSelectionModel(selectionModel);
168  BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
169  if (filter) {
170  connect(selectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
171  filter, SLOT(checkPreviousCurrentForRemoval(QModelIndex, QModelIndex)));
172  }
173 }
174 
175 
177 {
178  if (_config == config)
179  return;
180 
181  if (_config) {
182  disconnect(_config, 0, this, 0);
183  }
184 
185  _config = config;
186  if (config) {
187  connect(config, SIGNAL(networkIdSet(const NetworkId &)), this, SLOT(setRootIndexForNetworkId(const NetworkId &)));
189  }
190  else {
191  setIndentation(10);
192  setRootIndex(QModelIndex());
193  }
194 }
195 
196 
198 {
199  if (!networkId.isValid() || !model()) {
200  setIndentation(10);
201  setRootIndex(QModelIndex());
202  }
203  else {
204  setIndentation(5);
205  int networkCount = model()->rowCount();
206  QModelIndex child;
207  for (int i = 0; i < networkCount; i++) {
208  child = model()->index(i, 0);
209  if (networkId == model()->data(child, NetworkModel::NetworkIdRole).value<NetworkId>())
210  setRootIndex(child);
211  }
212  }
213 }
214 
215 
216 void BufferView::joinChannel(const QModelIndex &index)
217 {
218  BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
219 
220  if (bufferType != BufferInfo::ChannelBuffer)
221  return;
222 
223  BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
224 
225  Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
226 }
227 
228 
229 void BufferView::keyPressEvent(QKeyEvent *event)
230 {
231  if (event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
232  event->accept();
234  }
236 }
237 
238 
239 void BufferView::dropEvent(QDropEvent *event)
240 {
241  QModelIndex index = indexAt(event->pos());
242 
243  QRect indexRect = visualRect(index);
244  QPoint cursorPos = event->pos();
245 
246  // check if we're really _on_ the item and not indicating a move to just above or below the item
247  const int margin = 2;
248  if (cursorPos.y() - indexRect.top() < margin
249  || indexRect.bottom() - cursorPos.y() < margin)
250  return QTreeView::dropEvent(event);
251 
252  QList<QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
253  if (bufferList.count() != 1)
254  return QTreeView::dropEvent(event);
255 
256  BufferId bufferId2 = bufferList[0].second;
257 
259  return QTreeView::dropEvent(event);
260 
262  return QTreeView::dropEvent(event);
263 
264  BufferId bufferId1 = index.data(NetworkModel::BufferIdRole).value<BufferId>();
265  if (bufferId1 == bufferId2)
266  return QTreeView::dropEvent(event);
267 
268  int res = QMessageBox::question(0, tr("Merge buffers permanently?"),
269  tr("Do you want to merge the buffer \"%1\" permanently into buffer \"%2\"?\n This cannot be reversed!").arg(Client::networkModel()->bufferName(bufferId2)).arg(Client::networkModel()->bufferName(bufferId1)),
270  QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
271  if (res == QMessageBox::Yes) {
272  Client::mergeBuffersPermanently(bufferId1, bufferId2);
273  }
274 }
275 
276 
277 void BufferView::removeSelectedBuffers(bool permanently)
278 {
279  if (!config())
280  return;
281 
282  BufferId bufferId;
283  QSet<BufferId> removedRows;
284  foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
286  continue;
287 
288  bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
289  if (removedRows.contains(bufferId))
290  continue;
291 
292  removedRows << bufferId;
293  }
294 
295  foreach(BufferId bufferId, removedRows) {
296  if (permanently)
298  else
299  config()->requestRemoveBuffer(bufferId);
300  }
301 }
302 
303 
304 void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
305 {
306  QTreeView::rowsInserted(parent, start, end);
307 
308  // ensure that newly inserted network nodes are expanded per default
310  return;
311 
312  setExpandedState(parent);
313 }
314 
315 
317 {
318  int numNets = model()->rowCount(QModelIndex());
319  for (int row = 0; row < numNets; row++) {
320  QModelIndex networkIdx = model()->index(row, 0, QModelIndex());
321  setExpandedState(networkIdx);
322  }
323 }
324 
325 
327 {
328  Q_ASSERT(model());
329 
330  // expand all active networks... collapse inactive ones... unless manually changed
331  QModelIndex networkIdx;
332  NetworkId networkId;
333  for (int row = 0; row < model()->rowCount(); row++) {
334  networkIdx = model()->index(row, 0);
335  if (model()->rowCount(networkIdx) == 0)
336  continue;
337 
338  networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
339  if (!networkId.isValid())
340  continue;
341 
342  setExpandedState(networkIdx);
343  }
344 
345  if (config()) {
346  // update selection to current one
348  }
349 }
350 
351 
352 void BufferView::storeExpandedState(const QModelIndex &networkIdx)
353 {
354  NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
355 
356  int oldState = 0;
357  if (isExpanded(networkIdx))
358  oldState |= WasExpanded;
359  if (model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool())
360  oldState |= WasActive;
361 
362  _expandedState[networkId] = oldState;
363 }
364 
365 
366 void BufferView::setExpandedState(const QModelIndex &networkIdx)
367 {
368  if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
369  return;
370 
371  if (model()->rowCount(networkIdx) == 0)
372  return;
373 
374  NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
375 
376  bool networkActive = model()->data(networkIdx, NetworkModel::ItemActiveRole).toBool();
377  bool expandNetwork = networkActive;
378  if (_expandedState.contains(networkId)) {
379  int oldState = _expandedState[networkId];
380  if ((bool)(oldState & WasActive) == networkActive)
381  expandNetwork = (bool)(oldState & WasExpanded);
382  }
383 
384  if (expandNetwork != isExpanded(networkIdx)) {
385  update(networkIdx);
386  setExpanded(networkIdx, expandNetwork);
387  }
388  storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
389 }
390 
391 #if QT_VERSION < 0x050000
392 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
393 {
394  QTreeView::dataChanged(topLeft, bottomRight);
395 #else
396 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
397 {
398  QTreeView::dataChanged(topLeft, bottomRight, roles);
399 #endif
400 
401  // determine how many items have been changed and if any of them is a networkitem
402  // which just swichted from active to inactive or vice versa
404  return;
405 
406  for (int i = topLeft.row(); i <= bottomRight.row(); i++) {
407  QModelIndex networkIdx = topLeft.sibling(i, 0);
408  setExpandedState(networkIdx);
409  }
410 }
411 
412 
413 void BufferView::toggleHeader(bool checked)
414 {
415  QAction *action = qobject_cast<QAction *>(sender());
416  header()->setSectionHidden((action->property("column")).toInt(), !checked);
417 }
418 
419 
420 void BufferView::contextMenuEvent(QContextMenuEvent *event)
421 {
422  QModelIndex index = indexAt(event->pos());
423  if (!index.isValid())
424  index = rootIndex();
425 
426  QMenu contextMenu(this);
427 
428  if (index.isValid()) {
429  addActionsToMenu(&contextMenu, index);
430  }
431 
432  addFilterActions(&contextMenu, index);
433 
434  if (!contextMenu.actions().isEmpty())
435  contextMenu.exec(QCursor::pos());
436 }
437 
438 
439 void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
440 {
441  QModelIndexList indexList = selectedIndexes();
442  // make sure the item we clicked on is first
443  indexList.removeAll(index);
444  indexList.prepend(index);
445 
446  GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, "menuActionTriggered", (bool)config());
447 }
448 
449 
450 void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
451 {
452  BufferViewFilter *filter = qobject_cast<BufferViewFilter *>(model());
453  if (filter) {
454  QList<QAction *> filterActions = filter->actions(index);
455  if (!filterActions.isEmpty()) {
456  contextMenu->addSeparator();
457  foreach(QAction *action, filterActions) {
458  contextMenu->addAction(action);
459  }
460  }
461  }
462 }
463 
464 
465 void BufferView::menuActionTriggered(QAction *result)
466 {
468  switch (type) {
471  break;
473  removeSelectedBuffers(true);
474  break;
475  default:
476  return;
477  }
478 }
479 
480 
482 {
484 }
485 
486 
488 {
490 }
491 
492 
494 {
495  QModelIndex currentIndex = selectionModel()->currentIndex();
496  QModelIndex resultingIndex;
497 
498  if (currentIndex.parent().isValid()) {
499  //If we are a child node just switch among siblings unless it's the first/last child
500  resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
501 
502  if (!resultingIndex.isValid()) {
503  QModelIndex parent = currentIndex.parent();
504  if (direction == Backward)
505  resultingIndex = parent;
506  else
507  resultingIndex = parent.sibling(parent.row() + direction, 0);
508  }
509  }
510  else {
511  //If we have a toplevel node, try and get an adjacent child
512  if (direction == Backward) {
513  QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
514  if (model()->hasChildren(newParent))
515  resultingIndex = newParent.child(model()->rowCount(newParent) - 1, 0);
516  else
517  resultingIndex = newParent;
518  }
519  else {
520  if (model()->hasChildren(currentIndex))
521  resultingIndex = currentIndex.child(0, 0);
522  else
523  resultingIndex = currentIndex.sibling(currentIndex.row() + 1, 0);
524  }
525  }
526 
527  if (!resultingIndex.isValid())
528  return;
529 
530  selectionModel()->setCurrentIndex(resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
531  selectionModel()->select(resultingIndex, QItemSelectionModel::ClearAndSelect);
532 }
533 
534 
535 void BufferView::wheelEvent(QWheelEvent *event)
536 {
537  if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
538  return QTreeView::wheelEvent(event);
539 
540  int rowDelta = (event->delta() > 0) ? -1 : 1;
541  changeBuffer((Direction)rowDelta);
542 }
543 
544 
546 {
547  QModelIndex index = selectionModel()->currentIndex();
549  return;
550 
551  BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
552 
553  //The check above means we won't be looking at a network, which should always be the first row, so we can just go backwards.
555 
556  /*if(removedRows.contains(bufferId))
557  continue;
558 
559  removedRows << bufferId;*/
560  /*if(permanently)
561  config()->requestRemoveBufferPermanently(bufferId);
562  else*/
563  config()->requestRemoveBuffer(bufferId);
564 }
565 
566 
567 QSize BufferView::sizeHint() const
568 {
569  return QTreeView::sizeHint();
570 
571  if (!model())
572  return QTreeView::sizeHint();
573 
574  if (model()->rowCount() == 0)
575  return QSize(120, 50);
576 
577  int columnSize = 0;
578  for (int i = 0; i < model()->columnCount(); i++) {
579  if (!isColumnHidden(i))
580  columnSize += sizeHintForColumn(i);
581  }
582  return QSize(columnSize, 50);
583 }
584 
585 
586 // ****************************************
587 // BufferViewDelgate
588 // ****************************************
589 class ColorsChangedEvent : public QEvent
590 {
591 public:
592  ColorsChangedEvent() : QEvent(QEvent::User) {};
593 };
594 
595 
597  : QStyledItemDelegate(parent)
598 {
599 }
600 
601 
603 {
604  if (event->type() != QEvent::User)
605  return;
606 
607  event->accept();
608 }
609 
610 
611 bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
612 {
613  if (event->type() != QEvent::MouseButtonRelease)
614  return QStyledItemDelegate::editorEvent(event, model, option, index);
615 
616  if (!(model->flags(index) & Qt::ItemIsUserCheckable))
617  return QStyledItemDelegate::editorEvent(event, model, option, index);
618 
619  QVariant value = index.data(Qt::CheckStateRole);
620  if (!value.isValid())
621  return QStyledItemDelegate::editorEvent(event, model, option, index);
622 
623  QStyleOptionViewItemV4 viewOpt(option);
624  initStyleOption(&viewOpt, index);
625 
626  QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
627  QMouseEvent *me = static_cast<QMouseEvent *>(event);
628 
629  if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
630  return QStyledItemDelegate::editorEvent(event, model, option, index);
631 
632  Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
633  if (state == Qt::Unchecked)
634  state = Qt::PartiallyChecked;
635  else if (state == Qt::PartiallyChecked)
636  state = Qt::Checked;
637  else
638  state = Qt::Unchecked;
639  model->setData(index, state, Qt::CheckStateRole);
640  return true;
641 }
642 
643 
644 // ==============================
645 // BufferView Dock
646 // ==============================
648  : QDockWidget(parent),
649  _active(false),
650  _title(config->bufferViewName())
651 {
652  setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
653  toggleViewAction()->setData(config->bufferViewId());
654  setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
655  connect(config, SIGNAL(bufferViewNameSet(const QString &)), this, SLOT(bufferViewRenamed(const QString &)));
656  updateTitle();
657 }
658 
659 
661 {
662  QString title = _title;
663  if (isActive())
664  title.prepend(QString::fromUtf8("• "));
665  setWindowTitle(title);
666 }
667 
668 
669 void BufferViewDock::setActive(bool active)
670 {
671  if (active != isActive()) {
672  _active = active;
673  updateTitle();
674  if (active)
675  raise(); // for tabbed docks
676  }
677 }
678 
679 
680 void BufferViewDock::bufferViewRenamed(const QString &newName)
681 {
682  _title = newName;
683  updateTitle();
684  toggleViewAction()->setText(newName);
685 }
686 
687 
689 {
690  BufferView *view = bufferView();
691  if (!view)
692  return 0;
693 
694  if (view->config())
695  return view->config()->bufferViewId();
696  else
697  return 0;
698 }
699 
700 
702 {
703  BufferView *view = bufferView();
704  if (!view)
705  return 0;
706  else
707  return view->config();
708 }