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