2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2012 Frank Reininghaus <frank78ac@googlemail.com>
5 * Based on the Itemviews NG project from Trolltech Labs
7 * SPDX-License-Identifier: GPL-2.0-or-later
10 #include "kitemlistcontroller.h"
12 #include "kitemlistselectionmanager.h"
13 #include "kitemlistview.h"
14 #include "private/kitemlistkeyboardsearchmanager.h"
15 #include "private/kitemlistrubberband.h"
16 #include "views/draganddrophelper.h"
18 #include <KTwoFingerSwipe>
19 #include <KTwoFingerTap>
20 #include <KUrlMimeData>
22 #include <QAccessible>
23 #include <QApplication>
26 #include <QGraphicsScene>
27 #include <QGraphicsSceneEvent>
28 #include <QGraphicsView>
30 #include <QStyleHints>
32 #include <QTouchEvent>
34 KItemListController::KItemListController(KItemModelBase
* model
, KItemListView
* view
, QObject
* parent
) :
36 m_singleClickActivationEnforced(false),
37 m_selectionMode(false),
38 m_selectionTogglePressed(false),
39 m_clearSelectionIfItemsAreNotDragged(false),
40 m_isSwipeGesture(false),
41 m_dragActionOrRightClick(false),
42 m_scrollerIsScrolling(false),
43 m_pinchGestureInProgress(false),
45 m_isTouchEvent(false),
46 m_selectionBehavior(NoSelection
),
47 m_autoActivationBehavior(ActivationAndExpansion
),
48 m_mouseDoubleClickAction(ActivateItemOnly
),
51 m_selectionManager(new KItemListSelectionManager(this)),
52 m_keyboardManager(new KItemListKeyboardSearchManager(this)),
53 m_pressedIndex(std::nullopt
),
55 m_autoActivationTimer(nullptr),
56 m_longPressDetectionTimer(nullptr),
57 m_swipeGesture(Qt::CustomGesture
),
58 m_twoFingerTapGesture(Qt::CustomGesture
),
60 m_keyboardAnchorIndex(-1),
61 m_keyboardAnchorPos(0)
63 connect(m_keyboardManager
, &KItemListKeyboardSearchManager::changeCurrentItem
,
64 this, &KItemListController::slotChangeCurrentItem
);
65 connect(m_selectionManager
, &KItemListSelectionManager::currentChanged
,
66 m_keyboardManager
, &KItemListKeyboardSearchManager::slotCurrentChanged
);
67 connect(m_selectionManager
, &KItemListSelectionManager::selectionChanged
,
68 m_keyboardManager
, &KItemListKeyboardSearchManager::slotSelectionChanged
);
70 m_autoActivationTimer
= new QTimer(this);
71 m_autoActivationTimer
->setSingleShot(true);
72 m_autoActivationTimer
->setInterval(-1);
73 connect(m_autoActivationTimer
, &QTimer::timeout
, this, &KItemListController::slotAutoActivationTimeout
);
75 m_longPressDetectionTimer
= new QTimer(this);
76 m_longPressDetectionTimer
->setSingleShot(true);
77 m_longPressDetectionTimer
->setInterval(QGuiApplication::styleHints()->mousePressAndHoldInterval());
78 connect(m_longPressDetectionTimer
, &QTimer::timeout
, this, [this]() {
79 if (!m_selectionMode
) {
80 Q_EMIT
selectionModeChangeRequested(true);
87 m_swipeGesture
= QGestureRecognizer::registerRecognizer(new KTwoFingerSwipeRecognizer());
88 m_twoFingerTapGesture
= QGestureRecognizer::registerRecognizer(new KTwoFingerTapRecognizer());
89 view
->grabGesture(m_swipeGesture
);
90 view
->grabGesture(m_twoFingerTapGesture
);
91 view
->grabGesture(Qt::TapGesture
);
92 view
->grabGesture(Qt::TapAndHoldGesture
);
93 view
->grabGesture(Qt::PinchGesture
);
96 KItemListController::~KItemListController()
105 void KItemListController::setModel(KItemModelBase
* model
)
107 if (m_model
== model
) {
111 KItemModelBase
* oldModel
= m_model
;
113 oldModel
->deleteLater();
118 m_model
->setParent(this);
122 m_view
->setModel(m_model
);
125 m_selectionManager
->setModel(m_model
);
127 Q_EMIT
modelChanged(m_model
, oldModel
);
130 KItemModelBase
* KItemListController::model() const
135 KItemListSelectionManager
* KItemListController::selectionManager() const
137 return m_selectionManager
;
140 void KItemListController::setView(KItemListView
* view
)
142 if (m_view
== view
) {
146 KItemListView
* oldView
= m_view
;
148 disconnect(oldView
, &KItemListView::scrollOffsetChanged
, this, &KItemListController::slotViewScrollOffsetChanged
);
149 oldView
->deleteLater();
155 m_view
->setParent(this);
156 m_view
->setController(this);
157 m_view
->setModel(m_model
);
158 connect(m_view
, &KItemListView::scrollOffsetChanged
, this, &KItemListController::slotViewScrollOffsetChanged
);
159 updateExtendedSelectionRegion();
162 Q_EMIT
viewChanged(m_view
, oldView
);
165 KItemListView
* KItemListController::view() const
170 void KItemListController::setSelectionBehavior(SelectionBehavior behavior
)
172 m_selectionBehavior
= behavior
;
173 updateExtendedSelectionRegion();
176 KItemListController::SelectionBehavior
KItemListController::selectionBehavior() const
178 return m_selectionBehavior
;
181 void KItemListController::setAutoActivationBehavior(AutoActivationBehavior behavior
)
183 m_autoActivationBehavior
= behavior
;
186 KItemListController::AutoActivationBehavior
KItemListController::autoActivationBehavior() const
188 return m_autoActivationBehavior
;
191 void KItemListController::setMouseDoubleClickAction(MouseDoubleClickAction action
)
193 m_mouseDoubleClickAction
= action
;
196 KItemListController::MouseDoubleClickAction
KItemListController::mouseDoubleClickAction() const
198 return m_mouseDoubleClickAction
;
201 int KItemListController::indexCloseToMousePressedPosition() const
203 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_view
->m_visibleGroups
);
204 while (it
.hasNext()) {
206 KItemListGroupHeader
*groupHeader
= it
.value();
207 const QPointF mappedToGroup
= groupHeader
->mapFromItem(nullptr, m_pressedMousePos
);
208 if (groupHeader
->contains(mappedToGroup
)) {
209 return it
.key()->index();
215 void KItemListController::setAutoActivationDelay(int delay
)
217 m_autoActivationTimer
->setInterval(delay
);
220 int KItemListController::autoActivationDelay() const
222 return m_autoActivationTimer
->interval();
225 void KItemListController::setSingleClickActivationEnforced(bool singleClick
)
227 m_singleClickActivationEnforced
= singleClick
;
230 bool KItemListController::singleClickActivationEnforced() const
232 return m_singleClickActivationEnforced
;
235 void KItemListController::setSelectionModeEnabled(bool enabled
)
237 m_selectionMode
= enabled
;
240 bool KItemListController::selectionMode() const
242 return m_selectionMode
;
245 bool KItemListController::keyPressEvent(QKeyEvent
* event
)
247 int index
= m_selectionManager
->currentItem();
248 int key
= event
->key();
250 // Handle the expanding/collapsing of items
251 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
)) {
252 if (key
== Qt::Key_Right
) {
253 if (m_model
->setExpanded(index
, true)) {
256 } else if (key
== Qt::Key_Left
) {
257 if (m_model
->setExpanded(index
, false)) {
263 const bool shiftPressed
= event
->modifiers() & Qt::ShiftModifier
;
264 const bool controlPressed
= event
->modifiers() & Qt::ControlModifier
;
265 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
266 const bool navigationPressed
= key
== Qt::Key_Home
|| key
== Qt::Key_End
||
267 key
== Qt::Key_PageUp
|| key
== Qt::Key_PageDown
||
268 key
== Qt::Key_Up
|| key
== Qt::Key_Down
||
269 key
== Qt::Key_Left
|| key
== Qt::Key_Right
;
271 const int itemCount
= m_model
->count();
273 // For horizontal scroll orientation, transform
274 // the arrow keys to simplify the event handling.
275 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
277 case Qt::Key_Up
: key
= Qt::Key_Left
; break;
278 case Qt::Key_Down
: key
= Qt::Key_Right
; break;
279 case Qt::Key_Left
: key
= Qt::Key_Up
; break;
280 case Qt::Key_Right
: key
= Qt::Key_Down
; break;
285 const bool selectSingleItem
= m_selectionBehavior
!= NoSelection
&& itemCount
== 1 && navigationPressed
;
287 if (selectSingleItem
) {
288 const int current
= m_selectionManager
->currentItem();
289 m_selectionManager
->setSelected(current
);
296 m_keyboardAnchorIndex
= index
;
297 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
301 index
= itemCount
- 1;
302 m_keyboardAnchorIndex
= index
;
303 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
308 const int expandedParentsCount
= m_model
->expandedParentsCount(index
);
309 if (expandedParentsCount
== 0) {
312 // Go to the parent of the current item.
315 } while (index
> 0 && m_model
->expandedParentsCount(index
) == expandedParentsCount
);
317 m_keyboardAnchorIndex
= index
;
318 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
323 if (index
< itemCount
- 1) {
325 m_keyboardAnchorIndex
= index
;
326 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
331 updateKeyboardAnchor();
332 index
= previousRowIndex(index
);
336 updateKeyboardAnchor();
337 index
= nextRowIndex(index
);
341 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
342 // The new current index should correspond to the first item in the current column.
343 int newIndex
= qMax(index
- 1, 0);
344 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() < m_view
->itemRect(index
).topLeft().y()) {
346 newIndex
= qMax(index
- 1, 0);
348 m_keyboardAnchorIndex
= index
;
349 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
351 const qreal currentItemBottom
= m_view
->itemRect(index
).bottomLeft().y();
352 const qreal height
= m_view
->geometry().height();
354 // The new current item should be the first item in the current
355 // column whose itemRect's top coordinate is larger than targetY.
356 const qreal targetY
= currentItemBottom
- height
;
358 updateKeyboardAnchor();
359 int newIndex
= previousRowIndex(index
);
362 updateKeyboardAnchor();
363 newIndex
= previousRowIndex(index
);
364 } while (m_view
->itemRect(newIndex
).topLeft().y() > targetY
&& newIndex
!= index
);
368 case Qt::Key_PageDown
:
369 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
370 // The new current index should correspond to the last item in the current column.
371 int newIndex
= qMin(index
+ 1, m_model
->count() - 1);
372 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() > m_view
->itemRect(index
).topLeft().y()) {
374 newIndex
= qMin(index
+ 1, m_model
->count() - 1);
376 m_keyboardAnchorIndex
= index
;
377 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
379 const qreal currentItemTop
= m_view
->itemRect(index
).topLeft().y();
380 const qreal height
= m_view
->geometry().height();
382 // The new current item should be the last item in the current
383 // column whose itemRect's bottom coordinate is smaller than targetY.
384 const qreal targetY
= currentItemTop
+ height
;
386 updateKeyboardAnchor();
387 int newIndex
= nextRowIndex(index
);
390 updateKeyboardAnchor();
391 newIndex
= nextRowIndex(index
);
392 } while (m_view
->itemRect(newIndex
).bottomLeft().y() < targetY
&& newIndex
!= index
);
397 case Qt::Key_Return
: {
398 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
399 if (selectedItems
.count() >= 2) {
400 Q_EMIT
itemsActivated(selectedItems
);
401 } else if (selectedItems
.count() == 1) {
402 Q_EMIT
itemActivated(selectedItems
.first());
404 Q_EMIT
itemActivated(index
);
410 // Emit the signal itemContextMenuRequested() in case if at least one
411 // item is selected. Otherwise the signal viewContextMenuRequested() will be emitted.
412 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
414 if (selectedItems
.count() >= 2) {
415 const int currentItemIndex
= m_selectionManager
->currentItem();
416 index
= selectedItems
.contains(currentItemIndex
)
417 ? currentItemIndex
: selectedItems
.first();
418 } else if (selectedItems
.count() == 1) {
419 index
= selectedItems
.first();
423 const QRectF contextRect
= m_view
->itemContextRect(index
);
424 const QPointF
pos(m_view
->scene()->views().first()->mapToGlobal(contextRect
.bottomRight().toPoint()));
425 Q_EMIT
itemContextMenuRequested(index
, pos
);
427 Q_EMIT
viewContextMenuRequested(QCursor::pos());
433 if (m_selectionMode
) {
434 Q_EMIT
selectionModeChangeRequested(false);
435 } else if (m_selectionBehavior
!= SingleSelection
) {
436 m_selectionManager
->clearSelection();
438 m_keyboardManager
->cancelSearch();
439 Q_EMIT
escapePressed();
443 if (m_selectionBehavior
== MultiSelection
) {
444 if (controlPressed
) {
445 // Toggle the selection state of the current item.
446 m_selectionManager
->endAnchoredSelection();
447 m_selectionManager
->setSelected(index
, 1, KItemListSelectionManager::Toggle
);
448 m_selectionManager
->beginAnchoredSelection(index
);
451 // Select the current item if it is not selected yet.
452 const int current
= m_selectionManager
->currentItem();
453 if (!m_selectionManager
->isSelected(current
)) {
454 m_selectionManager
->setSelected(current
);
459 Q_FALLTHROUGH(); // fall through to the default case and add the Space to the current search string.
461 m_keyboardManager
->addKeys(event
->text());
462 // Make sure unconsumed events get propagated up the chain. #302329
467 if (m_selectionManager
->currentItem() != index
) {
468 switch (m_selectionBehavior
) {
470 m_selectionManager
->setCurrentItem(index
);
473 case SingleSelection
:
474 m_selectionManager
->setCurrentItem(index
);
475 m_selectionManager
->clearSelection();
476 m_selectionManager
->setSelected(index
, 1);
480 if (controlPressed
) {
481 m_selectionManager
->endAnchoredSelection();
484 m_selectionManager
->setCurrentItem(index
);
486 if (!shiftOrControlPressed
) {
487 m_selectionManager
->clearSelection();
488 m_selectionManager
->setSelected(index
, 1);
492 m_selectionManager
->beginAnchoredSelection(index
);
498 if (navigationPressed
) {
499 m_view
->scrollToItem(index
);
504 void KItemListController::slotChangeCurrentItem(const QString
& text
, bool searchFromNextItem
)
506 if (!m_model
|| m_model
->count() == 0) {
510 if (searchFromNextItem
) {
511 const int currentIndex
= m_selectionManager
->currentItem();
512 index
= m_model
->indexForKeyboardSearch(text
, (currentIndex
+ 1) % m_model
->count());
514 index
= m_model
->indexForKeyboardSearch(text
, 0);
517 m_selectionManager
->setCurrentItem(index
);
519 if (m_selectionBehavior
!= NoSelection
) {
520 m_selectionManager
->replaceSelection(index
);
521 m_selectionManager
->beginAnchoredSelection(index
);
524 m_view
->scrollToItem(index
);
528 void KItemListController::slotAutoActivationTimeout()
530 if (!m_model
|| !m_view
) {
534 const int index
= m_autoActivationTimer
->property("index").toInt();
535 if (index
< 0 || index
>= m_model
->count()) {
539 /* m_view->isUnderMouse() fixes a bug in the Folder-View-Panel and in the
542 * Bug: When you drag a file onto a Folder-View-Item or a Places-Item and
543 * then move away before the auto-activation timeout triggers, than the
544 * item still becomes activated/expanded.
546 * See Bug 293200 and 305783
548 if (m_model
->supportsDropping(index
) && m_view
->isUnderMouse()) {
549 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
)) {
550 const bool expanded
= m_model
->isExpanded(index
);
551 m_model
->setExpanded(index
, !expanded
);
552 } else if (m_autoActivationBehavior
!= ExpansionOnly
) {
553 Q_EMIT
itemActivated(index
);
558 bool KItemListController::inputMethodEvent(QInputMethodEvent
* event
)
564 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent
* event
, const QTransform
& transform
)
568 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& m_isTouchEvent
) {
576 m_pressedMousePos
= transform
.map(event
->pos());
577 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
579 const Qt::MouseButtons buttons
= event
->buttons();
581 if (!onPress(event
->screenPos(), event
->pos(), event
->modifiers(), buttons
)) {
589 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
, const QTransform
& transform
)
595 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
596 m_view
->m_tapAndHoldIndicator
->setActive(false);
599 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !m_dragActionOrRightClick
&& m_isTouchEvent
) {
603 const QPointF pos
= transform
.map(event
->pos());
604 if ((pos
- m_pressedMousePos
).manhattanLength() >= QApplication::startDragDistance()) {
605 m_longPressDetectionTimer
->stop();
608 if (m_pressedIndex
.has_value() && !m_view
->rubberBand()->isActive()) {
609 // Check whether a dragging should be started
610 if (event
->buttons() & Qt::LeftButton
) {
611 if ((pos
- m_pressedMousePos
).manhattanLength() >= QApplication::startDragDistance()) {
612 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
613 // Always assure that the dragged item gets selected. Usually this is already
614 // done on the mouse-press event, but when using the selection-toggle on a
615 // selected item the dragged item is not selected yet.
616 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
618 // A selected item has been clicked to drag all selected items
619 // -> the selection should not be cleared when the mouse button is released.
620 m_clearSelectionIfItemsAreNotDragged
= false;
623 m_mousePress
= false;
627 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
628 if (rubberBand
->isActive()) {
629 QPointF endPos
= transform
.map(event
->pos());
631 // Update the current item.
632 const std::optional
<int> newCurrent
= m_view
->itemAt(endPos
);
633 if (newCurrent
.has_value()) {
634 // It's expected that the new current index is also the new anchor (bug 163451).
635 m_selectionManager
->endAnchoredSelection();
636 m_selectionManager
->setCurrentItem(newCurrent
.value());
637 m_selectionManager
->beginAnchoredSelection(newCurrent
.value());
640 if (m_view
->scrollOrientation() == Qt::Vertical
) {
641 endPos
.ry() += m_view
->scrollOffset();
642 if (m_view
->itemSize().width() < 0) {
643 // Use a special rubberband for views that have only one column and
644 // expand the rubberband to use the whole width of the view.
645 endPos
.setX(m_view
->size().width());
648 endPos
.rx() += m_view
->scrollOffset();
650 rubberBand
->setEndPosition(endPos
);
657 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent
* event
, const QTransform
& transform
)
659 m_mousePress
= false;
660 m_isTouchEvent
= false;
666 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
667 m_view
->m_tapAndHoldIndicator
->setActive(false);
670 m_longPressDetectionTimer
->stop();
672 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
673 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !rubberBand
->isActive() && m_isTouchEvent
) {
677 Q_EMIT
mouseButtonReleased(m_pressedIndex
.value_or(-1), event
->buttons());
679 return onRelease(transform
.map(event
->pos()), event
->modifiers(), event
->button(), false);
682 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent
* event
, const QTransform
& transform
)
684 const QPointF pos
= transform
.map(event
->pos());
685 const std::optional
<int> index
= m_view
->itemAt(pos
);
687 // Expand item if desired - See Bug 295573
688 if (m_mouseDoubleClickAction
!= ActivateItemOnly
) {
689 if (m_view
&& m_model
&& m_view
->supportsItemExpanding() && m_model
->isExpandable(index
.value_or(-1))) {
690 const bool expanded
= m_model
->isExpanded(index
.value());
691 m_model
->setExpanded(index
.value(), !expanded
);
695 if (event
->button() & Qt::RightButton
) {
696 m_selectionManager
->clearSelection();
697 if (index
.has_value()) {
698 m_selectionManager
->setSelected(index
.value());
699 Q_EMIT
itemContextMenuRequested(index
.value(), event
->screenPos());
701 const QRectF headerBounds
= m_view
->headerBoundaries();
702 if (headerBounds
.contains(event
->pos())) {
703 Q_EMIT
headerContextMenuRequested(event
->screenPos());
705 Q_EMIT
viewContextMenuRequested(event
->screenPos());
711 bool emitItemActivated
= !(m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) &&
712 (event
->button() & Qt::LeftButton
) &&
713 index
.has_value() && index
.value() < m_model
->count();
714 if (emitItemActivated
) {
715 Q_EMIT
itemActivated(index
.value());
720 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
725 DragAndDropHelper::clearUrlListMatchesUrlCache();
730 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
735 m_autoActivationTimer
->stop();
736 m_view
->setAutoScroll(false);
737 m_view
->hideDropIndicator();
739 KItemListWidget
* widget
= hoveredWidget();
741 widget
->setHovered(false);
742 Q_EMIT
itemUnhovered(widget
->index());
747 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
749 if (!m_model
|| !m_view
) {
754 QUrl hoveredDir
= m_model
->directory();
755 KItemListWidget
* oldHoveredWidget
= hoveredWidget();
757 const QPointF pos
= transform
.map(event
->pos());
758 KItemListWidget
* newHoveredWidget
= widgetForDropPos(pos
);
760 if (oldHoveredWidget
!= newHoveredWidget
) {
761 m_autoActivationTimer
->stop();
763 if (oldHoveredWidget
) {
764 oldHoveredWidget
->setHovered(false);
765 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
769 if (newHoveredWidget
) {
770 bool droppingBetweenItems
= false;
771 if (m_model
->sortRole().isEmpty()) {
772 // The model supports inserting items between other items.
773 droppingBetweenItems
= (m_view
->showDropIndicator(pos
) >= 0);
776 const int index
= newHoveredWidget
->index();
778 if (m_model
->isDir(index
)) {
779 hoveredDir
= m_model
->url(index
);
782 if (!droppingBetweenItems
) {
783 if (m_model
->supportsDropping(index
)) {
784 // Something has been dragged on an item.
785 m_view
->hideDropIndicator();
786 if (!newHoveredWidget
->isHovered()) {
787 newHoveredWidget
->setHovered(true);
788 Q_EMIT
itemHovered(index
);
791 if (!m_autoActivationTimer
->isActive() && m_autoActivationTimer
->interval() >= 0) {
792 m_autoActivationTimer
->setProperty("index", index
);
793 m_autoActivationTimer
->start();
797 m_autoActivationTimer
->stop();
798 if (newHoveredWidget
&& newHoveredWidget
->isHovered()) {
799 newHoveredWidget
->setHovered(false);
800 Q_EMIT
itemUnhovered(index
);
804 m_view
->hideDropIndicator();
807 if (DragAndDropHelper::urlListMatchesUrl(event
->mimeData()->urls(), hoveredDir
)) {
808 event
->setDropAction(Qt::IgnoreAction
);
811 event
->setDropAction(event
->proposedAction());
817 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
823 m_autoActivationTimer
->stop();
824 m_view
->setAutoScroll(false);
826 const QPointF pos
= transform
.map(event
->pos());
828 int dropAboveIndex
= -1;
829 if (m_model
->sortRole().isEmpty()) {
830 // The model supports inserting of items between other items.
831 dropAboveIndex
= m_view
->showDropIndicator(pos
);
834 if (dropAboveIndex
>= 0) {
835 // Something has been dropped between two items.
836 m_view
->hideDropIndicator();
837 Q_EMIT
aboveItemDropEvent(dropAboveIndex
, event
);
838 } else if (!event
->mimeData()->hasFormat(m_model
->blacklistItemDropEventMimeType())) {
839 // Something has been dropped on an item or on an empty part of the view.
840 const KItemListWidget
*receivingWidget
= widgetForDropPos(pos
);
841 if (receivingWidget
) {
842 Q_EMIT
itemDropEvent(receivingWidget
->index(), event
);
844 Q_EMIT
itemDropEvent(-1, event
);
848 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropEnd
);
849 QAccessible::updateAccessibility(&accessibilityEvent
);
854 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent
* event
, const QTransform
& transform
)
861 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent
* event
, const QTransform
& transform
)
864 if (!m_model
|| !m_view
) {
868 // We identify the widget whose expansionArea had been hovered before this hoverMoveEvent() triggered.
869 // we can't use hoveredWidget() here (it handles the icon+text rect, not the expansion rect)
870 // like hoveredWidget(), we find the hovered widget for the expansion rect
871 const auto visibleItemListWidgets
= m_view
->visibleItemListWidgets();
872 const auto oldHoveredExpansionWidgetIterator
= std::find_if(visibleItemListWidgets
.begin(), visibleItemListWidgets
.end(), [](auto &widget
) {
873 return widget
->expansionAreaHovered();
875 const auto oldHoveredExpansionWidget
= oldHoveredExpansionWidgetIterator
== visibleItemListWidgets
.end() ?
876 std::nullopt
: std::make_optional(*oldHoveredExpansionWidgetIterator
);
878 const auto unhoverOldHoveredWidget
= [&]() {
879 if (auto oldHoveredWidget
= hoveredWidget(); oldHoveredWidget
) {
880 // handle the text+icon one
881 oldHoveredWidget
->setHovered(false);
882 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
886 const auto unhoverOldExpansionWidget
= [&]() {
887 if (oldHoveredExpansionWidget
) {
888 // then the expansion toggle
889 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
893 const QPointF pos
= transform
.map(event
->pos());
894 if (KItemListWidget
*newHoveredWidget
= widgetForPos(pos
); newHoveredWidget
) {
895 // something got hovered, work out which part and set hover for the appropriate widget
896 const auto mappedPos
= newHoveredWidget
->mapFromItem(m_view
, pos
);
897 const bool isOnExpansionToggle
= newHoveredWidget
->expansionToggleRect().contains(mappedPos
);
899 if (isOnExpansionToggle
) {
900 // make sure we unhover the old one first if old!=new
901 if (oldHoveredExpansionWidget
&& *oldHoveredExpansionWidget
!= newHoveredWidget
) {
902 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
904 // we also unhover any old icon+text hovers, in case the mouse movement from icon+text to expansion toggle is too fast (i.e. newHoveredWidget is never null between the transition)
905 unhoverOldHoveredWidget();
908 newHoveredWidget
->setExpansionAreaHovered(true);
910 // make sure we unhover the old one first if old!=new
911 auto oldHoveredWidget
= hoveredWidget();
912 if (oldHoveredWidget
&& oldHoveredWidget
!= newHoveredWidget
) {
913 oldHoveredWidget
->setHovered(false);
914 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
916 // we also unhover any old expansion toggle hovers, in case the mouse movement from expansion toggle to icon+text is too fast (i.e. newHoveredWidget is never null between the transition)
917 unhoverOldExpansionWidget();
919 const bool isOverIconAndText
= newHoveredWidget
->iconRect().contains(mappedPos
) || newHoveredWidget
->textRect().contains(mappedPos
);
920 const bool hasMultipleSelection
= m_selectionManager
->selectedItems().count() > 1;
922 if (hasMultipleSelection
&& !isOverIconAndText
) {
923 // In case we have multiple selections, clicking on any row will deselect the selection.
924 // So, as a visual cue for signalling that clicking anywhere won't select, but clear current highlights,
925 // we disable hover of the *row*(i.e. blank space to the right of the icon+text)
927 // (no-op in this branch for masked hover)
929 newHoveredWidget
->setHoverPosition(mappedPos
);
930 if (oldHoveredWidget
!= newHoveredWidget
) {
931 newHoveredWidget
->setHovered(true);
932 Q_EMIT
itemHovered(newHoveredWidget
->index());
937 // unhover any currently hovered expansion and text+icon widgets
938 unhoverOldHoveredWidget();
939 unhoverOldExpansionWidget();
944 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent
* event
, const QTransform
& transform
)
949 m_mousePress
= false;
950 m_isTouchEvent
= false;
952 if (!m_model
|| !m_view
) {
956 const auto widgets
= m_view
->visibleItemListWidgets();
957 for (KItemListWidget
* widget
: widgets
) {
958 if (widget
->isHovered()) {
959 widget
->setHovered(false);
960 Q_EMIT
itemUnhovered(widget
->index());
966 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent
* event
, const QTransform
& transform
)
973 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent
* event
, const QTransform
& transform
)
980 bool KItemListController::gestureEvent(QGestureEvent
* event
, const QTransform
& transform
)
986 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
987 //we use this to get the right QWidget
988 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
990 if (QGesture
* tap
= event
->gesture(Qt::TapGesture
)) {
991 QTapGesture
* tapGesture
= static_cast<QTapGesture
*>(tap
);
992 if (tapGesture
->state() == Qt::GestureStarted
) {
993 tapTriggered(tapGesture
, transform
);
999 bool accepted
= false;
1001 if (QGesture
* tap
= event
->gesture(Qt::TapGesture
)) {
1002 tapTriggered(static_cast<QTapGesture
*>(tap
), transform
);
1005 if (event
->gesture(Qt::TapAndHoldGesture
)) {
1006 tapAndHoldTriggered(event
, transform
);
1009 if (event
->gesture(Qt::PinchGesture
)) {
1010 pinchTriggered(event
, transform
);
1013 if (event
->gesture(m_swipeGesture
)) {
1014 swipeTriggered(event
, transform
);
1017 if (event
->gesture(m_twoFingerTapGesture
)) {
1018 twoFingerTapTriggered(event
, transform
);
1024 bool KItemListController::touchBeginEvent(QTouchEvent
* event
, const QTransform
& transform
)
1029 m_isTouchEvent
= true;
1033 void KItemListController::tapTriggered(QTapGesture
* tap
, const QTransform
& transform
)
1035 static bool scrollerWasActive
= false;
1037 if (tap
->state() == Qt::GestureStarted
) {
1038 m_dragActionOrRightClick
= false;
1039 m_isSwipeGesture
= false;
1040 m_pinchGestureInProgress
= false;
1041 scrollerWasActive
= m_scrollerIsScrolling
;
1044 if (tap
->state() == Qt::GestureFinished
) {
1045 m_mousePress
= false;
1047 //if at the moment of the gesture start the QScroller was active, the user made the tap
1048 //to stop the QScroller and not to tap on an item
1049 if (scrollerWasActive
) {
1053 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
1054 m_view
->m_tapAndHoldIndicator
->setActive(false);
1057 m_pressedMousePos
= transform
.map(tap
->position());
1058 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1060 if (m_dragActionOrRightClick
) {
1061 onPress(tap
->hotSpot().toPoint(), tap
->position().toPoint(), Qt::NoModifier
, Qt::RightButton
);
1062 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::RightButton
, false);
1063 m_dragActionOrRightClick
= false;
1066 onPress(tap
->hotSpot().toPoint(), tap
->position().toPoint(), Qt::NoModifier
, Qt::LeftButton
);
1067 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::LeftButton
, true);
1069 m_isTouchEvent
= false;
1073 void KItemListController::tapAndHoldTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1076 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
1077 if (!m_isTouchEvent
) {
1081 const QTapAndHoldGesture
* tap
= static_cast<QTapAndHoldGesture
*>(event
->gesture(Qt::TapAndHoldGesture
));
1082 if (tap
->state() == Qt::GestureFinished
) {
1083 //if a pinch gesture is in progress we don't want a TabAndHold gesture
1084 if (m_pinchGestureInProgress
) {
1087 m_pressedMousePos
= transform
.map(event
->mapToGraphicsScene(tap
->position()));
1088 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1090 if (m_pressedIndex
.has_value() && !m_selectionManager
->isSelected(m_pressedIndex
.value())) {
1091 m_selectionManager
->clearSelection();
1092 m_selectionManager
->setSelected(m_pressedIndex
.value());
1093 } else if (!m_pressedIndex
.has_value()) {
1094 m_selectionManager
->clearSelection();
1098 Q_EMIT
scrollerStop();
1100 m_view
->m_tapAndHoldIndicator
->setStartPosition(m_pressedMousePos
);
1101 m_view
->m_tapAndHoldIndicator
->setActive(true);
1103 m_dragActionOrRightClick
= true;
1107 void KItemListController::pinchTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1111 const QPinchGesture
* pinch
= static_cast<QPinchGesture
*>(event
->gesture(Qt::PinchGesture
));
1112 const qreal sensitivityModifier
= 0.2;
1113 static qreal counter
= 0;
1115 if (pinch
->state() == Qt::GestureStarted
) {
1116 m_pinchGestureInProgress
= true;
1119 if (pinch
->state() == Qt::GestureUpdated
) {
1120 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1121 if (m_isSwipeGesture
) {
1124 counter
= counter
+ (pinch
->scaleFactor() - 1);
1125 if (counter
>= sensitivityModifier
) {
1126 Q_EMIT
increaseZoom();
1128 } else if (counter
<= -sensitivityModifier
) {
1129 Q_EMIT
decreaseZoom();
1135 void KItemListController::swipeTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1139 const KTwoFingerSwipe
* swipe
= static_cast<KTwoFingerSwipe
*>(event
->gesture(m_swipeGesture
));
1144 if (swipe
->state() == Qt::GestureStarted
) {
1145 m_isSwipeGesture
= true;
1148 if (swipe
->state() == Qt::GestureCanceled
) {
1149 m_isSwipeGesture
= false;
1152 if (swipe
->state() == Qt::GestureFinished
) {
1153 Q_EMIT
scrollerStop();
1155 if (swipe
->swipeAngle() <= 20 || swipe
->swipeAngle() >= 340) {
1156 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::BackButton
);
1157 } else if (swipe
->swipeAngle() <= 200 && swipe
->swipeAngle() >= 160) {
1158 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::ForwardButton
);
1159 } else if (swipe
->swipeAngle() <= 110 && swipe
->swipeAngle() >= 60) {
1162 m_isSwipeGesture
= true;
1166 void KItemListController::twoFingerTapTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1168 const KTwoFingerTap
* twoTap
= static_cast<KTwoFingerTap
*>(event
->gesture(m_twoFingerTapGesture
));
1174 if (twoTap
->state() == Qt::GestureStarted
) {
1175 m_pressedMousePos
= transform
.map(twoTap
->pos());
1176 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1177 if (m_pressedIndex
.has_value()) {
1178 onPress(twoTap
->screenPos().toPoint(), twoTap
->pos().toPoint(), Qt::ControlModifier
, Qt::LeftButton
);
1179 onRelease(transform
.map(twoTap
->pos()), Qt::ControlModifier
, Qt::LeftButton
, false);
1185 bool KItemListController::processEvent(QEvent
* event
, const QTransform
& transform
)
1191 switch (event
->type()) {
1192 case QEvent::KeyPress
:
1193 return keyPressEvent(static_cast<QKeyEvent
*>(event
));
1194 case QEvent::InputMethod
:
1195 return inputMethodEvent(static_cast<QInputMethodEvent
*>(event
));
1196 case QEvent::GraphicsSceneMousePress
:
1197 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1198 case QEvent::GraphicsSceneMouseMove
:
1199 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1200 case QEvent::GraphicsSceneMouseRelease
:
1201 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1202 case QEvent::GraphicsSceneMouseDoubleClick
:
1203 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1204 case QEvent::GraphicsSceneWheel
:
1205 return wheelEvent(static_cast<QGraphicsSceneWheelEvent
*>(event
), QTransform());
1206 case QEvent::GraphicsSceneDragEnter
:
1207 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1208 case QEvent::GraphicsSceneDragLeave
:
1209 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1210 case QEvent::GraphicsSceneDragMove
:
1211 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1212 case QEvent::GraphicsSceneDrop
:
1213 return dropEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1214 case QEvent::GraphicsSceneHoverEnter
:
1215 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1216 case QEvent::GraphicsSceneHoverMove
:
1217 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1218 case QEvent::GraphicsSceneHoverLeave
:
1219 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1220 case QEvent::GraphicsSceneResize
:
1221 return resizeEvent(static_cast<QGraphicsSceneResizeEvent
*>(event
), transform
);
1222 case QEvent::Gesture
:
1223 return gestureEvent(static_cast<QGestureEvent
*>(event
), transform
);
1224 case QEvent::TouchBegin
:
1225 return touchBeginEvent(static_cast<QTouchEvent
*>(event
), transform
);
1233 void KItemListController::slotViewScrollOffsetChanged(qreal current
, qreal previous
)
1239 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1240 if (rubberBand
->isActive()) {
1241 const qreal diff
= current
- previous
;
1242 // TODO: Ideally just QCursor::pos() should be used as
1243 // new end-position but it seems there is no easy way
1244 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1245 // (... or I just missed an easy way to do the mapping)
1246 QPointF endPos
= rubberBand
->endPosition();
1247 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1248 endPos
.ry() += diff
;
1250 endPos
.rx() += diff
;
1253 rubberBand
->setEndPosition(endPos
);
1257 void KItemListController::slotRubberBandChanged()
1259 if (!m_view
|| !m_model
|| m_model
->count() <= 0) {
1263 const KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1264 const QPointF startPos
= rubberBand
->startPosition();
1265 const QPointF endPos
= rubberBand
->endPosition();
1266 QRectF rubberBandRect
= QRectF(startPos
, endPos
).normalized();
1268 const bool scrollVertical
= (m_view
->scrollOrientation() == Qt::Vertical
);
1269 if (scrollVertical
) {
1270 rubberBandRect
.translate(0, -m_view
->scrollOffset());
1272 rubberBandRect
.translate(-m_view
->scrollOffset(), 0);
1275 if (!m_oldSelection
.isEmpty()) {
1276 // Clear the old selection that was available before the rubberband has
1277 // been activated in case if no Shift- or Control-key are pressed
1278 const bool shiftOrControlPressed
= QApplication::keyboardModifiers() & Qt::ShiftModifier
||
1279 QApplication::keyboardModifiers() & Qt::ControlModifier
;
1280 if (!shiftOrControlPressed
&& !m_selectionMode
) {
1281 m_oldSelection
.clear();
1285 KItemSet selectedItems
;
1287 // Select all visible items that intersect with the rubberband
1288 const auto widgets
= m_view
->visibleItemListWidgets();
1289 for (const KItemListWidget
* widget
: widgets
) {
1290 const int index
= widget
->index();
1292 const QRectF widgetRect
= m_view
->itemRect(index
);
1293 if (widgetRect
.intersects(rubberBandRect
)) {
1294 const QRectF iconRect
= widget
->iconRect().translated(widgetRect
.topLeft());
1295 const QRectF textRect
= widget
->textRect().translated(widgetRect
.topLeft());
1296 if (iconRect
.intersects(rubberBandRect
) || textRect
.intersects(rubberBandRect
)) {
1297 selectedItems
.insert(index
);
1302 // Select all invisible items that intersect with the rubberband. Instead of
1303 // iterating all items only the area which might be touched by the rubberband
1305 const bool increaseIndex
= scrollVertical
?
1306 startPos
.y() > endPos
.y(): startPos
.x() > endPos
.x();
1308 int index
= increaseIndex
? m_view
->lastVisibleIndex() + 1 : m_view
->firstVisibleIndex() - 1;
1309 bool selectionFinished
= false;
1311 const QRectF widgetRect
= m_view
->itemRect(index
);
1312 if (widgetRect
.intersects(rubberBandRect
)) {
1313 selectedItems
.insert(index
);
1316 if (increaseIndex
) {
1318 selectionFinished
= (index
>= m_model
->count()) ||
1319 ( scrollVertical
&& widgetRect
.top() > rubberBandRect
.bottom()) ||
1320 (!scrollVertical
&& widgetRect
.left() > rubberBandRect
.right());
1323 selectionFinished
= (index
< 0) ||
1324 ( scrollVertical
&& widgetRect
.bottom() < rubberBandRect
.top()) ||
1325 (!scrollVertical
&& widgetRect
.right() < rubberBandRect
.left());
1327 } while (!selectionFinished
);
1329 if ((QApplication::keyboardModifiers() & Qt::ControlModifier
) || m_selectionMode
) {
1330 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1331 // Therefore, the new selection contains:
1332 // 1. All previously selected items which are not inside the rubberband, and
1333 // 2. all items inside the rubberband which have not been selected previously.
1334 m_selectionManager
->setSelectedItems(m_oldSelection
^ selectedItems
);
1337 m_selectionManager
->setSelectedItems(selectedItems
+ m_oldSelection
);
1341 void KItemListController::startDragging()
1343 if (!m_view
|| !m_model
) {
1347 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
1348 if (selectedItems
.isEmpty()) {
1352 QMimeData
*data
= m_model
->createMimeData(selectedItems
);
1356 KUrlMimeData::exportUrlsToPortal(data
);
1358 // The created drag object will be owned and deleted
1359 // by QApplication::activeWindow().
1360 QDrag
* drag
= new QDrag(QApplication::activeWindow());
1361 drag
->setMimeData(data
);
1363 const QPixmap pixmap
= m_view
->createDragPixmap(selectedItems
);
1364 drag
->setPixmap(pixmap
);
1366 const QPoint
hotSpot((pixmap
.width() / pixmap
.devicePixelRatio()) / 2, 0);
1367 drag
->setHotSpot(hotSpot
);
1369 drag
->exec(Qt::MoveAction
| Qt::CopyAction
| Qt::LinkAction
, Qt::CopyAction
);
1371 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropStart
);
1372 QAccessible::updateAccessibility(&accessibilityEvent
);
1375 KItemListWidget
* KItemListController::hoveredWidget() const
1379 const auto widgets
= m_view
->visibleItemListWidgets();
1380 for (KItemListWidget
* widget
: widgets
) {
1381 if (widget
->isHovered()) {
1389 KItemListWidget
* KItemListController::widgetForPos(const QPointF
& pos
) const
1393 const auto widgets
= m_view
->visibleItemListWidgets();
1394 for (KItemListWidget
* widget
: widgets
) {
1395 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1396 if (widget
->contains(mappedPos
) || widget
->selectionRect().contains(mappedPos
)) {
1404 KItemListWidget
* KItemListController::widgetForDropPos(const QPointF
& pos
) const
1408 const auto widgets
= m_view
->visibleItemListWidgets();
1409 for (KItemListWidget
* widget
: widgets
) {
1410 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1411 if (widget
->contains(mappedPos
)) {
1419 void KItemListController::updateKeyboardAnchor()
1421 const bool validAnchor
= m_keyboardAnchorIndex
>= 0 &&
1422 m_keyboardAnchorIndex
< m_model
->count() &&
1423 keyboardAnchorPos(m_keyboardAnchorIndex
) == m_keyboardAnchorPos
;
1425 const int index
= m_selectionManager
->currentItem();
1426 m_keyboardAnchorIndex
= index
;
1427 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
1431 int KItemListController::nextRowIndex(int index
) const
1433 if (m_keyboardAnchorIndex
< 0) {
1437 const int maxIndex
= m_model
->count() - 1;
1438 if (index
== maxIndex
) {
1442 // Calculate the index of the last column inside the row of the current index
1443 int lastColumnIndex
= index
;
1444 while (keyboardAnchorPos(lastColumnIndex
+ 1) > keyboardAnchorPos(lastColumnIndex
)) {
1446 if (lastColumnIndex
>= maxIndex
) {
1451 // Based on the last column index go to the next row and calculate the nearest index
1452 // that is below the current index
1453 int nextRowIndex
= lastColumnIndex
+ 1;
1454 int searchIndex
= nextRowIndex
;
1455 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(nextRowIndex
));
1456 while (searchIndex
< maxIndex
&& keyboardAnchorPos(searchIndex
+ 1) > keyboardAnchorPos(searchIndex
)) {
1458 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1459 if (searchDiff
< minDiff
) {
1460 minDiff
= searchDiff
;
1461 nextRowIndex
= searchIndex
;
1465 return nextRowIndex
;
1468 int KItemListController::previousRowIndex(int index
) const
1470 if (m_keyboardAnchorIndex
< 0 || index
== 0) {
1474 // Calculate the index of the first column inside the row of the current index
1475 int firstColumnIndex
= index
;
1476 while (keyboardAnchorPos(firstColumnIndex
- 1) < keyboardAnchorPos(firstColumnIndex
)) {
1478 if (firstColumnIndex
<= 0) {
1483 // Based on the first column index go to the previous row and calculate the nearest index
1484 // that is above the current index
1485 int previousRowIndex
= firstColumnIndex
- 1;
1486 int searchIndex
= previousRowIndex
;
1487 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(previousRowIndex
));
1488 while (searchIndex
> 0 && keyboardAnchorPos(searchIndex
- 1) < keyboardAnchorPos(searchIndex
)) {
1490 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1491 if (searchDiff
< minDiff
) {
1492 minDiff
= searchDiff
;
1493 previousRowIndex
= searchIndex
;
1497 return previousRowIndex
;
1500 qreal
KItemListController::keyboardAnchorPos(int index
) const
1502 const QRectF itemRect
= m_view
->itemRect(index
);
1503 if (!itemRect
.isEmpty()) {
1504 return (m_view
->scrollOrientation() == Qt::Vertical
) ? itemRect
.x() : itemRect
.y();
1510 void KItemListController::updateExtendedSelectionRegion()
1513 const bool extend
= (m_selectionBehavior
!= MultiSelection
);
1514 KItemListStyleOption option
= m_view
->styleOption();
1515 if (option
.extendedSelectionRegion
!= extend
) {
1516 option
.extendedSelectionRegion
= extend
;
1517 m_view
->setStyleOption(option
);
1522 bool KItemListController::onPress(const QPoint
& screenPos
, const QPointF
& pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
)
1524 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), buttons
);
1526 if (buttons
& (Qt::BackButton
| Qt::ForwardButton
)) {
1527 // Do not select items when clicking the back/forward buttons, see
1528 // https://bugs.kde.org/show_bug.cgi?id=327412.
1532 if (m_view
->isAboveExpansionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
)) {
1533 m_selectionManager
->endAnchoredSelection();
1534 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1535 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1539 m_selectionTogglePressed
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
);
1540 if (m_selectionTogglePressed
) {
1541 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1542 // The previous anchored selection has been finished already in
1543 // KItemListSelectionManager::setSelected(). We can safely change
1544 // the current item and start a new anchored selection now.
1545 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1546 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1550 const bool shiftPressed
= modifiers
& Qt::ShiftModifier
;
1551 const bool controlPressed
= (modifiers
& Qt::ControlModifier
) || m_selectionMode
; // Keeping selectionMode similar to pressing control will hopefully
1552 // simplify the overall logic and possibilities both for users and devs.
1553 const bool leftClick
= buttons
& Qt::LeftButton
;
1554 const bool rightClick
= buttons
& Qt::RightButton
;
1557 m_longPressDetectionTimer
->start();
1560 // The previous selection is cleared if either
1561 // 1. The selection mode is SingleSelection, or
1562 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1563 // a) Shift or Control are pressed.
1564 // b) The clicked item is selected already. In that case, the user might want to:
1565 // - start dragging multiple items, or
1566 // - open the context menu and perform an action for all selected items.
1567 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
1568 const bool pressedItemAlreadySelected
= m_pressedIndex
.has_value() && m_selectionManager
->isSelected(m_pressedIndex
.value());
1569 const bool clearSelection
= m_selectionBehavior
== SingleSelection
||
1570 (!shiftOrControlPressed
&& !pressedItemAlreadySelected
);
1573 // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller.
1574 if (clearSelection
) {
1575 const int selectedItemsCount
= m_selectionManager
->selectedItems().count();
1576 m_selectionManager
->clearSelection();
1577 // clear and bail when we got an existing multi-selection
1578 if (selectedItemsCount
> 1 && m_pressedIndex
.has_value()) {
1579 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1580 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1581 if (pressedItemAlreadySelected
|| row
->iconRect().contains(mappedPos
) || row
->textRect().contains(mappedPos
)) {
1582 // we are indeed inside the text/icon rect, keep m_pressedIndex what it is
1583 // and short-circuit for single-click activation (it will then propagate to onRelease and activate the item)
1584 // or we just keep going for double-click activation
1585 if (m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) {
1586 if (!pressedItemAlreadySelected
) {
1587 // An unselected item was clicked directly while deselecting multiple other items so we select it.
1588 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1589 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1590 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1592 return true; // event handled, don't create rubber band
1595 // we're not inside the text/icon rect, as we've already cleared the selection
1596 // we can just stop here and make sure handlers down the line (i.e. onRelease) don't activate
1597 m_pressedIndex
.reset();
1598 // we don't stop event propagation and proceed to create a rubber band and let onRelease
1599 // decide (based on m_pressedIndex) whether we're in a drag (drag => new rubber band, click => don't select the item)
1603 } else if (pressedItemAlreadySelected
&& !shiftOrControlPressed
&& leftClick
) {
1604 // The user might want to start dragging multiple items, but if he clicks the item
1605 // in order to trigger it instead, the other selected items must be deselected.
1606 // However, we do not know yet what the user is going to do.
1607 // -> remember that the user pressed an item which had been selected already and
1608 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1609 m_clearSelectionIfItemsAreNotDragged
= true;
1611 if (m_selectionManager
->selectedItems().count() == 1 && m_view
->isAboveText(m_pressedIndex
.value_or(-1), m_pressedMousePos
)) {
1612 Q_EMIT
selectedItemTextPressed(m_pressedIndex
.value_or(-1));
1616 if (!shiftPressed
) {
1617 // Finish the anchored selection before the current index is changed
1618 m_selectionManager
->endAnchoredSelection();
1623 // Do header hit check and short circuit before commencing any state changing effects
1624 if (m_view
->headerBoundaries().contains(pos
)) {
1625 Q_EMIT
headerContextMenuRequested(screenPos
);
1629 // Stop rubber band from persisting after right-clicks
1630 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1631 if (rubberBand
->isActive()) {
1632 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1633 rubberBand
->setActive(false);
1634 m_view
->setAutoScroll(false);
1638 if (m_pressedIndex
.has_value()) {
1639 // The hover highlight area of an item is being pressed.
1640 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1641 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value()); // anything outside of row.contains() will be the empty region of the row rect
1642 const bool hitTargetIsRowEmptyRegion
= !row
->contains(row
->mapFromItem(m_view
, pos
));
1643 // again, when this method returns false, a rubberBand selection is created as the event is not consumed;
1644 // createRubberBand here tells us whether to return true or false.
1645 bool createRubberBand
= (hitTargetIsRowEmptyRegion
&& m_selectionManager
->selectedItems().isEmpty());
1647 if (rightClick
&& hitTargetIsRowEmptyRegion
) {
1648 // We have a right click outside the icon and text rect but within the hover highlight area
1649 // but it is unclear if this means that a selection rectangle for an item was clicked or the background of the view.
1650 if (m_selectionManager
->selectedItems().contains(m_pressedIndex
.value())) {
1651 // The selection rectangle for an item was clicked
1652 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), screenPos
);
1654 row
->setHovered(false); // Removes the hover highlight so the context menu doesn't look like it applies to the row.
1655 Q_EMIT
viewContextMenuRequested(screenPos
);
1660 switch (m_selectionBehavior
) {
1664 case SingleSelection
:
1665 m_selectionManager
->setSelected(m_pressedIndex
.value());
1668 case MultiSelection
:
1669 if (controlPressed
&& !shiftPressed
&& leftClick
) {
1670 // A left mouse button press is happening on an item while control is pressed. This either means a user wants to:
1671 // - toggle the selection of item(s) or
1672 // - they want to begin a drag on the item(s) to copy them.
1673 // We rule out the latter, if the item is not clicked directly and was unselected previously.
1674 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1675 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1676 if (!row
->iconRect().contains(mappedPos
) && !row
->textRect().contains(mappedPos
) && !pressedItemAlreadySelected
) {
1677 createRubberBand
= true;
1679 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1680 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1681 createRubberBand
= false; // multi selection, don't propagate any further
1682 // This will be the start of an item drag-to-copy operation if the user now moves the mouse before releasing the mouse button.
1684 } else if (!shiftPressed
|| !m_selectionManager
->isAnchoredSelectionActive()) {
1685 // Select the pressed item and start a new anchored selection
1686 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1687 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1697 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), screenPos
);
1699 return !createRubberBand
;
1703 // header right click handling would have been done before this so just normal context
1704 // menu here is fine
1705 Q_EMIT
viewContextMenuRequested(screenPos
);
1712 bool KItemListController::onRelease(const QPointF
& pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
, bool touch
)
1714 const bool isAboveSelectionToggle
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
);
1715 if (isAboveSelectionToggle
) {
1716 m_selectionTogglePressed
= false;
1720 if (!isAboveSelectionToggle
&& m_selectionTogglePressed
) {
1721 m_selectionManager
->setSelected(m_pressedIndex
.value_or(-1), 1, KItemListSelectionManager::Toggle
);
1722 m_selectionTogglePressed
= false;
1726 const bool controlPressed
= modifiers
& Qt::ControlModifier
;
1727 const bool shiftOrControlPressed
= modifiers
& Qt::ShiftModifier
||
1730 const std::optional
<int> index
= m_view
->itemAt(pos
);
1732 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1733 bool rubberBandRelease
= false;
1734 if (rubberBand
->isActive()) {
1735 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1736 rubberBand
->setActive(false);
1737 m_oldSelection
.clear();
1738 m_view
->setAutoScroll(false);
1739 rubberBandRelease
= true;
1740 // We check for actual rubber band drag here: if delta between start and end is less than drag threshold,
1741 // then we have a single click on one of the rows
1742 if ((rubberBand
->endPosition() - rubberBand
->startPosition()).manhattanLength() < QApplication::startDragDistance()) {
1743 rubberBandRelease
= false; // since we're only selecting, unmark rubber band release flag
1744 // m_pressedIndex will have no value if we came from a multi-selection clearing onPress
1745 // in that case, we don't select anything
1746 if (index
.has_value() && m_pressedIndex
.has_value()) {
1747 if (controlPressed
&& m_selectionBehavior
== MultiSelection
) {
1748 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1750 m_selectionManager
->setSelected(index
.value());
1752 if (!m_selectionManager
->isAnchoredSelectionActive()) {
1753 m_selectionManager
->beginAnchoredSelection(index
.value());
1759 if (index
.has_value() && index
== m_pressedIndex
) {
1760 // The release event is done above the same item as the press event
1762 if (m_clearSelectionIfItemsAreNotDragged
) {
1763 // A selected item has been clicked, but no drag operation has been started
1764 // -> clear the rest of the selection.
1765 m_selectionManager
->clearSelection();
1766 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1767 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1770 if (buttons
& Qt::LeftButton
) {
1771 bool emitItemActivated
= true;
1772 if (m_view
->isAboveExpansionToggle(index
.value(), pos
)) {
1773 const bool expanded
= m_model
->isExpanded(index
.value());
1774 m_model
->setExpanded(index
.value(), !expanded
);
1776 Q_EMIT
itemExpansionToggleClicked(index
.value());
1777 emitItemActivated
= false;
1778 } else if (shiftOrControlPressed
&& m_selectionBehavior
!= SingleSelection
) {
1779 // The mouse click should only update the selection, not trigger the item, except when
1780 // we are in single selection mode
1781 emitItemActivated
= false;
1783 const bool singleClickActivation
= m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
;
1784 if (!singleClickActivation
) {
1785 emitItemActivated
= touch
&& !m_selectionMode
;
1787 // activate on single click only if we didn't come from a rubber band release
1788 emitItemActivated
= !rubberBandRelease
;
1791 if (emitItemActivated
) {
1792 Q_EMIT
itemActivated(index
.value());
1794 } else if (buttons
& Qt::MiddleButton
) {
1795 Q_EMIT
itemMiddleClicked(index
.value());
1799 m_pressedMousePos
= QPointF();
1800 m_pressedIndex
= std::nullopt
;
1801 m_clearSelectionIfItemsAreNotDragged
= false;
1805 void KItemListController::startRubberBand()
1807 if (m_selectionBehavior
== MultiSelection
) {
1808 QPointF startPos
= m_pressedMousePos
;
1809 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1810 startPos
.ry() += m_view
->scrollOffset();
1811 if (m_view
->itemSize().width() < 0) {
1812 // Use a special rubberband for views that have only one column and
1813 // expand the rubberband to use the whole width of the view.
1817 startPos
.rx() += m_view
->scrollOffset();
1820 m_oldSelection
= m_selectionManager
->selectedItems();
1821 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1822 rubberBand
->setStartPosition(startPos
);
1823 rubberBand
->setEndPosition(startPos
);
1824 rubberBand
->setActive(true);
1825 connect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1826 m_view
->setAutoScroll(true);
1830 void KItemListController::slotStateChanged(QScroller::State newState
)
1832 if (newState
== QScroller::Scrolling
) {
1833 m_scrollerIsScrolling
= true;
1834 } else if (newState
== QScroller::Inactive
) {
1835 m_scrollerIsScrolling
= false;