]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistcontroller.cpp
Migrate settings
[dolphin.git] / src / kitemviews / kitemlistcontroller.cpp
1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
3 * Copyright (C) 2012 by Frank Reininghaus <frank78ac@googlemail.com> *
4 * *
5 * Based on the Itemviews NG project from Trolltech Labs: *
6 * http://qt.gitorious.org/qt-labs/itemviews-ng *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
22 ***************************************************************************/
23
24 #include "kitemlistcontroller.h"
25
26 #include <QDebug>
27
28 #include "kitemlistview.h"
29 #include "kitemlistselectionmanager.h"
30
31 #include "private/kitemlistrubberband.h"
32 #include "private/kitemlistkeyboardsearchmanager.h"
33
34 #include <QApplication>
35 #include <QDrag>
36 #include <QEvent>
37 #include <QGraphicsScene>
38 #include <QGraphicsSceneEvent>
39 #include <QGraphicsView>
40 #include <QMimeData>
41 #include <QTimer>
42 #include <QAccessible>
43
44 KItemListController::KItemListController(KItemModelBase* model, KItemListView* view, QObject* parent) :
45 QObject(parent),
46 m_singleClickActivationEnforced(false),
47 m_selectionTogglePressed(false),
48 m_clearSelectionIfItemsAreNotDragged(false),
49 m_selectionBehavior(NoSelection),
50 m_autoActivationBehavior(ActivationAndExpansion),
51 m_mouseDoubleClickAction(ActivateItemOnly),
52 m_model(0),
53 m_view(0),
54 m_selectionManager(new KItemListSelectionManager(this)),
55 m_keyboardManager(new KItemListKeyboardSearchManager(this)),
56 m_pressedIndex(-1),
57 m_pressedMousePos(),
58 m_autoActivationTimer(0),
59 m_oldSelection(),
60 m_keyboardAnchorIndex(-1),
61 m_keyboardAnchorPos(0)
62 {
63 connect(m_keyboardManager, &KItemListKeyboardSearchManager::changeCurrentItem,
64 this, &KItemListController::slotChangeCurrentItem);
65 connect(m_selectionManager, &KItemListSelectionManager::currentChanged,
66 m_keyboardManager, &KItemListKeyboardSearchManager::slotCurrentChanged);
67
68 m_autoActivationTimer = new QTimer(this);
69 m_autoActivationTimer->setSingleShot(true);
70 m_autoActivationTimer->setInterval(-1);
71 connect(m_autoActivationTimer, &QTimer::timeout, this, &KItemListController::slotAutoActivationTimeout);
72
73 setModel(model);
74 setView(view);
75 }
76
77 KItemListController::~KItemListController()
78 {
79 setView(0);
80 Q_ASSERT(!m_view);
81
82 setModel(0);
83 Q_ASSERT(!m_model);
84 }
85
86 void KItemListController::setModel(KItemModelBase* model)
87 {
88 if (m_model == model) {
89 return;
90 }
91
92 KItemModelBase* oldModel = m_model;
93 if (oldModel) {
94 oldModel->deleteLater();
95 }
96
97 m_model = model;
98 if (m_model) {
99 m_model->setParent(this);
100 }
101
102 if (m_view) {
103 m_view->setModel(m_model);
104 }
105
106 m_selectionManager->setModel(m_model);
107
108 emit modelChanged(m_model, oldModel);
109 }
110
111 KItemModelBase* KItemListController::model() const
112 {
113 return m_model;
114 }
115
116 KItemListSelectionManager* KItemListController::selectionManager() const
117 {
118 return m_selectionManager;
119 }
120
121 void KItemListController::setView(KItemListView* view)
122 {
123 if (m_view == view) {
124 return;
125 }
126
127 KItemListView* oldView = m_view;
128 if (oldView) {
129 disconnect(oldView, &KItemListView::scrollOffsetChanged, this, &KItemListController::slotViewScrollOffsetChanged);
130 oldView->deleteLater();
131 }
132
133 m_view = view;
134
135 if (m_view) {
136 m_view->setParent(this);
137 m_view->setController(this);
138 m_view->setModel(m_model);
139 connect(m_view, &KItemListView::scrollOffsetChanged, this, &KItemListController::slotViewScrollOffsetChanged);
140 updateExtendedSelectionRegion();
141 }
142
143 emit viewChanged(m_view, oldView);
144 }
145
146 KItemListView* KItemListController::view() const
147 {
148 return m_view;
149 }
150
151 void KItemListController::setSelectionBehavior(SelectionBehavior behavior)
152 {
153 m_selectionBehavior = behavior;
154 updateExtendedSelectionRegion();
155 }
156
157 KItemListController::SelectionBehavior KItemListController::selectionBehavior() const
158 {
159 return m_selectionBehavior;
160 }
161
162 void KItemListController::setAutoActivationBehavior(AutoActivationBehavior behavior)
163 {
164 m_autoActivationBehavior = behavior;
165 }
166
167 KItemListController::AutoActivationBehavior KItemListController::autoActivationBehavior() const
168 {
169 return m_autoActivationBehavior;
170 }
171
172 void KItemListController::setMouseDoubleClickAction(MouseDoubleClickAction action)
173 {
174 m_mouseDoubleClickAction = action;
175 }
176
177 KItemListController::MouseDoubleClickAction KItemListController::mouseDoubleClickAction() const
178 {
179 return m_mouseDoubleClickAction;
180 }
181
182 void KItemListController::setAutoActivationDelay(int delay)
183 {
184 m_autoActivationTimer->setInterval(delay);
185 }
186
187 int KItemListController::autoActivationDelay() const
188 {
189 return m_autoActivationTimer->interval();
190 }
191
192 void KItemListController::setSingleClickActivationEnforced(bool singleClick)
193 {
194 m_singleClickActivationEnforced = singleClick;
195 }
196
197 bool KItemListController::singleClickActivationEnforced() const
198 {
199 return m_singleClickActivationEnforced;
200 }
201
202 bool KItemListController::showEvent(QShowEvent* event)
203 {
204 Q_UNUSED(event);
205 return false;
206 }
207
208 bool KItemListController::hideEvent(QHideEvent* event)
209 {
210 Q_UNUSED(event);
211 return false;
212 }
213
214 bool KItemListController::keyPressEvent(QKeyEvent* event)
215 {
216 int index = m_selectionManager->currentItem();
217 int key = event->key();
218
219 // Handle the expanding/collapsing of items
220 if (m_view->supportsItemExpanding() && m_model->isExpandable(index)) {
221 if (key == Qt::Key_Right) {
222 if (m_model->setExpanded(index, true)) {
223 return true;
224 }
225 } else if (key == Qt::Key_Left) {
226 if (m_model->setExpanded(index, false)) {
227 return true;
228 }
229 }
230 }
231
232 const bool shiftPressed = event->modifiers() & Qt::ShiftModifier;
233 const bool controlPressed = event->modifiers() & Qt::ControlModifier;
234 const bool shiftOrControlPressed = shiftPressed || controlPressed;
235
236 const int itemCount = m_model->count();
237
238 // For horizontal scroll orientation, transform
239 // the arrow keys to simplify the event handling.
240 if (m_view->scrollOrientation() == Qt::Horizontal) {
241 switch (key) {
242 case Qt::Key_Up: key = Qt::Key_Left; break;
243 case Qt::Key_Down: key = Qt::Key_Right; break;
244 case Qt::Key_Left: key = Qt::Key_Up; break;
245 case Qt::Key_Right: key = Qt::Key_Down; break;
246 default: break;
247 }
248 }
249
250 const bool selectSingleItem = m_selectionBehavior != NoSelection &&
251 itemCount == 1 &&
252 (key == Qt::Key_Home || key == Qt::Key_End ||
253 key == Qt::Key_Up || key == Qt::Key_Down ||
254 key == Qt::Key_Left || key == Qt::Key_Right);
255 if (selectSingleItem) {
256 const int current = m_selectionManager->currentItem();
257 m_selectionManager->setSelected(current);
258 return true;
259 }
260
261 switch (key) {
262 case Qt::Key_Home:
263 index = 0;
264 m_keyboardAnchorIndex = index;
265 m_keyboardAnchorPos = keyboardAnchorPos(index);
266 break;
267
268 case Qt::Key_End:
269 index = itemCount - 1;
270 m_keyboardAnchorIndex = index;
271 m_keyboardAnchorPos = keyboardAnchorPos(index);
272 break;
273
274 case Qt::Key_Left:
275 if (index > 0) {
276 const int expandedParentsCount = m_model->expandedParentsCount(index);
277 if (expandedParentsCount == 0) {
278 --index;
279 } else {
280 // Go to the parent of the current item.
281 do {
282 --index;
283 } while (index > 0 && m_model->expandedParentsCount(index) == expandedParentsCount);
284 }
285 m_keyboardAnchorIndex = index;
286 m_keyboardAnchorPos = keyboardAnchorPos(index);
287 }
288 break;
289
290 case Qt::Key_Right:
291 if (index < itemCount - 1) {
292 ++index;
293 m_keyboardAnchorIndex = index;
294 m_keyboardAnchorPos = keyboardAnchorPos(index);
295 }
296 break;
297
298 case Qt::Key_Up:
299 updateKeyboardAnchor();
300 index = previousRowIndex(index);
301 break;
302
303 case Qt::Key_Down:
304 updateKeyboardAnchor();
305 index = nextRowIndex(index);
306 break;
307
308 case Qt::Key_PageUp:
309 if (m_view->scrollOrientation() == Qt::Horizontal) {
310 // The new current index should correspond to the first item in the current column.
311 int newIndex = qMax(index - 1, 0);
312 while (newIndex != index && m_view->itemRect(newIndex).topLeft().y() < m_view->itemRect(index).topLeft().y()) {
313 index = newIndex;
314 newIndex = qMax(index - 1, 0);
315 }
316 m_keyboardAnchorIndex = index;
317 m_keyboardAnchorPos = keyboardAnchorPos(index);
318 } else {
319 const qreal currentItemBottom = m_view->itemRect(index).bottomLeft().y();
320 const qreal height = m_view->geometry().height();
321
322 // The new current item should be the first item in the current
323 // column whose itemRect's top coordinate is larger than targetY.
324 const qreal targetY = currentItemBottom - height;
325
326 updateKeyboardAnchor();
327 int newIndex = previousRowIndex(index);
328 do {
329 index = newIndex;
330 updateKeyboardAnchor();
331 newIndex = previousRowIndex(index);
332 } while (m_view->itemRect(newIndex).topLeft().y() > targetY && newIndex != index);
333 }
334 break;
335
336 case Qt::Key_PageDown:
337 if (m_view->scrollOrientation() == Qt::Horizontal) {
338 // The new current index should correspond to the last item in the current column.
339 int newIndex = qMin(index + 1, m_model->count() - 1);
340 while (newIndex != index && m_view->itemRect(newIndex).topLeft().y() > m_view->itemRect(index).topLeft().y()) {
341 index = newIndex;
342 newIndex = qMin(index + 1, m_model->count() - 1);
343 }
344 m_keyboardAnchorIndex = index;
345 m_keyboardAnchorPos = keyboardAnchorPos(index);
346 } else {
347 const qreal currentItemTop = m_view->itemRect(index).topLeft().y();
348 const qreal height = m_view->geometry().height();
349
350 // The new current item should be the last item in the current
351 // column whose itemRect's bottom coordinate is smaller than targetY.
352 const qreal targetY = currentItemTop + height;
353
354 updateKeyboardAnchor();
355 int newIndex = nextRowIndex(index);
356 do {
357 index = newIndex;
358 updateKeyboardAnchor();
359 newIndex = nextRowIndex(index);
360 } while (m_view->itemRect(newIndex).bottomLeft().y() < targetY && newIndex != index);
361 }
362 break;
363
364 case Qt::Key_Enter:
365 case Qt::Key_Return: {
366 const KItemSet selectedItems = m_selectionManager->selectedItems();
367 if (selectedItems.count() >= 2) {
368 emit itemsActivated(selectedItems);
369 } else if (selectedItems.count() == 1) {
370 emit itemActivated(selectedItems.first());
371 } else {
372 emit itemActivated(index);
373 }
374 break;
375 }
376
377 case Qt::Key_Menu: {
378 // Emit the signal itemContextMenuRequested() in case if at least one
379 // item is selected. Otherwise the signal viewContextMenuRequested() will be emitted.
380 const KItemSet selectedItems = m_selectionManager->selectedItems();
381 int index = -1;
382 if (selectedItems.count() >= 2) {
383 const int currentItemIndex = m_selectionManager->currentItem();
384 index = selectedItems.contains(currentItemIndex)
385 ? currentItemIndex : selectedItems.first();
386 } else if (selectedItems.count() == 1) {
387 index = selectedItems.first();
388 }
389
390 if (index >= 0) {
391 const QRectF contextRect = m_view->itemContextRect(index);
392 const QPointF pos(m_view->scene()->views().first()->mapToGlobal(contextRect.bottomRight().toPoint()));
393 emit itemContextMenuRequested(index, pos);
394 } else {
395 emit viewContextMenuRequested(QCursor::pos());
396 }
397 break;
398 }
399
400 case Qt::Key_Escape:
401 if (m_selectionBehavior != SingleSelection) {
402 m_selectionManager->clearSelection();
403 }
404 m_keyboardManager->cancelSearch();
405 emit escapePressed();
406 break;
407
408 case Qt::Key_Space:
409 if (m_selectionBehavior == MultiSelection) {
410 if (controlPressed) {
411 // Toggle the selection state of the current item.
412 m_selectionManager->endAnchoredSelection();
413 m_selectionManager->setSelected(index, 1, KItemListSelectionManager::Toggle);
414 m_selectionManager->beginAnchoredSelection(index);
415 break;
416 } else {
417 // Select the current item if it is not selected yet.
418 const int current = m_selectionManager->currentItem();
419 if (!m_selectionManager->isSelected(current)) {
420 m_selectionManager->setSelected(current);
421 break;
422 }
423 }
424 }
425 // Fall through to the default case and add the Space to the current search string.
426
427 default:
428 m_keyboardManager->addKeys(event->text());
429 // Make sure unconsumed events get propagated up the chain. #302329
430 event->ignore();
431 return false;
432 }
433
434 if (m_selectionManager->currentItem() != index) {
435 switch (m_selectionBehavior) {
436 case NoSelection:
437 m_selectionManager->setCurrentItem(index);
438 break;
439
440 case SingleSelection:
441 m_selectionManager->setCurrentItem(index);
442 m_selectionManager->clearSelection();
443 m_selectionManager->setSelected(index, 1);
444 break;
445
446 case MultiSelection:
447 if (controlPressed) {
448 m_selectionManager->endAnchoredSelection();
449 }
450
451 m_selectionManager->setCurrentItem(index);
452
453 if (!shiftOrControlPressed) {
454 m_selectionManager->clearSelection();
455 m_selectionManager->setSelected(index, 1);
456 }
457
458 if (!shiftPressed) {
459 m_selectionManager->beginAnchoredSelection(index);
460 }
461 break;
462 }
463
464 m_view->scrollToItem(index);
465 }
466 return true;
467 }
468
469 void KItemListController::slotChangeCurrentItem(const QString& text, bool searchFromNextItem)
470 {
471 if (!m_model || m_model->count() == 0) {
472 return;
473 }
474 const int currentIndex = m_selectionManager->currentItem();
475 int index;
476 if (searchFromNextItem) {
477 index = m_model->indexForKeyboardSearch(text, (currentIndex + 1) % m_model->count());
478 } else {
479 index = m_model->indexForKeyboardSearch(text, currentIndex);
480 }
481 if (index >= 0) {
482 m_selectionManager->setCurrentItem(index);
483
484 if (m_selectionBehavior != NoSelection) {
485 m_selectionManager->clearSelection();
486 m_selectionManager->setSelected(index, 1);
487 m_selectionManager->beginAnchoredSelection(index);
488 }
489
490 m_view->scrollToItem(index);
491 }
492 }
493
494 void KItemListController::slotAutoActivationTimeout()
495 {
496 if (!m_model || !m_view) {
497 return;
498 }
499
500 const int index = m_autoActivationTimer->property("index").toInt();
501 if (index < 0 || index >= m_model->count()) {
502 return;
503 }
504
505 /* m_view->isUnderMouse() fixes a bug in the Folder-View-Panel and in the
506 * Places-Panel.
507 *
508 * Bug: When you drag a file onto a Folder-View-Item or a Places-Item and
509 * then move away before the auto-activation timeout triggers, than the
510 * item still becomes activated/expanded.
511 *
512 * See Bug 293200 and 305783
513 */
514 if (m_model->supportsDropping(index) && m_view->isUnderMouse()) {
515 if (m_view->supportsItemExpanding() && m_model->isExpandable(index)) {
516 const bool expanded = m_model->isExpanded(index);
517 m_model->setExpanded(index, !expanded);
518 } else if (m_autoActivationBehavior != ExpansionOnly) {
519 emit itemActivated(index);
520 }
521 }
522 }
523
524 bool KItemListController::inputMethodEvent(QInputMethodEvent* event)
525 {
526 Q_UNUSED(event);
527 return false;
528 }
529
530 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
531 {
532 if (!m_view) {
533 return false;
534 }
535
536 m_pressedMousePos = transform.map(event->pos());
537 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
538 emit mouseButtonPressed(m_pressedIndex, event->buttons());
539
540 if (event->buttons() & (Qt::BackButton | Qt::ForwardButton)) {
541 // Do not select items when clicking the back/forward buttons, see
542 // https://bugs.kde.org/show_bug.cgi?id=327412.
543 return true;
544 }
545
546 if (m_view->isAboveExpansionToggle(m_pressedIndex, m_pressedMousePos)) {
547 m_selectionManager->endAnchoredSelection();
548 m_selectionManager->setCurrentItem(m_pressedIndex);
549 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
550 return true;
551 }
552
553 m_selectionTogglePressed = m_view->isAboveSelectionToggle(m_pressedIndex, m_pressedMousePos);
554 if (m_selectionTogglePressed) {
555 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
556 // The previous anchored selection has been finished already in
557 // KItemListSelectionManager::setSelected(). We can safely change
558 // the current item and start a new anchored selection now.
559 m_selectionManager->setCurrentItem(m_pressedIndex);
560 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
561 return true;
562 }
563
564 const bool shiftPressed = event->modifiers() & Qt::ShiftModifier;
565 const bool controlPressed = event->modifiers() & Qt::ControlModifier;
566
567 // The previous selection is cleared if either
568 // 1. The selection mode is SingleSelection, or
569 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
570 // a) Shift or Control are pressed.
571 // b) The clicked item is selected already. In that case, the user might want to:
572 // - start dragging multiple items, or
573 // - open the context menu and perform an action for all selected items.
574 const bool shiftOrControlPressed = shiftPressed || controlPressed;
575 const bool pressedItemAlreadySelected = m_pressedIndex >= 0 && m_selectionManager->isSelected(m_pressedIndex);
576 const bool clearSelection = m_selectionBehavior == SingleSelection ||
577 (!shiftOrControlPressed && !pressedItemAlreadySelected);
578 if (clearSelection) {
579 m_selectionManager->clearSelection();
580 } else if (pressedItemAlreadySelected && !shiftOrControlPressed && (event->buttons() & Qt::LeftButton)) {
581 // The user might want to start dragging multiple items, but if he clicks the item
582 // in order to trigger it instead, the other selected items must be deselected.
583 // However, we do not know yet what the user is going to do.
584 // -> remember that the user pressed an item which had been selected already and
585 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
586 m_clearSelectionIfItemsAreNotDragged = true;
587 }
588
589 if (!shiftPressed) {
590 // Finish the anchored selection before the current index is changed
591 m_selectionManager->endAnchoredSelection();
592 }
593
594 if (m_pressedIndex >= 0) {
595 m_selectionManager->setCurrentItem(m_pressedIndex);
596
597 switch (m_selectionBehavior) {
598 case NoSelection:
599 break;
600
601 case SingleSelection:
602 m_selectionManager->setSelected(m_pressedIndex);
603 break;
604
605 case MultiSelection:
606 if (controlPressed && !shiftPressed) {
607 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
608 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
609 } else if (!shiftPressed || !m_selectionManager->isAnchoredSelectionActive()) {
610 // Select the pressed item and start a new anchored selection
611 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Select);
612 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
613 }
614 break;
615
616 default:
617 Q_ASSERT(false);
618 break;
619 }
620
621 if (event->buttons() & Qt::RightButton) {
622 emit itemContextMenuRequested(m_pressedIndex, event->screenPos());
623 }
624
625 return true;
626 }
627
628 if (event->buttons() & Qt::RightButton) {
629 const QRectF headerBounds = m_view->headerBoundaries();
630 if (headerBounds.contains(event->pos())) {
631 emit headerContextMenuRequested(event->screenPos());
632 } else {
633 emit viewContextMenuRequested(event->screenPos());
634 }
635 return true;
636 }
637
638 if (m_selectionBehavior == MultiSelection) {
639 QPointF startPos = m_pressedMousePos;
640 if (m_view->scrollOrientation() == Qt::Vertical) {
641 startPos.ry() += m_view->scrollOffset();
642 if (m_view->itemSize().width() < 0) {
643 // Use a special rubberband for views that have only one column and
644 // expand the rubberband to use the whole width of the view.
645 startPos.setX(0);
646 }
647 } else {
648 startPos.rx() += m_view->scrollOffset();
649 }
650
651 m_oldSelection = m_selectionManager->selectedItems();
652 KItemListRubberBand* rubberBand = m_view->rubberBand();
653 rubberBand->setStartPosition(startPos);
654 rubberBand->setEndPosition(startPos);
655 rubberBand->setActive(true);
656 connect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged);
657 m_view->setAutoScroll(true);
658 }
659
660 return false;
661 }
662
663 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
664 {
665 if (!m_view) {
666 return false;
667 }
668
669 if (m_pressedIndex >= 0) {
670 // Check whether a dragging should be started
671 if (event->buttons() & Qt::LeftButton) {
672 const QPointF pos = transform.map(event->pos());
673 if ((pos - m_pressedMousePos).manhattanLength() >= QApplication::startDragDistance()) {
674 if (!m_selectionManager->isSelected(m_pressedIndex)) {
675 // Always assure that the dragged item gets selected. Usually this is already
676 // done on the mouse-press event, but when using the selection-toggle on a
677 // selected item the dragged item is not selected yet.
678 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
679 } else {
680 // A selected item has been clicked to drag all selected items
681 // -> the selection should not be cleared when the mouse button is released.
682 m_clearSelectionIfItemsAreNotDragged = false;
683 }
684
685 startDragging();
686 }
687 }
688 } else {
689 KItemListRubberBand* rubberBand = m_view->rubberBand();
690 if (rubberBand->isActive()) {
691 QPointF endPos = transform.map(event->pos());
692
693 // Update the current item.
694 const int newCurrent = m_view->itemAt(endPos);
695 if (newCurrent >= 0) {
696 // It's expected that the new current index is also the new anchor (bug 163451).
697 m_selectionManager->endAnchoredSelection();
698 m_selectionManager->setCurrentItem(newCurrent);
699 m_selectionManager->beginAnchoredSelection(newCurrent);
700 }
701
702 if (m_view->scrollOrientation() == Qt::Vertical) {
703 endPos.ry() += m_view->scrollOffset();
704 if (m_view->itemSize().width() < 0) {
705 // Use a special rubberband for views that have only one column and
706 // expand the rubberband to use the whole width of the view.
707 endPos.setX(m_view->size().width());
708 }
709 } else {
710 endPos.rx() += m_view->scrollOffset();
711 }
712 rubberBand->setEndPosition(endPos);
713 }
714 }
715
716 return false;
717 }
718
719 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
720 {
721 if (!m_view) {
722 return false;
723 }
724
725 emit mouseButtonReleased(m_pressedIndex, event->buttons());
726
727 const bool isAboveSelectionToggle = m_view->isAboveSelectionToggle(m_pressedIndex, m_pressedMousePos);
728 if (isAboveSelectionToggle) {
729 m_selectionTogglePressed = false;
730 return true;
731 }
732
733 if (!isAboveSelectionToggle && m_selectionTogglePressed) {
734 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
735 m_selectionTogglePressed = false;
736 return true;
737 }
738
739 const bool shiftOrControlPressed = event->modifiers() & Qt::ShiftModifier ||
740 event->modifiers() & Qt::ControlModifier;
741
742 KItemListRubberBand* rubberBand = m_view->rubberBand();
743 if (rubberBand->isActive()) {
744 disconnect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged);
745 rubberBand->setActive(false);
746 m_oldSelection.clear();
747 m_view->setAutoScroll(false);
748 }
749
750 const QPointF pos = transform.map(event->pos());
751 const int index = m_view->itemAt(pos);
752
753 if (index >= 0 && index == m_pressedIndex) {
754 // The release event is done above the same item as the press event
755
756 if (m_clearSelectionIfItemsAreNotDragged) {
757 // A selected item has been clicked, but no drag operation has been started
758 // -> clear the rest of the selection.
759 m_selectionManager->clearSelection();
760 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Select);
761 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
762 }
763
764 if (event->button() & Qt::LeftButton) {
765 bool emitItemActivated = true;
766 if (m_view->isAboveExpansionToggle(index, pos)) {
767 const bool expanded = m_model->isExpanded(index);
768 m_model->setExpanded(index, !expanded);
769
770 emit itemExpansionToggleClicked(index);
771 emitItemActivated = false;
772 } else if (shiftOrControlPressed) {
773 // The mouse click should only update the selection, not trigger the item
774 emitItemActivated = false;
775 } else if (!(m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) || m_singleClickActivationEnforced)) {
776 emitItemActivated = false;
777 }
778 if (emitItemActivated) {
779 emit itemActivated(index);
780 }
781 } else if (event->button() & Qt::MidButton) {
782 emit itemMiddleClicked(index);
783 }
784 }
785
786 m_pressedMousePos = QPointF();
787 m_pressedIndex = -1;
788 m_clearSelectionIfItemsAreNotDragged = false;
789 return false;
790 }
791
792 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
793 {
794 const QPointF pos = transform.map(event->pos());
795 const int index = m_view->itemAt(pos);
796
797 // Expand item if desired - See Bug 295573
798 if (m_mouseDoubleClickAction != ActivateItemOnly) {
799 if (m_view && m_model && m_view->supportsItemExpanding() && m_model->isExpandable(index)) {
800 const bool expanded = m_model->isExpanded(index);
801 m_model->setExpanded(index, !expanded);
802 }
803 }
804
805 bool emitItemActivated = !(m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) || m_singleClickActivationEnforced) &&
806 (event->button() & Qt::LeftButton) &&
807 index >= 0 && index < m_model->count();
808 if (emitItemActivated) {
809 emit itemActivated(index);
810 }
811 return false;
812 }
813
814 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
815 {
816 Q_UNUSED(event);
817 Q_UNUSED(transform);
818 return false;
819 }
820
821 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
822 {
823 Q_UNUSED(event);
824 Q_UNUSED(transform);
825
826 m_view->setAutoScroll(false);
827 m_view->hideDropIndicator();
828
829 KItemListWidget* widget = hoveredWidget();
830 if (widget) {
831 widget->setHovered(false);
832 emit itemUnhovered(widget->index());
833 }
834 return false;
835 }
836
837 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
838 {
839 if (!m_model || !m_view) {
840 return false;
841 }
842
843 event->acceptProposedAction();
844
845 KItemListWidget* oldHoveredWidget = hoveredWidget();
846
847 const QPointF pos = transform.map(event->pos());
848 KItemListWidget* newHoveredWidget = widgetForPos(pos);
849
850 if (oldHoveredWidget != newHoveredWidget) {
851 m_autoActivationTimer->stop();
852
853 if (oldHoveredWidget) {
854 oldHoveredWidget->setHovered(false);
855 emit itemUnhovered(oldHoveredWidget->index());
856 }
857 }
858
859 if (newHoveredWidget) {
860 bool droppingBetweenItems = false;
861 if (m_model->sortRole().isEmpty()) {
862 // The model supports inserting items between other items.
863 droppingBetweenItems = (m_view->showDropIndicator(pos) >= 0);
864 }
865
866 const int index = newHoveredWidget->index();
867 if (!droppingBetweenItems) {
868 if (m_model->supportsDropping(index)) {
869 // Something has been dragged on an item.
870 m_view->hideDropIndicator();
871 if (!newHoveredWidget->isHovered()) {
872 newHoveredWidget->setHovered(true);
873 emit itemHovered(index);
874 }
875
876 if (!m_autoActivationTimer->isActive() && m_autoActivationTimer->interval() >= 0) {
877 m_autoActivationTimer->setProperty("index", index);
878 m_autoActivationTimer->start();
879 }
880 }
881 } else {
882 m_autoActivationTimer->stop();
883 if (newHoveredWidget && newHoveredWidget->isHovered()) {
884 newHoveredWidget->setHovered(false);
885 emit itemUnhovered(index);
886 }
887 }
888 } else {
889 m_view->hideDropIndicator();
890 }
891
892 return false;
893 }
894
895 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
896 {
897 if (!m_view) {
898 return false;
899 }
900
901 m_autoActivationTimer->stop();
902 m_view->setAutoScroll(false);
903
904 const QPointF pos = transform.map(event->pos());
905
906 int dropAboveIndex = -1;
907 if (m_model->sortRole().isEmpty()) {
908 // The model supports inserting of items between other items.
909 dropAboveIndex = m_view->showDropIndicator(pos);
910 }
911
912 if (dropAboveIndex >= 0) {
913 // Something has been dropped between two items.
914 m_view->hideDropIndicator();
915 emit aboveItemDropEvent(dropAboveIndex, event);
916 } else {
917 // Something has been dropped on an item or on an empty part of the view.
918 emit itemDropEvent(m_view->itemAt(pos), event);
919 }
920
921 QAccessible::updateAccessibility(view(), 0, QAccessible::DragDropEnd);
922
923 return true;
924 }
925
926 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
927 {
928 Q_UNUSED(event);
929 Q_UNUSED(transform);
930 return false;
931 }
932
933 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
934 {
935 Q_UNUSED(transform);
936 if (!m_model || !m_view) {
937 return false;
938 }
939
940 KItemListWidget* oldHoveredWidget = hoveredWidget();
941 const QPointF pos = transform.map(event->pos());
942 KItemListWidget* newHoveredWidget = widgetForPos(pos);
943
944 if (oldHoveredWidget != newHoveredWidget) {
945 if (oldHoveredWidget) {
946 oldHoveredWidget->setHovered(false);
947 emit itemUnhovered(oldHoveredWidget->index());
948 }
949
950 if (newHoveredWidget) {
951 newHoveredWidget->setHovered(true);
952 const QPointF mappedPos = newHoveredWidget->mapFromItem(m_view, pos);
953 newHoveredWidget->setHoverPosition(mappedPos);
954 emit itemHovered(newHoveredWidget->index());
955 }
956 } else if (oldHoveredWidget) {
957 const QPointF mappedPos = oldHoveredWidget->mapFromItem(m_view, pos);
958 oldHoveredWidget->setHoverPosition(mappedPos);
959 }
960
961 return false;
962 }
963
964 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
965 {
966 Q_UNUSED(event);
967 Q_UNUSED(transform);
968
969 if (!m_model || !m_view) {
970 return false;
971 }
972
973 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
974 if (widget->isHovered()) {
975 widget->setHovered(false);
976 emit itemUnhovered(widget->index());
977 }
978 }
979 return false;
980 }
981
982 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent* event, const QTransform& transform)
983 {
984 Q_UNUSED(event);
985 Q_UNUSED(transform);
986 return false;
987 }
988
989 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent* event, const QTransform& transform)
990 {
991 Q_UNUSED(event);
992 Q_UNUSED(transform);
993 return false;
994 }
995
996 bool KItemListController::processEvent(QEvent* event, const QTransform& transform)
997 {
998 if (!event) {
999 return false;
1000 }
1001
1002 switch (event->type()) {
1003 case QEvent::KeyPress:
1004 return keyPressEvent(static_cast<QKeyEvent*>(event));
1005 case QEvent::InputMethod:
1006 return inputMethodEvent(static_cast<QInputMethodEvent*>(event));
1007 case QEvent::GraphicsSceneMousePress:
1008 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1009 case QEvent::GraphicsSceneMouseMove:
1010 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1011 case QEvent::GraphicsSceneMouseRelease:
1012 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1013 case QEvent::GraphicsSceneMouseDoubleClick:
1014 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1015 case QEvent::GraphicsSceneWheel:
1016 return wheelEvent(static_cast<QGraphicsSceneWheelEvent*>(event), QTransform());
1017 case QEvent::GraphicsSceneDragEnter:
1018 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1019 case QEvent::GraphicsSceneDragLeave:
1020 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1021 case QEvent::GraphicsSceneDragMove:
1022 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1023 case QEvent::GraphicsSceneDrop:
1024 return dropEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1025 case QEvent::GraphicsSceneHoverEnter:
1026 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1027 case QEvent::GraphicsSceneHoverMove:
1028 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1029 case QEvent::GraphicsSceneHoverLeave:
1030 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1031 case QEvent::GraphicsSceneResize:
1032 return resizeEvent(static_cast<QGraphicsSceneResizeEvent*>(event), transform);
1033 default:
1034 break;
1035 }
1036
1037 return false;
1038 }
1039
1040 void KItemListController::slotViewScrollOffsetChanged(qreal current, qreal previous)
1041 {
1042 if (!m_view) {
1043 return;
1044 }
1045
1046 KItemListRubberBand* rubberBand = m_view->rubberBand();
1047 if (rubberBand->isActive()) {
1048 const qreal diff = current - previous;
1049 // TODO: Ideally just QCursor::pos() should be used as
1050 // new end-position but it seems there is no easy way
1051 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1052 // (... or I just missed an easy way to do the mapping)
1053 QPointF endPos = rubberBand->endPosition();
1054 if (m_view->scrollOrientation() == Qt::Vertical) {
1055 endPos.ry() += diff;
1056 } else {
1057 endPos.rx() += diff;
1058 }
1059
1060 rubberBand->setEndPosition(endPos);
1061 }
1062 }
1063
1064 void KItemListController::slotRubberBandChanged()
1065 {
1066 if (!m_view || !m_model || m_model->count() <= 0) {
1067 return;
1068 }
1069
1070 const KItemListRubberBand* rubberBand = m_view->rubberBand();
1071 const QPointF startPos = rubberBand->startPosition();
1072 const QPointF endPos = rubberBand->endPosition();
1073 QRectF rubberBandRect = QRectF(startPos, endPos).normalized();
1074
1075 const bool scrollVertical = (m_view->scrollOrientation() == Qt::Vertical);
1076 if (scrollVertical) {
1077 rubberBandRect.translate(0, -m_view->scrollOffset());
1078 } else {
1079 rubberBandRect.translate(-m_view->scrollOffset(), 0);
1080 }
1081
1082 if (!m_oldSelection.isEmpty()) {
1083 // Clear the old selection that was available before the rubberband has
1084 // been activated in case if no Shift- or Control-key are pressed
1085 const bool shiftOrControlPressed = QApplication::keyboardModifiers() & Qt::ShiftModifier ||
1086 QApplication::keyboardModifiers() & Qt::ControlModifier;
1087 if (!shiftOrControlPressed) {
1088 m_oldSelection.clear();
1089 }
1090 }
1091
1092 KItemSet selectedItems;
1093
1094 // Select all visible items that intersect with the rubberband
1095 foreach (const KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1096 const int index = widget->index();
1097
1098 const QRectF widgetRect = m_view->itemRect(index);
1099 if (widgetRect.intersects(rubberBandRect)) {
1100 const QRectF iconRect = widget->iconRect().translated(widgetRect.topLeft());
1101 const QRectF textRect = widget->textRect().translated(widgetRect.topLeft());
1102 if (iconRect.intersects(rubberBandRect) || textRect.intersects(rubberBandRect)) {
1103 selectedItems.insert(index);
1104 }
1105 }
1106 }
1107
1108 // Select all invisible items that intersect with the rubberband. Instead of
1109 // iterating all items only the area which might be touched by the rubberband
1110 // will be checked.
1111 const bool increaseIndex = scrollVertical ?
1112 startPos.y() > endPos.y(): startPos.x() > endPos.x();
1113
1114 int index = increaseIndex ? m_view->lastVisibleIndex() + 1 : m_view->firstVisibleIndex() - 1;
1115 bool selectionFinished = false;
1116 do {
1117 const QRectF widgetRect = m_view->itemRect(index);
1118 if (widgetRect.intersects(rubberBandRect)) {
1119 selectedItems.insert(index);
1120 }
1121
1122 if (increaseIndex) {
1123 ++index;
1124 selectionFinished = (index >= m_model->count()) ||
1125 ( scrollVertical && widgetRect.top() > rubberBandRect.bottom()) ||
1126 (!scrollVertical && widgetRect.left() > rubberBandRect.right());
1127 } else {
1128 --index;
1129 selectionFinished = (index < 0) ||
1130 ( scrollVertical && widgetRect.bottom() < rubberBandRect.top()) ||
1131 (!scrollVertical && widgetRect.right() < rubberBandRect.left());
1132 }
1133 } while (!selectionFinished);
1134
1135 if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
1136 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1137 // Therefore, the new selection contains:
1138 // 1. All previously selected items which are not inside the rubberband, and
1139 // 2. all items inside the rubberband which have not been selected previously.
1140 m_selectionManager->setSelectedItems(m_oldSelection ^ selectedItems);
1141 }
1142 else {
1143 m_selectionManager->setSelectedItems(selectedItems + m_oldSelection);
1144 }
1145 }
1146
1147 void KItemListController::startDragging()
1148 {
1149 if (!m_view || !m_model) {
1150 return;
1151 }
1152
1153 const KItemSet selectedItems = m_selectionManager->selectedItems();
1154 if (selectedItems.isEmpty()) {
1155 return;
1156 }
1157
1158 QMimeData* data = m_model->createMimeData(selectedItems);
1159 if (!data) {
1160 return;
1161 }
1162
1163 // The created drag object will be owned and deleted
1164 // by QApplication::activeWindow().
1165 QDrag* drag = new QDrag(QApplication::activeWindow());
1166 drag->setMimeData(data);
1167
1168 const QPixmap pixmap = m_view->createDragPixmap(selectedItems);
1169 drag->setPixmap(pixmap);
1170
1171 const QPoint hotSpot(pixmap.width() / 2, 0);
1172 drag->setHotSpot(hotSpot);
1173
1174 drag->exec(Qt::MoveAction | Qt::CopyAction | Qt::LinkAction, Qt::CopyAction);
1175 QAccessible::updateAccessibility(view(), 0, QAccessible::DragDropStart);
1176 }
1177
1178 KItemListWidget* KItemListController::hoveredWidget() const
1179 {
1180 Q_ASSERT(m_view);
1181
1182 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1183 if (widget->isHovered()) {
1184 return widget;
1185 }
1186 }
1187
1188 return 0;
1189 }
1190
1191 KItemListWidget* KItemListController::widgetForPos(const QPointF& pos) const
1192 {
1193 Q_ASSERT(m_view);
1194
1195 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1196 const QPointF mappedPos = widget->mapFromItem(m_view, pos);
1197
1198 const bool hovered = widget->contains(mappedPos) &&
1199 !widget->expansionToggleRect().contains(mappedPos);
1200 if (hovered) {
1201 return widget;
1202 }
1203 }
1204
1205 return 0;
1206 }
1207
1208 void KItemListController::updateKeyboardAnchor()
1209 {
1210 const bool validAnchor = m_keyboardAnchorIndex >= 0 &&
1211 m_keyboardAnchorIndex < m_model->count() &&
1212 keyboardAnchorPos(m_keyboardAnchorIndex) == m_keyboardAnchorPos;
1213 if (!validAnchor) {
1214 const int index = m_selectionManager->currentItem();
1215 m_keyboardAnchorIndex = index;
1216 m_keyboardAnchorPos = keyboardAnchorPos(index);
1217 }
1218 }
1219
1220 int KItemListController::nextRowIndex(int index) const
1221 {
1222 if (m_keyboardAnchorIndex < 0) {
1223 return index;
1224 }
1225
1226 const int maxIndex = m_model->count() - 1;
1227 if (index == maxIndex) {
1228 return index;
1229 }
1230
1231 // Calculate the index of the last column inside the row of the current index
1232 int lastColumnIndex = index;
1233 while (keyboardAnchorPos(lastColumnIndex + 1) > keyboardAnchorPos(lastColumnIndex)) {
1234 ++lastColumnIndex;
1235 if (lastColumnIndex >= maxIndex) {
1236 return index;
1237 }
1238 }
1239
1240 // Based on the last column index go to the next row and calculate the nearest index
1241 // that is below the current index
1242 int nextRowIndex = lastColumnIndex + 1;
1243 int searchIndex = nextRowIndex;
1244 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(nextRowIndex));
1245 while (searchIndex < maxIndex && keyboardAnchorPos(searchIndex + 1) > keyboardAnchorPos(searchIndex)) {
1246 ++searchIndex;
1247 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1248 if (searchDiff < minDiff) {
1249 minDiff = searchDiff;
1250 nextRowIndex = searchIndex;
1251 }
1252 }
1253
1254 return nextRowIndex;
1255 }
1256
1257 int KItemListController::previousRowIndex(int index) const
1258 {
1259 if (m_keyboardAnchorIndex < 0 || index == 0) {
1260 return index;
1261 }
1262
1263 // Calculate the index of the first column inside the row of the current index
1264 int firstColumnIndex = index;
1265 while (keyboardAnchorPos(firstColumnIndex - 1) < keyboardAnchorPos(firstColumnIndex)) {
1266 --firstColumnIndex;
1267 if (firstColumnIndex <= 0) {
1268 return index;
1269 }
1270 }
1271
1272 // Based on the first column index go to the previous row and calculate the nearest index
1273 // that is above the current index
1274 int previousRowIndex = firstColumnIndex - 1;
1275 int searchIndex = previousRowIndex;
1276 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(previousRowIndex));
1277 while (searchIndex > 0 && keyboardAnchorPos(searchIndex - 1) < keyboardAnchorPos(searchIndex)) {
1278 --searchIndex;
1279 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1280 if (searchDiff < minDiff) {
1281 minDiff = searchDiff;
1282 previousRowIndex = searchIndex;
1283 }
1284 }
1285
1286 return previousRowIndex;
1287 }
1288
1289 qreal KItemListController::keyboardAnchorPos(int index) const
1290 {
1291 const QRectF itemRect = m_view->itemRect(index);
1292 if (!itemRect.isEmpty()) {
1293 return (m_view->scrollOrientation() == Qt::Vertical) ? itemRect.x() : itemRect.y();
1294 }
1295
1296 return 0;
1297 }
1298
1299 void KItemListController::updateExtendedSelectionRegion()
1300 {
1301 if (m_view) {
1302 const bool extend = (m_selectionBehavior != MultiSelection);
1303 KItemListStyleOption option = m_view->styleOption();
1304 if (option.extendedSelectionRegion != extend) {
1305 option.extendedSelectionRegion = extend;
1306 m_view->setStyleOption(option);
1307 }
1308 }
1309 }
1310