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