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