From 4d886d083ca6cb2d635da2d29efb804b2680b6de Mon Sep 17 00:00:00 2001 From: Peter Penz Date: Sun, 21 Sep 2008 19:57:37 +0000 Subject: renamed IconManager to KFilePreviewGenerator svn path=/trunk/KDE/kdebase/apps/; revision=863324 --- src/CMakeLists.txt | 2 +- src/dolphincolumnwidget.cpp | 14 +- src/dolphincolumnwidget.h | 4 +- src/dolphinview.cpp | 18 +- src/dolphinview.h | 4 +- src/iconmanager.cpp | 596 ------------------------------------------ src/iconmanager.h | 210 --------------- src/kfilepreviewgenerator.cpp | 596 ++++++++++++++++++++++++++++++++++++++++++ src/kfilepreviewgenerator.h | 210 +++++++++++++++ 9 files changed, 827 insertions(+), 827 deletions(-) delete mode 100644 src/iconmanager.cpp delete mode 100644 src/iconmanager.h create mode 100644 src/kfilepreviewgenerator.cpp create mode 100644 src/kfilepreviewgenerator.h (limited to 'src') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 9b188a183..42a4d0f8c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -35,7 +35,7 @@ set(dolphinprivate_LIB_SRCS dolphinview.cpp dolphinviewactionhandler.cpp folderexpander.cpp - iconmanager.cpp + kfilepreviewgenerator.cpp ktooltip.cpp kballoontipdelegate.cpp kformattedballoontipdelegate.cpp diff --git a/src/dolphincolumnwidget.cpp b/src/dolphincolumnwidget.cpp index fe35f5f42..5b3ffae59 100644 --- a/src/dolphincolumnwidget.cpp +++ b/src/dolphincolumnwidget.cpp @@ -29,7 +29,7 @@ #include "dolphin_generalsettings.h" #include "draganddrophelper.h" #include "folderexpander.h" -#include "iconmanager.h" +#include "kfilepreviewgenerator.h" #include "selectionmanager.h" #include "tooltipmanager.h" @@ -60,7 +60,7 @@ DolphinColumnWidget::DolphinColumnWidget(QWidget* parent, m_dirLister(0), m_dolphinModel(0), m_proxyModel(0), - m_iconManager(0), + m_previewGenerator(0), m_dropRect() { setMouseTracking(true); @@ -131,8 +131,8 @@ DolphinColumnWidget::DolphinColumnWidget(QWidget* parent, m_selectionManager, SLOT(reset())); } - m_iconManager = new IconManager(this, m_proxyModel); - m_iconManager->setShowPreview(m_view->m_controller->dolphinView()->showPreview()); + m_previewGenerator = new KFilePreviewGenerator(this, m_proxyModel); + m_previewGenerator->setShowPreview(m_view->m_controller->dolphinView()->showPreview()); if (DolphinSettings::instance().generalSettings()->showToolTips()) { new ToolTipManager(this, m_proxyModel); @@ -163,8 +163,8 @@ void DolphinColumnWidget::setDecorationSize(const QSize& size) setIconSize(size); m_decorationSize = size; doItemsLayout(); - if (m_iconManager != 0) { - m_iconManager->updatePreviews(); + if (m_previewGenerator != 0) { + m_previewGenerator->updatePreviews(); } if (m_selectionManager != 0) { m_selectionManager->reset(); @@ -213,7 +213,7 @@ void DolphinColumnWidget::setShowHiddenFiles(bool show) void DolphinColumnWidget::setShowPreview(bool show) { - m_iconManager->setShowPreview(show); + m_previewGenerator->setShowPreview(show); m_dirLister->stop(); m_dirLister->openUrl(m_url, KDirLister::Reload); diff --git a/src/dolphincolumnwidget.h b/src/dolphincolumnwidget.h index 72028da7c..15a09c8f9 100644 --- a/src/dolphincolumnwidget.h +++ b/src/dolphincolumnwidget.h @@ -32,8 +32,8 @@ class DolphinColumnView; class DolphinModel; class DolphinSortFilterProxyModel; -class IconManager; class KDirLister; +class KFilePreviewGenerator; class KJob; class KFileItem; class KFileItemList; @@ -153,7 +153,7 @@ private: DolphinModel* m_dolphinModel; DolphinSortFilterProxyModel* m_proxyModel; - IconManager* m_iconManager; + KFilePreviewGenerator* m_previewGenerator; QRect m_dropRect; diff --git a/src/dolphinview.cpp b/src/dolphinview.cpp index 45fdfebaf..42136f445 100644 --- a/src/dolphinview.cpp +++ b/src/dolphinview.cpp @@ -58,7 +58,7 @@ #include "dolphinsettings.h" #include "dolphin_generalsettings.h" #include "folderexpander.h" -#include "iconmanager.h" +#include "kfilepreviewgenerator.h" #include "renamedialog.h" #include "tooltipmanager.h" #include "viewproperties.h" @@ -87,7 +87,7 @@ DolphinView::DolphinView(QWidget* parent, m_dolphinModel(dolphinModel), m_dirLister(dirLister), m_proxyModel(proxyModel), - m_iconManager(0), + m_previewGenerator(0), m_toolTipManager(0), m_rootUrl(), m_currentItemUrl() @@ -373,7 +373,7 @@ void DolphinView::setZoomLevel(int level) if (level != zoomLevel()) { m_controller->setZoomLevel(level); - m_iconManager->updatePreviews(); + m_previewGenerator->updatePreviews(); emit zoomLevelChanged(level); } } @@ -452,7 +452,7 @@ void DolphinView::updateView(const KUrl& url, const KUrl& rootUrl) return; } - m_iconManager->cancelPreviews(); + m_previewGenerator->cancelPreviews(); m_controller->setUrl(url); // emits urlChanged, which we forward if (!rootUrl.isEmpty() && rootUrl.isParentOf(url)) { @@ -657,7 +657,7 @@ void DolphinView::setShowPreview(bool show) props.setShowPreview(show); m_showPreview = show; - m_iconManager->setShowPreview(show); + m_previewGenerator->setShowPreview(show); const int oldZoomLevel = m_controller->zoomLevel(); emit showPreviewChanged(); @@ -1107,7 +1107,7 @@ void DolphinView::applyViewProperties(const KUrl& url) const bool showPreview = props.showPreview(); if (showPreview != m_showPreview) { m_showPreview = showPreview; - m_iconManager->setShowPreview(showPreview); + m_previewGenerator->setShowPreview(showPreview); const int oldZoomLevel = m_controller->zoomLevel(); emit showPreviewChanged(); @@ -1180,8 +1180,8 @@ void DolphinView::createView() view->setSelectionMode(QAbstractItemView::ExtendedSelection); - m_iconManager = new IconManager(view, m_proxyModel); - m_iconManager->setShowPreview(m_showPreview); + m_previewGenerator = new KFilePreviewGenerator(view, m_proxyModel); + m_previewGenerator->setShowPreview(m_showPreview); if (DolphinSettings::instance().generalSettings()->showToolTips()) { m_toolTipManager = new ToolTipManager(view, m_proxyModel); @@ -1215,7 +1215,7 @@ void DolphinView::deleteView() m_detailsView = 0; m_columnView = 0; m_fileItemDelegate = 0; - m_iconManager = 0; + m_previewGenerator = 0; m_toolTipManager = 0; } } diff --git a/src/dolphinview.h b/src/dolphinview.h index acc9ba363..f0bacb989 100644 --- a/src/dolphinview.h +++ b/src/dolphinview.h @@ -45,7 +45,7 @@ class DolphinIconsView; class DolphinMainWindow; class DolphinModel; class DolphinSortFilterProxyModel; -class IconManager; +class KFilePreviewGenerator; class KAction; class KActionCollection; class KDirLister; @@ -709,7 +709,7 @@ private: KDirLister* m_dirLister; DolphinSortFilterProxyModel* m_proxyModel; - IconManager* m_iconManager; + KFilePreviewGenerator* m_previewGenerator; ToolTipManager* m_toolTipManager; KUrl m_rootUrl; diff --git a/src/iconmanager.cpp b/src/iconmanager.cpp deleted file mode 100644 index ab854d738..000000000 --- a/src/iconmanager.cpp +++ /dev/null @@ -1,596 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2008 by Peter Penz * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - * You should have received a copy of the GNU General Public License * - * along with this program; if not, write to the * - * Free Software Foundation, Inc., * - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * - ***************************************************************************/ - -#include "iconmanager.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -/** - * If the passed item view is an instance of QListView, expensive - * layout operations are blocked in the constructor and are unblocked - * again in the destructor. - * - * This helper class is a workaround for the following huge performance - * problem when having directories with several 1000 items: - * - each change of an icon emits a dataChanged() signal from the model - * - QListView iterates through all items on each dataChanged() signal - * and invokes QItemDelegate::sizeHint() - * - the sizeHint() implementation of KFileItemDelegate is quite complex, - * invoking it 1000 times for each icon change might block the UI - * - * QListView does not invoke QItemDelegate::sizeHint() when the - * uniformItemSize property has been set to true, so this property is - * set before exchanging a block of icons. It is important to reset - * it again before the event loop is entered, otherwise QListView - * would not get the correct size hints after dispatching the layoutChanged() - * signal. - */ -class LayoutBlocker { -public: - LayoutBlocker(QAbstractItemView* view) : - m_uniformSizes(false), - m_view(qobject_cast(view)) - { - if (m_view != 0) { - m_uniformSizes = m_view->uniformItemSizes(); - m_view->setUniformItemSizes(true); - } - } - - ~LayoutBlocker() - { - if (m_view != 0) { - m_view->setUniformItemSizes(m_uniformSizes); - } - } - -private: - bool m_uniformSizes; - QListView* m_view; -}; - -IconManager::IconManager(QAbstractItemView* parent, KDirSortFilterProxyModel* model) : - QObject(parent), - m_showPreview(false), - m_clearItemQueues(true), - m_hasCutSelection(false), - m_pendingVisiblePreviews(0), - m_view(parent), - m_previewTimer(0), - m_scrollAreaTimer(0), - m_previewJobs(), - m_dirModel(0), - m_proxyModel(model), - m_mimeTypeResolver(0), - m_cutItemsCache(), - m_previews(), - m_pendingItems(), - m_dispatchedItems() -{ - Q_ASSERT(m_view->iconSize().isValid()); // each view must provide its current icon size - - m_dirModel = static_cast(m_proxyModel->sourceModel()); - connect(m_dirModel->dirLister(), SIGNAL(newItems(const KFileItemList&)), - this, SLOT(generatePreviews(const KFileItemList&))); - - QClipboard* clipboard = QApplication::clipboard(); - connect(clipboard, SIGNAL(dataChanged()), - this, SLOT(updateCutItems())); - - m_previewTimer = new QTimer(this); - m_previewTimer->setSingleShot(true); - connect(m_previewTimer, SIGNAL(timeout()), this, SLOT(dispatchPreviewQueue())); - - // Whenever the scrollbar values have been changed, the pending previews should - // be reordered in a way that the previews for the visible items are generated - // first. The reordering is done with a small delay, so that during moving the - // scrollbars the CPU load is kept low. - m_scrollAreaTimer = new QTimer(this); - m_scrollAreaTimer->setSingleShot(true); - m_scrollAreaTimer->setInterval(200); - connect(m_scrollAreaTimer, SIGNAL(timeout()), - this, SLOT(resumePreviews())); - connect(m_view->horizontalScrollBar(), SIGNAL(valueChanged(int)), - this, SLOT(pausePreviews())); - connect(m_view->verticalScrollBar(), SIGNAL(valueChanged(int)), - this, SLOT(pausePreviews())); -} - -IconManager::~IconManager() -{ - killPreviewJobs(); - m_pendingItems.clear(); - m_dispatchedItems.clear(); - if (m_mimeTypeResolver != 0) { - m_mimeTypeResolver->deleteLater(); - m_mimeTypeResolver = 0; - } -} - -void IconManager::setShowPreview(bool show) -{ - if (m_showPreview != show) { - m_showPreview = show; - m_cutItemsCache.clear(); - updateCutItems(); - if (show) { - updatePreviews(); - } - } - - if (show && (m_mimeTypeResolver != 0)) { - // don't resolve the MIME types if the preview is turned on - m_mimeTypeResolver->deleteLater(); - m_mimeTypeResolver = 0; - } else if (!show && (m_mimeTypeResolver == 0)) { - // the preview is turned off: resolve the MIME-types so that - // the icons gets updated - m_mimeTypeResolver = new KMimeTypeResolver(m_view, m_dirModel); - } -} - -void IconManager::updatePreviews() -{ - if (!m_showPreview) { - return; - } - - killPreviewJobs(); - m_cutItemsCache.clear(); - m_pendingItems.clear(); - m_dispatchedItems.clear(); - - KFileItemList itemList; - const int rowCount = m_dirModel->rowCount(); - for (int row = 0; row < rowCount; ++row) { - const QModelIndex index = m_dirModel->index(row, 0); - KFileItem item = m_dirModel->itemForIndex(index); - itemList.append(item); - } - - generatePreviews(itemList); - updateCutItems(); -} - -void IconManager::cancelPreviews() -{ - killPreviewJobs(); - m_cutItemsCache.clear(); - m_pendingItems.clear(); - m_dispatchedItems.clear(); -} - -void IconManager::generatePreviews(const KFileItemList& items) -{ - applyCutItemEffect(); - - if (!m_showPreview) { - return; - } - - KFileItemList orderedItems = items; - orderItems(orderedItems); - - foreach (const KFileItem& item, orderedItems) { - m_pendingItems.append(item); - } - - startPreviewJob(orderedItems); -} - -void IconManager::addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap) -{ - if (!m_showPreview) { - // the preview has been canceled in the meantime - return; - } - const KUrl url = item.url(); - - // check whether the item is part of the directory lister (it is possible - // that a preview from an old directory lister is received) - KDirLister* dirLister = m_dirModel->dirLister(); - bool isOldPreview = true; - const KUrl::List dirs = dirLister->directories(); - const QString itemDir = url.directory(); - foreach (const KUrl& url, dirs) { - if (url.path() == itemDir) { - isOldPreview = false; - break; - } - } - if (isOldPreview) { - return; - } - - QPixmap icon = pixmap; - - const QString mimeType = item.mimetype(); - const QString mimeTypeGroup = mimeType.left(mimeType.indexOf('/')); - if ((mimeTypeGroup != "image") || !applyImageFrame(icon)) { - limitToSize(icon, m_view->iconSize()); - } - - if (m_hasCutSelection && isCutItem(item)) { - // Remember the current icon in the cache for cut items before - // the disabled effect is applied. This makes it possible restoring - // the uncut version again when cutting other items. - QList::iterator begin = m_cutItemsCache.begin(); - QList::iterator end = m_cutItemsCache.end(); - for (QList::iterator it = begin; it != end; ++it) { - if ((*it).url == item.url()) { - (*it).pixmap = icon; - break; - } - } - - // apply the disabled effect to the icon for marking it as "cut item" - // and apply the icon to the item - KIconEffect iconEffect; - icon = iconEffect.apply(icon, KIconLoader::Desktop, KIconLoader::DisabledState); - } - - // remember the preview and URL, so that it can be applied to the model - // in IconManager::dispatchPreviewQueue() - ItemInfo preview; - preview.url = url; - preview.pixmap = icon; - m_previews.append(preview); - - m_dispatchedItems.append(item); -} - -void IconManager::slotPreviewJobFinished(KJob* job) -{ - const int index = m_previewJobs.indexOf(job); - m_previewJobs.removeAt(index); - - if ((m_previewJobs.count() == 0) && m_clearItemQueues) { - m_pendingItems.clear(); - m_dispatchedItems.clear(); - m_pendingVisiblePreviews = 0; - QMetaObject::invokeMethod(this, "dispatchPreviewQueue", Qt::QueuedConnection); - } -} - -void IconManager::updateCutItems() -{ - // restore the icons of all previously selected items to the - // original state... - foreach (const ItemInfo& cutItem, m_cutItemsCache) { - const QModelIndex index = m_dirModel->indexForUrl(cutItem.url); - if (index.isValid()) { - m_dirModel->setData(index, QIcon(cutItem.pixmap), Qt::DecorationRole); - } - } - m_cutItemsCache.clear(); - - // ... and apply an item effect to all currently cut items - applyCutItemEffect(); -} - -void IconManager::dispatchPreviewQueue() -{ - const int previewsCount = m_previews.count(); - if (previewsCount > 0) { - // Applying the previews to the model must be done step by step - // in larger blocks: Applying a preview immediately when getting the signal - // 'gotPreview()' from the PreviewJob is too expensive, as a relayout - // of the view would be triggered for each single preview. - LayoutBlocker blocker(m_view); - for (int i = 0; i < previewsCount; ++i) { - const ItemInfo& preview = m_previews.first(); - - const QModelIndex idx = m_dirModel->indexForUrl(preview.url); - if (idx.isValid() && (idx.column() == 0)) { - m_dirModel->setData(idx, QIcon(preview.pixmap), Qt::DecorationRole); - } - - m_previews.pop_front(); - if (m_pendingVisiblePreviews > 0) { - --m_pendingVisiblePreviews; - } - } - } - - if (m_pendingVisiblePreviews > 0) { - // As long as there are pending previews for visible items, poll - // the preview queue each 200 ms. If there are no pending previews, - // the queue is dispatched in slotPreviewJobFinished(). - m_previewTimer->start(200); - } -} - -void IconManager::pausePreviews() -{ - foreach (KJob* job, m_previewJobs) { - Q_ASSERT(job != 0); - job->suspend(); - } - m_scrollAreaTimer->start(); -} - -void IconManager::resumePreviews() -{ - // Before creating new preview jobs the m_pendingItems queue must be - // cleaned up by removing the already dispatched items. Implementation - // note: The order of the m_dispatchedItems queue and the m_pendingItems - // queue is usually equal. So even when having a lot of elements the - // nested loop is no performance bottle neck, as the inner loop is only - // entered once in most cases. - foreach (const KFileItem& item, m_dispatchedItems) { - KFileItemList::iterator begin = m_pendingItems.begin(); - KFileItemList::iterator end = m_pendingItems.end(); - for (KFileItemList::iterator it = begin; it != end; ++it) { - if ((*it).url() == item.url()) { - m_pendingItems.erase(it); - break; - } - } - } - m_dispatchedItems.clear(); - - m_pendingVisiblePreviews = 0; - dispatchPreviewQueue(); - - KFileItemList orderedItems = m_pendingItems; - orderItems(orderedItems); - - // Kill all suspended preview jobs. Usually when a preview job - // has been finished, slotPreviewJobFinished() clears all item queues. - // This is not wanted in this case, as a new job is created afterwards - // for m_pendingItems. - m_clearItemQueues = false; - killPreviewJobs(); - m_clearItemQueues = true; - - startPreviewJob(orderedItems); -} - -bool IconManager::isCutItem(const KFileItem& item) const -{ - const QMimeData* mimeData = QApplication::clipboard()->mimeData(); - const KUrl::List cutUrls = KUrl::List::fromMimeData(mimeData); - - const KUrl itemUrl = item.url(); - foreach (const KUrl& url, cutUrls) { - if (url == itemUrl) { - return true; - } - } - - return false; -} - -void IconManager::applyCutItemEffect() -{ - const QMimeData* mimeData = QApplication::clipboard()->mimeData(); - m_hasCutSelection = KonqMimeData::decodeIsCutSelection(mimeData); - if (!m_hasCutSelection) { - return; - } - - KFileItemList items; - KDirLister* dirLister = m_dirModel->dirLister(); - const KUrl::List dirs = dirLister->directories(); - foreach (const KUrl& url, dirs) { - items << dirLister->itemsForDir(url); - } - - foreach (const KFileItem& item, items) { - if (isCutItem(item)) { - const QModelIndex index = m_dirModel->indexForItem(item); - const QVariant value = m_dirModel->data(index, Qt::DecorationRole); - if (value.type() == QVariant::Icon) { - const QIcon icon(qvariant_cast(value)); - const QSize actualSize = icon.actualSize(m_view->iconSize()); - QPixmap pixmap = icon.pixmap(actualSize); - - // remember current pixmap for the item to be able - // to restore it when other items get cut - ItemInfo cutItem; - cutItem.url = item.url(); - cutItem.pixmap = pixmap; - m_cutItemsCache.append(cutItem); - - // apply icon effect to the cut item - KIconEffect iconEffect; - pixmap = iconEffect.apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState); - m_dirModel->setData(index, QIcon(pixmap), Qt::DecorationRole); - } - } - } -} - -bool IconManager::applyImageFrame(QPixmap& icon) -{ - const QSize maxSize = m_view->iconSize(); - const bool applyFrame = (maxSize.width() > KIconLoader::SizeSmallMedium) && - (maxSize.height() > KIconLoader::SizeSmallMedium) && - ((icon.width() > KIconLoader::SizeLarge) || - (icon.height() > KIconLoader::SizeLarge)); - if (!applyFrame) { - // the maximum size or the image itself is too small for a frame - return false; - } - - const int frame = 4; - const int doubleFrame = frame * 2; - - // resize the icon to the maximum size minus the space required for the frame - limitToSize(icon, QSize(maxSize.width() - doubleFrame, maxSize.height() - doubleFrame)); - - QPainter painter; - const QPalette palette = m_view->palette(); - QPixmap framedIcon(icon.size().width() + doubleFrame, icon.size().height() + doubleFrame); - framedIcon.fill(palette.color(QPalette::Normal, QPalette::Base)); - const int width = framedIcon.width() - 1; - const int height = framedIcon.height() - 1; - - painter.begin(&framedIcon); - painter.drawPixmap(frame, frame, icon); - - // add a border - painter.setPen(palette.color(QPalette::Text)); - painter.drawRect(0, 0, width, height); - painter.drawRect(1, 1, width - 2, height - 2); - - painter.setCompositionMode(QPainter::CompositionMode_Plus); - QColor blendColor = palette.color(QPalette::Normal, QPalette::Base); - - blendColor.setAlpha(255 - 32); - painter.setPen(blendColor); - painter.drawRect(0, 0, width, height); - - blendColor.setAlpha(255 - 64); - painter.setPen(blendColor); - painter.drawRect(1, 1, width - 2, height - 2); - painter.end(); - - icon = framedIcon; - - return true; -} - -void IconManager::limitToSize(QPixmap& icon, const QSize& maxSize) -{ - if ((icon.width() > maxSize.width()) || (icon.height() > maxSize.height())) { - icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::FastTransformation); - } -} - -void IconManager::startPreviewJob(const KFileItemList& items) -{ - if (items.count() == 0) { - return; - } - - const QMimeData* mimeData = QApplication::clipboard()->mimeData(); - m_hasCutSelection = KonqMimeData::decodeIsCutSelection(mimeData); - - const QSize size = m_view->iconSize(); - - // PreviewJob internally caches items always with the size of - // 128 x 128 pixels or 256 x 256 pixels. A downscaling is done - // by PreviewJob if a smaller size is requested. As the IconManager must - // do a downscaling anyhow because of the frame, only the provided - // cache sizes are requested. - const int cacheSize = (size.width() > 128) || (size.height() > 128) ? 256 : 128; - KIO::PreviewJob* job = KIO::filePreview(items, cacheSize, cacheSize); - connect(job, SIGNAL(gotPreview(const KFileItem&, const QPixmap&)), - this, SLOT(addToPreviewQueue(const KFileItem&, const QPixmap&))); - connect(job, SIGNAL(finished(KJob*)), - this, SLOT(slotPreviewJobFinished(KJob*))); - - m_previewJobs.append(job); - m_previewTimer->start(200); -} - -void IconManager::killPreviewJobs() -{ - foreach (KJob* job, m_previewJobs) { - Q_ASSERT(job != 0); - job->kill(); - } - m_previewJobs.clear(); -} - -void IconManager::orderItems(KFileItemList& items) -{ - // Order the items in a way that the preview for the visible items - // is generated first, as this improves the feeled performance a lot. - // - // Implementation note: 2 different algorithms are used for the sorting. - // Algorithm 1 is faster when having a lot of items in comparison - // to the number of rows in the model. Algorithm 2 is faster - // when having quite less items in comparison to the number of rows in - // the model. Choosing the right algorithm is important when having directories - // with several hundreds or thousands of items. - - const int itemCount = items.count(); - const int rowCount = m_proxyModel->rowCount(); - const QRect visibleArea = m_view->viewport()->rect(); - - int insertPos = 0; - if (itemCount * 10 > rowCount) { - // Algorithm 1: The number of items is > 10 % of the row count. Parse all rows - // and check whether the received row is part of the item list. - for (int row = 0; row < rowCount; ++row) { - const QModelIndex proxyIndex = m_proxyModel->index(row, 0); - const QRect itemRect = m_view->visualRect(proxyIndex); - const QModelIndex dirIndex = m_proxyModel->mapToSource(proxyIndex); - - KFileItem item = m_dirModel->itemForIndex(dirIndex); // O(1) - const KUrl url = item.url(); - - // check whether the item is part of the item list 'items' - int index = -1; - for (int i = 0; i < itemCount; ++i) { - if (items.at(i).url() == url) { - index = i; - break; - } - } - - if ((index > 0) && itemRect.intersects(visibleArea)) { - // The current item is (at least partly) visible. Move it - // to the front of the list, so that the preview is - // generated earlier. - items.removeAt(index); - items.insert(insertPos, item); - ++insertPos; - ++m_pendingVisiblePreviews; - } - } - } else { - // Algorithm 2: The number of items is <= 10 % of the row count. In this case iterate - // all items and receive the corresponding row from the item. - for (int i = 0; i < itemCount; ++i) { - const QModelIndex dirIndex = m_dirModel->indexForItem(items.at(i)); // O(n) (n = number of rows) - const QModelIndex proxyIndex = m_proxyModel->mapFromSource(dirIndex); - const QRect itemRect = m_view->visualRect(proxyIndex); - - if (itemRect.intersects(visibleArea)) { - // The current item is (at least partly) visible. Move it - // to the front of the list, so that the preview is - // generated earlier. - items.insert(insertPos, items.at(i)); - items.removeAt(i + 1); - ++insertPos; - ++m_pendingVisiblePreviews; - } - } - } -} - -#include "iconmanager.moc" diff --git a/src/iconmanager.h b/src/iconmanager.h deleted file mode 100644 index 4f0b9645f..000000000 --- a/src/iconmanager.h +++ /dev/null @@ -1,210 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2008 by Peter Penz * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - * You should have received a copy of the GNU General Public License * - * along with this program; if not, write to the * - * Free Software Foundation, Inc., * - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * - ***************************************************************************/ - -#ifndef ICONMANAGER_H -#define ICONMANAGER_H - -#include -#include - -#include -#include -#include - -class KDirModel; -class KDirSortFilterProxyModel; -class KJob; -class KMimeTypeResolver; -class QAbstractItemView; - -/** - * @brief Manages the icon state of a directory model. - * - * Per default a preview is generated for each item. - * Additionally the clipboard is checked for cut items. - * The icon state for cut items gets dimmed automatically. - * - * The following strategy is used when creating previews: - * - The previews for currently visible items are created before - * the previews for invisible items. - * - If the user changes the visible area by using the scrollbars, - * all pending previews get paused. As soon as the user stays - * on the same position for a short delay, the previews are - * resumed. Also in this case the previews for the visible items - * are generated first. - */ -class IconManager : public QObject -{ - Q_OBJECT - -public: - IconManager(QAbstractItemView* parent, KDirSortFilterProxyModel* model); - virtual ~IconManager(); - void setShowPreview(bool show); - bool showPreview() const; - - /** - * Updates the previews for all already available items. It is only necessary - * to invoke this method when the icon size of the abstract item view has - * been changed. - */ - void updatePreviews(); - - /** - * Cancels all pending previews. Should be invoked when the URL of the item - * view has been changed. - */ - void cancelPreviews(); - -private slots: - /** - * Generates previews for the items \a items asynchronously. - */ - void generatePreviews(const KFileItemList& items); - - /** - * Adds the preview \a pixmap for the item \a item to the preview - * queue and starts a timer which will dispatch the preview queue - * later. - */ - void addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap); - - /** - * Is invoked when the preview job has been finished and - * removes the job from the m_previewJobs list. - */ - void slotPreviewJobFinished(KJob* job); - - /** Synchronizes the item icon with the clipboard of cut items. */ - void updateCutItems(); - - /** - * Dispatches the preview queue block by block within - * time slices. - */ - void dispatchPreviewQueue(); - - /** - * Pauses all preview jobs and invokes IconManager::resumePreviews() - * after a short delay. Is invoked as soon as the user has moved - * a scrollbar. - */ - void pausePreviews(); - - /** - * Resumes the previews that have been paused after moving the - * scrollbar. The previews for the current visible area are - * generated first. - */ - void resumePreviews(); - -private: - /** - * Returns true, if the item \a item has been cut into - * the clipboard. - */ - bool isCutItem(const KFileItem& item) const; - - /** Applies an item effect to all cut items. */ - void applyCutItemEffect(); - - /** - * Applies a frame around the icon. False is returned if - * no frame has been added because the icon is too small. - */ - bool applyImageFrame(QPixmap& icon); - - /** - * Resizes the icon to \a maxSize if the icon size does not - * fit into the maximum size. The aspect ratio of the icon - * is kept. - */ - void limitToSize(QPixmap& icon, const QSize& maxSize); - - /** - * Starts a new preview job for the items \a to m_previewJobs - * and triggers the preview timer. - */ - void startPreviewJob(const KFileItemList& items); - - /** Kills all ongoing preview jobs. */ - void killPreviewJobs(); - - /** - * Orders the items \a items in a way that the visible items - * are moved to the front of the list. When passing this - * list to a preview job, the visible items will get generated - * first. - */ - void orderItems(KFileItemList& items); - -private: - /** Remembers the pixmap for an item specified by an URL. */ - struct ItemInfo - { - KUrl url; - QPixmap pixmap; - }; - - bool m_showPreview; - - /** - * True, if m_pendingItems and m_dispatchedItems should be - * cleared when the preview jobs have been finished. - */ - bool m_clearItemQueues; - - /** - * True if a selection has been done which should cut items. - */ - bool m_hasCutSelection; - - int m_pendingVisiblePreviews; - - QAbstractItemView* m_view; - QTimer* m_previewTimer; - QTimer* m_scrollAreaTimer; - QList m_previewJobs; - KDirModel* m_dirModel; - KDirSortFilterProxyModel* m_proxyModel; - - KMimeTypeResolver* m_mimeTypeResolver; - - QList m_cutItemsCache; - QList m_previews; - - /** - * Contains all items where a preview must be generated, but - * where the preview job has not dispatched the items yet. - */ - KFileItemList m_pendingItems; - - /** - * Contains all items, where a preview has already been - * generated by the preview jobs. - */ - KFileItemList m_dispatchedItems; -}; - -inline bool IconManager::showPreview() const -{ - return m_showPreview; -} - -#endif diff --git a/src/kfilepreviewgenerator.cpp b/src/kfilepreviewgenerator.cpp new file mode 100644 index 000000000..e81f66980 --- /dev/null +++ b/src/kfilepreviewgenerator.cpp @@ -0,0 +1,596 @@ +/*************************************************************************** + * Copyright (C) 2008 by Peter Penz * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * + ***************************************************************************/ + +#include "kfilepreviewgenerator.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * If the passed item view is an instance of QListView, expensive + * layout operations are blocked in the constructor and are unblocked + * again in the destructor. + * + * This helper class is a workaround for the following huge performance + * problem when having directories with several 1000 items: + * - each change of an icon emits a dataChanged() signal from the model + * - QListView iterates through all items on each dataChanged() signal + * and invokes QItemDelegate::sizeHint() + * - the sizeHint() implementation of KFileItemDelegate is quite complex, + * invoking it 1000 times for each icon change might block the UI + * + * QListView does not invoke QItemDelegate::sizeHint() when the + * uniformItemSize property has been set to true, so this property is + * set before exchanging a block of icons. It is important to reset + * it again before the event loop is entered, otherwise QListView + * would not get the correct size hints after dispatching the layoutChanged() + * signal. + */ +class LayoutBlocker { +public: + LayoutBlocker(QAbstractItemView* view) : + m_uniformSizes(false), + m_view(qobject_cast(view)) + { + if (m_view != 0) { + m_uniformSizes = m_view->uniformItemSizes(); + m_view->setUniformItemSizes(true); + } + } + + ~LayoutBlocker() + { + if (m_view != 0) { + m_view->setUniformItemSizes(m_uniformSizes); + } + } + +private: + bool m_uniformSizes; + QListView* m_view; +}; + +KFilePreviewGenerator::KFilePreviewGenerator(QAbstractItemView* parent, KDirSortFilterProxyModel* model) : + QObject(parent), + m_showPreview(false), + m_clearItemQueues(true), + m_hasCutSelection(false), + m_pendingVisiblePreviews(0), + m_view(parent), + m_previewTimer(0), + m_scrollAreaTimer(0), + m_previewJobs(), + m_dirModel(0), + m_proxyModel(model), + m_mimeTypeResolver(0), + m_cutItemsCache(), + m_previews(), + m_pendingItems(), + m_dispatchedItems() +{ + Q_ASSERT(m_view->iconSize().isValid()); // each view must provide its current icon size + + m_dirModel = static_cast(m_proxyModel->sourceModel()); + connect(m_dirModel->dirLister(), SIGNAL(newItems(const KFileItemList&)), + this, SLOT(generatePreviews(const KFileItemList&))); + + QClipboard* clipboard = QApplication::clipboard(); + connect(clipboard, SIGNAL(dataChanged()), + this, SLOT(updateCutItems())); + + m_previewTimer = new QTimer(this); + m_previewTimer->setSingleShot(true); + connect(m_previewTimer, SIGNAL(timeout()), this, SLOT(dispatchPreviewQueue())); + + // Whenever the scrollbar values have been changed, the pending previews should + // be reordered in a way that the previews for the visible items are generated + // first. The reordering is done with a small delay, so that during moving the + // scrollbars the CPU load is kept low. + m_scrollAreaTimer = new QTimer(this); + m_scrollAreaTimer->setSingleShot(true); + m_scrollAreaTimer->setInterval(200); + connect(m_scrollAreaTimer, SIGNAL(timeout()), + this, SLOT(resumePreviews())); + connect(m_view->horizontalScrollBar(), SIGNAL(valueChanged(int)), + this, SLOT(pausePreviews())); + connect(m_view->verticalScrollBar(), SIGNAL(valueChanged(int)), + this, SLOT(pausePreviews())); +} + +KFilePreviewGenerator::~KFilePreviewGenerator() +{ + killPreviewJobs(); + m_pendingItems.clear(); + m_dispatchedItems.clear(); + if (m_mimeTypeResolver != 0) { + m_mimeTypeResolver->deleteLater(); + m_mimeTypeResolver = 0; + } +} + +void KFilePreviewGenerator::setShowPreview(bool show) +{ + if (m_showPreview != show) { + m_showPreview = show; + m_cutItemsCache.clear(); + updateCutItems(); + if (show) { + updatePreviews(); + } + } + + if (show && (m_mimeTypeResolver != 0)) { + // don't resolve the MIME types if the preview is turned on + m_mimeTypeResolver->deleteLater(); + m_mimeTypeResolver = 0; + } else if (!show && (m_mimeTypeResolver == 0)) { + // the preview is turned off: resolve the MIME-types so that + // the icons gets updated + m_mimeTypeResolver = new KMimeTypeResolver(m_view, m_dirModel); + } +} + +void KFilePreviewGenerator::updatePreviews() +{ + if (!m_showPreview) { + return; + } + + killPreviewJobs(); + m_cutItemsCache.clear(); + m_pendingItems.clear(); + m_dispatchedItems.clear(); + + KFileItemList itemList; + const int rowCount = m_dirModel->rowCount(); + for (int row = 0; row < rowCount; ++row) { + const QModelIndex index = m_dirModel->index(row, 0); + KFileItem item = m_dirModel->itemForIndex(index); + itemList.append(item); + } + + generatePreviews(itemList); + updateCutItems(); +} + +void KFilePreviewGenerator::cancelPreviews() +{ + killPreviewJobs(); + m_cutItemsCache.clear(); + m_pendingItems.clear(); + m_dispatchedItems.clear(); +} + +void KFilePreviewGenerator::generatePreviews(const KFileItemList& items) +{ + applyCutItemEffect(); + + if (!m_showPreview) { + return; + } + + KFileItemList orderedItems = items; + orderItems(orderedItems); + + foreach (const KFileItem& item, orderedItems) { + m_pendingItems.append(item); + } + + startPreviewJob(orderedItems); +} + +void KFilePreviewGenerator::addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap) +{ + if (!m_showPreview) { + // the preview has been canceled in the meantime + return; + } + const KUrl url = item.url(); + + // check whether the item is part of the directory lister (it is possible + // that a preview from an old directory lister is received) + KDirLister* dirLister = m_dirModel->dirLister(); + bool isOldPreview = true; + const KUrl::List dirs = dirLister->directories(); + const QString itemDir = url.directory(); + foreach (const KUrl& url, dirs) { + if (url.path() == itemDir) { + isOldPreview = false; + break; + } + } + if (isOldPreview) { + return; + } + + QPixmap icon = pixmap; + + const QString mimeType = item.mimetype(); + const QString mimeTypeGroup = mimeType.left(mimeType.indexOf('/')); + if ((mimeTypeGroup != "image") || !applyImageFrame(icon)) { + limitToSize(icon, m_view->iconSize()); + } + + if (m_hasCutSelection && isCutItem(item)) { + // Remember the current icon in the cache for cut items before + // the disabled effect is applied. This makes it possible restoring + // the uncut version again when cutting other items. + QList::iterator begin = m_cutItemsCache.begin(); + QList::iterator end = m_cutItemsCache.end(); + for (QList::iterator it = begin; it != end; ++it) { + if ((*it).url == item.url()) { + (*it).pixmap = icon; + break; + } + } + + // apply the disabled effect to the icon for marking it as "cut item" + // and apply the icon to the item + KIconEffect iconEffect; + icon = iconEffect.apply(icon, KIconLoader::Desktop, KIconLoader::DisabledState); + } + + // remember the preview and URL, so that it can be applied to the model + // in KFilePreviewGenerator::dispatchPreviewQueue() + ItemInfo preview; + preview.url = url; + preview.pixmap = icon; + m_previews.append(preview); + + m_dispatchedItems.append(item); +} + +void KFilePreviewGenerator::slotPreviewJobFinished(KJob* job) +{ + const int index = m_previewJobs.indexOf(job); + m_previewJobs.removeAt(index); + + if ((m_previewJobs.count() == 0) && m_clearItemQueues) { + m_pendingItems.clear(); + m_dispatchedItems.clear(); + m_pendingVisiblePreviews = 0; + QMetaObject::invokeMethod(this, "dispatchPreviewQueue", Qt::QueuedConnection); + } +} + +void KFilePreviewGenerator::updateCutItems() +{ + // restore the icons of all previously selected items to the + // original state... + foreach (const ItemInfo& cutItem, m_cutItemsCache) { + const QModelIndex index = m_dirModel->indexForUrl(cutItem.url); + if (index.isValid()) { + m_dirModel->setData(index, QIcon(cutItem.pixmap), Qt::DecorationRole); + } + } + m_cutItemsCache.clear(); + + // ... and apply an item effect to all currently cut items + applyCutItemEffect(); +} + +void KFilePreviewGenerator::dispatchPreviewQueue() +{ + const int previewsCount = m_previews.count(); + if (previewsCount > 0) { + // Applying the previews to the model must be done step by step + // in larger blocks: Applying a preview immediately when getting the signal + // 'gotPreview()' from the PreviewJob is too expensive, as a relayout + // of the view would be triggered for each single preview. + LayoutBlocker blocker(m_view); + for (int i = 0; i < previewsCount; ++i) { + const ItemInfo& preview = m_previews.first(); + + const QModelIndex idx = m_dirModel->indexForUrl(preview.url); + if (idx.isValid() && (idx.column() == 0)) { + m_dirModel->setData(idx, QIcon(preview.pixmap), Qt::DecorationRole); + } + + m_previews.pop_front(); + if (m_pendingVisiblePreviews > 0) { + --m_pendingVisiblePreviews; + } + } + } + + if (m_pendingVisiblePreviews > 0) { + // As long as there are pending previews for visible items, poll + // the preview queue each 200 ms. If there are no pending previews, + // the queue is dispatched in slotPreviewJobFinished(). + m_previewTimer->start(200); + } +} + +void KFilePreviewGenerator::pausePreviews() +{ + foreach (KJob* job, m_previewJobs) { + Q_ASSERT(job != 0); + job->suspend(); + } + m_scrollAreaTimer->start(); +} + +void KFilePreviewGenerator::resumePreviews() +{ + // Before creating new preview jobs the m_pendingItems queue must be + // cleaned up by removing the already dispatched items. Implementation + // note: The order of the m_dispatchedItems queue and the m_pendingItems + // queue is usually equal. So even when having a lot of elements the + // nested loop is no performance bottle neck, as the inner loop is only + // entered once in most cases. + foreach (const KFileItem& item, m_dispatchedItems) { + KFileItemList::iterator begin = m_pendingItems.begin(); + KFileItemList::iterator end = m_pendingItems.end(); + for (KFileItemList::iterator it = begin; it != end; ++it) { + if ((*it).url() == item.url()) { + m_pendingItems.erase(it); + break; + } + } + } + m_dispatchedItems.clear(); + + m_pendingVisiblePreviews = 0; + dispatchPreviewQueue(); + + KFileItemList orderedItems = m_pendingItems; + orderItems(orderedItems); + + // Kill all suspended preview jobs. Usually when a preview job + // has been finished, slotPreviewJobFinished() clears all item queues. + // This is not wanted in this case, as a new job is created afterwards + // for m_pendingItems. + m_clearItemQueues = false; + killPreviewJobs(); + m_clearItemQueues = true; + + startPreviewJob(orderedItems); +} + +bool KFilePreviewGenerator::isCutItem(const KFileItem& item) const +{ + const QMimeData* mimeData = QApplication::clipboard()->mimeData(); + const KUrl::List cutUrls = KUrl::List::fromMimeData(mimeData); + + const KUrl itemUrl = item.url(); + foreach (const KUrl& url, cutUrls) { + if (url == itemUrl) { + return true; + } + } + + return false; +} + +void KFilePreviewGenerator::applyCutItemEffect() +{ + const QMimeData* mimeData = QApplication::clipboard()->mimeData(); + m_hasCutSelection = KonqMimeData::decodeIsCutSelection(mimeData); + if (!m_hasCutSelection) { + return; + } + + KFileItemList items; + KDirLister* dirLister = m_dirModel->dirLister(); + const KUrl::List dirs = dirLister->directories(); + foreach (const KUrl& url, dirs) { + items << dirLister->itemsForDir(url); + } + + foreach (const KFileItem& item, items) { + if (isCutItem(item)) { + const QModelIndex index = m_dirModel->indexForItem(item); + const QVariant value = m_dirModel->data(index, Qt::DecorationRole); + if (value.type() == QVariant::Icon) { + const QIcon icon(qvariant_cast(value)); + const QSize actualSize = icon.actualSize(m_view->iconSize()); + QPixmap pixmap = icon.pixmap(actualSize); + + // remember current pixmap for the item to be able + // to restore it when other items get cut + ItemInfo cutItem; + cutItem.url = item.url(); + cutItem.pixmap = pixmap; + m_cutItemsCache.append(cutItem); + + // apply icon effect to the cut item + KIconEffect iconEffect; + pixmap = iconEffect.apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState); + m_dirModel->setData(index, QIcon(pixmap), Qt::DecorationRole); + } + } + } +} + +bool KFilePreviewGenerator::applyImageFrame(QPixmap& icon) +{ + const QSize maxSize = m_view->iconSize(); + const bool applyFrame = (maxSize.width() > KIconLoader::SizeSmallMedium) && + (maxSize.height() > KIconLoader::SizeSmallMedium) && + ((icon.width() > KIconLoader::SizeLarge) || + (icon.height() > KIconLoader::SizeLarge)); + if (!applyFrame) { + // the maximum size or the image itself is too small for a frame + return false; + } + + const int frame = 4; + const int doubleFrame = frame * 2; + + // resize the icon to the maximum size minus the space required for the frame + limitToSize(icon, QSize(maxSize.width() - doubleFrame, maxSize.height() - doubleFrame)); + + QPainter painter; + const QPalette palette = m_view->palette(); + QPixmap framedIcon(icon.size().width() + doubleFrame, icon.size().height() + doubleFrame); + framedIcon.fill(palette.color(QPalette::Normal, QPalette::Base)); + const int width = framedIcon.width() - 1; + const int height = framedIcon.height() - 1; + + painter.begin(&framedIcon); + painter.drawPixmap(frame, frame, icon); + + // add a border + painter.setPen(palette.color(QPalette::Text)); + painter.drawRect(0, 0, width, height); + painter.drawRect(1, 1, width - 2, height - 2); + + painter.setCompositionMode(QPainter::CompositionMode_Plus); + QColor blendColor = palette.color(QPalette::Normal, QPalette::Base); + + blendColor.setAlpha(255 - 32); + painter.setPen(blendColor); + painter.drawRect(0, 0, width, height); + + blendColor.setAlpha(255 - 64); + painter.setPen(blendColor); + painter.drawRect(1, 1, width - 2, height - 2); + painter.end(); + + icon = framedIcon; + + return true; +} + +void KFilePreviewGenerator::limitToSize(QPixmap& icon, const QSize& maxSize) +{ + if ((icon.width() > maxSize.width()) || (icon.height() > maxSize.height())) { + icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::FastTransformation); + } +} + +void KFilePreviewGenerator::startPreviewJob(const KFileItemList& items) +{ + if (items.count() == 0) { + return; + } + + const QMimeData* mimeData = QApplication::clipboard()->mimeData(); + m_hasCutSelection = KonqMimeData::decodeIsCutSelection(mimeData); + + const QSize size = m_view->iconSize(); + + // PreviewJob internally caches items always with the size of + // 128 x 128 pixels or 256 x 256 pixels. A downscaling is done + // by PreviewJob if a smaller size is requested. As the KFilePreviewGenerator must + // do a downscaling anyhow because of the frame, only the provided + // cache sizes are requested. + const int cacheSize = (size.width() > 128) || (size.height() > 128) ? 256 : 128; + KIO::PreviewJob* job = KIO::filePreview(items, cacheSize, cacheSize); + connect(job, SIGNAL(gotPreview(const KFileItem&, const QPixmap&)), + this, SLOT(addToPreviewQueue(const KFileItem&, const QPixmap&))); + connect(job, SIGNAL(finished(KJob*)), + this, SLOT(slotPreviewJobFinished(KJob*))); + + m_previewJobs.append(job); + m_previewTimer->start(200); +} + +void KFilePreviewGenerator::killPreviewJobs() +{ + foreach (KJob* job, m_previewJobs) { + Q_ASSERT(job != 0); + job->kill(); + } + m_previewJobs.clear(); +} + +void KFilePreviewGenerator::orderItems(KFileItemList& items) +{ + // Order the items in a way that the preview for the visible items + // is generated first, as this improves the feeled performance a lot. + // + // Implementation note: 2 different algorithms are used for the sorting. + // Algorithm 1 is faster when having a lot of items in comparison + // to the number of rows in the model. Algorithm 2 is faster + // when having quite less items in comparison to the number of rows in + // the model. Choosing the right algorithm is important when having directories + // with several hundreds or thousands of items. + + const int itemCount = items.count(); + const int rowCount = m_proxyModel->rowCount(); + const QRect visibleArea = m_view->viewport()->rect(); + + int insertPos = 0; + if (itemCount * 10 > rowCount) { + // Algorithm 1: The number of items is > 10 % of the row count. Parse all rows + // and check whether the received row is part of the item list. + for (int row = 0; row < rowCount; ++row) { + const QModelIndex proxyIndex = m_proxyModel->index(row, 0); + const QRect itemRect = m_view->visualRect(proxyIndex); + const QModelIndex dirIndex = m_proxyModel->mapToSource(proxyIndex); + + KFileItem item = m_dirModel->itemForIndex(dirIndex); // O(1) + const KUrl url = item.url(); + + // check whether the item is part of the item list 'items' + int index = -1; + for (int i = 0; i < itemCount; ++i) { + if (items.at(i).url() == url) { + index = i; + break; + } + } + + if ((index > 0) && itemRect.intersects(visibleArea)) { + // The current item is (at least partly) visible. Move it + // to the front of the list, so that the preview is + // generated earlier. + items.removeAt(index); + items.insert(insertPos, item); + ++insertPos; + ++m_pendingVisiblePreviews; + } + } + } else { + // Algorithm 2: The number of items is <= 10 % of the row count. In this case iterate + // all items and receive the corresponding row from the item. + for (int i = 0; i < itemCount; ++i) { + const QModelIndex dirIndex = m_dirModel->indexForItem(items.at(i)); // O(n) (n = number of rows) + const QModelIndex proxyIndex = m_proxyModel->mapFromSource(dirIndex); + const QRect itemRect = m_view->visualRect(proxyIndex); + + if (itemRect.intersects(visibleArea)) { + // The current item is (at least partly) visible. Move it + // to the front of the list, so that the preview is + // generated earlier. + items.insert(insertPos, items.at(i)); + items.removeAt(i + 1); + ++insertPos; + ++m_pendingVisiblePreviews; + } + } + } +} + +#include "kfilepreviewgenerator.moc" diff --git a/src/kfilepreviewgenerator.h b/src/kfilepreviewgenerator.h new file mode 100644 index 000000000..47aff66a7 --- /dev/null +++ b/src/kfilepreviewgenerator.h @@ -0,0 +1,210 @@ +/*************************************************************************** + * Copyright (C) 2008 by Peter Penz * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * + ***************************************************************************/ + +#ifndef KFILEPREVIEWGENERATOR_H +#define KFILEPREVIEWGENERATOR_H + +#include +#include + +#include +#include +#include + +class KDirModel; +class KDirSortFilterProxyModel; +class KJob; +class KMimeTypeResolver; +class QAbstractItemView; + +/** + * @brief Manages the icon state of a directory model. + * + * Per default a preview is generated for each item. + * Additionally the clipboard is checked for cut items. + * The icon state for cut items gets dimmed automatically. + * + * The following strategy is used when creating previews: + * - The previews for currently visible items are created before + * the previews for invisible items. + * - If the user changes the visible area by using the scrollbars, + * all pending previews get paused. As soon as the user stays + * on the same position for a short delay, the previews are + * resumed. Also in this case the previews for the visible items + * are generated first. + */ +class KFilePreviewGenerator : public QObject +{ + Q_OBJECT + +public: + KFilePreviewGenerator(QAbstractItemView* parent, KDirSortFilterProxyModel* model); + virtual ~KFilePreviewGenerator(); + void setShowPreview(bool show); + bool showPreview() const; + + /** + * Updates the previews for all already available items. It is only necessary + * to invoke this method when the icon size of the abstract item view has + * been changed. + */ + void updatePreviews(); + + /** + * Cancels all pending previews. Should be invoked when the URL of the item + * view has been changed. + */ + void cancelPreviews(); + +private slots: + /** + * Generates previews for the items \a items asynchronously. + */ + void generatePreviews(const KFileItemList& items); + + /** + * Adds the preview \a pixmap for the item \a item to the preview + * queue and starts a timer which will dispatch the preview queue + * later. + */ + void addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap); + + /** + * Is invoked when the preview job has been finished and + * removes the job from the m_previewJobs list. + */ + void slotPreviewJobFinished(KJob* job); + + /** Synchronizes the item icon with the clipboard of cut items. */ + void updateCutItems(); + + /** + * Dispatches the preview queue block by block within + * time slices. + */ + void dispatchPreviewQueue(); + + /** + * Pauses all preview jobs and invokes KFilePreviewGenerator::resumePreviews() + * after a short delay. Is invoked as soon as the user has moved + * a scrollbar. + */ + void pausePreviews(); + + /** + * Resumes the previews that have been paused after moving the + * scrollbar. The previews for the current visible area are + * generated first. + */ + void resumePreviews(); + +private: + /** + * Returns true, if the item \a item has been cut into + * the clipboard. + */ + bool isCutItem(const KFileItem& item) const; + + /** Applies an item effect to all cut items. */ + void applyCutItemEffect(); + + /** + * Applies a frame around the icon. False is returned if + * no frame has been added because the icon is too small. + */ + bool applyImageFrame(QPixmap& icon); + + /** + * Resizes the icon to \a maxSize if the icon size does not + * fit into the maximum size. The aspect ratio of the icon + * is kept. + */ + void limitToSize(QPixmap& icon, const QSize& maxSize); + + /** + * Starts a new preview job for the items \a to m_previewJobs + * and triggers the preview timer. + */ + void startPreviewJob(const KFileItemList& items); + + /** Kills all ongoing preview jobs. */ + void killPreviewJobs(); + + /** + * Orders the items \a items in a way that the visible items + * are moved to the front of the list. When passing this + * list to a preview job, the visible items will get generated + * first. + */ + void orderItems(KFileItemList& items); + +private: + /** Remembers the pixmap for an item specified by an URL. */ + struct ItemInfo + { + KUrl url; + QPixmap pixmap; + }; + + bool m_showPreview; + + /** + * True, if m_pendingItems and m_dispatchedItems should be + * cleared when the preview jobs have been finished. + */ + bool m_clearItemQueues; + + /** + * True if a selection has been done which should cut items. + */ + bool m_hasCutSelection; + + int m_pendingVisiblePreviews; + + QAbstractItemView* m_view; + QTimer* m_previewTimer; + QTimer* m_scrollAreaTimer; + QList m_previewJobs; + KDirModel* m_dirModel; + KDirSortFilterProxyModel* m_proxyModel; + + KMimeTypeResolver* m_mimeTypeResolver; + + QList m_cutItemsCache; + QList m_previews; + + /** + * Contains all items where a preview must be generated, but + * where the preview job has not dispatched the items yet. + */ + KFileItemList m_pendingItems; + + /** + * Contains all items, where a preview has already been + * generated by the preview jobs. + */ + KFileItemList m_dispatchedItems; +}; + +inline bool KFilePreviewGenerator::showPreview() const +{ + return m_showPreview; +} + +#endif -- cgit v1.3