]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphindetailsview.cpp
Restore "show hidden files" functionality in a generic way which works also for the...
[dolphin.git] / src / dolphindetailsview.cpp
1 /***************************************************************************
2 * Copyright (C) 2006 by Peter Penz (peter.penz@gmx.at) *
3 * Copyright (C) 2008 by Simon St. James (kdedevel@etotheipiplusone.com) *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
19 ***************************************************************************/
20
21 #include "dolphindetailsview.h"
22
23 #include "dolphinmodel.h"
24 #include "dolphincontroller.h"
25 #include "dolphinfileitemdelegate.h"
26 #include "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"
33
34 #include "dolphin_detailsmodesettings.h"
35 #include "dolphin_generalsettings.h"
36
37 #include <kdirmodel.h>
38 #include <klocale.h>
39 #include <kmenu.h>
40
41 #include <QAction>
42 #include <QApplication>
43 #include <QHeaderView>
44 #include <QRubberBand>
45 #include <QPainter>
46 #include <QScrollBar>
47
48 DolphinDetailsView::DolphinDetailsView(QWidget* parent,
49 DolphinController* controller,
50 DolphinSortFilterProxyModel* proxyModel) :
51 QTreeView(parent),
52 m_autoResize(true),
53 m_expandingTogglePressed(false),
54 m_keyPressed(false),
55 m_useDefaultIndexAt(true),
56 m_ignoreScrollTo(false),
57 m_controller(controller),
58 m_extensionsFactory(0),
59 m_expandableFoldersAction(0),
60 m_font(),
61 m_decorationSize(),
62 m_band()
63 {
64 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
65 Q_ASSERT(settings != 0);
66 Q_ASSERT(controller != 0);
67
68 setLayoutDirection(Qt::LeftToRight);
69 setAcceptDrops(true);
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);
79 setModel(proxyModel);
80
81 setMouseTracking(true);
82
83 const ViewProperties props(controller->url());
84 setSortIndicatorSection(props.sorting());
85 setSortIndicatorOrder(props.sortOrder());
86
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()));
97
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)));
102
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&)));
108 } else {
109 connect(this, SIGNAL(doubleClicked(const QModelIndex&)),
110 controller, SLOT(triggerItem(const QModelIndex&)));
111 }
112
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)));
125
126 if (settings->useSystemFont()) {
127 m_font = KGlobalSettings::generalFont();
128 } else {
129 m_font = QFont(settings->fontFamily(),
130 settings->fontSize(),
131 settings->fontWeight(),
132 settings->italicFont());
133 }
134
135 setVerticalScrollMode(QTreeView::ScrollPerPixel);
136 setHorizontalScrollMode(QTreeView::ScrollPerPixel);
137
138 const DolphinView* view = controller->dolphinView();
139 connect(view, SIGNAL(showPreviewChanged()),
140 this, SLOT(slotShowPreviewChanged()));
141
142
143 setFocus();
144 viewport()->installEventFilter(this);
145
146 connect(KGlobalSettings::self(), SIGNAL(settingsChanged(int)),
147 this, SLOT(slotGlobalSettingsChanged(int)));
148
149 m_useDefaultIndexAt = false;
150
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)));
155
156 m_extensionsFactory = new ViewExtensionsFactory(this, controller);
157 m_extensionsFactory->fileItemDelegate()->setMinimizedNameColumn(true);
158
159 updateDecorationSize(view->showPreview());
160 }
161
162 DolphinDetailsView::~DolphinDetailsView()
163 {
164 }
165
166 bool DolphinDetailsView::event(QEvent* event)
167 {
168 if (event->type() == QEvent::Polish) {
169 header()->setResizeMode(QHeaderView::Interactive);
170 updateColumnVisibility();
171 }
172
173 return QTreeView::event(event);
174 }
175
176 QStyleOptionViewItem DolphinDetailsView::viewOptions() const
177 {
178 QStyleOptionViewItem viewOptions = QTreeView::viewOptions();
179 viewOptions.font = m_font;
180 viewOptions.showDecorationSelected = true;
181 viewOptions.decorationSize = m_decorationSize;
182 return viewOptions;
183 }
184
185 void DolphinDetailsView::contextMenuEvent(QContextMenuEvent* event)
186 {
187 QTreeView::contextMenuEvent(event);
188
189 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
190 m_expandableFoldersAction->setChecked(settings->expandableFolders());
191 m_controller->triggerContextMenuRequest(event->pos(),
192 QList<QAction*>() << m_expandableFoldersAction);
193 }
194
195 void DolphinDetailsView::mousePressEvent(QMouseEvent* event)
196 {
197 m_controller->requestActivation();
198
199 const QModelIndex current = currentIndex();
200 QTreeView::mousePressEvent(event);
201
202 m_expandingTogglePressed = isAboveExpandingToggle(event->pos());
203
204 const QModelIndex index = indexAt(event->pos());
205 const bool updateState = index.isValid() &&
206 (index.column() == DolphinModel::Name) &&
207 (event->button() == Qt::LeftButton);
208 if (updateState) {
209 setState(QAbstractItemView::DraggingState);
210 }
211
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();
216 }
217
218 const Qt::KeyboardModifiers mod = QApplication::keyboardModifiers();
219 if (!m_expandingTogglePressed && !(mod & Qt::ShiftModifier) && !(mod & Qt::ControlModifier)) {
220 clearSelection();
221 }
222
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;
228
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);
232 m_band.show = true;
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();
239 }
240 }
241 }
242
243 void DolphinDetailsView::mouseMoveEvent(QMouseEvent* event)
244 {
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);
250 return;
251 }
252
253 if (m_band.show) {
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();
261 }
262
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);
267 updateElasticBand();
268 } else {
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);
273 }
274 }
275
276 void DolphinDetailsView::mouseReleaseEvent(QMouseEvent* event)
277 {
278 if (!m_expandingTogglePressed) {
279 const QModelIndex index = indexAt(event->pos());
280 if (index.isValid() && (index.column() == DolphinModel::Name)) {
281 QTreeView::mouseReleaseEvent(event);
282 } else {
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);
289 }
290 }
291 m_expandingTogglePressed = false;
292
293 if (m_band.show) {
294 setState(NoState);
295 updateElasticBand();
296 m_band.show = false;
297 }
298 }
299
300 void DolphinDetailsView::startDrag(Qt::DropActions supportedActions)
301 {
302 DragAndDropHelper::instance().startDrag(this, supportedActions, m_controller);
303 m_band.show = false;
304 }
305
306 void DolphinDetailsView::dragEnterEvent(QDragEnterEvent* event)
307 {
308 if (DragAndDropHelper::instance().isMimeDataSupported(event->mimeData())) {
309 event->acceptProposedAction();
310 }
311
312 if (m_band.show) {
313 updateElasticBand();
314 m_band.show = false;
315 }
316 }
317
318 void DolphinDetailsView::dragLeaveEvent(QDragLeaveEvent* event)
319 {
320 QTreeView::dragLeaveEvent(event);
321 setDirtyRegion(m_dropRect);
322 }
323
324 void DolphinDetailsView::dragMoveEvent(QDragMoveEvent* event)
325 {
326 QTreeView::dragMoveEvent(event);
327
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);
335 } else {
336 m_dropRect.setSize(QSize()); // set as invalid
337 }
338 setDirtyRegion(m_dropRect);
339 }
340
341 if (DragAndDropHelper::instance().isMimeDataSupported(event->mimeData())) {
342 // accept url drops, independently from the destination item
343 event->acceptProposedAction();
344 }
345 }
346
347 void DolphinDetailsView::dropEvent(QDropEvent* event)
348 {
349 const QModelIndex index = indexAt(event->pos());
350 KFileItem item;
351 if (index.isValid() && (index.column() == DolphinModel::Name)) {
352 item = m_controller->itemForIndex(index);
353 }
354 m_controller->indicateDroppedUrls(item, m_controller->url(), event);
355 QTreeView::dropEvent(event);
356 }
357
358 void DolphinDetailsView::paintEvent(QPaintEvent* event)
359 {
360 QTreeView::paintEvent(event);
361 if (m_band.show) {
362 // The following code has been taken from QListView
363 // and adapted to DolphinDetailsView.
364 // (C) 1992-2007 Trolltech ASA
365 QStyleOptionRubberBand opt;
366 opt.initFrom(this);
367 opt.shape = QRubberBand::Rectangle;
368 opt.opaque = false;
369 opt.rect = elasticBandRect();
370
371 QPainter painter(viewport());
372 painter.save();
373 style()->drawControl(QStyle::CE_RubberBand, &opt, &painter);
374 painter.restore();
375 }
376 }
377
378 void DolphinDetailsView::keyPressEvent(QKeyEvent* event)
379 {
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);
384
385 QTreeView::keyPressEvent(event);
386 m_controller->handleKeyPressEvent(event);
387 }
388
389 void DolphinDetailsView::keyReleaseEvent(QKeyEvent* event)
390 {
391 QTreeView::keyReleaseEvent(event);
392 m_keyPressed = false;
393 }
394
395 void DolphinDetailsView::resizeEvent(QResizeEvent* event)
396 {
397 QTreeView::resizeEvent(event);
398 if (m_autoResize) {
399 resizeColumns();
400 }
401 }
402
403 void DolphinDetailsView::wheelEvent(QWheelEvent* event)
404 {
405 // let Ctrl+wheel events propagate to the DolphinView for icon zooming
406 if (event->modifiers() & Qt::ControlModifier) {
407 event->ignore();
408 return;
409 }
410
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);
415 }
416
417 void DolphinDetailsView::currentChanged(const QModelIndex& current, const QModelIndex& previous)
418 {
419 QTreeView::currentChanged(current, previous);
420 m_extensionsFactory->handleCurrentIndexChange(current, previous);
421
422 // Stay consistent with QListView: When changing the current index by key presses,
423 // also change the selection.
424 if (m_keyPressed) {
425 selectionModel()->select(current, QItemSelectionModel::ClearAndSelect);
426 }
427 }
428
429 bool DolphinDetailsView::eventFilter(QObject* watched, QEvent* event)
430 {
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();
436 }
437
438 return QTreeView::eventFilter(watched, event);
439 }
440
441 QModelIndex DolphinDetailsView::indexAt(const QPoint& point) const
442 {
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;
448 }
449
450 void DolphinDetailsView::setSelection(const QRect& rect, QItemSelectionModel::SelectionFlags command)
451 {
452 // We must override setSelection() as Qt calls it internally and when this happens
453 // we must ensure that the default indexAt() is used.
454 if (!m_band.show) {
455 m_useDefaultIndexAt = true;
456 QTreeView::setSelection(rect, command);
457 m_useDefaultIndexAt = false;
458 } else {
459 // Use our own elastic band selection algorithm
460 updateElasticBandSelection();
461 }
462 }
463
464 void DolphinDetailsView::scrollTo(const QModelIndex & index, ScrollHint hint)
465 {
466 if (!m_ignoreScrollTo) {
467 QTreeView::scrollTo(index, hint);
468 }
469 }
470
471 void DolphinDetailsView::setSortIndicatorSection(DolphinView::Sorting sorting)
472 {
473 header()->setSortIndicator(sorting, header()->sortIndicatorOrder());
474 }
475
476 void DolphinDetailsView::setSortIndicatorOrder(Qt::SortOrder sortOrder)
477 {
478 header()->setSortIndicator(header()->sortIndicatorSection(), sortOrder);
479 }
480
481 void DolphinDetailsView::synchronizeSortingState(int column)
482 {
483 // The sorting has already been changed in QTreeView if this slot is
484 // invoked, but Dolphin is not informed about this.
485 DolphinView::Sorting sorting = DolphinSortFilterProxyModel::sortingForColumn(column);
486 const Qt::SortOrder sortOrder = header()->sortIndicatorOrder();
487 m_controller->indicateSortingChange(sorting);
488 m_controller->indicateSortOrderChange(sortOrder);
489 }
490
491 void DolphinDetailsView::slotEntered(const QModelIndex& index)
492 {
493 if (index.column() == DolphinModel::Name) {
494 m_controller->emitItemEntered(index);
495 } else {
496 m_controller->emitViewportEntered();
497 }
498 }
499
500 void DolphinDetailsView::updateElasticBand()
501 {
502 if (m_band.show) {
503 QRect dirtyRegion(elasticBandRect());
504 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
505 m_band.destination = viewport()->mapFromGlobal(QCursor::pos()) + scrollPos;
506 // 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);
510 }
511 if (m_band.destination.x() < 0) {
512 m_band.destination.setX(0);
513 }
514 dirtyRegion = dirtyRegion.united(elasticBandRect());
515 setDirtyRegion(dirtyRegion);
516 }
517 }
518
519 QRect DolphinDetailsView::elasticBandRect() const
520 {
521 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
522
523 const QPoint topLeft = m_band.origin - scrollPos;
524 const QPoint bottomRight = m_band.destination - scrollPos;
525 return QRect(topLeft, bottomRight).normalized();
526 }
527
528 void DolphinDetailsView::setNameFilter(const QString& nameFilter)
529 {
530 DolphinSortFilterProxyModel* proxyModel = static_cast<DolphinSortFilterProxyModel*>(model());
531 proxyModel->setFilterRegExp(nameFilter);
532 }
533
534 void DolphinDetailsView::setZoomLevel(int level)
535 {
536 const int size = ZoomLevelInfo::iconSizeForZoomLevel(level);
537 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
538
539 const bool showPreview = m_controller->dolphinView()->showPreview();
540 if (showPreview) {
541 settings->setPreviewSize(size);
542 } else {
543 settings->setIconSize(size);
544 }
545
546 updateDecorationSize(showPreview);
547 }
548
549 void DolphinDetailsView::slotShowPreviewChanged()
550 {
551 const DolphinView* view = m_controller->dolphinView();
552 updateDecorationSize(view->showPreview());
553 }
554
555 void DolphinDetailsView::configureSettings(const QPoint& pos)
556 {
557 KMenu popup(this);
558 popup.addTitle(i18nc("@title:menu", "Columns"));
559
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);
571 }
572 popup.addSeparator();
573
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();
578
579 KFileItemDelegate::InformationList list = m_controller->dolphinView()->additionalInfo();
580 const KFileItemDelegate::Information info = infoForColumn(columnIndex);
581 if (show) {
582 Q_ASSERT(!list.contains(info));
583 list.append(info);
584 } else {
585 Q_ASSERT(list.contains(info));
586 const int index = list.indexOf(info);
587 list.removeAt(index);
588 }
589
590 m_controller->indicateAdditionalInfoChange(list);
591 setColumnHidden(columnIndex, !show);
592 resizeColumns();
593 }
594 }
595
596 void DolphinDetailsView::updateColumnVisibility()
597 {
598 QHeaderView* headerView = header();
599 disconnect(headerView, SIGNAL(sectionMoved(int, int, int)),
600 this, SLOT(saveColumnPositions()));
601
602 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
603 const QList<int> columnPositions = settings->columnPositions();
604
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);
611 }
612
613 const int from = headerView->visualIndex(i);
614 headerView->moveSection(from, columnPositions[i]);
615 }
616
617 resizeColumns();
618
619 connect(headerView, SIGNAL(sectionMoved(int, int, int)),
620 this, SLOT(saveColumnPositions()));
621
622 }
623
624 void DolphinDetailsView::saveColumnPositions()
625 {
626 QList<int> columnPositions;
627 for (int i = DolphinModel::Name; i <= DolphinModel::Version; ++i) {
628 columnPositions.append(header()->visualIndex(i));
629 }
630
631 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
632 settings->setColumnPositions(columnPositions);
633 }
634
635 void DolphinDetailsView::slotHeaderSectionResized(int logicalIndex, int oldSize, int newSize)
636 {
637 Q_UNUSED(logicalIndex);
638 Q_UNUSED(oldSize);
639 Q_UNUSED(newSize);
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();
647 }
648 }
649
650 void DolphinDetailsView::slotActivationChanged(bool active)
651 {
652 setAlternatingRowColors(active);
653 }
654
655 void DolphinDetailsView::disableAutoResizing()
656 {
657 m_autoResize = false;
658 }
659
660 void DolphinDetailsView::requestActivation()
661 {
662 m_controller->requestActivation();
663 }
664
665 void DolphinDetailsView::slotGlobalSettingsChanged(int category)
666 {
667 Q_UNUSED(category);
668
669 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
670 Q_ASSERT(settings != 0);
671 if (settings->useSystemFont()) {
672 m_font = KGlobalSettings::generalFont();
673 }
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)));
679 } else {
680 connect(this, SIGNAL(doubleClicked(QModelIndex)), m_controller, SLOT(triggerItem(QModelIndex)));
681 }
682 }
683
684 void DolphinDetailsView::updateElasticBandSelection()
685 {
686 if (!m_band.show) {
687 return;
688 }
689
690 // Ensure the elastic band itself is up-to-date, in
691 // case we are being called due to e.g. a drag event.
692 updateElasticBand();
693
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();
705
706 if (selRect.isNull()) {
707 selectionModel()->select(m_band.originalSelection, QItemSelectionModel::ClearAndSelect);
708 m_band.ignoreOldInfo = true;
709 return;
710 }
711
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.
719 return;
720 }
721
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));
740
741 if (!itemSelectionChanged) {
742 return;
743 }
744 }
745 }
746 else {
747 // This is the only piece of optimization data that needs to be explicitly
748 // discarded.
749 m_band.lastSelectionOrigin = QPoint();
750 m_band.lastSelectionDestination = QPoint();
751 oldSelRect = selRect;
752 }
753
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;
759
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()) {
764 return;
765 }
766
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);
772 } else {
773 startIndex = model()->index(startIndex.row(), KDirModel::Name);
774 }
775 if (!startIndex.isValid()) {
776 selectionModel()->select(m_band.originalSelection, QItemSelectionModel::ClearAndSelect);
777 m_band.ignoreOldInfo = true;
778 return;
779 }
780
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;
787
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();
796
797 do {
798 QRect currIndexRect = nameColumnRect(currIndex);
799
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;
808 }
809 if ((cl > sr && cl < m_band.outsideNearestRightEdge)) {
810 m_band.outsideNearestRightEdge = cl;
811 }
812 if ((cl >= sl && cl <= sr && cl > m_band.insideNearestRightEdge)) {
813 m_band.insideNearestRightEdge = cl;
814 }
815 if ((cr >= sl && cr <= sr && cr < m_band.insideNearestLeftEdge)) {
816 m_band.insideNearestLeftEdge = cr;
817 }
818
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;
827 }
828
829 // NOTE: indexBelow actually walks up and down expanded trees for us.
830 QModelIndex nextIndex = indexBelow(currIndex);
831 allItemsInBoundDone = !nextIndex.isValid() || currIndexRect.top() > verticalCutoff;
832
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);
843 }
844 // Need to start a new range immediately with currIndex?
845 if (needToToggleItem) {
846 toggleIndexRangeBegin = currIndex;
847 formingToggleIndexRange = true;
848 }
849 if (allItemsInBoundDone && needToToggleItem) {
850 // Toggle the very last item in the bounds.
851 itemsToToggle.select(currIndex, currIndex);
852 }
853 }
854
855 // next item
856 lastIndex = currIndex;
857 currIndex = nextIndex;
858 } while (!allItemsInBoundDone);
859
860 selectionModel()->select(itemsToToggle, QItemSelectionModel::Toggle);
861
862 m_band.lastSelectionOrigin = m_band.origin;
863 m_band.lastSelectionDestination = m_band.destination;
864 m_band.ignoreOldInfo = false;
865 }
866
867 void DolphinDetailsView::setFoldersExpandable(bool expandable)
868 {
869 if (!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);
875 }
876 }
877 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
878 settings->setExpandableFolders(expandable);
879 setRootIsDecorated(expandable);
880 setItemsExpandable(expandable);
881 }
882
883 void DolphinDetailsView::updateDecorationSize(bool showPreview)
884 {
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);
889
890 doItemsLayout();
891 }
892
893 KFileItemDelegate::Information DolphinDetailsView::infoForColumn(int columnIndex) const
894 {
895 KFileItemDelegate::Information info = KFileItemDelegate::NoInformation;
896
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;
904 default: break;
905 }
906
907 return info;
908 }
909
910 void DolphinDetailsView::resizeColumns()
911 {
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).
917
918 QHeaderView* headerView = header();
919 QFontMetrics fontMetrics(viewport()->font());
920
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");
929
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]);
936 }
937 }
938
939 // resize the name column in a way that the whole available width is used
940 columnWidth[KDirModel::Name] = viewport()->width() - requiredWidth;
941
942 const int minNameWidth = 300;
943 if (columnWidth[KDirModel::Name] < minNameWidth) {
944 columnWidth[KDirModel::Name] = minNameWidth;
945
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;
957 }
958 }
959 }
960
961 headerView->resizeSection(KDirModel::Name, columnWidth[KDirModel::Name]);
962 }
963
964 QRect DolphinDetailsView::nameColumnRect(const QModelIndex& index) const
965 {
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);
971 }
972
973 return rect;
974 }
975
976 bool DolphinDetailsView::isAboveExpandingToggle(const QPoint& pos) const
977 {
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());
988 } else {
989 rect.moveLeft(rect.x() - toggleSize);
990 }
991 rect.setWidth(toggleSize);
992
993 QStyleOption opt;
994 opt.initFrom(this);
995 opt.rect = rect;
996 rect = style()->subElementRect(QStyle::SE_TreeViewDisclosureItem, &opt, this);
997
998 return rect.contains(pos);
999 }
1000 }
1001 return false;
1002 }
1003
1004 DolphinDetailsView::ElasticBand::ElasticBand() :
1005 show(false),
1006 origin(),
1007 destination(),
1008 lastSelectionOrigin(),
1009 lastSelectionDestination(),
1010 ignoreOldInfo(true),
1011 outsideNearestLeftEdge(0),
1012 outsideNearestRightEdge(0),
1013 insideNearestLeftEdge(0),
1014 insideNearestRightEdge(0)
1015 {
1016 }
1017
1018 #include "dolphindetailsview.moc"