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