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