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