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(750);
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::setAutoActivationEnabled(bool enabled
)
205 m_autoActivationEnabled
= enabled
;
208 bool KItemListController::isAutoActivationEnabled() const
210 return m_autoActivationEnabled
;
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 if (m_view
->layoutDirection() == Qt::RightToLeft
) {
247 // swap left and right arrow keys
260 // Handle the expanding/collapsing of items
261 // expand / collapse all selected directories
262 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
) && (key
== Qt::Key_Right
|| key
== Qt::Key_Left
)) {
263 const bool expandOrCollapse
= key
== Qt::Key_Right
? true : false;
264 bool shouldReturn
= m_model
->setExpanded(index
, expandOrCollapse
);
266 // edit in reverse to preserve index of the first handled items
267 const auto selectedItems
= m_selectionManager
->selectedItems();
268 for (auto it
= selectedItems
.rbegin(); it
!= selectedItems
.rend(); ++it
) {
269 shouldReturn
|= m_model
->setExpanded(*it
, expandOrCollapse
);
271 m_selectionManager
->setSelected(*it
);
275 // update keyboard anchors
277 m_keyboardAnchorIndex
= selectedItems
.count() > 0 ? qMin(index
, selectedItems
.last()) : index
;
278 m_keyboardAnchorPos
= keyboardAnchorPos(m_keyboardAnchorIndex
);
286 const bool controlPressed
= event
->modifiers() & Qt::ControlModifier
;
287 if (m_selectionMode
&& !controlPressed
&& !shiftPressed
&& (key
== Qt::Key_Enter
|| key
== Qt::Key_Return
)) {
288 key
= Qt::Key_Space
; // In selection mode one moves around with arrow keys and toggles selection with Enter.
290 const bool navigationPressed
= key
== Qt::Key_Home
|| key
== Qt::Key_End
|| key
== Qt::Key_PageUp
|| key
== Qt::Key_PageDown
|| key
== Qt::Key_Up
291 || key
== Qt::Key_Down
|| key
== Qt::Key_Left
|| key
== Qt::Key_Right
;
293 const int itemCount
= m_model
->count();
295 // For horizontal scroll orientation, transform
296 // the arrow keys to simplify the event handling.
297 if (horizontalScrolling
) {
316 const bool selectSingleItem
= m_selectionBehavior
!= NoSelection
&& itemCount
== 1 && navigationPressed
;
318 if (selectSingleItem
) {
319 const int current
= m_selectionManager
->currentItem();
320 m_selectionManager
->setSelected(current
);
327 m_keyboardAnchorIndex
= index
;
328 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
332 index
= itemCount
- 1;
333 m_keyboardAnchorIndex
= index
;
334 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
339 const int expandedParentsCount
= m_model
->expandedParentsCount(index
);
340 if (expandedParentsCount
== 0) {
343 // Go to the parent of the current item.
346 } while (index
> 0 && m_model
->expandedParentsCount(index
) == expandedParentsCount
);
348 m_keyboardAnchorIndex
= index
;
349 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
354 if (index
< itemCount
- 1) {
356 m_keyboardAnchorIndex
= index
;
357 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
362 updateKeyboardAnchor();
363 if (shiftPressed
&& !m_selectionManager
->isAnchoredSelectionActive() && m_selectionManager
->isSelected(index
)) {
364 m_selectionManager
->beginAnchoredSelection(index
);
366 index
= previousRowIndex(index
);
370 updateKeyboardAnchor();
371 if (shiftPressed
&& !m_selectionManager
->isAnchoredSelectionActive() && m_selectionManager
->isSelected(index
)) {
372 m_selectionManager
->beginAnchoredSelection(index
);
374 index
= nextRowIndex(index
);
378 if (horizontalScrolling
) {
379 // The new current index should correspond to the first item in the current column.
380 int newIndex
= qMax(index
- 1, 0);
381 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() < m_view
->itemRect(index
).topLeft().y()) {
383 newIndex
= qMax(index
- 1, 0);
385 m_keyboardAnchorIndex
= index
;
386 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
388 const qreal currentItemBottom
= m_view
->itemRect(index
).bottomLeft().y();
389 const qreal height
= m_view
->geometry().height();
391 // The new current item should be the first item in the current
392 // column whose itemRect's top coordinate is larger than targetY.
393 const qreal targetY
= currentItemBottom
- height
;
395 updateKeyboardAnchor();
396 int newIndex
= previousRowIndex(index
);
399 updateKeyboardAnchor();
400 newIndex
= previousRowIndex(index
);
401 } while (m_view
->itemRect(newIndex
).topLeft().y() > targetY
&& newIndex
!= index
);
405 case Qt::Key_PageDown
:
406 if (horizontalScrolling
) {
407 // The new current index should correspond to the last item in the current column.
408 int newIndex
= qMin(index
+ 1, m_model
->count() - 1);
409 while (newIndex
!= index
&& m_view
->itemRect(newIndex
).topLeft().y() > m_view
->itemRect(index
).topLeft().y()) {
411 newIndex
= qMin(index
+ 1, m_model
->count() - 1);
413 m_keyboardAnchorIndex
= index
;
414 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
416 const qreal currentItemTop
= m_view
->itemRect(index
).topLeft().y();
417 const qreal height
= m_view
->geometry().height();
419 // The new current item should be the last item in the current
420 // column whose itemRect's bottom coordinate is smaller than targetY.
421 const qreal targetY
= currentItemTop
+ height
;
423 updateKeyboardAnchor();
424 int newIndex
= nextRowIndex(index
);
427 updateKeyboardAnchor();
428 newIndex
= nextRowIndex(index
);
429 } while (m_view
->itemRect(newIndex
).bottomLeft().y() < targetY
&& newIndex
!= index
);
434 case Qt::Key_Return
: {
435 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
436 if (selectedItems
.count() >= 2) {
437 Q_EMIT
itemsActivated(selectedItems
);
438 } else if (selectedItems
.count() == 1) {
439 Q_EMIT
itemActivated(selectedItems
.first());
441 Q_EMIT
itemActivated(index
);
447 if (m_selectionMode
) {
448 Q_EMIT
selectionModeChangeRequested(false);
449 } else if (m_selectionBehavior
!= SingleSelection
) {
450 m_selectionManager
->clearSelection();
452 m_keyboardManager
->cancelSearch();
453 Q_EMIT
escapePressed();
457 if (m_selectionBehavior
== MultiSelection
) {
458 if (controlPressed
|| m_selectionMode
) {
459 // Toggle the selection state of the current item.
460 m_selectionManager
->endAnchoredSelection();
461 m_selectionManager
->setSelected(index
, 1, KItemListSelectionManager::Toggle
);
462 m_selectionManager
->beginAnchoredSelection(index
);
465 // Select the current item if it is not selected yet.
466 const int current
= m_selectionManager
->currentItem();
467 if (!m_selectionManager
->isSelected(current
)) {
468 m_selectionManager
->setSelected(current
);
473 Q_FALLTHROUGH(); // fall through to the default case and add the Space to the current search string.
475 m_keyboardManager
->addKeys(event
->text());
476 // Make sure unconsumed events get propagated up the chain. #302329
481 if (m_selectionManager
->currentItem() != index
) {
482 switch (m_selectionBehavior
) {
484 m_selectionManager
->setCurrentItem(index
);
487 case SingleSelection
:
488 m_selectionManager
->setCurrentItem(index
);
489 m_selectionManager
->clearSelection();
490 m_selectionManager
->setSelected(index
, 1);
494 if (controlPressed
|| (m_selectionMode
&& !shiftPressed
)) {
495 m_selectionManager
->endAnchoredSelection();
498 m_selectionManager
->setCurrentItem(index
);
500 if (!shiftPressed
&& !controlPressed
&& !m_selectionMode
) {
501 m_selectionManager
->clearSelection();
502 m_selectionManager
->setSelected(index
, 1);
506 m_selectionManager
->beginAnchoredSelection(index
);
512 if (navigationPressed
) {
513 m_view
->scrollToItem(index
);
518 void KItemListController::slotChangeCurrentItem(const QString
&text
, bool searchFromNextItem
)
520 if (!m_model
|| m_model
->count() == 0) {
524 // In selection mode, always use the current (underlined) item, or the next item, for search start position.
525 if (m_selectionBehavior
== NoSelection
|| m_selectionMode
|| m_selectionManager
->hasSelection()) {
526 index
= m_model
->indexForKeyboardSearch(text
, searchFromNextItem
? m_selectionManager
->currentItem() + 1 : m_selectionManager
->currentItem());
528 index
= m_model
->indexForKeyboardSearch(text
, 0);
531 if (m_selectionMode
) {
532 m_selectionManager
->endAnchoredSelection();
535 m_selectionManager
->setCurrentItem(index
);
537 if (m_selectionBehavior
!= NoSelection
) {
538 if (!m_selectionMode
) { // Don't clear the selection in selection mode.
539 m_selectionManager
->replaceSelection(index
);
541 m_selectionManager
->beginAnchoredSelection(index
);
544 m_view
->scrollToItem(index
, KItemListView::ViewItemPosition::Beginning
);
548 void KItemListController::slotAutoActivationTimeout()
550 if (!m_model
|| !m_view
) {
554 const int index
= m_autoActivationTimer
->property("index").toInt();
555 if (index
< 0 || index
>= m_model
->count()) {
559 /* m_view->isUnderMouse() fixes a bug in the Folder-View-Panel and in the
562 * Bug: When you drag a file onto a Folder-View-Item or a Places-Item and
563 * then move away before the auto-activation timeout triggers, than the
564 * item still becomes activated/expanded.
566 * See Bug 293200 and 305783
568 if (m_view
->isUnderMouse()) {
569 if (m_view
->supportsItemExpanding() && m_model
->isExpandable(index
)) {
570 const bool expanded
= m_model
->isExpanded(index
);
571 m_model
->setExpanded(index
, !expanded
);
572 } else if (m_autoActivationBehavior
!= ExpansionOnly
) {
573 Q_EMIT
itemActivated(index
);
578 bool KItemListController::inputMethodEvent(QInputMethodEvent
*event
)
584 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
587 m_pressedMouseGlobalPos
= event
->screenPos();
589 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& m_isTouchEvent
) {
597 const QPointF pressedMousePos
= transform
.map(event
->pos());
598 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
600 const Qt::MouseButtons buttons
= event
->buttons();
602 if (!onPress(event
->pos(), event
->modifiers(), buttons
)) {
610 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
616 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
617 m_view
->m_tapAndHoldIndicator
->setActive(false);
620 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !m_dragActionOrRightClick
&& m_isTouchEvent
) {
624 if (m_pressedIndex
.has_value() && !m_view
->rubberBand()->isActive()) {
625 // Check whether a dragging should be started
626 if (event
->buttons() & Qt::LeftButton
) {
627 const auto distance
= (event
->screenPos() - m_pressedMouseGlobalPos
).manhattanLength();
628 if (distance
>= QApplication::startDragDistance()) {
629 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
630 // Always assure that the dragged item gets selected. Usually this is already
631 // done on the mouse-press event, but when using the selection-toggle on a
632 // selected item the dragged item is not selected yet.
633 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
635 // A selected item has been clicked to drag all selected items
636 // -> the selection should not be cleared when the mouse button is released.
637 m_clearSelectionIfItemsAreNotDragged
= false;
640 m_mousePress
= false;
644 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
645 if (rubberBand
->isActive()) {
646 QPointF endPos
= transform
.map(event
->pos());
648 // Update the current item.
649 const std::optional
<int> newCurrent
= m_view
->itemAt(endPos
);
650 if (newCurrent
.has_value()) {
651 // It's expected that the new current index is also the new anchor (bug 163451).
652 m_selectionManager
->endAnchoredSelection();
653 m_selectionManager
->setCurrentItem(newCurrent
.value());
654 m_selectionManager
->beginAnchoredSelection(newCurrent
.value());
657 if (m_view
->scrollOrientation() == Qt::Vertical
) {
658 endPos
.ry() += m_view
->scrollOffset();
660 endPos
.rx() += m_view
->scrollOffset();
662 rubberBand
->setEndPosition(endPos
);
669 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
671 m_mousePress
= false;
672 m_isTouchEvent
= false;
678 for (KItemListWidget
*widget
: m_view
->visibleItemListWidgets()) {
679 widget
->setPressed(false);
682 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
683 m_view
->m_tapAndHoldIndicator
->setActive(false);
686 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
687 if (event
->source() == Qt::MouseEventSynthesizedByQt
&& !rubberBand
->isActive() && m_isTouchEvent
) {
691 Q_EMIT
mouseButtonReleased(m_pressedIndex
.value_or(-1), event
->buttons());
693 return onRelease(transform
.map(event
->pos()), event
->modifiers(), event
->button(), false);
696 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent
*event
, const QTransform
&transform
)
698 const QPointF pos
= transform
.map(event
->pos());
699 const std::optional
<int> index
= m_view
->itemAt(pos
);
701 if (event
->button() & (Qt::ForwardButton
| Qt::BackButton
)) {
702 // "Forward" and "Back" are reserved for quickly navigating through the
703 // history. Double-clicking those buttons should be interpreted as two
704 // separate button presses. We arrive here for the second click, which
705 // we now react to just as we would for a singular click
706 Q_EMIT
mouseButtonPressed(index
.value_or(-1), event
->button());
710 if (!index
.has_value()) {
711 Q_EMIT
doubleClickViewBackground(event
->button());
715 // Expand item if desired - See Bug 295573
716 if (m_mouseDoubleClickAction
!= ActivateItemOnly
) {
717 if (m_view
&& m_model
&& m_view
->supportsItemExpanding() && m_model
->isExpandable(index
.value_or(-1))) {
718 const bool expanded
= m_model
->isExpanded(index
.value());
719 m_model
->setExpanded(index
.value(), !expanded
);
723 if (event
->button() & ~Qt::LeftButton
) {
727 if (m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
) {
731 const bool emitItemActivated
= index
.has_value() && index
.value() < m_model
->count() && !m_view
->isAboveExpansionToggle(index
.value(), pos
);
732 if (emitItemActivated
) {
733 if (!QApplication::keyboardModifiers()) {
734 m_selectionManager
->clearSelection(); // The user does not want to manage/manipulate the item currently, only activate it.
736 Q_EMIT
itemActivated(index
.value());
741 bool KItemListController::contextMenuEvent(QContextMenuEvent
*event
)
743 if (event
->reason() == QContextMenuEvent::Keyboard
) {
744 // Emit the signal itemContextMenuRequested() if at least one item is selected.
745 // Otherwise the signal viewContextMenuRequested() will be emitted.
746 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
748 if (selectedItems
.count() >= 2) {
749 const int currentItemIndex
= m_selectionManager
->currentItem();
750 index
= selectedItems
.contains(currentItemIndex
) ? currentItemIndex
: selectedItems
.first();
751 } else if (selectedItems
.count() == 1) {
752 index
= selectedItems
.first();
756 const QRectF contextRect
= m_view
->itemContextRect(index
);
757 const QPointF
pos(m_view
->scene()->views().first()->mapToGlobal(contextRect
.bottomRight().toPoint()));
758 Q_EMIT
itemContextMenuRequested(index
, pos
);
760 Q_EMIT
viewContextMenuRequested(event
->globalPos());
765 const auto pos
= event
->pos();
766 const auto globalPos
= event
->globalPos();
768 if (m_view
->headerBoundaries().contains(pos
)) {
769 Q_EMIT
headerContextMenuRequested(globalPos
);
773 const auto pressedItem
= m_view
->itemAt(pos
);
774 // We only open a context menu for the pressed item if it is selected.
775 // 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.
776 if (pressedItem
&& m_selectionManager
->selectedItems().contains(pressedItem
.value())) {
777 // The selection rectangle for an item was clicked
778 Q_EMIT
itemContextMenuRequested(pressedItem
.value(), globalPos
);
782 // Remove any hover highlights so the context menu doesn't look like it applies to a row.
783 const auto widgets
= m_view
->visibleItemListWidgets();
784 for (KItemListWidget
*widget
: widgets
) {
785 if (widget
->isHovered()) {
786 widget
->setHovered(false);
787 Q_EMIT
itemUnhovered(widget
->index());
790 Q_EMIT
viewContextMenuRequested(globalPos
);
794 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
799 DragAndDropHelper::clearUrlListMatchesUrlCache();
804 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
809 m_autoActivationTimer
->stop();
810 m_view
->setAutoScroll(false);
811 m_view
->hideDropIndicator();
813 KItemListWidget
*widget
= hoveredWidget();
815 widget
->setHovered(false);
816 Q_EMIT
itemUnhovered(widget
->index());
821 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
823 if (!m_model
|| !m_view
) {
827 QUrl hoveredDir
= m_model
->directory();
828 KItemListWidget
*oldHoveredWidget
= hoveredWidget();
830 const QPointF pos
= transform
.map(event
->pos());
831 KItemListWidget
*newHoveredWidget
= widgetForDropPos(pos
);
834 if (oldHoveredWidget
!= newHoveredWidget
) {
835 m_autoActivationTimer
->stop();
837 if (oldHoveredWidget
) {
838 oldHoveredWidget
->setHovered(false);
839 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
843 if (newHoveredWidget
) {
844 bool droppingBetweenItems
= false;
845 if (m_model
->sortRole().isEmpty()) {
846 // The model supports inserting items between other items.
847 droppingBetweenItems
= (m_view
->showDropIndicator(pos
) >= 0);
850 index
= newHoveredWidget
->index();
852 if (m_model
->isDir(index
)) {
853 hoveredDir
= m_model
->url(index
);
856 if (!droppingBetweenItems
) {
857 // Something has been dragged on an item.
858 m_view
->hideDropIndicator();
859 if (!newHoveredWidget
->isHovered()) {
860 newHoveredWidget
->setHovered(true);
861 Q_EMIT
itemHovered(index
);
864 if (m_autoActivationEnabled
&& !m_autoActivationTimer
->isActive() && m_model
->canEnterOnHover(index
)) {
865 m_autoActivationTimer
->setProperty("index", index
);
866 m_autoActivationTimer
->start();
867 newHoveredWidget
->startActivateSoonAnimation(m_autoActivationTimer
->remainingTime());
871 m_autoActivationTimer
->stop();
872 if (newHoveredWidget
&& newHoveredWidget
->isHovered()) {
873 newHoveredWidget
->setHovered(false);
874 Q_EMIT
itemUnhovered(index
);
878 m_view
->hideDropIndicator();
881 if (DragAndDropHelper::urlListMatchesUrl(event
->mimeData()->urls(), hoveredDir
)) {
882 event
->setDropAction(Qt::IgnoreAction
);
885 if (m_model
->supportsDropping(index
)) {
886 event
->setDropAction(event
->proposedAction());
889 event
->setDropAction(Qt::IgnoreAction
);
896 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent
*event
, const QTransform
&transform
)
902 m_autoActivationTimer
->stop();
903 m_view
->setAutoScroll(false);
905 const QPointF pos
= transform
.map(event
->pos());
907 int dropAboveIndex
= -1;
908 if (m_model
->sortRole().isEmpty()) {
909 // The model supports inserting of items between other items.
910 dropAboveIndex
= m_view
->showDropIndicator(pos
);
913 if (dropAboveIndex
>= 0) {
914 // Something has been dropped between two items.
915 m_view
->hideDropIndicator();
916 Q_EMIT
aboveItemDropEvent(dropAboveIndex
, event
);
917 } else if (!event
->mimeData()->hasFormat(m_model
->blacklistItemDropEventMimeType())) {
918 // Something has been dropped on an item or on an empty part of the view.
919 const KItemListWidget
*receivingWidget
= widgetForDropPos(pos
);
920 if (receivingWidget
) {
921 Q_EMIT
itemDropEvent(receivingWidget
->index(), event
);
923 Q_EMIT
itemDropEvent(-1, event
);
927 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropEnd
);
928 QAccessible::updateAccessibility(&accessibilityEvent
);
933 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
940 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
943 if (!m_model
|| !m_view
) {
947 // We identify the widget whose expansionArea had been hovered before this hoverMoveEvent() triggered.
948 // we can't use hoveredWidget() here (it handles the icon+text rect, not the expansion rect)
949 // like hoveredWidget(), we find the hovered widget for the expansion rect
950 const auto visibleItemListWidgets
= m_view
->visibleItemListWidgets();
951 const auto oldHoveredExpansionWidgetIterator
= std::find_if(visibleItemListWidgets
.begin(), visibleItemListWidgets
.end(), [](auto &widget
) {
952 return widget
->expansionAreaHovered();
954 const auto oldHoveredExpansionWidget
=
955 oldHoveredExpansionWidgetIterator
== visibleItemListWidgets
.end() ? std::nullopt
: std::make_optional(*oldHoveredExpansionWidgetIterator
);
957 const auto unhoverOldHoveredWidget
= [&]() {
958 if (auto oldHoveredWidget
= hoveredWidget(); oldHoveredWidget
) {
959 // handle the text+icon one
960 oldHoveredWidget
->setHovered(false);
961 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
965 const auto unhoverOldExpansionWidget
= [&]() {
966 if (oldHoveredExpansionWidget
) {
967 // then the expansion toggle
968 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
972 const QPointF pos
= transform
.map(event
->pos());
973 if (KItemListWidget
*newHoveredWidget
= widgetForPos(pos
); newHoveredWidget
) {
974 // something got hovered, work out which part and set hover for the appropriate widget
975 const auto mappedPos
= newHoveredWidget
->mapFromItem(m_view
, pos
);
976 const bool isOnExpansionToggle
= newHoveredWidget
->expansionToggleRect().contains(mappedPos
);
978 if (isOnExpansionToggle
) {
979 // make sure we unhover the old one first if old!=new
980 if (oldHoveredExpansionWidget
&& *oldHoveredExpansionWidget
!= newHoveredWidget
) {
981 (*oldHoveredExpansionWidget
)->setExpansionAreaHovered(false);
983 // 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)
984 unhoverOldHoveredWidget();
986 newHoveredWidget
->setExpansionAreaHovered(true);
988 // make sure we unhover the old one first if old!=new
989 auto oldHoveredWidget
= hoveredWidget();
990 if (oldHoveredWidget
&& oldHoveredWidget
!= newHoveredWidget
) {
991 oldHoveredWidget
->setHovered(false);
992 Q_EMIT
itemUnhovered(oldHoveredWidget
->index());
994 // 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)
995 unhoverOldExpansionWidget();
997 const bool isOverIconAndText
= newHoveredWidget
->selectionRectCore().contains(mappedPos
);
998 const bool hasMultipleSelection
= m_selectionManager
->selectedItems().count() > 1;
1000 if (hasMultipleSelection
&& !isOverIconAndText
) {
1001 // In case we have multiple selections, clicking on any row will deselect the selection.
1002 // So, as a visual cue for signalling that clicking anywhere won't select, but clear current highlights,
1003 // we disable hover of the *row*(i.e. blank space to the right of the icon+text)
1005 // (no-op in this branch for masked hover)
1007 newHoveredWidget
->setHoverPosition(mappedPos
);
1008 if (oldHoveredWidget
!= newHoveredWidget
) {
1009 newHoveredWidget
->setHovered(true);
1010 Q_EMIT
itemHovered(newHoveredWidget
->index());
1015 // unhover any currently hovered expansion and text+icon widgets
1016 unhoverOldHoveredWidget();
1017 unhoverOldExpansionWidget();
1022 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent
*event
, const QTransform
&transform
)
1027 m_mousePress
= false;
1028 m_isTouchEvent
= false;
1030 if (!m_model
|| !m_view
) {
1034 const auto widgets
= m_view
->visibleItemListWidgets();
1035 for (KItemListWidget
*widget
: widgets
) {
1036 widget
->setPressed(false);
1037 if (widget
->isHovered()) {
1038 widget
->setHovered(false);
1039 Q_EMIT
itemUnhovered(widget
->index());
1045 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent
*event
, const QTransform
&transform
)
1052 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent
*event
, const QTransform
&transform
)
1059 bool KItemListController::gestureEvent(QGestureEvent
*event
, const QTransform
&transform
)
1065 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
1066 //we use this to get the right QWidget
1067 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
1068 if (!m_mousePress
) {
1069 if (QGesture
*tap
= event
->gesture(Qt::TapGesture
)) {
1070 QTapGesture
*tapGesture
= static_cast<QTapGesture
*>(tap
);
1071 if (tapGesture
->state() == Qt::GestureStarted
) {
1072 tapTriggered(tapGesture
, transform
);
1078 bool accepted
= false;
1080 if (QGesture
*tap
= event
->gesture(Qt::TapGesture
)) {
1081 tapTriggered(static_cast<QTapGesture
*>(tap
), transform
);
1084 if (event
->gesture(Qt::TapAndHoldGesture
)) {
1085 tapAndHoldTriggered(event
, transform
);
1088 if (event
->gesture(Qt::PinchGesture
)) {
1089 pinchTriggered(event
, transform
);
1092 if (event
->gesture(m_swipeGesture
)) {
1093 swipeTriggered(event
, transform
);
1096 if (event
->gesture(m_twoFingerTapGesture
)) {
1097 twoFingerTapTriggered(event
, transform
);
1103 bool KItemListController::touchBeginEvent(QTouchEvent
*event
, const QTransform
&transform
)
1108 m_isTouchEvent
= true;
1112 void KItemListController::tapTriggered(QTapGesture
*tap
, const QTransform
&transform
)
1114 static bool scrollerWasActive
= false;
1116 if (tap
->state() == Qt::GestureStarted
) {
1117 m_dragActionOrRightClick
= false;
1118 m_isSwipeGesture
= false;
1119 m_pinchGestureInProgress
= false;
1120 scrollerWasActive
= m_scrollerIsScrolling
;
1123 if (tap
->state() == Qt::GestureFinished
) {
1124 m_mousePress
= false;
1126 //if at the moment of the gesture start the QScroller was active, the user made the tap
1127 //to stop the QScroller and not to tap on an item
1128 if (scrollerWasActive
) {
1132 if (m_view
->m_tapAndHoldIndicator
->isActive()) {
1133 m_view
->m_tapAndHoldIndicator
->setActive(false);
1136 const QPointF pressedMousePos
= transform
.map(tap
->position());
1137 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1138 if (m_dragActionOrRightClick
) {
1139 m_dragActionOrRightClick
= false;
1141 onPress(tap
->position().toPoint(), Qt::NoModifier
, Qt::LeftButton
);
1142 onRelease(transform
.map(tap
->position()), Qt::NoModifier
, Qt::LeftButton
, true);
1144 m_isTouchEvent
= false;
1148 void KItemListController::tapAndHoldTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1150 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
1151 if (!m_isTouchEvent
) {
1155 const QTapAndHoldGesture
*tap
= static_cast<QTapAndHoldGesture
*>(event
->gesture(Qt::TapAndHoldGesture
));
1156 if (tap
->state() == Qt::GestureFinished
) {
1157 //if a pinch gesture is in progress we don't want a TabAndHold gesture
1158 if (m_pinchGestureInProgress
) {
1161 const QPointF pressedMousePos
= transform
.map(event
->mapToGraphicsScene(tap
->position()));
1162 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1163 if (m_pressedIndex
.has_value()) {
1164 if (!m_selectionManager
->isSelected(m_pressedIndex
.value())) {
1165 m_selectionManager
->clearSelection();
1166 m_selectionManager
->setSelected(m_pressedIndex
.value());
1168 if (!m_selectionMode
) {
1169 Q_EMIT
selectionModeChangeRequested(true);
1172 m_selectionManager
->clearSelection();
1176 Q_EMIT
scrollerStop();
1178 m_view
->m_tapAndHoldIndicator
->setStartPosition(pressedMousePos
);
1179 m_view
->m_tapAndHoldIndicator
->setActive(true);
1181 m_dragActionOrRightClick
= true;
1185 void KItemListController::pinchTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1189 const QPinchGesture
*pinch
= static_cast<QPinchGesture
*>(event
->gesture(Qt::PinchGesture
));
1190 const qreal sensitivityModifier
= 0.2;
1191 static qreal counter
= 0;
1193 if (pinch
->state() == Qt::GestureStarted
) {
1194 m_pinchGestureInProgress
= true;
1197 if (pinch
->state() == Qt::GestureUpdated
) {
1198 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1199 if (m_isSwipeGesture
) {
1202 counter
= counter
+ (pinch
->scaleFactor() - 1);
1203 if (counter
>= sensitivityModifier
) {
1204 Q_EMIT
increaseZoom();
1206 } else if (counter
<= -sensitivityModifier
) {
1207 Q_EMIT
decreaseZoom();
1213 void KItemListController::swipeTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1217 const KTwoFingerSwipe
*swipe
= static_cast<KTwoFingerSwipe
*>(event
->gesture(m_swipeGesture
));
1222 if (swipe
->state() == Qt::GestureStarted
) {
1223 m_isSwipeGesture
= true;
1226 if (swipe
->state() == Qt::GestureCanceled
) {
1227 m_isSwipeGesture
= false;
1230 if (swipe
->state() == Qt::GestureFinished
) {
1231 Q_EMIT
scrollerStop();
1233 if (swipe
->swipeAngle() <= 20 || swipe
->swipeAngle() >= 340) {
1234 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::BackButton
);
1235 } else if (swipe
->swipeAngle() <= 200 && swipe
->swipeAngle() >= 160) {
1236 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), Qt::ForwardButton
);
1237 } else if (swipe
->swipeAngle() <= 110 && swipe
->swipeAngle() >= 60) {
1240 m_isSwipeGesture
= true;
1244 void KItemListController::twoFingerTapTriggered(QGestureEvent
*event
, const QTransform
&transform
)
1246 const KTwoFingerTap
*twoTap
= static_cast<KTwoFingerTap
*>(event
->gesture(m_twoFingerTapGesture
));
1252 if (twoTap
->state() == Qt::GestureStarted
) {
1253 const QPointF pressedMousePos
= transform
.map(twoTap
->pos());
1254 m_pressedIndex
= m_view
->itemAt(pressedMousePos
);
1255 if (m_pressedIndex
.has_value()) {
1256 onPress(twoTap
->pos().toPoint(), Qt::ControlModifier
, Qt::LeftButton
);
1257 onRelease(transform
.map(twoTap
->pos()), Qt::ControlModifier
, Qt::LeftButton
, false);
1262 bool KItemListController::processEvent(QEvent
*event
, const QTransform
&transform
)
1268 switch (event
->type()) {
1269 case QEvent::KeyPress
:
1270 return keyPressEvent(static_cast<QKeyEvent
*>(event
));
1271 case QEvent::InputMethod
:
1272 return inputMethodEvent(static_cast<QInputMethodEvent
*>(event
));
1273 case QEvent::GraphicsSceneMousePress
:
1274 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1275 case QEvent::GraphicsSceneMouseMove
:
1276 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1277 case QEvent::GraphicsSceneMouseRelease
:
1278 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1279 case QEvent::GraphicsSceneMouseDoubleClick
:
1280 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent
*>(event
), QTransform());
1281 case QEvent::ContextMenu
:
1282 return contextMenuEvent(static_cast<QContextMenuEvent
*>(event
));
1283 case QEvent::GraphicsSceneWheel
:
1284 return wheelEvent(static_cast<QGraphicsSceneWheelEvent
*>(event
), QTransform());
1285 case QEvent::GraphicsSceneDragEnter
:
1286 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1287 case QEvent::GraphicsSceneDragLeave
:
1288 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1289 case QEvent::GraphicsSceneDragMove
:
1290 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1291 case QEvent::GraphicsSceneDrop
:
1292 return dropEvent(static_cast<QGraphicsSceneDragDropEvent
*>(event
), QTransform());
1293 case QEvent::GraphicsSceneHoverEnter
:
1294 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1295 case QEvent::GraphicsSceneHoverMove
:
1296 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1297 case QEvent::GraphicsSceneHoverLeave
:
1298 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent
*>(event
), QTransform());
1299 case QEvent::GraphicsSceneResize
:
1300 return resizeEvent(static_cast<QGraphicsSceneResizeEvent
*>(event
), transform
);
1301 case QEvent::Gesture
:
1302 return gestureEvent(static_cast<QGestureEvent
*>(event
), transform
);
1303 case QEvent::TouchBegin
:
1304 return touchBeginEvent(static_cast<QTouchEvent
*>(event
), transform
);
1312 void KItemListController::slotViewScrollOffsetChanged(qreal current
, qreal previous
)
1318 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1319 if (rubberBand
->isActive()) {
1320 const qreal diff
= current
- previous
;
1321 // TODO: Ideally just QCursor::pos() should be used as
1322 // new end-position but it seems there is no easy way
1323 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1324 // (... or I just missed an easy way to do the mapping)
1325 QPointF endPos
= rubberBand
->endPosition();
1326 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1327 endPos
.ry() += diff
;
1329 endPos
.rx() += diff
;
1332 rubberBand
->setEndPosition(endPos
);
1336 void KItemListController::slotRubberBandChanged()
1338 if (!m_view
|| !m_model
|| m_model
->count() <= 0) {
1342 const KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1343 const QPointF startPos
= rubberBand
->startPosition();
1344 const QPointF endPos
= rubberBand
->endPosition();
1345 QRectF rubberBandRect
= QRectF(startPos
, endPos
).normalized();
1347 const bool scrollVertical
= (m_view
->scrollOrientation() == Qt::Vertical
);
1348 if (scrollVertical
) {
1349 rubberBandRect
.translate(0, -m_view
->scrollOffset());
1351 rubberBandRect
.translate(-m_view
->scrollOffset(), 0);
1354 if (!m_oldSelection
.isEmpty()) {
1355 // Clear the old selection that was available before the rubberband has
1356 // been activated in case if no Shift- or Control-key are pressed
1357 const bool shiftOrControlPressed
= QApplication::keyboardModifiers() & Qt::ShiftModifier
|| QApplication::keyboardModifiers() & Qt::ControlModifier
;
1358 if (!shiftOrControlPressed
&& !m_selectionMode
) {
1359 m_oldSelection
.clear();
1363 KItemSet selectedItems
;
1365 // Select all visible items that intersect with the rubberband
1366 const auto widgets
= m_view
->visibleItemListWidgets();
1367 for (const KItemListWidget
*widget
: widgets
) {
1368 const int index
= widget
->index();
1370 const QRectF widgetRect
= m_view
->itemRect(index
);
1371 if (widgetRect
.intersects(rubberBandRect
)) {
1372 // Select the full row intersecting with the rubberband rectangle
1373 const QRectF selectionRect
= widget
->selectionRectFull().translated(widgetRect
.topLeft());
1374 if (selectionRect
.intersects(rubberBandRect
)) {
1375 selectedItems
.insert(index
);
1380 // Select all invisible items that intersect with the rubberband. Instead of
1381 // iterating all items only the area which might be touched by the rubberband
1383 const bool increaseIndex
= scrollVertical
? startPos
.y() > endPos
.y() : startPos
.x() > endPos
.x();
1385 int index
= increaseIndex
? m_view
->lastVisibleIndex() + 1 : m_view
->firstVisibleIndex() - 1;
1386 bool selectionFinished
= false;
1388 const QRectF widgetRect
= m_view
->itemRect(index
);
1389 if (widgetRect
.intersects(rubberBandRect
)) {
1390 selectedItems
.insert(index
);
1393 if (increaseIndex
) {
1395 selectionFinished
= (index
>= m_model
->count()) || (scrollVertical
&& widgetRect
.top() > rubberBandRect
.bottom())
1396 || (!scrollVertical
&& widgetRect
.left() > rubberBandRect
.right());
1399 selectionFinished
= (index
< 0) || (scrollVertical
&& widgetRect
.bottom() < rubberBandRect
.top())
1400 || (!scrollVertical
&& widgetRect
.right() < rubberBandRect
.left());
1402 } while (!selectionFinished
);
1404 if ((QApplication::keyboardModifiers() & Qt::ControlModifier
) || m_selectionMode
) {
1405 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1406 // Therefore, the new selection contains:
1407 // 1. All previously selected items which are not inside the rubberband, and
1408 // 2. all items inside the rubberband which have not been selected previously.
1409 m_selectionManager
->setSelectedItems(m_oldSelection
^ selectedItems
);
1411 m_selectionManager
->setSelectedItems(selectedItems
+ m_oldSelection
);
1415 void KItemListController::startDragging()
1417 if (!m_view
|| !m_model
) {
1421 const KItemSet selectedItems
= m_selectionManager
->selectedItems();
1422 if (selectedItems
.isEmpty()) {
1426 QMimeData
*data
= m_model
->createMimeData(selectedItems
);
1430 KUrlMimeData::exportUrlsToPortal(data
);
1432 // The created drag object will be owned and deleted
1433 // by QApplication::activeWindow().
1434 QDrag
*drag
= new QDrag(QApplication::activeWindow());
1435 drag
->setMimeData(data
);
1437 const QPixmap pixmap
= m_view
->createDragPixmap(selectedItems
);
1438 drag
->setPixmap(pixmap
);
1440 const QPoint
hotSpot((pixmap
.width() / pixmap
.devicePixelRatio()) / 2, 0);
1441 drag
->setHotSpot(hotSpot
);
1443 drag
->exec(Qt::MoveAction
| Qt::CopyAction
| Qt::LinkAction
, Qt::CopyAction
);
1445 QAccessibleEvent
accessibilityEvent(view(), QAccessible::DragDropStart
);
1446 QAccessible::updateAccessibility(&accessibilityEvent
);
1449 KItemListWidget
*KItemListController::hoveredWidget() const
1453 const auto widgets
= m_view
->visibleItemListWidgets();
1454 for (KItemListWidget
*widget
: widgets
) {
1455 if (widget
->isHovered()) {
1463 KItemListWidget
*KItemListController::widgetForPos(const QPointF
&pos
) const
1467 if (m_view
->headerBoundaries().contains(pos
)) {
1471 const auto widgets
= m_view
->visibleItemListWidgets();
1472 for (KItemListWidget
*widget
: widgets
) {
1473 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1474 if (widget
->contains(mappedPos
)) {
1482 KItemListWidget
*KItemListController::widgetForDropPos(const QPointF
&pos
) const
1486 if (m_view
->headerBoundaries().contains(pos
)) {
1490 const auto widgets
= m_view
->visibleItemListWidgets();
1491 for (KItemListWidget
*widget
: widgets
) {
1492 const QPointF mappedPos
= widget
->mapFromItem(m_view
, pos
);
1493 if (widget
->selectionRectCore().contains(mappedPos
)) {
1501 void KItemListController::updateKeyboardAnchor()
1503 const bool validAnchor
=
1504 m_keyboardAnchorIndex
>= 0 && m_keyboardAnchorIndex
< m_model
->count() && keyboardAnchorPos(m_keyboardAnchorIndex
) == m_keyboardAnchorPos
;
1506 const int index
= m_selectionManager
->currentItem();
1507 m_keyboardAnchorIndex
= index
;
1508 m_keyboardAnchorPos
= keyboardAnchorPos(index
);
1512 int KItemListController::nextRowIndex(int index
) const
1514 if (m_keyboardAnchorIndex
< 0) {
1518 const int maxIndex
= m_model
->count() - 1;
1519 if (index
== maxIndex
) {
1523 const bool reversed
= m_view
->layoutDirection() == Qt::RightToLeft
&& m_view
->scrollOrientation() == Qt::Vertical
;
1525 // Calculate the index of the last column inside the row of the current index
1526 int lastColumnIndex
= index
;
1527 while ((!reversed
&& keyboardAnchorPos(lastColumnIndex
+ 1) > keyboardAnchorPos(lastColumnIndex
))
1528 || (reversed
&& keyboardAnchorPos(lastColumnIndex
+ 1) < keyboardAnchorPos(lastColumnIndex
))) {
1530 if (lastColumnIndex
>= maxIndex
) {
1535 // Based on the last column index go to the next row and calculate the nearest index
1536 // that is below the current index
1537 int nextRowIndex
= lastColumnIndex
+ 1;
1538 int searchIndex
= nextRowIndex
;
1539 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(nextRowIndex
));
1540 while (searchIndex
< maxIndex
1541 && ((!reversed
&& keyboardAnchorPos(searchIndex
+ 1) > keyboardAnchorPos(searchIndex
))
1542 || (reversed
&& keyboardAnchorPos(searchIndex
+ 1) < keyboardAnchorPos(searchIndex
)))) {
1544 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1545 if (searchDiff
< minDiff
) {
1546 minDiff
= searchDiff
;
1547 nextRowIndex
= searchIndex
;
1551 return nextRowIndex
;
1554 int KItemListController::previousRowIndex(int index
) const
1556 if (m_keyboardAnchorIndex
< 0 || index
== 0) {
1560 const bool reversed
= m_view
->layoutDirection() == Qt::RightToLeft
&& m_view
->scrollOrientation() == Qt::Vertical
;
1562 // Calculate the index of the first column inside the row of the current index
1563 int firstColumnIndex
= index
;
1564 while ((!reversed
&& keyboardAnchorPos(firstColumnIndex
- 1) < keyboardAnchorPos(firstColumnIndex
))
1565 || (reversed
&& keyboardAnchorPos(firstColumnIndex
- 1) > keyboardAnchorPos(firstColumnIndex
))) {
1567 if (firstColumnIndex
<= 0) {
1572 // Based on the first column index go to the previous row and calculate the nearest index
1573 // that is above the current index
1574 int previousRowIndex
= firstColumnIndex
- 1;
1575 int searchIndex
= previousRowIndex
;
1576 qreal minDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(previousRowIndex
));
1577 while (searchIndex
> 0
1578 && ((!reversed
&& keyboardAnchorPos(searchIndex
- 1) < keyboardAnchorPos(searchIndex
))
1579 || (reversed
&& keyboardAnchorPos(searchIndex
- 1) > keyboardAnchorPos(searchIndex
)))) {
1581 const qreal searchDiff
= qAbs(m_keyboardAnchorPos
- keyboardAnchorPos(searchIndex
));
1582 if (searchDiff
< minDiff
) {
1583 minDiff
= searchDiff
;
1584 previousRowIndex
= searchIndex
;
1588 return previousRowIndex
;
1591 qreal
KItemListController::keyboardAnchorPos(int index
) const
1593 const QRectF itemRect
= m_view
->itemRect(index
);
1594 if (!itemRect
.isEmpty()) {
1595 return (m_view
->scrollOrientation() == Qt::Vertical
) ? itemRect
.x() : itemRect
.y();
1601 void KItemListController::updateExtendedSelectionRegion()
1604 const bool extend
= (m_selectionBehavior
!= MultiSelection
);
1605 KItemListStyleOption option
= m_view
->styleOption();
1606 if (option
.extendedSelectionRegion
!= extend
) {
1607 option
.extendedSelectionRegion
= extend
;
1608 m_view
->setStyleOption(option
);
1613 bool KItemListController::onPress(const QPointF
&pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
)
1615 Q_EMIT
mouseButtonPressed(m_pressedIndex
.value_or(-1), buttons
);
1617 if (buttons
& (Qt::BackButton
| Qt::ForwardButton
)) {
1618 // Do not select items when clicking the back/forward buttons, see
1619 // https://bugs.kde.org/show_bug.cgi?id=327412.
1623 const QPointF pressedMousePos
= m_view
->transform().map(pos
);
1625 if (m_view
->isAboveExpansionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
)) {
1626 m_selectionManager
->endAnchoredSelection();
1627 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1628 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1632 m_selectionTogglePressed
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
);
1633 if (m_selectionTogglePressed
) {
1634 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1635 // The previous anchored selection has been finished already in
1636 // KItemListSelectionManager::setSelected(). We can safely change
1637 // the current item and start a new anchored selection now.
1638 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1639 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1643 const bool shiftPressed
= modifiers
& Qt::ShiftModifier
;
1644 const bool controlPressed
= (modifiers
& Qt::ControlModifier
) || m_selectionMode
; // Keeping selectionMode similar to pressing control will hopefully
1645 // simplify the overall logic and possibilities both for users and devs.
1646 const bool leftClick
= buttons
& Qt::LeftButton
;
1647 const bool rightClick
= buttons
& Qt::RightButton
;
1648 const bool singleClickActivation
= m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
);
1650 // The previous selection is cleared if either
1651 // 1. The selection mode is SingleSelection, or
1652 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1653 // a) Shift or Control are pressed.
1654 // b) The clicked item is selected already. In that case, the user might want to:
1655 // - start dragging multiple items, or
1656 // - open the context menu and perform an action for all selected items.
1657 const bool shiftOrControlPressed
= shiftPressed
|| controlPressed
;
1658 const bool pressedItemAlreadySelected
= m_pressedIndex
.has_value() && m_selectionManager
->isSelected(m_pressedIndex
.value());
1659 const bool clearSelection
= m_selectionBehavior
== SingleSelection
|| (!shiftOrControlPressed
&& !pressedItemAlreadySelected
);
1661 // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller.
1662 if (clearSelection
) {
1663 const int selectedItemsCount
= m_selectionManager
->selectedItems().count();
1664 m_selectionManager
->clearSelection();
1665 // clear and bail when we got an existing multi-selection
1666 if (selectedItemsCount
> 1 && m_pressedIndex
.has_value()) {
1667 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1668 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1669 if (row
->selectionRectCore().contains(mappedPos
)) {
1670 // we are indeed inside the text/icon rect, keep m_pressedIndex what it is
1671 // and short-circuit for single-click activation (it will then propagate to onRelease and activate the item)
1672 // or we just keep going for double-click activation
1673 if (singleClickActivation
|| m_singleClickActivationEnforced
) {
1674 if (!pressedItemAlreadySelected
) {
1675 // An unselected item was clicked directly while deselecting multiple other items so we mark it "current".
1676 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1677 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1679 // We select the item here because this press is not meant to directly activate the item.
1680 // We do not want to select items unless the user wants to edit them.
1681 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1685 row
->setPressed(true);
1687 return true; // event handled, don't create rubber band
1690 // we're not inside the text/icon rect, as we've already cleared the selection
1691 // we can just stop here and make sure handlers down the line (i.e. onRelease) don't activate
1692 m_pressedIndex
.reset();
1693 // we don't stop event propagation and proceed to create a rubber band and let onRelease
1694 // decide (based on m_pressedIndex) whether we're in a drag (drag => new rubber band, click => don't select the item)
1698 } else if (pressedItemAlreadySelected
&& !shiftOrControlPressed
&& leftClick
) {
1699 // The user might want to start dragging multiple items, but if he clicks the item
1700 // in order to trigger it instead, the other selected items must be deselected.
1701 // However, we do not know yet what the user is going to do.
1702 // -> remember that the user pressed an item which had been selected already and
1703 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1704 m_clearSelectionIfItemsAreNotDragged
= true;
1706 if (m_selectionManager
->selectedItems().count() == 1 && m_view
->isAboveText(m_pressedIndex
.value_or(-1), pressedMousePos
)) {
1707 Q_EMIT
selectedItemTextPressed(m_pressedIndex
.value_or(-1));
1711 if (!shiftPressed
) {
1712 // Finish the anchored selection before the current index is changed
1713 m_selectionManager
->endAnchoredSelection();
1717 // Stop rubber band from persisting after right-clicks
1718 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1719 if (rubberBand
->isActive()) {
1720 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1721 rubberBand
->setActive(false);
1722 m_view
->setAutoScroll(false);
1725 if (!m_pressedIndex
.has_value()) {
1726 // We have a right-click in an empty region, don't create rubber band.
1731 if (m_pressedIndex
.has_value()) {
1732 // The hover highlight area of an item is being pressed.
1733 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
1735 const bool hitTargetIsRowEmptyRegion
= !row
->selectionRectCore().contains(row
->mapFromItem(m_view
, pos
));
1736 // again, when this method returns false, a rubberBand selection is created as the event is not consumed;
1737 // createRubberBand here tells us whether to return true or false.
1738 bool createRubberBand
= (hitTargetIsRowEmptyRegion
&& m_selectionManager
->selectedItems().isEmpty());
1741 row
->setPressed(true);
1744 if (rightClick
&& hitTargetIsRowEmptyRegion
) {
1745 // We have a right click outside the icon and text rect but within the hover highlight area.
1746 // We don't want items to get selected through this, so we return now.
1750 m_selectionManager
->setCurrentItem(m_pressedIndex
.value());
1752 switch (m_selectionBehavior
) {
1756 case SingleSelection
:
1757 if (!leftClick
|| shiftOrControlPressed
|| (!singleClickActivation
&& !m_singleClickActivationEnforced
)) {
1758 m_selectionManager
->setSelected(m_pressedIndex
.value());
1762 case MultiSelection
:
1763 if (controlPressed
&& !shiftPressed
&& leftClick
) {
1764 // A left mouse button press is happening on an item while control is pressed. This either means a user wants to:
1765 // - toggle the selection of item(s) or
1766 // - they want to begin a drag on the item(s) to copy them.
1767 // We rule out the latter, if the item is not clicked directly and was unselected previously.
1768 const auto row
= m_view
->m_visibleItems
.value(m_pressedIndex
.value());
1769 const auto mappedPos
= row
->mapFromItem(m_view
, pos
);
1770 if (!row
->selectionRectCore().contains(mappedPos
)) {
1771 createRubberBand
= true;
1773 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1774 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1775 createRubberBand
= false; // multi selection, don't propagate any further
1776 // This will be the start of an item drag-to-copy operation if the user now moves the mouse before releasing the mouse button.
1778 } else if (!shiftPressed
|| !m_selectionManager
->isAnchoredSelectionActive()) {
1779 // Select the pressed item and start a new anchored selection
1780 if (!leftClick
|| shiftOrControlPressed
|| (!singleClickActivation
&& !m_singleClickActivationEnforced
)) {
1781 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1783 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1792 return !createRubberBand
;
1798 bool KItemListController::onRelease(const QPointF
&pos
, const Qt::KeyboardModifiers modifiers
, const Qt::MouseButtons buttons
, bool touch
)
1800 const QPointF pressedMousePos
= pos
;
1801 const bool isAboveSelectionToggle
= m_view
->isAboveSelectionToggle(m_pressedIndex
.value_or(-1), pressedMousePos
);
1802 if (isAboveSelectionToggle
) {
1803 m_selectionTogglePressed
= false;
1807 if (!isAboveSelectionToggle
&& m_selectionTogglePressed
) {
1808 m_selectionManager
->setSelected(m_pressedIndex
.value_or(-1), 1, KItemListSelectionManager::Toggle
);
1809 m_selectionTogglePressed
= false;
1813 const bool controlPressed
= modifiers
& Qt::ControlModifier
;
1814 const bool shiftOrControlPressed
= modifiers
& Qt::ShiftModifier
|| controlPressed
;
1816 const std::optional
<int> index
= m_view
->itemAt(pos
);
1818 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1819 bool rubberBandRelease
= false;
1820 if (rubberBand
->isActive()) {
1821 disconnect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1822 rubberBand
->setActive(false);
1823 m_oldSelection
.clear();
1824 m_view
->setAutoScroll(false);
1825 rubberBandRelease
= true;
1826 // We check for actual rubber band drag here: if delta between start and end is less than drag threshold,
1827 // then we have a single click on one of the rows
1828 if ((rubberBand
->endPosition() - rubberBand
->startPosition()).manhattanLength() < QApplication::startDragDistance()) {
1829 rubberBandRelease
= false; // since we're only selecting, unmark rubber band release flag
1830 // m_pressedIndex will have no value if we came from a multi-selection clearing onPress
1831 // in that case, we don't select anything
1832 if (index
.has_value() && m_pressedIndex
.has_value()) {
1833 if (controlPressed
&& m_selectionBehavior
== MultiSelection
) {
1834 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Toggle
);
1836 m_selectionManager
->setSelected(index
.value());
1838 if (!m_selectionManager
->isAnchoredSelectionActive()) {
1839 m_selectionManager
->beginAnchoredSelection(index
.value());
1845 if (index
.has_value() && index
== m_pressedIndex
) {
1846 // The release event is done above the same item as the press event
1848 if (m_clearSelectionIfItemsAreNotDragged
) {
1849 // A selected item has been clicked, but no drag operation has been started
1850 // -> clear the rest of the selection.
1851 m_selectionManager
->clearSelection();
1852 m_selectionManager
->setSelected(m_pressedIndex
.value(), 1, KItemListSelectionManager::Select
);
1853 m_selectionManager
->beginAnchoredSelection(m_pressedIndex
.value());
1856 if (buttons
& Qt::LeftButton
) {
1857 bool emitItemActivated
= true;
1858 if (m_view
->isAboveExpansionToggle(index
.value(), pos
)) {
1859 const bool expanded
= m_model
->isExpanded(index
.value());
1860 m_model
->setExpanded(index
.value(), !expanded
);
1862 Q_EMIT
itemExpansionToggleClicked(index
.value());
1863 emitItemActivated
= false;
1864 } else if (shiftOrControlPressed
&& m_selectionBehavior
!= SingleSelection
) {
1865 // The mouse click should only update the selection, not trigger the item, except when
1866 // we are in single selection mode
1867 emitItemActivated
= false;
1869 const bool singleClickActivation
= m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
) || m_singleClickActivationEnforced
;
1870 if (!singleClickActivation
) {
1871 emitItemActivated
= touch
&& !m_selectionMode
;
1873 // activate on single click only if we didn't come from a rubber band release
1874 emitItemActivated
= !rubberBandRelease
;
1877 if (emitItemActivated
) {
1878 Q_EMIT
itemActivated(index
.value());
1880 } else if (buttons
& Qt::MiddleButton
) {
1881 Q_EMIT
itemMiddleClicked(index
.value());
1885 m_pressedMouseGlobalPos
= QPointF();
1886 m_pressedIndex
= std::nullopt
;
1887 m_clearSelectionIfItemsAreNotDragged
= false;
1891 void KItemListController::startRubberBand()
1893 if (m_selectionBehavior
== MultiSelection
) {
1894 QPoint startPos
= m_view
->transform().map(m_view
->scene()->views().first()->mapFromGlobal(m_pressedMouseGlobalPos
.toPoint()));
1895 if (m_view
->scrollOrientation() == Qt::Vertical
) {
1896 startPos
.ry() += m_view
->scrollOffset();
1898 startPos
.rx() += m_view
->scrollOffset();
1901 m_oldSelection
= m_selectionManager
->selectedItems();
1902 KItemListRubberBand
*rubberBand
= m_view
->rubberBand();
1903 rubberBand
->setStartPosition(startPos
);
1904 rubberBand
->setEndPosition(startPos
);
1905 rubberBand
->setActive(true);
1906 connect(rubberBand
, &KItemListRubberBand::endPositionChanged
, this, &KItemListController::slotRubberBandChanged
);
1907 m_view
->setAutoScroll(true);
1911 void KItemListController::slotStateChanged(QScroller::State newState
)
1913 if (newState
== QScroller::Scrolling
) {
1914 m_scrollerIsScrolling
= true;
1915 } else if (newState
== QScroller::Inactive
) {
1916 m_scrollerIsScrolling
= false;
1920 #include "moc_kitemlistcontroller.cpp"