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