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