]> cloud.milkyroute.net Git - dolphin.git/blobdiff - src/kitemviews/kstandarditemlistwidget.cpp
Fix selection rect after porting from QFontMetrics::width()
[dolphin.git] / src / kitemviews / kstandarditemlistwidget.cpp
index 51c5bc896a588f03a450cee07dd4e69d1a6a1918..214cc3755b505cb8f3656322001d7ac5052487d3 100644 (file)
 
 #include "kfileitemlistview.h"
 #include "kfileitemmodel.h"
+#include "private/kfileitemclipboard.h"
+#include "private/kitemlistroleeditor.h"
+#include "private/kpixmapmodifier.h"
 
-#include <QIcon>
 #include <KIconEffect>
 #include <KIconLoader>
 #include <KRatingPainter>
 #include <KStringHandler>
 
-#include "private/kfileitemclipboard.h"
-#include "private/kitemlistroleeditor.h"
-#include "private/kpixmapmodifier.h"
-
 #include <QGraphicsScene>
 #include <QGraphicsSceneResizeEvent>
 #include <QGraphicsView>
-#include <QPainter>
-#include <QStyleOption>
-#include <QTextLayout>
-#include <QTextLine>
-#include <QPixmapCache>
 #include <QGuiApplication>
+#include <QPixmapCache>
+#include <QStyleOption>
 
 // #define KSTANDARDITEMLISTWIDGET_DEBUG
 
@@ -56,15 +51,15 @@ KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
 void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector<qreal>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
 {
     switch (static_cast<const KStandardItemListView*>(view)->itemLayout()) {
-    case KStandardItemListWidget::IconsLayout:
+    case KStandardItemListView::IconsLayout:
         calculateIconsLayoutItemSizeHints(logicalHeightHints, logicalWidthHint, view);
         break;
 
-    case KStandardItemListWidget::CompactLayout:
+    case KStandardItemListView::CompactLayout:
         calculateCompactLayoutItemSizeHints(logicalHeightHints, logicalWidthHint, view);
         break;
 
-    case KStandardItemListWidget::DetailsLayout:
+    case KStandardItemListView::DetailsLayout:
         calculateDetailsLayoutItemSizeHints(logicalHeightHints, logicalWidthHint, view);
         break;
 
@@ -93,7 +88,7 @@ qreal KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArra
         // If current item is a link, we use the customized link font metrics instead of the normal font metrics.
         const QFontMetrics& fontMetrics = itemIsLink(index, view) ? linkFontMetrics : normalFontMetrics;
 
-        width += fontMetrics.width(text);
+        width += fontMetrics.horizontalAdvance(text);
 
         if (role == "text") {
             if (view->supportsItemExpanding()) {
@@ -118,8 +113,8 @@ QString KStandardItemListWidgetInformant::itemText(int index, const KItemListVie
 
 bool KStandardItemListWidgetInformant::itemIsLink(int index, const KItemListView* view) const
 {
-    Q_UNUSED(index);
-    Q_UNUSED(view);
+    Q_UNUSED(index)
+    Q_UNUSED(view)
     return false;
 }
 
@@ -219,12 +214,12 @@ void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVect
         qreal maximumRequiredWidth = 0.0;
 
         if (showOnlyTextRole) {
-            maximumRequiredWidth = fontMetrics.width(itemText(index, view));
+            maximumRequiredWidth = fontMetrics.horizontalAdvance(itemText(index, view));
         } else {
             const QHash<QByteArray, QVariant>& values = view->model()->data(index);
             foreach (const QByteArray& role, visibleRoles) {
                 const QString& text = roleText(role, values);
-                const qreal requiredWidth = fontMetrics.width(text);
+                const qreal requiredWidth = fontMetrics.horizontalAdvance(text);
                 maximumRequiredWidth = qMax(maximumRequiredWidth, requiredWidth);
             }
         }
@@ -273,8 +268,8 @@ KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant* infor
     m_additionalInfoTextColor(),
     m_overlay(),
     m_rating(),
-    m_roleEditor(0),
-    m_oldRoleEditor(0)
+    m_roleEditor(nullptr),
+    m_oldRoleEditor(nullptr)
 {
 }
 
@@ -483,7 +478,7 @@ QRectF KStandardItemListWidget::textFocusRect() const
         const KItemListStyleOption& option = styleOption();
         if (option.extendedSelectionRegion) {
             const QString text = textInfo->staticText.text();
-            rect.setWidth(m_customizedFontMetrics.width(text) + 2 * option.padding);
+            rect.setWidth(m_customizedFontMetrics.horizontalAdvance(text) + 2 * option.padding);
         }
 
         return rect;
@@ -605,7 +600,7 @@ void KStandardItemListWidget::refreshCache()
 
 bool KStandardItemListWidget::isRoleRightAligned(const QByteArray& role) const
 {
-    Q_UNUSED(role);
+    Q_UNUSED(role)
     return false;
 }
 
@@ -670,7 +665,7 @@ QString KStandardItemListWidget::roleText(const QByteArray& role,
 void KStandardItemListWidget::dataChanged(const QHash<QByteArray, QVariant>& current,
                                           const QSet<QByteArray>& roles)
 {
-    Q_UNUSED(current);
+    Q_UNUSED(current)
 
     m_dirtyContent = true;
 
@@ -702,7 +697,7 @@ void KStandardItemListWidget::dataChanged(const QHash<QByteArray, QVariant>& cur
 void KStandardItemListWidget::visibleRolesChanged(const QList<QByteArray>& current,
                                               const QList<QByteArray>& previous)
 {
-    Q_UNUSED(previous);
+    Q_UNUSED(previous)
     m_sortedVisibleRoles = current;
     m_dirtyLayout = true;
 }
@@ -711,38 +706,38 @@ void KStandardItemListWidget::columnWidthChanged(const QByteArray& role,
                                              qreal current,
                                              qreal previous)
 {
-    Q_UNUSED(role);
-    Q_UNUSED(current);
-    Q_UNUSED(previous);
+    Q_UNUSED(role)
+    Q_UNUSED(current)
+    Q_UNUSED(previous)
     m_dirtyLayout = true;
 }
 
 void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption& current,
                                              const KItemListStyleOption& previous)
 {
-    Q_UNUSED(current);
-    Q_UNUSED(previous);
+    Q_UNUSED(current)
+    Q_UNUSED(previous)
     updateAdditionalInfoTextColor();
     m_dirtyLayout = true;
 }
 
 void KStandardItemListWidget::hoveredChanged(bool hovered)
 {
-    Q_UNUSED(hovered);
+    Q_UNUSED(hovered)
     m_dirtyLayout = true;
 }
 
 void KStandardItemListWidget::selectedChanged(bool selected)
 {
-    Q_UNUSED(selected);
+    Q_UNUSED(selected)
     updateAdditionalInfoTextColor();
     m_dirtyContent = true;
 }
 
 void KStandardItemListWidget::siblingsInformationChanged(const QBitArray& current, const QBitArray& previous)
 {
-    Q_UNUSED(current);
-    Q_UNUSED(previous);
+    Q_UNUSED(current)
+    Q_UNUSED(previous)
     m_dirtyLayout = true;
 }
 
@@ -753,7 +748,7 @@ int KStandardItemListWidget::selectionLength(const QString& text) const
 
 void KStandardItemListWidget::editedRoleChanged(const QByteArray& current, const QByteArray& previous)
 {
-    Q_UNUSED(previous);
+    Q_UNUSED(previous)
 
     QGraphicsView* parent = scene()->views()[0];
     if (current.isEmpty() || !parent || current != "text") {
@@ -770,7 +765,7 @@ void KStandardItemListWidget::editedRoleChanged(const QByteArray& current, const
             }
             m_oldRoleEditor = m_roleEditor;
             m_roleEditor->hide();
-            m_roleEditor = 0;
+            m_roleEditor = nullptr;
         }
         return;
     }
@@ -850,6 +845,23 @@ void KStandardItemListWidget::hideEvent(QHideEvent* event)
     KItemListWidget::hideEvent(event);
 }
 
+bool KStandardItemListWidget::event(QEvent *event)
+{
+    if (event->type() == QEvent::WindowDeactivate || event->type() == QEvent::WindowActivate
+            || event->type() == QEvent::PaletteChange) {
+        m_dirtyContent = true;
+    }
+
+    return KItemListWidget::event(event);
+}
+
+void KStandardItemListWidget::finishRoleEditing()
+{
+    if (!editedRole().isEmpty() && m_roleEditor) {
+        slotRoleEditingFinished(editedRole(), KIO::encodeFileName(m_roleEditor->toPlainText()));
+    }
+}
+
 void KStandardItemListWidget::slotCutItemsChanged()
 {
     const QUrl itemUrl = data().value("url").toUrl();
@@ -954,7 +966,7 @@ void KStandardItemListWidget::updatePixmapCache()
                 iconName = QStringLiteral("unknown");
             }
             const QStringList overlays = values["iconOverlays"].toStringList();
-            m_pixmap = pixmapForIcon(iconName, overlays, maxIconHeight);
+            m_pixmap = pixmapForIcon(iconName, overlays, maxIconHeight, m_layout != IconsLayout && isActiveWindow() && isSelected() ? QIcon::Selected : QIcon::Normal);
 
         } else if (m_pixmap.width() / m_pixmap.devicePixelRatio() != maxIconWidth || m_pixmap.height() / m_pixmap.devicePixelRatio() != maxIconHeight) {
             // A custom pixmap has been applied. Assure that the pixmap
@@ -981,7 +993,7 @@ void KStandardItemListWidget::updatePixmapCache()
 
     if (!m_overlay.isNull()) {
         QPainter painter(&m_pixmap);
-        painter.drawPixmap(0, m_pixmap.height() - m_overlay.height(), m_overlay);
+        painter.drawPixmap(0, (m_pixmap.height() - m_overlay.height()) / m_pixmap.devicePixelRatio(), m_overlay);
     }
 
     int scaledIconSize = 0;
@@ -999,19 +1011,26 @@ void KStandardItemListWidget::updatePixmapCache()
     const int maxScaledIconHeight = scaledIconSize;
 
     m_scaledPixmapSize = m_pixmap.size();
-    m_scaledPixmapSize.scale(maxScaledIconWidth, maxScaledIconHeight, Qt::KeepAspectRatio);
+    m_scaledPixmapSize.scale(maxScaledIconWidth * qApp->devicePixelRatio(), maxScaledIconHeight * qApp->devicePixelRatio(), Qt::KeepAspectRatio);
+    m_scaledPixmapSize = m_scaledPixmapSize / qApp->devicePixelRatio();
 
     if (iconOnTop) {
         // Center horizontally and align on bottom within the icon-area
-        m_pixmapPos.setX((widgetSize.width() - m_scaledPixmapSize.width()) / 2);
+        m_pixmapPos.setX((widgetSize.width() - m_scaledPixmapSize.width()) / 2.0);
         m_pixmapPos.setY(padding + scaledIconSize - m_scaledPixmapSize.height());
     } else {
         // Center horizontally and vertically within the icon-area
         const TextInfo* textInfo = m_textInfo.value("text");
-        m_pixmapPos.setX(textInfo->pos.x() - 2 * padding
-                         - (scaledIconSize + m_scaledPixmapSize.width()) / 2);
-        m_pixmapPos.setY(padding
-                         + (scaledIconSize - m_scaledPixmapSize.height()) / 2);
+        m_pixmapPos.setX(textInfo->pos.x() - 2.0 * padding
+                      - (scaledIconSize + m_scaledPixmapSize.width()) / 2.0);
+
+        // Derive icon's vertical center from the center of the text frame, including
+        // any necessary adjustment if the font's midline is offset from the frame center
+        const qreal midlineShift = m_customizedFontMetrics.height() / 2.0
+                    - m_customizedFontMetrics.descent()
+                    - m_customizedFontMetrics.capHeight() / 2.0;
+        m_pixmapPos.setY(m_textRect.center().y() + midlineShift - m_scaledPixmapSize.height() / 2.0);
+
     }
 
     m_iconRect = QRectF(m_pixmapPos, QSizeF(m_scaledPixmapSize));
@@ -1080,11 +1099,13 @@ void KStandardItemListWidget::updateTextsCache()
         if (ratingSize.width() > availableWidth) {
             ratingSize.rwidth() = availableWidth;
         }
-        m_rating = QPixmap(ratingSize.toSize());
+        const qreal dpr = qApp->devicePixelRatio();
+        m_rating = QPixmap(ratingSize.toSize() * dpr);
+        m_rating.setDevicePixelRatio(dpr);
         m_rating.fill(Qt::transparent);
 
         QPainter painter(&m_rating);
-        const QRect rect(0, 0, m_rating.width(), m_rating.height());
+        const QRect rect(QPoint(0, 0), ratingSize.toSize());
         const int rating = data().value("rating").toInt();
         KRatingPainter::paintRating(&painter, rect, Qt::AlignJustify | Qt::AlignVCenter, rating);
     } else if (!m_rating.isNull()) {
@@ -1092,6 +1113,26 @@ void KStandardItemListWidget::updateTextsCache()
     }
 }
 
+QString KStandardItemListWidget::elideRightKeepExtension(const QString &text, int elidingWidth) const
+{
+    const auto extensionIndex = text.lastIndexOf('.');
+    if (extensionIndex != -1) {
+        // has file extension
+        const auto extensionLength = text.length() - extensionIndex;
+        const auto extensionWidth = m_customizedFontMetrics.horizontalAdvance(text.right(extensionLength));
+        if (elidingWidth > extensionWidth && extensionLength < 6 && (float(extensionWidth) / float(elidingWidth)) < 0.3) {
+            // if we have room to display the file extension and the extension is not too long
+            QString ret = m_customizedFontMetrics.elidedText(text.chopped(extensionLength),
+                                                             Qt::ElideRight,
+                                                             elidingWidth - extensionWidth);
+            ret.append(text.right(extensionLength));
+            return ret;
+        }
+    }
+    return m_customizedFontMetrics.elidedText(text,Qt::ElideRight,
+                                              elidingWidth);
+}
+
 void KStandardItemListWidget::updateIconsLayoutTextCache()
 {
     //      +------+
@@ -1143,13 +1184,11 @@ void KStandardItemListWidget::updateIconsLayoutTextCache()
                 qreal lastLineWidth;
                 do {
                     QString lastTextLine = nameText.mid(line.textStart());
-                    lastTextLine = m_customizedFontMetrics.elidedText(lastTextLine,
-                                                                      Qt::ElideRight,
-                                                                      elidingWidth);
+                    lastTextLine = elideRightKeepExtension(lastTextLine, elidingWidth);
                     const QString elidedText = nameText.left(line.textStart()) + lastTextLine;
                     nameTextInfo->staticText.setText(elidedText);
 
-                    lastLineWidth = m_customizedFontMetrics.boundingRect(lastTextLine).width();
+                    lastLineWidth = m_customizedFontMetrics.horizontalAdvance(lastTextLine);
 
                     // We do the text eliding in a loop with decreasing width (1 px / iteration)
                     // to avoid problems related to different width calculation code paths
@@ -1200,11 +1239,11 @@ void KStandardItemListWidget::updateIconsLayoutTextCache()
             textLine.setLineWidth(maxWidth);
             requiredWidth = textLine.naturalTextWidth();
             if (requiredWidth > maxWidth) {
-                const QString elidedText = m_customizedFontMetrics.elidedText(text, Qt::ElideRight, maxWidth);
+                const QString elidedText = elideRightKeepExtension(text, maxWidth);
                 textInfo->staticText.setText(elidedText);
-                requiredWidth = m_customizedFontMetrics.width(elidedText);
+                requiredWidth = m_customizedFontMetrics.horizontalAdvance(elidedText);
             } else if (role == "rating") {
-               // Use the width of the rating pixmap, because the rating text is empty.
+                // Use the width of the rating pixmap, because the rating text is empty.
                 requiredWidth = m_rating.width();
             }
         }
@@ -1246,10 +1285,10 @@ void KStandardItemListWidget::updateCompactLayoutTextCache()
         TextInfo* textInfo = m_textInfo.value(role);
         textInfo->staticText.setText(text);
 
-        qreal requiredWidth = m_customizedFontMetrics.width(text);
+        qreal requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
         if (requiredWidth > maxWidth) {
             requiredWidth = maxWidth;
-            const QString elidedText = m_customizedFontMetrics.elidedText(text, Qt::ElideRight, maxWidth);
+            const QString elidedText = elideRightKeepExtension(text, maxWidth);
             textInfo->staticText.setText(elidedText);
         }
 
@@ -1261,7 +1300,7 @@ void KStandardItemListWidget::updateCompactLayoutTextCache()
         y += lineSpacing;
     }
 
-    m_textRect = QRectF(x - 2 * option.padding, 0, maximumRequiredTextWidth + 3 * option.padding, widgetHeight);
+    m_textRect = QRectF(x - option.padding, 0, maximumRequiredTextWidth + 2 * option.padding, widgetHeight);
 }
 
 void KStandardItemListWidget::updateDetailsLayoutTextCache()
@@ -1296,7 +1335,7 @@ void KStandardItemListWidget::updateDetailsLayoutTextCache()
         QString text = roleText(role, values);
 
         // Elide the text in case it does not fit into the available column-width
-        qreal requiredWidth = m_customizedFontMetrics.width(text);
+        qreal requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
         const qreal roleWidth = columnWidth(role);
         qreal availableTextWidth = roleWidth - columnWidthInc;
 
@@ -1306,8 +1345,8 @@ void KStandardItemListWidget::updateDetailsLayoutTextCache()
         }
 
         if (requiredWidth > availableTextWidth) {
-            text = m_customizedFontMetrics.elidedText(text, Qt::ElideRight, availableTextWidth);
-            requiredWidth = m_customizedFontMetrics.width(text);
+            text = elideRightKeepExtension(text, availableTextWidth);
+            requiredWidth = m_customizedFontMetrics.horizontalAdvance(text);
         }
 
         TextInfo* textInfo = m_textInfo.value(role);
@@ -1319,8 +1358,8 @@ void KStandardItemListWidget::updateDetailsLayoutTextCache()
             const qreal textWidth = option.extendedSelectionRegion
                                     ? size().width() - textInfo->pos.x()
                                     : requiredWidth + 2 * option.padding;
-            m_textRect = QRectF(textInfo->pos.x() - 2 * option.padding, 0,
-                                textWidth + option.padding, size().height());
+            m_textRect = QRectF(textInfo->pos.x() - option.padding, 0,
+                                textWidth, size().height());
 
             // The column after the name should always be aligned on the same x-position independent
             // from the expansion-level shown in the name column
@@ -1435,40 +1474,23 @@ void KStandardItemListWidget::closeRoleEditor()
     }
     m_oldRoleEditor = m_roleEditor;
     m_roleEditor->hide();
-    m_roleEditor = 0;
+    m_roleEditor = nullptr;
 }
 
-QPixmap KStandardItemListWidget::pixmapForIcon(const QString& name, const QStringList& overlays, int size)
+QPixmap KStandardItemListWidget::pixmapForIcon(const QString& name, const QStringList& overlays, int size, QIcon::Mode mode)
 {
     static const QIcon fallbackIcon = QIcon::fromTheme(QStringLiteral("unknown"));
+
     size *= qApp->devicePixelRatio();
-    const QString key = "KStandardItemListWidget:" % name % ":" % overlays.join(QStringLiteral(":")) % ":" % QString::number(size);
+
+    const QString key = "KStandardItemListWidget:" % name % ":" % overlays.join(QLatin1Char(':')) % ":" % QString::number(size) % ":" % QString::number(mode);
     QPixmap pixmap;
 
-    if (!QPixmapCache::find(key, pixmap)) {
+    if (!QPixmapCache::find(key, &pixmap)) {
         const QIcon icon = QIcon::fromTheme(name, fallbackIcon);
 
-        int requestedSize;
-        if (size <= KIconLoader::SizeSmall) {
-            requestedSize = KIconLoader::SizeSmall;
-        } else if (size <= KIconLoader::SizeSmallMedium) {
-            requestedSize = KIconLoader::SizeSmallMedium;
-        } else if (size <= KIconLoader::SizeMedium) {
-            requestedSize = KIconLoader::SizeMedium;
-        } else if (size <= KIconLoader::SizeLarge) {
-            requestedSize = KIconLoader::SizeLarge;
-        } else if (size <= KIconLoader::SizeHuge) {
-            requestedSize = KIconLoader::SizeHuge;
-        } else if (size <= KIconLoader::SizeEnormous) {
-            requestedSize = KIconLoader::SizeEnormous;
-        } else if (size <= KIconLoader::SizeEnormous * 2) {
-            requestedSize = KIconLoader::SizeEnormous * 2;
-        } else {
-            requestedSize = size;
-        }
-
-        pixmap = icon.pixmap(requestedSize / qApp->devicePixelRatio(), requestedSize / qApp->devicePixelRatio());
-        if (requestedSize != size) {
+        pixmap = icon.pixmap(size / qApp->devicePixelRatio(), size / qApp->devicePixelRatio(), mode);
+        if (pixmap.width() != size || pixmap.height() != size) {
             KPixmapModifier::scale(pixmap, QSize(size, size));
         }
 
@@ -1479,9 +1501,25 @@ QPixmap KStandardItemListWidget::pixmapForIcon(const QString& name, const QStrin
         // setup time.
         foreach (const QString& overlay, overlays) {
             if (!overlay.isEmpty()) {
+                int state = KIconLoader::DefaultState;
+
+                switch (mode) {
+                case QIcon::Normal:
+                    break;
+                case QIcon::Active:
+                    state = KIconLoader::ActiveState;
+                    break;
+                case QIcon::Disabled:
+                    state = KIconLoader::DisabledState;
+                    break;
+                case QIcon::Selected:
+                    state = KIconLoader::SelectedState;
+                    break;
+                }
+
                 // There is at least one overlay, draw all overlays above m_pixmap
                 // and cancel the check
-                KIconLoader::global()->drawOverlays(overlays, pixmap, KIconLoader::Desktop);
+                KIconLoader::global()->drawOverlays(overlays, pixmap, KIconLoader::Desktop, state);
                 break;
             }
         }