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