]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistcontroller.cpp
Fix mouse back/forward buttons
[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 const Qt::MouseButtons buttons = event->buttons();
554
555 if (!onPress(event->screenPos(), event->pos(), event->modifiers(), buttons)) {
556 startRubberBand();
557 return false;
558 }
559
560 if (buttons & (Qt::BackButton | Qt::ForwardButton)) {
561 // Do not select items when clicking the back/forward buttons, see
562 // https://bugs.kde.org/show_bug.cgi?id=327412.
563 return true;
564 }
565
566 return true;
567 }
568
569 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
570 {
571 if (!m_view) {
572 return false;
573 }
574
575 if (m_view->m_tapAndHoldIndicator->isActive()) {
576 m_view->m_tapAndHoldIndicator->setActive(false);
577 }
578
579 if (event->source() == Qt::MouseEventSynthesizedByQt && !m_dragActionOrRightClick) {
580 return false;
581 }
582
583 if (m_pressedIndex >= 0) {
584 // Check whether a dragging should be started
585 if (event->buttons() & Qt::LeftButton) {
586 const QPointF pos = transform.map(event->pos());
587 if ((pos - m_pressedMousePos).manhattanLength() >= QApplication::startDragDistance()) {
588 if (!m_selectionManager->isSelected(m_pressedIndex)) {
589 // Always assure that the dragged item gets selected. Usually this is already
590 // done on the mouse-press event, but when using the selection-toggle on a
591 // selected item the dragged item is not selected yet.
592 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
593 } else {
594 // A selected item has been clicked to drag all selected items
595 // -> the selection should not be cleared when the mouse button is released.
596 m_clearSelectionIfItemsAreNotDragged = false;
597 }
598 startDragging();
599 m_mousePress = false;
600 }
601 }
602 } else {
603 KItemListRubberBand* rubberBand = m_view->rubberBand();
604 if (rubberBand->isActive()) {
605 QPointF endPos = transform.map(event->pos());
606
607 // Update the current item.
608 const int newCurrent = m_view->itemAt(endPos);
609 if (newCurrent >= 0) {
610 // It's expected that the new current index is also the new anchor (bug 163451).
611 m_selectionManager->endAnchoredSelection();
612 m_selectionManager->setCurrentItem(newCurrent);
613 m_selectionManager->beginAnchoredSelection(newCurrent);
614 }
615
616 if (m_view->scrollOrientation() == Qt::Vertical) {
617 endPos.ry() += m_view->scrollOffset();
618 if (m_view->itemSize().width() < 0) {
619 // Use a special rubberband for views that have only one column and
620 // expand the rubberband to use the whole width of the view.
621 endPos.setX(m_view->size().width());
622 }
623 } else {
624 endPos.rx() += m_view->scrollOffset();
625 }
626 rubberBand->setEndPosition(endPos);
627 }
628 }
629
630 return false;
631 }
632
633 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
634 {
635 m_mousePress = false;
636
637 if (!m_view) {
638 return false;
639 }
640
641 if (m_view->m_tapAndHoldIndicator->isActive()) {
642 m_view->m_tapAndHoldIndicator->setActive(false);
643 }
644
645 KItemListRubberBand* rubberBand = m_view->rubberBand();
646 if (event->source() == Qt::MouseEventSynthesizedByQt && !rubberBand->isActive()) {
647 return false;
648 }
649
650 emit mouseButtonReleased(m_pressedIndex, event->buttons());
651
652 return onRelease(transform.map(event->pos()), event->modifiers(), event->button(), false);
653 }
654
655 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
656 {
657 const QPointF pos = transform.map(event->pos());
658 const int index = m_view->itemAt(pos);
659
660 // Expand item if desired - See Bug 295573
661 if (m_mouseDoubleClickAction != ActivateItemOnly) {
662 if (m_view && m_model && m_view->supportsItemExpanding() && m_model->isExpandable(index)) {
663 const bool expanded = m_model->isExpanded(index);
664 m_model->setExpanded(index, !expanded);
665 }
666 }
667
668 if (event->button() & Qt::RightButton) {
669 m_selectionManager->clearSelection();
670 if (index >= 0) {
671 m_selectionManager->setSelected(index);
672 emit itemContextMenuRequested(index, event->screenPos());
673 } else {
674 const QRectF headerBounds = m_view->headerBoundaries();
675 if (headerBounds.contains(event->pos())) {
676 emit headerContextMenuRequested(event->screenPos());
677 } else {
678 emit viewContextMenuRequested(event->screenPos());
679 }
680 }
681 return true;
682 }
683
684 bool emitItemActivated = !(m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) || m_singleClickActivationEnforced) &&
685 (event->button() & Qt::LeftButton) &&
686 index >= 0 && index < m_model->count();
687 if (emitItemActivated) {
688 emit itemActivated(index);
689 }
690 return false;
691 }
692
693 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
694 {
695 Q_UNUSED(event)
696 Q_UNUSED(transform)
697
698 DragAndDropHelper::clearUrlListMatchesUrlCache();
699
700 return false;
701 }
702
703 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
704 {
705 Q_UNUSED(event)
706 Q_UNUSED(transform)
707
708 m_autoActivationTimer->stop();
709 m_view->setAutoScroll(false);
710 m_view->hideDropIndicator();
711
712 KItemListWidget* widget = hoveredWidget();
713 if (widget) {
714 widget->setHovered(false);
715 emit itemUnhovered(widget->index());
716 }
717 return false;
718 }
719
720 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
721 {
722 if (!m_model || !m_view) {
723 return false;
724 }
725
726
727 QUrl hoveredDir = m_model->directory();
728 KItemListWidget* oldHoveredWidget = hoveredWidget();
729
730 const QPointF pos = transform.map(event->pos());
731 KItemListWidget* newHoveredWidget = widgetForPos(pos);
732
733 if (oldHoveredWidget != newHoveredWidget) {
734 m_autoActivationTimer->stop();
735
736 if (oldHoveredWidget) {
737 oldHoveredWidget->setHovered(false);
738 emit itemUnhovered(oldHoveredWidget->index());
739 }
740 }
741
742 if (newHoveredWidget) {
743 bool droppingBetweenItems = false;
744 if (m_model->sortRole().isEmpty()) {
745 // The model supports inserting items between other items.
746 droppingBetweenItems = (m_view->showDropIndicator(pos) >= 0);
747 }
748
749 const int index = newHoveredWidget->index();
750
751 if (m_model->isDir(index)) {
752 hoveredDir = m_model->url(index);
753 }
754
755 if (!droppingBetweenItems) {
756 if (m_model->supportsDropping(index)) {
757 // Something has been dragged on an item.
758 m_view->hideDropIndicator();
759 if (!newHoveredWidget->isHovered()) {
760 newHoveredWidget->setHovered(true);
761 emit itemHovered(index);
762 }
763
764 if (!m_autoActivationTimer->isActive() && m_autoActivationTimer->interval() >= 0) {
765 m_autoActivationTimer->setProperty("index", index);
766 m_autoActivationTimer->start();
767 }
768 }
769 } else {
770 m_autoActivationTimer->stop();
771 if (newHoveredWidget && newHoveredWidget->isHovered()) {
772 newHoveredWidget->setHovered(false);
773 emit itemUnhovered(index);
774 }
775 }
776 } else {
777 m_view->hideDropIndicator();
778 }
779
780 if (DragAndDropHelper::urlListMatchesUrl(event->mimeData()->urls(), hoveredDir)) {
781 event->setDropAction(Qt::IgnoreAction);
782 event->ignore();
783 } else {
784 event->setDropAction(event->proposedAction());
785 event->accept();
786 }
787 return false;
788 }
789
790 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
791 {
792 if (!m_view) {
793 return false;
794 }
795
796 m_autoActivationTimer->stop();
797 m_view->setAutoScroll(false);
798
799 const QPointF pos = transform.map(event->pos());
800
801 int dropAboveIndex = -1;
802 if (m_model->sortRole().isEmpty()) {
803 // The model supports inserting of items between other items.
804 dropAboveIndex = m_view->showDropIndicator(pos);
805 }
806
807 if (dropAboveIndex >= 0) {
808 // Something has been dropped between two items.
809 m_view->hideDropIndicator();
810 emit aboveItemDropEvent(dropAboveIndex, event);
811 } else if (!event->mimeData()->hasFormat(m_model->blacklistItemDropEventMimeType())) {
812 // Something has been dropped on an item or on an empty part of the view.
813 emit itemDropEvent(m_view->itemAt(pos), event);
814 }
815
816 QAccessibleEvent accessibilityEvent(view(), QAccessible::DragDropEnd);
817 QAccessible::updateAccessibility(&accessibilityEvent);
818
819 return true;
820 }
821
822 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
823 {
824 Q_UNUSED(event)
825 Q_UNUSED(transform)
826 return false;
827 }
828
829 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
830 {
831 Q_UNUSED(transform)
832 if (!m_model || !m_view) {
833 return false;
834 }
835
836 KItemListWidget* oldHoveredWidget = hoveredWidget();
837 const QPointF pos = transform.map(event->pos());
838 KItemListWidget* newHoveredWidget = widgetForPos(pos);
839
840 if (oldHoveredWidget != newHoveredWidget) {
841 if (oldHoveredWidget) {
842 oldHoveredWidget->setHovered(false);
843 emit itemUnhovered(oldHoveredWidget->index());
844 }
845
846 if (newHoveredWidget) {
847 newHoveredWidget->setHovered(true);
848 const QPointF mappedPos = newHoveredWidget->mapFromItem(m_view, pos);
849 newHoveredWidget->setHoverPosition(mappedPos);
850 emit itemHovered(newHoveredWidget->index());
851 }
852 } else if (oldHoveredWidget) {
853 const QPointF mappedPos = oldHoveredWidget->mapFromItem(m_view, pos);
854 oldHoveredWidget->setHoverPosition(mappedPos);
855 }
856
857 return false;
858 }
859
860 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
861 {
862 Q_UNUSED(event)
863 Q_UNUSED(transform)
864
865 m_mousePress = false;
866
867 if (!m_model || !m_view) {
868 return false;
869 }
870
871 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
872 if (widget->isHovered()) {
873 widget->setHovered(false);
874 emit itemUnhovered(widget->index());
875 }
876 }
877 return false;
878 }
879
880 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent* event, const QTransform& transform)
881 {
882 Q_UNUSED(event)
883 Q_UNUSED(transform)
884 return false;
885 }
886
887 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent* event, const QTransform& transform)
888 {
889 Q_UNUSED(event)
890 Q_UNUSED(transform)
891 return false;
892 }
893
894 bool KItemListController::gestureEvent(QGestureEvent* event, const QTransform& transform)
895 {
896 if (!m_view) {
897 return false;
898 }
899
900 //you can touch on different views at the same time, but only one QWidget gets a mousePressEvent
901 //we use this to get the right QWidget
902 //the only exception is a tap gesture with state GestureStarted, we need to reset some variable
903 if (!m_mousePress) {
904 if (QGesture* tap = event->gesture(Qt::TapGesture)) {
905 QTapGesture* tapGesture = static_cast<QTapGesture*>(tap);
906 if (tapGesture->state() == Qt::GestureStarted) {
907 tapTriggered(tapGesture, transform);
908 }
909 }
910 return false;
911 }
912
913 bool accepted = false;
914
915 if (QGesture* tap = event->gesture(Qt::TapGesture)) {
916 tapTriggered(static_cast<QTapGesture*>(tap), transform);
917 accepted = true;
918 }
919 if (event->gesture(Qt::TapAndHoldGesture)) {
920 tapAndHoldTriggered(event, transform);
921 accepted = true;
922 }
923 if (event->gesture(Qt::PinchGesture)) {
924 pinchTriggered(event, transform);
925 accepted = true;
926 }
927 if (event->gesture(m_swipeGesture)) {
928 swipeTriggered(event, transform);
929 accepted = true;
930 }
931 if (event->gesture(m_twoFingerTapGesture)) {
932 twoFingerTapTriggered(event, transform);
933 accepted = true;
934 }
935 return accepted;
936 }
937
938 void KItemListController::tapTriggered(QTapGesture* tap, const QTransform& transform)
939 {
940 static bool scrollerWasActive = false;
941
942 if (tap->state() == Qt::GestureStarted) {
943 m_dragActionOrRightClick = false;
944 m_isSwipeGesture = false;
945 m_pinchGestureInProgress = false;
946 m_lastSource = Qt::MouseEventSynthesizedByQt;
947 scrollerWasActive = m_scrollerIsScrolling;
948 }
949
950 if (tap->state() == Qt::GestureFinished) {
951 m_mousePress = false;
952
953 //if at the moment of the gesture start the QScroller was active, the user made the tap
954 //to stop the QScroller and not to tap on an item
955 if (scrollerWasActive) {
956 return;
957 }
958
959 if (m_view->m_tapAndHoldIndicator->isActive()) {
960 m_view->m_tapAndHoldIndicator->setActive(false);
961 }
962
963 m_pressedMousePos = transform.map(tap->position());
964 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
965
966 if (m_dragActionOrRightClick) {
967 onPress(tap->hotSpot().toPoint(), tap->position().toPoint(), Qt::NoModifier, Qt::RightButton);
968 onRelease(transform.map(tap->position()), Qt::NoModifier, Qt::RightButton, false);
969 m_dragActionOrRightClick = false;
970 }
971 else {
972 onPress(tap->hotSpot().toPoint(), tap->position().toPoint(), Qt::NoModifier, Qt::LeftButton);
973 onRelease(transform.map(tap->position()), Qt::NoModifier, Qt::LeftButton, true);
974 }
975 }
976 }
977
978 void KItemListController::tapAndHoldTriggered(QGestureEvent* event, const QTransform& transform)
979 {
980
981 //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this
982 if (m_lastSource == Qt::MouseEventNotSynthesized) {
983 return;
984 }
985
986 const QTapAndHoldGesture* tap = static_cast<QTapAndHoldGesture*>(event->gesture(Qt::TapAndHoldGesture));
987 if (tap->state() == Qt::GestureFinished) {
988 //if a pinch gesture is in progress we don't want a TabAndHold gesture
989 if (m_pinchGestureInProgress) {
990 return;
991 }
992 m_pressedMousePos = transform.map(event->mapToGraphicsScene(tap->position()));
993 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
994
995 if (m_pressedIndex >= 0 && !m_selectionManager->isSelected(m_pressedIndex)) {
996 m_selectionManager->clearSelection();
997 m_selectionManager->setSelected(m_pressedIndex);
998 } else if (m_pressedIndex == -1) {
999 m_selectionManager->clearSelection();
1000 startRubberBand();
1001 }
1002
1003 emit scrollerStop();
1004
1005 m_view->m_tapAndHoldIndicator->setStartPosition(m_pressedMousePos);
1006 m_view->m_tapAndHoldIndicator->setActive(true);
1007
1008 m_dragActionOrRightClick = true;
1009 }
1010 }
1011
1012 void KItemListController::pinchTriggered(QGestureEvent* event, const QTransform& transform)
1013 {
1014 Q_UNUSED(transform)
1015
1016 const QPinchGesture* pinch = static_cast<QPinchGesture*>(event->gesture(Qt::PinchGesture));
1017 const qreal sensitivityModifier = 0.2;
1018 static qreal counter = 0;
1019
1020 if (pinch->state() == Qt::GestureStarted) {
1021 m_pinchGestureInProgress = true;
1022 counter = 0;
1023 }
1024 if (pinch->state() == Qt::GestureUpdated) {
1025 //if a swipe gesture was recognized or in progress, we don't want a pinch gesture to change the zoom
1026 if (m_isSwipeGesture) {
1027 return;
1028 }
1029 counter = counter + (pinch->scaleFactor() - 1);
1030 if (counter >= sensitivityModifier) {
1031 emit increaseZoom();
1032 counter = 0;
1033 } else if (counter <= -sensitivityModifier) {
1034 emit decreaseZoom();
1035 counter = 0;
1036 }
1037 }
1038 }
1039
1040 void KItemListController::swipeTriggered(QGestureEvent* event, const QTransform& transform)
1041 {
1042 Q_UNUSED(transform)
1043
1044 const KTwoFingerSwipe* swipe = static_cast<KTwoFingerSwipe*>(event->gesture(m_swipeGesture));
1045
1046 if (!swipe) {
1047 return;
1048 }
1049 if (swipe->state() == Qt::GestureStarted) {
1050 m_isSwipeGesture = true;
1051 }
1052
1053 if (swipe->state() == Qt::GestureCanceled) {
1054 m_isSwipeGesture = false;
1055 }
1056
1057 if (swipe->state() == Qt::GestureFinished) {
1058 emit scrollerStop();
1059
1060 if (swipe->swipeAngle() <= 20 || swipe->swipeAngle() >= 340) {
1061 emit mouseButtonPressed(m_pressedIndex, Qt::BackButton);
1062 } else if (swipe->swipeAngle() <= 200 && swipe->swipeAngle() >= 160) {
1063 emit mouseButtonPressed(m_pressedIndex, Qt::ForwardButton);
1064 } else if (swipe->swipeAngle() <= 110 && swipe->swipeAngle() >= 60) {
1065 emit swipeUp();
1066 }
1067 m_isSwipeGesture = true;
1068 }
1069 }
1070
1071 void KItemListController::twoFingerTapTriggered(QGestureEvent* event, const QTransform& transform)
1072 {
1073 const KTwoFingerTap* twoTap = static_cast<KTwoFingerTap*>(event->gesture(m_twoFingerTapGesture));
1074
1075 if (!twoTap) {
1076 return;
1077 }
1078
1079 if (twoTap->state() == Qt::GestureStarted) {
1080 m_pressedMousePos = transform.map(twoTap->pos());
1081 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
1082 if (m_pressedIndex >= 0) {
1083 onPress(twoTap->screenPos().toPoint(), twoTap->pos().toPoint(), Qt::ControlModifier, Qt::LeftButton);
1084 onRelease(transform.map(twoTap->pos()), Qt::ControlModifier, Qt::LeftButton, false);
1085 }
1086
1087 }
1088 }
1089
1090 bool KItemListController::processEvent(QEvent* event, const QTransform& transform)
1091 {
1092 if (!event) {
1093 return false;
1094 }
1095
1096 switch (event->type()) {
1097 case QEvent::KeyPress:
1098 return keyPressEvent(static_cast<QKeyEvent*>(event));
1099 case QEvent::InputMethod:
1100 return inputMethodEvent(static_cast<QInputMethodEvent*>(event));
1101 case QEvent::GraphicsSceneMousePress:
1102 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1103 case QEvent::GraphicsSceneMouseMove:
1104 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1105 case QEvent::GraphicsSceneMouseRelease:
1106 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1107 case QEvent::GraphicsSceneMouseDoubleClick:
1108 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1109 case QEvent::GraphicsSceneWheel:
1110 return wheelEvent(static_cast<QGraphicsSceneWheelEvent*>(event), QTransform());
1111 case QEvent::GraphicsSceneDragEnter:
1112 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1113 case QEvent::GraphicsSceneDragLeave:
1114 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1115 case QEvent::GraphicsSceneDragMove:
1116 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1117 case QEvent::GraphicsSceneDrop:
1118 return dropEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1119 case QEvent::GraphicsSceneHoverEnter:
1120 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1121 case QEvent::GraphicsSceneHoverMove:
1122 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1123 case QEvent::GraphicsSceneHoverLeave:
1124 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1125 case QEvent::GraphicsSceneResize:
1126 return resizeEvent(static_cast<QGraphicsSceneResizeEvent*>(event), transform);
1127 case QEvent::Gesture:
1128 return gestureEvent(static_cast<QGestureEvent*>(event), transform);
1129 default:
1130 break;
1131 }
1132
1133 return false;
1134 }
1135
1136 void KItemListController::slotViewScrollOffsetChanged(qreal current, qreal previous)
1137 {
1138 if (!m_view) {
1139 return;
1140 }
1141
1142 KItemListRubberBand* rubberBand = m_view->rubberBand();
1143 if (rubberBand->isActive()) {
1144 const qreal diff = current - previous;
1145 // TODO: Ideally just QCursor::pos() should be used as
1146 // new end-position but it seems there is no easy way
1147 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1148 // (... or I just missed an easy way to do the mapping)
1149 QPointF endPos = rubberBand->endPosition();
1150 if (m_view->scrollOrientation() == Qt::Vertical) {
1151 endPos.ry() += diff;
1152 } else {
1153 endPos.rx() += diff;
1154 }
1155
1156 rubberBand->setEndPosition(endPos);
1157 }
1158 }
1159
1160 void KItemListController::slotRubberBandChanged()
1161 {
1162 if (!m_view || !m_model || m_model->count() <= 0) {
1163 return;
1164 }
1165
1166 const KItemListRubberBand* rubberBand = m_view->rubberBand();
1167 const QPointF startPos = rubberBand->startPosition();
1168 const QPointF endPos = rubberBand->endPosition();
1169 QRectF rubberBandRect = QRectF(startPos, endPos).normalized();
1170
1171 const bool scrollVertical = (m_view->scrollOrientation() == Qt::Vertical);
1172 if (scrollVertical) {
1173 rubberBandRect.translate(0, -m_view->scrollOffset());
1174 } else {
1175 rubberBandRect.translate(-m_view->scrollOffset(), 0);
1176 }
1177
1178 if (!m_oldSelection.isEmpty()) {
1179 // Clear the old selection that was available before the rubberband has
1180 // been activated in case if no Shift- or Control-key are pressed
1181 const bool shiftOrControlPressed = QApplication::keyboardModifiers() & Qt::ShiftModifier ||
1182 QApplication::keyboardModifiers() & Qt::ControlModifier;
1183 if (!shiftOrControlPressed) {
1184 m_oldSelection.clear();
1185 }
1186 }
1187
1188 KItemSet selectedItems;
1189
1190 // Select all visible items that intersect with the rubberband
1191 foreach (const KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1192 const int index = widget->index();
1193
1194 const QRectF widgetRect = m_view->itemRect(index);
1195 if (widgetRect.intersects(rubberBandRect)) {
1196 const QRectF iconRect = widget->iconRect().translated(widgetRect.topLeft());
1197 const QRectF textRect = widget->textRect().translated(widgetRect.topLeft());
1198 if (iconRect.intersects(rubberBandRect) || textRect.intersects(rubberBandRect)) {
1199 selectedItems.insert(index);
1200 }
1201 }
1202 }
1203
1204 // Select all invisible items that intersect with the rubberband. Instead of
1205 // iterating all items only the area which might be touched by the rubberband
1206 // will be checked.
1207 const bool increaseIndex = scrollVertical ?
1208 startPos.y() > endPos.y(): startPos.x() > endPos.x();
1209
1210 int index = increaseIndex ? m_view->lastVisibleIndex() + 1 : m_view->firstVisibleIndex() - 1;
1211 bool selectionFinished = false;
1212 do {
1213 const QRectF widgetRect = m_view->itemRect(index);
1214 if (widgetRect.intersects(rubberBandRect)) {
1215 selectedItems.insert(index);
1216 }
1217
1218 if (increaseIndex) {
1219 ++index;
1220 selectionFinished = (index >= m_model->count()) ||
1221 ( scrollVertical && widgetRect.top() > rubberBandRect.bottom()) ||
1222 (!scrollVertical && widgetRect.left() > rubberBandRect.right());
1223 } else {
1224 --index;
1225 selectionFinished = (index < 0) ||
1226 ( scrollVertical && widgetRect.bottom() < rubberBandRect.top()) ||
1227 (!scrollVertical && widgetRect.right() < rubberBandRect.left());
1228 }
1229 } while (!selectionFinished);
1230
1231 if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
1232 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1233 // Therefore, the new selection contains:
1234 // 1. All previously selected items which are not inside the rubberband, and
1235 // 2. all items inside the rubberband which have not been selected previously.
1236 m_selectionManager->setSelectedItems(m_oldSelection ^ selectedItems);
1237 }
1238 else {
1239 m_selectionManager->setSelectedItems(selectedItems + m_oldSelection);
1240 }
1241 }
1242
1243 void KItemListController::startDragging()
1244 {
1245 if (!m_view || !m_model) {
1246 return;
1247 }
1248
1249 const KItemSet selectedItems = m_selectionManager->selectedItems();
1250 if (selectedItems.isEmpty()) {
1251 return;
1252 }
1253
1254 QMimeData* data = m_model->createMimeData(selectedItems);
1255 if (!data) {
1256 return;
1257 }
1258
1259 // The created drag object will be owned and deleted
1260 // by QApplication::activeWindow().
1261 QDrag* drag = new QDrag(QApplication::activeWindow());
1262 drag->setMimeData(data);
1263
1264 const QPixmap pixmap = m_view->createDragPixmap(selectedItems);
1265 drag->setPixmap(pixmap);
1266
1267 const QPoint hotSpot((pixmap.width() / pixmap.devicePixelRatio()) / 2, 0);
1268 drag->setHotSpot(hotSpot);
1269
1270 drag->exec(Qt::MoveAction | Qt::CopyAction | Qt::LinkAction, Qt::CopyAction);
1271
1272 QAccessibleEvent accessibilityEvent(view(), QAccessible::DragDropStart);
1273 QAccessible::updateAccessibility(&accessibilityEvent);
1274 }
1275
1276 KItemListWidget* KItemListController::hoveredWidget() const
1277 {
1278 Q_ASSERT(m_view);
1279
1280 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1281 if (widget->isHovered()) {
1282 return widget;
1283 }
1284 }
1285
1286 return nullptr;
1287 }
1288
1289 KItemListWidget* KItemListController::widgetForPos(const QPointF& pos) const
1290 {
1291 Q_ASSERT(m_view);
1292
1293 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1294 const QPointF mappedPos = widget->mapFromItem(m_view, pos);
1295
1296 const bool hovered = widget->contains(mappedPos) &&
1297 !widget->expansionToggleRect().contains(mappedPos);
1298 if (hovered) {
1299 return widget;
1300 }
1301 }
1302
1303 return nullptr;
1304 }
1305
1306 void KItemListController::updateKeyboardAnchor()
1307 {
1308 const bool validAnchor = m_keyboardAnchorIndex >= 0 &&
1309 m_keyboardAnchorIndex < m_model->count() &&
1310 keyboardAnchorPos(m_keyboardAnchorIndex) == m_keyboardAnchorPos;
1311 if (!validAnchor) {
1312 const int index = m_selectionManager->currentItem();
1313 m_keyboardAnchorIndex = index;
1314 m_keyboardAnchorPos = keyboardAnchorPos(index);
1315 }
1316 }
1317
1318 int KItemListController::nextRowIndex(int index) const
1319 {
1320 if (m_keyboardAnchorIndex < 0) {
1321 return index;
1322 }
1323
1324 const int maxIndex = m_model->count() - 1;
1325 if (index == maxIndex) {
1326 return index;
1327 }
1328
1329 // Calculate the index of the last column inside the row of the current index
1330 int lastColumnIndex = index;
1331 while (keyboardAnchorPos(lastColumnIndex + 1) > keyboardAnchorPos(lastColumnIndex)) {
1332 ++lastColumnIndex;
1333 if (lastColumnIndex >= maxIndex) {
1334 return index;
1335 }
1336 }
1337
1338 // Based on the last column index go to the next row and calculate the nearest index
1339 // that is below the current index
1340 int nextRowIndex = lastColumnIndex + 1;
1341 int searchIndex = nextRowIndex;
1342 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(nextRowIndex));
1343 while (searchIndex < maxIndex && keyboardAnchorPos(searchIndex + 1) > keyboardAnchorPos(searchIndex)) {
1344 ++searchIndex;
1345 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1346 if (searchDiff < minDiff) {
1347 minDiff = searchDiff;
1348 nextRowIndex = searchIndex;
1349 }
1350 }
1351
1352 return nextRowIndex;
1353 }
1354
1355 int KItemListController::previousRowIndex(int index) const
1356 {
1357 if (m_keyboardAnchorIndex < 0 || index == 0) {
1358 return index;
1359 }
1360
1361 // Calculate the index of the first column inside the row of the current index
1362 int firstColumnIndex = index;
1363 while (keyboardAnchorPos(firstColumnIndex - 1) < keyboardAnchorPos(firstColumnIndex)) {
1364 --firstColumnIndex;
1365 if (firstColumnIndex <= 0) {
1366 return index;
1367 }
1368 }
1369
1370 // Based on the first column index go to the previous row and calculate the nearest index
1371 // that is above the current index
1372 int previousRowIndex = firstColumnIndex - 1;
1373 int searchIndex = previousRowIndex;
1374 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(previousRowIndex));
1375 while (searchIndex > 0 && keyboardAnchorPos(searchIndex - 1) < keyboardAnchorPos(searchIndex)) {
1376 --searchIndex;
1377 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1378 if (searchDiff < minDiff) {
1379 minDiff = searchDiff;
1380 previousRowIndex = searchIndex;
1381 }
1382 }
1383
1384 return previousRowIndex;
1385 }
1386
1387 qreal KItemListController::keyboardAnchorPos(int index) const
1388 {
1389 const QRectF itemRect = m_view->itemRect(index);
1390 if (!itemRect.isEmpty()) {
1391 return (m_view->scrollOrientation() == Qt::Vertical) ? itemRect.x() : itemRect.y();
1392 }
1393
1394 return 0;
1395 }
1396
1397 void KItemListController::updateExtendedSelectionRegion()
1398 {
1399 if (m_view) {
1400 const bool extend = (m_selectionBehavior != MultiSelection);
1401 KItemListStyleOption option = m_view->styleOption();
1402 if (option.extendedSelectionRegion != extend) {
1403 option.extendedSelectionRegion = extend;
1404 m_view->setStyleOption(option);
1405 }
1406 }
1407 }
1408
1409 bool KItemListController::onPress(const QPoint& screenPos, const QPointF& pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons)
1410 {
1411 emit mouseButtonPressed(m_pressedIndex, buttons);
1412
1413 if (m_view->isAboveExpansionToggle(m_pressedIndex, m_pressedMousePos)) {
1414 m_selectionManager->endAnchoredSelection();
1415 m_selectionManager->setCurrentItem(m_pressedIndex);
1416 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
1417 return true;
1418 }
1419
1420 m_selectionTogglePressed = m_view->isAboveSelectionToggle(m_pressedIndex, m_pressedMousePos);
1421 if (m_selectionTogglePressed) {
1422 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
1423 // The previous anchored selection has been finished already in
1424 // KItemListSelectionManager::setSelected(). We can safely change
1425 // the current item and start a new anchored selection now.
1426 m_selectionManager->setCurrentItem(m_pressedIndex);
1427 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
1428 return true;
1429 }
1430
1431 const bool shiftPressed = modifiers & Qt::ShiftModifier;
1432 const bool controlPressed = modifiers & Qt::ControlModifier;
1433
1434 // The previous selection is cleared if either
1435 // 1. The selection mode is SingleSelection, or
1436 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
1437 // a) Shift or Control are pressed.
1438 // b) The clicked item is selected already. In that case, the user might want to:
1439 // - start dragging multiple items, or
1440 // - open the context menu and perform an action for all selected items.
1441 const bool shiftOrControlPressed = shiftPressed || controlPressed;
1442 const bool pressedItemAlreadySelected = m_pressedIndex >= 0 && m_selectionManager->isSelected(m_pressedIndex);
1443 const bool clearSelection = m_selectionBehavior == SingleSelection ||
1444 (!shiftOrControlPressed && !pressedItemAlreadySelected);
1445 if (clearSelection) {
1446 m_selectionManager->clearSelection();
1447 } else if (pressedItemAlreadySelected && !shiftOrControlPressed && (buttons & Qt::LeftButton)) {
1448 // The user might want to start dragging multiple items, but if he clicks the item
1449 // in order to trigger it instead, the other selected items must be deselected.
1450 // However, we do not know yet what the user is going to do.
1451 // -> remember that the user pressed an item which had been selected already and
1452 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
1453 m_clearSelectionIfItemsAreNotDragged = true;
1454
1455 if (m_selectionManager->selectedItems().count() == 1 && m_view->isAboveText(m_pressedIndex, m_pressedMousePos)) {
1456 emit selectedItemTextPressed(m_pressedIndex);
1457 }
1458 }
1459
1460 if (!shiftPressed) {
1461 // Finish the anchored selection before the current index is changed
1462 m_selectionManager->endAnchoredSelection();
1463 }
1464
1465 if (buttons & Qt::RightButton) {
1466 // Stop rubber band from persisting after right-clicks
1467 KItemListRubberBand* rubberBand = m_view->rubberBand();
1468 if (rubberBand->isActive()) {
1469 disconnect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged);
1470 rubberBand->setActive(false);
1471 m_view->setAutoScroll(false);
1472 }
1473 }
1474
1475 if (m_pressedIndex >= 0) {
1476 m_selectionManager->setCurrentItem(m_pressedIndex);
1477
1478 switch (m_selectionBehavior) {
1479 case NoSelection:
1480 break;
1481
1482 case SingleSelection:
1483 m_selectionManager->setSelected(m_pressedIndex);
1484 break;
1485
1486 case MultiSelection:
1487 if (controlPressed && !shiftPressed) {
1488 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
1489 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
1490 } else if (!shiftPressed || !m_selectionManager->isAnchoredSelectionActive()) {
1491 // Select the pressed item and start a new anchored selection
1492 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Select);
1493 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
1494 }
1495 break;
1496
1497 default:
1498 Q_ASSERT(false);
1499 break;
1500 }
1501
1502 if (buttons & Qt::RightButton) {
1503 emit itemContextMenuRequested(m_pressedIndex, screenPos);
1504 }
1505
1506 return true;
1507 }
1508
1509 if (buttons & Qt::RightButton) {
1510 const QRectF headerBounds = m_view->headerBoundaries();
1511 if (headerBounds.contains(pos)) {
1512 emit headerContextMenuRequested(screenPos);
1513 } else {
1514 emit viewContextMenuRequested(screenPos);
1515 }
1516 return true;
1517 }
1518
1519 return false;
1520 }
1521
1522 bool KItemListController::onRelease(const QPointF& pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons, bool touch)
1523 {
1524 const bool isAboveSelectionToggle = m_view->isAboveSelectionToggle(m_pressedIndex, m_pressedMousePos);
1525 if (isAboveSelectionToggle) {
1526 m_selectionTogglePressed = false;
1527 return true;
1528 }
1529
1530 if (!isAboveSelectionToggle && m_selectionTogglePressed) {
1531 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
1532 m_selectionTogglePressed = false;
1533 return true;
1534 }
1535
1536 const bool shiftOrControlPressed = modifiers & Qt::ShiftModifier ||
1537 modifiers & Qt::ControlModifier;
1538
1539 KItemListRubberBand* rubberBand = m_view->rubberBand();
1540 if (rubberBand->isActive()) {
1541 disconnect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged);
1542 rubberBand->setActive(false);
1543 m_oldSelection.clear();
1544 m_view->setAutoScroll(false);
1545 }
1546
1547 const int index = m_view->itemAt(pos);
1548
1549 if (index >= 0 && index == m_pressedIndex) {
1550 // The release event is done above the same item as the press event
1551
1552 if (m_clearSelectionIfItemsAreNotDragged) {
1553 // A selected item has been clicked, but no drag operation has been started
1554 // -> clear the rest of the selection.
1555 m_selectionManager->clearSelection();
1556 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Select);
1557 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
1558 }
1559
1560 if (buttons & Qt::LeftButton) {
1561 bool emitItemActivated = true;
1562 if (m_view->isAboveExpansionToggle(index, pos)) {
1563 const bool expanded = m_model->isExpanded(index);
1564 m_model->setExpanded(index, !expanded);
1565
1566 emit itemExpansionToggleClicked(index);
1567 emitItemActivated = false;
1568 } else if (shiftOrControlPressed) {
1569 // The mouse click should only update the selection, not trigger the item
1570 emitItemActivated = false;
1571 } else if (!(m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) || m_singleClickActivationEnforced)) {
1572 if (touch) {
1573 emitItemActivated = true;
1574 } else {
1575 emitItemActivated = false;
1576 }
1577 }
1578 if (emitItemActivated) {
1579 emit itemActivated(index);
1580 }
1581 } else if (buttons & Qt::MiddleButton) {
1582 emit itemMiddleClicked(index);
1583 }
1584 }
1585
1586 m_pressedMousePos = QPointF();
1587 m_pressedIndex = -1;
1588 m_clearSelectionIfItemsAreNotDragged = false;
1589 return false;
1590 }
1591
1592 void KItemListController::startRubberBand()
1593 {
1594 if (m_selectionBehavior == MultiSelection) {
1595 QPointF startPos = m_pressedMousePos;
1596 if (m_view->scrollOrientation() == Qt::Vertical) {
1597 startPos.ry() += m_view->scrollOffset();
1598 if (m_view->itemSize().width() < 0) {
1599 // Use a special rubberband for views that have only one column and
1600 // expand the rubberband to use the whole width of the view.
1601 startPos.setX(0);
1602 }
1603 } else {
1604 startPos.rx() += m_view->scrollOffset();
1605 }
1606
1607 m_oldSelection = m_selectionManager->selectedItems();
1608 KItemListRubberBand* rubberBand = m_view->rubberBand();
1609 rubberBand->setStartPosition(startPos);
1610 rubberBand->setEndPosition(startPos);
1611 rubberBand->setActive(true);
1612 connect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged);
1613 m_view->setAutoScroll(true);
1614 }
1615 }
1616
1617 void KItemListController::slotStateChanged(QScroller::State newState)
1618 {
1619 if (newState == QScroller::Scrolling) {
1620 m_scrollerIsScrolling = true;
1621 } else if (newState == QScroller::Inactive) {
1622 m_scrollerIsScrolling = false;
1623 }
1624 }