File indexing completed on 2024-05-12 04:19:49

0001 // vim: set tabstop=4 shiftwidth=4 expandtab:
0002 /*
0003 Gwenview: an image viewer
0004 Copyright 2009 Aurélien Gâteau <agateau@kde.org>
0005 
0006 This program is free software; you can redistribute it and/or
0007 modify it under the terms of the GNU General Public License
0008 as published by the Free Software Foundation; either version 2
0009 of the License, or (at your option) any later version.
0010 
0011 This program is distributed in the hope that it will be useful,
0012 but WITHOUT ANY WARRANTY; without even the implied warranty of
0013 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0014 GNU General Public License for more details.
0015 
0016 You should have received a copy of the GNU General Public License
0017 along with this program; if not, write to the Free Software
0018 Foundation, Inc., 51 Franklin Street, Fifth Floor, Cambridge, MA 02110-1301, USA.
0019 
0020 */
0021 // Self
0022 #include "itemeditor.h"
0023 
0024 // Qt
0025 #include <QApplication>
0026 #include <QMimeDatabase>
0027 #include <QShowEvent>
0028 
0029 // KF
0030 
0031 // Local
0032 #include "gwenview_lib_debug.h"
0033 
0034 namespace Gwenview
0035 {
0036 struct ItemEditorPrivate {
0037     QPoint mCenter;
0038 };
0039 
0040 ItemEditor::ItemEditor(QWidget *parent)
0041     : KLineEdit(parent)
0042     , d(new ItemEditorPrivate)
0043 {
0044     setPalette(QApplication::palette());
0045     connect(this, &ItemEditor::textChanged, this, &ItemEditor::resizeToContents);
0046     setTrapReturnKey(true);
0047 }
0048 
0049 ItemEditor::~ItemEditor()
0050 {
0051     delete d;
0052 }
0053 
0054 void ItemEditor::showEvent(QShowEvent *event)
0055 {
0056     // We can't do this in PreviewItemDelegate::updateEditorGeometry() because QAbstractItemView outsmarts us by calling selectAll() on the editor if it is a
0057     // QLineEdit
0058     QMimeDatabase db;
0059     const QString extension = db.suffixForFileName(text());
0060     if (!extension.isEmpty()) {
0061         // The filename contains an extension. Assure that only the filename
0062         // gets selected.
0063         const int selectionLength = text().length() - extension.length() - 1;
0064         setSelection(0, selectionLength);
0065     }
0066     KLineEdit::showEvent(event);
0067 }
0068 
0069 void ItemEditor::resizeToContents()
0070 {
0071     if (d->mCenter.isNull()) {
0072         d->mCenter = geometry().center();
0073     }
0074     int textWidth = fontMetrics().boundingRect(QStringLiteral("  ") + text() + QStringLiteral("  ")).width();
0075     QRect rect = geometry();
0076     rect.setWidth(textWidth);
0077     rect.moveCenter(d->mCenter);
0078     if (rect.right() > parentWidget()->width()) {
0079         rect.setRight(parentWidget()->width());
0080     }
0081     if (rect.left() < 0) {
0082         rect.setLeft(0);
0083     }
0084     setGeometry(rect);
0085 }
0086 
0087 } // namespace
0088 
0089 #include "moc_itemeditor.cpp"