]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistcontroller.cpp
Fix crash when closing Dolphin during generating previews
[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
762 KItemListWidget* widget = hoveredWidget();
763 if (widget) {
764 widget->setHovered(false);
765 emit itemUnhovered(widget->index());
766 }
767 return false;
768 }
769
770 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
771 {
772 Q_UNUSED(transform);
773 if (!m_model || !m_view) {
774 return false;
775 }
776
777 event->acceptProposedAction();
778
779 KItemListWidget* oldHoveredWidget = hoveredWidget();
780
781 const QPointF pos = transform.map(event->pos());
782 KItemListWidget* newHoveredWidget = widgetForPos(pos);
783
784 if (oldHoveredWidget != newHoveredWidget) {
785 m_autoActivationTimer->stop();
786
787 if (oldHoveredWidget) {
788 oldHoveredWidget->setHovered(false);
789 emit itemUnhovered(oldHoveredWidget->index());
790 }
791
792 if (newHoveredWidget) {
793 const int index = newHoveredWidget->index();
794 if (m_model->supportsDropping(index)) {
795 newHoveredWidget->setHovered(true);
796 }
797 emit itemHovered(index);
798
799 if (m_autoActivationTimer->interval() >= 0) {
800 m_autoActivationTimer->setProperty("index", index);
801 m_autoActivationTimer->start();
802 }
803 }
804 }
805
806 return false;
807 }
808
809 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
810 {
811 Q_UNUSED(transform)
812 if (!m_view) {
813 return false;
814 }
815
816 m_autoActivationTimer->stop();
817 m_view->setAutoScroll(false);
818
819 const QPointF pos = transform.map(event->pos());
820 const int index = m_view->itemAt(pos);
821 emit itemDropEvent(index, event);
822
823 return true;
824 }
825
826 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
827 {
828 Q_UNUSED(event);
829 Q_UNUSED(transform);
830 return false;
831 }
832
833 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
834 {
835 Q_UNUSED(transform);
836 if (!m_model || !m_view) {
837 return false;
838 }
839
840 KItemListWidget* oldHoveredWidget = hoveredWidget();
841 const QPointF pos = transform.map(event->pos());
842 KItemListWidget* newHoveredWidget = widgetForPos(pos);
843
844 if (oldHoveredWidget != newHoveredWidget) {
845 if (oldHoveredWidget) {
846 oldHoveredWidget->setHovered(false);
847 emit itemUnhovered(oldHoveredWidget->index());
848 }
849
850 if (newHoveredWidget) {
851 newHoveredWidget->setHovered(true);
852 emit itemHovered(newHoveredWidget->index());
853 }
854 }
855
856 return false;
857 }
858
859 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
860 {
861 Q_UNUSED(event);
862 Q_UNUSED(transform);
863
864 if (!m_model || !m_view) {
865 return false;
866 }
867
868 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
869 if (widget->isHovered()) {
870 widget->setHovered(false);
871 emit itemUnhovered(widget->index());
872 }
873 }
874 return false;
875 }
876
877 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent* event, const QTransform& transform)
878 {
879 Q_UNUSED(event);
880 Q_UNUSED(transform);
881 return false;
882 }
883
884 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent* event, const QTransform& transform)
885 {
886 Q_UNUSED(event);
887 Q_UNUSED(transform);
888 return false;
889 }
890
891 bool KItemListController::processEvent(QEvent* event, const QTransform& transform)
892 {
893 if (!event) {
894 return false;
895 }
896
897 switch (event->type()) {
898 case QEvent::KeyPress:
899 return keyPressEvent(static_cast<QKeyEvent*>(event));
900 case QEvent::InputMethod:
901 return inputMethodEvent(static_cast<QInputMethodEvent*>(event));
902 case QEvent::GraphicsSceneMousePress:
903 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
904 case QEvent::GraphicsSceneMouseMove:
905 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
906 case QEvent::GraphicsSceneMouseRelease:
907 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
908 case QEvent::GraphicsSceneMouseDoubleClick:
909 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
910 case QEvent::GraphicsSceneWheel:
911 return wheelEvent(static_cast<QGraphicsSceneWheelEvent*>(event), QTransform());
912 case QEvent::GraphicsSceneDragEnter:
913 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
914 case QEvent::GraphicsSceneDragLeave:
915 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
916 case QEvent::GraphicsSceneDragMove:
917 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
918 case QEvent::GraphicsSceneDrop:
919 return dropEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
920 case QEvent::GraphicsSceneHoverEnter:
921 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
922 case QEvent::GraphicsSceneHoverMove:
923 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
924 case QEvent::GraphicsSceneHoverLeave:
925 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
926 case QEvent::GraphicsSceneResize:
927 return resizeEvent(static_cast<QGraphicsSceneResizeEvent*>(event), transform);
928 default:
929 break;
930 }
931
932 return false;
933 }
934
935 void KItemListController::slotViewScrollOffsetChanged(qreal current, qreal previous)
936 {
937 if (!m_view) {
938 return;
939 }
940
941 KItemListRubberBand* rubberBand = m_view->rubberBand();
942 if (rubberBand->isActive()) {
943 const qreal diff = current - previous;
944 // TODO: Ideally just QCursor::pos() should be used as
945 // new end-position but it seems there is no easy way
946 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
947 // (... or I just missed an easy way to do the mapping)
948 QPointF endPos = rubberBand->endPosition();
949 if (m_view->scrollOrientation() == Qt::Vertical) {
950 endPos.ry() += diff;
951 } else {
952 endPos.rx() += diff;
953 }
954
955 rubberBand->setEndPosition(endPos);
956 }
957 }
958
959 void KItemListController::slotRubberBandChanged()
960 {
961 if (!m_view || !m_model || m_model->count() <= 0) {
962 return;
963 }
964
965 const KItemListRubberBand* rubberBand = m_view->rubberBand();
966 const QPointF startPos = rubberBand->startPosition();
967 const QPointF endPos = rubberBand->endPosition();
968 QRectF rubberBandRect = QRectF(startPos, endPos).normalized();
969
970 const bool scrollVertical = (m_view->scrollOrientation() == Qt::Vertical);
971 if (scrollVertical) {
972 rubberBandRect.translate(0, -m_view->scrollOffset());
973 } else {
974 rubberBandRect.translate(-m_view->scrollOffset(), 0);
975 }
976
977 if (!m_oldSelection.isEmpty()) {
978 // Clear the old selection that was available before the rubberband has
979 // been activated in case if no Shift- or Control-key are pressed
980 const bool shiftOrControlPressed = QApplication::keyboardModifiers() & Qt::ShiftModifier ||
981 QApplication::keyboardModifiers() & Qt::ControlModifier;
982 if (!shiftOrControlPressed) {
983 m_oldSelection.clear();
984 }
985 }
986
987 QSet<int> selectedItems;
988
989 // Select all visible items that intersect with the rubberband
990 foreach (const KItemListWidget* widget, m_view->visibleItemListWidgets()) {
991 const int index = widget->index();
992
993 const QRectF widgetRect = m_view->itemRect(index);
994 if (widgetRect.intersects(rubberBandRect)) {
995 const QRectF iconRect = widget->iconRect().translated(widgetRect.topLeft());
996 const QRectF textRect = widget->textRect().translated(widgetRect.topLeft());
997 if (iconRect.intersects(rubberBandRect) || textRect.intersects(rubberBandRect)) {
998 selectedItems.insert(index);
999 }
1000 }
1001 }
1002
1003 // Select all invisible items that intersect with the rubberband. Instead of
1004 // iterating all items only the area which might be touched by the rubberband
1005 // will be checked.
1006 const bool increaseIndex = scrollVertical ?
1007 startPos.y() > endPos.y(): startPos.x() > endPos.x();
1008
1009 int index = increaseIndex ? m_view->lastVisibleIndex() + 1 : m_view->firstVisibleIndex() - 1;
1010 bool selectionFinished = false;
1011 do {
1012 const QRectF widgetRect = m_view->itemRect(index);
1013 if (widgetRect.intersects(rubberBandRect)) {
1014 selectedItems.insert(index);
1015 }
1016
1017 if (increaseIndex) {
1018 ++index;
1019 selectionFinished = (index >= m_model->count()) ||
1020 ( scrollVertical && widgetRect.top() > rubberBandRect.bottom()) ||
1021 (!scrollVertical && widgetRect.left() > rubberBandRect.right());
1022 } else {
1023 --index;
1024 selectionFinished = (index < 0) ||
1025 ( scrollVertical && widgetRect.bottom() < rubberBandRect.top()) ||
1026 (!scrollVertical && widgetRect.right() < rubberBandRect.left());
1027 }
1028 } while (!selectionFinished);
1029
1030 if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
1031 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1032 // Therefore, the new selection contains:
1033 // 1. All previously selected items which are not inside the rubberband, and
1034 // 2. all items inside the rubberband which have not been selected previously.
1035 m_selectionManager->setSelectedItems((m_oldSelection - selectedItems) + (selectedItems - m_oldSelection));
1036 }
1037 else {
1038 m_selectionManager->setSelectedItems(selectedItems + m_oldSelection);
1039 }
1040 }
1041
1042 void KItemListController::startDragging()
1043 {
1044 if (!m_view || !m_model) {
1045 return;
1046 }
1047
1048 const QSet<int> selectedItems = m_selectionManager->selectedItems();
1049 if (selectedItems.isEmpty()) {
1050 return;
1051 }
1052
1053 QMimeData* data = m_model->createMimeData(selectedItems);
1054 if (!data) {
1055 return;
1056 }
1057
1058 // The created drag object will be owned and deleted
1059 // by QApplication::activeWindow().
1060 QDrag* drag = new QDrag(QApplication::activeWindow());
1061 drag->setMimeData(data);
1062
1063 const QPixmap pixmap = m_view->createDragPixmap(selectedItems);
1064 drag->setPixmap(pixmap);
1065
1066 drag->exec(Qt::MoveAction | Qt::CopyAction | Qt::LinkAction, Qt::CopyAction);
1067 }
1068
1069 KItemListWidget* KItemListController::hoveredWidget() const
1070 {
1071 Q_ASSERT(m_view);
1072
1073 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1074 if (widget->isHovered()) {
1075 return widget;
1076 }
1077 }
1078
1079 return 0;
1080 }
1081
1082 KItemListWidget* KItemListController::widgetForPos(const QPointF& pos) const
1083 {
1084 Q_ASSERT(m_view);
1085
1086 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1087 const QPointF mappedPos = widget->mapFromItem(m_view, pos);
1088
1089 const bool hovered = widget->contains(mappedPos) &&
1090 !widget->expansionToggleRect().contains(mappedPos);
1091 if (hovered) {
1092 return widget;
1093 }
1094 }
1095
1096 return 0;
1097 }
1098
1099 void KItemListController::updateKeyboardAnchor()
1100 {
1101 const bool validAnchor = m_keyboardAnchorIndex >= 0 &&
1102 m_keyboardAnchorIndex < m_model->count() &&
1103 keyboardAnchorPos(m_keyboardAnchorIndex) == m_keyboardAnchorPos;
1104 if (!validAnchor) {
1105 const int index = m_selectionManager->currentItem();
1106 m_keyboardAnchorIndex = index;
1107 m_keyboardAnchorPos = keyboardAnchorPos(index);
1108 }
1109 }
1110
1111 int KItemListController::nextRowIndex(int index) const
1112 {
1113 if (m_keyboardAnchorIndex < 0) {
1114 return index;
1115 }
1116
1117 const int maxIndex = m_model->count() - 1;
1118 if (index == maxIndex) {
1119 return index;
1120 }
1121
1122 // Calculate the index of the last column inside the row of the current index
1123 int lastColumnIndex = index;
1124 while (keyboardAnchorPos(lastColumnIndex + 1) > keyboardAnchorPos(lastColumnIndex)) {
1125 ++lastColumnIndex;
1126 if (lastColumnIndex >= maxIndex) {
1127 return index;
1128 }
1129 }
1130
1131 // Based on the last column index go to the next row and calculate the nearest index
1132 // that is below the current index
1133 int nextRowIndex = lastColumnIndex + 1;
1134 int searchIndex = nextRowIndex;
1135 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(nextRowIndex));
1136 while (searchIndex < maxIndex && keyboardAnchorPos(searchIndex + 1) > keyboardAnchorPos(searchIndex)) {
1137 ++searchIndex;
1138 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1139 if (searchDiff < minDiff) {
1140 minDiff = searchDiff;
1141 nextRowIndex = searchIndex;
1142 }
1143 }
1144
1145 return nextRowIndex;
1146 }
1147
1148 int KItemListController::previousRowIndex(int index) const
1149 {
1150 if (m_keyboardAnchorIndex < 0 || index == 0) {
1151 return index;
1152 }
1153
1154 // Calculate the index of the first column inside the row of the current index
1155 int firstColumnIndex = index;
1156 while (keyboardAnchorPos(firstColumnIndex - 1) < keyboardAnchorPos(firstColumnIndex)) {
1157 --firstColumnIndex;
1158 if (firstColumnIndex <= 0) {
1159 return index;
1160 }
1161 }
1162
1163 // Based on the first column index go to the previous row and calculate the nearest index
1164 // that is above the current index
1165 int previousRowIndex = firstColumnIndex - 1;
1166 int searchIndex = previousRowIndex;
1167 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(previousRowIndex));
1168 while (searchIndex > 0 && keyboardAnchorPos(searchIndex - 1) < keyboardAnchorPos(searchIndex)) {
1169 --searchIndex;
1170 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1171 if (searchDiff < minDiff) {
1172 minDiff = searchDiff;
1173 previousRowIndex = searchIndex;
1174 }
1175 }
1176
1177 return previousRowIndex;
1178 }
1179
1180 qreal KItemListController::keyboardAnchorPos(int index) const
1181 {
1182 const QRectF itemRect = m_view->itemRect(index);
1183 if (!itemRect.isEmpty()) {
1184 return (m_view->scrollOrientation() == Qt::Vertical) ? itemRect.x() : itemRect.y();
1185 }
1186
1187 return 0;
1188 }
1189
1190 void KItemListController::updateExtendedSelectionRegion()
1191 {
1192 if (m_view) {
1193 const bool extend = (m_selectionBehavior != MultiSelection);
1194 KItemListStyleOption option = m_view->styleOption();
1195 if (option.extendedSelectionRegion != extend) {
1196 option.extendedSelectionRegion = extend;
1197 m_view->setStyleOption(option);
1198 }
1199 }
1200 }
1201
1202 #include "kitemlistcontroller.moc"