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>
31 #include <QTouchEvent>
33 KItemListController::KItemListController(KItemModelBase
*model
, KItemListView
*view
, QObject
*parent
)
35 , m_singleClickActivationEnforced(false)
36 , m_selectionMode(false)
37 , m_selectionTogglePressed(false)
38 , m_clearSelectionIfItemsAreNotDragged(false)
39 , m_isSwipeGesture(false)
40 , m_dragActionOrRightClick(false)
41 , m_scrollerIsScrolling(false)
42 , m_pinchGestureInProgress(false)
44 , m_isTouchEvent(false)
45 , m_selectionBehavior(NoSelection
)
46 , m_autoActivationBehavior(ActivationAndExpansion
)
47 , m_mouseDoubleClickAction(ActivateItemOnly
)
50 , m_selectionManager(new KItemListSelectionManager(this))
51 , m_keyboardManager(new KItemListKeyboardSearchManager(this))
52 , m_pressedIndex(std::nullopt
)
54 , m_autoActivationTimer(nullptr)
55 , m_swipeGesture(Qt::CustomGesture
)
56 , m_twoFingerTapGesture(Qt::CustomGesture
)
58 , m_keyboardAnchorIndex(-1)
59 , m_keyboardAnchorPos(0)
61 connect(m_keyboardManager
, &KItemListKeyboardSearchManager::changeCurrentItem
, this, &KItemListController::slotChangeCurrentItem
);
62 connect(m_selectionManager
, &KItemListSelectionManager::currentChanged
, m_keyboardManager
, &KItemListKeyboardSearchManager::slotCurrentChanged
);
63 connect(m_selectionManager
, &KItemListSelectionManager::selectionChanged
, m_keyboardManager
, &KItemListKeyboardSearchManager::slotSelectionChanged
);
65 m_autoActivationTimer
= new QTimer(this);
66 m_autoActivationTimer
->setSingleShot(true);
67 m_autoActivationTimer
->setInterval(-1);
68 connect(m_autoActivationTimer
, &QTimer::timeout
, this, &KItemListController::slotAutoActivationTimeout
);
73 m_swipeGesture
= QGestureRecognizer::registerRecognizer(new KTwoFingerSwipeRecognizer());
74 m_twoFingerTapGesture
= QGestureRecognizer::registerRecognizer(new KTwoFingerTapRecognizer());
75 view
->grabGesture(m_swipeGesture
);
76 view
->grabGesture(m_twoFingerTapGesture
);
77 view
->grabGesture(Qt::TapGesture
);
78 view
->grabGesture(Qt::TapAndHoldGesture
);
79 view
->grabGesture(Qt::PinchGesture
);
82 KItemListController::~KItemListController()
91 void KItemListController::setModel(KItemModelBase
*model
)
93 if (m_model
== model
) {
97 KItemModelBase
*oldModel
= m_model
;
99 oldModel
->deleteLater();
104 m_model
->setParent(this);
108 m_view
->setModel(m_model
);
111 m_selectionManager
->setModel(m_model
);
113 Q_EMIT
modelChanged(m_model
, oldModel
);
116 KItemModelBase
*KItemListController::model() const
121 KItemListSelectionManager
*KItemListController::selectionManager() const
123 return m_selectionManager
;
126 void KItemListController::setView(KItemListView
*view
)
128 if (m_view
== view
) {
132 KItemListView
*oldView
= m_view
;
134 disconnect(oldView
, &KItemListView::scrollOffsetChanged
, this, &KItemListController::slotViewScrollOffsetChanged
);
135 oldView
->deleteLater();
141 m_view
->setParent(this);
142 m_view
->setController(this);
143 m_view
->setModel(m_model
);
144 connect(m_view
, &KItemListView::scrollOffsetChanged
, this, &KItemListController::slotViewScrollOffsetChanged
);
145 updateExtendedSelectionRegion();
148 Q_EMIT
viewChanged(m_view
, oldView
);
151 KItemListView
*KItemListController::view() const
156 void KItemListController::setSelectionBehavior(SelectionBehavior behavior
)
158 m_selectionBehavior
= behavior
;
159 updateExtendedSelectionRegion();
162 KItemListController::SelectionBehavior
KItemListController::selectionBehavior() const
164 return m_selectionBehavior
;
167 void KItemListController::setAutoActivationBehavior(AutoActivationBehavior behavior
)
169 m_autoActivationBehavior
= behavior
;
172 KItemListController::AutoActivationBehavior
KItemListController::autoActivationBehavior() const
174 return m_autoActivationBehavior
;
177 void KItemListController::setMouseDoubleClickAction(MouseDoubleClickAction action
)
179 m_mouseDoubleClickAction
= action
;
182 KItemListController::MouseDoubleClickAction
KItemListController::mouseDoubleClickAction() const
184 return m_mouseDoubleClickAction
;
187 int KItemListController::indexCloseToMousePressedPosition() const
189 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_view
->m_visibleGroups
);
190 while (it
.hasNext()) {
192 KItemListGroupHeader
*groupHeader
= it
.value();
193 const QPointF mappedToGroup
= groupHeader
->mapFromItem(nullptr, m_pressedMousePos
);
194 if (groupHeader
->contains(mappedToGroup
)) {
195 return it
.key()->index();
201 void KItemListController::setAutoActivationDelay(int delay
)
203 m_autoActivationTimer
->setInterval(delay
);
206 int KItemListController::autoActivationDelay() const
208 return m_autoActivationTimer
->interval();
211 void KItemListController::setSingleClickActivationEnforced(bool singleClick
)
213 m_singleClickActivationEnforced
= singleClick
;
216 bool KItemListController::singleClickActivationEnforced() const
218 return m_singleClickActivationEnforced
;
221 void KItemListController::setSelectionModeEnabled(bool enabled
)
223 m_selectionMode
= enabled
;
226 bool KItemListController::selectionMode() const
228 return m_selectionMode
;
231 bool KItemListController::keyPressEvent(QKeyEvent
*event
)
233 int index
= m_selectionManager
->currentItem();
234 int key
= event
->key();
236 // Handle the expanding/collapsing of items
237 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
)) {
238 if (key
== Qt::Key_Right
) {
239 if (m_model
->setExpanded(index
, true)) {
242 } else if (key
== Qt::Key_Left
) {
243 if (m_model
->setExpanded(index
, false)) {
249 const bool shiftPressed
= event
->modifiers() & Qt::ShiftModifier
;
250 const bool controlPressed
= event
->modifiers() & Qt::ControlModifier
;
251 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
252 const bool navigationPressed
= key
== Qt::Key_Home
|| key
== Qt::Key_End
|| key
== Qt::Key_PageUp
|| key
== Qt::Key_PageDown
|| key
== Qt::Key_Up
253 || key
== Qt::Key_Down
|| key
== Qt::Key_Left
|| key
== Qt::Key_Right
;
255 const int itemCount
= m_model
->count();
257 // For horizontal scroll orientation, transform
258 // the arrow keys to simplify the event handling.
259 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
278 const bool selectSingleItem
= m_selectionBehavior
!= NoSelection
&& itemCount
== 1 && navigationPressed
;
280 if (selectSingleItem
) {
281 const int current
= m_selectionManager
->currentItem();
282 m_selectionManager
->setSelected(current
);
289 m_keyboardAnchorIndex
= index
;
290 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
294 index
= itemCount
- 1;
295 m_keyboardAnchorIndex
= index
;
296 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
301 const int expandedParentsCount
= m_model
->expandedParentsCount(index
);
302 if (expandedParentsCount
== 0) {
305 // Go to the parent of the current item.
308 } while (index
> 0 && m_model
->expandedParentsCount(index
) == expandedParentsCount
);
310 m_keyboardAnchorIndex
= index
;
311 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
316 if (index
< itemCount
- 1) {
318 m_keyboardAnchorIndex
= index
;
319 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
324 updateKeyboardAnchor();
325 index
= previousRowIndex(index
);
329 updateKeyboardAnchor();
330 index
= nextRowIndex(index
);
334 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
335 // The new current index should correspond to the first item in the current column.
336 int newIndex
= qMax(index
- 1, 0);
337 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() < m_view
->itemRect(index
).topLeft().y()) {
339 newIndex
= qMax(index
- 1, 0);
341 m_keyboardAnchorIndex
= index
;
342 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
344 const qreal currentItemBottom
= m_view
->itemRect(index
).bottomLeft().y();
345 const qreal height
= m_view
->geometry().height();
347 // The new current item should be the first item in the current
348 // column whose itemRect's top coordinate is larger than targetY.
349 const qreal targetY
= currentItemBottom
- height
;
351 updateKeyboardAnchor();
352 int newIndex
= previousRowIndex(index
);
355 updateKeyboardAnchor();
356 newIndex
= previousRowIndex(index
);
357 } while (m_view
->itemRect(newIndex
).topLeft().y() > targetY
&& newIndex
!= index
);
361 case Qt::Key_PageDown
:
362 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
363 // The new current index should correspond to the last item in the current column.
364 int newIndex
= qMin(index
+ 1, m_model
->count() - 1);
365 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() > m_view
->itemRect(index
).topLeft().y()) {
367 newIndex
= qMin(index
+ 1, m_model
->count() - 1);
369 m_keyboardAnchorIndex
= index
;
370 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
372 const qreal currentItemTop
= m_view
->itemRect(index
).topLeft().y();
373 const qreal height
= m_view
->geometry().height();
375 // The new current item should be the last item in the current
376 // column whose itemRect's bottom coordinate is smaller than targetY.
377 const qreal targetY
= currentItemTop
+ height
;
379 updateKeyboardAnchor();
380 int newIndex
= nextRowIndex(index
);
383 updateKeyboardAnchor();
384 newIndex
= nextRowIndex(index
);
385 } while (m_view
->itemRect(newIndex
).bottomLeft().y() < targetY
&& newIndex
!= index
);
390 case Qt::Key_Return
: {
391 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
392 if (selectedItems
.count() >= 2) {
393 Q_EMIT
itemsActivated(selectedItems
);
394 } else if (selectedItems
.count() == 1) {
395 Q_EMIT
itemActivated(selectedItems
.first());
397 Q_EMIT
itemActivated(index
);
403 // Emit the signal itemContextMenuRequested() in case if at least one
404 // item is selected. Otherwise the signal viewContextMenuRequested() will be emitted.
405 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
407 if (selectedItems
.count() >= 2) {
408 const int currentItemIndex
= m_selectionManager
->currentItem();
409 index
= selectedItems
.contains(currentItemIndex
) ? currentItemIndex
: selectedItems
.first();
410 } else if (selectedItems
.count() == 1) {
411 index
= selectedItems
.first();
415 const QRectF contextRect
= m_view
->itemContextRect(index
);
416 const QPointF
pos(m_view
->scene()->views().first()->mapToGlobal(contextRect
.bottomRight().toPoint()));
417 Q_EMIT
itemContextMenuRequested(index
, pos
);
419 Q_EMIT
viewContextMenuRequested(QCursor::pos());
425 if (m_selectionMode
) {
426 Q_EMIT
selectionModeChangeRequested(false);
427 } else if (m_selectionBehavior
!= SingleSelection
) {
428 m_selectionManager
->clearSelection();
430 m_keyboardManager
->cancelSearch();
431 Q_EMIT
escapePressed();
435 if (m_selectionBehavior
== MultiSelection
) {
436 if (controlPressed
) {
437 // Toggle the selection state of the current item.
438 m_selectionManager
->endAnchoredSelection();
439 m_selectionManager
->setSelected(index
, 1, KItemListSelectionManager::Toggle
);
440 m_selectionManager
->beginAnchoredSelection(index
);
442 } else if (m_keyboardManager
->addKeyBeginsNewSearch()) { // File names shouldn't start with a space,
443 // so we can use this press as a keyboard shortcut instead.
444 Q_EMIT
selectionModeChangeRequested(!m_selectionMode
);
448 Q_FALLTHROUGH(); // fall through to the default case and add the Space to the current search string.
450 m_keyboardManager
->addKeys(event
->text());
451 // Make sure unconsumed events get propagated up the chain. #302329
456 if (m_selectionManager
->currentItem() != index
) {
457 switch (m_selectionBehavior
) {
459 m_selectionManager
->setCurrentItem(index
);
462 case SingleSelection
:
463 m_selectionManager
->setCurrentItem(index
);
464 m_selectionManager
->clearSelection();
465 m_selectionManager
->setSelected(index
, 1);
469 if (controlPressed
) {
470 m_selectionManager
->endAnchoredSelection();
473 m_selectionManager
->setCurrentItem(index
);
475 if (!shiftOrControlPressed
) {
476 m_selectionManager
->clearSelection();
477 m_selectionManager
->setSelected(index
, 1);
481 m_selectionManager
->beginAnchoredSelection(index
);
487 if (navigationPressed
) {
488 m_view
->scrollToItem(index
);
493 void KItemListController::slotChangeCurrentItem(const QString
&text
, bool searchFromNextItem
)
495 if (!m_model
|| m_model
->count() == 0) {
499 if (searchFromNextItem
) {
500 const int currentIndex
= m_selectionManager
->currentItem();
501 index
= m_model
->indexForKeyboardSearch(text
, (currentIndex
+ 1) % m_model
->count());
503 index
= m_model
->indexForKeyboardSearch(text
, 0);
506 m_selectionManager
->setCurrentItem(index
);
508 if (m_selectionBehavior
!= NoSelection
) {
509 m_selectionManager
->replaceSelection(index
);
510 m_selectionManager
->beginAnchoredSelection(index
);
513 m_view
->scrollToItem(index
);
517 void KItemListController::slotAutoActivationTimeout()
519 if (!m_model
|| !m_view
) {
523 const int index
= m_autoActivationTimer
->property("index").toInt();
524 if (index
< 0 || index
>= m_model
->count()) {
528 /* m_view->isUnderMouse() fixes a bug in the Folder-View-Panel and in the
531 * Bug: When you drag a file onto a Folder-View-Item or a Places-Item and
532 * then move away before the auto-activation timeout triggers, than the
533 * item still becomes activated/expanded.
535 * See Bug 293200 and 305783
537 if (m_model
->supportsDropping(index
) && m_view
->isUnderMouse()) {
538 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
)) {
539 const bool expanded
= m_model
->isExpanded(index
);
540 m_model
->setExpanded(index
, !expanded
);
541 } else if (m_autoActivationBehavior
!= ExpansionOnly
) {
542 Q_EMIT
itemActivated(index
);
547 bool KItemListController::inputMethodEvent(QInputMethodEvent
*event
)
553 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
557 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& m_isTouchEvent
) {
565 m_pressedMousePos
= transform
.map(event
->pos());
566 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
568 const Qt::MouseButtons buttons
= event
->buttons();
570 if (!onPress(event
->screenPos(), event
->pos(), event
->modifiers(), buttons
)) {
578 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
584 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
585 m_view
->m_tapAndHoldIndicator
->setActive(false);
588 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !m_dragActionOrRightClick
&& m_isTouchEvent
) {
592 const QPointF pos
= transform
.map(event
->pos());
594 if (m_pressedIndex
.has_value() && !m_view
->rubberBand()->isActive()) {
595 // Check whether a dragging should be started
596 if (event
->buttons() & Qt::LeftButton
) {
597 if ((pos
- m_pressedMousePos
).manhattanLength() >= QApplication::startDragDistance()) {
598 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
599 // Always assure that the dragged item gets selected. Usually this is already
600 // done on the mouse-press event, but when using the selection-toggle on a
601 // selected item the dragged item is not selected yet.
602 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
604 // A selected item has been clicked to drag all selected items
605 // -> the selection should not be cleared when the mouse button is released.
606 m_clearSelectionIfItemsAreNotDragged
= false;
609 m_mousePress
= false;
613 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
614 if (rubberBand
->isActive()) {
615 QPointF endPos
= transform
.map(event
->pos());
617 // Update the current item.
618 const std::optional
<int> newCurrent
= m_view
->itemAt(endPos
);
619 if (newCurrent
.has_value()) {
620 // It's expected that the new current index is also the new anchor (bug 163451).
621 m_selectionManager
->endAnchoredSelection();
622 m_selectionManager
->setCurrentItem(newCurrent
.value());
623 m_selectionManager
->beginAnchoredSelection(newCurrent
.value());
626 if (m_view
->scrollOrientation() == Qt::Vertical
) {
627 endPos
.ry() += m_view
->scrollOffset();
628 if (m_view
->itemSize().width() < 0) {
629 // Use a special rubberband for views that have only one column and
630 // expand the rubberband to use the whole width of the view.
631 endPos
.setX(m_view
->size().width());
634 endPos
.rx() += m_view
->scrollOffset();
636 rubberBand
->setEndPosition(endPos
);
643 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
645 m_mousePress
= false;
646 m_isTouchEvent
= false;
652 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
653 m_view
->m_tapAndHoldIndicator
->setActive(false);
656 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
657 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !rubberBand
->isActive() && m_isTouchEvent
) {
661 Q_EMIT
mouseButtonReleased(m_pressedIndex
.value_or(-1), event
->buttons());
663 return onRelease(transform
.map(event
->pos()), event
->modifiers(), event
->button(), false);
666 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
668 const QPointF pos
= transform
.map(event
->pos());
669 const std::optional
<int> index
= m_view
->itemAt(pos
);
671 // Expand item if desired - See Bug 295573
672 if (m_mouseDoubleClickAction
!= ActivateItemOnly
) {
673 if (m_view
&& m_model
&& m_view
->supportsItemExpanding() && m_model
->isExpandable(index
.value_or(-1))) {
674 const bool expanded
= m_model
->isExpanded(index
.value());
675 m_model
->setExpanded(index
.value(), !expanded
);
679 if (event
->button() & Qt::RightButton
) {
680 m_selectionManager
->clearSelection();
681 if (index
.has_value()) {
682 m_selectionManager
->setSelected(index
.value());
683 Q_EMIT
itemContextMenuRequested(index
.value(), event
->screenPos());
685 const QRectF headerBounds
= m_view
->headerBoundaries();
686 if (headerBounds
.contains(event
->pos())) {
687 Q_EMIT
headerContextMenuRequested(event
->screenPos());
689 Q_EMIT
viewContextMenuRequested(event
->screenPos());
695 bool emitItemActivated
= !(m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
)
696 && (event
->button() & Qt::LeftButton
) && index
.has_value() && index
.value() < m_model
->count();
697 if (emitItemActivated
) {
698 Q_EMIT
itemActivated(index
.value());
703 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
708 DragAndDropHelper::clearUrlListMatchesUrlCache();
713 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
718 m_autoActivationTimer
->stop();
719 m_view
->setAutoScroll(false);
720 m_view
->hideDropIndicator();
722 KItemListWidget
*widget
= hoveredWidget();
724 widget
->setHovered(false);
725 Q_EMIT
itemUnhovered(widget
->index());
730 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
732 if (!m_model
|| !m_view
) {
736 QUrl hoveredDir
= m_model
->directory();
737 KItemListWidget
*oldHoveredWidget
= hoveredWidget();
739 const QPointF pos
= transform
.map(event
->pos());
740 KItemListWidget
*newHoveredWidget
= widgetForDropPos(pos
);
742 if (oldHoveredWidget
!= newHoveredWidget
) {
743 m_autoActivationTimer
->stop();
745 if (oldHoveredWidget
) {
746 oldHoveredWidget
->setHovered(false);
747 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
751 if (newHoveredWidget
) {
752 bool droppingBetweenItems
= false;
753 if (m_model
->sortRole().isEmpty()) {
754 // The model supports inserting items between other items.
755 droppingBetweenItems
= (m_view
->showDropIndicator(pos
) >= 0);
758 const int index
= newHoveredWidget
->index();
760 if (m_model
->isDir(index
)) {
761 hoveredDir
= m_model
->url(index
);
764 if (!droppingBetweenItems
) {
765 if (m_model
->supportsDropping(index
)) {
766 // Something has been dragged on an item.
767 m_view
->hideDropIndicator();
768 if (!newHoveredWidget
->isHovered()) {
769 newHoveredWidget
->setHovered(true);
770 Q_EMIT
itemHovered(index
);
773 if (!m_autoActivationTimer
->isActive() && m_autoActivationTimer
->interval() >= 0) {
774 m_autoActivationTimer
->setProperty("index", index
);
775 m_autoActivationTimer
->start();
779 m_autoActivationTimer
->stop();
780 if (newHoveredWidget
&& newHoveredWidget
->isHovered()) {
781 newHoveredWidget
->setHovered(false);
782 Q_EMIT
itemUnhovered(index
);
786 m_view
->hideDropIndicator();
789 if (DragAndDropHelper::urlListMatchesUrl(event
->mimeData()->urls(), hoveredDir
)) {
790 event
->setDropAction(Qt::IgnoreAction
);
793 event
->setDropAction(event
->proposedAction());
799 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
805 m_autoActivationTimer
->stop();
806 m_view
->setAutoScroll(false);
808 const QPointF pos
= transform
.map(event
->pos());
810 int dropAboveIndex
= -1;
811 if (m_model
->sortRole().isEmpty()) {
812 // The model supports inserting of items between other items.
813 dropAboveIndex
= m_view
->showDropIndicator(pos
);
816 if (dropAboveIndex
>= 0) {
817 // Something has been dropped between two items.
818 m_view
->hideDropIndicator();
819 Q_EMIT
aboveItemDropEvent(dropAboveIndex
, event
);
820 } else if (!event
->mimeData()->hasFormat(m_model
->blacklistItemDropEventMimeType())) {
821 // Something has been dropped on an item or on an empty part of the view.
822 const KItemListWidget
*receivingWidget
= widgetForDropPos(pos
);
823 if (receivingWidget
) {
824 Q_EMIT
itemDropEvent(receivingWidget
->index(), event
);
826 Q_EMIT
itemDropEvent(-1, event
);
830 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropEnd
);
831 QAccessible::updateAccessibility(&accessibilityEvent
);
836 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
843 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
846 if (!m_model
|| !m_view
) {
850 // We identify the widget whose expansionArea had been hovered before this hoverMoveEvent() triggered.
851 // we can't use hoveredWidget() here (it handles the icon+text rect, not the expansion rect)
852 // like hoveredWidget(), we find the hovered widget for the expansion rect
853 const auto visibleItemListWidgets
= m_view
->visibleItemListWidgets();
854 const auto oldHoveredExpansionWidgetIterator
= std::find_if(visibleItemListWidgets
.begin(), visibleItemListWidgets
.end(), [](auto &widget
) {
855 return widget
->expansionAreaHovered();
857 const auto oldHoveredExpansionWidget
=
858 oldHoveredExpansionWidgetIterator
== visibleItemListWidgets
.end() ? std::nullopt
: std::make_optional(*oldHoveredExpansionWidgetIterator
);
860 const auto unhoverOldHoveredWidget
= [&]() {
861 if (auto oldHoveredWidget
= hoveredWidget(); oldHoveredWidget
) {
862 // handle the text+icon one
863 oldHoveredWidget
->setHovered(false);
864 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
868 const auto unhoverOldExpansionWidget
= [&]() {
869 if (oldHoveredExpansionWidget
) {
870 // then the expansion toggle
871 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
875 const QPointF pos
= transform
.map(event
->pos());
876 if (KItemListWidget
*newHoveredWidget
= widgetForPos(pos
); newHoveredWidget
) {
877 // something got hovered, work out which part and set hover for the appropriate widget
878 const auto mappedPos
= newHoveredWidget
->mapFromItem(m_view
, pos
);
879 const bool isOnExpansionToggle
= newHoveredWidget
->expansionToggleRect().contains(mappedPos
);
881 if (isOnExpansionToggle
) {
882 // make sure we unhover the old one first if old!=new
883 if (oldHoveredExpansionWidget
&& *oldHoveredExpansionWidget
!= newHoveredWidget
) {
884 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
886 // 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)
887 unhoverOldHoveredWidget();
889 newHoveredWidget
->setExpansionAreaHovered(true);
891 // make sure we unhover the old one first if old!=new
892 auto oldHoveredWidget
= hoveredWidget();
893 if (oldHoveredWidget
&& oldHoveredWidget
!= newHoveredWidget
) {
894 oldHoveredWidget
->setHovered(false);
895 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
897 // 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)
898 unhoverOldExpansionWidget();
900 const bool isOverIconAndText
= newHoveredWidget
->iconRect().contains(mappedPos
) || newHoveredWidget
->textRect().contains(mappedPos
);
901 const bool hasMultipleSelection
= m_selectionManager
->selectedItems().count() > 1;
903 if (hasMultipleSelection
&& !isOverIconAndText
) {
904 // In case we have multiple selections, clicking on any row will deselect the selection.
905 // So, as a visual cue for signalling that clicking anywhere won't select, but clear current highlights,
906 // we disable hover of the *row*(i.e. blank space to the right of the icon+text)
908 // (no-op in this branch for masked hover)
910 newHoveredWidget
->setHoverPosition(mappedPos
);
911 if (oldHoveredWidget
!= newHoveredWidget
) {
912 newHoveredWidget
->setHovered(true);
913 Q_EMIT
itemHovered(newHoveredWidget
->index());
918 // unhover any currently hovered expansion and text+icon widgets
919 unhoverOldHoveredWidget();
920 unhoverOldExpansionWidget();
925 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
930 m_mousePress
= false;
931 m_isTouchEvent
= false;
933 if (!m_model
|| !m_view
) {
937 const auto widgets
= m_view
->visibleItemListWidgets();
938 for (KItemListWidget
*widget
: widgets
) {
939 if (widget
->isHovered()) {
940 widget
->setHovered(false);
941 Q_EMIT
itemUnhovered(widget
->index());
947 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent
*event
, const QTransform
&transform
)
954 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent
*event
, const QTransform
&transform
)
961 bool KItemListController::gestureEvent(QGestureEvent
*event
, const QTransform
&transform
)
967 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
968 //we use this to get the right QWidget
969 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
971 if (QGesture
*tap
= event
->gesture(Qt::TapGesture
)) {
972 QTapGesture
*tapGesture
= static_cast<QTapGesture
*>(tap
);
973 if (tapGesture
->state() == Qt::GestureStarted
) {
974 tapTriggered(tapGesture
, transform
);
980 bool accepted
= false;
982 if (QGesture
*tap
= event
->gesture(Qt::TapGesture
)) {
983 tapTriggered(static_cast<QTapGesture
*>(tap
), transform
);
986 if (event
->gesture(Qt::TapAndHoldGesture
)) {
987 tapAndHoldTriggered(event
, transform
);
990 if (event
->gesture(Qt::PinchGesture
)) {
991 pinchTriggered(event
, transform
);
994 if (event
->gesture(m_swipeGesture
)) {
995 swipeTriggered(event
, transform
);
998 if (event
->gesture(m_twoFingerTapGesture
)) {
999 twoFingerTapTriggered(event
, transform
);
1005 bool KItemListController::touchBeginEvent(QTouchEvent
*event
, const QTransform
&transform
)
1010 m_isTouchEvent
= true;
1014 void KItemListController::tapTriggered(QTapGesture
*tap
, const QTransform
&transform
)
1016 static bool scrollerWasActive
= false;
1018 if (tap
->state() == Qt::GestureStarted
) {
1019 m_dragActionOrRightClick
= false;
1020 m_isSwipeGesture
= false;
1021 m_pinchGestureInProgress
= false;
1022 scrollerWasActive
= m_scrollerIsScrolling
;
1025 if (tap
->state() == Qt::GestureFinished
) {
1026 m_mousePress
= false;
1028 //if at the moment of the gesture start the QScroller was active, the user made the tap
1029 //to stop the QScroller and not to tap on an item
1030 if (scrollerWasActive
) {
1034 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
1035 m_view
->m_tapAndHoldIndicator
->setActive(false);
1038 m_pressedMousePos
= transform
.map(tap
->position());
1039 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1041 if (m_dragActionOrRightClick
) {
1042 m_dragActionOrRightClick
= false;
1044 onPress(tap
->hotSpot().toPoint(), tap
->position().toPoint(), Qt::NoModifier
, Qt::LeftButton
);
1045 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::LeftButton
, true);
1047 m_isTouchEvent
= false;
1051 void KItemListController::tapAndHoldTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1053 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
1054 if (!m_isTouchEvent
) {
1058 const QTapAndHoldGesture
*tap
= static_cast<QTapAndHoldGesture
*>(event
->gesture(Qt::TapAndHoldGesture
));
1059 if (tap
->state() == Qt::GestureFinished
) {
1060 //if a pinch gesture is in progress we don't want a TabAndHold gesture
1061 if (m_pinchGestureInProgress
) {
1064 m_pressedMousePos
= transform
.map(event
->mapToGraphicsScene(tap
->position()));
1065 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1067 if (m_pressedIndex
.has_value() && !m_selectionManager
->isSelected(m_pressedIndex
.value())) {
1068 m_selectionManager
->clearSelection();
1069 m_selectionManager
->setSelected(m_pressedIndex
.value());
1070 if (!m_selectionMode
) {
1071 Q_EMIT
selectionModeChangeRequested(true);
1073 } else if (!m_pressedIndex
.has_value()) {
1074 m_selectionManager
->clearSelection();
1078 Q_EMIT
scrollerStop();
1080 m_view
->m_tapAndHoldIndicator
->setStartPosition(m_pressedMousePos
);
1081 m_view
->m_tapAndHoldIndicator
->setActive(true);
1083 m_dragActionOrRightClick
= true;
1087 void KItemListController::pinchTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1091 const QPinchGesture
*pinch
= static_cast<QPinchGesture
*>(event
->gesture(Qt::PinchGesture
));
1092 const qreal sensitivityModifier
= 0.2;
1093 static qreal counter
= 0;
1095 if (pinch
->state() == Qt::GestureStarted
) {
1096 m_pinchGestureInProgress
= true;
1099 if (pinch
->state() == Qt::GestureUpdated
) {
1100 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1101 if (m_isSwipeGesture
) {
1104 counter
= counter
+ (pinch
->scaleFactor() - 1);
1105 if (counter
>= sensitivityModifier
) {
1106 Q_EMIT
increaseZoom();
1108 } else if (counter
<= -sensitivityModifier
) {
1109 Q_EMIT
decreaseZoom();
1115 void KItemListController::swipeTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1119 const KTwoFingerSwipe
*swipe
= static_cast<KTwoFingerSwipe
*>(event
->gesture(m_swipeGesture
));
1124 if (swipe
->state() == Qt::GestureStarted
) {
1125 m_isSwipeGesture
= true;
1128 if (swipe
->state() == Qt::GestureCanceled
) {
1129 m_isSwipeGesture
= false;
1132 if (swipe
->state() == Qt::GestureFinished
) {
1133 Q_EMIT
scrollerStop();
1135 if (swipe
->swipeAngle() <= 20 || swipe
->swipeAngle() >= 340) {
1136 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::BackButton
);
1137 } else if (swipe
->swipeAngle() <= 200 && swipe
->swipeAngle() >= 160) {
1138 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::ForwardButton
);
1139 } else if (swipe
->swipeAngle() <= 110 && swipe
->swipeAngle() >= 60) {
1142 m_isSwipeGesture
= true;
1146 void KItemListController::twoFingerTapTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1148 const KTwoFingerTap
*twoTap
= static_cast<KTwoFingerTap
*>(event
->gesture(m_twoFingerTapGesture
));
1154 if (twoTap
->state() == Qt::GestureStarted
) {
1155 m_pressedMousePos
= transform
.map(twoTap
->pos());
1156 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1157 if (m_pressedIndex
.has_value()) {
1158 onPress(twoTap
->screenPos().toPoint(), twoTap
->pos().toPoint(), Qt::ControlModifier
, Qt::LeftButton
);
1159 onRelease(transform
.map(twoTap
->pos()), Qt::ControlModifier
, Qt::LeftButton
, false);
1164 bool KItemListController::processEvent(QEvent
*event
, const QTransform
&transform
)
1170 switch (event
->type()) {
1171 case QEvent::KeyPress
:
1172 return keyPressEvent(static_cast<QKeyEvent
*>(event
));
1173 case QEvent::InputMethod
:
1174 return inputMethodEvent(static_cast<QInputMethodEvent
*>(event
));
1175 case QEvent::GraphicsSceneMousePress
:
1176 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1177 case QEvent::GraphicsSceneMouseMove
:
1178 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1179 case QEvent::GraphicsSceneMouseRelease
:
1180 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1181 case QEvent::GraphicsSceneMouseDoubleClick
:
1182 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1183 case QEvent::GraphicsSceneWheel
:
1184 return wheelEvent(static_cast<QGraphicsSceneWheelEvent
*>(event
), QTransform());
1185 case QEvent::GraphicsSceneDragEnter
:
1186 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1187 case QEvent::GraphicsSceneDragLeave
:
1188 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1189 case QEvent::GraphicsSceneDragMove
:
1190 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1191 case QEvent::GraphicsSceneDrop
:
1192 return dropEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1193 case QEvent::GraphicsSceneHoverEnter
:
1194 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1195 case QEvent::GraphicsSceneHoverMove
:
1196 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1197 case QEvent::GraphicsSceneHoverLeave
:
1198 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1199 case QEvent::GraphicsSceneResize
:
1200 return resizeEvent(static_cast<QGraphicsSceneResizeEvent
*>(event
), transform
);
1201 case QEvent::Gesture
:
1202 return gestureEvent(static_cast<QGestureEvent
*>(event
), transform
);
1203 case QEvent::TouchBegin
:
1204 return touchBeginEvent(static_cast<QTouchEvent
*>(event
), transform
);
1212 void KItemListController::slotViewScrollOffsetChanged(qreal current
, qreal previous
)
1218 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1219 if (rubberBand
->isActive()) {
1220 const qreal diff
= current
- previous
;
1221 // TODO: Ideally just QCursor::pos() should be used as
1222 // new end-position but it seems there is no easy way
1223 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1224 // (... or I just missed an easy way to do the mapping)
1225 QPointF endPos
= rubberBand
->endPosition();
1226 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1227 endPos
.ry() += diff
;
1229 endPos
.rx() += diff
;
1232 rubberBand
->setEndPosition(endPos
);
1236 void KItemListController::slotRubberBandChanged()
1238 if (!m_view
|| !m_model
|| m_model
->count() <= 0) {
1242 const KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1243 const QPointF startPos
= rubberBand
->startPosition();
1244 const QPointF endPos
= rubberBand
->endPosition();
1245 QRectF rubberBandRect
= QRectF(startPos
, endPos
).normalized();
1247 const bool scrollVertical
= (m_view
->scrollOrientation() == Qt::Vertical
);
1248 if (scrollVertical
) {
1249 rubberBandRect
.translate(0, -m_view
->scrollOffset());
1251 rubberBandRect
.translate(-m_view
->scrollOffset(), 0);
1254 if (!m_oldSelection
.isEmpty()) {
1255 // Clear the old selection that was available before the rubberband has
1256 // been activated in case if no Shift- or Control-key are pressed
1257 const bool shiftOrControlPressed
= QApplication::keyboardModifiers() & Qt::ShiftModifier
|| QApplication::keyboardModifiers() & Qt::ControlModifier
;
1258 if (!shiftOrControlPressed
&& !m_selectionMode
) {
1259 m_oldSelection
.clear();
1263 KItemSet selectedItems
;
1265 // Select all visible items that intersect with the rubberband
1266 const auto widgets
= m_view
->visibleItemListWidgets();
1267 for (const KItemListWidget
*widget
: widgets
) {
1268 const int index
= widget
->index();
1270 const QRectF widgetRect
= m_view
->itemRect(index
);
1271 if (widgetRect
.intersects(rubberBandRect
)) {
1272 const QRectF iconRect
= widget
->iconRect().translated(widgetRect
.topLeft());
1273 const QRectF textRect
= widget
->textRect().translated(widgetRect
.topLeft());
1274 if (iconRect
.intersects(rubberBandRect
) || textRect
.intersects(rubberBandRect
)) {
1275 selectedItems
.insert(index
);
1280 // Select all invisible items that intersect with the rubberband. Instead of
1281 // iterating all items only the area which might be touched by the rubberband
1283 const bool increaseIndex
= scrollVertical
? startPos
.y() > endPos
.y() : startPos
.x() > endPos
.x();
1285 int index
= increaseIndex
? m_view
->lastVisibleIndex() + 1 : m_view
->firstVisibleIndex() - 1;
1286 bool selectionFinished
= false;
1288 const QRectF widgetRect
= m_view
->itemRect(index
);
1289 if (widgetRect
.intersects(rubberBandRect
)) {
1290 selectedItems
.insert(index
);
1293 if (increaseIndex
) {
1295 selectionFinished
= (index
>= m_model
->count()) || (scrollVertical
&& widgetRect
.top() > rubberBandRect
.bottom())
1296 || (!scrollVertical
&& widgetRect
.left() > rubberBandRect
.right());
1299 selectionFinished
= (index
< 0) || (scrollVertical
&& widgetRect
.bottom() < rubberBandRect
.top())
1300 || (!scrollVertical
&& widgetRect
.right() < rubberBandRect
.left());
1302 } while (!selectionFinished
);
1304 if ((QApplication::keyboardModifiers() & Qt::ControlModifier
) || m_selectionMode
) {
1305 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1306 // Therefore, the new selection contains:
1307 // 1. All previously selected items which are not inside the rubberband, and
1308 // 2. all items inside the rubberband which have not been selected previously.
1309 m_selectionManager
->setSelectedItems(m_oldSelection
^ selectedItems
);
1311 m_selectionManager
->setSelectedItems(selectedItems
+ m_oldSelection
);
1315 void KItemListController::startDragging()
1317 if (!m_view
|| !m_model
) {
1321 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
1322 if (selectedItems
.isEmpty()) {
1326 QMimeData
*data
= m_model
->createMimeData(selectedItems
);
1330 KUrlMimeData::exportUrlsToPortal(data
);
1332 // The created drag object will be owned and deleted
1333 // by QApplication::activeWindow().
1334 QDrag
*drag
= new QDrag(QApplication::activeWindow());
1335 drag
->setMimeData(data
);
1337 const QPixmap pixmap
= m_view
->createDragPixmap(selectedItems
);
1338 drag
->setPixmap(pixmap
);
1340 const QPoint
hotSpot((pixmap
.width() / pixmap
.devicePixelRatio()) / 2, 0);
1341 drag
->setHotSpot(hotSpot
);
1343 drag
->exec(Qt::MoveAction
| Qt::CopyAction
| Qt::LinkAction
, Qt::CopyAction
);
1345 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropStart
);
1346 QAccessible::updateAccessibility(&accessibilityEvent
);
1349 KItemListWidget
*KItemListController::hoveredWidget() const
1353 const auto widgets
= m_view
->visibleItemListWidgets();
1354 for (KItemListWidget
*widget
: widgets
) {
1355 if (widget
->isHovered()) {
1363 KItemListWidget
*KItemListController::widgetForPos(const QPointF
&pos
) const
1367 const auto widgets
= m_view
->visibleItemListWidgets();
1368 for (KItemListWidget
*widget
: widgets
) {
1369 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1370 if (widget
->contains(mappedPos
) || widget
->selectionRect().contains(mappedPos
)) {
1378 KItemListWidget
*KItemListController::widgetForDropPos(const QPointF
&pos
) const
1382 const auto widgets
= m_view
->visibleItemListWidgets();
1383 for (KItemListWidget
*widget
: widgets
) {
1384 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1385 if (widget
->contains(mappedPos
)) {
1393 void KItemListController::updateKeyboardAnchor()
1395 const bool validAnchor
=
1396 m_keyboardAnchorIndex
>= 0 && m_keyboardAnchorIndex
< m_model
->count() && keyboardAnchorPos(m_keyboardAnchorIndex
) == m_keyboardAnchorPos
;
1398 const int index
= m_selectionManager
->currentItem();
1399 m_keyboardAnchorIndex
= index
;
1400 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
1404 int KItemListController::nextRowIndex(int index
) const
1406 if (m_keyboardAnchorIndex
< 0) {
1410 const int maxIndex
= m_model
->count() - 1;
1411 if (index
== maxIndex
) {
1415 // Calculate the index of the last column inside the row of the current index
1416 int lastColumnIndex
= index
;
1417 while (keyboardAnchorPos(lastColumnIndex
+ 1) > keyboardAnchorPos(lastColumnIndex
)) {
1419 if (lastColumnIndex
>= maxIndex
) {
1424 // Based on the last column index go to the next row and calculate the nearest index
1425 // that is below the current index
1426 int nextRowIndex
= lastColumnIndex
+ 1;
1427 int searchIndex
= nextRowIndex
;
1428 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(nextRowIndex
));
1429 while (searchIndex
< maxIndex
&& keyboardAnchorPos(searchIndex
+ 1) > keyboardAnchorPos(searchIndex
)) {
1431 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1432 if (searchDiff
< minDiff
) {
1433 minDiff
= searchDiff
;
1434 nextRowIndex
= searchIndex
;
1438 return nextRowIndex
;
1441 int KItemListController::previousRowIndex(int index
) const
1443 if (m_keyboardAnchorIndex
< 0 || index
== 0) {
1447 // Calculate the index of the first column inside the row of the current index
1448 int firstColumnIndex
= index
;
1449 while (keyboardAnchorPos(firstColumnIndex
- 1) < keyboardAnchorPos(firstColumnIndex
)) {
1451 if (firstColumnIndex
<= 0) {
1456 // Based on the first column index go to the previous row and calculate the nearest index
1457 // that is above the current index
1458 int previousRowIndex
= firstColumnIndex
- 1;
1459 int searchIndex
= previousRowIndex
;
1460 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(previousRowIndex
));
1461 while (searchIndex
> 0 && keyboardAnchorPos(searchIndex
- 1) < keyboardAnchorPos(searchIndex
)) {
1463 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1464 if (searchDiff
< minDiff
) {
1465 minDiff
= searchDiff
;
1466 previousRowIndex
= searchIndex
;
1470 return previousRowIndex
;
1473 qreal
KItemListController::keyboardAnchorPos(int index
) const
1475 const QRectF itemRect
= m_view
->itemRect(index
);
1476 if (!itemRect
.isEmpty()) {
1477 return (m_view
->scrollOrientation() == Qt::Vertical
) ? itemRect
.x() : itemRect
.y();
1483 void KItemListController::updateExtendedSelectionRegion()
1486 const bool extend
= (m_selectionBehavior
!= MultiSelection
);
1487 KItemListStyleOption option
= m_view
->styleOption();
1488 if (option
.extendedSelectionRegion
!= extend
) {
1489 option
.extendedSelectionRegion
= extend
;
1490 m_view
->setStyleOption(option
);
1495 bool KItemListController::onPress(const QPoint
&screenPos
, const QPointF
&pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
)
1497 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), buttons
);
1499 if (buttons
& (Qt::BackButton
| Qt::ForwardButton
)) {
1500 // Do not select items when clicking the back/forward buttons, see
1501 // https://bugs.kde.org/show_bug.cgi?id=327412.
1505 if (m_view
->isAboveExpansionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
)) {
1506 m_selectionManager
->endAnchoredSelection();
1507 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1508 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1512 m_selectionTogglePressed
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
);
1513 if (m_selectionTogglePressed
) {
1514 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1515 // The previous anchored selection has been finished already in
1516 // KItemListSelectionManager::setSelected(). We can safely change
1517 // the current item and start a new anchored selection now.
1518 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1519 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1523 const bool shiftPressed
= modifiers
& Qt::ShiftModifier
;
1524 const bool controlPressed
= (modifiers
& Qt::ControlModifier
) || m_selectionMode
; // Keeping selectionMode similar to pressing control will hopefully
1525 // simplify the overall logic and possibilities both for users and devs.
1526 const bool leftClick
= buttons
& Qt::LeftButton
;
1527 const bool rightClick
= buttons
& Qt::RightButton
;
1529 // The previous selection is cleared if either
1530 // 1. The selection mode is SingleSelection, or
1531 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1532 // a) Shift or Control are pressed.
1533 // b) The clicked item is selected already. In that case, the user might want to:
1534 // - start dragging multiple items, or
1535 // - open the context menu and perform an action for all selected items.
1536 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
1537 const bool pressedItemAlreadySelected
= m_pressedIndex
.has_value() && m_selectionManager
->isSelected(m_pressedIndex
.value());
1538 const bool clearSelection
= m_selectionBehavior
== SingleSelection
|| (!shiftOrControlPressed
&& !pressedItemAlreadySelected
);
1540 // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller.
1541 if (clearSelection
) {
1542 const int selectedItemsCount
= m_selectionManager
->selectedItems().count();
1543 m_selectionManager
->clearSelection();
1544 // clear and bail when we got an existing multi-selection
1545 if (selectedItemsCount
> 1 && m_pressedIndex
.has_value()) {
1546 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1547 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1548 if (pressedItemAlreadySelected
|| row
->iconRect().contains(mappedPos
) || row
->textRect().contains(mappedPos
)) {
1549 // we are indeed inside the text/icon rect, keep m_pressedIndex what it is
1550 // and short-circuit for single-click activation (it will then propagate to onRelease and activate the item)
1551 // or we just keep going for double-click activation
1552 if (m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) {
1553 if (!pressedItemAlreadySelected
) {
1554 // An unselected item was clicked directly while deselecting multiple other items so we select it.
1555 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1556 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1557 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1559 return true; // event handled, don't create rubber band
1562 // we're not inside the text/icon rect, as we've already cleared the selection
1563 // we can just stop here and make sure handlers down the line (i.e. onRelease) don't activate
1564 m_pressedIndex
.reset();
1565 // we don't stop event propagation and proceed to create a rubber band and let onRelease
1566 // decide (based on m_pressedIndex) whether we're in a drag (drag => new rubber band, click => don't select the item)
1570 } else if (pressedItemAlreadySelected
&& !shiftOrControlPressed
&& leftClick
) {
1571 // The user might want to start dragging multiple items, but if he clicks the item
1572 // in order to trigger it instead, the other selected items must be deselected.
1573 // However, we do not know yet what the user is going to do.
1574 // -> remember that the user pressed an item which had been selected already and
1575 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1576 m_clearSelectionIfItemsAreNotDragged
= true;
1578 if (m_selectionManager
->selectedItems().count() == 1 && m_view
->isAboveText(m_pressedIndex
.value_or(-1), m_pressedMousePos
)) {
1579 Q_EMIT
selectedItemTextPressed(m_pressedIndex
.value_or(-1));
1583 if (!shiftPressed
) {
1584 // Finish the anchored selection before the current index is changed
1585 m_selectionManager
->endAnchoredSelection();
1589 // Do header hit check and short circuit before commencing any state changing effects
1590 if (m_view
->headerBoundaries().contains(pos
)) {
1591 Q_EMIT
headerContextMenuRequested(screenPos
);
1595 // Stop rubber band from persisting after right-clicks
1596 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1597 if (rubberBand
->isActive()) {
1598 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1599 rubberBand
->setActive(false);
1600 m_view
->setAutoScroll(false);
1604 if (m_pressedIndex
.has_value()) {
1605 // The hover highlight area of an item is being pressed.
1606 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1607 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
1608 const bool hitTargetIsRowEmptyRegion
= !row
->contains(row
->mapFromItem(m_view
, pos
));
1609 // again, when this method returns false, a rubberBand selection is created as the event is not consumed;
1610 // createRubberBand here tells us whether to return true or false.
1611 bool createRubberBand
= (hitTargetIsRowEmptyRegion
&& m_selectionManager
->selectedItems().isEmpty());
1613 if (rightClick
&& hitTargetIsRowEmptyRegion
) {
1614 // We have a right click outside the icon and text rect but within the hover highlight area
1615 // but it is unclear if this means that a selection rectangle for an item was clicked or the background of the view.
1616 if (m_selectionManager
->selectedItems().contains(m_pressedIndex
.value())) {
1617 // The selection rectangle for an item was clicked
1618 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), screenPos
);
1620 row
->setHovered(false); // Removes the hover highlight so the context menu doesn't look like it applies to the row.
1621 Q_EMIT
viewContextMenuRequested(screenPos
);
1626 switch (m_selectionBehavior
) {
1630 case SingleSelection
:
1631 m_selectionManager
->setSelected(m_pressedIndex
.value());
1634 case MultiSelection
:
1635 if (controlPressed
&& !shiftPressed
&& leftClick
) {
1636 // A left mouse button press is happening on an item while control is pressed. This either means a user wants to:
1637 // - toggle the selection of item(s) or
1638 // - they want to begin a drag on the item(s) to copy them.
1639 // We rule out the latter, if the item is not clicked directly and was unselected previously.
1640 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1641 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1642 if (!row
->iconRect().contains(mappedPos
) && !row
->textRect().contains(mappedPos
) && !pressedItemAlreadySelected
) {
1643 createRubberBand
= true;
1645 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1646 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1647 createRubberBand
= false; // multi selection, don't propagate any further
1648 // This will be the start of an item drag-to-copy operation if the user now moves the mouse before releasing the mouse button.
1650 } else if (!shiftPressed
|| !m_selectionManager
->isAnchoredSelectionActive()) {
1651 // Select the pressed item and start a new anchored selection
1652 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1653 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1663 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), screenPos
);
1665 return !createRubberBand
;
1669 // header right click handling would have been done before this so just normal context
1670 // menu here is fine
1671 Q_EMIT
viewContextMenuRequested(screenPos
);
1678 bool KItemListController::onRelease(const QPointF
&pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
, bool touch
)
1680 const bool isAboveSelectionToggle
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
);
1681 if (isAboveSelectionToggle
) {
1682 m_selectionTogglePressed
= false;
1686 if (!isAboveSelectionToggle
&& m_selectionTogglePressed
) {
1687 m_selectionManager
->setSelected(m_pressedIndex
.value_or(-1), 1, KItemListSelectionManager::Toggle
);
1688 m_selectionTogglePressed
= false;
1692 const bool controlPressed
= modifiers
& Qt::ControlModifier
;
1693 const bool shiftOrControlPressed
= modifiers
& Qt::ShiftModifier
|| controlPressed
;
1695 const std::optional
<int> index
= m_view
->itemAt(pos
);
1697 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1698 bool rubberBandRelease
= false;
1699 if (rubberBand
->isActive()) {
1700 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1701 rubberBand
->setActive(false);
1702 m_oldSelection
.clear();
1703 m_view
->setAutoScroll(false);
1704 rubberBandRelease
= true;
1705 // We check for actual rubber band drag here: if delta between start and end is less than drag threshold,
1706 // then we have a single click on one of the rows
1707 if ((rubberBand
->endPosition() - rubberBand
->startPosition()).manhattanLength() < QApplication::startDragDistance()) {
1708 rubberBandRelease
= false; // since we're only selecting, unmark rubber band release flag
1709 // m_pressedIndex will have no value if we came from a multi-selection clearing onPress
1710 // in that case, we don't select anything
1711 if (index
.has_value() && m_pressedIndex
.has_value()) {
1712 if (controlPressed
&& m_selectionBehavior
== MultiSelection
) {
1713 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1715 m_selectionManager
->setSelected(index
.value());
1717 if (!m_selectionManager
->isAnchoredSelectionActive()) {
1718 m_selectionManager
->beginAnchoredSelection(index
.value());
1724 if (index
.has_value() && index
== m_pressedIndex
) {
1725 // The release event is done above the same item as the press event
1727 if (m_clearSelectionIfItemsAreNotDragged
) {
1728 // A selected item has been clicked, but no drag operation has been started
1729 // -> clear the rest of the selection.
1730 m_selectionManager
->clearSelection();
1731 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1732 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1735 if (buttons
& Qt::LeftButton
) {
1736 bool emitItemActivated
= true;
1737 if (m_view
->isAboveExpansionToggle(index
.value(), pos
)) {
1738 const bool expanded
= m_model
->isExpanded(index
.value());
1739 m_model
->setExpanded(index
.value(), !expanded
);
1741 Q_EMIT
itemExpansionToggleClicked(index
.value());
1742 emitItemActivated
= false;
1743 } else if (shiftOrControlPressed
&& m_selectionBehavior
!= SingleSelection
) {
1744 // The mouse click should only update the selection, not trigger the item, except when
1745 // we are in single selection mode
1746 emitItemActivated
= false;
1748 const bool singleClickActivation
= m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
;
1749 if (!singleClickActivation
) {
1750 emitItemActivated
= touch
&& !m_selectionMode
;
1752 // activate on single click only if we didn't come from a rubber band release
1753 emitItemActivated
= !rubberBandRelease
;
1756 if (emitItemActivated
) {
1757 Q_EMIT
itemActivated(index
.value());
1759 } else if (buttons
& Qt::MiddleButton
) {
1760 Q_EMIT
itemMiddleClicked(index
.value());
1764 m_pressedMousePos
= QPointF();
1765 m_pressedIndex
= std::nullopt
;
1766 m_clearSelectionIfItemsAreNotDragged
= false;
1770 void KItemListController::startRubberBand()
1772 if (m_selectionBehavior
== MultiSelection
) {
1773 QPointF startPos
= m_pressedMousePos
;
1774 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1775 startPos
.ry() += m_view
->scrollOffset();
1776 if (m_view
->itemSize().width() < 0) {
1777 // Use a special rubberband for views that have only one column and
1778 // expand the rubberband to use the whole width of the view.
1782 startPos
.rx() += m_view
->scrollOffset();
1785 m_oldSelection
= m_selectionManager
->selectedItems();
1786 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1787 rubberBand
->setStartPosition(startPos
);
1788 rubberBand
->setEndPosition(startPos
);
1789 rubberBand
->setActive(true);
1790 connect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1791 m_view
->setAutoScroll(true);
1795 void KItemListController::slotStateChanged(QScroller::State newState
)
1797 if (newState
== QScroller::Scrolling
) {
1798 m_scrollerIsScrolling
= true;
1799 } else if (newState
== QScroller::Inactive
) {
1800 m_scrollerIsScrolling
= false;