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
,
62 this, &KItemListController::slotChangeCurrentItem
);
63 connect(m_selectionManager
, &KItemListSelectionManager::currentChanged
,
64 m_keyboardManager
, &KItemListKeyboardSearchManager::slotCurrentChanged
);
65 connect(m_selectionManager
, &KItemListSelectionManager::selectionChanged
,
66 m_keyboardManager
, &KItemListKeyboardSearchManager::slotSelectionChanged
);
68 m_autoActivationTimer
= new QTimer(this);
69 m_autoActivationTimer
->setSingleShot(true);
70 m_autoActivationTimer
->setInterval(-1);
71 connect(m_autoActivationTimer
, &QTimer::timeout
, this, &KItemListController::slotAutoActivationTimeout
);
76 m_swipeGesture
= QGestureRecognizer::registerRecognizer(new KTwoFingerSwipeRecognizer());
77 m_twoFingerTapGesture
= QGestureRecognizer::registerRecognizer(new KTwoFingerTapRecognizer());
78 view
->grabGesture(m_swipeGesture
);
79 view
->grabGesture(m_twoFingerTapGesture
);
80 view
->grabGesture(Qt::TapGesture
);
81 view
->grabGesture(Qt::TapAndHoldGesture
);
82 view
->grabGesture(Qt::PinchGesture
);
85 KItemListController::~KItemListController()
94 void KItemListController::setModel(KItemModelBase
* model
)
96 if (m_model
== model
) {
100 KItemModelBase
* oldModel
= m_model
;
102 oldModel
->deleteLater();
107 m_model
->setParent(this);
111 m_view
->setModel(m_model
);
114 m_selectionManager
->setModel(m_model
);
116 Q_EMIT
modelChanged(m_model
, oldModel
);
119 KItemModelBase
* KItemListController::model() const
124 KItemListSelectionManager
* KItemListController::selectionManager() const
126 return m_selectionManager
;
129 void KItemListController::setView(KItemListView
* view
)
131 if (m_view
== view
) {
135 KItemListView
* oldView
= m_view
;
137 disconnect(oldView
, &KItemListView::scrollOffsetChanged
, this, &KItemListController::slotViewScrollOffsetChanged
);
138 oldView
->deleteLater();
144 m_view
->setParent(this);
145 m_view
->setController(this);
146 m_view
->setModel(m_model
);
147 connect(m_view
, &KItemListView::scrollOffsetChanged
, this, &KItemListController::slotViewScrollOffsetChanged
);
148 updateExtendedSelectionRegion();
151 Q_EMIT
viewChanged(m_view
, oldView
);
154 KItemListView
* KItemListController::view() const
159 void KItemListController::setSelectionBehavior(SelectionBehavior behavior
)
161 m_selectionBehavior
= behavior
;
162 updateExtendedSelectionRegion();
165 KItemListController::SelectionBehavior
KItemListController::selectionBehavior() const
167 return m_selectionBehavior
;
170 void KItemListController::setAutoActivationBehavior(AutoActivationBehavior behavior
)
172 m_autoActivationBehavior
= behavior
;
175 KItemListController::AutoActivationBehavior
KItemListController::autoActivationBehavior() const
177 return m_autoActivationBehavior
;
180 void KItemListController::setMouseDoubleClickAction(MouseDoubleClickAction action
)
182 m_mouseDoubleClickAction
= action
;
185 KItemListController::MouseDoubleClickAction
KItemListController::mouseDoubleClickAction() const
187 return m_mouseDoubleClickAction
;
190 int KItemListController::indexCloseToMousePressedPosition() const
192 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_view
->m_visibleGroups
);
193 while (it
.hasNext()) {
195 KItemListGroupHeader
*groupHeader
= it
.value();
196 const QPointF mappedToGroup
= groupHeader
->mapFromItem(nullptr, m_pressedMousePos
);
197 if (groupHeader
->contains(mappedToGroup
)) {
198 return it
.key()->index();
204 void KItemListController::setAutoActivationDelay(int delay
)
206 m_autoActivationTimer
->setInterval(delay
);
209 int KItemListController::autoActivationDelay() const
211 return m_autoActivationTimer
->interval();
214 void KItemListController::setSingleClickActivationEnforced(bool singleClick
)
216 m_singleClickActivationEnforced
= singleClick
;
219 bool KItemListController::singleClickActivationEnforced() const
221 return m_singleClickActivationEnforced
;
224 void KItemListController::setSelectionModeEnabled(bool enabled
)
226 m_selectionMode
= enabled
;
229 bool KItemListController::selectionMode() const
231 return m_selectionMode
;
234 bool KItemListController::keyPressEvent(QKeyEvent
* event
)
236 int index
= m_selectionManager
->currentItem();
237 int key
= event
->key();
239 // Handle the expanding/collapsing of items
240 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
)) {
241 if (key
== Qt::Key_Right
) {
242 if (m_model
->setExpanded(index
, true)) {
245 } else if (key
== Qt::Key_Left
) {
246 if (m_model
->setExpanded(index
, false)) {
252 const bool shiftPressed
= event
->modifiers() & Qt::ShiftModifier
;
253 const bool controlPressed
= event
->modifiers() & Qt::ControlModifier
;
254 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
255 const bool navigationPressed
= key
== Qt::Key_Home
|| key
== Qt::Key_End
||
256 key
== Qt::Key_PageUp
|| key
== Qt::Key_PageDown
||
257 key
== Qt::Key_Up
|| key
== Qt::Key_Down
||
258 key
== Qt::Key_Left
|| key
== Qt::Key_Right
;
260 const int itemCount
= m_model
->count();
262 // For horizontal scroll orientation, transform
263 // the arrow keys to simplify the event handling.
264 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
266 case Qt::Key_Up
: key
= Qt::Key_Left
; break;
267 case Qt::Key_Down
: key
= Qt::Key_Right
; break;
268 case Qt::Key_Left
: key
= Qt::Key_Up
; break;
269 case Qt::Key_Right
: key
= Qt::Key_Down
; break;
274 const bool selectSingleItem
= m_selectionBehavior
!= NoSelection
&& itemCount
== 1 && navigationPressed
;
276 if (selectSingleItem
) {
277 const int current
= m_selectionManager
->currentItem();
278 m_selectionManager
->setSelected(current
);
285 m_keyboardAnchorIndex
= index
;
286 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
290 index
= itemCount
- 1;
291 m_keyboardAnchorIndex
= index
;
292 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
297 const int expandedParentsCount
= m_model
->expandedParentsCount(index
);
298 if (expandedParentsCount
== 0) {
301 // Go to the parent of the current item.
304 } while (index
> 0 && m_model
->expandedParentsCount(index
) == expandedParentsCount
);
306 m_keyboardAnchorIndex
= index
;
307 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
312 if (index
< itemCount
- 1) {
314 m_keyboardAnchorIndex
= index
;
315 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
320 updateKeyboardAnchor();
321 index
= previousRowIndex(index
);
325 updateKeyboardAnchor();
326 index
= nextRowIndex(index
);
330 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
331 // The new current index should correspond to the first item in the current column.
332 int newIndex
= qMax(index
- 1, 0);
333 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() < m_view
->itemRect(index
).topLeft().y()) {
335 newIndex
= qMax(index
- 1, 0);
337 m_keyboardAnchorIndex
= index
;
338 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
340 const qreal currentItemBottom
= m_view
->itemRect(index
).bottomLeft().y();
341 const qreal height
= m_view
->geometry().height();
343 // The new current item should be the first item in the current
344 // column whose itemRect's top coordinate is larger than targetY.
345 const qreal targetY
= currentItemBottom
- height
;
347 updateKeyboardAnchor();
348 int newIndex
= previousRowIndex(index
);
351 updateKeyboardAnchor();
352 newIndex
= previousRowIndex(index
);
353 } while (m_view
->itemRect(newIndex
).topLeft().y() > targetY
&& newIndex
!= index
);
357 case Qt::Key_PageDown
:
358 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
359 // The new current index should correspond to the last item in the current column.
360 int newIndex
= qMin(index
+ 1, m_model
->count() - 1);
361 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() > m_view
->itemRect(index
).topLeft().y()) {
363 newIndex
= qMin(index
+ 1, m_model
->count() - 1);
365 m_keyboardAnchorIndex
= index
;
366 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
368 const qreal currentItemTop
= m_view
->itemRect(index
).topLeft().y();
369 const qreal height
= m_view
->geometry().height();
371 // The new current item should be the last item in the current
372 // column whose itemRect's bottom coordinate is smaller than targetY.
373 const qreal targetY
= currentItemTop
+ height
;
375 updateKeyboardAnchor();
376 int newIndex
= nextRowIndex(index
);
379 updateKeyboardAnchor();
380 newIndex
= nextRowIndex(index
);
381 } while (m_view
->itemRect(newIndex
).bottomLeft().y() < targetY
&& newIndex
!= index
);
386 case Qt::Key_Return
: {
387 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
388 if (selectedItems
.count() >= 2) {
389 Q_EMIT
itemsActivated(selectedItems
);
390 } else if (selectedItems
.count() == 1) {
391 Q_EMIT
itemActivated(selectedItems
.first());
393 Q_EMIT
itemActivated(index
);
399 // Emit the signal itemContextMenuRequested() in case if at least one
400 // item is selected. Otherwise the signal viewContextMenuRequested() will be emitted.
401 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
403 if (selectedItems
.count() >= 2) {
404 const int currentItemIndex
= m_selectionManager
->currentItem();
405 index
= selectedItems
.contains(currentItemIndex
)
406 ? currentItemIndex
: selectedItems
.first();
407 } else if (selectedItems
.count() == 1) {
408 index
= selectedItems
.first();
412 const QRectF contextRect
= m_view
->itemContextRect(index
);
413 const QPointF
pos(m_view
->scene()->views().first()->mapToGlobal(contextRect
.bottomRight().toPoint()));
414 Q_EMIT
itemContextMenuRequested(index
, pos
);
416 Q_EMIT
viewContextMenuRequested(QCursor::pos());
422 if (m_selectionMode
) {
423 Q_EMIT
selectionModeChangeRequested(false);
424 } else if (m_selectionBehavior
!= SingleSelection
) {
425 m_selectionManager
->clearSelection();
427 m_keyboardManager
->cancelSearch();
428 Q_EMIT
escapePressed();
432 if (m_selectionBehavior
== MultiSelection
) {
433 if (controlPressed
) {
434 // Toggle the selection state of the current item.
435 m_selectionManager
->endAnchoredSelection();
436 m_selectionManager
->setSelected(index
, 1, KItemListSelectionManager::Toggle
);
437 m_selectionManager
->beginAnchoredSelection(index
);
440 // Select the current item if it is not selected yet.
441 const int current
= m_selectionManager
->currentItem();
442 if (!m_selectionManager
->isSelected(current
)) {
443 m_selectionManager
->setSelected(current
);
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
) &&
697 index
.has_value() && index
.value() < m_model
->count();
698 if (emitItemActivated
) {
699 Q_EMIT
itemActivated(index
.value());
704 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
709 DragAndDropHelper::clearUrlListMatchesUrlCache();
714 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
719 m_autoActivationTimer
->stop();
720 m_view
->setAutoScroll(false);
721 m_view
->hideDropIndicator();
723 KItemListWidget
* widget
= hoveredWidget();
725 widget
->setHovered(false);
726 Q_EMIT
itemUnhovered(widget
->index());
731 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
733 if (!m_model
|| !m_view
) {
738 QUrl hoveredDir
= m_model
->directory();
739 KItemListWidget
* oldHoveredWidget
= hoveredWidget();
741 const QPointF pos
= transform
.map(event
->pos());
742 KItemListWidget
* newHoveredWidget
= widgetForDropPos(pos
);
744 if (oldHoveredWidget
!= newHoveredWidget
) {
745 m_autoActivationTimer
->stop();
747 if (oldHoveredWidget
) {
748 oldHoveredWidget
->setHovered(false);
749 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
753 if (newHoveredWidget
) {
754 bool droppingBetweenItems
= false;
755 if (m_model
->sortRole().isEmpty()) {
756 // The model supports inserting items between other items.
757 droppingBetweenItems
= (m_view
->showDropIndicator(pos
) >= 0);
760 const int index
= newHoveredWidget
->index();
762 if (m_model
->isDir(index
)) {
763 hoveredDir
= m_model
->url(index
);
766 if (!droppingBetweenItems
) {
767 if (m_model
->supportsDropping(index
)) {
768 // Something has been dragged on an item.
769 m_view
->hideDropIndicator();
770 if (!newHoveredWidget
->isHovered()) {
771 newHoveredWidget
->setHovered(true);
772 Q_EMIT
itemHovered(index
);
775 if (!m_autoActivationTimer
->isActive() && m_autoActivationTimer
->interval() >= 0) {
776 m_autoActivationTimer
->setProperty("index", index
);
777 m_autoActivationTimer
->start();
781 m_autoActivationTimer
->stop();
782 if (newHoveredWidget
&& newHoveredWidget
->isHovered()) {
783 newHoveredWidget
->setHovered(false);
784 Q_EMIT
itemUnhovered(index
);
788 m_view
->hideDropIndicator();
791 if (DragAndDropHelper::urlListMatchesUrl(event
->mimeData()->urls(), hoveredDir
)) {
792 event
->setDropAction(Qt::IgnoreAction
);
795 event
->setDropAction(event
->proposedAction());
801 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
807 m_autoActivationTimer
->stop();
808 m_view
->setAutoScroll(false);
810 const QPointF pos
= transform
.map(event
->pos());
812 int dropAboveIndex
= -1;
813 if (m_model
->sortRole().isEmpty()) {
814 // The model supports inserting of items between other items.
815 dropAboveIndex
= m_view
->showDropIndicator(pos
);
818 if (dropAboveIndex
>= 0) {
819 // Something has been dropped between two items.
820 m_view
->hideDropIndicator();
821 Q_EMIT
aboveItemDropEvent(dropAboveIndex
, event
);
822 } else if (!event
->mimeData()->hasFormat(m_model
->blacklistItemDropEventMimeType())) {
823 // Something has been dropped on an item or on an empty part of the view.
824 const KItemListWidget
*receivingWidget
= widgetForDropPos(pos
);
825 if (receivingWidget
) {
826 Q_EMIT
itemDropEvent(receivingWidget
->index(), event
);
828 Q_EMIT
itemDropEvent(-1, event
);
832 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropEnd
);
833 QAccessible::updateAccessibility(&accessibilityEvent
);
838 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent
* event
, const QTransform
& transform
)
845 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent
* event
, const QTransform
& transform
)
848 if (!m_model
|| !m_view
) {
852 // We identify the widget whose expansionArea had been hovered before this hoverMoveEvent() triggered.
853 // we can't use hoveredWidget() here (it handles the icon+text rect, not the expansion rect)
854 // like hoveredWidget(), we find the hovered widget for the expansion rect
855 const auto visibleItemListWidgets
= m_view
->visibleItemListWidgets();
856 const auto oldHoveredExpansionWidgetIterator
= std::find_if(visibleItemListWidgets
.begin(), visibleItemListWidgets
.end(), [](auto &widget
) {
857 return widget
->expansionAreaHovered();
859 const auto oldHoveredExpansionWidget
= oldHoveredExpansionWidgetIterator
== visibleItemListWidgets
.end() ?
860 std::nullopt
: std::make_optional(*oldHoveredExpansionWidgetIterator
);
862 const auto unhoverOldHoveredWidget
= [&]() {
863 if (auto oldHoveredWidget
= hoveredWidget(); oldHoveredWidget
) {
864 // handle the text+icon one
865 oldHoveredWidget
->setHovered(false);
866 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
870 const auto unhoverOldExpansionWidget
= [&]() {
871 if (oldHoveredExpansionWidget
) {
872 // then the expansion toggle
873 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
877 const QPointF pos
= transform
.map(event
->pos());
878 if (KItemListWidget
*newHoveredWidget
= widgetForPos(pos
); newHoveredWidget
) {
879 // something got hovered, work out which part and set hover for the appropriate widget
880 const auto mappedPos
= newHoveredWidget
->mapFromItem(m_view
, pos
);
881 const bool isOnExpansionToggle
= newHoveredWidget
->expansionToggleRect().contains(mappedPos
);
883 if (isOnExpansionToggle
) {
884 // make sure we unhover the old one first if old!=new
885 if (oldHoveredExpansionWidget
&& *oldHoveredExpansionWidget
!= newHoveredWidget
) {
886 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
888 // 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)
889 unhoverOldHoveredWidget();
892 newHoveredWidget
->setExpansionAreaHovered(true);
894 // make sure we unhover the old one first if old!=new
895 auto oldHoveredWidget
= hoveredWidget();
896 if (oldHoveredWidget
&& oldHoveredWidget
!= newHoveredWidget
) {
897 oldHoveredWidget
->setHovered(false);
898 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
900 // 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)
901 unhoverOldExpansionWidget();
903 const bool isOverIconAndText
= newHoveredWidget
->iconRect().contains(mappedPos
) || newHoveredWidget
->textRect().contains(mappedPos
);
904 const bool hasMultipleSelection
= m_selectionManager
->selectedItems().count() > 1;
906 if (hasMultipleSelection
&& !isOverIconAndText
) {
907 // In case we have multiple selections, clicking on any row will deselect the selection.
908 // So, as a visual cue for signalling that clicking anywhere won't select, but clear current highlights,
909 // we disable hover of the *row*(i.e. blank space to the right of the icon+text)
911 // (no-op in this branch for masked hover)
913 newHoveredWidget
->setHoverPosition(mappedPos
);
914 if (oldHoveredWidget
!= newHoveredWidget
) {
915 newHoveredWidget
->setHovered(true);
916 Q_EMIT
itemHovered(newHoveredWidget
->index());
921 // unhover any currently hovered expansion and text+icon widgets
922 unhoverOldHoveredWidget();
923 unhoverOldExpansionWidget();
928 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent
* event
, const QTransform
& transform
)
933 m_mousePress
= false;
934 m_isTouchEvent
= false;
936 if (!m_model
|| !m_view
) {
940 const auto widgets
= m_view
->visibleItemListWidgets();
941 for (KItemListWidget
* widget
: widgets
) {
942 if (widget
->isHovered()) {
943 widget
->setHovered(false);
944 Q_EMIT
itemUnhovered(widget
->index());
950 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent
* event
, const QTransform
& transform
)
957 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent
* event
, const QTransform
& transform
)
964 bool KItemListController::gestureEvent(QGestureEvent
* event
, const QTransform
& transform
)
970 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
971 //we use this to get the right QWidget
972 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
974 if (QGesture
* tap
= event
->gesture(Qt::TapGesture
)) {
975 QTapGesture
* tapGesture
= static_cast<QTapGesture
*>(tap
);
976 if (tapGesture
->state() == Qt::GestureStarted
) {
977 tapTriggered(tapGesture
, transform
);
983 bool accepted
= false;
985 if (QGesture
* tap
= event
->gesture(Qt::TapGesture
)) {
986 tapTriggered(static_cast<QTapGesture
*>(tap
), transform
);
989 if (event
->gesture(Qt::TapAndHoldGesture
)) {
990 tapAndHoldTriggered(event
, transform
);
993 if (event
->gesture(Qt::PinchGesture
)) {
994 pinchTriggered(event
, transform
);
997 if (event
->gesture(m_swipeGesture
)) {
998 swipeTriggered(event
, transform
);
1001 if (event
->gesture(m_twoFingerTapGesture
)) {
1002 twoFingerTapTriggered(event
, transform
);
1008 bool KItemListController::touchBeginEvent(QTouchEvent
* event
, const QTransform
& transform
)
1013 m_isTouchEvent
= true;
1017 void KItemListController::tapTriggered(QTapGesture
* tap
, const QTransform
& transform
)
1019 static bool scrollerWasActive
= false;
1021 if (tap
->state() == Qt::GestureStarted
) {
1022 m_dragActionOrRightClick
= false;
1023 m_isSwipeGesture
= false;
1024 m_pinchGestureInProgress
= false;
1025 scrollerWasActive
= m_scrollerIsScrolling
;
1028 if (tap
->state() == Qt::GestureFinished
) {
1029 m_mousePress
= false;
1031 //if at the moment of the gesture start the QScroller was active, the user made the tap
1032 //to stop the QScroller and not to tap on an item
1033 if (scrollerWasActive
) {
1037 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
1038 m_view
->m_tapAndHoldIndicator
->setActive(false);
1041 m_pressedMousePos
= transform
.map(tap
->position());
1042 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1044 if (m_dragActionOrRightClick
) {
1045 m_dragActionOrRightClick
= false;
1048 onPress(tap
->hotSpot().toPoint(), tap
->position().toPoint(), Qt::NoModifier
, Qt::LeftButton
);
1049 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::LeftButton
, true);
1051 m_isTouchEvent
= false;
1055 void KItemListController::tapAndHoldTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1058 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
1059 if (!m_isTouchEvent
) {
1063 const QTapAndHoldGesture
* tap
= static_cast<QTapAndHoldGesture
*>(event
->gesture(Qt::TapAndHoldGesture
));
1064 if (tap
->state() == Qt::GestureFinished
) {
1065 //if a pinch gesture is in progress we don't want a TabAndHold gesture
1066 if (m_pinchGestureInProgress
) {
1069 m_pressedMousePos
= transform
.map(event
->mapToGraphicsScene(tap
->position()));
1070 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1072 if (m_pressedIndex
.has_value() && !m_selectionManager
->isSelected(m_pressedIndex
.value())) {
1073 m_selectionManager
->clearSelection();
1074 m_selectionManager
->setSelected(m_pressedIndex
.value());
1075 if (!m_selectionMode
) {
1076 Q_EMIT
selectionModeChangeRequested(true);
1078 } else if (!m_pressedIndex
.has_value()) {
1079 m_selectionManager
->clearSelection();
1083 Q_EMIT
scrollerStop();
1085 m_view
->m_tapAndHoldIndicator
->setStartPosition(m_pressedMousePos
);
1086 m_view
->m_tapAndHoldIndicator
->setActive(true);
1088 m_dragActionOrRightClick
= true;
1092 void KItemListController::pinchTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1096 const QPinchGesture
* pinch
= static_cast<QPinchGesture
*>(event
->gesture(Qt::PinchGesture
));
1097 const qreal sensitivityModifier
= 0.2;
1098 static qreal counter
= 0;
1100 if (pinch
->state() == Qt::GestureStarted
) {
1101 m_pinchGestureInProgress
= true;
1104 if (pinch
->state() == Qt::GestureUpdated
) {
1105 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1106 if (m_isSwipeGesture
) {
1109 counter
= counter
+ (pinch
->scaleFactor() - 1);
1110 if (counter
>= sensitivityModifier
) {
1111 Q_EMIT
increaseZoom();
1113 } else if (counter
<= -sensitivityModifier
) {
1114 Q_EMIT
decreaseZoom();
1120 void KItemListController::swipeTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1124 const KTwoFingerSwipe
* swipe
= static_cast<KTwoFingerSwipe
*>(event
->gesture(m_swipeGesture
));
1129 if (swipe
->state() == Qt::GestureStarted
) {
1130 m_isSwipeGesture
= true;
1133 if (swipe
->state() == Qt::GestureCanceled
) {
1134 m_isSwipeGesture
= false;
1137 if (swipe
->state() == Qt::GestureFinished
) {
1138 Q_EMIT
scrollerStop();
1140 if (swipe
->swipeAngle() <= 20 || swipe
->swipeAngle() >= 340) {
1141 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::BackButton
);
1142 } else if (swipe
->swipeAngle() <= 200 && swipe
->swipeAngle() >= 160) {
1143 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::ForwardButton
);
1144 } else if (swipe
->swipeAngle() <= 110 && swipe
->swipeAngle() >= 60) {
1147 m_isSwipeGesture
= true;
1151 void KItemListController::twoFingerTapTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1153 const KTwoFingerTap
* twoTap
= static_cast<KTwoFingerTap
*>(event
->gesture(m_twoFingerTapGesture
));
1159 if (twoTap
->state() == Qt::GestureStarted
) {
1160 m_pressedMousePos
= transform
.map(twoTap
->pos());
1161 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1162 if (m_pressedIndex
.has_value()) {
1163 onPress(twoTap
->screenPos().toPoint(), twoTap
->pos().toPoint(), Qt::ControlModifier
, Qt::LeftButton
);
1164 onRelease(transform
.map(twoTap
->pos()), Qt::ControlModifier
, Qt::LeftButton
, false);
1170 bool KItemListController::processEvent(QEvent
* event
, const QTransform
& transform
)
1176 switch (event
->type()) {
1177 case QEvent::KeyPress
:
1178 return keyPressEvent(static_cast<QKeyEvent
*>(event
));
1179 case QEvent::InputMethod
:
1180 return inputMethodEvent(static_cast<QInputMethodEvent
*>(event
));
1181 case QEvent::GraphicsSceneMousePress
:
1182 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1183 case QEvent::GraphicsSceneMouseMove
:
1184 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1185 case QEvent::GraphicsSceneMouseRelease
:
1186 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1187 case QEvent::GraphicsSceneMouseDoubleClick
:
1188 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1189 case QEvent::GraphicsSceneWheel
:
1190 return wheelEvent(static_cast<QGraphicsSceneWheelEvent
*>(event
), QTransform());
1191 case QEvent::GraphicsSceneDragEnter
:
1192 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1193 case QEvent::GraphicsSceneDragLeave
:
1194 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1195 case QEvent::GraphicsSceneDragMove
:
1196 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1197 case QEvent::GraphicsSceneDrop
:
1198 return dropEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1199 case QEvent::GraphicsSceneHoverEnter
:
1200 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1201 case QEvent::GraphicsSceneHoverMove
:
1202 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1203 case QEvent::GraphicsSceneHoverLeave
:
1204 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1205 case QEvent::GraphicsSceneResize
:
1206 return resizeEvent(static_cast<QGraphicsSceneResizeEvent
*>(event
), transform
);
1207 case QEvent::Gesture
:
1208 return gestureEvent(static_cast<QGestureEvent
*>(event
), transform
);
1209 case QEvent::TouchBegin
:
1210 return touchBeginEvent(static_cast<QTouchEvent
*>(event
), transform
);
1218 void KItemListController::slotViewScrollOffsetChanged(qreal current
, qreal previous
)
1224 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1225 if (rubberBand
->isActive()) {
1226 const qreal diff
= current
- previous
;
1227 // TODO: Ideally just QCursor::pos() should be used as
1228 // new end-position but it seems there is no easy way
1229 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1230 // (... or I just missed an easy way to do the mapping)
1231 QPointF endPos
= rubberBand
->endPosition();
1232 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1233 endPos
.ry() += diff
;
1235 endPos
.rx() += diff
;
1238 rubberBand
->setEndPosition(endPos
);
1242 void KItemListController::slotRubberBandChanged()
1244 if (!m_view
|| !m_model
|| m_model
->count() <= 0) {
1248 const KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1249 const QPointF startPos
= rubberBand
->startPosition();
1250 const QPointF endPos
= rubberBand
->endPosition();
1251 QRectF rubberBandRect
= QRectF(startPos
, endPos
).normalized();
1253 const bool scrollVertical
= (m_view
->scrollOrientation() == Qt::Vertical
);
1254 if (scrollVertical
) {
1255 rubberBandRect
.translate(0, -m_view
->scrollOffset());
1257 rubberBandRect
.translate(-m_view
->scrollOffset(), 0);
1260 if (!m_oldSelection
.isEmpty()) {
1261 // Clear the old selection that was available before the rubberband has
1262 // been activated in case if no Shift- or Control-key are pressed
1263 const bool shiftOrControlPressed
= QApplication::keyboardModifiers() & Qt::ShiftModifier
||
1264 QApplication::keyboardModifiers() & Qt::ControlModifier
;
1265 if (!shiftOrControlPressed
&& !m_selectionMode
) {
1266 m_oldSelection
.clear();
1270 KItemSet selectedItems
;
1272 // Select all visible items that intersect with the rubberband
1273 const auto widgets
= m_view
->visibleItemListWidgets();
1274 for (const KItemListWidget
* widget
: widgets
) {
1275 const int index
= widget
->index();
1277 const QRectF widgetRect
= m_view
->itemRect(index
);
1278 if (widgetRect
.intersects(rubberBandRect
)) {
1279 const QRectF iconRect
= widget
->iconRect().translated(widgetRect
.topLeft());
1280 const QRectF textRect
= widget
->textRect().translated(widgetRect
.topLeft());
1281 if (iconRect
.intersects(rubberBandRect
) || textRect
.intersects(rubberBandRect
)) {
1282 selectedItems
.insert(index
);
1287 // Select all invisible items that intersect with the rubberband. Instead of
1288 // iterating all items only the area which might be touched by the rubberband
1290 const bool increaseIndex
= scrollVertical
?
1291 startPos
.y() > endPos
.y(): startPos
.x() > endPos
.x();
1293 int index
= increaseIndex
? m_view
->lastVisibleIndex() + 1 : m_view
->firstVisibleIndex() - 1;
1294 bool selectionFinished
= false;
1296 const QRectF widgetRect
= m_view
->itemRect(index
);
1297 if (widgetRect
.intersects(rubberBandRect
)) {
1298 selectedItems
.insert(index
);
1301 if (increaseIndex
) {
1303 selectionFinished
= (index
>= m_model
->count()) ||
1304 ( scrollVertical
&& widgetRect
.top() > rubberBandRect
.bottom()) ||
1305 (!scrollVertical
&& widgetRect
.left() > rubberBandRect
.right());
1308 selectionFinished
= (index
< 0) ||
1309 ( scrollVertical
&& widgetRect
.bottom() < rubberBandRect
.top()) ||
1310 (!scrollVertical
&& widgetRect
.right() < rubberBandRect
.left());
1312 } while (!selectionFinished
);
1314 if ((QApplication::keyboardModifiers() & Qt::ControlModifier
) || m_selectionMode
) {
1315 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1316 // Therefore, the new selection contains:
1317 // 1. All previously selected items which are not inside the rubberband, and
1318 // 2. all items inside the rubberband which have not been selected previously.
1319 m_selectionManager
->setSelectedItems(m_oldSelection
^ selectedItems
);
1322 m_selectionManager
->setSelectedItems(selectedItems
+ m_oldSelection
);
1326 void KItemListController::startDragging()
1328 if (!m_view
|| !m_model
) {
1332 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
1333 if (selectedItems
.isEmpty()) {
1337 QMimeData
*data
= m_model
->createMimeData(selectedItems
);
1341 KUrlMimeData::exportUrlsToPortal(data
);
1343 // The created drag object will be owned and deleted
1344 // by QApplication::activeWindow().
1345 QDrag
* drag
= new QDrag(QApplication::activeWindow());
1346 drag
->setMimeData(data
);
1348 const QPixmap pixmap
= m_view
->createDragPixmap(selectedItems
);
1349 drag
->setPixmap(pixmap
);
1351 const QPoint
hotSpot((pixmap
.width() / pixmap
.devicePixelRatio()) / 2, 0);
1352 drag
->setHotSpot(hotSpot
);
1354 drag
->exec(Qt::MoveAction
| Qt::CopyAction
| Qt::LinkAction
, Qt::CopyAction
);
1356 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropStart
);
1357 QAccessible::updateAccessibility(&accessibilityEvent
);
1360 KItemListWidget
* KItemListController::hoveredWidget() const
1364 const auto widgets
= m_view
->visibleItemListWidgets();
1365 for (KItemListWidget
* widget
: widgets
) {
1366 if (widget
->isHovered()) {
1374 KItemListWidget
* KItemListController::widgetForPos(const QPointF
& pos
) const
1378 const auto widgets
= m_view
->visibleItemListWidgets();
1379 for (KItemListWidget
* widget
: widgets
) {
1380 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1381 if (widget
->contains(mappedPos
) || widget
->selectionRect().contains(mappedPos
)) {
1389 KItemListWidget
* KItemListController::widgetForDropPos(const QPointF
& pos
) const
1393 const auto widgets
= m_view
->visibleItemListWidgets();
1394 for (KItemListWidget
* widget
: widgets
) {
1395 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1396 if (widget
->contains(mappedPos
)) {
1404 void KItemListController::updateKeyboardAnchor()
1406 const bool validAnchor
= m_keyboardAnchorIndex
>= 0 &&
1407 m_keyboardAnchorIndex
< m_model
->count() &&
1408 keyboardAnchorPos(m_keyboardAnchorIndex
) == m_keyboardAnchorPos
;
1410 const int index
= m_selectionManager
->currentItem();
1411 m_keyboardAnchorIndex
= index
;
1412 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
1416 int KItemListController::nextRowIndex(int index
) const
1418 if (m_keyboardAnchorIndex
< 0) {
1422 const int maxIndex
= m_model
->count() - 1;
1423 if (index
== maxIndex
) {
1427 // Calculate the index of the last column inside the row of the current index
1428 int lastColumnIndex
= index
;
1429 while (keyboardAnchorPos(lastColumnIndex
+ 1) > keyboardAnchorPos(lastColumnIndex
)) {
1431 if (lastColumnIndex
>= maxIndex
) {
1436 // Based on the last column index go to the next row and calculate the nearest index
1437 // that is below the current index
1438 int nextRowIndex
= lastColumnIndex
+ 1;
1439 int searchIndex
= nextRowIndex
;
1440 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(nextRowIndex
));
1441 while (searchIndex
< maxIndex
&& keyboardAnchorPos(searchIndex
+ 1) > keyboardAnchorPos(searchIndex
)) {
1443 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1444 if (searchDiff
< minDiff
) {
1445 minDiff
= searchDiff
;
1446 nextRowIndex
= searchIndex
;
1450 return nextRowIndex
;
1453 int KItemListController::previousRowIndex(int index
) const
1455 if (m_keyboardAnchorIndex
< 0 || index
== 0) {
1459 // Calculate the index of the first column inside the row of the current index
1460 int firstColumnIndex
= index
;
1461 while (keyboardAnchorPos(firstColumnIndex
- 1) < keyboardAnchorPos(firstColumnIndex
)) {
1463 if (firstColumnIndex
<= 0) {
1468 // Based on the first column index go to the previous row and calculate the nearest index
1469 // that is above the current index
1470 int previousRowIndex
= firstColumnIndex
- 1;
1471 int searchIndex
= previousRowIndex
;
1472 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(previousRowIndex
));
1473 while (searchIndex
> 0 && keyboardAnchorPos(searchIndex
- 1) < keyboardAnchorPos(searchIndex
)) {
1475 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1476 if (searchDiff
< minDiff
) {
1477 minDiff
= searchDiff
;
1478 previousRowIndex
= searchIndex
;
1482 return previousRowIndex
;
1485 qreal
KItemListController::keyboardAnchorPos(int index
) const
1487 const QRectF itemRect
= m_view
->itemRect(index
);
1488 if (!itemRect
.isEmpty()) {
1489 return (m_view
->scrollOrientation() == Qt::Vertical
) ? itemRect
.x() : itemRect
.y();
1495 void KItemListController::updateExtendedSelectionRegion()
1498 const bool extend
= (m_selectionBehavior
!= MultiSelection
);
1499 KItemListStyleOption option
= m_view
->styleOption();
1500 if (option
.extendedSelectionRegion
!= extend
) {
1501 option
.extendedSelectionRegion
= extend
;
1502 m_view
->setStyleOption(option
);
1507 bool KItemListController::onPress(const QPoint
& screenPos
, const QPointF
& pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
)
1509 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), buttons
);
1511 if (buttons
& (Qt::BackButton
| Qt::ForwardButton
)) {
1512 // Do not select items when clicking the back/forward buttons, see
1513 // https://bugs.kde.org/show_bug.cgi?id=327412.
1517 if (m_view
->isAboveExpansionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
)) {
1518 m_selectionManager
->endAnchoredSelection();
1519 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1520 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1524 m_selectionTogglePressed
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
);
1525 if (m_selectionTogglePressed
) {
1526 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1527 // The previous anchored selection has been finished already in
1528 // KItemListSelectionManager::setSelected(). We can safely change
1529 // the current item and start a new anchored selection now.
1530 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1531 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1535 const bool shiftPressed
= modifiers
& Qt::ShiftModifier
;
1536 const bool controlPressed
= (modifiers
& Qt::ControlModifier
) || m_selectionMode
; // Keeping selectionMode similar to pressing control will hopefully
1537 // simplify the overall logic and possibilities both for users and devs.
1538 const bool leftClick
= buttons
& Qt::LeftButton
;
1539 const bool rightClick
= buttons
& Qt::RightButton
;
1541 // The previous selection is cleared if either
1542 // 1. The selection mode is SingleSelection, or
1543 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1544 // a) Shift or Control are pressed.
1545 // b) The clicked item is selected already. In that case, the user might want to:
1546 // - start dragging multiple items, or
1547 // - open the context menu and perform an action for all selected items.
1548 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
1549 const bool pressedItemAlreadySelected
= m_pressedIndex
.has_value() && m_selectionManager
->isSelected(m_pressedIndex
.value());
1550 const bool clearSelection
= m_selectionBehavior
== SingleSelection
||
1551 (!shiftOrControlPressed
&& !pressedItemAlreadySelected
);
1554 // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller.
1555 if (clearSelection
) {
1556 const int selectedItemsCount
= m_selectionManager
->selectedItems().count();
1557 m_selectionManager
->clearSelection();
1558 // clear and bail when we got an existing multi-selection
1559 if (selectedItemsCount
> 1 && m_pressedIndex
.has_value()) {
1560 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1561 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1562 if (pressedItemAlreadySelected
|| row
->iconRect().contains(mappedPos
) || row
->textRect().contains(mappedPos
)) {
1563 // we are indeed inside the text/icon rect, keep m_pressedIndex what it is
1564 // and short-circuit for single-click activation (it will then propagate to onRelease and activate the item)
1565 // or we just keep going for double-click activation
1566 if (m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) {
1567 if (!pressedItemAlreadySelected
) {
1568 // An unselected item was clicked directly while deselecting multiple other items so we select it.
1569 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1570 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1571 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1573 return true; // event handled, don't create rubber band
1576 // we're not inside the text/icon rect, as we've already cleared the selection
1577 // we can just stop here and make sure handlers down the line (i.e. onRelease) don't activate
1578 m_pressedIndex
.reset();
1579 // we don't stop event propagation and proceed to create a rubber band and let onRelease
1580 // decide (based on m_pressedIndex) whether we're in a drag (drag => new rubber band, click => don't select the item)
1584 } else if (pressedItemAlreadySelected
&& !shiftOrControlPressed
&& leftClick
) {
1585 // The user might want to start dragging multiple items, but if he clicks the item
1586 // in order to trigger it instead, the other selected items must be deselected.
1587 // However, we do not know yet what the user is going to do.
1588 // -> remember that the user pressed an item which had been selected already and
1589 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1590 m_clearSelectionIfItemsAreNotDragged
= true;
1592 if (m_selectionManager
->selectedItems().count() == 1 && m_view
->isAboveText(m_pressedIndex
.value_or(-1), m_pressedMousePos
)) {
1593 Q_EMIT
selectedItemTextPressed(m_pressedIndex
.value_or(-1));
1597 if (!shiftPressed
) {
1598 // Finish the anchored selection before the current index is changed
1599 m_selectionManager
->endAnchoredSelection();
1604 // Do header hit check and short circuit before commencing any state changing effects
1605 if (m_view
->headerBoundaries().contains(pos
)) {
1606 Q_EMIT
headerContextMenuRequested(screenPos
);
1610 // Stop rubber band from persisting after right-clicks
1611 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1612 if (rubberBand
->isActive()) {
1613 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1614 rubberBand
->setActive(false);
1615 m_view
->setAutoScroll(false);
1619 if (m_pressedIndex
.has_value()) {
1620 // The hover highlight area of an item is being pressed.
1621 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1622 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
1623 const bool hitTargetIsRowEmptyRegion
= !row
->contains(row
->mapFromItem(m_view
, pos
));
1624 // again, when this method returns false, a rubberBand selection is created as the event is not consumed;
1625 // createRubberBand here tells us whether to return true or false.
1626 bool createRubberBand
= (hitTargetIsRowEmptyRegion
&& m_selectionManager
->selectedItems().isEmpty());
1628 if (rightClick
&& hitTargetIsRowEmptyRegion
) {
1629 // We have a right click outside the icon and text rect but within the hover highlight area
1630 // but it is unclear if this means that a selection rectangle for an item was clicked or the background of the view.
1631 if (m_selectionManager
->selectedItems().contains(m_pressedIndex
.value())) {
1632 // The selection rectangle for an item was clicked
1633 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), screenPos
);
1635 row
->setHovered(false); // Removes the hover highlight so the context menu doesn't look like it applies to the row.
1636 Q_EMIT
viewContextMenuRequested(screenPos
);
1641 switch (m_selectionBehavior
) {
1645 case SingleSelection
:
1646 m_selectionManager
->setSelected(m_pressedIndex
.value());
1649 case MultiSelection
:
1650 if (controlPressed
&& !shiftPressed
&& leftClick
) {
1651 // A left mouse button press is happening on an item while control is pressed. This either means a user wants to:
1652 // - toggle the selection of item(s) or
1653 // - they want to begin a drag on the item(s) to copy them.
1654 // We rule out the latter, if the item is not clicked directly and was unselected previously.
1655 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1656 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1657 if (!row
->iconRect().contains(mappedPos
) && !row
->textRect().contains(mappedPos
) && !pressedItemAlreadySelected
) {
1658 createRubberBand
= true;
1660 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1661 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1662 createRubberBand
= false; // multi selection, don't propagate any further
1663 // This will be the start of an item drag-to-copy operation if the user now moves the mouse before releasing the mouse button.
1665 } else if (!shiftPressed
|| !m_selectionManager
->isAnchoredSelectionActive()) {
1666 // Select the pressed item and start a new anchored selection
1667 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1668 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1678 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), screenPos
);
1680 return !createRubberBand
;
1684 // header right click handling would have been done before this so just normal context
1685 // menu here is fine
1686 Q_EMIT
viewContextMenuRequested(screenPos
);
1693 bool KItemListController::onRelease(const QPointF
& pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
, bool touch
)
1695 const bool isAboveSelectionToggle
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
);
1696 if (isAboveSelectionToggle
) {
1697 m_selectionTogglePressed
= false;
1701 if (!isAboveSelectionToggle
&& m_selectionTogglePressed
) {
1702 m_selectionManager
->setSelected(m_pressedIndex
.value_or(-1), 1, KItemListSelectionManager::Toggle
);
1703 m_selectionTogglePressed
= false;
1707 const bool controlPressed
= modifiers
& Qt::ControlModifier
;
1708 const bool shiftOrControlPressed
= modifiers
& Qt::ShiftModifier
||
1711 const std::optional
<int> index
= m_view
->itemAt(pos
);
1713 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1714 bool rubberBandRelease
= false;
1715 if (rubberBand
->isActive()) {
1716 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1717 rubberBand
->setActive(false);
1718 m_oldSelection
.clear();
1719 m_view
->setAutoScroll(false);
1720 rubberBandRelease
= true;
1721 // We check for actual rubber band drag here: if delta between start and end is less than drag threshold,
1722 // then we have a single click on one of the rows
1723 if ((rubberBand
->endPosition() - rubberBand
->startPosition()).manhattanLength() < QApplication::startDragDistance()) {
1724 rubberBandRelease
= false; // since we're only selecting, unmark rubber band release flag
1725 // m_pressedIndex will have no value if we came from a multi-selection clearing onPress
1726 // in that case, we don't select anything
1727 if (index
.has_value() && m_pressedIndex
.has_value()) {
1728 if (controlPressed
&& m_selectionBehavior
== MultiSelection
) {
1729 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1731 m_selectionManager
->setSelected(index
.value());
1733 if (!m_selectionManager
->isAnchoredSelectionActive()) {
1734 m_selectionManager
->beginAnchoredSelection(index
.value());
1740 if (index
.has_value() && index
== m_pressedIndex
) {
1741 // The release event is done above the same item as the press event
1743 if (m_clearSelectionIfItemsAreNotDragged
) {
1744 // A selected item has been clicked, but no drag operation has been started
1745 // -> clear the rest of the selection.
1746 m_selectionManager
->clearSelection();
1747 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1748 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1751 if (buttons
& Qt::LeftButton
) {
1752 bool emitItemActivated
= true;
1753 if (m_view
->isAboveExpansionToggle(index
.value(), pos
)) {
1754 const bool expanded
= m_model
->isExpanded(index
.value());
1755 m_model
->setExpanded(index
.value(), !expanded
);
1757 Q_EMIT
itemExpansionToggleClicked(index
.value());
1758 emitItemActivated
= false;
1759 } else if (shiftOrControlPressed
&& m_selectionBehavior
!= SingleSelection
) {
1760 // The mouse click should only update the selection, not trigger the item, except when
1761 // we are in single selection mode
1762 emitItemActivated
= false;
1764 const bool singleClickActivation
= m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
;
1765 if (!singleClickActivation
) {
1766 emitItemActivated
= touch
&& !m_selectionMode
;
1768 // activate on single click only if we didn't come from a rubber band release
1769 emitItemActivated
= !rubberBandRelease
;
1772 if (emitItemActivated
) {
1773 Q_EMIT
itemActivated(index
.value());
1775 } else if (buttons
& Qt::MiddleButton
) {
1776 Q_EMIT
itemMiddleClicked(index
.value());
1780 m_pressedMousePos
= QPointF();
1781 m_pressedIndex
= std::nullopt
;
1782 m_clearSelectionIfItemsAreNotDragged
= false;
1786 void KItemListController::startRubberBand()
1788 if (m_selectionBehavior
== MultiSelection
) {
1789 QPointF startPos
= m_pressedMousePos
;
1790 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1791 startPos
.ry() += m_view
->scrollOffset();
1792 if (m_view
->itemSize().width() < 0) {
1793 // Use a special rubberband for views that have only one column and
1794 // expand the rubberband to use the whole width of the view.
1798 startPos
.rx() += m_view
->scrollOffset();
1801 m_oldSelection
= m_selectionManager
->selectedItems();
1802 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1803 rubberBand
->setStartPosition(startPos
);
1804 rubberBand
->setEndPosition(startPos
);
1805 rubberBand
->setActive(true);
1806 connect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1807 m_view
->setAutoScroll(true);
1811 void KItemListController::slotStateChanged(QScroller::State newState
)
1813 if (newState
== QScroller::Scrolling
) {
1814 m_scrollerIsScrolling
= true;
1815 } else if (newState
== QScroller::Inactive
) {
1816 m_scrollerIsScrolling
= false;