From: vsr Date: Thu, 7 Aug 2014 16:27:44 +0000 (+0400) Subject: 0022671: [CEA] Standalone Help Browser X-Git-Tag: V7_5_0a1~27 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=554fcedd87e4d0421169f9eac39535c4e21e0b9c;p=modules%2Fgui.git 0022671: [CEA] Standalone Help Browser --- diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 08c7b287c..54e4e19ad 100755 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -21,7 +21,7 @@ # Common packages ## SET(SUBDIRS_COMMON - CASCatch Qtx Style DDS QDS ObjBrowser SUIT SUITApp STD CAF + CASCatch Qtx HelpBrowser Style DDS QDS ObjBrowser SUIT SUITApp STD CAF CAM LogWindow Prs Event OpenGLUtils ViewerData ViewerTools ImageComposer GUI_PY ) diff --git a/src/HelpBrowser/CMakeLists.txt b/src/HelpBrowser/CMakeLists.txt new file mode 100644 index 000000000..6a90e2ef5 --- /dev/null +++ b/src/HelpBrowser/CMakeLists.txt @@ -0,0 +1,77 @@ +# Copyright (C) 2012-2014 CEA/DEN, EDF R&D, OPEN CASCADE +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +# --- options --- + +# additional include directories +INCLUDE_DIRECTORIES( + ${QT_INCLUDES} + ${PROJECT_SOURCE_DIR}/src/Qtx +) + +# additional preprocessor / compiler flags +ADD_DEFINITIONS( + ${QT_DEFINITIONS} +) + +# libraries to link to +SET(_link_LIBRARIES + ${QT_LIBRARIES} + qtx +) + +# --- headers --- + +SET(_moc_HEADERS + qtlocalpeer.h + qtsingleapplication.h +) + +# --- resources --- + +# resource files / to be processed by rcc +SET(_rcc_RESOURCES HelpBrowser.qrc) + +# --- sources --- + +# sources / rcc wrappings +QT4_ADD_RESOURCES(_rcc_SOURCES ${_rcc_RESOURCES}) + +# sources / moc wrappings +QT4_WRAP_CPP(_moc_SOURCES ${_moc_HEADERS}) + +# sources / to compile +SET(_other_SOURCES + qtlocalpeer.cpp + qtsingleapplication.cpp + HelpBrowser.cxx +) + +# sources / to compile +SET(HelpBrowser_SOURCES + ${_other_SOURCES} + ${_moc_SOURCES} + ${_rcc_SOURCES} +) + +# --- rules --- + +ADD_EXECUTABLE(HelpBrowser ${HelpBrowser_SOURCES}) +TARGET_LINK_LIBRARIES(HelpBrowser ${_link_LIBRARIES}) +INSTALL(TARGETS HelpBrowser EXPORT ${PROJECT_NAME}TargetGroup DESTINATION ${SALOME_INSTALL_BINS}) diff --git a/src/HelpBrowser/COPYING b/src/HelpBrowser/COPYING new file mode 100644 index 000000000..53d5fb72c --- /dev/null +++ b/src/HelpBrowser/COPYING @@ -0,0 +1,36 @@ +/**************************************************************************** +** +** 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. +** +** 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." +** +****************************************************************************/ diff --git a/src/HelpBrowser/HelpBrowser.cxx b/src/HelpBrowser/HelpBrowser.cxx new file mode 100644 index 000000000..844799135 --- /dev/null +++ b/src/HelpBrowser/HelpBrowser.cxx @@ -0,0 +1,190 @@ +// Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE +// +// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, +// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// File : HelpBrowser.cxx +// Author : Vadim SANDLER, OpenCASCADE S.A.S. (vadim.sandler@opencascade.com) + +#include "qtsingleapplication.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace +{ + void printHelp() + { + QFileInfo fi( QtSingleApplication::arguments().at(0) ); + + std::cout << std::endl; + std::cout << "SALOME Help Browser" << std::endl; + std::cout << std::endl; + std::cout << "usage: " << qPrintable( fi.fileName() ) << " [options] file" << std::endl; + std::cout << " file is a help file to be opened" << std::endl; + std::cout << std::endl; + std::cout << "Options:" << std::endl; + std::cout << "-h, --help Prints this help and quits." << std::endl; + std::cout << "--language=LANG Use LANG language in menus." << std::endl; + std::cout << std::endl; + } +} + +class RaiseWindowHelper: public QDialog +{ +public: + RaiseWindowHelper( QWidget* parent ) : QDialog( parent, Qt::FramelessWindowHint ) + { + setAttribute( Qt::WA_DeleteOnClose, true ); + resize( 1, 1 ); + show(); + QTimer::singleShot( 100, this, SLOT( close() ) ); + QTimer::singleShot( 500, parent, SLOT( setFocus() ) ); + } +}; + +class HelpBrowser: public QtxWebBrowser +{ +public: + HelpBrowser() : QtxWebBrowser() + { + Q_INIT_RESOURCE( Qtx ); + + setAttribute( Qt::WA_DeleteOnClose, false ); + } + ~HelpBrowser() + { + if ( resourceMgr() ) + resourceMgr()->save(); + } + void about() + { + QStringList info; + QFile f( ":/COPYING" ); + f.open( QIODevice::ReadOnly ); + QTextStream in( &f ); + + info << QtxWebBrowser::tr( "%1 has been developed using %2" ).arg( QString( "SALOME %1").arg( tr( "Help Browser" ) ) ).arg( "Qt Solutions Component: Single Application." ); + info << ""; + info << in.readAll().split( "\n" ); + + QMessageBox::about( this, tr( "About %1" ).arg( tr( "Help Browser" ) ), + info.join( "\n" ) ); + } + void load( const QString& url ) + { + QtxWebBrowser::load( url ); + RaiseWindowHelper* helper = new RaiseWindowHelper( this ); + } +}; + +int main( int argc, char **argv ) +{ + // set application name (for preferences) + + QtSingleApplication::setApplicationName( "salome" ); + + // create application instance + + QtSingleApplication instance( argc, argv ); + + // parse command line arguments + + bool showHelp = false; + QString language; + QString helpfile; + + QRegExp rl( "--language=(.+)" ); + rl.setMinimal( false ); + + for ( int a = 1; a < argc; ++a ) { + QString param = argv[a]; + if ( param == "--help" || param == "-h" ) + showHelp = true; + else if ( rl.exactMatch( param ) ) + language = rl.cap( 1 ); + else + helpfile = param; + } + + // show help and exit if --help or -h option has been specified via command line + + if ( showHelp ) { + printHelp(); + exit( 0 ); + } + + if ( instance.sendMessage( helpfile ) ) + return 0; + + // load translations + + QtxTranslator tqt, tsal; + if ( !language.isEmpty() ) { + if ( tqt.load( QString( "qt_%1" ).arg( language ), QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ) ) + instance.installTranslator( &tqt ); + + QDir appDir = QtSingleApplication::applicationDirPath(); + appDir.cdUp(); appDir.cdUp(); + + if ( tsal.load( QString( "Qtx_msg_%1" ).arg( language ), appDir.filePath( "share/salome/resources/gui" ) ) ) + instance.installTranslator( &tsal ); + } + + // initialize resource manager (for preferences) + + QtxResourceMgr* resMgr = new QtxResourceMgr( "HelpBrowser", "%1Config" ); + resMgr->setCurrentFormat( "xml" ); + QtxWebBrowser::setResourceMgr( resMgr ); + + // show main window + + HelpBrowser browser; + browser.show(); + + // load file specified via command line + + if ( helpfile.isEmpty() ) { + QString docdir = qgetenv( "DOCUMENTATION_ROOT_DIR" ); + if ( !docdir.isEmpty() ) + helpfile = QDir::toNativeSeparators( QString( "%1/index.html" ).arg( docdir ) ); + } + + if ( !helpfile.isEmpty() ) { + browser.load( helpfile ); + } + + // finalize main window activation + + instance.setActivationWindow( &browser ); + + QObject::connect( &instance, SIGNAL( messageReceived( QString ) ), + &browser, SLOT( load ( QString ) ) ); + + return instance.exec(); +} diff --git a/src/HelpBrowser/HelpBrowser.qrc b/src/HelpBrowser/HelpBrowser.qrc new file mode 100644 index 000000000..820e86274 --- /dev/null +++ b/src/HelpBrowser/HelpBrowser.qrc @@ -0,0 +1,6 @@ + + + COPYING + + + diff --git a/src/HelpBrowser/qtlocalpeer.cpp b/src/HelpBrowser/qtlocalpeer.cpp new file mode 100644 index 000000000..332b0643f --- /dev/null +++ b/src/HelpBrowser/qtlocalpeer.cpp @@ -0,0 +1,203 @@ +/**************************************************************************** +** +** 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 "qtlocalpeer.h" +#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 (socket->bytesAvailable() < (int)sizeof(quint32)) + 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; + emit messageReceived(message); //### (might take a long time to return) +} diff --git a/src/HelpBrowser/qtlocalpeer.h b/src/HelpBrowser/qtlocalpeer.h new file mode 100644 index 000000000..1b533b1ab --- /dev/null +++ b/src/HelpBrowser/qtlocalpeer.h @@ -0,0 +1,77 @@ +/**************************************************************************** +** +** 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/src/HelpBrowser/qtlockedfile.cpp b/src/HelpBrowser/qtlockedfile.cpp new file mode 100644 index 000000000..c142a863a --- /dev/null +++ b/src/HelpBrowser/qtlockedfile.cpp @@ -0,0 +1,193 @@ +/**************************************************************************** +** +** 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/src/HelpBrowser/qtlockedfile.h b/src/HelpBrowser/qtlockedfile.h new file mode 100644 index 000000000..84c18e5c9 --- /dev/null +++ b/src/HelpBrowser/qtlockedfile.h @@ -0,0 +1,97 @@ +/**************************************************************************** +** +** 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/src/HelpBrowser/qtlockedfile_unix.cpp b/src/HelpBrowser/qtlockedfile_unix.cpp new file mode 100644 index 000000000..976c1b9ee --- /dev/null +++ b/src/HelpBrowser/qtlockedfile_unix.cpp @@ -0,0 +1,115 @@ +/**************************************************************************** +** +** 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/src/HelpBrowser/qtlockedfile_win.cpp b/src/HelpBrowser/qtlockedfile_win.cpp new file mode 100644 index 000000000..049acaffe --- /dev/null +++ b/src/HelpBrowser/qtlockedfile_win.cpp @@ -0,0 +1,211 @@ +/**************************************************************************** +** +** 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, (LPCWSTR)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, (LPCWSTR)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 { + 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/src/HelpBrowser/qtsingleapplication.cpp b/src/HelpBrowser/qtsingleapplication.cpp new file mode 100644 index 000000000..d0fb15d76 --- /dev/null +++ b/src/HelpBrowser/qtsingleapplication.cpp @@ -0,0 +1,347 @@ +/**************************************************************************** +** +** 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 "qtsingleapplication.h" +#include "qtlocalpeer.h" +#include + + +/*! + \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) { + actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized); + actWin->raise(); + actWin->activateWindow(); + } +} + + +/*! + \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/src/HelpBrowser/qtsingleapplication.h b/src/HelpBrowser/qtsingleapplication.h new file mode 100644 index 000000000..049406f72 --- /dev/null +++ b/src/HelpBrowser/qtsingleapplication.h @@ -0,0 +1,105 @@ +/**************************************************************************** +** +** 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/src/LightApp/LightApp_Application.cxx b/src/LightApp/LightApp_Application.cxx index 0e2d4108c..66ff3fba1 100644 --- a/src/LightApp/LightApp_Application.cxx +++ b/src/LightApp/LightApp_Application.cxx @@ -93,7 +93,6 @@ #include #include #include -#include #include @@ -311,19 +310,6 @@ LightApp_Application::LightApp_Application() SUIT_ResourceMgr* aResMgr = SUIT_Session::session()->resourceMgr(); QPixmap aLogo = aResMgr->loadPixmap( "LightApp", tr( "APP_DEFAULT_ICO" ), false ); - QtxWebBrowser::setResourceManager( aResMgr ); - QtxWebBrowser::setData("browser:icon", aResMgr->loadPixmap( "LightApp", tr( "BROWSER_ICON" ) ) ); - QtxWebBrowser::setData("browser:title", tr( "BROWSER_TITLE" ) ); - QtxWebBrowser::setData("toolbar:title", tr( "BROWSER_TOOLBAR_TITLE" ) ); - QtxWebBrowser::setData("menu:file:title", tr( "BROWSER_FILEMENU" ) ); - QtxWebBrowser::setData("action:close:title", tr( "BROWSER_CLOSE" ) ); - QtxWebBrowser::setData("action:close:icon", aResMgr->loadPixmap( "LightApp", tr( "BROWSER_CLOSE_ICON" ) ) ); - QtxWebBrowser::setData("action:back:title", tr( "BROWSER_BACK" ) ); - QtxWebBrowser::setData("action:forward:title", tr( "BROWSER_FORWARD" ) ); - QtxWebBrowser::setData("action:find:title", tr( "BROWSER_FIND" ) ); - QtxWebBrowser::setData("action:findnext:title", tr( "BROWSER_FINDNEXT" ) ); - QtxWebBrowser::setData("action:findprev:title", tr( "BROWSER_FINDPREV" ) ); - desktop()->setWindowIcon( aLogo ); desktop()->setDockableMenuBar( false ); desktop()->setDockableStatusBar( false ); @@ -1096,13 +1082,10 @@ void LightApp_Application::onHelpContentsModule() } } else { -#ifdef WIN32 - // On Win32 platform QWebKit of the Qt 4.6.3 hang up in case 'file://' protocol - // is defined. On Linux platform QWebKit doesn't work correctly without 'file://' protocol. - QtxWebBrowser::loadUrl(helpFile); -#else - QtxWebBrowser::loadUrl(QString("file://%1").arg(helpFile)); -#endif + QStringList parameters; + parameters << QString( "--language=%1" ).arg( resMgr->stringValue( "language", "language" ) ); + parameters << helpFile; + QProcess::startDetached( "HelpBrowser", parameters ); } } @@ -1169,14 +1152,10 @@ void LightApp_Application::onHelpContextModule( const QString& theComponentName, } } else { -#ifdef WIN32 - // On Win32 platform QWebKit of the Qt 4.6.3 hang up in case 'file://' protocol - // is defined. On Linux platform QWebKit doesn't work correctly without 'file://' protocol. - QtxWebBrowser::loadUrl(helpFile, context); -#else - QtxWebBrowser::loadUrl(QString("file://%1").arg(helpFile), context); -#endif - + QStringList parameters; + parameters << QString( "--language=%1" ).arg( resMgr->stringValue( "language", "language" ) ); + parameters << QString( "%1#%2" ).arg( helpFile ).arg( context ); + QProcess::startDetached( "HelpBrowser", parameters ); } } @@ -3035,13 +3014,6 @@ void LightApp_Application::preferencesChanged( const QString& sec, const QString dynamic_cast( desktop() )->workstack()->setOpaqueResize( opaqueResize ); } - if ( sec == "ExternalBrowser" && param == "use_external_browser" ) { - if ( resMgr->booleanValue("ExternalBrowser", "use_external_browser", false ) ) - { - QtxWebBrowser::shutdown(); - } - } - #ifndef DISABLE_PLOT2DVIEWER QList lst; viewManagers( Plot2d_Viewer::Type(), lst ); diff --git a/src/LightApp/resources/LightApp_images.ts b/src/LightApp/resources/LightApp_images.ts index dae481992..98d12bcfc 100644 --- a/src/LightApp/resources/LightApp_images.ts +++ b/src/LightApp/resources/LightApp_images.ts @@ -31,13 +31,5 @@ APP_MODULE_ICO icon_module.png - - BROWSER_ICON - icon_default.png - - - BROWSER_CLOSE_ICON - close.png - diff --git a/src/LightApp/resources/LightApp_msg_en.ts b/src/LightApp/resources/LightApp_msg_en.ts index 306362bd5..94dae2e0b 100644 --- a/src/LightApp/resources/LightApp_msg_en.ts +++ b/src/LightApp/resources/LightApp_msg_en.ts @@ -50,42 +50,6 @@ CEA/DEN, CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITASENTRY_COLUMN Entry - - BROWSER_TITLE - SALOME Help Browser - - - BROWSER_TOOLBAR_TITLE - Navigation - - - BROWSER_FILEMENU - &File - - - BROWSER_CLOSE - &Close - - - BROWSER_BACK - Go Back - - - BROWSER_FORWARD - Go Forward - - - BROWSER_FIND - &Find... - - - BROWSER_FINDNEXT - Find &next - - - BROWSER_FINDPREV - Find &previous - LightApp_Application diff --git a/src/LightApp/resources/LightApp_msg_fr.ts b/src/LightApp/resources/LightApp_msg_fr.ts index e07ece124..50918d26f 100755 --- a/src/LightApp/resources/LightApp_msg_fr.ts +++ b/src/LightApp/resources/LightApp_msg_fr.ts @@ -50,42 +50,6 @@ CEA/DEN, CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITASENTRY_COLUMN Entrée - - BROWSER_TITLE - Aide de SALOME - - - BROWSER_TOOLBAR_TITLE - Navigation - - - BROWSER_FILEMENU - &Fichier - - - BROWSER_CLOSE - &Fermer - - - BROWSER_BACK - Reculer - - - BROWSER_FORWARD - Avancer - - - BROWSER_FIND - &Chercher... - - - BROWSER_FINDNEXT - Chercher &suivant - - - BROWSER_FINDPREV - Chercher &précédent - LightApp_Application diff --git a/src/LightApp/resources/LightApp_msg_ja.ts b/src/LightApp/resources/LightApp_msg_ja.ts index 3253f1ea6..bdf471261 100644 --- a/src/LightApp/resources/LightApp_msg_ja.ts +++ b/src/LightApp/resources/LightApp_msg_ja.ts @@ -50,42 +50,6 @@ CEA/DEN, CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITASENTRY_COLUMN エントリ - - BROWSER_TITLE - Salome ヘルプ ・ ブラウザー - - - BROWSER_TOOLBAR_TITLE - ナビゲーション - - - BROWSER_FILEMENU - ファイル(&F) - - - BROWSER_CLOSE - 閉じる(&C) - - - BROWSER_BACK - 戻る - - - BROWSER_FORWARD - 進む - - - BROWSER_FIND - 検索(&F) - - - BROWSER_FINDNEXT - 次を検索(&n) - - - BROWSER_FINDPREV - 前を検索(&p) - LightApp_Application diff --git a/src/Qtx/Qtx.qrc b/src/Qtx/Qtx.qrc index 15aa9c467..e5017a8eb 100644 --- a/src/Qtx/Qtx.qrc +++ b/src/Qtx/Qtx.qrc @@ -29,6 +29,9 @@ images/qtx_split4_19.png images/qtx_split4_20.png images/qtx_split4_21.png + images/open.png + images/close.png + images/appicon.png diff --git a/src/Qtx/QtxTranslator.h b/src/Qtx/QtxTranslator.h index 154f98b9c..f3e5af4f7 100644 --- a/src/Qtx/QtxTranslator.h +++ b/src/Qtx/QtxTranslator.h @@ -23,9 +23,11 @@ #ifndef QTXTRANSLATOR_H #define QTXTRANSLATOR_H +#include "Qtx.h" + #include -class QtxTranslator : public QTranslator +class QTX_EXPORT QtxTranslator : public QTranslator { public: QtxTranslator( QObject* parent = 0 ); diff --git a/src/Qtx/QtxWebBrowser.cxx b/src/Qtx/QtxWebBrowser.cxx index 32963733e..1dc8a0531 100644 --- a/src/Qtx/QtxWebBrowser.cxx +++ b/src/Qtx/QtxWebBrowser.cxx @@ -44,6 +44,16 @@ #include #include #include +#include + +namespace +{ + bool isLocalFile( const QUrl& url ) + { + QFileInfo fi( url.path() ); + return fi.exists(); + } +} /*! \class QtxWebBrowser::Searcher @@ -169,21 +179,21 @@ QtxWebBrowser::Downloader::Downloader( const QString& fileName, int action, cons : QDialog( parent ), myProgram( program ) { setModal( true ); - setWindowTitle( tr( "Open URL" ) ); + setWindowTitle( QtxWebBrowser::tr( "Open URL" ) ); setSizeGripEnabled( true ); myFileName = new QLabel( this ); - QRadioButton* rbOpen = new QRadioButton( tr( "Open in" ), this ); - QRadioButton* rbSave = new QRadioButton( tr( "Save file" ), this ); - myBrowse = new QPushButton( tr( "&Browse..." ), this ); - myRepeat = new QCheckBox( tr( "Use this program for all files of this type" ), this ); + QRadioButton* rbOpen = new QRadioButton( QtxWebBrowser::tr( "Open in" ), this ); + QRadioButton* rbSave = new QRadioButton( QtxWebBrowser::tr( "Save file" ), this ); + myBrowse = new QPushButton( QtxWebBrowser::tr( "&Browse..." ), this ); + myRepeat = new QCheckBox( QtxWebBrowser::tr( "Use this program for all files of this type" ), this ); myAction = new QButtonGroup( this ); myAction->addButton( rbOpen, mOpen ); myAction->addButton( rbSave, mSave ); - QPushButton* btnOk = new QPushButton( tr( "&OK" ), this ); - QPushButton* btnCancel = new QPushButton( tr( "&Cancel" ), this ); + QPushButton* btnOk = new QPushButton( QtxWebBrowser::tr( "&OK" ), this ); + QPushButton* btnCancel = new QPushButton( QtxWebBrowser::tr( "&Cancel" ), this ); QFont f = myFileName->font(); f.setBold( true ); myFileName->setFont( f ); @@ -193,10 +203,10 @@ QtxWebBrowser::Downloader::Downloader( const QString& fileName, int action, cons btnLayout->addWidget( btnCancel ); QGridLayout* l = new QGridLayout( this ); - l->addWidget( new QLabel( tr( "You are opening the file" ), this ), + l->addWidget( new QLabel( QtxWebBrowser::tr( "You are opening the file" ), this ), 0, 0, 1, 4 ); l->addWidget( myFileName, 1, 1, 1, 3 ); - l->addWidget( new QLabel( tr( "Please choose the action to be done" ), this ), + l->addWidget( new QLabel( QtxWebBrowser::tr( "Please choose the action to be done" ), this ), 3, 0, 1, 4 ); l->addWidget( rbOpen, 4, 1, 1, 1 ); l->addWidget( myBrowse, 4, 2, 1, 1 ); @@ -267,7 +277,7 @@ void QtxWebBrowser::Downloader::setAction( int action ) */ void QtxWebBrowser::Downloader::browse() { - QString program = QFileDialog::getOpenFileName( this, tr( "Choose program" ), myProgram ); + QString program = QFileDialog::getOpenFileName( this, QtxWebBrowser::tr( "Choose program" ), myProgram ); if ( !program.isEmpty() ) myProgram = program; } @@ -275,7 +285,7 @@ void QtxWebBrowser::Downloader::browse() /*! \class QtxWebBrowser - \brief The QtxWebBrowser provides a window that can display html pages. + \brief The QtxWebBrowser provides a window that can display html pages from local file system. Only one instance of the QtxWebBrowser class can be created. To access the browser window, use static method QtxWebBrowser::webBrowser(), which creates an @@ -286,36 +296,22 @@ void QtxWebBrowser::Downloader::browse() closing of the browser window. To close window programmatically use method close(). - To set visual properties of the browser use static method setData(). - Optionally resource manager can be specified to automatically store - action (open/save) and program to be used to download files to the - user preferences. + action (open/save) and program to be used to download files in the + application preferences. The following sample demonstrates how to use web browser. In this code the browser window is created, /data/index.html file is opened and scrolled to the "anchor1" anchor on this page. \code - int main(int argc, char *argv[]) - { - QApplication app(argc, argv); - - // set resource manager - QtxWebBrowser::setResourceManager(myResourceMgr); - // set icon, title and menu items - QtxWebBrowser::setData("browser:title", tr("Web Browser")); - QtxWebBrowser::setData("browser:icon", QPixmap(":/icon.png")); - QtxWebBrowser::setData("menu:file:title", tr("&File")); - QtxWebBrowser::setData("action:close:title", tr("&Close")); - - // show HTML page - QtxWebBrowser::loadUrl("file:///data/index.html", "anchor1"); - - return app.exec(); - } + // initialize application + // - set resource manager + QtxWebBrowser::setResourceMgr(myResourceMgr); + // ... + // show HTML page + QtxWebBrowser::loadUrl("file:///data/index.html", "anchor1"); \endcode - */ //! The only one instance of web browser @@ -324,15 +320,14 @@ QtxWebBrowser* QtxWebBrowser::myBrowser = 0; //! Resources manager QtxResourceMgr* QtxWebBrowser::myResourceMgr = 0; -//! Internal data map to store resources of the browser. -QMap QtxWebBrowser::myData; - /*! \brief Constructor. Construct the web browser. */ QtxWebBrowser::QtxWebBrowser( ) : QMainWindow( 0 ) { + Q_INIT_RESOURCE( Qtx ); + setAttribute( Qt::WA_DeleteOnClose ); statusBar(); @@ -340,12 +335,13 @@ QtxWebBrowser::QtxWebBrowser( ) : QMainWindow( 0 ) myWebView = new QWebView( frame ); - QAction *copyAction = myWebView->pageAction(QWebPage::Copy); - copyAction->setShortcut(QKeySequence::Copy); - myWebView->addAction(copyAction); - - + myWebView->pageAction( QWebPage::Copy )->setShortcut( QKeySequence::Copy ); + myWebView->addAction( myWebView->pageAction( QWebPage::Copy ) ); + myWebView->pageAction( QWebPage::OpenLinkInNewWindow )->setVisible( false ); + myWebView->pageAction( QWebPage::Back )->setText( tr( "Go Back" ) ); + myWebView->pageAction( QWebPage::Forward )->setText( tr( "Go Forward" ) ); myWebView->page()->setLinkDelegationPolicy( QWebPage::DelegateAllLinks ); + myFindPanel = new QtxSearchTool( frame, myWebView, QtxSearchTool::Basic | QtxSearchTool::Case | QtxSearchTool::Wrap, Qt::Horizontal ); @@ -354,17 +350,32 @@ QtxWebBrowser::QtxWebBrowser( ) : QMainWindow( 0 ) myFindPanel->setSearcher( new Searcher( myWebView ) ); myFindPanel->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ); - myToolbar = addToolBar( tr( "Navigation" ) ); - myToolbar->addAction( myWebView->pageAction( QWebPage::Back ) ); - myToolbar->addAction( myWebView->pageAction( QWebPage::Forward ) ); - - myMenus[ File ] = menuBar()->addMenu( tr( "&File" ) ); - myActions[ Find ] = myMenus[ File ]->addAction( tr( "&Find in text..." ), myFindPanel, SLOT( find() ), QKeySequence( QKeySequence::Find ) ); - myActions[ FindNext ] = myMenus[ File ]->addAction( tr( "&Find next" ), myFindPanel, SLOT( findNext() ), QKeySequence( QKeySequence::FindNext ) ); - myActions[ FindPrev ] = myMenus[ File ]->addAction( tr( "&Find previous" ), myFindPanel, SLOT( findPrevious() ), QKeySequence( QKeySequence::FindPrevious ) ); - myMenus[ File ]->addSeparator(); - myActions[ Close ] = myMenus[ File ]->addAction( tr( "&Close" ), this, SLOT( close() ) ); - + QToolBar* toolbar = addToolBar( tr( "Navigation" ) ); + toolbar->addAction( myWebView->pageAction( QWebPage::Back ) ); + toolbar->addAction( myWebView->pageAction( QWebPage::Forward ) ); + + QMenu* fileMenu = menuBar()->addMenu( tr( "&File" ) ); + fileMenu->addAction( QPixmap( ":/images/open.png" ), tr( "&Open..." ), + this, SLOT( open() ), + QKeySequence( QKeySequence::Open ) ); + fileMenu->addSeparator(); + fileMenu->addAction( tr( "&Find in text..." ), + myFindPanel, SLOT( find() ), + QKeySequence( QKeySequence::Find ) ); + fileMenu->addAction( tr( "&Find next" ), + myFindPanel, SLOT( findNext() ), + QKeySequence( QKeySequence::FindNext ) ); + fileMenu->addAction( tr( "&Find previous" ), + myFindPanel, SLOT( findPrevious() ), + QKeySequence( QKeySequence::FindPrevious ) ); + fileMenu->addSeparator(); + fileMenu->addAction( QPixmap( ":/images/close.png" ), tr( "&Close" ), + this, SLOT( close() ) ); + + QMenu* helpMenu = menuBar()->addMenu( tr( "&Help" ) ); + helpMenu->addAction( tr( "&About..." ), + this, SLOT( about() ) ); + QVBoxLayout* main = new QVBoxLayout( frame ); main->addWidget( myWebView ); main->addWidget( myFindPanel ); @@ -382,13 +393,10 @@ QtxWebBrowser::QtxWebBrowser( ) : QMainWindow( 0 ) connect( myWebView->pageAction( QWebPage::OpenLink ), SIGNAL( activated() ), SLOT( linkAction() ) ); - - myWebView->pageAction( QWebPage::OpenLinkInNewWindow )->setVisible( false ); - setCentralWidget( frame ); setFocusProxy( myWebView ); - updateData(); - qAddPostRoutine( QtxWebBrowser::clearData ); + setWindowIcon( QPixmap( ":/images/appicon.png" ) ); + adjustTitle(); } /*! @@ -419,53 +427,17 @@ void QtxWebBrowser::loadUrl( const QString& url, const QString& anchor ) { QString anUrl = url; if( !anchor.isEmpty() ) anUrl += "#" + anchor; - anUrl.replace('\\', '/'); Qtx::alignWidget( webBrowser(), (QWidget*)QApplication::desktop(), Qtx::AlignCenter ); QtxWebBrowser* browser = webBrowser(); browser->show(); - browser->myWebView->load( QUrl( anUrl ) ); + browser->load( anUrl ); browser->setFocus(); browser->activateWindow(); browser->raise(); } -/*! - \brief Set browser settings from. - - This method can be used to setup the browser properties. - - \c "browser:title" : title of the browser window - - \c "browser:icon" : icon of the browser window - - \c "toolbar:title" : title of the toolbar - - \c "menu:file:title" : File menu of the browser - - \c "action:close:title" : File/Close menu item title - - \c "action:close:icon" : File/Close menu item icon - - \c "action:back:title" : Navigation/Back menu item title - - \c "action:back:icon" : Navigation/Back menu item icon - - \c "action:forward:title" : Navigation/Forward menu item title - - \c "action:forward:icon" : Navigation/Forward menu item icon - - \c "action:find:title" : File/Find menu item title - - \c "action:find:icon" : File/Find menu item icon - - \c "action:findnext:title" : File/Find Next menu item title - - \c "action:findnext:icon" : File/Find Next menu item icon - - \c "action:findprev:title" : File/Find Previous menu item title - - \c "action:findprev:icon" : File/Find Previous menu item icon - - \c "preferences:section" : Preferences file section (base, used as prefix to the file extension) - - \c "preferences:action" : Preferences file parameter name for action - - \c "preferences:program" : Preferences file parameter name for program - - \c "preferences:repeat" : Preferences file parameter name for repeat action flag - - \param key name of the property - \param val value of the property - -*/ -void QtxWebBrowser::setData( const QString& key, const QVariant& val ) -{ - myData.insert( key, val ); - if ( myBrowser ) myBrowser->updateData(); -} - /*! \brief Shutdown help browser */ @@ -476,134 +448,30 @@ void QtxWebBrowser::shutdown() } /*! - \brief Get string value by key from the internal data map - \param key data key identifier - \param def default value - \return string value assigned to the key (null string if data is not assigned to the key) - \internal -*/ -QString QtxWebBrowser::getStringValue( const QString& key, const QString& def ) -{ - QString val = def; - if ( myData.contains( key ) && myData[key].canConvert( QVariant::String ) ) - val = myData[key].toString(); - return val; -} - -/*! - \brief Get icon value by key from the internal data map - \param key data key identifier - \param def default value - \return icon assigned to the key (null icon if data is not assigned to the key) - \internal -*/ -QIcon QtxWebBrowser::getIconValue( const QString& key, const QIcon& def ) -{ - QIcon val = def; - if ( myData.contains( key ) ) { - if ( myData[key].canConvert( QVariant::Pixmap ) ) - val = myData[key].value(); - else if ( myData[key].canConvert( QVariant::Icon ) ) - val = myData[key].value(); - } - return val; -} - -/*! - \brief Update web browser properties from internal data map + \brief Set resource manager + \param resMgr resource manager */ -void QtxWebBrowser::updateData() +void QtxWebBrowser::setResourceMgr( QtxResourceMgr* resMgr ) { - // main title - adjustTitle(); - - // window icon - QIcon icon = getIconValue( "browser:icon" ); - if ( !icon.isNull() ) - setWindowIcon( icon ); - - // toolbar title - QString tbTitle = getStringValue( "toolbar:title" ); - if ( myToolbar && !tbTitle.isEmpty() ) - myToolbar->setWindowTitle( tbTitle ); - - // File menu - QString fmenu = getStringValue( "menu:file:title" ); - if ( myMenus.contains( File ) && !fmenu.isEmpty() ) - myMenus[ File ]->setTitle( fmenu ); - - // File/Close menu - QString closeTlt = getStringValue( "action:close:title" ); - QIcon closeIco = getIconValue( "action:close:icon" ); - if ( myActions.contains( Close ) ) { - if ( !closeTlt.isEmpty() ) - myActions[ Close ]->setText( closeTlt ); - if ( !closeIco.isNull() ) - myActions[ Close ]->setIcon( closeIco ); - } - - // Navigation/Go Back menu - QString backTlt = getStringValue( "action:back:title" ); - QIcon backIco = getIconValue( "action:back:icon" ); - if ( !backTlt.isEmpty() ) - myWebView->pageAction( QWebPage::Back )->setText( backTlt ); - if ( !backIco.isNull() ) - myWebView->pageAction( QWebPage::Back )->setIcon( backIco ); - - // Navigation/Go Forward menu - QString fwdTlt = getStringValue( "action:forward:title" ); - QIcon fwdIco = getIconValue( "action:forward:icon" ); - if ( !fwdTlt.isEmpty() ) - myWebView->pageAction( QWebPage::Forward )->setText( fwdTlt ); - if ( !fwdIco.isNull() ) - myWebView->pageAction( QWebPage::Forward )->setIcon( fwdIco ); - - // File/Find menu - QString findTlt = getStringValue( "action:find:title" ); - QIcon findIco = getIconValue( "action:find:icon" ); - if ( myActions.contains( Find ) ) { - if ( !findTlt.isEmpty() ) - myActions[ Find ]->setText( findTlt ); - if ( !findIco.isNull() ) - myActions[ Find ]->setIcon( findIco ); - } - - // File/Find Next menu - QString findNextTlt = getStringValue( "action:findnext:title" ); - QIcon findNextIco = getIconValue( "action:findnext:icon" ); - if ( myActions.contains( FindNext ) ) { - if ( !findNextTlt.isEmpty() ) - myActions[ FindNext ]->setText( findNextTlt ); - if ( !findNextIco.isNull() ) - myActions[ FindNext ]->setIcon( findNextIco ); - } - - // File/Find Previous menu - QString findPrevTlt = getStringValue( "action:findprev:title" ); - QIcon findPrevIco = getIconValue( "action:findprev:icon" ); - if ( myActions.contains( FindPrev ) ) { - if ( !findPrevTlt.isEmpty() ) - myActions[ FindPrev ]->setText( findPrevTlt ); - if ( !findPrevIco.isNull() ) - myActions[ FindPrev ]->setIcon( findPrevIco ); - } + myResourceMgr = resMgr; } /*! - \brief Clear internal data map - \internal + \brief Get resource manager + \return resource manager */ -void QtxWebBrowser::clearData() +QtxResourceMgr* QtxWebBrowser::resourceMgr() const { - myData.clear(); + return myResourceMgr; } /*! - \brief Set resource manager + Shows About dialog box */ -void QtxWebBrowser::setResourceManager( QtxResourceMgr* resMgr ) +void QtxWebBrowser::about() { - myResourceMgr = resMgr; + QMessageBox::about( this, tr( "About %1" ).arg( tr( "Help Browser" ) ), + QString( "SALOME %1" ).arg( tr( "Help Browser" ) ) ); } /*! @@ -628,7 +496,7 @@ void QtxWebBrowser::linkClicked( const QUrl& url ) void QtxWebBrowser::linkHovered( const QString& link, const QString& /*title*/, const QString& /*context*/ ) { QUrl url = link; - if ( !link.isEmpty() && url.scheme() == "file" ) myLastUrl = url; + if ( !link.isEmpty() && isLocalFile( url ) ) myLastUrl = url; statusBar()->showMessage( link ); } @@ -638,8 +506,9 @@ void QtxWebBrowser::linkHovered( const QString& link, const QString& /*title*/, */ void QtxWebBrowser::adjustTitle() { - QString title = getStringValue( "browser:title" ); - setWindowTitle( title.isEmpty() ? myWebView->title() : title + QString( " [%1]" ).arg( myWebView->title() ) ); + QString title = tr( "Help Browser" ); + if ( !myWebView->title().isEmpty() ) title += QString( " [%1]" ).arg( myWebView->title() ); + setWindowTitle( title ); } /* @@ -649,8 +518,8 @@ void QtxWebBrowser::adjustTitle() void QtxWebBrowser::finished( bool ok ) { if ( !ok && !myLastUrl.isEmpty() ) { - if ( myLastUrl.scheme() == "file" ) { - QString filename = myLastUrl.toLocalFile(); + if ( isLocalFile( myLastUrl ) ) { + QString filename = myLastUrl.path(); QString extension = QFileInfo( filename ).suffix(); if ( extension == "html" || extension == "htm" ) return; openLink( filename ); @@ -665,10 +534,10 @@ void QtxWebBrowser::linkAction() { QObject* s = sender(); if ( s == myWebView->pageAction( QWebPage::DownloadLinkToDisk ) ) { - saveLink( myLastUrl.toLocalFile() ); + saveLink( myLastUrl.path() ); } else if ( s == myWebView->pageAction( QWebPage::OpenLink ) ) { - QString fileName = myLastUrl.toLocalFile(); + QString fileName = myLastUrl.path(); QString extension = QFileInfo( fileName ).suffix(); if ( extension != "html" && extension != "htm" ) { openLink( fileName, true ); @@ -690,10 +559,10 @@ void QtxWebBrowser::openLink( const QString& fileName, bool force ) int defAction = Downloader::mOpen; bool defRepeat = false; QString defProgram; - QString resSection = QString( "%1:%2" ).arg( getStringValue( "preferences:section", "web_browser" ) ).arg( extension ); - QString actionParam = getStringValue( "preferences:action", "action" ); - QString programParam = getStringValue( "preferences:program", "program" ); - QString repeatParam = getStringValue( "preferences:repeat", "repeat" ); + QString resSection = QString( "%1:%2" ).arg( "web_browser" ).arg( extension ); + QString actionParam = "action"; + QString programParam = "program"; + QString repeatParam = "repeat"; if ( !extension.isEmpty() && myResourceMgr ) { defAction = myResourceMgr->integerValue( resSection, actionParam, defAction ); @@ -717,14 +586,18 @@ void QtxWebBrowser::openLink( const QString& fileName, bool force ) switch( defAction ) { case Downloader::mOpen: if ( !defProgram.isEmpty() ) { + QStringList parameters; #ifdef WIN32 - QString cmd = ""; + QString cmd = defProgram; #else // If Salome Qt version is lower than the system one, on KDE an unresolved symbol is raised // In this case, we can try to launch the pdf viewer after unsetting the LD_LIBRARY_PATH environnement variable - QString cmd = "env LD_LIBRARY_PATH=/usr/lib:/usr/lib64"; + QString cmd = "env"; + parameters << "LD_LIBRARY_PATH=/usr/lib:/usr/lib64"; + parameters << defProgram; #endif - int r = ::system( QString( "%1 %2 %3 &" ).arg( cmd ).arg( defProgram ).arg( myLastUrl.toLocalFile() ).toLatin1().constData() ); + parameters << QFileInfo( myLastUrl.path() ).absoluteFilePath(); + QProcess::startDetached( cmd, parameters ); } break; case Downloader::mSave: @@ -737,6 +610,17 @@ void QtxWebBrowser::openLink( const QString& fileName, bool force ) } } +/*! + \brief Load URL + \param url path to the file to be opened in the browser +*/ +void QtxWebBrowser::load( const QString& url ) +{ + QString u = url; + if ( !u.isEmpty() ) + myWebView->load( QUrl( u.replace('\\', '/') ) ); +} + /*! \brief Save file \param fileName link to the file being saved @@ -744,7 +628,7 @@ void QtxWebBrowser::openLink( const QString& fileName, bool force ) */ void QtxWebBrowser::saveLink( const QString& fileName ) { - QString newFileName = QFileDialog::getSaveFileName( this, tr( "Save File" ), fileName, + QString newFileName = QFileDialog::getSaveFileName( this, tr( "Save file" ), fileName, QString( "*.%1" ).arg( QFileInfo( fileName ).suffix() ) ); if ( !newFileName.isEmpty() && QFileInfo( newFileName ).canonicalFilePath() != QFileInfo( fileName ).canonicalFilePath() ) { @@ -754,3 +638,15 @@ void QtxWebBrowser::saveLink( const QString& fileName ) QMessageBox::warning( this, tr( "Error"), tr( "Can't save file:\n%1" ).arg( newFileName ) ); } } + +/*! + \brief Open file + Shows "Open file" standard dialog box to allow user to choose file to open. +*/ +void QtxWebBrowser::open() +{ + QString url; + if ( isLocalFile( myWebView->url() ) ) url = myWebView->url().path(); + url = QFileDialog::getOpenFileName( this, tr( "Open file" ), url, "HTML files (*.html *.htm);; All files (*)" ); + if ( !url.isEmpty() ) load( url ); +} diff --git a/src/Qtx/QtxWebBrowser.h b/src/Qtx/QtxWebBrowser.h index b1adf3f45..bbe43d2d5 100644 --- a/src/Qtx/QtxWebBrowser.h +++ b/src/Qtx/QtxWebBrowser.h @@ -31,16 +31,12 @@ #include #include -#include #include -class QAction; class QButtonGroup; class QCheckBox; class QLabel; -class QMenu; class QPushButton; -class QToolBar; class QWebView; class QtxResourceMgr; class QtxSearchTool; @@ -49,49 +45,43 @@ class QTX_EXPORT QtxWebBrowser : public QMainWindow { Q_OBJECT - enum { File }; - enum { Find, FindNext, FindPrev, Close }; - class Downloader; class Searcher; -private: - QtxWebBrowser(); - public: virtual ~QtxWebBrowser(); static QtxWebBrowser* webBrowser(); static void loadUrl( const QString&, const QString& = QString() ); - static void setData( const QString&, const QVariant& ); - static void setResourceManager( QtxResourceMgr* ); + static void setResourceMgr( QtxResourceMgr* ); static void shutdown(); +protected: + QtxWebBrowser(); + QtxResourceMgr* resourceMgr() const; + private: - static QString getStringValue( const QString&, const QString& = QString() ); - static QIcon getIconValue( const QString&, const QIcon& = QIcon() ); - void updateData(); - static void clearData(); void saveLink( const QString& ); void openLink( const QString&, bool = false ); -protected slots: +public Q_SLOTS: + virtual void load( const QString& ); + +protected Q_SLOTS: + virtual void about(); virtual void linkClicked( const QUrl& ); virtual void linkHovered( const QString&, const QString&, const QString& ); -private slots: +private Q_SLOTS: + void open(); void adjustTitle(); void finished( bool ); void linkAction(); private: - static QMap myData; static QtxWebBrowser* myBrowser; static QtxResourceMgr* myResourceMgr; QWebView* myWebView; - QToolBar* myToolbar; - QMap myMenus; - QMap myActions; QtxSearchTool* myFindPanel; QUrl myLastUrl; }; @@ -110,7 +100,7 @@ public: bool isRepeatAction() const; QString program() const; -private slots: +private Q_SLOTS: void setAction( int ); void browse(); diff --git a/src/Qtx/images/appicon.png b/src/Qtx/images/appicon.png new file mode 100644 index 000000000..0140a6667 Binary files /dev/null and b/src/Qtx/images/appicon.png differ diff --git a/src/Qtx/images/close.png b/src/Qtx/images/close.png new file mode 100644 index 000000000..4364ce7fe Binary files /dev/null and b/src/Qtx/images/close.png differ diff --git a/src/Qtx/images/open.png b/src/Qtx/images/open.png new file mode 100644 index 000000000..8ed143ebd Binary files /dev/null and b/src/Qtx/images/open.png differ diff --git a/src/Qtx/resources/Qtx_msg_fr.ts b/src/Qtx/resources/Qtx_msg_fr.ts index 48d7c6d87..bb99d9848 100644 --- a/src/Qtx/resources/Qtx_msg_fr.ts +++ b/src/Qtx/resources/Qtx_msg_fr.ts @@ -384,4 +384,115 @@ &Fermer + + QtxWebBrowser + + Open URL + Ouvrir le URL + + + Open in + Open in + + + Save file + Sauvegarder le fichier + + + &Browse... + &Parcourir... + + + Use this program for all files of this type + Use this program for all files of this type + + + &OK + &OK + + + &Cancel + &Annuler + + + You are opening the file + You are opening the file + + + Please choose the action to be done + Please choose the action to be done + + + Choose program + Choose program + + + Go Back + Reculer + + + Go Forward + Avancer + + + Navigation + Navigation + + + &File + &Fichier + + + &Open... + &Ouvrir... + + + &Find in text... + &Chercher... + + + &Find next + Chercher &suivant + + + &Find previous + Chercher &précédent + + + &Close + &Fermer + + + &Help + &Aide + + + &About... + &A propos de... + + + About %1 + A propos de %1 + + + Help Browser + Help Browser + + + Error + Erreur + + + Can't save file:\n%1 + Impossible de sauvegarder le fichier:\n%1 + + + Open file + Ouvrir le fichier + + + %1 has been developed using %2 + %1 has been developed using %2 + +