]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphindetailsview.cpp
Provide the destination of a symbolic link as a column in Dolphin's
[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 "dolphinviewcontroller.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 "viewmodecontroller.h"
32 #include "viewproperties.h"
33 #include "zoomlevelinfo.h"
34
35 #include "dolphin_detailsmodesettings.h"
36 #include "dolphin_generalsettings.h"
37
38 #include <kdirmodel.h>
39 #include <klocale.h>
40 #include <kmenu.h>
41
42 #include <QAction>
43 #include <QApplication>
44 #include <QHeaderView>
45 #include <QRubberBand>
46 #include <QPainter>
47 #include <QScrollBar>
48
49 DolphinDetailsView::DolphinDetailsView(QWidget* parent,
50 DolphinViewController* dolphinViewController,
51 const ViewModeController* viewModeController,
52 DolphinSortFilterProxyModel* proxyModel) :
53 QTreeView(parent),
54 m_autoResize(true),
55 m_expandingTogglePressed(false),
56 m_keyPressed(false),
57 m_useDefaultIndexAt(true),
58 m_ignoreScrollTo(false),
59 m_dolphinViewController(dolphinViewController),
60 m_viewModeController(viewModeController),
61 m_extensionsFactory(0),
62 m_expandableFoldersAction(0),
63 m_expandedUrls(),
64 m_font(),
65 m_decorationSize(),
66 m_band()
67 {
68 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
69 Q_ASSERT(settings != 0);
70 Q_ASSERT(dolphinViewController != 0);
71 Q_ASSERT(viewModeController != 0);
72
73 setLayoutDirection(Qt::LeftToRight);
74 setAcceptDrops(true);
75 setSortingEnabled(true);
76 setUniformRowHeights(true);
77 setSelectionBehavior(SelectItems);
78 setDragDropMode(QAbstractItemView::DragDrop);
79 setDropIndicatorShown(false);
80 setAlternatingRowColors(true);
81 setRootIsDecorated(settings->expandableFolders());
82 setItemsExpandable(settings->expandableFolders());
83 setEditTriggers(QAbstractItemView::NoEditTriggers);
84 setModel(proxyModel);
85
86 setMouseTracking(true);
87
88 const ViewProperties props(viewModeController->url());
89 setSortIndicatorSection(props.sorting());
90 setSortIndicatorOrder(props.sortOrder());
91
92 QHeaderView* headerView = header();
93 connect(headerView, SIGNAL(sectionClicked(int)),
94 this, SLOT(synchronizeSortingState(int)));
95 headerView->setContextMenuPolicy(Qt::CustomContextMenu);
96 connect(headerView, SIGNAL(customContextMenuRequested(const QPoint&)),
97 this, SLOT(configureSettings(const QPoint&)));
98 connect(headerView, SIGNAL(sectionResized(int, int, int)),
99 this, SLOT(slotHeaderSectionResized(int, int, int)));
100 connect(headerView, SIGNAL(sectionHandleDoubleClicked(int)),
101 this, SLOT(disableAutoResizing()));
102
103 connect(parent, SIGNAL(sortingChanged(DolphinView::Sorting)),
104 this, SLOT(setSortIndicatorSection(DolphinView::Sorting)));
105 connect(parent, SIGNAL(sortOrderChanged(Qt::SortOrder)),
106 this, SLOT(setSortIndicatorOrder(Qt::SortOrder)));
107
108 connect(this, SIGNAL(clicked(const QModelIndex&)),
109 dolphinViewController, SLOT(requestTab(const QModelIndex&)));
110 if (KGlobalSettings::singleClick()) {
111 connect(this, SIGNAL(clicked(const QModelIndex&)),
112 dolphinViewController, SLOT(triggerItem(const QModelIndex&)));
113 } else {
114 connect(this, SIGNAL(doubleClicked(const QModelIndex&)),
115 dolphinViewController, SLOT(triggerItem(const QModelIndex&)));
116 }
117
118 connect(this, SIGNAL(entered(const QModelIndex&)),
119 this, SLOT(slotEntered(const QModelIndex&)));
120 connect(this, SIGNAL(viewportEntered()),
121 dolphinViewController, SLOT(emitViewportEntered()));
122 connect(viewModeController, SIGNAL(zoomLevelChanged(int)),
123 this, SLOT(setZoomLevel(int)));
124 connect(dolphinViewController->view(), SIGNAL(additionalInfoChanged()),
125 this, SLOT(updateColumnVisibility()));
126 connect(viewModeController, 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 qRound(settings->fontSize()),
134 settings->fontWeight(),
135 settings->italicFont());
136 m_font.setPointSizeF(settings->fontSize());
137 }
138
139 setVerticalScrollMode(QTreeView::ScrollPerPixel);
140 setHorizontalScrollMode(QTreeView::ScrollPerPixel);
141
142 const DolphinView* view = dolphinViewController->view();
143 connect(view, SIGNAL(showPreviewChanged()),
144 this, SLOT(slotShowPreviewChanged()));
145
146
147 setFocus();
148 viewport()->installEventFilter(this);
149
150 connect(KGlobalSettings::self(), SIGNAL(settingsChanged(int)),
151 this, SLOT(slotGlobalSettingsChanged(int)));
152
153 m_useDefaultIndexAt = false;
154
155 m_expandableFoldersAction = new QAction(i18nc("@option:check", "Expandable Folders"), this);
156 m_expandableFoldersAction->setCheckable(true);
157 connect(m_expandableFoldersAction, SIGNAL(toggled(bool)),
158 this, SLOT(setFoldersExpandable(bool)));
159
160 connect(this, SIGNAL(expanded(const QModelIndex&)), this, SLOT(slotExpanded(const QModelIndex&)));
161 connect(this, SIGNAL(collapsed(const QModelIndex&)), this, SLOT(slotCollapsed(const QModelIndex&)));
162
163 updateDecorationSize(view->showPreview());
164
165 m_extensionsFactory = new ViewExtensionsFactory(this, dolphinViewController, viewModeController);
166 m_extensionsFactory->fileItemDelegate()->setMinimizedNameColumn(true);
167 m_extensionsFactory->setAutoFolderExpandingEnabled(settings->expandableFolders());
168 }
169
170 DolphinDetailsView::~DolphinDetailsView()
171 {
172 }
173
174 QSet<KUrl> DolphinDetailsView::expandedUrls() const
175 {
176 return m_expandedUrls;
177 }
178
179 QRegion DolphinDetailsView::visualRegionForSelection(const QItemSelection& selection) const
180 {
181 // We have to make sure that the visualRect of each model index is inside the region.
182 // QTreeView::visualRegionForSelection does not do it right because it assumes implicitly
183 // that all visualRects have the same width, which is in general not the case here.
184 QRegion selectionRegion;
185 const QModelIndexList indexes = selection.indexes();
186
187 foreach(const QModelIndex& index, indexes) {
188 selectionRegion += visualRect(index);
189 }
190
191 return selectionRegion;
192 }
193
194 bool DolphinDetailsView::event(QEvent* event)
195 {
196 switch (event->type()) {
197 case QEvent::Polish:
198 header()->setResizeMode(QHeaderView::Interactive);
199 updateColumnVisibility();
200 break;
201
202 case QEvent::FocusOut:
203 // If a key-press triggers an action that e. g. opens a dialog, the
204 // widget gets no key-release event. Assure that the pressed state
205 // is reset to prevent accidently setting the current index during a selection.
206 m_keyPressed = false;
207 break;
208
209 default:
210 break;
211 }
212
213 return QTreeView::event(event);
214 }
215
216 QStyleOptionViewItem DolphinDetailsView::viewOptions() const
217 {
218 QStyleOptionViewItem viewOptions = QTreeView::viewOptions();
219 viewOptions.font = m_font;
220 viewOptions.fontMetrics = QFontMetrics(m_font);
221 viewOptions.showDecorationSelected = true;
222 viewOptions.decorationSize = m_decorationSize;
223 return viewOptions;
224 }
225
226 void DolphinDetailsView::contextMenuEvent(QContextMenuEvent* event)
227 {
228 QTreeView::contextMenuEvent(event);
229
230 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
231 m_expandableFoldersAction->setChecked(settings->expandableFolders());
232 m_dolphinViewController->triggerContextMenuRequest(event->pos(),
233 QList<QAction*>() << m_expandableFoldersAction);
234 }
235
236 void DolphinDetailsView::mousePressEvent(QMouseEvent* event)
237 {
238 m_dolphinViewController->requestActivation();
239
240 const QModelIndex current = currentIndex();
241 QTreeView::mousePressEvent(event);
242
243 m_expandingTogglePressed = isAboveExpandingToggle(event->pos());
244
245 const QModelIndex index = indexAt(event->pos());
246 const bool updateState = index.isValid() &&
247 (index.column() == DolphinModel::Name) &&
248 (event->button() == Qt::LeftButton);
249 if (updateState) {
250 setState(QAbstractItemView::DraggingState);
251 }
252
253 if (!index.isValid() || (index.column() != DolphinModel::Name)) {
254 // the mouse press is done somewhere outside the filename column
255 if (QApplication::mouseButtons() & Qt::MidButton) {
256 m_dolphinViewController->replaceUrlByClipboard();
257 }
258
259 const Qt::KeyboardModifiers mod = QApplication::keyboardModifiers();
260 if (!m_expandingTogglePressed && !(mod & Qt::ShiftModifier) && !(mod & Qt::ControlModifier)) {
261 clearSelection();
262 }
263
264 // restore the current index, other columns are handled as viewport area.
265 // setCurrentIndex(...) implicitly calls scrollTo(...), which we want to ignore.
266 m_ignoreScrollTo = true;
267 selectionModel()->setCurrentIndex(current, QItemSelectionModel::Current);
268 m_ignoreScrollTo = false;
269
270 if ((event->button() == Qt::LeftButton) && !m_expandingTogglePressed) {
271 // Inform Qt about what we are doing - otherwise it starts dragging items around!
272 setState(DragSelectingState);
273 m_band.show = true;
274 // Incremental update data will not be useful - start from scratch.
275 m_band.ignoreOldInfo = true;
276 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
277 m_band.origin = event->pos() + scrollPos;
278 m_band.destination = m_band.origin;
279 m_band.originalSelection = selectionModel()->selection();
280 }
281 }
282 }
283
284 void DolphinDetailsView::mouseMoveEvent(QMouseEvent* event)
285 {
286 if (m_expandingTogglePressed) {
287 // Per default QTreeView starts either a selection or a drag operation when dragging
288 // the expanding toggle button (Qt-issue - see TODO comment in DolphinIconsView::mousePressEvent()).
289 // Turn off this behavior in Dolphin to stay predictable:
290 setState(QAbstractItemView::NoState);
291 return;
292 }
293
294 if (m_band.show) {
295 const QPoint mousePos = event->pos();
296 const QModelIndex index = indexAt(mousePos);
297 if (!index.isValid()) {
298 // the destination of the selection rectangle is above the viewport. In this
299 // case QTreeView does no selection at all, which is not the wanted behavior
300 // in Dolphin -> select all items within the elastic band rectangle
301 updateElasticBandSelection();
302 }
303
304 // TODO: enable QTreeView::mouseMoveEvent(event) again, as soon
305 // as the Qt-issue #199631 has been fixed.
306 // QTreeView::mouseMoveEvent(event);
307 QAbstractItemView::mouseMoveEvent(event);
308 updateElasticBand();
309 } else {
310 // TODO: enable QTreeView::mouseMoveEvent(event) again, as soon
311 // as the Qt-issue #199631 has been fixed.
312 // QTreeView::mouseMoveEvent(event);
313 QAbstractItemView::mouseMoveEvent(event);
314 }
315 }
316
317 void DolphinDetailsView::mouseReleaseEvent(QMouseEvent* event)
318 {
319 if (!m_expandingTogglePressed) {
320 const QModelIndex index = indexAt(event->pos());
321 if (index.isValid() && (index.column() == DolphinModel::Name)) {
322 QTreeView::mouseReleaseEvent(event);
323 } else {
324 // don't change the current index if the cursor is released
325 // above any other column than the name column, as the other
326 // columns act as viewport
327 const QModelIndex current = currentIndex();
328 QTreeView::mouseReleaseEvent(event);
329 selectionModel()->setCurrentIndex(current, QItemSelectionModel::Current);
330 }
331 }
332 m_expandingTogglePressed = false;
333
334 if (m_band.show) {
335 setState(NoState);
336 updateElasticBand();
337 m_band.show = false;
338 }
339 }
340
341 void DolphinDetailsView::startDrag(Qt::DropActions supportedActions)
342 {
343 DragAndDropHelper::instance().startDrag(this, supportedActions, m_dolphinViewController);
344 m_band.show = false;
345 }
346
347 void DolphinDetailsView::dragEnterEvent(QDragEnterEvent* event)
348 {
349 if (DragAndDropHelper::instance().isMimeDataSupported(event->mimeData())) {
350 event->acceptProposedAction();
351 }
352
353 if (m_band.show) {
354 updateElasticBand();
355 m_band.show = false;
356 }
357 }
358
359 void DolphinDetailsView::dragLeaveEvent(QDragLeaveEvent* event)
360 {
361 QTreeView::dragLeaveEvent(event);
362 setDirtyRegion(m_dropRect);
363 }
364
365 void DolphinDetailsView::dragMoveEvent(QDragMoveEvent* event)
366 {
367 QTreeView::dragMoveEvent(event);
368
369 // TODO: remove this code when the issue #160611 is solved in Qt 4.4
370 setDirtyRegion(m_dropRect);
371 const QModelIndex index = indexAt(event->pos());
372 if (index.isValid() && (index.column() == DolphinModel::Name)) {
373 const KFileItem item = m_dolphinViewController->itemForIndex(index);
374 if (!item.isNull() && item.isDir()) {
375 m_dropRect = visualRect(index);
376 } else {
377 m_dropRect.setSize(QSize()); // set as invalid
378 }
379 setDirtyRegion(m_dropRect);
380 }
381
382 if (DragAndDropHelper::instance().isMimeDataSupported(event->mimeData())) {
383 // accept url drops, independently from the destination item
384 event->acceptProposedAction();
385 }
386 }
387
388 void DolphinDetailsView::dropEvent(QDropEvent* event)
389 {
390 const QModelIndex index = indexAt(event->pos());
391 KFileItem item;
392 if (index.isValid() && (index.column() == DolphinModel::Name)) {
393 item = m_dolphinViewController->itemForIndex(index);
394 }
395 m_dolphinViewController->indicateDroppedUrls(item, m_viewModeController->url(), event);
396 QTreeView::dropEvent(event);
397 }
398
399 void DolphinDetailsView::paintEvent(QPaintEvent* event)
400 {
401 QTreeView::paintEvent(event);
402 if (m_band.show) {
403 // The following code has been taken from QListView
404 // and adapted to DolphinDetailsView.
405 // (C) 1992-2007 Trolltech ASA
406 QStyleOptionRubberBand opt;
407 opt.initFrom(this);
408 opt.shape = QRubberBand::Rectangle;
409 opt.opaque = false;
410 opt.rect = elasticBandRect();
411
412 QPainter painter(viewport());
413 painter.save();
414 style()->drawControl(QStyle::CE_RubberBand, &opt, &painter);
415 painter.restore();
416 }
417 }
418
419 void DolphinDetailsView::keyPressEvent(QKeyEvent* event)
420 {
421 // If the Control modifier is pressed, a multiple selection
422 // is done and DolphinDetailsView::currentChanged() may not
423 // not change the selection in a custom way.
424 m_keyPressed = !(event->modifiers() & Qt::ControlModifier);
425
426 QTreeView::keyPressEvent(event);
427 m_dolphinViewController->handleKeyPressEvent(event);
428 }
429
430 void DolphinDetailsView::keyReleaseEvent(QKeyEvent* event)
431 {
432 QTreeView::keyReleaseEvent(event);
433 m_keyPressed = false;
434 }
435
436 void DolphinDetailsView::resizeEvent(QResizeEvent* event)
437 {
438 QTreeView::resizeEvent(event);
439 if (m_autoResize) {
440 resizeColumns();
441 }
442 }
443
444 void DolphinDetailsView::wheelEvent(QWheelEvent* event)
445 {
446 const int step = m_decorationSize.height();
447 verticalScrollBar()->setSingleStep(step);
448 QTreeView::wheelEvent(event);
449 }
450
451 void DolphinDetailsView::currentChanged(const QModelIndex& current, const QModelIndex& previous)
452 {
453 QTreeView::currentChanged(current, previous);
454 m_extensionsFactory->handleCurrentIndexChange(current, previous);
455
456 // Stay consistent with QListView: When changing the current index by key presses,
457 // also change the selection.
458 if (m_keyPressed) {
459 setCurrentIndex(current);
460 }
461
462 // If folders are expanded, the width which is available for editing may have changed
463 // because it depends on the level of the current item in the folder hierarchy.
464 adjustMaximumSizeForEditing(current);
465 }
466
467 bool DolphinDetailsView::eventFilter(QObject* watched, QEvent* event)
468 {
469 if ((watched == viewport()) && (event->type() == QEvent::Leave)) {
470 // if the mouse is above an item and moved very fast outside the widget,
471 // no viewportEntered() signal might be emitted although the mouse has been moved
472 // above the viewport
473 m_dolphinViewController->emitViewportEntered();
474 }
475
476 return QTreeView::eventFilter(watched, event);
477 }
478
479 QModelIndex DolphinDetailsView::indexAt(const QPoint& point) const
480 {
481 // the blank portion of the name column counts as empty space
482 const QModelIndex index = QTreeView::indexAt(point);
483 const bool isAboveEmptySpace = !m_useDefaultIndexAt &&
484 (index.column() == KDirModel::Name) && !visualRect(index).contains(point);
485 return isAboveEmptySpace ? QModelIndex() : index;
486 }
487
488 QRect DolphinDetailsView::visualRect(const QModelIndex& index) const
489 {
490 QRect rect = QTreeView::visualRect(index);
491 const KFileItem item = m_dolphinViewController->itemForIndex(index);
492 if (!item.isNull()) {
493 const int width = DolphinFileItemDelegate::nameColumnWidth(item.text(), viewOptions());
494 rect.setWidth(width);
495 }
496
497 return rect;
498 }
499
500 void DolphinDetailsView::setSelection(const QRect& rect, QItemSelectionModel::SelectionFlags command)
501 {
502 // We must override setSelection() as Qt calls it internally and when this happens
503 // we must ensure that the default indexAt() is used.
504 if (!m_band.show) {
505 m_useDefaultIndexAt = true;
506 QTreeView::setSelection(rect, command);
507 m_useDefaultIndexAt = false;
508 } else {
509 // Use our own elastic band selection algorithm
510 updateElasticBandSelection();
511 }
512 }
513
514 void DolphinDetailsView::scrollTo(const QModelIndex & index, ScrollHint hint)
515 {
516 if (!m_ignoreScrollTo) {
517 QTreeView::scrollTo(index, hint);
518 }
519 }
520
521 void DolphinDetailsView::setSortIndicatorSection(DolphinView::Sorting sorting)
522 {
523 header()->setSortIndicator(sorting, header()->sortIndicatorOrder());
524 }
525
526 void DolphinDetailsView::setSortIndicatorOrder(Qt::SortOrder sortOrder)
527 {
528 header()->setSortIndicator(header()->sortIndicatorSection(), sortOrder);
529 }
530
531 void DolphinDetailsView::synchronizeSortingState(int column)
532 {
533 // The sorting has already been changed in QTreeView if this slot is
534 // invoked, but Dolphin is not informed about this.
535 DolphinView::Sorting sorting = DolphinSortFilterProxyModel::sortingForColumn(column);
536 const Qt::SortOrder sortOrder = header()->sortIndicatorOrder();
537 m_dolphinViewController->indicateSortingChange(sorting);
538 m_dolphinViewController->indicateSortOrderChange(sortOrder);
539 }
540
541 void DolphinDetailsView::slotEntered(const QModelIndex& index)
542 {
543 if (index.column() == DolphinModel::Name) {
544 m_dolphinViewController->emitItemEntered(index);
545 } else {
546 m_dolphinViewController->emitViewportEntered();
547 }
548 }
549
550 void DolphinDetailsView::updateElasticBand()
551 {
552 if (m_band.show) {
553 QRect dirtyRegion(elasticBandRect());
554 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
555 m_band.destination = viewport()->mapFromGlobal(QCursor::pos()) + scrollPos;
556 // Going above the (logical) top-left of the view causes complications during selection;
557 // we may as well prevent it.
558 if (m_band.destination.y() < 0) {
559 m_band.destination.setY(0);
560 }
561 if (m_band.destination.x() < 0) {
562 m_band.destination.setX(0);
563 }
564 dirtyRegion = dirtyRegion.united(elasticBandRect());
565 setDirtyRegion(dirtyRegion);
566 }
567 }
568
569 QRect DolphinDetailsView::elasticBandRect() const
570 {
571 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
572
573 const QPoint topLeft = m_band.origin - scrollPos;
574 const QPoint bottomRight = m_band.destination - scrollPos;
575 return QRect(topLeft, bottomRight).normalized();
576 }
577
578 void DolphinDetailsView::setZoomLevel(int level)
579 {
580 const int size = ZoomLevelInfo::iconSizeForZoomLevel(level);
581 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
582
583 const bool showPreview = m_dolphinViewController->view()->showPreview();
584 if (showPreview) {
585 settings->setPreviewSize(size);
586 } else {
587 settings->setIconSize(size);
588 }
589
590 updateDecorationSize(showPreview);
591 }
592
593 void DolphinDetailsView::slotShowPreviewChanged()
594 {
595 const DolphinView* view = m_dolphinViewController->view();
596 updateDecorationSize(view->showPreview());
597 }
598
599 void DolphinDetailsView::configureSettings(const QPoint& pos)
600 {
601 KMenu popup(this);
602 popup.addTitle(i18nc("@title:menu", "Columns"));
603
604 // add checkbox items for each column
605 QHeaderView* headerView = header();
606 const int columns = model()->columnCount();
607 for (int i = 0; i < columns; ++i) {
608 const int logicalIndex = headerView->logicalIndex(i);
609 const QString text = model()->headerData(logicalIndex, Qt::Horizontal).toString();
610 QAction* action = popup.addAction(text);
611 action->setCheckable(true);
612 action->setChecked(!headerView->isSectionHidden(logicalIndex));
613 action->setData(logicalIndex);
614 action->setEnabled(logicalIndex != DolphinModel::Name);
615 }
616 popup.addSeparator();
617
618 QAction* activatedAction = popup.exec(header()->mapToGlobal(pos));
619 if (activatedAction != 0) {
620 const bool show = activatedAction->isChecked();
621 const int columnIndex = activatedAction->data().toInt();
622
623 KFileItemDelegate::InformationList list = m_dolphinViewController->view()->additionalInfo();
624 const KFileItemDelegate::Information info = infoForColumn(columnIndex);
625 if (show) {
626 Q_ASSERT(!list.contains(info));
627 list.append(info);
628 } else {
629 Q_ASSERT(list.contains(info));
630 const int index = list.indexOf(info);
631 list.removeAt(index);
632 }
633
634 m_dolphinViewController->indicateAdditionalInfoChange(list);
635 setColumnHidden(columnIndex, !show);
636 resizeColumns();
637 }
638 }
639
640 void DolphinDetailsView::updateColumnVisibility()
641 {
642 QHeaderView* headerView = header();
643 disconnect(headerView, SIGNAL(sectionMoved(int, int, int)),
644 this, SLOT(saveColumnPositions()));
645
646 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
647 const QList<int> columnPositions = settings->columnPositions();
648
649 const KFileItemDelegate::InformationList list = m_dolphinViewController->view()->additionalInfo();
650 for (int i = DolphinModel::Name; i < DolphinModel::ExtraColumnCount; ++i) {
651 const KFileItemDelegate::Information info = infoForColumn(i);
652 const bool hide = !list.contains(info) && (i != DolphinModel::Name);
653 if (isColumnHidden(i) != hide) {
654 setColumnHidden(i, hide);
655 }
656
657 // If the list columnPositions has been written by an older Dolphin version,
658 // its length might be smaller than DolphinModel::ExtraColumnCount. Therefore,
659 // we have to check if item number i exists before accessing it.
660 if (i < columnPositions.length()) {
661 const int position = columnPositions[i];
662
663 // The position might be outside the correct range if the list columnPositions
664 // has been written by a newer Dolphin version with more columns.
665 if (position < DolphinModel::ExtraColumnCount) {
666 const int from = headerView->visualIndex(i);
667 headerView->moveSection(from, position);
668 }
669 }
670 }
671
672 resizeColumns();
673
674 connect(headerView, SIGNAL(sectionMoved(int, int, int)),
675 this, SLOT(saveColumnPositions()));
676 }
677
678 void DolphinDetailsView::saveColumnPositions()
679 {
680 QList<int> columnPositions;
681 for (int i = DolphinModel::Name; i < DolphinModel::ExtraColumnCount; ++i) {
682 columnPositions.append(header()->visualIndex(i));
683 }
684
685 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
686 settings->setColumnPositions(columnPositions);
687 }
688
689 void DolphinDetailsView::slotHeaderSectionResized(int logicalIndex, int oldSize, int newSize)
690 {
691 Q_UNUSED(logicalIndex);
692 Q_UNUSED(oldSize);
693 Q_UNUSED(newSize);
694 // If the user changes the size of the headers, the autoresize feature should be
695 // turned off. As there is no dedicated interface to find out whether the header
696 // section has been resized by the user or by a resize event, another approach is used.
697 // Attention: Take care when changing the if-condition to verify that there is no
698 // regression in combination with bug 178630 (see fix in comment #8).
699 if ((QApplication::mouseButtons() & Qt::LeftButton) && header()->underMouse()) {
700 disableAutoResizing();
701 }
702
703 adjustMaximumSizeForEditing(currentIndex());
704 }
705
706 void DolphinDetailsView::slotActivationChanged(bool active)
707 {
708 setAlternatingRowColors(active);
709 }
710
711 void DolphinDetailsView::disableAutoResizing()
712 {
713 m_autoResize = false;
714 }
715
716 void DolphinDetailsView::requestActivation()
717 {
718 m_dolphinViewController->requestActivation();
719 }
720
721 void DolphinDetailsView::slotGlobalSettingsChanged(int category)
722 {
723 Q_UNUSED(category);
724
725 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
726 Q_ASSERT(settings != 0);
727 if (settings->useSystemFont()) {
728 m_font = KGlobalSettings::generalFont();
729 }
730 //Disconnect then reconnect, since the settings have been changed, the connection requirements may have also.
731 disconnect(this, SIGNAL(clicked(QModelIndex)), m_dolphinViewController, SLOT(triggerItem(QModelIndex)));
732 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), m_dolphinViewController, SLOT(triggerItem(QModelIndex)));
733 if (KGlobalSettings::singleClick()) {
734 connect(this, SIGNAL(clicked(QModelIndex)), m_dolphinViewController, SLOT(triggerItem(QModelIndex)));
735 } else {
736 connect(this, SIGNAL(doubleClicked(QModelIndex)), m_dolphinViewController, SLOT(triggerItem(QModelIndex)));
737 }
738 }
739
740 void DolphinDetailsView::updateElasticBandSelection()
741 {
742 if (!m_band.show) {
743 return;
744 }
745
746 // Ensure the elastic band itself is up-to-date, in
747 // case we are being called due to e.g. a drag event.
748 updateElasticBand();
749
750 // Clip horizontally to the name column, as some filenames will be
751 // longer than the column. We don't clip vertically as origin
752 // may be above or below the current viewport area.
753 const int nameColumnX = header()->sectionPosition(DolphinModel::Name);
754 const int nameColumnWidth = header()->sectionSize(DolphinModel::Name);
755 QRect selRect = elasticBandRect().normalized();
756 QRect nameColumnArea(nameColumnX, selRect.y(), nameColumnWidth, selRect.height());
757 selRect = nameColumnArea.intersect(selRect).normalized();
758 // Get the last elastic band rectangle, expressed in viewpoint coordinates.
759 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
760 QRect oldSelRect = QRect(m_band.lastSelectionOrigin - scrollPos, m_band.lastSelectionDestination - scrollPos).normalized();
761
762 if (selRect.isNull()) {
763 selectionModel()->select(m_band.originalSelection, QItemSelectionModel::ClearAndSelect);
764 m_band.ignoreOldInfo = true;
765 return;
766 }
767
768 if (!m_band.ignoreOldInfo) {
769 // Do some quick checks to see if we can rule out the need to
770 // update the selection.
771 Q_ASSERT(uniformRowHeights());
772 QModelIndex dummyIndex = model()->index(0, 0);
773 if (!dummyIndex.isValid()) {
774 // No items in the model presumably.
775 return;
776 }
777
778 // If the elastic band does not cover the same rows as before, we'll
779 // need to re-check, and also invalidate the old item distances.
780 const int rowHeight = QTreeView::rowHeight(dummyIndex);
781 const bool coveringSameRows =
782 (selRect.top() / rowHeight == oldSelRect.top() / rowHeight) &&
783 (selRect.bottom() / rowHeight == oldSelRect.bottom() / rowHeight);
784 if (coveringSameRows) {
785 // Covering the same rows, but have we moved far enough horizontally
786 // that we might have (de)selected some other items?
787 const bool itemSelectionChanged =
788 ((selRect.left() > oldSelRect.left()) &&
789 (selRect.left() > m_band.insideNearestLeftEdge)) ||
790 ((selRect.left() < oldSelRect.left()) &&
791 (selRect.left() <= m_band.outsideNearestLeftEdge)) ||
792 ((selRect.right() < oldSelRect.right()) &&
793 (selRect.left() >= m_band.insideNearestRightEdge)) ||
794 ((selRect.right() > oldSelRect.right()) &&
795 (selRect.right() >= m_band.outsideNearestRightEdge));
796
797 if (!itemSelectionChanged) {
798 return;
799 }
800 }
801 } else {
802 // This is the only piece of optimization data that needs to be explicitly
803 // discarded.
804 m_band.lastSelectionOrigin = QPoint();
805 m_band.lastSelectionDestination = QPoint();
806 oldSelRect = selRect;
807 }
808
809 // Do the selection from scratch. Force a update of the horizontal distances info.
810 m_band.insideNearestLeftEdge = nameColumnX + nameColumnWidth + 1;
811 m_band.insideNearestRightEdge = nameColumnX - 1;
812 m_band.outsideNearestLeftEdge = nameColumnX - 1;
813 m_band.outsideNearestRightEdge = nameColumnX + nameColumnWidth + 1;
814
815 // Include the old selection rect as well, so we can deselect
816 // items that were inside it but not in the new selRect.
817 const QRect boundingRect = selRect.united(oldSelRect).normalized();
818 if (boundingRect.isNull()) {
819 return;
820 }
821
822 // Get the index of the item in this row in the name column.
823 // TODO - would this still work if the columns could be re-ordered?
824 QModelIndex startIndex = QTreeView::indexAt(boundingRect.topLeft());
825 if (startIndex.parent().isValid()) {
826 startIndex = startIndex.parent().child(startIndex.row(), KDirModel::Name);
827 } else {
828 startIndex = model()->index(startIndex.row(), KDirModel::Name);
829 }
830 if (!startIndex.isValid()) {
831 selectionModel()->select(m_band.originalSelection, QItemSelectionModel::ClearAndSelect);
832 m_band.ignoreOldInfo = true;
833 return;
834 }
835
836 // Go through all indexes between the top and bottom of boundingRect, and
837 // update the selection.
838 const int verticalCutoff = boundingRect.bottom();
839 QModelIndex currIndex = startIndex;
840 QModelIndex lastIndex;
841 bool allItemsInBoundDone = false;
842
843 // Calling selectionModel()->select(...) for each item that needs to be
844 // toggled is slow as each call emits selectionChanged(...) so store them
845 // and do the selection toggle in one batch.
846 QItemSelection itemsToToggle;
847 // QItemSelection's deal with continuous ranges of indexes better than
848 // single indexes, so try to portion items that need to be toggled into ranges.
849 bool formingToggleIndexRange = false;
850 QModelIndex toggleIndexRangeBegin = QModelIndex();
851
852 do {
853 QRect currIndexRect = visualRect(currIndex);
854
855 // Update some optimization info as we go.
856 const int cr = currIndexRect.right();
857 const int cl = currIndexRect.left();
858 const int sl = selRect.left();
859 const int sr = selRect.right();
860 // "The right edge of the name is outside of the rect but nearer than m_outsideNearestLeft", etc
861 if ((cr < sl && cr > m_band.outsideNearestLeftEdge)) {
862 m_band.outsideNearestLeftEdge = cr;
863 }
864 if ((cl > sr && cl < m_band.outsideNearestRightEdge)) {
865 m_band.outsideNearestRightEdge = cl;
866 }
867 if ((cl >= sl && cl <= sr && cl > m_band.insideNearestRightEdge)) {
868 m_band.insideNearestRightEdge = cl;
869 }
870 if ((cr >= sl && cr <= sr && cr < m_band.insideNearestLeftEdge)) {
871 m_band.insideNearestLeftEdge = cr;
872 }
873
874 bool currentlySelected = selectionModel()->isSelected(currIndex);
875 bool originallySelected = m_band.originalSelection.contains(currIndex);
876 bool intersectsSelectedRect = currIndexRect.intersects(selRect);
877 bool shouldBeSelected = (intersectsSelectedRect && !originallySelected) || (!intersectsSelectedRect && originallySelected);
878 bool needToToggleItem = (currentlySelected && !shouldBeSelected) || (!currentlySelected && shouldBeSelected);
879 if (needToToggleItem && !formingToggleIndexRange) {
880 toggleIndexRangeBegin = currIndex;
881 formingToggleIndexRange = true;
882 }
883
884 // NOTE: indexBelow actually walks up and down expanded trees for us.
885 QModelIndex nextIndex = indexBelow(currIndex);
886 allItemsInBoundDone = !nextIndex.isValid() || currIndexRect.top() > verticalCutoff;
887
888 const bool commitToggleIndexRange = formingToggleIndexRange &&
889 (!needToToggleItem ||
890 allItemsInBoundDone ||
891 currIndex.parent() != toggleIndexRangeBegin.parent());
892 if (commitToggleIndexRange) {
893 formingToggleIndexRange = false;
894 // If this is the last item in the bounds and it is also the beginning of a range,
895 // don't toggle lastIndex - it will already have been dealt with.
896 if (!allItemsInBoundDone || toggleIndexRangeBegin != currIndex) {
897 itemsToToggle.select(toggleIndexRangeBegin, lastIndex);
898 }
899 // Need to start a new range immediately with currIndex?
900 if (needToToggleItem) {
901 toggleIndexRangeBegin = currIndex;
902 formingToggleIndexRange = true;
903 }
904 if (allItemsInBoundDone && needToToggleItem) {
905 // Toggle the very last item in the bounds.
906 itemsToToggle.select(currIndex, currIndex);
907 }
908 }
909
910 // next item
911 lastIndex = currIndex;
912 currIndex = nextIndex;
913 } while (!allItemsInBoundDone);
914
915
916 selectionModel()->select(itemsToToggle, QItemSelectionModel::Toggle);
917
918 m_band.lastSelectionOrigin = m_band.origin;
919 m_band.lastSelectionDestination = m_band.destination;
920 m_band.ignoreOldInfo = false;
921 }
922
923 void DolphinDetailsView::setFoldersExpandable(bool expandable)
924 {
925 if (!expandable) {
926 // collapse all expanded folders, as QTreeView::setItemsExpandable(false)
927 // does not do this task
928 const int rowCount = model()->rowCount();
929 for (int row = 0; row < rowCount; ++row) {
930 setExpanded(model()->index(row, 0), false);
931 }
932 }
933 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
934 settings->setExpandableFolders(expandable);
935 setRootIsDecorated(expandable);
936 setItemsExpandable(expandable);
937
938 // The width of the space which is available for editing has changed
939 // because of the (dis)appearance of the expanding toggles
940 adjustMaximumSizeForEditing(currentIndex());
941 }
942
943 void DolphinDetailsView::slotExpanded(const QModelIndex& index)
944 {
945 KFileItem item = m_dolphinViewController->itemForIndex(index);
946 if (!item.isNull()) {
947 m_expandedUrls.insert(item.url());
948 }
949 }
950
951 void DolphinDetailsView::slotCollapsed(const QModelIndex& index)
952 {
953 KFileItem item = m_dolphinViewController->itemForIndex(index);
954 if (!item.isNull()) {
955 m_expandedUrls.remove(item.url());
956 }
957 }
958
959 void DolphinDetailsView::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
960 {
961 removeExpandedIndexes(parent, start, end);
962 QTreeView::rowsAboutToBeRemoved(parent, start, end);
963 }
964
965 void DolphinDetailsView::removeExpandedIndexes(const QModelIndex& parent, int start, int end)
966 {
967 if (m_expandedUrls.isEmpty()) {
968 return;
969 }
970
971 for (int row = start; row <= end; row++) {
972 const QModelIndex index = model()->index(row, 0, parent);
973 if (isExpanded(index)) {
974 slotCollapsed(index);
975 removeExpandedIndexes(index, 0, model()->rowCount(index) - 1);
976 }
977 }
978 }
979
980 void DolphinDetailsView::updateDecorationSize(bool showPreview)
981 {
982 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
983 const int iconSize = showPreview ? settings->previewSize() : settings->iconSize();
984 setIconSize(QSize(iconSize, iconSize));
985 m_decorationSize = QSize(iconSize, iconSize);
986
987 doItemsLayout();
988 }
989
990 KFileItemDelegate::Information DolphinDetailsView::infoForColumn(int columnIndex) const
991 {
992 KFileItemDelegate::Information info = KFileItemDelegate::NoInformation;
993
994 switch (columnIndex) {
995 case DolphinModel::Size: info = KFileItemDelegate::Size; break;
996 case DolphinModel::ModifiedTime: info = KFileItemDelegate::ModificationTime; break;
997 case DolphinModel::Permissions: info = KFileItemDelegate::Permissions; break;
998 case DolphinModel::Owner: info = KFileItemDelegate::Owner; break;
999 case DolphinModel::Group: info = KFileItemDelegate::OwnerAndGroup; break;
1000 case DolphinModel::Type: info = KFileItemDelegate::FriendlyMimeType; break;
1001 case DolphinModel::LinkDestination: info = KFileItemDelegate::LinkDest; break;
1002 default: break;
1003 }
1004
1005 return info;
1006 }
1007
1008 void DolphinDetailsView::resizeColumns()
1009 {
1010 // Using the resize mode QHeaderView::ResizeToContents is too slow (it takes
1011 // around 3 seconds for each (!) resize operation when having > 10000 items).
1012 // This gets a problem especially when opening large directories, where several
1013 // resize operations are received for showing the currently available items during
1014 // loading (the application hangs around 20 seconds when loading > 10000 items).
1015
1016 QHeaderView* headerView = header();
1017 QFontMetrics fontMetrics(viewport()->font());
1018
1019 int columnWidth[DolphinModel::ExtraColumnCount];
1020 columnWidth[DolphinModel::Size] = fontMetrics.width("00000 Items");
1021 columnWidth[DolphinModel::ModifiedTime] = fontMetrics.width("0000-00-00 00:00");
1022 columnWidth[DolphinModel::Permissions] = fontMetrics.width("xxxxxxxxxx");
1023 columnWidth[DolphinModel::Owner] = fontMetrics.width("xxxxxxxxxx");
1024 columnWidth[DolphinModel::Group] = fontMetrics.width("xxxxxxxxxx");
1025 columnWidth[DolphinModel::Type] = fontMetrics.width("XXXX Xxxxxxx");
1026 columnWidth[DolphinModel::Version] = fontMetrics.width("xxxxxxxx");
1027 columnWidth[DolphinModel::LinkDestination] = fontMetrics.width("xxxxxxxx");
1028
1029 int requiredWidth = 0;
1030 for (int i = KDirModel::Size; i <= KDirModel::Type; ++i) {
1031 if (!isColumnHidden(i)) {
1032 columnWidth[i] += 20; // provide a default gap
1033 requiredWidth += columnWidth[i];
1034 headerView->resizeSection(i, columnWidth[i]);
1035 }
1036 }
1037
1038 // resize the name column in a way that the whole available width is used
1039 columnWidth[KDirModel::Name] = viewport()->width() - requiredWidth;
1040
1041 const int minNameWidth = 300;
1042 if (columnWidth[KDirModel::Name] < minNameWidth) {
1043 columnWidth[KDirModel::Name] = minNameWidth;
1044
1045 // It might be possible that the name column width can be
1046 // decreased without clipping any text. For performance
1047 // reasons the exact necessary width for full visible names is
1048 // only checked for up to 200 items:
1049 const int rowCount = model()->rowCount();
1050 if (rowCount > 0 && rowCount < 200) {
1051 const int nameWidth = sizeHintForColumn(DolphinModel::Name);
1052 if (nameWidth + requiredWidth <= viewport()->width()) {
1053 columnWidth[KDirModel::Name] = viewport()->width() - requiredWidth;
1054 } else if (nameWidth < minNameWidth) {
1055 columnWidth[KDirModel::Name] = nameWidth;
1056 }
1057 }
1058 }
1059
1060 headerView->resizeSection(KDirModel::Name, columnWidth[KDirModel::Name]);
1061 }
1062
1063 bool DolphinDetailsView::isAboveExpandingToggle(const QPoint& pos) const
1064 {
1065 // QTreeView offers no public API to get the information whether an index has an
1066 // expanding toggle and what boundaries the toggle has. The following approach
1067 // also assumes a toggle for file items.
1068 if (itemsExpandable()) {
1069 const QModelIndex index = QTreeView::indexAt(pos);
1070 if (index.isValid() && (index.column() == KDirModel::Name)) {
1071 QRect rect = visualRect(index);
1072 const int toggleSize = rect.height();
1073 if (isRightToLeft()) {
1074 rect.moveRight(rect.right());
1075 } else {
1076 rect.moveLeft(rect.x() - toggleSize);
1077 }
1078 rect.setWidth(toggleSize);
1079
1080 QStyleOption opt;
1081 opt.initFrom(this);
1082 opt.rect = rect;
1083 rect = style()->subElementRect(QStyle::SE_TreeViewDisclosureItem, &opt, this);
1084
1085 return rect.contains(pos);
1086 }
1087 }
1088 return false;
1089 }
1090
1091 void DolphinDetailsView::adjustMaximumSizeForEditing(const QModelIndex& index)
1092 {
1093 // Make sure that the full width of the "Name" column is available for "Rename Inline"
1094 m_extensionsFactory->fileItemDelegate()->setMaximumSize(QTreeView::visualRect(index).size());
1095 }
1096
1097 DolphinDetailsView::ElasticBand::ElasticBand() :
1098 show(false),
1099 origin(),
1100 destination(),
1101 lastSelectionOrigin(),
1102 lastSelectionDestination(),
1103 ignoreOldInfo(true),
1104 outsideNearestLeftEdge(0),
1105 outsideNearestRightEdge(0),
1106 insideNearestLeftEdge(0),
1107 insideNearestRightEdge(0)
1108 {
1109 }
1110
1111 #include "dolphindetailsview.moc"