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();
835 m_autoActivationTimer
->stop();
836 if (newHoveredWidget
&& newHoveredWidget
->isHovered()) {
837 newHoveredWidget
->setHovered(false);
838 Q_EMIT
itemUnhovered(index
);
842 m_view
->hideDropIndicator();
845 if (DragAndDropHelper::urlListMatchesUrl(event
->mimeData()->urls(), hoveredDir
)) {
846 event
->setDropAction(Qt::IgnoreAction
);
849 if (m_model
->supportsDropping(index
)) {
850 event
->setDropAction(event
->proposedAction());
853 event
->setDropAction(Qt::IgnoreAction
);
860 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
866 m_autoActivationTimer
->stop();
867 m_view
->setAutoScroll(false);
869 const QPointF pos
= transform
.map(event
->pos());
871 int dropAboveIndex
= -1;
872 if (m_model
->sortRole().isEmpty()) {
873 // The model supports inserting of items between other items.
874 dropAboveIndex
= m_view
->showDropIndicator(pos
);
877 if (dropAboveIndex
>= 0) {
878 // Something has been dropped between two items.
879 m_view
->hideDropIndicator();
880 Q_EMIT
aboveItemDropEvent(dropAboveIndex
, event
);
881 } else if (!event
->mimeData()->hasFormat(m_model
->blacklistItemDropEventMimeType())) {
882 // Something has been dropped on an item or on an empty part of the view.
883 const KItemListWidget
*receivingWidget
= widgetForDropPos(pos
);
884 if (receivingWidget
) {
885 Q_EMIT
itemDropEvent(receivingWidget
->index(), event
);
887 Q_EMIT
itemDropEvent(-1, event
);
891 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropEnd
);
892 QAccessible::updateAccessibility(&accessibilityEvent
);
897 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
904 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
907 if (!m_model
|| !m_view
) {
911 // We identify the widget whose expansionArea had been hovered before this hoverMoveEvent() triggered.
912 // we can't use hoveredWidget() here (it handles the icon+text rect, not the expansion rect)
913 // like hoveredWidget(), we find the hovered widget for the expansion rect
914 const auto visibleItemListWidgets
= m_view
->visibleItemListWidgets();
915 const auto oldHoveredExpansionWidgetIterator
= std::find_if(visibleItemListWidgets
.begin(), visibleItemListWidgets
.end(), [](auto &widget
) {
916 return widget
->expansionAreaHovered();
918 const auto oldHoveredExpansionWidget
=
919 oldHoveredExpansionWidgetIterator
== visibleItemListWidgets
.end() ? std::nullopt
: std::make_optional(*oldHoveredExpansionWidgetIterator
);
921 const auto unhoverOldHoveredWidget
= [&]() {
922 if (auto oldHoveredWidget
= hoveredWidget(); oldHoveredWidget
) {
923 // handle the text+icon one
924 oldHoveredWidget
->setHovered(false);
925 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
929 const auto unhoverOldExpansionWidget
= [&]() {
930 if (oldHoveredExpansionWidget
) {
931 // then the expansion toggle
932 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
936 const QPointF pos
= transform
.map(event
->pos());
937 if (KItemListWidget
*newHoveredWidget
= widgetForPos(pos
); newHoveredWidget
) {
938 // something got hovered, work out which part and set hover for the appropriate widget
939 const auto mappedPos
= newHoveredWidget
->mapFromItem(m_view
, pos
);
940 const bool isOnExpansionToggle
= newHoveredWidget
->expansionToggleRect().contains(mappedPos
);
942 if (isOnExpansionToggle
) {
943 // make sure we unhover the old one first if old!=new
944 if (oldHoveredExpansionWidget
&& *oldHoveredExpansionWidget
!= newHoveredWidget
) {
945 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
947 // 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)
948 unhoverOldHoveredWidget();
950 newHoveredWidget
->setExpansionAreaHovered(true);
952 // make sure we unhover the old one first if old!=new
953 auto oldHoveredWidget
= hoveredWidget();
954 if (oldHoveredWidget
&& oldHoveredWidget
!= newHoveredWidget
) {
955 oldHoveredWidget
->setHovered(false);
956 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
958 // 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)
959 unhoverOldExpansionWidget();
961 const bool isOverIconAndText
= newHoveredWidget
->iconRect().contains(mappedPos
) || newHoveredWidget
->textRect().contains(mappedPos
);
962 const bool hasMultipleSelection
= m_selectionManager
->selectedItems().count() > 1;
964 if (hasMultipleSelection
&& !isOverIconAndText
) {
965 // In case we have multiple selections, clicking on any row will deselect the selection.
966 // So, as a visual cue for signalling that clicking anywhere won't select, but clear current highlights,
967 // we disable hover of the *row*(i.e. blank space to the right of the icon+text)
969 // (no-op in this branch for masked hover)
971 newHoveredWidget
->setHoverPosition(mappedPos
);
972 if (oldHoveredWidget
!= newHoveredWidget
) {
973 newHoveredWidget
->setHovered(true);
974 Q_EMIT
itemHovered(newHoveredWidget
->index());
979 // unhover any currently hovered expansion and text+icon widgets
980 unhoverOldHoveredWidget();
981 unhoverOldExpansionWidget();
986 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
991 m_mousePress
= false;
992 m_isTouchEvent
= false;
994 if (!m_model
|| !m_view
) {
998 const auto widgets
= m_view
->visibleItemListWidgets();
999 for (KItemListWidget
*widget
: widgets
) {
1000 if (widget
->isHovered()) {
1001 widget
->setHovered(false);
1002 Q_EMIT
itemUnhovered(widget
->index());
1008 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent
*event
, const QTransform
&transform
)
1015 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent
*event
, const QTransform
&transform
)
1022 bool KItemListController::gestureEvent(QGestureEvent
*event
, const QTransform
&transform
)
1028 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
1029 //we use this to get the right QWidget
1030 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
1031 if (!m_mousePress
) {
1032 if (QGesture
*tap
= event
->gesture(Qt::TapGesture
)) {
1033 QTapGesture
*tapGesture
= static_cast<QTapGesture
*>(tap
);
1034 if (tapGesture
->state() == Qt::GestureStarted
) {
1035 tapTriggered(tapGesture
, transform
);
1041 bool accepted
= false;
1043 if (QGesture
*tap
= event
->gesture(Qt::TapGesture
)) {
1044 tapTriggered(static_cast<QTapGesture
*>(tap
), transform
);
1047 if (event
->gesture(Qt::TapAndHoldGesture
)) {
1048 tapAndHoldTriggered(event
, transform
);
1051 if (event
->gesture(Qt::PinchGesture
)) {
1052 pinchTriggered(event
, transform
);
1055 if (event
->gesture(m_swipeGesture
)) {
1056 swipeTriggered(event
, transform
);
1059 if (event
->gesture(m_twoFingerTapGesture
)) {
1060 twoFingerTapTriggered(event
, transform
);
1066 bool KItemListController::touchBeginEvent(QTouchEvent
*event
, const QTransform
&transform
)
1071 m_isTouchEvent
= true;
1075 void KItemListController::tapTriggered(QTapGesture
*tap
, const QTransform
&transform
)
1077 static bool scrollerWasActive
= false;
1079 if (tap
->state() == Qt::GestureStarted
) {
1080 m_dragActionOrRightClick
= false;
1081 m_isSwipeGesture
= false;
1082 m_pinchGestureInProgress
= false;
1083 scrollerWasActive
= m_scrollerIsScrolling
;
1086 if (tap
->state() == Qt::GestureFinished
) {
1087 m_mousePress
= false;
1089 //if at the moment of the gesture start the QScroller was active, the user made the tap
1090 //to stop the QScroller and not to tap on an item
1091 if (scrollerWasActive
) {
1095 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
1096 m_view
->m_tapAndHoldIndicator
->setActive(false);
1099 const QPointF pressedMousePos
= transform
.map(tap
->position());
1100 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1101 if (m_dragActionOrRightClick
) {
1102 m_dragActionOrRightClick
= false;
1104 onPress(m_pressedMouseGlobalPos
.toPoint(), tap
->position().toPoint(), Qt::NoModifier
, Qt::LeftButton
);
1105 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::LeftButton
, true);
1107 m_isTouchEvent
= false;
1111 void KItemListController::tapAndHoldTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1113 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
1114 if (!m_isTouchEvent
) {
1118 const QTapAndHoldGesture
*tap
= static_cast<QTapAndHoldGesture
*>(event
->gesture(Qt::TapAndHoldGesture
));
1119 if (tap
->state() == Qt::GestureFinished
) {
1120 //if a pinch gesture is in progress we don't want a TabAndHold gesture
1121 if (m_pinchGestureInProgress
) {
1124 const QPointF pressedMousePos
= transform
.map(event
->mapToGraphicsScene(tap
->position()));
1125 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1126 if (m_pressedIndex
.has_value()) {
1127 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
1128 m_selectionManager
->clearSelection();
1129 m_selectionManager
->setSelected(m_pressedIndex
.value());
1131 if (!m_selectionMode
) {
1132 Q_EMIT
selectionModeChangeRequested(true);
1135 m_selectionManager
->clearSelection();
1139 Q_EMIT
scrollerStop();
1141 m_view
->m_tapAndHoldIndicator
->setStartPosition(pressedMousePos
);
1142 m_view
->m_tapAndHoldIndicator
->setActive(true);
1144 m_dragActionOrRightClick
= true;
1148 void KItemListController::pinchTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1152 const QPinchGesture
*pinch
= static_cast<QPinchGesture
*>(event
->gesture(Qt::PinchGesture
));
1153 const qreal sensitivityModifier
= 0.2;
1154 static qreal counter
= 0;
1156 if (pinch
->state() == Qt::GestureStarted
) {
1157 m_pinchGestureInProgress
= true;
1160 if (pinch
->state() == Qt::GestureUpdated
) {
1161 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1162 if (m_isSwipeGesture
) {
1165 counter
= counter
+ (pinch
->scaleFactor() - 1);
1166 if (counter
>= sensitivityModifier
) {
1167 Q_EMIT
increaseZoom();
1169 } else if (counter
<= -sensitivityModifier
) {
1170 Q_EMIT
decreaseZoom();
1176 void KItemListController::swipeTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1180 const KTwoFingerSwipe
*swipe
= static_cast<KTwoFingerSwipe
*>(event
->gesture(m_swipeGesture
));
1185 if (swipe
->state() == Qt::GestureStarted
) {
1186 m_isSwipeGesture
= true;
1189 if (swipe
->state() == Qt::GestureCanceled
) {
1190 m_isSwipeGesture
= false;
1193 if (swipe
->state() == Qt::GestureFinished
) {
1194 Q_EMIT
scrollerStop();
1196 if (swipe
->swipeAngle() <= 20 || swipe
->swipeAngle() >= 340) {
1197 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::BackButton
);
1198 } else if (swipe
->swipeAngle() <= 200 && swipe
->swipeAngle() >= 160) {
1199 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::ForwardButton
);
1200 } else if (swipe
->swipeAngle() <= 110 && swipe
->swipeAngle() >= 60) {
1203 m_isSwipeGesture
= true;
1207 void KItemListController::twoFingerTapTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1209 const KTwoFingerTap
*twoTap
= static_cast<KTwoFingerTap
*>(event
->gesture(m_twoFingerTapGesture
));
1215 if (twoTap
->state() == Qt::GestureStarted
) {
1216 const QPointF pressedMousePos
= transform
.map(twoTap
->pos());
1217 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1218 if (m_pressedIndex
.has_value()) {
1219 onPress(twoTap
->screenPos().toPoint(), twoTap
->pos().toPoint(), Qt::ControlModifier
, Qt::LeftButton
);
1220 onRelease(transform
.map(twoTap
->pos()), Qt::ControlModifier
, Qt::LeftButton
, false);
1225 bool KItemListController::processEvent(QEvent
*event
, const QTransform
&transform
)
1231 switch (event
->type()) {
1232 case QEvent::KeyPress
:
1233 return keyPressEvent(static_cast<QKeyEvent
*>(event
));
1234 case QEvent::InputMethod
:
1235 return inputMethodEvent(static_cast<QInputMethodEvent
*>(event
));
1236 case QEvent::GraphicsSceneMousePress
:
1237 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1238 case QEvent::GraphicsSceneMouseMove
:
1239 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1240 case QEvent::GraphicsSceneMouseRelease
:
1241 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1242 case QEvent::GraphicsSceneMouseDoubleClick
:
1243 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1244 case QEvent::ContextMenu
:
1245 return contextMenuEvent(static_cast<QContextMenuEvent
*>(event
));
1246 case QEvent::GraphicsSceneWheel
:
1247 return wheelEvent(static_cast<QGraphicsSceneWheelEvent
*>(event
), QTransform());
1248 case QEvent::GraphicsSceneDragEnter
:
1249 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1250 case QEvent::GraphicsSceneDragLeave
:
1251 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1252 case QEvent::GraphicsSceneDragMove
:
1253 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1254 case QEvent::GraphicsSceneDrop
:
1255 return dropEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1256 case QEvent::GraphicsSceneHoverEnter
:
1257 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1258 case QEvent::GraphicsSceneHoverMove
:
1259 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1260 case QEvent::GraphicsSceneHoverLeave
:
1261 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1262 case QEvent::GraphicsSceneResize
:
1263 return resizeEvent(static_cast<QGraphicsSceneResizeEvent
*>(event
), transform
);
1264 case QEvent::Gesture
:
1265 return gestureEvent(static_cast<QGestureEvent
*>(event
), transform
);
1266 case QEvent::TouchBegin
:
1267 return touchBeginEvent(static_cast<QTouchEvent
*>(event
), transform
);
1275 void KItemListController::slotViewScrollOffsetChanged(qreal current
, qreal previous
)
1281 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1282 if (rubberBand
->isActive()) {
1283 const qreal diff
= current
- previous
;
1284 // TODO: Ideally just QCursor::pos() should be used as
1285 // new end-position but it seems there is no easy way
1286 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1287 // (... or I just missed an easy way to do the mapping)
1288 QPointF endPos
= rubberBand
->endPosition();
1289 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1290 endPos
.ry() += diff
;
1292 endPos
.rx() += diff
;
1295 rubberBand
->setEndPosition(endPos
);
1299 void KItemListController::slotRubberBandChanged()
1301 if (!m_view
|| !m_model
|| m_model
->count() <= 0) {
1305 const KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1306 const QPointF startPos
= rubberBand
->startPosition();
1307 const QPointF endPos
= rubberBand
->endPosition();
1308 QRectF rubberBandRect
= QRectF(startPos
, endPos
).normalized();
1310 const bool scrollVertical
= (m_view
->scrollOrientation() == Qt::Vertical
);
1311 if (scrollVertical
) {
1312 rubberBandRect
.translate(0, -m_view
->scrollOffset());
1314 rubberBandRect
.translate(-m_view
->scrollOffset(), 0);
1317 if (!m_oldSelection
.isEmpty()) {
1318 // Clear the old selection that was available before the rubberband has
1319 // been activated in case if no Shift- or Control-key are pressed
1320 const bool shiftOrControlPressed
= QApplication::keyboardModifiers() & Qt::ShiftModifier
|| QApplication::keyboardModifiers() & Qt::ControlModifier
;
1321 if (!shiftOrControlPressed
&& !m_selectionMode
) {
1322 m_oldSelection
.clear();
1326 KItemSet selectedItems
;
1328 // Select all visible items that intersect with the rubberband
1329 const auto widgets
= m_view
->visibleItemListWidgets();
1330 for (const KItemListWidget
*widget
: widgets
) {
1331 const int index
= widget
->index();
1333 const QRectF widgetRect
= m_view
->itemRect(index
);
1334 if (widgetRect
.intersects(rubberBandRect
)) {
1335 // Select the full row intersecting with the rubberband rectangle
1336 const QRectF selectionRect
= widget
->selectionRect().translated(widgetRect
.topLeft());
1337 const QRectF iconRect
= widget
->iconRect().translated(widgetRect
.topLeft());
1338 if (selectionRect
.intersects(rubberBandRect
) || iconRect
.intersects(rubberBandRect
)) {
1339 selectedItems
.insert(index
);
1344 // Select all invisible items that intersect with the rubberband. Instead of
1345 // iterating all items only the area which might be touched by the rubberband
1347 const bool increaseIndex
= scrollVertical
? startPos
.y() > endPos
.y() : startPos
.x() > endPos
.x();
1349 int index
= increaseIndex
? m_view
->lastVisibleIndex() + 1 : m_view
->firstVisibleIndex() - 1;
1350 bool selectionFinished
= false;
1352 const QRectF widgetRect
= m_view
->itemRect(index
);
1353 if (widgetRect
.intersects(rubberBandRect
)) {
1354 selectedItems
.insert(index
);
1357 if (increaseIndex
) {
1359 selectionFinished
= (index
>= m_model
->count()) || (scrollVertical
&& widgetRect
.top() > rubberBandRect
.bottom())
1360 || (!scrollVertical
&& widgetRect
.left() > rubberBandRect
.right());
1363 selectionFinished
= (index
< 0) || (scrollVertical
&& widgetRect
.bottom() < rubberBandRect
.top())
1364 || (!scrollVertical
&& widgetRect
.right() < rubberBandRect
.left());
1366 } while (!selectionFinished
);
1368 if ((QApplication::keyboardModifiers() & Qt::ControlModifier
) || m_selectionMode
) {
1369 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1370 // Therefore, the new selection contains:
1371 // 1. All previously selected items which are not inside the rubberband, and
1372 // 2. all items inside the rubberband which have not been selected previously.
1373 m_selectionManager
->setSelectedItems(m_oldSelection
^ selectedItems
);
1375 m_selectionManager
->setSelectedItems(selectedItems
+ m_oldSelection
);
1379 void KItemListController::startDragging()
1381 if (!m_view
|| !m_model
) {
1385 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
1386 if (selectedItems
.isEmpty()) {
1390 QMimeData
*data
= m_model
->createMimeData(selectedItems
);
1394 KUrlMimeData::exportUrlsToPortal(data
);
1396 // The created drag object will be owned and deleted
1397 // by QApplication::activeWindow().
1398 QDrag
*drag
= new QDrag(QApplication::activeWindow());
1399 drag
->setMimeData(data
);
1401 const QPixmap pixmap
= m_view
->createDragPixmap(selectedItems
);
1402 drag
->setPixmap(pixmap
);
1404 const QPoint
hotSpot((pixmap
.width() / pixmap
.devicePixelRatio()) / 2, 0);
1405 drag
->setHotSpot(hotSpot
);
1407 drag
->exec(Qt::MoveAction
| Qt::CopyAction
| Qt::LinkAction
, Qt::CopyAction
);
1409 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropStart
);
1410 QAccessible::updateAccessibility(&accessibilityEvent
);
1413 KItemListWidget
*KItemListController::hoveredWidget() const
1417 const auto widgets
= m_view
->visibleItemListWidgets();
1418 for (KItemListWidget
*widget
: widgets
) {
1419 if (widget
->isHovered()) {
1427 KItemListWidget
*KItemListController::widgetForPos(const QPointF
&pos
) const
1431 if (m_view
->headerBoundaries().contains(pos
)) {
1435 const auto widgets
= m_view
->visibleItemListWidgets();
1436 for (KItemListWidget
*widget
: widgets
) {
1437 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1438 if (widget
->contains(mappedPos
) || widget
->selectionRect().contains(mappedPos
)) {
1446 KItemListWidget
*KItemListController::widgetForDropPos(const QPointF
&pos
) const
1450 if (m_view
->headerBoundaries().contains(pos
)) {
1454 const auto widgets
= m_view
->visibleItemListWidgets();
1455 for (KItemListWidget
*widget
: widgets
) {
1456 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1457 if (widget
->contains(mappedPos
)) {
1465 void KItemListController::updateKeyboardAnchor()
1467 const bool validAnchor
=
1468 m_keyboardAnchorIndex
>= 0 && m_keyboardAnchorIndex
< m_model
->count() && keyboardAnchorPos(m_keyboardAnchorIndex
) == m_keyboardAnchorPos
;
1470 const int index
= m_selectionManager
->currentItem();
1471 m_keyboardAnchorIndex
= index
;
1472 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
1476 int KItemListController::nextRowIndex(int index
) const
1478 if (m_keyboardAnchorIndex
< 0) {
1482 const int maxIndex
= m_model
->count() - 1;
1483 if (index
== maxIndex
) {
1487 const bool leftToRight
= m_view
->layoutDirection() != Qt::RightToLeft
;
1489 // Calculate the index of the last column inside the row of the current index
1490 int lastColumnIndex
= index
;
1491 while ((leftToRight
&& keyboardAnchorPos(lastColumnIndex
+ 1) > keyboardAnchorPos(lastColumnIndex
))
1492 || (!leftToRight
&& keyboardAnchorPos(lastColumnIndex
+ 1) < keyboardAnchorPos(lastColumnIndex
))) {
1494 if (lastColumnIndex
>= maxIndex
) {
1499 // Based on the last column index go to the next row and calculate the nearest index
1500 // that is below the current index
1501 int nextRowIndex
= lastColumnIndex
+ 1;
1502 int searchIndex
= nextRowIndex
;
1503 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(nextRowIndex
));
1504 while (searchIndex
< maxIndex
1505 && ((leftToRight
&& keyboardAnchorPos(searchIndex
+ 1) > keyboardAnchorPos(searchIndex
))
1506 || (!leftToRight
&& keyboardAnchorPos(searchIndex
+ 1) < keyboardAnchorPos(searchIndex
)))) {
1508 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1509 if (searchDiff
< minDiff
) {
1510 minDiff
= searchDiff
;
1511 nextRowIndex
= searchIndex
;
1515 return nextRowIndex
;
1518 int KItemListController::previousRowIndex(int index
) const
1520 if (m_keyboardAnchorIndex
< 0 || index
== 0) {
1524 const bool leftToRight
= m_view
->layoutDirection() != Qt::RightToLeft
;
1526 // Calculate the index of the first column inside the row of the current index
1527 int firstColumnIndex
= index
;
1528 while ((leftToRight
&& keyboardAnchorPos(firstColumnIndex
- 1) < keyboardAnchorPos(firstColumnIndex
))
1529 || (!leftToRight
&& keyboardAnchorPos(firstColumnIndex
- 1) > keyboardAnchorPos(firstColumnIndex
))) {
1531 if (firstColumnIndex
<= 0) {
1536 // Based on the first column index go to the previous row and calculate the nearest index
1537 // that is above the current index
1538 int previousRowIndex
= firstColumnIndex
- 1;
1539 int searchIndex
= previousRowIndex
;
1540 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(previousRowIndex
));
1541 while (searchIndex
> 0
1542 && ((leftToRight
&& keyboardAnchorPos(searchIndex
- 1) < keyboardAnchorPos(searchIndex
))
1543 || (!leftToRight
&& keyboardAnchorPos(searchIndex
- 1) > keyboardAnchorPos(searchIndex
)))) {
1545 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1546 if (searchDiff
< minDiff
) {
1547 minDiff
= searchDiff
;
1548 previousRowIndex
= searchIndex
;
1552 return previousRowIndex
;
1555 qreal
KItemListController::keyboardAnchorPos(int index
) const
1557 const QRectF itemRect
= m_view
->itemRect(index
);
1558 if (!itemRect
.isEmpty()) {
1559 return (m_view
->scrollOrientation() == Qt::Vertical
) ? itemRect
.x() : itemRect
.y();
1565 void KItemListController::updateExtendedSelectionRegion()
1568 const bool extend
= (m_selectionBehavior
!= MultiSelection
);
1569 KItemListStyleOption option
= m_view
->styleOption();
1570 if (option
.extendedSelectionRegion
!= extend
) {
1571 option
.extendedSelectionRegion
= extend
;
1572 m_view
->setStyleOption(option
);
1577 bool KItemListController::onPress(const QPoint
&screenPos
, const QPointF
&pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
)
1579 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), buttons
);
1581 if (buttons
& (Qt::BackButton
| Qt::ForwardButton
)) {
1582 // Do not select items when clicking the back/forward buttons, see
1583 // https://bugs.kde.org/show_bug.cgi?id=327412.
1587 const QPointF pressedMousePos
= m_view
->transform().map(pos
);
1589 if (m_view
->isAboveExpansionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
)) {
1590 m_selectionManager
->endAnchoredSelection();
1591 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1592 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1596 m_selectionTogglePressed
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
);
1597 if (m_selectionTogglePressed
) {
1598 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1599 // The previous anchored selection has been finished already in
1600 // KItemListSelectionManager::setSelected(). We can safely change
1601 // the current item and start a new anchored selection now.
1602 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1603 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1607 const bool shiftPressed
= modifiers
& Qt::ShiftModifier
;
1608 const bool controlPressed
= (modifiers
& Qt::ControlModifier
) || m_selectionMode
; // Keeping selectionMode similar to pressing control will hopefully
1609 // simplify the overall logic and possibilities both for users and devs.
1610 const bool leftClick
= buttons
& Qt::LeftButton
;
1611 const bool rightClick
= buttons
& Qt::RightButton
;
1613 // The previous selection is cleared if either
1614 // 1. The selection mode is SingleSelection, or
1615 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1616 // a) Shift or Control are pressed.
1617 // b) The clicked item is selected already. In that case, the user might want to:
1618 // - start dragging multiple items, or
1619 // - open the context menu and perform an action for all selected items.
1620 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
1621 const bool pressedItemAlreadySelected
= m_pressedIndex
.has_value() && m_selectionManager
->isSelected(m_pressedIndex
.value());
1622 const bool clearSelection
= m_selectionBehavior
== SingleSelection
|| (!shiftOrControlPressed
&& !pressedItemAlreadySelected
);
1624 // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller.
1625 if (clearSelection
) {
1626 const int selectedItemsCount
= m_selectionManager
->selectedItems().count();
1627 m_selectionManager
->clearSelection();
1628 // clear and bail when we got an existing multi-selection
1629 if (selectedItemsCount
> 1 && m_pressedIndex
.has_value()) {
1630 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1631 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1632 if (pressedItemAlreadySelected
|| row
->iconRect().contains(mappedPos
) || row
->textRect().contains(mappedPos
)) {
1633 // we are indeed inside the text/icon rect, keep m_pressedIndex what it is
1634 // and short-circuit for single-click activation (it will then propagate to onRelease and activate the item)
1635 // or we just keep going for double-click activation
1636 if (m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) {
1637 if (!pressedItemAlreadySelected
) {
1638 // An unselected item was clicked directly while deselecting multiple other items so we select it.
1639 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1640 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1641 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1643 return true; // event handled, don't create rubber band
1646 // we're not inside the text/icon rect, as we've already cleared the selection
1647 // we can just stop here and make sure handlers down the line (i.e. onRelease) don't activate
1648 m_pressedIndex
.reset();
1649 // we don't stop event propagation and proceed to create a rubber band and let onRelease
1650 // decide (based on m_pressedIndex) whether we're in a drag (drag => new rubber band, click => don't select the item)
1654 } else if (pressedItemAlreadySelected
&& !shiftOrControlPressed
&& leftClick
) {
1655 // The user might want to start dragging multiple items, but if he clicks the item
1656 // in order to trigger it instead, the other selected items must be deselected.
1657 // However, we do not know yet what the user is going to do.
1658 // -> remember that the user pressed an item which had been selected already and
1659 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1660 m_clearSelectionIfItemsAreNotDragged
= true;
1662 if (m_selectionManager
->selectedItems().count() == 1 && m_view
->isAboveText(m_pressedIndex
.value_or(-1), pressedMousePos
)) {
1663 Q_EMIT
selectedItemTextPressed(m_pressedIndex
.value_or(-1));
1667 if (!shiftPressed
) {
1668 // Finish the anchored selection before the current index is changed
1669 m_selectionManager
->endAnchoredSelection();
1673 // Stop rubber band from persisting after right-clicks
1674 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1675 if (rubberBand
->isActive()) {
1676 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1677 rubberBand
->setActive(false);
1678 m_view
->setAutoScroll(false);
1682 if (m_pressedIndex
.has_value()) {
1683 // The hover highlight area of an item is being pressed.
1684 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
1685 const bool hitTargetIsRowEmptyRegion
= !row
->contains(row
->mapFromItem(m_view
, pos
));
1686 // again, when this method returns false, a rubberBand selection is created as the event is not consumed;
1687 // createRubberBand here tells us whether to return true or false.
1688 bool createRubberBand
= (hitTargetIsRowEmptyRegion
&& m_selectionManager
->selectedItems().isEmpty());
1690 if (rightClick
&& hitTargetIsRowEmptyRegion
) {
1691 // We have a right click outside the icon and text rect but within the hover highlight area.
1692 // We don't want items to get selected through this, so we return now.
1696 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1698 switch (m_selectionBehavior
) {
1702 case SingleSelection
:
1703 m_selectionManager
->setSelected(m_pressedIndex
.value());
1706 case MultiSelection
:
1707 if (controlPressed
&& !shiftPressed
&& leftClick
) {
1708 // A left mouse button press is happening on an item while control is pressed. This either means a user wants to:
1709 // - toggle the selection of item(s) or
1710 // - they want to begin a drag on the item(s) to copy them.
1711 // We rule out the latter, if the item is not clicked directly and was unselected previously.
1712 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1713 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1714 if (!row
->iconRect().contains(mappedPos
) && !row
->textRect().contains(mappedPos
) && !pressedItemAlreadySelected
) {
1715 createRubberBand
= true;
1717 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1718 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1719 createRubberBand
= false; // multi selection, don't propagate any further
1720 // This will be the start of an item drag-to-copy operation if the user now moves the mouse before releasing the mouse button.
1722 } else if (!shiftPressed
|| !m_selectionManager
->isAnchoredSelectionActive()) {
1723 // Select the pressed item and start a new anchored selection
1724 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1725 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1734 return !createRubberBand
;
1740 bool KItemListController::onRelease(const QPointF
&pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
, bool touch
)
1742 const QPointF pressedMousePos
= pos
;
1743 const bool isAboveSelectionToggle
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
);
1744 if (isAboveSelectionToggle
) {
1745 m_selectionTogglePressed
= false;
1749 if (!isAboveSelectionToggle
&& m_selectionTogglePressed
) {
1750 m_selectionManager
->setSelected(m_pressedIndex
.value_or(-1), 1, KItemListSelectionManager::Toggle
);
1751 m_selectionTogglePressed
= false;
1755 const bool controlPressed
= modifiers
& Qt::ControlModifier
;
1756 const bool shiftOrControlPressed
= modifiers
& Qt::ShiftModifier
|| controlPressed
;
1758 const std::optional
<int> index
= m_view
->itemAt(pos
);
1760 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1761 bool rubberBandRelease
= false;
1762 if (rubberBand
->isActive()) {
1763 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1764 rubberBand
->setActive(false);
1765 m_oldSelection
.clear();
1766 m_view
->setAutoScroll(false);
1767 rubberBandRelease
= true;
1768 // We check for actual rubber band drag here: if delta between start and end is less than drag threshold,
1769 // then we have a single click on one of the rows
1770 if ((rubberBand
->endPosition() - rubberBand
->startPosition()).manhattanLength() < QApplication::startDragDistance()) {
1771 rubberBandRelease
= false; // since we're only selecting, unmark rubber band release flag
1772 // m_pressedIndex will have no value if we came from a multi-selection clearing onPress
1773 // in that case, we don't select anything
1774 if (index
.has_value() && m_pressedIndex
.has_value()) {
1775 if (controlPressed
&& m_selectionBehavior
== MultiSelection
) {
1776 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1778 m_selectionManager
->setSelected(index
.value());
1780 if (!m_selectionManager
->isAnchoredSelectionActive()) {
1781 m_selectionManager
->beginAnchoredSelection(index
.value());
1787 if (index
.has_value() && index
== m_pressedIndex
) {
1788 // The release event is done above the same item as the press event
1790 if (m_clearSelectionIfItemsAreNotDragged
) {
1791 // A selected item has been clicked, but no drag operation has been started
1792 // -> clear the rest of the selection.
1793 m_selectionManager
->clearSelection();
1794 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1795 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1798 if (buttons
& Qt::LeftButton
) {
1799 bool emitItemActivated
= true;
1800 if (m_view
->isAboveExpansionToggle(index
.value(), pos
)) {
1801 const bool expanded
= m_model
->isExpanded(index
.value());
1802 m_model
->setExpanded(index
.value(), !expanded
);
1804 Q_EMIT
itemExpansionToggleClicked(index
.value());
1805 emitItemActivated
= false;
1806 } else if (shiftOrControlPressed
&& m_selectionBehavior
!= SingleSelection
) {
1807 // The mouse click should only update the selection, not trigger the item, except when
1808 // we are in single selection mode
1809 emitItemActivated
= false;
1811 const bool singleClickActivation
= m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
;
1812 if (!singleClickActivation
) {
1813 emitItemActivated
= touch
&& !m_selectionMode
;
1815 // activate on single click only if we didn't come from a rubber band release
1816 emitItemActivated
= !rubberBandRelease
;
1819 if (emitItemActivated
) {
1820 Q_EMIT
itemActivated(index
.value());
1822 } else if (buttons
& Qt::MiddleButton
) {
1823 Q_EMIT
itemMiddleClicked(index
.value());
1827 m_pressedMouseGlobalPos
= QPointF();
1828 m_pressedIndex
= std::nullopt
;
1829 m_clearSelectionIfItemsAreNotDragged
= false;
1833 void KItemListController::startRubberBand()
1835 if (m_selectionBehavior
== MultiSelection
) {
1836 QPoint startPos
= m_view
->transform().map(m_view
->scene()->views().first()->mapFromGlobal(m_pressedMouseGlobalPos
.toPoint()));
1837 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1838 startPos
.ry() += m_view
->scrollOffset();
1840 startPos
.rx() += m_view
->scrollOffset();
1843 m_oldSelection
= m_selectionManager
->selectedItems();
1844 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1845 rubberBand
->setStartPosition(startPos
);
1846 rubberBand
->setEndPosition(startPos
);
1847 rubberBand
->setActive(true);
1848 connect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1849 m_view
->setAutoScroll(true);
1853 void KItemListController::slotStateChanged(QScroller::State newState
)
1855 if (newState
== QScroller::Scrolling
) {
1856 m_scrollerIsScrolling
= true;
1857 } else if (newState
== QScroller::Inactive
) {
1858 m_scrollerIsScrolling
= false;
1862 #include "moc_kitemlistcontroller.cpp"