From 3e8b53a46ce8c54de17b0ae6bf5a6fa3eacaa143 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Wed, 4 May 2011 13:08:02 +0200 Subject: moving some more files around. --- src/gui/image/image.pri | 9 - src/gui/image/qicon.cpp | 1165 --------------------- src/gui/image/qicon.h | 143 --- src/gui/image/qicon_p.h | 139 --- src/gui/image/qiconengine.cpp | 324 ------ src/gui/image/qiconengine.h | 104 -- src/gui/image/qiconengineplugin.cpp | 171 ---- src/gui/image/qiconengineplugin.h | 104 -- src/gui/image/qiconloader.cpp | 573 ----------- src/gui/image/qiconloader_p.h | 192 ---- src/gui/kernel/kernel.pri | 13 +- src/gui/kernel/qicon.cpp | 1165 +++++++++++++++++++++ src/gui/kernel/qicon.h | 143 +++ src/gui/kernel/qicon_p.h | 139 +++ src/gui/kernel/qiconengine.cpp | 324 ++++++ src/gui/kernel/qiconengine.h | 104 ++ src/gui/kernel/qiconengineplugin.cpp | 171 ++++ src/gui/kernel/qiconengineplugin.h | 104 ++ src/gui/kernel/qiconloader.cpp | 573 +++++++++++ src/gui/kernel/qiconloader_p.h | 192 ++++ src/gui/text/qlinecontrol.cpp | 1833 ++++++++++++++++++++++++++++++++++ src/gui/text/qlinecontrol_p.h | 456 +++++++++ src/gui/text/text.pri | 6 +- src/gui/widgets/qlinecontrol.cpp | 1833 ---------------------------------- src/gui/widgets/qlinecontrol_p.h | 456 --------- src/gui/widgets/widgets.pri | 2 - 26 files changed, 5219 insertions(+), 5219 deletions(-) delete mode 100644 src/gui/image/qicon.cpp delete mode 100644 src/gui/image/qicon.h delete mode 100644 src/gui/image/qicon_p.h delete mode 100644 src/gui/image/qiconengine.cpp delete mode 100644 src/gui/image/qiconengine.h delete mode 100644 src/gui/image/qiconengineplugin.cpp delete mode 100644 src/gui/image/qiconengineplugin.h delete mode 100644 src/gui/image/qiconloader.cpp delete mode 100644 src/gui/image/qiconloader_p.h create mode 100644 src/gui/kernel/qicon.cpp create mode 100644 src/gui/kernel/qicon.h create mode 100644 src/gui/kernel/qicon_p.h create mode 100644 src/gui/kernel/qiconengine.cpp create mode 100644 src/gui/kernel/qiconengine.h create mode 100644 src/gui/kernel/qiconengineplugin.cpp create mode 100644 src/gui/kernel/qiconengineplugin.h create mode 100644 src/gui/kernel/qiconloader.cpp create mode 100644 src/gui/kernel/qiconloader_p.h create mode 100644 src/gui/text/qlinecontrol.cpp create mode 100644 src/gui/text/qlinecontrol_p.h delete mode 100644 src/gui/widgets/qlinecontrol.cpp delete mode 100644 src/gui/widgets/qlinecontrol_p.h (limited to 'src') diff --git a/src/gui/image/image.pri b/src/gui/image/image.pri index e970fb05a1..f9e0fa449a 100644 --- a/src/gui/image/image.pri +++ b/src/gui/image/image.pri @@ -5,11 +5,6 @@ HEADERS += \ image/qbitmap.h \ - image/qicon.h \ - image/qicon_p.h \ - image/qiconloader_p.h \ - image/qiconengine.h \ - image/qiconengineplugin.h \ image/qimage.h \ image/qimage_p.h \ image/qimageiohandler.h \ @@ -36,8 +31,6 @@ HEADERS += \ SOURCES += \ image/qbitmap.cpp \ - image/qicon.cpp \ - image/qiconloader.cpp \ image/qimage.cpp \ image/qimageiohandler.cpp \ image/qimagereader.cpp \ @@ -50,8 +43,6 @@ SOURCES += \ image/qpixmapdata.cpp \ image/qpixmapdatafactory.cpp \ image/qpixmapfilter.cpp \ - image/qiconengine.cpp \ - image/qiconengineplugin.cpp \ image/qmovie.cpp \ image/qpixmap_raster.cpp \ image/qpixmap_blitter.cpp \ diff --git a/src/gui/image/qicon.cpp b/src/gui/image/qicon.cpp deleted file mode 100644 index 59687c709d..0000000000 --- a/src/gui/image/qicon.cpp +++ /dev/null @@ -1,1165 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qicon.h" -#include "qicon_p.h" -#include "qiconengine.h" -#include "qiconengineplugin.h" -#include "private/qfactoryloader_p.h" -#include "private/qiconloader_p.h" -#include "qstyleoption.h" -#include "qpainter.h" -#include "qfileinfo.h" -#include "qstyle.h" -#include "qpixmapcache.h" -#include "qvariant.h" -#include "qcache.h" -#include "qdebug.h" -#include "private/qguiplatformplugin_p.h" -#include "qguiapplication.h" - -#ifdef Q_WS_MAC -#include -#include -#endif - -#ifdef Q_WS_X11 -#include "private/qt_x11_p.h" -#include "private/qkde_p.h" -#endif - -#include "private/qhexstring_p.h" - -#ifndef QT_NO_ICON -QT_BEGIN_NAMESPACE - -/*! - \enum QIcon::Mode - - This enum type describes the mode for which a pixmap is intended - to be used. The currently defined modes are: - - \value Normal - Display the pixmap when the user is - not interacting with the icon, but the - functionality represented by the icon is available. - \value Disabled - Display the pixmap when the - functionality represented by the icon is not available. - \value Active - Display the pixmap when the - functionality represented by the icon is available and - the user is interacting with the icon, for example, moving the - mouse over it or clicking it. - \value Selected - Display the pixmap when the item represented by the icon is - selected. -*/ - -/*! - \enum QIcon::State - - This enum describes the state for which a pixmap is intended to be - used. The \e state can be: - - \value Off Display the pixmap when the widget is in an "off" state - \value On Display the pixmap when the widget is in an "on" state -*/ - -static QBasicAtomicInt serialNumCounter = Q_BASIC_ATOMIC_INITIALIZER(1); - -static void qt_cleanup_icon_cache(); -typedef QCache IconCache; -Q_GLOBAL_STATIC_WITH_INITIALIZER(IconCache, qtIconCache, qAddPostRoutine(qt_cleanup_icon_cache)) - -static void qt_cleanup_icon_cache() -{ - qtIconCache()->clear(); -} - -QIconPrivate::QIconPrivate() - : engine(0), ref(1), - serialNum(serialNumCounter.fetchAndAddRelaxed(1)), - detach_no(0), - engine_version(2), - v1RefCount(0) -{ -} - -QPixmapIconEngine::QPixmapIconEngine() -{ -} - -QPixmapIconEngine::QPixmapIconEngine(const QPixmapIconEngine &other) - : QIconEngineV2(other), pixmaps(other.pixmaps) -{ -} - -QPixmapIconEngine::~QPixmapIconEngine() -{ -} - -void QPixmapIconEngine::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) -{ - QSize pixmapSize = rect.size(); -#if defined(Q_WS_MAC) - pixmapSize *= qt_mac_get_scalefactor(); -#endif - painter->drawPixmap(rect, pixmap(pixmapSize, mode, state)); -} - -static inline int area(const QSize &s) { return s.width() * s.height(); } - -// returns the smallest of the two that is still larger than or equal to size. -static QPixmapIconEngineEntry *bestSizeMatch( const QSize &size, QPixmapIconEngineEntry *pa, QPixmapIconEngineEntry *pb) -{ - int s = area(size); - if (pa->size == QSize() && pa->pixmap.isNull()) { - pa->pixmap = QPixmap(pa->fileName); - pa->size = pa->pixmap.size(); - } - int a = area(pa->size); - if (pb->size == QSize() && pb->pixmap.isNull()) { - pb->pixmap = QPixmap(pb->fileName); - pb->size = pb->pixmap.size(); - } - int b = area(pb->size); - int res = a; - if (qMin(a,b) >= s) - res = qMin(a,b); - else - res = qMax(a,b); - if (res == a) - return pa; - return pb; -} - -QPixmapIconEngineEntry *QPixmapIconEngine::tryMatch(const QSize &size, QIcon::Mode mode, QIcon::State state) -{ - QPixmapIconEngineEntry *pe = 0; - for (int i = 0; i < pixmaps.count(); ++i) - if (pixmaps.at(i).mode == mode && pixmaps.at(i).state == state) { - if (pe) - pe = bestSizeMatch(size, &pixmaps[i], pe); - else - pe = &pixmaps[i]; - } - return pe; -} - - -QPixmapIconEngineEntry *QPixmapIconEngine::bestMatch(const QSize &size, QIcon::Mode mode, QIcon::State state, bool sizeOnly) -{ - QPixmapIconEngineEntry *pe = tryMatch(size, mode, state); - while (!pe){ - QIcon::State oppositeState = (state == QIcon::On) ? QIcon::Off : QIcon::On; - if (mode == QIcon::Disabled || mode == QIcon::Selected) { - QIcon::Mode oppositeMode = (mode == QIcon::Disabled) ? QIcon::Selected : QIcon::Disabled; - if ((pe = tryMatch(size, QIcon::Normal, state))) - break; - if ((pe = tryMatch(size, QIcon::Active, state))) - break; - if ((pe = tryMatch(size, mode, oppositeState))) - break; - if ((pe = tryMatch(size, QIcon::Normal, oppositeState))) - break; - if ((pe = tryMatch(size, QIcon::Active, oppositeState))) - break; - if ((pe = tryMatch(size, oppositeMode, state))) - break; - if ((pe = tryMatch(size, oppositeMode, oppositeState))) - break; - } else { - QIcon::Mode oppositeMode = (mode == QIcon::Normal) ? QIcon::Active : QIcon::Normal; - if ((pe = tryMatch(size, oppositeMode, state))) - break; - if ((pe = tryMatch(size, mode, oppositeState))) - break; - if ((pe = tryMatch(size, oppositeMode, oppositeState))) - break; - if ((pe = tryMatch(size, QIcon::Disabled, state))) - break; - if ((pe = tryMatch(size, QIcon::Selected, state))) - break; - if ((pe = tryMatch(size, QIcon::Disabled, oppositeState))) - break; - if ((pe = tryMatch(size, QIcon::Selected, oppositeState))) - break; - } - - if (!pe) - return pe; - } - - if (sizeOnly ? (pe->size.isNull() || !pe->size.isValid()) : pe->pixmap.isNull()) { - pe->pixmap = QPixmap(pe->fileName); - if (!pe->pixmap.isNull()) - pe->size = pe->pixmap.size(); - } - - return pe; -} - -QPixmap QPixmapIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) -{ - QPixmap pm; - QPixmapIconEngineEntry *pe = bestMatch(size, mode, state, false); - if (pe) - pm = pe->pixmap; - - if (pm.isNull()) { - int idx = pixmaps.count(); - while (--idx >= 0) { - if (pe == &pixmaps[idx]) { - pixmaps.remove(idx); - break; - } - } - if (pixmaps.isEmpty()) - return pm; - else - return pixmap(size, mode, state); - } - - QSize actualSize = pm.size(); - if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height())) - actualSize.scale(size, Qt::KeepAspectRatio); - - // #### Qt5 no idea what this really does, but we need to remove the QApp and style references -// QString key = QLatin1Literal("qt_") -// % HexString(pm.cacheKey()) -// % HexString(pe->mode) -// % HexString(QApplication::palette().cacheKey()) -// % HexString(actualSize.width()) -// % HexString(actualSize.height()); - -// if (mode == QIcon::Active) { -// if (QPixmapCache::find(key % HexString(mode), pm)) -// return pm; // horray -// if (QPixmapCache::find(key % HexString(QIcon::Normal), pm)) { -// QStyleOption opt(0); -// opt.palette = QApplication::palette(); -// QPixmap active = QApplication::style()->generatedIconPixmap(QIcon::Active, pm, &opt); -// if (pm.cacheKey() == active.cacheKey()) -// return pm; -// } -// } - -// if (!QPixmapCache::find(key % HexString(mode), pm)) { - if (pm.size() != actualSize) - pm = pm.scaled(actualSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); -// if (pe->mode != mode && mode != QIcon::Normal) { -// QStyleOption opt(0); -// opt.palette = QApplication::palette(); -// QPixmap generated = QApplication::style()->generatedIconPixmap(mode, pm, &opt); -// if (!generated.isNull()) -// pm = generated; -// } -// QPixmapCache::insert(key % HexString(mode), pm); -// } - return pm; -} - -QSize QPixmapIconEngine::actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state) -{ - QSize actualSize; - if (QPixmapIconEngineEntry *pe = bestMatch(size, mode, state, true)) - actualSize = pe->size; - - if (actualSize.isNull()) - return actualSize; - - if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height())) - actualSize.scale(size, Qt::KeepAspectRatio); - return actualSize; -} - -void QPixmapIconEngine::addPixmap(const QPixmap &pixmap, QIcon::Mode mode, QIcon::State state) -{ - if (!pixmap.isNull()) { - QPixmapIconEngineEntry *pe = tryMatch(pixmap.size(), mode, state); - if(pe && pe->size == pixmap.size()) { - pe->pixmap = pixmap; - pe->fileName.clear(); - } else { - pixmaps += QPixmapIconEngineEntry(pixmap, mode, state); - } - } -} - -void QPixmapIconEngine::addFile(const QString &fileName, const QSize &_size, QIcon::Mode mode, QIcon::State state) -{ - if (!fileName.isEmpty()) { - QSize size = _size; - QPixmap pixmap; - - QString abs = fileName; - if (fileName.at(0) != QLatin1Char(':')) - abs = QFileInfo(fileName).absoluteFilePath(); - - for (int i = 0; i < pixmaps.count(); ++i) { - if (pixmaps.at(i).mode == mode && pixmaps.at(i).state == state) { - QPixmapIconEngineEntry *pe = &pixmaps[i]; - if(size == QSize()) { - pixmap = QPixmap(abs); - size = pixmap.size(); - } - if (pe->size == QSize() && pe->pixmap.isNull()) { - pe->pixmap = QPixmap(pe->fileName); - pe->size = pe->pixmap.size(); - } - if(pe->size == size) { - pe->pixmap = pixmap; - pe->fileName = abs; - return; - } - } - } - QPixmapIconEngineEntry e(abs, size, mode, state); - e.pixmap = pixmap; - pixmaps += e; - } -} - -QString QPixmapIconEngine::key() const -{ - return QLatin1String("QPixmapIconEngine"); -} - -QIconEngineV2 *QPixmapIconEngine::clone() const -{ - return new QPixmapIconEngine(*this); -} - -bool QPixmapIconEngine::read(QDataStream &in) -{ - int num_entries; - QPixmap pm; - QString fileName; - QSize sz; - uint mode; - uint state; - - in >> num_entries; - for (int i=0; i < num_entries; ++i) { - if (in.atEnd()) { - pixmaps.clear(); - return false; - } - in >> pm; - in >> fileName; - in >> sz; - in >> mode; - in >> state; - if (pm.isNull()) { - addFile(fileName, sz, QIcon::Mode(mode), QIcon::State(state)); - } else { - QPixmapIconEngineEntry pe(fileName, sz, QIcon::Mode(mode), QIcon::State(state)); - pe.pixmap = pm; - pixmaps += pe; - } - } - return true; -} - -bool QPixmapIconEngine::write(QDataStream &out) const -{ - int num_entries = pixmaps.size(); - out << num_entries; - for (int i=0; i < num_entries; ++i) { - if (pixmaps.at(i).pixmap.isNull()) - out << QPixmap(pixmaps.at(i).fileName); - else - out << pixmaps.at(i).pixmap; - out << pixmaps.at(i).fileName; - out << pixmaps.at(i).size; - out << (uint) pixmaps.at(i).mode; - out << (uint) pixmaps.at(i).state; - } - return true; -} - -void QPixmapIconEngine::virtual_hook(int id, void *data) -{ - switch (id) { - case QIconEngineV2::AvailableSizesHook: { - QIconEngineV2::AvailableSizesArgument &arg = - *reinterpret_cast(data); - arg.sizes.clear(); - for (int i = 0; i < pixmaps.size(); ++i) { - QPixmapIconEngineEntry &pe = pixmaps[i]; - if (pe.size == QSize() && pe.pixmap.isNull()) { - pe.pixmap = QPixmap(pe.fileName); - pe.size = pe.pixmap.size(); - } - if (pe.mode == arg.mode && pe.state == arg.state && !pe.size.isEmpty()) - arg.sizes.push_back(pe.size); - } - break; - } - default: - QIconEngineV2::virtual_hook(id, data); - } -} - -#ifndef QT_NO_LIBRARY -Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, - (QIconEngineFactoryInterface_iid, QLatin1String("/iconengines"), Qt::CaseInsensitive)) -Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loaderV2, - (QIconEngineFactoryInterfaceV2_iid, QLatin1String("/iconengines"), Qt::CaseInsensitive)) -#endif - - - -/*! - \class QIcon - - \brief The QIcon class provides scalable icons in different modes - and states. - - \ingroup painting - \ingroup shared - - - A QIcon can generate smaller, larger, active, and disabled pixmaps - from the set of pixmaps it is given. Such pixmaps are used by Qt - widgets to show an icon representing a particular action. - - The simplest use of QIcon is to create one from a QPixmap file or - resource, and then use it, allowing Qt to work out all the required - icon styles and sizes. For example: - - \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 0 - - To undo a QIcon, simply set a null icon in its place: - - \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 1 - - Use the QImageReader::supportedImageFormats() and - QImageWriter::supportedImageFormats() functions to retrieve a - complete list of the supported file formats. - - When you retrieve a pixmap using pixmap(QSize, Mode, State), and no - pixmap for this given size, mode and state has been added with - addFile() or addPixmap(), then QIcon will generate one on the - fly. This pixmap generation happens in a QIconEngineV2. The default - engine scales pixmaps down if required, but never up, and it uses - the current style to calculate a disabled appearance. By using - custom icon engines, you can customize every aspect of generated - icons. With QIconEnginePluginV2 it is possible to register different - icon engines for different file suffixes, making it possible for - third parties to provide additional icon engines to those included - with Qt. - - \note Since Qt 4.2, an icon engine that supports SVG is included. - - \section1 Making Classes that Use QIcon - - If you write your own widgets that have an option to set a small - pixmap, consider allowing a QIcon to be set for that pixmap. The - Qt class QToolButton is an example of such a widget. - - Provide a method to set a QIcon, and when you draw the icon, choose - whichever pixmap is appropriate for the current state of your widget. - For example: - \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 2 - - You might also make use of the \c Active mode, perhaps making your - widget \c Active when the mouse is over the widget (see \l - QWidget::enterEvent()), while the mouse is pressed pending the - release that will activate the function, or when it is the currently - selected item. If the widget can be toggled, the "On" mode might be - used to draw a different icon. - - \img icon.png QIcon - - \sa {fowler}{GUI Design Handbook: Iconic Label}, {Icons Example} -*/ - - -/*! - Constructs a null icon. -*/ -QIcon::QIcon() - : d(0) -{ -} - -/*! - Constructs an icon from a \a pixmap. - */ -QIcon::QIcon(const QPixmap &pixmap) - :d(0) -{ - addPixmap(pixmap); -} - -/*! - Constructs a copy of \a other. This is very fast. -*/ -QIcon::QIcon(const QIcon &other) - :d(other.d) -{ - if (d) - d->ref.ref(); -} - -/*! - Constructs an icon from the file with the given \a fileName. The - file will be loaded on demand. - - If \a fileName contains a relative path (e.g. the filename only) - the relevant file must be found relative to the runtime working - directory. - - The file name can be either refer to an actual file on disk or to - one of the application's embedded resources. See the - \l{resources.html}{Resource System} overview for details on how to - embed images and other resource files in the application's - executable. - - Use the QImageReader::supportedImageFormats() and - QImageWriter::supportedImageFormats() functions to retrieve a - complete list of the supported file formats. -*/ -QIcon::QIcon(const QString &fileName) - : d(0) -{ - addFile(fileName); -} - - -/*! - Creates an icon with a specific icon \a engine. The icon takes - ownership of the engine. -*/ -QIcon::QIcon(QIconEngine *engine) - :d(new QIconPrivate) -{ - d->engine_version = 1; - d->engine = engine; - d->v1RefCount = new QAtomicInt(1); -} - -/*! - Creates an icon with a specific icon \a engine. The icon takes - ownership of the engine. -*/ -QIcon::QIcon(QIconEngineV2 *engine) - :d(new QIconPrivate) -{ - d->engine_version = 2; - d->engine = engine; -} - -/*! - Destroys the icon. -*/ -QIcon::~QIcon() -{ - if (d && !d->ref.deref()) - delete d; -} - -/*! - Assigns the \a other icon to this icon and returns a reference to - this icon. -*/ -QIcon &QIcon::operator=(const QIcon &other) -{ - if (other.d) - other.d->ref.ref(); - if (d && !d->ref.deref()) - delete d; - d = other.d; - return *this; -} - -/*! - \fn void QIcon::swap(QIcon &other) - \since 4.8 - - Swaps icon \a other with this icon. This operation is very - fast and never fails. -*/ - -/*! - Returns the icon as a QVariant. -*/ -QIcon::operator QVariant() const -{ - return QVariant(QVariant::Icon, this); -} - -/*! \obsolete - - Returns a number that identifies the contents of this - QIcon object. Distinct QIcon objects can have - the same serial number if they refer to the same contents - (but they don't have to). Also, the serial number of - a QIcon object may change during its lifetime. - - Use cacheKey() instead. - - A null icon always has a serial number of 0. - - Serial numbers are mostly useful in conjunction with caching. - - \sa QPixmap::serialNumber() -*/ - -int QIcon::serialNumber() const -{ - return d ? d->serialNum : 0; -} - -/*! - Returns a number that identifies the contents of this QIcon - object. Distinct QIcon objects can have the same key if - they refer to the same contents. - \since 4.3 - - The cacheKey() will change when the icon is altered via - addPixmap() or addFile(). - - Cache keys are mostly useful in conjunction with caching. - - \sa QPixmap::cacheKey() -*/ -qint64 QIcon::cacheKey() const -{ - if (!d) - return 0; - return (((qint64) d->serialNum) << 32) | ((qint64) (d->detach_no)); -} - -/*! - Returns a pixmap with the requested \a size, \a mode, and \a - state, generating one if necessary. The pixmap might be smaller than - requested, but never larger. - - \sa actualSize(), paint() -*/ -QPixmap QIcon::pixmap(const QSize &size, Mode mode, State state) const -{ - if (!d) - return QPixmap(); - return d->engine->pixmap(size, mode, state); -} - -/*! - \fn QPixmap QIcon::pixmap(int w, int h, Mode mode = Normal, State state = Off) const - - \overload - - Returns a pixmap of size QSize(\a w, \a h). The pixmap might be smaller than - requested, but never larger. -*/ - -/*! - \fn QPixmap QIcon::pixmap(int extent, Mode mode = Normal, State state = Off) const - - \overload - - Returns a pixmap of size QSize(\a extent, \a extent). The pixmap might be smaller - than requested, but never larger. -*/ - -/*! Returns the actual size of the icon for the requested \a size, \a - mode, and \a state. The result might be smaller than requested, but - never larger. - - \sa pixmap(), paint() -*/ -QSize QIcon::actualSize(const QSize &size, Mode mode, State state) const -{ - if (!d) - return QSize(); - return d->engine->actualSize(size, mode, state); -} - - -/*! - Uses the \a painter to paint the icon with specified \a alignment, - required \a mode, and \a state into the rectangle \a rect. - - \sa actualSize(), pixmap() -*/ -void QIcon::paint(QPainter *painter, const QRect &rect, Qt::Alignment alignment, Mode mode, State state) const -{ - if (!d || !painter) - return; - QRect alignedRect = QStyle::alignedRect(painter->layoutDirection(), alignment, d->engine->actualSize(rect.size(), mode, state), rect); - d->engine->paint(painter, alignedRect, mode, state); -} - -/*! - \fn void QIcon::paint(QPainter *painter, int x, int y, int w, int h, Qt::Alignment alignment, - Mode mode, State state) const - - \overload - - Paints the icon into the rectangle QRect(\a x, \a y, \a w, \a h). -*/ - -/*! - Returns true if the icon is empty; otherwise returns false. - - An icon is empty if it has neither a pixmap nor a filename. - - Note: Even a non-null icon might not be able to create valid - pixmaps, eg. if the file does not exist or cannot be read. -*/ -bool QIcon::isNull() const -{ - return !d; -} - -/*!\internal - */ -bool QIcon::isDetached() const -{ - return !d || d->ref == 1; -} - -/*! \internal - */ -void QIcon::detach() -{ - if (d) { - if (d->ref != 1) { - QIconPrivate *x = new QIconPrivate; - if (d->engine_version > 1) { - QIconEngineV2 *engine = static_cast(d->engine); - x->engine = engine->clone(); - } else { - x->engine = d->engine; - x->v1RefCount = d->v1RefCount; - x->v1RefCount->ref(); - } - x->engine_version = d->engine_version; - if (!d->ref.deref()) - delete d; - d = x; - } - ++d->detach_no; - } -} - -/*! - Adds \a pixmap to the icon, as a specialization for \a mode and - \a state. - - Custom icon engines are free to ignore additionally added - pixmaps. - - \sa addFile() -*/ -void QIcon::addPixmap(const QPixmap &pixmap, Mode mode, State state) -{ - if (pixmap.isNull()) - return; - if (!d) { - d = new QIconPrivate; - d->engine = new QPixmapIconEngine; - } else { - detach(); - } - d->engine->addPixmap(pixmap, mode, state); -} - - -/*! Adds an image from the file with the given \a fileName to the - icon, as a specialization for \a size, \a mode and \a state. The - file will be loaded on demand. Note: custom icon engines are free - to ignore additionally added pixmaps. - - If \a fileName contains a relative path (e.g. the filename only) - the relevant file must be found relative to the runtime working - directory. - - The file name can be either refer to an actual file on disk or to - one of the application's embedded resources. See the - \l{resources.html}{Resource System} overview for details on how to - embed images and other resource files in the application's - executable. - - Use the QImageReader::supportedImageFormats() and - QImageWriter::supportedImageFormats() functions to retrieve a - complete list of the supported file formats. - - Note: When you add a non-empty filename to a QIcon, the icon becomes - non-null, even if the file doesn't exist or points to a corrupt file. - - \sa addPixmap() - */ -void QIcon::addFile(const QString &fileName, const QSize &size, Mode mode, State state) -{ - if (fileName.isEmpty()) - return; - if (!d) { -#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) - QFileInfo info(fileName); - QString suffix = info.suffix(); - if (!suffix.isEmpty()) { - // first try version 2 engines.. - if (QIconEngineFactoryInterfaceV2 *factory = qobject_cast(loaderV2()->instance(suffix))) { - if (QIconEngine *engine = factory->create(fileName)) { - d = new QIconPrivate; - d->engine = engine; - } - } - // ..then fall back and try to load version 1 engines - if (!d) { - if (QIconEngineFactoryInterface *factory = qobject_cast(loader()->instance(suffix))) { - if (QIconEngine *engine = factory->create(fileName)) { - d = new QIconPrivate; - d->engine = engine; - d->engine_version = 1; - d->v1RefCount = new QAtomicInt(1); - } - } - } - } -#endif - // ...then fall back to the default engine - if (!d) { - d = new QIconPrivate; - d->engine = new QPixmapIconEngine; - } - } else { - detach(); - } - d->engine->addFile(fileName, size, mode, state); -} - -/*! - \since 4.5 - - Returns a list of available icon sizes for the specified \a mode and - \a state. -*/ -QList QIcon::availableSizes(Mode mode, State state) const -{ - if (!d || !d->engine || d->engine_version < 2) - return QList(); - QIconEngineV2 *engine = static_cast(d->engine); - return engine->availableSizes(mode, state); -} - -/*! - \since 4.7 - - Returns the name used to create the icon, if available. - - Depending on the way the icon was created, it may have an associated - name. This is the case for icons created with fromTheme() or icons - using a QIconEngine which supports the QIconEngineV2::IconNameHook. - - \sa fromTheme(), QIconEngine -*/ -QString QIcon::name() const -{ - if (!d || !d->engine || d->engine_version < 2) - return QString(); - QIconEngineV2 *engine = static_cast(d->engine); - return engine->iconName(); -} - -/*! - \since 4.6 - - Sets the search paths for icon themes to \a paths. - \sa themeSearchPaths(), fromTheme(), setThemeName() -*/ -void QIcon::setThemeSearchPaths(const QStringList &paths) -{ - QIconLoader::instance()->setThemeSearchPath(paths); -} - -/*! - \since 4.6 - - Returns the search paths for icon themes. - - The default value will depend on the platform: - - On X11, the search path will use the XDG_DATA_DIRS environment - variable if available. - - By default all platforms will have the resource directory - \c{:\icons} as a fallback. You can use "rcc -project" to generate a - resource file from your icon theme. - - \sa setThemeSearchPaths(), fromTheme(), setThemeName() -*/ -QStringList QIcon::themeSearchPaths() -{ - return QIconLoader::instance()->themeSearchPaths(); -} - -/*! - \since 4.6 - - Sets the current icon theme to \a name. - - The \a name should correspond to a directory name in the - themeSearchPath() containing an index.theme - file describing it's contents. - - \sa themeSearchPaths(), themeName() -*/ -void QIcon::setThemeName(const QString &name) -{ - QIconLoader::instance()->setThemeName(name); -} - -/*! - \since 4.6 - - Returns the name of the current icon theme. - - On X11, the current icon theme depends on your desktop - settings. On other platforms it is not set by default. - - \sa setThemeName(), themeSearchPaths(), fromTheme(), - hasThemeIcon() -*/ -QString QIcon::themeName() -{ - return QIconLoader::instance()->themeName(); -} - -/*! - \since 4.6 - - Returns the QIcon corresponding to \a name in the current - icon theme. If no such icon is found in the current theme - \a fallback is returned instead. - - The latest version of the freedesktop icon specification and naming - specification can be obtained here: - - \list - \o \l{http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html} - \o \l{http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html} - \endlist - - To fetch an icon from the current icon theme: - - \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 3 - - Or if you want to provide a guaranteed fallback for platforms that - do not support theme icons, you can use the second argument: - - \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 4 - - \note By default, only X11 will support themed icons. In order to - use themed icons on Mac and Windows, you will have to bundle a - compliant theme in one of your themeSearchPaths() and set the - appropriate themeName(). - - \sa themeName(), setThemeName(), themeSearchPaths() -*/ -QIcon QIcon::fromTheme(const QString &name, const QIcon &fallback) -{ - QIcon icon; - - if (qtIconCache()->contains(name)) { - icon = *qtIconCache()->object(name); - } else { - QIcon *cachedIcon = new QIcon(new QIconLoaderEngine(name)); - qtIconCache()->insert(name, cachedIcon); - icon = *cachedIcon; - } - - // Note the qapp check is to allow lazy loading of static icons - // Supporting fallbacks will not work for this case. - if (qApp && icon.availableSizes().isEmpty()) - return fallback; - - return icon; -} - -/*! - \since 4.6 - - Returns true if there is an icon available for \a name in the - current icon theme, otherwise returns false. - - \sa themeSearchPaths(), fromTheme(), setThemeName() -*/ -bool QIcon::hasThemeIcon(const QString &name) -{ - QIcon icon = fromTheme(name); - - return !icon.isNull(); -} - - -/***************************************************************************** - QIcon stream functions - *****************************************************************************/ -#if !defined(QT_NO_DATASTREAM) -/*! - \fn QDataStream &operator<<(QDataStream &stream, const QIcon &icon) - \relates QIcon - \since 4.2 - - Writes the given \a icon to the given \a stream as a PNG - image. If the icon contains more than one image, all images will - be written to the stream. Note that writing the stream to a file - will not produce a valid image file. -*/ - -QDataStream &operator<<(QDataStream &s, const QIcon &icon) -{ - if (s.version() >= QDataStream::Qt_4_3) { - if (icon.isNull()) { - s << QString(); - } else { - if (icon.d->engine_version > 1) { - QIconEngineV2 *engine = static_cast(icon.d->engine); - s << engine->key(); - engine->write(s); - } else { - // not really supported - qWarning("QIcon: Cannot stream QIconEngine. Use QIconEngineV2 instead."); - } - } - } else if (s.version() == QDataStream::Qt_4_2) { - if (icon.isNull()) { - s << 0; - } else { - QPixmapIconEngine *engine = static_cast(icon.d->engine); - int num_entries = engine->pixmaps.size(); - s << num_entries; - for (int i=0; i < num_entries; ++i) { - s << engine->pixmaps.at(i).pixmap; - s << engine->pixmaps.at(i).fileName; - s << engine->pixmaps.at(i).size; - s << (uint) engine->pixmaps.at(i).mode; - s << (uint) engine->pixmaps.at(i).state; - } - } - } else { - s << QPixmap(icon.pixmap(22,22)); - } - return s; -} - -/*! - \fn QDataStream &operator>>(QDataStream &stream, QIcon &icon) - \relates QIcon - \since 4.2 - - Reads an image, or a set of images, from the given \a stream into - the given \a icon. -*/ - -QDataStream &operator>>(QDataStream &s, QIcon &icon) -{ - if (s.version() >= QDataStream::Qt_4_3) { - icon = QIcon(); - QString key; - s >> key; - if (key == QLatin1String("QPixmapIconEngine")) { - icon.d = new QIconPrivate; - QIconEngineV2 *engine = new QPixmapIconEngine; - icon.d->engine = engine; - engine->read(s); - } else if (key == QLatin1String("QIconLoaderEngine")) { - icon.d = new QIconPrivate; - QIconEngineV2 *engine = new QIconLoaderEngine(); - icon.d->engine = engine; - engine->read(s); -#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) - } else if (QIconEngineFactoryInterfaceV2 *factory = qobject_cast(loaderV2()->instance(key))) { - if (QIconEngineV2 *engine= factory->create()) { - icon.d = new QIconPrivate; - icon.d->engine = engine; - engine->read(s); - } -#endif - } - } else if (s.version() == QDataStream::Qt_4_2) { - icon = QIcon(); - int num_entries; - QPixmap pm; - QString fileName; - QSize sz; - uint mode; - uint state; - - s >> num_entries; - for (int i=0; i < num_entries; ++i) { - s >> pm; - s >> fileName; - s >> sz; - s >> mode; - s >> state; - if (pm.isNull()) - icon.addFile(fileName, sz, QIcon::Mode(mode), QIcon::State(state)); - else - icon.addPixmap(pm, QIcon::Mode(mode), QIcon::State(state)); - } - } else { - QPixmap pm; - s >> pm; - icon.addPixmap(pm); - } - return s; -} - -#endif //QT_NO_DATASTREAM - -/*! - \fn DataPtr &QIcon::data_ptr() - \internal -*/ - -/*! - \typedef QIcon::DataPtr - \internal -*/ - -QT_END_NAMESPACE -#endif //QT_NO_ICON diff --git a/src/gui/image/qicon.h b/src/gui/image/qicon.h deleted file mode 100644 index 4e3960925e..0000000000 --- a/src/gui/image/qicon.h +++ /dev/null @@ -1,143 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QICON_H -#define QICON_H - -#include -#include -#include -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Gui) - -class QIconPrivate; -class QIconEngine; -class QIconEngineV2; - -class Q_GUI_EXPORT QIcon -{ -public: - enum Mode { Normal, Disabled, Active, Selected }; - enum State { On, Off }; - - QIcon(); - QIcon(const QPixmap &pixmap); - QIcon(const QIcon &other); - explicit QIcon(const QString &fileName); // file or resource name - explicit QIcon(QIconEngine *engine); - explicit QIcon(QIconEngineV2 *engine); - ~QIcon(); - QIcon &operator=(const QIcon &other); -#ifdef Q_COMPILER_RVALUE_REFS - inline QIcon &operator=(QIcon &&other) - { qSwap(d, other.d); return *this; } -#endif - inline void swap(QIcon &other) { qSwap(d, other.d); } - - operator QVariant() const; - - QPixmap pixmap(const QSize &size, Mode mode = Normal, State state = Off) const; - inline QPixmap pixmap(int w, int h, Mode mode = Normal, State state = Off) const - { return pixmap(QSize(w, h), mode, state); } - inline QPixmap pixmap(int extent, Mode mode = Normal, State state = Off) const - { return pixmap(QSize(extent, extent), mode, state); } - - QSize actualSize(const QSize &size, Mode mode = Normal, State state = Off) const; - - QString name() const; - - void paint(QPainter *painter, const QRect &rect, Qt::Alignment alignment = Qt::AlignCenter, Mode mode = Normal, State state = Off) const; - inline void paint(QPainter *painter, int x, int y, int w, int h, Qt::Alignment alignment = Qt::AlignCenter, Mode mode = Normal, State state = Off) const - { paint(painter, QRect(x, y, w, h), alignment, mode, state); } - - bool isNull() const; - bool isDetached() const; - void detach(); - - int serialNumber() const; - qint64 cacheKey() const; - - void addPixmap(const QPixmap &pixmap, Mode mode = Normal, State state = Off); - void addFile(const QString &fileName, const QSize &size = QSize(), Mode mode = Normal, State state = Off); - - QList availableSizes(Mode mode = Normal, State state = Off) const; - - static QIcon fromTheme(const QString &name, const QIcon &fallback = QIcon()); - static bool hasThemeIcon(const QString &name); - - static QStringList themeSearchPaths(); - static void setThemeSearchPaths(const QStringList &searchpath); - - static QString themeName(); - static void setThemeName(const QString &path); - - Q_DUMMY_COMPARISON_OPERATOR(QIcon) - -private: - QIconPrivate *d; -#if !defined(QT_NO_DATASTREAM) - friend Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QIcon &); - friend Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QIcon &); -#endif - -public: - typedef QIconPrivate * DataPtr; - inline DataPtr &data_ptr() { return d; } -}; - -Q_DECLARE_SHARED(QIcon) -Q_DECLARE_TYPEINFO(QIcon, Q_MOVABLE_TYPE); - -#if !defined(QT_NO_DATASTREAM) -Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QIcon &); -Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QIcon &); -#endif - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QICON_H diff --git a/src/gui/image/qicon_p.h b/src/gui/image/qicon_p.h deleted file mode 100644 index 0bf7e65cc1..0000000000 --- a/src/gui/image/qicon_p.h +++ /dev/null @@ -1,139 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QICON_P_H -#define QICON_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include - -#ifndef QT_NO_ICON -QT_BEGIN_NAMESPACE - -class QIconPrivate -{ -public: - QIconPrivate(); - - ~QIconPrivate() { - if (engine_version == 1) { - if (!v1RefCount->deref()) { - delete engine; - delete v1RefCount; - } - } else if (engine_version == 2) { - delete engine; - } - } - - QIconEngine *engine; - - QAtomicInt ref; - int serialNum; - int detach_no; - int engine_version; - - QAtomicInt *v1RefCount; -}; - - -struct QPixmapIconEngineEntry -{ - QPixmapIconEngineEntry():mode(QIcon::Normal), state(QIcon::Off){} - QPixmapIconEngineEntry(const QPixmap &pm, QIcon::Mode m = QIcon::Normal, QIcon::State s = QIcon::Off) - :pixmap(pm), size(pm.size()), mode(m), state(s){} - QPixmapIconEngineEntry(const QString &file, const QSize &sz = QSize(), QIcon::Mode m = QIcon::Normal, QIcon::State s = QIcon::Off) - :fileName(file), size(sz), mode(m), state(s){} - QPixmap pixmap; - QString fileName; - QSize size; - QIcon::Mode mode; - QIcon::State state; - bool isNull() const {return (fileName.isEmpty() && pixmap.isNull()); } -}; - - - -class QPixmapIconEngine : public QIconEngineV2 { -public: - QPixmapIconEngine(); - QPixmapIconEngine(const QPixmapIconEngine &); - ~QPixmapIconEngine(); - void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state); - QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state); - QPixmapIconEngineEntry *bestMatch(const QSize &size, QIcon::Mode mode, QIcon::State state, bool sizeOnly); - QSize actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state); - void addPixmap(const QPixmap &pixmap, QIcon::Mode mode, QIcon::State state); - void addFile(const QString &fileName, const QSize &size, QIcon::Mode mode, QIcon::State state); - - // v2 functions - QString key() const; - QIconEngineV2 *clone() const; - bool read(QDataStream &in); - bool write(QDataStream &out) const; - void virtual_hook(int id, void *data); - -private: - QPixmapIconEngineEntry *tryMatch(const QSize &size, QIcon::Mode mode, QIcon::State state); - QVector pixmaps; - - friend QDataStream &operator<<(QDataStream &s, const QIcon &icon); - friend class QIconThemeEngine; -}; - -QT_END_NAMESPACE -#endif //QT_NO_ICON -#endif // QICON_P_H diff --git a/src/gui/image/qiconengine.cpp b/src/gui/image/qiconengine.cpp deleted file mode 100644 index 6168a83940..0000000000 --- a/src/gui/image/qiconengine.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qiconengine.h" -#include "qpainter.h" - -QT_BEGIN_NAMESPACE - -/*! - \class QIconEngine - - \brief The QIconEngine class provides an abstract base class for QIcon renderers. - - \ingroup painting - - \bold {Use QIconEngineV2 instead.} - - An icon engine provides the rendering functions for a QIcon. Each icon has a - corresponding icon engine that is responsible for drawing the icon with a - requested size, mode and state. - - The icon is rendered by the paint() function, and the icon can additionally be - obtained as a pixmap with the pixmap() function (the default implementation - simply uses paint() to achieve this). The addPixmap() function can be used to - add new pixmaps to the icon engine, and is used by QIcon to add specialized - custom pixmaps. - - The paint(), pixmap(), and addPixmap() functions are all virtual, and can - therefore be reimplemented in subclasses of QIconEngine. - - \sa QIconEngineV2, QIconEnginePlugin - -*/ - -/*! - \fn virtual void QIconEngine::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) = 0; - - Uses the given \a painter to paint the icon with the required \a mode and - \a state into the rectangle \a rect. -*/ - -/*! Returns the actual size of the icon the engine provides for the - requested \a size, \a mode and \a state. The default implementation - returns the given \a size. - */ -QSize QIconEngine::actualSize(const QSize &size, QIcon::Mode /*mode*/, QIcon::State /*state*/) -{ - return size; -} - - -/*! - Destroys the icon engine. - */ -QIconEngine::~QIconEngine() -{ -} - - -/*! - Returns the icon as a pixmap with the required \a size, \a mode, - and \a state. The default implementation creates a new pixmap and - calls paint() to fill it. -*/ -QPixmap QIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) -{ - QPixmap pm(size); - { - QPainter p(&pm); - paint(&p, QRect(QPoint(0,0),size), mode, state); - } - return pm; -} - -/*! - Called by QIcon::addPixmap(). Adds a specialized \a pixmap for the given - \a mode and \a state. The default pixmap-based engine stores any supplied - pixmaps, and it uses them instead of scaled pixmaps if the size of a pixmap - matches the size of icon requested. Custom icon engines that implement - scalable vector formats are free to ignores any extra pixmaps. - */ -void QIconEngine::addPixmap(const QPixmap &/*pixmap*/, QIcon::Mode /*mode*/, QIcon::State /*state*/) -{ -} - - -/*! Called by QIcon::addFile(). Adds a specialized pixmap from the - file with the given \a fileName, \a size, \a mode and \a state. The - default pixmap-based engine stores any supplied file names, and it - loads the pixmaps on demand instead of using scaled pixmaps if the - size of a pixmap matches the size of icon requested. Custom icon - engines that implement scalable vector formats are free to ignores - any extra files. - */ -void QIconEngine::addFile(const QString &/*fileName*/, const QSize &/*size*/, QIcon::Mode /*mode*/, QIcon::State /*state*/) -{ -} - - - -// version 2 functions - - -/*! - \class QIconEngineV2 - - \brief The QIconEngineV2 class provides an abstract base class for QIcon renderers. - - \ingroup painting - \since 4.3 - - An icon engine renders \l{QIcon}s. With icon engines, you can - customize icons. Qt provides a default engine that makes icons - adhere to the current style by scaling the icons and providing a - disabled appearance. - - An engine is installed on an icon either through a QIcon - constructor or through a QIconEnginePluginV2. The plugins are used - by Qt if a specific engine is not given when the icon is created. - See the QIconEngineV2 class description to learn how to create - icon engine plugins. - - An icon engine provides the rendering functions for a QIcon. Each - icon has a corresponding icon engine that is responsible for drawing - the icon with a requested size, mode and state. - - QIconEngineV2 extends the API of QIconEngine to allow streaming of - the icon engine contents, and should be used instead of QIconEngine - for implementing new icon engines. - - \sa QIconEnginePluginV2 - -*/ - -/*! - \enum QIconEngineV2::IconEngineHook - \since 4.5 - - These enum values are used for virtual_hook() to allow additional - queries to icon engine without breaking binary compatibility. - - \value AvailableSizesHook Allows to query the sizes of the - contained pixmaps for pixmap-based engines. The \a data argument - of the virtual_hook() function is a AvailableSizesArgument pointer - that should be filled with icon sizes. Engines that work in terms - of a scalable, vectorial format normally return an empty list. - - \value IconNameHook Allows to query the name used to create the - icon, for example when instantiating an icon using - QIcon::fromTheme(). - - \sa virtual_hook() - */ - -/*! - \class QIconEngineV2::AvailableSizesArgument - \since 4.5 - - This struct represents arguments to virtual_hook() function when - \a id parameter is QIconEngineV2::AvailableSizesHook. - - \sa virtual_hook(), QIconEngineV2::IconEngineHook - */ - -/*! - \variable QIconEngineV2::AvailableSizesArgument::mode - \brief the requested mode of an image. - - \sa QIcon::Mode -*/ - -/*! - \variable QIconEngineV2::AvailableSizesArgument::state - \brief the requested state of an image. - - \sa QIcon::State -*/ - -/*! - \variable QIconEngineV2::AvailableSizesArgument::sizes - - \brief image sizes that are available with specified \a mode and - \a state. This is an output parameter and is filled after call to - virtual_hook(). Engines that work in terms of a scalable, - vectorial format normally return an empty list. -*/ - - -/*! - Returns a key that identifies this icon engine. - */ -QString QIconEngineV2::key() const -{ - return QString(); -} - -/*! - Returns a clone of this icon engine. - */ -QIconEngineV2 *QIconEngineV2::clone() const -{ - return 0; -} - -/*! - Reads icon engine contents from the QDataStream \a in. Returns - true if the contents were read; otherwise returns false. - - QIconEngineV2's default implementation always return false. - */ -bool QIconEngineV2::read(QDataStream &) -{ - return false; -} - -/*! - Writes the contents of this engine to the QDataStream \a out. - Returns true if the contents were written; otherwise returns false. - - QIconEngineV2's default implementation always return false. - */ -bool QIconEngineV2::write(QDataStream &) const -{ - return false; -} - -/*! - \since 4.5 - - Additional method to allow extending QIconEngineV2 without - adding new virtual methods (and without breaking binary compatibility). - The actual action and format of \a data depends on \a id argument - which is in fact a constant from IconEngineHook enum. - - \sa IconEngineHook -*/ -void QIconEngineV2::virtual_hook(int id, void *data) -{ - switch (id) { - case QIconEngineV2::AvailableSizesHook: { - QIconEngineV2::AvailableSizesArgument &arg = - *reinterpret_cast(data); - arg.sizes.clear(); - break; - } - default: - break; - } -} - -/*! - \since 4.5 - - Returns sizes of all images that are contained in the engine for the - specific \a mode and \a state. - - \note This is a helper method and the actual work is done by - virtual_hook() method, hence this method depends on icon engine support - and may not work with all icon engines. - */ -QList QIconEngineV2::availableSizes(QIcon::Mode mode, QIcon::State state) -{ - AvailableSizesArgument arg; - arg.mode = mode; - arg.state = state; - virtual_hook(QIconEngineV2::AvailableSizesHook, reinterpret_cast(&arg)); - return arg.sizes; -} - -/*! - \since 4.7 - - Returns the name used to create the engine, if available. - - \note This is a helper method and the actual work is done by - virtual_hook() method, hence this method depends on icon engine support - and may not work with all icon engines. - */ -QString QIconEngineV2::iconName() -{ - QString name; - virtual_hook(QIconEngineV2::IconNameHook, reinterpret_cast(&name)); - return name; -} - -QT_END_NAMESPACE diff --git a/src/gui/image/qiconengine.h b/src/gui/image/qiconengine.h deleted file mode 100644 index 12caea8a20..0000000000 --- a/src/gui/image/qiconengine.h +++ /dev/null @@ -1,104 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QICONENGINE_H -#define QICONENGINE_H - -#include -#include -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Gui) - -class Q_GUI_EXPORT QIconEngine -{ -public: - virtual ~QIconEngine(); - virtual void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) = 0; - virtual QSize actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state); - virtual QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state); - - virtual void addPixmap(const QPixmap &pixmap, QIcon::Mode mode, QIcon::State state); - virtual void addFile(const QString &fileName, const QSize &size, QIcon::Mode mode, QIcon::State state); - -#if 0 - virtual int frameCount(QIcon::Mode fromMode, QIcon::State fromState, QIcon::Mode toMode, QIcon::State toState); - virtual void paintFrame(QPainter *painter, const QRect &rect, int frameNumber, QIcon::Mode fromMode, QIcon::State fromState, QIcon::Mode toMode, QIcon::State toState); -#endif -}; - -// ### Qt 5: move the below into QIconEngine -class Q_GUI_EXPORT QIconEngineV2 : public QIconEngine -{ -public: - virtual QString key() const; - virtual QIconEngineV2 *clone() const; - virtual bool read(QDataStream &in); - virtual bool write(QDataStream &out) const; - virtual void virtual_hook(int id, void *data); - -public: - enum IconEngineHook { AvailableSizesHook = 1, IconNameHook }; - - struct AvailableSizesArgument - { - QIcon::Mode mode; - QIcon::State state; - QList sizes; - }; - - // ### Qt 5: make this function const and virtual. - QList availableSizes(QIcon::Mode mode = QIcon::Normal, - QIcon::State state = QIcon::Off); - - // ### Qt 5: make this function const and virtual. - QString iconName(); -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QICONENGINE_H diff --git a/src/gui/image/qiconengineplugin.cpp b/src/gui/image/qiconengineplugin.cpp deleted file mode 100644 index 7c8c3a3c1a..0000000000 --- a/src/gui/image/qiconengineplugin.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qiconengineplugin.h" -#include "qiconengine.h" - -QT_BEGIN_NAMESPACE - -/*! - \class QIconEnginePlugin - \brief The QIconEnginePlugin class provides an abstract base for custom QIconEngine plugins. - - \ingroup plugins - - \bold {Use QIconEnginePluginV2 instead.} - - The icon engine plugin is a simple plugin interface that makes it easy to - create custom icon engines that can be loaded dynamically into applications - through QIcon. QIcon uses the file or resource name's suffix to determine - what icon engine to use. - - Writing a icon engine plugin is achieved by subclassing this base class, - reimplementing the pure virtual functions keys() and create(), and - exporting the class with the Q_EXPORT_PLUGIN2() macro. - - \sa {How to Create Qt Plugins} -*/ - -/*! - \fn QStringList QIconEnginePlugin::keys() const - - Returns a list of icon engine keys that this plugin supports. The keys correspond - to the suffix of the file or resource name used when the plugin was created. - Keys are case insensitive. - - \sa create() -*/ - -/*! - \fn QIconEngine* QIconEnginePlugin::create(const QString& filename) - - Creates and returns a QIconEngine object for the icon with the given - \a filename. - - \sa keys() -*/ - -/*! - Constructs a icon engine plugin with the given \a parent. This is invoked - automatically by the Q_EXPORT_PLUGIN2() macro. -*/ -QIconEnginePlugin::QIconEnginePlugin(QObject *parent) - : QObject(parent) -{ -} - -/*! - Destroys the icon engine plugin. - - You never have to call this explicitly. Qt destroys a plugin - automatically when it is no longer used. -*/ -QIconEnginePlugin::~QIconEnginePlugin() -{ -} - -// version 2 - -/*! - \class QIconEnginePluginV2 - \brief The QIconEnginePluginV2 class provides an abstract base for custom QIconEngineV2 plugins. - - \ingroup plugins - \since 4.3 - - Icon engine plugins produces \l{QIconEngine}s for \l{QIcon}s; an - icon engine is used to render the icon. The keys that identifies - the engines the plugin can create are suffixes of - icon filenames; they are returned by keys(). The create() function - receives the icon filename to return an engine for; it should - return 0 if it cannot produce an engine for the file. - - Writing an icon engine plugin is achieved by inheriting - QIconEnginePluginV2, reimplementing keys() and create(), and - adding the Q_EXPORT_PLUGIN2() macro. - - You should ensure that you do not duplicate keys. Qt will query - the plugins for icon engines in the order in which the plugins are - found during plugin search (see the plugins \l{How to Create Qt - Plugins}{overview document}). - - \sa {How to Create Qt Plugins} -*/ - -/*! - \fn QStringList QIconEnginePluginV2::keys() const - - Returns a list of icon engine keys that this plugin supports. The keys correspond - to the suffix of the file or resource name used when the plugin was created. - Keys are case insensitive. - - \sa create() -*/ - -/*! - \fn QIconEngineV2* QIconEnginePluginV2::create(const QString& filename = QString()) - - Creates and returns a QIconEngine object for the icon with the given - \a filename. - - \sa keys() -*/ - -/*! - Constructs a icon engine plugin with the given \a parent. This is invoked - automatically by the Q_EXPORT_PLUGIN2() macro. -*/ -QIconEnginePluginV2::QIconEnginePluginV2(QObject *parent) - : QObject(parent) -{ -} - -/*! - Destroys the icon engine plugin. - - You never have to call this explicitly. Qt destroys a plugin - automatically when it is no longer used. -*/ -QIconEnginePluginV2::~QIconEnginePluginV2() -{ -} - -QT_END_NAMESPACE diff --git a/src/gui/image/qiconengineplugin.h b/src/gui/image/qiconengineplugin.h deleted file mode 100644 index e892a38f7b..0000000000 --- a/src/gui/image/qiconengineplugin.h +++ /dev/null @@ -1,104 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QICONENGINEPLUGIN_H -#define QICONENGINEPLUGIN_H - -#include -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Gui) - -class QIconEngine; -class QIconEngineV2; - -struct Q_GUI_EXPORT QIconEngineFactoryInterface : public QFactoryInterface -{ - virtual QIconEngine *create(const QString &filename) = 0; -}; - -#define QIconEngineFactoryInterface_iid \ - "com.trolltech.Qt.QIconEngineFactoryInterface" -Q_DECLARE_INTERFACE(QIconEngineFactoryInterface, QIconEngineFactoryInterface_iid) - -class Q_GUI_EXPORT QIconEnginePlugin : public QObject, public QIconEngineFactoryInterface -{ - Q_OBJECT - Q_INTERFACES(QIconEngineFactoryInterface:QFactoryInterface) -public: - QIconEnginePlugin(QObject *parent = 0); - ~QIconEnginePlugin(); - - virtual QStringList keys() const = 0; - virtual QIconEngine *create(const QString &filename) = 0; -}; - -// ### Qt 5: remove version 2 -struct Q_GUI_EXPORT QIconEngineFactoryInterfaceV2 : public QFactoryInterface -{ - virtual QIconEngineV2 *create(const QString &filename = QString()) = 0; -}; - -#define QIconEngineFactoryInterfaceV2_iid \ - "com.trolltech.Qt.QIconEngineFactoryInterfaceV2" -Q_DECLARE_INTERFACE(QIconEngineFactoryInterfaceV2, QIconEngineFactoryInterfaceV2_iid) - -class Q_GUI_EXPORT QIconEnginePluginV2 : public QObject, public QIconEngineFactoryInterfaceV2 -{ - Q_OBJECT - Q_INTERFACES(QIconEngineFactoryInterfaceV2:QFactoryInterface) -public: - QIconEnginePluginV2(QObject *parent = 0); - ~QIconEnginePluginV2(); - - virtual QStringList keys() const = 0; - virtual QIconEngineV2 *create(const QString &filename = QString()) = 0; -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QICONENGINEPLUGIN_H diff --git a/src/gui/image/qiconloader.cpp b/src/gui/image/qiconloader.cpp deleted file mode 100644 index 19be636e9c..0000000000 --- a/src/gui/image/qiconloader.cpp +++ /dev/null @@ -1,573 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ -#ifndef QT_NO_ICON -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef Q_WS_MAC -#include -#endif - -#ifdef Q_WS_X11 -#include -#endif - -#include - -QT_BEGIN_NAMESPACE - -Q_GLOBAL_STATIC(QIconLoader, iconLoaderInstance) - -/* Theme to use in last resort, if the theme does not have the icon, neither the parents */ -static QString fallbackTheme() -{ -#ifdef Q_WS_X11 - if (X11->desktopEnvironment == DE_GNOME) { - return QLatin1String("gnome"); - } else if (X11->desktopEnvironment == DE_KDE) { - return X11->desktopVersion >= 4 - ? QString::fromLatin1("oxygen") - : QString::fromLatin1("crystalsvg"); - } else { - return QLatin1String("hicolor"); - } -#endif - return QString(); -} - -QIconLoader::QIconLoader() : - m_themeKey(1), m_supportsSvg(false), m_initialized(false) -{ -} - -// We lazily initialize the loader to make static icons -// work. Though we do not officially support this. -void QIconLoader::ensureInitialized() -{ - if (!m_initialized) { - m_initialized = true; - - Q_ASSERT(qApp); - - m_systemTheme = qt_guiPlatformPlugin()->systemIconThemeName(); - if (m_systemTheme.isEmpty()) - m_systemTheme = fallbackTheme(); -#ifndef QT_NO_LIBRARY - QFactoryLoader iconFactoryLoader(QIconEngineFactoryInterfaceV2_iid, - QLatin1String("/iconengines"), - Qt::CaseInsensitive); - if (iconFactoryLoader.keys().contains(QLatin1String("svg"))) - m_supportsSvg = true; -#endif //QT_NO_LIBRARY - } -} - -QIconLoader *QIconLoader::instance() -{ - return iconLoaderInstance(); -} - -// Queries the system theme and invalidates existing -// icons if the theme has changed. -void QIconLoader::updateSystemTheme() -{ - // Only change if this is not explicitly set by the user - if (m_userTheme.isEmpty()) { - QString theme = qt_guiPlatformPlugin()->systemIconThemeName(); - if (theme.isEmpty()) - theme = fallbackTheme(); - if (theme != m_systemTheme) { - m_systemTheme = theme; - invalidateKey(); - } - } -} - -void QIconLoader::setThemeName(const QString &themeName) -{ - m_userTheme = themeName; - invalidateKey(); -} - -void QIconLoader::setThemeSearchPath(const QStringList &searchPaths) -{ - m_iconDirs = searchPaths; - themeList.clear(); - invalidateKey(); -} - -QStringList QIconLoader::themeSearchPaths() const -{ - if (m_iconDirs.isEmpty()) { - m_iconDirs = qt_guiPlatformPlugin()->iconThemeSearchPaths(); - // Always add resource directory as search path - m_iconDirs.append(QLatin1String(":/icons")); - } - return m_iconDirs; -} - -QIconTheme::QIconTheme(const QString &themeName) - : m_valid(false) -{ - QFile themeIndex; - - QList keyList; - QStringList iconDirs = QIcon::themeSearchPaths(); - for ( int i = 0 ; i < iconDirs.size() ; ++i) { - QDir iconDir(iconDirs[i]); - QString themeDir = iconDir.path() + QLatin1Char('/') + themeName; - themeIndex.setFileName(themeDir + QLatin1String("/index.theme")); - if (themeIndex.exists()) { - m_contentDir = themeDir; - m_valid = true; - break; - } - } -#ifndef QT_NO_SETTINGS - if (themeIndex.exists()) { - const QSettings indexReader(themeIndex.fileName(), QSettings::IniFormat); - QStringListIterator keyIterator(indexReader.allKeys()); - while (keyIterator.hasNext()) { - - const QString key = keyIterator.next(); - if (key.endsWith(QLatin1String("/Size"))) { - // Note the QSettings ini-format does not accept - // slashes in key names, hence we have to cheat - if (int size = indexReader.value(key).toInt()) { - QString directoryKey = key.left(key.size() - 5); - QIconDirInfo dirInfo(directoryKey); - dirInfo.size = size; - QString type = indexReader.value(directoryKey + - QLatin1String("/Type") - ).toString(); - - if (type == QLatin1String("Fixed")) - dirInfo.type = QIconDirInfo::Fixed; - else if (type == QLatin1String("Scalable")) - dirInfo.type = QIconDirInfo::Scalable; - else - dirInfo.type = QIconDirInfo::Threshold; - - dirInfo.threshold = indexReader.value(directoryKey + - QLatin1String("/Threshold"), - 2).toInt(); - - dirInfo.minSize = indexReader.value(directoryKey + - QLatin1String("/MinSize"), - size).toInt(); - - dirInfo.maxSize = indexReader.value(directoryKey + - QLatin1String("/MaxSize"), - size).toInt(); - m_keyList.append(dirInfo); - } - } - } - - // Parent themes provide fallbacks for missing icons - m_parents = indexReader.value( - QLatin1String("Icon Theme/Inherits")).toStringList(); - - // Ensure a default platform fallback for all themes - if (m_parents.isEmpty()) - m_parents.append(fallbackTheme()); - - // Ensure that all themes fall back to hicolor - if (!m_parents.contains(QLatin1String("hicolor"))) - m_parents.append(QLatin1String("hicolor")); - } -#endif //QT_NO_SETTINGS -} - -QThemeIconEntries QIconLoader::findIconHelper(const QString &themeName, - const QString &iconName, - QStringList &visited) const -{ - QThemeIconEntries entries; - Q_ASSERT(!themeName.isEmpty()); - - QPixmap pixmap; - - // Used to protect against potential recursions - visited << themeName; - - QIconTheme theme = themeList.value(themeName); - if (!theme.isValid()) { - theme = QIconTheme(themeName); - if (!theme.isValid()) - theme = QIconTheme(fallbackTheme()); - - themeList.insert(themeName, theme); - } - - QString contentDir = theme.contentDir() + QLatin1Char('/'); - QList subDirs = theme.keyList(); - - const QString svgext(QLatin1String(".svg")); - const QString pngext(QLatin1String(".png")); - - // Add all relevant files - for (int i = 0; i < subDirs.size() ; ++i) { - const QIconDirInfo &dirInfo = subDirs.at(i); - QString subdir = dirInfo.path; - QDir currentDir(contentDir + subdir); - if (currentDir.exists(iconName + pngext)) { - PixmapEntry *iconEntry = new PixmapEntry; - iconEntry->dir = dirInfo; - iconEntry->filename = currentDir.filePath(iconName + pngext); - // Notice we ensure that pixmap entries always come before - // scalable to preserve search order afterwards - entries.prepend(iconEntry); - } else if (m_supportsSvg && - currentDir.exists(iconName + svgext)) { - ScalableEntry *iconEntry = new ScalableEntry; - iconEntry->dir = dirInfo; - iconEntry->filename = currentDir.filePath(iconName + svgext); - entries.append(iconEntry); - } - } - - if (entries.isEmpty()) { - const QStringList parents = theme.parents(); - // Search recursively through inherited themes - for (int i = 0 ; i < parents.size() ; ++i) { - - const QString parentTheme = parents.at(i).trimmed(); - - if (!visited.contains(parentTheme)) // guard against recursion - entries = findIconHelper(parentTheme, iconName, visited); - - if (!entries.isEmpty()) // success - break; - } - } - return entries; -} - -QThemeIconEntries QIconLoader::loadIcon(const QString &name) const -{ - if (!themeName().isEmpty()) { - QStringList visited; - return findIconHelper(themeName(), name, visited); - } - - return QThemeIconEntries(); -} - - -// -------- Icon Loader Engine -------- // - - -QIconLoaderEngine::QIconLoaderEngine(const QString& iconName) - : m_iconName(iconName), m_key(0) -{ -} - -QIconLoaderEngine::~QIconLoaderEngine() -{ - while (!m_entries.isEmpty()) - delete m_entries.takeLast(); - Q_ASSERT(m_entries.size() == 0); -} - -QIconLoaderEngine::QIconLoaderEngine(const QIconLoaderEngine &other) - : QIconEngineV2(other), - m_iconName(other.m_iconName), - m_key(0) -{ -} - -QIconEngineV2 *QIconLoaderEngine::clone() const -{ - return new QIconLoaderEngine(*this); -} - -bool QIconLoaderEngine::read(QDataStream &in) { - in >> m_iconName; - return true; -} - -bool QIconLoaderEngine::write(QDataStream &out) const -{ - out << m_iconName; - return true; -} - -bool QIconLoaderEngine::hasIcon() const -{ - return !(m_entries.isEmpty()); -} - -// Lazily load the icon -void QIconLoaderEngine::ensureLoaded() -{ - - iconLoaderInstance()->ensureInitialized(); - - if (!(iconLoaderInstance()->themeKey() == m_key)) { - - while (!m_entries.isEmpty()) - delete m_entries.takeLast(); - - Q_ASSERT(m_entries.size() == 0); - m_entries = iconLoaderInstance()->loadIcon(m_iconName); - m_key = iconLoaderInstance()->themeKey(); - } -} - -void QIconLoaderEngine::paint(QPainter *painter, const QRect &rect, - QIcon::Mode mode, QIcon::State state) -{ - QSize pixmapSize = rect.size(); -#if defined(Q_WS_MAC) - pixmapSize *= qt_mac_get_scalefactor(); -#endif - painter->drawPixmap(rect, pixmap(pixmapSize, mode, state)); -} - -/* - * This algorithm is defined by the freedesktop spec: - * http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html - */ -static bool directoryMatchesSize(const QIconDirInfo &dir, int iconsize) -{ - if (dir.type == QIconDirInfo::Fixed) { - return dir.size == iconsize; - - } else if (dir.type == QIconDirInfo::Scalable) { - return dir.size <= dir.maxSize && - iconsize >= dir.minSize; - - } else if (dir.type == QIconDirInfo::Threshold) { - return iconsize >= dir.size - dir.threshold && - iconsize <= dir.size + dir.threshold; - } - - Q_ASSERT(1); // Not a valid value - return false; -} - -/* - * This algorithm is defined by the freedesktop spec: - * http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html - */ -static int directorySizeDistance(const QIconDirInfo &dir, int iconsize) -{ - if (dir.type == QIconDirInfo::Fixed) { - return qAbs(dir.size - iconsize); - - } else if (dir.type == QIconDirInfo::Scalable) { - if (iconsize < dir.minSize) - return dir.minSize - iconsize; - else if (iconsize > dir.maxSize) - return iconsize - dir.maxSize; - else - return 0; - - } else if (dir.type == QIconDirInfo::Threshold) { - if (iconsize < dir.size - dir.threshold) - return dir.minSize - iconsize; - else if (iconsize > dir.size + dir.threshold) - return iconsize - dir.maxSize; - else return 0; - } - - Q_ASSERT(1); // Not a valid value - return INT_MAX; -} - -QIconLoaderEngineEntry *QIconLoaderEngine::entryForSize(const QSize &size) -{ - int iconsize = qMin(size.width(), size.height()); - - // Note that m_entries are sorted so that png-files - // come first - - // Search for exact matches first - for (int i = 0; i < m_entries.count(); ++i) { - QIconLoaderEngineEntry *entry = m_entries.at(i); - if (directoryMatchesSize(entry->dir, iconsize)) { - return entry; - } - } - - // Find the minimum distance icon - int minimalSize = INT_MAX; - QIconLoaderEngineEntry *closestMatch = 0; - for (int i = 0; i < m_entries.count(); ++i) { - QIconLoaderEngineEntry *entry = m_entries.at(i); - int distance = directorySizeDistance(entry->dir, iconsize); - if (distance < minimalSize) { - minimalSize = distance; - closestMatch = entry; - } - } - return closestMatch; -} - -/* - * Returns the actual icon size. For scalable svg's this is equivalent - * to the requested size. Otherwise the closest match is returned but - * we can never return a bigger size than the requested size. - * - */ -QSize QIconLoaderEngine::actualSize(const QSize &size, QIcon::Mode mode, - QIcon::State state) -{ - ensureLoaded(); - - QIconLoaderEngineEntry *entry = entryForSize(size); - if (entry) { - const QIconDirInfo &dir = entry->dir; - if (dir.type == QIconDirInfo::Scalable) - return size; - else { - int result = qMin(dir.size, qMin(size.width(), size.height())); - return QSize(result, result); - } - } - return QIconEngineV2::actualSize(size, mode, state); -} - -QPixmap PixmapEntry::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) -{ - Q_UNUSED(state); - - // Ensure that basePixmap is lazily initialized before generating the - // key, otherwise the cache key is not unique - if (basePixmap.isNull()) - basePixmap.load(filename); - -#if 0 // ### Qt5 - int actualSize = qMin(size.width(), size.height()); - QString key = QLatin1Literal("$qt_theme_") - % HexString(basePixmap.cacheKey()) - % HexString(mode) - % HexString(qApp->palette().cacheKey()) - % HexString(actualSize); - - QPixmap cachedPixmap; - if (QPixmapCache::find(key, &cachedPixmap)) { - return cachedPixmap; - } else { - QStyleOption opt(0); - opt.palette = qApp->palette(); - cachedPixmap = qApp->style()->generatedIconPixmap(mode, basePixmap, &opt); - QPixmapCache::insert(key, cachedPixmap); - } - return cachedPixmap; -#else - return basePixmap; -#endif -} - -QPixmap ScalableEntry::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) -{ - if (svgIcon.isNull()) - svgIcon = QIcon(filename); - - // Simply reuse svg icon engine - return svgIcon.pixmap(size, mode, state); -} - -QPixmap QIconLoaderEngine::pixmap(const QSize &size, QIcon::Mode mode, - QIcon::State state) -{ - ensureLoaded(); - - QIconLoaderEngineEntry *entry = entryForSize(size); - if (entry) - return entry->pixmap(size, mode, state); - - return QPixmap(); -} - -QString QIconLoaderEngine::key() const -{ - return QLatin1String("QIconLoaderEngine"); -} - -void QIconLoaderEngine::virtual_hook(int id, void *data) -{ - ensureLoaded(); - - switch (id) { - case QIconEngineV2::AvailableSizesHook: - { - QIconEngineV2::AvailableSizesArgument &arg - = *reinterpret_cast(data); - const QList directoryKey = iconLoaderInstance()->theme().keyList(); - arg.sizes.clear(); - - // Gets all sizes from the DirectoryInfo entries - for (int i = 0 ; i < m_entries.size() ; ++i) { - int size = m_entries.at(i)->dir.size; - arg.sizes.append(QSize(size, size)); - } - } - break; - case QIconEngineV2::IconNameHook: - { - QString &name = *reinterpret_cast(data); - name = m_iconName; - } - break; - default: - QIconEngineV2::virtual_hook(id, data); - } -} - -QT_END_NAMESPACE - -#endif //QT_NO_ICON diff --git a/src/gui/image/qiconloader_p.h b/src/gui/image/qiconloader_p.h deleted file mode 100644 index 00a3976b40..0000000000 --- a/src/gui/image/qiconloader_p.h +++ /dev/null @@ -1,192 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QDESKTOPICON_P_H -#define QDESKTOPICON_P_H - -#ifndef QT_NO_ICON -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -class QIconLoader; - -struct QIconDirInfo -{ - enum Type { Fixed, Scalable, Threshold }; - QIconDirInfo(const QString &_path = QString()) : - path(_path), - size(0), - maxSize(0), - minSize(0), - threshold(0), - type(Threshold) {} - QString path; - short size; - short maxSize; - short minSize; - short threshold; - Type type : 4; -}; - -class QIconLoaderEngineEntry - { -public: - virtual ~QIconLoaderEngineEntry() {} - virtual QPixmap pixmap(const QSize &size, - QIcon::Mode mode, - QIcon::State state) = 0; - QString filename; - QIconDirInfo dir; - static int count; -}; - -struct ScalableEntry : public QIconLoaderEngineEntry -{ - QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state); - QIcon svgIcon; -}; - -struct PixmapEntry : public QIconLoaderEngineEntry -{ - QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state); - QPixmap basePixmap; -}; - -typedef QList QThemeIconEntries; - -class QIconLoaderEngine : public QIconEngineV2 -{ -public: - QIconLoaderEngine(const QString& iconName = QString()); - ~QIconLoaderEngine(); - - void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state); - QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state); - QSize actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state); - QIconEngineV2 *clone() const; - bool read(QDataStream &in); - bool write(QDataStream &out) const; - -private: - QString key() const; - bool hasIcon() const; - void ensureLoaded(); - void virtual_hook(int id, void *data); - QIconLoaderEngineEntry *entryForSize(const QSize &size); - QIconLoaderEngine(const QIconLoaderEngine &other); - QThemeIconEntries m_entries; - QString m_iconName; - uint m_key; - - friend class QIconLoader; -}; - -class QIconTheme -{ -public: - QIconTheme(const QString &name); - QIconTheme() : m_valid(false) {} - QStringList parents() { return m_parents; } - QList keyList() { return m_keyList; } - QString contentDir() { return m_contentDir; } - bool isValid() { return m_valid; } - -private: - QString m_contentDir; - QList m_keyList; - QStringList m_parents; - bool m_valid; -}; - -class QIconLoader : public QObject -{ -public: - QIconLoader(); - QThemeIconEntries loadIcon(const QString &iconName) const; - uint themeKey() const { return m_themeKey; } - - QString themeName() const { return m_userTheme.isEmpty() ? m_systemTheme : m_userTheme; } - void setThemeName(const QString &themeName); - QIconTheme theme() { return themeList.value(themeName()); } - void setThemeSearchPath(const QStringList &searchPaths); - QStringList themeSearchPaths() const; - QIconDirInfo dirInfo(int dirindex); - static QIconLoader *instance(); - void updateSystemTheme(); - void invalidateKey() { m_themeKey++; } - void ensureInitialized(); - -private: - QThemeIconEntries findIconHelper(const QString &themeName, - const QString &iconName, - QStringList &visited) const; - uint m_themeKey; - bool m_supportsSvg; - bool m_initialized; - - mutable QString m_userTheme; - mutable QString m_systemTheme; - mutable QStringList m_iconDirs; - mutable QHash themeList; -}; - -QT_END_NAMESPACE - -#endif // QDESKTOPICON_P_H - -#endif //QT_NO_ICON diff --git a/src/gui/kernel/kernel.pri b/src/gui/kernel/kernel.pri index c2559b1225..d32533dbc1 100644 --- a/src/gui/kernel/kernel.pri +++ b/src/gui/kernel/kernel.pri @@ -16,7 +16,12 @@ HEADERS += \ kernel/qdesktopwidget.h \ kernel/qformlayout.h \ kernel/qgridlayout.h \ - kernel/qlayout.h \ + kernel/qicon.h \ + kernel/qicon_p.h \ + kernel/qiconloader_p.h \ + kernel/qiconengine.h \ + kernel/qiconengineplugin.h \ + kernel/qlayout.h \ kernel/qlayout_p.h \ kernel/qlayoutengine_p.h \ kernel/qlayoutitem.h \ @@ -46,7 +51,11 @@ SOURCES += \ kernel/qboxlayout.cpp \ kernel/qformlayout.cpp \ kernel/qgridlayout.cpp \ - kernel/qlayout.cpp \ + kernel/qicon.cpp \ + kernel/qiconloader.cpp \ + kernel/qiconengine.cpp \ + kernel/qiconengineplugin.cpp \ + kernel/qlayout.cpp \ kernel/qlayoutengine.cpp \ kernel/qlayoutitem.cpp \ kernel/qpalette.cpp \ diff --git a/src/gui/kernel/qicon.cpp b/src/gui/kernel/qicon.cpp new file mode 100644 index 0000000000..59687c709d --- /dev/null +++ b/src/gui/kernel/qicon.cpp @@ -0,0 +1,1165 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qicon.h" +#include "qicon_p.h" +#include "qiconengine.h" +#include "qiconengineplugin.h" +#include "private/qfactoryloader_p.h" +#include "private/qiconloader_p.h" +#include "qstyleoption.h" +#include "qpainter.h" +#include "qfileinfo.h" +#include "qstyle.h" +#include "qpixmapcache.h" +#include "qvariant.h" +#include "qcache.h" +#include "qdebug.h" +#include "private/qguiplatformplugin_p.h" +#include "qguiapplication.h" + +#ifdef Q_WS_MAC +#include +#include +#endif + +#ifdef Q_WS_X11 +#include "private/qt_x11_p.h" +#include "private/qkde_p.h" +#endif + +#include "private/qhexstring_p.h" + +#ifndef QT_NO_ICON +QT_BEGIN_NAMESPACE + +/*! + \enum QIcon::Mode + + This enum type describes the mode for which a pixmap is intended + to be used. The currently defined modes are: + + \value Normal + Display the pixmap when the user is + not interacting with the icon, but the + functionality represented by the icon is available. + \value Disabled + Display the pixmap when the + functionality represented by the icon is not available. + \value Active + Display the pixmap when the + functionality represented by the icon is available and + the user is interacting with the icon, for example, moving the + mouse over it or clicking it. + \value Selected + Display the pixmap when the item represented by the icon is + selected. +*/ + +/*! + \enum QIcon::State + + This enum describes the state for which a pixmap is intended to be + used. The \e state can be: + + \value Off Display the pixmap when the widget is in an "off" state + \value On Display the pixmap when the widget is in an "on" state +*/ + +static QBasicAtomicInt serialNumCounter = Q_BASIC_ATOMIC_INITIALIZER(1); + +static void qt_cleanup_icon_cache(); +typedef QCache IconCache; +Q_GLOBAL_STATIC_WITH_INITIALIZER(IconCache, qtIconCache, qAddPostRoutine(qt_cleanup_icon_cache)) + +static void qt_cleanup_icon_cache() +{ + qtIconCache()->clear(); +} + +QIconPrivate::QIconPrivate() + : engine(0), ref(1), + serialNum(serialNumCounter.fetchAndAddRelaxed(1)), + detach_no(0), + engine_version(2), + v1RefCount(0) +{ +} + +QPixmapIconEngine::QPixmapIconEngine() +{ +} + +QPixmapIconEngine::QPixmapIconEngine(const QPixmapIconEngine &other) + : QIconEngineV2(other), pixmaps(other.pixmaps) +{ +} + +QPixmapIconEngine::~QPixmapIconEngine() +{ +} + +void QPixmapIconEngine::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) +{ + QSize pixmapSize = rect.size(); +#if defined(Q_WS_MAC) + pixmapSize *= qt_mac_get_scalefactor(); +#endif + painter->drawPixmap(rect, pixmap(pixmapSize, mode, state)); +} + +static inline int area(const QSize &s) { return s.width() * s.height(); } + +// returns the smallest of the two that is still larger than or equal to size. +static QPixmapIconEngineEntry *bestSizeMatch( const QSize &size, QPixmapIconEngineEntry *pa, QPixmapIconEngineEntry *pb) +{ + int s = area(size); + if (pa->size == QSize() && pa->pixmap.isNull()) { + pa->pixmap = QPixmap(pa->fileName); + pa->size = pa->pixmap.size(); + } + int a = area(pa->size); + if (pb->size == QSize() && pb->pixmap.isNull()) { + pb->pixmap = QPixmap(pb->fileName); + pb->size = pb->pixmap.size(); + } + int b = area(pb->size); + int res = a; + if (qMin(a,b) >= s) + res = qMin(a,b); + else + res = qMax(a,b); + if (res == a) + return pa; + return pb; +} + +QPixmapIconEngineEntry *QPixmapIconEngine::tryMatch(const QSize &size, QIcon::Mode mode, QIcon::State state) +{ + QPixmapIconEngineEntry *pe = 0; + for (int i = 0; i < pixmaps.count(); ++i) + if (pixmaps.at(i).mode == mode && pixmaps.at(i).state == state) { + if (pe) + pe = bestSizeMatch(size, &pixmaps[i], pe); + else + pe = &pixmaps[i]; + } + return pe; +} + + +QPixmapIconEngineEntry *QPixmapIconEngine::bestMatch(const QSize &size, QIcon::Mode mode, QIcon::State state, bool sizeOnly) +{ + QPixmapIconEngineEntry *pe = tryMatch(size, mode, state); + while (!pe){ + QIcon::State oppositeState = (state == QIcon::On) ? QIcon::Off : QIcon::On; + if (mode == QIcon::Disabled || mode == QIcon::Selected) { + QIcon::Mode oppositeMode = (mode == QIcon::Disabled) ? QIcon::Selected : QIcon::Disabled; + if ((pe = tryMatch(size, QIcon::Normal, state))) + break; + if ((pe = tryMatch(size, QIcon::Active, state))) + break; + if ((pe = tryMatch(size, mode, oppositeState))) + break; + if ((pe = tryMatch(size, QIcon::Normal, oppositeState))) + break; + if ((pe = tryMatch(size, QIcon::Active, oppositeState))) + break; + if ((pe = tryMatch(size, oppositeMode, state))) + break; + if ((pe = tryMatch(size, oppositeMode, oppositeState))) + break; + } else { + QIcon::Mode oppositeMode = (mode == QIcon::Normal) ? QIcon::Active : QIcon::Normal; + if ((pe = tryMatch(size, oppositeMode, state))) + break; + if ((pe = tryMatch(size, mode, oppositeState))) + break; + if ((pe = tryMatch(size, oppositeMode, oppositeState))) + break; + if ((pe = tryMatch(size, QIcon::Disabled, state))) + break; + if ((pe = tryMatch(size, QIcon::Selected, state))) + break; + if ((pe = tryMatch(size, QIcon::Disabled, oppositeState))) + break; + if ((pe = tryMatch(size, QIcon::Selected, oppositeState))) + break; + } + + if (!pe) + return pe; + } + + if (sizeOnly ? (pe->size.isNull() || !pe->size.isValid()) : pe->pixmap.isNull()) { + pe->pixmap = QPixmap(pe->fileName); + if (!pe->pixmap.isNull()) + pe->size = pe->pixmap.size(); + } + + return pe; +} + +QPixmap QPixmapIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) +{ + QPixmap pm; + QPixmapIconEngineEntry *pe = bestMatch(size, mode, state, false); + if (pe) + pm = pe->pixmap; + + if (pm.isNull()) { + int idx = pixmaps.count(); + while (--idx >= 0) { + if (pe == &pixmaps[idx]) { + pixmaps.remove(idx); + break; + } + } + if (pixmaps.isEmpty()) + return pm; + else + return pixmap(size, mode, state); + } + + QSize actualSize = pm.size(); + if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height())) + actualSize.scale(size, Qt::KeepAspectRatio); + + // #### Qt5 no idea what this really does, but we need to remove the QApp and style references +// QString key = QLatin1Literal("qt_") +// % HexString(pm.cacheKey()) +// % HexString(pe->mode) +// % HexString(QApplication::palette().cacheKey()) +// % HexString(actualSize.width()) +// % HexString(actualSize.height()); + +// if (mode == QIcon::Active) { +// if (QPixmapCache::find(key % HexString(mode), pm)) +// return pm; // horray +// if (QPixmapCache::find(key % HexString(QIcon::Normal), pm)) { +// QStyleOption opt(0); +// opt.palette = QApplication::palette(); +// QPixmap active = QApplication::style()->generatedIconPixmap(QIcon::Active, pm, &opt); +// if (pm.cacheKey() == active.cacheKey()) +// return pm; +// } +// } + +// if (!QPixmapCache::find(key % HexString(mode), pm)) { + if (pm.size() != actualSize) + pm = pm.scaled(actualSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); +// if (pe->mode != mode && mode != QIcon::Normal) { +// QStyleOption opt(0); +// opt.palette = QApplication::palette(); +// QPixmap generated = QApplication::style()->generatedIconPixmap(mode, pm, &opt); +// if (!generated.isNull()) +// pm = generated; +// } +// QPixmapCache::insert(key % HexString(mode), pm); +// } + return pm; +} + +QSize QPixmapIconEngine::actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state) +{ + QSize actualSize; + if (QPixmapIconEngineEntry *pe = bestMatch(size, mode, state, true)) + actualSize = pe->size; + + if (actualSize.isNull()) + return actualSize; + + if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height())) + actualSize.scale(size, Qt::KeepAspectRatio); + return actualSize; +} + +void QPixmapIconEngine::addPixmap(const QPixmap &pixmap, QIcon::Mode mode, QIcon::State state) +{ + if (!pixmap.isNull()) { + QPixmapIconEngineEntry *pe = tryMatch(pixmap.size(), mode, state); + if(pe && pe->size == pixmap.size()) { + pe->pixmap = pixmap; + pe->fileName.clear(); + } else { + pixmaps += QPixmapIconEngineEntry(pixmap, mode, state); + } + } +} + +void QPixmapIconEngine::addFile(const QString &fileName, const QSize &_size, QIcon::Mode mode, QIcon::State state) +{ + if (!fileName.isEmpty()) { + QSize size = _size; + QPixmap pixmap; + + QString abs = fileName; + if (fileName.at(0) != QLatin1Char(':')) + abs = QFileInfo(fileName).absoluteFilePath(); + + for (int i = 0; i < pixmaps.count(); ++i) { + if (pixmaps.at(i).mode == mode && pixmaps.at(i).state == state) { + QPixmapIconEngineEntry *pe = &pixmaps[i]; + if(size == QSize()) { + pixmap = QPixmap(abs); + size = pixmap.size(); + } + if (pe->size == QSize() && pe->pixmap.isNull()) { + pe->pixmap = QPixmap(pe->fileName); + pe->size = pe->pixmap.size(); + } + if(pe->size == size) { + pe->pixmap = pixmap; + pe->fileName = abs; + return; + } + } + } + QPixmapIconEngineEntry e(abs, size, mode, state); + e.pixmap = pixmap; + pixmaps += e; + } +} + +QString QPixmapIconEngine::key() const +{ + return QLatin1String("QPixmapIconEngine"); +} + +QIconEngineV2 *QPixmapIconEngine::clone() const +{ + return new QPixmapIconEngine(*this); +} + +bool QPixmapIconEngine::read(QDataStream &in) +{ + int num_entries; + QPixmap pm; + QString fileName; + QSize sz; + uint mode; + uint state; + + in >> num_entries; + for (int i=0; i < num_entries; ++i) { + if (in.atEnd()) { + pixmaps.clear(); + return false; + } + in >> pm; + in >> fileName; + in >> sz; + in >> mode; + in >> state; + if (pm.isNull()) { + addFile(fileName, sz, QIcon::Mode(mode), QIcon::State(state)); + } else { + QPixmapIconEngineEntry pe(fileName, sz, QIcon::Mode(mode), QIcon::State(state)); + pe.pixmap = pm; + pixmaps += pe; + } + } + return true; +} + +bool QPixmapIconEngine::write(QDataStream &out) const +{ + int num_entries = pixmaps.size(); + out << num_entries; + for (int i=0; i < num_entries; ++i) { + if (pixmaps.at(i).pixmap.isNull()) + out << QPixmap(pixmaps.at(i).fileName); + else + out << pixmaps.at(i).pixmap; + out << pixmaps.at(i).fileName; + out << pixmaps.at(i).size; + out << (uint) pixmaps.at(i).mode; + out << (uint) pixmaps.at(i).state; + } + return true; +} + +void QPixmapIconEngine::virtual_hook(int id, void *data) +{ + switch (id) { + case QIconEngineV2::AvailableSizesHook: { + QIconEngineV2::AvailableSizesArgument &arg = + *reinterpret_cast(data); + arg.sizes.clear(); + for (int i = 0; i < pixmaps.size(); ++i) { + QPixmapIconEngineEntry &pe = pixmaps[i]; + if (pe.size == QSize() && pe.pixmap.isNull()) { + pe.pixmap = QPixmap(pe.fileName); + pe.size = pe.pixmap.size(); + } + if (pe.mode == arg.mode && pe.state == arg.state && !pe.size.isEmpty()) + arg.sizes.push_back(pe.size); + } + break; + } + default: + QIconEngineV2::virtual_hook(id, data); + } +} + +#ifndef QT_NO_LIBRARY +Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, + (QIconEngineFactoryInterface_iid, QLatin1String("/iconengines"), Qt::CaseInsensitive)) +Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loaderV2, + (QIconEngineFactoryInterfaceV2_iid, QLatin1String("/iconengines"), Qt::CaseInsensitive)) +#endif + + + +/*! + \class QIcon + + \brief The QIcon class provides scalable icons in different modes + and states. + + \ingroup painting + \ingroup shared + + + A QIcon can generate smaller, larger, active, and disabled pixmaps + from the set of pixmaps it is given. Such pixmaps are used by Qt + widgets to show an icon representing a particular action. + + The simplest use of QIcon is to create one from a QPixmap file or + resource, and then use it, allowing Qt to work out all the required + icon styles and sizes. For example: + + \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 0 + + To undo a QIcon, simply set a null icon in its place: + + \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 1 + + Use the QImageReader::supportedImageFormats() and + QImageWriter::supportedImageFormats() functions to retrieve a + complete list of the supported file formats. + + When you retrieve a pixmap using pixmap(QSize, Mode, State), and no + pixmap for this given size, mode and state has been added with + addFile() or addPixmap(), then QIcon will generate one on the + fly. This pixmap generation happens in a QIconEngineV2. The default + engine scales pixmaps down if required, but never up, and it uses + the current style to calculate a disabled appearance. By using + custom icon engines, you can customize every aspect of generated + icons. With QIconEnginePluginV2 it is possible to register different + icon engines for different file suffixes, making it possible for + third parties to provide additional icon engines to those included + with Qt. + + \note Since Qt 4.2, an icon engine that supports SVG is included. + + \section1 Making Classes that Use QIcon + + If you write your own widgets that have an option to set a small + pixmap, consider allowing a QIcon to be set for that pixmap. The + Qt class QToolButton is an example of such a widget. + + Provide a method to set a QIcon, and when you draw the icon, choose + whichever pixmap is appropriate for the current state of your widget. + For example: + \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 2 + + You might also make use of the \c Active mode, perhaps making your + widget \c Active when the mouse is over the widget (see \l + QWidget::enterEvent()), while the mouse is pressed pending the + release that will activate the function, or when it is the currently + selected item. If the widget can be toggled, the "On" mode might be + used to draw a different icon. + + \img icon.png QIcon + + \sa {fowler}{GUI Design Handbook: Iconic Label}, {Icons Example} +*/ + + +/*! + Constructs a null icon. +*/ +QIcon::QIcon() + : d(0) +{ +} + +/*! + Constructs an icon from a \a pixmap. + */ +QIcon::QIcon(const QPixmap &pixmap) + :d(0) +{ + addPixmap(pixmap); +} + +/*! + Constructs a copy of \a other. This is very fast. +*/ +QIcon::QIcon(const QIcon &other) + :d(other.d) +{ + if (d) + d->ref.ref(); +} + +/*! + Constructs an icon from the file with the given \a fileName. The + file will be loaded on demand. + + If \a fileName contains a relative path (e.g. the filename only) + the relevant file must be found relative to the runtime working + directory. + + The file name can be either refer to an actual file on disk or to + one of the application's embedded resources. See the + \l{resources.html}{Resource System} overview for details on how to + embed images and other resource files in the application's + executable. + + Use the QImageReader::supportedImageFormats() and + QImageWriter::supportedImageFormats() functions to retrieve a + complete list of the supported file formats. +*/ +QIcon::QIcon(const QString &fileName) + : d(0) +{ + addFile(fileName); +} + + +/*! + Creates an icon with a specific icon \a engine. The icon takes + ownership of the engine. +*/ +QIcon::QIcon(QIconEngine *engine) + :d(new QIconPrivate) +{ + d->engine_version = 1; + d->engine = engine; + d->v1RefCount = new QAtomicInt(1); +} + +/*! + Creates an icon with a specific icon \a engine. The icon takes + ownership of the engine. +*/ +QIcon::QIcon(QIconEngineV2 *engine) + :d(new QIconPrivate) +{ + d->engine_version = 2; + d->engine = engine; +} + +/*! + Destroys the icon. +*/ +QIcon::~QIcon() +{ + if (d && !d->ref.deref()) + delete d; +} + +/*! + Assigns the \a other icon to this icon and returns a reference to + this icon. +*/ +QIcon &QIcon::operator=(const QIcon &other) +{ + if (other.d) + other.d->ref.ref(); + if (d && !d->ref.deref()) + delete d; + d = other.d; + return *this; +} + +/*! + \fn void QIcon::swap(QIcon &other) + \since 4.8 + + Swaps icon \a other with this icon. This operation is very + fast and never fails. +*/ + +/*! + Returns the icon as a QVariant. +*/ +QIcon::operator QVariant() const +{ + return QVariant(QVariant::Icon, this); +} + +/*! \obsolete + + Returns a number that identifies the contents of this + QIcon object. Distinct QIcon objects can have + the same serial number if they refer to the same contents + (but they don't have to). Also, the serial number of + a QIcon object may change during its lifetime. + + Use cacheKey() instead. + + A null icon always has a serial number of 0. + + Serial numbers are mostly useful in conjunction with caching. + + \sa QPixmap::serialNumber() +*/ + +int QIcon::serialNumber() const +{ + return d ? d->serialNum : 0; +} + +/*! + Returns a number that identifies the contents of this QIcon + object. Distinct QIcon objects can have the same key if + they refer to the same contents. + \since 4.3 + + The cacheKey() will change when the icon is altered via + addPixmap() or addFile(). + + Cache keys are mostly useful in conjunction with caching. + + \sa QPixmap::cacheKey() +*/ +qint64 QIcon::cacheKey() const +{ + if (!d) + return 0; + return (((qint64) d->serialNum) << 32) | ((qint64) (d->detach_no)); +} + +/*! + Returns a pixmap with the requested \a size, \a mode, and \a + state, generating one if necessary. The pixmap might be smaller than + requested, but never larger. + + \sa actualSize(), paint() +*/ +QPixmap QIcon::pixmap(const QSize &size, Mode mode, State state) const +{ + if (!d) + return QPixmap(); + return d->engine->pixmap(size, mode, state); +} + +/*! + \fn QPixmap QIcon::pixmap(int w, int h, Mode mode = Normal, State state = Off) const + + \overload + + Returns a pixmap of size QSize(\a w, \a h). The pixmap might be smaller than + requested, but never larger. +*/ + +/*! + \fn QPixmap QIcon::pixmap(int extent, Mode mode = Normal, State state = Off) const + + \overload + + Returns a pixmap of size QSize(\a extent, \a extent). The pixmap might be smaller + than requested, but never larger. +*/ + +/*! Returns the actual size of the icon for the requested \a size, \a + mode, and \a state. The result might be smaller than requested, but + never larger. + + \sa pixmap(), paint() +*/ +QSize QIcon::actualSize(const QSize &size, Mode mode, State state) const +{ + if (!d) + return QSize(); + return d->engine->actualSize(size, mode, state); +} + + +/*! + Uses the \a painter to paint the icon with specified \a alignment, + required \a mode, and \a state into the rectangle \a rect. + + \sa actualSize(), pixmap() +*/ +void QIcon::paint(QPainter *painter, const QRect &rect, Qt::Alignment alignment, Mode mode, State state) const +{ + if (!d || !painter) + return; + QRect alignedRect = QStyle::alignedRect(painter->layoutDirection(), alignment, d->engine->actualSize(rect.size(), mode, state), rect); + d->engine->paint(painter, alignedRect, mode, state); +} + +/*! + \fn void QIcon::paint(QPainter *painter, int x, int y, int w, int h, Qt::Alignment alignment, + Mode mode, State state) const + + \overload + + Paints the icon into the rectangle QRect(\a x, \a y, \a w, \a h). +*/ + +/*! + Returns true if the icon is empty; otherwise returns false. + + An icon is empty if it has neither a pixmap nor a filename. + + Note: Even a non-null icon might not be able to create valid + pixmaps, eg. if the file does not exist or cannot be read. +*/ +bool QIcon::isNull() const +{ + return !d; +} + +/*!\internal + */ +bool QIcon::isDetached() const +{ + return !d || d->ref == 1; +} + +/*! \internal + */ +void QIcon::detach() +{ + if (d) { + if (d->ref != 1) { + QIconPrivate *x = new QIconPrivate; + if (d->engine_version > 1) { + QIconEngineV2 *engine = static_cast(d->engine); + x->engine = engine->clone(); + } else { + x->engine = d->engine; + x->v1RefCount = d->v1RefCount; + x->v1RefCount->ref(); + } + x->engine_version = d->engine_version; + if (!d->ref.deref()) + delete d; + d = x; + } + ++d->detach_no; + } +} + +/*! + Adds \a pixmap to the icon, as a specialization for \a mode and + \a state. + + Custom icon engines are free to ignore additionally added + pixmaps. + + \sa addFile() +*/ +void QIcon::addPixmap(const QPixmap &pixmap, Mode mode, State state) +{ + if (pixmap.isNull()) + return; + if (!d) { + d = new QIconPrivate; + d->engine = new QPixmapIconEngine; + } else { + detach(); + } + d->engine->addPixmap(pixmap, mode, state); +} + + +/*! Adds an image from the file with the given \a fileName to the + icon, as a specialization for \a size, \a mode and \a state. The + file will be loaded on demand. Note: custom icon engines are free + to ignore additionally added pixmaps. + + If \a fileName contains a relative path (e.g. the filename only) + the relevant file must be found relative to the runtime working + directory. + + The file name can be either refer to an actual file on disk or to + one of the application's embedded resources. See the + \l{resources.html}{Resource System} overview for details on how to + embed images and other resource files in the application's + executable. + + Use the QImageReader::supportedImageFormats() and + QImageWriter::supportedImageFormats() functions to retrieve a + complete list of the supported file formats. + + Note: When you add a non-empty filename to a QIcon, the icon becomes + non-null, even if the file doesn't exist or points to a corrupt file. + + \sa addPixmap() + */ +void QIcon::addFile(const QString &fileName, const QSize &size, Mode mode, State state) +{ + if (fileName.isEmpty()) + return; + if (!d) { +#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) + QFileInfo info(fileName); + QString suffix = info.suffix(); + if (!suffix.isEmpty()) { + // first try version 2 engines.. + if (QIconEngineFactoryInterfaceV2 *factory = qobject_cast(loaderV2()->instance(suffix))) { + if (QIconEngine *engine = factory->create(fileName)) { + d = new QIconPrivate; + d->engine = engine; + } + } + // ..then fall back and try to load version 1 engines + if (!d) { + if (QIconEngineFactoryInterface *factory = qobject_cast(loader()->instance(suffix))) { + if (QIconEngine *engine = factory->create(fileName)) { + d = new QIconPrivate; + d->engine = engine; + d->engine_version = 1; + d->v1RefCount = new QAtomicInt(1); + } + } + } + } +#endif + // ...then fall back to the default engine + if (!d) { + d = new QIconPrivate; + d->engine = new QPixmapIconEngine; + } + } else { + detach(); + } + d->engine->addFile(fileName, size, mode, state); +} + +/*! + \since 4.5 + + Returns a list of available icon sizes for the specified \a mode and + \a state. +*/ +QList QIcon::availableSizes(Mode mode, State state) const +{ + if (!d || !d->engine || d->engine_version < 2) + return QList(); + QIconEngineV2 *engine = static_cast(d->engine); + return engine->availableSizes(mode, state); +} + +/*! + \since 4.7 + + Returns the name used to create the icon, if available. + + Depending on the way the icon was created, it may have an associated + name. This is the case for icons created with fromTheme() or icons + using a QIconEngine which supports the QIconEngineV2::IconNameHook. + + \sa fromTheme(), QIconEngine +*/ +QString QIcon::name() const +{ + if (!d || !d->engine || d->engine_version < 2) + return QString(); + QIconEngineV2 *engine = static_cast(d->engine); + return engine->iconName(); +} + +/*! + \since 4.6 + + Sets the search paths for icon themes to \a paths. + \sa themeSearchPaths(), fromTheme(), setThemeName() +*/ +void QIcon::setThemeSearchPaths(const QStringList &paths) +{ + QIconLoader::instance()->setThemeSearchPath(paths); +} + +/*! + \since 4.6 + + Returns the search paths for icon themes. + + The default value will depend on the platform: + + On X11, the search path will use the XDG_DATA_DIRS environment + variable if available. + + By default all platforms will have the resource directory + \c{:\icons} as a fallback. You can use "rcc -project" to generate a + resource file from your icon theme. + + \sa setThemeSearchPaths(), fromTheme(), setThemeName() +*/ +QStringList QIcon::themeSearchPaths() +{ + return QIconLoader::instance()->themeSearchPaths(); +} + +/*! + \since 4.6 + + Sets the current icon theme to \a name. + + The \a name should correspond to a directory name in the + themeSearchPath() containing an index.theme + file describing it's contents. + + \sa themeSearchPaths(), themeName() +*/ +void QIcon::setThemeName(const QString &name) +{ + QIconLoader::instance()->setThemeName(name); +} + +/*! + \since 4.6 + + Returns the name of the current icon theme. + + On X11, the current icon theme depends on your desktop + settings. On other platforms it is not set by default. + + \sa setThemeName(), themeSearchPaths(), fromTheme(), + hasThemeIcon() +*/ +QString QIcon::themeName() +{ + return QIconLoader::instance()->themeName(); +} + +/*! + \since 4.6 + + Returns the QIcon corresponding to \a name in the current + icon theme. If no such icon is found in the current theme + \a fallback is returned instead. + + The latest version of the freedesktop icon specification and naming + specification can be obtained here: + + \list + \o \l{http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html} + \o \l{http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html} + \endlist + + To fetch an icon from the current icon theme: + + \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 3 + + Or if you want to provide a guaranteed fallback for platforms that + do not support theme icons, you can use the second argument: + + \snippet doc/src/snippets/code/src_gui_image_qicon.cpp 4 + + \note By default, only X11 will support themed icons. In order to + use themed icons on Mac and Windows, you will have to bundle a + compliant theme in one of your themeSearchPaths() and set the + appropriate themeName(). + + \sa themeName(), setThemeName(), themeSearchPaths() +*/ +QIcon QIcon::fromTheme(const QString &name, const QIcon &fallback) +{ + QIcon icon; + + if (qtIconCache()->contains(name)) { + icon = *qtIconCache()->object(name); + } else { + QIcon *cachedIcon = new QIcon(new QIconLoaderEngine(name)); + qtIconCache()->insert(name, cachedIcon); + icon = *cachedIcon; + } + + // Note the qapp check is to allow lazy loading of static icons + // Supporting fallbacks will not work for this case. + if (qApp && icon.availableSizes().isEmpty()) + return fallback; + + return icon; +} + +/*! + \since 4.6 + + Returns true if there is an icon available for \a name in the + current icon theme, otherwise returns false. + + \sa themeSearchPaths(), fromTheme(), setThemeName() +*/ +bool QIcon::hasThemeIcon(const QString &name) +{ + QIcon icon = fromTheme(name); + + return !icon.isNull(); +} + + +/***************************************************************************** + QIcon stream functions + *****************************************************************************/ +#if !defined(QT_NO_DATASTREAM) +/*! + \fn QDataStream &operator<<(QDataStream &stream, const QIcon &icon) + \relates QIcon + \since 4.2 + + Writes the given \a icon to the given \a stream as a PNG + image. If the icon contains more than one image, all images will + be written to the stream. Note that writing the stream to a file + will not produce a valid image file. +*/ + +QDataStream &operator<<(QDataStream &s, const QIcon &icon) +{ + if (s.version() >= QDataStream::Qt_4_3) { + if (icon.isNull()) { + s << QString(); + } else { + if (icon.d->engine_version > 1) { + QIconEngineV2 *engine = static_cast(icon.d->engine); + s << engine->key(); + engine->write(s); + } else { + // not really supported + qWarning("QIcon: Cannot stream QIconEngine. Use QIconEngineV2 instead."); + } + } + } else if (s.version() == QDataStream::Qt_4_2) { + if (icon.isNull()) { + s << 0; + } else { + QPixmapIconEngine *engine = static_cast(icon.d->engine); + int num_entries = engine->pixmaps.size(); + s << num_entries; + for (int i=0; i < num_entries; ++i) { + s << engine->pixmaps.at(i).pixmap; + s << engine->pixmaps.at(i).fileName; + s << engine->pixmaps.at(i).size; + s << (uint) engine->pixmaps.at(i).mode; + s << (uint) engine->pixmaps.at(i).state; + } + } + } else { + s << QPixmap(icon.pixmap(22,22)); + } + return s; +} + +/*! + \fn QDataStream &operator>>(QDataStream &stream, QIcon &icon) + \relates QIcon + \since 4.2 + + Reads an image, or a set of images, from the given \a stream into + the given \a icon. +*/ + +QDataStream &operator>>(QDataStream &s, QIcon &icon) +{ + if (s.version() >= QDataStream::Qt_4_3) { + icon = QIcon(); + QString key; + s >> key; + if (key == QLatin1String("QPixmapIconEngine")) { + icon.d = new QIconPrivate; + QIconEngineV2 *engine = new QPixmapIconEngine; + icon.d->engine = engine; + engine->read(s); + } else if (key == QLatin1String("QIconLoaderEngine")) { + icon.d = new QIconPrivate; + QIconEngineV2 *engine = new QIconLoaderEngine(); + icon.d->engine = engine; + engine->read(s); +#if !defined (QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) + } else if (QIconEngineFactoryInterfaceV2 *factory = qobject_cast(loaderV2()->instance(key))) { + if (QIconEngineV2 *engine= factory->create()) { + icon.d = new QIconPrivate; + icon.d->engine = engine; + engine->read(s); + } +#endif + } + } else if (s.version() == QDataStream::Qt_4_2) { + icon = QIcon(); + int num_entries; + QPixmap pm; + QString fileName; + QSize sz; + uint mode; + uint state; + + s >> num_entries; + for (int i=0; i < num_entries; ++i) { + s >> pm; + s >> fileName; + s >> sz; + s >> mode; + s >> state; + if (pm.isNull()) + icon.addFile(fileName, sz, QIcon::Mode(mode), QIcon::State(state)); + else + icon.addPixmap(pm, QIcon::Mode(mode), QIcon::State(state)); + } + } else { + QPixmap pm; + s >> pm; + icon.addPixmap(pm); + } + return s; +} + +#endif //QT_NO_DATASTREAM + +/*! + \fn DataPtr &QIcon::data_ptr() + \internal +*/ + +/*! + \typedef QIcon::DataPtr + \internal +*/ + +QT_END_NAMESPACE +#endif //QT_NO_ICON diff --git a/src/gui/kernel/qicon.h b/src/gui/kernel/qicon.h new file mode 100644 index 0000000000..4e3960925e --- /dev/null +++ b/src/gui/kernel/qicon.h @@ -0,0 +1,143 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QICON_H +#define QICON_H + +#include +#include +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Gui) + +class QIconPrivate; +class QIconEngine; +class QIconEngineV2; + +class Q_GUI_EXPORT QIcon +{ +public: + enum Mode { Normal, Disabled, Active, Selected }; + enum State { On, Off }; + + QIcon(); + QIcon(const QPixmap &pixmap); + QIcon(const QIcon &other); + explicit QIcon(const QString &fileName); // file or resource name + explicit QIcon(QIconEngine *engine); + explicit QIcon(QIconEngineV2 *engine); + ~QIcon(); + QIcon &operator=(const QIcon &other); +#ifdef Q_COMPILER_RVALUE_REFS + inline QIcon &operator=(QIcon &&other) + { qSwap(d, other.d); return *this; } +#endif + inline void swap(QIcon &other) { qSwap(d, other.d); } + + operator QVariant() const; + + QPixmap pixmap(const QSize &size, Mode mode = Normal, State state = Off) const; + inline QPixmap pixmap(int w, int h, Mode mode = Normal, State state = Off) const + { return pixmap(QSize(w, h), mode, state); } + inline QPixmap pixmap(int extent, Mode mode = Normal, State state = Off) const + { return pixmap(QSize(extent, extent), mode, state); } + + QSize actualSize(const QSize &size, Mode mode = Normal, State state = Off) const; + + QString name() const; + + void paint(QPainter *painter, const QRect &rect, Qt::Alignment alignment = Qt::AlignCenter, Mode mode = Normal, State state = Off) const; + inline void paint(QPainter *painter, int x, int y, int w, int h, Qt::Alignment alignment = Qt::AlignCenter, Mode mode = Normal, State state = Off) const + { paint(painter, QRect(x, y, w, h), alignment, mode, state); } + + bool isNull() const; + bool isDetached() const; + void detach(); + + int serialNumber() const; + qint64 cacheKey() const; + + void addPixmap(const QPixmap &pixmap, Mode mode = Normal, State state = Off); + void addFile(const QString &fileName, const QSize &size = QSize(), Mode mode = Normal, State state = Off); + + QList availableSizes(Mode mode = Normal, State state = Off) const; + + static QIcon fromTheme(const QString &name, const QIcon &fallback = QIcon()); + static bool hasThemeIcon(const QString &name); + + static QStringList themeSearchPaths(); + static void setThemeSearchPaths(const QStringList &searchpath); + + static QString themeName(); + static void setThemeName(const QString &path); + + Q_DUMMY_COMPARISON_OPERATOR(QIcon) + +private: + QIconPrivate *d; +#if !defined(QT_NO_DATASTREAM) + friend Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QIcon &); + friend Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QIcon &); +#endif + +public: + typedef QIconPrivate * DataPtr; + inline DataPtr &data_ptr() { return d; } +}; + +Q_DECLARE_SHARED(QIcon) +Q_DECLARE_TYPEINFO(QIcon, Q_MOVABLE_TYPE); + +#if !defined(QT_NO_DATASTREAM) +Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QIcon &); +Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QIcon &); +#endif + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QICON_H diff --git a/src/gui/kernel/qicon_p.h b/src/gui/kernel/qicon_p.h new file mode 100644 index 0000000000..0bf7e65cc1 --- /dev/null +++ b/src/gui/kernel/qicon_p.h @@ -0,0 +1,139 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QICON_P_H +#define QICON_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include + +#ifndef QT_NO_ICON +QT_BEGIN_NAMESPACE + +class QIconPrivate +{ +public: + QIconPrivate(); + + ~QIconPrivate() { + if (engine_version == 1) { + if (!v1RefCount->deref()) { + delete engine; + delete v1RefCount; + } + } else if (engine_version == 2) { + delete engine; + } + } + + QIconEngine *engine; + + QAtomicInt ref; + int serialNum; + int detach_no; + int engine_version; + + QAtomicInt *v1RefCount; +}; + + +struct QPixmapIconEngineEntry +{ + QPixmapIconEngineEntry():mode(QIcon::Normal), state(QIcon::Off){} + QPixmapIconEngineEntry(const QPixmap &pm, QIcon::Mode m = QIcon::Normal, QIcon::State s = QIcon::Off) + :pixmap(pm), size(pm.size()), mode(m), state(s){} + QPixmapIconEngineEntry(const QString &file, const QSize &sz = QSize(), QIcon::Mode m = QIcon::Normal, QIcon::State s = QIcon::Off) + :fileName(file), size(sz), mode(m), state(s){} + QPixmap pixmap; + QString fileName; + QSize size; + QIcon::Mode mode; + QIcon::State state; + bool isNull() const {return (fileName.isEmpty() && pixmap.isNull()); } +}; + + + +class QPixmapIconEngine : public QIconEngineV2 { +public: + QPixmapIconEngine(); + QPixmapIconEngine(const QPixmapIconEngine &); + ~QPixmapIconEngine(); + void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state); + QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state); + QPixmapIconEngineEntry *bestMatch(const QSize &size, QIcon::Mode mode, QIcon::State state, bool sizeOnly); + QSize actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state); + void addPixmap(const QPixmap &pixmap, QIcon::Mode mode, QIcon::State state); + void addFile(const QString &fileName, const QSize &size, QIcon::Mode mode, QIcon::State state); + + // v2 functions + QString key() const; + QIconEngineV2 *clone() const; + bool read(QDataStream &in); + bool write(QDataStream &out) const; + void virtual_hook(int id, void *data); + +private: + QPixmapIconEngineEntry *tryMatch(const QSize &size, QIcon::Mode mode, QIcon::State state); + QVector pixmaps; + + friend QDataStream &operator<<(QDataStream &s, const QIcon &icon); + friend class QIconThemeEngine; +}; + +QT_END_NAMESPACE +#endif //QT_NO_ICON +#endif // QICON_P_H diff --git a/src/gui/kernel/qiconengine.cpp b/src/gui/kernel/qiconengine.cpp new file mode 100644 index 0000000000..6168a83940 --- /dev/null +++ b/src/gui/kernel/qiconengine.cpp @@ -0,0 +1,324 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qiconengine.h" +#include "qpainter.h" + +QT_BEGIN_NAMESPACE + +/*! + \class QIconEngine + + \brief The QIconEngine class provides an abstract base class for QIcon renderers. + + \ingroup painting + + \bold {Use QIconEngineV2 instead.} + + An icon engine provides the rendering functions for a QIcon. Each icon has a + corresponding icon engine that is responsible for drawing the icon with a + requested size, mode and state. + + The icon is rendered by the paint() function, and the icon can additionally be + obtained as a pixmap with the pixmap() function (the default implementation + simply uses paint() to achieve this). The addPixmap() function can be used to + add new pixmaps to the icon engine, and is used by QIcon to add specialized + custom pixmaps. + + The paint(), pixmap(), and addPixmap() functions are all virtual, and can + therefore be reimplemented in subclasses of QIconEngine. + + \sa QIconEngineV2, QIconEnginePlugin + +*/ + +/*! + \fn virtual void QIconEngine::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) = 0; + + Uses the given \a painter to paint the icon with the required \a mode and + \a state into the rectangle \a rect. +*/ + +/*! Returns the actual size of the icon the engine provides for the + requested \a size, \a mode and \a state. The default implementation + returns the given \a size. + */ +QSize QIconEngine::actualSize(const QSize &size, QIcon::Mode /*mode*/, QIcon::State /*state*/) +{ + return size; +} + + +/*! + Destroys the icon engine. + */ +QIconEngine::~QIconEngine() +{ +} + + +/*! + Returns the icon as a pixmap with the required \a size, \a mode, + and \a state. The default implementation creates a new pixmap and + calls paint() to fill it. +*/ +QPixmap QIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) +{ + QPixmap pm(size); + { + QPainter p(&pm); + paint(&p, QRect(QPoint(0,0),size), mode, state); + } + return pm; +} + +/*! + Called by QIcon::addPixmap(). Adds a specialized \a pixmap for the given + \a mode and \a state. The default pixmap-based engine stores any supplied + pixmaps, and it uses them instead of scaled pixmaps if the size of a pixmap + matches the size of icon requested. Custom icon engines that implement + scalable vector formats are free to ignores any extra pixmaps. + */ +void QIconEngine::addPixmap(const QPixmap &/*pixmap*/, QIcon::Mode /*mode*/, QIcon::State /*state*/) +{ +} + + +/*! Called by QIcon::addFile(). Adds a specialized pixmap from the + file with the given \a fileName, \a size, \a mode and \a state. The + default pixmap-based engine stores any supplied file names, and it + loads the pixmaps on demand instead of using scaled pixmaps if the + size of a pixmap matches the size of icon requested. Custom icon + engines that implement scalable vector formats are free to ignores + any extra files. + */ +void QIconEngine::addFile(const QString &/*fileName*/, const QSize &/*size*/, QIcon::Mode /*mode*/, QIcon::State /*state*/) +{ +} + + + +// version 2 functions + + +/*! + \class QIconEngineV2 + + \brief The QIconEngineV2 class provides an abstract base class for QIcon renderers. + + \ingroup painting + \since 4.3 + + An icon engine renders \l{QIcon}s. With icon engines, you can + customize icons. Qt provides a default engine that makes icons + adhere to the current style by scaling the icons and providing a + disabled appearance. + + An engine is installed on an icon either through a QIcon + constructor or through a QIconEnginePluginV2. The plugins are used + by Qt if a specific engine is not given when the icon is created. + See the QIconEngineV2 class description to learn how to create + icon engine plugins. + + An icon engine provides the rendering functions for a QIcon. Each + icon has a corresponding icon engine that is responsible for drawing + the icon with a requested size, mode and state. + + QIconEngineV2 extends the API of QIconEngine to allow streaming of + the icon engine contents, and should be used instead of QIconEngine + for implementing new icon engines. + + \sa QIconEnginePluginV2 + +*/ + +/*! + \enum QIconEngineV2::IconEngineHook + \since 4.5 + + These enum values are used for virtual_hook() to allow additional + queries to icon engine without breaking binary compatibility. + + \value AvailableSizesHook Allows to query the sizes of the + contained pixmaps for pixmap-based engines. The \a data argument + of the virtual_hook() function is a AvailableSizesArgument pointer + that should be filled with icon sizes. Engines that work in terms + of a scalable, vectorial format normally return an empty list. + + \value IconNameHook Allows to query the name used to create the + icon, for example when instantiating an icon using + QIcon::fromTheme(). + + \sa virtual_hook() + */ + +/*! + \class QIconEngineV2::AvailableSizesArgument + \since 4.5 + + This struct represents arguments to virtual_hook() function when + \a id parameter is QIconEngineV2::AvailableSizesHook. + + \sa virtual_hook(), QIconEngineV2::IconEngineHook + */ + +/*! + \variable QIconEngineV2::AvailableSizesArgument::mode + \brief the requested mode of an image. + + \sa QIcon::Mode +*/ + +/*! + \variable QIconEngineV2::AvailableSizesArgument::state + \brief the requested state of an image. + + \sa QIcon::State +*/ + +/*! + \variable QIconEngineV2::AvailableSizesArgument::sizes + + \brief image sizes that are available with specified \a mode and + \a state. This is an output parameter and is filled after call to + virtual_hook(). Engines that work in terms of a scalable, + vectorial format normally return an empty list. +*/ + + +/*! + Returns a key that identifies this icon engine. + */ +QString QIconEngineV2::key() const +{ + return QString(); +} + +/*! + Returns a clone of this icon engine. + */ +QIconEngineV2 *QIconEngineV2::clone() const +{ + return 0; +} + +/*! + Reads icon engine contents from the QDataStream \a in. Returns + true if the contents were read; otherwise returns false. + + QIconEngineV2's default implementation always return false. + */ +bool QIconEngineV2::read(QDataStream &) +{ + return false; +} + +/*! + Writes the contents of this engine to the QDataStream \a out. + Returns true if the contents were written; otherwise returns false. + + QIconEngineV2's default implementation always return false. + */ +bool QIconEngineV2::write(QDataStream &) const +{ + return false; +} + +/*! + \since 4.5 + + Additional method to allow extending QIconEngineV2 without + adding new virtual methods (and without breaking binary compatibility). + The actual action and format of \a data depends on \a id argument + which is in fact a constant from IconEngineHook enum. + + \sa IconEngineHook +*/ +void QIconEngineV2::virtual_hook(int id, void *data) +{ + switch (id) { + case QIconEngineV2::AvailableSizesHook: { + QIconEngineV2::AvailableSizesArgument &arg = + *reinterpret_cast(data); + arg.sizes.clear(); + break; + } + default: + break; + } +} + +/*! + \since 4.5 + + Returns sizes of all images that are contained in the engine for the + specific \a mode and \a state. + + \note This is a helper method and the actual work is done by + virtual_hook() method, hence this method depends on icon engine support + and may not work with all icon engines. + */ +QList QIconEngineV2::availableSizes(QIcon::Mode mode, QIcon::State state) +{ + AvailableSizesArgument arg; + arg.mode = mode; + arg.state = state; + virtual_hook(QIconEngineV2::AvailableSizesHook, reinterpret_cast(&arg)); + return arg.sizes; +} + +/*! + \since 4.7 + + Returns the name used to create the engine, if available. + + \note This is a helper method and the actual work is done by + virtual_hook() method, hence this method depends on icon engine support + and may not work with all icon engines. + */ +QString QIconEngineV2::iconName() +{ + QString name; + virtual_hook(QIconEngineV2::IconNameHook, reinterpret_cast(&name)); + return name; +} + +QT_END_NAMESPACE diff --git a/src/gui/kernel/qiconengine.h b/src/gui/kernel/qiconengine.h new file mode 100644 index 0000000000..12caea8a20 --- /dev/null +++ b/src/gui/kernel/qiconengine.h @@ -0,0 +1,104 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QICONENGINE_H +#define QICONENGINE_H + +#include +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Gui) + +class Q_GUI_EXPORT QIconEngine +{ +public: + virtual ~QIconEngine(); + virtual void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) = 0; + virtual QSize actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state); + virtual QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state); + + virtual void addPixmap(const QPixmap &pixmap, QIcon::Mode mode, QIcon::State state); + virtual void addFile(const QString &fileName, const QSize &size, QIcon::Mode mode, QIcon::State state); + +#if 0 + virtual int frameCount(QIcon::Mode fromMode, QIcon::State fromState, QIcon::Mode toMode, QIcon::State toState); + virtual void paintFrame(QPainter *painter, const QRect &rect, int frameNumber, QIcon::Mode fromMode, QIcon::State fromState, QIcon::Mode toMode, QIcon::State toState); +#endif +}; + +// ### Qt 5: move the below into QIconEngine +class Q_GUI_EXPORT QIconEngineV2 : public QIconEngine +{ +public: + virtual QString key() const; + virtual QIconEngineV2 *clone() const; + virtual bool read(QDataStream &in); + virtual bool write(QDataStream &out) const; + virtual void virtual_hook(int id, void *data); + +public: + enum IconEngineHook { AvailableSizesHook = 1, IconNameHook }; + + struct AvailableSizesArgument + { + QIcon::Mode mode; + QIcon::State state; + QList sizes; + }; + + // ### Qt 5: make this function const and virtual. + QList availableSizes(QIcon::Mode mode = QIcon::Normal, + QIcon::State state = QIcon::Off); + + // ### Qt 5: make this function const and virtual. + QString iconName(); +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QICONENGINE_H diff --git a/src/gui/kernel/qiconengineplugin.cpp b/src/gui/kernel/qiconengineplugin.cpp new file mode 100644 index 0000000000..7c8c3a3c1a --- /dev/null +++ b/src/gui/kernel/qiconengineplugin.cpp @@ -0,0 +1,171 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qiconengineplugin.h" +#include "qiconengine.h" + +QT_BEGIN_NAMESPACE + +/*! + \class QIconEnginePlugin + \brief The QIconEnginePlugin class provides an abstract base for custom QIconEngine plugins. + + \ingroup plugins + + \bold {Use QIconEnginePluginV2 instead.} + + The icon engine plugin is a simple plugin interface that makes it easy to + create custom icon engines that can be loaded dynamically into applications + through QIcon. QIcon uses the file or resource name's suffix to determine + what icon engine to use. + + Writing a icon engine plugin is achieved by subclassing this base class, + reimplementing the pure virtual functions keys() and create(), and + exporting the class with the Q_EXPORT_PLUGIN2() macro. + + \sa {How to Create Qt Plugins} +*/ + +/*! + \fn QStringList QIconEnginePlugin::keys() const + + Returns a list of icon engine keys that this plugin supports. The keys correspond + to the suffix of the file or resource name used when the plugin was created. + Keys are case insensitive. + + \sa create() +*/ + +/*! + \fn QIconEngine* QIconEnginePlugin::create(const QString& filename) + + Creates and returns a QIconEngine object for the icon with the given + \a filename. + + \sa keys() +*/ + +/*! + Constructs a icon engine plugin with the given \a parent. This is invoked + automatically by the Q_EXPORT_PLUGIN2() macro. +*/ +QIconEnginePlugin::QIconEnginePlugin(QObject *parent) + : QObject(parent) +{ +} + +/*! + Destroys the icon engine plugin. + + You never have to call this explicitly. Qt destroys a plugin + automatically when it is no longer used. +*/ +QIconEnginePlugin::~QIconEnginePlugin() +{ +} + +// version 2 + +/*! + \class QIconEnginePluginV2 + \brief The QIconEnginePluginV2 class provides an abstract base for custom QIconEngineV2 plugins. + + \ingroup plugins + \since 4.3 + + Icon engine plugins produces \l{QIconEngine}s for \l{QIcon}s; an + icon engine is used to render the icon. The keys that identifies + the engines the plugin can create are suffixes of + icon filenames; they are returned by keys(). The create() function + receives the icon filename to return an engine for; it should + return 0 if it cannot produce an engine for the file. + + Writing an icon engine plugin is achieved by inheriting + QIconEnginePluginV2, reimplementing keys() and create(), and + adding the Q_EXPORT_PLUGIN2() macro. + + You should ensure that you do not duplicate keys. Qt will query + the plugins for icon engines in the order in which the plugins are + found during plugin search (see the plugins \l{How to Create Qt + Plugins}{overview document}). + + \sa {How to Create Qt Plugins} +*/ + +/*! + \fn QStringList QIconEnginePluginV2::keys() const + + Returns a list of icon engine keys that this plugin supports. The keys correspond + to the suffix of the file or resource name used when the plugin was created. + Keys are case insensitive. + + \sa create() +*/ + +/*! + \fn QIconEngineV2* QIconEnginePluginV2::create(const QString& filename = QString()) + + Creates and returns a QIconEngine object for the icon with the given + \a filename. + + \sa keys() +*/ + +/*! + Constructs a icon engine plugin with the given \a parent. This is invoked + automatically by the Q_EXPORT_PLUGIN2() macro. +*/ +QIconEnginePluginV2::QIconEnginePluginV2(QObject *parent) + : QObject(parent) +{ +} + +/*! + Destroys the icon engine plugin. + + You never have to call this explicitly. Qt destroys a plugin + automatically when it is no longer used. +*/ +QIconEnginePluginV2::~QIconEnginePluginV2() +{ +} + +QT_END_NAMESPACE diff --git a/src/gui/kernel/qiconengineplugin.h b/src/gui/kernel/qiconengineplugin.h new file mode 100644 index 0000000000..e892a38f7b --- /dev/null +++ b/src/gui/kernel/qiconengineplugin.h @@ -0,0 +1,104 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QICONENGINEPLUGIN_H +#define QICONENGINEPLUGIN_H + +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Gui) + +class QIconEngine; +class QIconEngineV2; + +struct Q_GUI_EXPORT QIconEngineFactoryInterface : public QFactoryInterface +{ + virtual QIconEngine *create(const QString &filename) = 0; +}; + +#define QIconEngineFactoryInterface_iid \ + "com.trolltech.Qt.QIconEngineFactoryInterface" +Q_DECLARE_INTERFACE(QIconEngineFactoryInterface, QIconEngineFactoryInterface_iid) + +class Q_GUI_EXPORT QIconEnginePlugin : public QObject, public QIconEngineFactoryInterface +{ + Q_OBJECT + Q_INTERFACES(QIconEngineFactoryInterface:QFactoryInterface) +public: + QIconEnginePlugin(QObject *parent = 0); + ~QIconEnginePlugin(); + + virtual QStringList keys() const = 0; + virtual QIconEngine *create(const QString &filename) = 0; +}; + +// ### Qt 5: remove version 2 +struct Q_GUI_EXPORT QIconEngineFactoryInterfaceV2 : public QFactoryInterface +{ + virtual QIconEngineV2 *create(const QString &filename = QString()) = 0; +}; + +#define QIconEngineFactoryInterfaceV2_iid \ + "com.trolltech.Qt.QIconEngineFactoryInterfaceV2" +Q_DECLARE_INTERFACE(QIconEngineFactoryInterfaceV2, QIconEngineFactoryInterfaceV2_iid) + +class Q_GUI_EXPORT QIconEnginePluginV2 : public QObject, public QIconEngineFactoryInterfaceV2 +{ + Q_OBJECT + Q_INTERFACES(QIconEngineFactoryInterfaceV2:QFactoryInterface) +public: + QIconEnginePluginV2(QObject *parent = 0); + ~QIconEnginePluginV2(); + + virtual QStringList keys() const = 0; + virtual QIconEngineV2 *create(const QString &filename = QString()) = 0; +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QICONENGINEPLUGIN_H diff --git a/src/gui/kernel/qiconloader.cpp b/src/gui/kernel/qiconloader.cpp new file mode 100644 index 0000000000..19be636e9c --- /dev/null +++ b/src/gui/kernel/qiconloader.cpp @@ -0,0 +1,573 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#ifndef QT_NO_ICON +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef Q_WS_MAC +#include +#endif + +#ifdef Q_WS_X11 +#include +#endif + +#include + +QT_BEGIN_NAMESPACE + +Q_GLOBAL_STATIC(QIconLoader, iconLoaderInstance) + +/* Theme to use in last resort, if the theme does not have the icon, neither the parents */ +static QString fallbackTheme() +{ +#ifdef Q_WS_X11 + if (X11->desktopEnvironment == DE_GNOME) { + return QLatin1String("gnome"); + } else if (X11->desktopEnvironment == DE_KDE) { + return X11->desktopVersion >= 4 + ? QString::fromLatin1("oxygen") + : QString::fromLatin1("crystalsvg"); + } else { + return QLatin1String("hicolor"); + } +#endif + return QString(); +} + +QIconLoader::QIconLoader() : + m_themeKey(1), m_supportsSvg(false), m_initialized(false) +{ +} + +// We lazily initialize the loader to make static icons +// work. Though we do not officially support this. +void QIconLoader::ensureInitialized() +{ + if (!m_initialized) { + m_initialized = true; + + Q_ASSERT(qApp); + + m_systemTheme = qt_guiPlatformPlugin()->systemIconThemeName(); + if (m_systemTheme.isEmpty()) + m_systemTheme = fallbackTheme(); +#ifndef QT_NO_LIBRARY + QFactoryLoader iconFactoryLoader(QIconEngineFactoryInterfaceV2_iid, + QLatin1String("/iconengines"), + Qt::CaseInsensitive); + if (iconFactoryLoader.keys().contains(QLatin1String("svg"))) + m_supportsSvg = true; +#endif //QT_NO_LIBRARY + } +} + +QIconLoader *QIconLoader::instance() +{ + return iconLoaderInstance(); +} + +// Queries the system theme and invalidates existing +// icons if the theme has changed. +void QIconLoader::updateSystemTheme() +{ + // Only change if this is not explicitly set by the user + if (m_userTheme.isEmpty()) { + QString theme = qt_guiPlatformPlugin()->systemIconThemeName(); + if (theme.isEmpty()) + theme = fallbackTheme(); + if (theme != m_systemTheme) { + m_systemTheme = theme; + invalidateKey(); + } + } +} + +void QIconLoader::setThemeName(const QString &themeName) +{ + m_userTheme = themeName; + invalidateKey(); +} + +void QIconLoader::setThemeSearchPath(const QStringList &searchPaths) +{ + m_iconDirs = searchPaths; + themeList.clear(); + invalidateKey(); +} + +QStringList QIconLoader::themeSearchPaths() const +{ + if (m_iconDirs.isEmpty()) { + m_iconDirs = qt_guiPlatformPlugin()->iconThemeSearchPaths(); + // Always add resource directory as search path + m_iconDirs.append(QLatin1String(":/icons")); + } + return m_iconDirs; +} + +QIconTheme::QIconTheme(const QString &themeName) + : m_valid(false) +{ + QFile themeIndex; + + QList keyList; + QStringList iconDirs = QIcon::themeSearchPaths(); + for ( int i = 0 ; i < iconDirs.size() ; ++i) { + QDir iconDir(iconDirs[i]); + QString themeDir = iconDir.path() + QLatin1Char('/') + themeName; + themeIndex.setFileName(themeDir + QLatin1String("/index.theme")); + if (themeIndex.exists()) { + m_contentDir = themeDir; + m_valid = true; + break; + } + } +#ifndef QT_NO_SETTINGS + if (themeIndex.exists()) { + const QSettings indexReader(themeIndex.fileName(), QSettings::IniFormat); + QStringListIterator keyIterator(indexReader.allKeys()); + while (keyIterator.hasNext()) { + + const QString key = keyIterator.next(); + if (key.endsWith(QLatin1String("/Size"))) { + // Note the QSettings ini-format does not accept + // slashes in key names, hence we have to cheat + if (int size = indexReader.value(key).toInt()) { + QString directoryKey = key.left(key.size() - 5); + QIconDirInfo dirInfo(directoryKey); + dirInfo.size = size; + QString type = indexReader.value(directoryKey + + QLatin1String("/Type") + ).toString(); + + if (type == QLatin1String("Fixed")) + dirInfo.type = QIconDirInfo::Fixed; + else if (type == QLatin1String("Scalable")) + dirInfo.type = QIconDirInfo::Scalable; + else + dirInfo.type = QIconDirInfo::Threshold; + + dirInfo.threshold = indexReader.value(directoryKey + + QLatin1String("/Threshold"), + 2).toInt(); + + dirInfo.minSize = indexReader.value(directoryKey + + QLatin1String("/MinSize"), + size).toInt(); + + dirInfo.maxSize = indexReader.value(directoryKey + + QLatin1String("/MaxSize"), + size).toInt(); + m_keyList.append(dirInfo); + } + } + } + + // Parent themes provide fallbacks for missing icons + m_parents = indexReader.value( + QLatin1String("Icon Theme/Inherits")).toStringList(); + + // Ensure a default platform fallback for all themes + if (m_parents.isEmpty()) + m_parents.append(fallbackTheme()); + + // Ensure that all themes fall back to hicolor + if (!m_parents.contains(QLatin1String("hicolor"))) + m_parents.append(QLatin1String("hicolor")); + } +#endif //QT_NO_SETTINGS +} + +QThemeIconEntries QIconLoader::findIconHelper(const QString &themeName, + const QString &iconName, + QStringList &visited) const +{ + QThemeIconEntries entries; + Q_ASSERT(!themeName.isEmpty()); + + QPixmap pixmap; + + // Used to protect against potential recursions + visited << themeName; + + QIconTheme theme = themeList.value(themeName); + if (!theme.isValid()) { + theme = QIconTheme(themeName); + if (!theme.isValid()) + theme = QIconTheme(fallbackTheme()); + + themeList.insert(themeName, theme); + } + + QString contentDir = theme.contentDir() + QLatin1Char('/'); + QList subDirs = theme.keyList(); + + const QString svgext(QLatin1String(".svg")); + const QString pngext(QLatin1String(".png")); + + // Add all relevant files + for (int i = 0; i < subDirs.size() ; ++i) { + const QIconDirInfo &dirInfo = subDirs.at(i); + QString subdir = dirInfo.path; + QDir currentDir(contentDir + subdir); + if (currentDir.exists(iconName + pngext)) { + PixmapEntry *iconEntry = new PixmapEntry; + iconEntry->dir = dirInfo; + iconEntry->filename = currentDir.filePath(iconName + pngext); + // Notice we ensure that pixmap entries always come before + // scalable to preserve search order afterwards + entries.prepend(iconEntry); + } else if (m_supportsSvg && + currentDir.exists(iconName + svgext)) { + ScalableEntry *iconEntry = new ScalableEntry; + iconEntry->dir = dirInfo; + iconEntry->filename = currentDir.filePath(iconName + svgext); + entries.append(iconEntry); + } + } + + if (entries.isEmpty()) { + const QStringList parents = theme.parents(); + // Search recursively through inherited themes + for (int i = 0 ; i < parents.size() ; ++i) { + + const QString parentTheme = parents.at(i).trimmed(); + + if (!visited.contains(parentTheme)) // guard against recursion + entries = findIconHelper(parentTheme, iconName, visited); + + if (!entries.isEmpty()) // success + break; + } + } + return entries; +} + +QThemeIconEntries QIconLoader::loadIcon(const QString &name) const +{ + if (!themeName().isEmpty()) { + QStringList visited; + return findIconHelper(themeName(), name, visited); + } + + return QThemeIconEntries(); +} + + +// -------- Icon Loader Engine -------- // + + +QIconLoaderEngine::QIconLoaderEngine(const QString& iconName) + : m_iconName(iconName), m_key(0) +{ +} + +QIconLoaderEngine::~QIconLoaderEngine() +{ + while (!m_entries.isEmpty()) + delete m_entries.takeLast(); + Q_ASSERT(m_entries.size() == 0); +} + +QIconLoaderEngine::QIconLoaderEngine(const QIconLoaderEngine &other) + : QIconEngineV2(other), + m_iconName(other.m_iconName), + m_key(0) +{ +} + +QIconEngineV2 *QIconLoaderEngine::clone() const +{ + return new QIconLoaderEngine(*this); +} + +bool QIconLoaderEngine::read(QDataStream &in) { + in >> m_iconName; + return true; +} + +bool QIconLoaderEngine::write(QDataStream &out) const +{ + out << m_iconName; + return true; +} + +bool QIconLoaderEngine::hasIcon() const +{ + return !(m_entries.isEmpty()); +} + +// Lazily load the icon +void QIconLoaderEngine::ensureLoaded() +{ + + iconLoaderInstance()->ensureInitialized(); + + if (!(iconLoaderInstance()->themeKey() == m_key)) { + + while (!m_entries.isEmpty()) + delete m_entries.takeLast(); + + Q_ASSERT(m_entries.size() == 0); + m_entries = iconLoaderInstance()->loadIcon(m_iconName); + m_key = iconLoaderInstance()->themeKey(); + } +} + +void QIconLoaderEngine::paint(QPainter *painter, const QRect &rect, + QIcon::Mode mode, QIcon::State state) +{ + QSize pixmapSize = rect.size(); +#if defined(Q_WS_MAC) + pixmapSize *= qt_mac_get_scalefactor(); +#endif + painter->drawPixmap(rect, pixmap(pixmapSize, mode, state)); +} + +/* + * This algorithm is defined by the freedesktop spec: + * http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html + */ +static bool directoryMatchesSize(const QIconDirInfo &dir, int iconsize) +{ + if (dir.type == QIconDirInfo::Fixed) { + return dir.size == iconsize; + + } else if (dir.type == QIconDirInfo::Scalable) { + return dir.size <= dir.maxSize && + iconsize >= dir.minSize; + + } else if (dir.type == QIconDirInfo::Threshold) { + return iconsize >= dir.size - dir.threshold && + iconsize <= dir.size + dir.threshold; + } + + Q_ASSERT(1); // Not a valid value + return false; +} + +/* + * This algorithm is defined by the freedesktop spec: + * http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html + */ +static int directorySizeDistance(const QIconDirInfo &dir, int iconsize) +{ + if (dir.type == QIconDirInfo::Fixed) { + return qAbs(dir.size - iconsize); + + } else if (dir.type == QIconDirInfo::Scalable) { + if (iconsize < dir.minSize) + return dir.minSize - iconsize; + else if (iconsize > dir.maxSize) + return iconsize - dir.maxSize; + else + return 0; + + } else if (dir.type == QIconDirInfo::Threshold) { + if (iconsize < dir.size - dir.threshold) + return dir.minSize - iconsize; + else if (iconsize > dir.size + dir.threshold) + return iconsize - dir.maxSize; + else return 0; + } + + Q_ASSERT(1); // Not a valid value + return INT_MAX; +} + +QIconLoaderEngineEntry *QIconLoaderEngine::entryForSize(const QSize &size) +{ + int iconsize = qMin(size.width(), size.height()); + + // Note that m_entries are sorted so that png-files + // come first + + // Search for exact matches first + for (int i = 0; i < m_entries.count(); ++i) { + QIconLoaderEngineEntry *entry = m_entries.at(i); + if (directoryMatchesSize(entry->dir, iconsize)) { + return entry; + } + } + + // Find the minimum distance icon + int minimalSize = INT_MAX; + QIconLoaderEngineEntry *closestMatch = 0; + for (int i = 0; i < m_entries.count(); ++i) { + QIconLoaderEngineEntry *entry = m_entries.at(i); + int distance = directorySizeDistance(entry->dir, iconsize); + if (distance < minimalSize) { + minimalSize = distance; + closestMatch = entry; + } + } + return closestMatch; +} + +/* + * Returns the actual icon size. For scalable svg's this is equivalent + * to the requested size. Otherwise the closest match is returned but + * we can never return a bigger size than the requested size. + * + */ +QSize QIconLoaderEngine::actualSize(const QSize &size, QIcon::Mode mode, + QIcon::State state) +{ + ensureLoaded(); + + QIconLoaderEngineEntry *entry = entryForSize(size); + if (entry) { + const QIconDirInfo &dir = entry->dir; + if (dir.type == QIconDirInfo::Scalable) + return size; + else { + int result = qMin(dir.size, qMin(size.width(), size.height())); + return QSize(result, result); + } + } + return QIconEngineV2::actualSize(size, mode, state); +} + +QPixmap PixmapEntry::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) +{ + Q_UNUSED(state); + + // Ensure that basePixmap is lazily initialized before generating the + // key, otherwise the cache key is not unique + if (basePixmap.isNull()) + basePixmap.load(filename); + +#if 0 // ### Qt5 + int actualSize = qMin(size.width(), size.height()); + QString key = QLatin1Literal("$qt_theme_") + % HexString(basePixmap.cacheKey()) + % HexString(mode) + % HexString(qApp->palette().cacheKey()) + % HexString(actualSize); + + QPixmap cachedPixmap; + if (QPixmapCache::find(key, &cachedPixmap)) { + return cachedPixmap; + } else { + QStyleOption opt(0); + opt.palette = qApp->palette(); + cachedPixmap = qApp->style()->generatedIconPixmap(mode, basePixmap, &opt); + QPixmapCache::insert(key, cachedPixmap); + } + return cachedPixmap; +#else + return basePixmap; +#endif +} + +QPixmap ScalableEntry::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) +{ + if (svgIcon.isNull()) + svgIcon = QIcon(filename); + + // Simply reuse svg icon engine + return svgIcon.pixmap(size, mode, state); +} + +QPixmap QIconLoaderEngine::pixmap(const QSize &size, QIcon::Mode mode, + QIcon::State state) +{ + ensureLoaded(); + + QIconLoaderEngineEntry *entry = entryForSize(size); + if (entry) + return entry->pixmap(size, mode, state); + + return QPixmap(); +} + +QString QIconLoaderEngine::key() const +{ + return QLatin1String("QIconLoaderEngine"); +} + +void QIconLoaderEngine::virtual_hook(int id, void *data) +{ + ensureLoaded(); + + switch (id) { + case QIconEngineV2::AvailableSizesHook: + { + QIconEngineV2::AvailableSizesArgument &arg + = *reinterpret_cast(data); + const QList directoryKey = iconLoaderInstance()->theme().keyList(); + arg.sizes.clear(); + + // Gets all sizes from the DirectoryInfo entries + for (int i = 0 ; i < m_entries.size() ; ++i) { + int size = m_entries.at(i)->dir.size; + arg.sizes.append(QSize(size, size)); + } + } + break; + case QIconEngineV2::IconNameHook: + { + QString &name = *reinterpret_cast(data); + name = m_iconName; + } + break; + default: + QIconEngineV2::virtual_hook(id, data); + } +} + +QT_END_NAMESPACE + +#endif //QT_NO_ICON diff --git a/src/gui/kernel/qiconloader_p.h b/src/gui/kernel/qiconloader_p.h new file mode 100644 index 0000000000..00a3976b40 --- /dev/null +++ b/src/gui/kernel/qiconloader_p.h @@ -0,0 +1,192 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QDESKTOPICON_P_H +#define QDESKTOPICON_P_H + +#ifndef QT_NO_ICON +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QIconLoader; + +struct QIconDirInfo +{ + enum Type { Fixed, Scalable, Threshold }; + QIconDirInfo(const QString &_path = QString()) : + path(_path), + size(0), + maxSize(0), + minSize(0), + threshold(0), + type(Threshold) {} + QString path; + short size; + short maxSize; + short minSize; + short threshold; + Type type : 4; +}; + +class QIconLoaderEngineEntry + { +public: + virtual ~QIconLoaderEngineEntry() {} + virtual QPixmap pixmap(const QSize &size, + QIcon::Mode mode, + QIcon::State state) = 0; + QString filename; + QIconDirInfo dir; + static int count; +}; + +struct ScalableEntry : public QIconLoaderEngineEntry +{ + QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state); + QIcon svgIcon; +}; + +struct PixmapEntry : public QIconLoaderEngineEntry +{ + QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state); + QPixmap basePixmap; +}; + +typedef QList QThemeIconEntries; + +class QIconLoaderEngine : public QIconEngineV2 +{ +public: + QIconLoaderEngine(const QString& iconName = QString()); + ~QIconLoaderEngine(); + + void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state); + QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state); + QSize actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state); + QIconEngineV2 *clone() const; + bool read(QDataStream &in); + bool write(QDataStream &out) const; + +private: + QString key() const; + bool hasIcon() const; + void ensureLoaded(); + void virtual_hook(int id, void *data); + QIconLoaderEngineEntry *entryForSize(const QSize &size); + QIconLoaderEngine(const QIconLoaderEngine &other); + QThemeIconEntries m_entries; + QString m_iconName; + uint m_key; + + friend class QIconLoader; +}; + +class QIconTheme +{ +public: + QIconTheme(const QString &name); + QIconTheme() : m_valid(false) {} + QStringList parents() { return m_parents; } + QList keyList() { return m_keyList; } + QString contentDir() { return m_contentDir; } + bool isValid() { return m_valid; } + +private: + QString m_contentDir; + QList m_keyList; + QStringList m_parents; + bool m_valid; +}; + +class QIconLoader : public QObject +{ +public: + QIconLoader(); + QThemeIconEntries loadIcon(const QString &iconName) const; + uint themeKey() const { return m_themeKey; } + + QString themeName() const { return m_userTheme.isEmpty() ? m_systemTheme : m_userTheme; } + void setThemeName(const QString &themeName); + QIconTheme theme() { return themeList.value(themeName()); } + void setThemeSearchPath(const QStringList &searchPaths); + QStringList themeSearchPaths() const; + QIconDirInfo dirInfo(int dirindex); + static QIconLoader *instance(); + void updateSystemTheme(); + void invalidateKey() { m_themeKey++; } + void ensureInitialized(); + +private: + QThemeIconEntries findIconHelper(const QString &themeName, + const QString &iconName, + QStringList &visited) const; + uint m_themeKey; + bool m_supportsSvg; + bool m_initialized; + + mutable QString m_userTheme; + mutable QString m_systemTheme; + mutable QStringList m_iconDirs; + mutable QHash themeList; +}; + +QT_END_NAMESPACE + +#endif // QDESKTOPICON_P_H + +#endif //QT_NO_ICON diff --git a/src/gui/text/qlinecontrol.cpp b/src/gui/text/qlinecontrol.cpp new file mode 100644 index 0000000000..eb4e142328 --- /dev/null +++ b/src/gui/text/qlinecontrol.cpp @@ -0,0 +1,1833 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qlinecontrol_p.h" + +#ifndef QT_NO_LINEEDIT + +#include "qabstractitemview.h" +#include "qclipboard.h" +#ifndef QT_NO_ACCESSIBILITY +#include "qaccessible.h" +#endif +#ifndef QT_NO_IM +#include "qinputcontext.h" +#include "qlist.h" +#endif +#include "qapplication.h" +#ifndef QT_NO_GRAPHICSVIEW +#include "qgraphicssceneevent.h" +#endif + +QT_BEGIN_NAMESPACE + +/*! + \internal + + Updates the display text based of the current edit text + If the text has changed will emit displayTextChanged() +*/ +void QLineControl::updateDisplayText(bool forceUpdate) +{ + QString orig = m_textLayout.text(); + QString str; + if (m_echoMode == QLineEdit::NoEcho) + str = QString::fromLatin1(""); + else + str = m_text; + + if (m_echoMode == QLineEdit::Password || (m_echoMode == QLineEdit::PasswordEchoOnEdit + && !m_passwordEchoEditing)) + str.fill(m_passwordCharacter); + + // replace certain non-printable characters with spaces (to avoid + // drawing boxes when using fonts that don't have glyphs for such + // characters) + QChar* uc = str.data(); + for (int i = 0; i < (int)str.length(); ++i) { + if ((uc[i] < 0x20 && uc[i] != 0x09) + || uc[i] == QChar::LineSeparator + || uc[i] == QChar::ParagraphSeparator + || uc[i] == QChar::ObjectReplacementCharacter) + uc[i] = QChar(0x0020); + } + + m_textLayout.setText(str); + + QTextOption option; + option.setTextDirection(m_layoutDirection); + option.setFlags(QTextOption::IncludeTrailingSpaces); + m_textLayout.setTextOption(option); + + m_textLayout.beginLayout(); + QTextLine l = m_textLayout.createLine(); + m_textLayout.endLayout(); + m_ascent = qRound(l.ascent()); + + if (str != orig || forceUpdate) + emit displayTextChanged(str); +} + +#ifndef QT_NO_CLIPBOARD +/*! + \internal + + Copies the currently selected text into the clipboard using the given + \a mode. + + \note If the echo mode is set to a mode other than Normal then copy + will not work. This is to prevent using copy as a method of bypassing + password features of the line control. +*/ +void QLineControl::copy(QClipboard::Mode mode) const +{ + QString t = selectedText(); + if (!t.isEmpty() && m_echoMode == QLineEdit::Normal) { + disconnect(QApplication::clipboard(), SIGNAL(selectionChanged()), this, 0); + QApplication::clipboard()->setText(t, mode); + connect(QApplication::clipboard(), SIGNAL(selectionChanged()), + this, SLOT(_q_clipboardChanged())); + } +} + +/*! + \internal + + Inserts the text stored in the application clipboard into the line + control. + + \sa insert() +*/ +void QLineControl::paste(QClipboard::Mode clipboardMode) +{ + QString clip = QApplication::clipboard()->text(clipboardMode); + if (!clip.isEmpty() || hasSelectedText()) { + separate(); //make it a separate undo/redo command + insert(clip); + separate(); + } +} + +#endif // !QT_NO_CLIPBOARD + +/*! + \internal + + Handles the behavior for the backspace key or function. + Removes the current selection if there is a selection, otherwise + removes the character prior to the cursor position. + + \sa del() +*/ +void QLineControl::backspace() +{ + int priorState = m_undoState; + if (hasSelectedText()) { + removeSelectedText(); + } else if (m_cursor) { + --m_cursor; + if (m_maskData) + m_cursor = prevMaskBlank(m_cursor); + QChar uc = m_text.at(m_cursor); + if (m_cursor > 0 && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) { + // second half of a surrogate, check if we have the first half as well, + // if yes delete both at once + uc = m_text.at(m_cursor - 1); + if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00) { + internalDelete(true); + --m_cursor; + } + } + internalDelete(true); + } + finishChange(priorState); +} + +/*! + \internal + + Handles the behavior for the delete key or function. + Removes the current selection if there is a selection, otherwise + removes the character after the cursor position. + + \sa del() +*/ +void QLineControl::del() +{ + int priorState = m_undoState; + if (hasSelectedText()) { + removeSelectedText(); + } else { + int n = m_textLayout.nextCursorPosition(m_cursor) - m_cursor; + while (n--) + internalDelete(); + } + finishChange(priorState); +} + +/*! + \internal + + Inserts the given \a newText at the current cursor position. + If there is any selected text it is removed prior to insertion of + the new text. +*/ +void QLineControl::insert(const QString &newText) +{ + int priorState = m_undoState; + removeSelectedText(); + internalInsert(newText); + finishChange(priorState); +} + +/*! + \internal + + Clears the line control text. +*/ +void QLineControl::clear() +{ + int priorState = m_undoState; + m_selstart = 0; + m_selend = m_text.length(); + removeSelectedText(); + separate(); + finishChange(priorState, /*update*/false, /*edited*/false); +} + +/*! + \internal + + Sets \a length characters from the given \a start position as selected. + The given \a start position must be within the current text for + the line control. If \a length characters cannot be selected, then + the selection will extend to the end of the current text. +*/ +void QLineControl::setSelection(int start, int length) +{ + if(start < 0 || start > (int)m_text.length()){ + qWarning("QLineControl::setSelection: Invalid start position"); + return; + } + + if (length > 0) { + if (start == m_selstart && start + length == m_selend) + return; + m_selstart = start; + m_selend = qMin(start + length, (int)m_text.length()); + m_cursor = m_selend; + } else if (length < 0){ + if (start == m_selend && start + length == m_selstart) + return; + m_selstart = qMax(start + length, 0); + m_selend = start; + m_cursor = m_selstart; + } else if (m_selstart != m_selend) { + m_selstart = 0; + m_selend = 0; + m_cursor = start; + } else { + m_cursor = start; + emitCursorPositionChanged(); + return; + } + emit selectionChanged(); + emitCursorPositionChanged(); +} + +void QLineControl::_q_clipboardChanged() +{ +} + +void QLineControl::_q_deleteSelected() +{ + if (!hasSelectedText()) + return; + + int priorState = m_undoState; + emit resetInputContext(); + removeSelectedText(); + separate(); + finishChange(priorState); +} + +/*! + \internal + + Initializes the line control with a starting text value of \a txt. +*/ +void QLineControl::init(const QString &txt) +{ + m_text = txt; + updateDisplayText(); + m_cursor = m_text.length(); +} + +/*! + \internal + + Sets the password echo editing to \a editing. If password echo editing + is true, then the text of the password is displayed even if the echo + mode is set to QLineEdit::PasswordEchoOnEdit. Password echoing editing + does not affect other echo modes. +*/ +void QLineControl::updatePasswordEchoEditing(bool editing) +{ + m_passwordEchoEditing = editing; + updateDisplayText(); +} + +/*! + \internal + + Returns the cursor position of the given \a x pixel value in relation + to the displayed text. The given \a betweenOrOn specified what kind + of cursor position is requested. +*/ +int QLineControl::xToPos(int x, QTextLine::CursorPosition betweenOrOn) const +{ + return m_textLayout.lineAt(0).xToCursor(x, betweenOrOn); +} + +/*! + \internal + + Returns the bounds of the current cursor, as defined as a + between characters cursor. +*/ +QRect QLineControl::cursorRect() const +{ + QTextLine l = m_textLayout.lineAt(0); + int c = m_cursor; + if (m_preeditCursor != -1) + c += m_preeditCursor; + int cix = qRound(l.cursorToX(c)); + int w = m_cursorWidth; + int ch = l.height() + 1; + + return QRect(cix-5, 0, w+9, ch); +} + +/*! + \internal + + Fixes the current text so that it is valid given any set validators. + + Returns true if the text was changed. Otherwise returns false. +*/ +bool QLineControl::fixup() // this function assumes that validate currently returns != Acceptable +{ +#ifndef QT_NO_VALIDATOR + if (m_validator) { + QString textCopy = m_text; + int cursorCopy = m_cursor; + m_validator->fixup(textCopy); + if (m_validator->validate(textCopy, cursorCopy) == QValidator::Acceptable) { + if (textCopy != m_text || cursorCopy != m_cursor) + internalSetText(textCopy, cursorCopy); + return true; + } + } +#endif + return false; +} + +/*! + \internal + + Moves the cursor to the given position \a pos. If \a mark is true will + adjust the currently selected text. +*/ +void QLineControl::moveCursor(int pos, bool mark) +{ + if (pos != m_cursor) { + separate(); + if (m_maskData) + pos = pos > m_cursor ? nextMaskBlank(pos) : prevMaskBlank(pos); + } + if (mark) { + int anchor; + if (m_selend > m_selstart && m_cursor == m_selstart) + anchor = m_selend; + else if (m_selend > m_selstart && m_cursor == m_selend) + anchor = m_selstart; + else + anchor = m_cursor; + m_selstart = qMin(anchor, pos); + m_selend = qMax(anchor, pos); + updateDisplayText(); + } else { + internalDeselect(); + } + m_cursor = pos; + if (mark || m_selDirty) { + m_selDirty = false; + emit selectionChanged(); + } + emitCursorPositionChanged(); +} + +/*! + \internal + + Applies the given input method event \a event to the text of the line + control +*/ +void QLineControl::processInputMethodEvent(QInputMethodEvent *event) +{ + int priorState = 0; + bool isGettingInput = !event->commitString().isEmpty() + || event->preeditString() != preeditAreaText() + || event->replacementLength() > 0; + bool cursorPositionChanged = false; + + if (isGettingInput) { + // If any text is being input, remove selected text. + priorState = m_undoState; + if (echoMode() == QLineEdit::PasswordEchoOnEdit && !passwordEchoEditing()) { + updatePasswordEchoEditing(true); + m_selstart = 0; + m_selend = m_text.length(); + } + removeSelectedText(); + } + + int c = m_cursor; // cursor position after insertion of commit string + if (event->replacementStart() <= 0) + c += event->commitString().length() - qMin(-event->replacementStart(), event->replacementLength()); + + m_cursor += event->replacementStart(); + + // insert commit string + if (event->replacementLength()) { + m_selstart = m_cursor; + m_selend = m_selstart + event->replacementLength(); + removeSelectedText(); + } + if (!event->commitString().isEmpty()) { + internalInsert(event->commitString()); + cursorPositionChanged = true; + } + + m_cursor = qMin(c, m_text.length()); + + for (int i = 0; i < event->attributes().size(); ++i) { + const QInputMethodEvent::Attribute &a = event->attributes().at(i); + if (a.type == QInputMethodEvent::Selection) { + m_cursor = qBound(0, a.start + a.length, m_text.length()); + if (a.length) { + m_selstart = qMax(0, qMin(a.start, m_text.length())); + m_selend = m_cursor; + if (m_selend < m_selstart) { + qSwap(m_selstart, m_selend); + } + } else { + m_selstart = m_selend = 0; + } + cursorPositionChanged = true; + } + } +#ifndef QT_NO_IM + setPreeditArea(m_cursor, event->preeditString()); +#endif //QT_NO_IM + const int oldPreeditCursor = m_preeditCursor; + m_preeditCursor = event->preeditString().length(); + m_hideCursor = false; + QList formats; + for (int i = 0; i < event->attributes().size(); ++i) { + const QInputMethodEvent::Attribute &a = event->attributes().at(i); + if (a.type == QInputMethodEvent::Cursor) { + m_preeditCursor = a.start; + m_hideCursor = !a.length; + } else if (a.type == QInputMethodEvent::TextFormat) { + QTextCharFormat f = qvariant_cast(a.value).toCharFormat(); + if (f.isValid()) { + QTextLayout::FormatRange o; + o.start = a.start + m_cursor; + o.length = a.length; + o.format = f; + formats.append(o); + } + } + } + m_textLayout.setAdditionalFormats(formats); + updateDisplayText(/*force*/ true); + if (cursorPositionChanged) + emitCursorPositionChanged(); + else if (m_preeditCursor != oldPreeditCursor) + emit updateMicroFocus(); + if (isGettingInput) + finishChange(priorState); +} + +/*! + \internal + + Draws the display text for the line control using the given + \a painter, \a clip, and \a offset. Which aspects of the display text + are drawn is specified by the given \a flags. + + If the flags contain DrawSelections, then the selection or input mask + backgrounds and foregrounds will be applied before drawing the text. + + If the flags contain DrawCursor a cursor of the current cursorWidth() + will be drawn after drawing the text. + + The display text will only be drawn if the flags contain DrawText +*/ +void QLineControl::draw(QPainter *painter, const QPoint &offset, const QRect &clip, int flags) +{ + QVector selections; + if (flags & DrawSelections) { + QTextLayout::FormatRange o; + if (m_selstart < m_selend) { + o.start = m_selstart; + o.length = m_selend - m_selstart; + o.format.setBackground(m_palette.brush(QPalette::Highlight)); + o.format.setForeground(m_palette.brush(QPalette::HighlightedText)); + } else { + // mask selection + if(!m_blinkPeriod || m_blinkStatus){ + o.start = m_cursor; + o.length = 1; + o.format.setBackground(m_palette.brush(QPalette::Text)); + o.format.setForeground(m_palette.brush(QPalette::Window)); + } + } + selections.append(o); + } + + if (flags & DrawText) + m_textLayout.draw(painter, offset, selections, clip); + + if (flags & DrawCursor){ + int cursor = m_cursor; + if (m_preeditCursor != -1) + cursor += m_preeditCursor; + if (!m_hideCursor && (!m_blinkPeriod || m_blinkStatus)) + m_textLayout.drawCursor(painter, offset, cursor, m_cursorWidth); + } +} + +/*! + \internal + + Sets the selection to cover the word at the given cursor position. + The word boundaries are defined by the behavior of QTextLayout::SkipWords + cursor mode. +*/ +void QLineControl::selectWordAtPos(int cursor) +{ + int next = cursor + 1; + if(next > end()) + --next; + int c = m_textLayout.previousCursorPosition(next, QTextLayout::SkipWords); + moveCursor(c, false); + // ## text layout should support end of words. + int end = m_textLayout.nextCursorPosition(c, QTextLayout::SkipWords); + while (end > cursor && m_text[end-1].isSpace()) + --end; + moveCursor(end, true); +} + +/*! + \internal + + Completes a change to the line control text. If the change is not valid + will undo the line control state back to the given \a validateFromState. + + If \a edited is true and the change is valid, will emit textEdited() in + addition to textChanged(). Otherwise only emits textChanged() on a valid + change. + + The \a update value is currently unused. +*/ +bool QLineControl::finishChange(int validateFromState, bool update, bool edited) +{ + Q_UNUSED(update) + bool lineDirty = m_selDirty; + if (m_textDirty) { + // do validation + bool wasValidInput = m_validInput; + m_validInput = true; +#ifndef QT_NO_VALIDATOR + if (m_validator) { + m_validInput = false; + QString textCopy = m_text; + int cursorCopy = m_cursor; + m_validInput = (m_validator->validate(textCopy, cursorCopy) != QValidator::Invalid); + if (m_validInput) { + if (m_text != textCopy) { + internalSetText(textCopy, cursorCopy); + return true; + } + m_cursor = cursorCopy; + } + } +#endif + if (validateFromState >= 0 && wasValidInput && !m_validInput) { + if (m_transactions.count()) + return false; + internalUndo(validateFromState); + m_history.resize(m_undoState); + if (m_modifiedState > m_undoState) + m_modifiedState = -1; + m_validInput = true; + m_textDirty = false; + } + updateDisplayText(); + lineDirty |= m_textDirty; + if (m_textDirty) { + m_textDirty = false; + QString actualText = text(); + if (edited) + emit textEdited(actualText); + emit textChanged(actualText); + } + } + if (m_selDirty) { + m_selDirty = false; + emit selectionChanged(); + } + emitCursorPositionChanged(); + return true; +} + +/*! + \internal + + An internal function for setting the text of the line control. +*/ +void QLineControl::internalSetText(const QString &txt, int pos, bool edited) +{ + internalDeselect(); + emit resetInputContext(); + QString oldText = m_text; + if (m_maskData) { + m_text = maskString(0, txt, true); + m_text += clearString(m_text.length(), m_maxLength - m_text.length()); + } else { + m_text = txt.isEmpty() ? txt : txt.left(m_maxLength); + } + m_history.clear(); + m_modifiedState = m_undoState = 0; + m_cursor = (pos < 0 || pos > m_text.length()) ? m_text.length() : pos; + m_textDirty = (oldText != m_text); + finishChange(-1, true, edited); +} + + +/*! + \internal + + Adds the given \a command to the undo history + of the line control. Does not apply the command. +*/ +void QLineControl::addCommand(const Command &cmd) +{ + if (m_separator && m_undoState && m_history[m_undoState - 1].type != Separator) { + m_history.resize(m_undoState + 2); + m_history[m_undoState++] = Command(Separator, m_cursor, 0, m_selstart, m_selend); + } else { + m_history.resize(m_undoState + 1); + } + m_separator = false; + m_history[m_undoState++] = cmd; +} + +/*! + \internal + + Inserts the given string \a s into the line + control. + + Also adds the appropriate commands into the undo history. + This function does not call finishChange(), and may leave the text + in an invalid state. +*/ +void QLineControl::internalInsert(const QString &s) +{ + if (hasSelectedText()) + addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend)); + if (m_maskData) { + QString ms = maskString(m_cursor, s); + for (int i = 0; i < (int) ms.length(); ++i) { + addCommand (Command(DeleteSelection, m_cursor + i, m_text.at(m_cursor + i), -1, -1)); + addCommand(Command(Insert, m_cursor + i, ms.at(i), -1, -1)); + } + m_text.replace(m_cursor, ms.length(), ms); + m_cursor += ms.length(); + m_cursor = nextMaskBlank(m_cursor); + m_textDirty = true; + } else { + int remaining = m_maxLength - m_text.length(); + if (remaining != 0) { + m_text.insert(m_cursor, s.left(remaining)); + for (int i = 0; i < (int) s.left(remaining).length(); ++i) + addCommand(Command(Insert, m_cursor++, s.at(i), -1, -1)); + m_textDirty = true; + } + } +} + +/*! + \internal + + deletes a single character from the current text. If \a wasBackspace, + the character prior to the cursor is removed. Otherwise the character + after the cursor is removed. + + Also adds the appropriate commands into the undo history. + This function does not call finishChange(), and may leave the text + in an invalid state. +*/ +void QLineControl::internalDelete(bool wasBackspace) +{ + if (m_cursor < (int) m_text.length()) { + if (hasSelectedText()) + addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend)); + addCommand(Command((CommandType)((m_maskData ? 2 : 0) + (wasBackspace ? Remove : Delete)), + m_cursor, m_text.at(m_cursor), -1, -1)); + if (m_maskData) { + m_text.replace(m_cursor, 1, clearString(m_cursor, 1)); + addCommand(Command(Insert, m_cursor, m_text.at(m_cursor), -1, -1)); + } else { + m_text.remove(m_cursor, 1); + } + m_textDirty = true; + } +} + +/*! + \internal + + removes the currently selected text from the line control. + + Also adds the appropriate commands into the undo history. + This function does not call finishChange(), and may leave the text + in an invalid state. +*/ +void QLineControl::removeSelectedText() +{ + if (m_selstart < m_selend && m_selend <= (int) m_text.length()) { + separate(); + int i ; + addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend)); + if (m_selstart <= m_cursor && m_cursor < m_selend) { + // cursor is within the selection. Split up the commands + // to be able to restore the correct cursor position + for (i = m_cursor; i >= m_selstart; --i) + addCommand (Command(DeleteSelection, i, m_text.at(i), -1, 1)); + for (i = m_selend - 1; i > m_cursor; --i) + addCommand (Command(DeleteSelection, i - m_cursor + m_selstart - 1, m_text.at(i), -1, -1)); + } else { + for (i = m_selend-1; i >= m_selstart; --i) + addCommand (Command(RemoveSelection, i, m_text.at(i), -1, -1)); + } + if (m_maskData) { + m_text.replace(m_selstart, m_selend - m_selstart, clearString(m_selstart, m_selend - m_selstart)); + for (int i = 0; i < m_selend - m_selstart; ++i) + addCommand(Command(Insert, m_selstart + i, m_text.at(m_selstart + i), -1, -1)); + } else { + m_text.remove(m_selstart, m_selend - m_selstart); + } + if (m_cursor > m_selstart) + m_cursor -= qMin(m_cursor, m_selend) - m_selstart; + internalDeselect(); + m_textDirty = true; + } +} + +/*! + \internal + + Parses the input mask specified by \a maskFields to generate + the mask data used to handle input masks. +*/ +void QLineControl::parseInputMask(const QString &maskFields) +{ + int delimiter = maskFields.indexOf(QLatin1Char(';')); + if (maskFields.isEmpty() || delimiter == 0) { + if (m_maskData) { + delete [] m_maskData; + m_maskData = 0; + m_maxLength = 32767; + internalSetText(QString()); + } + return; + } + + if (delimiter == -1) { + m_blank = QLatin1Char(' '); + m_inputMask = maskFields; + } else { + m_inputMask = maskFields.left(delimiter); + m_blank = (delimiter + 1 < maskFields.length()) ? maskFields[delimiter + 1] : QLatin1Char(' '); + } + + // calculate m_maxLength / m_maskData length + m_maxLength = 0; + QChar c = 0; + for (int i=0; i 0 && m_inputMask.at(i-1) == QLatin1Char('\\')) { + m_maxLength++; + continue; + } + if (c != QLatin1Char('\\') && c != QLatin1Char('!') && + c != QLatin1Char('<') && c != QLatin1Char('>') && + c != QLatin1Char('{') && c != QLatin1Char('}') && + c != QLatin1Char('[') && c != QLatin1Char(']')) + m_maxLength++; + } + + delete [] m_maskData; + m_maskData = new MaskInputData[m_maxLength]; + + MaskInputData::Casemode m = MaskInputData::NoCaseMode; + c = 0; + bool s; + bool escape = false; + int index = 0; + for (int i = 0; i < m_inputMask.length(); i++) { + c = m_inputMask.at(i); + if (escape) { + s = true; + m_maskData[index].maskChar = c; + m_maskData[index].separator = s; + m_maskData[index].caseMode = m; + index++; + escape = false; + } else if (c == QLatin1Char('<')) { + m = MaskInputData::Lower; + } else if (c == QLatin1Char('>')) { + m = MaskInputData::Upper; + } else if (c == QLatin1Char('!')) { + m = MaskInputData::NoCaseMode; + } else if (c != QLatin1Char('{') && c != QLatin1Char('}') && c != QLatin1Char('[') && c != QLatin1Char(']')) { + switch (c.unicode()) { + case 'A': + case 'a': + case 'N': + case 'n': + case 'X': + case 'x': + case '9': + case '0': + case 'D': + case 'd': + case '#': + case 'H': + case 'h': + case 'B': + case 'b': + s = false; + break; + case '\\': + escape = true; + default: + s = true; + break; + } + + if (!escape) { + m_maskData[index].maskChar = c; + m_maskData[index].separator = s; + m_maskData[index].caseMode = m; + index++; + } + } + } + internalSetText(m_text); +} + + +/*! + \internal + + checks if the key is valid compared to the inputMask +*/ +bool QLineControl::isValidInput(QChar key, QChar mask) const +{ + switch (mask.unicode()) { + case 'A': + if (key.isLetter()) + return true; + break; + case 'a': + if (key.isLetter() || key == m_blank) + return true; + break; + case 'N': + if (key.isLetterOrNumber()) + return true; + break; + case 'n': + if (key.isLetterOrNumber() || key == m_blank) + return true; + break; + case 'X': + if (key.isPrint()) + return true; + break; + case 'x': + if (key.isPrint() || key == m_blank) + return true; + break; + case '9': + if (key.isNumber()) + return true; + break; + case '0': + if (key.isNumber() || key == m_blank) + return true; + break; + case 'D': + if (key.isNumber() && key.digitValue() > 0) + return true; + break; + case 'd': + if ((key.isNumber() && key.digitValue() > 0) || key == m_blank) + return true; + break; + case '#': + if (key.isNumber() || key == QLatin1Char('+') || key == QLatin1Char('-') || key == m_blank) + return true; + break; + case 'B': + if (key == QLatin1Char('0') || key == QLatin1Char('1')) + return true; + break; + case 'b': + if (key == QLatin1Char('0') || key == QLatin1Char('1') || key == m_blank) + return true; + break; + case 'H': + if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F'))) + return true; + break; + case 'h': + if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')) || key == m_blank) + return true; + break; + default: + break; + } + return false; +} + +/*! + \internal + + Returns true if the given text \a str is valid for any + validator or input mask set for the line control. + + Otherwise returns false +*/ +bool QLineControl::hasAcceptableInput(const QString &str) const +{ +#ifndef QT_NO_VALIDATOR + QString textCopy = str; + int cursorCopy = m_cursor; + if (m_validator && m_validator->validate(textCopy, cursorCopy) + != QValidator::Acceptable) + return false; +#endif + + if (!m_maskData) + return true; + + if (str.length() != m_maxLength) + return false; + + for (int i=0; i < m_maxLength; ++i) { + if (m_maskData[i].separator) { + if (str.at(i) != m_maskData[i].maskChar) + return false; + } else { + if (!isValidInput(str.at(i), m_maskData[i].maskChar)) + return false; + } + } + return true; +} + +/*! + \internal + + Applies the inputMask on \a str starting from position \a pos in the mask. \a clear + specifies from where characters should be gotten when a separator is met in \a str - true means + that blanks will be used, false that previous input is used. + Calling this when no inputMask is set is undefined. +*/ +QString QLineControl::maskString(uint pos, const QString &str, bool clear) const +{ + if (pos >= (uint)m_maxLength) + return QString::fromLatin1(""); + + QString fill; + fill = clear ? clearString(0, m_maxLength) : m_text; + + int strIndex = 0; + QString s = QString::fromLatin1(""); + int i = pos; + while (i < m_maxLength) { + if (strIndex < str.length()) { + if (m_maskData[i].separator) { + s += m_maskData[i].maskChar; + if (str[(int)strIndex] == m_maskData[i].maskChar) + strIndex++; + ++i; + } else { + if (isValidInput(str[(int)strIndex], m_maskData[i].maskChar)) { + switch (m_maskData[i].caseMode) { + case MaskInputData::Upper: + s += str[(int)strIndex].toUpper(); + break; + case MaskInputData::Lower: + s += str[(int)strIndex].toLower(); + break; + default: + s += str[(int)strIndex]; + } + ++i; + } else { + // search for separator first + int n = findInMask(i, true, true, str[(int)strIndex]); + if (n != -1) { + if (str.length() != 1 || i == 0 || (i > 0 && (!m_maskData[i-1].separator || m_maskData[i-1].maskChar != str[(int)strIndex]))) { + s += fill.mid(i, n-i+1); + i = n + 1; // update i to find + 1 + } + } else { + // search for valid m_blank if not + n = findInMask(i, true, false, str[(int)strIndex]); + if (n != -1) { + s += fill.mid(i, n-i); + switch (m_maskData[n].caseMode) { + case MaskInputData::Upper: + s += str[(int)strIndex].toUpper(); + break; + case MaskInputData::Lower: + s += str[(int)strIndex].toLower(); + break; + default: + s += str[(int)strIndex]; + } + i = n + 1; // updates i to find + 1 + } + } + } + ++strIndex; + } + } else + break; + } + + return s; +} + + + +/*! + \internal + + Returns a "cleared" string with only separators and blank chars. + Calling this when no inputMask is set is undefined. +*/ +QString QLineControl::clearString(uint pos, uint len) const +{ + if (pos >= (uint)m_maxLength) + return QString(); + + QString s; + int end = qMin((uint)m_maxLength, pos + len); + for (int i = pos; i < end; ++i) + if (m_maskData[i].separator) + s += m_maskData[i].maskChar; + else + s += m_blank; + + return s; +} + +/*! + \internal + + Strips blank parts of the input in a QLineControl when an inputMask is set, + separators are still included. Typically "127.0__.0__.1__" becomes "127.0.0.1". +*/ +QString QLineControl::stripString(const QString &str) const +{ + if (!m_maskData) + return str; + + QString s; + int end = qMin(m_maxLength, (int)str.length()); + for (int i = 0; i < end; ++i) + if (m_maskData[i].separator) + s += m_maskData[i].maskChar; + else + if (str[i] != m_blank) + s += str[i]; + + return s; +} + +/*! + \internal + searches forward/backward in m_maskData for either a separator or a m_blank +*/ +int QLineControl::findInMask(int pos, bool forward, bool findSeparator, QChar searchChar) const +{ + if (pos >= m_maxLength || pos < 0) + return -1; + + int end = forward ? m_maxLength : -1; + int step = forward ? 1 : -1; + int i = pos; + + while (i != end) { + if (findSeparator) { + if (m_maskData[i].separator && m_maskData[i].maskChar == searchChar) + return i; + } else { + if (!m_maskData[i].separator) { + if (searchChar.isNull()) + return i; + else if (isValidInput(searchChar, m_maskData[i].maskChar)) + return i; + } + } + i += step; + } + return -1; +} + +void QLineControl::internalUndo(int until) +{ + if (!isUndoAvailable()) + return; + internalDeselect(); + while (m_undoState && m_undoState > until) { + Command& cmd = m_history[--m_undoState]; + switch (cmd.type) { + case Insert: + m_text.remove(cmd.pos, 1); + m_cursor = cmd.pos; + break; + case SetSelection: + m_selstart = cmd.selStart; + m_selend = cmd.selEnd; + m_cursor = cmd.pos; + break; + case Remove: + case RemoveSelection: + m_text.insert(cmd.pos, cmd.uc); + m_cursor = cmd.pos + 1; + break; + case Delete: + case DeleteSelection: + m_text.insert(cmd.pos, cmd.uc); + m_cursor = cmd.pos; + break; + case Separator: + continue; + } + if (until < 0 && m_undoState) { + Command& next = m_history[m_undoState-1]; + if (next.type != cmd.type && next.type < RemoveSelection + && (cmd.type < RemoveSelection || next.type == Separator)) + break; + } + } + m_textDirty = true; + emitCursorPositionChanged(); +} + +void QLineControl::internalRedo() +{ + if (!isRedoAvailable()) + return; + internalDeselect(); + while (m_undoState < (int)m_history.size()) { + Command& cmd = m_history[m_undoState++]; + switch (cmd.type) { + case Insert: + m_text.insert(cmd.pos, cmd.uc); + m_cursor = cmd.pos + 1; + break; + case SetSelection: + m_selstart = cmd.selStart; + m_selend = cmd.selEnd; + m_cursor = cmd.pos; + break; + case Remove: + case Delete: + case RemoveSelection: + case DeleteSelection: + m_text.remove(cmd.pos, 1); + m_selstart = cmd.selStart; + m_selend = cmd.selEnd; + m_cursor = cmd.pos; + break; + case Separator: + m_selstart = cmd.selStart; + m_selend = cmd.selEnd; + m_cursor = cmd.pos; + break; + } + if (m_undoState < (int)m_history.size()) { + Command& next = m_history[m_undoState]; + if (next.type != cmd.type && cmd.type < RemoveSelection && next.type != Separator + && (next.type < RemoveSelection || cmd.type == Separator)) + break; + } + } + m_textDirty = true; + emitCursorPositionChanged(); +} + +/*! + \internal + + If the current cursor position differs from the last emitted cursor + position, emits cursorPositionChanged(). +*/ +void QLineControl::emitCursorPositionChanged() +{ + if (m_cursor != m_lastCursorPos) { + const int oldLast = m_lastCursorPos; + m_lastCursorPos = m_cursor; + cursorPositionChanged(oldLast, m_cursor); + } +} + +#ifndef QT_NO_COMPLETER +// iterating forward(dir=1)/backward(dir=-1) from the +// current row based. dir=0 indicates a new completion prefix was set. +bool QLineControl::advanceToEnabledItem(int dir) +{ + int start = m_completer->currentRow(); + if (start == -1) + return false; + int i = start + dir; + if (dir == 0) dir = 1; + do { + if (!m_completer->setCurrentRow(i)) { + if (!m_completer->wrapAround()) + break; + i = i > 0 ? 0 : m_completer->completionCount() - 1; + } else { + QModelIndex currentIndex = m_completer->currentIndex(); + if (m_completer->completionModel()->flags(currentIndex) & Qt::ItemIsEnabled) + return true; + i += dir; + } + } while (i != start); + + m_completer->setCurrentRow(start); // restore + return false; +} + +void QLineControl::complete(int key) +{ + if (!m_completer || isReadOnly() || echoMode() != QLineEdit::Normal) + return; + + QString text = this->text(); + if (m_completer->completionMode() == QCompleter::InlineCompletion) { + if (key == Qt::Key_Backspace) + return; + int n = 0; + if (key == Qt::Key_Up || key == Qt::Key_Down) { + if (textAfterSelection().length()) + return; + QString prefix = hasSelectedText() ? textBeforeSelection() + : text; + if (text.compare(m_completer->currentCompletion(), m_completer->caseSensitivity()) != 0 + || prefix.compare(m_completer->completionPrefix(), m_completer->caseSensitivity()) != 0) { + m_completer->setCompletionPrefix(prefix); + } else { + n = (key == Qt::Key_Up) ? -1 : +1; + } + } else { + m_completer->setCompletionPrefix(text); + } + if (!advanceToEnabledItem(n)) + return; + } else { +#ifndef QT_KEYPAD_NAVIGATION + if (text.isEmpty()) { + m_completer->popup()->hide(); + return; + } +#endif + m_completer->setCompletionPrefix(text); + } + + m_completer->complete(); +} +#endif + +void QLineControl::setCursorBlinkPeriod(int msec) +{ + if (msec == m_blinkPeriod) + return; + if (m_blinkTimer) { + killTimer(m_blinkTimer); + } + if (msec) { + m_blinkTimer = startTimer(msec / 2); + m_blinkStatus = 1; + } else { + m_blinkTimer = 0; + if (m_blinkStatus == 1) + emit updateNeeded(inputMask().isEmpty() ? cursorRect() : QRect()); + } + m_blinkPeriod = msec; +} + +void QLineControl::resetCursorBlinkTimer() +{ + if (m_blinkPeriod == 0 || m_blinkTimer == 0) + return; + killTimer(m_blinkTimer); + m_blinkTimer = startTimer(m_blinkPeriod / 2); + m_blinkStatus = 1; +} + +void QLineControl::timerEvent(QTimerEvent *event) +{ + if (event->timerId() == m_blinkTimer) { + m_blinkStatus = !m_blinkStatus; + emit updateNeeded(inputMask().isEmpty() ? cursorRect() : QRect()); + } else if (event->timerId() == m_deleteAllTimer) { + killTimer(m_deleteAllTimer); + m_deleteAllTimer = 0; + clear(); + } else if (event->timerId() == m_tripleClickTimer) { + killTimer(m_tripleClickTimer); + m_tripleClickTimer = 0; + } +} + +bool QLineControl::processEvent(QEvent* ev) +{ +#ifdef QT_KEYPAD_NAVIGATION + if (QApplication::keypadNavigationEnabled()) { + if ((ev->type() == QEvent::KeyPress) || (ev->type() == QEvent::KeyRelease)) { + QKeyEvent *ke = (QKeyEvent *)ev; + if (ke->key() == Qt::Key_Back) { + if (ke->isAutoRepeat()) { + // Swallow it. We don't want back keys running amok. + ke->accept(); + return true; + } + if ((ev->type() == QEvent::KeyRelease) + && !isReadOnly() + && m_deleteAllTimer) { + killTimer(m_deleteAllTimer); + m_deleteAllTimer = 0; + backspace(); + ke->accept(); + return true; + } + } + } + } +#endif + switch(ev->type()){ +#ifndef QT_NO_GRAPHICSVIEW + case QEvent::GraphicsSceneMouseDoubleClick: + case QEvent::GraphicsSceneMouseMove: + case QEvent::GraphicsSceneMouseRelease: + case QEvent::GraphicsSceneMousePress:{ + QGraphicsSceneMouseEvent *gvEv = static_cast(ev); + QMouseEvent* mouse = new QMouseEvent(ev->type(), + gvEv->pos().toPoint(), gvEv->button(), gvEv->buttons(), gvEv->modifiers()); + processMouseEvent(mouse); break; + } +#endif + case QEvent::MouseButtonPress: + case QEvent::MouseButtonRelease: + case QEvent::MouseButtonDblClick: + case QEvent::MouseMove: + processMouseEvent(static_cast(ev)); break; + case QEvent::KeyPress: + case QEvent::KeyRelease: + processKeyEvent(static_cast(ev)); break; + case QEvent::InputMethod: + processInputMethodEvent(static_cast(ev)); break; +#ifndef QT_NO_SHORTCUT + case QEvent::ShortcutOverride:{ + if (isReadOnly()) + return false; + QKeyEvent* ke = static_cast(ev); + if (ke == QKeySequence::Copy + || ke == QKeySequence::Paste + || ke == QKeySequence::Cut + || ke == QKeySequence::Redo + || ke == QKeySequence::Undo + || ke == QKeySequence::MoveToNextWord + || ke == QKeySequence::MoveToPreviousWord + || ke == QKeySequence::MoveToStartOfDocument + || ke == QKeySequence::MoveToEndOfDocument + || ke == QKeySequence::SelectNextWord + || ke == QKeySequence::SelectPreviousWord + || ke == QKeySequence::SelectStartOfLine + || ke == QKeySequence::SelectEndOfLine + || ke == QKeySequence::SelectStartOfBlock + || ke == QKeySequence::SelectEndOfBlock + || ke == QKeySequence::SelectStartOfDocument + || ke == QKeySequence::SelectAll + || ke == QKeySequence::SelectEndOfDocument) { + ke->accept(); + } else if (ke->modifiers() == Qt::NoModifier || ke->modifiers() == Qt::ShiftModifier + || ke->modifiers() == Qt::KeypadModifier) { + if (ke->key() < Qt::Key_Escape) { + ke->accept(); + } else { + switch (ke->key()) { + case Qt::Key_Delete: + case Qt::Key_Home: + case Qt::Key_End: + case Qt::Key_Backspace: + case Qt::Key_Left: + case Qt::Key_Right: + ke->accept(); + default: + break; + } + } + } + } +#endif + default: + return false; + } + return true; +} + +void QLineControl::processMouseEvent(QMouseEvent* ev) +{ + + switch (ev->type()) { + case QEvent::GraphicsSceneMousePress: + case QEvent::MouseButtonPress:{ + if (m_tripleClickTimer + && (ev->pos() - m_tripleClick).manhattanLength() + < QApplication::startDragDistance()) { + selectAll(); + return; + } + if (ev->button() == Qt::RightButton) + return; + + bool mark = ev->modifiers() & Qt::ShiftModifier; + int cursor = xToPos(ev->pos().x()); + moveCursor(cursor, mark); + break; + } + case QEvent::GraphicsSceneMouseDoubleClick: + case QEvent::MouseButtonDblClick: + if (ev->button() == Qt::LeftButton) { + selectWordAtPos(xToPos(ev->pos().x())); + if (m_tripleClickTimer) + killTimer(m_tripleClickTimer); + m_tripleClickTimer = startTimer(QApplication::doubleClickInterval()); + m_tripleClick = ev->pos(); + } + break; + case QEvent::GraphicsSceneMouseRelease: + case QEvent::MouseButtonRelease: +#ifndef QT_NO_CLIPBOARD + if (QApplication::clipboard()->supportsSelection()) { + if (ev->button() == Qt::LeftButton) { + copy(QClipboard::Selection); + } else if (!isReadOnly() && ev->button() == Qt::MidButton) { + deselect(); + insert(QApplication::clipboard()->text(QClipboard::Selection)); + } + } +#endif + break; + case QEvent::GraphicsSceneMouseMove: + case QEvent::MouseMove: + if (ev->buttons() & Qt::LeftButton) { + moveCursor(xToPos(ev->pos().x()), true); + } + break; + default: + break; + } +} + +void QLineControl::processKeyEvent(QKeyEvent* event) +{ + bool inlineCompletionAccepted = false; + +#ifndef QT_NO_COMPLETER + if (m_completer) { + QCompleter::CompletionMode completionMode = m_completer->completionMode(); + if ((completionMode == QCompleter::PopupCompletion + || completionMode == QCompleter::UnfilteredPopupCompletion) + && m_completer->popup() + && m_completer->popup()->isVisible()) { + // The following keys are forwarded by the completer to the widget + // Ignoring the events lets the completer provide suitable default behavior + switch (event->key()) { + case Qt::Key_Escape: + event->ignore(); + return; + case Qt::Key_Enter: + case Qt::Key_Return: + case Qt::Key_F4: +#ifdef QT_KEYPAD_NAVIGATION + case Qt::Key_Select: + if (!QApplication::keypadNavigationEnabled()) + break; +#endif + m_completer->popup()->hide(); // just hide. will end up propagating to parent + default: + break; // normal key processing + } + } else if (completionMode == QCompleter::InlineCompletion) { + switch (event->key()) { + case Qt::Key_Enter: + case Qt::Key_Return: + case Qt::Key_F4: +#ifdef QT_KEYPAD_NAVIGATION + case Qt::Key_Select: + if (!QApplication::keypadNavigationEnabled()) + break; +#endif + if (!m_completer->currentCompletion().isEmpty() && hasSelectedText() + && textAfterSelection().isEmpty()) { + setText(m_completer->currentCompletion()); + inlineCompletionAccepted = true; + } + default: + break; // normal key processing + } + } + } +#endif // QT_NO_COMPLETER + + if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { + if (hasAcceptableInput() || fixup()) { + emit accepted(); + emit editingFinished(); + } + if (inlineCompletionAccepted) + event->accept(); + else + event->ignore(); + return; + } + + if (echoMode() == QLineEdit::PasswordEchoOnEdit + && !passwordEchoEditing() + && !isReadOnly() + && !event->text().isEmpty() +#ifdef QT_KEYPAD_NAVIGATION + && event->key() != Qt::Key_Select + && event->key() != Qt::Key_Up + && event->key() != Qt::Key_Down + && event->key() != Qt::Key_Back +#endif + && !(event->modifiers() & Qt::ControlModifier)) { + // Clear the edit and reset to normal echo mode while editing; the + // echo mode switches back when the edit loses focus + // ### resets current content. dubious code; you can + // navigate with keys up, down, back, and select(?), but if you press + // "left" or "right" it clears? + updatePasswordEchoEditing(true); + clear(); + } + + bool unknown = false; + bool visual = cursorMoveStyle() == QTextCursor::Visual; + + if (false) { + } +#ifndef QT_NO_SHORTCUT + else if (event == QKeySequence::Undo) { + if (!isReadOnly()) + undo(); + } + else if (event == QKeySequence::Redo) { + if (!isReadOnly()) + redo(); + } + else if (event == QKeySequence::SelectAll) { + selectAll(); + } +#ifndef QT_NO_CLIPBOARD + else if (event == QKeySequence::Copy) { + copy(); + } + else if (event == QKeySequence::Paste) { + if (!isReadOnly()) { + QClipboard::Mode mode = QClipboard::Clipboard; +#ifdef Q_WS_X11 + if (event->modifiers() == (Qt::CTRL | Qt::SHIFT) && event->key() == Qt::Key_Insert) + mode = QClipboard::Selection; +#endif + paste(mode); + } + } + else if (event == QKeySequence::Cut) { + if (!isReadOnly()) { + copy(); + del(); + } + } + else if (event == QKeySequence::DeleteEndOfLine) { + if (!isReadOnly()) { + setSelection(cursor(), end()); + copy(); + del(); + } + } +#endif //QT_NO_CLIPBOARD + else if (event == QKeySequence::MoveToStartOfLine || event == QKeySequence::MoveToStartOfBlock) { + home(0); + } + else if (event == QKeySequence::MoveToEndOfLine || event == QKeySequence::MoveToEndOfBlock) { + end(0); + } + else if (event == QKeySequence::SelectStartOfLine || event == QKeySequence::SelectStartOfBlock) { + home(1); + } + else if (event == QKeySequence::SelectEndOfLine || event == QKeySequence::SelectEndOfBlock) { + end(1); + } + else if (event == QKeySequence::MoveToNextChar) { +#if !defined(Q_WS_WIN) || defined(QT_NO_COMPLETER) + if (hasSelectedText()) { +#else + if (hasSelectedText() && m_completer + && m_completer->completionMode() == QCompleter::InlineCompletion) { +#endif + moveCursor(selectionEnd(), false); + } else { + cursorForward(0, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1)); + } + } + else if (event == QKeySequence::SelectNextChar) { + cursorForward(1, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1)); + } + else if (event == QKeySequence::MoveToPreviousChar) { +#if !defined(Q_WS_WIN) || defined(QT_NO_COMPLETER) + if (hasSelectedText()) { +#else + if (hasSelectedText() && m_completer + && m_completer->completionMode() == QCompleter::InlineCompletion) { +#endif + moveCursor(selectionStart(), false); + } else { + cursorForward(0, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1)); + } + } + else if (event == QKeySequence::SelectPreviousChar) { + cursorForward(1, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1)); + } + else if (event == QKeySequence::MoveToNextWord) { + if (echoMode() == QLineEdit::Normal) + layoutDirection() == Qt::LeftToRight ? cursorWordForward(0) : cursorWordBackward(0); + else + layoutDirection() == Qt::LeftToRight ? end(0) : home(0); + } + else if (event == QKeySequence::MoveToPreviousWord) { + if (echoMode() == QLineEdit::Normal) + layoutDirection() == Qt::LeftToRight ? cursorWordBackward(0) : cursorWordForward(0); + else if (!isReadOnly()) { + layoutDirection() == Qt::LeftToRight ? home(0) : end(0); + } + } + else if (event == QKeySequence::SelectNextWord) { + if (echoMode() == QLineEdit::Normal) + layoutDirection() == Qt::LeftToRight ? cursorWordForward(1) : cursorWordBackward(1); + else + layoutDirection() == Qt::LeftToRight ? end(1) : home(1); + } + else if (event == QKeySequence::SelectPreviousWord) { + if (echoMode() == QLineEdit::Normal) + layoutDirection() == Qt::LeftToRight ? cursorWordBackward(1) : cursorWordForward(1); + else + layoutDirection() == Qt::LeftToRight ? home(1) : end(1); + } + else if (event == QKeySequence::Delete) { + if (!isReadOnly()) + del(); + } + else if (event == QKeySequence::DeleteEndOfWord) { + if (!isReadOnly()) { + cursorWordForward(true); + del(); + } + } + else if (event == QKeySequence::DeleteStartOfWord) { + if (!isReadOnly()) { + cursorWordBackward(true); + del(); + } + } +#endif // QT_NO_SHORTCUT + else { + bool handled = false; +#ifdef Q_WS_MAC + if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) { + Qt::KeyboardModifiers myModifiers = (event->modifiers() & ~Qt::KeypadModifier); + if (myModifiers & Qt::ShiftModifier) { + if (myModifiers == (Qt::ControlModifier|Qt::ShiftModifier) + || myModifiers == (Qt::AltModifier|Qt::ShiftModifier) + || myModifiers == Qt::ShiftModifier) { + + event->key() == Qt::Key_Up ? home(1) : end(1); + } + } else { + if ((myModifiers == Qt::ControlModifier + || myModifiers == Qt::AltModifier + || myModifiers == Qt::NoModifier)) { + event->key() == Qt::Key_Up ? home(0) : end(0); + } + } + handled = true; + } +#endif + if (event->modifiers() & Qt::ControlModifier) { + switch (event->key()) { + case Qt::Key_Backspace: + if (!isReadOnly()) { + cursorWordBackward(true); + del(); + } + break; +#ifndef QT_NO_COMPLETER + case Qt::Key_Up: + case Qt::Key_Down: + complete(event->key()); + break; +#endif +#if defined(Q_WS_X11) + case Qt::Key_E: + end(0); + break; + + case Qt::Key_U: + if (!isReadOnly()) { + setSelection(0, text().size()); +#ifndef QT_NO_CLIPBOARD + copy(); +#endif + del(); + } + break; +#endif + default: + if (!handled) + unknown = true; + } + } else { // ### check for *no* modifier + switch (event->key()) { + case Qt::Key_Backspace: + if (!isReadOnly()) { + backspace(); +#ifndef QT_NO_COMPLETER + complete(Qt::Key_Backspace); +#endif + } + break; +#ifdef QT_KEYPAD_NAVIGATION + case Qt::Key_Back: + if (QApplication::keypadNavigationEnabled() && !event->isAutoRepeat() + && !isReadOnly()) { + if (text().length() == 0) { + setText(m_cancelText); + + if (passwordEchoEditing()) + updatePasswordEchoEditing(false); + + emit editFocusChange(false); + } else if (!m_deleteAllTimer) { + m_deleteAllTimer = startTimer(750); + } + } else { + unknown = true; + } + break; +#endif + default: + if (!handled) + unknown = true; + } + } + } + + if (event->key() == Qt::Key_Direction_L || event->key() == Qt::Key_Direction_R) { + setLayoutDirection((event->key() == Qt::Key_Direction_L) ? Qt::LeftToRight : Qt::RightToLeft); + unknown = false; + } + + if (unknown && !isReadOnly()) { + QString t = event->text(); + if (!t.isEmpty() && t.at(0).isPrint()) { + insert(t); +#ifndef QT_NO_COMPLETER + complete(event->key()); +#endif + event->accept(); + return; + } + } + + if (unknown) + event->ignore(); + else + event->accept(); +} + + +QT_END_NAMESPACE + +#endif diff --git a/src/gui/text/qlinecontrol_p.h b/src/gui/text/qlinecontrol_p.h new file mode 100644 index 0000000000..0042f17261 --- /dev/null +++ b/src/gui/text/qlinecontrol_p.h @@ -0,0 +1,456 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QLINECONTROL_P_H +#define QLINECONTROL_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "QtCore/qglobal.h" + +#ifndef QT_NO_LINEEDIT +#include "private/qwidget_p.h" +#include "QtGui/qlineedit.h" +#include "QtGui/qtextlayout.h" +#include "QtGui/qstyleoption.h" +#include "QtCore/qpointer.h" +#include "QtGui/qlineedit.h" +#include "QtGui/qclipboard.h" +#include "QtCore/qpoint.h" +#include "QtGui/qcompleter.h" + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Gui) + +class Q_GUI_EXPORT QLineControl : public QObject +{ + Q_OBJECT + +public: + QLineControl(const QString &txt = QString()) + : m_cursor(0), m_preeditCursor(0), m_cursorWidth(0), m_layoutDirection(Qt::LayoutDirectionAuto), + m_hideCursor(false), m_separator(0), m_readOnly(0), + m_dragEnabled(0), m_echoMode(0), m_textDirty(0), m_selDirty(0), + m_validInput(1), m_blinkStatus(0), m_blinkPeriod(0), m_blinkTimer(0), m_deleteAllTimer(0), + m_ascent(0), m_maxLength(32767), m_lastCursorPos(-1), + m_tripleClickTimer(0), m_maskData(0), m_modifiedState(0), m_undoState(0), + m_selstart(0), m_selend(0), m_passwordEchoEditing(false) + { + init(txt); + } + + ~QLineControl() + { + delete [] m_maskData; + } + + int nextMaskBlank(int pos) + { + int c = findInMask(pos, true, false); + m_separator |= (c != pos); + return (c != -1 ? c : m_maxLength); + } + + int prevMaskBlank(int pos) + { + int c = findInMask(pos, false, false); + m_separator |= (c != pos); + return (c != -1 ? c : 0); + } + + bool isUndoAvailable() const { return !m_readOnly && m_undoState; } + bool isRedoAvailable() const { return !m_readOnly && m_undoState < (int)m_history.size(); } + void clearUndo() { m_history.clear(); m_modifiedState = m_undoState = 0; } + + bool isModified() const { return m_modifiedState != m_undoState; } + void setModified(bool modified) { m_modifiedState = modified ? -1 : m_undoState; } + + bool allSelected() const { return !m_text.isEmpty() && m_selstart == 0 && m_selend == (int)m_text.length(); } + bool hasSelectedText() const { return !m_text.isEmpty() && m_selend > m_selstart; } + + int width() const { return qRound(m_textLayout.lineAt(0).width()) + 1; } + int height() const { return qRound(m_textLayout.lineAt(0).height()) + 1; } + int ascent() const { return m_ascent; } + qreal naturalTextWidth() const { return m_textLayout.lineAt(0).naturalTextWidth(); } + + void setSelection(int start, int length); + + inline QString selectedText() const { return hasSelectedText() ? m_text.mid(m_selstart, m_selend - m_selstart) : QString(); } + QString textBeforeSelection() const { return hasSelectedText() ? m_text.left(m_selstart) : QString(); } + QString textAfterSelection() const { return hasSelectedText() ? m_text.mid(m_selend) : QString(); } + + int selectionStart() const { return hasSelectedText() ? m_selstart : -1; } + int selectionEnd() const { return hasSelectedText() ? m_selend : -1; } + bool inSelection(int x) const + { + if (m_selstart >= m_selend) + return false; + int pos = xToPos(x, QTextLine::CursorOnCharacter); + return pos >= m_selstart && pos < m_selend; + } + + void removeSelection() + { + int priorState = m_undoState; + removeSelectedText(); + finishChange(priorState); + } + + int start() const { return 0; } + int end() const { return m_text.length(); } + +#ifndef QT_NO_CLIPBOARD + void copy(QClipboard::Mode mode = QClipboard::Clipboard) const; + void paste(QClipboard::Mode mode = QClipboard::Clipboard); +#endif + + int cursor() const{ return m_cursor; } + int preeditCursor() const { return m_preeditCursor; } + + int cursorWidth() const { return m_cursorWidth; } + void setCursorWidth(int value) { m_cursorWidth = value; } + + QTextCursor::MoveStyle cursorMoveStyle() const { return m_textLayout.cursorMoveStyle(); } + void setCursorMoveStyle(QTextCursor::MoveStyle style) { m_textLayout.setCursorMoveStyle(style); } + + void moveCursor(int pos, bool mark = false); + void cursorForward(bool mark, int steps) + { + int c = m_cursor; + if (steps > 0) { + while (steps--) + c = cursorMoveStyle() == QTextCursor::Visual ? m_textLayout.rightCursorPosition(c) + : m_textLayout.nextCursorPosition(c); + } else if (steps < 0) { + while (steps++) + c = cursorMoveStyle() == QTextCursor::Visual ? m_textLayout.leftCursorPosition(c) + : m_textLayout.previousCursorPosition(c); + } + moveCursor(c, mark); + } + + void cursorWordForward(bool mark) { moveCursor(m_textLayout.nextCursorPosition(m_cursor, QTextLayout::SkipWords), mark); } + void cursorWordBackward(bool mark) { moveCursor(m_textLayout.previousCursorPosition(m_cursor, QTextLayout::SkipWords), mark); } + + void home(bool mark) { moveCursor(0, mark); } + void end(bool mark) { moveCursor(text().length(), mark); } + + int xToPos(int x, QTextLine::CursorPosition = QTextLine::CursorBetweenCharacters) const; + QRect cursorRect() const; + + qreal cursorToX(int cursor) const { return m_textLayout.lineAt(0).cursorToX(cursor); } + qreal cursorToX() const + { + int cursor = m_cursor; + if (m_preeditCursor != -1) + cursor += m_preeditCursor; + return cursorToX(cursor); + } + + bool isReadOnly() const { return m_readOnly; } + void setReadOnly(bool enable) { m_readOnly = enable; } + + QString text() const + { + QString res = m_maskData ? stripString(m_text) : m_text; + return (res.isNull() ? QString::fromLatin1("") : res); + } + void setText(const QString &txt) { internalSetText(txt, -1, false); } + QString displayText() const { return m_textLayout.text(); } + + void backspace(); + void del(); + void deselect() { internalDeselect(); finishChange(); } + void selectAll() { m_selstart = m_selend = m_cursor = 0; moveCursor(m_text.length(), true); } + + void insert(const QString &); + void clear(); + void undo() { internalUndo(); finishChange(-1, true); } + void redo() { internalRedo(); finishChange(); } + void selectWordAtPos(int); + + uint echoMode() const { return m_echoMode; } + void setEchoMode(uint mode) + { + m_echoMode = mode; + m_passwordEchoEditing = false; + updateDisplayText(); + } + + int maxLength() const { return m_maxLength; } + void setMaxLength(int maxLength) + { + if (m_maskData) + return; + m_maxLength = maxLength; + setText(m_text); + } + +#ifndef QT_NO_VALIDATOR + const QValidator *validator() const { return m_validator; } + void setValidator(const QValidator *v) { m_validator = const_cast(v); } +#endif + +#ifndef QT_NO_COMPLETER + QCompleter *completer() const { return m_completer; } + /* Note that you must set the widget for the completer separately */ + void setCompleter(const QCompleter *c) { m_completer = const_cast(c); } + void complete(int key); +#endif + + int cursorPosition() const { return m_cursor; } + void setCursorPosition(int pos) { if (pos <= m_text.length()) moveCursor(qMax(0, pos)); } + + bool hasAcceptableInput() const { return hasAcceptableInput(m_text); } + bool fixup(); + + QString inputMask() const { return m_maskData ? m_inputMask + QLatin1Char(';') + m_blank : QString(); } + void setInputMask(const QString &mask) + { + parseInputMask(mask); + if (m_maskData) + moveCursor(nextMaskBlank(0)); + } + + // input methods +#ifndef QT_NO_IM + bool composeMode() const { return !m_textLayout.preeditAreaText().isEmpty(); } + void setPreeditArea(int cursor, const QString &text) { m_textLayout.setPreeditArea(cursor, text); } +#endif + + QString preeditAreaText() const { return m_textLayout.preeditAreaText(); } + + void updatePasswordEchoEditing(bool editing); + bool passwordEchoEditing() const { return m_passwordEchoEditing; } + + QChar passwordCharacter() const { return m_passwordCharacter; } + void setPasswordCharacter(const QChar &character) { m_passwordCharacter = character; updateDisplayText(); } + + Qt::LayoutDirection layoutDirection() const { + if (m_layoutDirection == Qt::LayoutDirectionAuto) { + if (m_text.isEmpty()) + return QApplication::keyboardInputDirection(); + return m_text.isRightToLeft() ? Qt::RightToLeft : Qt::LeftToRight; + } + return m_layoutDirection; + } + void setLayoutDirection(Qt::LayoutDirection direction) + { + if (direction != m_layoutDirection) { + m_layoutDirection = direction; + updateDisplayText(); + } + } + + void setFont(const QFont &font) { m_textLayout.setFont(font); updateDisplayText(); } + + void processInputMethodEvent(QInputMethodEvent *event); + void processMouseEvent(QMouseEvent* ev); + void processKeyEvent(QKeyEvent* ev); + + int cursorBlinkPeriod() const { return m_blinkPeriod; } + void setCursorBlinkPeriod(int msec); + void resetCursorBlinkTimer(); + + QString cancelText() const { return m_cancelText; } + void setCancelText(const QString &text) { m_cancelText = text; } + + const QPalette &palette() const { return m_palette; } + void setPalette(const QPalette &p) { m_palette = p; } + + enum DrawFlags { + DrawText = 0x01, + DrawSelections = 0x02, + DrawCursor = 0x04, + DrawAll = DrawText | DrawSelections | DrawCursor + }; + void draw(QPainter *, const QPoint &, const QRect &, int flags = DrawAll); + + bool processEvent(QEvent *ev); + +private: + void init(const QString &txt); + void removeSelectedText(); + void internalSetText(const QString &txt, int pos = -1, bool edited = true); + void updateDisplayText(bool forceUpdate = false); + + void internalInsert(const QString &s); + void internalDelete(bool wasBackspace = false); + void internalRemove(int pos); + + inline void internalDeselect() + { + m_selDirty |= (m_selend > m_selstart); + m_selstart = m_selend = 0; + } + + void internalUndo(int until = -1); + void internalRedo(); + + QString m_text; + QPalette m_palette; + int m_cursor; + int m_preeditCursor; + int m_cursorWidth; + Qt::LayoutDirection m_layoutDirection; + uint m_hideCursor : 1; // used to hide the m_cursor inside preedit areas + uint m_separator : 1; + uint m_readOnly : 1; + uint m_dragEnabled : 1; + uint m_echoMode : 2; + uint m_textDirty : 1; + uint m_selDirty : 1; + uint m_validInput : 1; + uint m_blinkStatus : 1; + int m_blinkPeriod; // 0 for non-blinking cursor + int m_blinkTimer; + int m_deleteAllTimer; + int m_ascent; + int m_maxLength; + int m_lastCursorPos; + QList m_transactions; + QPoint m_tripleClick; + int m_tripleClickTimer; + QString m_cancelText; + + void emitCursorPositionChanged(); + + bool finishChange(int validateFromState = -1, bool update = false, bool edited = true); + +#ifndef QT_NO_VALIDATOR + QPointer m_validator; +#endif + QPointer m_completer; +#ifndef QT_NO_COMPLETER + bool advanceToEnabledItem(int dir); +#endif + + struct MaskInputData { + enum Casemode { NoCaseMode, Upper, Lower }; + QChar maskChar; // either the separator char or the inputmask + bool separator; + Casemode caseMode; + }; + QString m_inputMask; + QChar m_blank; + MaskInputData *m_maskData; + + // undo/redo handling + enum CommandType { Separator, Insert, Remove, Delete, RemoveSelection, DeleteSelection, SetSelection }; + struct Command { + inline Command() {} + inline Command(CommandType t, int p, QChar c, int ss, int se) : type(t),uc(c),pos(p),selStart(ss),selEnd(se) {} + uint type : 4; + QChar uc; + int pos, selStart, selEnd; + }; + int m_modifiedState; + int m_undoState; + QVector m_history; + void addCommand(const Command& cmd); + + inline void separate() { m_separator = true; } + + // selection + int m_selstart; + int m_selend; + + // masking + void parseInputMask(const QString &maskFields); + bool isValidInput(QChar key, QChar mask) const; + bool hasAcceptableInput(const QString &text) const; + QString maskString(uint pos, const QString &str, bool clear = false) const; + QString clearString(uint pos, uint len) const; + QString stripString(const QString &str) const; + int findInMask(int pos, bool forward, bool findSeparator, QChar searchChar = QChar()) const; + + // complex text layout + QTextLayout m_textLayout; + + bool m_passwordEchoEditing; + QChar m_passwordCharacter; + +Q_SIGNALS: + void cursorPositionChanged(int, int); + void selectionChanged(); + + void displayTextChanged(const QString &); + void textChanged(const QString &); + void textEdited(const QString &); + + void resetInputContext(); + void updateMicroFocus(); + + void accepted(); + void editingFinished(); + void updateNeeded(const QRect &); + +#ifdef QT_KEYPAD_NAVIGATION + void editFocusChange(bool); +#endif +protected: + virtual void timerEvent(QTimerEvent *event); + +private Q_SLOTS: + void _q_clipboardChanged(); + void _q_deleteSelected(); + +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QT_NO_LINEEDIT + +#endif // QLINECONTROL_P_H diff --git a/src/gui/text/text.pri b/src/gui/text/text.pri index ba6ddb32f0..7a9aee62fd 100644 --- a/src/gui/text/text.pri +++ b/src/gui/text/text.pri @@ -9,7 +9,8 @@ HEADERS += \ text/qfontmetrics.h \ text/qfont_p.h \ text/qfontsubset_p.h \ - text/qtextcontrol_p.h \ + text/qlinecontrol_p.h \ + text/qtextcontrol_p.h \ text/qtextcontrol_p_p.h \ text/qtextengine_p.h \ text/qtextlayout.h \ @@ -51,7 +52,8 @@ SOURCES += \ text/qfontsubset.cpp \ text/qfontmetrics.cpp \ text/qfontdatabase.cpp \ - text/qtextcontrol.cpp \ + text/qlinecontrol.cpp \ + text/qtextcontrol.cpp \ text/qtextengine.cpp \ text/qtextlayout.cpp \ text/qtextformat.cpp \ diff --git a/src/gui/widgets/qlinecontrol.cpp b/src/gui/widgets/qlinecontrol.cpp deleted file mode 100644 index eb4e142328..0000000000 --- a/src/gui/widgets/qlinecontrol.cpp +++ /dev/null @@ -1,1833 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qlinecontrol_p.h" - -#ifndef QT_NO_LINEEDIT - -#include "qabstractitemview.h" -#include "qclipboard.h" -#ifndef QT_NO_ACCESSIBILITY -#include "qaccessible.h" -#endif -#ifndef QT_NO_IM -#include "qinputcontext.h" -#include "qlist.h" -#endif -#include "qapplication.h" -#ifndef QT_NO_GRAPHICSVIEW -#include "qgraphicssceneevent.h" -#endif - -QT_BEGIN_NAMESPACE - -/*! - \internal - - Updates the display text based of the current edit text - If the text has changed will emit displayTextChanged() -*/ -void QLineControl::updateDisplayText(bool forceUpdate) -{ - QString orig = m_textLayout.text(); - QString str; - if (m_echoMode == QLineEdit::NoEcho) - str = QString::fromLatin1(""); - else - str = m_text; - - if (m_echoMode == QLineEdit::Password || (m_echoMode == QLineEdit::PasswordEchoOnEdit - && !m_passwordEchoEditing)) - str.fill(m_passwordCharacter); - - // replace certain non-printable characters with spaces (to avoid - // drawing boxes when using fonts that don't have glyphs for such - // characters) - QChar* uc = str.data(); - for (int i = 0; i < (int)str.length(); ++i) { - if ((uc[i] < 0x20 && uc[i] != 0x09) - || uc[i] == QChar::LineSeparator - || uc[i] == QChar::ParagraphSeparator - || uc[i] == QChar::ObjectReplacementCharacter) - uc[i] = QChar(0x0020); - } - - m_textLayout.setText(str); - - QTextOption option; - option.setTextDirection(m_layoutDirection); - option.setFlags(QTextOption::IncludeTrailingSpaces); - m_textLayout.setTextOption(option); - - m_textLayout.beginLayout(); - QTextLine l = m_textLayout.createLine(); - m_textLayout.endLayout(); - m_ascent = qRound(l.ascent()); - - if (str != orig || forceUpdate) - emit displayTextChanged(str); -} - -#ifndef QT_NO_CLIPBOARD -/*! - \internal - - Copies the currently selected text into the clipboard using the given - \a mode. - - \note If the echo mode is set to a mode other than Normal then copy - will not work. This is to prevent using copy as a method of bypassing - password features of the line control. -*/ -void QLineControl::copy(QClipboard::Mode mode) const -{ - QString t = selectedText(); - if (!t.isEmpty() && m_echoMode == QLineEdit::Normal) { - disconnect(QApplication::clipboard(), SIGNAL(selectionChanged()), this, 0); - QApplication::clipboard()->setText(t, mode); - connect(QApplication::clipboard(), SIGNAL(selectionChanged()), - this, SLOT(_q_clipboardChanged())); - } -} - -/*! - \internal - - Inserts the text stored in the application clipboard into the line - control. - - \sa insert() -*/ -void QLineControl::paste(QClipboard::Mode clipboardMode) -{ - QString clip = QApplication::clipboard()->text(clipboardMode); - if (!clip.isEmpty() || hasSelectedText()) { - separate(); //make it a separate undo/redo command - insert(clip); - separate(); - } -} - -#endif // !QT_NO_CLIPBOARD - -/*! - \internal - - Handles the behavior for the backspace key or function. - Removes the current selection if there is a selection, otherwise - removes the character prior to the cursor position. - - \sa del() -*/ -void QLineControl::backspace() -{ - int priorState = m_undoState; - if (hasSelectedText()) { - removeSelectedText(); - } else if (m_cursor) { - --m_cursor; - if (m_maskData) - m_cursor = prevMaskBlank(m_cursor); - QChar uc = m_text.at(m_cursor); - if (m_cursor > 0 && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) { - // second half of a surrogate, check if we have the first half as well, - // if yes delete both at once - uc = m_text.at(m_cursor - 1); - if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00) { - internalDelete(true); - --m_cursor; - } - } - internalDelete(true); - } - finishChange(priorState); -} - -/*! - \internal - - Handles the behavior for the delete key or function. - Removes the current selection if there is a selection, otherwise - removes the character after the cursor position. - - \sa del() -*/ -void QLineControl::del() -{ - int priorState = m_undoState; - if (hasSelectedText()) { - removeSelectedText(); - } else { - int n = m_textLayout.nextCursorPosition(m_cursor) - m_cursor; - while (n--) - internalDelete(); - } - finishChange(priorState); -} - -/*! - \internal - - Inserts the given \a newText at the current cursor position. - If there is any selected text it is removed prior to insertion of - the new text. -*/ -void QLineControl::insert(const QString &newText) -{ - int priorState = m_undoState; - removeSelectedText(); - internalInsert(newText); - finishChange(priorState); -} - -/*! - \internal - - Clears the line control text. -*/ -void QLineControl::clear() -{ - int priorState = m_undoState; - m_selstart = 0; - m_selend = m_text.length(); - removeSelectedText(); - separate(); - finishChange(priorState, /*update*/false, /*edited*/false); -} - -/*! - \internal - - Sets \a length characters from the given \a start position as selected. - The given \a start position must be within the current text for - the line control. If \a length characters cannot be selected, then - the selection will extend to the end of the current text. -*/ -void QLineControl::setSelection(int start, int length) -{ - if(start < 0 || start > (int)m_text.length()){ - qWarning("QLineControl::setSelection: Invalid start position"); - return; - } - - if (length > 0) { - if (start == m_selstart && start + length == m_selend) - return; - m_selstart = start; - m_selend = qMin(start + length, (int)m_text.length()); - m_cursor = m_selend; - } else if (length < 0){ - if (start == m_selend && start + length == m_selstart) - return; - m_selstart = qMax(start + length, 0); - m_selend = start; - m_cursor = m_selstart; - } else if (m_selstart != m_selend) { - m_selstart = 0; - m_selend = 0; - m_cursor = start; - } else { - m_cursor = start; - emitCursorPositionChanged(); - return; - } - emit selectionChanged(); - emitCursorPositionChanged(); -} - -void QLineControl::_q_clipboardChanged() -{ -} - -void QLineControl::_q_deleteSelected() -{ - if (!hasSelectedText()) - return; - - int priorState = m_undoState; - emit resetInputContext(); - removeSelectedText(); - separate(); - finishChange(priorState); -} - -/*! - \internal - - Initializes the line control with a starting text value of \a txt. -*/ -void QLineControl::init(const QString &txt) -{ - m_text = txt; - updateDisplayText(); - m_cursor = m_text.length(); -} - -/*! - \internal - - Sets the password echo editing to \a editing. If password echo editing - is true, then the text of the password is displayed even if the echo - mode is set to QLineEdit::PasswordEchoOnEdit. Password echoing editing - does not affect other echo modes. -*/ -void QLineControl::updatePasswordEchoEditing(bool editing) -{ - m_passwordEchoEditing = editing; - updateDisplayText(); -} - -/*! - \internal - - Returns the cursor position of the given \a x pixel value in relation - to the displayed text. The given \a betweenOrOn specified what kind - of cursor position is requested. -*/ -int QLineControl::xToPos(int x, QTextLine::CursorPosition betweenOrOn) const -{ - return m_textLayout.lineAt(0).xToCursor(x, betweenOrOn); -} - -/*! - \internal - - Returns the bounds of the current cursor, as defined as a - between characters cursor. -*/ -QRect QLineControl::cursorRect() const -{ - QTextLine l = m_textLayout.lineAt(0); - int c = m_cursor; - if (m_preeditCursor != -1) - c += m_preeditCursor; - int cix = qRound(l.cursorToX(c)); - int w = m_cursorWidth; - int ch = l.height() + 1; - - return QRect(cix-5, 0, w+9, ch); -} - -/*! - \internal - - Fixes the current text so that it is valid given any set validators. - - Returns true if the text was changed. Otherwise returns false. -*/ -bool QLineControl::fixup() // this function assumes that validate currently returns != Acceptable -{ -#ifndef QT_NO_VALIDATOR - if (m_validator) { - QString textCopy = m_text; - int cursorCopy = m_cursor; - m_validator->fixup(textCopy); - if (m_validator->validate(textCopy, cursorCopy) == QValidator::Acceptable) { - if (textCopy != m_text || cursorCopy != m_cursor) - internalSetText(textCopy, cursorCopy); - return true; - } - } -#endif - return false; -} - -/*! - \internal - - Moves the cursor to the given position \a pos. If \a mark is true will - adjust the currently selected text. -*/ -void QLineControl::moveCursor(int pos, bool mark) -{ - if (pos != m_cursor) { - separate(); - if (m_maskData) - pos = pos > m_cursor ? nextMaskBlank(pos) : prevMaskBlank(pos); - } - if (mark) { - int anchor; - if (m_selend > m_selstart && m_cursor == m_selstart) - anchor = m_selend; - else if (m_selend > m_selstart && m_cursor == m_selend) - anchor = m_selstart; - else - anchor = m_cursor; - m_selstart = qMin(anchor, pos); - m_selend = qMax(anchor, pos); - updateDisplayText(); - } else { - internalDeselect(); - } - m_cursor = pos; - if (mark || m_selDirty) { - m_selDirty = false; - emit selectionChanged(); - } - emitCursorPositionChanged(); -} - -/*! - \internal - - Applies the given input method event \a event to the text of the line - control -*/ -void QLineControl::processInputMethodEvent(QInputMethodEvent *event) -{ - int priorState = 0; - bool isGettingInput = !event->commitString().isEmpty() - || event->preeditString() != preeditAreaText() - || event->replacementLength() > 0; - bool cursorPositionChanged = false; - - if (isGettingInput) { - // If any text is being input, remove selected text. - priorState = m_undoState; - if (echoMode() == QLineEdit::PasswordEchoOnEdit && !passwordEchoEditing()) { - updatePasswordEchoEditing(true); - m_selstart = 0; - m_selend = m_text.length(); - } - removeSelectedText(); - } - - int c = m_cursor; // cursor position after insertion of commit string - if (event->replacementStart() <= 0) - c += event->commitString().length() - qMin(-event->replacementStart(), event->replacementLength()); - - m_cursor += event->replacementStart(); - - // insert commit string - if (event->replacementLength()) { - m_selstart = m_cursor; - m_selend = m_selstart + event->replacementLength(); - removeSelectedText(); - } - if (!event->commitString().isEmpty()) { - internalInsert(event->commitString()); - cursorPositionChanged = true; - } - - m_cursor = qMin(c, m_text.length()); - - for (int i = 0; i < event->attributes().size(); ++i) { - const QInputMethodEvent::Attribute &a = event->attributes().at(i); - if (a.type == QInputMethodEvent::Selection) { - m_cursor = qBound(0, a.start + a.length, m_text.length()); - if (a.length) { - m_selstart = qMax(0, qMin(a.start, m_text.length())); - m_selend = m_cursor; - if (m_selend < m_selstart) { - qSwap(m_selstart, m_selend); - } - } else { - m_selstart = m_selend = 0; - } - cursorPositionChanged = true; - } - } -#ifndef QT_NO_IM - setPreeditArea(m_cursor, event->preeditString()); -#endif //QT_NO_IM - const int oldPreeditCursor = m_preeditCursor; - m_preeditCursor = event->preeditString().length(); - m_hideCursor = false; - QList formats; - for (int i = 0; i < event->attributes().size(); ++i) { - const QInputMethodEvent::Attribute &a = event->attributes().at(i); - if (a.type == QInputMethodEvent::Cursor) { - m_preeditCursor = a.start; - m_hideCursor = !a.length; - } else if (a.type == QInputMethodEvent::TextFormat) { - QTextCharFormat f = qvariant_cast(a.value).toCharFormat(); - if (f.isValid()) { - QTextLayout::FormatRange o; - o.start = a.start + m_cursor; - o.length = a.length; - o.format = f; - formats.append(o); - } - } - } - m_textLayout.setAdditionalFormats(formats); - updateDisplayText(/*force*/ true); - if (cursorPositionChanged) - emitCursorPositionChanged(); - else if (m_preeditCursor != oldPreeditCursor) - emit updateMicroFocus(); - if (isGettingInput) - finishChange(priorState); -} - -/*! - \internal - - Draws the display text for the line control using the given - \a painter, \a clip, and \a offset. Which aspects of the display text - are drawn is specified by the given \a flags. - - If the flags contain DrawSelections, then the selection or input mask - backgrounds and foregrounds will be applied before drawing the text. - - If the flags contain DrawCursor a cursor of the current cursorWidth() - will be drawn after drawing the text. - - The display text will only be drawn if the flags contain DrawText -*/ -void QLineControl::draw(QPainter *painter, const QPoint &offset, const QRect &clip, int flags) -{ - QVector selections; - if (flags & DrawSelections) { - QTextLayout::FormatRange o; - if (m_selstart < m_selend) { - o.start = m_selstart; - o.length = m_selend - m_selstart; - o.format.setBackground(m_palette.brush(QPalette::Highlight)); - o.format.setForeground(m_palette.brush(QPalette::HighlightedText)); - } else { - // mask selection - if(!m_blinkPeriod || m_blinkStatus){ - o.start = m_cursor; - o.length = 1; - o.format.setBackground(m_palette.brush(QPalette::Text)); - o.format.setForeground(m_palette.brush(QPalette::Window)); - } - } - selections.append(o); - } - - if (flags & DrawText) - m_textLayout.draw(painter, offset, selections, clip); - - if (flags & DrawCursor){ - int cursor = m_cursor; - if (m_preeditCursor != -1) - cursor += m_preeditCursor; - if (!m_hideCursor && (!m_blinkPeriod || m_blinkStatus)) - m_textLayout.drawCursor(painter, offset, cursor, m_cursorWidth); - } -} - -/*! - \internal - - Sets the selection to cover the word at the given cursor position. - The word boundaries are defined by the behavior of QTextLayout::SkipWords - cursor mode. -*/ -void QLineControl::selectWordAtPos(int cursor) -{ - int next = cursor + 1; - if(next > end()) - --next; - int c = m_textLayout.previousCursorPosition(next, QTextLayout::SkipWords); - moveCursor(c, false); - // ## text layout should support end of words. - int end = m_textLayout.nextCursorPosition(c, QTextLayout::SkipWords); - while (end > cursor && m_text[end-1].isSpace()) - --end; - moveCursor(end, true); -} - -/*! - \internal - - Completes a change to the line control text. If the change is not valid - will undo the line control state back to the given \a validateFromState. - - If \a edited is true and the change is valid, will emit textEdited() in - addition to textChanged(). Otherwise only emits textChanged() on a valid - change. - - The \a update value is currently unused. -*/ -bool QLineControl::finishChange(int validateFromState, bool update, bool edited) -{ - Q_UNUSED(update) - bool lineDirty = m_selDirty; - if (m_textDirty) { - // do validation - bool wasValidInput = m_validInput; - m_validInput = true; -#ifndef QT_NO_VALIDATOR - if (m_validator) { - m_validInput = false; - QString textCopy = m_text; - int cursorCopy = m_cursor; - m_validInput = (m_validator->validate(textCopy, cursorCopy) != QValidator::Invalid); - if (m_validInput) { - if (m_text != textCopy) { - internalSetText(textCopy, cursorCopy); - return true; - } - m_cursor = cursorCopy; - } - } -#endif - if (validateFromState >= 0 && wasValidInput && !m_validInput) { - if (m_transactions.count()) - return false; - internalUndo(validateFromState); - m_history.resize(m_undoState); - if (m_modifiedState > m_undoState) - m_modifiedState = -1; - m_validInput = true; - m_textDirty = false; - } - updateDisplayText(); - lineDirty |= m_textDirty; - if (m_textDirty) { - m_textDirty = false; - QString actualText = text(); - if (edited) - emit textEdited(actualText); - emit textChanged(actualText); - } - } - if (m_selDirty) { - m_selDirty = false; - emit selectionChanged(); - } - emitCursorPositionChanged(); - return true; -} - -/*! - \internal - - An internal function for setting the text of the line control. -*/ -void QLineControl::internalSetText(const QString &txt, int pos, bool edited) -{ - internalDeselect(); - emit resetInputContext(); - QString oldText = m_text; - if (m_maskData) { - m_text = maskString(0, txt, true); - m_text += clearString(m_text.length(), m_maxLength - m_text.length()); - } else { - m_text = txt.isEmpty() ? txt : txt.left(m_maxLength); - } - m_history.clear(); - m_modifiedState = m_undoState = 0; - m_cursor = (pos < 0 || pos > m_text.length()) ? m_text.length() : pos; - m_textDirty = (oldText != m_text); - finishChange(-1, true, edited); -} - - -/*! - \internal - - Adds the given \a command to the undo history - of the line control. Does not apply the command. -*/ -void QLineControl::addCommand(const Command &cmd) -{ - if (m_separator && m_undoState && m_history[m_undoState - 1].type != Separator) { - m_history.resize(m_undoState + 2); - m_history[m_undoState++] = Command(Separator, m_cursor, 0, m_selstart, m_selend); - } else { - m_history.resize(m_undoState + 1); - } - m_separator = false; - m_history[m_undoState++] = cmd; -} - -/*! - \internal - - Inserts the given string \a s into the line - control. - - Also adds the appropriate commands into the undo history. - This function does not call finishChange(), and may leave the text - in an invalid state. -*/ -void QLineControl::internalInsert(const QString &s) -{ - if (hasSelectedText()) - addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend)); - if (m_maskData) { - QString ms = maskString(m_cursor, s); - for (int i = 0; i < (int) ms.length(); ++i) { - addCommand (Command(DeleteSelection, m_cursor + i, m_text.at(m_cursor + i), -1, -1)); - addCommand(Command(Insert, m_cursor + i, ms.at(i), -1, -1)); - } - m_text.replace(m_cursor, ms.length(), ms); - m_cursor += ms.length(); - m_cursor = nextMaskBlank(m_cursor); - m_textDirty = true; - } else { - int remaining = m_maxLength - m_text.length(); - if (remaining != 0) { - m_text.insert(m_cursor, s.left(remaining)); - for (int i = 0; i < (int) s.left(remaining).length(); ++i) - addCommand(Command(Insert, m_cursor++, s.at(i), -1, -1)); - m_textDirty = true; - } - } -} - -/*! - \internal - - deletes a single character from the current text. If \a wasBackspace, - the character prior to the cursor is removed. Otherwise the character - after the cursor is removed. - - Also adds the appropriate commands into the undo history. - This function does not call finishChange(), and may leave the text - in an invalid state. -*/ -void QLineControl::internalDelete(bool wasBackspace) -{ - if (m_cursor < (int) m_text.length()) { - if (hasSelectedText()) - addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend)); - addCommand(Command((CommandType)((m_maskData ? 2 : 0) + (wasBackspace ? Remove : Delete)), - m_cursor, m_text.at(m_cursor), -1, -1)); - if (m_maskData) { - m_text.replace(m_cursor, 1, clearString(m_cursor, 1)); - addCommand(Command(Insert, m_cursor, m_text.at(m_cursor), -1, -1)); - } else { - m_text.remove(m_cursor, 1); - } - m_textDirty = true; - } -} - -/*! - \internal - - removes the currently selected text from the line control. - - Also adds the appropriate commands into the undo history. - This function does not call finishChange(), and may leave the text - in an invalid state. -*/ -void QLineControl::removeSelectedText() -{ - if (m_selstart < m_selend && m_selend <= (int) m_text.length()) { - separate(); - int i ; - addCommand(Command(SetSelection, m_cursor, 0, m_selstart, m_selend)); - if (m_selstart <= m_cursor && m_cursor < m_selend) { - // cursor is within the selection. Split up the commands - // to be able to restore the correct cursor position - for (i = m_cursor; i >= m_selstart; --i) - addCommand (Command(DeleteSelection, i, m_text.at(i), -1, 1)); - for (i = m_selend - 1; i > m_cursor; --i) - addCommand (Command(DeleteSelection, i - m_cursor + m_selstart - 1, m_text.at(i), -1, -1)); - } else { - for (i = m_selend-1; i >= m_selstart; --i) - addCommand (Command(RemoveSelection, i, m_text.at(i), -1, -1)); - } - if (m_maskData) { - m_text.replace(m_selstart, m_selend - m_selstart, clearString(m_selstart, m_selend - m_selstart)); - for (int i = 0; i < m_selend - m_selstart; ++i) - addCommand(Command(Insert, m_selstart + i, m_text.at(m_selstart + i), -1, -1)); - } else { - m_text.remove(m_selstart, m_selend - m_selstart); - } - if (m_cursor > m_selstart) - m_cursor -= qMin(m_cursor, m_selend) - m_selstart; - internalDeselect(); - m_textDirty = true; - } -} - -/*! - \internal - - Parses the input mask specified by \a maskFields to generate - the mask data used to handle input masks. -*/ -void QLineControl::parseInputMask(const QString &maskFields) -{ - int delimiter = maskFields.indexOf(QLatin1Char(';')); - if (maskFields.isEmpty() || delimiter == 0) { - if (m_maskData) { - delete [] m_maskData; - m_maskData = 0; - m_maxLength = 32767; - internalSetText(QString()); - } - return; - } - - if (delimiter == -1) { - m_blank = QLatin1Char(' '); - m_inputMask = maskFields; - } else { - m_inputMask = maskFields.left(delimiter); - m_blank = (delimiter + 1 < maskFields.length()) ? maskFields[delimiter + 1] : QLatin1Char(' '); - } - - // calculate m_maxLength / m_maskData length - m_maxLength = 0; - QChar c = 0; - for (int i=0; i 0 && m_inputMask.at(i-1) == QLatin1Char('\\')) { - m_maxLength++; - continue; - } - if (c != QLatin1Char('\\') && c != QLatin1Char('!') && - c != QLatin1Char('<') && c != QLatin1Char('>') && - c != QLatin1Char('{') && c != QLatin1Char('}') && - c != QLatin1Char('[') && c != QLatin1Char(']')) - m_maxLength++; - } - - delete [] m_maskData; - m_maskData = new MaskInputData[m_maxLength]; - - MaskInputData::Casemode m = MaskInputData::NoCaseMode; - c = 0; - bool s; - bool escape = false; - int index = 0; - for (int i = 0; i < m_inputMask.length(); i++) { - c = m_inputMask.at(i); - if (escape) { - s = true; - m_maskData[index].maskChar = c; - m_maskData[index].separator = s; - m_maskData[index].caseMode = m; - index++; - escape = false; - } else if (c == QLatin1Char('<')) { - m = MaskInputData::Lower; - } else if (c == QLatin1Char('>')) { - m = MaskInputData::Upper; - } else if (c == QLatin1Char('!')) { - m = MaskInputData::NoCaseMode; - } else if (c != QLatin1Char('{') && c != QLatin1Char('}') && c != QLatin1Char('[') && c != QLatin1Char(']')) { - switch (c.unicode()) { - case 'A': - case 'a': - case 'N': - case 'n': - case 'X': - case 'x': - case '9': - case '0': - case 'D': - case 'd': - case '#': - case 'H': - case 'h': - case 'B': - case 'b': - s = false; - break; - case '\\': - escape = true; - default: - s = true; - break; - } - - if (!escape) { - m_maskData[index].maskChar = c; - m_maskData[index].separator = s; - m_maskData[index].caseMode = m; - index++; - } - } - } - internalSetText(m_text); -} - - -/*! - \internal - - checks if the key is valid compared to the inputMask -*/ -bool QLineControl::isValidInput(QChar key, QChar mask) const -{ - switch (mask.unicode()) { - case 'A': - if (key.isLetter()) - return true; - break; - case 'a': - if (key.isLetter() || key == m_blank) - return true; - break; - case 'N': - if (key.isLetterOrNumber()) - return true; - break; - case 'n': - if (key.isLetterOrNumber() || key == m_blank) - return true; - break; - case 'X': - if (key.isPrint()) - return true; - break; - case 'x': - if (key.isPrint() || key == m_blank) - return true; - break; - case '9': - if (key.isNumber()) - return true; - break; - case '0': - if (key.isNumber() || key == m_blank) - return true; - break; - case 'D': - if (key.isNumber() && key.digitValue() > 0) - return true; - break; - case 'd': - if ((key.isNumber() && key.digitValue() > 0) || key == m_blank) - return true; - break; - case '#': - if (key.isNumber() || key == QLatin1Char('+') || key == QLatin1Char('-') || key == m_blank) - return true; - break; - case 'B': - if (key == QLatin1Char('0') || key == QLatin1Char('1')) - return true; - break; - case 'b': - if (key == QLatin1Char('0') || key == QLatin1Char('1') || key == m_blank) - return true; - break; - case 'H': - if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F'))) - return true; - break; - case 'h': - if (key.isNumber() || (key >= QLatin1Char('a') && key <= QLatin1Char('f')) || (key >= QLatin1Char('A') && key <= QLatin1Char('F')) || key == m_blank) - return true; - break; - default: - break; - } - return false; -} - -/*! - \internal - - Returns true if the given text \a str is valid for any - validator or input mask set for the line control. - - Otherwise returns false -*/ -bool QLineControl::hasAcceptableInput(const QString &str) const -{ -#ifndef QT_NO_VALIDATOR - QString textCopy = str; - int cursorCopy = m_cursor; - if (m_validator && m_validator->validate(textCopy, cursorCopy) - != QValidator::Acceptable) - return false; -#endif - - if (!m_maskData) - return true; - - if (str.length() != m_maxLength) - return false; - - for (int i=0; i < m_maxLength; ++i) { - if (m_maskData[i].separator) { - if (str.at(i) != m_maskData[i].maskChar) - return false; - } else { - if (!isValidInput(str.at(i), m_maskData[i].maskChar)) - return false; - } - } - return true; -} - -/*! - \internal - - Applies the inputMask on \a str starting from position \a pos in the mask. \a clear - specifies from where characters should be gotten when a separator is met in \a str - true means - that blanks will be used, false that previous input is used. - Calling this when no inputMask is set is undefined. -*/ -QString QLineControl::maskString(uint pos, const QString &str, bool clear) const -{ - if (pos >= (uint)m_maxLength) - return QString::fromLatin1(""); - - QString fill; - fill = clear ? clearString(0, m_maxLength) : m_text; - - int strIndex = 0; - QString s = QString::fromLatin1(""); - int i = pos; - while (i < m_maxLength) { - if (strIndex < str.length()) { - if (m_maskData[i].separator) { - s += m_maskData[i].maskChar; - if (str[(int)strIndex] == m_maskData[i].maskChar) - strIndex++; - ++i; - } else { - if (isValidInput(str[(int)strIndex], m_maskData[i].maskChar)) { - switch (m_maskData[i].caseMode) { - case MaskInputData::Upper: - s += str[(int)strIndex].toUpper(); - break; - case MaskInputData::Lower: - s += str[(int)strIndex].toLower(); - break; - default: - s += str[(int)strIndex]; - } - ++i; - } else { - // search for separator first - int n = findInMask(i, true, true, str[(int)strIndex]); - if (n != -1) { - if (str.length() != 1 || i == 0 || (i > 0 && (!m_maskData[i-1].separator || m_maskData[i-1].maskChar != str[(int)strIndex]))) { - s += fill.mid(i, n-i+1); - i = n + 1; // update i to find + 1 - } - } else { - // search for valid m_blank if not - n = findInMask(i, true, false, str[(int)strIndex]); - if (n != -1) { - s += fill.mid(i, n-i); - switch (m_maskData[n].caseMode) { - case MaskInputData::Upper: - s += str[(int)strIndex].toUpper(); - break; - case MaskInputData::Lower: - s += str[(int)strIndex].toLower(); - break; - default: - s += str[(int)strIndex]; - } - i = n + 1; // updates i to find + 1 - } - } - } - ++strIndex; - } - } else - break; - } - - return s; -} - - - -/*! - \internal - - Returns a "cleared" string with only separators and blank chars. - Calling this when no inputMask is set is undefined. -*/ -QString QLineControl::clearString(uint pos, uint len) const -{ - if (pos >= (uint)m_maxLength) - return QString(); - - QString s; - int end = qMin((uint)m_maxLength, pos + len); - for (int i = pos; i < end; ++i) - if (m_maskData[i].separator) - s += m_maskData[i].maskChar; - else - s += m_blank; - - return s; -} - -/*! - \internal - - Strips blank parts of the input in a QLineControl when an inputMask is set, - separators are still included. Typically "127.0__.0__.1__" becomes "127.0.0.1". -*/ -QString QLineControl::stripString(const QString &str) const -{ - if (!m_maskData) - return str; - - QString s; - int end = qMin(m_maxLength, (int)str.length()); - for (int i = 0; i < end; ++i) - if (m_maskData[i].separator) - s += m_maskData[i].maskChar; - else - if (str[i] != m_blank) - s += str[i]; - - return s; -} - -/*! - \internal - searches forward/backward in m_maskData for either a separator or a m_blank -*/ -int QLineControl::findInMask(int pos, bool forward, bool findSeparator, QChar searchChar) const -{ - if (pos >= m_maxLength || pos < 0) - return -1; - - int end = forward ? m_maxLength : -1; - int step = forward ? 1 : -1; - int i = pos; - - while (i != end) { - if (findSeparator) { - if (m_maskData[i].separator && m_maskData[i].maskChar == searchChar) - return i; - } else { - if (!m_maskData[i].separator) { - if (searchChar.isNull()) - return i; - else if (isValidInput(searchChar, m_maskData[i].maskChar)) - return i; - } - } - i += step; - } - return -1; -} - -void QLineControl::internalUndo(int until) -{ - if (!isUndoAvailable()) - return; - internalDeselect(); - while (m_undoState && m_undoState > until) { - Command& cmd = m_history[--m_undoState]; - switch (cmd.type) { - case Insert: - m_text.remove(cmd.pos, 1); - m_cursor = cmd.pos; - break; - case SetSelection: - m_selstart = cmd.selStart; - m_selend = cmd.selEnd; - m_cursor = cmd.pos; - break; - case Remove: - case RemoveSelection: - m_text.insert(cmd.pos, cmd.uc); - m_cursor = cmd.pos + 1; - break; - case Delete: - case DeleteSelection: - m_text.insert(cmd.pos, cmd.uc); - m_cursor = cmd.pos; - break; - case Separator: - continue; - } - if (until < 0 && m_undoState) { - Command& next = m_history[m_undoState-1]; - if (next.type != cmd.type && next.type < RemoveSelection - && (cmd.type < RemoveSelection || next.type == Separator)) - break; - } - } - m_textDirty = true; - emitCursorPositionChanged(); -} - -void QLineControl::internalRedo() -{ - if (!isRedoAvailable()) - return; - internalDeselect(); - while (m_undoState < (int)m_history.size()) { - Command& cmd = m_history[m_undoState++]; - switch (cmd.type) { - case Insert: - m_text.insert(cmd.pos, cmd.uc); - m_cursor = cmd.pos + 1; - break; - case SetSelection: - m_selstart = cmd.selStart; - m_selend = cmd.selEnd; - m_cursor = cmd.pos; - break; - case Remove: - case Delete: - case RemoveSelection: - case DeleteSelection: - m_text.remove(cmd.pos, 1); - m_selstart = cmd.selStart; - m_selend = cmd.selEnd; - m_cursor = cmd.pos; - break; - case Separator: - m_selstart = cmd.selStart; - m_selend = cmd.selEnd; - m_cursor = cmd.pos; - break; - } - if (m_undoState < (int)m_history.size()) { - Command& next = m_history[m_undoState]; - if (next.type != cmd.type && cmd.type < RemoveSelection && next.type != Separator - && (next.type < RemoveSelection || cmd.type == Separator)) - break; - } - } - m_textDirty = true; - emitCursorPositionChanged(); -} - -/*! - \internal - - If the current cursor position differs from the last emitted cursor - position, emits cursorPositionChanged(). -*/ -void QLineControl::emitCursorPositionChanged() -{ - if (m_cursor != m_lastCursorPos) { - const int oldLast = m_lastCursorPos; - m_lastCursorPos = m_cursor; - cursorPositionChanged(oldLast, m_cursor); - } -} - -#ifndef QT_NO_COMPLETER -// iterating forward(dir=1)/backward(dir=-1) from the -// current row based. dir=0 indicates a new completion prefix was set. -bool QLineControl::advanceToEnabledItem(int dir) -{ - int start = m_completer->currentRow(); - if (start == -1) - return false; - int i = start + dir; - if (dir == 0) dir = 1; - do { - if (!m_completer->setCurrentRow(i)) { - if (!m_completer->wrapAround()) - break; - i = i > 0 ? 0 : m_completer->completionCount() - 1; - } else { - QModelIndex currentIndex = m_completer->currentIndex(); - if (m_completer->completionModel()->flags(currentIndex) & Qt::ItemIsEnabled) - return true; - i += dir; - } - } while (i != start); - - m_completer->setCurrentRow(start); // restore - return false; -} - -void QLineControl::complete(int key) -{ - if (!m_completer || isReadOnly() || echoMode() != QLineEdit::Normal) - return; - - QString text = this->text(); - if (m_completer->completionMode() == QCompleter::InlineCompletion) { - if (key == Qt::Key_Backspace) - return; - int n = 0; - if (key == Qt::Key_Up || key == Qt::Key_Down) { - if (textAfterSelection().length()) - return; - QString prefix = hasSelectedText() ? textBeforeSelection() - : text; - if (text.compare(m_completer->currentCompletion(), m_completer->caseSensitivity()) != 0 - || prefix.compare(m_completer->completionPrefix(), m_completer->caseSensitivity()) != 0) { - m_completer->setCompletionPrefix(prefix); - } else { - n = (key == Qt::Key_Up) ? -1 : +1; - } - } else { - m_completer->setCompletionPrefix(text); - } - if (!advanceToEnabledItem(n)) - return; - } else { -#ifndef QT_KEYPAD_NAVIGATION - if (text.isEmpty()) { - m_completer->popup()->hide(); - return; - } -#endif - m_completer->setCompletionPrefix(text); - } - - m_completer->complete(); -} -#endif - -void QLineControl::setCursorBlinkPeriod(int msec) -{ - if (msec == m_blinkPeriod) - return; - if (m_blinkTimer) { - killTimer(m_blinkTimer); - } - if (msec) { - m_blinkTimer = startTimer(msec / 2); - m_blinkStatus = 1; - } else { - m_blinkTimer = 0; - if (m_blinkStatus == 1) - emit updateNeeded(inputMask().isEmpty() ? cursorRect() : QRect()); - } - m_blinkPeriod = msec; -} - -void QLineControl::resetCursorBlinkTimer() -{ - if (m_blinkPeriod == 0 || m_blinkTimer == 0) - return; - killTimer(m_blinkTimer); - m_blinkTimer = startTimer(m_blinkPeriod / 2); - m_blinkStatus = 1; -} - -void QLineControl::timerEvent(QTimerEvent *event) -{ - if (event->timerId() == m_blinkTimer) { - m_blinkStatus = !m_blinkStatus; - emit updateNeeded(inputMask().isEmpty() ? cursorRect() : QRect()); - } else if (event->timerId() == m_deleteAllTimer) { - killTimer(m_deleteAllTimer); - m_deleteAllTimer = 0; - clear(); - } else if (event->timerId() == m_tripleClickTimer) { - killTimer(m_tripleClickTimer); - m_tripleClickTimer = 0; - } -} - -bool QLineControl::processEvent(QEvent* ev) -{ -#ifdef QT_KEYPAD_NAVIGATION - if (QApplication::keypadNavigationEnabled()) { - if ((ev->type() == QEvent::KeyPress) || (ev->type() == QEvent::KeyRelease)) { - QKeyEvent *ke = (QKeyEvent *)ev; - if (ke->key() == Qt::Key_Back) { - if (ke->isAutoRepeat()) { - // Swallow it. We don't want back keys running amok. - ke->accept(); - return true; - } - if ((ev->type() == QEvent::KeyRelease) - && !isReadOnly() - && m_deleteAllTimer) { - killTimer(m_deleteAllTimer); - m_deleteAllTimer = 0; - backspace(); - ke->accept(); - return true; - } - } - } - } -#endif - switch(ev->type()){ -#ifndef QT_NO_GRAPHICSVIEW - case QEvent::GraphicsSceneMouseDoubleClick: - case QEvent::GraphicsSceneMouseMove: - case QEvent::GraphicsSceneMouseRelease: - case QEvent::GraphicsSceneMousePress:{ - QGraphicsSceneMouseEvent *gvEv = static_cast(ev); - QMouseEvent* mouse = new QMouseEvent(ev->type(), - gvEv->pos().toPoint(), gvEv->button(), gvEv->buttons(), gvEv->modifiers()); - processMouseEvent(mouse); break; - } -#endif - case QEvent::MouseButtonPress: - case QEvent::MouseButtonRelease: - case QEvent::MouseButtonDblClick: - case QEvent::MouseMove: - processMouseEvent(static_cast(ev)); break; - case QEvent::KeyPress: - case QEvent::KeyRelease: - processKeyEvent(static_cast(ev)); break; - case QEvent::InputMethod: - processInputMethodEvent(static_cast(ev)); break; -#ifndef QT_NO_SHORTCUT - case QEvent::ShortcutOverride:{ - if (isReadOnly()) - return false; - QKeyEvent* ke = static_cast(ev); - if (ke == QKeySequence::Copy - || ke == QKeySequence::Paste - || ke == QKeySequence::Cut - || ke == QKeySequence::Redo - || ke == QKeySequence::Undo - || ke == QKeySequence::MoveToNextWord - || ke == QKeySequence::MoveToPreviousWord - || ke == QKeySequence::MoveToStartOfDocument - || ke == QKeySequence::MoveToEndOfDocument - || ke == QKeySequence::SelectNextWord - || ke == QKeySequence::SelectPreviousWord - || ke == QKeySequence::SelectStartOfLine - || ke == QKeySequence::SelectEndOfLine - || ke == QKeySequence::SelectStartOfBlock - || ke == QKeySequence::SelectEndOfBlock - || ke == QKeySequence::SelectStartOfDocument - || ke == QKeySequence::SelectAll - || ke == QKeySequence::SelectEndOfDocument) { - ke->accept(); - } else if (ke->modifiers() == Qt::NoModifier || ke->modifiers() == Qt::ShiftModifier - || ke->modifiers() == Qt::KeypadModifier) { - if (ke->key() < Qt::Key_Escape) { - ke->accept(); - } else { - switch (ke->key()) { - case Qt::Key_Delete: - case Qt::Key_Home: - case Qt::Key_End: - case Qt::Key_Backspace: - case Qt::Key_Left: - case Qt::Key_Right: - ke->accept(); - default: - break; - } - } - } - } -#endif - default: - return false; - } - return true; -} - -void QLineControl::processMouseEvent(QMouseEvent* ev) -{ - - switch (ev->type()) { - case QEvent::GraphicsSceneMousePress: - case QEvent::MouseButtonPress:{ - if (m_tripleClickTimer - && (ev->pos() - m_tripleClick).manhattanLength() - < QApplication::startDragDistance()) { - selectAll(); - return; - } - if (ev->button() == Qt::RightButton) - return; - - bool mark = ev->modifiers() & Qt::ShiftModifier; - int cursor = xToPos(ev->pos().x()); - moveCursor(cursor, mark); - break; - } - case QEvent::GraphicsSceneMouseDoubleClick: - case QEvent::MouseButtonDblClick: - if (ev->button() == Qt::LeftButton) { - selectWordAtPos(xToPos(ev->pos().x())); - if (m_tripleClickTimer) - killTimer(m_tripleClickTimer); - m_tripleClickTimer = startTimer(QApplication::doubleClickInterval()); - m_tripleClick = ev->pos(); - } - break; - case QEvent::GraphicsSceneMouseRelease: - case QEvent::MouseButtonRelease: -#ifndef QT_NO_CLIPBOARD - if (QApplication::clipboard()->supportsSelection()) { - if (ev->button() == Qt::LeftButton) { - copy(QClipboard::Selection); - } else if (!isReadOnly() && ev->button() == Qt::MidButton) { - deselect(); - insert(QApplication::clipboard()->text(QClipboard::Selection)); - } - } -#endif - break; - case QEvent::GraphicsSceneMouseMove: - case QEvent::MouseMove: - if (ev->buttons() & Qt::LeftButton) { - moveCursor(xToPos(ev->pos().x()), true); - } - break; - default: - break; - } -} - -void QLineControl::processKeyEvent(QKeyEvent* event) -{ - bool inlineCompletionAccepted = false; - -#ifndef QT_NO_COMPLETER - if (m_completer) { - QCompleter::CompletionMode completionMode = m_completer->completionMode(); - if ((completionMode == QCompleter::PopupCompletion - || completionMode == QCompleter::UnfilteredPopupCompletion) - && m_completer->popup() - && m_completer->popup()->isVisible()) { - // The following keys are forwarded by the completer to the widget - // Ignoring the events lets the completer provide suitable default behavior - switch (event->key()) { - case Qt::Key_Escape: - event->ignore(); - return; - case Qt::Key_Enter: - case Qt::Key_Return: - case Qt::Key_F4: -#ifdef QT_KEYPAD_NAVIGATION - case Qt::Key_Select: - if (!QApplication::keypadNavigationEnabled()) - break; -#endif - m_completer->popup()->hide(); // just hide. will end up propagating to parent - default: - break; // normal key processing - } - } else if (completionMode == QCompleter::InlineCompletion) { - switch (event->key()) { - case Qt::Key_Enter: - case Qt::Key_Return: - case Qt::Key_F4: -#ifdef QT_KEYPAD_NAVIGATION - case Qt::Key_Select: - if (!QApplication::keypadNavigationEnabled()) - break; -#endif - if (!m_completer->currentCompletion().isEmpty() && hasSelectedText() - && textAfterSelection().isEmpty()) { - setText(m_completer->currentCompletion()); - inlineCompletionAccepted = true; - } - default: - break; // normal key processing - } - } - } -#endif // QT_NO_COMPLETER - - if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { - if (hasAcceptableInput() || fixup()) { - emit accepted(); - emit editingFinished(); - } - if (inlineCompletionAccepted) - event->accept(); - else - event->ignore(); - return; - } - - if (echoMode() == QLineEdit::PasswordEchoOnEdit - && !passwordEchoEditing() - && !isReadOnly() - && !event->text().isEmpty() -#ifdef QT_KEYPAD_NAVIGATION - && event->key() != Qt::Key_Select - && event->key() != Qt::Key_Up - && event->key() != Qt::Key_Down - && event->key() != Qt::Key_Back -#endif - && !(event->modifiers() & Qt::ControlModifier)) { - // Clear the edit and reset to normal echo mode while editing; the - // echo mode switches back when the edit loses focus - // ### resets current content. dubious code; you can - // navigate with keys up, down, back, and select(?), but if you press - // "left" or "right" it clears? - updatePasswordEchoEditing(true); - clear(); - } - - bool unknown = false; - bool visual = cursorMoveStyle() == QTextCursor::Visual; - - if (false) { - } -#ifndef QT_NO_SHORTCUT - else if (event == QKeySequence::Undo) { - if (!isReadOnly()) - undo(); - } - else if (event == QKeySequence::Redo) { - if (!isReadOnly()) - redo(); - } - else if (event == QKeySequence::SelectAll) { - selectAll(); - } -#ifndef QT_NO_CLIPBOARD - else if (event == QKeySequence::Copy) { - copy(); - } - else if (event == QKeySequence::Paste) { - if (!isReadOnly()) { - QClipboard::Mode mode = QClipboard::Clipboard; -#ifdef Q_WS_X11 - if (event->modifiers() == (Qt::CTRL | Qt::SHIFT) && event->key() == Qt::Key_Insert) - mode = QClipboard::Selection; -#endif - paste(mode); - } - } - else if (event == QKeySequence::Cut) { - if (!isReadOnly()) { - copy(); - del(); - } - } - else if (event == QKeySequence::DeleteEndOfLine) { - if (!isReadOnly()) { - setSelection(cursor(), end()); - copy(); - del(); - } - } -#endif //QT_NO_CLIPBOARD - else if (event == QKeySequence::MoveToStartOfLine || event == QKeySequence::MoveToStartOfBlock) { - home(0); - } - else if (event == QKeySequence::MoveToEndOfLine || event == QKeySequence::MoveToEndOfBlock) { - end(0); - } - else if (event == QKeySequence::SelectStartOfLine || event == QKeySequence::SelectStartOfBlock) { - home(1); - } - else if (event == QKeySequence::SelectEndOfLine || event == QKeySequence::SelectEndOfBlock) { - end(1); - } - else if (event == QKeySequence::MoveToNextChar) { -#if !defined(Q_WS_WIN) || defined(QT_NO_COMPLETER) - if (hasSelectedText()) { -#else - if (hasSelectedText() && m_completer - && m_completer->completionMode() == QCompleter::InlineCompletion) { -#endif - moveCursor(selectionEnd(), false); - } else { - cursorForward(0, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1)); - } - } - else if (event == QKeySequence::SelectNextChar) { - cursorForward(1, visual ? 1 : (layoutDirection() == Qt::LeftToRight ? 1 : -1)); - } - else if (event == QKeySequence::MoveToPreviousChar) { -#if !defined(Q_WS_WIN) || defined(QT_NO_COMPLETER) - if (hasSelectedText()) { -#else - if (hasSelectedText() && m_completer - && m_completer->completionMode() == QCompleter::InlineCompletion) { -#endif - moveCursor(selectionStart(), false); - } else { - cursorForward(0, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1)); - } - } - else if (event == QKeySequence::SelectPreviousChar) { - cursorForward(1, visual ? -1 : (layoutDirection() == Qt::LeftToRight ? -1 : 1)); - } - else if (event == QKeySequence::MoveToNextWord) { - if (echoMode() == QLineEdit::Normal) - layoutDirection() == Qt::LeftToRight ? cursorWordForward(0) : cursorWordBackward(0); - else - layoutDirection() == Qt::LeftToRight ? end(0) : home(0); - } - else if (event == QKeySequence::MoveToPreviousWord) { - if (echoMode() == QLineEdit::Normal) - layoutDirection() == Qt::LeftToRight ? cursorWordBackward(0) : cursorWordForward(0); - else if (!isReadOnly()) { - layoutDirection() == Qt::LeftToRight ? home(0) : end(0); - } - } - else if (event == QKeySequence::SelectNextWord) { - if (echoMode() == QLineEdit::Normal) - layoutDirection() == Qt::LeftToRight ? cursorWordForward(1) : cursorWordBackward(1); - else - layoutDirection() == Qt::LeftToRight ? end(1) : home(1); - } - else if (event == QKeySequence::SelectPreviousWord) { - if (echoMode() == QLineEdit::Normal) - layoutDirection() == Qt::LeftToRight ? cursorWordBackward(1) : cursorWordForward(1); - else - layoutDirection() == Qt::LeftToRight ? home(1) : end(1); - } - else if (event == QKeySequence::Delete) { - if (!isReadOnly()) - del(); - } - else if (event == QKeySequence::DeleteEndOfWord) { - if (!isReadOnly()) { - cursorWordForward(true); - del(); - } - } - else if (event == QKeySequence::DeleteStartOfWord) { - if (!isReadOnly()) { - cursorWordBackward(true); - del(); - } - } -#endif // QT_NO_SHORTCUT - else { - bool handled = false; -#ifdef Q_WS_MAC - if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) { - Qt::KeyboardModifiers myModifiers = (event->modifiers() & ~Qt::KeypadModifier); - if (myModifiers & Qt::ShiftModifier) { - if (myModifiers == (Qt::ControlModifier|Qt::ShiftModifier) - || myModifiers == (Qt::AltModifier|Qt::ShiftModifier) - || myModifiers == Qt::ShiftModifier) { - - event->key() == Qt::Key_Up ? home(1) : end(1); - } - } else { - if ((myModifiers == Qt::ControlModifier - || myModifiers == Qt::AltModifier - || myModifiers == Qt::NoModifier)) { - event->key() == Qt::Key_Up ? home(0) : end(0); - } - } - handled = true; - } -#endif - if (event->modifiers() & Qt::ControlModifier) { - switch (event->key()) { - case Qt::Key_Backspace: - if (!isReadOnly()) { - cursorWordBackward(true); - del(); - } - break; -#ifndef QT_NO_COMPLETER - case Qt::Key_Up: - case Qt::Key_Down: - complete(event->key()); - break; -#endif -#if defined(Q_WS_X11) - case Qt::Key_E: - end(0); - break; - - case Qt::Key_U: - if (!isReadOnly()) { - setSelection(0, text().size()); -#ifndef QT_NO_CLIPBOARD - copy(); -#endif - del(); - } - break; -#endif - default: - if (!handled) - unknown = true; - } - } else { // ### check for *no* modifier - switch (event->key()) { - case Qt::Key_Backspace: - if (!isReadOnly()) { - backspace(); -#ifndef QT_NO_COMPLETER - complete(Qt::Key_Backspace); -#endif - } - break; -#ifdef QT_KEYPAD_NAVIGATION - case Qt::Key_Back: - if (QApplication::keypadNavigationEnabled() && !event->isAutoRepeat() - && !isReadOnly()) { - if (text().length() == 0) { - setText(m_cancelText); - - if (passwordEchoEditing()) - updatePasswordEchoEditing(false); - - emit editFocusChange(false); - } else if (!m_deleteAllTimer) { - m_deleteAllTimer = startTimer(750); - } - } else { - unknown = true; - } - break; -#endif - default: - if (!handled) - unknown = true; - } - } - } - - if (event->key() == Qt::Key_Direction_L || event->key() == Qt::Key_Direction_R) { - setLayoutDirection((event->key() == Qt::Key_Direction_L) ? Qt::LeftToRight : Qt::RightToLeft); - unknown = false; - } - - if (unknown && !isReadOnly()) { - QString t = event->text(); - if (!t.isEmpty() && t.at(0).isPrint()) { - insert(t); -#ifndef QT_NO_COMPLETER - complete(event->key()); -#endif - event->accept(); - return; - } - } - - if (unknown) - event->ignore(); - else - event->accept(); -} - - -QT_END_NAMESPACE - -#endif diff --git a/src/gui/widgets/qlinecontrol_p.h b/src/gui/widgets/qlinecontrol_p.h deleted file mode 100644 index 0042f17261..0000000000 --- a/src/gui/widgets/qlinecontrol_p.h +++ /dev/null @@ -1,456 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the Technology Preview License Agreement accompanying -** this package. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain additional -** rights. These rights are described in the Nokia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** If you have questions regarding the use of this file, please contact -** Nokia at qt-info@nokia.com. -** -** -** -** -** -** -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QLINECONTROL_P_H -#define QLINECONTROL_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "QtCore/qglobal.h" - -#ifndef QT_NO_LINEEDIT -#include "private/qwidget_p.h" -#include "QtGui/qlineedit.h" -#include "QtGui/qtextlayout.h" -#include "QtGui/qstyleoption.h" -#include "QtCore/qpointer.h" -#include "QtGui/qlineedit.h" -#include "QtGui/qclipboard.h" -#include "QtCore/qpoint.h" -#include "QtGui/qcompleter.h" - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Gui) - -class Q_GUI_EXPORT QLineControl : public QObject -{ - Q_OBJECT - -public: - QLineControl(const QString &txt = QString()) - : m_cursor(0), m_preeditCursor(0), m_cursorWidth(0), m_layoutDirection(Qt::LayoutDirectionAuto), - m_hideCursor(false), m_separator(0), m_readOnly(0), - m_dragEnabled(0), m_echoMode(0), m_textDirty(0), m_selDirty(0), - m_validInput(1), m_blinkStatus(0), m_blinkPeriod(0), m_blinkTimer(0), m_deleteAllTimer(0), - m_ascent(0), m_maxLength(32767), m_lastCursorPos(-1), - m_tripleClickTimer(0), m_maskData(0), m_modifiedState(0), m_undoState(0), - m_selstart(0), m_selend(0), m_passwordEchoEditing(false) - { - init(txt); - } - - ~QLineControl() - { - delete [] m_maskData; - } - - int nextMaskBlank(int pos) - { - int c = findInMask(pos, true, false); - m_separator |= (c != pos); - return (c != -1 ? c : m_maxLength); - } - - int prevMaskBlank(int pos) - { - int c = findInMask(pos, false, false); - m_separator |= (c != pos); - return (c != -1 ? c : 0); - } - - bool isUndoAvailable() const { return !m_readOnly && m_undoState; } - bool isRedoAvailable() const { return !m_readOnly && m_undoState < (int)m_history.size(); } - void clearUndo() { m_history.clear(); m_modifiedState = m_undoState = 0; } - - bool isModified() const { return m_modifiedState != m_undoState; } - void setModified(bool modified) { m_modifiedState = modified ? -1 : m_undoState; } - - bool allSelected() const { return !m_text.isEmpty() && m_selstart == 0 && m_selend == (int)m_text.length(); } - bool hasSelectedText() const { return !m_text.isEmpty() && m_selend > m_selstart; } - - int width() const { return qRound(m_textLayout.lineAt(0).width()) + 1; } - int height() const { return qRound(m_textLayout.lineAt(0).height()) + 1; } - int ascent() const { return m_ascent; } - qreal naturalTextWidth() const { return m_textLayout.lineAt(0).naturalTextWidth(); } - - void setSelection(int start, int length); - - inline QString selectedText() const { return hasSelectedText() ? m_text.mid(m_selstart, m_selend - m_selstart) : QString(); } - QString textBeforeSelection() const { return hasSelectedText() ? m_text.left(m_selstart) : QString(); } - QString textAfterSelection() const { return hasSelectedText() ? m_text.mid(m_selend) : QString(); } - - int selectionStart() const { return hasSelectedText() ? m_selstart : -1; } - int selectionEnd() const { return hasSelectedText() ? m_selend : -1; } - bool inSelection(int x) const - { - if (m_selstart >= m_selend) - return false; - int pos = xToPos(x, QTextLine::CursorOnCharacter); - return pos >= m_selstart && pos < m_selend; - } - - void removeSelection() - { - int priorState = m_undoState; - removeSelectedText(); - finishChange(priorState); - } - - int start() const { return 0; } - int end() const { return m_text.length(); } - -#ifndef QT_NO_CLIPBOARD - void copy(QClipboard::Mode mode = QClipboard::Clipboard) const; - void paste(QClipboard::Mode mode = QClipboard::Clipboard); -#endif - - int cursor() const{ return m_cursor; } - int preeditCursor() const { return m_preeditCursor; } - - int cursorWidth() const { return m_cursorWidth; } - void setCursorWidth(int value) { m_cursorWidth = value; } - - QTextCursor::MoveStyle cursorMoveStyle() const { return m_textLayout.cursorMoveStyle(); } - void setCursorMoveStyle(QTextCursor::MoveStyle style) { m_textLayout.setCursorMoveStyle(style); } - - void moveCursor(int pos, bool mark = false); - void cursorForward(bool mark, int steps) - { - int c = m_cursor; - if (steps > 0) { - while (steps--) - c = cursorMoveStyle() == QTextCursor::Visual ? m_textLayout.rightCursorPosition(c) - : m_textLayout.nextCursorPosition(c); - } else if (steps < 0) { - while (steps++) - c = cursorMoveStyle() == QTextCursor::Visual ? m_textLayout.leftCursorPosition(c) - : m_textLayout.previousCursorPosition(c); - } - moveCursor(c, mark); - } - - void cursorWordForward(bool mark) { moveCursor(m_textLayout.nextCursorPosition(m_cursor, QTextLayout::SkipWords), mark); } - void cursorWordBackward(bool mark) { moveCursor(m_textLayout.previousCursorPosition(m_cursor, QTextLayout::SkipWords), mark); } - - void home(bool mark) { moveCursor(0, mark); } - void end(bool mark) { moveCursor(text().length(), mark); } - - int xToPos(int x, QTextLine::CursorPosition = QTextLine::CursorBetweenCharacters) const; - QRect cursorRect() const; - - qreal cursorToX(int cursor) const { return m_textLayout.lineAt(0).cursorToX(cursor); } - qreal cursorToX() const - { - int cursor = m_cursor; - if (m_preeditCursor != -1) - cursor += m_preeditCursor; - return cursorToX(cursor); - } - - bool isReadOnly() const { return m_readOnly; } - void setReadOnly(bool enable) { m_readOnly = enable; } - - QString text() const - { - QString res = m_maskData ? stripString(m_text) : m_text; - return (res.isNull() ? QString::fromLatin1("") : res); - } - void setText(const QString &txt) { internalSetText(txt, -1, false); } - QString displayText() const { return m_textLayout.text(); } - - void backspace(); - void del(); - void deselect() { internalDeselect(); finishChange(); } - void selectAll() { m_selstart = m_selend = m_cursor = 0; moveCursor(m_text.length(), true); } - - void insert(const QString &); - void clear(); - void undo() { internalUndo(); finishChange(-1, true); } - void redo() { internalRedo(); finishChange(); } - void selectWordAtPos(int); - - uint echoMode() const { return m_echoMode; } - void setEchoMode(uint mode) - { - m_echoMode = mode; - m_passwordEchoEditing = false; - updateDisplayText(); - } - - int maxLength() const { return m_maxLength; } - void setMaxLength(int maxLength) - { - if (m_maskData) - return; - m_maxLength = maxLength; - setText(m_text); - } - -#ifndef QT_NO_VALIDATOR - const QValidator *validator() const { return m_validator; } - void setValidator(const QValidator *v) { m_validator = const_cast(v); } -#endif - -#ifndef QT_NO_COMPLETER - QCompleter *completer() const { return m_completer; } - /* Note that you must set the widget for the completer separately */ - void setCompleter(const QCompleter *c) { m_completer = const_cast(c); } - void complete(int key); -#endif - - int cursorPosition() const { return m_cursor; } - void setCursorPosition(int pos) { if (pos <= m_text.length()) moveCursor(qMax(0, pos)); } - - bool hasAcceptableInput() const { return hasAcceptableInput(m_text); } - bool fixup(); - - QString inputMask() const { return m_maskData ? m_inputMask + QLatin1Char(';') + m_blank : QString(); } - void setInputMask(const QString &mask) - { - parseInputMask(mask); - if (m_maskData) - moveCursor(nextMaskBlank(0)); - } - - // input methods -#ifndef QT_NO_IM - bool composeMode() const { return !m_textLayout.preeditAreaText().isEmpty(); } - void setPreeditArea(int cursor, const QString &text) { m_textLayout.setPreeditArea(cursor, text); } -#endif - - QString preeditAreaText() const { return m_textLayout.preeditAreaText(); } - - void updatePasswordEchoEditing(bool editing); - bool passwordEchoEditing() const { return m_passwordEchoEditing; } - - QChar passwordCharacter() const { return m_passwordCharacter; } - void setPasswordCharacter(const QChar &character) { m_passwordCharacter = character; updateDisplayText(); } - - Qt::LayoutDirection layoutDirection() const { - if (m_layoutDirection == Qt::LayoutDirectionAuto) { - if (m_text.isEmpty()) - return QApplication::keyboardInputDirection(); - return m_text.isRightToLeft() ? Qt::RightToLeft : Qt::LeftToRight; - } - return m_layoutDirection; - } - void setLayoutDirection(Qt::LayoutDirection direction) - { - if (direction != m_layoutDirection) { - m_layoutDirection = direction; - updateDisplayText(); - } - } - - void setFont(const QFont &font) { m_textLayout.setFont(font); updateDisplayText(); } - - void processInputMethodEvent(QInputMethodEvent *event); - void processMouseEvent(QMouseEvent* ev); - void processKeyEvent(QKeyEvent* ev); - - int cursorBlinkPeriod() const { return m_blinkPeriod; } - void setCursorBlinkPeriod(int msec); - void resetCursorBlinkTimer(); - - QString cancelText() const { return m_cancelText; } - void setCancelText(const QString &text) { m_cancelText = text; } - - const QPalette &palette() const { return m_palette; } - void setPalette(const QPalette &p) { m_palette = p; } - - enum DrawFlags { - DrawText = 0x01, - DrawSelections = 0x02, - DrawCursor = 0x04, - DrawAll = DrawText | DrawSelections | DrawCursor - }; - void draw(QPainter *, const QPoint &, const QRect &, int flags = DrawAll); - - bool processEvent(QEvent *ev); - -private: - void init(const QString &txt); - void removeSelectedText(); - void internalSetText(const QString &txt, int pos = -1, bool edited = true); - void updateDisplayText(bool forceUpdate = false); - - void internalInsert(const QString &s); - void internalDelete(bool wasBackspace = false); - void internalRemove(int pos); - - inline void internalDeselect() - { - m_selDirty |= (m_selend > m_selstart); - m_selstart = m_selend = 0; - } - - void internalUndo(int until = -1); - void internalRedo(); - - QString m_text; - QPalette m_palette; - int m_cursor; - int m_preeditCursor; - int m_cursorWidth; - Qt::LayoutDirection m_layoutDirection; - uint m_hideCursor : 1; // used to hide the m_cursor inside preedit areas - uint m_separator : 1; - uint m_readOnly : 1; - uint m_dragEnabled : 1; - uint m_echoMode : 2; - uint m_textDirty : 1; - uint m_selDirty : 1; - uint m_validInput : 1; - uint m_blinkStatus : 1; - int m_blinkPeriod; // 0 for non-blinking cursor - int m_blinkTimer; - int m_deleteAllTimer; - int m_ascent; - int m_maxLength; - int m_lastCursorPos; - QList m_transactions; - QPoint m_tripleClick; - int m_tripleClickTimer; - QString m_cancelText; - - void emitCursorPositionChanged(); - - bool finishChange(int validateFromState = -1, bool update = false, bool edited = true); - -#ifndef QT_NO_VALIDATOR - QPointer m_validator; -#endif - QPointer m_completer; -#ifndef QT_NO_COMPLETER - bool advanceToEnabledItem(int dir); -#endif - - struct MaskInputData { - enum Casemode { NoCaseMode, Upper, Lower }; - QChar maskChar; // either the separator char or the inputmask - bool separator; - Casemode caseMode; - }; - QString m_inputMask; - QChar m_blank; - MaskInputData *m_maskData; - - // undo/redo handling - enum CommandType { Separator, Insert, Remove, Delete, RemoveSelection, DeleteSelection, SetSelection }; - struct Command { - inline Command() {} - inline Command(CommandType t, int p, QChar c, int ss, int se) : type(t),uc(c),pos(p),selStart(ss),selEnd(se) {} - uint type : 4; - QChar uc; - int pos, selStart, selEnd; - }; - int m_modifiedState; - int m_undoState; - QVector m_history; - void addCommand(const Command& cmd); - - inline void separate() { m_separator = true; } - - // selection - int m_selstart; - int m_selend; - - // masking - void parseInputMask(const QString &maskFields); - bool isValidInput(QChar key, QChar mask) const; - bool hasAcceptableInput(const QString &text) const; - QString maskString(uint pos, const QString &str, bool clear = false) const; - QString clearString(uint pos, uint len) const; - QString stripString(const QString &str) const; - int findInMask(int pos, bool forward, bool findSeparator, QChar searchChar = QChar()) const; - - // complex text layout - QTextLayout m_textLayout; - - bool m_passwordEchoEditing; - QChar m_passwordCharacter; - -Q_SIGNALS: - void cursorPositionChanged(int, int); - void selectionChanged(); - - void displayTextChanged(const QString &); - void textChanged(const QString &); - void textEdited(const QString &); - - void resetInputContext(); - void updateMicroFocus(); - - void accepted(); - void editingFinished(); - void updateNeeded(const QRect &); - -#ifdef QT_KEYPAD_NAVIGATION - void editFocusChange(bool); -#endif -protected: - virtual void timerEvent(QTimerEvent *event); - -private Q_SLOTS: - void _q_clipboardChanged(); - void _q_deleteSelected(); - -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QT_NO_LINEEDIT - -#endif // QLINECONTROL_P_H diff --git a/src/gui/widgets/widgets.pri b/src/gui/widgets/widgets.pri index 4cbcbe3983..9797d6c717 100644 --- a/src/gui/widgets/widgets.pri +++ b/src/gui/widgets/widgets.pri @@ -30,7 +30,6 @@ HEADERS += \ widgets/qlcdnumber.h \ widgets/qlineedit.h \ widgets/qlineedit_p.h \ - widgets/qlinecontrol_p.h \ widgets/qmainwindow.h \ widgets/qmainwindowlayout_p.h \ widgets/qmdiarea.h \ @@ -103,7 +102,6 @@ SOURCES += \ widgets/qlcdnumber.cpp \ widgets/qlineedit_p.cpp \ widgets/qlineedit.cpp \ - widgets/qlinecontrol.cpp \ widgets/qmainwindow.cpp \ widgets/qmainwindowlayout.cpp \ widgets/qmdiarea.cpp \ -- cgit v1.2.3