Debian Codegraph @

core/libs/album/treeview/abstractalbumtreeview.cpp

raw
1 /* ============================================================
2 *
3 * This file is a part of digiKam project
4 * https://www.digikam.org
5 *
6 * Date : 2009-03-25
7 * Description : Tree View for album models
8 *
9 * SPDX-FileCopyrightText: 2009-2011 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de>
10 * SPDX-FileCopyrightText: 2010-2011 by Andi Clemens <andi dot clemens at gmail dot com>
11 * SPDX-FileCopyrightText: 2014 by Mohamed_Anwer <m_dot_anwer at gmx dot com>
12 * SPDX-FileCopyrightText: 2014 by Michael G. Hansen <mike at mghansen dot de>
13 * SPDX-FileCopyrightText: 2009-2026 by Gilles Caulier <caulier dot gilles at gmail dot com>
14 *
15 * SPDX-License-Identifier: GPL-2.0-or-later
16 *
17 * ============================================================ */
18
19 #include "abstractalbumtreeview_p.h"
20
21 namespace Digikam
22 {
23
24 AbstractAlbumTreeView::AbstractAlbumTreeView(QWidget* const parent, Flags flags)
25 : QTreeView (parent),
26 StateSavingObject(this),
27 m_flags (flags),
28 d (new Private)
29 {
30 if (flags & CreateDefaultDelegate)
31 {
32 d->delegate = new AlbumTreeViewDelegate(this);
33 setItemDelegate(d->delegate);
34 setUniformRowHeights(true);
35 }
36
37 d->resizeColumnsTimer = new QTimer(this);
38 d->resizeColumnsTimer->setInterval(200);
39 d->resizeColumnsTimer->setSingleShot(true);
40
41 d->contextMenuIcon = QIcon::fromTheme(QLatin1String("digikam")).pixmap(style()->pixelMetric(QStyle::PM_SmallIconSize));
42 d->contextMenuTitle = i18n("Context menu");
43
44 connect(d->resizeColumnsTimer, SIGNAL(timeout()),
45 this, SLOT(adaptColumnsToContent()));
46
47 connect(ApplicationSettings::instance(), SIGNAL(setupChanged()),
48 this, SLOT(albumSettingsChanged()));
49
50 connect(this, SIGNAL(currentAlbumChanged(Album*)),
51 this, SLOT(currentAlbumChangedForBackupSelection(Album*)));
52
53 if (flags & CreateDefaultFilterModel)
54 {
55 this->setAlbumFilterModel(new AlbumFilterModel(this));
56 }
57
58 setSortingEnabled(true);
59 albumSettingsChanged();
60 }
61
62 AbstractAlbumTreeView::~AbstractAlbumTreeView()
63 {
64 delete d;
65 }
66
67 void AbstractAlbumTreeView::setAlbumModel(AbstractSpecificAlbumModel* const model)
68 {
69 if (m_albumModel == model)
70 {
71 return;
72 }
73
74 if (m_albumModel)
75 {
76 disconnect(m_albumModel, nullptr,
77 this, nullptr);
78 }
79
80 m_albumModel = model;
81
82 if (m_albumFilterModel)
83 {
84 m_albumFilterModel->setSourceAlbumModel(m_albumModel);
85 }
86
87 if (m_albumModel)
88 {
89 if (!m_albumModel->rootAlbum())
90 {
91 connect(m_albumModel, SIGNAL(rootAlbumAvailable()),
92 this, SLOT(slotRootAlbumAvailable()));
93 }
94
95 if (m_albumFilterModel)
96 {
97 expand(m_albumFilterModel->rootAlbumIndex());
98 }
99 }
100 }
101
102 void AbstractAlbumTreeView::setAlbumFilterModel(AlbumFilterModel* const filterModel)
103 {
104 if (filterModel == m_albumFilterModel)
105 {
106 return;
107 }
108
109 if (m_albumFilterModel)
110 {
111 disconnect(m_albumFilterModel);
112 }
113
114 if (selectionModel())
115 {
116 disconnect(selectionModel());
117 }
118
119 m_albumFilterModel = filterModel;
120 setModel(m_albumFilterModel);
121
122 if (m_albumFilterModel)
123 {
124 m_albumFilterModel->setSourceAlbumModel(m_albumModel);
125
126 connect(m_albumFilterModel, SIGNAL(searchTextSettingsAboutToChange(bool,bool)),
127 this, SLOT(slotSearchTextSettingsAboutToChange(bool,bool)));
128
129 connect(m_albumFilterModel, SIGNAL(searchTextSettingsChanged(bool,bool)),
130 this, SLOT(slotSearchTextSettingsChanged(bool,bool)));
131
132 /**
133 * @note When only single selection was available, everything was
134 * implemented using currentAlbum() which was equal with selectedAlbum()
135 * after enabling multiple selection they are no longer the same
136 * and some options must use selected others only currentAlbum
137 * Now AlbumManager implementation is a little bit of mess
138 * because selected are now currentAlbums().
139 */
140
141 connect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
142 this, SLOT(slotCurrentChanged()));
143
144 connect(selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
145 this, SLOT(slotSelectionChanged()));
146
147 connect(m_albumFilterModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
148 this, SLOT(adaptColumnsOnDataChange(QModelIndex,QModelIndex)));
149
150 connect(m_albumFilterModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
151 this, SLOT(adaptColumnsOnRowChange(QModelIndex,int,int)));
152
153 connect(m_albumFilterModel, SIGNAL(rowsRemoved(QModelIndex,int,int)),
154 this, SLOT(adaptColumnsOnRowChange(QModelIndex,int,int)));
155
156 connect(m_albumFilterModel, SIGNAL(layoutChanged()),
157 this, SLOT(adaptColumnsOnLayoutChange()));
158
159 connect(horizontalScrollBar(), SIGNAL(valueChanged(int)),
160 this, SLOT(slotScrollBarValueChanged(int)));
161
162 connect(horizontalScrollBar(), SIGNAL(actionTriggered(int)),
163 this, SLOT(slotScrollBarActionTriggered(int)));
164
165 adaptColumnsToContent();
166
167 if (m_albumModel)
168 {
169 expand(m_albumFilterModel->rootAlbumIndex());
170 }
171 /*
172 m_albumFilterModel->setDynamicSortFilter(true);
173 */
174 }
175 }
176
177 AbstractSpecificAlbumModel* AbstractAlbumTreeView::albumModel() const
178 {
179 return m_albumModel;
180 }
181
182 AlbumFilterModel* AbstractAlbumTreeView::albumFilterModel() const
183 {
184 return m_albumFilterModel;
185 }
186
187 void AbstractAlbumTreeView::setExpandOnSingleClick(const bool doThat)
188 {
189 d->expandOnSingleClick = doThat;
190 }
191
192 void AbstractAlbumTreeView::setExpandNewCurrentItem(const bool doThat)
193 {
194 d->expandNewCurrent = doThat;
195 }
196
197 void AbstractAlbumTreeView::setSelectAlbumOnClick(const bool selectOnClick)
198 {
199 d->selectAlbumOnClick = selectOnClick;
200 }
201
202 QModelIndex AbstractAlbumTreeView::indexVisuallyAt(const QPoint& p)
203 {
204 if (viewport()->rect().contains(p))
205 {
206 const QModelIndex index = indexAt(p);
207
208 if (index.isValid() && visualRect(index).contains(p))
209 {
210 return index;
211 }
212 }
213
214 return QModelIndex();
215 }
216
217 template<class A>
218 QList<A*> AbstractAlbumTreeView::currentAlbums()
219 {
220 QList<A*> albums;
221 const QList<Album*> currentAl = AlbumManager::instance()->currentAlbums();
222
223 for (QList<Album*>::const_iterator it = currentAl.constBegin() ; it != currentAl.constEnd() ; ++it)
224 {
225 A* const item = dynamic_cast<A*>(*it);
226
227 if (item)
228 {
229 albums.append(item);
230 }
231 }
232
233 return albums;
234 }
235
236 void AbstractAlbumTreeView::slotSearchTextSettingsAboutToChange(bool searched, bool willSearch)
237 {
238 // backup before we begin searching
239
240 if (!searched && willSearch && d->searchBackup.isEmpty())
241 {
242 qCDebug(DIGIKAM_GENERAL_LOG) << "Searching started, backing up state";
243
244 QList<int> selection, expansion;
245 saveStateRecursive(QModelIndex(), selection, expansion);
246
247 // selection is ignored here because the user may have changed this
248 // while searching
249
250 for (const int& expandedId : std::as_const(expansion))
251 {
252 d->searchBackup[expandedId].expanded = true;
253 }
254
255 // also backup the last selected album in case this didn't work via the slot
256
257 const QList<Album*> selList = selectedAlbums<Album>(selectionModel(),
258 m_albumFilterModel);
259 if (!selList.isEmpty())
260 {
261 d->lastSelectedAlbum = selList.first();
262 }
263 }
264 }
265
266 void AbstractAlbumTreeView::slotSearchTextSettingsChanged(bool wasSearching, bool searched)
267 {
268 // ensure that all search results are visible if there is currently a search working
269
270 if (searched)
271 {
272 qCDebug(DIGIKAM_GENERAL_LOG) << "Searched, expanding all results";
273 expandMatches(QModelIndex());
274 }
275
276 // Restore the tree view state if searching finished
277
278 if (wasSearching && !searched && !d->searchBackup.isEmpty())
279 {
280
281 qCDebug(DIGIKAM_GENERAL_LOG) << "Searching finished, restoring tree view state";
282
283 collapseAll();
284 restoreStateForHierarchy(QModelIndex(), d->searchBackup);
285 d->searchBackup.clear();
286
287 if (d->lastSelectedAlbum)
288 {
289 setCurrentAlbums(QList<Album*>() << d->lastSelectedAlbum, false);
290
291 // Doing this twice somehow ensures that all parents are expanded
292 // and we are at the right position. Maybe a hack... ;)
293
294 scrollTo(m_albumFilterModel->indexForAlbum(d->lastSelectedAlbum));
295 scrollTo(m_albumFilterModel->indexForAlbum(d->lastSelectedAlbum));
296 }
297 }
298 }
299
300 void AbstractAlbumTreeView::currentAlbumChangedForBackupSelection(Album* currentAlbum)
301 {
302 d->lastSelectedAlbum = currentAlbum;
303 }
304
305 void AbstractAlbumTreeView::slotRootAlbumAvailable()
306 {
307 expand(m_albumFilterModel->rootAlbumIndex());
308 }
309
310 bool AbstractAlbumTreeView::expandMatches(const QModelIndex& index)
311 {
312 bool anyMatch = false;
313
314 // Expand index if a child matches
315
316 const QModelIndex source_index = m_albumFilterModel->mapToSource(index);
317 const AlbumFilterModel::MatchResult result = m_albumFilterModel->matchResult(source_index);
318
319 switch (result)
320 {
321 case AlbumFilterModel::NoMatch:
322 {
323 if (index != rootIndex())
324 {
325 return false;
326 }
327
328 break;
329 }
330
331 case AlbumFilterModel::ParentMatch:
332 {
333 // Does not rule out additional child match, return value is unknown
334
335 break;
336 }
337
338 case AlbumFilterModel::DirectMatch:
339 {
340 // Does not rule out additional child match, but we know we will return true
341
342 anyMatch = true;
343 break;
344 }
345
346 case AlbumFilterModel::ChildMatch:
347 case AlbumFilterModel::SpecialMatch:
348 {
349 // We know already to expand, and we know already we will return true.
350
351 anyMatch = true;
352 expand(index);
353
354 break;
355 }
356 }
357
358 // Recurse. Expand if children if have an (indirect) match
359
360 const int rows = m_albumFilterModel->rowCount(index);
361
362 for (int i = 0 ; i < rows ; ++i)
363 {
364 const QModelIndex child = m_albumFilterModel->index(i, 0, index);
365 const bool childResult = expandMatches(child);
366
367 if (childResult)
368 {
369 anyMatch = true;
370
371 // if there is a direct match _and_ a child match, do not forget to expand the parent
372
373 expand(index);
374 }
375 }
376
377 return anyMatch;
378 }
379
380 void AbstractAlbumTreeView::setSearchTextSettings(const SearchTextSettings& settings)
381 {
382 m_albumFilterModel->setSearchTextSettings(settings);
383 }
384
385 void AbstractAlbumTreeView::setAlbumManagerCurrentAlbum(const bool set)
386 {
387 d->setInAlbumManager = set;
388 }
389
390 void AbstractAlbumTreeView::setCurrentAlbums(const QList<Album*>& albums, bool selectInAlbumManager)
391 {
392 if (!model())
393 {
394 return;
395 }
396
397 if (selectInAlbumManager && d->setInAlbumManager)
398 {
399 AlbumManager::instance()->setCurrentAlbums(albums);
400 }
401
402 setCurrentIndex(albumFilterModel()->indexForAlbum(albums.first()));
403
404 QItemSelectionModel* const model = selectionModel();
405 model->clearSelection();
406
407 for (int it = 0 ; it < albums.size() ; ++it)
408 {
409 model->select(albumFilterModel()->indexForAlbum(albums.at(it)),
410 model->Select);
411 }
412 }
413
414 void AbstractAlbumTreeView::slotCurrentChanged()
415 {
416 // It seems that QItemSelectionModel::selectedIndexes() has not been updated at this point
417 // and returns the previously selected items. Therefore the line below did not work.
418 /*
419 QList<Album*> selected = selectedAlbums<Album>(selectionModel(),
420 m_albumFilterModel);
421 */
422 // Instead, we call QItemSelectionModel::currentIndex to get the current index.
423
424 const QModelIndex cIndex = selectionModel()->currentIndex();
425
426 if (!cIndex.isValid())
427 {
428 return;
429 }
430
431 Album* const cAlbum = m_albumFilterModel->albumForIndex(cIndex);
432
433 if (!cAlbum)
434 {
435 return;
436 }
437
438 Q_EMIT currentAlbumChanged(cAlbum);
439 }
440
441 void AbstractAlbumTreeView::slotSelectionChanged()
442 {
443 // FIXME: Dead signal? Nobody listens to it
444 /*
445 Q_EMIT selectedAlbumsChanged(selectedAlbums<Album>(selectionModel(), m_albumFilterModel));
446 */
447 if (d->selectAlbumOnClick)
448 {
449 AlbumManager::instance()->setCurrentAlbums(selectedAlbums<Album>(selectionModel(),
450 m_albumFilterModel));
451 }
452 }
453
454 void AbstractAlbumTreeView::mousePressEvent(QMouseEvent* e)
455 {
456 const QModelIndex currentBefor = currentIndex();
457
458 QTreeView::mousePressEvent(e);
459
460 if ((d->expandOnSingleClick || d->expandNewCurrent) && (e->button() == Qt::LeftButton))
461 {
462 const QModelIndex index = indexVisuallyAt(e->pos());
463
464 if (index.isValid())
465 {
466 if (d->expandOnSingleClick)
467 {
468 // See bug #126871: collapse/expand treeview using left mouse button single click.
469 // Exception: If a newly selected item is already expanded, do not collapse on selection.
470
471 const bool expanded = isExpanded(index);
472
473 if ((index == currentIndex()) || !expanded)
474 {
475 setExpanded(index, !expanded);
476 }
477 }
478 else
479 {
480 if (currentBefor != currentIndex())
481 {
482 expand(index);
483 }
484 }
485 }
486 }
487 else if (m_checkOnMiddleClick && (e->button() == Qt::MiddleButton))
488 {
489 Album* const a = m_albumFilterModel->albumForIndex(indexAt(e->pos()));
490
491 if (a)
492 {
493 middleButtonPressed(a);
494 }
495 }
496 }
497
498 void AbstractAlbumTreeView::middleButtonPressed(Album*)
499 {
500 // reimplement if needed
501 }
502
503 void AbstractAlbumTreeView::startDrag(Qt::DropActions supportedActions)
504 {
505 const QModelIndexList indexes = selectedIndexes();
506
507 if (indexes.count() > 0)
508 {
509 QMimeData* const data = m_albumFilterModel->mimeData(indexes);
510
511 if (!data)
512 {
513 return;
514 }
515
516 QStyleOptionViewItem option;
517
518 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
519
520 initViewItemOption(&option);
521
522 #else
523
524 option = viewOptions();
525
526 #endif
527
528 option.rect = viewport()->rect();
529 const QPixmap pixmap = /*m_delegate->*/pixmapForDrag(option, indexes);
530 QDrag* const drag = new QDrag(this);
531 drag->setPixmap(pixmap);
532 drag->setMimeData(data);
533 drag->exec(supportedActions, Qt::CopyAction);
534 }
535 }
536
537 /**
538 * @todo Move to delegate, when we have one.
539 * Copy code from image delegate for creating icons when dragging multiple items
540 */
541 QPixmap AbstractAlbumTreeView::pixmapForDrag(const QStyleOptionViewItem&, QList<QModelIndex> indexes)
542 {
543 if (indexes.isEmpty())
544 {
545 return QPixmap();
546 }
547
548 const QVariant decoration = indexes.first().data(Qt::DecorationRole);
549
550 return (decoration.value<QPixmap>());
551 }
552
553 void AbstractAlbumTreeView::dragEnterEvent(QDragEnterEvent* e)
554 {
555 AlbumModelDragDropHandler* const handler = m_albumModel->dragDropHandler();
556
557 if (handler && handler->acceptsMimeData(e->mimeData()))
558 {
559 setState(DraggingState);
560 e->accept();
561 }
562 else
563 {
564 e->ignore();
565 }
566 }
567
568 void AbstractAlbumTreeView::dragMoveEvent(QDragMoveEvent* e)
569 {
570 QTreeView::dragMoveEvent(e);
571 AlbumModelDragDropHandler* const handler = m_albumModel->dragDropHandler();
572
573 if (handler)
574 {
575
576 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
577
578 const QModelIndex index = indexVisuallyAt(e->position().toPoint());
579
580 #else
581
582 const QModelIndex index = indexVisuallyAt(e->pos());
583
584 #endif
585
586 const QModelIndex source = m_albumFilterModel->mapToSourceAlbumModel(index);
587 const Qt::DropAction action = handler->accepts(e, source);
588
589 if (action == Qt::IgnoreAction)
590 {
591 m_albumModel->setDropIndex(QModelIndex());
592 e->ignore();
593 }
594 else
595 {
596 m_albumModel->setDropIndex(source);
597 e->setDropAction(action);
598 e->accept();
599 }
600 }
601 }
602
603 void AbstractAlbumTreeView::dragLeaveEvent(QDragLeaveEvent* e)
604 {
605 QTreeView::dragLeaveEvent(e);
606
607 m_albumModel->setDropIndex(QModelIndex());
608 }
609
610 void AbstractAlbumTreeView::dropEvent(QDropEvent* e)
611 {
612 QTreeView::dropEvent(e);
613 AlbumModelDragDropHandler* const handler = m_albumModel->dragDropHandler();
614
615 if (handler)
616 {
617
618 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
619
620 const QModelIndex index = indexVisuallyAt(e->position().toPoint());
621
622 #else
623
624 const QModelIndex index = indexVisuallyAt(e->pos());
625
626 #endif
627
628 if (handler->dropEvent(this, e, m_albumFilterModel->mapToSourceAlbumModel(index)))
629 {
630 e->accept();
631 }
632 else
633 {
634 m_albumModel->setDropIndex(QModelIndex());
635 }
636 }
637 }
638
639 bool AbstractAlbumTreeView::viewportEvent(QEvent* event)
640 {
641 return QTreeView::viewportEvent(event);
642 }
643
644 QList<Album*> AbstractAlbumTreeView::selectedItems()
645 {
646 return selectedAlbums<Album>(selectionModel(), m_albumFilterModel);
647 }
648
649 void AbstractAlbumTreeView::doLoadState()
650 {
651 KConfigGroup configGroup = getConfigGroup();
652 /*
653 qCDebug(DIGIKAM_GENERAL_LOG) << "Loading view state from " << this << configGroup.name() << objectName();
654 */
655 // extract the selection from the config
656
657 const QStringList selection = configGroup.readEntry(entryName(d->configSelectionEntry), QStringList());
658 /*
659 qCDebug(DIGIKAM_GENERAL_LOG) << "selection: " << selection;
660 */
661 for (const QString& key : std::as_const(selection))
662 {
663 bool validId;
664 const int id = key.toInt(&validId);
665
666 if (validId)
667 {
668 d->statesByAlbumId[id].selected = true;
669 }
670 }
671
672 // extract expansion state from config
673
674 const QStringList expansion = configGroup.readEntry(entryName(d->configExpansionEntry), QStringList());
675 /*
676 qCDebug(DIGIKAM_GENERAL_LOG) << "expansion: " << expansion;
677 */
678 // If no expansion was done, at least expand the root albums
679
680 if (expansion.isEmpty())
681 {
682 QList<AlbumRootInfo> roots = CoreDbAccess().db()->getAlbumRoots();
683
684 for (const AlbumRootInfo& info : std::as_const(roots))
685 {
686 int albumId = CoreDbAccess().db()->getAlbumForPath(info.id, QLatin1String("/"), false);
687
688 if (albumId != -1)
689 {
690 d->statesByAlbumId[albumId].expanded = true;
691 }
692 }
693 }
694 else
695 {
696 for (const QString& key : std::as_const(expansion))
697 {
698 bool validId;
699 const int id = key.toInt(&validId);
700
701 if (validId)
702 {
703 d->statesByAlbumId[id].expanded = true;
704 }
705 }
706 }
707
708 // extract current index from config
709
710 const QString key = configGroup.readEntry(entryName(d->configCurrentIndexEntry), QString());
711 /*
712 qCDebug(DIGIKAM_GENERAL_LOG) << "currentIndex: " << key;
713 */
714 bool validId;
715 const int id = key.toInt(&validId);
716
717 if (validId)
718 {
719 d->statesByAlbumId[id].currentIndex = true;
720 }
721
722 /*
723 for (QMap<int, Digikam::State>::iterator it = d->statesByAlbumId.begin() ; it
724 != d->statesByAlbumId.end() ; ++it)
725 {
726 qCDebug(DIGIKAM_GENERAL_LOG) << "id = " << it.key() << ": recovered state (selected = "
727 << it.value().selected << ", expanded = "
728 << it.value().expanded << ", currentIndex = "
729 << it.value().currentIndex << ")";
730 }
731 */
732
733 // initial restore run, for everything already loaded
734 /*
735 qCDebug(DIGIKAM_GENERAL_LOG) << "initial restore run with " << model()->rowCount() << " rows";
736 */
737 restoreStateForHierarchy(QModelIndex(), d->statesByAlbumId);
738
739 // also restore the sorting order
740
741 sortByColumn(configGroup.readEntry(entryName(d->configSortColumnEntry), 0),
742 (Qt::SortOrder) configGroup.readEntry(entryName(d->configSortOrderEntry), (int)Qt::AscendingOrder));
743
744 // use a timer to scroll to the first possible selected album
745
746 QTimer::singleShot(200, this, SLOT(scrollToSelectedAlbum()));
747 }
748
749 void AbstractAlbumTreeView::restoreStateForHierarchy(const QModelIndex& index, const QMap<int, Digikam::State>& stateStore)
750 {
751 restoreState(index, stateStore);
752
753 // do a recursive call of the state restoration
754
755 for (int i = 0 ; i < model()->rowCount(index) ; ++i)
756 {
757 const QModelIndex child = model()->index(i, 0, index);
758 restoreStateForHierarchy(child, stateStore);
759 }
760 }
761
762 void AbstractAlbumTreeView::restoreState(const QModelIndex& index, const QMap<int, Digikam::State>& stateStore)
763 {
764 const Album* const album = albumFilterModel()->albumForIndex(index);
765
766 if (album && stateStore.contains(album->id()))
767 {
768
769 Digikam::State state = stateStore.value(album->id());
770
771 /*
772 qCDebug(DIGIKAM_GENERAL_LOG) << "Trying to restore state of album " << album->title() << "(" <<album->id() << ")"
773 << ": state(selected = " << state.selected
774 << ", expanded = " << state.expanded
775 << ", currentIndex = " << state.currentIndex << ")" << this;
776 */
777 // Block signals to prevent that the searches started when the last
778 // selected index is restored when loading the GUI
779
780 selectionModel()->blockSignals(true);
781
782 if (state.selected)
783 {
784 /*
785 qCDebug(DIGIKAM_GENERAL_LOG) << "Selecting" << album->title();
786 */
787 selectionModel()->select(index, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
788 }
789
790 // Restore expansion state but ensure that the root album is always expanded
791
792 if (!album->isRoot())
793 {
794 setExpanded(index, state.expanded);
795 }
796 else
797 {
798 setExpanded(index, true);
799 }
800
801 // Restore the current index
802
803 if (state.currentIndex)
804 {
805 /*
806 qCDebug(DIGIKAM_GENERAL_LOG) << "Setting current index" << album->title() << "(" << album->id() << ")";
807 */
808 selectionModel()->setCurrentIndex(index, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
809 }
810
811 selectionModel()->blockSignals(false);
812 }
813 }
814
815 void AbstractAlbumTreeView::rowsInserted(const QModelIndex& parent, int start, int end)
816 {
817 QTreeView::rowsInserted(parent, start, end);
818
819 if (!d->statesByAlbumId.isEmpty())
820 {
821 /*
822 qCDebug(DIGIKAM_GENERAL_LOG) << "slot rowInserted called with index = " << index
823 << ", start = " << start << ", end = " << end
824 << "remaining ids" << d->statesByAlbumId.keys();
825 */
826 // Restore state for parent a second time - expansion can only be restored if there are children
827
828 restoreState(parent, d->statesByAlbumId);
829
830 for (int i = start ; i <= end ; ++i)
831 {
832 const QModelIndex child = model()->index(i, 0, parent);
833 restoreState(child, d->statesByAlbumId);
834 }
835 }
836 }
837
838 void AbstractAlbumTreeView::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
839 {
840 QTreeView::rowsAboutToBeRemoved(parent, start, end);
841
842 // Clean up map if album id is reused for a new album
843
844 if (!d->statesByAlbumId.isEmpty())
845 {
846 for (int i = start ; i <= end ; ++i)
847 {
848 const QModelIndex child = model()->index(i, 0, parent);
849 const Album* const album = albumModel()->albumForIndex(child);
850
851 if (album)
852 {
853 d->statesByAlbumId.remove(album->id());
854 }
855 }
856 }
857 }
858
859 void AbstractAlbumTreeView::adaptColumnsToContent()
860 {
861 resizeColumnToContents(0);
862 }
863
864 void AbstractAlbumTreeView::scrollToSelectedAlbum()
865 {
866 const QModelIndexList selected = selectedIndexes();
867
868 if (!selected.isEmpty())
869 {
870 scrollTo(selected.first(), PositionAtCenter);
871 horizontalScrollBar()->setValue(0);
872 }
873 }
874
875 void AbstractAlbumTreeView::expandEverything(const QModelIndex& index)
876 {
877 for (int row = 0 ; row < albumFilterModel()->rowCount(index) ; ++row)
878 {
879 const QModelIndex rowIndex = albumFilterModel()->index(row, 0, index);
880 expand(rowIndex);
881 expandEverything(rowIndex);
882 }
883 }
884
885 void AbstractAlbumTreeView::slotExpandNode()
886 {
887 QItemSelectionModel* const model = selectionModel();
888 QModelIndexList selected = model->selectedIndexes();
889
890 for (const QModelIndex& index : std::as_const(selected))
891 {
892 expandRecursively(index);
893 }
894 }
895
896 void AbstractAlbumTreeView::slotCollapseNode()
897 {
898 QItemSelectionModel* const model = selectionModel();
899 QModelIndexList selected = model->selectedIndexes();
900
901 QQueue<QModelIndex> greyNodes;
902
903 for (const QModelIndex& index : std::as_const(selected))
904 {
905 greyNodes.append(index);
906 collapse(index);
907 }
908
909 while (!greyNodes.isEmpty())
910 {
911 QModelIndex current = greyNodes.dequeue();
912
913 if (!current.isValid())
914 {
915 continue;
916 }
917
918 int it = 0;
919 QModelIndex child = current.model()->index(it++, 0, current);
920
921 while (child.isValid())
922 {
923 collapse(child);
924 greyNodes.enqueue(child);
925 child = current.model()->index(it++, 0, current);
926 }
927 }
928 }
929
930 void AbstractAlbumTreeView::slotCollapseAllNodes()
931 {
932 QQueue<QModelIndex> greyNodes;
933 greyNodes.append(m_albumFilterModel->rootAlbumIndex());
934
935 while (!greyNodes.isEmpty())
936 {
937 QModelIndex current = greyNodes.dequeue();
938
939 if (!current.isValid())
940 {
941 continue;
942 }
943
944 int it = 0;
945 QModelIndex child = current.model()->index(it++, 0, current);
946
947 while (child.isValid())
948 {
949 collapse(child);
950 greyNodes.enqueue(child);
951 child = current.model()->index(it++, 0, current);
952 }
953 }
954 }
955
956 void AbstractAlbumTreeView::adaptColumnsOnDataChange(const QModelIndex& topLeft, const QModelIndex& bottomRight)
957 {
958 Q_UNUSED(topLeft);
959 Q_UNUSED(bottomRight);
960
961 if (!d->resizeColumnsTimer->isActive())
962 {
963 d->resizeColumnsTimer->start();
964 }
965 }
966
967 void AbstractAlbumTreeView::adaptColumnsOnRowChange(const QModelIndex& parent, int start, int end)
968 {
969 Q_UNUSED(parent);
970 Q_UNUSED(start);
971 Q_UNUSED(end);
972
973 if (!d->resizeColumnsTimer->isActive())
974 {
975 d->resizeColumnsTimer->start();
976 }
977 }
978
979 void AbstractAlbumTreeView::adaptColumnsOnLayoutChange()
980 {
981 if (!d->resizeColumnsTimer->isActive())
982 {
983 d->resizeColumnsTimer->start();
984 }
985 }
986
987 void AbstractAlbumTreeView::doSaveState()
988 {
989 KConfigGroup configGroup = getConfigGroup();
990
991 QList<int> selection, expansion;
992
993 for (int i = 0 ; i < model()->rowCount() ; ++i)
994 {
995 const QModelIndex index = model()->index(i, 0);
996 saveStateRecursive(index, selection, expansion);
997 }
998
999 const Album* const selectedAlbum = albumFilterModel()->albumForIndex(selectionModel()->currentIndex());
1000 QString currentIndex;
1001
1002 if (selectedAlbum)
1003 {
1004 currentIndex = QString::number(selectedAlbum->id());
1005 }
1006
1007 configGroup.writeEntry(entryName(d->configSelectionEntry), selection);
1008 configGroup.writeEntry(entryName(d->configExpansionEntry), expansion);
1009 configGroup.writeEntry(entryName(d->configCurrentIndexEntry), currentIndex);
1010 configGroup.writeEntry(entryName(d->configSortColumnEntry), albumFilterModel()->sortColumn());
1011 configGroup.writeEntry(entryName(d->configSortOrderEntry), int(albumFilterModel()->sortOrder()));
1012 }
1013
1014 void AbstractAlbumTreeView::saveStateRecursive(const QModelIndex& index, QList<int>& selection, QList<int>& expansion)
1015 {
1016 const Album* const album = albumFilterModel()->albumForIndex(index);
1017
1018 if (album)
1019 {
1020 const int id = album->id();
1021
1022 if (selectionModel()->isSelected(index))
1023 {
1024 selection.append(id);
1025 }
1026
1027 if (isExpanded(index))
1028 {
1029 expansion.append(id);
1030 }
1031 }
1032
1033 for (int i = 0 ; i < model()->rowCount(index) ; ++i)
1034 {
1035 const QModelIndex child = model()->index(i, 0, index);
1036 saveStateRecursive(child, selection, expansion);
1037 }
1038 }
1039
1040 void AbstractAlbumTreeView::setEnableContextMenu(const bool enable)
1041 {
1042 d->enableContextMenu = enable;
1043 }
1044
1045 bool AbstractAlbumTreeView::showContextMenuAt(QContextMenuEvent* event, Album* albumForEvent)
1046 {
1047 Q_UNUSED(event);
1048
1049 return albumForEvent;
1050 }
1051
1052 void AbstractAlbumTreeView::setContextMenuIcon(const QPixmap& pixmap)
1053 {
1054 d->contextMenuIcon = pixmap;
1055 }
1056
1057 void AbstractAlbumTreeView::setContextMenuTitle(const QString& title)
1058 {
1059 d->contextMenuTitle = title;
1060 }
1061
1062 QPixmap AbstractAlbumTreeView::contextMenuIcon() const
1063 {
1064 return d->contextMenuIcon;
1065 }
1066
1067 QString AbstractAlbumTreeView::contextMenuTitle() const
1068 {
1069 return d->contextMenuTitle;
1070 }
1071
1072 void AbstractAlbumTreeView::addContextMenuElement(ContextMenuElement* element)
1073 {
1074 d->contextMenuElements << element;
1075 }
1076
1077 void AbstractAlbumTreeView::removeContextMenuElement(ContextMenuElement* element)
1078 {
1079 d->contextMenuElements.removeAll(element);
1080 }
1081
1082 QList<AbstractAlbumTreeView::ContextMenuElement*> AbstractAlbumTreeView::contextMenuElements() const
1083 {
1084 return d->contextMenuElements;
1085 }
1086
1087 void AbstractAlbumTreeView::contextMenuEvent(QContextMenuEvent* event)
1088 {
1089 if (!d->enableContextMenu)
1090 {
1091 return;
1092 }
1093
1094 Album* const album = albumFilterModel()->albumForIndex(indexAt(event->pos()));
1095
1096 if (!album)
1097 {
1098 return;
1099 }
1100
1101 if (album->isTrashAlbum())
1102 {
1103 QMenu* const trashAlbumMenu = new QMenu(this);
1104 ContextMenuHelper cmhelper(trashAlbumMenu);
1105 addCustomContextMenuActions(cmhelper, album);
1106
1107 QAction* emptyTrashAction = new QAction(QIcon::fromTheme(QLatin1String("edit-delete")),
1108 i18n("Empty Trash"), this);
1109
1110 connect(emptyTrashAction, SIGNAL(triggered()),
1111 AlbumManager::instance(), SIGNAL(signalEmptyTrash()));
1112
1113 cmhelper.addAction(emptyTrashAction);
1114 AlbumPointer<Album> albumPointer(album);
1115 QAction* const choice = cmhelper.exec(QCursor::pos());
1116 handleCustomContextMenuAction(choice, albumPointer);
1117
1118 return;
1119 }
1120
1121 if (!showContextMenuAt(event, album))
1122 {
1123 return;
1124 }
1125
1126 // switch to the selected album if need
1127
1128 if (d->selectOnContextMenu)
1129 {
1130 setCurrentAlbums(QList<Album*>() << album);
1131 }
1132
1133 // --------------------------------------------------------
1134
1135 QMenu* const popmenu = new QMenu(this);
1136 popmenu->addSection(contextMenuIcon(), contextMenuTitle());
1137 ContextMenuHelper cmhelper(popmenu);
1138
1139 addCustomContextMenuActions(cmhelper, album);
1140
1141 for (ContextMenuElement* const element : std::as_const(d->contextMenuElements))
1142 {
1143 element->addActions(this, cmhelper, album);
1144 }
1145
1146 AlbumPointer<Album> albumPointer(album);
1147 QAction* const choice = cmhelper.exec(QCursor::pos());
1148 handleCustomContextMenuAction(choice, albumPointer);
1149 }
1150
1151 void AbstractAlbumTreeView::setSelectOnContextMenu(const bool select)
1152 {
1153 d->selectOnContextMenu = select;
1154 }
1155
1156 void AbstractAlbumTreeView::addCustomContextMenuActions(ContextMenuHelper& cmh, Album* album)
1157 {
1158 Q_UNUSED(cmh);
1159 Q_UNUSED(album);
1160 }
1161
1162 void AbstractAlbumTreeView::handleCustomContextMenuAction(QAction* action, const AlbumPointer<Album>& album)
1163 {
1164 Q_UNUSED(action);
1165 Q_UNUSED(album);
1166 }
1167
1168 void AbstractAlbumTreeView::albumSettingsChanged()
1169 {
1170 setFont(ApplicationSettings::instance()->getTreeViewFont());
1171
1172 if (d->delegate)
1173 {
1174 d->delegate->updateHeight();
1175 }
1176 }
1177
1178 void AbstractAlbumTreeView::slotScrollBarValueChanged(int value)
1179 {
1180 if (m_lastScrollBarValue == -1)
1181 {
1182 m_lastScrollBarValue = value;
1183 }
1184
1185 if ((value == 0) && (m_lastScrollBarValue > 0))
1186 {
1187 horizontalScrollBar()->setValue(m_lastScrollBarValue);
1188 }
1189 }
1190
1191 void AbstractAlbumTreeView::slotScrollBarActionTriggered(int action)
1192 {
1193 if (
1194 (action == QAbstractSlider::SliderMove) ||
1195 (action == QAbstractSlider::SliderToMinimum) ||
1196 (action == QAbstractSlider::SliderPageStepSub) ||
1197 (action == QAbstractSlider::SliderSingleStepSub)
1198 )
1199 {
1200 m_lastScrollBarValue = -1;
1201 }
1202 }
1203
1204 } // namespace Digikam
1205
1206 #include "moc_abstractalbumtreeview.cpp"
1207
1208 #include "moc_abstractalbumtreeview_p.cpp"