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