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