]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphindetailsview.cpp
Essential validity check that fell through the cracks when setSelectionRecursive...
[dolphin.git] / src / dolphindetailsview.cpp
1 /***************************************************************************
2 * Copyright (C) 2006 by Peter Penz (peter.penz@gmx.at) *
3 * Copyright (C) 2008 by Simon St. James (kdedevel@etotheipiplusone.com) *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
19 ***************************************************************************/
20
21 #include "dolphindetailsview.h"
22
23 #include "dolphinmodel.h"
24 #include "dolphincontroller.h"
25 #include "dolphinfileitemdelegate.h"
26 #include "dolphinsettings.h"
27 #include "dolphinsortfilterproxymodel.h"
28 #include "draganddrophelper.h"
29 #include "selectionmanager.h"
30 #include "viewproperties.h"
31 #include "zoomlevelinfo.h"
32
33 #include "dolphin_detailsmodesettings.h"
34 #include "dolphin_generalsettings.h"
35
36 #include <kdirmodel.h>
37 #include <klocale.h>
38 #include <kmenu.h>
39
40 #include <QAbstractProxyModel>
41 #include <QAction>
42 #include <QApplication>
43 #include <QHeaderView>
44 #include <QRubberBand>
45 #include <QPainter>
46 #include <QScrollBar>
47
48 DolphinDetailsView::DolphinDetailsView(QWidget* parent, DolphinController* controller) :
49 QTreeView(parent),
50 m_autoResize(true),
51 m_expandingTogglePressed(false),
52 m_keyPressed(false),
53 m_useDefaultIndexAt(true),
54 m_controller(controller),
55 m_selectionManager(0),
56 m_font(),
57 m_decorationSize(),
58 m_band(),
59 m_ignoreScrollTo(false)
60 {
61 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
62 Q_ASSERT(settings != 0);
63 Q_ASSERT(controller != 0);
64
65 setLayoutDirection(Qt::LeftToRight);
66 setAcceptDrops(true);
67 setSortingEnabled(true);
68 setUniformRowHeights(true);
69 setSelectionBehavior(SelectItems);
70 setDragDropMode(QAbstractItemView::DragDrop);
71 setDropIndicatorShown(false);
72 setAlternatingRowColors(true);
73 setRootIsDecorated(settings->expandableFolders());
74 setItemsExpandable(settings->expandableFolders());
75 setEditTriggers(QAbstractItemView::NoEditTriggers);
76
77 setMouseTracking(true);
78
79 const ViewProperties props(controller->url());
80 setSortIndicatorSection(props.sorting());
81 setSortIndicatorOrder(props.sortOrder());
82
83 QHeaderView* headerView = header();
84 connect(headerView, SIGNAL(sectionClicked(int)),
85 this, SLOT(synchronizeSortingState(int)));
86 headerView->setContextMenuPolicy(Qt::CustomContextMenu);
87 connect(headerView, SIGNAL(customContextMenuRequested(const QPoint&)),
88 this, SLOT(configureColumns(const QPoint&)));
89 connect(headerView, SIGNAL(sectionResized(int, int, int)),
90 this, SLOT(slotHeaderSectionResized(int, int, int)));
91 connect(headerView, SIGNAL(sectionHandleDoubleClicked(int)),
92 this, SLOT(disableAutoResizing()));
93
94 connect(parent, SIGNAL(sortingChanged(DolphinView::Sorting)),
95 this, SLOT(setSortIndicatorSection(DolphinView::Sorting)));
96 connect(parent, SIGNAL(sortOrderChanged(Qt::SortOrder)),
97 this, SLOT(setSortIndicatorOrder(Qt::SortOrder)));
98
99 // TODO: Connecting to the signal 'activated()' is not possible, as kstyle
100 // does not forward the single vs. doubleclick to it yet (KDE 4.1?). Hence it is
101 // necessary connecting the signal 'singleClick()' or 'doubleClick' and to handle the
102 // RETURN-key in keyPressEvent().
103 if (KGlobalSettings::singleClick()) {
104 connect(this, SIGNAL(clicked(const QModelIndex&)),
105 controller, SLOT(triggerItem(const QModelIndex&)));
106 } else {
107 connect(this, SIGNAL(doubleClicked(const QModelIndex&)),
108 controller, SLOT(triggerItem(const QModelIndex&)));
109 }
110
111 if (DolphinSettings::instance().generalSettings()->showSelectionToggle()) {
112 m_selectionManager = new SelectionManager(this);
113 connect(m_selectionManager, SIGNAL(selectionChanged()),
114 this, SLOT(requestActivation()));
115 connect(m_controller, SIGNAL(urlChanged(const KUrl&)),
116 m_selectionManager, SLOT(reset()));
117 }
118
119 connect(this, SIGNAL(entered(const QModelIndex&)),
120 this, SLOT(slotEntered(const QModelIndex&)));
121 connect(this, SIGNAL(viewportEntered()),
122 controller, SLOT(emitViewportEntered()));
123 connect(controller, SIGNAL(zoomLevelChanged(int)),
124 this, SLOT(setZoomLevel(int)));
125 connect(controller->dolphinView(), SIGNAL(additionalInfoChanged()),
126 this, SLOT(updateColumnVisibility()));
127 connect(controller, SIGNAL(activationChanged(bool)),
128 this, SLOT(slotActivationChanged(bool)));
129
130 if (settings->useSystemFont()) {
131 m_font = KGlobalSettings::generalFont();
132 } else {
133 m_font = QFont(settings->fontFamily(),
134 settings->fontSize(),
135 settings->fontWeight(),
136 settings->italicFont());
137 }
138
139 setVerticalScrollMode(QTreeView::ScrollPerPixel);
140 setHorizontalScrollMode(QTreeView::ScrollPerPixel);
141
142 const DolphinView* view = controller->dolphinView();
143 connect(view, SIGNAL(showPreviewChanged()),
144 this, SLOT(slotShowPreviewChanged()));
145
146 updateDecorationSize(view->showPreview());
147
148 setFocus();
149 viewport()->installEventFilter(this);
150
151 connect(KGlobalSettings::self(), SIGNAL(kdisplayFontChanged()),
152 this, SLOT(updateFont()));
153
154 m_useDefaultIndexAt = false;
155 }
156
157 DolphinDetailsView::~DolphinDetailsView()
158 {
159 }
160
161 bool DolphinDetailsView::event(QEvent* event)
162 {
163 if (event->type() == QEvent::Polish) {
164 QHeaderView* headerView = header();
165 headerView->setResizeMode(QHeaderView::Interactive);
166 headerView->setMovable(false);
167
168 updateColumnVisibility();
169
170 hideColumn(DolphinModel::Rating);
171 hideColumn(DolphinModel::Tags);
172 } else if (event->type() == QEvent::UpdateRequest) {
173 // a wheel movement will scroll 4 items
174 if (model()->rowCount() > 0) {
175 verticalScrollBar()->setSingleStep((sizeHintForRow(0) / 3) * 4);
176 }
177 }
178
179 return QTreeView::event(event);
180 }
181
182 QStyleOptionViewItem DolphinDetailsView::viewOptions() const
183 {
184 QStyleOptionViewItem viewOptions = QTreeView::viewOptions();
185 viewOptions.font = m_font;
186 viewOptions.showDecorationSelected = true;
187 viewOptions.decorationSize = m_decorationSize;
188 return viewOptions;
189 }
190
191 void DolphinDetailsView::contextMenuEvent(QContextMenuEvent* event)
192 {
193 QTreeView::contextMenuEvent(event);
194 m_controller->triggerContextMenuRequest(event->pos());
195 }
196
197 void DolphinDetailsView::mousePressEvent(QMouseEvent* event)
198 {
199 m_controller->requestActivation();
200
201 const QModelIndex current = currentIndex();
202 QTreeView::mousePressEvent(event);
203
204 m_expandingTogglePressed = false;
205 const QModelIndex index = indexAt(event->pos());
206 const bool updateState = index.isValid() &&
207 (index.column() == DolphinModel::Name) &&
208 (event->button() == Qt::LeftButton);
209 if (updateState) {
210 // TODO: See comment in DolphinIconsView::mousePressEvent(). Only update
211 // the state if no expanding/collapsing area has been hit:
212 const QRect rect = visualRect(index);
213 if (event->pos().x() >= rect.x() + indentation()) {
214 setState(QAbstractItemView::DraggingState);
215 } else {
216 m_expandingTogglePressed = true;
217 kDebug() << "m_expandingTogglePressed " << m_expandingTogglePressed;
218 }
219 }
220
221 if (!index.isValid() || (index.column() != DolphinModel::Name)) {
222 // the mouse press is done somewhere outside the filename column
223 if (QApplication::mouseButtons() & Qt::MidButton) {
224 m_controller->replaceUrlByClipboard();
225 }
226
227 const Qt::KeyboardModifiers modifier = QApplication::keyboardModifiers();
228 if (!(modifier & Qt::ShiftModifier) && !(modifier & Qt::ControlModifier)) {
229 clearSelection();
230 }
231
232 // restore the current index, other columns are handled as viewport area.
233 // setCurrentIndex(...) implicitly calls scrollTo(...), which we want to ignore.
234 m_ignoreScrollTo = true;
235 selectionModel()->setCurrentIndex(current, QItemSelectionModel::Current);
236 m_ignoreScrollTo = false;
237
238 if ((event->button() == Qt::LeftButton) && !m_expandingTogglePressed) {
239 // Inform Qt about what we are doing - otherwise it starts dragging items around!
240 setState(DragSelectingState);
241 m_band.show = true;
242 // Incremental update data will not be useful - start from scratch.
243 m_band.ignoreOldInfo = true;
244 const QPoint pos = contentsPos();
245 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
246 m_band.origin = event->pos() + pos + scrollPos;
247 m_band.destination = m_band.origin;
248 }
249 }
250 }
251
252 void DolphinDetailsView::mouseMoveEvent(QMouseEvent* event)
253 {
254 if (m_band.show) {
255 const QPoint mousePos = event->pos();
256 const QModelIndex index = indexAt(mousePos);
257 if (!index.isValid()) {
258 // the destination of the selection rectangle is above the viewport. In this
259 // case QTreeView does no selection at all, which is not the wanted behavior
260 // in Dolphin -> select all items within the elastic band rectangle
261 updateElasticBandSelection();
262 }
263
264 // TODO: enable QTreeView::mouseMoveEvent(event) again, as soon
265 // as the Qt-issue #199631 has been fixed.
266 // QTreeView::mouseMoveEvent(event);
267 QAbstractItemView::mouseMoveEvent(event);
268 updateElasticBand();
269 } else {
270 // TODO: enable QTreeView::mouseMoveEvent(event) again, as soon
271 // as the Qt-issue #199631 has been fixed.
272 // QTreeView::mouseMoveEvent(event);
273 QAbstractItemView::mouseMoveEvent(event);
274 }
275
276 if (m_expandingTogglePressed) {
277 // Per default QTreeView starts either a selection or a drag operation when dragging
278 // the expanding toggle button (Qt-issue - see TODO comment in DolphinIconsView::mousePressEvent()).
279 // Turn off this behavior in Dolphin to stay predictable:
280 clearSelection();
281 setState(QAbstractItemView::NoState);
282 }
283 }
284
285 void DolphinDetailsView::mouseReleaseEvent(QMouseEvent* event)
286 {
287 const QModelIndex index = indexAt(event->pos());
288 if (index.isValid() && (index.column() == DolphinModel::Name)) {
289 QTreeView::mouseReleaseEvent(event);
290 } else {
291 // don't change the current index if the cursor is released
292 // above any other column than the name column, as the other
293 // columns act as viewport
294 const QModelIndex current = currentIndex();
295 QTreeView::mouseReleaseEvent(event);
296 selectionModel()->setCurrentIndex(current, QItemSelectionModel::Current);
297 }
298
299 m_expandingTogglePressed = false;
300 if (m_band.show) {
301 setState(NoState);
302 updateElasticBand();
303 m_band.show = false;
304 }
305 }
306
307 void DolphinDetailsView::startDrag(Qt::DropActions supportedActions)
308 {
309 DragAndDropHelper::startDrag(this, supportedActions, m_controller);
310 m_band.show = false;
311 }
312
313 void DolphinDetailsView::dragEnterEvent(QDragEnterEvent* event)
314 {
315 if (DragAndDropHelper::isMimeDataSupported(event->mimeData())) {
316 event->acceptProposedAction();
317 }
318
319 if (m_band.show) {
320 updateElasticBand();
321 m_band.show = false;
322 }
323 }
324
325 void DolphinDetailsView::dragLeaveEvent(QDragLeaveEvent* event)
326 {
327 QTreeView::dragLeaveEvent(event);
328 setDirtyRegion(m_dropRect);
329 }
330
331 void DolphinDetailsView::dragMoveEvent(QDragMoveEvent* event)
332 {
333 QTreeView::dragMoveEvent(event);
334
335 // TODO: remove this code when the issue #160611 is solved in Qt 4.4
336 setDirtyRegion(m_dropRect);
337 const QModelIndex index = indexAt(event->pos());
338 if (index.isValid() && (index.column() == DolphinModel::Name)) {
339 const KFileItem item = m_controller->itemForIndex(index);
340 if (!item.isNull() && item.isDir()) {
341 m_dropRect = visualRect(index);
342 } else {
343 m_dropRect.setSize(QSize()); // set as invalid
344 }
345 setDirtyRegion(m_dropRect);
346 }
347
348 if (DragAndDropHelper::isMimeDataSupported(event->mimeData())) {
349 // accept url drops, independently from the destination item
350 event->acceptProposedAction();
351 }
352 }
353
354 void DolphinDetailsView::dropEvent(QDropEvent* event)
355 {
356 const QModelIndex index = indexAt(event->pos());
357 KFileItem item;
358 if (index.isValid() && (index.column() == DolphinModel::Name)) {
359 item = m_controller->itemForIndex(index);
360 }
361 m_controller->indicateDroppedUrls(item, m_controller->url(), event);
362 QTreeView::dropEvent(event);
363 }
364
365 void DolphinDetailsView::paintEvent(QPaintEvent* event)
366 {
367 QTreeView::paintEvent(event);
368 if (m_band.show) {
369 // The following code has been taken from QListView
370 // and adapted to DolphinDetailsView.
371 // (C) 1992-2007 Trolltech ASA
372 QStyleOptionRubberBand opt;
373 opt.initFrom(this);
374 opt.shape = QRubberBand::Rectangle;
375 opt.opaque = false;
376 opt.rect = elasticBandRect();
377
378 QPainter painter(viewport());
379 painter.save();
380 style()->drawControl(QStyle::CE_RubberBand, &opt, &painter);
381 painter.restore();
382 }
383 }
384
385 void DolphinDetailsView::keyPressEvent(QKeyEvent* event)
386 {
387 // If the Control modifier is pressed, a multiple selection
388 // is done and DolphinDetailsView::currentChanged() may not
389 // not change the selection in a custom way.
390 m_keyPressed = !(event->modifiers() & Qt::ControlModifier);
391
392 QTreeView::keyPressEvent(event);
393 m_controller->handleKeyPressEvent(event);
394 }
395
396 void DolphinDetailsView::keyReleaseEvent(QKeyEvent* event)
397 {
398 QTreeView::keyReleaseEvent(event);
399 m_keyPressed = false;
400 }
401
402 void DolphinDetailsView::resizeEvent(QResizeEvent* event)
403 {
404 if (m_autoResize) {
405 resizeColumns();
406 }
407 QTreeView::resizeEvent(event);
408 }
409
410 void DolphinDetailsView::wheelEvent(QWheelEvent* event)
411 {
412 if (m_selectionManager != 0) {
413 m_selectionManager->reset();
414 }
415
416 // let Ctrl+wheel events propagate to the DolphinView for icon zooming
417 if (event->modifiers() & Qt::ControlModifier) {
418 event->ignore();
419 return;
420 }
421
422 QTreeView::wheelEvent(event);
423 }
424
425 void DolphinDetailsView::currentChanged(const QModelIndex& current, const QModelIndex& previous)
426 {
427 QTreeView::currentChanged(current, previous);
428
429 // Stay consistent with QListView: When changing the current index by key presses,
430 // also change the selection.
431 if (m_keyPressed) {
432 selectionModel()->select(current, QItemSelectionModel::ClearAndSelect);
433 }
434 }
435
436 bool DolphinDetailsView::eventFilter(QObject* watched, QEvent* event)
437 {
438 if ((watched == viewport()) && (event->type() == QEvent::Leave)) {
439 // if the mouse is above an item and moved very fast outside the widget,
440 // no viewportEntered() signal might be emitted although the mouse has been moved
441 // above the viewport
442 m_controller->emitViewportEntered();
443 }
444
445 return QTreeView::eventFilter(watched, event);
446 }
447
448 QModelIndex DolphinDetailsView::indexAt(const QPoint& point) const
449 {
450 // the blank portion of the name column counts as empty space
451 const QModelIndex index = QTreeView::indexAt(point);
452 const bool isAboveEmptySpace = !m_useDefaultIndexAt &&
453 (index.column() == KDirModel::Name) && !nameColumnRect(index).contains(point);
454 return isAboveEmptySpace ? QModelIndex() : index;
455 }
456
457 void DolphinDetailsView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command)
458 {
459 // We must override setSelection() as Qt calls it internally and when this happens
460 // we must ensure that the default indexAt() is used.
461 if (!m_band.show) {
462 m_useDefaultIndexAt = true;
463 QTreeView::setSelection(rect, command);
464 m_useDefaultIndexAt = false;
465 } else {
466
467 // Use our own elastic band selection algorithm
468 updateElasticBandSelection();
469 }
470 }
471
472 void DolphinDetailsView::scrollTo(const QModelIndex & index, ScrollHint hint)
473 {
474 if (m_ignoreScrollTo)
475 return;
476 QTreeView::scrollTo(index, hint);
477 }
478
479 void DolphinDetailsView::setSortIndicatorSection(DolphinView::Sorting sorting)
480 {
481 QHeaderView* headerView = header();
482 headerView->setSortIndicator(sorting, headerView->sortIndicatorOrder());
483 }
484
485 void DolphinDetailsView::setSortIndicatorOrder(Qt::SortOrder sortOrder)
486 {
487 QHeaderView* headerView = header();
488 headerView->setSortIndicator(headerView->sortIndicatorSection(), sortOrder);
489 }
490
491 void DolphinDetailsView::synchronizeSortingState(int column)
492 {
493 // The sorting has already been changed in QTreeView if this slot is
494 // invoked, but Dolphin is not informed about this.
495 DolphinView::Sorting sorting = DolphinSortFilterProxyModel::sortingForColumn(column);
496 const Qt::SortOrder sortOrder = header()->sortIndicatorOrder();
497 m_controller->indicateSortingChange(sorting);
498 m_controller->indicateSortOrderChange(sortOrder);
499 }
500
501 void DolphinDetailsView::slotEntered(const QModelIndex& index)
502 {
503 if (index.column() == DolphinModel::Name) {
504 m_controller->emitItemEntered(index);
505 } else {
506 m_controller->emitViewportEntered();
507 }
508 }
509
510 void DolphinDetailsView::updateElasticBand()
511 {
512 if (m_band.show) {
513 QRect dirtyRegion(elasticBandRect());
514 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
515 m_band.destination = viewport()->mapFromGlobal(QCursor::pos()) + scrollPos;
516 dirtyRegion = dirtyRegion.united(elasticBandRect());
517 setDirtyRegion(dirtyRegion);
518 }
519 }
520
521 QRect DolphinDetailsView::elasticBandRect() const
522 {
523 const QPoint pos(contentsPos());
524 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
525
526 const QPoint topLeft = m_band.origin - pos - scrollPos;
527 const QPoint bottomRight = m_band.destination - pos - scrollPos;
528 return QRect(topLeft, bottomRight).normalized();
529 }
530
531 void DolphinDetailsView::setZoomLevel(int level)
532 {
533 const int size = ZoomLevelInfo::iconSizeForZoomLevel(level);
534 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
535
536 const bool showPreview = m_controller->dolphinView()->showPreview();
537 if (showPreview) {
538 settings->setPreviewSize(size);
539 } else {
540 settings->setIconSize(size);
541 }
542
543 updateDecorationSize(showPreview);
544 }
545
546
547 void DolphinDetailsView::slotShowPreviewChanged()
548 {
549 const DolphinView* view = m_controller->dolphinView();
550 updateDecorationSize(view->showPreview());
551 }
552
553 void DolphinDetailsView::configureColumns(const QPoint& pos)
554 {
555 KMenu popup(this);
556 popup.addTitle(i18nc("@title:menu", "Columns"));
557
558 QHeaderView* headerView = header();
559 for (int i = DolphinModel::Size; i <= DolphinModel::Type; ++i) {
560 const int logicalIndex = headerView->logicalIndex(i);
561 const QString text = model()->headerData(i, Qt::Horizontal).toString();
562 QAction* action = popup.addAction(text);
563 action->setCheckable(true);
564 action->setChecked(!headerView->isSectionHidden(logicalIndex));
565 action->setData(i);
566 }
567
568 QAction* activatedAction = popup.exec(header()->mapToGlobal(pos));
569 if (activatedAction != 0) {
570 const bool show = activatedAction->isChecked();
571 const int columnIndex = activatedAction->data().toInt();
572
573 KFileItemDelegate::InformationList list = m_controller->dolphinView()->additionalInfo();
574 const KFileItemDelegate::Information info = infoForColumn(columnIndex);
575 if (show) {
576 Q_ASSERT(!list.contains(info));
577 list.append(info);
578 } else {
579 Q_ASSERT(list.contains(info));
580 const int index = list.indexOf(info);
581 list.removeAt(index);
582 }
583
584 m_controller->indicateAdditionalInfoChange(list);
585 setColumnHidden(columnIndex, !show);
586 }
587 }
588
589 void DolphinDetailsView::updateColumnVisibility()
590 {
591 const KFileItemDelegate::InformationList list = m_controller->dolphinView()->additionalInfo();
592 for (int i = DolphinModel::Size; i <= DolphinModel::Type; ++i) {
593 const KFileItemDelegate::Information info = infoForColumn(i);
594 const bool hide = !list.contains(info);
595 if (isColumnHidden(i) != hide) {
596 setColumnHidden(i, hide);
597 }
598 }
599
600 resizeColumns();
601 }
602
603 void DolphinDetailsView::slotHeaderSectionResized(int logicalIndex, int oldSize, int newSize)
604 {
605 Q_UNUSED(logicalIndex);
606 Q_UNUSED(oldSize);
607 Q_UNUSED(newSize);
608 if (QApplication::mouseButtons() & Qt::LeftButton) {
609 disableAutoResizing();
610 }
611 }
612
613 void DolphinDetailsView::slotActivationChanged(bool active)
614 {
615 setAlternatingRowColors(active);
616 }
617
618 void DolphinDetailsView::disableAutoResizing()
619 {
620 m_autoResize = false;
621 }
622
623 void DolphinDetailsView::requestActivation()
624 {
625 m_controller->requestActivation();
626 }
627
628 void DolphinDetailsView::updateFont()
629 {
630 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
631 Q_ASSERT(settings != 0);
632
633 if (settings->useSystemFont()) {
634 m_font = KGlobalSettings::generalFont();
635 }
636 }
637
638 void DolphinDetailsView::updateElasticBandSelection()
639 {
640 if (!m_band.show) {
641 return;
642 }
643
644 // Ensure the elastic band itself is up-to-date, in
645 // case we are being called due to e.g. a drag event.
646 updateElasticBand();
647
648 // Clip horizontally to the name column, as some filenames will be
649 // longer than the column. We don't clip vertically as origin
650 // may be above or below the current viewport area.
651 const int nameColumnX = header()->sectionPosition(DolphinModel::Name);
652 const int nameColumnWidth = header()->sectionSize(DolphinModel::Name);
653 QRect selRect = elasticBandRect().normalized();
654 QRect nameColumnRect(nameColumnX, selRect.y(), nameColumnWidth, selRect.height());
655 selRect = nameColumnRect.intersect(selRect).normalized();
656
657 if (selRect.isNull()) {
658 clearSelection();
659 m_band.ignoreOldInfo = true;
660 return;
661 }
662
663 if (!m_band.ignoreOldInfo) {
664 // Do some quick checks to see if we can rule out the need to
665 // update the selection.
666 Q_ASSERT(uniformRowHeights());
667 QModelIndex dummyIndex = model()->index(0, 0);
668 if (!dummyIndex.isValid()) {
669 // No items in the model presumably.
670 return;
671 }
672
673 // If the elastic band does not cover the same rows as before, we'll
674 // need to re-check, and also invalidate the old item distances.
675 const int rowHeight = QTreeView::rowHeight(dummyIndex);
676 const bool coveringSameRows =
677 (selRect.top() / rowHeight == m_band.oldSelectionRect.top() / rowHeight) &&
678 (selRect.bottom() / rowHeight == m_band.oldSelectionRect.bottom() / rowHeight);
679 if (coveringSameRows) {
680 // Covering the same rows, but have we moved far enough horizontally
681 // that we might have (de)selected some other items?
682 const QRect oldSelRect = m_band.oldSelectionRect;
683 const bool itemSelectionChanged =
684 ((selRect.left() > oldSelRect.left()) &&
685 (selRect.left() > m_band.insideNearestLeftEdge)) ||
686 ((selRect.left() < oldSelRect.left()) &&
687 (selRect.left() <= m_band.outsideNearestLeftEdge)) ||
688 ((selRect.right() < oldSelRect.right()) &&
689 (selRect.left() >= m_band.insideNearestRightEdge)) ||
690 ((selRect.right() > oldSelRect.right()) &&
691 (selRect.right() >= m_band.outsideNearestRightEdge));
692
693 if (!itemSelectionChanged) {
694 return;
695 }
696 }
697 }
698
699 // Do the selection from scratch. Force a update of the horizontal distances info.
700 m_band.insideNearestLeftEdge = nameColumnX + nameColumnWidth + 1;
701 m_band.insideNearestRightEdge = nameColumnX - 1;
702 m_band.outsideNearestLeftEdge = nameColumnX - 1;
703 m_band.outsideNearestRightEdge = nameColumnX + nameColumnWidth + 1;
704
705 // Include the old selection rect as well, so we can deselect
706 // items that were inside it but not in the new selRect.
707 const QRect boundingRect = selRect.united(m_band.oldSelectionRect).normalized();
708 if (boundingRect.isNull()) {
709 return;
710 }
711
712 // Get the index of the item in this row in the name column.
713 // TODO - would this still work if the columns could be re-ordered?
714 QModelIndex startIndex = QTreeView::indexAt(boundingRect.topLeft());
715 if (startIndex.parent().isValid()) {
716 startIndex = startIndex.parent().child(startIndex.row(), KDirModel::Name);
717 } else {
718 startIndex = model()->index(startIndex.row(), KDirModel::Name);
719 }
720 if (!startIndex.isValid()) {
721 clearSelection();
722 m_band.ignoreOldInfo = true;
723 return;
724 }
725
726 // Go through all indexes between the top and bottom of boundingRect, and
727 // update the selection.
728 const int verticalCutoff = boundingRect.bottom();
729 QModelIndex currIndex = startIndex;
730 QModelIndex lastIndex;
731 bool allItemsInBoundDone = false;
732
733 // Calling selectionModel()->select(...) for each item that needs to be
734 // toggled is slow as each call emits selectionChanged(...) so store them
735 // and do the selection toggle in one batch.
736 QItemSelection itemsToToggle;
737 // QItemSelection's deal with continuous ranges of indexes better than
738 // single indexes, so try to portion items that need to be toggled into ranges.
739 bool formingToggleIndexRange = false;
740 QModelIndex toggleIndexRangeBegin = QModelIndex();
741
742 do {
743 QRect currIndexRect = visualRect(currIndex);
744 const QString name = m_controller->itemForIndex(currIndex).name();
745 currIndexRect.setWidth(DolphinFileItemDelegate::nameColumnWidth(name, viewOptions()));
746
747 // Update some optimisation info as we go.
748 const int cr = currIndexRect.right();
749 const int cl = currIndexRect.left();
750 const int sl = selRect.left();
751 const int sr = selRect.right();
752 // "The right edge of the name is outside of the rect but nearer than m_outsideNearestLeft", etc
753 if ((cr < sl && cr > m_band.outsideNearestLeftEdge)) {
754 m_band.outsideNearestLeftEdge = cr;
755 }
756 if ((cl > sr && cl < m_band.outsideNearestRightEdge)) {
757 m_band.outsideNearestRightEdge = cl;
758 }
759 if ((cl >= sl && cl <= sr && cl > m_band.insideNearestRightEdge)) {
760 m_band.insideNearestRightEdge = cl;
761 }
762 if ((cr >= sl && cr <= sr && cr < m_band.insideNearestLeftEdge)) {
763 m_band.insideNearestLeftEdge = cr;
764 }
765
766 bool currentlySelected = selectionModel()->isSelected(currIndex);
767 bool intersectsSelectedRect = currIndexRect.intersects(selRect);
768 bool needToToggleItem = (currentlySelected && !intersectsSelectedRect) || (!currentlySelected && intersectsSelectedRect);
769 if (needToToggleItem && !formingToggleIndexRange) {
770 toggleIndexRangeBegin = currIndex;
771 formingToggleIndexRange = true;
772 }
773
774 // NOTE: indexBelow actually walks up and down expanded trees for us.
775 QModelIndex nextIndex = indexBelow(currIndex);
776 allItemsInBoundDone = !nextIndex.isValid() || currIndexRect.top() > verticalCutoff;
777
778 const bool commitToggleIndexRange = formingToggleIndexRange &&
779 (!needToToggleItem ||
780 allItemsInBoundDone ||
781 currIndex.parent() != toggleIndexRangeBegin.parent());
782 if (commitToggleIndexRange) {
783 itemsToToggle.select(toggleIndexRangeBegin, lastIndex );
784 // Immediately start a new range with currIndex?
785 if (needToToggleItem) {
786 toggleIndexRangeBegin = currIndex;
787 }
788 formingToggleIndexRange = needToToggleItem;
789 }
790
791 // next item
792 lastIndex = currIndex;
793 currIndex = nextIndex;
794 } while (!allItemsInBoundDone);
795
796 selectionModel()->select(itemsToToggle, QItemSelectionModel::Toggle);
797
798 m_band.oldSelectionRect = selRect;
799 m_band.ignoreOldInfo = false;
800 }
801
802 void DolphinDetailsView::updateDecorationSize(bool showPreview)
803 {
804 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
805 const int iconSize = showPreview ? settings->previewSize() : settings->iconSize();
806 setIconSize(QSize(iconSize, iconSize));
807 m_decorationSize = QSize(iconSize, iconSize);
808
809 if (m_selectionManager != 0) {
810 m_selectionManager->reset();
811 }
812
813 doItemsLayout();
814 }
815
816 QPoint DolphinDetailsView::contentsPos() const
817 {
818 // implementation note: the horizonal position is ignored currently, as no
819 // horizontal scrolling is done anyway during a selection
820 const QScrollBar* scrollbar = verticalScrollBar();
821 Q_ASSERT(scrollbar != 0);
822
823 const int maxHeight = maximumViewportSize().height();
824 const int height = scrollbar->maximum() - scrollbar->minimum() + 1;
825 const int visibleHeight = model()->rowCount() + 1 - height;
826 if (visibleHeight <= 0) {
827 return QPoint(0, 0);
828 }
829
830 const int y = scrollbar->sliderPosition() * maxHeight / visibleHeight;
831 return QPoint(0, y);
832 }
833
834 KFileItemDelegate::Information DolphinDetailsView::infoForColumn(int columnIndex) const
835 {
836 KFileItemDelegate::Information info = KFileItemDelegate::NoInformation;
837
838 switch (columnIndex) {
839 case DolphinModel::Size: info = KFileItemDelegate::Size; break;
840 case DolphinModel::ModifiedTime: info = KFileItemDelegate::ModificationTime; break;
841 case DolphinModel::Permissions: info = KFileItemDelegate::Permissions; break;
842 case DolphinModel::Owner: info = KFileItemDelegate::Owner; break;
843 case DolphinModel::Group: info = KFileItemDelegate::OwnerAndGroup; break;
844 case DolphinModel::Type: info = KFileItemDelegate::FriendlyMimeType; break;
845 default: break;
846 }
847
848 return info;
849 }
850
851 void DolphinDetailsView::resizeColumns()
852 {
853 // Using the resize mode QHeaderView::ResizeToContents is too slow (it takes
854 // around 3 seconds for each (!) resize operation when having > 10000 items).
855 // This gets a problem especially when opening large directories, where several
856 // resize operations are received for showing the currently available items during
857 // loading (the application hangs around 20 seconds when loading > 10000 items).
858
859 QHeaderView* headerView = header();
860 QFontMetrics fontMetrics(viewport()->font());
861
862 int columnWidth[KDirModel::ColumnCount];
863 columnWidth[KDirModel::Size] = fontMetrics.width("00000 Items");
864 columnWidth[KDirModel::ModifiedTime] = fontMetrics.width("0000-00-00 00:00");
865 columnWidth[KDirModel::Permissions] = fontMetrics.width("xxxxxxxxxx");
866 columnWidth[KDirModel::Owner] = fontMetrics.width("xxxxxxxxxx");
867 columnWidth[KDirModel::Group] = fontMetrics.width("xxxxxxxxxx");
868 columnWidth[KDirModel::Type] = fontMetrics.width("XXXX Xxxxxxx");
869
870 int requiredWidth = 0;
871 for (int i = KDirModel::Size; i <= KDirModel::Type; ++i) {
872 if (!isColumnHidden(i)) {
873 columnWidth[i] += 20; // provide a default gap
874 requiredWidth += columnWidth[i];
875 headerView->resizeSection(i, columnWidth[i]);
876 }
877 }
878
879 // resize the name column in a way that the whole available width is used
880 columnWidth[KDirModel::Name] = viewport()->width() - requiredWidth;
881 if (columnWidth[KDirModel::Name] < 120) {
882 columnWidth[KDirModel::Name] = 120;
883 }
884 headerView->resizeSection(KDirModel::Name, columnWidth[KDirModel::Name]);
885 }
886
887 QRect DolphinDetailsView::nameColumnRect(const QModelIndex& index) const
888 {
889 QRect rect = visualRect(index);
890 const KFileItem item = m_controller->itemForIndex(index);
891 if (!item.isNull()) {
892 const int width = DolphinFileItemDelegate::nameColumnWidth(item.name(), viewOptions());
893 rect.setWidth(width);
894 }
895
896 return rect;
897 }
898
899 DolphinDetailsView::ElasticBand::ElasticBand() :
900 show(false),
901 origin(),
902 destination(),
903 oldSelectionRect(),
904 ignoreOldInfo(true),
905 outsideNearestLeftEdge(0),
906 outsideNearestRightEdge(0),
907 insideNearestLeftEdge(0),
908 insideNearestRightEdge(0)
909 {
910 }
911
912 #include "dolphindetailsview.moc"