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 // For right to left languages, exchange right and left arrow keys.
299 if (m_view
->layoutDirection() == Qt::RightToLeft
) {
312 const bool selectSingleItem
= m_selectionBehavior
!= NoSelection
&& itemCount
== 1 && navigationPressed
;
314 if (selectSingleItem
) {
315 const int current
= m_selectionManager
->currentItem();
316 m_selectionManager
->setSelected(current
);
323 m_keyboardAnchorIndex
= index
;
324 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
328 index
= itemCount
- 1;
329 m_keyboardAnchorIndex
= index
;
330 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
335 const int expandedParentsCount
= m_model
->expandedParentsCount(index
);
336 if (expandedParentsCount
== 0) {
339 // Go to the parent of the current item.
342 } while (index
> 0 && m_model
->expandedParentsCount(index
) == expandedParentsCount
);
344 m_keyboardAnchorIndex
= index
;
345 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
350 if (index
< itemCount
- 1) {
352 m_keyboardAnchorIndex
= index
;
353 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
358 updateKeyboardAnchor();
359 if (shiftPressed
&& !m_selectionManager
->isAnchoredSelectionActive() && m_selectionManager
->isSelected(index
)) {
360 m_selectionManager
->beginAnchoredSelection(index
);
362 index
= previousRowIndex(index
);
366 updateKeyboardAnchor();
367 if (shiftPressed
&& !m_selectionManager
->isAnchoredSelectionActive() && m_selectionManager
->isSelected(index
)) {
368 m_selectionManager
->beginAnchoredSelection(index
);
370 index
= nextRowIndex(index
);
374 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
375 // The new current index should correspond to the first item in the current column.
376 int newIndex
= qMax(index
- 1, 0);
377 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() < m_view
->itemRect(index
).topLeft().y()) {
379 newIndex
= qMax(index
- 1, 0);
381 m_keyboardAnchorIndex
= index
;
382 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
384 const qreal currentItemBottom
= m_view
->itemRect(index
).bottomLeft().y();
385 const qreal height
= m_view
->geometry().height();
387 // The new current item should be the first item in the current
388 // column whose itemRect's top coordinate is larger than targetY.
389 const qreal targetY
= currentItemBottom
- height
;
391 updateKeyboardAnchor();
392 int newIndex
= previousRowIndex(index
);
395 updateKeyboardAnchor();
396 newIndex
= previousRowIndex(index
);
397 } while (m_view
->itemRect(newIndex
).topLeft().y() > targetY
&& newIndex
!= index
);
401 case Qt::Key_PageDown
:
402 if (m_view
->scrollOrientation() == Qt::Horizontal
) {
403 // The new current index should correspond to the last item in the current column.
404 int newIndex
= qMin(index
+ 1, m_model
->count() - 1);
405 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() > m_view
->itemRect(index
).topLeft().y()) {
407 newIndex
= qMin(index
+ 1, m_model
->count() - 1);
409 m_keyboardAnchorIndex
= index
;
410 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
412 const qreal currentItemTop
= m_view
->itemRect(index
).topLeft().y();
413 const qreal height
= m_view
->geometry().height();
415 // The new current item should be the last item in the current
416 // column whose itemRect's bottom coordinate is smaller than targetY.
417 const qreal targetY
= currentItemTop
+ height
;
419 updateKeyboardAnchor();
420 int newIndex
= nextRowIndex(index
);
423 updateKeyboardAnchor();
424 newIndex
= nextRowIndex(index
);
425 } while (m_view
->itemRect(newIndex
).bottomLeft().y() < targetY
&& newIndex
!= index
);
430 case Qt::Key_Return
: {
431 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
432 if (selectedItems
.count() >= 2) {
433 Q_EMIT
itemsActivated(selectedItems
);
434 } else if (selectedItems
.count() == 1) {
435 Q_EMIT
itemActivated(selectedItems
.first());
437 Q_EMIT
itemActivated(index
);
443 if (m_selectionMode
) {
444 Q_EMIT
selectionModeChangeRequested(false);
445 } else if (m_selectionBehavior
!= SingleSelection
) {
446 m_selectionManager
->clearSelection();
448 m_keyboardManager
->cancelSearch();
449 Q_EMIT
escapePressed();
453 if (m_selectionBehavior
== MultiSelection
) {
454 if (controlPressed
) {
455 // Toggle the selection state of the current item.
456 m_selectionManager
->endAnchoredSelection();
457 m_selectionManager
->setSelected(index
, 1, KItemListSelectionManager::Toggle
);
458 m_selectionManager
->beginAnchoredSelection(index
);
461 // Select the current item if it is not selected yet.
462 const int current
= m_selectionManager
->currentItem();
463 if (!m_selectionManager
->isSelected(current
)) {
464 m_selectionManager
->setSelected(current
);
469 Q_FALLTHROUGH(); // fall through to the default case and add the Space to the current search string.
471 m_keyboardManager
->addKeys(event
->text());
472 // Make sure unconsumed events get propagated up the chain. #302329
477 if (m_selectionManager
->currentItem() != index
) {
478 switch (m_selectionBehavior
) {
480 m_selectionManager
->setCurrentItem(index
);
483 case SingleSelection
:
484 m_selectionManager
->setCurrentItem(index
);
485 m_selectionManager
->clearSelection();
486 m_selectionManager
->setSelected(index
, 1);
490 if (controlPressed
) {
491 m_selectionManager
->endAnchoredSelection();
494 m_selectionManager
->setCurrentItem(index
);
496 if (!shiftOrControlPressed
) {
497 m_selectionManager
->clearSelection();
498 m_selectionManager
->setSelected(index
, 1);
502 m_selectionManager
->beginAnchoredSelection(index
);
508 if (navigationPressed
) {
509 m_view
->scrollToItem(index
);
514 void KItemListController::slotChangeCurrentItem(const QString
&text
, bool searchFromNextItem
)
516 if (!m_model
|| m_model
->count() == 0) {
520 if (searchFromNextItem
) {
521 const int currentIndex
= m_selectionManager
->currentItem();
522 index
= m_model
->indexForKeyboardSearch(text
, (currentIndex
+ 1) % m_model
->count());
524 index
= m_model
->indexForKeyboardSearch(text
, 0);
527 m_selectionManager
->setCurrentItem(index
);
529 if (m_selectionBehavior
!= NoSelection
) {
530 m_selectionManager
->replaceSelection(index
);
531 m_selectionManager
->beginAnchoredSelection(index
);
534 m_view
->scrollToItem(index
, KItemListView::ViewItemPosition::Beginning
);
538 void KItemListController::slotAutoActivationTimeout()
540 if (!m_model
|| !m_view
) {
544 const int index
= m_autoActivationTimer
->property("index").toInt();
545 if (index
< 0 || index
>= m_model
->count()) {
549 /* m_view->isUnderMouse() fixes a bug in the Folder-View-Panel and in the
552 * Bug: When you drag a file onto a Folder-View-Item or a Places-Item and
553 * then move away before the auto-activation timeout triggers, than the
554 * item still becomes activated/expanded.
556 * See Bug 293200 and 305783
558 if (m_view
->isUnderMouse()) {
559 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
)) {
560 const bool expanded
= m_model
->isExpanded(index
);
561 m_model
->setExpanded(index
, !expanded
);
562 } else if (m_autoActivationBehavior
!= ExpansionOnly
) {
563 Q_EMIT
itemActivated(index
);
568 bool KItemListController::inputMethodEvent(QInputMethodEvent
*event
)
574 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
577 m_pressedMouseGlobalPos
= event
->screenPos();
579 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& m_isTouchEvent
) {
587 const QPointF pressedMousePos
= transform
.map(event
->pos());
588 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
590 const Qt::MouseButtons buttons
= event
->buttons();
592 if (!onPress(event
->screenPos(), event
->pos(), event
->modifiers(), buttons
)) {
600 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
606 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
607 m_view
->m_tapAndHoldIndicator
->setActive(false);
610 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !m_dragActionOrRightClick
&& m_isTouchEvent
) {
614 if (m_pressedIndex
.has_value() && !m_view
->rubberBand()->isActive()) {
615 // Check whether a dragging should be started
616 if (event
->buttons() & Qt::LeftButton
) {
617 const auto distance
= (event
->screenPos() - m_pressedMouseGlobalPos
).manhattanLength();
618 if (distance
>= QApplication::startDragDistance()) {
619 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
620 // Always assure that the dragged item gets selected. Usually this is already
621 // done on the mouse-press event, but when using the selection-toggle on a
622 // selected item the dragged item is not selected yet.
623 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
625 // A selected item has been clicked to drag all selected items
626 // -> the selection should not be cleared when the mouse button is released.
627 m_clearSelectionIfItemsAreNotDragged
= false;
630 m_mousePress
= false;
634 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
635 if (rubberBand
->isActive()) {
636 QPointF endPos
= transform
.map(event
->pos());
638 // Update the current item.
639 const std::optional
<int> newCurrent
= m_view
->itemAt(endPos
);
640 if (newCurrent
.has_value()) {
641 // It's expected that the new current index is also the new anchor (bug 163451).
642 m_selectionManager
->endAnchoredSelection();
643 m_selectionManager
->setCurrentItem(newCurrent
.value());
644 m_selectionManager
->beginAnchoredSelection(newCurrent
.value());
647 if (m_view
->scrollOrientation() == Qt::Vertical
) {
648 endPos
.ry() += m_view
->scrollOffset();
650 endPos
.rx() += m_view
->scrollOffset();
652 rubberBand
->setEndPosition(endPos
);
659 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
661 m_mousePress
= false;
662 m_isTouchEvent
= false;
668 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
669 m_view
->m_tapAndHoldIndicator
->setActive(false);
672 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
673 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !rubberBand
->isActive() && m_isTouchEvent
) {
677 Q_EMIT
mouseButtonReleased(m_pressedIndex
.value_or(-1), event
->buttons());
679 return onRelease(transform
.map(event
->pos()), event
->modifiers(), event
->button(), false);
682 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
684 const QPointF pos
= transform
.map(event
->pos());
685 const std::optional
<int> index
= m_view
->itemAt(pos
);
687 // Expand item if desired - See Bug 295573
688 if (m_mouseDoubleClickAction
!= ActivateItemOnly
) {
689 if (m_view
&& m_model
&& m_view
->supportsItemExpanding() && m_model
->isExpandable(index
.value_or(-1))) {
690 const bool expanded
= m_model
->isExpanded(index
.value());
691 m_model
->setExpanded(index
.value(), !expanded
);
695 if (event
->button() & Qt::RightButton
) {
699 bool emitItemActivated
= !(m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
)
700 && (event
->button() & Qt::LeftButton
) && index
.has_value() && index
.value() < m_model
->count();
701 if (emitItemActivated
) {
702 Q_EMIT
itemActivated(index
.value());
707 bool KItemListController::contextMenuEvent(QContextMenuEvent
*event
)
709 if (event
->reason() == QContextMenuEvent::Keyboard
) {
710 // Emit the signal itemContextMenuRequested() if at least one item is selected.
711 // Otherwise the signal viewContextMenuRequested() will be emitted.
712 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
714 if (selectedItems
.count() >= 2) {
715 const int currentItemIndex
= m_selectionManager
->currentItem();
716 index
= selectedItems
.contains(currentItemIndex
) ? currentItemIndex
: selectedItems
.first();
717 } else if (selectedItems
.count() == 1) {
718 index
= selectedItems
.first();
722 const QRectF contextRect
= m_view
->itemContextRect(index
);
723 const QPointF
pos(m_view
->scene()->views().first()->mapToGlobal(contextRect
.bottomRight().toPoint()));
724 Q_EMIT
itemContextMenuRequested(index
, pos
);
726 Q_EMIT
viewContextMenuRequested(event
->globalPos());
731 const auto pos
= event
->pos();
732 const auto globalPos
= event
->globalPos();
734 if (m_view
->headerBoundaries().contains(pos
)) {
735 Q_EMIT
headerContextMenuRequested(globalPos
);
739 const auto pressedItem
= m_view
->itemAt(pos
);
740 // We only open a context menu for the pressed item if it is selected.
741 // That's because the same click might have de-selected the item or because the press was only in the row of the item but not on it.
742 if (pressedItem
&& m_selectionManager
->selectedItems().contains(pressedItem
.value())) {
743 // The selection rectangle for an item was clicked
744 Q_EMIT
itemContextMenuRequested(m_pressedIndex
.value(), globalPos
);
748 // Remove any hover highlights so the context menu doesn't look like it applies to a row.
749 const auto widgets
= m_view
->visibleItemListWidgets();
750 for (KItemListWidget
*widget
: widgets
) {
751 if (widget
->isHovered()) {
752 widget
->setHovered(false);
753 Q_EMIT
itemUnhovered(widget
->index());
756 Q_EMIT
viewContextMenuRequested(globalPos
);
760 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
765 DragAndDropHelper::clearUrlListMatchesUrlCache();
770 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
775 m_autoActivationTimer
->stop();
776 m_view
->setAutoScroll(false);
777 m_view
->hideDropIndicator();
779 KItemListWidget
*widget
= hoveredWidget();
781 widget
->setHovered(false);
782 Q_EMIT
itemUnhovered(widget
->index());
787 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
789 if (!m_model
|| !m_view
) {
793 QUrl hoveredDir
= m_model
->directory();
794 KItemListWidget
*oldHoveredWidget
= hoveredWidget();
796 const QPointF pos
= transform
.map(event
->pos());
797 KItemListWidget
*newHoveredWidget
= widgetForDropPos(pos
);
800 if (oldHoveredWidget
!= newHoveredWidget
) {
801 m_autoActivationTimer
->stop();
803 if (oldHoveredWidget
) {
804 oldHoveredWidget
->setHovered(false);
805 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
809 if (newHoveredWidget
) {
810 bool droppingBetweenItems
= false;
811 if (m_model
->sortRole().isEmpty()) {
812 // The model supports inserting items between other items.
813 droppingBetweenItems
= (m_view
->showDropIndicator(pos
) >= 0);
816 index
= newHoveredWidget
->index();
818 if (m_model
->isDir(index
)) {
819 hoveredDir
= m_model
->url(index
);
822 if (!droppingBetweenItems
) {
823 // Something has been dragged on an item.
824 m_view
->hideDropIndicator();
825 if (!newHoveredWidget
->isHovered()) {
826 newHoveredWidget
->setHovered(true);
827 Q_EMIT
itemHovered(index
);
830 if (!m_autoActivationTimer
->isActive() && m_autoActivationTimer
->interval() >= 0) {
831 m_autoActivationTimer
->setProperty("index", index
);
832 m_autoActivationTimer
->start();
833 newHoveredWidget
->startActivateSoonAnimation(m_autoActivationTimer
->remainingTime());
836 m_autoActivationTimer
->stop();
837 if (newHoveredWidget
&& newHoveredWidget
->isHovered()) {
838 newHoveredWidget
->setHovered(false);
839 Q_EMIT
itemUnhovered(index
);
843 m_view
->hideDropIndicator();
846 if (DragAndDropHelper::urlListMatchesUrl(event
->mimeData()->urls(), hoveredDir
)) {
847 event
->setDropAction(Qt::IgnoreAction
);
850 if (m_model
->supportsDropping(index
)) {
851 event
->setDropAction(event
->proposedAction());
854 event
->setDropAction(Qt::IgnoreAction
);
861 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
867 m_autoActivationTimer
->stop();
868 m_view
->setAutoScroll(false);
870 const QPointF pos
= transform
.map(event
->pos());
872 int dropAboveIndex
= -1;
873 if (m_model
->sortRole().isEmpty()) {
874 // The model supports inserting of items between other items.
875 dropAboveIndex
= m_view
->showDropIndicator(pos
);
878 if (dropAboveIndex
>= 0) {
879 // Something has been dropped between two items.
880 m_view
->hideDropIndicator();
881 Q_EMIT
aboveItemDropEvent(dropAboveIndex
, event
);
882 } else if (!event
->mimeData()->hasFormat(m_model
->blacklistItemDropEventMimeType())) {
883 // Something has been dropped on an item or on an empty part of the view.
884 const KItemListWidget
*receivingWidget
= widgetForDropPos(pos
);
885 if (receivingWidget
) {
886 Q_EMIT
itemDropEvent(receivingWidget
->index(), event
);
888 Q_EMIT
itemDropEvent(-1, event
);
892 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropEnd
);
893 QAccessible::updateAccessibility(&accessibilityEvent
);
898 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
905 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
908 if (!m_model
|| !m_view
) {
912 // We identify the widget whose expansionArea had been hovered before this hoverMoveEvent() triggered.
913 // we can't use hoveredWidget() here (it handles the icon+text rect, not the expansion rect)
914 // like hoveredWidget(), we find the hovered widget for the expansion rect
915 const auto visibleItemListWidgets
= m_view
->visibleItemListWidgets();
916 const auto oldHoveredExpansionWidgetIterator
= std::find_if(visibleItemListWidgets
.begin(), visibleItemListWidgets
.end(), [](auto &widget
) {
917 return widget
->expansionAreaHovered();
919 const auto oldHoveredExpansionWidget
=
920 oldHoveredExpansionWidgetIterator
== visibleItemListWidgets
.end() ? std::nullopt
: std::make_optional(*oldHoveredExpansionWidgetIterator
);
922 const auto unhoverOldHoveredWidget
= [&]() {
923 if (auto oldHoveredWidget
= hoveredWidget(); oldHoveredWidget
) {
924 // handle the text+icon one
925 oldHoveredWidget
->setHovered(false);
926 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
930 const auto unhoverOldExpansionWidget
= [&]() {
931 if (oldHoveredExpansionWidget
) {
932 // then the expansion toggle
933 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
937 const QPointF pos
= transform
.map(event
->pos());
938 if (KItemListWidget
*newHoveredWidget
= widgetForPos(pos
); newHoveredWidget
) {
939 // something got hovered, work out which part and set hover for the appropriate widget
940 const auto mappedPos
= newHoveredWidget
->mapFromItem(m_view
, pos
);
941 const bool isOnExpansionToggle
= newHoveredWidget
->expansionToggleRect().contains(mappedPos
);
943 if (isOnExpansionToggle
) {
944 // make sure we unhover the old one first if old!=new
945 if (oldHoveredExpansionWidget
&& *oldHoveredExpansionWidget
!= newHoveredWidget
) {
946 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
948 // 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)
949 unhoverOldHoveredWidget();
951 newHoveredWidget
->setExpansionAreaHovered(true);
953 // make sure we unhover the old one first if old!=new
954 auto oldHoveredWidget
= hoveredWidget();
955 if (oldHoveredWidget
&& oldHoveredWidget
!= newHoveredWidget
) {
956 oldHoveredWidget
->setHovered(false);
957 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
959 // 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)
960 unhoverOldExpansionWidget();
962 const bool isOverIconAndText
= newHoveredWidget
->iconRect().contains(mappedPos
) || newHoveredWidget
->textRect().contains(mappedPos
);
963 const bool hasMultipleSelection
= m_selectionManager
->selectedItems().count() > 1;
965 if (hasMultipleSelection
&& !isOverIconAndText
) {
966 // In case we have multiple selections, clicking on any row will deselect the selection.
967 // So, as a visual cue for signalling that clicking anywhere won't select, but clear current highlights,
968 // we disable hover of the *row*(i.e. blank space to the right of the icon+text)
970 // (no-op in this branch for masked hover)
972 newHoveredWidget
->setHoverPosition(mappedPos
);
973 if (oldHoveredWidget
!= newHoveredWidget
) {
974 newHoveredWidget
->setHovered(true);
975 Q_EMIT
itemHovered(newHoveredWidget
->index());
980 // unhover any currently hovered expansion and text+icon widgets
981 unhoverOldHoveredWidget();
982 unhoverOldExpansionWidget();
987 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
992 m_mousePress
= false;
993 m_isTouchEvent
= false;
995 if (!m_model
|| !m_view
) {
999 const auto widgets
= m_view
->visibleItemListWidgets();
1000 for (KItemListWidget
*widget
: widgets
) {
1001 if (widget
->isHovered()) {
1002 widget
->setHovered(false);
1003 Q_EMIT
itemUnhovered(widget
->index());
1009 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent
*event
, const QTransform
&transform
)
1016 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent
*event
, const QTransform
&transform
)
1023 bool KItemListController::gestureEvent(QGestureEvent
*event
, const QTransform
&transform
)
1029 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
1030 //we use this to get the right QWidget
1031 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
1032 if (!m_mousePress
) {
1033 if (QGesture
*tap
= event
->gesture(Qt::TapGesture
)) {
1034 QTapGesture
*tapGesture
= static_cast<QTapGesture
*>(tap
);
1035 if (tapGesture
->state() == Qt::GestureStarted
) {
1036 tapTriggered(tapGesture
, transform
);
1042 bool accepted
= false;
1044 if (QGesture
*tap
= event
->gesture(Qt::TapGesture
)) {
1045 tapTriggered(static_cast<QTapGesture
*>(tap
), transform
);
1048 if (event
->gesture(Qt::TapAndHoldGesture
)) {
1049 tapAndHoldTriggered(event
, transform
);
1052 if (event
->gesture(Qt::PinchGesture
)) {
1053 pinchTriggered(event
, transform
);
1056 if (event
->gesture(m_swipeGesture
)) {
1057 swipeTriggered(event
, transform
);
1060 if (event
->gesture(m_twoFingerTapGesture
)) {
1061 twoFingerTapTriggered(event
, transform
);
1067 bool KItemListController::touchBeginEvent(QTouchEvent
*event
, const QTransform
&transform
)
1072 m_isTouchEvent
= true;
1076 void KItemListController::tapTriggered(QTapGesture
*tap
, const QTransform
&transform
)
1078 static bool scrollerWasActive
= false;
1080 if (tap
->state() == Qt::GestureStarted
) {
1081 m_dragActionOrRightClick
= false;
1082 m_isSwipeGesture
= false;
1083 m_pinchGestureInProgress
= false;
1084 scrollerWasActive
= m_scrollerIsScrolling
;
1087 if (tap
->state() == Qt::GestureFinished
) {
1088 m_mousePress
= false;
1090 //if at the moment of the gesture start the QScroller was active, the user made the tap
1091 //to stop the QScroller and not to tap on an item
1092 if (scrollerWasActive
) {
1096 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
1097 m_view
->m_tapAndHoldIndicator
->setActive(false);
1100 const QPointF pressedMousePos
= transform
.map(tap
->position());
1101 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1102 if (m_dragActionOrRightClick
) {
1103 m_dragActionOrRightClick
= false;
1105 onPress(m_pressedMouseGlobalPos
.toPoint(), tap
->position().toPoint(), Qt::NoModifier
, Qt::LeftButton
);
1106 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::LeftButton
, true);
1108 m_isTouchEvent
= false;
1112 void KItemListController::tapAndHoldTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1114 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
1115 if (!m_isTouchEvent
) {
1119 const QTapAndHoldGesture
*tap
= static_cast<QTapAndHoldGesture
*>(event
->gesture(Qt::TapAndHoldGesture
));
1120 if (tap
->state() == Qt::GestureFinished
) {
1121 //if a pinch gesture is in progress we don't want a TabAndHold gesture
1122 if (m_pinchGestureInProgress
) {
1125 const QPointF pressedMousePos
= transform
.map(event
->mapToGraphicsScene(tap
->position()));
1126 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1127 if (m_pressedIndex
.has_value()) {
1128 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
1129 m_selectionManager
->clearSelection();
1130 m_selectionManager
->setSelected(m_pressedIndex
.value());
1132 if (!m_selectionMode
) {
1133 Q_EMIT
selectionModeChangeRequested(true);
1136 m_selectionManager
->clearSelection();
1140 Q_EMIT
scrollerStop();
1142 m_view
->m_tapAndHoldIndicator
->setStartPosition(pressedMousePos
);
1143 m_view
->m_tapAndHoldIndicator
->setActive(true);
1145 m_dragActionOrRightClick
= true;
1149 void KItemListController::pinchTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1153 const QPinchGesture
*pinch
= static_cast<QPinchGesture
*>(event
->gesture(Qt::PinchGesture
));
1154 const qreal sensitivityModifier
= 0.2;
1155 static qreal counter
= 0;
1157 if (pinch
->state() == Qt::GestureStarted
) {
1158 m_pinchGestureInProgress
= true;
1161 if (pinch
->state() == Qt::GestureUpdated
) {
1162 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1163 if (m_isSwipeGesture
) {
1166 counter
= counter
+ (pinch
->scaleFactor() - 1);
1167 if (counter
>= sensitivityModifier
) {
1168 Q_EMIT
increaseZoom();
1170 } else if (counter
<= -sensitivityModifier
) {
1171 Q_EMIT
decreaseZoom();
1177 void KItemListController::swipeTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1181 const KTwoFingerSwipe
*swipe
= static_cast<KTwoFingerSwipe
*>(event
->gesture(m_swipeGesture
));
1186 if (swipe
->state() == Qt::GestureStarted
) {
1187 m_isSwipeGesture
= true;
1190 if (swipe
->state() == Qt::GestureCanceled
) {
1191 m_isSwipeGesture
= false;
1194 if (swipe
->state() == Qt::GestureFinished
) {
1195 Q_EMIT
scrollerStop();
1197 if (swipe
->swipeAngle() <= 20 || swipe
->swipeAngle() >= 340) {
1198 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::BackButton
);
1199 } else if (swipe
->swipeAngle() <= 200 && swipe
->swipeAngle() >= 160) {
1200 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::ForwardButton
);
1201 } else if (swipe
->swipeAngle() <= 110 && swipe
->swipeAngle() >= 60) {
1204 m_isSwipeGesture
= true;
1208 void KItemListController::twoFingerTapTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1210 const KTwoFingerTap
*twoTap
= static_cast<KTwoFingerTap
*>(event
->gesture(m_twoFingerTapGesture
));
1216 if (twoTap
->state() == Qt::GestureStarted
) {
1217 const QPointF pressedMousePos
= transform
.map(twoTap
->pos());
1218 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1219 if (m_pressedIndex
.has_value()) {
1220 onPress(twoTap
->screenPos().toPoint(), twoTap
->pos().toPoint(), Qt::ControlModifier
, Qt::LeftButton
);
1221 onRelease(transform
.map(twoTap
->pos()), Qt::ControlModifier
, Qt::LeftButton
, false);
1226 bool KItemListController::processEvent(QEvent
*event
, const QTransform
&transform
)
1232 switch (event
->type()) {
1233 case QEvent::KeyPress
:
1234 return keyPressEvent(static_cast<QKeyEvent
*>(event
));
1235 case QEvent::InputMethod
:
1236 return inputMethodEvent(static_cast<QInputMethodEvent
*>(event
));
1237 case QEvent::GraphicsSceneMousePress
:
1238 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1239 case QEvent::GraphicsSceneMouseMove
:
1240 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1241 case QEvent::GraphicsSceneMouseRelease
:
1242 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1243 case QEvent::GraphicsSceneMouseDoubleClick
:
1244 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1245 case QEvent::ContextMenu
:
1246 return contextMenuEvent(static_cast<QContextMenuEvent
*>(event
));
1247 case QEvent::GraphicsSceneWheel
:
1248 return wheelEvent(static_cast<QGraphicsSceneWheelEvent
*>(event
), QTransform());
1249 case QEvent::GraphicsSceneDragEnter
:
1250 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1251 case QEvent::GraphicsSceneDragLeave
:
1252 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1253 case QEvent::GraphicsSceneDragMove
:
1254 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1255 case QEvent::GraphicsSceneDrop
:
1256 return dropEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1257 case QEvent::GraphicsSceneHoverEnter
:
1258 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1259 case QEvent::GraphicsSceneHoverMove
:
1260 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1261 case QEvent::GraphicsSceneHoverLeave
:
1262 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1263 case QEvent::GraphicsSceneResize
:
1264 return resizeEvent(static_cast<QGraphicsSceneResizeEvent
*>(event
), transform
);
1265 case QEvent::Gesture
:
1266 return gestureEvent(static_cast<QGestureEvent
*>(event
), transform
);
1267 case QEvent::TouchBegin
:
1268 return touchBeginEvent(static_cast<QTouchEvent
*>(event
), transform
);
1276 void KItemListController::slotViewScrollOffsetChanged(qreal current
, qreal previous
)
1282 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1283 if (rubberBand
->isActive()) {
1284 const qreal diff
= current
- previous
;
1285 // TODO: Ideally just QCursor::pos() should be used as
1286 // new end-position but it seems there is no easy way
1287 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1288 // (... or I just missed an easy way to do the mapping)
1289 QPointF endPos
= rubberBand
->endPosition();
1290 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1291 endPos
.ry() += diff
;
1293 endPos
.rx() += diff
;
1296 rubberBand
->setEndPosition(endPos
);
1300 void KItemListController::slotRubberBandChanged()
1302 if (!m_view
|| !m_model
|| m_model
->count() <= 0) {
1306 const KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1307 const QPointF startPos
= rubberBand
->startPosition();
1308 const QPointF endPos
= rubberBand
->endPosition();
1309 QRectF rubberBandRect
= QRectF(startPos
, endPos
).normalized();
1311 const bool scrollVertical
= (m_view
->scrollOrientation() == Qt::Vertical
);
1312 if (scrollVertical
) {
1313 rubberBandRect
.translate(0, -m_view
->scrollOffset());
1315 rubberBandRect
.translate(-m_view
->scrollOffset(), 0);
1318 if (!m_oldSelection
.isEmpty()) {
1319 // Clear the old selection that was available before the rubberband has
1320 // been activated in case if no Shift- or Control-key are pressed
1321 const bool shiftOrControlPressed
= QApplication::keyboardModifiers() & Qt::ShiftModifier
|| QApplication::keyboardModifiers() & Qt::ControlModifier
;
1322 if (!shiftOrControlPressed
&& !m_selectionMode
) {
1323 m_oldSelection
.clear();
1327 KItemSet selectedItems
;
1329 // Select all visible items that intersect with the rubberband
1330 const auto widgets
= m_view
->visibleItemListWidgets();
1331 for (const KItemListWidget
*widget
: widgets
) {
1332 const int index
= widget
->index();
1334 const QRectF widgetRect
= m_view
->itemRect(index
);
1335 if (widgetRect
.intersects(rubberBandRect
)) {
1336 // Select the full row intersecting with the rubberband rectangle
1337 const QRectF selectionRect
= widget
->selectionRect().translated(widgetRect
.topLeft());
1338 const QRectF iconRect
= widget
->iconRect().translated(widgetRect
.topLeft());
1339 if (selectionRect
.intersects(rubberBandRect
) || iconRect
.intersects(rubberBandRect
)) {
1340 selectedItems
.insert(index
);
1345 // Select all invisible items that intersect with the rubberband. Instead of
1346 // iterating all items only the area which might be touched by the rubberband
1348 const bool increaseIndex
= scrollVertical
? startPos
.y() > endPos
.y() : startPos
.x() > endPos
.x();
1350 int index
= increaseIndex
? m_view
->lastVisibleIndex() + 1 : m_view
->firstVisibleIndex() - 1;
1351 bool selectionFinished
= false;
1353 const QRectF widgetRect
= m_view
->itemRect(index
);
1354 if (widgetRect
.intersects(rubberBandRect
)) {
1355 selectedItems
.insert(index
);
1358 if (increaseIndex
) {
1360 selectionFinished
= (index
>= m_model
->count()) || (scrollVertical
&& widgetRect
.top() > rubberBandRect
.bottom())
1361 || (!scrollVertical
&& widgetRect
.left() > rubberBandRect
.right());
1364 selectionFinished
= (index
< 0) || (scrollVertical
&& widgetRect
.bottom() < rubberBandRect
.top())
1365 || (!scrollVertical
&& widgetRect
.right() < rubberBandRect
.left());
1367 } while (!selectionFinished
);
1369 if ((QApplication::keyboardModifiers() & Qt::ControlModifier
) || m_selectionMode
) {
1370 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1371 // Therefore, the new selection contains:
1372 // 1. All previously selected items which are not inside the rubberband, and
1373 // 2. all items inside the rubberband which have not been selected previously.
1374 m_selectionManager
->setSelectedItems(m_oldSelection
^ selectedItems
);
1376 m_selectionManager
->setSelectedItems(selectedItems
+ m_oldSelection
);
1380 void KItemListController::startDragging()
1382 if (!m_view
|| !m_model
) {
1386 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
1387 if (selectedItems
.isEmpty()) {
1391 QMimeData
*data
= m_model
->createMimeData(selectedItems
);
1395 KUrlMimeData::exportUrlsToPortal(data
);
1397 // The created drag object will be owned and deleted
1398 // by QApplication::activeWindow().
1399 QDrag
*drag
= new QDrag(QApplication::activeWindow());
1400 drag
->setMimeData(data
);
1402 const QPixmap pixmap
= m_view
->createDragPixmap(selectedItems
);
1403 drag
->setPixmap(pixmap
);
1405 const QPoint
hotSpot((pixmap
.width() / pixmap
.devicePixelRatio()) / 2, 0);
1406 drag
->setHotSpot(hotSpot
);
1408 drag
->exec(Qt::MoveAction
| Qt::CopyAction
| Qt::LinkAction
, Qt::CopyAction
);
1410 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropStart
);
1411 QAccessible::updateAccessibility(&accessibilityEvent
);
1414 KItemListWidget
*KItemListController::hoveredWidget() const
1418 const auto widgets
= m_view
->visibleItemListWidgets();
1419 for (KItemListWidget
*widget
: widgets
) {
1420 if (widget
->isHovered()) {
1428 KItemListWidget
*KItemListController::widgetForPos(const QPointF
&pos
) const
1432 if (m_view
->headerBoundaries().contains(pos
)) {
1436 const auto widgets
= m_view
->visibleItemListWidgets();
1437 for (KItemListWidget
*widget
: widgets
) {
1438 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1439 if (widget
->contains(mappedPos
) || widget
->selectionRect().contains(mappedPos
)) {
1447 KItemListWidget
*KItemListController::widgetForDropPos(const QPointF
&pos
) const
1451 if (m_view
->headerBoundaries().contains(pos
)) {
1455 const auto widgets
= m_view
->visibleItemListWidgets();
1456 for (KItemListWidget
*widget
: widgets
) {
1457 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1458 if (widget
->contains(mappedPos
)) {
1466 void KItemListController::updateKeyboardAnchor()
1468 const bool validAnchor
=
1469 m_keyboardAnchorIndex
>= 0 && m_keyboardAnchorIndex
< m_model
->count() && keyboardAnchorPos(m_keyboardAnchorIndex
) == m_keyboardAnchorPos
;
1471 const int index
= m_selectionManager
->currentItem();
1472 m_keyboardAnchorIndex
= index
;
1473 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
1477 int KItemListController::nextRowIndex(int index
) const
1479 if (m_keyboardAnchorIndex
< 0) {
1483 const int maxIndex
= m_model
->count() - 1;
1484 if (index
== maxIndex
) {
1488 const bool leftToRight
= m_view
->layoutDirection() != Qt::RightToLeft
;
1490 // Calculate the index of the last column inside the row of the current index
1491 int lastColumnIndex
= index
;
1492 while ((leftToRight
&& keyboardAnchorPos(lastColumnIndex
+ 1) > keyboardAnchorPos(lastColumnIndex
))
1493 || (!leftToRight
&& keyboardAnchorPos(lastColumnIndex
+ 1) < keyboardAnchorPos(lastColumnIndex
))) {
1495 if (lastColumnIndex
>= maxIndex
) {
1500 // Based on the last column index go to the next row and calculate the nearest index
1501 // that is below the current index
1502 int nextRowIndex
= lastColumnIndex
+ 1;
1503 int searchIndex
= nextRowIndex
;
1504 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(nextRowIndex
));
1505 while (searchIndex
< maxIndex
1506 && ((leftToRight
&& keyboardAnchorPos(searchIndex
+ 1) > keyboardAnchorPos(searchIndex
))
1507 || (!leftToRight
&& keyboardAnchorPos(searchIndex
+ 1) < keyboardAnchorPos(searchIndex
)))) {
1509 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1510 if (searchDiff
< minDiff
) {
1511 minDiff
= searchDiff
;
1512 nextRowIndex
= searchIndex
;
1516 return nextRowIndex
;
1519 int KItemListController::previousRowIndex(int index
) const
1521 if (m_keyboardAnchorIndex
< 0 || index
== 0) {
1525 const bool leftToRight
= m_view
->layoutDirection() != Qt::RightToLeft
;
1527 // Calculate the index of the first column inside the row of the current index
1528 int firstColumnIndex
= index
;
1529 while ((leftToRight
&& keyboardAnchorPos(firstColumnIndex
- 1) < keyboardAnchorPos(firstColumnIndex
))
1530 || (!leftToRight
&& keyboardAnchorPos(firstColumnIndex
- 1) > keyboardAnchorPos(firstColumnIndex
))) {
1532 if (firstColumnIndex
<= 0) {
1537 // Based on the first column index go to the previous row and calculate the nearest index
1538 // that is above the current index
1539 int previousRowIndex
= firstColumnIndex
- 1;
1540 int searchIndex
= previousRowIndex
;
1541 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(previousRowIndex
));
1542 while (searchIndex
> 0
1543 && ((leftToRight
&& keyboardAnchorPos(searchIndex
- 1) < keyboardAnchorPos(searchIndex
))
1544 || (!leftToRight
&& keyboardAnchorPos(searchIndex
- 1) > keyboardAnchorPos(searchIndex
)))) {
1546 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1547 if (searchDiff
< minDiff
) {
1548 minDiff
= searchDiff
;
1549 previousRowIndex
= searchIndex
;
1553 return previousRowIndex
;
1556 qreal
KItemListController::keyboardAnchorPos(int index
) const
1558 const QRectF itemRect
= m_view
->itemRect(index
);
1559 if (!itemRect
.isEmpty()) {
1560 return (m_view
->scrollOrientation() == Qt::Vertical
) ? itemRect
.x() : itemRect
.y();
1566 void KItemListController::updateExtendedSelectionRegion()
1569 const bool extend
= (m_selectionBehavior
!= MultiSelection
);
1570 KItemListStyleOption option
= m_view
->styleOption();
1571 if (option
.extendedSelectionRegion
!= extend
) {
1572 option
.extendedSelectionRegion
= extend
;
1573 m_view
->setStyleOption(option
);
1578 bool KItemListController::onPress(const QPoint
&screenPos
, const QPointF
&pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
)
1580 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), buttons
);
1582 if (buttons
& (Qt::BackButton
| Qt::ForwardButton
)) {
1583 // Do not select items when clicking the back/forward buttons, see
1584 // https://bugs.kde.org/show_bug.cgi?id=327412.
1588 const QPointF pressedMousePos
= m_view
->transform().map(pos
);
1590 if (m_view
->isAboveExpansionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
)) {
1591 m_selectionManager
->endAnchoredSelection();
1592 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1593 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1597 m_selectionTogglePressed
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
);
1598 if (m_selectionTogglePressed
) {
1599 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1600 // The previous anchored selection has been finished already in
1601 // KItemListSelectionManager::setSelected(). We can safely change
1602 // the current item and start a new anchored selection now.
1603 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1604 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1608 const bool shiftPressed
= modifiers
& Qt::ShiftModifier
;
1609 const bool controlPressed
= (modifiers
& Qt::ControlModifier
) || m_selectionMode
; // Keeping selectionMode similar to pressing control will hopefully
1610 // simplify the overall logic and possibilities both for users and devs.
1611 const bool leftClick
= buttons
& Qt::LeftButton
;
1612 const bool rightClick
= buttons
& Qt::RightButton
;
1614 // The previous selection is cleared if either
1615 // 1. The selection mode is SingleSelection, or
1616 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1617 // a) Shift or Control are pressed.
1618 // b) The clicked item is selected already. In that case, the user might want to:
1619 // - start dragging multiple items, or
1620 // - open the context menu and perform an action for all selected items.
1621 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
1622 const bool pressedItemAlreadySelected
= m_pressedIndex
.has_value() && m_selectionManager
->isSelected(m_pressedIndex
.value());
1623 const bool clearSelection
= m_selectionBehavior
== SingleSelection
|| (!shiftOrControlPressed
&& !pressedItemAlreadySelected
);
1625 // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller.
1626 if (clearSelection
) {
1627 const int selectedItemsCount
= m_selectionManager
->selectedItems().count();
1628 m_selectionManager
->clearSelection();
1629 // clear and bail when we got an existing multi-selection
1630 if (selectedItemsCount
> 1 && m_pressedIndex
.has_value()) {
1631 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1632 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1633 if (pressedItemAlreadySelected
|| row
->iconRect().contains(mappedPos
) || row
->textRect().contains(mappedPos
)) {
1634 // we are indeed inside the text/icon rect, keep m_pressedIndex what it is
1635 // and short-circuit for single-click activation (it will then propagate to onRelease and activate the item)
1636 // or we just keep going for double-click activation
1637 if (m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) {
1638 if (!pressedItemAlreadySelected
) {
1639 // An unselected item was clicked directly while deselecting multiple other items so we select it.
1640 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1641 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1642 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1644 return true; // event handled, don't create rubber band
1647 // we're not inside the text/icon rect, as we've already cleared the selection
1648 // we can just stop here and make sure handlers down the line (i.e. onRelease) don't activate
1649 m_pressedIndex
.reset();
1650 // we don't stop event propagation and proceed to create a rubber band and let onRelease
1651 // decide (based on m_pressedIndex) whether we're in a drag (drag => new rubber band, click => don't select the item)
1655 } else if (pressedItemAlreadySelected
&& !shiftOrControlPressed
&& leftClick
) {
1656 // The user might want to start dragging multiple items, but if he clicks the item
1657 // in order to trigger it instead, the other selected items must be deselected.
1658 // However, we do not know yet what the user is going to do.
1659 // -> remember that the user pressed an item which had been selected already and
1660 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1661 m_clearSelectionIfItemsAreNotDragged
= true;
1663 if (m_selectionManager
->selectedItems().count() == 1 && m_view
->isAboveText(m_pressedIndex
.value_or(-1), pressedMousePos
)) {
1664 Q_EMIT
selectedItemTextPressed(m_pressedIndex
.value_or(-1));
1668 if (!shiftPressed
) {
1669 // Finish the anchored selection before the current index is changed
1670 m_selectionManager
->endAnchoredSelection();
1674 // Stop rubber band from persisting after right-clicks
1675 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1676 if (rubberBand
->isActive()) {
1677 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1678 rubberBand
->setActive(false);
1679 m_view
->setAutoScroll(false);
1683 if (m_pressedIndex
.has_value()) {
1684 // The hover highlight area of an item is being pressed.
1685 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
1686 const bool hitTargetIsRowEmptyRegion
= !row
->contains(row
->mapFromItem(m_view
, pos
));
1687 // again, when this method returns false, a rubberBand selection is created as the event is not consumed;
1688 // createRubberBand here tells us whether to return true or false.
1689 bool createRubberBand
= (hitTargetIsRowEmptyRegion
&& m_selectionManager
->selectedItems().isEmpty());
1691 if (rightClick
&& hitTargetIsRowEmptyRegion
) {
1692 // We have a right click outside the icon and text rect but within the hover highlight area.
1693 // We don't want items to get selected through this, so we return now.
1697 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1699 switch (m_selectionBehavior
) {
1703 case SingleSelection
:
1704 m_selectionManager
->setSelected(m_pressedIndex
.value());
1707 case MultiSelection
:
1708 if (controlPressed
&& !shiftPressed
&& leftClick
) {
1709 // A left mouse button press is happening on an item while control is pressed. This either means a user wants to:
1710 // - toggle the selection of item(s) or
1711 // - they want to begin a drag on the item(s) to copy them.
1712 // We rule out the latter, if the item is not clicked directly and was unselected previously.
1713 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1714 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1715 if (!row
->iconRect().contains(mappedPos
) && !row
->textRect().contains(mappedPos
) && !pressedItemAlreadySelected
) {
1716 createRubberBand
= true;
1718 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1719 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1720 createRubberBand
= false; // multi selection, don't propagate any further
1721 // This will be the start of an item drag-to-copy operation if the user now moves the mouse before releasing the mouse button.
1723 } else if (!shiftPressed
|| !m_selectionManager
->isAnchoredSelectionActive()) {
1724 // Select the pressed item and start a new anchored selection
1725 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1726 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1735 return !createRubberBand
;
1741 bool KItemListController::onRelease(const QPointF
&pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
, bool touch
)
1743 const QPointF pressedMousePos
= pos
;
1744 const bool isAboveSelectionToggle
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
);
1745 if (isAboveSelectionToggle
) {
1746 m_selectionTogglePressed
= false;
1750 if (!isAboveSelectionToggle
&& m_selectionTogglePressed
) {
1751 m_selectionManager
->setSelected(m_pressedIndex
.value_or(-1), 1, KItemListSelectionManager::Toggle
);
1752 m_selectionTogglePressed
= false;
1756 const bool controlPressed
= modifiers
& Qt::ControlModifier
;
1757 const bool shiftOrControlPressed
= modifiers
& Qt::ShiftModifier
|| controlPressed
;
1759 const std::optional
<int> index
= m_view
->itemAt(pos
);
1761 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1762 bool rubberBandRelease
= false;
1763 if (rubberBand
->isActive()) {
1764 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1765 rubberBand
->setActive(false);
1766 m_oldSelection
.clear();
1767 m_view
->setAutoScroll(false);
1768 rubberBandRelease
= true;
1769 // We check for actual rubber band drag here: if delta between start and end is less than drag threshold,
1770 // then we have a single click on one of the rows
1771 if ((rubberBand
->endPosition() - rubberBand
->startPosition()).manhattanLength() < QApplication::startDragDistance()) {
1772 rubberBandRelease
= false; // since we're only selecting, unmark rubber band release flag
1773 // m_pressedIndex will have no value if we came from a multi-selection clearing onPress
1774 // in that case, we don't select anything
1775 if (index
.has_value() && m_pressedIndex
.has_value()) {
1776 if (controlPressed
&& m_selectionBehavior
== MultiSelection
) {
1777 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1779 m_selectionManager
->setSelected(index
.value());
1781 if (!m_selectionManager
->isAnchoredSelectionActive()) {
1782 m_selectionManager
->beginAnchoredSelection(index
.value());
1788 if (index
.has_value() && index
== m_pressedIndex
) {
1789 // The release event is done above the same item as the press event
1791 if (m_clearSelectionIfItemsAreNotDragged
) {
1792 // A selected item has been clicked, but no drag operation has been started
1793 // -> clear the rest of the selection.
1794 m_selectionManager
->clearSelection();
1795 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1796 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1799 if (buttons
& Qt::LeftButton
) {
1800 bool emitItemActivated
= true;
1801 if (m_view
->isAboveExpansionToggle(index
.value(), pos
)) {
1802 const bool expanded
= m_model
->isExpanded(index
.value());
1803 m_model
->setExpanded(index
.value(), !expanded
);
1805 Q_EMIT
itemExpansionToggleClicked(index
.value());
1806 emitItemActivated
= false;
1807 } else if (shiftOrControlPressed
&& m_selectionBehavior
!= SingleSelection
) {
1808 // The mouse click should only update the selection, not trigger the item, except when
1809 // we are in single selection mode
1810 emitItemActivated
= false;
1812 const bool singleClickActivation
= m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
;
1813 if (!singleClickActivation
) {
1814 emitItemActivated
= touch
&& !m_selectionMode
;
1816 // activate on single click only if we didn't come from a rubber band release
1817 emitItemActivated
= !rubberBandRelease
;
1820 if (emitItemActivated
) {
1821 Q_EMIT
itemActivated(index
.value());
1823 } else if (buttons
& Qt::MiddleButton
) {
1824 Q_EMIT
itemMiddleClicked(index
.value());
1828 m_pressedMouseGlobalPos
= QPointF();
1829 m_pressedIndex
= std::nullopt
;
1830 m_clearSelectionIfItemsAreNotDragged
= false;
1834 void KItemListController::startRubberBand()
1836 if (m_selectionBehavior
== MultiSelection
) {
1837 QPoint startPos
= m_view
->transform().map(m_view
->scene()->views().first()->mapFromGlobal(m_pressedMouseGlobalPos
.toPoint()));
1838 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1839 startPos
.ry() += m_view
->scrollOffset();
1841 startPos
.rx() += m_view
->scrollOffset();
1844 m_oldSelection
= m_selectionManager
->selectedItems();
1845 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1846 rubberBand
->setStartPosition(startPos
);
1847 rubberBand
->setEndPosition(startPos
);
1848 rubberBand
->setActive(true);
1849 connect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1850 m_view
->setAutoScroll(true);
1854 void KItemListController::slotStateChanged(QScroller::State newState
)
1856 if (newState
== QScroller::Scrolling
) {
1857 m_scrollerIsScrolling
= true;
1858 } else if (newState
== QScroller::Inactive
) {
1859 m_scrollerIsScrolling
= false;
1863 #include "moc_kitemlistcontroller.cpp"