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 const bool horizontalScrolling
= m_view
->scrollOrientation() == Qt::Horizontal
;
246 // Handle the expanding/collapsing of items
247 // expand / collapse all selected directories
248 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
) && (key
== Qt::Key_Right
|| key
== Qt::Key_Left
)) {
249 const bool expandOrCollapse
= key
== Qt::Key_Right
? true : false;
250 bool shouldReturn
= m_model
->setExpanded(index
, expandOrCollapse
);
252 // edit in reverse to preserve index of the first handled items
253 const auto selectedItems
= m_selectionManager
->selectedItems();
254 for (auto it
= selectedItems
.rbegin(); it
!= selectedItems
.rend(); ++it
) {
255 shouldReturn
|= m_model
->setExpanded(*it
, expandOrCollapse
);
257 m_selectionManager
->setSelected(*it
);
261 // update keyboard anchors
263 m_keyboardAnchorIndex
= selectedItems
.count() > 0 ? qMin(index
, selectedItems
.last()) : index
;
264 m_keyboardAnchorPos
= keyboardAnchorPos(m_keyboardAnchorIndex
);
272 const bool controlPressed
= event
->modifiers() & Qt::ControlModifier
;
273 if (m_selectionMode
&& !controlPressed
&& !shiftPressed
&& (key
== Qt::Key_Enter
|| key
== Qt::Key_Return
)) {
274 key
= Qt::Key_Space
; // In selection mode one moves around with arrow keys and toggles selection with Enter.
276 const bool navigationPressed
= key
== Qt::Key_Home
|| key
== Qt::Key_End
|| key
== Qt::Key_PageUp
|| key
== Qt::Key_PageDown
|| key
== Qt::Key_Up
277 || key
== Qt::Key_Down
|| key
== Qt::Key_Left
|| key
== Qt::Key_Right
;
279 const int itemCount
= m_model
->count();
281 // For horizontal scroll orientation, transform
282 // the arrow keys to simplify the event handling.
283 if (horizontalScrolling
) {
302 if (m_view
->layoutDirection() == Qt::RightToLeft
) {
303 if (horizontalScrolling
) {
304 // swap up and down arrow keys
315 } else if (!m_view
->supportsItemExpanding()) {
316 // swap left and right arrow keys
330 const bool selectSingleItem
= m_selectionBehavior
!= NoSelection
&& itemCount
== 1 && navigationPressed
;
332 if (selectSingleItem
) {
333 const int current
= m_selectionManager
->currentItem();
334 m_selectionManager
->setSelected(current
);
341 m_keyboardAnchorIndex
= index
;
342 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
346 index
= itemCount
- 1;
347 m_keyboardAnchorIndex
= index
;
348 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
353 const int expandedParentsCount
= m_model
->expandedParentsCount(index
);
354 if (expandedParentsCount
== 0) {
357 // Go to the parent of the current item.
360 } while (index
> 0 && m_model
->expandedParentsCount(index
) == expandedParentsCount
);
362 m_keyboardAnchorIndex
= index
;
363 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
368 if (index
< itemCount
- 1) {
370 m_keyboardAnchorIndex
= index
;
371 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
376 updateKeyboardAnchor();
377 if (shiftPressed
&& !m_selectionManager
->isAnchoredSelectionActive() && m_selectionManager
->isSelected(index
)) {
378 m_selectionManager
->beginAnchoredSelection(index
);
380 index
= previousRowIndex(index
);
384 updateKeyboardAnchor();
385 if (shiftPressed
&& !m_selectionManager
->isAnchoredSelectionActive() && m_selectionManager
->isSelected(index
)) {
386 m_selectionManager
->beginAnchoredSelection(index
);
388 index
= nextRowIndex(index
);
392 if (horizontalScrolling
) {
393 // The new current index should correspond to the first item in the current column.
394 int newIndex
= qMax(index
- 1, 0);
395 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() < m_view
->itemRect(index
).topLeft().y()) {
397 newIndex
= qMax(index
- 1, 0);
399 m_keyboardAnchorIndex
= index
;
400 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
402 const qreal currentItemBottom
= m_view
->itemRect(index
).bottomLeft().y();
403 const qreal height
= m_view
->geometry().height();
405 // The new current item should be the first item in the current
406 // column whose itemRect's top coordinate is larger than targetY.
407 const qreal targetY
= currentItemBottom
- height
;
409 updateKeyboardAnchor();
410 int newIndex
= previousRowIndex(index
);
413 updateKeyboardAnchor();
414 newIndex
= previousRowIndex(index
);
415 } while (m_view
->itemRect(newIndex
).topLeft().y() > targetY
&& newIndex
!= index
);
419 case Qt::Key_PageDown
:
420 if (horizontalScrolling
) {
421 // The new current index should correspond to the last item in the current column.
422 int newIndex
= qMin(index
+ 1, m_model
->count() - 1);
423 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() > m_view
->itemRect(index
).topLeft().y()) {
425 newIndex
= qMin(index
+ 1, m_model
->count() - 1);
427 m_keyboardAnchorIndex
= index
;
428 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
430 const qreal currentItemTop
= m_view
->itemRect(index
).topLeft().y();
431 const qreal height
= m_view
->geometry().height();
433 // The new current item should be the last item in the current
434 // column whose itemRect's bottom coordinate is smaller than targetY.
435 const qreal targetY
= currentItemTop
+ height
;
437 updateKeyboardAnchor();
438 int newIndex
= nextRowIndex(index
);
441 updateKeyboardAnchor();
442 newIndex
= nextRowIndex(index
);
443 } while (m_view
->itemRect(newIndex
).bottomLeft().y() < targetY
&& newIndex
!= index
);
448 case Qt::Key_Return
: {
449 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
450 if (selectedItems
.count() >= 2) {
451 Q_EMIT
itemsActivated(selectedItems
);
452 } else if (selectedItems
.count() == 1) {
453 Q_EMIT
itemActivated(selectedItems
.first());
455 Q_EMIT
itemActivated(index
);
461 if (m_selectionMode
) {
462 Q_EMIT
selectionModeChangeRequested(false);
463 } else if (m_selectionBehavior
!= SingleSelection
) {
464 m_selectionManager
->clearSelection();
466 m_keyboardManager
->cancelSearch();
467 Q_EMIT
escapePressed();
471 if (m_selectionBehavior
== MultiSelection
) {
472 if (controlPressed
|| m_selectionMode
) {
473 // Toggle the selection state of the current item.
474 m_selectionManager
->endAnchoredSelection();
475 m_selectionManager
->setSelected(index
, 1, KItemListSelectionManager::Toggle
);
476 m_selectionManager
->beginAnchoredSelection(index
);
479 // Select the current item if it is not selected yet.
480 const int current
= m_selectionManager
->currentItem();
481 if (!m_selectionManager
->isSelected(current
)) {
482 m_selectionManager
->setSelected(current
);
487 Q_FALLTHROUGH(); // fall through to the default case and add the Space to the current search string.
489 m_keyboardManager
->addKeys(event
->text());
490 // Make sure unconsumed events get propagated up the chain. #302329
495 if (m_selectionManager
->currentItem() != index
) {
496 switch (m_selectionBehavior
) {
498 m_selectionManager
->setCurrentItem(index
);
501 case SingleSelection
:
502 m_selectionManager
->setCurrentItem(index
);
503 m_selectionManager
->clearSelection();
504 m_selectionManager
->setSelected(index
, 1);
508 if (controlPressed
|| (m_selectionMode
&& !shiftPressed
)) {
509 m_selectionManager
->endAnchoredSelection();
512 m_selectionManager
->setCurrentItem(index
);
514 if (!shiftPressed
&& !controlPressed
&& !m_selectionMode
) {
515 m_selectionManager
->clearSelection();
516 m_selectionManager
->setSelected(index
, 1);
520 m_selectionManager
->beginAnchoredSelection(index
);
526 if (navigationPressed
) {
527 m_view
->scrollToItem(index
);
532 void KItemListController::slotChangeCurrentItem(const QString
&text
, bool searchFromNextItem
)
534 if (!m_model
|| m_model
->count() == 0) {
538 if (searchFromNextItem
) {
539 const int currentIndex
= m_selectionManager
->currentItem();
540 index
= m_model
->indexForKeyboardSearch(text
, (currentIndex
+ 1) % m_model
->count());
542 index
= m_model
->indexForKeyboardSearch(text
, 0);
545 if (m_selectionMode
) {
546 m_selectionManager
->endAnchoredSelection();
549 m_selectionManager
->setCurrentItem(index
);
551 if (m_selectionBehavior
!= NoSelection
) {
552 if (!m_selectionMode
) { // Don't clear the selection in selection mode.
553 m_selectionManager
->replaceSelection(index
);
555 m_selectionManager
->beginAnchoredSelection(index
);
558 m_view
->scrollToItem(index
, KItemListView::ViewItemPosition::Beginning
);
562 void KItemListController::slotAutoActivationTimeout()
564 if (!m_model
|| !m_view
) {
568 const int index
= m_autoActivationTimer
->property("index").toInt();
569 if (index
< 0 || index
>= m_model
->count()) {
573 /* m_view->isUnderMouse() fixes a bug in the Folder-View-Panel and in the
576 * Bug: When you drag a file onto a Folder-View-Item or a Places-Item and
577 * then move away before the auto-activation timeout triggers, than the
578 * item still becomes activated/expanded.
580 * See Bug 293200 and 305783
582 if (m_view
->isUnderMouse()) {
583 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
)) {
584 const bool expanded
= m_model
->isExpanded(index
);
585 m_model
->setExpanded(index
, !expanded
);
586 } else if (m_autoActivationBehavior
!= ExpansionOnly
) {
587 Q_EMIT
itemActivated(index
);
592 bool KItemListController::inputMethodEvent(QInputMethodEvent
*event
)
598 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
601 m_pressedMouseGlobalPos
= event
->screenPos();
603 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& m_isTouchEvent
) {
611 const QPointF pressedMousePos
= transform
.map(event
->pos());
612 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
614 const Qt::MouseButtons buttons
= event
->buttons();
616 if (!onPress(event
->pos(), event
->modifiers(), buttons
)) {
624 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
630 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
631 m_view
->m_tapAndHoldIndicator
->setActive(false);
634 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !m_dragActionOrRightClick
&& m_isTouchEvent
) {
638 if (m_pressedIndex
.has_value() && !m_view
->rubberBand()->isActive()) {
639 // Check whether a dragging should be started
640 if (event
->buttons() & Qt::LeftButton
) {
641 const auto distance
= (event
->screenPos() - m_pressedMouseGlobalPos
).manhattanLength();
642 if (distance
>= QApplication::startDragDistance()) {
643 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
644 // Always assure that the dragged item gets selected. Usually this is already
645 // done on the mouse-press event, but when using the selection-toggle on a
646 // selected item the dragged item is not selected yet.
647 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
649 // A selected item has been clicked to drag all selected items
650 // -> the selection should not be cleared when the mouse button is released.
651 m_clearSelectionIfItemsAreNotDragged
= false;
654 m_mousePress
= false;
658 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
659 if (rubberBand
->isActive()) {
660 QPointF endPos
= transform
.map(event
->pos());
662 // Update the current item.
663 const std::optional
<int> newCurrent
= m_view
->itemAt(endPos
);
664 if (newCurrent
.has_value()) {
665 // It's expected that the new current index is also the new anchor (bug 163451).
666 m_selectionManager
->endAnchoredSelection();
667 m_selectionManager
->setCurrentItem(newCurrent
.value());
668 m_selectionManager
->beginAnchoredSelection(newCurrent
.value());
671 if (m_view
->scrollOrientation() == Qt::Vertical
) {
672 endPos
.ry() += m_view
->scrollOffset();
674 endPos
.rx() += m_view
->scrollOffset();
676 rubberBand
->setEndPosition(endPos
);
683 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
685 m_mousePress
= false;
686 m_isTouchEvent
= false;
692 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
693 m_view
->m_tapAndHoldIndicator
->setActive(false);
696 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
697 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !rubberBand
->isActive() && m_isTouchEvent
) {
701 Q_EMIT
mouseButtonReleased(m_pressedIndex
.value_or(-1), event
->buttons());
703 return onRelease(transform
.map(event
->pos()), event
->modifiers(), event
->button(), false);
706 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
708 const QPointF pos
= transform
.map(event
->pos());
709 const std::optional
<int> index
= m_view
->itemAt(pos
);
711 if (event
->button() & (Qt::ForwardButton
| Qt::BackButton
)) {
712 // "Forward" and "Back" are reserved for quickly navigating through the
713 // history. Double-clicking those buttons should be interpreted as two
714 // separate button presses. We arrive here for the second click, which
715 // we now react to just as we would for a singular click
716 Q_EMIT
mouseButtonPressed(index
.value_or(-1), event
->button());
720 if (!index
.has_value()) {
721 Q_EMIT
doubleClickViewBackground(event
->button());
725 // Expand item if desired - See Bug 295573
726 if (m_mouseDoubleClickAction
!= ActivateItemOnly
) {
727 if (m_view
&& m_model
&& m_view
->supportsItemExpanding() && m_model
->isExpandable(index
.value_or(-1))) {
728 const bool expanded
= m_model
->isExpanded(index
.value());
729 m_model
->setExpanded(index
.value(), !expanded
);
733 if (event
->button() & ~Qt::LeftButton
) {
737 if (m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) {
741 const bool emitItemActivated
= index
.has_value() && index
.value() < m_model
->count() && !m_view
->isAboveExpansionToggle(index
.value(), pos
);
742 if (emitItemActivated
) {
743 if (!QApplication::keyboardModifiers()) {
744 m_selectionManager
->clearSelection(); // The user does not want to manage/manipulate the item currently, only activate it.
746 Q_EMIT
itemActivated(index
.value());
751 bool KItemListController::contextMenuEvent(QContextMenuEvent
*event
)
753 if (event
->reason() == QContextMenuEvent::Keyboard
) {
754 // Emit the signal itemContextMenuRequested() if at least one item is selected.
755 // Otherwise the signal viewContextMenuRequested() will be emitted.
756 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
758 if (selectedItems
.count() >= 2) {
759 const int currentItemIndex
= m_selectionManager
->currentItem();
760 index
= selectedItems
.contains(currentItemIndex
) ? currentItemIndex
: selectedItems
.first();
761 } else if (selectedItems
.count() == 1) {
762 index
= selectedItems
.first();
766 const QRectF contextRect
= m_view
->itemContextRect(index
);
767 const QPointF
pos(m_view
->scene()->views().first()->mapToGlobal(contextRect
.bottomRight().toPoint()));
768 Q_EMIT
itemContextMenuRequested(index
, pos
);
770 Q_EMIT
viewContextMenuRequested(event
->globalPos());
775 const auto pos
= event
->pos();
776 const auto globalPos
= event
->globalPos();
778 if (m_view
->headerBoundaries().contains(pos
)) {
779 Q_EMIT
headerContextMenuRequested(globalPos
);
783 const auto pressedItem
= m_view
->itemAt(pos
);
784 // We only open a context menu for the pressed item if it is selected.
785 // 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.
786 if (pressedItem
&& m_selectionManager
->selectedItems().contains(pressedItem
.value())) {
787 // The selection rectangle for an item was clicked
788 Q_EMIT
itemContextMenuRequested(pressedItem
.value(), globalPos
);
792 // Remove any hover highlights so the context menu doesn't look like it applies to a row.
793 const auto widgets
= m_view
->visibleItemListWidgets();
794 for (KItemListWidget
*widget
: widgets
) {
795 if (widget
->isHovered()) {
796 widget
->setHovered(false);
797 Q_EMIT
itemUnhovered(widget
->index());
800 Q_EMIT
viewContextMenuRequested(globalPos
);
804 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
809 DragAndDropHelper::clearUrlListMatchesUrlCache();
814 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
819 m_autoActivationTimer
->stop();
820 m_view
->setAutoScroll(false);
821 m_view
->hideDropIndicator();
823 KItemListWidget
*widget
= hoveredWidget();
825 widget
->setHovered(false);
826 Q_EMIT
itemUnhovered(widget
->index());
831 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
833 if (!m_model
|| !m_view
) {
837 QUrl hoveredDir
= m_model
->directory();
838 KItemListWidget
*oldHoveredWidget
= hoveredWidget();
840 const QPointF pos
= transform
.map(event
->pos());
841 KItemListWidget
*newHoveredWidget
= widgetForDropPos(pos
);
844 if (oldHoveredWidget
!= newHoveredWidget
) {
845 m_autoActivationTimer
->stop();
847 if (oldHoveredWidget
) {
848 oldHoveredWidget
->setHovered(false);
849 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
853 if (newHoveredWidget
) {
854 bool droppingBetweenItems
= false;
855 if (m_model
->sortRole().isEmpty()) {
856 // The model supports inserting items between other items.
857 droppingBetweenItems
= (m_view
->showDropIndicator(pos
) >= 0);
860 index
= newHoveredWidget
->index();
862 if (m_model
->isDir(index
)) {
863 hoveredDir
= m_model
->url(index
);
866 if (!droppingBetweenItems
) {
867 // Something has been dragged on an item.
868 m_view
->hideDropIndicator();
869 if (!newHoveredWidget
->isHovered()) {
870 newHoveredWidget
->setHovered(true);
871 Q_EMIT
itemHovered(index
);
874 if (!m_autoActivationTimer
->isActive() && m_autoActivationTimer
->interval() >= 0 && m_model
->canEnterOnHover(index
)) {
875 m_autoActivationTimer
->setProperty("index", index
);
876 m_autoActivationTimer
->start();
877 newHoveredWidget
->startActivateSoonAnimation(m_autoActivationTimer
->remainingTime());
881 m_autoActivationTimer
->stop();
882 if (newHoveredWidget
&& newHoveredWidget
->isHovered()) {
883 newHoveredWidget
->setHovered(false);
884 Q_EMIT
itemUnhovered(index
);
888 m_view
->hideDropIndicator();
891 if (DragAndDropHelper::urlListMatchesUrl(event
->mimeData()->urls(), hoveredDir
)) {
892 event
->setDropAction(Qt::IgnoreAction
);
895 if (m_model
->supportsDropping(index
)) {
896 event
->setDropAction(event
->proposedAction());
899 event
->setDropAction(Qt::IgnoreAction
);
906 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
912 m_autoActivationTimer
->stop();
913 m_view
->setAutoScroll(false);
915 const QPointF pos
= transform
.map(event
->pos());
917 int dropAboveIndex
= -1;
918 if (m_model
->sortRole().isEmpty()) {
919 // The model supports inserting of items between other items.
920 dropAboveIndex
= m_view
->showDropIndicator(pos
);
923 if (dropAboveIndex
>= 0) {
924 // Something has been dropped between two items.
925 m_view
->hideDropIndicator();
926 Q_EMIT
aboveItemDropEvent(dropAboveIndex
, event
);
927 } else if (!event
->mimeData()->hasFormat(m_model
->blacklistItemDropEventMimeType())) {
928 // Something has been dropped on an item or on an empty part of the view.
929 const KItemListWidget
*receivingWidget
= widgetForDropPos(pos
);
930 if (receivingWidget
) {
931 Q_EMIT
itemDropEvent(receivingWidget
->index(), event
);
933 Q_EMIT
itemDropEvent(-1, event
);
937 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropEnd
);
938 QAccessible::updateAccessibility(&accessibilityEvent
);
943 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
950 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
953 if (!m_model
|| !m_view
) {
957 // We identify the widget whose expansionArea had been hovered before this hoverMoveEvent() triggered.
958 // we can't use hoveredWidget() here (it handles the icon+text rect, not the expansion rect)
959 // like hoveredWidget(), we find the hovered widget for the expansion rect
960 const auto visibleItemListWidgets
= m_view
->visibleItemListWidgets();
961 const auto oldHoveredExpansionWidgetIterator
= std::find_if(visibleItemListWidgets
.begin(), visibleItemListWidgets
.end(), [](auto &widget
) {
962 return widget
->expansionAreaHovered();
964 const auto oldHoveredExpansionWidget
=
965 oldHoveredExpansionWidgetIterator
== visibleItemListWidgets
.end() ? std::nullopt
: std::make_optional(*oldHoveredExpansionWidgetIterator
);
967 const auto unhoverOldHoveredWidget
= [&]() {
968 if (auto oldHoveredWidget
= hoveredWidget(); oldHoveredWidget
) {
969 // handle the text+icon one
970 oldHoveredWidget
->setHovered(false);
971 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
975 const auto unhoverOldExpansionWidget
= [&]() {
976 if (oldHoveredExpansionWidget
) {
977 // then the expansion toggle
978 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
982 const QPointF pos
= transform
.map(event
->pos());
983 if (KItemListWidget
*newHoveredWidget
= widgetForPos(pos
); newHoveredWidget
) {
984 // something got hovered, work out which part and set hover for the appropriate widget
985 const auto mappedPos
= newHoveredWidget
->mapFromItem(m_view
, pos
);
986 const bool isOnExpansionToggle
= newHoveredWidget
->expansionToggleRect().contains(mappedPos
);
988 if (isOnExpansionToggle
) {
989 // make sure we unhover the old one first if old!=new
990 if (oldHoveredExpansionWidget
&& *oldHoveredExpansionWidget
!= newHoveredWidget
) {
991 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
993 // 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)
994 unhoverOldHoveredWidget();
996 newHoveredWidget
->setExpansionAreaHovered(true);
998 // make sure we unhover the old one first if old!=new
999 auto oldHoveredWidget
= hoveredWidget();
1000 if (oldHoveredWidget
&& oldHoveredWidget
!= newHoveredWidget
) {
1001 oldHoveredWidget
->setHovered(false);
1002 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
1004 // 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)
1005 unhoverOldExpansionWidget();
1007 const bool isOverIconAndText
= newHoveredWidget
->iconRect().contains(mappedPos
) || newHoveredWidget
->textRect().contains(mappedPos
);
1008 const bool hasMultipleSelection
= m_selectionManager
->selectedItems().count() > 1;
1010 if (hasMultipleSelection
&& !isOverIconAndText
) {
1011 // In case we have multiple selections, clicking on any row will deselect the selection.
1012 // So, as a visual cue for signalling that clicking anywhere won't select, but clear current highlights,
1013 // we disable hover of the *row*(i.e. blank space to the right of the icon+text)
1015 // (no-op in this branch for masked hover)
1017 newHoveredWidget
->setHoverPosition(mappedPos
);
1018 if (oldHoveredWidget
!= newHoveredWidget
) {
1019 newHoveredWidget
->setHovered(true);
1020 Q_EMIT
itemHovered(newHoveredWidget
->index());
1025 // unhover any currently hovered expansion and text+icon widgets
1026 unhoverOldHoveredWidget();
1027 unhoverOldExpansionWidget();
1032 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
1037 m_mousePress
= false;
1038 m_isTouchEvent
= false;
1040 if (!m_model
|| !m_view
) {
1044 const auto widgets
= m_view
->visibleItemListWidgets();
1045 for (KItemListWidget
*widget
: widgets
) {
1046 if (widget
->isHovered()) {
1047 widget
->setHovered(false);
1048 Q_EMIT
itemUnhovered(widget
->index());
1054 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent
*event
, const QTransform
&transform
)
1061 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent
*event
, const QTransform
&transform
)
1068 bool KItemListController::gestureEvent(QGestureEvent
*event
, const QTransform
&transform
)
1074 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
1075 //we use this to get the right QWidget
1076 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
1077 if (!m_mousePress
) {
1078 if (QGesture
*tap
= event
->gesture(Qt::TapGesture
)) {
1079 QTapGesture
*tapGesture
= static_cast<QTapGesture
*>(tap
);
1080 if (tapGesture
->state() == Qt::GestureStarted
) {
1081 tapTriggered(tapGesture
, transform
);
1087 bool accepted
= false;
1089 if (QGesture
*tap
= event
->gesture(Qt::TapGesture
)) {
1090 tapTriggered(static_cast<QTapGesture
*>(tap
), transform
);
1093 if (event
->gesture(Qt::TapAndHoldGesture
)) {
1094 tapAndHoldTriggered(event
, transform
);
1097 if (event
->gesture(Qt::PinchGesture
)) {
1098 pinchTriggered(event
, transform
);
1101 if (event
->gesture(m_swipeGesture
)) {
1102 swipeTriggered(event
, transform
);
1105 if (event
->gesture(m_twoFingerTapGesture
)) {
1106 twoFingerTapTriggered(event
, transform
);
1112 bool KItemListController::touchBeginEvent(QTouchEvent
*event
, const QTransform
&transform
)
1117 m_isTouchEvent
= true;
1121 void KItemListController::tapTriggered(QTapGesture
*tap
, const QTransform
&transform
)
1123 static bool scrollerWasActive
= false;
1125 if (tap
->state() == Qt::GestureStarted
) {
1126 m_dragActionOrRightClick
= false;
1127 m_isSwipeGesture
= false;
1128 m_pinchGestureInProgress
= false;
1129 scrollerWasActive
= m_scrollerIsScrolling
;
1132 if (tap
->state() == Qt::GestureFinished
) {
1133 m_mousePress
= false;
1135 //if at the moment of the gesture start the QScroller was active, the user made the tap
1136 //to stop the QScroller and not to tap on an item
1137 if (scrollerWasActive
) {
1141 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
1142 m_view
->m_tapAndHoldIndicator
->setActive(false);
1145 const QPointF pressedMousePos
= transform
.map(tap
->position());
1146 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1147 if (m_dragActionOrRightClick
) {
1148 m_dragActionOrRightClick
= false;
1150 onPress(tap
->position().toPoint(), Qt::NoModifier
, Qt::LeftButton
);
1151 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::LeftButton
, true);
1153 m_isTouchEvent
= false;
1157 void KItemListController::tapAndHoldTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1159 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
1160 if (!m_isTouchEvent
) {
1164 const QTapAndHoldGesture
*tap
= static_cast<QTapAndHoldGesture
*>(event
->gesture(Qt::TapAndHoldGesture
));
1165 if (tap
->state() == Qt::GestureFinished
) {
1166 //if a pinch gesture is in progress we don't want a TabAndHold gesture
1167 if (m_pinchGestureInProgress
) {
1170 const QPointF pressedMousePos
= transform
.map(event
->mapToGraphicsScene(tap
->position()));
1171 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1172 if (m_pressedIndex
.has_value()) {
1173 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
1174 m_selectionManager
->clearSelection();
1175 m_selectionManager
->setSelected(m_pressedIndex
.value());
1177 if (!m_selectionMode
) {
1178 Q_EMIT
selectionModeChangeRequested(true);
1181 m_selectionManager
->clearSelection();
1185 Q_EMIT
scrollerStop();
1187 m_view
->m_tapAndHoldIndicator
->setStartPosition(pressedMousePos
);
1188 m_view
->m_tapAndHoldIndicator
->setActive(true);
1190 m_dragActionOrRightClick
= true;
1194 void KItemListController::pinchTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1198 const QPinchGesture
*pinch
= static_cast<QPinchGesture
*>(event
->gesture(Qt::PinchGesture
));
1199 const qreal sensitivityModifier
= 0.2;
1200 static qreal counter
= 0;
1202 if (pinch
->state() == Qt::GestureStarted
) {
1203 m_pinchGestureInProgress
= true;
1206 if (pinch
->state() == Qt::GestureUpdated
) {
1207 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1208 if (m_isSwipeGesture
) {
1211 counter
= counter
+ (pinch
->scaleFactor() - 1);
1212 if (counter
>= sensitivityModifier
) {
1213 Q_EMIT
increaseZoom();
1215 } else if (counter
<= -sensitivityModifier
) {
1216 Q_EMIT
decreaseZoom();
1222 void KItemListController::swipeTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1226 const KTwoFingerSwipe
*swipe
= static_cast<KTwoFingerSwipe
*>(event
->gesture(m_swipeGesture
));
1231 if (swipe
->state() == Qt::GestureStarted
) {
1232 m_isSwipeGesture
= true;
1235 if (swipe
->state() == Qt::GestureCanceled
) {
1236 m_isSwipeGesture
= false;
1239 if (swipe
->state() == Qt::GestureFinished
) {
1240 Q_EMIT
scrollerStop();
1242 if (swipe
->swipeAngle() <= 20 || swipe
->swipeAngle() >= 340) {
1243 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::BackButton
);
1244 } else if (swipe
->swipeAngle() <= 200 && swipe
->swipeAngle() >= 160) {
1245 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::ForwardButton
);
1246 } else if (swipe
->swipeAngle() <= 110 && swipe
->swipeAngle() >= 60) {
1249 m_isSwipeGesture
= true;
1253 void KItemListController::twoFingerTapTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1255 const KTwoFingerTap
*twoTap
= static_cast<KTwoFingerTap
*>(event
->gesture(m_twoFingerTapGesture
));
1261 if (twoTap
->state() == Qt::GestureStarted
) {
1262 const QPointF pressedMousePos
= transform
.map(twoTap
->pos());
1263 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1264 if (m_pressedIndex
.has_value()) {
1265 onPress(twoTap
->pos().toPoint(), Qt::ControlModifier
, Qt::LeftButton
);
1266 onRelease(transform
.map(twoTap
->pos()), Qt::ControlModifier
, Qt::LeftButton
, false);
1271 bool KItemListController::processEvent(QEvent
*event
, const QTransform
&transform
)
1277 switch (event
->type()) {
1278 case QEvent::KeyPress
:
1279 return keyPressEvent(static_cast<QKeyEvent
*>(event
));
1280 case QEvent::InputMethod
:
1281 return inputMethodEvent(static_cast<QInputMethodEvent
*>(event
));
1282 case QEvent::GraphicsSceneMousePress
:
1283 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1284 case QEvent::GraphicsSceneMouseMove
:
1285 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1286 case QEvent::GraphicsSceneMouseRelease
:
1287 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1288 case QEvent::GraphicsSceneMouseDoubleClick
:
1289 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1290 case QEvent::ContextMenu
:
1291 return contextMenuEvent(static_cast<QContextMenuEvent
*>(event
));
1292 case QEvent::GraphicsSceneWheel
:
1293 return wheelEvent(static_cast<QGraphicsSceneWheelEvent
*>(event
), QTransform());
1294 case QEvent::GraphicsSceneDragEnter
:
1295 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1296 case QEvent::GraphicsSceneDragLeave
:
1297 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1298 case QEvent::GraphicsSceneDragMove
:
1299 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1300 case QEvent::GraphicsSceneDrop
:
1301 return dropEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1302 case QEvent::GraphicsSceneHoverEnter
:
1303 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1304 case QEvent::GraphicsSceneHoverMove
:
1305 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1306 case QEvent::GraphicsSceneHoverLeave
:
1307 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1308 case QEvent::GraphicsSceneResize
:
1309 return resizeEvent(static_cast<QGraphicsSceneResizeEvent
*>(event
), transform
);
1310 case QEvent::Gesture
:
1311 return gestureEvent(static_cast<QGestureEvent
*>(event
), transform
);
1312 case QEvent::TouchBegin
:
1313 return touchBeginEvent(static_cast<QTouchEvent
*>(event
), transform
);
1321 void KItemListController::slotViewScrollOffsetChanged(qreal current
, qreal previous
)
1327 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1328 if (rubberBand
->isActive()) {
1329 const qreal diff
= current
- previous
;
1330 // TODO: Ideally just QCursor::pos() should be used as
1331 // new end-position but it seems there is no easy way
1332 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1333 // (... or I just missed an easy way to do the mapping)
1334 QPointF endPos
= rubberBand
->endPosition();
1335 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1336 endPos
.ry() += diff
;
1338 endPos
.rx() += diff
;
1341 rubberBand
->setEndPosition(endPos
);
1345 void KItemListController::slotRubberBandChanged()
1347 if (!m_view
|| !m_model
|| m_model
->count() <= 0) {
1351 const KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1352 const QPointF startPos
= rubberBand
->startPosition();
1353 const QPointF endPos
= rubberBand
->endPosition();
1354 QRectF rubberBandRect
= QRectF(startPos
, endPos
).normalized();
1356 const bool scrollVertical
= (m_view
->scrollOrientation() == Qt::Vertical
);
1357 if (scrollVertical
) {
1358 rubberBandRect
.translate(0, -m_view
->scrollOffset());
1360 rubberBandRect
.translate(-m_view
->scrollOffset(), 0);
1363 if (!m_oldSelection
.isEmpty()) {
1364 // Clear the old selection that was available before the rubberband has
1365 // been activated in case if no Shift- or Control-key are pressed
1366 const bool shiftOrControlPressed
= QApplication::keyboardModifiers() & Qt::ShiftModifier
|| QApplication::keyboardModifiers() & Qt::ControlModifier
;
1367 if (!shiftOrControlPressed
&& !m_selectionMode
) {
1368 m_oldSelection
.clear();
1372 KItemSet selectedItems
;
1374 // Select all visible items that intersect with the rubberband
1375 const auto widgets
= m_view
->visibleItemListWidgets();
1376 for (const KItemListWidget
*widget
: widgets
) {
1377 const int index
= widget
->index();
1379 const QRectF widgetRect
= m_view
->itemRect(index
);
1380 if (widgetRect
.intersects(rubberBandRect
)) {
1381 // Select the full row intersecting with the rubberband rectangle
1382 const QRectF selectionRect
= widget
->selectionRect().translated(widgetRect
.topLeft());
1383 const QRectF iconRect
= widget
->iconRect().translated(widgetRect
.topLeft());
1384 if (selectionRect
.intersects(rubberBandRect
) || iconRect
.intersects(rubberBandRect
)) {
1385 selectedItems
.insert(index
);
1390 // Select all invisible items that intersect with the rubberband. Instead of
1391 // iterating all items only the area which might be touched by the rubberband
1393 const bool increaseIndex
= scrollVertical
? startPos
.y() > endPos
.y() : startPos
.x() > endPos
.x();
1395 int index
= increaseIndex
? m_view
->lastVisibleIndex() + 1 : m_view
->firstVisibleIndex() - 1;
1396 bool selectionFinished
= false;
1398 const QRectF widgetRect
= m_view
->itemRect(index
);
1399 if (widgetRect
.intersects(rubberBandRect
)) {
1400 selectedItems
.insert(index
);
1403 if (increaseIndex
) {
1405 selectionFinished
= (index
>= m_model
->count()) || (scrollVertical
&& widgetRect
.top() > rubberBandRect
.bottom())
1406 || (!scrollVertical
&& widgetRect
.left() > rubberBandRect
.right());
1409 selectionFinished
= (index
< 0) || (scrollVertical
&& widgetRect
.bottom() < rubberBandRect
.top())
1410 || (!scrollVertical
&& widgetRect
.right() < rubberBandRect
.left());
1412 } while (!selectionFinished
);
1414 if ((QApplication::keyboardModifiers() & Qt::ControlModifier
) || m_selectionMode
) {
1415 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1416 // Therefore, the new selection contains:
1417 // 1. All previously selected items which are not inside the rubberband, and
1418 // 2. all items inside the rubberband which have not been selected previously.
1419 m_selectionManager
->setSelectedItems(m_oldSelection
^ selectedItems
);
1421 m_selectionManager
->setSelectedItems(selectedItems
+ m_oldSelection
);
1425 void KItemListController::startDragging()
1427 if (!m_view
|| !m_model
) {
1431 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
1432 if (selectedItems
.isEmpty()) {
1436 QMimeData
*data
= m_model
->createMimeData(selectedItems
);
1440 KUrlMimeData::exportUrlsToPortal(data
);
1442 // The created drag object will be owned and deleted
1443 // by QApplication::activeWindow().
1444 QDrag
*drag
= new QDrag(QApplication::activeWindow());
1445 drag
->setMimeData(data
);
1447 const QPixmap pixmap
= m_view
->createDragPixmap(selectedItems
);
1448 drag
->setPixmap(pixmap
);
1450 const QPoint
hotSpot((pixmap
.width() / pixmap
.devicePixelRatio()) / 2, 0);
1451 drag
->setHotSpot(hotSpot
);
1453 drag
->exec(Qt::MoveAction
| Qt::CopyAction
| Qt::LinkAction
, Qt::CopyAction
);
1455 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropStart
);
1456 QAccessible::updateAccessibility(&accessibilityEvent
);
1459 KItemListWidget
*KItemListController::hoveredWidget() const
1463 const auto widgets
= m_view
->visibleItemListWidgets();
1464 for (KItemListWidget
*widget
: widgets
) {
1465 if (widget
->isHovered()) {
1473 KItemListWidget
*KItemListController::widgetForPos(const QPointF
&pos
) const
1477 if (m_view
->headerBoundaries().contains(pos
)) {
1481 const auto widgets
= m_view
->visibleItemListWidgets();
1482 for (KItemListWidget
*widget
: widgets
) {
1483 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1484 if (widget
->contains(mappedPos
) || widget
->selectionRect().contains(mappedPos
)) {
1492 KItemListWidget
*KItemListController::widgetForDropPos(const QPointF
&pos
) const
1496 if (m_view
->headerBoundaries().contains(pos
)) {
1500 const auto widgets
= m_view
->visibleItemListWidgets();
1501 for (KItemListWidget
*widget
: widgets
) {
1502 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1503 if (widget
->contains(mappedPos
)) {
1511 void KItemListController::updateKeyboardAnchor()
1513 const bool validAnchor
=
1514 m_keyboardAnchorIndex
>= 0 && m_keyboardAnchorIndex
< m_model
->count() && keyboardAnchorPos(m_keyboardAnchorIndex
) == m_keyboardAnchorPos
;
1516 const int index
= m_selectionManager
->currentItem();
1517 m_keyboardAnchorIndex
= index
;
1518 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
1522 int KItemListController::nextRowIndex(int index
) const
1524 if (m_keyboardAnchorIndex
< 0) {
1528 const int maxIndex
= m_model
->count() - 1;
1529 if (index
== maxIndex
) {
1533 const bool reversed
= m_view
->layoutDirection() == Qt::RightToLeft
&& m_view
->scrollOrientation() == Qt::Vertical
;
1535 // Calculate the index of the last column inside the row of the current index
1536 int lastColumnIndex
= index
;
1537 while ((!reversed
&& keyboardAnchorPos(lastColumnIndex
+ 1) > keyboardAnchorPos(lastColumnIndex
))
1538 || (reversed
&& keyboardAnchorPos(lastColumnIndex
+ 1) < keyboardAnchorPos(lastColumnIndex
))) {
1540 if (lastColumnIndex
>= maxIndex
) {
1545 // Based on the last column index go to the next row and calculate the nearest index
1546 // that is below the current index
1547 int nextRowIndex
= lastColumnIndex
+ 1;
1548 int searchIndex
= nextRowIndex
;
1549 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(nextRowIndex
));
1550 while (searchIndex
< maxIndex
1551 && ((!reversed
&& keyboardAnchorPos(searchIndex
+ 1) > keyboardAnchorPos(searchIndex
))
1552 || (reversed
&& keyboardAnchorPos(searchIndex
+ 1) < keyboardAnchorPos(searchIndex
)))) {
1554 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1555 if (searchDiff
< minDiff
) {
1556 minDiff
= searchDiff
;
1557 nextRowIndex
= searchIndex
;
1561 return nextRowIndex
;
1564 int KItemListController::previousRowIndex(int index
) const
1566 if (m_keyboardAnchorIndex
< 0 || index
== 0) {
1570 const bool reversed
= m_view
->layoutDirection() == Qt::RightToLeft
&& m_view
->scrollOrientation() == Qt::Vertical
;
1572 // Calculate the index of the first column inside the row of the current index
1573 int firstColumnIndex
= index
;
1574 while ((!reversed
&& keyboardAnchorPos(firstColumnIndex
- 1) < keyboardAnchorPos(firstColumnIndex
))
1575 || (reversed
&& keyboardAnchorPos(firstColumnIndex
- 1) > keyboardAnchorPos(firstColumnIndex
))) {
1577 if (firstColumnIndex
<= 0) {
1582 // Based on the first column index go to the previous row and calculate the nearest index
1583 // that is above the current index
1584 int previousRowIndex
= firstColumnIndex
- 1;
1585 int searchIndex
= previousRowIndex
;
1586 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(previousRowIndex
));
1587 while (searchIndex
> 0
1588 && ((!reversed
&& keyboardAnchorPos(searchIndex
- 1) < keyboardAnchorPos(searchIndex
))
1589 || (reversed
&& keyboardAnchorPos(searchIndex
- 1) > keyboardAnchorPos(searchIndex
)))) {
1591 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1592 if (searchDiff
< minDiff
) {
1593 minDiff
= searchDiff
;
1594 previousRowIndex
= searchIndex
;
1598 return previousRowIndex
;
1601 qreal
KItemListController::keyboardAnchorPos(int index
) const
1603 const QRectF itemRect
= m_view
->itemRect(index
);
1604 if (!itemRect
.isEmpty()) {
1605 return (m_view
->scrollOrientation() == Qt::Vertical
) ? itemRect
.x() : itemRect
.y();
1611 void KItemListController::updateExtendedSelectionRegion()
1614 const bool extend
= (m_selectionBehavior
!= MultiSelection
);
1615 KItemListStyleOption option
= m_view
->styleOption();
1616 if (option
.extendedSelectionRegion
!= extend
) {
1617 option
.extendedSelectionRegion
= extend
;
1618 m_view
->setStyleOption(option
);
1623 bool KItemListController::onPress(const QPointF
&pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
)
1625 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), buttons
);
1627 if (buttons
& (Qt::BackButton
| Qt::ForwardButton
)) {
1628 // Do not select items when clicking the back/forward buttons, see
1629 // https://bugs.kde.org/show_bug.cgi?id=327412.
1633 const QPointF pressedMousePos
= m_view
->transform().map(pos
);
1635 if (m_view
->isAboveExpansionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
)) {
1636 m_selectionManager
->endAnchoredSelection();
1637 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1638 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1642 m_selectionTogglePressed
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
);
1643 if (m_selectionTogglePressed
) {
1644 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1645 // The previous anchored selection has been finished already in
1646 // KItemListSelectionManager::setSelected(). We can safely change
1647 // the current item and start a new anchored selection now.
1648 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1649 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1653 const bool shiftPressed
= modifiers
& Qt::ShiftModifier
;
1654 const bool controlPressed
= (modifiers
& Qt::ControlModifier
) || m_selectionMode
; // Keeping selectionMode similar to pressing control will hopefully
1655 // simplify the overall logic and possibilities both for users and devs.
1656 const bool leftClick
= buttons
& Qt::LeftButton
;
1657 const bool rightClick
= buttons
& Qt::RightButton
;
1659 // The previous selection is cleared if either
1660 // 1. The selection mode is SingleSelection, or
1661 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1662 // a) Shift or Control are pressed.
1663 // b) The clicked item is selected already. In that case, the user might want to:
1664 // - start dragging multiple items, or
1665 // - open the context menu and perform an action for all selected items.
1666 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
1667 const bool pressedItemAlreadySelected
= m_pressedIndex
.has_value() && m_selectionManager
->isSelected(m_pressedIndex
.value());
1668 const bool clearSelection
= m_selectionBehavior
== SingleSelection
|| (!shiftOrControlPressed
&& !pressedItemAlreadySelected
);
1670 // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller.
1671 if (clearSelection
) {
1672 const int selectedItemsCount
= m_selectionManager
->selectedItems().count();
1673 m_selectionManager
->clearSelection();
1674 // clear and bail when we got an existing multi-selection
1675 if (selectedItemsCount
> 1 && m_pressedIndex
.has_value()) {
1676 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1677 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1678 if (pressedItemAlreadySelected
|| row
->iconRect().contains(mappedPos
) || row
->textRect().contains(mappedPos
)) {
1679 // we are indeed inside the text/icon rect, keep m_pressedIndex what it is
1680 // and short-circuit for single-click activation (it will then propagate to onRelease and activate the item)
1681 // or we just keep going for double-click activation
1682 if (m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) {
1683 if (!pressedItemAlreadySelected
) {
1684 // An unselected item was clicked directly while deselecting multiple other items so we mark it "current".
1685 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1686 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1688 // We select the item here because this press is not meant to directly activate the item.
1689 // We do not want to select items unless the user wants to edit them.
1690 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1693 return true; // event handled, don't create rubber band
1696 // we're not inside the text/icon rect, as we've already cleared the selection
1697 // we can just stop here and make sure handlers down the line (i.e. onRelease) don't activate
1698 m_pressedIndex
.reset();
1699 // we don't stop event propagation and proceed to create a rubber band and let onRelease
1700 // decide (based on m_pressedIndex) whether we're in a drag (drag => new rubber band, click => don't select the item)
1704 } else if (pressedItemAlreadySelected
&& !shiftOrControlPressed
&& leftClick
) {
1705 // The user might want to start dragging multiple items, but if he clicks the item
1706 // in order to trigger it instead, the other selected items must be deselected.
1707 // However, we do not know yet what the user is going to do.
1708 // -> remember that the user pressed an item which had been selected already and
1709 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1710 m_clearSelectionIfItemsAreNotDragged
= true;
1712 if (m_selectionManager
->selectedItems().count() == 1 && m_view
->isAboveText(m_pressedIndex
.value_or(-1), pressedMousePos
)) {
1713 Q_EMIT
selectedItemTextPressed(m_pressedIndex
.value_or(-1));
1717 if (!shiftPressed
) {
1718 // Finish the anchored selection before the current index is changed
1719 m_selectionManager
->endAnchoredSelection();
1723 // Stop rubber band from persisting after right-clicks
1724 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1725 if (rubberBand
->isActive()) {
1726 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1727 rubberBand
->setActive(false);
1728 m_view
->setAutoScroll(false);
1731 if (!m_pressedIndex
.has_value()) {
1732 // We have a right-click in an empty region, don't create rubber band.
1737 if (m_pressedIndex
.has_value()) {
1738 // The hover highlight area of an item is being pressed.
1739 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
1740 const bool hitTargetIsRowEmptyRegion
= !row
->contains(row
->mapFromItem(m_view
, pos
));
1741 // again, when this method returns false, a rubberBand selection is created as the event is not consumed;
1742 // createRubberBand here tells us whether to return true or false.
1743 bool createRubberBand
= (hitTargetIsRowEmptyRegion
&& m_selectionManager
->selectedItems().isEmpty());
1745 if (rightClick
&& hitTargetIsRowEmptyRegion
) {
1746 // We have a right click outside the icon and text rect but within the hover highlight area.
1747 // We don't want items to get selected through this, so we return now.
1751 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1753 switch (m_selectionBehavior
) {
1757 case SingleSelection
:
1758 if (!leftClick
|| shiftOrControlPressed
1759 || (!m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) && !m_singleClickActivationEnforced
)) {
1760 m_selectionManager
->setSelected(m_pressedIndex
.value());
1764 case MultiSelection
:
1765 if (controlPressed
&& !shiftPressed
&& leftClick
) {
1766 // A left mouse button press is happening on an item while control is pressed. This either means a user wants to:
1767 // - toggle the selection of item(s) or
1768 // - they want to begin a drag on the item(s) to copy them.
1769 // We rule out the latter, if the item is not clicked directly and was unselected previously.
1770 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1771 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1772 if (!row
->iconRect().contains(mappedPos
) && !row
->textRect().contains(mappedPos
) && !pressedItemAlreadySelected
) {
1773 createRubberBand
= true;
1775 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1776 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1777 createRubberBand
= false; // multi selection, don't propagate any further
1778 // This will be the start of an item drag-to-copy operation if the user now moves the mouse before releasing the mouse button.
1780 } else if (!shiftPressed
|| !m_selectionManager
->isAnchoredSelectionActive()) {
1781 // Select the pressed item and start a new anchored selection
1782 if (!leftClick
|| shiftOrControlPressed
1783 || (!m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) && !m_singleClickActivationEnforced
)) {
1784 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1786 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1795 return !createRubberBand
;
1801 bool KItemListController::onRelease(const QPointF
&pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
, bool touch
)
1803 const QPointF pressedMousePos
= pos
;
1804 const bool isAboveSelectionToggle
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
);
1805 if (isAboveSelectionToggle
) {
1806 m_selectionTogglePressed
= false;
1810 if (!isAboveSelectionToggle
&& m_selectionTogglePressed
) {
1811 m_selectionManager
->setSelected(m_pressedIndex
.value_or(-1), 1, KItemListSelectionManager::Toggle
);
1812 m_selectionTogglePressed
= false;
1816 const bool controlPressed
= modifiers
& Qt::ControlModifier
;
1817 const bool shiftOrControlPressed
= modifiers
& Qt::ShiftModifier
|| controlPressed
;
1819 const std::optional
<int> index
= m_view
->itemAt(pos
);
1821 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1822 bool rubberBandRelease
= false;
1823 if (rubberBand
->isActive()) {
1824 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1825 rubberBand
->setActive(false);
1826 m_oldSelection
.clear();
1827 m_view
->setAutoScroll(false);
1828 rubberBandRelease
= true;
1829 // We check for actual rubber band drag here: if delta between start and end is less than drag threshold,
1830 // then we have a single click on one of the rows
1831 if ((rubberBand
->endPosition() - rubberBand
->startPosition()).manhattanLength() < QApplication::startDragDistance()) {
1832 rubberBandRelease
= false; // since we're only selecting, unmark rubber band release flag
1833 // m_pressedIndex will have no value if we came from a multi-selection clearing onPress
1834 // in that case, we don't select anything
1835 if (index
.has_value() && m_pressedIndex
.has_value()) {
1836 if (controlPressed
&& m_selectionBehavior
== MultiSelection
) {
1837 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1839 m_selectionManager
->setSelected(index
.value());
1841 if (!m_selectionManager
->isAnchoredSelectionActive()) {
1842 m_selectionManager
->beginAnchoredSelection(index
.value());
1848 if (index
.has_value() && index
== m_pressedIndex
) {
1849 // The release event is done above the same item as the press event
1851 if (m_clearSelectionIfItemsAreNotDragged
) {
1852 // A selected item has been clicked, but no drag operation has been started
1853 // -> clear the rest of the selection.
1854 m_selectionManager
->clearSelection();
1855 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1856 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1859 if (buttons
& Qt::LeftButton
) {
1860 bool emitItemActivated
= true;
1861 if (m_view
->isAboveExpansionToggle(index
.value(), pos
)) {
1862 const bool expanded
= m_model
->isExpanded(index
.value());
1863 m_model
->setExpanded(index
.value(), !expanded
);
1865 Q_EMIT
itemExpansionToggleClicked(index
.value());
1866 emitItemActivated
= false;
1867 } else if (shiftOrControlPressed
&& m_selectionBehavior
!= SingleSelection
) {
1868 // The mouse click should only update the selection, not trigger the item, except when
1869 // we are in single selection mode
1870 emitItemActivated
= false;
1872 const bool singleClickActivation
= m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
;
1873 if (!singleClickActivation
) {
1874 emitItemActivated
= touch
&& !m_selectionMode
;
1876 // activate on single click only if we didn't come from a rubber band release
1877 emitItemActivated
= !rubberBandRelease
;
1880 if (emitItemActivated
) {
1881 Q_EMIT
itemActivated(index
.value());
1883 } else if (buttons
& Qt::MiddleButton
) {
1884 Q_EMIT
itemMiddleClicked(index
.value());
1888 m_pressedMouseGlobalPos
= QPointF();
1889 m_pressedIndex
= std::nullopt
;
1890 m_clearSelectionIfItemsAreNotDragged
= false;
1894 void KItemListController::startRubberBand()
1896 if (m_selectionBehavior
== MultiSelection
) {
1897 QPoint startPos
= m_view
->transform().map(m_view
->scene()->views().first()->mapFromGlobal(m_pressedMouseGlobalPos
.toPoint()));
1898 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1899 startPos
.ry() += m_view
->scrollOffset();
1901 startPos
.rx() += m_view
->scrollOffset();
1904 m_oldSelection
= m_selectionManager
->selectedItems();
1905 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1906 rubberBand
->setStartPosition(startPos
);
1907 rubberBand
->setEndPosition(startPos
);
1908 rubberBand
->setActive(true);
1909 connect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1910 m_view
->setAutoScroll(true);
1914 void KItemListController::slotStateChanged(QScroller::State newState
)
1916 if (newState
== QScroller::Scrolling
) {
1917 m_scrollerIsScrolling
= true;
1918 } else if (newState
== QScroller::Inactive
) {
1919 m_scrollerIsScrolling
= false;
1923 #include "moc_kitemlistcontroller.cpp"