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>
21 #include <QAccessible>
22 #include <QApplication>
25 #include <QGraphicsScene>
26 #include <QGraphicsSceneEvent>
27 #include <QGraphicsView>
30 #include <QTouchEvent>
32 KItemListController::KItemListController(KItemModelBase
* model
, KItemListView
* view
, QObject
* parent
) :
34 m_singleClickActivationEnforced(false),
35 m_selectionTogglePressed(false),
36 m_clearSelectionIfItemsAreNotDragged(false),
37 m_isSwipeGesture(false),
38 m_dragActionOrRightClick(false),
39 m_scrollerIsScrolling(false),
40 m_pinchGestureInProgress(false),
42 m_isTouchEvent(false),
43 m_selectionBehavior(NoSelection
),
44 m_autoActivationBehavior(ActivationAndExpansion
),
45 m_mouseDoubleClickAction(ActivateItemOnly
),
48 m_selectionManager(new KItemListSelectionManager(this)),
49 m_keyboardManager(new KItemListKeyboardSearchManager(this)),
50 m_pressedIndex(std::nullopt
),
52 m_autoActivationTimer(nullptr),
53 m_swipeGesture(Qt::CustomGesture
),
54 m_twoFingerTapGesture(Qt::CustomGesture
),
56 m_keyboardAnchorIndex(-1),
57 m_keyboardAnchorPos(0)
59 connect(m_keyboardManager
, &KItemListKeyboardSearchManager::changeCurrentItem
,
60 this, &KItemListController::slotChangeCurrentItem
);
61 connect(m_selectionManager
, &KItemListSelectionManager::currentChanged
,
62 m_keyboardManager
, &KItemListKeyboardSearchManager::slotCurrentChanged
);
63 connect(m_selectionManager
, &KItemListSelectionManager::selectionChanged
,
64 m_keyboardManager
, &KItemListKeyboardSearchManager::slotSelectionChanged
);
66 m_autoActivationTimer
= new QTimer(this);
67 m_autoActivationTimer
->setSingleShot(true);
68 m_autoActivationTimer
->setInterval(-1);
69 connect(m_autoActivationTimer
, &QTimer::timeout
, this, &KItemListController::slotAutoActivationTimeout
);
74 m_swipeGesture
= QGestureRecognizer::registerRecognizer(new KTwoFingerSwipeRecognizer());
75 m_twoFingerTapGesture
= QGestureRecognizer::registerRecognizer(new KTwoFingerTapRecognizer());
76 view
->grabGesture(m_swipeGesture
);
77 view
->grabGesture(m_twoFingerTapGesture
);
78 view
->grabGesture(Qt::TapGesture
);
79 view
->grabGesture(Qt::TapAndHoldGesture
);
80 view
->grabGesture(Qt::PinchGesture
);
83 KItemListController::~KItemListController()
92 void KItemListController::setModel(KItemModelBase
* model
)
94 if (m_model
== model
) {
98 KItemModelBase
* oldModel
= m_model
;
100 oldModel
->deleteLater();
105 m_model
->setParent(this);
109 m_view
->setModel(m_model
);
112 m_selectionManager
->setModel(m_model
);
114 Q_EMIT
modelChanged(m_model
, oldModel
);
117 KItemModelBase
* KItemListController::model() const
122 KItemListSelectionManager
* KItemListController::selectionManager() const
124 return m_selectionManager
;
127 void KItemListController::setView(KItemListView
* view
)
129 if (m_view
== view
) {
133 KItemListView
* oldView
= m_view
;
135 disconnect(oldView
, &KItemListView::scrollOffsetChanged
, this, &KItemListController::slotViewScrollOffsetChanged
);
136 oldView
->deleteLater();
142 m_view
->setParent(this);
143 m_view
->setController(this);
144 m_view
->setModel(m_model
);
145 connect(m_view
, &KItemListView::scrollOffsetChanged
, this, &KItemListController::slotViewScrollOffsetChanged
);
146 updateExtendedSelectionRegion();
149 Q_EMIT
viewChanged(m_view
, oldView
);
152 KItemListView
* KItemListController::view() const
157 void KItemListController::setSelectionBehavior(SelectionBehavior behavior
)
159 m_selectionBehavior
= behavior
;
160 updateExtendedSelectionRegion();
163 KItemListController::SelectionBehavior
KItemListController::selectionBehavior() const
165 return m_selectionBehavior
;
168 void KItemListController::setAutoActivationBehavior(AutoActivationBehavior behavior
)
170 m_autoActivationBehavior
= behavior
;
173 KItemListController::AutoActivationBehavior
KItemListController::autoActivationBehavior() const
175 return m_autoActivationBehavior
;
178 void KItemListController::setMouseDoubleClickAction(MouseDoubleClickAction action
)
180 m_mouseDoubleClickAction
= action
;
183 KItemListController::MouseDoubleClickAction
KItemListController::mouseDoubleClickAction() const
185 return m_mouseDoubleClickAction
;
188 int KItemListController::indexCloseToMousePressedPosition() const
190 QHashIterator
<KItemListWidget
*, KItemListGroupHeader
*> it(m_view
->m_visibleGroups
);
191 while (it
.hasNext()) {
193 KItemListGroupHeader
*groupHeader
= it
.value();
194 const QPointF mappedToGroup
= groupHeader
->mapFromItem(nullptr, m_pressedMousePos
);
195 if (groupHeader
->contains(mappedToGroup
)) {
196 return it
.key()->index();
202 void KItemListController::setAutoActivationDelay(int delay
)
204 m_autoActivationTimer
->setInterval(delay
);
207 int KItemListController::autoActivationDelay() const
209 return m_autoActivationTimer
->interval();
212 void KItemListController::setSingleClickActivationEnforced(bool singleClick
)
214 m_singleClickActivationEnforced
= singleClick
;
217 bool KItemListController::singleClickActivationEnforced() const
219 return m_singleClickActivationEnforced
;
222 bool KItemListController::keyPressEvent(QKeyEvent
* event
)
224 int index
= m_selectionManager
->currentItem();
225 int key
= event
->key();
227 // Handle the expanding/collapsing of items
228 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
)) {
229 if (key
== Qt::Key_Right
) {
230 if (m_model
->setExpanded(index
, true)) {
233 } else if (key
== Qt::Key_Left
) {
234 if (m_model
->setExpanded(index
, false)) {
240 const bool shiftPressed
= event
->modifiers() & Qt::ShiftModifier
;
241 const bool controlPressed
= event
->modifiers() & Qt::ControlModifier
;
242 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
243 const bool navigationPressed
= key
== Qt::Key_Home
|| key
== Qt::Key_End
||
244 key
== Qt::Key_PageUp
|| key
== Qt::Key_PageDown
||
245 key
== Qt::Key_Up
|| key
== Qt::Key_Down
||
246 key
== Qt::Key_Left
|| key
== Qt::Key_Right
;
248 const int itemCount
= m_model
->count();
250 // For horizontal scroll orientation, transform
251 // the arrow keys to simplify the event handling.
252 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
254 case Qt::Key_Up
: key
= Qt::Key_Left
; break;
255 case Qt::Key_Down
: key
= Qt::Key_Right
; break;
256 case Qt::Key_Left
: key
= Qt::Key_Up
; break;
257 case Qt::Key_Right
: key
= Qt::Key_Down
; break;
262 const bool selectSingleItem
= m_selectionBehavior
!= NoSelection
&& itemCount
== 1 && navigationPressed
;
264 if (selectSingleItem
) {
265 const int current
= m_selectionManager
->currentItem();
266 m_selectionManager
->setSelected(current
);
273 m_keyboardAnchorIndex
= index
;
274 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
278 index
= itemCount
- 1;
279 m_keyboardAnchorIndex
= index
;
280 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
285 const int expandedParentsCount
= m_model
->expandedParentsCount(index
);
286 if (expandedParentsCount
== 0) {
289 // Go to the parent of the current item.
292 } while (index
> 0 && m_model
->expandedParentsCount(index
) == expandedParentsCount
);
294 m_keyboardAnchorIndex
= index
;
295 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
300 if (index
< itemCount
- 1) {
302 m_keyboardAnchorIndex
= index
;
303 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
308 updateKeyboardAnchor();
309 index
= previousRowIndex(index
);
313 updateKeyboardAnchor();
314 index
= nextRowIndex(index
);
318 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
319 // The new current index should correspond to the first item in the current column.
320 int newIndex
= qMax(index
- 1, 0);
321 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() < m_view
->itemRect(index
).topLeft().y()) {
323 newIndex
= qMax(index
- 1, 0);
325 m_keyboardAnchorIndex
= index
;
326 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
328 const qreal currentItemBottom
= m_view
->itemRect(index
).bottomLeft().y();
329 const qreal height
= m_view
->geometry().height();
331 // The new current item should be the first item in the current
332 // column whose itemRect's top coordinate is larger than targetY.
333 const qreal targetY
= currentItemBottom
- height
;
335 updateKeyboardAnchor();
336 int newIndex
= previousRowIndex(index
);
339 updateKeyboardAnchor();
340 newIndex
= previousRowIndex(index
);
341 } while (m_view
->itemRect(newIndex
).topLeft().y() > targetY
&& newIndex
!= index
);
345 case Qt::Key_PageDown
:
346 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
347 // The new current index should correspond to the last item in the current column.
348 int newIndex
= qMin(index
+ 1, m_model
->count() - 1);
349 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() > m_view
->itemRect(index
).topLeft().y()) {
351 newIndex
= qMin(index
+ 1, m_model
->count() - 1);
353 m_keyboardAnchorIndex
= index
;
354 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
356 const qreal currentItemTop
= m_view
->itemRect(index
).topLeft().y();
357 const qreal height
= m_view
->geometry().height();
359 // The new current item should be the last item in the current
360 // column whose itemRect's bottom coordinate is smaller than targetY.
361 const qreal targetY
= currentItemTop
+ height
;
363 updateKeyboardAnchor();
364 int newIndex
= nextRowIndex(index
);
367 updateKeyboardAnchor();
368 newIndex
= nextRowIndex(index
);
369 } while (m_view
->itemRect(newIndex
).bottomLeft().y() < targetY
&& newIndex
!= index
);
374 case Qt::Key_Return
: {
375 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
376 if (selectedItems
.count() >= 2) {
377 Q_EMIT
itemsActivated(selectedItems
);
378 } else if (selectedItems
.count() == 1) {
379 Q_EMIT
itemActivated(selectedItems
.first());
381 Q_EMIT
itemActivated(index
);
387 // Emit the signal itemContextMenuRequested() in case if at least one
388 // item is selected. Otherwise the signal viewContextMenuRequested() will be emitted.
389 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
391 if (selectedItems
.count() >= 2) {
392 const int currentItemIndex
= m_selectionManager
->currentItem();
393 index
= selectedItems
.contains(currentItemIndex
)
394 ? currentItemIndex
: selectedItems
.first();
395 } else if (selectedItems
.count() == 1) {
396 index
= selectedItems
.first();
400 const QRectF contextRect
= m_view
->itemContextRect(index
);
401 const QPointF
pos(m_view
->scene()->views().first()->mapToGlobal(contextRect
.bottomRight().toPoint()));
402 Q_EMIT
itemContextMenuRequested(index
, pos
);
404 Q_EMIT
viewContextMenuRequested(QCursor::pos());
410 if (m_selectionBehavior
!= SingleSelection
) {
411 m_selectionManager
->clearSelection();
413 m_keyboardManager
->cancelSearch();
414 Q_EMIT
escapePressed();
418 if (m_selectionBehavior
== MultiSelection
) {
419 if (controlPressed
) {
420 // Toggle the selection state of the current item.
421 m_selectionManager
->endAnchoredSelection();
422 m_selectionManager
->setSelected(index
, 1, KItemListSelectionManager::Toggle
);
423 m_selectionManager
->beginAnchoredSelection(index
);
426 // Select the current item if it is not selected yet.
427 const int current
= m_selectionManager
->currentItem();
428 if (!m_selectionManager
->isSelected(current
)) {
429 m_selectionManager
->setSelected(current
);
434 Q_FALLTHROUGH(); // fall through to the default case and add the Space to the current search string.
436 m_keyboardManager
->addKeys(event
->text());
437 // Make sure unconsumed events get propagated up the chain. #302329
442 if (m_selectionManager
->currentItem() != index
) {
443 switch (m_selectionBehavior
) {
445 m_selectionManager
->setCurrentItem(index
);
448 case SingleSelection
:
449 m_selectionManager
->setCurrentItem(index
);
450 m_selectionManager
->clearSelection();
451 m_selectionManager
->setSelected(index
, 1);
455 if (controlPressed
) {
456 m_selectionManager
->endAnchoredSelection();
459 m_selectionManager
->setCurrentItem(index
);
461 if (!shiftOrControlPressed
) {
462 m_selectionManager
->clearSelection();
463 m_selectionManager
->setSelected(index
, 1);
467 m_selectionManager
->beginAnchoredSelection(index
);
473 if (navigationPressed
) {
474 m_view
->scrollToItem(index
);
479 void KItemListController::slotChangeCurrentItem(const QString
& text
, bool searchFromNextItem
)
481 if (!m_model
|| m_model
->count() == 0) {
485 if (searchFromNextItem
) {
486 const int currentIndex
= m_selectionManager
->currentItem();
487 index
= m_model
->indexForKeyboardSearch(text
, (currentIndex
+ 1) % m_model
->count());
489 index
= m_model
->indexForKeyboardSearch(text
, 0);
492 m_selectionManager
->setCurrentItem(index
);
494 if (m_selectionBehavior
!= NoSelection
) {
495 m_selectionManager
->replaceSelection(index
);
496 m_selectionManager
->beginAnchoredSelection(index
);
499 m_view
->scrollToItem(index
);
503 void KItemListController::slotAutoActivationTimeout()
505 if (!m_model
|| !m_view
) {
509 const int index
= m_autoActivationTimer
->property("index").toInt();
510 if (index
< 0 || index
>= m_model
->count()) {
514 /* m_view->isUnderMouse() fixes a bug in the Folder-View-Panel and in the
517 * Bug: When you drag a file onto a Folder-View-Item or a Places-Item and
518 * then move away before the auto-activation timeout triggers, than the
519 * item still becomes activated/expanded.
521 * See Bug 293200 and 305783
523 if (m_model
->supportsDropping(index
) && m_view
->isUnderMouse()) {
524 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
)) {
525 const bool expanded
= m_model
->isExpanded(index
);
526 m_model
->setExpanded(index
, !expanded
);
527 } else if (m_autoActivationBehavior
!= ExpansionOnly
) {
528 Q_EMIT
itemActivated(index
);
533 bool KItemListController::inputMethodEvent(QInputMethodEvent
* event
)
539 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent
* event
, const QTransform
& transform
)
543 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& m_isTouchEvent
) {
551 m_pressedMousePos
= transform
.map(event
->pos());
552 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
554 const Qt::MouseButtons buttons
= event
->buttons();
556 if (!onPress(event
->screenPos(), event
->pos(), event
->modifiers(), buttons
)) {
564 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent
* event
, const QTransform
& transform
)
570 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
571 m_view
->m_tapAndHoldIndicator
->setActive(false);
574 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !m_dragActionOrRightClick
&& m_isTouchEvent
) {
578 if (m_pressedIndex
.has_value() && !m_view
->rubberBand()->isActive()) {
579 // Check whether a dragging should be started
580 if (event
->buttons() & Qt::LeftButton
) {
581 const QPointF pos
= transform
.map(event
->pos());
582 if ((pos
- m_pressedMousePos
).manhattanLength() >= QApplication::startDragDistance()) {
583 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
584 // Always assure that the dragged item gets selected. Usually this is already
585 // done on the mouse-press event, but when using the selection-toggle on a
586 // selected item the dragged item is not selected yet.
587 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
589 // A selected item has been clicked to drag all selected items
590 // -> the selection should not be cleared when the mouse button is released.
591 m_clearSelectionIfItemsAreNotDragged
= false;
594 m_mousePress
= false;
598 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
599 if (rubberBand
->isActive()) {
600 QPointF endPos
= transform
.map(event
->pos());
602 // Update the current item.
603 const std::optional
<int> newCurrent
= m_view
->itemAt(endPos
);
604 if (newCurrent
.has_value()) {
605 // It's expected that the new current index is also the new anchor (bug 163451).
606 m_selectionManager
->endAnchoredSelection();
607 m_selectionManager
->setCurrentItem(newCurrent
.value());
608 m_selectionManager
->beginAnchoredSelection(newCurrent
.value());
611 if (m_view
->scrollOrientation() == Qt::Vertical
) {
612 endPos
.ry() += m_view
->scrollOffset();
613 if (m_view
->itemSize().width() < 0) {
614 // Use a special rubberband for views that have only one column and
615 // expand the rubberband to use the whole width of the view.
616 endPos
.setX(m_view
->size().width());
619 endPos
.rx() += m_view
->scrollOffset();
621 rubberBand
->setEndPosition(endPos
);
628 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent
* event
, const QTransform
& transform
)
630 m_mousePress
= false;
631 m_isTouchEvent
= false;
637 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
638 m_view
->m_tapAndHoldIndicator
->setActive(false);
641 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
642 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !rubberBand
->isActive() && m_isTouchEvent
) {
646 Q_EMIT
mouseButtonReleased(m_pressedIndex
.value_or(-1), event
->buttons());
648 return onRelease(transform
.map(event
->pos()), event
->modifiers(), event
->button(), false);
651 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent
* event
, const QTransform
& transform
)
653 const QPointF pos
= transform
.map(event
->pos());
654 const std::optional
<int> index
= m_view
->itemAt(pos
);
656 // Expand item if desired - See Bug 295573
657 if (m_mouseDoubleClickAction
!= ActivateItemOnly
) {
658 if (m_view
&& m_model
&& m_view
->supportsItemExpanding() && m_model
->isExpandable(index
.value_or(-1))) {
659 const bool expanded
= m_model
->isExpanded(index
.value());
660 m_model
->setExpanded(index
.value(), !expanded
);
664 if (event
->button() & Qt::RightButton
) {
665 m_selectionManager
->clearSelection();
666 if (index
.has_value()) {
667 m_selectionManager
->setSelected(index
.value());
668 Q_EMIT
itemContextMenuRequested(index
.value(), event
->screenPos());
670 const QRectF headerBounds
= m_view
->headerBoundaries();
671 if (headerBounds
.contains(event
->pos())) {
672 Q_EMIT
headerContextMenuRequested(event
->screenPos());
674 Q_EMIT
viewContextMenuRequested(event
->screenPos());
680 bool emitItemActivated
= !(m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) &&
681 (event
->button() & Qt::LeftButton
) &&
682 index
.has_value() && index
.value() < m_model
->count();
683 if (emitItemActivated
) {
684 Q_EMIT
itemActivated(index
.value());
689 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
694 DragAndDropHelper::clearUrlListMatchesUrlCache();
699 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
704 m_autoActivationTimer
->stop();
705 m_view
->setAutoScroll(false);
706 m_view
->hideDropIndicator();
708 KItemListWidget
* widget
= hoveredWidget();
710 widget
->setHovered(false);
711 Q_EMIT
itemUnhovered(widget
->index());
716 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
718 if (!m_model
|| !m_view
) {
723 QUrl hoveredDir
= m_model
->directory();
724 KItemListWidget
* oldHoveredWidget
= hoveredWidget();
726 const QPointF pos
= transform
.map(event
->pos());
727 KItemListWidget
* newHoveredWidget
= widgetForPos(pos
);
729 if (oldHoveredWidget
!= newHoveredWidget
) {
730 m_autoActivationTimer
->stop();
732 if (oldHoveredWidget
) {
733 oldHoveredWidget
->setHovered(false);
734 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
738 if (newHoveredWidget
) {
739 bool droppingBetweenItems
= false;
740 if (m_model
->sortRole().isEmpty()) {
741 // The model supports inserting items between other items.
742 droppingBetweenItems
= (m_view
->showDropIndicator(pos
) >= 0);
745 const int index
= newHoveredWidget
->index();
747 if (m_model
->isDir(index
)) {
748 hoveredDir
= m_model
->url(index
);
751 if (!droppingBetweenItems
) {
752 if (m_model
->supportsDropping(index
)) {
753 // Something has been dragged on an item.
754 m_view
->hideDropIndicator();
755 if (!newHoveredWidget
->isHovered()) {
756 newHoveredWidget
->setHovered(true);
757 Q_EMIT
itemHovered(index
);
760 if (!m_autoActivationTimer
->isActive() && m_autoActivationTimer
->interval() >= 0) {
761 m_autoActivationTimer
->setProperty("index", index
);
762 m_autoActivationTimer
->start();
766 m_autoActivationTimer
->stop();
767 if (newHoveredWidget
&& newHoveredWidget
->isHovered()) {
768 newHoveredWidget
->setHovered(false);
769 Q_EMIT
itemUnhovered(index
);
773 m_view
->hideDropIndicator();
776 if (DragAndDropHelper::urlListMatchesUrl(event
->mimeData()->urls(), hoveredDir
)) {
777 event
->setDropAction(Qt::IgnoreAction
);
780 event
->setDropAction(event
->proposedAction());
786 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent
* event
, const QTransform
& transform
)
792 m_autoActivationTimer
->stop();
793 m_view
->setAutoScroll(false);
795 const QPointF pos
= transform
.map(event
->pos());
797 int dropAboveIndex
= -1;
798 if (m_model
->sortRole().isEmpty()) {
799 // The model supports inserting of items between other items.
800 dropAboveIndex
= m_view
->showDropIndicator(pos
);
803 if (dropAboveIndex
>= 0) {
804 // Something has been dropped between two items.
805 m_view
->hideDropIndicator();
806 Q_EMIT
aboveItemDropEvent(dropAboveIndex
, event
);
807 } else if (!event
->mimeData()->hasFormat(m_model
->blacklistItemDropEventMimeType())) {
808 // Something has been dropped on an item or on an empty part of the view.
809 Q_EMIT
itemDropEvent(m_view
->itemAt(pos
).value_or(-1), event
);
812 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropEnd
);
813 QAccessible::updateAccessibility(&accessibilityEvent
);
818 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent
* event
, const QTransform
& transform
)
825 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent
* event
, const QTransform
& transform
)
828 if (!m_model
|| !m_view
) {
832 // We identify the widget whose expansionArea had been hovered before this hoverMoveEvent() triggered.
833 // we can't use hoveredWidget() here (it handles the icon+text rect, not the expansion rect)
834 // like hoveredWidget(), we find the hovered widget for the expansion rect
835 const auto visibleItemListWidgets
= m_view
->visibleItemListWidgets();
836 const auto oldHoveredExpansionWidgetIterator
= std::find_if(visibleItemListWidgets
.begin(), visibleItemListWidgets
.end(), [](auto &widget
) {
837 return widget
->expansionAreaHovered();
839 const auto oldHoveredExpansionWidget
= oldHoveredExpansionWidgetIterator
== visibleItemListWidgets
.end() ?
840 std::nullopt
: std::make_optional(*oldHoveredExpansionWidgetIterator
);
842 const auto unhoverOldHoveredWidget
= [&]() {
843 if (auto oldHoveredWidget
= hoveredWidget(); oldHoveredWidget
) {
844 // handle the text+icon one
845 oldHoveredWidget
->setHovered(false);
846 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
850 const auto unhoverOldExpansionWidget
= [&]() {
851 if (oldHoveredExpansionWidget
) {
852 // then the expansion toggle
853 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
857 const QPointF pos
= transform
.map(event
->pos());
858 if (KItemListWidget
*newHoveredWidget
= widgetForPos(pos
); newHoveredWidget
) {
859 // something got hovered, work out which part and set hover for the appropriate widget
860 const auto mappedPos
= newHoveredWidget
->mapFromItem(m_view
, pos
);
861 const bool isOnExpansionToggle
= newHoveredWidget
->expansionToggleRect().contains(mappedPos
);
863 if (isOnExpansionToggle
) {
864 // make sure we unhover the old one first if old!=new
865 if (oldHoveredExpansionWidget
&& *oldHoveredExpansionWidget
!= newHoveredWidget
) {
866 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
868 // 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)
869 unhoverOldHoveredWidget();
872 newHoveredWidget
->setExpansionAreaHovered(true);
874 // make sure we unhover the old one first if old!=new
875 auto oldHoveredWidget
= hoveredWidget();
876 if (oldHoveredWidget
&& oldHoveredWidget
!= newHoveredWidget
) {
877 oldHoveredWidget
->setHovered(false);
878 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
880 // 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)
881 unhoverOldExpansionWidget();
883 const bool isOverIconAndText
= newHoveredWidget
->iconRect().contains(mappedPos
) || newHoveredWidget
->textRect().contains(mappedPos
);
884 const bool hasMultipleSelection
= m_selectionManager
->selectedItems().count() > 1;
886 if (hasMultipleSelection
&& !isOverIconAndText
) {
887 // In case we have multiple selections, clicking on any row will deselect the selection.
888 // So, as a visual cue for signalling that clicking anywhere won't select, but clear current highlights,
889 // we disable hover of the *row*(i.e. blank space to the right of the icon+text)
891 // (no-op in this branch for masked hover)
893 newHoveredWidget
->setHoverPosition(mappedPos
);
894 if (oldHoveredWidget
!= newHoveredWidget
) {
895 newHoveredWidget
->setHovered(true);
896 Q_EMIT
itemHovered(newHoveredWidget
->index());
901 // unhover any currently hovered expansion and text+icon widgets
902 unhoverOldHoveredWidget();
903 unhoverOldExpansionWidget();
908 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent
* event
, const QTransform
& transform
)
913 m_mousePress
= false;
914 m_isTouchEvent
= false;
916 if (!m_model
|| !m_view
) {
920 const auto widgets
= m_view
->visibleItemListWidgets();
921 for (KItemListWidget
* widget
: widgets
) {
922 if (widget
->isHovered()) {
923 widget
->setHovered(false);
924 Q_EMIT
itemUnhovered(widget
->index());
930 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent
* event
, const QTransform
& transform
)
937 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent
* event
, const QTransform
& transform
)
944 bool KItemListController::gestureEvent(QGestureEvent
* event
, const QTransform
& transform
)
950 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
951 //we use this to get the right QWidget
952 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
954 if (QGesture
* tap
= event
->gesture(Qt::TapGesture
)) {
955 QTapGesture
* tapGesture
= static_cast<QTapGesture
*>(tap
);
956 if (tapGesture
->state() == Qt::GestureStarted
) {
957 tapTriggered(tapGesture
, transform
);
963 bool accepted
= false;
965 if (QGesture
* tap
= event
->gesture(Qt::TapGesture
)) {
966 tapTriggered(static_cast<QTapGesture
*>(tap
), transform
);
969 if (event
->gesture(Qt::TapAndHoldGesture
)) {
970 tapAndHoldTriggered(event
, transform
);
973 if (event
->gesture(Qt::PinchGesture
)) {
974 pinchTriggered(event
, transform
);
977 if (event
->gesture(m_swipeGesture
)) {
978 swipeTriggered(event
, transform
);
981 if (event
->gesture(m_twoFingerTapGesture
)) {
982 twoFingerTapTriggered(event
, transform
);
988 bool KItemListController::touchBeginEvent(QTouchEvent
* event
, const QTransform
& transform
)
993 m_isTouchEvent
= true;
997 void KItemListController::tapTriggered(QTapGesture
* tap
, const QTransform
& transform
)
999 static bool scrollerWasActive
= false;
1001 if (tap
->state() == Qt::GestureStarted
) {
1002 m_dragActionOrRightClick
= false;
1003 m_isSwipeGesture
= false;
1004 m_pinchGestureInProgress
= false;
1005 scrollerWasActive
= m_scrollerIsScrolling
;
1008 if (tap
->state() == Qt::GestureFinished
) {
1009 m_mousePress
= false;
1011 //if at the moment of the gesture start the QScroller was active, the user made the tap
1012 //to stop the QScroller and not to tap on an item
1013 if (scrollerWasActive
) {
1017 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
1018 m_view
->m_tapAndHoldIndicator
->setActive(false);
1021 m_pressedMousePos
= transform
.map(tap
->position());
1022 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1024 if (m_dragActionOrRightClick
) {
1025 onPress(tap
->hotSpot().toPoint(), tap
->position().toPoint(), Qt::NoModifier
, Qt::RightButton
);
1026 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::RightButton
, false);
1027 m_dragActionOrRightClick
= false;
1030 onPress(tap
->hotSpot().toPoint(), tap
->position().toPoint(), Qt::NoModifier
, Qt::LeftButton
);
1031 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::LeftButton
, true);
1033 m_isTouchEvent
= false;
1037 void KItemListController::tapAndHoldTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1040 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
1041 if (!m_isTouchEvent
) {
1045 const QTapAndHoldGesture
* tap
= static_cast<QTapAndHoldGesture
*>(event
->gesture(Qt::TapAndHoldGesture
));
1046 if (tap
->state() == Qt::GestureFinished
) {
1047 //if a pinch gesture is in progress we don't want a TabAndHold gesture
1048 if (m_pinchGestureInProgress
) {
1051 m_pressedMousePos
= transform
.map(event
->mapToGraphicsScene(tap
->position()));
1052 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1054 if (m_pressedIndex
.has_value() && !m_selectionManager
->isSelected(m_pressedIndex
.value())) {
1055 m_selectionManager
->clearSelection();
1056 m_selectionManager
->setSelected(m_pressedIndex
.value());
1057 } else if (!m_pressedIndex
.has_value()) {
1058 m_selectionManager
->clearSelection();
1062 Q_EMIT
scrollerStop();
1064 m_view
->m_tapAndHoldIndicator
->setStartPosition(m_pressedMousePos
);
1065 m_view
->m_tapAndHoldIndicator
->setActive(true);
1067 m_dragActionOrRightClick
= true;
1071 void KItemListController::pinchTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1075 const QPinchGesture
* pinch
= static_cast<QPinchGesture
*>(event
->gesture(Qt::PinchGesture
));
1076 const qreal sensitivityModifier
= 0.2;
1077 static qreal counter
= 0;
1079 if (pinch
->state() == Qt::GestureStarted
) {
1080 m_pinchGestureInProgress
= true;
1083 if (pinch
->state() == Qt::GestureUpdated
) {
1084 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1085 if (m_isSwipeGesture
) {
1088 counter
= counter
+ (pinch
->scaleFactor() - 1);
1089 if (counter
>= sensitivityModifier
) {
1090 Q_EMIT
increaseZoom();
1092 } else if (counter
<= -sensitivityModifier
) {
1093 Q_EMIT
decreaseZoom();
1099 void KItemListController::swipeTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1103 const KTwoFingerSwipe
* swipe
= static_cast<KTwoFingerSwipe
*>(event
->gesture(m_swipeGesture
));
1108 if (swipe
->state() == Qt::GestureStarted
) {
1109 m_isSwipeGesture
= true;
1112 if (swipe
->state() == Qt::GestureCanceled
) {
1113 m_isSwipeGesture
= false;
1116 if (swipe
->state() == Qt::GestureFinished
) {
1117 Q_EMIT
scrollerStop();
1119 if (swipe
->swipeAngle() <= 20 || swipe
->swipeAngle() >= 340) {
1120 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::BackButton
);
1121 } else if (swipe
->swipeAngle() <= 200 && swipe
->swipeAngle() >= 160) {
1122 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::ForwardButton
);
1123 } else if (swipe
->swipeAngle() <= 110 && swipe
->swipeAngle() >= 60) {
1126 m_isSwipeGesture
= true;
1130 void KItemListController::twoFingerTapTriggered(QGestureEvent
* event
, const QTransform
& transform
)
1132 const KTwoFingerTap
* twoTap
= static_cast<KTwoFingerTap
*>(event
->gesture(m_twoFingerTapGesture
));
1138 if (twoTap
->state() == Qt::GestureStarted
) {
1139 m_pressedMousePos
= transform
.map(twoTap
->pos());
1140 m_pressedIndex
= m_view
->itemAt(m_pressedMousePos
);
1141 if (m_pressedIndex
.has_value()) {
1142 onPress(twoTap
->screenPos().toPoint(), twoTap
->pos().toPoint(), Qt::ControlModifier
, Qt::LeftButton
);
1143 onRelease(transform
.map(twoTap
->pos()), Qt::ControlModifier
, Qt::LeftButton
, false);
1149 bool KItemListController::processEvent(QEvent
* event
, const QTransform
& transform
)
1155 switch (event
->type()) {
1156 case QEvent::KeyPress
:
1157 return keyPressEvent(static_cast<QKeyEvent
*>(event
));
1158 case QEvent::InputMethod
:
1159 return inputMethodEvent(static_cast<QInputMethodEvent
*>(event
));
1160 case QEvent::GraphicsSceneMousePress
:
1161 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1162 case QEvent::GraphicsSceneMouseMove
:
1163 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1164 case QEvent::GraphicsSceneMouseRelease
:
1165 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1166 case QEvent::GraphicsSceneMouseDoubleClick
:
1167 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1168 case QEvent::GraphicsSceneWheel
:
1169 return wheelEvent(static_cast<QGraphicsSceneWheelEvent
*>(event
), QTransform());
1170 case QEvent::GraphicsSceneDragEnter
:
1171 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1172 case QEvent::GraphicsSceneDragLeave
:
1173 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1174 case QEvent::GraphicsSceneDragMove
:
1175 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1176 case QEvent::GraphicsSceneDrop
:
1177 return dropEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1178 case QEvent::GraphicsSceneHoverEnter
:
1179 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1180 case QEvent::GraphicsSceneHoverMove
:
1181 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1182 case QEvent::GraphicsSceneHoverLeave
:
1183 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1184 case QEvent::GraphicsSceneResize
:
1185 return resizeEvent(static_cast<QGraphicsSceneResizeEvent
*>(event
), transform
);
1186 case QEvent::Gesture
:
1187 return gestureEvent(static_cast<QGestureEvent
*>(event
), transform
);
1188 case QEvent::TouchBegin
:
1189 return touchBeginEvent(static_cast<QTouchEvent
*>(event
), transform
);
1197 void KItemListController::slotViewScrollOffsetChanged(qreal current
, qreal previous
)
1203 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1204 if (rubberBand
->isActive()) {
1205 const qreal diff
= current
- previous
;
1206 // TODO: Ideally just QCursor::pos() should be used as
1207 // new end-position but it seems there is no easy way
1208 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1209 // (... or I just missed an easy way to do the mapping)
1210 QPointF endPos
= rubberBand
->endPosition();
1211 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1212 endPos
.ry() += diff
;
1214 endPos
.rx() += diff
;
1217 rubberBand
->setEndPosition(endPos
);
1221 void KItemListController::slotRubberBandChanged()
1223 if (!m_view
|| !m_model
|| m_model
->count() <= 0) {
1227 const KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1228 const QPointF startPos
= rubberBand
->startPosition();
1229 const QPointF endPos
= rubberBand
->endPosition();
1230 QRectF rubberBandRect
= QRectF(startPos
, endPos
).normalized();
1232 const bool scrollVertical
= (m_view
->scrollOrientation() == Qt::Vertical
);
1233 if (scrollVertical
) {
1234 rubberBandRect
.translate(0, -m_view
->scrollOffset());
1236 rubberBandRect
.translate(-m_view
->scrollOffset(), 0);
1239 if (!m_oldSelection
.isEmpty()) {
1240 // Clear the old selection that was available before the rubberband has
1241 // been activated in case if no Shift- or Control-key are pressed
1242 const bool shiftOrControlPressed
= QApplication::keyboardModifiers() & Qt::ShiftModifier
||
1243 QApplication::keyboardModifiers() & Qt::ControlModifier
;
1244 if (!shiftOrControlPressed
) {
1245 m_oldSelection
.clear();
1249 KItemSet selectedItems
;
1251 // Select all visible items that intersect with the rubberband
1252 const auto widgets
= m_view
->visibleItemListWidgets();
1253 for (const KItemListWidget
* widget
: widgets
) {
1254 const int index
= widget
->index();
1256 const QRectF widgetRect
= m_view
->itemRect(index
);
1257 if (widgetRect
.intersects(rubberBandRect
)) {
1258 const QRectF iconRect
= widget
->iconRect().translated(widgetRect
.topLeft());
1259 const QRectF textRect
= widget
->textRect().translated(widgetRect
.topLeft());
1260 if (iconRect
.intersects(rubberBandRect
) || textRect
.intersects(rubberBandRect
)) {
1261 selectedItems
.insert(index
);
1266 // Select all invisible items that intersect with the rubberband. Instead of
1267 // iterating all items only the area which might be touched by the rubberband
1269 const bool increaseIndex
= scrollVertical
?
1270 startPos
.y() > endPos
.y(): startPos
.x() > endPos
.x();
1272 int index
= increaseIndex
? m_view
->lastVisibleIndex() + 1 : m_view
->firstVisibleIndex() - 1;
1273 bool selectionFinished
= false;
1275 const QRectF widgetRect
= m_view
->itemRect(index
);
1276 if (widgetRect
.intersects(rubberBandRect
)) {
1277 selectedItems
.insert(index
);
1280 if (increaseIndex
) {
1282 selectionFinished
= (index
>= m_model
->count()) ||
1283 ( scrollVertical
&& widgetRect
.top() > rubberBandRect
.bottom()) ||
1284 (!scrollVertical
&& widgetRect
.left() > rubberBandRect
.right());
1287 selectionFinished
= (index
< 0) ||
1288 ( scrollVertical
&& widgetRect
.bottom() < rubberBandRect
.top()) ||
1289 (!scrollVertical
&& widgetRect
.right() < rubberBandRect
.left());
1291 } while (!selectionFinished
);
1293 if (QApplication::keyboardModifiers() & Qt::ControlModifier
) {
1294 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1295 // Therefore, the new selection contains:
1296 // 1. All previously selected items which are not inside the rubberband, and
1297 // 2. all items inside the rubberband which have not been selected previously.
1298 m_selectionManager
->setSelectedItems(m_oldSelection
^ selectedItems
);
1301 m_selectionManager
->setSelectedItems(selectedItems
+ m_oldSelection
);
1305 void KItemListController::startDragging()
1307 if (!m_view
|| !m_model
) {
1311 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
1312 if (selectedItems
.isEmpty()) {
1316 QMimeData
* data
= m_model
->createMimeData(selectedItems
);
1321 // The created drag object will be owned and deleted
1322 // by QApplication::activeWindow().
1323 QDrag
* drag
= new QDrag(QApplication::activeWindow());
1324 drag
->setMimeData(data
);
1326 const QPixmap pixmap
= m_view
->createDragPixmap(selectedItems
);
1327 drag
->setPixmap(pixmap
);
1329 const QPoint
hotSpot((pixmap
.width() / pixmap
.devicePixelRatio()) / 2, 0);
1330 drag
->setHotSpot(hotSpot
);
1332 drag
->exec(Qt::MoveAction
| Qt::CopyAction
| Qt::LinkAction
, Qt::CopyAction
);
1334 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropStart
);
1335 QAccessible::updateAccessibility(&accessibilityEvent
);
1338 KItemListWidget
* KItemListController::hoveredWidget() const
1342 const auto widgets
= m_view
->visibleItemListWidgets();
1343 for (KItemListWidget
* widget
: widgets
) {
1344 if (widget
->isHovered()) {
1352 KItemListWidget
* KItemListController::widgetForPos(const QPointF
& pos
) const
1356 const auto widgets
= m_view
->visibleItemListWidgets();
1357 for (KItemListWidget
* widget
: widgets
) {
1358 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1359 if (widget
->contains(mappedPos
) || widget
->selectionRect().contains(mappedPos
)) {
1367 void KItemListController::updateKeyboardAnchor()
1369 const bool validAnchor
= m_keyboardAnchorIndex
>= 0 &&
1370 m_keyboardAnchorIndex
< m_model
->count() &&
1371 keyboardAnchorPos(m_keyboardAnchorIndex
) == m_keyboardAnchorPos
;
1373 const int index
= m_selectionManager
->currentItem();
1374 m_keyboardAnchorIndex
= index
;
1375 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
1379 int KItemListController::nextRowIndex(int index
) const
1381 if (m_keyboardAnchorIndex
< 0) {
1385 const int maxIndex
= m_model
->count() - 1;
1386 if (index
== maxIndex
) {
1390 // Calculate the index of the last column inside the row of the current index
1391 int lastColumnIndex
= index
;
1392 while (keyboardAnchorPos(lastColumnIndex
+ 1) > keyboardAnchorPos(lastColumnIndex
)) {
1394 if (lastColumnIndex
>= maxIndex
) {
1399 // Based on the last column index go to the next row and calculate the nearest index
1400 // that is below the current index
1401 int nextRowIndex
= lastColumnIndex
+ 1;
1402 int searchIndex
= nextRowIndex
;
1403 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(nextRowIndex
));
1404 while (searchIndex
< maxIndex
&& keyboardAnchorPos(searchIndex
+ 1) > keyboardAnchorPos(searchIndex
)) {
1406 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1407 if (searchDiff
< minDiff
) {
1408 minDiff
= searchDiff
;
1409 nextRowIndex
= searchIndex
;
1413 return nextRowIndex
;
1416 int KItemListController::previousRowIndex(int index
) const
1418 if (m_keyboardAnchorIndex
< 0 || index
== 0) {
1422 // Calculate the index of the first column inside the row of the current index
1423 int firstColumnIndex
= index
;
1424 while (keyboardAnchorPos(firstColumnIndex
- 1) < keyboardAnchorPos(firstColumnIndex
)) {
1426 if (firstColumnIndex
<= 0) {
1431 // Based on the first column index go to the previous row and calculate the nearest index
1432 // that is above the current index
1433 int previousRowIndex
= firstColumnIndex
- 1;
1434 int searchIndex
= previousRowIndex
;
1435 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(previousRowIndex
));
1436 while (searchIndex
> 0 && keyboardAnchorPos(searchIndex
- 1) < keyboardAnchorPos(searchIndex
)) {
1438 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1439 if (searchDiff
< minDiff
) {
1440 minDiff
= searchDiff
;
1441 previousRowIndex
= searchIndex
;
1445 return previousRowIndex
;
1448 qreal
KItemListController::keyboardAnchorPos(int index
) const
1450 const QRectF itemRect
= m_view
->itemRect(index
);
1451 if (!itemRect
.isEmpty()) {
1452 return (m_view
->scrollOrientation() == Qt::Vertical
) ? itemRect
.x() : itemRect
.y();
1458 void KItemListController::updateExtendedSelectionRegion()
1461 const bool extend
= (m_selectionBehavior
!= MultiSelection
);
1462 KItemListStyleOption option
= m_view
->styleOption();
1463 if (option
.extendedSelectionRegion
!= extend
) {
1464 option
.extendedSelectionRegion
= extend
;
1465 m_view
->setStyleOption(option
);
1470 bool KItemListController::onPress(const QPoint
& screenPos
, const QPointF
& pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
)
1472 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), buttons
);
1474 if (buttons
& (Qt::BackButton
| Qt::ForwardButton
)) {
1475 // Do not select items when clicking the back/forward buttons, see
1476 // https://bugs.kde.org/show_bug.cgi?id=327412.
1480 if (m_view
->isAboveExpansionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
)) {
1481 m_selectionManager
->endAnchoredSelection();
1482 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1483 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1487 m_selectionTogglePressed
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
);
1488 if (m_selectionTogglePressed
) {
1489 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1490 // The previous anchored selection has been finished already in
1491 // KItemListSelectionManager::setSelected(). We can safely change
1492 // the current item and start a new anchored selection now.
1493 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1494 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1498 const bool shiftPressed
= modifiers
& Qt::ShiftModifier
;
1499 const bool controlPressed
= modifiers
& Qt::ControlModifier
;
1500 const bool rightClick
= buttons
& Qt::RightButton
;
1502 // The previous selection is cleared if either
1503 // 1. The selection mode is SingleSelection, or
1504 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1505 // a) Shift or Control are pressed.
1506 // b) The clicked item is selected already. In that case, the user might want to:
1507 // - start dragging multiple items, or
1508 // - open the context menu and perform an action for all selected items.
1509 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
1510 const bool pressedItemAlreadySelected
= m_pressedIndex
.has_value() && m_selectionManager
->isSelected(m_pressedIndex
.value());
1511 const bool clearSelection
= m_selectionBehavior
== SingleSelection
||
1512 (!shiftOrControlPressed
&& !pressedItemAlreadySelected
);
1515 // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller.
1516 if (clearSelection
) {
1517 const int selectedItemsCount
= m_selectionManager
->selectedItems().count();
1518 m_selectionManager
->clearSelection();
1519 // clear and bail when we got an existing multi-selection
1520 if (selectedItemsCount
> 1 && m_pressedIndex
.has_value()) {
1521 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1522 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1523 if (pressedItemAlreadySelected
|| row
->iconRect().contains(mappedPos
) || row
->textRect().contains(mappedPos
)) {
1524 // we are indeed inside the text/icon rect, keep m_pressedIndex what it is
1525 // and short-circuit for single-click activation (it will then propagate to onRelease and activate the item)
1526 // or we just keep going for double-click activation
1527 if (m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) {
1528 if (!pressedItemAlreadySelected
) {
1529 // An unselected item was clicked directly while deselecting multiple other items so we select it.
1530 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1531 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1532 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1534 return true; // event handled, don't create rubber band
1537 // we're not inside the text/icon rect, as we've already cleared the selection
1538 // we can just stop here and make sure handlers down the line (i.e. onRelease) don't activate
1539 m_pressedIndex
.reset();
1540 // we don't stop event propagation and proceed to create a rubber band and let onRelease
1541 // decide (based on m_pressedIndex) whether we're in a drag (drag => new rubber band, click => don't select the item)
1545 } else if (pressedItemAlreadySelected
&& !shiftOrControlPressed
&& (buttons
& Qt::LeftButton
)) {
1546 // The user might want to start dragging multiple items, but if he clicks the item
1547 // in order to trigger it instead, the other selected items must be deselected.
1548 // However, we do not know yet what the user is going to do.
1549 // -> remember that the user pressed an item which had been selected already and
1550 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1551 m_clearSelectionIfItemsAreNotDragged
= true;
1553 if (m_selectionManager
->selectedItems().count() == 1 && m_view
->isAboveText(m_pressedIndex
.value_or(-1), m_pressedMousePos
)) {
1554 Q_EMIT
selectedItemTextPressed(m_pressedIndex
.value_or(-1));
1558 if (!shiftPressed
) {
1559 // Finish the anchored selection before the current index is changed
1560 m_selectionManager
->endAnchoredSelection();
1565 // Do header hit check and short circuit before commencing any state changing effects
1566 if (m_view
->headerBoundaries().contains(pos
)) {
1567 Q_EMIT
headerContextMenuRequested(screenPos
);
1571 // Stop rubber band from persisting after right-clicks
1572 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1573 if (rubberBand
->isActive()) {
1574 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1575 rubberBand
->setActive(false);
1576 m_view
->setAutoScroll(false);
1580 if (m_pressedIndex
.has_value()) {
1581 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1582 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
1583 const bool hitTargetIsRowEmptyRegion
= !row
->contains(row
->mapFromItem(m_view
, pos
));
1584 // again, when this method returns false, a rubberBand selection is created as the event is not consumed;
1585 // createRubberBand here tells us whether to return true or false.
1586 bool createRubberBand
= (hitTargetIsRowEmptyRegion
&& m_selectionManager
->selectedItems().isEmpty());
1588 if (rightClick
&& hitTargetIsRowEmptyRegion
) {
1589 // we got a right click outside the text rect, default to action on the current url and not the pressed item
1590 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), screenPos
);
1594 switch (m_selectionBehavior
) {
1598 case SingleSelection
:
1599 m_selectionManager
->setSelected(m_pressedIndex
.value());
1602 case MultiSelection
:
1603 if (controlPressed
&& !shiftPressed
) {
1604 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1605 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1606 createRubberBand
= false; // multi selection, don't propagate any further
1607 } else if (!shiftPressed
|| !m_selectionManager
->isAnchoredSelectionActive()) {
1608 // Select the pressed item and start a new anchored selection
1609 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1610 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1620 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), screenPos
);
1622 return !createRubberBand
;
1626 // header right click handling would have been done before this so just normal context
1627 // menu here is fine
1628 Q_EMIT
viewContextMenuRequested(screenPos
);
1635 bool KItemListController::onRelease(const QPointF
& pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
, bool touch
)
1637 const bool isAboveSelectionToggle
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), m_pressedMousePos
);
1638 if (isAboveSelectionToggle
) {
1639 m_selectionTogglePressed
= false;
1643 if (!isAboveSelectionToggle
&& m_selectionTogglePressed
) {
1644 m_selectionManager
->setSelected(m_pressedIndex
.value_or(-1), 1, KItemListSelectionManager::Toggle
);
1645 m_selectionTogglePressed
= false;
1649 const bool controlPressed
= modifiers
& Qt::ControlModifier
;
1650 const bool shiftOrControlPressed
= modifiers
& Qt::ShiftModifier
||
1653 const std::optional
<int> index
= m_view
->itemAt(pos
);
1655 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1656 bool rubberBandRelease
= false;
1657 if (rubberBand
->isActive()) {
1658 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1659 rubberBand
->setActive(false);
1660 m_oldSelection
.clear();
1661 m_view
->setAutoScroll(false);
1662 rubberBandRelease
= true;
1663 // We check for actual rubber band drag here: if delta between start and end is less than drag threshold,
1664 // then we have a single click on one of the rows
1665 if ((rubberBand
->endPosition() - rubberBand
->startPosition()).manhattanLength() < QApplication::startDragDistance()) {
1666 rubberBandRelease
= false; // since we're only selecting, unmark rubber band release flag
1667 // m_pressedIndex will have no value if we came from a multi-selection clearing onPress
1668 // in that case, we don't select anything
1669 if (index
.has_value() && m_pressedIndex
.has_value()) {
1670 if (controlPressed
&& m_selectionBehavior
== MultiSelection
) {
1671 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1673 m_selectionManager
->setSelected(index
.value());
1675 if (!m_selectionManager
->isAnchoredSelectionActive()) {
1676 m_selectionManager
->beginAnchoredSelection(index
.value());
1682 if (index
.has_value() && index
== m_pressedIndex
) {
1683 // The release event is done above the same item as the press event
1685 if (m_clearSelectionIfItemsAreNotDragged
) {
1686 // A selected item has been clicked, but no drag operation has been started
1687 // -> clear the rest of the selection.
1688 m_selectionManager
->clearSelection();
1689 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1690 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1693 if (buttons
& Qt::LeftButton
) {
1694 bool emitItemActivated
= true;
1695 if (m_view
->isAboveExpansionToggle(index
.value(), pos
)) {
1696 const bool expanded
= m_model
->isExpanded(index
.value());
1697 m_model
->setExpanded(index
.value(), !expanded
);
1699 Q_EMIT
itemExpansionToggleClicked(index
.value());
1700 emitItemActivated
= false;
1701 } else if (shiftOrControlPressed
&& m_selectionBehavior
!= SingleSelection
) {
1702 // The mouse click should only update the selection, not trigger the item, except when
1703 // we are in single selection mode
1704 emitItemActivated
= false;
1706 const bool singleClickActivation
= m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
;
1707 if (!singleClickActivation
) {
1708 emitItemActivated
= touch
;
1710 // activate on single click only if we didn't come from a rubber band release
1711 emitItemActivated
= !rubberBandRelease
;
1714 if (emitItemActivated
) {
1715 Q_EMIT
itemActivated(index
.value());
1717 } else if (buttons
& Qt::MiddleButton
) {
1718 Q_EMIT
itemMiddleClicked(index
.value());
1722 m_pressedMousePos
= QPointF();
1723 m_pressedIndex
= std::nullopt
;
1724 m_clearSelectionIfItemsAreNotDragged
= false;
1728 void KItemListController::startRubberBand()
1730 if (m_selectionBehavior
== MultiSelection
) {
1731 QPointF startPos
= m_pressedMousePos
;
1732 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1733 startPos
.ry() += m_view
->scrollOffset();
1734 if (m_view
->itemSize().width() < 0) {
1735 // Use a special rubberband for views that have only one column and
1736 // expand the rubberband to use the whole width of the view.
1740 startPos
.rx() += m_view
->scrollOffset();
1743 m_oldSelection
= m_selectionManager
->selectedItems();
1744 KItemListRubberBand
* rubberBand
= m_view
->rubberBand();
1745 rubberBand
->setStartPosition(startPos
);
1746 rubberBand
->setEndPosition(startPos
);
1747 rubberBand
->setActive(true);
1748 connect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1749 m_view
->setAutoScroll(true);
1753 void KItemListController::slotStateChanged(QScroller::State newState
)
1755 if (newState
== QScroller::Scrolling
) {
1756 m_scrollerIsScrolling
= true;
1757 } else if (newState
== QScroller::Inactive
) {
1758 m_scrollerIsScrolling
= false;