]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistcontroller.cpp
Merge branch 'release/22.04'
[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 auto oldHoveredWidget = hoveredWidget();
876 if (oldHoveredWidget && oldHoveredWidget != newHoveredWidget) {
877 oldHoveredWidget->setHovered(false);
878 Q_EMIT itemUnhovered(oldHoveredWidget->index());
879 }
880 // 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)
881 unhoverOldExpansionWidget();
882
883 const bool isOverIconAndText = newHoveredWidget->iconRect().contains(mappedPos) || newHoveredWidget->textRect().contains(mappedPos);
884 const bool hasMultipleSelection = m_selectionManager->selectedItems().count() > 1;
885
886 if (hasMultipleSelection && !isOverIconAndText) {
887 // In case we have multiple selections, clicking on any row will deselect the selection.
888 // So, as a visual cue for signalling that clicking anywhere won't select, but clear current highlights,
889 // we disable hover of the *row*(i.e. blank space to the right of the icon+text)
890
891 // (no-op in this branch for masked hover)
892 } else {
893 newHoveredWidget->setHoverPosition(mappedPos);
894 if (oldHoveredWidget != newHoveredWidget) {
895 newHoveredWidget->setHovered(true);
896 Q_EMIT itemHovered(newHoveredWidget->index());
897 }
898 }
899 }
900 } else {
901 // unhover any currently hovered expansion and text+icon widgets
902 unhoverOldHoveredWidget();
903 unhoverOldExpansionWidget();
904 }
905 return false;
906 }
907
908 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
909 {
910 Q_UNUSED(event)
911 Q_UNUSED(transform)
912
913 m_mousePress = false;
914 m_isTouchEvent = false;
915
916 if (!m_model || !m_view) {
917 return false;
918 }
919
920 const auto widgets = m_view->visibleItemListWidgets();
921 for (KItemListWidget* widget : widgets) {
922 if (widget->isHovered()) {
923 widget->setHovered(false);
924 Q_EMIT itemUnhovered(widget->index());
925 }
926 }
927 return false;
928 }
929
930 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent* event, const QTransform& transform)
931 {
932 Q_UNUSED(event)
933 Q_UNUSED(transform)
934 return false;
935 }
936
937 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent* event, const QTransform& transform)
938 {
939 Q_UNUSED(event)
940 Q_UNUSED(transform)
941 return false;
942 }
943
944 bool KItemListController::gestureEvent(QGestureEvent* event, const QTransform& transform)
945 {
946 if (!m_view) {
947 return false;
948 }
949
950 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
951 //we use this to get the right QWidget
952 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
953 if (!m_mousePress) {
954 if (QGesture* tap = event->gesture(Qt::TapGesture)) {
955 QTapGesture* tapGesture = static_cast<QTapGesture*>(tap);
956 if (tapGesture->state() == Qt::GestureStarted) {
957 tapTriggered(tapGesture, transform);
958 }
959 }
960 return false;
961 }
962
963 bool accepted = false;
964
965 if (QGesture* tap = event->gesture(Qt::TapGesture)) {
966 tapTriggered(static_cast<QTapGesture*>(tap), transform);
967 accepted = true;
968 }
969 if (event->gesture(Qt::TapAndHoldGesture)) {
970 tapAndHoldTriggered(event, transform);
971 accepted = true;
972 }
973 if (event->gesture(Qt::PinchGesture)) {
974 pinchTriggered(event, transform);
975 accepted = true;
976 }
977 if (event->gesture(m_swipeGesture)) {
978 swipeTriggered(event, transform);
979 accepted = true;
980 }
981 if (event->gesture(m_twoFingerTapGesture)) {
982 twoFingerTapTriggered(event, transform);
983 accepted = true;
984 }
985 return accepted;
986 }
987
988 bool KItemListController::touchBeginEvent(QTouchEvent* event, const QTransform& transform)
989 {
990 Q_UNUSED(event)
991 Q_UNUSED(transform)
992
993 m_isTouchEvent = true;
994 return false;
995 }
996
997 void KItemListController::tapTriggered(QTapGesture* tap, const QTransform& transform)
998 {
999 static bool scrollerWasActive = false;
1000
1001 if (tap->state() == Qt::GestureStarted) {
1002 m_dragActionOrRightClick = false;
1003 m_isSwipeGesture = false;
1004 m_pinchGestureInProgress = false;
1005 scrollerWasActive = m_scrollerIsScrolling;
1006 }
1007
1008 if (tap->state() == Qt::GestureFinished) {
1009 m_mousePress = false;
1010
1011 //if at the moment of the gesture start the QScroller was active, the user made the tap
1012 //to stop the QScroller and not to tap on an item
1013 if (scrollerWasActive) {
1014 return;
1015 }
1016
1017 if (m_view->m_tapAndHoldIndicator->isActive()) {
1018 m_view->m_tapAndHoldIndicator->setActive(false);
1019 }
1020
1021 m_pressedMousePos = transform.map(tap->position());
1022 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
1023
1024 if (m_dragActionOrRightClick) {
1025 onPress(tap->hotSpot().toPoint(), tap->position().toPoint(), Qt::NoModifier, Qt::RightButton);
1026 onRelease(transform.map(tap->position()), Qt::NoModifier, Qt::RightButton, false);
1027 m_dragActionOrRightClick = false;
1028 }
1029 else {
1030 onPress(tap->hotSpot().toPoint(), tap->position().toPoint(), Qt::NoModifier, Qt::LeftButton);
1031 onRelease(transform.map(tap->position()), Qt::NoModifier, Qt::LeftButton, true);
1032 }
1033 m_isTouchEvent = false;
1034 }
1035 }
1036
1037 void KItemListController::tapAndHoldTriggered(QGestureEvent* event, const QTransform& transform)
1038 {
1039
1040 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
1041 if (!m_isTouchEvent) {
1042 return;
1043 }
1044
1045 const QTapAndHoldGesture* tap = static_cast<QTapAndHoldGesture*>(event->gesture(Qt::TapAndHoldGesture));
1046 if (tap->state() == Qt::GestureFinished) {
1047 //if a pinch gesture is in progress we don't want a TabAndHold gesture
1048 if (m_pinchGestureInProgress) {
1049 return;
1050 }
1051 m_pressedMousePos = transform.map(event->mapToGraphicsScene(tap->position()));
1052 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
1053
1054 if (m_pressedIndex.has_value() && !m_selectionManager->isSelected(m_pressedIndex.value())) {
1055 m_selectionManager->clearSelection();
1056 m_selectionManager->setSelected(m_pressedIndex.value());
1057 } else if (!m_pressedIndex.has_value()) {
1058 m_selectionManager->clearSelection();
1059 startRubberBand();
1060 }
1061
1062 Q_EMIT scrollerStop();
1063
1064 m_view->m_tapAndHoldIndicator->setStartPosition(m_pressedMousePos);
1065 m_view->m_tapAndHoldIndicator->setActive(true);
1066
1067 m_dragActionOrRightClick = true;
1068 }
1069 }
1070
1071 void KItemListController::pinchTriggered(QGestureEvent* event, const QTransform& transform)
1072 {
1073 Q_UNUSED(transform)
1074
1075 const QPinchGesture* pinch = static_cast<QPinchGesture*>(event->gesture(Qt::PinchGesture));
1076 const qreal sensitivityModifier = 0.2;
1077 static qreal counter = 0;
1078
1079 if (pinch->state() == Qt::GestureStarted) {
1080 m_pinchGestureInProgress = true;
1081 counter = 0;
1082 }
1083 if (pinch->state() == Qt::GestureUpdated) {
1084 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1085 if (m_isSwipeGesture) {
1086 return;
1087 }
1088 counter = counter + (pinch->scaleFactor() - 1);
1089 if (counter >= sensitivityModifier) {
1090 Q_EMIT increaseZoom();
1091 counter = 0;
1092 } else if (counter <= -sensitivityModifier) {
1093 Q_EMIT decreaseZoom();
1094 counter = 0;
1095 }
1096 }
1097 }
1098
1099 void KItemListController::swipeTriggered(QGestureEvent* event, const QTransform& transform)
1100 {
1101 Q_UNUSED(transform)
1102
1103 const KTwoFingerSwipe* swipe = static_cast<KTwoFingerSwipe*>(event->gesture(m_swipeGesture));
1104
1105 if (!swipe) {
1106 return;
1107 }
1108 if (swipe->state() == Qt::GestureStarted) {
1109 m_isSwipeGesture = true;
1110 }
1111
1112 if (swipe->state() == Qt::GestureCanceled) {
1113 m_isSwipeGesture = false;
1114 }
1115
1116 if (swipe->state() == Qt::GestureFinished) {
1117 Q_EMIT scrollerStop();
1118
1119 if (swipe->swipeAngle() <= 20 || swipe->swipeAngle() >= 340) {
1120 Q_EMIT mouseButtonPressed(m_pressedIndex.value_or(-1), Qt::BackButton);
1121 } else if (swipe->swipeAngle() <= 200 && swipe->swipeAngle() >= 160) {
1122 Q_EMIT mouseButtonPressed(m_pressedIndex.value_or(-1), Qt::ForwardButton);
1123 } else if (swipe->swipeAngle() <= 110 && swipe->swipeAngle() >= 60) {
1124 Q_EMIT swipeUp();
1125 }
1126 m_isSwipeGesture = true;
1127 }
1128 }
1129
1130 void KItemListController::twoFingerTapTriggered(QGestureEvent* event, const QTransform& transform)
1131 {
1132 const KTwoFingerTap* twoTap = static_cast<KTwoFingerTap*>(event->gesture(m_twoFingerTapGesture));
1133
1134 if (!twoTap) {
1135 return;
1136 }
1137
1138 if (twoTap->state() == Qt::GestureStarted) {
1139 m_pressedMousePos = transform.map(twoTap->pos());
1140 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
1141 if (m_pressedIndex.has_value()) {
1142 onPress(twoTap->screenPos().toPoint(), twoTap->pos().toPoint(), Qt::ControlModifier, Qt::LeftButton);
1143 onRelease(transform.map(twoTap->pos()), Qt::ControlModifier, Qt::LeftButton, false);
1144 }
1145
1146 }
1147 }
1148
1149 bool KItemListController::processEvent(QEvent* event, const QTransform& transform)
1150 {
1151 if (!event) {
1152 return false;
1153 }
1154
1155 switch (event->type()) {
1156 case QEvent::KeyPress:
1157 return keyPressEvent(static_cast<QKeyEvent*>(event));
1158 case QEvent::InputMethod:
1159 return inputMethodEvent(static_cast<QInputMethodEvent*>(event));
1160 case QEvent::GraphicsSceneMousePress:
1161 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1162 case QEvent::GraphicsSceneMouseMove:
1163 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1164 case QEvent::GraphicsSceneMouseRelease:
1165 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1166 case QEvent::GraphicsSceneMouseDoubleClick:
1167 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1168 case QEvent::GraphicsSceneWheel:
1169 return wheelEvent(static_cast<QGraphicsSceneWheelEvent*>(event), QTransform());
1170 case QEvent::GraphicsSceneDragEnter:
1171 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1172 case QEvent::GraphicsSceneDragLeave:
1173 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1174 case QEvent::GraphicsSceneDragMove:
1175 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1176 case QEvent::GraphicsSceneDrop:
1177 return dropEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1178 case QEvent::GraphicsSceneHoverEnter:
1179 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1180 case QEvent::GraphicsSceneHoverMove:
1181 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1182 case QEvent::GraphicsSceneHoverLeave:
1183 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1184 case QEvent::GraphicsSceneResize:
1185 return resizeEvent(static_cast<QGraphicsSceneResizeEvent*>(event), transform);
1186 case QEvent::Gesture:
1187 return gestureEvent(static_cast<QGestureEvent*>(event), transform);
1188 case QEvent::TouchBegin:
1189 return touchBeginEvent(static_cast<QTouchEvent*>(event), transform);
1190 default:
1191 break;
1192 }
1193
1194 return false;
1195 }
1196
1197 void KItemListController::slotViewScrollOffsetChanged(qreal current, qreal previous)
1198 {
1199 if (!m_view) {
1200 return;
1201 }
1202
1203 KItemListRubberBand* rubberBand = m_view->rubberBand();
1204 if (rubberBand->isActive()) {
1205 const qreal diff = current - previous;
1206 // TODO: Ideally just QCursor::pos() should be used as
1207 // new end-position but it seems there is no easy way
1208 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1209 // (... or I just missed an easy way to do the mapping)
1210 QPointF endPos = rubberBand->endPosition();
1211 if (m_view->scrollOrientation() == Qt::Vertical) {
1212 endPos.ry() += diff;
1213 } else {
1214 endPos.rx() += diff;
1215 }
1216
1217 rubberBand->setEndPosition(endPos);
1218 }
1219 }
1220
1221 void KItemListController::slotRubberBandChanged()
1222 {
1223 if (!m_view || !m_model || m_model->count() <= 0) {
1224 return;
1225 }
1226
1227 const KItemListRubberBand* rubberBand = m_view->rubberBand();
1228 const QPointF startPos = rubberBand->startPosition();
1229 const QPointF endPos = rubberBand->endPosition();
1230 QRectF rubberBandRect = QRectF(startPos, endPos).normalized();
1231
1232 const bool scrollVertical = (m_view->scrollOrientation() == Qt::Vertical);
1233 if (scrollVertical) {
1234 rubberBandRect.translate(0, -m_view->scrollOffset());
1235 } else {
1236 rubberBandRect.translate(-m_view->scrollOffset(), 0);
1237 }
1238
1239 if (!m_oldSelection.isEmpty()) {
1240 // Clear the old selection that was available before the rubberband has
1241 // been activated in case if no Shift- or Control-key are pressed
1242 const bool shiftOrControlPressed = QApplication::keyboardModifiers() & Qt::ShiftModifier ||
1243 QApplication::keyboardModifiers() & Qt::ControlModifier;
1244 if (!shiftOrControlPressed) {
1245 m_oldSelection.clear();
1246 }
1247 }
1248
1249 KItemSet selectedItems;
1250
1251 // Select all visible items that intersect with the rubberband
1252 const auto widgets = m_view->visibleItemListWidgets();
1253 for (const KItemListWidget* widget : widgets) {
1254 const int index = widget->index();
1255
1256 const QRectF widgetRect = m_view->itemRect(index);
1257 if (widgetRect.intersects(rubberBandRect)) {
1258 const QRectF iconRect = widget->iconRect().translated(widgetRect.topLeft());
1259 const QRectF textRect = widget->textRect().translated(widgetRect.topLeft());
1260 if (iconRect.intersects(rubberBandRect) || textRect.intersects(rubberBandRect)) {
1261 selectedItems.insert(index);
1262 }
1263 }
1264 }
1265
1266 // Select all invisible items that intersect with the rubberband. Instead of
1267 // iterating all items only the area which might be touched by the rubberband
1268 // will be checked.
1269 const bool increaseIndex = scrollVertical ?
1270 startPos.y() > endPos.y(): startPos.x() > endPos.x();
1271
1272 int index = increaseIndex ? m_view->lastVisibleIndex() + 1 : m_view->firstVisibleIndex() - 1;
1273 bool selectionFinished = false;
1274 do {
1275 const QRectF widgetRect = m_view->itemRect(index);
1276 if (widgetRect.intersects(rubberBandRect)) {
1277 selectedItems.insert(index);
1278 }
1279
1280 if (increaseIndex) {
1281 ++index;
1282 selectionFinished = (index >= m_model->count()) ||
1283 ( scrollVertical && widgetRect.top() > rubberBandRect.bottom()) ||
1284 (!scrollVertical && widgetRect.left() > rubberBandRect.right());
1285 } else {
1286 --index;
1287 selectionFinished = (index < 0) ||
1288 ( scrollVertical && widgetRect.bottom() < rubberBandRect.top()) ||
1289 (!scrollVertical && widgetRect.right() < rubberBandRect.left());
1290 }
1291 } while (!selectionFinished);
1292
1293 if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
1294 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1295 // Therefore, the new selection contains:
1296 // 1. All previously selected items which are not inside the rubberband, and
1297 // 2. all items inside the rubberband which have not been selected previously.
1298 m_selectionManager->setSelectedItems(m_oldSelection ^ selectedItems);
1299 }
1300 else {
1301 m_selectionManager->setSelectedItems(selectedItems + m_oldSelection);
1302 }
1303 }
1304
1305 void KItemListController::startDragging()
1306 {
1307 if (!m_view || !m_model) {
1308 return;
1309 }
1310
1311 const KItemSet selectedItems = m_selectionManager->selectedItems();
1312 if (selectedItems.isEmpty()) {
1313 return;
1314 }
1315
1316 QMimeData* data = m_model->createMimeData(selectedItems);
1317 if (!data) {
1318 return;
1319 }
1320
1321 // The created drag object will be owned and deleted
1322 // by QApplication::activeWindow().
1323 QDrag* drag = new QDrag(QApplication::activeWindow());
1324 drag->setMimeData(data);
1325
1326 const QPixmap pixmap = m_view->createDragPixmap(selectedItems);
1327 drag->setPixmap(pixmap);
1328
1329 const QPoint hotSpot((pixmap.width() / pixmap.devicePixelRatio()) / 2, 0);
1330 drag->setHotSpot(hotSpot);
1331
1332 drag->exec(Qt::MoveAction | Qt::CopyAction | Qt::LinkAction, Qt::CopyAction);
1333
1334 QAccessibleEvent accessibilityEvent(view(), QAccessible::DragDropStart);
1335 QAccessible::updateAccessibility(&accessibilityEvent);
1336 }
1337
1338 KItemListWidget* KItemListController::hoveredWidget() const
1339 {
1340 Q_ASSERT(m_view);
1341
1342 const auto widgets = m_view->visibleItemListWidgets();
1343 for (KItemListWidget* widget : widgets) {
1344 if (widget->isHovered()) {
1345 return widget;
1346 }
1347 }
1348
1349 return nullptr;
1350 }
1351
1352 KItemListWidget* KItemListController::widgetForPos(const QPointF& pos) const
1353 {
1354 Q_ASSERT(m_view);
1355
1356 const auto widgets = m_view->visibleItemListWidgets();
1357 for (KItemListWidget* widget : widgets) {
1358 const QPointF mappedPos = widget->mapFromItem(m_view, pos);
1359 if (widget->contains(mappedPos) || widget->selectionRect().contains(mappedPos)) {
1360 return widget;
1361 }
1362 }
1363
1364 return nullptr;
1365 }
1366
1367 void KItemListController::updateKeyboardAnchor()
1368 {
1369 const bool validAnchor = m_keyboardAnchorIndex >= 0 &&
1370 m_keyboardAnchorIndex < m_model->count() &&
1371 keyboardAnchorPos(m_keyboardAnchorIndex) == m_keyboardAnchorPos;
1372 if (!validAnchor) {
1373 const int index = m_selectionManager->currentItem();
1374 m_keyboardAnchorIndex = index;
1375 m_keyboardAnchorPos = keyboardAnchorPos(index);
1376 }
1377 }
1378
1379 int KItemListController::nextRowIndex(int index) const
1380 {
1381 if (m_keyboardAnchorIndex < 0) {
1382 return index;
1383 }
1384
1385 const int maxIndex = m_model->count() - 1;
1386 if (index == maxIndex) {
1387 return index;
1388 }
1389
1390 // Calculate the index of the last column inside the row of the current index
1391 int lastColumnIndex = index;
1392 while (keyboardAnchorPos(lastColumnIndex + 1) > keyboardAnchorPos(lastColumnIndex)) {
1393 ++lastColumnIndex;
1394 if (lastColumnIndex >= maxIndex) {
1395 return index;
1396 }
1397 }
1398
1399 // Based on the last column index go to the next row and calculate the nearest index
1400 // that is below the current index
1401 int nextRowIndex = lastColumnIndex + 1;
1402 int searchIndex = nextRowIndex;
1403 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(nextRowIndex));
1404 while (searchIndex < maxIndex && keyboardAnchorPos(searchIndex + 1) > keyboardAnchorPos(searchIndex)) {
1405 ++searchIndex;
1406 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1407 if (searchDiff < minDiff) {
1408 minDiff = searchDiff;
1409 nextRowIndex = searchIndex;
1410 }
1411 }
1412
1413 return nextRowIndex;
1414 }
1415
1416 int KItemListController::previousRowIndex(int index) const
1417 {
1418 if (m_keyboardAnchorIndex < 0 || index == 0) {
1419 return index;
1420 }
1421
1422 // Calculate the index of the first column inside the row of the current index
1423 int firstColumnIndex = index;
1424 while (keyboardAnchorPos(firstColumnIndex - 1) < keyboardAnchorPos(firstColumnIndex)) {
1425 --firstColumnIndex;
1426 if (firstColumnIndex <= 0) {
1427 return index;
1428 }
1429 }
1430
1431 // Based on the first column index go to the previous row and calculate the nearest index
1432 // that is above the current index
1433 int previousRowIndex = firstColumnIndex - 1;
1434 int searchIndex = previousRowIndex;
1435 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(previousRowIndex));
1436 while (searchIndex > 0 && keyboardAnchorPos(searchIndex - 1) < keyboardAnchorPos(searchIndex)) {
1437 --searchIndex;
1438 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1439 if (searchDiff < minDiff) {
1440 minDiff = searchDiff;
1441 previousRowIndex = searchIndex;
1442 }
1443 }
1444
1445 return previousRowIndex;
1446 }
1447
1448 qreal KItemListController::keyboardAnchorPos(int index) const
1449 {
1450 const QRectF itemRect = m_view->itemRect(index);
1451 if (!itemRect.isEmpty()) {
1452 return (m_view->scrollOrientation() == Qt::Vertical) ? itemRect.x() : itemRect.y();
1453 }
1454
1455 return 0;
1456 }
1457
1458 void KItemListController::updateExtendedSelectionRegion()
1459 {
1460 if (m_view) {
1461 const bool extend = (m_selectionBehavior != MultiSelection);
1462 KItemListStyleOption option = m_view->styleOption();
1463 if (option.extendedSelectionRegion != extend) {
1464 option.extendedSelectionRegion = extend;
1465 m_view->setStyleOption(option);
1466 }
1467 }
1468 }
1469
1470 bool KItemListController::onPress(const QPoint& screenPos, const QPointF& pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons)
1471 {
1472 Q_EMIT mouseButtonPressed(m_pressedIndex.value_or(-1), buttons);
1473
1474 if (buttons & (Qt::BackButton | Qt::ForwardButton)) {
1475 // Do not select items when clicking the back/forward buttons, see
1476 // https://bugs.kde.org/show_bug.cgi?id=327412.
1477 return true;
1478 }
1479
1480 if (m_view->isAboveExpansionToggle(m_pressedIndex.value_or(-1), m_pressedMousePos)) {
1481 m_selectionManager->endAnchoredSelection();
1482 m_selectionManager->setCurrentItem(m_pressedIndex.value());
1483 m_selectionManager->beginAnchoredSelection(m_pressedIndex.value());
1484 return true;
1485 }
1486
1487 m_selectionTogglePressed = m_view->isAboveSelectionToggle(m_pressedIndex.value_or(-1), m_pressedMousePos);
1488 if (m_selectionTogglePressed) {
1489 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Toggle);
1490 // The previous anchored selection has been finished already in
1491 // KItemListSelectionManager::setSelected(). We can safely change
1492 // the current item and start a new anchored selection now.
1493 m_selectionManager->setCurrentItem(m_pressedIndex.value());
1494 m_selectionManager->beginAnchoredSelection(m_pressedIndex.value());
1495 return true;
1496 }
1497
1498 const bool shiftPressed = modifiers & Qt::ShiftModifier;
1499 const bool controlPressed = modifiers & Qt::ControlModifier;
1500 const bool rightClick = buttons & Qt::RightButton;
1501
1502 // The previous selection is cleared if either
1503 // 1. The selection mode is SingleSelection, or
1504 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1505 // a) Shift or Control are pressed.
1506 // b) The clicked item is selected already. In that case, the user might want to:
1507 // - start dragging multiple items, or
1508 // - open the context menu and perform an action for all selected items.
1509 const bool shiftOrControlPressed = shiftPressed || controlPressed;
1510 const bool pressedItemAlreadySelected = m_pressedIndex.has_value() && m_selectionManager->isSelected(m_pressedIndex.value());
1511 const bool clearSelection = m_selectionBehavior == SingleSelection ||
1512 (!shiftOrControlPressed && !pressedItemAlreadySelected);
1513
1514
1515 // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller.
1516 if (clearSelection) {
1517 const int selectedItemsCount = m_selectionManager->selectedItems().count();
1518 m_selectionManager->clearSelection();
1519 // clear and bail when we got an existing multi-selection
1520 if (selectedItemsCount > 1 && m_pressedIndex.has_value()) {
1521 const auto row = m_view->m_visibleItems.value(m_pressedIndex.value());
1522 const auto mappedPos = row->mapFromItem(m_view, pos);
1523 if (pressedItemAlreadySelected || row->iconRect().contains(mappedPos) || row->textRect().contains(mappedPos)) {
1524 // we are indeed inside the text/icon rect, keep m_pressedIndex what it is
1525 // and short-circuit for single-click activation (it will then propagate to onRelease and activate the item)
1526 // or we just keep going for double-click activation
1527 if (m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) || m_singleClickActivationEnforced) {
1528 if (!pressedItemAlreadySelected) {
1529 // An unselected item was clicked directly while deselecting multiple other items so we select it.
1530 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Toggle);
1531 m_selectionManager->setCurrentItem(m_pressedIndex.value());
1532 m_selectionManager->beginAnchoredSelection(m_pressedIndex.value());
1533 }
1534 return true; // event handled, don't create rubber band
1535 }
1536 } else {
1537 // we're not inside the text/icon rect, as we've already cleared the selection
1538 // we can just stop here and make sure handlers down the line (i.e. onRelease) don't activate
1539 m_pressedIndex.reset();
1540 // we don't stop event propagation and proceed to create a rubber band and let onRelease
1541 // decide (based on m_pressedIndex) whether we're in a drag (drag => new rubber band, click => don't select the item)
1542 return false;
1543 }
1544 }
1545 } else if (pressedItemAlreadySelected && !shiftOrControlPressed && (buttons & Qt::LeftButton)) {
1546 // The user might want to start dragging multiple items, but if he clicks the item
1547 // in order to trigger it instead, the other selected items must be deselected.
1548 // However, we do not know yet what the user is going to do.
1549 // -> remember that the user pressed an item which had been selected already and
1550 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1551 m_clearSelectionIfItemsAreNotDragged = true;
1552
1553 if (m_selectionManager->selectedItems().count() == 1 && m_view->isAboveText(m_pressedIndex.value_or(-1), m_pressedMousePos)) {
1554 Q_EMIT selectedItemTextPressed(m_pressedIndex.value_or(-1));
1555 }
1556 }
1557
1558 if (!shiftPressed) {
1559 // Finish the anchored selection before the current index is changed
1560 m_selectionManager->endAnchoredSelection();
1561 }
1562
1563 if (rightClick) {
1564
1565 // Do header hit check and short circuit before commencing any state changing effects
1566 if (m_view->headerBoundaries().contains(pos)) {
1567 Q_EMIT headerContextMenuRequested(screenPos);
1568 return true;
1569 }
1570
1571 // Stop rubber band from persisting after right-clicks
1572 KItemListRubberBand* rubberBand = m_view->rubberBand();
1573 if (rubberBand->isActive()) {
1574 disconnect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged);
1575 rubberBand->setActive(false);
1576 m_view->setAutoScroll(false);
1577 }
1578 }
1579
1580 if (m_pressedIndex.has_value()) {
1581 m_selectionManager->setCurrentItem(m_pressedIndex.value());
1582 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
1583 const bool hitTargetIsRowEmptyRegion = !row->contains(row->mapFromItem(m_view, pos));
1584 // again, when this method returns false, a rubberBand selection is created as the event is not consumed;
1585 // createRubberBand here tells us whether to return true or false.
1586 bool createRubberBand = (hitTargetIsRowEmptyRegion && m_selectionManager->selectedItems().isEmpty());
1587
1588 if (rightClick && hitTargetIsRowEmptyRegion) {
1589 // we got a right click outside the text rect, default to action on the current url and not the pressed item
1590 Q_EMIT itemContextMenuRequested(m_pressedIndex.value(), screenPos);
1591 return true;
1592 }
1593
1594 switch (m_selectionBehavior) {
1595 case NoSelection:
1596 break;
1597
1598 case SingleSelection:
1599 m_selectionManager->setSelected(m_pressedIndex.value());
1600 break;
1601
1602 case MultiSelection:
1603 if (controlPressed && !shiftPressed) {
1604 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Toggle);
1605 m_selectionManager->beginAnchoredSelection(m_pressedIndex.value());
1606 createRubberBand = false; // multi selection, don't propagate any further
1607 } else if (!shiftPressed || !m_selectionManager->isAnchoredSelectionActive()) {
1608 // Select the pressed item and start a new anchored selection
1609 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Select);
1610 m_selectionManager->beginAnchoredSelection(m_pressedIndex.value());
1611 }
1612 break;
1613
1614 default:
1615 Q_ASSERT(false);
1616 break;
1617 }
1618
1619 if (rightClick) {
1620 Q_EMIT itemContextMenuRequested(m_pressedIndex.value(), screenPos);
1621 }
1622 return !createRubberBand;
1623 }
1624
1625 if (rightClick) {
1626 // header right click handling would have been done before this so just normal context
1627 // menu here is fine
1628 Q_EMIT viewContextMenuRequested(screenPos);
1629 return true;
1630 }
1631
1632 return false;
1633 }
1634
1635 bool KItemListController::onRelease(const QPointF& pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons, bool touch)
1636 {
1637 const bool isAboveSelectionToggle = m_view->isAboveSelectionToggle(m_pressedIndex.value_or(-1), m_pressedMousePos);
1638 if (isAboveSelectionToggle) {
1639 m_selectionTogglePressed = false;
1640 return true;
1641 }
1642
1643 if (!isAboveSelectionToggle && m_selectionTogglePressed) {
1644 m_selectionManager->setSelected(m_pressedIndex.value_or(-1), 1, KItemListSelectionManager::Toggle);
1645 m_selectionTogglePressed = false;
1646 return true;
1647 }
1648
1649 const bool controlPressed = modifiers & Qt::ControlModifier;
1650 const bool shiftOrControlPressed = modifiers & Qt::ShiftModifier ||
1651 controlPressed;
1652
1653 const std::optional<int> index = m_view->itemAt(pos);
1654
1655 KItemListRubberBand* rubberBand = m_view->rubberBand();
1656 bool rubberBandRelease = false;
1657 if (rubberBand->isActive()) {
1658 disconnect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged);
1659 rubberBand->setActive(false);
1660 m_oldSelection.clear();
1661 m_view->setAutoScroll(false);
1662 rubberBandRelease = true;
1663 // We check for actual rubber band drag here: if delta between start and end is less than drag threshold,
1664 // then we have a single click on one of the rows
1665 if ((rubberBand->endPosition() - rubberBand->startPosition()).manhattanLength() < QApplication::startDragDistance()) {
1666 rubberBandRelease = false; // since we're only selecting, unmark rubber band release flag
1667 // m_pressedIndex will have no value if we came from a multi-selection clearing onPress
1668 // in that case, we don't select anything
1669 if (index.has_value() && m_pressedIndex.has_value()) {
1670 if (controlPressed && m_selectionBehavior == MultiSelection) {
1671 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Toggle);
1672 } else {
1673 m_selectionManager->setSelected(index.value());
1674 }
1675 if (!m_selectionManager->isAnchoredSelectionActive()) {
1676 m_selectionManager->beginAnchoredSelection(index.value());
1677 }
1678 }
1679 }
1680 }
1681
1682 if (index.has_value() && index == m_pressedIndex) {
1683 // The release event is done above the same item as the press event
1684
1685 if (m_clearSelectionIfItemsAreNotDragged) {
1686 // A selected item has been clicked, but no drag operation has been started
1687 // -> clear the rest of the selection.
1688 m_selectionManager->clearSelection();
1689 m_selectionManager->setSelected(m_pressedIndex.value(), 1, KItemListSelectionManager::Select);
1690 m_selectionManager->beginAnchoredSelection(m_pressedIndex.value());
1691 }
1692
1693 if (buttons & Qt::LeftButton) {
1694 bool emitItemActivated = true;
1695 if (m_view->isAboveExpansionToggle(index.value(), pos)) {
1696 const bool expanded = m_model->isExpanded(index.value());
1697 m_model->setExpanded(index.value(), !expanded);
1698
1699 Q_EMIT itemExpansionToggleClicked(index.value());
1700 emitItemActivated = false;
1701 } else if (shiftOrControlPressed && m_selectionBehavior != SingleSelection) {
1702 // The mouse click should only update the selection, not trigger the item, except when
1703 // we are in single selection mode
1704 emitItemActivated = false;
1705 } else {
1706 const bool singleClickActivation = m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) || m_singleClickActivationEnforced;
1707 if (!singleClickActivation) {
1708 emitItemActivated = touch;
1709 } else {
1710 // activate on single click only if we didn't come from a rubber band release
1711 emitItemActivated = !rubberBandRelease;
1712 }
1713 }
1714 if (emitItemActivated) {
1715 Q_EMIT itemActivated(index.value());
1716 }
1717 } else if (buttons & Qt::MiddleButton) {
1718 Q_EMIT itemMiddleClicked(index.value());
1719 }
1720 }
1721
1722 m_pressedMousePos = QPointF();
1723 m_pressedIndex = std::nullopt;
1724 m_clearSelectionIfItemsAreNotDragged = false;
1725 return false;
1726 }
1727
1728 void KItemListController::startRubberBand()
1729 {
1730 if (m_selectionBehavior == MultiSelection) {
1731 QPointF startPos = m_pressedMousePos;
1732 if (m_view->scrollOrientation() == Qt::Vertical) {
1733 startPos.ry() += m_view->scrollOffset();
1734 if (m_view->itemSize().width() < 0) {
1735 // Use a special rubberband for views that have only one column and
1736 // expand the rubberband to use the whole width of the view.
1737 startPos.setX(0);
1738 }
1739 } else {
1740 startPos.rx() += m_view->scrollOffset();
1741 }
1742
1743 m_oldSelection = m_selectionManager->selectedItems();
1744 KItemListRubberBand* rubberBand = m_view->rubberBand();
1745 rubberBand->setStartPosition(startPos);
1746 rubberBand->setEndPosition(startPos);
1747 rubberBand->setActive(true);
1748 connect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged);
1749 m_view->setAutoScroll(true);
1750 }
1751 }
1752
1753 void KItemListController::slotStateChanged(QScroller::State newState)
1754 {
1755 if (newState == QScroller::Scrolling) {
1756 m_scrollerIsScrolling = true;
1757 } else if (newState == QScroller::Inactive) {
1758 m_scrollerIsScrolling = false;
1759 }
1760 }