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
)
53 , m_pressedMouseGlobalPos()
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 const QPointF pressedMousePos
= m_view
->transform().map(m_view
->scene()->views().first()->mapFromGlobal(m_pressedMouseGlobalPos
.toPoint()));
191 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_view
->m_visibleGroups
);
192 while (it
.hasNext()) {
194 KItemListGroupHeader
*groupHeader
= it
.value();
195 const QPointF mappedToGroup
= groupHeader
->mapFromItem(nullptr, pressedMousePos
);
196 if (groupHeader
->contains(mappedToGroup
)) {
197 return it
.key()->index();
203 void KItemListController::setAutoActivationDelay(int delay
)
205 m_autoActivationTimer
->setInterval(delay
);
208 int KItemListController::autoActivationDelay() const
210 return m_autoActivationTimer
->interval();
213 void KItemListController::setSingleClickActivationEnforced(bool singleClick
)
215 m_singleClickActivationEnforced
= singleClick
;
218 bool KItemListController::singleClickActivationEnforced() const
220 return m_singleClickActivationEnforced
;
223 void KItemListController::setSelectionModeEnabled(bool enabled
)
225 m_selectionMode
= enabled
;
228 bool KItemListController::selectionMode() const
230 return m_selectionMode
;
233 bool KItemListController::isSearchAsYouTypeActive() const
235 return m_keyboardManager
->isSearchAsYouTypeActive();
238 bool KItemListController::keyPressEvent(QKeyEvent
*event
)
240 int index
= m_selectionManager
->currentItem();
241 int key
= event
->key();
242 const bool shiftPressed
= event
->modifiers() & Qt::ShiftModifier
;
244 // Handle the expanding/collapsing of items
245 // expand / collapse all selected directories
246 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
) && (key
== Qt::Key_Right
|| key
== Qt::Key_Left
)) {
247 const bool expandOrCollapse
= key
== Qt::Key_Right
? true : false;
248 bool shouldReturn
= m_model
->setExpanded(index
, expandOrCollapse
);
250 // edit in reverse to preserve index of the first handled items
251 const auto selectedItems
= m_selectionManager
->selectedItems();
252 for (auto it
= selectedItems
.rbegin(); it
!= selectedItems
.rend(); ++it
) {
253 shouldReturn
|= m_model
->setExpanded(*it
, expandOrCollapse
);
255 m_selectionManager
->setSelected(*it
);
259 // update keyboard anchors
261 m_keyboardAnchorIndex
= selectedItems
.count() > 0 ? qMin(index
, selectedItems
.last()) : index
;
262 m_keyboardAnchorPos
= keyboardAnchorPos(m_keyboardAnchorIndex
);
270 const bool controlPressed
= event
->modifiers() & Qt::ControlModifier
;
271 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
272 const bool navigationPressed
= key
== Qt::Key_Home
|| key
== Qt::Key_End
|| key
== Qt::Key_PageUp
|| key
== Qt::Key_PageDown
|| key
== Qt::Key_Up
273 || key
== Qt::Key_Down
|| key
== Qt::Key_Left
|| key
== Qt::Key_Right
;
275 const int itemCount
= m_model
->count();
277 // For horizontal scroll orientation, transform
278 // the arrow keys to simplify the event handling.
279 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
298 const bool selectSingleItem
= m_selectionBehavior
!= NoSelection
&& itemCount
== 1 && navigationPressed
;
300 if (selectSingleItem
) {
301 const int current
= m_selectionManager
->currentItem();
302 m_selectionManager
->setSelected(current
);
309 m_keyboardAnchorIndex
= index
;
310 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
314 index
= itemCount
- 1;
315 m_keyboardAnchorIndex
= index
;
316 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
321 const int expandedParentsCount
= m_model
->expandedParentsCount(index
);
322 if (expandedParentsCount
== 0) {
325 // Go to the parent of the current item.
328 } while (index
> 0 && m_model
->expandedParentsCount(index
) == expandedParentsCount
);
330 m_keyboardAnchorIndex
= index
;
331 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
336 if (index
< itemCount
- 1) {
338 m_keyboardAnchorIndex
= index
;
339 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
344 updateKeyboardAnchor();
345 if (shiftPressed
&& !m_selectionManager
->isAnchoredSelectionActive() && m_selectionManager
->isSelected(index
)) {
346 m_selectionManager
->beginAnchoredSelection(index
);
348 index
= previousRowIndex(index
);
352 updateKeyboardAnchor();
353 if (shiftPressed
&& !m_selectionManager
->isAnchoredSelectionActive() && m_selectionManager
->isSelected(index
)) {
354 m_selectionManager
->beginAnchoredSelection(index
);
356 index
= nextRowIndex(index
);
360 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
361 // The new current index should correspond to the first item in the current column.
362 int newIndex
= qMax(index
- 1, 0);
363 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() < m_view
->itemRect(index
).topLeft().y()) {
365 newIndex
= qMax(index
- 1, 0);
367 m_keyboardAnchorIndex
= index
;
368 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
370 const qreal currentItemBottom
= m_view
->itemRect(index
).bottomLeft().y();
371 const qreal height
= m_view
->geometry().height();
373 // The new current item should be the first item in the current
374 // column whose itemRect's top coordinate is larger than targetY.
375 const qreal targetY
= currentItemBottom
- height
;
377 updateKeyboardAnchor();
378 int newIndex
= previousRowIndex(index
);
381 updateKeyboardAnchor();
382 newIndex
= previousRowIndex(index
);
383 } while (m_view
->itemRect(newIndex
).topLeft().y() > targetY
&& newIndex
!= index
);
387 case Qt::Key_PageDown
:
388 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
389 // The new current index should correspond to the last item in the current column.
390 int newIndex
= qMin(index
+ 1, m_model
->count() - 1);
391 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() > m_view
->itemRect(index
).topLeft().y()) {
393 newIndex
= qMin(index
+ 1, m_model
->count() - 1);
395 m_keyboardAnchorIndex
= index
;
396 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
398 const qreal currentItemTop
= m_view
->itemRect(index
).topLeft().y();
399 const qreal height
= m_view
->geometry().height();
401 // The new current item should be the last item in the current
402 // column whose itemRect's bottom coordinate is smaller than targetY.
403 const qreal targetY
= currentItemTop
+ height
;
405 updateKeyboardAnchor();
406 int newIndex
= nextRowIndex(index
);
409 updateKeyboardAnchor();
410 newIndex
= nextRowIndex(index
);
411 } while (m_view
->itemRect(newIndex
).bottomLeft().y() < targetY
&& newIndex
!= index
);
416 case Qt::Key_Return
: {
417 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
418 if (selectedItems
.count() >= 2) {
419 Q_EMIT
itemsActivated(selectedItems
);
420 } else if (selectedItems
.count() == 1) {
421 Q_EMIT
itemActivated(selectedItems
.first());
423 Q_EMIT
itemActivated(index
);
429 // Emit the signal itemContextMenuRequested() in case if at least one
430 // item is selected. Otherwise the signal viewContextMenuRequested() will be emitted.
431 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
433 if (selectedItems
.count() >= 2) {
434 const int currentItemIndex
= m_selectionManager
->currentItem();
435 index
= selectedItems
.contains(currentItemIndex
) ? currentItemIndex
: selectedItems
.first();
436 } else if (selectedItems
.count() == 1) {
437 index
= selectedItems
.first();
441 const QRectF contextRect
= m_view
->itemContextRect(index
);
442 const QPointF
pos(m_view
->scene()->views().first()->mapToGlobal(contextRect
.bottomRight().toPoint()));
443 Q_EMIT
itemContextMenuRequested(index
, pos
);
445 Q_EMIT
viewContextMenuRequested(QCursor::pos());
451 if (m_selectionMode
) {
452 Q_EMIT
selectionModeChangeRequested(false);
453 } else if (m_selectionBehavior
!= SingleSelection
) {
454 m_selectionManager
->clearSelection();
456 m_keyboardManager
->cancelSearch();
457 Q_EMIT
escapePressed();
461 if (m_selectionBehavior
== MultiSelection
) {
462 if (controlPressed
) {
463 // Toggle the selection state of the current item.
464 m_selectionManager
->endAnchoredSelection();
465 m_selectionManager
->setSelected(index
, 1, KItemListSelectionManager::Toggle
);
466 m_selectionManager
->beginAnchoredSelection(index
);
469 // Select the current item if it is not selected yet.
470 const int current
= m_selectionManager
->currentItem();
471 if (!m_selectionManager
->isSelected(current
)) {
472 m_selectionManager
->setSelected(current
);
477 Q_FALLTHROUGH(); // fall through to the default case and add the Space to the current search string.
479 m_keyboardManager
->addKeys(event
->text());
480 // Make sure unconsumed events get propagated up the chain. #302329
485 if (m_selectionManager
->currentItem() != index
) {
486 switch (m_selectionBehavior
) {
488 m_selectionManager
->setCurrentItem(index
);
491 case SingleSelection
:
492 m_selectionManager
->setCurrentItem(index
);
493 m_selectionManager
->clearSelection();
494 m_selectionManager
->setSelected(index
, 1);
498 if (controlPressed
) {
499 m_selectionManager
->endAnchoredSelection();
502 m_selectionManager
->setCurrentItem(index
);
504 if (!shiftOrControlPressed
) {
505 m_selectionManager
->clearSelection();
506 m_selectionManager
->setSelected(index
, 1);
510 m_selectionManager
->beginAnchoredSelection(index
);
516 if (navigationPressed
) {
517 m_view
->scrollToItem(index
);
522 void KItemListController::slotChangeCurrentItem(const QString
&text
, bool searchFromNextItem
)
524 if (!m_model
|| m_model
->count() == 0) {
528 if (searchFromNextItem
) {
529 const int currentIndex
= m_selectionManager
->currentItem();
530 index
= m_model
->indexForKeyboardSearch(text
, (currentIndex
+ 1) % m_model
->count());
532 index
= m_model
->indexForKeyboardSearch(text
, 0);
535 m_selectionManager
->setCurrentItem(index
);
537 if (m_selectionBehavior
!= NoSelection
) {
538 m_selectionManager
->replaceSelection(index
);
539 m_selectionManager
->beginAnchoredSelection(index
);
542 m_view
->scrollToItem(index
);
546 void KItemListController::slotAutoActivationTimeout()
548 if (!m_model
|| !m_view
) {
552 const int index
= m_autoActivationTimer
->property("index").toInt();
553 if (index
< 0 || index
>= m_model
->count()) {
557 /* m_view->isUnderMouse() fixes a bug in the Folder-View-Panel and in the
560 * Bug: When you drag a file onto a Folder-View-Item or a Places-Item and
561 * then move away before the auto-activation timeout triggers, than the
562 * item still becomes activated/expanded.
564 * See Bug 293200 and 305783
566 if (m_view
->isUnderMouse()) {
567 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
)) {
568 const bool expanded
= m_model
->isExpanded(index
);
569 m_model
->setExpanded(index
, !expanded
);
570 } else if (m_autoActivationBehavior
!= ExpansionOnly
) {
571 Q_EMIT
itemActivated(index
);
576 bool KItemListController::inputMethodEvent(QInputMethodEvent
*event
)
582 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
585 m_pressedMouseGlobalPos
= event
->screenPos();
587 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& m_isTouchEvent
) {
595 const QPointF pressedMousePos
= transform
.map(event
->pos());
596 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
598 const Qt::MouseButtons buttons
= event
->buttons();
600 if (!onPress(event
->screenPos(), event
->pos(), event
->modifiers(), buttons
)) {
608 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
614 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
615 m_view
->m_tapAndHoldIndicator
->setActive(false);
618 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !m_dragActionOrRightClick
&& m_isTouchEvent
) {
622 if (m_pressedIndex
.has_value() && !m_view
->rubberBand()->isActive()) {
623 // Check whether a dragging should be started
624 if (event
->buttons() & Qt::LeftButton
) {
625 const auto distance
= (event
->screenPos() - m_pressedMouseGlobalPos
).manhattanLength();
626 if (distance
>= QApplication::startDragDistance()) {
627 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
628 // Always assure that the dragged item gets selected. Usually this is already
629 // done on the mouse-press event, but when using the selection-toggle on a
630 // selected item the dragged item is not selected yet.
631 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
633 // A selected item has been clicked to drag all selected items
634 // -> the selection should not be cleared when the mouse button is released.
635 m_clearSelectionIfItemsAreNotDragged
= false;
638 m_mousePress
= false;
642 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
643 if (rubberBand
->isActive()) {
644 QPointF endPos
= transform
.map(event
->pos());
646 // Update the current item.
647 const std::optional
<int> newCurrent
= m_view
->itemAt(endPos
);
648 if (newCurrent
.has_value()) {
649 // It's expected that the new current index is also the new anchor (bug 163451).
650 m_selectionManager
->endAnchoredSelection();
651 m_selectionManager
->setCurrentItem(newCurrent
.value());
652 m_selectionManager
->beginAnchoredSelection(newCurrent
.value());
655 if (m_view
->scrollOrientation() == Qt::Vertical
) {
656 endPos
.ry() += m_view
->scrollOffset();
658 endPos
.rx() += m_view
->scrollOffset();
660 rubberBand
->setEndPosition(endPos
);
667 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
669 m_mousePress
= false;
670 m_isTouchEvent
= false;
676 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
677 m_view
->m_tapAndHoldIndicator
->setActive(false);
680 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
681 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !rubberBand
->isActive() && m_isTouchEvent
) {
685 Q_EMIT
mouseButtonReleased(m_pressedIndex
.value_or(-1), event
->buttons());
687 return onRelease(transform
.map(event
->pos()), event
->modifiers(), event
->button(), false);
690 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
692 const QPointF pos
= transform
.map(event
->pos());
693 const std::optional
<int> index
= m_view
->itemAt(pos
);
695 // Expand item if desired - See Bug 295573
696 if (m_mouseDoubleClickAction
!= ActivateItemOnly
) {
697 if (m_view
&& m_model
&& m_view
->supportsItemExpanding() && m_model
->isExpandable(index
.value_or(-1))) {
698 const bool expanded
= m_model
->isExpanded(index
.value());
699 m_model
->setExpanded(index
.value(), !expanded
);
703 if (event
->button() & Qt::RightButton
) {
704 m_selectionManager
->clearSelection();
705 if (index
.has_value()) {
706 m_selectionManager
->setSelected(index
.value());
707 Q_EMIT
itemContextMenuRequested(index
.value(), event
->screenPos());
709 const QRectF headerBounds
= m_view
->headerBoundaries();
710 if (headerBounds
.contains(event
->pos())) {
711 Q_EMIT
headerContextMenuRequested(event
->screenPos());
713 Q_EMIT
viewContextMenuRequested(event
->screenPos());
719 bool emitItemActivated
= !(m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
)
720 && (event
->button() & Qt::LeftButton
) && index
.has_value() && index
.value() < m_model
->count();
721 if (emitItemActivated
) {
722 Q_EMIT
itemActivated(index
.value());
727 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
732 DragAndDropHelper::clearUrlListMatchesUrlCache();
737 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
742 m_autoActivationTimer
->stop();
743 m_view
->setAutoScroll(false);
744 m_view
->hideDropIndicator();
746 KItemListWidget
*widget
= hoveredWidget();
748 widget
->setHovered(false);
749 Q_EMIT
itemUnhovered(widget
->index());
754 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
756 if (!m_model
|| !m_view
) {
760 QUrl hoveredDir
= m_model
->directory();
761 KItemListWidget
*oldHoveredWidget
= hoveredWidget();
763 const QPointF pos
= transform
.map(event
->pos());
764 KItemListWidget
*newHoveredWidget
= widgetForDropPos(pos
);
767 if (oldHoveredWidget
!= newHoveredWidget
) {
768 m_autoActivationTimer
->stop();
770 if (oldHoveredWidget
) {
771 oldHoveredWidget
->setHovered(false);
772 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
776 if (newHoveredWidget
) {
777 bool droppingBetweenItems
= false;
778 if (m_model
->sortRole().isEmpty()) {
779 // The model supports inserting items between other items.
780 droppingBetweenItems
= (m_view
->showDropIndicator(pos
) >= 0);
783 index
= newHoveredWidget
->index();
785 if (m_model
->isDir(index
)) {
786 hoveredDir
= m_model
->url(index
);
789 if (!droppingBetweenItems
) {
790 // Something has been dragged on an item.
791 m_view
->hideDropIndicator();
792 if (!newHoveredWidget
->isHovered()) {
793 newHoveredWidget
->setHovered(true);
794 Q_EMIT
itemHovered(index
);
797 if (!m_autoActivationTimer
->isActive() && m_autoActivationTimer
->interval() >= 0) {
798 m_autoActivationTimer
->setProperty("index", index
);
799 m_autoActivationTimer
->start();
802 m_autoActivationTimer
->stop();
803 if (newHoveredWidget
&& newHoveredWidget
->isHovered()) {
804 newHoveredWidget
->setHovered(false);
805 Q_EMIT
itemUnhovered(index
);
809 m_view
->hideDropIndicator();
812 if (DragAndDropHelper::urlListMatchesUrl(event
->mimeData()->urls(), hoveredDir
)) {
813 event
->setDropAction(Qt::IgnoreAction
);
816 if (m_model
->supportsDropping(index
)) {
817 event
->setDropAction(event
->proposedAction());
820 event
->setDropAction(Qt::IgnoreAction
);
827 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
833 m_autoActivationTimer
->stop();
834 m_view
->setAutoScroll(false);
836 const QPointF pos
= transform
.map(event
->pos());
838 int dropAboveIndex
= -1;
839 if (m_model
->sortRole().isEmpty()) {
840 // The model supports inserting of items between other items.
841 dropAboveIndex
= m_view
->showDropIndicator(pos
);
844 if (dropAboveIndex
>= 0) {
845 // Something has been dropped between two items.
846 m_view
->hideDropIndicator();
847 Q_EMIT
aboveItemDropEvent(dropAboveIndex
, event
);
848 } else if (!event
->mimeData()->hasFormat(m_model
->blacklistItemDropEventMimeType())) {
849 // Something has been dropped on an item or on an empty part of the view.
850 const KItemListWidget
*receivingWidget
= widgetForDropPos(pos
);
851 if (receivingWidget
) {
852 Q_EMIT
itemDropEvent(receivingWidget
->index(), event
);
854 Q_EMIT
itemDropEvent(-1, event
);
858 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropEnd
);
859 QAccessible::updateAccessibility(&accessibilityEvent
);
864 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
871 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
874 if (!m_model
|| !m_view
) {
878 // We identify the widget whose expansionArea had been hovered before this hoverMoveEvent() triggered.
879 // we can't use hoveredWidget() here (it handles the icon+text rect, not the expansion rect)
880 // like hoveredWidget(), we find the hovered widget for the expansion rect
881 const auto visibleItemListWidgets
= m_view
->visibleItemListWidgets();
882 const auto oldHoveredExpansionWidgetIterator
= std::find_if(visibleItemListWidgets
.begin(), visibleItemListWidgets
.end(), [](auto &widget
) {
883 return widget
->expansionAreaHovered();
885 const auto oldHoveredExpansionWidget
=
886 oldHoveredExpansionWidgetIterator
== visibleItemListWidgets
.end() ? std::nullopt
: std::make_optional(*oldHoveredExpansionWidgetIterator
);
888 const auto unhoverOldHoveredWidget
= [&]() {
889 if (auto oldHoveredWidget
= hoveredWidget(); oldHoveredWidget
) {
890 // handle the text+icon one
891 oldHoveredWidget
->setHovered(false);
892 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
896 const auto unhoverOldExpansionWidget
= [&]() {
897 if (oldHoveredExpansionWidget
) {
898 // then the expansion toggle
899 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
903 const QPointF pos
= transform
.map(event
->pos());
904 if (KItemListWidget
*newHoveredWidget
= widgetForPos(pos
); newHoveredWidget
) {
905 // something got hovered, work out which part and set hover for the appropriate widget
906 const auto mappedPos
= newHoveredWidget
->mapFromItem(m_view
, pos
);
907 const bool isOnExpansionToggle
= newHoveredWidget
->expansionToggleRect().contains(mappedPos
);
909 if (isOnExpansionToggle
) {
910 // make sure we unhover the old one first if old!=new
911 if (oldHoveredExpansionWidget
&& *oldHoveredExpansionWidget
!= newHoveredWidget
) {
912 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
914 // 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)
915 unhoverOldHoveredWidget();
917 newHoveredWidget
->setExpansionAreaHovered(true);
919 // make sure we unhover the old one first if old!=new
920 auto oldHoveredWidget
= hoveredWidget();
921 if (oldHoveredWidget
&& oldHoveredWidget
!= newHoveredWidget
) {
922 oldHoveredWidget
->setHovered(false);
923 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
925 // 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)
926 unhoverOldExpansionWidget();
928 const bool isOverIconAndText
= newHoveredWidget
->iconRect().contains(mappedPos
) || newHoveredWidget
->textRect().contains(mappedPos
);
929 const bool hasMultipleSelection
= m_selectionManager
->selectedItems().count() > 1;
931 if (hasMultipleSelection
&& !isOverIconAndText
) {
932 // In case we have multiple selections, clicking on any row will deselect the selection.
933 // So, as a visual cue for signalling that clicking anywhere won't select, but clear current highlights,
934 // we disable hover of the *row*(i.e. blank space to the right of the icon+text)
936 // (no-op in this branch for masked hover)
938 newHoveredWidget
->setHoverPosition(mappedPos
);
939 if (oldHoveredWidget
!= newHoveredWidget
) {
940 newHoveredWidget
->setHovered(true);
941 Q_EMIT
itemHovered(newHoveredWidget
->index());
946 // unhover any currently hovered expansion and text+icon widgets
947 unhoverOldHoveredWidget();
948 unhoverOldExpansionWidget();
953 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
958 m_mousePress
= false;
959 m_isTouchEvent
= false;
961 if (!m_model
|| !m_view
) {
965 const auto widgets
= m_view
->visibleItemListWidgets();
966 for (KItemListWidget
*widget
: widgets
) {
967 if (widget
->isHovered()) {
968 widget
->setHovered(false);
969 Q_EMIT
itemUnhovered(widget
->index());
975 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent
*event
, const QTransform
&transform
)
982 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent
*event
, const QTransform
&transform
)
989 bool KItemListController::gestureEvent(QGestureEvent
*event
, const QTransform
&transform
)
995 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
996 //we use this to get the right QWidget
997 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
999 if (QGesture
*tap
= event
->gesture(Qt::TapGesture
)) {
1000 QTapGesture
*tapGesture
= static_cast<QTapGesture
*>(tap
);
1001 if (tapGesture
->state() == Qt::GestureStarted
) {
1002 tapTriggered(tapGesture
, transform
);
1008 bool accepted
= false;
1010 if (QGesture
*tap
= event
->gesture(Qt::TapGesture
)) {
1011 tapTriggered(static_cast<QTapGesture
*>(tap
), transform
);
1014 if (event
->gesture(Qt::TapAndHoldGesture
)) {
1015 tapAndHoldTriggered(event
, transform
);
1018 if (event
->gesture(Qt::PinchGesture
)) {
1019 pinchTriggered(event
, transform
);
1022 if (event
->gesture(m_swipeGesture
)) {
1023 swipeTriggered(event
, transform
);
1026 if (event
->gesture(m_twoFingerTapGesture
)) {
1027 twoFingerTapTriggered(event
, transform
);
1033 bool KItemListController::touchBeginEvent(QTouchEvent
*event
, const QTransform
&transform
)
1038 m_isTouchEvent
= true;
1042 void KItemListController::tapTriggered(QTapGesture
*tap
, const QTransform
&transform
)
1044 static bool scrollerWasActive
= false;
1046 if (tap
->state() == Qt::GestureStarted
) {
1047 m_dragActionOrRightClick
= false;
1048 m_isSwipeGesture
= false;
1049 m_pinchGestureInProgress
= false;
1050 scrollerWasActive
= m_scrollerIsScrolling
;
1053 if (tap
->state() == Qt::GestureFinished
) {
1054 m_mousePress
= false;
1056 //if at the moment of the gesture start the QScroller was active, the user made the tap
1057 //to stop the QScroller and not to tap on an item
1058 if (scrollerWasActive
) {
1062 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
1063 m_view
->m_tapAndHoldIndicator
->setActive(false);
1066 const QPointF pressedMousePos
= transform
.map(tap
->position());
1067 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1068 if (m_dragActionOrRightClick
) {
1069 m_dragActionOrRightClick
= false;
1071 onPress(m_pressedMouseGlobalPos
.toPoint(), tap
->position().toPoint(), Qt::NoModifier
, Qt::LeftButton
);
1072 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::LeftButton
, true);
1074 m_isTouchEvent
= false;
1078 void KItemListController::tapAndHoldTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1080 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
1081 if (!m_isTouchEvent
) {
1085 const QTapAndHoldGesture
*tap
= static_cast<QTapAndHoldGesture
*>(event
->gesture(Qt::TapAndHoldGesture
));
1086 if (tap
->state() == Qt::GestureFinished
) {
1087 //if a pinch gesture is in progress we don't want a TabAndHold gesture
1088 if (m_pinchGestureInProgress
) {
1091 const QPointF pressedMousePos
= transform
.map(event
->mapToGraphicsScene(tap
->position()));
1092 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1093 if (m_pressedIndex
.has_value()) {
1094 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
1095 m_selectionManager
->clearSelection();
1096 m_selectionManager
->setSelected(m_pressedIndex
.value());
1098 if (!m_selectionMode
) {
1099 Q_EMIT
selectionModeChangeRequested(true);
1102 m_selectionManager
->clearSelection();
1106 Q_EMIT
scrollerStop();
1108 m_view
->m_tapAndHoldIndicator
->setStartPosition(pressedMousePos
);
1109 m_view
->m_tapAndHoldIndicator
->setActive(true);
1111 m_dragActionOrRightClick
= true;
1115 void KItemListController::pinchTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1119 const QPinchGesture
*pinch
= static_cast<QPinchGesture
*>(event
->gesture(Qt::PinchGesture
));
1120 const qreal sensitivityModifier
= 0.2;
1121 static qreal counter
= 0;
1123 if (pinch
->state() == Qt::GestureStarted
) {
1124 m_pinchGestureInProgress
= true;
1127 if (pinch
->state() == Qt::GestureUpdated
) {
1128 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1129 if (m_isSwipeGesture
) {
1132 counter
= counter
+ (pinch
->scaleFactor() - 1);
1133 if (counter
>= sensitivityModifier
) {
1134 Q_EMIT
increaseZoom();
1136 } else if (counter
<= -sensitivityModifier
) {
1137 Q_EMIT
decreaseZoom();
1143 void KItemListController::swipeTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1147 const KTwoFingerSwipe
*swipe
= static_cast<KTwoFingerSwipe
*>(event
->gesture(m_swipeGesture
));
1152 if (swipe
->state() == Qt::GestureStarted
) {
1153 m_isSwipeGesture
= true;
1156 if (swipe
->state() == Qt::GestureCanceled
) {
1157 m_isSwipeGesture
= false;
1160 if (swipe
->state() == Qt::GestureFinished
) {
1161 Q_EMIT
scrollerStop();
1163 if (swipe
->swipeAngle() <= 20 || swipe
->swipeAngle() >= 340) {
1164 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::BackButton
);
1165 } else if (swipe
->swipeAngle() <= 200 && swipe
->swipeAngle() >= 160) {
1166 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::ForwardButton
);
1167 } else if (swipe
->swipeAngle() <= 110 && swipe
->swipeAngle() >= 60) {
1170 m_isSwipeGesture
= true;
1174 void KItemListController::twoFingerTapTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1176 const KTwoFingerTap
*twoTap
= static_cast<KTwoFingerTap
*>(event
->gesture(m_twoFingerTapGesture
));
1182 if (twoTap
->state() == Qt::GestureStarted
) {
1183 const QPointF pressedMousePos
= transform
.map(twoTap
->pos());
1184 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1185 if (m_pressedIndex
.has_value()) {
1186 onPress(twoTap
->screenPos().toPoint(), twoTap
->pos().toPoint(), Qt::ControlModifier
, Qt::LeftButton
);
1187 onRelease(transform
.map(twoTap
->pos()), Qt::ControlModifier
, Qt::LeftButton
, false);
1192 bool KItemListController::processEvent(QEvent
*event
, const QTransform
&transform
)
1198 switch (event
->type()) {
1199 case QEvent::KeyPress
:
1200 return keyPressEvent(static_cast<QKeyEvent
*>(event
));
1201 case QEvent::InputMethod
:
1202 return inputMethodEvent(static_cast<QInputMethodEvent
*>(event
));
1203 case QEvent::GraphicsSceneMousePress
:
1204 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1205 case QEvent::GraphicsSceneMouseMove
:
1206 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1207 case QEvent::GraphicsSceneMouseRelease
:
1208 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1209 case QEvent::GraphicsSceneMouseDoubleClick
:
1210 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1211 case QEvent::GraphicsSceneWheel
:
1212 return wheelEvent(static_cast<QGraphicsSceneWheelEvent
*>(event
), QTransform());
1213 case QEvent::GraphicsSceneDragEnter
:
1214 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1215 case QEvent::GraphicsSceneDragLeave
:
1216 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1217 case QEvent::GraphicsSceneDragMove
:
1218 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1219 case QEvent::GraphicsSceneDrop
:
1220 return dropEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1221 case QEvent::GraphicsSceneHoverEnter
:
1222 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1223 case QEvent::GraphicsSceneHoverMove
:
1224 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1225 case QEvent::GraphicsSceneHoverLeave
:
1226 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1227 case QEvent::GraphicsSceneResize
:
1228 return resizeEvent(static_cast<QGraphicsSceneResizeEvent
*>(event
), transform
);
1229 case QEvent::Gesture
:
1230 return gestureEvent(static_cast<QGestureEvent
*>(event
), transform
);
1231 case QEvent::TouchBegin
:
1232 return touchBeginEvent(static_cast<QTouchEvent
*>(event
), transform
);
1240 void KItemListController::slotViewScrollOffsetChanged(qreal current
, qreal previous
)
1246 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1247 if (rubberBand
->isActive()) {
1248 const qreal diff
= current
- previous
;
1249 // TODO: Ideally just QCursor::pos() should be used as
1250 // new end-position but it seems there is no easy way
1251 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1252 // (... or I just missed an easy way to do the mapping)
1253 QPointF endPos
= rubberBand
->endPosition();
1254 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1255 endPos
.ry() += diff
;
1257 endPos
.rx() += diff
;
1260 rubberBand
->setEndPosition(endPos
);
1264 void KItemListController::slotRubberBandChanged()
1266 if (!m_view
|| !m_model
|| m_model
->count() <= 0) {
1270 const KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1271 const QPointF startPos
= rubberBand
->startPosition();
1272 const QPointF endPos
= rubberBand
->endPosition();
1273 QRectF rubberBandRect
= QRectF(startPos
, endPos
).normalized();
1275 const bool scrollVertical
= (m_view
->scrollOrientation() == Qt::Vertical
);
1276 if (scrollVertical
) {
1277 rubberBandRect
.translate(0, -m_view
->scrollOffset());
1279 rubberBandRect
.translate(-m_view
->scrollOffset(), 0);
1282 if (!m_oldSelection
.isEmpty()) {
1283 // Clear the old selection that was available before the rubberband has
1284 // been activated in case if no Shift- or Control-key are pressed
1285 const bool shiftOrControlPressed
= QApplication::keyboardModifiers() & Qt::ShiftModifier
|| QApplication::keyboardModifiers() & Qt::ControlModifier
;
1286 if (!shiftOrControlPressed
&& !m_selectionMode
) {
1287 m_oldSelection
.clear();
1291 KItemSet selectedItems
;
1293 // Select all visible items that intersect with the rubberband
1294 const auto widgets
= m_view
->visibleItemListWidgets();
1295 for (const KItemListWidget
*widget
: widgets
) {
1296 const int index
= widget
->index();
1298 const QRectF widgetRect
= m_view
->itemRect(index
);
1299 if (widgetRect
.intersects(rubberBandRect
)) {
1300 // Select the full row intersecting with the rubberband rectangle
1301 const QRectF selectionRect
= widget
->selectionRect().translated(widgetRect
.topLeft());
1302 if (selectionRect
.intersects(rubberBandRect
)) {
1303 selectedItems
.insert(index
);
1308 // Select all invisible items that intersect with the rubberband. Instead of
1309 // iterating all items only the area which might be touched by the rubberband
1311 const bool increaseIndex
= scrollVertical
? startPos
.y() > endPos
.y() : startPos
.x() > endPos
.x();
1313 int index
= increaseIndex
? m_view
->lastVisibleIndex() + 1 : m_view
->firstVisibleIndex() - 1;
1314 bool selectionFinished
= false;
1316 const QRectF widgetRect
= m_view
->itemRect(index
);
1317 if (widgetRect
.intersects(rubberBandRect
)) {
1318 selectedItems
.insert(index
);
1321 if (increaseIndex
) {
1323 selectionFinished
= (index
>= m_model
->count()) || (scrollVertical
&& widgetRect
.top() > rubberBandRect
.bottom())
1324 || (!scrollVertical
&& widgetRect
.left() > rubberBandRect
.right());
1327 selectionFinished
= (index
< 0) || (scrollVertical
&& widgetRect
.bottom() < rubberBandRect
.top())
1328 || (!scrollVertical
&& widgetRect
.right() < rubberBandRect
.left());
1330 } while (!selectionFinished
);
1332 if ((QApplication::keyboardModifiers() & Qt::ControlModifier
) || m_selectionMode
) {
1333 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1334 // Therefore, the new selection contains:
1335 // 1. All previously selected items which are not inside the rubberband, and
1336 // 2. all items inside the rubberband which have not been selected previously.
1337 m_selectionManager
->setSelectedItems(m_oldSelection
^ selectedItems
);
1339 m_selectionManager
->setSelectedItems(selectedItems
+ m_oldSelection
);
1343 void KItemListController::startDragging()
1345 if (!m_view
|| !m_model
) {
1349 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
1350 if (selectedItems
.isEmpty()) {
1354 QMimeData
*data
= m_model
->createMimeData(selectedItems
);
1358 KUrlMimeData::exportUrlsToPortal(data
);
1360 // The created drag object will be owned and deleted
1361 // by QApplication::activeWindow().
1362 QDrag
*drag
= new QDrag(QApplication::activeWindow());
1363 drag
->setMimeData(data
);
1365 const QPixmap pixmap
= m_view
->createDragPixmap(selectedItems
);
1366 drag
->setPixmap(pixmap
);
1368 const QPoint
hotSpot((pixmap
.width() / pixmap
.devicePixelRatio()) / 2, 0);
1369 drag
->setHotSpot(hotSpot
);
1371 drag
->exec(Qt::MoveAction
| Qt::CopyAction
| Qt::LinkAction
, Qt::CopyAction
);
1373 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropStart
);
1374 QAccessible::updateAccessibility(&accessibilityEvent
);
1377 KItemListWidget
*KItemListController::hoveredWidget() const
1381 const auto widgets
= m_view
->visibleItemListWidgets();
1382 for (KItemListWidget
*widget
: widgets
) {
1383 if (widget
->isHovered()) {
1391 KItemListWidget
*KItemListController::widgetForPos(const QPointF
&pos
) const
1395 const auto widgets
= m_view
->visibleItemListWidgets();
1396 for (KItemListWidget
*widget
: widgets
) {
1397 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1398 if (widget
->contains(mappedPos
) || widget
->selectionRect().contains(mappedPos
)) {
1406 KItemListWidget
*KItemListController::widgetForDropPos(const QPointF
&pos
) const
1410 const auto widgets
= m_view
->visibleItemListWidgets();
1411 for (KItemListWidget
*widget
: widgets
) {
1412 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1413 if (widget
->contains(mappedPos
)) {
1421 void KItemListController::updateKeyboardAnchor()
1423 const bool validAnchor
=
1424 m_keyboardAnchorIndex
>= 0 && m_keyboardAnchorIndex
< m_model
->count() && keyboardAnchorPos(m_keyboardAnchorIndex
) == m_keyboardAnchorPos
;
1426 const int index
= m_selectionManager
->currentItem();
1427 m_keyboardAnchorIndex
= index
;
1428 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
1432 int KItemListController::nextRowIndex(int index
) const
1434 if (m_keyboardAnchorIndex
< 0) {
1438 const int maxIndex
= m_model
->count() - 1;
1439 if (index
== maxIndex
) {
1443 // Calculate the index of the last column inside the row of the current index
1444 int lastColumnIndex
= index
;
1445 while (keyboardAnchorPos(lastColumnIndex
+ 1) > keyboardAnchorPos(lastColumnIndex
)) {
1447 if (lastColumnIndex
>= maxIndex
) {
1452 // Based on the last column index go to the next row and calculate the nearest index
1453 // that is below the current index
1454 int nextRowIndex
= lastColumnIndex
+ 1;
1455 int searchIndex
= nextRowIndex
;
1456 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(nextRowIndex
));
1457 while (searchIndex
< maxIndex
&& keyboardAnchorPos(searchIndex
+ 1) > keyboardAnchorPos(searchIndex
)) {
1459 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1460 if (searchDiff
< minDiff
) {
1461 minDiff
= searchDiff
;
1462 nextRowIndex
= searchIndex
;
1466 return nextRowIndex
;
1469 int KItemListController::previousRowIndex(int index
) const
1471 if (m_keyboardAnchorIndex
< 0 || index
== 0) {
1475 // Calculate the index of the first column inside the row of the current index
1476 int firstColumnIndex
= index
;
1477 while (keyboardAnchorPos(firstColumnIndex
- 1) < keyboardAnchorPos(firstColumnIndex
)) {
1479 if (firstColumnIndex
<= 0) {
1484 // Based on the first column index go to the previous row and calculate the nearest index
1485 // that is above the current index
1486 int previousRowIndex
= firstColumnIndex
- 1;
1487 int searchIndex
= previousRowIndex
;
1488 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(previousRowIndex
));
1489 while (searchIndex
> 0 && keyboardAnchorPos(searchIndex
- 1) < keyboardAnchorPos(searchIndex
)) {
1491 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1492 if (searchDiff
< minDiff
) {
1493 minDiff
= searchDiff
;
1494 previousRowIndex
= searchIndex
;
1498 return previousRowIndex
;
1501 qreal
KItemListController::keyboardAnchorPos(int index
) const
1503 const QRectF itemRect
= m_view
->itemRect(index
);
1504 if (!itemRect
.isEmpty()) {
1505 return (m_view
->scrollOrientation() == Qt::Vertical
) ? itemRect
.x() : itemRect
.y();
1511 void KItemListController::updateExtendedSelectionRegion()
1514 const bool extend
= (m_selectionBehavior
!= MultiSelection
);
1515 KItemListStyleOption option
= m_view
->styleOption();
1516 if (option
.extendedSelectionRegion
!= extend
) {
1517 option
.extendedSelectionRegion
= extend
;
1518 m_view
->setStyleOption(option
);
1523 bool KItemListController::onPress(const QPoint
&screenPos
, const QPointF
&pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
)
1525 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), buttons
);
1527 if (buttons
& (Qt::BackButton
| Qt::ForwardButton
)) {
1528 // Do not select items when clicking the back/forward buttons, see
1529 // https://bugs.kde.org/show_bug.cgi?id=327412.
1533 const QPointF pressedMousePos
= m_view
->transform().map(pos
);
1535 if (m_view
->isAboveExpansionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
)) {
1536 m_selectionManager
->endAnchoredSelection();
1537 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1538 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1542 m_selectionTogglePressed
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
);
1543 if (m_selectionTogglePressed
) {
1544 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1545 // The previous anchored selection has been finished already in
1546 // KItemListSelectionManager::setSelected(). We can safely change
1547 // the current item and start a new anchored selection now.
1548 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1549 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1553 const bool shiftPressed
= modifiers
& Qt::ShiftModifier
;
1554 const bool controlPressed
= (modifiers
& Qt::ControlModifier
) || m_selectionMode
; // Keeping selectionMode similar to pressing control will hopefully
1555 // simplify the overall logic and possibilities both for users and devs.
1556 const bool leftClick
= buttons
& Qt::LeftButton
;
1557 const bool rightClick
= buttons
& Qt::RightButton
;
1559 // The previous selection is cleared if either
1560 // 1. The selection mode is SingleSelection, or
1561 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1562 // a) Shift or Control are pressed.
1563 // b) The clicked item is selected already. In that case, the user might want to:
1564 // - start dragging multiple items, or
1565 // - open the context menu and perform an action for all selected items.
1566 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
1567 const bool pressedItemAlreadySelected
= m_pressedIndex
.has_value() && m_selectionManager
->isSelected(m_pressedIndex
.value());
1568 const bool clearSelection
= m_selectionBehavior
== SingleSelection
|| (!shiftOrControlPressed
&& !pressedItemAlreadySelected
);
1570 // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller.
1571 if (clearSelection
) {
1572 const int selectedItemsCount
= m_selectionManager
->selectedItems().count();
1573 m_selectionManager
->clearSelection();
1574 // clear and bail when we got an existing multi-selection
1575 if (selectedItemsCount
> 1 && m_pressedIndex
.has_value()) {
1576 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1577 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1578 if (pressedItemAlreadySelected
|| row
->iconRect().contains(mappedPos
) || row
->textRect().contains(mappedPos
)) {
1579 // we are indeed inside the text/icon rect, keep m_pressedIndex what it is
1580 // and short-circuit for single-click activation (it will then propagate to onRelease and activate the item)
1581 // or we just keep going for double-click activation
1582 if (m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) {
1583 if (!pressedItemAlreadySelected
) {
1584 // An unselected item was clicked directly while deselecting multiple other items so we select it.
1585 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1586 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1587 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1589 return true; // event handled, don't create rubber band
1592 // we're not inside the text/icon rect, as we've already cleared the selection
1593 // we can just stop here and make sure handlers down the line (i.e. onRelease) don't activate
1594 m_pressedIndex
.reset();
1595 // we don't stop event propagation and proceed to create a rubber band and let onRelease
1596 // decide (based on m_pressedIndex) whether we're in a drag (drag => new rubber band, click => don't select the item)
1600 } else if (pressedItemAlreadySelected
&& !shiftOrControlPressed
&& leftClick
) {
1601 // The user might want to start dragging multiple items, but if he clicks the item
1602 // in order to trigger it instead, the other selected items must be deselected.
1603 // However, we do not know yet what the user is going to do.
1604 // -> remember that the user pressed an item which had been selected already and
1605 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1606 m_clearSelectionIfItemsAreNotDragged
= true;
1608 if (m_selectionManager
->selectedItems().count() == 1 && m_view
->isAboveText(m_pressedIndex
.value_or(-1), pressedMousePos
)) {
1609 Q_EMIT
selectedItemTextPressed(m_pressedIndex
.value_or(-1));
1613 if (!shiftPressed
) {
1614 // Finish the anchored selection before the current index is changed
1615 m_selectionManager
->endAnchoredSelection();
1619 // Do header hit check and short circuit before commencing any state changing effects
1620 if (m_view
->headerBoundaries().contains(pos
)) {
1621 Q_EMIT
headerContextMenuRequested(screenPos
);
1625 // Stop rubber band from persisting after right-clicks
1626 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1627 if (rubberBand
->isActive()) {
1628 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1629 rubberBand
->setActive(false);
1630 m_view
->setAutoScroll(false);
1634 if (m_pressedIndex
.has_value()) {
1635 // The hover highlight area of an item is being pressed.
1636 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1637 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
1638 const bool hitTargetIsRowEmptyRegion
= !row
->contains(row
->mapFromItem(m_view
, pos
));
1639 // again, when this method returns false, a rubberBand selection is created as the event is not consumed;
1640 // createRubberBand here tells us whether to return true or false.
1641 bool createRubberBand
= (hitTargetIsRowEmptyRegion
&& m_selectionManager
->selectedItems().isEmpty());
1643 if (rightClick
&& hitTargetIsRowEmptyRegion
) {
1644 // We have a right click outside the icon and text rect but within the hover highlight area
1645 // but it is unclear if this means that a selection rectangle for an item was clicked or the background of the view.
1646 if (m_selectionManager
->selectedItems().contains(m_pressedIndex
.value())) {
1647 // The selection rectangle for an item was clicked
1648 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), screenPos
);
1650 row
->setHovered(false); // Removes the hover highlight so the context menu doesn't look like it applies to the row.
1651 Q_EMIT
viewContextMenuRequested(screenPos
);
1656 switch (m_selectionBehavior
) {
1660 case SingleSelection
:
1661 m_selectionManager
->setSelected(m_pressedIndex
.value());
1664 case MultiSelection
:
1665 if (controlPressed
&& !shiftPressed
&& leftClick
) {
1666 // A left mouse button press is happening on an item while control is pressed. This either means a user wants to:
1667 // - toggle the selection of item(s) or
1668 // - they want to begin a drag on the item(s) to copy them.
1669 // We rule out the latter, if the item is not clicked directly and was unselected previously.
1670 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1671 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1672 if (!row
->iconRect().contains(mappedPos
) && !row
->textRect().contains(mappedPos
) && !pressedItemAlreadySelected
) {
1673 createRubberBand
= true;
1675 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1676 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1677 createRubberBand
= false; // multi selection, don't propagate any further
1678 // This will be the start of an item drag-to-copy operation if the user now moves the mouse before releasing the mouse button.
1680 } else if (!shiftPressed
|| !m_selectionManager
->isAnchoredSelectionActive()) {
1681 // Select the pressed item and start a new anchored selection
1682 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1683 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1693 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), screenPos
);
1695 return !createRubberBand
;
1699 // header right click handling would have been done before this so just normal context
1700 // menu here is fine
1701 Q_EMIT
viewContextMenuRequested(screenPos
);
1708 bool KItemListController::onRelease(const QPointF
&pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
, bool touch
)
1710 const QPointF pressedMousePos
= pos
;
1711 const bool isAboveSelectionToggle
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
);
1712 if (isAboveSelectionToggle
) {
1713 m_selectionTogglePressed
= false;
1717 if (!isAboveSelectionToggle
&& m_selectionTogglePressed
) {
1718 m_selectionManager
->setSelected(m_pressedIndex
.value_or(-1), 1, KItemListSelectionManager::Toggle
);
1719 m_selectionTogglePressed
= false;
1723 const bool controlPressed
= modifiers
& Qt::ControlModifier
;
1724 const bool shiftOrControlPressed
= modifiers
& Qt::ShiftModifier
|| controlPressed
;
1726 const std::optional
<int> index
= m_view
->itemAt(pos
);
1728 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1729 bool rubberBandRelease
= false;
1730 if (rubberBand
->isActive()) {
1731 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1732 rubberBand
->setActive(false);
1733 m_oldSelection
.clear();
1734 m_view
->setAutoScroll(false);
1735 rubberBandRelease
= true;
1736 // We check for actual rubber band drag here: if delta between start and end is less than drag threshold,
1737 // then we have a single click on one of the rows
1738 if ((rubberBand
->endPosition() - rubberBand
->startPosition()).manhattanLength() < QApplication::startDragDistance()) {
1739 rubberBandRelease
= false; // since we're only selecting, unmark rubber band release flag
1740 // m_pressedIndex will have no value if we came from a multi-selection clearing onPress
1741 // in that case, we don't select anything
1742 if (index
.has_value() && m_pressedIndex
.has_value()) {
1743 if (controlPressed
&& m_selectionBehavior
== MultiSelection
) {
1744 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1746 m_selectionManager
->setSelected(index
.value());
1748 if (!m_selectionManager
->isAnchoredSelectionActive()) {
1749 m_selectionManager
->beginAnchoredSelection(index
.value());
1755 if (index
.has_value() && index
== m_pressedIndex
) {
1756 // The release event is done above the same item as the press event
1758 if (m_clearSelectionIfItemsAreNotDragged
) {
1759 // A selected item has been clicked, but no drag operation has been started
1760 // -> clear the rest of the selection.
1761 m_selectionManager
->clearSelection();
1762 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1763 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1766 if (buttons
& Qt::LeftButton
) {
1767 bool emitItemActivated
= true;
1768 if (m_view
->isAboveExpansionToggle(index
.value(), pos
)) {
1769 const bool expanded
= m_model
->isExpanded(index
.value());
1770 m_model
->setExpanded(index
.value(), !expanded
);
1772 Q_EMIT
itemExpansionToggleClicked(index
.value());
1773 emitItemActivated
= false;
1774 } else if (shiftOrControlPressed
&& m_selectionBehavior
!= SingleSelection
) {
1775 // The mouse click should only update the selection, not trigger the item, except when
1776 // we are in single selection mode
1777 emitItemActivated
= false;
1779 const bool singleClickActivation
= m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
;
1780 if (!singleClickActivation
) {
1781 emitItemActivated
= touch
&& !m_selectionMode
;
1783 // activate on single click only if we didn't come from a rubber band release
1784 emitItemActivated
= !rubberBandRelease
;
1787 if (emitItemActivated
) {
1788 Q_EMIT
itemActivated(index
.value());
1790 } else if (buttons
& Qt::MiddleButton
) {
1791 Q_EMIT
itemMiddleClicked(index
.value());
1795 m_pressedMouseGlobalPos
= QPointF();
1796 m_pressedIndex
= std::nullopt
;
1797 m_clearSelectionIfItemsAreNotDragged
= false;
1801 void KItemListController::startRubberBand()
1803 if (m_selectionBehavior
== MultiSelection
) {
1804 QPoint startPos
= m_view
->transform().map(m_view
->scene()->views().first()->mapFromGlobal(m_pressedMouseGlobalPos
.toPoint()));
1805 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1806 startPos
.ry() += m_view
->scrollOffset();
1808 startPos
.rx() += m_view
->scrollOffset();
1811 m_oldSelection
= m_selectionManager
->selectedItems();
1812 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1813 rubberBand
->setStartPosition(startPos
);
1814 rubberBand
->setEndPosition(startPos
);
1815 rubberBand
->setActive(true);
1816 connect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1817 m_view
->setAutoScroll(true);
1821 void KItemListController::slotStateChanged(QScroller::State newState
)
1823 if (newState
== QScroller::Scrolling
) {
1824 m_scrollerIsScrolling
= true;
1825 } else if (newState
== QScroller::Inactive
) {
1826 m_scrollerIsScrolling
= false;
1830 #include "moc_kitemlistcontroller.cpp"