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 "additionalinfoaccessor.h"
24 #include "dolphinmodel.h"
25 #include "dolphinviewcontroller.h"
26 #include "dolphinfileitemdelegate.h"
27 #include "settings/dolphinsettings.h"
28 #include "dolphinsortfilterproxymodel.h"
29 #include "dolphinviewautoscroller.h"
30 #include "draganddrophelper.h"
31 #include "viewextensionsfactory.h"
32 #include "viewmodecontroller.h"
33 #include "viewproperties.h"
34 #include "zoomlevelinfo.h"
36 #include "dolphin_detailsmodesettings.h"
37 #include "dolphin_generalsettings.h"
39 #include <kdirmodel.h>
44 #include <QApplication>
45 #include <QHeaderView>
46 #include <QRubberBand>
50 DolphinDetailsView::DolphinDetailsView(QWidget
* parent
,
51 DolphinViewController
* dolphinViewController
,
52 const ViewModeController
* viewModeController
,
53 DolphinSortFilterProxyModel
* proxyModel
) :
56 m_expandingTogglePressed(false),
58 m_useDefaultIndexAt(true),
59 m_ignoreScrollTo(false),
60 m_dolphinViewController(dolphinViewController
),
61 m_viewModeController(viewModeController
),
62 m_extensionsFactory(0),
63 m_expandableFoldersAction(0),
69 const DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
70 Q_ASSERT(settings
!= 0);
71 Q_ASSERT(dolphinViewController
!= 0);
72 Q_ASSERT(viewModeController
!= 0);
74 setLayoutDirection(Qt::LeftToRight
);
76 setSortingEnabled(true);
77 setUniformRowHeights(true);
78 setSelectionBehavior(SelectItems
);
79 setDragDropMode(QAbstractItemView::DragDrop
);
80 setDropIndicatorShown(false);
81 setAlternatingRowColors(true);
82 setRootIsDecorated(settings
->expandableFolders());
83 setItemsExpandable(settings
->expandableFolders());
84 setEditTriggers(QAbstractItemView::NoEditTriggers
);
87 setMouseTracking(true);
89 const ViewProperties
props(viewModeController
->url());
90 setSortIndicatorSection(props
.sorting());
91 setSortIndicatorOrder(props
.sortOrder());
93 QHeaderView
* headerView
= header();
94 connect(headerView
, SIGNAL(sectionClicked(int)),
95 this, SLOT(synchronizeSortingState(int)));
96 headerView
->setContextMenuPolicy(Qt::CustomContextMenu
);
97 connect(headerView
, SIGNAL(customContextMenuRequested(const QPoint
&)),
98 this, SLOT(configureSettings(const QPoint
&)));
99 connect(headerView
, SIGNAL(sectionResized(int, int, int)),
100 this, SLOT(slotHeaderSectionResized(int, int, int)));
101 connect(headerView
, SIGNAL(sectionHandleDoubleClicked(int)),
102 this, SLOT(disableAutoResizing()));
104 connect(parent
, SIGNAL(sortingChanged(DolphinView::Sorting
)),
105 this, SLOT(setSortIndicatorSection(DolphinView::Sorting
)));
106 connect(parent
, SIGNAL(sortOrderChanged(Qt::SortOrder
)),
107 this, SLOT(setSortIndicatorOrder(Qt::SortOrder
)));
109 connect(this, SIGNAL(clicked(const QModelIndex
&)),
110 dolphinViewController
, SLOT(requestTab(const QModelIndex
&)));
111 if (KGlobalSettings::singleClick()) {
112 connect(this, SIGNAL(clicked(const QModelIndex
&)),
113 dolphinViewController
, SLOT(triggerItem(const QModelIndex
&)));
115 connect(this, SIGNAL(doubleClicked(const QModelIndex
&)),
116 dolphinViewController
, SLOT(triggerItem(const QModelIndex
&)));
119 connect(this, SIGNAL(entered(const QModelIndex
&)),
120 this, SLOT(slotEntered(const QModelIndex
&)));
121 connect(this, SIGNAL(viewportEntered()),
122 dolphinViewController
, SLOT(emitViewportEntered()));
123 connect(viewModeController
, SIGNAL(zoomLevelChanged(int)),
124 this, SLOT(setZoomLevel(int)));
125 connect(dolphinViewController
->view(), SIGNAL(additionalInfoChanged()),
126 this, SLOT(updateColumnVisibility()));
127 connect(viewModeController
, SIGNAL(activationChanged(bool)),
128 this, SLOT(slotActivationChanged(bool)));
130 if (settings
->useSystemFont()) {
131 m_font
= KGlobalSettings::generalFont();
133 m_font
= QFont(settings
->fontFamily(),
134 qRound(settings
->fontSize()),
135 settings
->fontWeight(),
136 settings
->italicFont());
137 m_font
.setPointSizeF(settings
->fontSize());
140 setVerticalScrollMode(QTreeView::ScrollPerPixel
);
141 setHorizontalScrollMode(QTreeView::ScrollPerPixel
);
143 const DolphinView
* view
= dolphinViewController
->view();
144 connect(view
, SIGNAL(showPreviewChanged()),
145 this, SLOT(slotShowPreviewChanged()));
149 viewport()->installEventFilter(this);
151 connect(KGlobalSettings::self(), SIGNAL(settingsChanged(int)),
152 this, SLOT(slotGlobalSettingsChanged(int)));
154 m_useDefaultIndexAt
= false;
156 m_expandableFoldersAction
= new QAction(i18nc("@option:check", "Expandable Folders"), this);
157 m_expandableFoldersAction
->setCheckable(true);
158 connect(m_expandableFoldersAction
, SIGNAL(toggled(bool)),
159 this, SLOT(setFoldersExpandable(bool)));
161 connect(this, SIGNAL(expanded(const QModelIndex
&)), this, SLOT(slotExpanded(const QModelIndex
&)));
162 connect(this, SIGNAL(collapsed(const QModelIndex
&)), this, SLOT(slotCollapsed(const QModelIndex
&)));
164 updateDecorationSize(view
->showPreview());
166 m_extensionsFactory
= new ViewExtensionsFactory(this, dolphinViewController
, viewModeController
);
167 m_extensionsFactory
->fileItemDelegate()->setMinimizedNameColumn(true);
168 m_extensionsFactory
->setAutoFolderExpandingEnabled(settings
->expandableFolders());
171 DolphinDetailsView::~DolphinDetailsView()
175 QSet
<KUrl
> DolphinDetailsView::expandedUrls() const
177 return m_expandedUrls
;
180 QRegion
DolphinDetailsView::visualRegionForSelection(const QItemSelection
& selection
) const
182 // We have to make sure that the visualRect of each model index is inside the region.
183 // QTreeView::visualRegionForSelection does not do it right because it assumes implicitly
184 // that all visualRects have the same width, which is in general not the case here.
185 QRegion selectionRegion
;
186 const QModelIndexList indexes
= selection
.indexes();
188 foreach(const QModelIndex
& index
, indexes
) {
189 selectionRegion
+= visualRect(index
);
192 return selectionRegion
;
195 bool DolphinDetailsView::event(QEvent
* event
)
197 switch (event
->type()) {
199 header()->setResizeMode(QHeaderView::Interactive
);
200 updateColumnVisibility();
203 case QEvent::FocusOut
:
204 // If a key-press triggers an action that e. g. opens a dialog, the
205 // widget gets no key-release event. Assure that the pressed state
206 // is reset to prevent accidently setting the current index during a selection.
207 m_keyPressed
= false;
214 return QTreeView::event(event
);
217 QStyleOptionViewItem
DolphinDetailsView::viewOptions() const
219 QStyleOptionViewItem viewOptions
= QTreeView::viewOptions();
220 viewOptions
.font
= m_font
;
221 viewOptions
.fontMetrics
= QFontMetrics(m_font
);
222 viewOptions
.showDecorationSelected
= true;
223 viewOptions
.decorationSize
= m_decorationSize
;
227 void DolphinDetailsView::contextMenuEvent(QContextMenuEvent
* event
)
229 QTreeView::contextMenuEvent(event
);
231 DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
232 m_expandableFoldersAction
->setChecked(settings
->expandableFolders());
233 m_dolphinViewController
->triggerContextMenuRequest(event
->pos(),
234 QList
<QAction
*>() << m_expandableFoldersAction
);
237 void DolphinDetailsView::mousePressEvent(QMouseEvent
* event
)
239 m_dolphinViewController
->requestActivation();
241 const QModelIndex current
= currentIndex();
242 QTreeView::mousePressEvent(event
);
244 m_expandingTogglePressed
= isAboveExpandingToggle(event
->pos());
246 const QModelIndex index
= indexAt(event
->pos());
247 const bool updateState
= index
.isValid() &&
248 (index
.column() == DolphinModel::Name
) &&
249 (event
->button() == Qt::LeftButton
);
251 setState(QAbstractItemView::DraggingState
);
254 if (!index
.isValid() || (index
.column() != DolphinModel::Name
)) {
255 // the mouse press is done somewhere outside the filename column
256 if (QApplication::mouseButtons() & Qt::MidButton
) {
257 m_dolphinViewController
->replaceUrlByClipboard();
260 const Qt::KeyboardModifiers mod
= QApplication::keyboardModifiers();
261 if (!m_expandingTogglePressed
&& !(mod
& Qt::ShiftModifier
) && !(mod
& Qt::ControlModifier
)) {
265 // restore the current index, other columns are handled as viewport area.
266 // setCurrentIndex(...) implicitly calls scrollTo(...), which we want to ignore.
267 m_ignoreScrollTo
= true;
268 selectionModel()->setCurrentIndex(current
, QItemSelectionModel::Current
);
269 m_ignoreScrollTo
= false;
271 if ((event
->button() == Qt::LeftButton
) && !m_expandingTogglePressed
) {
272 // Inform Qt about what we are doing - otherwise it starts dragging items around!
273 setState(DragSelectingState
);
275 // Incremental update data will not be useful - start from scratch.
276 m_band
.ignoreOldInfo
= true;
277 const QPoint
scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
278 m_band
.origin
= event
->pos() + scrollPos
;
279 m_band
.destination
= m_band
.origin
;
280 m_band
.originalSelection
= selectionModel()->selection();
285 void DolphinDetailsView::mouseMoveEvent(QMouseEvent
* event
)
287 if (m_expandingTogglePressed
) {
288 // Per default QTreeView starts either a selection or a drag operation when dragging
289 // the expanding toggle button (Qt-issue - see TODO comment in DolphinIconsView::mousePressEvent()).
290 // Turn off this behavior in Dolphin to stay predictable:
291 setState(QAbstractItemView::NoState
);
296 const QPoint mousePos
= event
->pos();
297 const QModelIndex index
= indexAt(mousePos
);
298 if (!index
.isValid()) {
299 // the destination of the selection rectangle is above the viewport. In this
300 // case QTreeView does no selection at all, which is not the wanted behavior
301 // in Dolphin -> select all items within the elastic band rectangle
302 updateElasticBandSelection();
305 // TODO: enable QTreeView::mouseMoveEvent(event) again, as soon
306 // as the Qt-issue #199631 has been fixed.
307 // QTreeView::mouseMoveEvent(event);
308 QAbstractItemView::mouseMoveEvent(event
);
311 // TODO: enable QTreeView::mouseMoveEvent(event) again, as soon
312 // as the Qt-issue #199631 has been fixed.
313 // QTreeView::mouseMoveEvent(event);
314 QAbstractItemView::mouseMoveEvent(event
);
318 void DolphinDetailsView::mouseReleaseEvent(QMouseEvent
* event
)
320 if (!m_expandingTogglePressed
) {
321 const QModelIndex index
= indexAt(event
->pos());
322 if (index
.isValid() && (index
.column() == DolphinModel::Name
)) {
323 QTreeView::mouseReleaseEvent(event
);
325 // don't change the current index if the cursor is released
326 // above any other column than the name column, as the other
327 // columns act as viewport
328 const QModelIndex current
= currentIndex();
329 QTreeView::mouseReleaseEvent(event
);
330 selectionModel()->setCurrentIndex(current
, QItemSelectionModel::Current
);
333 m_expandingTogglePressed
= false;
342 void DolphinDetailsView::startDrag(Qt::DropActions supportedActions
)
344 DragAndDropHelper::instance().startDrag(this, supportedActions
, m_dolphinViewController
);
348 void DolphinDetailsView::dragEnterEvent(QDragEnterEvent
* event
)
350 if (DragAndDropHelper::instance().isMimeDataSupported(event
->mimeData())) {
351 event
->acceptProposedAction();
360 void DolphinDetailsView::dragLeaveEvent(QDragLeaveEvent
* event
)
362 QTreeView::dragLeaveEvent(event
);
363 setDirtyRegion(m_dropRect
);
366 void DolphinDetailsView::dragMoveEvent(QDragMoveEvent
* event
)
368 QTreeView::dragMoveEvent(event
);
370 // TODO: remove this code when the issue #160611 is solved in Qt 4.4
371 setDirtyRegion(m_dropRect
);
372 const QModelIndex index
= indexAt(event
->pos());
373 if (index
.isValid() && (index
.column() == DolphinModel::Name
)) {
374 const KFileItem item
= m_dolphinViewController
->itemForIndex(index
);
375 if (!item
.isNull() && item
.isDir()) {
376 m_dropRect
= visualRect(index
);
378 m_dropRect
.setSize(QSize()); // set as invalid
380 setDirtyRegion(m_dropRect
);
383 if (DragAndDropHelper::instance().isMimeDataSupported(event
->mimeData())) {
384 // accept url drops, independently from the destination item
385 event
->acceptProposedAction();
389 void DolphinDetailsView::dropEvent(QDropEvent
* event
)
391 const QModelIndex index
= indexAt(event
->pos());
393 if (index
.isValid() && (index
.column() == DolphinModel::Name
)) {
394 item
= m_dolphinViewController
->itemForIndex(index
);
396 m_dolphinViewController
->indicateDroppedUrls(item
, m_viewModeController
->url(), event
);
397 QTreeView::dropEvent(event
);
400 void DolphinDetailsView::paintEvent(QPaintEvent
* event
)
402 QTreeView::paintEvent(event
);
404 // The following code has been taken from QListView
405 // and adapted to DolphinDetailsView.
406 // (C) 1992-2007 Trolltech ASA
407 QStyleOptionRubberBand opt
;
409 opt
.shape
= QRubberBand::Rectangle
;
411 opt
.rect
= elasticBandRect();
413 QPainter
painter(viewport());
415 style()->drawControl(QStyle::CE_RubberBand
, &opt
, &painter
);
420 void DolphinDetailsView::keyPressEvent(QKeyEvent
* event
)
422 // If the Control modifier is pressed, a multiple selection
423 // is done and DolphinDetailsView::currentChanged() may not
424 // not change the selection in a custom way.
425 m_keyPressed
= !(event
->modifiers() & Qt::ControlModifier
);
427 QTreeView::keyPressEvent(event
);
428 m_dolphinViewController
->handleKeyPressEvent(event
);
431 void DolphinDetailsView::keyReleaseEvent(QKeyEvent
* event
)
433 QTreeView::keyReleaseEvent(event
);
434 m_keyPressed
= false;
437 void DolphinDetailsView::resizeEvent(QResizeEvent
* event
)
439 QTreeView::resizeEvent(event
);
445 void DolphinDetailsView::wheelEvent(QWheelEvent
* event
)
447 const int step
= m_decorationSize
.height();
448 verticalScrollBar()->setSingleStep(step
);
449 QTreeView::wheelEvent(event
);
452 void DolphinDetailsView::currentChanged(const QModelIndex
& current
, const QModelIndex
& previous
)
454 QTreeView::currentChanged(current
, previous
);
455 m_extensionsFactory
->handleCurrentIndexChange(current
, previous
);
457 // Stay consistent with QListView: When changing the current index by key presses,
458 // also change the selection.
460 setCurrentIndex(current
);
463 // If folders are expanded, the width which is available for editing may have changed
464 // because it depends on the level of the current item in the folder hierarchy.
465 adjustMaximumSizeForEditing(current
);
468 bool DolphinDetailsView::eventFilter(QObject
* watched
, QEvent
* event
)
470 if ((watched
== viewport()) && (event
->type() == QEvent::Leave
)) {
471 // if the mouse is above an item and moved very fast outside the widget,
472 // no viewportEntered() signal might be emitted although the mouse has been moved
473 // above the viewport
474 m_dolphinViewController
->emitViewportEntered();
477 return QTreeView::eventFilter(watched
, event
);
480 QModelIndex
DolphinDetailsView::indexAt(const QPoint
& point
) const
482 // the blank portion of the name column counts as empty space
483 const QModelIndex index
= QTreeView::indexAt(point
);
484 const bool isAboveEmptySpace
= !m_useDefaultIndexAt
&&
485 (index
.column() == KDirModel::Name
) && !visualRect(index
).contains(point
);
486 return isAboveEmptySpace
? QModelIndex() : index
;
489 QRect
DolphinDetailsView::visualRect(const QModelIndex
& index
) const
491 QRect rect
= QTreeView::visualRect(index
);
492 const KFileItem item
= m_dolphinViewController
->itemForIndex(index
);
493 if (!item
.isNull()) {
494 const int width
= DolphinFileItemDelegate::nameColumnWidth(item
.text(), viewOptions());
495 rect
.setWidth(width
);
501 void DolphinDetailsView::setSelection(const QRect
& rect
, QItemSelectionModel::SelectionFlags command
)
503 // We must override setSelection() as Qt calls it internally and when this happens
504 // we must ensure that the default indexAt() is used.
506 m_useDefaultIndexAt
= true;
507 QTreeView::setSelection(rect
, command
);
508 m_useDefaultIndexAt
= false;
510 // Use our own elastic band selection algorithm
511 updateElasticBandSelection();
515 void DolphinDetailsView::scrollTo(const QModelIndex
& index
, ScrollHint hint
)
517 if (!m_ignoreScrollTo
) {
518 QTreeView::scrollTo(index
, hint
);
522 void DolphinDetailsView::setSortIndicatorSection(DolphinView::Sorting sorting
)
524 header()->setSortIndicator(sorting
, header()->sortIndicatorOrder());
527 void DolphinDetailsView::setSortIndicatorOrder(Qt::SortOrder sortOrder
)
529 header()->setSortIndicator(header()->sortIndicatorSection(), sortOrder
);
532 void DolphinDetailsView::synchronizeSortingState(int column
)
534 // The sorting has already been changed in QTreeView if this slot is
535 // invoked, but Dolphin is not informed about this.
536 DolphinView::Sorting sorting
= DolphinSortFilterProxyModel::sortingForColumn(column
);
537 const Qt::SortOrder sortOrder
= header()->sortIndicatorOrder();
538 m_dolphinViewController
->indicateSortingChange(sorting
);
539 m_dolphinViewController
->indicateSortOrderChange(sortOrder
);
542 void DolphinDetailsView::slotEntered(const QModelIndex
& index
)
544 if (index
.column() == DolphinModel::Name
) {
545 m_dolphinViewController
->emitItemEntered(index
);
547 m_dolphinViewController
->emitViewportEntered();
551 void DolphinDetailsView::updateElasticBand()
554 QRect
dirtyRegion(elasticBandRect());
555 const QPoint
scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
556 m_band
.destination
= viewport()->mapFromGlobal(QCursor::pos()) + scrollPos
;
557 // Going above the (logical) top-left of the view causes complications during selection;
558 // we may as well prevent it.
559 if (m_band
.destination
.y() < 0) {
560 m_band
.destination
.setY(0);
562 if (m_band
.destination
.x() < 0) {
563 m_band
.destination
.setX(0);
565 dirtyRegion
= dirtyRegion
.united(elasticBandRect());
566 setDirtyRegion(dirtyRegion
);
570 QRect
DolphinDetailsView::elasticBandRect() const
572 const QPoint
scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
574 const QPoint topLeft
= m_band
.origin
- scrollPos
;
575 const QPoint bottomRight
= m_band
.destination
- scrollPos
;
576 return QRect(topLeft
, bottomRight
).normalized();
579 void DolphinDetailsView::setZoomLevel(int level
)
581 const int size
= ZoomLevelInfo::iconSizeForZoomLevel(level
);
582 DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
584 const bool showPreview
= m_dolphinViewController
->view()->showPreview();
586 settings
->setPreviewSize(size
);
588 settings
->setIconSize(size
);
591 updateDecorationSize(showPreview
);
594 void DolphinDetailsView::slotShowPreviewChanged()
596 const DolphinView
* view
= m_dolphinViewController
->view();
597 updateDecorationSize(view
->showPreview());
600 void DolphinDetailsView::configureSettings(const QPoint
& pos
)
603 popup
.addTitle(i18nc("@title:menu", "Columns"));
605 // add checkbox items for each column
606 QHeaderView
* headerView
= header();
607 const int columns
= model()->columnCount();
608 for (int i
= 0; i
< columns
; ++i
) {
609 const int logicalIndex
= headerView
->logicalIndex(i
);
610 const QString text
= model()->headerData(logicalIndex
, Qt::Horizontal
).toString();
611 if (!text
.isEmpty()) {
612 QAction
* action
= popup
.addAction(text
);
613 action
->setCheckable(true);
614 action
->setChecked(!headerView
->isSectionHidden(logicalIndex
));
615 action
->setData(logicalIndex
);
616 action
->setEnabled(logicalIndex
!= DolphinModel::Name
);
619 popup
.addSeparator();
621 QAction
* activatedAction
= popup
.exec(header()->mapToGlobal(pos
));
622 if (activatedAction
!= 0) {
623 const bool show
= activatedAction
->isChecked();
624 const int columnIndex
= activatedAction
->data().toInt();
626 KFileItemDelegate::InformationList list
= m_dolphinViewController
->view()->additionalInfo();
627 const KFileItemDelegate::Information info
= infoForColumn(columnIndex
);
629 Q_ASSERT(!list
.contains(info
));
632 Q_ASSERT(list
.contains(info
));
633 const int index
= list
.indexOf(info
);
634 list
.removeAt(index
);
637 m_dolphinViewController
->indicateAdditionalInfoChange(list
);
638 setColumnHidden(columnIndex
, !show
);
643 void DolphinDetailsView::updateColumnVisibility()
645 QHeaderView
* headerView
= header();
646 disconnect(headerView
, SIGNAL(sectionMoved(int, int, int)),
647 this, SLOT(saveColumnPositions()));
649 const DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
650 const QList
<int> columnPositions
= settings
->columnPositions();
652 const KFileItemDelegate::InformationList list
= m_dolphinViewController
->view()->additionalInfo();
653 for (int i
= DolphinModel::Name
; i
< DolphinModel::ExtraColumnCount
; ++i
) {
654 const KFileItemDelegate::Information info
= infoForColumn(i
);
655 const bool hide
= !list
.contains(info
) && (i
!= DolphinModel::Name
);
656 if (isColumnHidden(i
) != hide
) {
657 setColumnHidden(i
, hide
);
660 // If the list columnPositions has been written by an older Dolphin version,
661 // its length might be smaller than DolphinModel::ExtraColumnCount. Therefore,
662 // we have to check if item number i exists before accessing it.
663 if (i
< columnPositions
.length()) {
664 const int position
= columnPositions
[i
];
666 // The position might be outside the correct range if the list columnPositions
667 // has been written by a newer Dolphin version with more columns.
668 if (position
< DolphinModel::ExtraColumnCount
) {
669 const int from
= headerView
->visualIndex(i
);
670 headerView
->moveSection(from
, position
);
677 connect(headerView
, SIGNAL(sectionMoved(int, int, int)),
678 this, SLOT(saveColumnPositions()));
681 void DolphinDetailsView::saveColumnPositions()
683 QList
<int> columnPositions
;
684 for (int i
= DolphinModel::Name
; i
< DolphinModel::ExtraColumnCount
; ++i
) {
685 columnPositions
.append(header()->visualIndex(i
));
688 DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
689 settings
->setColumnPositions(columnPositions
);
692 void DolphinDetailsView::slotHeaderSectionResized(int logicalIndex
, int oldSize
, int newSize
)
694 Q_UNUSED(logicalIndex
);
697 // If the user changes the size of the headers, the autoresize feature should be
698 // turned off. As there is no dedicated interface to find out whether the header
699 // section has been resized by the user or by a resize event, another approach is used.
700 // Attention: Take care when changing the if-condition to verify that there is no
701 // regression in combination with bug 178630 (see fix in comment #8).
702 if ((QApplication::mouseButtons() & Qt::LeftButton
) && header()->underMouse()) {
703 disableAutoResizing();
706 adjustMaximumSizeForEditing(currentIndex());
709 void DolphinDetailsView::slotActivationChanged(bool active
)
711 setAlternatingRowColors(active
);
714 void DolphinDetailsView::disableAutoResizing()
716 m_autoResize
= false;
719 void DolphinDetailsView::requestActivation()
721 m_dolphinViewController
->requestActivation();
724 void DolphinDetailsView::slotGlobalSettingsChanged(int category
)
728 const DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
729 Q_ASSERT(settings
!= 0);
730 if (settings
->useSystemFont()) {
731 m_font
= KGlobalSettings::generalFont();
733 //Disconnect then reconnect, since the settings have been changed, the connection requirements may have also.
734 disconnect(this, SIGNAL(clicked(QModelIndex
)), m_dolphinViewController
, SLOT(triggerItem(QModelIndex
)));
735 disconnect(this, SIGNAL(doubleClicked(QModelIndex
)), m_dolphinViewController
, SLOT(triggerItem(QModelIndex
)));
736 if (KGlobalSettings::singleClick()) {
737 connect(this, SIGNAL(clicked(QModelIndex
)), m_dolphinViewController
, SLOT(triggerItem(QModelIndex
)));
739 connect(this, SIGNAL(doubleClicked(QModelIndex
)), m_dolphinViewController
, SLOT(triggerItem(QModelIndex
)));
743 void DolphinDetailsView::updateElasticBandSelection()
749 // Ensure the elastic band itself is up-to-date, in
750 // case we are being called due to e.g. a drag event.
753 // Clip horizontally to the name column, as some filenames will be
754 // longer than the column. We don't clip vertically as origin
755 // may be above or below the current viewport area.
756 const int nameColumnX
= header()->sectionPosition(DolphinModel::Name
);
757 const int nameColumnWidth
= header()->sectionSize(DolphinModel::Name
);
758 QRect selRect
= elasticBandRect().normalized();
759 QRect
nameColumnArea(nameColumnX
, selRect
.y(), nameColumnWidth
, selRect
.height());
760 selRect
= nameColumnArea
.intersect(selRect
).normalized();
761 // Get the last elastic band rectangle, expressed in viewpoint coordinates.
762 const QPoint
scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
763 QRect oldSelRect
= QRect(m_band
.lastSelectionOrigin
- scrollPos
, m_band
.lastSelectionDestination
- scrollPos
).normalized();
765 if (selRect
.isNull()) {
766 selectionModel()->select(m_band
.originalSelection
, QItemSelectionModel::ClearAndSelect
);
767 m_band
.ignoreOldInfo
= true;
771 if (!m_band
.ignoreOldInfo
) {
772 // Do some quick checks to see if we can rule out the need to
773 // update the selection.
774 Q_ASSERT(uniformRowHeights());
775 QModelIndex dummyIndex
= model()->index(0, 0);
776 if (!dummyIndex
.isValid()) {
777 // No items in the model presumably.
781 // If the elastic band does not cover the same rows as before, we'll
782 // need to re-check, and also invalidate the old item distances.
783 const int rowHeight
= QTreeView::rowHeight(dummyIndex
);
784 const bool coveringSameRows
=
785 (selRect
.top() / rowHeight
== oldSelRect
.top() / rowHeight
) &&
786 (selRect
.bottom() / rowHeight
== oldSelRect
.bottom() / rowHeight
);
787 if (coveringSameRows
) {
788 // Covering the same rows, but have we moved far enough horizontally
789 // that we might have (de)selected some other items?
790 const bool itemSelectionChanged
=
791 ((selRect
.left() > oldSelRect
.left()) &&
792 (selRect
.left() > m_band
.insideNearestLeftEdge
)) ||
793 ((selRect
.left() < oldSelRect
.left()) &&
794 (selRect
.left() <= m_band
.outsideNearestLeftEdge
)) ||
795 ((selRect
.right() < oldSelRect
.right()) &&
796 (selRect
.left() >= m_band
.insideNearestRightEdge
)) ||
797 ((selRect
.right() > oldSelRect
.right()) &&
798 (selRect
.right() >= m_band
.outsideNearestRightEdge
));
800 if (!itemSelectionChanged
) {
805 // This is the only piece of optimization data that needs to be explicitly
807 m_band
.lastSelectionOrigin
= QPoint();
808 m_band
.lastSelectionDestination
= QPoint();
809 oldSelRect
= selRect
;
812 // Do the selection from scratch. Force a update of the horizontal distances info.
813 m_band
.insideNearestLeftEdge
= nameColumnX
+ nameColumnWidth
+ 1;
814 m_band
.insideNearestRightEdge
= nameColumnX
- 1;
815 m_band
.outsideNearestLeftEdge
= nameColumnX
- 1;
816 m_band
.outsideNearestRightEdge
= nameColumnX
+ nameColumnWidth
+ 1;
818 // Include the old selection rect as well, so we can deselect
819 // items that were inside it but not in the new selRect.
820 const QRect boundingRect
= selRect
.united(oldSelRect
).normalized();
821 if (boundingRect
.isNull()) {
825 // Get the index of the item in this row in the name column.
826 // TODO - would this still work if the columns could be re-ordered?
827 QModelIndex startIndex
= QTreeView::indexAt(boundingRect
.topLeft());
828 if (startIndex
.parent().isValid()) {
829 startIndex
= startIndex
.parent().child(startIndex
.row(), KDirModel::Name
);
831 startIndex
= model()->index(startIndex
.row(), KDirModel::Name
);
833 if (!startIndex
.isValid()) {
834 selectionModel()->select(m_band
.originalSelection
, QItemSelectionModel::ClearAndSelect
);
835 m_band
.ignoreOldInfo
= true;
839 // Go through all indexes between the top and bottom of boundingRect, and
840 // update the selection.
841 const int verticalCutoff
= boundingRect
.bottom();
842 QModelIndex currIndex
= startIndex
;
843 QModelIndex lastIndex
;
844 bool allItemsInBoundDone
= false;
846 // Calling selectionModel()->select(...) for each item that needs to be
847 // toggled is slow as each call emits selectionChanged(...) so store them
848 // and do the selection toggle in one batch.
849 QItemSelection itemsToToggle
;
850 // QItemSelection's deal with continuous ranges of indexes better than
851 // single indexes, so try to portion items that need to be toggled into ranges.
852 bool formingToggleIndexRange
= false;
853 QModelIndex toggleIndexRangeBegin
= QModelIndex();
856 QRect currIndexRect
= visualRect(currIndex
);
858 // Update some optimization info as we go.
859 const int cr
= currIndexRect
.right();
860 const int cl
= currIndexRect
.left();
861 const int sl
= selRect
.left();
862 const int sr
= selRect
.right();
863 // "The right edge of the name is outside of the rect but nearer than m_outsideNearestLeft", etc
864 if ((cr
< sl
&& cr
> m_band
.outsideNearestLeftEdge
)) {
865 m_band
.outsideNearestLeftEdge
= cr
;
867 if ((cl
> sr
&& cl
< m_band
.outsideNearestRightEdge
)) {
868 m_band
.outsideNearestRightEdge
= cl
;
870 if ((cl
>= sl
&& cl
<= sr
&& cl
> m_band
.insideNearestRightEdge
)) {
871 m_band
.insideNearestRightEdge
= cl
;
873 if ((cr
>= sl
&& cr
<= sr
&& cr
< m_band
.insideNearestLeftEdge
)) {
874 m_band
.insideNearestLeftEdge
= cr
;
877 bool currentlySelected
= selectionModel()->isSelected(currIndex
);
878 bool originallySelected
= m_band
.originalSelection
.contains(currIndex
);
879 bool intersectsSelectedRect
= currIndexRect
.intersects(selRect
);
880 bool shouldBeSelected
= (intersectsSelectedRect
&& !originallySelected
) || (!intersectsSelectedRect
&& originallySelected
);
881 bool needToToggleItem
= (currentlySelected
&& !shouldBeSelected
) || (!currentlySelected
&& shouldBeSelected
);
882 if (needToToggleItem
&& !formingToggleIndexRange
) {
883 toggleIndexRangeBegin
= currIndex
;
884 formingToggleIndexRange
= true;
887 // NOTE: indexBelow actually walks up and down expanded trees for us.
888 QModelIndex nextIndex
= indexBelow(currIndex
);
889 allItemsInBoundDone
= !nextIndex
.isValid() || currIndexRect
.top() > verticalCutoff
;
891 const bool commitToggleIndexRange
= formingToggleIndexRange
&&
892 (!needToToggleItem
||
893 allItemsInBoundDone
||
894 currIndex
.parent() != toggleIndexRangeBegin
.parent());
895 if (commitToggleIndexRange
) {
896 formingToggleIndexRange
= false;
897 // If this is the last item in the bounds and it is also the beginning of a range,
898 // don't toggle lastIndex - it will already have been dealt with.
899 if (!allItemsInBoundDone
|| toggleIndexRangeBegin
!= currIndex
) {
900 itemsToToggle
.select(toggleIndexRangeBegin
, lastIndex
);
902 // Need to start a new range immediately with currIndex?
903 if (needToToggleItem
) {
904 toggleIndexRangeBegin
= currIndex
;
905 formingToggleIndexRange
= true;
907 if (allItemsInBoundDone
&& needToToggleItem
) {
908 // Toggle the very last item in the bounds.
909 itemsToToggle
.select(currIndex
, currIndex
);
914 lastIndex
= currIndex
;
915 currIndex
= nextIndex
;
916 } while (!allItemsInBoundDone
);
919 selectionModel()->select(itemsToToggle
, QItemSelectionModel::Toggle
);
921 m_band
.lastSelectionOrigin
= m_band
.origin
;
922 m_band
.lastSelectionDestination
= m_band
.destination
;
923 m_band
.ignoreOldInfo
= false;
926 void DolphinDetailsView::setFoldersExpandable(bool expandable
)
929 // collapse all expanded folders, as QTreeView::setItemsExpandable(false)
930 // does not do this task
931 const int rowCount
= model()->rowCount();
932 for (int row
= 0; row
< rowCount
; ++row
) {
933 setExpanded(model()->index(row
, 0), false);
936 DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
937 settings
->setExpandableFolders(expandable
);
938 setRootIsDecorated(expandable
);
939 setItemsExpandable(expandable
);
941 // The width of the space which is available for editing has changed
942 // because of the (dis)appearance of the expanding toggles
943 adjustMaximumSizeForEditing(currentIndex());
946 void DolphinDetailsView::slotExpanded(const QModelIndex
& index
)
948 KFileItem item
= m_dolphinViewController
->itemForIndex(index
);
949 if (!item
.isNull()) {
950 m_expandedUrls
.insert(item
.url());
954 void DolphinDetailsView::slotCollapsed(const QModelIndex
& index
)
956 KFileItem item
= m_dolphinViewController
->itemForIndex(index
);
957 if (!item
.isNull()) {
958 m_expandedUrls
.remove(item
.url());
962 void DolphinDetailsView::rowsAboutToBeRemoved(const QModelIndex
&parent
, int start
, int end
)
964 removeExpandedIndexes(parent
, start
, end
);
965 QTreeView::rowsAboutToBeRemoved(parent
, start
, end
);
968 void DolphinDetailsView::removeExpandedIndexes(const QModelIndex
& parent
, int start
, int end
)
970 if (m_expandedUrls
.isEmpty()) {
974 for (int row
= start
; row
<= end
; row
++) {
975 const QModelIndex index
= model()->index(row
, 0, parent
);
976 if (isExpanded(index
)) {
977 slotCollapsed(index
);
978 removeExpandedIndexes(index
, 0, model()->rowCount(index
) - 1);
983 void DolphinDetailsView::updateDecorationSize(bool showPreview
)
985 DetailsModeSettings
* settings
= DolphinSettings::instance().detailsModeSettings();
986 const int iconSize
= showPreview
? settings
->previewSize() : settings
->iconSize();
987 setIconSize(QSize(iconSize
, iconSize
));
988 m_decorationSize
= QSize(iconSize
, iconSize
);
993 KFileItemDelegate::Information
DolphinDetailsView::infoForColumn(int columnIndex
) const
995 return AdditionalInfoAccessor::instance().keyForColumn(columnIndex
);
998 void DolphinDetailsView::resizeColumns()
1000 // Using the resize mode QHeaderView::ResizeToContents is too slow (it takes
1001 // around 3 seconds for each (!) resize operation when having > 10000 items).
1002 // This gets a problem especially when opening large directories, where several
1003 // resize operations are received for showing the currently available items during
1004 // loading (the application hangs around 20 seconds when loading > 10000 items).
1006 QHeaderView
* headerView
= header();
1007 QFontMetrics
fontMetrics(viewport()->font());
1009 // Calculate the required with for each column and store it in columnWidth[]
1010 int columnWidth
[DolphinModel::ExtraColumnCount
];
1011 const int defaultWidth
= fontMetrics
.width("xxxxxxxxxx");
1013 for (int i
= 0; i
< DolphinModel::ExtraColumnCount
; ++i
) {
1014 const int logicalIndex
= headerView
->logicalIndex(i
);
1015 const QString headline
= model()->headerData(logicalIndex
, Qt::Horizontal
).toString();
1016 const int headlineWidth
= fontMetrics
.width(headline
);
1018 columnWidth
[i
] = qMax(defaultWidth
, headlineWidth
);
1021 const int defaultSizeWidth
= fontMetrics
.width("00000 Items");
1022 if (defaultSizeWidth
> columnWidth
[DolphinModel::Size
]) {
1023 columnWidth
[DolphinModel::Size
] = defaultSizeWidth
;
1026 const int defaultTimeWidth
= fontMetrics
.width("0000-00-00 00:00");
1027 if (defaultTimeWidth
> columnWidth
[DolphinModel::ModifiedTime
]) {
1028 columnWidth
[DolphinModel::ModifiedTime
] = defaultTimeWidth
;
1031 int requiredWidth
= 0;
1032 for (int i
= KDirModel::Size
; i
< DolphinModel::ExtraColumnCount
; ++i
) {
1033 if (!isColumnHidden(i
)) {
1034 columnWidth
[i
] += 20; // provide a default gap
1035 requiredWidth
+= columnWidth
[i
];
1036 headerView
->resizeSection(i
, columnWidth
[i
]);
1040 // Resize the name column in a way that the whole available width is used
1041 columnWidth
[KDirModel::Name
] = viewport()->width() - requiredWidth
;
1043 const int minNameWidth
= 300;
1044 if (columnWidth
[KDirModel::Name
] < minNameWidth
) {
1045 columnWidth
[KDirModel::Name
] = minNameWidth
;
1047 // It might be possible that the name column width can be
1048 // decreased without clipping any text. For performance
1049 // reasons the exact necessary width for full visible names is
1050 // only checked for up to 200 items:
1051 const int rowCount
= model()->rowCount();
1052 if (rowCount
> 0 && rowCount
< 200) {
1053 const int nameWidth
= sizeHintForColumn(DolphinModel::Name
);
1054 if (nameWidth
+ requiredWidth
<= viewport()->width()) {
1055 columnWidth
[KDirModel::Name
] = viewport()->width() - requiredWidth
;
1056 } else if (nameWidth
< minNameWidth
) {
1057 columnWidth
[KDirModel::Name
] = nameWidth
;
1062 headerView
->resizeSection(KDirModel::Name
, columnWidth
[KDirModel::Name
]);
1065 bool DolphinDetailsView::isAboveExpandingToggle(const QPoint
& pos
) const
1067 // QTreeView offers no public API to get the information whether an index has an
1068 // expanding toggle and what boundaries the toggle has. The following approach
1069 // also assumes a toggle for file items.
1070 if (itemsExpandable()) {
1071 const QModelIndex index
= QTreeView::indexAt(pos
);
1072 if (index
.isValid() && (index
.column() == KDirModel::Name
)) {
1073 QRect rect
= visualRect(index
);
1074 const int toggleSize
= rect
.height();
1075 if (isRightToLeft()) {
1076 rect
.moveRight(rect
.right());
1078 rect
.moveLeft(rect
.x() - toggleSize
);
1080 rect
.setWidth(toggleSize
);
1085 rect
= style()->subElementRect(QStyle::SE_TreeViewDisclosureItem
, &opt
, this);
1087 return rect
.contains(pos
);
1093 void DolphinDetailsView::adjustMaximumSizeForEditing(const QModelIndex
& index
)
1095 // Make sure that the full width of the "Name" column is available for "Rename Inline"
1096 m_extensionsFactory
->fileItemDelegate()->setMaximumSize(QTreeView::visualRect(index
).size());
1099 DolphinDetailsView::ElasticBand::ElasticBand() :
1103 lastSelectionOrigin(),
1104 lastSelectionDestination(),
1105 ignoreOldInfo(true),
1106 outsideNearestLeftEdge(0),
1107 outsideNearestRightEdge(0),
1108 insideNearestLeftEdge(0),
1109 insideNearestRightEdge(0)
1113 #include "dolphindetailsview.moc"