]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistcontroller.cpp
Replace context menu on long press with selection mode
[dolphin.git] / src / kitemviews / kitemlistcontroller.cpp
1 /*
2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2012 Frank Reininghaus <frank78ac@googlemail.com>
4 *
5 * Based on the Itemviews NG project from Trolltech Labs
6 *
7 * SPDX-License-Identifier: GPL-2.0-or-later
8 */
9
10 #include "kitemlistcontroller.h"
11
12 #include "kitemlistselectionmanager.h"
13 #include "kitemlistview.h"
14 #include "private/kitemlistkeyboardsearchmanager.h"
15 #include "private/kitemlistrubberband.h"
16 #include "views/draganddrophelper.h"
17
18 #include <KTwoFingerSwipe>
19 #include <KTwoFingerTap>
20 #include <KUrlMimeData>
21
22 #include <QAccessible>
23 #include <QApplication>
24 #include <QDrag>
25 #include <QGesture>
26 #include <QGraphicsScene>
27 #include <QGraphicsSceneEvent>
28 #include <QGraphicsView>
29 #include <QMimeData>
30 #include <QTimer>
31 #include <QTouchEvent>
32
33 KItemListController::KItemListController(KItemModelBase* model, KItemListView* view, QObject* parent) :
34 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),
43 m_mousePress(false),
44 m_isTouchEvent(false),
45 m_selectionBehavior(NoSelection),
46 m_autoActivationBehavior(ActivationAndExpansion),
47 m_mouseDoubleClickAction(ActivateItemOnly),
48 m_model(nullptr),
49 m_view(nullptr),
50 m_selectionManager(new KItemListSelectionManager(this)),
51 m_keyboardManager(new KItemListKeyboardSearchManager(this)),
52 m_pressedIndex(std::nullopt),
53 m_pressedMousePos(),
54 m_autoActivationTimer(nullptr),
55 m_swipeGesture(Qt::CustomGesture),
56 m_twoFingerTapGesture(Qt::CustomGesture),
57 m_oldSelection(),
58 m_keyboardAnchorIndex(-1),
59 m_keyboardAnchorPos(0)
60 {
61 connect(m_keyboardManager, &KItemListKeyboardSearchManager::changeCurrentItem,
62 this, &KItemListController::slotChangeCurrentItem);
63 connect(m_selectionManager, &KItemListSelectionManager::currentChanged,
64 m_keyboardManager, &KItemListKeyboardSearchManager::slotCurrentChanged);
65 connect(m_selectionManager, &KItemListSelectionManager::selectionChanged,
66 m_keyboardManager, &KItemListKeyboardSearchManager::slotSelectionChanged);
67
68 m_autoActivationTimer = new QTimer(this);
69 m_autoActivationTimer->setSingleShot(true);
70 m_autoActivationTimer->setInterval(-1);
71 connect(m_autoActivationTimer, &QTimer::timeout, this, &KItemListController::slotAutoActivationTimeout);
72
73 setModel(model);
74 setView(view);
75
76 m_swipeGesture = QGestureRecognizer::registerRecognizer(new KTwoFingerSwipeRecognizer());
77 m_twoFingerTapGesture = QGestureRecognizer::registerRecognizer(new KTwoFingerTapRecognizer());
78 view->grabGesture(m_swipeGesture);
79 view->grabGesture(m_twoFingerTapGesture);
80 view->grabGesture(Qt::TapGesture);
81 view->grabGesture(Qt::TapAndHoldGesture);
82 view->grabGesture(Qt::PinchGesture);
83 }
84
85 KItemListController::~KItemListController()
86 {
87 setView(nullptr);
88 Q_ASSERT(!m_view);
89
90 setModel(nullptr);
91 Q_ASSERT(!m_model);
92 }
93
94 void KItemListController::setModel(KItemModelBase* model)
95 {
96 if (m_model == model) {
97 return;
98 }
99
100 KItemModelBase* oldModel = m_model;
101 if (oldModel) {
102 oldModel->deleteLater();
103 }
104
105 m_model = model;
106 if (m_model) {
107 m_model->setParent(this);
108 }
109
110 if (m_view) {
111 m_view->setModel(m_model);
112 }
113
114 m_selectionManager->setModel(m_model);
115
116 Q_EMIT modelChanged(m_model, oldModel);
117 }
118
119 KItemModelBase* KItemListController::model() const
120 {
121 return m_model;
122 }
123
124 KItemListSelectionManager* KItemListController::selectionManager() const
125 {
126 return m_selectionManager;
127 }
128
129 void KItemListController::setView(KItemListView* view)
130 {
131 if (m_view == view) {
132 return;
133 }
134
135 KItemListView* oldView = m_view;
136 if (oldView) {
137 disconnect(oldView, &KItemListView::scrollOffsetChanged, this, &KItemListController::slotViewScrollOffsetChanged);
138 oldView->deleteLater();
139 }
140
141 m_view = view;
142
143 if (m_view) {
144 m_view->setParent(this);
145 m_view->setController(this);
146 m_view->setModel(m_model);
147 connect(m_view, &KItemListView::scrollOffsetChanged, this, &KItemListController::slotViewScrollOffsetChanged);
148 updateExtendedSelectionRegion();
149 }
150
151 Q_EMIT viewChanged(m_view, oldView);
152 }
153
154 KItemListView* KItemListController::view() const
155 {
156 return m_view;
157 }
158
159 void KItemListController::setSelectionBehavior(SelectionBehavior behavior)
160 {
161 m_selectionBehavior = behavior;
162 updateExtendedSelectionRegion();
163 }
164
165 KItemListController::SelectionBehavior KItemListController::selectionBehavior() const
166 {
167 return m_selectionBehavior;
168 }
169
170 void KItemListController::setAutoActivationBehavior(AutoActivationBehavior behavior)
171 {
172 m_autoActivationBehavior = behavior;
173 }
174
175 KItemListController::AutoActivationBehavior KItemListController::autoActivationBehavior() const
176 {
177 return m_autoActivationBehavior;
178 }
179
180 void KItemListController::setMouseDoubleClickAction(MouseDoubleClickAction action)
181 {
182 m_mouseDoubleClickAction = action;
183 }
184
185 KItemListController::MouseDoubleClickAction KItemListController::mouseDoubleClickAction() const
186 {
187 return m_mouseDoubleClickAction;
188 }
189
190 int KItemListController::indexCloseToMousePressedPosition() const
191 {
192 QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_view->m_visibleGroups);
193 while (it.hasNext()) {
194 it.next();
195 KItemListGroupHeader *groupHeader = it.value();
196 const QPointF mappedToGroup = groupHeader->mapFromItem(nullptr, m_pressedMousePos);
197 if (groupHeader->contains(mappedToGroup)) {
198 return it.key()->index();
199 }
200 }
201 return -1;
202 }
203
204 void KItemListController::setAutoActivationDelay(int delay)
205 {
206 m_autoActivationTimer->setInterval(delay);
207 }
208
209 int KItemListController::autoActivationDelay() const
210 {
211 return m_autoActivationTimer->interval();
212 }
213
214 void KItemListController::setSingleClickActivationEnforced(bool singleClick)
215 {
216 m_singleClickActivationEnforced = singleClick;
217 }
218
219 bool KItemListController::singleClickActivationEnforced() const
220 {
221 return m_singleClickActivationEnforced;
222 }
223
224 void KItemListController::setSelectionModeEnabled(bool enabled)
225 {
226 m_selectionMode = enabled;
227 }
228
229 bool KItemListController::selectionMode() const
230 {
231 return m_selectionMode;
232 }
233
234 bool KItemListController::keyPressEvent(QKeyEvent* event)
235 {
236 int index = m_selectionManager->currentItem();
237 int key = event->key();
238
239 // Handle the expanding/collapsing of items
240 if (m_view->supportsItemExpanding() && m_model->isExpandable(index)) {
241 if (key == Qt::Key_Right) {
242 if (m_model->setExpanded(index, true)) {
243 return true;
244 }
245 } else if (key == Qt::Key_Left) {
246 if (m_model->setExpanded(index, false)) {
247 return true;
248 }
249 }
250 }
251
252 const bool shiftPressed = event->modifiers() & Qt::ShiftModifier;
253 const bool controlPressed = event->modifiers() & Qt::ControlModifier;
254 const bool shiftOrControlPressed = shiftPressed || controlPressed;
255 const bool navigationPressed = key == Qt::Key_Home || key == Qt::Key_End ||
256 key == Qt::Key_PageUp || key == Qt::Key_PageDown ||
257 key == Qt::Key_Up || key == Qt::Key_Down ||
258 key == Qt::Key_Left || key == Qt::Key_Right;
259
260 const int itemCount = m_model->count();
261
262 // For horizontal scroll orientation, transform
263 // the arrow keys to simplify the event handling.
264 if (m_view->scrollOrientation() == Qt::Horizontal) {
265 switch (key) {
266 case Qt::Key_Up: key = Qt::Key_Left; break;
267 case Qt::Key_Down: key = Qt::Key_Right; break;
268 case Qt::Key_Left: key = Qt::Key_Up; break;
269 case Qt::Key_Right: key = Qt::Key_Down; break;
270 default: break;
271 }
272 }
273
274 const bool selectSingleItem = m_selectionBehavior != NoSelection && itemCount == 1 && navigationPressed;
275
276 if (selectSingleItem) {
277 const int current = m_selectionManager->currentItem();
278 m_selectionManager->setSelected(current);
279 return true;
280 }
281
282 switch (key) {
283 case Qt::Key_Home:
284 index = 0;
285 m_keyboardAnchorIndex = index;
286 m_keyboardAnchorPos = keyboardAnchorPos(index);
287 break;
288
289 case Qt::Key_End:
290 index = itemCount - 1;
291 m_keyboardAnchorIndex = index;
292 m_keyboardAnchorPos = keyboardAnchorPos(index);
293 break;
294
295 case Qt::Key_Left:
296 if (index > 0) {
297 const int expandedParentsCount = m_model->expandedParentsCount(index);
298 if (expandedParentsCount == 0) {
299 --index;
300 } else {
301 // Go to the parent of the current item.
302 do {
303 --index;
304 } while (index > 0 && m_model->expandedParentsCount(index) == expandedParentsCount);
305 }
306 m_keyboardAnchorIndex = index;
307 m_keyboardAnchorPos = keyboardAnchorPos(index);
308 }
309 break;
310
311 case Qt::Key_Right:
312 if (index < itemCount - 1) {
313 ++index;
314 m_keyboardAnchorIndex = index;
315 m_keyboardAnchorPos = keyboardAnchorPos(index);
316 }
317 break;
318
319 case Qt::Key_Up:
320 updateKeyboardAnchor();
321 index = previousRowIndex(index);
322 break;
323
324 case Qt::Key_Down:
325 updateKeyboardAnchor();
326 index = nextRowIndex(index);
327 break;
328
329 case Qt::Key_PageUp:
330 if (m_view->scrollOrientation() == Qt::Horizontal) {
331 // The new current index should correspond to the first item in the current column.
332 int newIndex = qMax(index - 1, 0);
333 while (newIndex != index && m_view->itemRect(newIndex).topLeft().y() < m_view->itemRect(index).topLeft().y()) {
334 index = newIndex;
335 newIndex = qMax(index - 1, 0);
336 }
337 m_keyboardAnchorIndex = index;
338 m_keyboardAnchorPos = keyboardAnchorPos(index);
339 } else {
340 const qreal currentItemBottom = m_view->itemRect(index).bottomLeft().y();
341 const qreal height = m_view->geometry().height();
342
343 // The new current item should be the first item in the current
344 // column whose itemRect's top coordinate is larger than targetY.
345 const qreal targetY = currentItemBottom - height;
346
347 updateKeyboardAnchor();
348 int newIndex = previousRowIndex(index);
349 do {
350 index = newIndex;
351 updateKeyboardAnchor();
352 newIndex = previousRowIndex(index);
353 } while (m_view->itemRect(newIndex).topLeft().y() > targetY && newIndex != index);
354 }
355 break;
356
357 case Qt::Key_PageDown:
358 if (m_view->scrollOrientation() == Qt::Horizontal) {
359 // The new current index should correspond to the last item in the current column.
360 int newIndex = qMin(index + 1, m_model->count() - 1);
361 while (newIndex != index && m_view->itemRect(newIndex).topLeft().y() > m_view->itemRect(index).topLeft().y()) {
362 index = newIndex;
363 newIndex = qMin(index + 1, m_model->count() - 1);
364 }
365 m_keyboardAnchorIndex = index;
366 m_keyboardAnchorPos = keyboardAnchorPos(index);
367 } else {
368 const qreal currentItemTop = m_view->itemRect(index).topLeft().y();
369 const qreal height = m_view->geometry().height();
370
371 // The new current item should be the last item in the current
372 // column whose itemRect's bottom coordinate is smaller than targetY.
373 const qreal targetY = currentItemTop + height;
374
375 updateKeyboardAnchor();
376 int newIndex = nextRowIndex(index);
377 do {
378 index = newIndex;
379 updateKeyboardAnchor();
380 newIndex = nextRowIndex(index);
381 } while (m_view->itemRect(newIndex).bottomLeft().y() < targetY && newIndex != index);
382 }
383 break;
384
385 case Qt::Key_Enter:
386 case Qt::Key_Return: {
387 const KItemSet selectedItems = m_selectionManager->selectedItems();
388 if (selectedItems.count() >= 2) {
389 Q_EMIT itemsActivated(selectedItems);
390 } else if (selectedItems.count() == 1) {
391 Q_EMIT itemActivated(selectedItems.first());
392 } else {
393 Q_EMIT itemActivated(index);
394 }
395 break;
396 }
397
398 case Qt::Key_Menu: {
399 // Emit the signal itemContextMenuRequested() in case if at least one
400 // item is selected. Otherwise the signal viewContextMenuRequested() will be emitted.
401 const KItemSet selectedItems = m_selectionManager->selectedItems();
402 int index = -1;
403 if (selectedItems.count() >= 2) {
404 const int currentItemIndex = m_selectionManager->currentItem();
405 index = selectedItems.contains(currentItemIndex)
406 ? currentItemIndex : selectedItems.first();
407 } else if (selectedItems.count() == 1) {
408 index = selectedItems.first();
409 }
410
411 if (index >= 0) {
412 const QRectF contextRect = m_view->itemContextRect(index);
413 const QPointF pos(m_view->scene()->views().first()->mapToGlobal(contextRect.bottomRight().toPoint()));
414 Q_EMIT itemContextMenuRequested(index, pos);
415 } else {
416 Q_EMIT viewContextMenuRequested(QCursor::pos());
417 }
418 break;
419 }
420
421 case Qt::Key_Escape:
422 if (m_selectionMode) {
423 Q_EMIT selectionModeChangeRequested(false);
424 } else if (m_selectionBehavior != SingleSelection) {
425 m_selectionManager->clearSelection();
426 }
427 m_keyboardManager->cancelSearch();
428 Q_EMIT escapePressed();
429 break;
430
431 case Qt::Key_Space:
432 if (m_selectionBehavior == MultiSelection) {
433 if (controlPressed) {
434 // Toggle the selection state of the current item.
435 m_selectionManager->endAnchoredSelection();
436 m_selectionManager->setSelected(index, 1, KItemListSelectionManager::Toggle);
437 m_selectionManager->beginAnchoredSelection(index);
438 break;
439 } else {
440 // Select the current item if it is not selected yet.
441 const int current = m_selectionManager->currentItem();
442 if (!m_selectionManager->isSelected(current)) {
443 m_selectionManager->setSelected(current);
444 break;
445 }
446 }
447 }
448 Q_FALLTHROUGH(); // fall through to the default case and add the Space to the current search string.
449 default:
450 m_keyboardManager->addKeys(event->text());
451 // Make sure unconsumed events get propagated up the chain. #302329
452 event->ignore();
453 return false;
454 }
455
456 if (m_selectionManager->currentItem() != index) {
457 switch (m_selectionBehavior) {
458 case NoSelection:
459 m_selectionManager->setCurrentItem(index);
460 break;
461
462 case SingleSelection:
463 m_selectionManager->setCurrentItem(index);
464 m_selectionManager->clearSelection();
465 m_selectionManager->setSelected(index, 1);
466 break;
467
468 case MultiSelection:
469 if (controlPressed) {
470 m_selectionManager->endAnchoredSelection();
471 }
472
473 m_selectionManager->setCurrentItem(index);
474
475 if (!shiftOrControlPressed) {
476 m_selectionManager->clearSelection();
477 m_selectionManager->setSelected(index, 1);
478 }
479
480 if (!shiftPressed) {
481 m_selectionManager->beginAnchoredSelection(index);
482 }
483 break;
484 }
485 }
486
487 if (navigationPressed) {
488 m_view->scrollToItem(index);
489 }
490 return true;
491 }
492
493 void KItemListController::slotChangeCurrentItem(const QString& text, bool searchFromNextItem)
494 {
495 if (!m_model || m_model->count() == 0) {
496 return;
497 }
498 int index;
499 if (searchFromNextItem) {
500 const int currentIndex = m_selectionManager->currentItem();
501 index = m_model->indexForKeyboardSearch(text, (currentIndex + 1) % m_model->count());
502 } else {
503 index = m_model->indexForKeyboardSearch(text, 0);
504 }
505 if (index >= 0) {
506 m_selectionManager->setCurrentItem(index);
507
508 if (m_selectionBehavior != NoSelection) {
509 m_selectionManager->replaceSelection(index);
510 m_selectionManager->beginAnchoredSelection(index);
511 }
512
513 m_view->scrollToItem(index);
514 }
515 }
516
517 void KItemListController::slotAutoActivationTimeout()
518 {
519 if (!m_model || !m_view) {
520 return;
521 }
522
523 const int index = m_autoActivationTimer->property("index").toInt();
524 if (index < 0 || index >= m_model->count()) {
525 return;
526 }
527
528 /* m_view->isUnderMouse() fixes a bug in the Folder-View-Panel and in the
529 * Places-Panel.
530 *
531 * Bug: When you drag a file onto a Folder-View-Item or a Places-Item and
532 * then move away before the auto-activation timeout triggers, than the
533 * item still becomes activated/expanded.
534 *
535 * See Bug 293200 and 305783
536 */
537 if (m_model->supportsDropping(index) && m_view->isUnderMouse()) {
538 if (m_view->supportsItemExpanding() && m_model->isExpandable(index)) {
539 const bool expanded = m_model->isExpanded(index);
540 m_model->setExpanded(index, !expanded);
541 } else if (m_autoActivationBehavior != ExpansionOnly) {
542 Q_EMIT itemActivated(index);
543 }
544 }
545 }
546
547 bool KItemListController::inputMethodEvent(QInputMethodEvent* event)
548 {
549 Q_UNUSED(event)
550 return false;
551 }
552
553 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
554 {
555 m_mousePress = true;
556
557 if (event->source() == Qt::MouseEventSynthesizedByQt && m_isTouchEvent) {
558 return false;
559 }
560
561 if (!m_view) {
562 return false;
563 }
564
565 m_pressedMousePos = transform.map(event->pos());
566 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
567
568 const Qt::MouseButtons buttons = event->buttons();
569
570 if (!onPress(event->screenPos(), event->pos(), event->modifiers(), buttons)) {
571 startRubberBand();
572 return false;
573 }
574
575 return true;
576 }
577
578 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
579 {
580 if (!m_view) {
581 return false;
582 }
583
584 if (m_view->m_tapAndHoldIndicator->isActive()) {
585 m_view->m_tapAndHoldIndicator->setActive(false);
586 }
587
588 if (event->source() == Qt::MouseEventSynthesizedByQt && !m_dragActionOrRightClick && m_isTouchEvent) {
589 return false;
590 }
591
592 const QPointF pos = transform.map(event->pos());
593
594 if (m_pressedIndex.has_value() && !m_view->rubberBand()->isActive()) {
595 // Check whether a dragging should be started
596 if (event->buttons() & Qt::LeftButton) {
597 if ((pos - m_pressedMousePos).manhattanLength() >= QApplication::startDragDistance()) {
598 if (!m_selectionManager->isSelected(m_pressedIndex.value())) {
599 // Always assure that the dragged item gets selected. Usually this is already
600 // done on the mouse-press event, but when using the selection-toggle on a
601 // selected item the dragged item is not selected yet.
602 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Toggle);
603 } else {
604 // A selected item has been clicked to drag all selected items
605 // -> the selection should not be cleared when the mouse button is released.
606 m_clearSelectionIfItemsAreNotDragged = false;
607 }
608 startDragging();
609 m_mousePress = false;
610 }
611 }
612 } else {
613 KItemListRubberBand* rubberBand = m_view->rubberBand();
614 if (rubberBand->isActive()) {
615 QPointF endPos = transform.map(event->pos());
616
617 // Update the current item.
618 const std::optional<int> newCurrent = m_view->itemAt(endPos);
619 if (newCurrent.has_value()) {
620 // It's expected that the new current index is also the new anchor (bug 163451).
621 m_selectionManager->endAnchoredSelection();
622 m_selectionManager->setCurrentItem(newCurrent.value());
623 m_selectionManager->beginAnchoredSelection(newCurrent.value());
624 }
625
626 if (m_view->scrollOrientation() == Qt::Vertical) {
627 endPos.ry() += m_view->scrollOffset();
628 if (m_view->itemSize().width() < 0) {
629 // Use a special rubberband for views that have only one column and
630 // expand the rubberband to use the whole width of the view.
631 endPos.setX(m_view->size().width());
632 }
633 } else {
634 endPos.rx() += m_view->scrollOffset();
635 }
636 rubberBand->setEndPosition(endPos);
637 }
638 }
639
640 return false;
641 }
642
643 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
644 {
645 m_mousePress = false;
646 m_isTouchEvent = false;
647
648 if (!m_view) {
649 return false;
650 }
651
652 if (m_view->m_tapAndHoldIndicator->isActive()) {
653 m_view->m_tapAndHoldIndicator->setActive(false);
654 }
655
656 KItemListRubberBand* rubberBand = m_view->rubberBand();
657 if (event->source() == Qt::MouseEventSynthesizedByQt && !rubberBand->isActive() && m_isTouchEvent) {
658 return false;
659 }
660
661 Q_EMIT mouseButtonReleased(m_pressedIndex.value_or(-1), event->buttons());
662
663 return onRelease(transform.map(event->pos()), event->modifiers(), event->button(), false);
664 }
665
666 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
667 {
668 const QPointF pos = transform.map(event->pos());
669 const std::optional<int> index = m_view->itemAt(pos);
670
671 // Expand item if desired - See Bug 295573
672 if (m_mouseDoubleClickAction != ActivateItemOnly) {
673 if (m_view && m_model && m_view->supportsItemExpanding() && m_model->isExpandable(index.value_or(-1))) {
674 const bool expanded = m_model->isExpanded(index.value());
675 m_model->setExpanded(index.value(), !expanded);
676 }
677 }
678
679 if (event->button() & Qt::RightButton) {
680 m_selectionManager->clearSelection();
681 if (index.has_value()) {
682 m_selectionManager->setSelected(index.value());
683 Q_EMIT itemContextMenuRequested(index.value(), event->screenPos());
684 } else {
685 const QRectF headerBounds = m_view->headerBoundaries();
686 if (headerBounds.contains(event->pos())) {
687 Q_EMIT headerContextMenuRequested(event->screenPos());
688 } else {
689 Q_EMIT viewContextMenuRequested(event->screenPos());
690 }
691 }
692 return true;
693 }
694
695 bool emitItemActivated = !(m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) || m_singleClickActivationEnforced) &&
696 (event->button() & Qt::LeftButton) &&
697 index.has_value() && index.value() < m_model->count();
698 if (emitItemActivated) {
699 Q_EMIT itemActivated(index.value());
700 }
701 return false;
702 }
703
704 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
705 {
706 Q_UNUSED(event)
707 Q_UNUSED(transform)
708
709 DragAndDropHelper::clearUrlListMatchesUrlCache();
710
711 return false;
712 }
713
714 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
715 {
716 Q_UNUSED(event)
717 Q_UNUSED(transform)
718
719 m_autoActivationTimer->stop();
720 m_view->setAutoScroll(false);
721 m_view->hideDropIndicator();
722
723 KItemListWidget* widget = hoveredWidget();
724 if (widget) {
725 widget->setHovered(false);
726 Q_EMIT itemUnhovered(widget->index());
727 }
728 return false;
729 }
730
731 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
732 {
733 if (!m_model || !m_view) {
734 return false;
735 }
736
737
738 QUrl hoveredDir = m_model->directory();
739 KItemListWidget* oldHoveredWidget = hoveredWidget();
740
741 const QPointF pos = transform.map(event->pos());
742 KItemListWidget* newHoveredWidget = widgetForDropPos(pos);
743
744 if (oldHoveredWidget != newHoveredWidget) {
745 m_autoActivationTimer->stop();
746
747 if (oldHoveredWidget) {
748 oldHoveredWidget->setHovered(false);
749 Q_EMIT itemUnhovered(oldHoveredWidget->index());
750 }
751 }
752
753 if (newHoveredWidget) {
754 bool droppingBetweenItems = false;
755 if (m_model->sortRole().isEmpty()) {
756 // The model supports inserting items between other items.
757 droppingBetweenItems = (m_view->showDropIndicator(pos) >= 0);
758 }
759
760 const int index = newHoveredWidget->index();
761
762 if (m_model->isDir(index)) {
763 hoveredDir = m_model->url(index);
764 }
765
766 if (!droppingBetweenItems) {
767 if (m_model->supportsDropping(index)) {
768 // Something has been dragged on an item.
769 m_view->hideDropIndicator();
770 if (!newHoveredWidget->isHovered()) {
771 newHoveredWidget->setHovered(true);
772 Q_EMIT itemHovered(index);
773 }
774
775 if (!m_autoActivationTimer->isActive() && m_autoActivationTimer->interval() >= 0) {
776 m_autoActivationTimer->setProperty("index", index);
777 m_autoActivationTimer->start();
778 }
779 }
780 } else {
781 m_autoActivationTimer->stop();
782 if (newHoveredWidget && newHoveredWidget->isHovered()) {
783 newHoveredWidget->setHovered(false);
784 Q_EMIT itemUnhovered(index);
785 }
786 }
787 } else {
788 m_view->hideDropIndicator();
789 }
790
791 if (DragAndDropHelper::urlListMatchesUrl(event->mimeData()->urls(), hoveredDir)) {
792 event->setDropAction(Qt::IgnoreAction);
793 event->ignore();
794 } else {
795 event->setDropAction(event->proposedAction());
796 event->accept();
797 }
798 return false;
799 }
800
801 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
802 {
803 if (!m_view) {
804 return false;
805 }
806
807 m_autoActivationTimer->stop();
808 m_view->setAutoScroll(false);
809
810 const QPointF pos = transform.map(event->pos());
811
812 int dropAboveIndex = -1;
813 if (m_model->sortRole().isEmpty()) {
814 // The model supports inserting of items between other items.
815 dropAboveIndex = m_view->showDropIndicator(pos);
816 }
817
818 if (dropAboveIndex >= 0) {
819 // Something has been dropped between two items.
820 m_view->hideDropIndicator();
821 Q_EMIT aboveItemDropEvent(dropAboveIndex, event);
822 } else if (!event->mimeData()->hasFormat(m_model->blacklistItemDropEventMimeType())) {
823 // Something has been dropped on an item or on an empty part of the view.
824 const KItemListWidget *receivingWidget = widgetForDropPos(pos);
825 if (receivingWidget) {
826 Q_EMIT itemDropEvent(receivingWidget->index(), event);
827 } else {
828 Q_EMIT itemDropEvent(-1, event);
829 }
830 }
831
832 QAccessibleEvent accessibilityEvent(view(), QAccessible::DragDropEnd);
833 QAccessible::updateAccessibility(&accessibilityEvent);
834
835 return true;
836 }
837
838 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
839 {
840 Q_UNUSED(event)
841 Q_UNUSED(transform)
842 return false;
843 }
844
845 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
846 {
847 Q_UNUSED(transform)
848 if (!m_model || !m_view) {
849 return false;
850 }
851
852 // We identify the widget whose expansionArea had been hovered before this hoverMoveEvent() triggered.
853 // we can't use hoveredWidget() here (it handles the icon+text rect, not the expansion rect)
854 // like hoveredWidget(), we find the hovered widget for the expansion rect
855 const auto visibleItemListWidgets = m_view->visibleItemListWidgets();
856 const auto oldHoveredExpansionWidgetIterator = std::find_if(visibleItemListWidgets.begin(), visibleItemListWidgets.end(), [](auto &widget) {
857 return widget->expansionAreaHovered();
858 });
859 const auto oldHoveredExpansionWidget = oldHoveredExpansionWidgetIterator == visibleItemListWidgets.end() ?
860 std::nullopt : std::make_optional(*oldHoveredExpansionWidgetIterator);
861
862 const auto unhoverOldHoveredWidget = [&]() {
863 if (auto oldHoveredWidget = hoveredWidget(); oldHoveredWidget) {
864 // handle the text+icon one
865 oldHoveredWidget->setHovered(false);
866 Q_EMIT itemUnhovered(oldHoveredWidget->index());
867 }
868 };
869
870 const auto unhoverOldExpansionWidget = [&]() {
871 if (oldHoveredExpansionWidget) {
872 // then the expansion toggle
873 (*oldHoveredExpansionWidget)->setExpansionAreaHovered(false);
874 }
875 };
876
877 const QPointF pos = transform.map(event->pos());
878 if (KItemListWidget *newHoveredWidget = widgetForPos(pos); newHoveredWidget) {
879 // something got hovered, work out which part and set hover for the appropriate widget
880 const auto mappedPos = newHoveredWidget->mapFromItem(m_view, pos);
881 const bool isOnExpansionToggle = newHoveredWidget->expansionToggleRect().contains(mappedPos);
882
883 if (isOnExpansionToggle) {
884 // make sure we unhover the old one first if old!=new
885 if (oldHoveredExpansionWidget && *oldHoveredExpansionWidget != newHoveredWidget) {
886 (*oldHoveredExpansionWidget)->setExpansionAreaHovered(false);
887 }
888 // 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)
889 unhoverOldHoveredWidget();
890
891
892 newHoveredWidget->setExpansionAreaHovered(true);
893 } else {
894 // make sure we unhover the old one first if old!=new
895 auto oldHoveredWidget = hoveredWidget();
896 if (oldHoveredWidget && oldHoveredWidget != newHoveredWidget) {
897 oldHoveredWidget->setHovered(false);
898 Q_EMIT itemUnhovered(oldHoveredWidget->index());
899 }
900 // 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)
901 unhoverOldExpansionWidget();
902
903 const bool isOverIconAndText = newHoveredWidget->iconRect().contains(mappedPos) || newHoveredWidget->textRect().contains(mappedPos);
904 const bool hasMultipleSelection = m_selectionManager->selectedItems().count() > 1;
905
906 if (hasMultipleSelection && !isOverIconAndText) {
907 // In case we have multiple selections, clicking on any row will deselect the selection.
908 // So, as a visual cue for signalling that clicking anywhere won't select, but clear current highlights,
909 // we disable hover of the *row*(i.e. blank space to the right of the icon+text)
910
911 // (no-op in this branch for masked hover)
912 } else {
913 newHoveredWidget->setHoverPosition(mappedPos);
914 if (oldHoveredWidget != newHoveredWidget) {
915 newHoveredWidget->setHovered(true);
916 Q_EMIT itemHovered(newHoveredWidget->index());
917 }
918 }
919 }
920 } else {
921 // unhover any currently hovered expansion and text+icon widgets
922 unhoverOldHoveredWidget();
923 unhoverOldExpansionWidget();
924 }
925 return false;
926 }
927
928 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
929 {
930 Q_UNUSED(event)
931 Q_UNUSED(transform)
932
933 m_mousePress = false;
934 m_isTouchEvent = false;
935
936 if (!m_model || !m_view) {
937 return false;
938 }
939
940 const auto widgets = m_view->visibleItemListWidgets();
941 for (KItemListWidget* widget : widgets) {
942 if (widget->isHovered()) {
943 widget->setHovered(false);
944 Q_EMIT itemUnhovered(widget->index());
945 }
946 }
947 return false;
948 }
949
950 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent* event, const QTransform& transform)
951 {
952 Q_UNUSED(event)
953 Q_UNUSED(transform)
954 return false;
955 }
956
957 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent* event, const QTransform& transform)
958 {
959 Q_UNUSED(event)
960 Q_UNUSED(transform)
961 return false;
962 }
963
964 bool KItemListController::gestureEvent(QGestureEvent* event, const QTransform& transform)
965 {
966 if (!m_view) {
967 return false;
968 }
969
970 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
971 //we use this to get the right QWidget
972 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
973 if (!m_mousePress) {
974 if (QGesture* tap = event->gesture(Qt::TapGesture)) {
975 QTapGesture* tapGesture = static_cast<QTapGesture*>(tap);
976 if (tapGesture->state() == Qt::GestureStarted) {
977 tapTriggered(tapGesture, transform);
978 }
979 }
980 return false;
981 }
982
983 bool accepted = false;
984
985 if (QGesture* tap = event->gesture(Qt::TapGesture)) {
986 tapTriggered(static_cast<QTapGesture*>(tap), transform);
987 accepted = true;
988 }
989 if (event->gesture(Qt::TapAndHoldGesture)) {
990 tapAndHoldTriggered(event, transform);
991 accepted = true;
992 }
993 if (event->gesture(Qt::PinchGesture)) {
994 pinchTriggered(event, transform);
995 accepted = true;
996 }
997 if (event->gesture(m_swipeGesture)) {
998 swipeTriggered(event, transform);
999 accepted = true;
1000 }
1001 if (event->gesture(m_twoFingerTapGesture)) {
1002 twoFingerTapTriggered(event, transform);
1003 accepted = true;
1004 }
1005 return accepted;
1006 }
1007
1008 bool KItemListController::touchBeginEvent(QTouchEvent* event, const QTransform& transform)
1009 {
1010 Q_UNUSED(event)
1011 Q_UNUSED(transform)
1012
1013 m_isTouchEvent = true;
1014 return false;
1015 }
1016
1017 void KItemListController::tapTriggered(QTapGesture* tap, const QTransform& transform)
1018 {
1019 static bool scrollerWasActive = false;
1020
1021 if (tap->state() == Qt::GestureStarted) {
1022 m_dragActionOrRightClick = false;
1023 m_isSwipeGesture = false;
1024 m_pinchGestureInProgress = false;
1025 scrollerWasActive = m_scrollerIsScrolling;
1026 }
1027
1028 if (tap->state() == Qt::GestureFinished) {
1029 m_mousePress = false;
1030
1031 //if at the moment of the gesture start the QScroller was active, the user made the tap
1032 //to stop the QScroller and not to tap on an item
1033 if (scrollerWasActive) {
1034 return;
1035 }
1036
1037 if (m_view->m_tapAndHoldIndicator->isActive()) {
1038 m_view->m_tapAndHoldIndicator->setActive(false);
1039 }
1040
1041 m_pressedMousePos = transform.map(tap->position());
1042 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
1043
1044 if (m_dragActionOrRightClick) {
1045 m_dragActionOrRightClick = false;
1046 }
1047 else {
1048 onPress(tap->hotSpot().toPoint(), tap->position().toPoint(), Qt::NoModifier, Qt::LeftButton);
1049 onRelease(transform.map(tap->position()), Qt::NoModifier, Qt::LeftButton, true);
1050 }
1051 m_isTouchEvent = false;
1052 }
1053 }
1054
1055 void KItemListController::tapAndHoldTriggered(QGestureEvent* event, const QTransform& transform)
1056 {
1057
1058 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
1059 if (!m_isTouchEvent) {
1060 return;
1061 }
1062
1063 const QTapAndHoldGesture* tap = static_cast<QTapAndHoldGesture*>(event->gesture(Qt::TapAndHoldGesture));
1064 if (tap->state() == Qt::GestureFinished) {
1065 //if a pinch gesture is in progress we don't want a TabAndHold gesture
1066 if (m_pinchGestureInProgress) {
1067 return;
1068 }
1069 m_pressedMousePos = transform.map(event->mapToGraphicsScene(tap->position()));
1070 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
1071
1072 if (m_pressedIndex.has_value() && !m_selectionManager->isSelected(m_pressedIndex.value())) {
1073 m_selectionManager->clearSelection();
1074 m_selectionManager->setSelected(m_pressedIndex.value());
1075 if (!m_selectionMode) {
1076 Q_EMIT selectionModeChangeRequested(true);
1077 }
1078 } else if (!m_pressedIndex.has_value()) {
1079 m_selectionManager->clearSelection();
1080 startRubberBand();
1081 }
1082
1083 Q_EMIT scrollerStop();
1084
1085 m_view->m_tapAndHoldIndicator->setStartPosition(m_pressedMousePos);
1086 m_view->m_tapAndHoldIndicator->setActive(true);
1087
1088 m_dragActionOrRightClick = true;
1089 }
1090 }
1091
1092 void KItemListController::pinchTriggered(QGestureEvent* event, const QTransform& transform)
1093 {
1094 Q_UNUSED(transform)
1095
1096 const QPinchGesture* pinch = static_cast<QPinchGesture*>(event->gesture(Qt::PinchGesture));
1097 const qreal sensitivityModifier = 0.2;
1098 static qreal counter = 0;
1099
1100 if (pinch->state() == Qt::GestureStarted) {
1101 m_pinchGestureInProgress = true;
1102 counter = 0;
1103 }
1104 if (pinch->state() == Qt::GestureUpdated) {
1105 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1106 if (m_isSwipeGesture) {
1107 return;
1108 }
1109 counter = counter + (pinch->scaleFactor() - 1);
1110 if (counter >= sensitivityModifier) {
1111 Q_EMIT increaseZoom();
1112 counter = 0;
1113 } else if (counter <= -sensitivityModifier) {
1114 Q_EMIT decreaseZoom();
1115 counter = 0;
1116 }
1117 }
1118 }
1119
1120 void KItemListController::swipeTriggered(QGestureEvent* event, const QTransform& transform)
1121 {
1122 Q_UNUSED(transform)
1123
1124 const KTwoFingerSwipe* swipe = static_cast<KTwoFingerSwipe*>(event->gesture(m_swipeGesture));
1125
1126 if (!swipe) {
1127 return;
1128 }
1129 if (swipe->state() == Qt::GestureStarted) {
1130 m_isSwipeGesture = true;
1131 }
1132
1133 if (swipe->state() == Qt::GestureCanceled) {
1134 m_isSwipeGesture = false;
1135 }
1136
1137 if (swipe->state() == Qt::GestureFinished) {
1138 Q_EMIT scrollerStop();
1139
1140 if (swipe->swipeAngle() <= 20 || swipe->swipeAngle() >= 340) {
1141 Q_EMIT mouseButtonPressed(m_pressedIndex.value_or(-1), Qt::BackButton);
1142 } else if (swipe->swipeAngle() <= 200 && swipe->swipeAngle() >= 160) {
1143 Q_EMIT mouseButtonPressed(m_pressedIndex.value_or(-1), Qt::ForwardButton);
1144 } else if (swipe->swipeAngle() <= 110 && swipe->swipeAngle() >= 60) {
1145 Q_EMIT swipeUp();
1146 }
1147 m_isSwipeGesture = true;
1148 }
1149 }
1150
1151 void KItemListController::twoFingerTapTriggered(QGestureEvent* event, const QTransform& transform)
1152 {
1153 const KTwoFingerTap* twoTap = static_cast<KTwoFingerTap*>(event->gesture(m_twoFingerTapGesture));
1154
1155 if (!twoTap) {
1156 return;
1157 }
1158
1159 if (twoTap->state() == Qt::GestureStarted) {
1160 m_pressedMousePos = transform.map(twoTap->pos());
1161 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
1162 if (m_pressedIndex.has_value()) {
1163 onPress(twoTap->screenPos().toPoint(), twoTap->pos().toPoint(), Qt::ControlModifier, Qt::LeftButton);
1164 onRelease(transform.map(twoTap->pos()), Qt::ControlModifier, Qt::LeftButton, false);
1165 }
1166
1167 }
1168 }
1169
1170 bool KItemListController::processEvent(QEvent* event, const QTransform& transform)
1171 {
1172 if (!event) {
1173 return false;
1174 }
1175
1176 switch (event->type()) {
1177 case QEvent::KeyPress:
1178 return keyPressEvent(static_cast<QKeyEvent*>(event));
1179 case QEvent::InputMethod:
1180 return inputMethodEvent(static_cast<QInputMethodEvent*>(event));
1181 case QEvent::GraphicsSceneMousePress:
1182 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1183 case QEvent::GraphicsSceneMouseMove:
1184 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1185 case QEvent::GraphicsSceneMouseRelease:
1186 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1187 case QEvent::GraphicsSceneMouseDoubleClick:
1188 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1189 case QEvent::GraphicsSceneWheel:
1190 return wheelEvent(static_cast<QGraphicsSceneWheelEvent*>(event), QTransform());
1191 case QEvent::GraphicsSceneDragEnter:
1192 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1193 case QEvent::GraphicsSceneDragLeave:
1194 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1195 case QEvent::GraphicsSceneDragMove:
1196 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1197 case QEvent::GraphicsSceneDrop:
1198 return dropEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1199 case QEvent::GraphicsSceneHoverEnter:
1200 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1201 case QEvent::GraphicsSceneHoverMove:
1202 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1203 case QEvent::GraphicsSceneHoverLeave:
1204 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1205 case QEvent::GraphicsSceneResize:
1206 return resizeEvent(static_cast<QGraphicsSceneResizeEvent*>(event), transform);
1207 case QEvent::Gesture:
1208 return gestureEvent(static_cast<QGestureEvent*>(event), transform);
1209 case QEvent::TouchBegin:
1210 return touchBeginEvent(static_cast<QTouchEvent*>(event), transform);
1211 default:
1212 break;
1213 }
1214
1215 return false;
1216 }
1217
1218 void KItemListController::slotViewScrollOffsetChanged(qreal current, qreal previous)
1219 {
1220 if (!m_view) {
1221 return;
1222 }
1223
1224 KItemListRubberBand* rubberBand = m_view->rubberBand();
1225 if (rubberBand->isActive()) {
1226 const qreal diff = current - previous;
1227 // TODO: Ideally just QCursor::pos() should be used as
1228 // new end-position but it seems there is no easy way
1229 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1230 // (... or I just missed an easy way to do the mapping)
1231 QPointF endPos = rubberBand->endPosition();
1232 if (m_view->scrollOrientation() == Qt::Vertical) {
1233 endPos.ry() += diff;
1234 } else {
1235 endPos.rx() += diff;
1236 }
1237
1238 rubberBand->setEndPosition(endPos);
1239 }
1240 }
1241
1242 void KItemListController::slotRubberBandChanged()
1243 {
1244 if (!m_view || !m_model || m_model->count() <= 0) {
1245 return;
1246 }
1247
1248 const KItemListRubberBand* rubberBand = m_view->rubberBand();
1249 const QPointF startPos = rubberBand->startPosition();
1250 const QPointF endPos = rubberBand->endPosition();
1251 QRectF rubberBandRect = QRectF(startPos, endPos).normalized();
1252
1253 const bool scrollVertical = (m_view->scrollOrientation() == Qt::Vertical);
1254 if (scrollVertical) {
1255 rubberBandRect.translate(0, -m_view->scrollOffset());
1256 } else {
1257 rubberBandRect.translate(-m_view->scrollOffset(), 0);
1258 }
1259
1260 if (!m_oldSelection.isEmpty()) {
1261 // Clear the old selection that was available before the rubberband has
1262 // been activated in case if no Shift- or Control-key are pressed
1263 const bool shiftOrControlPressed = QApplication::keyboardModifiers() & Qt::ShiftModifier ||
1264 QApplication::keyboardModifiers() & Qt::ControlModifier;
1265 if (!shiftOrControlPressed && !m_selectionMode) {
1266 m_oldSelection.clear();
1267 }
1268 }
1269
1270 KItemSet selectedItems;
1271
1272 // Select all visible items that intersect with the rubberband
1273 const auto widgets = m_view->visibleItemListWidgets();
1274 for (const KItemListWidget* widget : widgets) {
1275 const int index = widget->index();
1276
1277 const QRectF widgetRect = m_view->itemRect(index);
1278 if (widgetRect.intersects(rubberBandRect)) {
1279 const QRectF iconRect = widget->iconRect().translated(widgetRect.topLeft());
1280 const QRectF textRect = widget->textRect().translated(widgetRect.topLeft());
1281 if (iconRect.intersects(rubberBandRect) || textRect.intersects(rubberBandRect)) {
1282 selectedItems.insert(index);
1283 }
1284 }
1285 }
1286
1287 // Select all invisible items that intersect with the rubberband. Instead of
1288 // iterating all items only the area which might be touched by the rubberband
1289 // will be checked.
1290 const bool increaseIndex = scrollVertical ?
1291 startPos.y() > endPos.y(): startPos.x() > endPos.x();
1292
1293 int index = increaseIndex ? m_view->lastVisibleIndex() + 1 : m_view->firstVisibleIndex() - 1;
1294 bool selectionFinished = false;
1295 do {
1296 const QRectF widgetRect = m_view->itemRect(index);
1297 if (widgetRect.intersects(rubberBandRect)) {
1298 selectedItems.insert(index);
1299 }
1300
1301 if (increaseIndex) {
1302 ++index;
1303 selectionFinished = (index >= m_model->count()) ||
1304 ( scrollVertical && widgetRect.top() > rubberBandRect.bottom()) ||
1305 (!scrollVertical && widgetRect.left() > rubberBandRect.right());
1306 } else {
1307 --index;
1308 selectionFinished = (index < 0) ||
1309 ( scrollVertical && widgetRect.bottom() < rubberBandRect.top()) ||
1310 (!scrollVertical && widgetRect.right() < rubberBandRect.left());
1311 }
1312 } while (!selectionFinished);
1313
1314 if ((QApplication::keyboardModifiers() & Qt::ControlModifier) || m_selectionMode) {
1315 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1316 // Therefore, the new selection contains:
1317 // 1. All previously selected items which are not inside the rubberband, and
1318 // 2. all items inside the rubberband which have not been selected previously.
1319 m_selectionManager->setSelectedItems(m_oldSelection ^ selectedItems);
1320 }
1321 else {
1322 m_selectionManager->setSelectedItems(selectedItems + m_oldSelection);
1323 }
1324 }
1325
1326 void KItemListController::startDragging()
1327 {
1328 if (!m_view || !m_model) {
1329 return;
1330 }
1331
1332 const KItemSet selectedItems = m_selectionManager->selectedItems();
1333 if (selectedItems.isEmpty()) {
1334 return;
1335 }
1336
1337 QMimeData *data = m_model->createMimeData(selectedItems);
1338 if (!data) {
1339 return;
1340 }
1341 KUrlMimeData::exportUrlsToPortal(data);
1342
1343 // The created drag object will be owned and deleted
1344 // by QApplication::activeWindow().
1345 QDrag* drag = new QDrag(QApplication::activeWindow());
1346 drag->setMimeData(data);
1347
1348 const QPixmap pixmap = m_view->createDragPixmap(selectedItems);
1349 drag->setPixmap(pixmap);
1350
1351 const QPoint hotSpot((pixmap.width() / pixmap.devicePixelRatio()) / 2, 0);
1352 drag->setHotSpot(hotSpot);
1353
1354 drag->exec(Qt::MoveAction | Qt::CopyAction | Qt::LinkAction, Qt::CopyAction);
1355
1356 QAccessibleEvent accessibilityEvent(view(), QAccessible::DragDropStart);
1357 QAccessible::updateAccessibility(&accessibilityEvent);
1358 }
1359
1360 KItemListWidget* KItemListController::hoveredWidget() const
1361 {
1362 Q_ASSERT(m_view);
1363
1364 const auto widgets = m_view->visibleItemListWidgets();
1365 for (KItemListWidget* widget : widgets) {
1366 if (widget->isHovered()) {
1367 return widget;
1368 }
1369 }
1370
1371 return nullptr;
1372 }
1373
1374 KItemListWidget* KItemListController::widgetForPos(const QPointF& pos) const
1375 {
1376 Q_ASSERT(m_view);
1377
1378 const auto widgets = m_view->visibleItemListWidgets();
1379 for (KItemListWidget* widget : widgets) {
1380 const QPointF mappedPos = widget->mapFromItem(m_view, pos);
1381 if (widget->contains(mappedPos) || widget->selectionRect().contains(mappedPos)) {
1382 return widget;
1383 }
1384 }
1385
1386 return nullptr;
1387 }
1388
1389 KItemListWidget* KItemListController::widgetForDropPos(const QPointF& pos) const
1390 {
1391 Q_ASSERT(m_view);
1392
1393 const auto widgets = m_view->visibleItemListWidgets();
1394 for (KItemListWidget* widget : widgets) {
1395 const QPointF mappedPos = widget->mapFromItem(m_view, pos);
1396 if (widget->contains(mappedPos)) {
1397 return widget;
1398 }
1399 }
1400
1401 return nullptr;
1402 }
1403
1404 void KItemListController::updateKeyboardAnchor()
1405 {
1406 const bool validAnchor = m_keyboardAnchorIndex >= 0 &&
1407 m_keyboardAnchorIndex < m_model->count() &&
1408 keyboardAnchorPos(m_keyboardAnchorIndex) == m_keyboardAnchorPos;
1409 if (!validAnchor) {
1410 const int index = m_selectionManager->currentItem();
1411 m_keyboardAnchorIndex = index;
1412 m_keyboardAnchorPos = keyboardAnchorPos(index);
1413 }
1414 }
1415
1416 int KItemListController::nextRowIndex(int index) const
1417 {
1418 if (m_keyboardAnchorIndex < 0) {
1419 return index;
1420 }
1421
1422 const int maxIndex = m_model->count() - 1;
1423 if (index == maxIndex) {
1424 return index;
1425 }
1426
1427 // Calculate the index of the last column inside the row of the current index
1428 int lastColumnIndex = index;
1429 while (keyboardAnchorPos(lastColumnIndex + 1) > keyboardAnchorPos(lastColumnIndex)) {
1430 ++lastColumnIndex;
1431 if (lastColumnIndex >= maxIndex) {
1432 return index;
1433 }
1434 }
1435
1436 // Based on the last column index go to the next row and calculate the nearest index
1437 // that is below the current index
1438 int nextRowIndex = lastColumnIndex + 1;
1439 int searchIndex = nextRowIndex;
1440 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(nextRowIndex));
1441 while (searchIndex < maxIndex && keyboardAnchorPos(searchIndex + 1) > keyboardAnchorPos(searchIndex)) {
1442 ++searchIndex;
1443 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1444 if (searchDiff < minDiff) {
1445 minDiff = searchDiff;
1446 nextRowIndex = searchIndex;
1447 }
1448 }
1449
1450 return nextRowIndex;
1451 }
1452
1453 int KItemListController::previousRowIndex(int index) const
1454 {
1455 if (m_keyboardAnchorIndex < 0 || index == 0) {
1456 return index;
1457 }
1458
1459 // Calculate the index of the first column inside the row of the current index
1460 int firstColumnIndex = index;
1461 while (keyboardAnchorPos(firstColumnIndex - 1) < keyboardAnchorPos(firstColumnIndex)) {
1462 --firstColumnIndex;
1463 if (firstColumnIndex <= 0) {
1464 return index;
1465 }
1466 }
1467
1468 // Based on the first column index go to the previous row and calculate the nearest index
1469 // that is above the current index
1470 int previousRowIndex = firstColumnIndex - 1;
1471 int searchIndex = previousRowIndex;
1472 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(previousRowIndex));
1473 while (searchIndex > 0 && keyboardAnchorPos(searchIndex - 1) < keyboardAnchorPos(searchIndex)) {
1474 --searchIndex;
1475 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1476 if (searchDiff < minDiff) {
1477 minDiff = searchDiff;
1478 previousRowIndex = searchIndex;
1479 }
1480 }
1481
1482 return previousRowIndex;
1483 }
1484
1485 qreal KItemListController::keyboardAnchorPos(int index) const
1486 {
1487 const QRectF itemRect = m_view->itemRect(index);
1488 if (!itemRect.isEmpty()) {
1489 return (m_view->scrollOrientation() == Qt::Vertical) ? itemRect.x() : itemRect.y();
1490 }
1491
1492 return 0;
1493 }
1494
1495 void KItemListController::updateExtendedSelectionRegion()
1496 {
1497 if (m_view) {
1498 const bool extend = (m_selectionBehavior != MultiSelection);
1499 KItemListStyleOption option = m_view->styleOption();
1500 if (option.extendedSelectionRegion != extend) {
1501 option.extendedSelectionRegion = extend;
1502 m_view->setStyleOption(option);
1503 }
1504 }
1505 }
1506
1507 bool KItemListController::onPress(const QPoint& screenPos, const QPointF& pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons)
1508 {
1509 Q_EMIT mouseButtonPressed(m_pressedIndex.value_or(-1), buttons);
1510
1511 if (buttons & (Qt::BackButton | Qt::ForwardButton)) {
1512 // Do not select items when clicking the back/forward buttons, see
1513 // https://bugs.kde.org/show_bug.cgi?id=327412.
1514 return true;
1515 }
1516
1517 if (m_view->isAboveExpansionToggle(m_pressedIndex.value_or(-1), m_pressedMousePos)) {
1518 m_selectionManager->endAnchoredSelection();
1519 m_selectionManager->setCurrentItem(m_pressedIndex.value());
1520 m_selectionManager->beginAnchoredSelection(m_pressedIndex.value());
1521 return true;
1522 }
1523
1524 m_selectionTogglePressed = m_view->isAboveSelectionToggle(m_pressedIndex.value_or(-1), m_pressedMousePos);
1525 if (m_selectionTogglePressed) {
1526 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Toggle);
1527 // The previous anchored selection has been finished already in
1528 // KItemListSelectionManager::setSelected(). We can safely change
1529 // the current item and start a new anchored selection now.
1530 m_selectionManager->setCurrentItem(m_pressedIndex.value());
1531 m_selectionManager->beginAnchoredSelection(m_pressedIndex.value());
1532 return true;
1533 }
1534
1535 const bool shiftPressed = modifiers & Qt::ShiftModifier;
1536 const bool controlPressed = (modifiers & Qt::ControlModifier) || m_selectionMode; // Keeping selectionMode similar to pressing control will hopefully
1537 // simplify the overall logic and possibilities both for users and devs.
1538 const bool leftClick = buttons & Qt::LeftButton;
1539 const bool rightClick = buttons & Qt::RightButton;
1540
1541 // The previous selection is cleared if either
1542 // 1. The selection mode is SingleSelection, or
1543 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1544 // a) Shift or Control are pressed.
1545 // b) The clicked item is selected already. In that case, the user might want to:
1546 // - start dragging multiple items, or
1547 // - open the context menu and perform an action for all selected items.
1548 const bool shiftOrControlPressed = shiftPressed || controlPressed;
1549 const bool pressedItemAlreadySelected = m_pressedIndex.has_value() && m_selectionManager->isSelected(m_pressedIndex.value());
1550 const bool clearSelection = m_selectionBehavior == SingleSelection ||
1551 (!shiftOrControlPressed && !pressedItemAlreadySelected);
1552
1553
1554 // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller.
1555 if (clearSelection) {
1556 const int selectedItemsCount = m_selectionManager->selectedItems().count();
1557 m_selectionManager->clearSelection();
1558 // clear and bail when we got an existing multi-selection
1559 if (selectedItemsCount > 1 && m_pressedIndex.has_value()) {
1560 const auto row = m_view->m_visibleItems.value(m_pressedIndex.value());
1561 const auto mappedPos = row->mapFromItem(m_view, pos);
1562 if (pressedItemAlreadySelected || row->iconRect().contains(mappedPos) || row->textRect().contains(mappedPos)) {
1563 // we are indeed inside the text/icon rect, keep m_pressedIndex what it is
1564 // and short-circuit for single-click activation (it will then propagate to onRelease and activate the item)
1565 // or we just keep going for double-click activation
1566 if (m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) || m_singleClickActivationEnforced) {
1567 if (!pressedItemAlreadySelected) {
1568 // An unselected item was clicked directly while deselecting multiple other items so we select it.
1569 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Toggle);
1570 m_selectionManager->setCurrentItem(m_pressedIndex.value());
1571 m_selectionManager->beginAnchoredSelection(m_pressedIndex.value());
1572 }
1573 return true; // event handled, don't create rubber band
1574 }
1575 } else {
1576 // we're not inside the text/icon rect, as we've already cleared the selection
1577 // we can just stop here and make sure handlers down the line (i.e. onRelease) don't activate
1578 m_pressedIndex.reset();
1579 // we don't stop event propagation and proceed to create a rubber band and let onRelease
1580 // decide (based on m_pressedIndex) whether we're in a drag (drag => new rubber band, click => don't select the item)
1581 return false;
1582 }
1583 }
1584 } else if (pressedItemAlreadySelected && !shiftOrControlPressed && leftClick) {
1585 // The user might want to start dragging multiple items, but if he clicks the item
1586 // in order to trigger it instead, the other selected items must be deselected.
1587 // However, we do not know yet what the user is going to do.
1588 // -> remember that the user pressed an item which had been selected already and
1589 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1590 m_clearSelectionIfItemsAreNotDragged = true;
1591
1592 if (m_selectionManager->selectedItems().count() == 1 && m_view->isAboveText(m_pressedIndex.value_or(-1), m_pressedMousePos)) {
1593 Q_EMIT selectedItemTextPressed(m_pressedIndex.value_or(-1));
1594 }
1595 }
1596
1597 if (!shiftPressed) {
1598 // Finish the anchored selection before the current index is changed
1599 m_selectionManager->endAnchoredSelection();
1600 }
1601
1602 if (rightClick) {
1603
1604 // Do header hit check and short circuit before commencing any state changing effects
1605 if (m_view->headerBoundaries().contains(pos)) {
1606 Q_EMIT headerContextMenuRequested(screenPos);
1607 return true;
1608 }
1609
1610 // Stop rubber band from persisting after right-clicks
1611 KItemListRubberBand* rubberBand = m_view->rubberBand();
1612 if (rubberBand->isActive()) {
1613 disconnect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged);
1614 rubberBand->setActive(false);
1615 m_view->setAutoScroll(false);
1616 }
1617 }
1618
1619 if (m_pressedIndex.has_value()) {
1620 // The hover highlight area of an item is being pressed.
1621 m_selectionManager->setCurrentItem(m_pressedIndex.value());
1622 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
1623 const bool hitTargetIsRowEmptyRegion = !row->contains(row->mapFromItem(m_view, pos));
1624 // again, when this method returns false, a rubberBand selection is created as the event is not consumed;
1625 // createRubberBand here tells us whether to return true or false.
1626 bool createRubberBand = (hitTargetIsRowEmptyRegion && m_selectionManager->selectedItems().isEmpty());
1627
1628 if (rightClick && hitTargetIsRowEmptyRegion) {
1629 // We have a right click outside the icon and text rect but within the hover highlight area
1630 // but it is unclear if this means that a selection rectangle for an item was clicked or the background of the view.
1631 if (m_selectionManager->selectedItems().contains(m_pressedIndex.value())) {
1632 // The selection rectangle for an item was clicked
1633 Q_EMIT itemContextMenuRequested(m_pressedIndex.value(), screenPos);
1634 } else {
1635 row->setHovered(false); // Removes the hover highlight so the context menu doesn't look like it applies to the row.
1636 Q_EMIT viewContextMenuRequested(screenPos);
1637 }
1638 return true;
1639 }
1640
1641 switch (m_selectionBehavior) {
1642 case NoSelection:
1643 break;
1644
1645 case SingleSelection:
1646 m_selectionManager->setSelected(m_pressedIndex.value());
1647 break;
1648
1649 case MultiSelection:
1650 if (controlPressed && !shiftPressed && leftClick) {
1651 // A left mouse button press is happening on an item while control is pressed. This either means a user wants to:
1652 // - toggle the selection of item(s) or
1653 // - they want to begin a drag on the item(s) to copy them.
1654 // We rule out the latter, if the item is not clicked directly and was unselected previously.
1655 const auto row = m_view->m_visibleItems.value(m_pressedIndex.value());
1656 const auto mappedPos = row->mapFromItem(m_view, pos);
1657 if (!row->iconRect().contains(mappedPos) && !row->textRect().contains(mappedPos) && !pressedItemAlreadySelected) {
1658 createRubberBand = true;
1659 } else {
1660 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Toggle);
1661 m_selectionManager->beginAnchoredSelection(m_pressedIndex.value());
1662 createRubberBand = false; // multi selection, don't propagate any further
1663 // This will be the start of an item drag-to-copy operation if the user now moves the mouse before releasing the mouse button.
1664 }
1665 } else if (!shiftPressed || !m_selectionManager->isAnchoredSelectionActive()) {
1666 // Select the pressed item and start a new anchored selection
1667 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Select);
1668 m_selectionManager->beginAnchoredSelection(m_pressedIndex.value());
1669 }
1670 break;
1671
1672 default:
1673 Q_ASSERT(false);
1674 break;
1675 }
1676
1677 if (rightClick) {
1678 Q_EMIT itemContextMenuRequested(m_pressedIndex.value(), screenPos);
1679 }
1680 return !createRubberBand;
1681 }
1682
1683 if (rightClick) {
1684 // header right click handling would have been done before this so just normal context
1685 // menu here is fine
1686 Q_EMIT viewContextMenuRequested(screenPos);
1687 return true;
1688 }
1689
1690 return false;
1691 }
1692
1693 bool KItemListController::onRelease(const QPointF& pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons, bool touch)
1694 {
1695 const bool isAboveSelectionToggle = m_view->isAboveSelectionToggle(m_pressedIndex.value_or(-1), m_pressedMousePos);
1696 if (isAboveSelectionToggle) {
1697 m_selectionTogglePressed = false;
1698 return true;
1699 }
1700
1701 if (!isAboveSelectionToggle && m_selectionTogglePressed) {
1702 m_selectionManager->setSelected(m_pressedIndex.value_or(-1), 1, KItemListSelectionManager::Toggle);
1703 m_selectionTogglePressed = false;
1704 return true;
1705 }
1706
1707 const bool controlPressed = modifiers & Qt::ControlModifier;
1708 const bool shiftOrControlPressed = modifiers & Qt::ShiftModifier ||
1709 controlPressed;
1710
1711 const std::optional<int> index = m_view->itemAt(pos);
1712
1713 KItemListRubberBand* rubberBand = m_view->rubberBand();
1714 bool rubberBandRelease = false;
1715 if (rubberBand->isActive()) {
1716 disconnect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged);
1717 rubberBand->setActive(false);
1718 m_oldSelection.clear();
1719 m_view->setAutoScroll(false);
1720 rubberBandRelease = true;
1721 // We check for actual rubber band drag here: if delta between start and end is less than drag threshold,
1722 // then we have a single click on one of the rows
1723 if ((rubberBand->endPosition() - rubberBand->startPosition()).manhattanLength() < QApplication::startDragDistance()) {
1724 rubberBandRelease = false; // since we're only selecting, unmark rubber band release flag
1725 // m_pressedIndex will have no value if we came from a multi-selection clearing onPress
1726 // in that case, we don't select anything
1727 if (index.has_value() && m_pressedIndex.has_value()) {
1728 if (controlPressed && m_selectionBehavior == MultiSelection) {
1729 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Toggle);
1730 } else {
1731 m_selectionManager->setSelected(index.value());
1732 }
1733 if (!m_selectionManager->isAnchoredSelectionActive()) {
1734 m_selectionManager->beginAnchoredSelection(index.value());
1735 }
1736 }
1737 }
1738 }
1739
1740 if (index.has_value() && index == m_pressedIndex) {
1741 // The release event is done above the same item as the press event
1742
1743 if (m_clearSelectionIfItemsAreNotDragged) {
1744 // A selected item has been clicked, but no drag operation has been started
1745 // -> clear the rest of the selection.
1746 m_selectionManager->clearSelection();
1747 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Select);
1748 m_selectionManager->beginAnchoredSelection(m_pressedIndex.value());
1749 }
1750
1751 if (buttons & Qt::LeftButton) {
1752 bool emitItemActivated = true;
1753 if (m_view->isAboveExpansionToggle(index.value(), pos)) {
1754 const bool expanded = m_model->isExpanded(index.value());
1755 m_model->setExpanded(index.value(), !expanded);
1756
1757 Q_EMIT itemExpansionToggleClicked(index.value());
1758 emitItemActivated = false;
1759 } else if (shiftOrControlPressed && m_selectionBehavior != SingleSelection) {
1760 // The mouse click should only update the selection, not trigger the item, except when
1761 // we are in single selection mode
1762 emitItemActivated = false;
1763 } else {
1764 const bool singleClickActivation = m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) || m_singleClickActivationEnforced;
1765 if (!singleClickActivation) {
1766 emitItemActivated = touch && !m_selectionMode;
1767 } else {
1768 // activate on single click only if we didn't come from a rubber band release
1769 emitItemActivated = !rubberBandRelease;
1770 }
1771 }
1772 if (emitItemActivated) {
1773 Q_EMIT itemActivated(index.value());
1774 }
1775 } else if (buttons & Qt::MiddleButton) {
1776 Q_EMIT itemMiddleClicked(index.value());
1777 }
1778 }
1779
1780 m_pressedMousePos = QPointF();
1781 m_pressedIndex = std::nullopt;
1782 m_clearSelectionIfItemsAreNotDragged = false;
1783 return false;
1784 }
1785
1786 void KItemListController::startRubberBand()
1787 {
1788 if (m_selectionBehavior == MultiSelection) {
1789 QPointF startPos = m_pressedMousePos;
1790 if (m_view->scrollOrientation() == Qt::Vertical) {
1791 startPos.ry() += m_view->scrollOffset();
1792 if (m_view->itemSize().width() < 0) {
1793 // Use a special rubberband for views that have only one column and
1794 // expand the rubberband to use the whole width of the view.
1795 startPos.setX(0);
1796 }
1797 } else {
1798 startPos.rx() += m_view->scrollOffset();
1799 }
1800
1801 m_oldSelection = m_selectionManager->selectedItems();
1802 KItemListRubberBand* rubberBand = m_view->rubberBand();
1803 rubberBand->setStartPosition(startPos);
1804 rubberBand->setEndPosition(startPos);
1805 rubberBand->setActive(true);
1806 connect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged);
1807 m_view->setAutoScroll(true);
1808 }
1809 }
1810
1811 void KItemListController::slotStateChanged(QScroller::State newState)
1812 {
1813 if (newState == QScroller::Scrolling) {
1814 m_scrollerIsScrolling = true;
1815 } else if (newState == QScroller::Inactive) {
1816 m_scrollerIsScrolling = false;
1817 }
1818 }