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
selectionModeRequested();
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::setSelectionMode(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_selectionBehavior
!= SingleSelection
) {
434 m_selectionManager
->clearSelection();
436 m_keyboardManager
->cancelSearch();
437 Q_EMIT
escapePressed();
441 if (m_selectionBehavior
== MultiSelection
) {
442 if (controlPressed
) {
443 // Toggle the selection state of the current item.
444 m_selectionManager
->endAnchoredSelection();
445 m_selectionManager
->setSelected(index
, 1, KItemListSelectionManager::Toggle
);
446 m_selectionManager
->beginAnchoredSelection(index
);
449 // Select the current item if it is not selected yet.
450 const int current
= m_selectionManager
->currentItem();
451 if (!m_selectionManager
->isSelected(current
)) {
452 m_selectionManager
->setSelected(current
);
457 Q_FALLTHROUGH(); // fall through to the default case and add the Space to the current search string.
459 m_keyboardManager
->addKeys(event
->text());
460 // Make sure unconsumed events get propagated up the chain. #302329
465 if (m_selectionManager
->currentItem() != index
) {
466 switch (m_selectionBehavior
) {
468 m_selectionManager
->setCurrentItem(index
);
471 case SingleSelection
:
472 m_selectionManager
->setCurrentItem(index
);
473 m_selectionManager
->clearSelection();
474 m_selectionManager
->setSelected(index
, 1);
478 if (controlPressed
) {
479 m_selectionManager
->endAnchoredSelection();
482 m_selectionManager
->setCurrentItem(index
);
484 if (!shiftOrControlPressed
) {
485 m_selectionManager
->clearSelection();
486 m_selectionManager
->setSelected(index
, 1);
490 m_selectionManager
->beginAnchoredSelection(index
);
496 if (navigationPressed
) {
497 m_view
->scrollToItem(index
);
502 void KItemListController::slotChangeCurrentItem(const QString
& text
, bool searchFromNextItem
)
504 if (!m_model
|| m_model
->count() == 0) {
508 if (searchFromNextItem
) {
509 const int currentIndex
= m_selectionManager
->currentItem();
510 index
= m_model
->indexForKeyboardSearch(text
, (currentIndex
+ 1) % m_model
->count());
512 index
= m_model
->indexForKeyboardSearch(text
, 0);
515 m_selectionManager
->setCurrentItem(index
);
517 if (m_selectionBehavior
!= NoSelection
) {
518 m_selectionManager
->replaceSelection(index
);
519 m_selectionManager
->beginAnchoredSelection(index
);
522 m_view
->scrollToItem(index
);
526 void KItemListController::slotAutoActivationTimeout()
528 if (!m_model
|| !m_view
) {
532 const int index
= m_autoActivationTimer
->property("index").toInt();
533 if (index
< 0 || index
>= m_model
->count()) {
537 /* m_view->isUnderMouse() fixes a bug in the Folder-View-Panel and in the
540 * Bug: When you drag a file onto a Folder-View-Item or a Places-Item and
541 * then move away before the auto-activation timeout triggers, than the
542 * item still becomes activated/expanded.
544 * See Bug 293200 and 305783
546 if (m_model
->supportsDropping(index
) && m_view
->isUnderMouse()) {
547 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
)) {
548 const bool expanded
= m_model
->isExpanded(index
);
549 m_model
->setExpanded(index
, !expanded
);
550 } else if (m_autoActivationBehavior
!= ExpansionOnly
) {
551 Q_EMIT
itemActivated(index
);
556 bool KItemListController::inputMethodEvent(QInputMethodEvent
* event
)
562 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent
* event
, const QTransform
& transform
)
566 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& m_isTouchEvent
) {
574 m_pressedMousePos
= transform
.map(event
->pos());
575 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
577 const Qt::MouseButtons buttons
= event
->buttons();
579 if (!onPress(event
->screenPos(), event
->pos(), event
->modifiers(), buttons
)) {
587 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
, const QTransform
& transform
)
593 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
594 m_view
->m_tapAndHoldIndicator
->setActive(false);
597 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !m_dragActionOrRightClick
&& m_isTouchEvent
) {
601 const QPointF pos
= transform
.map(event
->pos());
602 if ((pos
- m_pressedMousePos
).manhattanLength() >= QApplication::startDragDistance()) {
603 m_longPressDetectionTimer
->stop();
606 if (m_pressedIndex
.has_value() && !m_view
->rubberBand()->isActive()) {
607 // Check whether a dragging should be started
608 if (event
->buttons() & Qt::LeftButton
) {
609 if ((pos
- m_pressedMousePos
).manhattanLength() >= QApplication::startDragDistance()) {
610 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
611 // Always assure that the dragged item gets selected. Usually this is already
612 // done on the mouse-press event, but when using the selection-toggle on a
613 // selected item the dragged item is not selected yet.
614 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
616 // A selected item has been clicked to drag all selected items
617 // -> the selection should not be cleared when the mouse button is released.
618 m_clearSelectionIfItemsAreNotDragged
= false;
621 m_mousePress
= false;
625 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
626 if (rubberBand
->isActive()) {
627 QPointF endPos
= transform
.map(event
->pos());
629 // Update the current item.
630 const std::optional
<int> newCurrent
= m_view
->itemAt(endPos
);
631 if (newCurrent
.has_value()) {
632 // It's expected that the new current index is also the new anchor (bug 163451).
633 m_selectionManager
->endAnchoredSelection();
634 m_selectionManager
->setCurrentItem(newCurrent
.value());
635 m_selectionManager
->beginAnchoredSelection(newCurrent
.value());
638 if (m_view
->scrollOrientation() == Qt::Vertical
) {
639 endPos
.ry() += m_view
->scrollOffset();
640 if (m_view
->itemSize().width() < 0) {
641 // Use a special rubberband for views that have only one column and
642 // expand the rubberband to use the whole width of the view.
643 endPos
.setX(m_view
->size().width());
646 endPos
.rx() += m_view
->scrollOffset();
648 rubberBand
->setEndPosition(endPos
);
655 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent
* event
, const QTransform
& transform
)
657 m_mousePress
= false;
658 m_isTouchEvent
= false;
664 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
665 m_view
->m_tapAndHoldIndicator
->setActive(false);
668 m_longPressDetectionTimer
->stop();
670 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
671 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !rubberBand
->isActive() && m_isTouchEvent
) {
675 Q_EMIT
mouseButtonReleased(m_pressedIndex
.value_or(-1), event
->buttons());
677 return onRelease(transform
.map(event
->pos()), event
->modifiers(), event
->button(), false);
680 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent
* event
, const QTransform
& transform
)
682 const QPointF pos
= transform
.map(event
->pos());
683 const std::optional
<int> index
= m_view
->itemAt(pos
);
685 // Expand item if desired - See Bug 295573
686 if (m_mouseDoubleClickAction
!= ActivateItemOnly
) {
687 if (m_view
&& m_model
&& m_view
->supportsItemExpanding() && m_model
->isExpandable(index
.value_or(-1))) {
688 const bool expanded
= m_model
->isExpanded(index
.value());
689 m_model
->setExpanded(index
.value(), !expanded
);
693 if (event
->button() & Qt::RightButton
) {
694 m_selectionManager
->clearSelection();
695 if (index
.has_value()) {
696 m_selectionManager
->setSelected(index
.value());
697 Q_EMIT
itemContextMenuRequested(index
.value(), event
->screenPos());
699 const QRectF headerBounds
= m_view
->headerBoundaries();
700 if (headerBounds
.contains(event
->pos())) {
701 Q_EMIT
headerContextMenuRequested(event
->screenPos());
703 Q_EMIT
viewContextMenuRequested(event
->screenPos());
709 bool emitItemActivated
= !(m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) &&
710 (event
->button() & Qt::LeftButton
) &&
711 index
.has_value() && index
.value() < m_model
->count();
712 if (emitItemActivated
) {
713 Q_EMIT
itemActivated(index
.value());
718 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
723 DragAndDropHelper::clearUrlListMatchesUrlCache();
728 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
733 m_autoActivationTimer
->stop();
734 m_view
->setAutoScroll(false);
735 m_view
->hideDropIndicator();
737 KItemListWidget
* widget
= hoveredWidget();
739 widget
->setHovered(false);
740 Q_EMIT
itemUnhovered(widget
->index());
745 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
747 if (!m_model
|| !m_view
) {
752 QUrl hoveredDir
= m_model
->directory();
753 KItemListWidget
* oldHoveredWidget
= hoveredWidget();
755 const QPointF pos
= transform
.map(event
->pos());
756 KItemListWidget
* newHoveredWidget
= widgetForDropPos(pos
);
758 if (oldHoveredWidget
!= newHoveredWidget
) {
759 m_autoActivationTimer
->stop();
761 if (oldHoveredWidget
) {
762 oldHoveredWidget
->setHovered(false);
763 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
767 if (newHoveredWidget
) {
768 bool droppingBetweenItems
= false;
769 if (m_model
->sortRole().isEmpty()) {
770 // The model supports inserting items between other items.
771 droppingBetweenItems
= (m_view
->showDropIndicator(pos
) >= 0);
774 const int index
= newHoveredWidget
->index();
776 if (m_model
->isDir(index
)) {
777 hoveredDir
= m_model
->url(index
);
780 if (!droppingBetweenItems
) {
781 if (m_model
->supportsDropping(index
)) {
782 // Something has been dragged on an item.
783 m_view
->hideDropIndicator();
784 if (!newHoveredWidget
->isHovered()) {
785 newHoveredWidget
->setHovered(true);
786 Q_EMIT
itemHovered(index
);
789 if (!m_autoActivationTimer
->isActive() && m_autoActivationTimer
->interval() >= 0) {
790 m_autoActivationTimer
->setProperty("index", index
);
791 m_autoActivationTimer
->start();
795 m_autoActivationTimer
->stop();
796 if (newHoveredWidget
&& newHoveredWidget
->isHovered()) {
797 newHoveredWidget
->setHovered(false);
798 Q_EMIT
itemUnhovered(index
);
802 m_view
->hideDropIndicator();
805 if (DragAndDropHelper::urlListMatchesUrl(event
->mimeData()->urls(), hoveredDir
)) {
806 event
->setDropAction(Qt::IgnoreAction
);
809 event
->setDropAction(event
->proposedAction());
815 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
821 m_autoActivationTimer
->stop();
822 m_view
->setAutoScroll(false);
824 const QPointF pos
= transform
.map(event
->pos());
826 int dropAboveIndex
= -1;
827 if (m_model
->sortRole().isEmpty()) {
828 // The model supports inserting of items between other items.
829 dropAboveIndex
= m_view
->showDropIndicator(pos
);
832 if (dropAboveIndex
>= 0) {
833 // Something has been dropped between two items.
834 m_view
->hideDropIndicator();
835 Q_EMIT
aboveItemDropEvent(dropAboveIndex
, event
);
836 } else if (!event
->mimeData()->hasFormat(m_model
->blacklistItemDropEventMimeType())) {
837 // Something has been dropped on an item or on an empty part of the view.
838 const KItemListWidget
*receivingWidget
= widgetForDropPos(pos
);
839 if (receivingWidget
) {
840 Q_EMIT
itemDropEvent(receivingWidget
->index(), event
);
842 Q_EMIT
itemDropEvent(-1, event
);
846 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropEnd
);
847 QAccessible::updateAccessibility(&accessibilityEvent
);
852 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent
* event
, const QTransform
& transform
)
859 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent
* event
, const QTransform
& transform
)
862 if (!m_model
|| !m_view
) {
866 // We identify the widget whose expansionArea had been hovered before this hoverMoveEvent() triggered.
867 // we can't use hoveredWidget() here (it handles the icon+text rect, not the expansion rect)
868 // like hoveredWidget(), we find the hovered widget for the expansion rect
869 const auto visibleItemListWidgets
= m_view
->visibleItemListWidgets();
870 const auto oldHoveredExpansionWidgetIterator
= std::find_if(visibleItemListWidgets
.begin(), visibleItemListWidgets
.end(), [](auto &widget
) {
871 return widget
->expansionAreaHovered();
873 const auto oldHoveredExpansionWidget
= oldHoveredExpansionWidgetIterator
== visibleItemListWidgets
.end() ?
874 std::nullopt
: std::make_optional(*oldHoveredExpansionWidgetIterator
);
876 const auto unhoverOldHoveredWidget
= [&]() {
877 if (auto oldHoveredWidget
= hoveredWidget(); oldHoveredWidget
) {
878 // handle the text+icon one
879 oldHoveredWidget
->setHovered(false);
880 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
884 const auto unhoverOldExpansionWidget
= [&]() {
885 if (oldHoveredExpansionWidget
) {
886 // then the expansion toggle
887 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
891 const QPointF pos
= transform
.map(event
->pos());
892 if (KItemListWidget
*newHoveredWidget
= widgetForPos(pos
); newHoveredWidget
) {
893 // something got hovered, work out which part and set hover for the appropriate widget
894 const auto mappedPos
= newHoveredWidget
->mapFromItem(m_view
, pos
);
895 const bool isOnExpansionToggle
= newHoveredWidget
->expansionToggleRect().contains(mappedPos
);
897 if (isOnExpansionToggle
) {
898 // make sure we unhover the old one first if old!=new
899 if (oldHoveredExpansionWidget
&& *oldHoveredExpansionWidget
!= newHoveredWidget
) {
900 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
902 // 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)
903 unhoverOldHoveredWidget();
906 newHoveredWidget
->setExpansionAreaHovered(true);
908 // make sure we unhover the old one first if old!=new
909 auto oldHoveredWidget
= hoveredWidget();
910 if (oldHoveredWidget
&& oldHoveredWidget
!= newHoveredWidget
) {
911 oldHoveredWidget
->setHovered(false);
912 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
914 // 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)
915 unhoverOldExpansionWidget();
917 const bool isOverIconAndText
= newHoveredWidget
->iconRect().contains(mappedPos
) || newHoveredWidget
->textRect().contains(mappedPos
);
918 const bool hasMultipleSelection
= m_selectionManager
->selectedItems().count() > 1;
920 if (hasMultipleSelection
&& !isOverIconAndText
) {
921 // In case we have multiple selections, clicking on any row will deselect the selection.
922 // So, as a visual cue for signalling that clicking anywhere won't select, but clear current highlights,
923 // we disable hover of the *row*(i.e. blank space to the right of the icon+text)
925 // (no-op in this branch for masked hover)
927 newHoveredWidget
->setHoverPosition(mappedPos
);
928 if (oldHoveredWidget
!= newHoveredWidget
) {
929 newHoveredWidget
->setHovered(true);
930 Q_EMIT
itemHovered(newHoveredWidget
->index());
935 // unhover any currently hovered expansion and text+icon widgets
936 unhoverOldHoveredWidget();
937 unhoverOldExpansionWidget();
942 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent
* event
, const QTransform
& transform
)
947 m_mousePress
= false;
948 m_isTouchEvent
= false;
950 if (!m_model
|| !m_view
) {
954 const auto widgets
= m_view
->visibleItemListWidgets();
955 for (KItemListWidget
* widget
: widgets
) {
956 if (widget
->isHovered()) {
957 widget
->setHovered(false);
958 Q_EMIT
itemUnhovered(widget
->index());
964 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent
* event
, const QTransform
& transform
)
971 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent
* event
, const QTransform
& transform
)
978 bool KItemListController::gestureEvent(QGestureEvent
* event
, const QTransform
& transform
)
984 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
985 //we use this to get the right QWidget
986 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
988 if (QGesture
* tap
= event
->gesture(Qt::TapGesture
)) {
989 QTapGesture
* tapGesture
= static_cast<QTapGesture
*>(tap
);
990 if (tapGesture
->state() == Qt::GestureStarted
) {
991 tapTriggered(tapGesture
, transform
);
997 bool accepted
= false;
999 if (QGesture
* tap
= event
->gesture(Qt::TapGesture
)) {
1000 tapTriggered(static_cast<QTapGesture
*>(tap
), transform
);
1003 if (event
->gesture(Qt::TapAndHoldGesture
)) {
1004 tapAndHoldTriggered(event
, transform
);
1007 if (event
->gesture(Qt::PinchGesture
)) {
1008 pinchTriggered(event
, transform
);
1011 if (event
->gesture(m_swipeGesture
)) {
1012 swipeTriggered(event
, transform
);
1015 if (event
->gesture(m_twoFingerTapGesture
)) {
1016 twoFingerTapTriggered(event
, transform
);
1022 bool KItemListController::touchBeginEvent(QTouchEvent
* event
, const QTransform
& transform
)
1027 m_isTouchEvent
= true;
1031 void KItemListController::tapTriggered(QTapGesture
* tap
, const QTransform
& transform
)
1033 static bool scrollerWasActive
= false;
1035 if (tap
->state() == Qt::GestureStarted
) {
1036 m_dragActionOrRightClick
= false;
1037 m_isSwipeGesture
= false;
1038 m_pinchGestureInProgress
= false;
1039 scrollerWasActive
= m_scrollerIsScrolling
;
1042 if (tap
->state() == Qt::GestureFinished
) {
1043 m_mousePress
= false;
1045 //if at the moment of the gesture start the QScroller was active, the user made the tap
1046 //to stop the QScroller and not to tap on an item
1047 if (scrollerWasActive
) {
1051 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
1052 m_view
->m_tapAndHoldIndicator
->setActive(false);
1055 m_pressedMousePos
= transform
.map(tap
->position());
1056 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1058 if (m_dragActionOrRightClick
) {
1059 onPress(tap
->hotSpot().toPoint(), tap
->position().toPoint(), Qt::NoModifier
, Qt::RightButton
);
1060 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::RightButton
, false);
1061 m_dragActionOrRightClick
= false;
1064 onPress(tap
->hotSpot().toPoint(), tap
->position().toPoint(), Qt::NoModifier
, Qt::LeftButton
);
1065 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::LeftButton
, true);
1067 m_isTouchEvent
= false;
1071 void KItemListController::tapAndHoldTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1074 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
1075 if (!m_isTouchEvent
) {
1079 const QTapAndHoldGesture
* tap
= static_cast<QTapAndHoldGesture
*>(event
->gesture(Qt::TapAndHoldGesture
));
1080 if (tap
->state() == Qt::GestureFinished
) {
1081 //if a pinch gesture is in progress we don't want a TabAndHold gesture
1082 if (m_pinchGestureInProgress
) {
1085 m_pressedMousePos
= transform
.map(event
->mapToGraphicsScene(tap
->position()));
1086 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1088 if (m_pressedIndex
.has_value() && !m_selectionManager
->isSelected(m_pressedIndex
.value())) {
1089 m_selectionManager
->clearSelection();
1090 m_selectionManager
->setSelected(m_pressedIndex
.value());
1091 } else if (!m_pressedIndex
.has_value()) {
1092 m_selectionManager
->clearSelection();
1096 Q_EMIT
scrollerStop();
1098 m_view
->m_tapAndHoldIndicator
->setStartPosition(m_pressedMousePos
);
1099 m_view
->m_tapAndHoldIndicator
->setActive(true);
1101 m_dragActionOrRightClick
= true;
1105 void KItemListController::pinchTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1109 const QPinchGesture
* pinch
= static_cast<QPinchGesture
*>(event
->gesture(Qt::PinchGesture
));
1110 const qreal sensitivityModifier
= 0.2;
1111 static qreal counter
= 0;
1113 if (pinch
->state() == Qt::GestureStarted
) {
1114 m_pinchGestureInProgress
= true;
1117 if (pinch
->state() == Qt::GestureUpdated
) {
1118 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1119 if (m_isSwipeGesture
) {
1122 counter
= counter
+ (pinch
->scaleFactor() - 1);
1123 if (counter
>= sensitivityModifier
) {
1124 Q_EMIT
increaseZoom();
1126 } else if (counter
<= -sensitivityModifier
) {
1127 Q_EMIT
decreaseZoom();
1133 void KItemListController::swipeTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1137 const KTwoFingerSwipe
* swipe
= static_cast<KTwoFingerSwipe
*>(event
->gesture(m_swipeGesture
));
1142 if (swipe
->state() == Qt::GestureStarted
) {
1143 m_isSwipeGesture
= true;
1146 if (swipe
->state() == Qt::GestureCanceled
) {
1147 m_isSwipeGesture
= false;
1150 if (swipe
->state() == Qt::GestureFinished
) {
1151 Q_EMIT
scrollerStop();
1153 if (swipe
->swipeAngle() <= 20 || swipe
->swipeAngle() >= 340) {
1154 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::BackButton
);
1155 } else if (swipe
->swipeAngle() <= 200 && swipe
->swipeAngle() >= 160) {
1156 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::ForwardButton
);
1157 } else if (swipe
->swipeAngle() <= 110 && swipe
->swipeAngle() >= 60) {
1160 m_isSwipeGesture
= true;
1164 void KItemListController::twoFingerTapTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1166 const KTwoFingerTap
* twoTap
= static_cast<KTwoFingerTap
*>(event
->gesture(m_twoFingerTapGesture
));
1172 if (twoTap
->state() == Qt::GestureStarted
) {
1173 m_pressedMousePos
= transform
.map(twoTap
->pos());
1174 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1175 if (m_pressedIndex
.has_value()) {
1176 onPress(twoTap
->screenPos().toPoint(), twoTap
->pos().toPoint(), Qt::ControlModifier
, Qt::LeftButton
);
1177 onRelease(transform
.map(twoTap
->pos()), Qt::ControlModifier
, Qt::LeftButton
, false);
1183 bool KItemListController::processEvent(QEvent
* event
, const QTransform
& transform
)
1189 switch (event
->type()) {
1190 case QEvent::KeyPress
:
1191 return keyPressEvent(static_cast<QKeyEvent
*>(event
));
1192 case QEvent::InputMethod
:
1193 return inputMethodEvent(static_cast<QInputMethodEvent
*>(event
));
1194 case QEvent::GraphicsSceneMousePress
:
1195 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1196 case QEvent::GraphicsSceneMouseMove
:
1197 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1198 case QEvent::GraphicsSceneMouseRelease
:
1199 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1200 case QEvent::GraphicsSceneMouseDoubleClick
:
1201 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1202 case QEvent::GraphicsSceneWheel
:
1203 return wheelEvent(static_cast<QGraphicsSceneWheelEvent
*>(event
), QTransform());
1204 case QEvent::GraphicsSceneDragEnter
:
1205 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1206 case QEvent::GraphicsSceneDragLeave
:
1207 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1208 case QEvent::GraphicsSceneDragMove
:
1209 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1210 case QEvent::GraphicsSceneDrop
:
1211 return dropEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1212 case QEvent::GraphicsSceneHoverEnter
:
1213 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1214 case QEvent::GraphicsSceneHoverMove
:
1215 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1216 case QEvent::GraphicsSceneHoverLeave
:
1217 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1218 case QEvent::GraphicsSceneResize
:
1219 return resizeEvent(static_cast<QGraphicsSceneResizeEvent
*>(event
), transform
);
1220 case QEvent::Gesture
:
1221 return gestureEvent(static_cast<QGestureEvent
*>(event
), transform
);
1222 case QEvent::TouchBegin
:
1223 return touchBeginEvent(static_cast<QTouchEvent
*>(event
), transform
);
1231 void KItemListController::slotViewScrollOffsetChanged(qreal current
, qreal previous
)
1237 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1238 if (rubberBand
->isActive()) {
1239 const qreal diff
= current
- previous
;
1240 // TODO: Ideally just QCursor::pos() should be used as
1241 // new end-position but it seems there is no easy way
1242 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1243 // (... or I just missed an easy way to do the mapping)
1244 QPointF endPos
= rubberBand
->endPosition();
1245 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1246 endPos
.ry() += diff
;
1248 endPos
.rx() += diff
;
1251 rubberBand
->setEndPosition(endPos
);
1255 void KItemListController::slotRubberBandChanged()
1257 if (!m_view
|| !m_model
|| m_model
->count() <= 0) {
1261 const KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1262 const QPointF startPos
= rubberBand
->startPosition();
1263 const QPointF endPos
= rubberBand
->endPosition();
1264 QRectF rubberBandRect
= QRectF(startPos
, endPos
).normalized();
1266 const bool scrollVertical
= (m_view
->scrollOrientation() == Qt::Vertical
);
1267 if (scrollVertical
) {
1268 rubberBandRect
.translate(0, -m_view
->scrollOffset());
1270 rubberBandRect
.translate(-m_view
->scrollOffset(), 0);
1273 if (!m_oldSelection
.isEmpty()) {
1274 // Clear the old selection that was available before the rubberband has
1275 // been activated in case if no Shift- or Control-key are pressed
1276 const bool shiftOrControlPressed
= QApplication::keyboardModifiers() & Qt::ShiftModifier
||
1277 QApplication::keyboardModifiers() & Qt::ControlModifier
;
1278 if (!shiftOrControlPressed
&& !m_selectionMode
) {
1279 m_oldSelection
.clear();
1283 KItemSet selectedItems
;
1285 // Select all visible items that intersect with the rubberband
1286 const auto widgets
= m_view
->visibleItemListWidgets();
1287 for (const KItemListWidget
* widget
: widgets
) {
1288 const int index
= widget
->index();
1290 const QRectF widgetRect
= m_view
->itemRect(index
);
1291 if (widgetRect
.intersects(rubberBandRect
)) {
1292 const QRectF iconRect
= widget
->iconRect().translated(widgetRect
.topLeft());
1293 const QRectF textRect
= widget
->textRect().translated(widgetRect
.topLeft());
1294 if (iconRect
.intersects(rubberBandRect
) || textRect
.intersects(rubberBandRect
)) {
1295 selectedItems
.insert(index
);
1300 // Select all invisible items that intersect with the rubberband. Instead of
1301 // iterating all items only the area which might be touched by the rubberband
1303 const bool increaseIndex
= scrollVertical
?
1304 startPos
.y() > endPos
.y(): startPos
.x() > endPos
.x();
1306 int index
= increaseIndex
? m_view
->lastVisibleIndex() + 1 : m_view
->firstVisibleIndex() - 1;
1307 bool selectionFinished
= false;
1309 const QRectF widgetRect
= m_view
->itemRect(index
);
1310 if (widgetRect
.intersects(rubberBandRect
)) {
1311 selectedItems
.insert(index
);
1314 if (increaseIndex
) {
1316 selectionFinished
= (index
>= m_model
->count()) ||
1317 ( scrollVertical
&& widgetRect
.top() > rubberBandRect
.bottom()) ||
1318 (!scrollVertical
&& widgetRect
.left() > rubberBandRect
.right());
1321 selectionFinished
= (index
< 0) ||
1322 ( scrollVertical
&& widgetRect
.bottom() < rubberBandRect
.top()) ||
1323 (!scrollVertical
&& widgetRect
.right() < rubberBandRect
.left());
1325 } while (!selectionFinished
);
1327 if ((QApplication::keyboardModifiers() & Qt::ControlModifier
) || m_selectionMode
) {
1328 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1329 // Therefore, the new selection contains:
1330 // 1. All previously selected items which are not inside the rubberband, and
1331 // 2. all items inside the rubberband which have not been selected previously.
1332 m_selectionManager
->setSelectedItems(m_oldSelection
^ selectedItems
);
1335 m_selectionManager
->setSelectedItems(selectedItems
+ m_oldSelection
);
1339 void KItemListController::startDragging()
1341 if (!m_view
|| !m_model
) {
1345 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
1346 if (selectedItems
.isEmpty()) {
1350 QMimeData
*data
= m_model
->createMimeData(selectedItems
);
1354 KUrlMimeData::exportUrlsToPortal(data
);
1356 // The created drag object will be owned and deleted
1357 // by QApplication::activeWindow().
1358 QDrag
* drag
= new QDrag(QApplication::activeWindow());
1359 drag
->setMimeData(data
);
1361 const QPixmap pixmap
= m_view
->createDragPixmap(selectedItems
);
1362 drag
->setPixmap(pixmap
);
1364 const QPoint
hotSpot((pixmap
.width() / pixmap
.devicePixelRatio()) / 2, 0);
1365 drag
->setHotSpot(hotSpot
);
1367 drag
->exec(Qt::MoveAction
| Qt::CopyAction
| Qt::LinkAction
, Qt::CopyAction
);
1369 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropStart
);
1370 QAccessible::updateAccessibility(&accessibilityEvent
);
1373 KItemListWidget
* KItemListController::hoveredWidget() const
1377 const auto widgets
= m_view
->visibleItemListWidgets();
1378 for (KItemListWidget
* widget
: widgets
) {
1379 if (widget
->isHovered()) {
1387 KItemListWidget
* KItemListController::widgetForPos(const QPointF
& pos
) const
1391 const auto widgets
= m_view
->visibleItemListWidgets();
1392 for (KItemListWidget
* widget
: widgets
) {
1393 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1394 if (widget
->contains(mappedPos
) || widget
->selectionRect().contains(mappedPos
)) {
1402 KItemListWidget
* KItemListController::widgetForDropPos(const QPointF
& pos
) const
1406 const auto widgets
= m_view
->visibleItemListWidgets();
1407 for (KItemListWidget
* widget
: widgets
) {
1408 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1409 if (widget
->contains(mappedPos
)) {
1417 void KItemListController::updateKeyboardAnchor()
1419 const bool validAnchor
= m_keyboardAnchorIndex
>= 0 &&
1420 m_keyboardAnchorIndex
< m_model
->count() &&
1421 keyboardAnchorPos(m_keyboardAnchorIndex
) == m_keyboardAnchorPos
;
1423 const int index
= m_selectionManager
->currentItem();
1424 m_keyboardAnchorIndex
= index
;
1425 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
1429 int KItemListController::nextRowIndex(int index
) const
1431 if (m_keyboardAnchorIndex
< 0) {
1435 const int maxIndex
= m_model
->count() - 1;
1436 if (index
== maxIndex
) {
1440 // Calculate the index of the last column inside the row of the current index
1441 int lastColumnIndex
= index
;
1442 while (keyboardAnchorPos(lastColumnIndex
+ 1) > keyboardAnchorPos(lastColumnIndex
)) {
1444 if (lastColumnIndex
>= maxIndex
) {
1449 // Based on the last column index go to the next row and calculate the nearest index
1450 // that is below the current index
1451 int nextRowIndex
= lastColumnIndex
+ 1;
1452 int searchIndex
= nextRowIndex
;
1453 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(nextRowIndex
));
1454 while (searchIndex
< maxIndex
&& keyboardAnchorPos(searchIndex
+ 1) > keyboardAnchorPos(searchIndex
)) {
1456 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1457 if (searchDiff
< minDiff
) {
1458 minDiff
= searchDiff
;
1459 nextRowIndex
= searchIndex
;
1463 return nextRowIndex
;
1466 int KItemListController::previousRowIndex(int index
) const
1468 if (m_keyboardAnchorIndex
< 0 || index
== 0) {
1472 // Calculate the index of the first column inside the row of the current index
1473 int firstColumnIndex
= index
;
1474 while (keyboardAnchorPos(firstColumnIndex
- 1) < keyboardAnchorPos(firstColumnIndex
)) {
1476 if (firstColumnIndex
<= 0) {
1481 // Based on the first column index go to the previous row and calculate the nearest index
1482 // that is above the current index
1483 int previousRowIndex
= firstColumnIndex
- 1;
1484 int searchIndex
= previousRowIndex
;
1485 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(previousRowIndex
));
1486 while (searchIndex
> 0 && keyboardAnchorPos(searchIndex
- 1) < keyboardAnchorPos(searchIndex
)) {
1488 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1489 if (searchDiff
< minDiff
) {
1490 minDiff
= searchDiff
;
1491 previousRowIndex
= searchIndex
;
1495 return previousRowIndex
;
1498 qreal
KItemListController::keyboardAnchorPos(int index
) const
1500 const QRectF itemRect
= m_view
->itemRect(index
);
1501 if (!itemRect
.isEmpty()) {
1502 return (m_view
->scrollOrientation() == Qt::Vertical
) ? itemRect
.x() : itemRect
.y();
1508 void KItemListController::updateExtendedSelectionRegion()
1511 const bool extend
= (m_selectionBehavior
!= MultiSelection
);
1512 KItemListStyleOption option
= m_view
->styleOption();
1513 if (option
.extendedSelectionRegion
!= extend
) {
1514 option
.extendedSelectionRegion
= extend
;
1515 m_view
->setStyleOption(option
);
1520 bool KItemListController::onPress(const QPoint
& screenPos
, const QPointF
& pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
)
1522 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), buttons
);
1524 if (buttons
& (Qt::BackButton
| Qt::ForwardButton
)) {
1525 // Do not select items when clicking the back/forward buttons, see
1526 // https://bugs.kde.org/show_bug.cgi?id=327412.
1530 if (m_view
->isAboveExpansionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
)) {
1531 m_selectionManager
->endAnchoredSelection();
1532 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1533 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1537 m_selectionTogglePressed
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
);
1538 if (m_selectionTogglePressed
) {
1539 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1540 // The previous anchored selection has been finished already in
1541 // KItemListSelectionManager::setSelected(). We can safely change
1542 // the current item and start a new anchored selection now.
1543 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1544 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1548 const bool shiftPressed
= modifiers
& Qt::ShiftModifier
;
1549 const bool controlPressed
= (modifiers
& Qt::ControlModifier
) || m_selectionMode
;
1550 const bool leftClick
= buttons
& Qt::LeftButton
;
1551 const bool rightClick
= buttons
& Qt::RightButton
;
1554 m_longPressDetectionTimer
->start();
1557 // The previous selection is cleared if either
1558 // 1. The selection mode is SingleSelection, or
1559 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1560 // a) Shift or Control are pressed.
1561 // b) The clicked item is selected already. In that case, the user might want to:
1562 // - start dragging multiple items, or
1563 // - open the context menu and perform an action for all selected items.
1564 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
1565 const bool pressedItemAlreadySelected
= m_pressedIndex
.has_value() && m_selectionManager
->isSelected(m_pressedIndex
.value());
1566 const bool clearSelection
= m_selectionBehavior
== SingleSelection
||
1567 (!shiftOrControlPressed
&& !pressedItemAlreadySelected
);
1570 // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller.
1571 if (clearSelection
) {
1572 const int selectedItemsCount
= m_selectionManager
->selectedItems().count();
1573 m_selectionManager
->clearSelection();
1574 // clear and bail when we got an existing multi-selection
1575 if (selectedItemsCount
> 1 && m_pressedIndex
.has_value()) {
1576 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1577 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1578 if (pressedItemAlreadySelected
|| row
->iconRect().contains(mappedPos
) || row
->textRect().contains(mappedPos
)) {
1579 // we are indeed inside the text/icon rect, keep m_pressedIndex what it is
1580 // and short-circuit for single-click activation (it will then propagate to onRelease and activate the item)
1581 // or we just keep going for double-click activation
1582 if (m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) {
1583 if (!pressedItemAlreadySelected
) {
1584 // An unselected item was clicked directly while deselecting multiple other items so we select it.
1585 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1586 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1587 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1589 return true; // event handled, don't create rubber band
1592 // we're not inside the text/icon rect, as we've already cleared the selection
1593 // we can just stop here and make sure handlers down the line (i.e. onRelease) don't activate
1594 m_pressedIndex
.reset();
1595 // we don't stop event propagation and proceed to create a rubber band and let onRelease
1596 // decide (based on m_pressedIndex) whether we're in a drag (drag => new rubber band, click => don't select the item)
1600 } else if (pressedItemAlreadySelected
&& !shiftOrControlPressed
&& leftClick
) {
1601 // The user might want to start dragging multiple items, but if he clicks the item
1602 // in order to trigger it instead, the other selected items must be deselected.
1603 // However, we do not know yet what the user is going to do.
1604 // -> remember that the user pressed an item which had been selected already and
1605 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1606 m_clearSelectionIfItemsAreNotDragged
= true;
1608 if (m_selectionManager
->selectedItems().count() == 1 && m_view
->isAboveText(m_pressedIndex
.value_or(-1), m_pressedMousePos
)) {
1609 Q_EMIT
selectedItemTextPressed(m_pressedIndex
.value_or(-1));
1613 if (!shiftPressed
) {
1614 // Finish the anchored selection before the current index is changed
1615 m_selectionManager
->endAnchoredSelection();
1620 // Do header hit check and short circuit before commencing any state changing effects
1621 if (m_view
->headerBoundaries().contains(pos
)) {
1622 Q_EMIT
headerContextMenuRequested(screenPos
);
1626 // Stop rubber band from persisting after right-clicks
1627 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1628 if (rubberBand
->isActive()) {
1629 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1630 rubberBand
->setActive(false);
1631 m_view
->setAutoScroll(false);
1635 if (m_pressedIndex
.has_value()) {
1636 // The hover highlight area of an item is being pressed.
1637 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1638 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
1639 const bool hitTargetIsRowEmptyRegion
= !row
->contains(row
->mapFromItem(m_view
, pos
));
1640 // again, when this method returns false, a rubberBand selection is created as the event is not consumed;
1641 // createRubberBand here tells us whether to return true or false.
1642 bool createRubberBand
= (hitTargetIsRowEmptyRegion
&& m_selectionManager
->selectedItems().isEmpty());
1644 if (rightClick
&& hitTargetIsRowEmptyRegion
) {
1645 // We have a right click outside the icon and text rect but within the hover highlight area
1646 // but it is unclear if this means that a selection rectangle for an item was clicked or the background of the view.
1647 if (m_selectionManager
->selectedItems().contains(m_pressedIndex
.value())) {
1648 // The selection rectangle for an item was clicked
1649 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), screenPos
);
1651 row
->setHovered(false); // Removes the hover highlight so the context menu doesn't look like it applies to the row.
1652 Q_EMIT
viewContextMenuRequested(screenPos
);
1657 switch (m_selectionBehavior
) {
1661 case SingleSelection
:
1662 m_selectionManager
->setSelected(m_pressedIndex
.value());
1665 case MultiSelection
:
1666 if (controlPressed
&& !shiftPressed
&& leftClick
) {
1667 // A left mouse button press is happening on an item while control is pressed. This either means a user wants to:
1668 // - toggle the selection of item(s) or
1669 // - they want to begin a drag on the item(s) to copy them.
1670 // We rule out the latter, if the item is not clicked directly and was unselected previously.
1671 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1672 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1673 if (!row
->iconRect().contains(mappedPos
) && !row
->textRect().contains(mappedPos
) && !pressedItemAlreadySelected
) {
1674 createRubberBand
= true;
1676 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1677 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1678 createRubberBand
= false; // multi selection, don't propagate any further
1679 // This will be the start of an item drag-to-copy operation if the user now moves the mouse before releasing the mouse button.
1681 } else if (!shiftPressed
|| !m_selectionManager
->isAnchoredSelectionActive()) {
1682 // Select the pressed item and start a new anchored selection
1683 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1684 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1694 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), screenPos
);
1696 return !createRubberBand
;
1700 // header right click handling would have been done before this so just normal context
1701 // menu here is fine
1702 Q_EMIT
viewContextMenuRequested(screenPos
);
1709 bool KItemListController::onRelease(const QPointF
& pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
, bool touch
)
1711 const bool isAboveSelectionToggle
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
);
1712 if (isAboveSelectionToggle
) {
1713 m_selectionTogglePressed
= false;
1717 if (!isAboveSelectionToggle
&& m_selectionTogglePressed
) {
1718 m_selectionManager
->setSelected(m_pressedIndex
.value_or(-1), 1, KItemListSelectionManager::Toggle
);
1719 m_selectionTogglePressed
= false;
1723 const bool controlPressed
= modifiers
& Qt::ControlModifier
;
1724 const bool shiftOrControlPressed
= modifiers
& Qt::ShiftModifier
||
1727 const std::optional
<int> index
= m_view
->itemAt(pos
);
1729 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1730 bool rubberBandRelease
= false;
1731 if (rubberBand
->isActive()) {
1732 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1733 rubberBand
->setActive(false);
1734 m_oldSelection
.clear();
1735 m_view
->setAutoScroll(false);
1736 rubberBandRelease
= true;
1737 // We check for actual rubber band drag here: if delta between start and end is less than drag threshold,
1738 // then we have a single click on one of the rows
1739 if ((rubberBand
->endPosition() - rubberBand
->startPosition()).manhattanLength() < QApplication::startDragDistance()) {
1740 rubberBandRelease
= false; // since we're only selecting, unmark rubber band release flag
1741 // m_pressedIndex will have no value if we came from a multi-selection clearing onPress
1742 // in that case, we don't select anything
1743 if (index
.has_value() && m_pressedIndex
.has_value()) {
1744 if (controlPressed
&& m_selectionBehavior
== MultiSelection
) {
1745 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1747 m_selectionManager
->setSelected(index
.value());
1749 if (!m_selectionManager
->isAnchoredSelectionActive()) {
1750 m_selectionManager
->beginAnchoredSelection(index
.value());
1756 if (index
.has_value() && index
== m_pressedIndex
) {
1757 // The release event is done above the same item as the press event
1759 if (m_clearSelectionIfItemsAreNotDragged
) {
1760 // A selected item has been clicked, but no drag operation has been started
1761 // -> clear the rest of the selection.
1762 m_selectionManager
->clearSelection();
1763 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1764 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1767 if (buttons
& Qt::LeftButton
) {
1768 bool emitItemActivated
= true;
1769 if (m_view
->isAboveExpansionToggle(index
.value(), pos
)) {
1770 const bool expanded
= m_model
->isExpanded(index
.value());
1771 m_model
->setExpanded(index
.value(), !expanded
);
1773 Q_EMIT
itemExpansionToggleClicked(index
.value());
1774 emitItemActivated
= false;
1775 } else if (shiftOrControlPressed
&& m_selectionBehavior
!= SingleSelection
) {
1776 // The mouse click should only update the selection, not trigger the item, except when
1777 // we are in single selection mode
1778 emitItemActivated
= false;
1780 const bool singleClickActivation
= m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
;
1781 if (!singleClickActivation
) {
1782 emitItemActivated
= touch
;
1784 // activate on single click only if we didn't come from a rubber band release
1785 emitItemActivated
= !rubberBandRelease
;
1788 if (emitItemActivated
) {
1789 Q_EMIT
itemActivated(index
.value());
1791 } else if (buttons
& Qt::MiddleButton
) {
1792 Q_EMIT
itemMiddleClicked(index
.value());
1796 m_pressedMousePos
= QPointF();
1797 m_pressedIndex
= std::nullopt
;
1798 m_clearSelectionIfItemsAreNotDragged
= false;
1802 void KItemListController::startRubberBand()
1804 if (m_selectionBehavior
== MultiSelection
) {
1805 QPointF startPos
= m_pressedMousePos
;
1806 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1807 startPos
.ry() += m_view
->scrollOffset();
1808 if (m_view
->itemSize().width() < 0) {
1809 // Use a special rubberband for views that have only one column and
1810 // expand the rubberband to use the whole width of the view.
1814 startPos
.rx() += m_view
->scrollOffset();
1817 m_oldSelection
= m_selectionManager
->selectedItems();
1818 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1819 rubberBand
->setStartPosition(startPos
);
1820 rubberBand
->setEndPosition(startPos
);
1821 rubberBand
->setActive(true);
1822 connect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1823 m_view
->setAutoScroll(true);
1827 void KItemListController::slotStateChanged(QScroller::State newState
)
1829 if (newState
== QScroller::Scrolling
) {
1830 m_scrollerIsScrolling
= true;
1831 } else if (newState
== QScroller::Inactive
) {
1832 m_scrollerIsScrolling
= false;