From 8b011bf8477f9a25afea68422edebc9ac996e592 Mon Sep 17 00:00:00 2001 From: zhangjiaping Date: Wed, 6 Jan 2021 09:59:08 +0800 Subject: [PATCH] feat(searchList): Add keyword highlight. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Description: 关键字高亮 Log: 关键字高亮 --- libsearch/global-settings.cpp | 24 +- libsearch/global-settings.h | 8 +- libsearch/libsearch.h | 1 + singleapplication/QtLockedFile | 1 - singleapplication/QtSingleApplication | 1 - singleapplication/qt-local-peer.cpp | 213 ---------- singleapplication/qt-local-peer.h | 77 ---- singleapplication/qt-single-application.cpp | 364 ------------------ singleapplication/qt-single-application.h | 105 ----- singleapplication/qt-single-application.pri | 24 -- singleapplication/qtlockedfile.cpp | 193 ---------- singleapplication/qtlockedfile.h | 97 ----- singleapplication/qtlockedfile_unix.cpp | 115 ------ singleapplication/qtlockedfile_win.cpp | 211 ---------- singleapplication/qtsinglecoreapplication.cpp | 149 ------- singleapplication/qtsinglecoreapplication.h | 71 ---- singleapplication/qtsinglecoreapplication.pri | 10 - src/content-widget.cpp | 9 +- src/content-widget.h | 2 +- src/control/control.pri | 2 + src/control/highlight-item-delegate.cpp | 147 +++++++ src/control/highlight-item-delegate.h | 19 + src/control/search-detail-view.cpp | 32 +- src/control/search-detail-view.h | 4 +- src/control/search-list-view.cpp | 5 +- src/control/search-list-view.h | 5 +- src/main.cpp | 2 +- src/mainwindow.cpp | 12 +- src/model/search-item-model.cpp | 3 + src/settings-widget.cpp | 2 + src/settings-widget.h | 2 + 31 files changed, 248 insertions(+), 1662 deletions(-) delete mode 100644 singleapplication/QtLockedFile delete mode 100644 singleapplication/QtSingleApplication delete mode 100644 singleapplication/qt-local-peer.cpp delete mode 100644 singleapplication/qt-local-peer.h delete mode 100644 singleapplication/qt-single-application.cpp delete mode 100644 singleapplication/qt-single-application.h delete mode 100644 singleapplication/qt-single-application.pri delete mode 100644 singleapplication/qtlockedfile.cpp delete mode 100644 singleapplication/qtlockedfile.h delete mode 100644 singleapplication/qtlockedfile_unix.cpp delete mode 100644 singleapplication/qtlockedfile_win.cpp delete mode 100644 singleapplication/qtsinglecoreapplication.cpp delete mode 100644 singleapplication/qtsinglecoreapplication.h delete mode 100644 singleapplication/qtsinglecoreapplication.pri create mode 100644 src/control/highlight-item-delegate.cpp create mode 100644 src/control/highlight-item-delegate.h diff --git a/libsearch/global-settings.cpp b/libsearch/global-settings.cpp index 50b5765..66c2877 100644 --- a/libsearch/global-settings.cpp +++ b/libsearch/global-settings.cpp @@ -3,17 +3,17 @@ #include #include "global-settings.h" -static GlobalSettings *global_instance = nullptr; +static GlobalSettingsZjp *global_instance = nullptr; -GlobalSettings *GlobalSettings::getInstance() +GlobalSettingsZjp *GlobalSettingsZjp::getInstance() { if (!global_instance) { - global_instance = new GlobalSettings; + global_instance = new GlobalSettingsZjp; } return global_instance; } -GlobalSettings::GlobalSettings(QObject *parent) : QObject(parent) +GlobalSettingsZjp::GlobalSettingsZjp(QObject *parent) : QObject(parent) { m_settings = new QSettings("org.ukui", "ukui-search", this); //the default number of transparency in mainwindow is 0.7 @@ -33,22 +33,22 @@ GlobalSettings::GlobalSettings(QObject *parent) : QObject(parent) m_cache.insert(TRANSPARENCY_KEY, m_gsettings->get(TRANSPARENCY_KEY).toDouble()); } -GlobalSettings::~GlobalSettings() +GlobalSettingsZjp::~GlobalSettingsZjp() { } -const QVariant GlobalSettings::getValue(const QString &key) +const QVariant GlobalSettingsZjp::getValue(const QString &key) { return m_cache.value(key); } -bool GlobalSettings::isExist(const QString &key) +bool GlobalSettingsZjp::isExist(const QString &key) { return !m_cache.value(key).isNull(); } -void GlobalSettings::reset(const QString &key) +void GlobalSettingsZjp::reset(const QString &key) { m_cache.remove(key); QtConcurrent::run([=]() { @@ -61,7 +61,7 @@ void GlobalSettings::reset(const QString &key) Q_EMIT this->valueChanged(key); } -void GlobalSettings::resetAll() +void GlobalSettingsZjp::resetAll() { QStringList tmp = m_cache.keys(); m_cache.clear(); @@ -77,12 +77,12 @@ void GlobalSettings::resetAll() }); } -QList GlobalSettings::getBlockDirs() +QList GlobalSettingsZjp::getBlockDirs() { return m_cache.keys(); } -void GlobalSettings::setValue(const QString &key, const QVariant &value) +void GlobalSettingsZjp::setValue(const QString &key, const QVariant &value) { m_cache.insert(key, value); QtConcurrent::run([=]() { @@ -94,7 +94,7 @@ void GlobalSettings::setValue(const QString &key, const QVariant &value) }); } -void GlobalSettings::forceSync(const QString &key) +void GlobalSettingsZjp::forceSync(const QString &key) { m_settings->sync(); if (key.isNull()) { diff --git a/libsearch/global-settings.h b/libsearch/global-settings.h index 4a3e3d6..1837713 100644 --- a/libsearch/global-settings.h +++ b/libsearch/global-settings.h @@ -18,11 +18,11 @@ #define CONTENT_INDEX_DATABASE_STATE "content_index_database_state" #define INDEX_GENERATOR_NORMAL_EXIT "index_generator_normal_exit" -class LIBSEARCH_EXPORT GlobalSettings : public QObject +class LIBSEARCH_EXPORT GlobalSettingsZjp : public QObject { Q_OBJECT public: - static GlobalSettings *getInstance(); + static GlobalSettingsZjp *getInstance(); const QVariant getValue(const QString&); bool isExist(const QString&); @@ -39,8 +39,8 @@ public Q_SLOTS: void forceSync(const QString& = nullptr); private: - explicit GlobalSettings(QObject *parent = nullptr); - ~GlobalSettings(); + explicit GlobalSettingsZjp(QObject *parent = nullptr); + ~GlobalSettingsZjp(); QSettings* m_settings; QGSettings* m_gsettings; diff --git a/libsearch/libsearch.h b/libsearch/libsearch.h index 8c1c3b2..db29471 100644 --- a/libsearch/libsearch.h +++ b/libsearch/libsearch.h @@ -7,6 +7,7 @@ #include "settingsearch/setting-match.h" #include "index/inotify.h" #include "file-utils.h" +#include "global-settings.h" #include "index/filetypefilter.h" diff --git a/singleapplication/QtLockedFile b/singleapplication/QtLockedFile deleted file mode 100644 index 16b48ba..0000000 --- a/singleapplication/QtLockedFile +++ /dev/null @@ -1 +0,0 @@ -#include "qtlockedfile.h" diff --git a/singleapplication/QtSingleApplication b/singleapplication/QtSingleApplication deleted file mode 100644 index 7284e11..0000000 --- a/singleapplication/QtSingleApplication +++ /dev/null @@ -1 +0,0 @@ -#include "qt-single-application.h" diff --git a/singleapplication/qt-local-peer.cpp b/singleapplication/qt-local-peer.cpp deleted file mode 100644 index f90195d..0000000 --- a/singleapplication/qt-local-peer.cpp +++ /dev/null @@ -1,213 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Solutions component. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#include "qt-local-peer.h" -#include -#include -#include - -#if defined(Q_OS_WIN) -#include -#include -typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*); -static PProcessIdToSessionId pProcessIdToSessionId = 0; -#endif -#if defined(Q_OS_UNIX) -#include -#include -#include -#endif - -namespace QtLP_Private { -#include "qtlockedfile.cpp" -#if defined(Q_OS_WIN) -#include "qtlockedfile_win.cpp" -#else -#include "qtlockedfile_unix.cpp" -#endif -} - -const char* QtLocalPeer::ack = "ack"; - -QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId) - : QObject(parent), id(appId) -{ - QString prefix = id; - if (id.isEmpty()) { - id = QCoreApplication::applicationFilePath(); -#if defined(Q_OS_WIN) - id = id.toLower(); -#endif - prefix = id.section(QLatin1Char('/'), -1); - } - prefix.remove(QRegExp("[^a-zA-Z]")); - prefix.truncate(6); - - QByteArray idc = id.toUtf8(); - quint16 idNum = qChecksum(idc.constData(), idc.size()); - socketName = QLatin1String("qtsingleapp-") + prefix - + QLatin1Char('-') + QString::number(idNum, 16); - -#if defined(Q_OS_WIN) - if (!pProcessIdToSessionId) { - QLibrary lib("kernel32"); - pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId"); - } - if (pProcessIdToSessionId) { - DWORD sessionId = 0; - pProcessIdToSessionId(GetCurrentProcessId(), &sessionId); - socketName += QLatin1Char('-') + QString::number(sessionId, 16); - } -#else - socketName += QLatin1Char('-') + QString::number(::getuid(), 16); -#endif - - server = new QLocalServer(this); - QString lockName = QDir(QDir::tempPath()).absolutePath() - + QLatin1Char('/') + socketName - + QLatin1String("-lockfile"); - lockFile.setFileName(lockName); - lockFile.open(QIODevice::ReadWrite); -} - - - -bool QtLocalPeer::isClient() -{ - if (lockFile.isLocked()) - return false; - - if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false)) - return true; - - bool res = server->listen(socketName); -#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0)) - // ### Workaround - if (!res && server->serverError() == QAbstractSocket::AddressInUseError) { - QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName); - res = server->listen(socketName); - } -#endif - if (!res) - qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString())); - QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection())); - return false; -} - - -bool QtLocalPeer::sendMessage(const QString &message, int timeout) -{ - if (!isClient()) - return false; - - QLocalSocket socket; - bool connOk = false; - for(int i = 0; i < 2; i++) { - // Try twice, in case the other instance is just starting up - socket.connectToServer(socketName); - connOk = socket.waitForConnected(timeout/2); - if (connOk || i) - break; - int ms = 250; -#if defined(Q_OS_WIN) - Sleep(DWORD(ms)); -#else - struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; - nanosleep(&ts, NULL); -#endif - } - if (!connOk) - return false; - - QByteArray uMsg(message.toUtf8()); - QDataStream ds(&socket); - ds.writeBytes(uMsg.constData(), uMsg.size()); - bool res = socket.waitForBytesWritten(timeout); - if (res) { - res &= socket.waitForReadyRead(timeout); // wait for ack - if (res) - res &= (socket.read(qstrlen(ack)) == ack); - } - return res; -} - - -void QtLocalPeer::receiveConnection() -{ - QLocalSocket* socket = server->nextPendingConnection(); - if (!socket) - return; - - while (true) { - if (socket->state() == QLocalSocket::UnconnectedState) { - qWarning("QtLocalPeer: Peer disconnected"); - delete socket; - return; - } - if (socket->bytesAvailable() >= qint64(sizeof(quint32))) - break; - socket->waitForReadyRead(); - } - - QDataStream ds(socket); - QByteArray uMsg; - quint32 remaining; - ds >> remaining; - uMsg.resize(remaining); - int got = 0; - char* uMsgBuf = uMsg.data(); - do { - got = ds.readRawData(uMsgBuf, remaining); - remaining -= got; - uMsgBuf += got; - } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); - if (got < 0) { - qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); - delete socket; - return; - } - QString message(QString::fromUtf8(uMsg)); - socket->write(ack, qstrlen(ack)); - socket->waitForBytesWritten(1000); - socket->waitForDisconnected(1000); // make sure client reads ack - delete socket; - Q_EMIT messageReceived(message); //### (might take a long time to return) -} diff --git a/singleapplication/qt-local-peer.h b/singleapplication/qt-local-peer.h deleted file mode 100644 index 1b533b1..0000000 --- a/singleapplication/qt-local-peer.h +++ /dev/null @@ -1,77 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Solutions component. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QTLOCALPEER_H -#define QTLOCALPEER_H - -#include -#include -#include - -#include "qtlockedfile.h" - -class QtLocalPeer : public QObject -{ - Q_OBJECT - -public: - QtLocalPeer(QObject *parent = 0, const QString &appId = QString()); - bool isClient(); - bool sendMessage(const QString &message, int timeout); - QString applicationId() const - { return id; } - -Q_SIGNALS: - void messageReceived(const QString &message); - -protected Q_SLOTS: - void receiveConnection(); - -protected: - QString id; - QString socketName; - QLocalServer* server; - QtLP_Private::QtLockedFile lockFile; - -private: - static const char* ack; -}; - -#endif // QTLOCALPEER_H diff --git a/singleapplication/qt-single-application.cpp b/singleapplication/qt-single-application.cpp deleted file mode 100644 index 710fa4c..0000000 --- a/singleapplication/qt-single-application.cpp +++ /dev/null @@ -1,364 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Solutions component. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#include "qt-single-application.h" -#include "qt-local-peer.h" -#include -#include -#include -#include -#include -#include "src/mainwindow.h" - - -/*! - \class QtSingleApplication qtsingleapplication.h - \brief The QtSingleApplication class provides an API to detect and - communicate with running instances of an application. - - This class allows you to create applications where only one - instance should be running at a time. I.e., if the user tries to - launch another instance, the already running instance will be - activated instead. Another usecase is a client-server system, - where the first started instance will assume the role of server, - and the later instances will act as clients of that server. - - By default, the full path of the executable file is used to - determine whether two processes are instances of the same - application. You can also provide an explicit identifier string - that will be compared instead. - - The application should create the QtSingleApplication object early - in the startup phase, and call isRunning() to find out if another - instance of this application is already running. If isRunning() - returns false, it means that no other instance is running, and - this instance has assumed the role as the running instance. In - this case, the application should continue with the initialization - of the application user interface before entering the event loop - with exec(), as normal. - - The messageReceived() signal will be emitted when the running - application receives messages from another instance of the same - application. When a message is received it might be helpful to the - user to raise the application so that it becomes visible. To - facilitate this, QtSingleApplication provides the - setActivationWindow() function and the activateWindow() slot. - - If isRunning() returns true, another instance is already - running. It may be alerted to the fact that another instance has - started by using the sendMessage() function. Also data such as - startup parameters (e.g. the name of the file the user wanted this - new instance to open) can be passed to the running instance with - this function. Then, the application should terminate (or enter - client mode). - - If isRunning() returns true, but sendMessage() fails, that is an - indication that the running instance is frozen. - - Here's an example that shows how to convert an existing - application to use QtSingleApplication. It is very simple and does - not make use of all QtSingleApplication's functionality (see the - examples for that). - - \code - // Original - int main(int argc, char **argv) - { - QApplication app(argc, argv); - - MyMainWidget mmw; - mmw.show(); - return app.exec(); - } - - // Single instance - int main(int argc, char **argv) - { - QtSingleApplication app(argc, argv); - - if (app.isRunning()) - return !app.sendMessage(someDataString); - - MyMainWidget mmw; - app.setActivationWindow(&mmw); - mmw.show(); - return app.exec(); - } - \endcode - - Once this QtSingleApplication instance is destroyed (normally when - the process exits or crashes), when the user next attempts to run the - application this instance will not, of course, be encountered. The - next instance to call isRunning() or sendMessage() will assume the - role as the new running instance. - - For console (non-GUI) applications, QtSingleCoreApplication may be - used instead of this class, to avoid the dependency on the QtGui - library. - - \sa QtSingleCoreApplication -*/ - - -void QtSingleApplication::sysInit(const QString &appId) -{ - actWin = 0; - peer = new QtLocalPeer(this, appId); - connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&))); -} - - -/*! - Creates a QtSingleApplication object. The application identifier - will be QCoreApplication::applicationFilePath(). \a argc, \a - argv, and \a GUIenabled are passed on to the QAppliation constructor. - - If you are creating a console application (i.e. setting \a - GUIenabled to false), you may consider using - QtSingleCoreApplication instead. -*/ - -QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled) - : QApplication(argc, argv, GUIenabled) -{ - sysInit(); -} - - -/*! - Creates a QtSingleApplication object with the application - identifier \a appId. \a argc and \a argv are passed on to the - QAppliation constructor. -*/ - -QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv) - : QApplication(argc, argv) -{ - sysInit(appId); -} - -#if QT_VERSION < 0x050000 - -/*! - Creates a QtSingleApplication object. The application identifier - will be QCoreApplication::applicationFilePath(). \a argc, \a - argv, and \a type are passed on to the QAppliation constructor. -*/ -QtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type) - : QApplication(argc, argv, type) -{ - sysInit(); -} - - -# if defined(Q_WS_X11) -/*! - Special constructor for X11, ref. the documentation of - QApplication's corresponding constructor. The application identifier - will be QCoreApplication::applicationFilePath(). \a dpy, \a visual, - and \a cmap are passed on to the QApplication constructor. -*/ -QtSingleApplication::QtSingleApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE cmap) - : QApplication(dpy, visual, cmap) -{ - sysInit(); -} - -/*! - Special constructor for X11, ref. the documentation of - QApplication's corresponding constructor. The application identifier - will be QCoreApplication::applicationFilePath(). \a dpy, \a argc, \a - argv, \a visual, and \a cmap are passed on to the QApplication - constructor. -*/ -QtSingleApplication::QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) - : QApplication(dpy, argc, argv, visual, cmap) -{ - sysInit(); -} - -/*! - Special constructor for X11, ref. the documentation of - QApplication's corresponding constructor. The application identifier - will be \a appId. \a dpy, \a argc, \a - argv, \a visual, and \a cmap are passed on to the QApplication - constructor. -*/ -QtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) - : QApplication(dpy, argc, argv, visual, cmap) -{ - sysInit(appId); -} -# endif // Q_WS_X11 -#endif // QT_VERSION < 0x050000 - - -/*! - Returns true if another instance of this application is running; - otherwise false. - - This function does not find instances of this application that are - being run by a different user (on Windows: that are running in - another session). - - \sa sendMessage() -*/ - -bool QtSingleApplication::isRunning() -{ - return peer->isClient(); -} - - -/*! - Tries to send the text \a message to the currently running - instance. The QtSingleApplication object in the running instance - will emit the messageReceived() signal when it receives the - message. - - This function returns true if the message has been sent to, and - processed by, the current instance. If there is no instance - currently running, or if the running instance fails to process the - message within \a timeout milliseconds, this function return false. - - \sa isRunning(), messageReceived() -*/ -bool QtSingleApplication::sendMessage(const QString &message, int timeout) -{ - return peer->sendMessage(message, timeout); -} - - -/*! - Returns the application identifier. Two processes with the same - identifier will be regarded as instances of the same application. -*/ -QString QtSingleApplication::id() const -{ - return peer->applicationId(); -} - - -/*! - Sets the activation window of this application to \a aw. The - activation window is the widget that will be activated by - activateWindow(). This is typically the application's main window. - - If \a activateOnMessage is true (the default), the window will be - activated automatically every time a message is received, just prior - to the messageReceived() signal being emitted. - - \sa activateWindow(), messageReceived() -*/ - -void QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage) -{ - actWin = aw; - if (activateOnMessage) - connect(peer, SIGNAL(messageReceived(const QString&)), this, SLOT(activateWindow())); - else - disconnect(peer, SIGNAL(messageReceived(const QString&)), this, SLOT(activateWindow())); -} - - -/*! - Returns the applications activation window if one has been set by - calling setActivationWindow(), otherwise returns 0. - - \sa setActivationWindow() -*/ -QWidget* QtSingleApplication::activationWindow() const -{ - return actWin; -} - - -/*! - De-minimizes, raises, and activates this application's activation window. - This function does nothing if no activation window has been set. - - This is a convenience function to show the user that this - application instance has been activated when he has tried to start - another instance. - - This function should typically be called in response to the - messageReceived() signal. By default, that will happen - automatically, if an activation window has been set. - - \sa setActivationWindow(), messageReceived(), initialize() -*/ -void QtSingleApplication::activateWindow() -{ - if (actWin) { - if(this->applicationState() & Qt::ApplicationInactive) - { - MainWindow* w=qobject_cast(actWin); -// w->loadMainWindow(); - w->clearSearchResult(); - actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized); - actWin->raise(); - actWin->showNormal(); - actWin->activateWindow(); - } - else { - actWin->setWindowState(actWin->windowState() & Qt::WindowMinimized); - actWin->hide(); - } - - } -} - - -/*! - \fn void QtSingleApplication::messageReceived(const QString& message) - - This signal is emitted when the current instance receives a \a - message from another instance of this application. - - \sa sendMessage(), setActivationWindow(), activateWindow() -*/ - - -/*! - \fn void QtSingleApplication::initialize(bool dummy = true) - - \obsolete -*/ diff --git a/singleapplication/qt-single-application.h b/singleapplication/qt-single-application.h deleted file mode 100644 index 049406f..0000000 --- a/singleapplication/qt-single-application.h +++ /dev/null @@ -1,105 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Solutions component. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QTSINGLEAPPLICATION_H -#define QTSINGLEAPPLICATION_H - -#include - -class QtLocalPeer; - -#if defined(Q_OS_WIN) -# if !defined(QT_QTSINGLEAPPLICATION_EXPORT) && !defined(QT_QTSINGLEAPPLICATION_IMPORT) -# define QT_QTSINGLEAPPLICATION_EXPORT -# elif defined(QT_QTSINGLEAPPLICATION_IMPORT) -# if defined(QT_QTSINGLEAPPLICATION_EXPORT) -# undef QT_QTSINGLEAPPLICATION_EXPORT -# endif -# define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllimport) -# elif defined(QT_QTSINGLEAPPLICATION_EXPORT) -# undef QT_QTSINGLEAPPLICATION_EXPORT -# define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllexport) -# endif -#else -# define QT_QTSINGLEAPPLICATION_EXPORT -#endif - -class QT_QTSINGLEAPPLICATION_EXPORT QtSingleApplication : public QApplication -{ - Q_OBJECT - -public: - QtSingleApplication(int &argc, char **argv, bool GUIenabled = true); - QtSingleApplication(const QString &id, int &argc, char **argv); -#if QT_VERSION < 0x050000 - QtSingleApplication(int &argc, char **argv, Type type); -# if defined(Q_WS_X11) - QtSingleApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); - QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap= 0); - QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); -# endif // Q_WS_X11 -#endif // QT_VERSION < 0x050000 - - bool isRunning(); - QString id() const; - - void setActivationWindow(QWidget* aw, bool activateOnMessage = true); - QWidget* activationWindow() const; - - // Obsolete: - void initialize(bool dummy = true) - { isRunning(); Q_UNUSED(dummy) } - -public Q_SLOTS: - bool sendMessage(const QString &message, int timeout = 5000); - void activateWindow(); - - -Q_SIGNALS: - void messageReceived(const QString &message); - - -private: - void sysInit(const QString &appId = QString()); - QtLocalPeer *peer; - QWidget *actWin; -}; - -#endif // QTSINGLEAPPLICATION_H diff --git a/singleapplication/qt-single-application.pri b/singleapplication/qt-single-application.pri deleted file mode 100644 index cd136ac..0000000 --- a/singleapplication/qt-single-application.pri +++ /dev/null @@ -1,24 +0,0 @@ -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD -QT *= network -greaterThan(QT_MAJOR_VERSION, 4): QT *= widgets - -qtsingleapplication-uselib:!qtsingleapplication-buildlib { - LIBS += -L$$QTSINGLEAPPLICATION_LIBDIR -l$$QTSINGLEAPPLICATION_LIBNAME -} else { - SOURCES += - HEADERS += -} - -win32 { - contains(TEMPLATE, lib):contains(CONFIG, shared):DEFINES += QT_QTSINGLEAPPLICATION_EXPORT - else:qtsingleapplication-uselib:DEFINES += QT_QTSINGLEAPPLICATION_IMPORT -} - -HEADERS += \ - $$PWD/qt-local-peer.h \ - $$PWD/qt-single-application.h - -SOURCES += \ - $$PWD/qt-local-peer.cpp \ - $$PWD/qt-single-application.cpp diff --git a/singleapplication/qtlockedfile.cpp b/singleapplication/qtlockedfile.cpp deleted file mode 100644 index c142a86..0000000 --- a/singleapplication/qtlockedfile.cpp +++ /dev/null @@ -1,193 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Solutions component. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qtlockedfile.h" - -/*! - \class QtLockedFile - - \brief The QtLockedFile class extends QFile with advisory locking - functions. - - A file may be locked in read or write mode. Multiple instances of - \e QtLockedFile, created in multiple processes running on the same - machine, may have a file locked in read mode. Exactly one instance - may have it locked in write mode. A read and a write lock cannot - exist simultaneously on the same file. - - The file locks are advisory. This means that nothing prevents - another process from manipulating a locked file using QFile or - file system functions offered by the OS. Serialization is only - guaranteed if all processes that access the file use - QLockedFile. Also, while holding a lock on a file, a process - must not open the same file again (through any API), or locks - can be unexpectedly lost. - - The lock provided by an instance of \e QtLockedFile is released - whenever the program terminates. This is true even when the - program crashes and no destructors are called. -*/ - -/*! \enum QtLockedFile::LockMode - - This enum describes the available lock modes. - - \value ReadLock A read lock. - \value WriteLock A write lock. - \value NoLock Neither a read lock nor a write lock. -*/ - -/*! - Constructs an unlocked \e QtLockedFile object. This constructor - behaves in the same way as \e QFile::QFile(). - - \sa QFile::QFile() -*/ -QtLockedFile::QtLockedFile() - : QFile() -{ -#ifdef Q_OS_WIN - wmutex = 0; - rmutex = 0; -#endif - m_lock_mode = NoLock; -} - -/*! - Constructs an unlocked QtLockedFile object with file \a name. This - constructor behaves in the same way as \e QFile::QFile(const - QString&). - - \sa QFile::QFile() -*/ -QtLockedFile::QtLockedFile(const QString &name) - : QFile(name) -{ -#ifdef Q_OS_WIN - wmutex = 0; - rmutex = 0; -#endif - m_lock_mode = NoLock; -} - -/*! - Opens the file in OpenMode \a mode. - - This is identical to QFile::open(), with the one exception that the - Truncate mode flag is disallowed. Truncation would conflict with the - advisory file locking, since the file would be modified before the - write lock is obtained. If truncation is required, use resize(0) - after obtaining the write lock. - - Returns true if successful; otherwise false. - - \sa QFile::open(), QFile::resize() -*/ -bool QtLockedFile::open(OpenMode mode) -{ - if (mode & QIODevice::Truncate) { - qWarning("QtLockedFile::open(): Truncate mode not allowed."); - return false; - } - return QFile::open(mode); -} - -/*! - Returns \e true if this object has a in read or write lock; - otherwise returns \e false. - - \sa lockMode() -*/ -bool QtLockedFile::isLocked() const -{ - return m_lock_mode != NoLock; -} - -/*! - Returns the type of lock currently held by this object, or \e - QtLockedFile::NoLock. - - \sa isLocked() -*/ -QtLockedFile::LockMode QtLockedFile::lockMode() const -{ - return m_lock_mode; -} - -/*! - \fn bool QtLockedFile::lock(LockMode mode, bool block = true) - - Obtains a lock of type \a mode. The file must be opened before it - can be locked. - - If \a block is true, this function will block until the lock is - aquired. If \a block is false, this function returns \e false - immediately if the lock cannot be aquired. - - If this object already has a lock of type \a mode, this function - returns \e true immediately. If this object has a lock of a - different type than \a mode, the lock is first released and then a - new lock is obtained. - - This function returns \e true if, after it executes, the file is - locked by this object, and \e false otherwise. - - \sa unlock(), isLocked(), lockMode() -*/ - -/*! - \fn bool QtLockedFile::unlock() - - Releases a lock. - - If the object has no lock, this function returns immediately. - - This function returns \e true if, after it executes, the file is - not locked by this object, and \e false otherwise. - - \sa lock(), isLocked(), lockMode() -*/ - -/*! - \fn QtLockedFile::~QtLockedFile() - - Destroys the \e QtLockedFile object. If any locks were held, they - are released. -*/ diff --git a/singleapplication/qtlockedfile.h b/singleapplication/qtlockedfile.h deleted file mode 100644 index 84c18e5..0000000 --- a/singleapplication/qtlockedfile.h +++ /dev/null @@ -1,97 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Solutions component. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QTLOCKEDFILE_H -#define QTLOCKEDFILE_H - -#include -#ifdef Q_OS_WIN -#include -#endif - -#if defined(Q_OS_WIN) -# if !defined(QT_QTLOCKEDFILE_EXPORT) && !defined(QT_QTLOCKEDFILE_IMPORT) -# define QT_QTLOCKEDFILE_EXPORT -# elif defined(QT_QTLOCKEDFILE_IMPORT) -# if defined(QT_QTLOCKEDFILE_EXPORT) -# undef QT_QTLOCKEDFILE_EXPORT -# endif -# define QT_QTLOCKEDFILE_EXPORT __declspec(dllimport) -# elif defined(QT_QTLOCKEDFILE_EXPORT) -# undef QT_QTLOCKEDFILE_EXPORT -# define QT_QTLOCKEDFILE_EXPORT __declspec(dllexport) -# endif -#else -# define QT_QTLOCKEDFILE_EXPORT -#endif - -namespace QtLP_Private { - -class QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile -{ -public: - enum LockMode { NoLock = 0, ReadLock, WriteLock }; - - QtLockedFile(); - QtLockedFile(const QString &name); - ~QtLockedFile(); - - bool open(OpenMode mode); - - bool lock(LockMode mode, bool block = true); - bool unlock(); - bool isLocked() const; - LockMode lockMode() const; - -private: -#ifdef Q_OS_WIN - Qt::HANDLE wmutex; - Qt::HANDLE rmutex; - QVector rmutexes; - QString mutexname; - - Qt::HANDLE getMutexHandle(int idx, bool doCreate); - bool waitMutex(Qt::HANDLE mutex, bool doBlock); - -#endif - LockMode m_lock_mode; -}; -} -#endif diff --git a/singleapplication/qtlockedfile_unix.cpp b/singleapplication/qtlockedfile_unix.cpp deleted file mode 100644 index 976c1b9..0000000 --- a/singleapplication/qtlockedfile_unix.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Solutions component. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include - -#include "qtlockedfile.h" - -bool QtLockedFile::lock(LockMode mode, bool block) -{ - if (!isOpen()) { - qWarning("QtLockedFile::lock(): file is not opened"); - return false; - } - - if (mode == NoLock) - return unlock(); - - if (mode == m_lock_mode) - return true; - - if (m_lock_mode != NoLock) - unlock(); - - struct flock fl; - fl.l_whence = SEEK_SET; - fl.l_start = 0; - fl.l_len = 0; - fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK; - int cmd = block ? F_SETLKW : F_SETLK; - int ret = fcntl(handle(), cmd, &fl); - - if (ret == -1) { - if (errno != EINTR && errno != EAGAIN) - qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); - return false; - } - - - m_lock_mode = mode; - return true; -} - - -bool QtLockedFile::unlock() -{ - if (!isOpen()) { - qWarning("QtLockedFile::unlock(): file is not opened"); - return false; - } - - if (!isLocked()) - return true; - - struct flock fl; - fl.l_whence = SEEK_SET; - fl.l_start = 0; - fl.l_len = 0; - fl.l_type = F_UNLCK; - int ret = fcntl(handle(), F_SETLKW, &fl); - - if (ret == -1) { - qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); - return false; - } - - m_lock_mode = NoLock; - return true; -} - -QtLockedFile::~QtLockedFile() -{ - if (isOpen()) - unlock(); -} - diff --git a/singleapplication/qtlockedfile_win.cpp b/singleapplication/qtlockedfile_win.cpp deleted file mode 100644 index 6144ea7..0000000 --- a/singleapplication/qtlockedfile_win.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Solutions component. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qtlockedfile.h" -#include -#include - -#define MUTEX_PREFIX "QtLockedFile mutex " -// Maximum number of concurrent read locks. Must not be greater than MAXIMUM_WAIT_OBJECTS -#define MAX_READERS MAXIMUM_WAIT_OBJECTS - -#if QT_VERSION >= 0x050000 -#define QT_WA(unicode, ansi) unicode -#endif - -Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate) -{ - if (mutexname.isEmpty()) { - QFileInfo fi(*this); - mutexname = QString::fromLatin1(MUTEX_PREFIX) - + fi.absoluteFilePath().toLower(); - } - QString mname(mutexname); - if (idx >= 0) - mname += QString::number(idx); - - Qt::HANDLE mutex; - if (doCreate) { - QT_WA( { mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); }, - { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); } ); - if (!mutex) { - qErrnoWarning("QtLockedFile::lock(): CreateMutex failed"); - return 0; - } - } - else { - QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR*)mname.utf16()); }, - { mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); } ); - if (!mutex) { - if (GetLastError() != ERROR_FILE_NOT_FOUND) - qErrnoWarning("QtLockedFile::lock(): OpenMutex failed"); - return 0; - } - } - return mutex; -} - -bool QtLockedFile::waitMutex(Qt::HANDLE mutex, bool doBlock) -{ - Q_ASSERT(mutex); - DWORD res = WaitForSingleObject(mutex, doBlock ? INFINITE : 0); - switch (res) { - case WAIT_OBJECT_0: - case WAIT_ABANDONED: - return true; - break; - case WAIT_TIMEOUT: - break; - default: - qErrnoWarning("QtLockedFile::lock(): WaitForSingleObject failed"); - } - return false; -} - - - -bool QtLockedFile::lock(LockMode mode, bool block) -{ - if (!isOpen()) { - qWarning("QtLockedFile::lock(): file is not opened"); - return false; - } - - if (mode == NoLock) - return unlock(); - - if (mode == m_lock_mode) - return true; - - if (m_lock_mode != NoLock) - unlock(); - - if (!wmutex && !(wmutex = getMutexHandle(-1, true))) - return false; - - if (!waitMutex(wmutex, block)) - return false; - - if (mode == ReadLock) { - int idx = 0; - for (; idx < MAX_READERS; idx++) { - rmutex = getMutexHandle(idx, false); - if (!rmutex || waitMutex(rmutex, false)) - break; - CloseHandle(rmutex); - } - bool ok = true; - if (idx >= MAX_READERS) { - qWarning("QtLockedFile::lock(): too many readers"); - rmutex = 0; - ok = false; - } - else if (!rmutex) { - rmutex = getMutexHandle(idx, true); - if (!rmutex || !waitMutex(rmutex, false)) - ok = false; - } - if (!ok && rmutex) { - CloseHandle(rmutex); - rmutex = 0; - } - ReleaseMutex(wmutex); - if (!ok) - return false; - } - else { - Q_ASSERT(rmutexes.isEmpty()); - for (int i = 0; i < MAX_READERS; i++) { - Qt::HANDLE mutex = getMutexHandle(i, false); - if (mutex) - rmutexes.append(mutex); - } - if (rmutexes.size()) { - DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(), - TRUE, block ? INFINITE : 0); - if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) { - if (res != WAIT_TIMEOUT) - qErrnoWarning("QtLockedFile::lock(): WaitForMultipleObjects failed"); - m_lock_mode = WriteLock; // trick unlock() to clean up - semiyucky - unlock(); - return false; - } - } - } - - m_lock_mode = mode; - return true; -} - -bool QtLockedFile::unlock() -{ - if (!isOpen()) { - qWarning("QtLockedFile::unlock(): file is not opened"); - return false; - } - - if (!isLocked()) - return true; - - if (m_lock_mode == ReadLock) { - ReleaseMutex(rmutex); - CloseHandle(rmutex); - rmutex = 0; - } - else { - Q_FOREACH(Qt::HANDLE mutex, rmutexes) { - ReleaseMutex(mutex); - CloseHandle(mutex); - } - rmutexes.clear(); - ReleaseMutex(wmutex); - } - - m_lock_mode = QtLockedFile::NoLock; - return true; -} - -QtLockedFile::~QtLockedFile() -{ - if (isOpen()) - unlock(); - if (wmutex) - CloseHandle(wmutex); -} diff --git a/singleapplication/qtsinglecoreapplication.cpp b/singleapplication/qtsinglecoreapplication.cpp deleted file mode 100644 index 5634537..0000000 --- a/singleapplication/qtsinglecoreapplication.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Solutions component. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#include "qtsinglecoreapplication.h" -#include "qtlocalpeer.h" - -/*! - \class QtSingleCoreApplication qtsinglecoreapplication.h - \brief A variant of the QtSingleApplication class for non-GUI applications. - - This class is a variant of QtSingleApplication suited for use in - console (non-GUI) applications. It is an extension of - QCoreApplication (instead of QApplication). It does not require - the QtGui library. - - The API and usage is identical to QtSingleApplication, except that - functions relating to the "activation window" are not present, for - obvious reasons. Please refer to the QtSingleApplication - documentation for explanation of the usage. - - A QtSingleCoreApplication instance can communicate to a - QtSingleApplication instance if they share the same application - id. Hence, this class can be used to create a light-weight - command-line tool that sends commands to a GUI application. - - \sa QtSingleApplication -*/ - -/*! - Creates a QtSingleCoreApplication object. The application identifier - will be QCoreApplication::applicationFilePath(). \a argc and \a - argv are passed on to the QCoreAppliation constructor. -*/ - -QtSingleCoreApplication::QtSingleCoreApplication(int &argc, char **argv) - : QCoreApplication(argc, argv) -{ - peer = new QtLocalPeer(this); - connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&))); -} - - -/*! - Creates a QtSingleCoreApplication object with the application - identifier \a appId. \a argc and \a argv are passed on to the - QCoreAppliation constructor. -*/ -QtSingleCoreApplication::QtSingleCoreApplication(const QString &appId, int &argc, char **argv) - : QCoreApplication(argc, argv) -{ - peer = new QtLocalPeer(this, appId); - connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&))); -} - - -/*! - Returns true if another instance of this application is running; - otherwise false. - - This function does not find instances of this application that are - being run by a different user (on Windows: that are running in - another session). - - \sa sendMessage() -*/ - -bool QtSingleCoreApplication::isRunning() -{ - return peer->isClient(); -} - - -/*! - Tries to send the text \a message to the currently running - instance. The QtSingleCoreApplication object in the running instance - will emit the messageReceived() signal when it receives the - message. - - This function returns true if the message has been sent to, and - processed by, the current instance. If there is no instance - currently running, or if the running instance fails to process the - message within \a timeout milliseconds, this function return false. - - \sa isRunning(), messageReceived() -*/ - -bool QtSingleCoreApplication::sendMessage(const QString &message, int timeout) -{ - return peer->sendMessage(message, timeout); -} - - -/*! - Returns the application identifier. Two processes with the same - identifier will be regarded as instances of the same application. -*/ - -QString QtSingleCoreApplication::id() const -{ - return peer->applicationId(); -} - - -/*! - \fn void QtSingleCoreApplication::messageReceived(const QString& message) - - This signal is emitted when the current instance receives a \a - message from another instance of this application. - - \sa sendMessage() -*/ diff --git a/singleapplication/qtsinglecoreapplication.h b/singleapplication/qtsinglecoreapplication.h deleted file mode 100644 index b87fffe..0000000 --- a/singleapplication/qtsinglecoreapplication.h +++ /dev/null @@ -1,71 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Solutions component. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QTSINGLECOREAPPLICATION_H -#define QTSINGLECOREAPPLICATION_H - -#include - -class QtLocalPeer; - -class QtSingleCoreApplication : public QCoreApplication -{ - Q_OBJECT - -public: - QtSingleCoreApplication(int &argc, char **argv); - QtSingleCoreApplication(const QString &id, int &argc, char **argv); - - bool isRunning(); - QString id() const; - -public Q_SLOTS: - bool sendMessage(const QString &message, int timeout = 5000); - - -Q_SIGNALS: - void messageReceived(const QString &message); - - -private: - QtLocalPeer* peer; -}; - -#endif // QTSINGLECOREAPPLICATION_H diff --git a/singleapplication/qtsinglecoreapplication.pri b/singleapplication/qtsinglecoreapplication.pri deleted file mode 100644 index d2d6cc3..0000000 --- a/singleapplication/qtsinglecoreapplication.pri +++ /dev/null @@ -1,10 +0,0 @@ -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD -HEADERS += $$PWD/qtsinglecoreapplication.h $$PWD/qtlocalpeer.h -SOURCES += $$PWD/qtsinglecoreapplication.cpp $$PWD/qtlocalpeer.cpp - -QT *= network - -win32:contains(TEMPLATE, lib):contains(CONFIG, shared) { - DEFINES += QT_QTSINGLECOREAPPLICATION_EXPORT=__declspec(dllexport) -} diff --git a/src/content-widget.cpp b/src/content-widget.cpp index 0a1f4da..295b42c 100644 --- a/src/content-widget.cpp +++ b/src/content-widget.cpp @@ -131,8 +131,9 @@ int ContentWidget::currentPage() { * @brief ContentWidget::refreshSearchList 刷新/构建搜索结果列表 * @param types 获取到的搜索结果类型,仅针对有搜索结果的类型构建listview * @param lists 获取到的搜索结果列表(每个类型对应一个列表) + * @param keyword 搜索关键字 */ -void ContentWidget::refreshSearchList(const QVector& types, const QVector& lists) { +void ContentWidget::refreshSearchList(const QVector& types, const QVector& lists, const QString& keyword) { if (!m_listLyt->isEmpty()) { clearSearchList(); } @@ -144,7 +145,7 @@ void ContentWidget::refreshSearchList(const QVector& types, const QVectorsetContentsMargins(8, 0, 0, 0); titleLabel->setStyleSheet("QLabel{background: rgba(0,0,0,0.1);}"); @@ -158,7 +159,7 @@ void ContentWidget::refreshSearchList(const QVector& types, const QVectorsetContent(m_contentList.at(searchList->currentIndex().row())); + m_detailView->setContent(m_contentList.at(searchList->currentIndex().row()), keyword); } m_detailView->setupWidget(type, path); searchList->is_current_list = true; @@ -178,7 +179,7 @@ void ContentWidget::refreshSearchList(const QVector& types, const QVectorclearLayout(); //没有搜到结果,清空详情页 return; } - SearchListView * searchList = new SearchListView(m_resultList, bestList, SearchItem::SearchType::Best); //Treeview + SearchListView * searchList = new SearchListView(m_resultList, bestList, SearchItem::SearchType::Best, keyword); //Treeview QLabel * titleLabel = new QLabel(m_resultList); //表头 titleLabel->setContentsMargins(8, 0, 0, 0); titleLabel->setStyleSheet("QLabel{background: rgba(0,0,0,0.1);}"); diff --git a/src/content-widget.h b/src/content-widget.h index 3c03abe..327a05a 100644 --- a/src/content-widget.h +++ b/src/content-widget.h @@ -17,7 +17,7 @@ public: void setPage(const int&); int currentPage(); - void refreshSearchList(const QVector&, const QVector&); + void refreshSearchList(const QVector&, const QVector&, const QString&); void initHomePage(const QVector&); void setContentList(const QStringList&); private: diff --git a/src/control/control.pri b/src/control/control.pri index 11120f7..39aaa21 100644 --- a/src/control/control.pri +++ b/src/control/control.pri @@ -3,6 +3,7 @@ INCLUDEPATH += $$PWD HEADERS += \ $$PWD/config-file.h \ $$PWD/folder-list-item.h \ + $$PWD/highlight-item-delegate.h \ $$PWD/search-list-view.h \ $$PWD/search-detail-view.h \ $$PWD/option-view.h \ @@ -11,6 +12,7 @@ HEADERS += \ SOURCES += \ $$PWD/config-file.cpp \ $$PWD/folder-list-item.cpp \ + $$PWD/highlight-item-delegate.cpp \ $$PWD/search-list-view.cpp \ $$PWD/search-detail-view.cpp \ $$PWD/option-view.cpp \ diff --git a/src/control/highlight-item-delegate.cpp b/src/control/highlight-item-delegate.cpp new file mode 100644 index 0000000..8bc1e0a --- /dev/null +++ b/src/control/highlight-item-delegate.cpp @@ -0,0 +1,147 @@ +#include "highlight-item-delegate.h" +#include +#include +#include +#include +#include +#include + +HighlightItemDelegate::HighlightItemDelegate() +{ +} + +/** + * \brief treewidget_styledItemDelegate::paint + * \param painter + * \param option + * \param index + */ +void HighlightItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const +{ + QStyleOptionViewItemV4 optionV4 = option; + initStyleOption(&optionV4, index); + + QStyle *style = optionV4.widget? optionV4.widget->style() : QApplication::style(); + + optionV4.text = QString(); + style->drawControl(QStyle::CE_ItemViewItem, &optionV4, painter); //绘制非文本区域内容 + if (index.model()->data(index,Qt::DisplayRole).toString().isEmpty()) return; + + QTextDocument doc; + doc.setHtml(getHtmlText(painter, option, index)); //提取富文本 + QAbstractTextDocumentLayout::PaintContext ctx; + + if (optionV4.state & QStyle::State_Selected) + ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active, QPalette::HighlightedText)); + + QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &optionV4); + textRect.adjust(0, 5, 0, 0); + painter->save(); + painter->translate(textRect.topLeft()); + painter->setClipRect(textRect.translated(-textRect.topLeft())); + doc.documentLayout()->draw(painter, ctx); //绘制文本区域内容 + painter->restore(); + + //以下为drawitemtext方法绘制文字,印加粗字体与原字体不等宽导致像素不对齐,视觉效果较差,已暂时摒弃 +// QStyleOptionViewItem itemOption = option; +// initStyleOption(&itemOption, index); +// if (itemOption.state & QStyle::State_HasFocus) { +// itemOption.state = itemOption.state ^ QStyle::State_HasFocus;//去掉选中时候的Item的虚线框,也就是焦点 +// } +// QStyledItemDelegate::paint(painter, itemOption, index); +// findKeyWord(painter, itemOption, index); +} + +/** + * @brief HighlightItemDelegate::getHtmlText 将文本区域内容转换为标记语言形式(在关键字左右加来加粗部分文字) + * @param painter + * @param itemOption + * @param index + * @return + */ +QString HighlightItemDelegate::getHtmlText(QPainter *painter, const QStyleOptionViewItem &itemOption, const QModelIndex &index) const +{ + int indexFindLeft = 0; + QString indexString = index.model()->data(index,Qt::DisplayRole).toString(); + QFontMetrics m_QFontMetrics = painter->fontMetrics(); + QString indexColString = m_QFontMetrics.elidedText(indexString, Qt::ElideRight, itemOption.rect.width() - 2); //当字体超过Item的长度时显示为省略号 + QString htmlString; + if ((indexColString.toUpper()).contains((m_regFindKeyWords.toUpper()))) { + indexFindLeft = indexColString.toUpper().indexOf(m_regFindKeyWords.toUpper()); //得到查找字体在当前整个Item字体中的位置 +// paintKeywordHighlight(painter, itemOption, indexColString, indexFindLeft, m_regFindKeyWords.length()); + htmlString = indexColString.left(indexFindLeft) + "" + indexColString.mid(indexFindLeft, m_regFindKeyWords.length())+ "" + indexColString.right(indexColString.length() - indexFindLeft - m_regFindKeyWords.length()); + } else { + bool boldOpenned = false; + for (int i = 0; i < indexColString.length(); i++) { + if ((m_regFindKeyWords.toUpper()).contains(QString(indexColString.at(i)).toUpper())) { +// paintKeywordHighlight(painter, itemOption, indexColString, i, 1); + if (! boldOpenned) { + boldOpenned = true; + htmlString.append(QString("")); + } + htmlString.append(QString(indexColString.at(i))); + } else { + if (boldOpenned) { + boldOpenned = false; + htmlString.append(QString("")); + } + htmlString.append(QString(indexColString.at(i))); + + } + } + } +// qDebug()<"<setPen(pen); + QFont font = QApplication::font(itemOption.widget); +// QFont boldFont = QApplication::font(itemOption.widget); +// boldFont.setBold(true); +// boldFont.setStyleStrategy(QFont::PreferAntialias); + painter->setFont(font); + painter->setRenderHint(QPainter::Antialiasing); + + QFontMetrics m_leftFontMetrics = painter->fontMetrics();//得到这个item原字体的像素 +// painter->setFont(boldFont); +// QFontMetrics m_QFontMetrics = painter->fontMetrics();//得到这个加粗字体的像素 + const QWidget * m_QWidget = itemOption.widget; + QStyle * m_QStyle = m_QWidget ? m_QWidget->style() : QApplication::style(); //得到当前的style + QRect m_QRect = itemOption.rect;//得到Item的自己的Rect + QPalette::ColorRole textDisplayRole = QPalette::NoRole; //设置text的role + if (itemOption.state & QStyle::State_Selected) + { + textDisplayRole = QPalette::HighlightedText; //当选中字体的时候字体显示高亮 + } else { + textDisplayRole = QPalette::Text; + } + + int findKeyWordWidth = m_leftFontMetrics.width(m_regFindKeyWords); //得到查找字体的像素宽度 + int preFindKeyWordWidth = m_leftFontMetrics.width(indexColString.mid(0,indexFindLeft)); //得到查找字体前面的字体的像素宽度 + + m_QRect = m_QRect.adjusted(preFindKeyWordWidth + 3, 0, findKeyWordWidth, 0); + //高亮字段 + m_QStyle->drawItemText(painter, m_QRect, itemOption.displayAlignment, QApplication::palette(), true, indexColString.mid(indexFindLeft, keywordLength), textDisplayRole); +// painter->restore(); +} + +/** + * \brief treewidget_styledItemDelegate::search_keyword 赋值关键字 + * \param regFindKeyWords + */ +void HighlightItemDelegate::setSearchKeyword(const QString ®FindKeyWords) +{ + m_regFindKeyWords.clear(); + m_regFindKeyWords = regFindKeyWords; +} diff --git a/src/control/highlight-item-delegate.h b/src/control/highlight-item-delegate.h new file mode 100644 index 0000000..5a23371 --- /dev/null +++ b/src/control/highlight-item-delegate.h @@ -0,0 +1,19 @@ +#ifndef HIGHLIGHTITEMDELEGATE_H +#define HIGHLIGHTITEMDELEGATE_H + +#include + +class HighlightItemDelegate : public QStyledItemDelegate +{ + Q_OBJECT +public: + explicit HighlightItemDelegate(); + void setSearchKeyword(const QString &); +private: + QString m_regFindKeyWords = 0; + void paint(QPainter *,const QStyleOptionViewItem &, const QModelIndex &) const override; + QString getHtmlText(QPainter *, const QStyleOptionViewItem &, const QModelIndex &) const; + void paintKeywordHighlight(QPainter *, const QStyleOptionViewItem &, const QString &, const int &, const int &) const; +}; + +#endif // HIGHLIGHTITEMDELEGATE_H diff --git a/src/control/search-detail-view.cpp b/src/control/search-detail-view.cpp index 84b5f5e..0b6b8a4 100644 --- a/src/control/search-detail-view.cpp +++ b/src/control/search-detail-view.cpp @@ -49,10 +49,33 @@ void SearchDetailView::clearLayout() { /** * @brief SearchDetailView::setContent 设置文本区域内容(仅内容搜索) - * @param text + * @param text 内容搜索结果组成的文段 + * @param keyword 搜索关键词 */ -void SearchDetailView::setContent(const QString& text) { +void SearchDetailView::setContent(const QString& text, const QString& keyword) { m_contentText = text; + m_keyword = keyword; +} + +QString SearchDetailView::getHtmlText(const QString & text, const QString & keyword) { + QString htmlString; + bool boldOpenned = false; + for (int i = 0; i < text.length(); i++) { + if ((keyword.toUpper()).contains(QString(text.at(i)).toUpper())) { + if (! boldOpenned) { + boldOpenned = true; + htmlString.append(QString("")); + } + htmlString.append(QString(text.at(i))); + } else { + if (boldOpenned) { + boldOpenned = false; + htmlString.append(QString("")); + } + htmlString.append(QString(text.at(i))); + } + } + return htmlString; } /** @@ -96,11 +119,12 @@ void SearchDetailView::setupWidget(const int& type, const QString& path) { QFrame * detailFrame = new QFrame(this); QVBoxLayout * detailLyt = new QVBoxLayout(detailFrame); detailLyt->setContentsMargins(0,0,0,0); - if (type == SearchListView::ResType::Content) { + if (type == SearchListView::ResType::Content) { //文件内容区域 QLabel * contentLabel = new QLabel(detailFrame); contentLabel->setWordWrap(true); contentLabel->setContentsMargins(9, 0, 9, 0); - contentLabel->setText(m_contentText); +// contentLabel->setText(m_contentText); + contentLabel->setText(QApplication::translate("", getHtmlText(m_contentText, m_keyword).toLocal8Bit(), nullptr)); detailLyt->addWidget(contentLabel); } QFrame * pathFrame = new QFrame(detailFrame); diff --git a/src/control/search-detail-view.h b/src/control/search-detail-view.h index 747c84a..3ecbe1b 100644 --- a/src/control/search-detail-view.h +++ b/src/control/search-detail-view.h @@ -13,16 +13,18 @@ public: void setupWidget(const int&, const QString&); void clearLayout(); - void setContent(const QString&); + void setContent(const QString&, const QString&); private: QVBoxLayout * m_layout = nullptr; QString m_contentText; + QString m_keyword; bool openAction(const int&, const QString&); bool addDesktopShortcut(const QString&); bool addPanelShortcut(const QString&); bool openPathAction(const QString&); bool copyPathAction(const QString&); + QString getHtmlText(const QString&, const QString&); Q_SIGNALS: private Q_SLOTS: diff --git a/src/control/search-list-view.cpp b/src/control/search-list-view.cpp index 134e1ae..1295d20 100644 --- a/src/control/search-list-view.cpp +++ b/src/control/search-list-view.cpp @@ -2,7 +2,7 @@ #include #include -SearchListView::SearchListView(QWidget * parent, const QStringList& list, const int& type) : QTreeView(parent) +SearchListView::SearchListView(QWidget * parent, const QStringList& list, const int& type, const QString& keyword) : QTreeView(parent) { setSelectionBehavior(QAbstractItemView::SelectRows); setSelectionMode(QAbstractItemView::SingleSelection); @@ -19,6 +19,9 @@ SearchListView::SearchListView(QWidget * parent, const QStringList& list, const this->setAttribute(Qt::WA_TranslucentBackground, true); this->setAutoFillBackground(false); this->setStyleSheet("QWidget{background:transparent;}"); + m_styleDelegate = new HighlightItemDelegate(); + m_styleDelegate->setSearchKeyword(keyword); + this->setItemDelegate(m_styleDelegate); m_type = type; connect(this->selectionModel(), &QItemSelectionModel::selectionChanged, this, [ = ]() { diff --git a/src/control/search-list-view.h b/src/control/search-list-view.h index b16c99f..8367c67 100644 --- a/src/control/search-list-view.h +++ b/src/control/search-list-view.h @@ -5,12 +5,13 @@ #include #include "model/search-item-model.h" #include "model/search-item.h" +#include "highlight-item-delegate.h" class SearchListView : public QTreeView { Q_OBJECT public: - explicit SearchListView(QWidget *, const QStringList&, const int&); + explicit SearchListView(QWidget *, const QStringList&, const int&, const QString&); ~SearchListView(); enum ResType { //搜索结果可能出现的类型:应用、文件、设置、文件夹 @@ -30,6 +31,8 @@ private: SearchItemModel * m_model = nullptr; SearchItem * m_item = nullptr; + HighlightItemDelegate * m_styleDelegate = nullptr; + int m_type; Q_SIGNALS: diff --git a/src/main.cpp b/src/main.cpp index 0b1b6e0..4a331d9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -76,7 +76,7 @@ int main(int argc, char *argv[]) /*-------------文本搜索 Test End-----------------*/ /*-------------GlobalSettings Test start-----------------*/ - GlobalSettings::getInstance(); +// GlobalSettings::getInstance(); /*-------------GlobalSettings Test End-----------------*/ diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index ebda995..e1adbce 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -33,6 +33,7 @@ //#include "inotify-manager.h" #include "settings-widget.h" +#include "global-settings.h" extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); /** @@ -56,7 +57,7 @@ MainWindow::MainWindow(QWidget *parent) : // im->start(); /*-------------Inotify Test End-----------------*/ - this->setWindowFlags(Qt::CustomizeWindowHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint); + this->setWindowFlags(Qt::CustomizeWindowHint | Qt::FramelessWindowHint); this->setAttribute(Qt::WA_TranslucentBackground, true); this->setAutoFillBackground(false); this->setFocusPolicy(Qt::StrongFocus); @@ -134,6 +135,12 @@ void MainWindow::initUi() } m_settingsWidget = new SettingsWidget(); m_settingsWidget->show(); + connect(m_settingsWidget, &SettingsWidget::settingWidgetClosed, this, [ = ]() { + QTimer::singleShot(100, this, [ = ] { + this->showNormal(); + m_settingsWidget->deleteLater(); + }); + }); }); m_titleLyt->addWidget(m_iconLabel); m_titleLyt->addWidget(m_titleLabel); @@ -302,7 +309,7 @@ void MainWindow::searchContent(QString searchcontent){ // QVector types; m_types.append(SearchItem::SearchType::Dirs); m_types.append(SearchItem::SearchType::Files); - m_contentFrame->refreshSearchList(m_types, m_lists); + m_contentFrame->refreshSearchList(m_types, m_lists, searchcontent); }); searcher->onKeywordSearch(searchcontent,0,10); // QStringList res = IndexGenerator::IndexSearch(searchcontent); @@ -320,6 +327,7 @@ double MainWindow::getTransparentData() //todo modify here!!!!!!!!!!!!!!!!!!!!!!!!!!!! //todo modify here!!!!!!!!!!!!!!!!!!!!!!!!!!!! //if you have questions, please ask iaom or MouseZhangZh +// return GlobalSettings::getInstance()->getValue(TRANSPARENCY_KEY).toDouble(); if (!m_transparency_gsettings) { return 0.7; } diff --git a/src/model/search-item-model.cpp b/src/model/search-item-model.cpp index 2b4e994..5b8b4b8 100644 --- a/src/model/search-item-model.cpp +++ b/src/model/search-item-model.cpp @@ -91,6 +91,9 @@ QVariant SearchItemModel::data(const QModelIndex &index, int role) const case Qt::DisplayRole: { return QVariant(m_item->getName(index.row())); } +// case Qt::ForegroundRole: { +// return QColor(50, 50, 50); +// } default: return QVariant(); } diff --git a/src/settings-widget.cpp b/src/settings-widget.cpp index bf50906..20a00c2 100644 --- a/src/settings-widget.cpp +++ b/src/settings-widget.cpp @@ -53,6 +53,7 @@ void SettingsWidget::initUi() { m_closeBtn->setStyleSheet("QPushButton{background: transparent;}" "QPushButton:hover:!pressed{background: transparent;}"); connect(m_closeBtn, &QPushButton::clicked, this, [ = ]() { + Q_EMIT this->settingWidgetClosed(); this->close(); }); m_titleLyt->addWidget(m_titleIcon); @@ -233,6 +234,7 @@ void SettingsWidget::onBtnConfirmClicked() { * @brief SettingsWidget::onBtnCancelClicked 点击取消按钮的槽函数 */ void SettingsWidget::onBtnCancelClicked() { + Q_EMIT this->settingWidgetClosed(); this->close(); } diff --git a/src/settings-widget.h b/src/settings-widget.h index 2618da7..f7c8d5c 100644 --- a/src/settings-widget.h +++ b/src/settings-widget.h @@ -67,7 +67,9 @@ private: QHBoxLayout * m_bottomBtnLyt = nullptr; QPushButton * m_cancelBtn = nullptr; QPushButton * m_confirmBtn = nullptr; + Q_SIGNALS: + void settingWidgetClosed(); private Q_SLOTS: void onBtnConfirmClicked();