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