]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistcontroller.cpp
Drag-pixmap fixes
[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 if (m_model->supportsDropping(index)) {
471 if (m_view->supportsItemExpanding() && m_model->isExpandable(index)) {
472 const bool expanded = m_model->isExpanded(index);
473 m_model->setExpanded(index, !expanded);
474 } else {
475 emit itemActivated(index);
476 }
477 }
478 }
479
480 bool KItemListController::inputMethodEvent(QInputMethodEvent* event)
481 {
482 Q_UNUSED(event);
483 return false;
484 }
485
486 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
487 {
488 if (!m_view) {
489 return false;
490 }
491
492 m_pressedMousePos = transform.map(event->pos());
493 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
494 emit mouseButtonPressed(m_pressedIndex, event->buttons());
495
496 if (m_view->isAboveExpansionToggle(m_pressedIndex, m_pressedMousePos)) {
497 m_selectionManager->endAnchoredSelection();
498 m_selectionManager->setCurrentItem(m_pressedIndex);
499 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
500 return true;
501 }
502
503 m_selectionTogglePressed = m_view->isAboveSelectionToggle(m_pressedIndex, m_pressedMousePos);
504 if (m_selectionTogglePressed) {
505 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
506 // The previous anchored selection has been finished already in
507 // KItemListSelectionManager::setSelected(). We can safely change
508 // the current item and start a new anchored selection now.
509 m_selectionManager->setCurrentItem(m_pressedIndex);
510 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
511 return true;
512 }
513
514 const bool shiftPressed = event->modifiers() & Qt::ShiftModifier;
515 const bool controlPressed = event->modifiers() & Qt::ControlModifier;
516
517 // The previous selection is cleared if either
518 // 1. The selection mode is SingleSelection, or
519 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
520 // a) Shift or Control are pressed.
521 // b) The clicked item is selected already. In that case, the user might want to:
522 // - start dragging multiple items, or
523 // - open the context menu and perform an action for all selected items.
524 const bool shiftOrControlPressed = shiftPressed || controlPressed;
525 const bool pressedItemAlreadySelected = m_pressedIndex >= 0 && m_selectionManager->isSelected(m_pressedIndex);
526 const bool clearSelection = m_selectionBehavior == SingleSelection ||
527 (!shiftOrControlPressed && !pressedItemAlreadySelected);
528 if (clearSelection) {
529 m_selectionManager->clearSelection();
530 } else if (pressedItemAlreadySelected && !shiftOrControlPressed && (event->buttons() & Qt::LeftButton)) {
531 // The user might want to start dragging multiple items, but if he clicks the item
532 // in order to trigger it instead, the other selected items must be deselected.
533 // However, we do not know yet what the user is going to do.
534 // -> remember that the user pressed an item which had been selected already and
535 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
536 m_clearSelectionIfItemsAreNotDragged = true;
537 }
538
539 if (!shiftPressed) {
540 // Finish the anchored selection before the current index is changed
541 m_selectionManager->endAnchoredSelection();
542 }
543
544 if (m_pressedIndex >= 0) {
545 m_selectionManager->setCurrentItem(m_pressedIndex);
546
547 switch (m_selectionBehavior) {
548 case NoSelection:
549 break;
550
551 case SingleSelection:
552 m_selectionManager->setSelected(m_pressedIndex);
553 break;
554
555 case MultiSelection:
556 if (controlPressed && !shiftPressed) {
557 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
558 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
559 } else if (!shiftPressed || !m_selectionManager->isAnchoredSelectionActive()) {
560 // Select the pressed item and start a new anchored selection
561 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Select);
562 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
563 }
564 break;
565
566 default:
567 Q_ASSERT(false);
568 break;
569 }
570
571 if (event->buttons() & Qt::RightButton) {
572 emit itemContextMenuRequested(m_pressedIndex, event->screenPos());
573 }
574
575 return true;
576 }
577
578 if (event->buttons() & Qt::RightButton) {
579 const QRectF headerBounds = m_view->headerBoundaries();
580 if (headerBounds.contains(event->pos())) {
581 emit headerContextMenuRequested(event->screenPos());
582 } else {
583 emit viewContextMenuRequested(event->screenPos());
584 }
585 return true;
586 }
587
588 if (m_selectionBehavior == MultiSelection) {
589 QPointF startPos = m_pressedMousePos;
590 if (m_view->scrollOrientation() == Qt::Vertical) {
591 startPos.ry() += m_view->scrollOffset();
592 if (m_view->itemSize().width() < 0) {
593 // Use a special rubberband for views that have only one column and
594 // expand the rubberband to use the whole width of the view.
595 startPos.setX(0);
596 }
597 } else {
598 startPos.rx() += m_view->scrollOffset();
599 }
600
601 m_oldSelection = m_selectionManager->selectedItems();
602 KItemListRubberBand* rubberBand = m_view->rubberBand();
603 rubberBand->setStartPosition(startPos);
604 rubberBand->setEndPosition(startPos);
605 rubberBand->setActive(true);
606 connect(rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandChanged()));
607 m_view->setAutoScroll(true);
608 }
609
610 return false;
611 }
612
613 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
614 {
615 if (!m_view) {
616 return false;
617 }
618
619 if (m_pressedIndex >= 0) {
620 // Check whether a dragging should be started
621 if (event->buttons() & Qt::LeftButton) {
622 const QPointF pos = transform.map(event->pos());
623 if ((pos - m_pressedMousePos).manhattanLength() >= QApplication::startDragDistance()) {
624 if (!m_selectionManager->isSelected(m_pressedIndex)) {
625 // Always assure that the dragged item gets selected. Usually this is already
626 // done on the mouse-press event, but when using the selection-toggle on a
627 // selected item the dragged item is not selected yet.
628 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
629 } else {
630 // A selected item has been clicked to drag all selected items
631 // -> the selection should not be cleared when the mouse button is released.
632 m_clearSelectionIfItemsAreNotDragged = false;
633 }
634
635 startDragging();
636 }
637 }
638 } else {
639 KItemListRubberBand* rubberBand = m_view->rubberBand();
640 if (rubberBand->isActive()) {
641 QPointF endPos = transform.map(event->pos());
642
643 // Update the current item.
644 const int newCurrent = m_view->itemAt(endPos);
645 if (newCurrent >= 0) {
646 // It's expected that the new current index is also the new anchor (bug 163451).
647 m_selectionManager->endAnchoredSelection();
648 m_selectionManager->setCurrentItem(newCurrent);
649 m_selectionManager->beginAnchoredSelection(newCurrent);
650 }
651
652 if (m_view->scrollOrientation() == Qt::Vertical) {
653 endPos.ry() += m_view->scrollOffset();
654 if (m_view->itemSize().width() < 0) {
655 // Use a special rubberband for views that have only one column and
656 // expand the rubberband to use the whole width of the view.
657 endPos.setX(m_view->size().width());
658 }
659 } else {
660 endPos.rx() += m_view->scrollOffset();
661 }
662 rubberBand->setEndPosition(endPos);
663 }
664 }
665
666 return false;
667 }
668
669 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
670 {
671 if (!m_view) {
672 return false;
673 }
674
675 emit mouseButtonReleased(m_pressedIndex, event->buttons());
676
677 const bool isAboveSelectionToggle = m_view->isAboveSelectionToggle(m_pressedIndex, m_pressedMousePos);
678 if (isAboveSelectionToggle) {
679 m_selectionTogglePressed = false;
680 return true;
681 }
682
683 if (!isAboveSelectionToggle && m_selectionTogglePressed) {
684 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
685 m_selectionTogglePressed = false;
686 return true;
687 }
688
689 const bool shiftOrControlPressed = event->modifiers() & Qt::ShiftModifier ||
690 event->modifiers() & Qt::ControlModifier;
691
692 KItemListRubberBand* rubberBand = m_view->rubberBand();
693 if (rubberBand->isActive()) {
694 disconnect(rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandChanged()));
695 rubberBand->setActive(false);
696 m_oldSelection.clear();
697 m_view->setAutoScroll(false);
698 }
699
700 const QPointF pos = transform.map(event->pos());
701 const int index = m_view->itemAt(pos);
702
703 if (index >= 0 && index == m_pressedIndex) {
704 // The release event is done above the same item as the press event
705
706 if (m_clearSelectionIfItemsAreNotDragged) {
707 // A selected item has been clicked, but no drag operation has been started
708 // -> clear the rest of the selection.
709 m_selectionManager->clearSelection();
710 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Select);
711 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
712 }
713
714 if (event->button() & Qt::LeftButton) {
715 bool emitItemActivated = true;
716 if (m_view->isAboveExpansionToggle(index, pos)) {
717 const bool expanded = m_model->isExpanded(index);
718 m_model->setExpanded(index, !expanded);
719
720 emit itemExpansionToggleClicked(index);
721 emitItemActivated = false;
722 } else if (shiftOrControlPressed) {
723 // The mouse click should only update the selection, not trigger the item
724 emitItemActivated = false;
725 } else if (!m_singleClickActivation) {
726 emitItemActivated = false;
727 }
728 if (emitItemActivated) {
729 emit itemActivated(index);
730 }
731 } else if (event->button() & Qt::MidButton) {
732 emit itemMiddleClicked(index);
733 }
734 }
735
736 m_pressedMousePos = QPointF();
737 m_pressedIndex = -1;
738 m_clearSelectionIfItemsAreNotDragged = false;
739 return false;
740 }
741
742 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
743 {
744 const QPointF pos = transform.map(event->pos());
745 const int index = m_view->itemAt(pos);
746
747 bool emitItemActivated = !m_singleClickActivation &&
748 (event->button() & Qt::LeftButton) &&
749 index >= 0 && index < m_model->count();
750 if (emitItemActivated) {
751 emit itemActivated(index);
752 }
753 return false;
754 }
755
756 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
757 {
758 Q_UNUSED(event);
759 Q_UNUSED(transform);
760 return false;
761 }
762
763 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
764 {
765 Q_UNUSED(event);
766 Q_UNUSED(transform);
767
768 m_view->setAutoScroll(false);
769 m_view->hideDropIndicator();
770
771 KItemListWidget* widget = hoveredWidget();
772 if (widget) {
773 widget->setHovered(false);
774 emit itemUnhovered(widget->index());
775 }
776 return false;
777 }
778
779 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
780 {
781 Q_UNUSED(transform);
782 if (!m_model || !m_view) {
783 return false;
784 }
785
786 event->acceptProposedAction();
787
788 KItemListWidget* oldHoveredWidget = hoveredWidget();
789
790 const QPointF pos = transform.map(event->pos());
791 KItemListWidget* newHoveredWidget = widgetForPos(pos);
792
793 if (oldHoveredWidget != newHoveredWidget) {
794 m_autoActivationTimer->stop();
795
796 if (oldHoveredWidget) {
797 oldHoveredWidget->setHovered(false);
798 emit itemUnhovered(oldHoveredWidget->index());
799 }
800
801 if (newHoveredWidget) {
802 const int index = newHoveredWidget->index();
803 if (m_model->supportsDropping(index)) {
804 newHoveredWidget->setHovered(true);
805 } else if (m_model->sortRole().isEmpty()) {
806 // The model supports inserting of items on
807 // the given index. Assure that a drop-indicator
808 // is shown by the view.
809 m_view->showDropIndicator(pos);
810 }
811 emit itemHovered(index);
812
813 if (m_autoActivationTimer->interval() >= 0) {
814 m_autoActivationTimer->setProperty("index", index);
815 m_autoActivationTimer->start();
816 }
817 }
818 }
819
820 return false;
821 }
822
823 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
824 {
825 Q_UNUSED(transform)
826 if (!m_view) {
827 return false;
828 }
829
830 m_autoActivationTimer->stop();
831 m_view->setAutoScroll(false);
832
833 const QPointF pos = transform.map(event->pos());
834 if (m_model->sortRole().isEmpty()) {
835 // The model supports inserting of items on
836 // a given index.
837 const int dropIndex = m_view->showDropIndicator(pos);
838 m_view->hideDropIndicator();
839 emit itemDropEvent(dropIndex, event);
840 } else {
841 emit itemDropEvent(m_view->itemAt(pos), event);
842 }
843
844 return true;
845 }
846
847 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
848 {
849 Q_UNUSED(event);
850 Q_UNUSED(transform);
851 return false;
852 }
853
854 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
855 {
856 Q_UNUSED(transform);
857 if (!m_model || !m_view) {
858 return false;
859 }
860
861 KItemListWidget* oldHoveredWidget = hoveredWidget();
862 const QPointF pos = transform.map(event->pos());
863 KItemListWidget* newHoveredWidget = widgetForPos(pos);
864
865 if (oldHoveredWidget != newHoveredWidget) {
866 if (oldHoveredWidget) {
867 oldHoveredWidget->setHovered(false);
868 emit itemUnhovered(oldHoveredWidget->index());
869 }
870
871 if (newHoveredWidget) {
872 newHoveredWidget->setHovered(true);
873 emit itemHovered(newHoveredWidget->index());
874 }
875 }
876
877 return false;
878 }
879
880 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
881 {
882 Q_UNUSED(event);
883 Q_UNUSED(transform);
884
885 if (!m_model || !m_view) {
886 return false;
887 }
888
889 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
890 if (widget->isHovered()) {
891 widget->setHovered(false);
892 emit itemUnhovered(widget->index());
893 }
894 }
895 return false;
896 }
897
898 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent* event, const QTransform& transform)
899 {
900 Q_UNUSED(event);
901 Q_UNUSED(transform);
902 return false;
903 }
904
905 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent* event, const QTransform& transform)
906 {
907 Q_UNUSED(event);
908 Q_UNUSED(transform);
909 return false;
910 }
911
912 bool KItemListController::processEvent(QEvent* event, const QTransform& transform)
913 {
914 if (!event) {
915 return false;
916 }
917
918 switch (event->type()) {
919 case QEvent::KeyPress:
920 return keyPressEvent(static_cast<QKeyEvent*>(event));
921 case QEvent::InputMethod:
922 return inputMethodEvent(static_cast<QInputMethodEvent*>(event));
923 case QEvent::GraphicsSceneMousePress:
924 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
925 case QEvent::GraphicsSceneMouseMove:
926 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
927 case QEvent::GraphicsSceneMouseRelease:
928 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
929 case QEvent::GraphicsSceneMouseDoubleClick:
930 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
931 case QEvent::GraphicsSceneWheel:
932 return wheelEvent(static_cast<QGraphicsSceneWheelEvent*>(event), QTransform());
933 case QEvent::GraphicsSceneDragEnter:
934 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
935 case QEvent::GraphicsSceneDragLeave:
936 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
937 case QEvent::GraphicsSceneDragMove:
938 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
939 case QEvent::GraphicsSceneDrop:
940 return dropEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
941 case QEvent::GraphicsSceneHoverEnter:
942 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
943 case QEvent::GraphicsSceneHoverMove:
944 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
945 case QEvent::GraphicsSceneHoverLeave:
946 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
947 case QEvent::GraphicsSceneResize:
948 return resizeEvent(static_cast<QGraphicsSceneResizeEvent*>(event), transform);
949 default:
950 break;
951 }
952
953 return false;
954 }
955
956 void KItemListController::slotViewScrollOffsetChanged(qreal current, qreal previous)
957 {
958 if (!m_view) {
959 return;
960 }
961
962 KItemListRubberBand* rubberBand = m_view->rubberBand();
963 if (rubberBand->isActive()) {
964 const qreal diff = current - previous;
965 // TODO: Ideally just QCursor::pos() should be used as
966 // new end-position but it seems there is no easy way
967 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
968 // (... or I just missed an easy way to do the mapping)
969 QPointF endPos = rubberBand->endPosition();
970 if (m_view->scrollOrientation() == Qt::Vertical) {
971 endPos.ry() += diff;
972 } else {
973 endPos.rx() += diff;
974 }
975
976 rubberBand->setEndPosition(endPos);
977 }
978 }
979
980 void KItemListController::slotRubberBandChanged()
981 {
982 if (!m_view || !m_model || m_model->count() <= 0) {
983 return;
984 }
985
986 const KItemListRubberBand* rubberBand = m_view->rubberBand();
987 const QPointF startPos = rubberBand->startPosition();
988 const QPointF endPos = rubberBand->endPosition();
989 QRectF rubberBandRect = QRectF(startPos, endPos).normalized();
990
991 const bool scrollVertical = (m_view->scrollOrientation() == Qt::Vertical);
992 if (scrollVertical) {
993 rubberBandRect.translate(0, -m_view->scrollOffset());
994 } else {
995 rubberBandRect.translate(-m_view->scrollOffset(), 0);
996 }
997
998 if (!m_oldSelection.isEmpty()) {
999 // Clear the old selection that was available before the rubberband has
1000 // been activated in case if no Shift- or Control-key are pressed
1001 const bool shiftOrControlPressed = QApplication::keyboardModifiers() & Qt::ShiftModifier ||
1002 QApplication::keyboardModifiers() & Qt::ControlModifier;
1003 if (!shiftOrControlPressed) {
1004 m_oldSelection.clear();
1005 }
1006 }
1007
1008 QSet<int> selectedItems;
1009
1010 // Select all visible items that intersect with the rubberband
1011 foreach (const KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1012 const int index = widget->index();
1013
1014 const QRectF widgetRect = m_view->itemRect(index);
1015 if (widgetRect.intersects(rubberBandRect)) {
1016 const QRectF iconRect = widget->iconRect().translated(widgetRect.topLeft());
1017 const QRectF textRect = widget->textRect().translated(widgetRect.topLeft());
1018 if (iconRect.intersects(rubberBandRect) || textRect.intersects(rubberBandRect)) {
1019 selectedItems.insert(index);
1020 }
1021 }
1022 }
1023
1024 // Select all invisible items that intersect with the rubberband. Instead of
1025 // iterating all items only the area which might be touched by the rubberband
1026 // will be checked.
1027 const bool increaseIndex = scrollVertical ?
1028 startPos.y() > endPos.y(): startPos.x() > endPos.x();
1029
1030 int index = increaseIndex ? m_view->lastVisibleIndex() + 1 : m_view->firstVisibleIndex() - 1;
1031 bool selectionFinished = false;
1032 do {
1033 const QRectF widgetRect = m_view->itemRect(index);
1034 if (widgetRect.intersects(rubberBandRect)) {
1035 selectedItems.insert(index);
1036 }
1037
1038 if (increaseIndex) {
1039 ++index;
1040 selectionFinished = (index >= m_model->count()) ||
1041 ( scrollVertical && widgetRect.top() > rubberBandRect.bottom()) ||
1042 (!scrollVertical && widgetRect.left() > rubberBandRect.right());
1043 } else {
1044 --index;
1045 selectionFinished = (index < 0) ||
1046 ( scrollVertical && widgetRect.bottom() < rubberBandRect.top()) ||
1047 (!scrollVertical && widgetRect.right() < rubberBandRect.left());
1048 }
1049 } while (!selectionFinished);
1050
1051 if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
1052 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1053 // Therefore, the new selection contains:
1054 // 1. All previously selected items which are not inside the rubberband, and
1055 // 2. all items inside the rubberband which have not been selected previously.
1056 m_selectionManager->setSelectedItems((m_oldSelection - selectedItems) + (selectedItems - m_oldSelection));
1057 }
1058 else {
1059 m_selectionManager->setSelectedItems(selectedItems + m_oldSelection);
1060 }
1061 }
1062
1063 void KItemListController::startDragging()
1064 {
1065 if (!m_view || !m_model) {
1066 return;
1067 }
1068
1069 const QSet<int> selectedItems = m_selectionManager->selectedItems();
1070 if (selectedItems.isEmpty()) {
1071 return;
1072 }
1073
1074 QMimeData* data = m_model->createMimeData(selectedItems);
1075 if (!data) {
1076 return;
1077 }
1078
1079 // The created drag object will be owned and deleted
1080 // by QApplication::activeWindow().
1081 QDrag* drag = new QDrag(QApplication::activeWindow());
1082 drag->setMimeData(data);
1083
1084 const QPixmap pixmap = m_view->createDragPixmap(selectedItems);
1085 drag->setPixmap(pixmap);
1086
1087 const QPoint hotSpot(pixmap.width() / 2, 0);
1088 drag->setHotSpot(hotSpot);
1089
1090 drag->exec(Qt::MoveAction | Qt::CopyAction | Qt::LinkAction, Qt::CopyAction);
1091 }
1092
1093 KItemListWidget* KItemListController::hoveredWidget() const
1094 {
1095 Q_ASSERT(m_view);
1096
1097 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1098 if (widget->isHovered()) {
1099 return widget;
1100 }
1101 }
1102
1103 return 0;
1104 }
1105
1106 KItemListWidget* KItemListController::widgetForPos(const QPointF& pos) const
1107 {
1108 Q_ASSERT(m_view);
1109
1110 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1111 const QPointF mappedPos = widget->mapFromItem(m_view, pos);
1112
1113 const bool hovered = widget->contains(mappedPos) &&
1114 !widget->expansionToggleRect().contains(mappedPos);
1115 if (hovered) {
1116 return widget;
1117 }
1118 }
1119
1120 return 0;
1121 }
1122
1123 void KItemListController::updateKeyboardAnchor()
1124 {
1125 const bool validAnchor = m_keyboardAnchorIndex >= 0 &&
1126 m_keyboardAnchorIndex < m_model->count() &&
1127 keyboardAnchorPos(m_keyboardAnchorIndex) == m_keyboardAnchorPos;
1128 if (!validAnchor) {
1129 const int index = m_selectionManager->currentItem();
1130 m_keyboardAnchorIndex = index;
1131 m_keyboardAnchorPos = keyboardAnchorPos(index);
1132 }
1133 }
1134
1135 int KItemListController::nextRowIndex(int index) const
1136 {
1137 if (m_keyboardAnchorIndex < 0) {
1138 return index;
1139 }
1140
1141 const int maxIndex = m_model->count() - 1;
1142 if (index == maxIndex) {
1143 return index;
1144 }
1145
1146 // Calculate the index of the last column inside the row of the current index
1147 int lastColumnIndex = index;
1148 while (keyboardAnchorPos(lastColumnIndex + 1) > keyboardAnchorPos(lastColumnIndex)) {
1149 ++lastColumnIndex;
1150 if (lastColumnIndex >= maxIndex) {
1151 return index;
1152 }
1153 }
1154
1155 // Based on the last column index go to the next row and calculate the nearest index
1156 // that is below the current index
1157 int nextRowIndex = lastColumnIndex + 1;
1158 int searchIndex = nextRowIndex;
1159 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(nextRowIndex));
1160 while (searchIndex < maxIndex && keyboardAnchorPos(searchIndex + 1) > keyboardAnchorPos(searchIndex)) {
1161 ++searchIndex;
1162 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1163 if (searchDiff < minDiff) {
1164 minDiff = searchDiff;
1165 nextRowIndex = searchIndex;
1166 }
1167 }
1168
1169 return nextRowIndex;
1170 }
1171
1172 int KItemListController::previousRowIndex(int index) const
1173 {
1174 if (m_keyboardAnchorIndex < 0 || index == 0) {
1175 return index;
1176 }
1177
1178 // Calculate the index of the first column inside the row of the current index
1179 int firstColumnIndex = index;
1180 while (keyboardAnchorPos(firstColumnIndex - 1) < keyboardAnchorPos(firstColumnIndex)) {
1181 --firstColumnIndex;
1182 if (firstColumnIndex <= 0) {
1183 return index;
1184 }
1185 }
1186
1187 // Based on the first column index go to the previous row and calculate the nearest index
1188 // that is above the current index
1189 int previousRowIndex = firstColumnIndex - 1;
1190 int searchIndex = previousRowIndex;
1191 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(previousRowIndex));
1192 while (searchIndex > 0 && keyboardAnchorPos(searchIndex - 1) < keyboardAnchorPos(searchIndex)) {
1193 --searchIndex;
1194 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1195 if (searchDiff < minDiff) {
1196 minDiff = searchDiff;
1197 previousRowIndex = searchIndex;
1198 }
1199 }
1200
1201 return previousRowIndex;
1202 }
1203
1204 qreal KItemListController::keyboardAnchorPos(int index) const
1205 {
1206 const QRectF itemRect = m_view->itemRect(index);
1207 if (!itemRect.isEmpty()) {
1208 return (m_view->scrollOrientation() == Qt::Vertical) ? itemRect.x() : itemRect.y();
1209 }
1210
1211 return 0;
1212 }
1213
1214 void KItemListController::updateExtendedSelectionRegion()
1215 {
1216 if (m_view) {
1217 const bool extend = (m_selectionBehavior != MultiSelection);
1218 KItemListStyleOption option = m_view->styleOption();
1219 if (option.extendedSelectionRegion != extend) {
1220 option.extendedSelectionRegion = extend;
1221 m_view->setStyleOption(option);
1222 }
1223 }
1224 }
1225
1226 #include "kitemlistcontroller.moc"