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