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