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