1 /***************************************************************************
2 * Copyright (C) 2006 by Peter Penz (peter.penz@gmx.at) *
3 * Copyright (C) 2008 by Simon St. James (kdedevel@etotheipiplusone.com) *
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. *
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. *
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 ***************************************************************************/
21 #include "dolphindetailsview.h"
23 #include "dolphinmodel.h"
24 #include "dolphincontroller.h"
25 #include "dolphinfileitemdelegate.h"
26 #include "settings/dolphinsettings.h"
27 #include "dolphinsortfilterproxymodel.h"
28 #include "dolphinviewautoscroller.h"
29 #include "draganddrophelper.h"
30 #include "viewextensionsfactory.h"
31 #include "viewproperties.h"
32 #include "zoomlevelinfo.h"
34 #include "dolphin_detailsmodesettings.h"
35 #include "dolphin_generalsettings.h"
37 #include <kdirmodel.h>
42 #include <QApplication>
43 #include <QHeaderView>
44 #include <QRubberBand>
48 DolphinDetailsView::DolphinDetailsView(QWidget
* parent
,
49 DolphinController
* controller
,
50 DolphinSortFilterProxyModel
* proxyModel
) :
53 m_expandingTogglePressed(false),
55 m_useDefaultIndexAt(true),
56 m_ignoreScrollTo(false),
57 m_controller(controller
),
58 m_extensionsFactory(0),
59 m_expandableFoldersAction(0),
64 const DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
65 Q_ASSERT(settings
!= 0);
66 Q_ASSERT(controller
!= 0);
68 setLayoutDirection(Qt::LeftToRight
);
70 setSortingEnabled(true);
71 setUniformRowHeights(true);
72 setSelectionBehavior(SelectItems
);
73 setDragDropMode(QAbstractItemView::DragDrop
);
74 setDropIndicatorShown(false);
75 setAlternatingRowColors(true);
76 setRootIsDecorated(settings
->expandableFolders());
77 setItemsExpandable(settings
->expandableFolders());
78 setEditTriggers(QAbstractItemView::NoEditTriggers
);
81 setMouseTracking(true);
83 const ViewProperties
props(controller
->url());
84 setSortIndicatorSection(props
.sorting());
85 setSortIndicatorOrder(props
.sortOrder());
87 QHeaderView
* headerView
= header();
88 connect(headerView
, SIGNAL(sectionClicked(int)),
89 this, SLOT(synchronizeSortingState(int)));
90 headerView
->setContextMenuPolicy(Qt::CustomContextMenu
);
91 connect(headerView
, SIGNAL(customContextMenuRequested(const QPoint
&)),
92 this, SLOT(configureSettings(const QPoint
&)));
93 connect(headerView
, SIGNAL(sectionResized(int, int, int)),
94 this, SLOT(slotHeaderSectionResized(int, int, int)));
95 connect(headerView
, SIGNAL(sectionHandleDoubleClicked(int)),
96 this, SLOT(disableAutoResizing()));
98 connect(parent
, SIGNAL(sortingChanged(DolphinView::Sorting
)),
99 this, SLOT(setSortIndicatorSection(DolphinView::Sorting
)));
100 connect(parent
, SIGNAL(sortOrderChanged(Qt::SortOrder
)),
101 this, SLOT(setSortIndicatorOrder(Qt::SortOrder
)));
103 connect(this, SIGNAL(clicked(const QModelIndex
&)),
104 controller
, SLOT(requestTab(const QModelIndex
&)));
105 if (KGlobalSettings::singleClick()) {
106 connect(this, SIGNAL(clicked(const QModelIndex
&)),
107 controller
, SLOT(triggerItem(const QModelIndex
&)));
109 connect(this, SIGNAL(doubleClicked(const QModelIndex
&)),
110 controller
, SLOT(triggerItem(const QModelIndex
&)));
113 connect(this, SIGNAL(entered(const QModelIndex
&)),
114 this, SLOT(slotEntered(const QModelIndex
&)));
115 connect(this, SIGNAL(viewportEntered()),
116 controller
, SLOT(emitViewportEntered()));
117 connect(controller
, SIGNAL(nameFilterChanged(const QString
&)),
118 this, SLOT(setNameFilter(const QString
&)));
119 connect(controller
, SIGNAL(zoomLevelChanged(int)),
120 this, SLOT(setZoomLevel(int)));
121 connect(controller
->dolphinView(), SIGNAL(additionalInfoChanged()),
122 this, SLOT(updateColumnVisibility()));
123 connect(controller
, SIGNAL(activationChanged(bool)),
124 this, SLOT(slotActivationChanged(bool)));
126 if (settings
->useSystemFont()) {
127 m_font
= KGlobalSettings::generalFont();
129 m_font
= QFont(settings
->fontFamily(),
130 settings
->fontSize(),
131 settings
->fontWeight(),
132 settings
->italicFont());
135 setVerticalScrollMode(QTreeView::ScrollPerPixel
);
136 setHorizontalScrollMode(QTreeView::ScrollPerPixel
);
138 const DolphinView
* view
= controller
->dolphinView();
139 connect(view
, SIGNAL(showPreviewChanged()),
140 this, SLOT(slotShowPreviewChanged()));
144 viewport()->installEventFilter(this);
146 connect(KGlobalSettings::self(), SIGNAL(settingsChanged(int)),
147 this, SLOT(slotGlobalSettingsChanged(int)));
149 m_useDefaultIndexAt
= false;
151 m_expandableFoldersAction
= new QAction(i18nc("@option:check", "Expandable Folders"), this);
152 m_expandableFoldersAction
->setCheckable(true);
153 connect(m_expandableFoldersAction
, SIGNAL(toggled(bool)),
154 this, SLOT(setFoldersExpandable(bool)));
156 m_extensionsFactory
= new ViewExtensionsFactory(this, controller
);
157 m_extensionsFactory
->fileItemDelegate()->setMinimizedNameColumn(true);
159 updateDecorationSize(view
->showPreview());
162 DolphinDetailsView::~DolphinDetailsView()
166 bool DolphinDetailsView::event(QEvent
* event
)
168 if (event
->type() == QEvent::Polish
) {
169 header()->setResizeMode(QHeaderView::Interactive
);
170 updateColumnVisibility();
173 return QTreeView::event(event
);
176 QStyleOptionViewItem
DolphinDetailsView::viewOptions() const
178 QStyleOptionViewItem viewOptions
= QTreeView::viewOptions();
179 viewOptions
.font
= m_font
;
180 viewOptions
.showDecorationSelected
= true;
181 viewOptions
.decorationSize
= m_decorationSize
;
185 void DolphinDetailsView::contextMenuEvent(QContextMenuEvent
* event
)
187 QTreeView::contextMenuEvent(event
);
189 DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
190 m_expandableFoldersAction
->setChecked(settings
->expandableFolders());
191 m_controller
->triggerContextMenuRequest(event
->pos(),
192 QList
<QAction
*>() << m_expandableFoldersAction
);
195 void DolphinDetailsView::mousePressEvent(QMouseEvent
* event
)
197 m_controller
->requestActivation();
199 const QModelIndex current
= currentIndex();
200 QTreeView::mousePressEvent(event
);
202 m_expandingTogglePressed
= isAboveExpandingToggle(event
->pos());
204 const QModelIndex index
= indexAt(event
->pos());
205 const bool updateState
= index
.isValid() &&
206 (index
.column() == DolphinModel::Name
) &&
207 (event
->button() == Qt::LeftButton
);
209 setState(QAbstractItemView::DraggingState
);
212 if (!index
.isValid() || (index
.column() != DolphinModel::Name
)) {
213 // the mouse press is done somewhere outside the filename column
214 if (QApplication::mouseButtons() & Qt::MidButton
) {
215 m_controller
->replaceUrlByClipboard();
218 const Qt::KeyboardModifiers mod
= QApplication::keyboardModifiers();
219 if (!m_expandingTogglePressed
&& !(mod
& Qt::ShiftModifier
) && !(mod
& Qt::ControlModifier
)) {
223 // restore the current index, other columns are handled as viewport area.
224 // setCurrentIndex(...) implicitly calls scrollTo(...), which we want to ignore.
225 m_ignoreScrollTo
= true;
226 selectionModel()->setCurrentIndex(current
, QItemSelectionModel::Current
);
227 m_ignoreScrollTo
= false;
229 if ((event
->button() == Qt::LeftButton
) && !m_expandingTogglePressed
) {
230 // Inform Qt about what we are doing - otherwise it starts dragging items around!
231 setState(DragSelectingState
);
233 // Incremental update data will not be useful - start from scratch.
234 m_band
.ignoreOldInfo
= true;
235 const QPoint
scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
236 m_band
.origin
= event
->pos() + scrollPos
;
237 m_band
.destination
= m_band
.origin
;
238 m_band
.originalSelection
= selectionModel()->selection();
243 void DolphinDetailsView::mouseMoveEvent(QMouseEvent
* event
)
245 if (m_expandingTogglePressed
) {
246 // Per default QTreeView starts either a selection or a drag operation when dragging
247 // the expanding toggle button (Qt-issue - see TODO comment in DolphinIconsView::mousePressEvent()).
248 // Turn off this behavior in Dolphin to stay predictable:
249 setState(QAbstractItemView::NoState
);
254 const QPoint mousePos
= event
->pos();
255 const QModelIndex index
= indexAt(mousePos
);
256 if (!index
.isValid()) {
257 // the destination of the selection rectangle is above the viewport. In this
258 // case QTreeView does no selection at all, which is not the wanted behavior
259 // in Dolphin -> select all items within the elastic band rectangle
260 updateElasticBandSelection();
263 // TODO: enable QTreeView::mouseMoveEvent(event) again, as soon
264 // as the Qt-issue #199631 has been fixed.
265 // QTreeView::mouseMoveEvent(event);
266 QAbstractItemView::mouseMoveEvent(event
);
269 // TODO: enable QTreeView::mouseMoveEvent(event) again, as soon
270 // as the Qt-issue #199631 has been fixed.
271 // QTreeView::mouseMoveEvent(event);
272 QAbstractItemView::mouseMoveEvent(event
);
276 void DolphinDetailsView::mouseReleaseEvent(QMouseEvent
* event
)
278 if (!m_expandingTogglePressed
) {
279 const QModelIndex index
= indexAt(event
->pos());
280 if (index
.isValid() && (index
.column() == DolphinModel::Name
)) {
281 QTreeView::mouseReleaseEvent(event
);
283 // don't change the current index if the cursor is released
284 // above any other column than the name column, as the other
285 // columns act as viewport
286 const QModelIndex current
= currentIndex();
287 QTreeView::mouseReleaseEvent(event
);
288 selectionModel()->setCurrentIndex(current
, QItemSelectionModel::Current
);
291 m_expandingTogglePressed
= false;
300 void DolphinDetailsView::startDrag(Qt::DropActions supportedActions
)
302 DragAndDropHelper::instance().startDrag(this, supportedActions
, m_controller
);
306 void DolphinDetailsView::dragEnterEvent(QDragEnterEvent
* event
)
308 if (DragAndDropHelper::instance().isMimeDataSupported(event
->mimeData())) {
309 event
->acceptProposedAction();
318 void DolphinDetailsView::dragLeaveEvent(QDragLeaveEvent
* event
)
320 QTreeView::dragLeaveEvent(event
);
321 setDirtyRegion(m_dropRect
);
324 void DolphinDetailsView::dragMoveEvent(QDragMoveEvent
* event
)
326 QTreeView::dragMoveEvent(event
);
328 // TODO: remove this code when the issue #160611 is solved in Qt 4.4
329 setDirtyRegion(m_dropRect
);
330 const QModelIndex index
= indexAt(event
->pos());
331 if (index
.isValid() && (index
.column() == DolphinModel::Name
)) {
332 const KFileItem item
= m_controller
->itemForIndex(index
);
333 if (!item
.isNull() && item
.isDir()) {
334 m_dropRect
= visualRect(index
);
336 m_dropRect
.setSize(QSize()); // set as invalid
338 setDirtyRegion(m_dropRect
);
341 if (DragAndDropHelper::instance().isMimeDataSupported(event
->mimeData())) {
342 // accept url drops, independently from the destination item
343 event
->acceptProposedAction();
347 void DolphinDetailsView::dropEvent(QDropEvent
* event
)
349 const QModelIndex index
= indexAt(event
->pos());
351 if (index
.isValid() && (index
.column() == DolphinModel::Name
)) {
352 item
= m_controller
->itemForIndex(index
);
354 m_controller
->indicateDroppedUrls(item
, m_controller
->url(), event
);
355 QTreeView::dropEvent(event
);
358 void DolphinDetailsView::paintEvent(QPaintEvent
* event
)
360 QTreeView::paintEvent(event
);
362 // The following code has been taken from QListView
363 // and adapted to DolphinDetailsView.
364 // (C) 1992-2007 Trolltech ASA
365 QStyleOptionRubberBand opt
;
367 opt
.shape
= QRubberBand::Rectangle
;
369 opt
.rect
= elasticBandRect();
371 QPainter
painter(viewport());
373 style()->drawControl(QStyle::CE_RubberBand
, &opt
, &painter
);
378 void DolphinDetailsView::keyPressEvent(QKeyEvent
* event
)
380 // If the Control modifier is pressed, a multiple selection
381 // is done and DolphinDetailsView::currentChanged() may not
382 // not change the selection in a custom way.
383 m_keyPressed
= !(event
->modifiers() & Qt::ControlModifier
);
385 QTreeView::keyPressEvent(event
);
386 m_controller
->handleKeyPressEvent(event
);
389 void DolphinDetailsView::keyReleaseEvent(QKeyEvent
* event
)
391 QTreeView::keyReleaseEvent(event
);
392 m_keyPressed
= false;
395 void DolphinDetailsView::resizeEvent(QResizeEvent
* event
)
397 QTreeView::resizeEvent(event
);
403 void DolphinDetailsView::wheelEvent(QWheelEvent
* event
)
405 // let Ctrl+wheel events propagate to the DolphinView for icon zooming
406 if (event
->modifiers() & Qt::ControlModifier
) {
411 const int height
= m_decorationSize
.height();
412 const int step
= (height
>= KIconLoader::SizeHuge
) ? height
/ 10 : (KIconLoader::SizeHuge
- height
) / 2;
413 verticalScrollBar()->setSingleStep(step
);
414 QTreeView::wheelEvent(event
);
417 void DolphinDetailsView::currentChanged(const QModelIndex
& current
, const QModelIndex
& previous
)
419 QTreeView::currentChanged(current
, previous
);
420 m_extensionsFactory
->handleCurrentIndexChange(current
, previous
);
422 // Stay consistent with QListView: When changing the current index by key presses,
423 // also change the selection.
425 selectionModel()->select(current
, QItemSelectionModel::ClearAndSelect
);
429 bool DolphinDetailsView::eventFilter(QObject
* watched
, QEvent
* event
)
431 if ((watched
== viewport()) && (event
->type() == QEvent::Leave
)) {
432 // if the mouse is above an item and moved very fast outside the widget,
433 // no viewportEntered() signal might be emitted although the mouse has been moved
434 // above the viewport
435 m_controller
->emitViewportEntered();
438 return QTreeView::eventFilter(watched
, event
);
441 QModelIndex
DolphinDetailsView::indexAt(const QPoint
& point
) const
443 // the blank portion of the name column counts as empty space
444 const QModelIndex index
= QTreeView::indexAt(point
);
445 const bool isAboveEmptySpace
= !m_useDefaultIndexAt
&&
446 (index
.column() == KDirModel::Name
) && !nameColumnRect(index
).contains(point
);
447 return isAboveEmptySpace
? QModelIndex() : index
;
450 void DolphinDetailsView::setSelection(const QRect
& rect
, QItemSelectionModel::SelectionFlags command
)
452 // We must override setSelection() as Qt calls it internally and when this happens
453 // we must ensure that the default indexAt() is used.
455 m_useDefaultIndexAt
= true;
456 QTreeView::setSelection(rect
, command
);
457 m_useDefaultIndexAt
= false;
459 // Use our own elastic band selection algorithm
460 updateElasticBandSelection();
464 void DolphinDetailsView::scrollTo(const QModelIndex
& index
, ScrollHint hint
)
466 if (!m_ignoreScrollTo
) {
467 QTreeView::scrollTo(index
, hint
);
471 void DolphinDetailsView::setSortIndicatorSection(DolphinView::Sorting sorting
)
473 header()->setSortIndicator(sorting
, header()->sortIndicatorOrder());
476 void DolphinDetailsView::setSortIndicatorOrder(Qt::SortOrder sortOrder
)
478 header()->setSortIndicator(header()->sortIndicatorSection(), sortOrder
);
481 void DolphinDetailsView::synchronizeSortingState(int column
)
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
);
491 void DolphinDetailsView::slotEntered(const QModelIndex
& index
)
493 if (index
.column() == DolphinModel::Name
) {
494 m_controller
->emitItemEntered(index
);
496 m_controller
->emitViewportEntered();
500 void DolphinDetailsView::updateElasticBand()
503 QRect
dirtyRegion(elasticBandRect());
504 const QPoint
scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
505 m_band
.destination
= viewport()->mapFromGlobal(QCursor::pos()) + scrollPos
;
506 // Going above the (logical) top-left of the view causes complications during selection;
507 // we may as well prevent it.
508 if (m_band
.destination
.y() < 0) {
509 m_band
.destination
.setY(0);
511 if (m_band
.destination
.x() < 0) {
512 m_band
.destination
.setX(0);
514 dirtyRegion
= dirtyRegion
.united(elasticBandRect());
515 setDirtyRegion(dirtyRegion
);
519 QRect
DolphinDetailsView::elasticBandRect() const
521 const QPoint
scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
523 const QPoint topLeft
= m_band
.origin
- scrollPos
;
524 const QPoint bottomRight
= m_band
.destination
- scrollPos
;
525 return QRect(topLeft
, bottomRight
).normalized();
528 void DolphinDetailsView::setNameFilter(const QString
& nameFilter
)
530 DolphinSortFilterProxyModel
* proxyModel
= static_cast<DolphinSortFilterProxyModel
*>(model());
531 proxyModel
->setFilterRegExp(nameFilter
);
534 void DolphinDetailsView::setZoomLevel(int level
)
536 const int size
= ZoomLevelInfo::iconSizeForZoomLevel(level
);
537 DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
539 const bool showPreview
= m_controller
->dolphinView()->showPreview();
541 settings
->setPreviewSize(size
);
543 settings
->setIconSize(size
);
546 updateDecorationSize(showPreview
);
549 void DolphinDetailsView::slotShowPreviewChanged()
551 const DolphinView
* view
= m_controller
->dolphinView();
552 updateDecorationSize(view
->showPreview());
555 void DolphinDetailsView::configureSettings(const QPoint
& pos
)
558 popup
.addTitle(i18nc("@title:menu", "Columns"));
560 // add checkbox items for each column
561 QHeaderView
* headerView
= header();
562 const int columns
= model()->columnCount();
563 for (int i
= 0; i
< columns
; ++i
) {
564 const int logicalIndex
= headerView
->logicalIndex(i
);
565 const QString text
= model()->headerData(logicalIndex
, Qt::Horizontal
).toString();
566 QAction
* action
= popup
.addAction(text
);
567 action
->setCheckable(true);
568 action
->setChecked(!headerView
->isSectionHidden(logicalIndex
));
569 action
->setData(logicalIndex
);
570 action
->setEnabled(logicalIndex
!= DolphinModel::Name
);
572 popup
.addSeparator();
574 QAction
* activatedAction
= popup
.exec(header()->mapToGlobal(pos
));
575 if (activatedAction
!= 0) {
576 const bool show
= activatedAction
->isChecked();
577 const int columnIndex
= activatedAction
->data().toInt();
579 KFileItemDelegate::InformationList list
= m_controller
->dolphinView()->additionalInfo();
580 const KFileItemDelegate::Information info
= infoForColumn(columnIndex
);
582 Q_ASSERT(!list
.contains(info
));
585 Q_ASSERT(list
.contains(info
));
586 const int index
= list
.indexOf(info
);
587 list
.removeAt(index
);
590 m_controller
->indicateAdditionalInfoChange(list
);
591 setColumnHidden(columnIndex
, !show
);
596 void DolphinDetailsView::updateColumnVisibility()
598 QHeaderView
* headerView
= header();
599 disconnect(headerView
, SIGNAL(sectionMoved(int, int, int)),
600 this, SLOT(saveColumnPositions()));
602 const DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
603 const QList
<int> columnPositions
= settings
->columnPositions();
605 const KFileItemDelegate::InformationList list
= m_controller
->dolphinView()->additionalInfo();
606 for (int i
= DolphinModel::Name
; i
<= DolphinModel::Version
; ++i
) {
607 const KFileItemDelegate::Information info
= infoForColumn(i
);
608 const bool hide
= !list
.contains(info
) && (i
!= DolphinModel::Name
);
609 if (isColumnHidden(i
) != hide
) {
610 setColumnHidden(i
, hide
);
613 const int from
= headerView
->visualIndex(i
);
614 headerView
->moveSection(from
, columnPositions
[i
]);
619 connect(headerView
, SIGNAL(sectionMoved(int, int, int)),
620 this, SLOT(saveColumnPositions()));
624 void DolphinDetailsView::saveColumnPositions()
626 QList
<int> columnPositions
;
627 for (int i
= DolphinModel::Name
; i
<= DolphinModel::Version
; ++i
) {
628 columnPositions
.append(header()->visualIndex(i
));
631 DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
632 settings
->setColumnPositions(columnPositions
);
635 void DolphinDetailsView::slotHeaderSectionResized(int logicalIndex
, int oldSize
, int newSize
)
637 Q_UNUSED(logicalIndex
);
640 // If the user changes the size of the headers, the autoresize feature should be
641 // turned off. As there is no dedicated interface to find out whether the header
642 // section has been resized by the user or by a resize event, another approach is used.
643 // Attention: Take care when changing the if-condition to verify that there is no
644 // regression in combination with bug 178630 (see fix in comment #8).
645 if ((QApplication::mouseButtons() & Qt::LeftButton
) && header()->underMouse()) {
646 disableAutoResizing();
650 void DolphinDetailsView::slotActivationChanged(bool active
)
652 setAlternatingRowColors(active
);
655 void DolphinDetailsView::disableAutoResizing()
657 m_autoResize
= false;
660 void DolphinDetailsView::requestActivation()
662 m_controller
->requestActivation();
665 void DolphinDetailsView::slotGlobalSettingsChanged(int category
)
669 const DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
670 Q_ASSERT(settings
!= 0);
671 if (settings
->useSystemFont()) {
672 m_font
= KGlobalSettings::generalFont();
674 //Disconnect then reconnect, since the settings have been changed, the connection requirements may have also.
675 disconnect(this, SIGNAL(clicked(QModelIndex
)), m_controller
, SLOT(triggerItem(QModelIndex
)));
676 disconnect(this, SIGNAL(doubleClicked(QModelIndex
)), m_controller
, SLOT(triggerItem(QModelIndex
)));
677 if (KGlobalSettings::singleClick()) {
678 connect(this, SIGNAL(clicked(QModelIndex
)), m_controller
, SLOT(triggerItem(QModelIndex
)));
680 connect(this, SIGNAL(doubleClicked(QModelIndex
)), m_controller
, SLOT(triggerItem(QModelIndex
)));
684 void DolphinDetailsView::updateElasticBandSelection()
690 // Ensure the elastic band itself is up-to-date, in
691 // case we are being called due to e.g. a drag event.
694 // Clip horizontally to the name column, as some filenames will be
695 // longer than the column. We don't clip vertically as origin
696 // may be above or below the current viewport area.
697 const int nameColumnX
= header()->sectionPosition(DolphinModel::Name
);
698 const int nameColumnWidth
= header()->sectionSize(DolphinModel::Name
);
699 QRect selRect
= elasticBandRect().normalized();
700 QRect
nameColumnArea(nameColumnX
, selRect
.y(), nameColumnWidth
, selRect
.height());
701 selRect
= nameColumnArea
.intersect(selRect
).normalized();
702 // Get the last elastic band rectangle, expressed in viewpoint coordinates.
703 const QPoint
scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
704 QRect oldSelRect
= QRect(m_band
.lastSelectionOrigin
- scrollPos
, m_band
.lastSelectionDestination
- scrollPos
).normalized();
706 if (selRect
.isNull()) {
707 selectionModel()->select(m_band
.originalSelection
, QItemSelectionModel::ClearAndSelect
);
708 m_band
.ignoreOldInfo
= true;
712 if (!m_band
.ignoreOldInfo
) {
713 // Do some quick checks to see if we can rule out the need to
714 // update the selection.
715 Q_ASSERT(uniformRowHeights());
716 QModelIndex dummyIndex
= model()->index(0, 0);
717 if (!dummyIndex
.isValid()) {
718 // No items in the model presumably.
722 // If the elastic band does not cover the same rows as before, we'll
723 // need to re-check, and also invalidate the old item distances.
724 const int rowHeight
= QTreeView::rowHeight(dummyIndex
);
725 const bool coveringSameRows
=
726 (selRect
.top() / rowHeight
== oldSelRect
.top() / rowHeight
) &&
727 (selRect
.bottom() / rowHeight
== oldSelRect
.bottom() / rowHeight
);
728 if (coveringSameRows
) {
729 // Covering the same rows, but have we moved far enough horizontally
730 // that we might have (de)selected some other items?
731 const bool itemSelectionChanged
=
732 ((selRect
.left() > oldSelRect
.left()) &&
733 (selRect
.left() > m_band
.insideNearestLeftEdge
)) ||
734 ((selRect
.left() < oldSelRect
.left()) &&
735 (selRect
.left() <= m_band
.outsideNearestLeftEdge
)) ||
736 ((selRect
.right() < oldSelRect
.right()) &&
737 (selRect
.left() >= m_band
.insideNearestRightEdge
)) ||
738 ((selRect
.right() > oldSelRect
.right()) &&
739 (selRect
.right() >= m_band
.outsideNearestRightEdge
));
741 if (!itemSelectionChanged
) {
747 // This is the only piece of optimization data that needs to be explicitly
749 m_band
.lastSelectionOrigin
= QPoint();
750 m_band
.lastSelectionDestination
= QPoint();
751 oldSelRect
= selRect
;
754 // Do the selection from scratch. Force a update of the horizontal distances info.
755 m_band
.insideNearestLeftEdge
= nameColumnX
+ nameColumnWidth
+ 1;
756 m_band
.insideNearestRightEdge
= nameColumnX
- 1;
757 m_band
.outsideNearestLeftEdge
= nameColumnX
- 1;
758 m_band
.outsideNearestRightEdge
= nameColumnX
+ nameColumnWidth
+ 1;
760 // Include the old selection rect as well, so we can deselect
761 // items that were inside it but not in the new selRect.
762 const QRect boundingRect
= selRect
.united(oldSelRect
).normalized();
763 if (boundingRect
.isNull()) {
767 // Get the index of the item in this row in the name column.
768 // TODO - would this still work if the columns could be re-ordered?
769 QModelIndex startIndex
= QTreeView::indexAt(boundingRect
.topLeft());
770 if (startIndex
.parent().isValid()) {
771 startIndex
= startIndex
.parent().child(startIndex
.row(), KDirModel::Name
);
773 startIndex
= model()->index(startIndex
.row(), KDirModel::Name
);
775 if (!startIndex
.isValid()) {
776 selectionModel()->select(m_band
.originalSelection
, QItemSelectionModel::ClearAndSelect
);
777 m_band
.ignoreOldInfo
= true;
781 // Go through all indexes between the top and bottom of boundingRect, and
782 // update the selection.
783 const int verticalCutoff
= boundingRect
.bottom();
784 QModelIndex currIndex
= startIndex
;
785 QModelIndex lastIndex
;
786 bool allItemsInBoundDone
= false;
788 // Calling selectionModel()->select(...) for each item that needs to be
789 // toggled is slow as each call emits selectionChanged(...) so store them
790 // and do the selection toggle in one batch.
791 QItemSelection itemsToToggle
;
792 // QItemSelection's deal with continuous ranges of indexes better than
793 // single indexes, so try to portion items that need to be toggled into ranges.
794 bool formingToggleIndexRange
= false;
795 QModelIndex toggleIndexRangeBegin
= QModelIndex();
798 QRect currIndexRect
= nameColumnRect(currIndex
);
800 // Update some optimization info as we go.
801 const int cr
= currIndexRect
.right();
802 const int cl
= currIndexRect
.left();
803 const int sl
= selRect
.left();
804 const int sr
= selRect
.right();
805 // "The right edge of the name is outside of the rect but nearer than m_outsideNearestLeft", etc
806 if ((cr
< sl
&& cr
> m_band
.outsideNearestLeftEdge
)) {
807 m_band
.outsideNearestLeftEdge
= cr
;
809 if ((cl
> sr
&& cl
< m_band
.outsideNearestRightEdge
)) {
810 m_band
.outsideNearestRightEdge
= cl
;
812 if ((cl
>= sl
&& cl
<= sr
&& cl
> m_band
.insideNearestRightEdge
)) {
813 m_band
.insideNearestRightEdge
= cl
;
815 if ((cr
>= sl
&& cr
<= sr
&& cr
< m_band
.insideNearestLeftEdge
)) {
816 m_band
.insideNearestLeftEdge
= cr
;
819 bool currentlySelected
= selectionModel()->isSelected(currIndex
);
820 bool originallySelected
= m_band
.originalSelection
.contains(currIndex
);
821 bool intersectsSelectedRect
= currIndexRect
.intersects(selRect
);
822 bool shouldBeSelected
= (intersectsSelectedRect
&& !originallySelected
) || (!intersectsSelectedRect
&& originallySelected
);
823 bool needToToggleItem
= (currentlySelected
&& !shouldBeSelected
) || (!currentlySelected
&& shouldBeSelected
);
824 if (needToToggleItem
&& !formingToggleIndexRange
) {
825 toggleIndexRangeBegin
= currIndex
;
826 formingToggleIndexRange
= true;
829 // NOTE: indexBelow actually walks up and down expanded trees for us.
830 QModelIndex nextIndex
= indexBelow(currIndex
);
831 allItemsInBoundDone
= !nextIndex
.isValid() || currIndexRect
.top() > verticalCutoff
;
833 const bool commitToggleIndexRange
= formingToggleIndexRange
&&
834 (!needToToggleItem
||
835 allItemsInBoundDone
||
836 currIndex
.parent() != toggleIndexRangeBegin
.parent());
837 if (commitToggleIndexRange
) {
838 formingToggleIndexRange
= false;
839 // If this is the last item in the bounds and it is also the beginning of a range,
840 // don't toggle lastIndex - it will already have been dealt with.
841 if (!allItemsInBoundDone
|| toggleIndexRangeBegin
!= currIndex
) {
842 itemsToToggle
.select(toggleIndexRangeBegin
, lastIndex
);
844 // Need to start a new range immediately with currIndex?
845 if (needToToggleItem
) {
846 toggleIndexRangeBegin
= currIndex
;
847 formingToggleIndexRange
= true;
849 if (allItemsInBoundDone
&& needToToggleItem
) {
850 // Toggle the very last item in the bounds.
851 itemsToToggle
.select(currIndex
, currIndex
);
856 lastIndex
= currIndex
;
857 currIndex
= nextIndex
;
858 } while (!allItemsInBoundDone
);
860 selectionModel()->select(itemsToToggle
, QItemSelectionModel::Toggle
);
862 m_band
.lastSelectionOrigin
= m_band
.origin
;
863 m_band
.lastSelectionDestination
= m_band
.destination
;
864 m_band
.ignoreOldInfo
= false;
867 void DolphinDetailsView::setFoldersExpandable(bool expandable
)
870 // collapse all expanded folders, as QTreeView::setItemsExpandable(false)
871 // does not do this task
872 const int rowCount
= model()->rowCount();
873 for (int row
= 0; row
< rowCount
; ++row
) {
874 setExpanded(model()->index(row
, 0), false);
877 DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
878 settings
->setExpandableFolders(expandable
);
879 setRootIsDecorated(expandable
);
880 setItemsExpandable(expandable
);
883 void DolphinDetailsView::updateDecorationSize(bool showPreview
)
885 DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
886 const int iconSize
= showPreview
? settings
->previewSize() : settings
->iconSize();
887 setIconSize(QSize(iconSize
, iconSize
));
888 m_decorationSize
= QSize(iconSize
, iconSize
);
893 KFileItemDelegate::Information
DolphinDetailsView::infoForColumn(int columnIndex
) const
895 KFileItemDelegate::Information info
= KFileItemDelegate::NoInformation
;
897 switch (columnIndex
) {
898 case DolphinModel::Size
: info
= KFileItemDelegate::Size
; break;
899 case DolphinModel::ModifiedTime
: info
= KFileItemDelegate::ModificationTime
; break;
900 case DolphinModel::Permissions
: info
= KFileItemDelegate::Permissions
; break;
901 case DolphinModel::Owner
: info
= KFileItemDelegate::Owner
; break;
902 case DolphinModel::Group
: info
= KFileItemDelegate::OwnerAndGroup
; break;
903 case DolphinModel::Type
: info
= KFileItemDelegate::FriendlyMimeType
; break;
910 void DolphinDetailsView::resizeColumns()
912 // Using the resize mode QHeaderView::ResizeToContents is too slow (it takes
913 // around 3 seconds for each (!) resize operation when having > 10000 items).
914 // This gets a problem especially when opening large directories, where several
915 // resize operations are received for showing the currently available items during
916 // loading (the application hangs around 20 seconds when loading > 10000 items).
918 QHeaderView
* headerView
= header();
919 QFontMetrics
fontMetrics(viewport()->font());
921 int columnWidth
[DolphinModel::Version
+ 1];
922 columnWidth
[DolphinModel::Size
] = fontMetrics
.width("00000 Items");
923 columnWidth
[DolphinModel::ModifiedTime
] = fontMetrics
.width("0000-00-00 00:00");
924 columnWidth
[DolphinModel::Permissions
] = fontMetrics
.width("xxxxxxxxxx");
925 columnWidth
[DolphinModel::Owner
] = fontMetrics
.width("xxxxxxxxxx");
926 columnWidth
[DolphinModel::Group
] = fontMetrics
.width("xxxxxxxxxx");
927 columnWidth
[DolphinModel::Type
] = fontMetrics
.width("XXXX Xxxxxxx");
928 columnWidth
[DolphinModel::Version
] = fontMetrics
.width("xxxxxxxx");
930 int requiredWidth
= 0;
931 for (int i
= KDirModel::Size
; i
<= KDirModel::Type
; ++i
) {
932 if (!isColumnHidden(i
)) {
933 columnWidth
[i
] += 20; // provide a default gap
934 requiredWidth
+= columnWidth
[i
];
935 headerView
->resizeSection(i
, columnWidth
[i
]);
939 // resize the name column in a way that the whole available width is used
940 columnWidth
[KDirModel::Name
] = viewport()->width() - requiredWidth
;
942 const int minNameWidth
= 300;
943 if (columnWidth
[KDirModel::Name
] < minNameWidth
) {
944 columnWidth
[KDirModel::Name
] = minNameWidth
;
946 // It might be possible that the name column width can be
947 // decreased without clipping any text. For performance
948 // reasons the exact necessary width for full visible names is
949 // only checked for up to 200 items:
950 const int rowCount
= model()->rowCount();
951 if (rowCount
> 0 && rowCount
< 200) {
952 const int nameWidth
= sizeHintForColumn(DolphinModel::Name
);
953 if (nameWidth
+ requiredWidth
<= viewport()->width()) {
954 columnWidth
[KDirModel::Name
] = viewport()->width() - requiredWidth
;
955 } else if (nameWidth
< minNameWidth
) {
956 columnWidth
[KDirModel::Name
] = nameWidth
;
961 headerView
->resizeSection(KDirModel::Name
, columnWidth
[KDirModel::Name
]);
964 QRect
DolphinDetailsView::nameColumnRect(const QModelIndex
& index
) const
966 QRect rect
= visualRect(index
);
967 const KFileItem item
= m_controller
->itemForIndex(index
);
968 if (!item
.isNull()) {
969 const int width
= DolphinFileItemDelegate::nameColumnWidth(item
.text(), viewOptions());
970 rect
.setWidth(width
);
976 bool DolphinDetailsView::isAboveExpandingToggle(const QPoint
& pos
) const
978 // QTreeView offers no public API to get the information whether an index has an
979 // expanding toggle and what boundaries the toggle has. The following approach
980 // also assumes a toggle for file items.
981 if (itemsExpandable()) {
982 const QModelIndex index
= QTreeView::indexAt(pos
);
983 if (index
.isValid() && (index
.column() == KDirModel::Name
)) {
984 QRect rect
= nameColumnRect(index
);
985 const int toggleSize
= rect
.height();
986 if (isRightToLeft()) {
987 rect
.moveRight(rect
.right());
989 rect
.moveLeft(rect
.x() - toggleSize
);
991 rect
.setWidth(toggleSize
);
996 rect
= style()->subElementRect(QStyle::SE_TreeViewDisclosureItem
, &opt
, this);
998 return rect
.contains(pos
);
1004 DolphinDetailsView::ElasticBand::ElasticBand() :
1008 lastSelectionOrigin(),
1009 lastSelectionDestination(),
1010 ignoreOldInfo(true),
1011 outsideNearestLeftEdge(0),
1012 outsideNearestRightEdge(0),
1013 insideNearestLeftEdge(0),
1014 insideNearestRightEdge(0)
1018 #include "dolphindetailsview.moc"