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