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