]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphindetailsview.cpp
Allow to add menu groups like "View Mode", "Sort By"... to be added as toolbar item...
[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::Version; ++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 const int from = headerView->visualIndex(i);
658 headerView->moveSection(from, columnPositions[i]);
659 }
660
661 resizeColumns();
662
663 connect(headerView, SIGNAL(sectionMoved(int, int, int)),
664 this, SLOT(saveColumnPositions()));
665
666 }
667
668 void DolphinDetailsView::saveColumnPositions()
669 {
670 QList<int> columnPositions;
671 for (int i = DolphinModel::Name; i <= DolphinModel::Version; ++i) {
672 columnPositions.append(header()->visualIndex(i));
673 }
674
675 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
676 settings->setColumnPositions(columnPositions);
677 }
678
679 void DolphinDetailsView::slotHeaderSectionResized(int logicalIndex, int oldSize, int newSize)
680 {
681 Q_UNUSED(logicalIndex);
682 Q_UNUSED(oldSize);
683 Q_UNUSED(newSize);
684 // If the user changes the size of the headers, the autoresize feature should be
685 // turned off. As there is no dedicated interface to find out whether the header
686 // section has been resized by the user or by a resize event, another approach is used.
687 // Attention: Take care when changing the if-condition to verify that there is no
688 // regression in combination with bug 178630 (see fix in comment #8).
689 if ((QApplication::mouseButtons() & Qt::LeftButton) && header()->underMouse()) {
690 disableAutoResizing();
691 }
692
693 adjustMaximumSizeForEditing(currentIndex());
694 }
695
696 void DolphinDetailsView::slotActivationChanged(bool active)
697 {
698 setAlternatingRowColors(active);
699 }
700
701 void DolphinDetailsView::disableAutoResizing()
702 {
703 m_autoResize = false;
704 }
705
706 void DolphinDetailsView::requestActivation()
707 {
708 m_dolphinViewController->requestActivation();
709 }
710
711 void DolphinDetailsView::slotGlobalSettingsChanged(int category)
712 {
713 Q_UNUSED(category);
714
715 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
716 Q_ASSERT(settings != 0);
717 if (settings->useSystemFont()) {
718 m_font = KGlobalSettings::generalFont();
719 }
720 //Disconnect then reconnect, since the settings have been changed, the connection requirements may have also.
721 disconnect(this, SIGNAL(clicked(QModelIndex)), m_dolphinViewController, SLOT(triggerItem(QModelIndex)));
722 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), m_dolphinViewController, SLOT(triggerItem(QModelIndex)));
723 if (KGlobalSettings::singleClick()) {
724 connect(this, SIGNAL(clicked(QModelIndex)), m_dolphinViewController, SLOT(triggerItem(QModelIndex)));
725 } else {
726 connect(this, SIGNAL(doubleClicked(QModelIndex)), m_dolphinViewController, SLOT(triggerItem(QModelIndex)));
727 }
728 }
729
730 void DolphinDetailsView::updateElasticBandSelection()
731 {
732 if (!m_band.show) {
733 return;
734 }
735
736 // Ensure the elastic band itself is up-to-date, in
737 // case we are being called due to e.g. a drag event.
738 updateElasticBand();
739
740 // Clip horizontally to the name column, as some filenames will be
741 // longer than the column. We don't clip vertically as origin
742 // may be above or below the current viewport area.
743 const int nameColumnX = header()->sectionPosition(DolphinModel::Name);
744 const int nameColumnWidth = header()->sectionSize(DolphinModel::Name);
745 QRect selRect = elasticBandRect().normalized();
746 QRect nameColumnArea(nameColumnX, selRect.y(), nameColumnWidth, selRect.height());
747 selRect = nameColumnArea.intersect(selRect).normalized();
748 // Get the last elastic band rectangle, expressed in viewpoint coordinates.
749 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
750 QRect oldSelRect = QRect(m_band.lastSelectionOrigin - scrollPos, m_band.lastSelectionDestination - scrollPos).normalized();
751
752 if (selRect.isNull()) {
753 selectionModel()->select(m_band.originalSelection, QItemSelectionModel::ClearAndSelect);
754 m_band.ignoreOldInfo = true;
755 return;
756 }
757
758 if (!m_band.ignoreOldInfo) {
759 // Do some quick checks to see if we can rule out the need to
760 // update the selection.
761 Q_ASSERT(uniformRowHeights());
762 QModelIndex dummyIndex = model()->index(0, 0);
763 if (!dummyIndex.isValid()) {
764 // No items in the model presumably.
765 return;
766 }
767
768 // If the elastic band does not cover the same rows as before, we'll
769 // need to re-check, and also invalidate the old item distances.
770 const int rowHeight = QTreeView::rowHeight(dummyIndex);
771 const bool coveringSameRows =
772 (selRect.top() / rowHeight == oldSelRect.top() / rowHeight) &&
773 (selRect.bottom() / rowHeight == oldSelRect.bottom() / rowHeight);
774 if (coveringSameRows) {
775 // Covering the same rows, but have we moved far enough horizontally
776 // that we might have (de)selected some other items?
777 const bool itemSelectionChanged =
778 ((selRect.left() > oldSelRect.left()) &&
779 (selRect.left() > m_band.insideNearestLeftEdge)) ||
780 ((selRect.left() < oldSelRect.left()) &&
781 (selRect.left() <= m_band.outsideNearestLeftEdge)) ||
782 ((selRect.right() < oldSelRect.right()) &&
783 (selRect.left() >= m_band.insideNearestRightEdge)) ||
784 ((selRect.right() > oldSelRect.right()) &&
785 (selRect.right() >= m_band.outsideNearestRightEdge));
786
787 if (!itemSelectionChanged) {
788 return;
789 }
790 }
791 } else {
792 // This is the only piece of optimization data that needs to be explicitly
793 // discarded.
794 m_band.lastSelectionOrigin = QPoint();
795 m_band.lastSelectionDestination = QPoint();
796 oldSelRect = selRect;
797 }
798
799 // Do the selection from scratch. Force a update of the horizontal distances info.
800 m_band.insideNearestLeftEdge = nameColumnX + nameColumnWidth + 1;
801 m_band.insideNearestRightEdge = nameColumnX - 1;
802 m_band.outsideNearestLeftEdge = nameColumnX - 1;
803 m_band.outsideNearestRightEdge = nameColumnX + nameColumnWidth + 1;
804
805 // Include the old selection rect as well, so we can deselect
806 // items that were inside it but not in the new selRect.
807 const QRect boundingRect = selRect.united(oldSelRect).normalized();
808 if (boundingRect.isNull()) {
809 return;
810 }
811
812 // Get the index of the item in this row in the name column.
813 // TODO - would this still work if the columns could be re-ordered?
814 QModelIndex startIndex = QTreeView::indexAt(boundingRect.topLeft());
815 if (startIndex.parent().isValid()) {
816 startIndex = startIndex.parent().child(startIndex.row(), KDirModel::Name);
817 } else {
818 startIndex = model()->index(startIndex.row(), KDirModel::Name);
819 }
820 if (!startIndex.isValid()) {
821 selectionModel()->select(m_band.originalSelection, QItemSelectionModel::ClearAndSelect);
822 m_band.ignoreOldInfo = true;
823 return;
824 }
825
826 // Go through all indexes between the top and bottom of boundingRect, and
827 // update the selection.
828 const int verticalCutoff = boundingRect.bottom();
829 QModelIndex currIndex = startIndex;
830 QModelIndex lastIndex;
831 bool allItemsInBoundDone = false;
832
833 // Calling selectionModel()->select(...) for each item that needs to be
834 // toggled is slow as each call emits selectionChanged(...) so store them
835 // and do the selection toggle in one batch.
836 QItemSelection itemsToToggle;
837 // QItemSelection's deal with continuous ranges of indexes better than
838 // single indexes, so try to portion items that need to be toggled into ranges.
839 bool formingToggleIndexRange = false;
840 QModelIndex toggleIndexRangeBegin = QModelIndex();
841
842 do {
843 QRect currIndexRect = visualRect(currIndex);
844
845 // Update some optimization info as we go.
846 const int cr = currIndexRect.right();
847 const int cl = currIndexRect.left();
848 const int sl = selRect.left();
849 const int sr = selRect.right();
850 // "The right edge of the name is outside of the rect but nearer than m_outsideNearestLeft", etc
851 if ((cr < sl && cr > m_band.outsideNearestLeftEdge)) {
852 m_band.outsideNearestLeftEdge = cr;
853 }
854 if ((cl > sr && cl < m_band.outsideNearestRightEdge)) {
855 m_band.outsideNearestRightEdge = cl;
856 }
857 if ((cl >= sl && cl <= sr && cl > m_band.insideNearestRightEdge)) {
858 m_band.insideNearestRightEdge = cl;
859 }
860 if ((cr >= sl && cr <= sr && cr < m_band.insideNearestLeftEdge)) {
861 m_band.insideNearestLeftEdge = cr;
862 }
863
864 bool currentlySelected = selectionModel()->isSelected(currIndex);
865 bool originallySelected = m_band.originalSelection.contains(currIndex);
866 bool intersectsSelectedRect = currIndexRect.intersects(selRect);
867 bool shouldBeSelected = (intersectsSelectedRect && !originallySelected) || (!intersectsSelectedRect && originallySelected);
868 bool needToToggleItem = (currentlySelected && !shouldBeSelected) || (!currentlySelected && shouldBeSelected);
869 if (needToToggleItem && !formingToggleIndexRange) {
870 toggleIndexRangeBegin = currIndex;
871 formingToggleIndexRange = true;
872 }
873
874 // NOTE: indexBelow actually walks up and down expanded trees for us.
875 QModelIndex nextIndex = indexBelow(currIndex);
876 allItemsInBoundDone = !nextIndex.isValid() || currIndexRect.top() > verticalCutoff;
877
878 const bool commitToggleIndexRange = formingToggleIndexRange &&
879 (!needToToggleItem ||
880 allItemsInBoundDone ||
881 currIndex.parent() != toggleIndexRangeBegin.parent());
882 if (commitToggleIndexRange) {
883 formingToggleIndexRange = false;
884 // If this is the last item in the bounds and it is also the beginning of a range,
885 // don't toggle lastIndex - it will already have been dealt with.
886 if (!allItemsInBoundDone || toggleIndexRangeBegin != currIndex) {
887 itemsToToggle.select(toggleIndexRangeBegin, lastIndex);
888 }
889 // Need to start a new range immediately with currIndex?
890 if (needToToggleItem) {
891 toggleIndexRangeBegin = currIndex;
892 formingToggleIndexRange = true;
893 }
894 if (allItemsInBoundDone && needToToggleItem) {
895 // Toggle the very last item in the bounds.
896 itemsToToggle.select(currIndex, currIndex);
897 }
898 }
899
900 // next item
901 lastIndex = currIndex;
902 currIndex = nextIndex;
903 } while (!allItemsInBoundDone);
904
905
906 selectionModel()->select(itemsToToggle, QItemSelectionModel::Toggle);
907
908 m_band.lastSelectionOrigin = m_band.origin;
909 m_band.lastSelectionDestination = m_band.destination;
910 m_band.ignoreOldInfo = false;
911 }
912
913 void DolphinDetailsView::setFoldersExpandable(bool expandable)
914 {
915 if (!expandable) {
916 // collapse all expanded folders, as QTreeView::setItemsExpandable(false)
917 // does not do this task
918 const int rowCount = model()->rowCount();
919 for (int row = 0; row < rowCount; ++row) {
920 setExpanded(model()->index(row, 0), false);
921 }
922 }
923 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
924 settings->setExpandableFolders(expandable);
925 setRootIsDecorated(expandable);
926 setItemsExpandable(expandable);
927
928 // The width of the space which is available for editing has changed
929 // because of the (dis)appearance of the expanding toggles
930 adjustMaximumSizeForEditing(currentIndex());
931 }
932
933 void DolphinDetailsView::slotExpanded(const QModelIndex& index)
934 {
935 KFileItem item = m_dolphinViewController->itemForIndex(index);
936 if (!item.isNull()) {
937 m_expandedUrls.insert(item.url());
938 }
939 }
940
941 void DolphinDetailsView::slotCollapsed(const QModelIndex& index)
942 {
943 KFileItem item = m_dolphinViewController->itemForIndex(index);
944 if (!item.isNull()) {
945 m_expandedUrls.remove(item.url());
946 }
947 }
948
949 void DolphinDetailsView::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
950 {
951 removeExpandedIndexes(parent, start, end);
952 QTreeView::rowsAboutToBeRemoved(parent, start, end);
953 }
954
955 void DolphinDetailsView::removeExpandedIndexes(const QModelIndex& parent, int start, int end)
956 {
957 if (m_expandedUrls.isEmpty()) {
958 return;
959 }
960
961 for (int row = start; row <= end; row++) {
962 const QModelIndex index = model()->index(row, 0, parent);
963 if (isExpanded(index)) {
964 slotCollapsed(index);
965 removeExpandedIndexes(index, 0, model()->rowCount(index) - 1);
966 }
967 }
968 }
969
970 void DolphinDetailsView::updateDecorationSize(bool showPreview)
971 {
972 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
973 const int iconSize = showPreview ? settings->previewSize() : settings->iconSize();
974 setIconSize(QSize(iconSize, iconSize));
975 m_decorationSize = QSize(iconSize, iconSize);
976
977 doItemsLayout();
978 }
979
980 KFileItemDelegate::Information DolphinDetailsView::infoForColumn(int columnIndex) const
981 {
982 KFileItemDelegate::Information info = KFileItemDelegate::NoInformation;
983
984 switch (columnIndex) {
985 case DolphinModel::Size: info = KFileItemDelegate::Size; break;
986 case DolphinModel::ModifiedTime: info = KFileItemDelegate::ModificationTime; break;
987 case DolphinModel::Permissions: info = KFileItemDelegate::Permissions; break;
988 case DolphinModel::Owner: info = KFileItemDelegate::Owner; break;
989 case DolphinModel::Group: info = KFileItemDelegate::OwnerAndGroup; break;
990 case DolphinModel::Type: info = KFileItemDelegate::FriendlyMimeType; break;
991 default: break;
992 }
993
994 return info;
995 }
996
997 void DolphinDetailsView::resizeColumns()
998 {
999 // Using the resize mode QHeaderView::ResizeToContents is too slow (it takes
1000 // around 3 seconds for each (!) resize operation when having > 10000 items).
1001 // This gets a problem especially when opening large directories, where several
1002 // resize operations are received for showing the currently available items during
1003 // loading (the application hangs around 20 seconds when loading > 10000 items).
1004
1005 QHeaderView* headerView = header();
1006 QFontMetrics fontMetrics(viewport()->font());
1007
1008 int columnWidth[DolphinModel::Version + 1];
1009 columnWidth[DolphinModel::Size] = fontMetrics.width("00000 Items");
1010 columnWidth[DolphinModel::ModifiedTime] = fontMetrics.width("0000-00-00 00:00");
1011 columnWidth[DolphinModel::Permissions] = fontMetrics.width("xxxxxxxxxx");
1012 columnWidth[DolphinModel::Owner] = fontMetrics.width("xxxxxxxxxx");
1013 columnWidth[DolphinModel::Group] = fontMetrics.width("xxxxxxxxxx");
1014 columnWidth[DolphinModel::Type] = fontMetrics.width("XXXX Xxxxxxx");
1015 columnWidth[DolphinModel::Version] = fontMetrics.width("xxxxxxxx");
1016
1017 int requiredWidth = 0;
1018 for (int i = KDirModel::Size; i <= KDirModel::Type; ++i) {
1019 if (!isColumnHidden(i)) {
1020 columnWidth[i] += 20; // provide a default gap
1021 requiredWidth += columnWidth[i];
1022 headerView->resizeSection(i, columnWidth[i]);
1023 }
1024 }
1025
1026 // resize the name column in a way that the whole available width is used
1027 columnWidth[KDirModel::Name] = viewport()->width() - requiredWidth;
1028
1029 const int minNameWidth = 300;
1030 if (columnWidth[KDirModel::Name] < minNameWidth) {
1031 columnWidth[KDirModel::Name] = minNameWidth;
1032
1033 // It might be possible that the name column width can be
1034 // decreased without clipping any text. For performance
1035 // reasons the exact necessary width for full visible names is
1036 // only checked for up to 200 items:
1037 const int rowCount = model()->rowCount();
1038 if (rowCount > 0 && rowCount < 200) {
1039 const int nameWidth = sizeHintForColumn(DolphinModel::Name);
1040 if (nameWidth + requiredWidth <= viewport()->width()) {
1041 columnWidth[KDirModel::Name] = viewport()->width() - requiredWidth;
1042 } else if (nameWidth < minNameWidth) {
1043 columnWidth[KDirModel::Name] = nameWidth;
1044 }
1045 }
1046 }
1047
1048 headerView->resizeSection(KDirModel::Name, columnWidth[KDirModel::Name]);
1049 }
1050
1051 bool DolphinDetailsView::isAboveExpandingToggle(const QPoint& pos) const
1052 {
1053 // QTreeView offers no public API to get the information whether an index has an
1054 // expanding toggle and what boundaries the toggle has. The following approach
1055 // also assumes a toggle for file items.
1056 if (itemsExpandable()) {
1057 const QModelIndex index = QTreeView::indexAt(pos);
1058 if (index.isValid() && (index.column() == KDirModel::Name)) {
1059 QRect rect = visualRect(index);
1060 const int toggleSize = rect.height();
1061 if (isRightToLeft()) {
1062 rect.moveRight(rect.right());
1063 } else {
1064 rect.moveLeft(rect.x() - toggleSize);
1065 }
1066 rect.setWidth(toggleSize);
1067
1068 QStyleOption opt;
1069 opt.initFrom(this);
1070 opt.rect = rect;
1071 rect = style()->subElementRect(QStyle::SE_TreeViewDisclosureItem, &opt, this);
1072
1073 return rect.contains(pos);
1074 }
1075 }
1076 return false;
1077 }
1078
1079 void DolphinDetailsView::adjustMaximumSizeForEditing(const QModelIndex& index)
1080 {
1081 // Make sure that the full width of the "Name" column is available for "Rename Inline"
1082 m_extensionsFactory->fileItemDelegate()->setMaximumSize(QTreeView::visualRect(index).size());
1083 }
1084
1085 DolphinDetailsView::ElasticBand::ElasticBand() :
1086 show(false),
1087 origin(),
1088 destination(),
1089 lastSelectionOrigin(),
1090 lastSelectionDestination(),
1091 ignoreOldInfo(true),
1092 outsideNearestLeftEdge(0),
1093 outsideNearestRightEdge(0),
1094 insideNearestLeftEdge(0),
1095 insideNearestRightEdge(0)
1096 {
1097 }
1098
1099 #include "dolphindetailsview.moc"