diff options
author | Warwick Allison <warwick.allison@nokia.com> | 2010-02-15 02:43:54 (GMT) |
---|---|---|
committer | Warwick Allison <warwick.allison@nokia.com> | 2010-02-15 02:43:54 (GMT) |
commit | 126fb248ab351969d8805733cb35fc7b4232f91b (patch) | |
tree | 7a336dfac89465a1320da7f2787e83a3d7620b2d /tools | |
parent | fb28599786d069a2b99040bd7eee8c5ad8ef1ba9 (diff) | |
parent | 23968ba6c18f96f70dcd6f8e1b411711401f2ab3 (diff) | |
download | Qt-126fb248ab351969d8805733cb35fc7b4232f91b.zip Qt-126fb248ab351969d8805733cb35fc7b4232f91b.tar.gz Qt-126fb248ab351969d8805733cb35fc7b4232f91b.tar.bz2 |
Merge branch 'master' of scm.dev.nokia.troll.no:qt/qt-qml
Diffstat (limited to 'tools')
48 files changed, 1968 insertions, 1056 deletions
diff --git a/tools/assistant/tools/assistant/aboutdialog.cpp b/tools/assistant/tools/assistant/aboutdialog.cpp index 26d488d..a9bc352 100644 --- a/tools/assistant/tools/assistant/aboutdialog.cpp +++ b/tools/assistant/tools/assistant/aboutdialog.cpp @@ -70,7 +70,7 @@ void AboutLabel::setText(const QString &text, const QByteArray &resources) TRACE_OBJ QDataStream in(resources); in >> m_resourceMap; - + QTextBrowser::setText(text); } @@ -96,34 +96,34 @@ QVariant AboutLabel::loadResource(int type, const QUrl &name) void AboutLabel::setSource(const QUrl &url) { TRACE_OBJ - if (url.isValid() && (!HelpViewer::isLocalUrl(url) - || !HelpViewer::canOpenPage(url.path()))) { + if (url.isValid() && (!AbstractHelpViewer::isLocalUrl(url) + || !AbstractHelpViewer::canOpenPage(url.path()))) { if (!QDesktopServices::openUrl(url)) { QMessageBox::warning(this, tr("Warning"), - tr("Unable to launch external application.\n"), - tr("OK")); + tr("Unable to launch external application.\n"), tr("OK")); } } } AboutDialog::AboutDialog(QWidget *parent) - : QDialog(parent, Qt::MSWindowsFixedSizeDialogHint|Qt::WindowTitleHint|Qt::WindowSystemMenuHint) + : QDialog(parent, Qt::MSWindowsFixedSizeDialogHint | + Qt::WindowTitleHint|Qt::WindowSystemMenuHint) { TRACE_OBJ m_pixmapLabel = 0; m_aboutLabel = new AboutLabel(); - + m_closeButton = new QPushButton(); m_closeButton->setText(tr("&Close")); - connect(m_closeButton, SIGNAL(clicked()), - this, SLOT(close())); + connect(m_closeButton, SIGNAL(clicked()), this, SLOT(close())); m_layout = new QGridLayout(this); m_layout->addWidget(m_aboutLabel, 1, 0, 1, -1); - m_layout->addItem(new QSpacerItem(20, 10, QSizePolicy::Minimum, QSizePolicy::Fixed), 2, 1, 1, 1); + m_layout->addItem(new QSpacerItem(20, 10, QSizePolicy::Minimum, + QSizePolicy::Fixed), 2, 1, 1, 1); m_layout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding), 3, 0, 1, 1); m_layout->addWidget(m_closeButton, 3, 1, 1, 1); - m_layout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding), 3, 2, 1, 1); + m_layout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding), 3, 2, 1, 1); } void AboutDialog::setText(const QString &text, const QByteArray &resources) @@ -153,7 +153,8 @@ QString AboutDialog::documentTitle() const void AboutDialog::updateSize() { TRACE_OBJ - QSize screenSize = QApplication::desktop()->availableGeometry(QCursor::pos()).size(); + QSize screenSize = QApplication::desktop()->availableGeometry(QCursor::pos()) + .size(); int limit = qMin(screenSize.width()/2, 500); #ifdef Q_WS_MAC @@ -165,7 +166,7 @@ void AboutDialog::updateSize() if (width > limit) width = limit; - + QFontMetrics fm(qApp->font("QWorkspaceTitleBar")); int windowTitleWidth = qMin(fm.width(windowTitle()) + 50, limit); if (windowTitleWidth > width) @@ -173,8 +174,8 @@ void AboutDialog::updateSize() layout()->activate(); int height = (layout()->hasHeightForWidth()) - ? layout()->totalHeightForWidth(width) - : layout()->totalMinimumSize().height(); + ? layout()->totalHeightForWidth(width) + : layout()->totalMinimumSize().height(); setFixedSize(width, height); QCoreApplication::removePostedEvents(this, QEvent::LayoutRequest); } diff --git a/tools/assistant/tools/assistant/assistant.pro b/tools/assistant/tools/assistant/assistant.pro index edaf076..0733128 100644 --- a/tools/assistant/tools/assistant/assistant.pro +++ b/tools/assistant/tools/assistant/assistant.pro @@ -29,6 +29,8 @@ HEADERS += aboutdialog.h \ filternamedialog.h \ helpenginewrapper.h \ helpviewer.h \ + helpviewer_qtb.h \ + helpviewer_qwv.h \ indexwindow.h \ installdialog.h \ mainwindow.h \ @@ -55,6 +57,8 @@ SOURCES += aboutdialog.cpp \ filternamedialog.cpp \ helpenginewrapper.cpp \ helpviewer.cpp \ + helpviewer_qtb.cpp \ + helpviewer_qwv.cpp \ indexwindow.cpp \ installdialog.cpp \ main.cpp \ diff --git a/tools/assistant/tools/assistant/bookmarkdialog.cpp b/tools/assistant/tools/assistant/bookmarkdialog.cpp index f081c15..c053b62 100644 --- a/tools/assistant/tools/assistant/bookmarkdialog.cpp +++ b/tools/assistant/tools/assistant/bookmarkdialog.cpp @@ -38,12 +38,12 @@ ** $QT_END_LICENSE$ ** ****************************************************************************/ -#include "tracer.h" - #include "bookmarkdialog.h" #include "bookmarkfiltermodel.h" #include "bookmarkitem.h" #include "bookmarkmodel.h" +#include "helpenginewrapper.h" +#include "tracer.h" #include <QtGui/QKeyEvent> #include <QtGui/QMenu> @@ -94,6 +94,10 @@ BookmarkDialog::BookmarkDialog(BookmarkModel *sourceModel, const QString &title, ui.bookmarkFolders->setCurrentIndex(0); ui.treeView->setCurrentIndex(ui.treeView->indexAt(QPoint(2, 2))); + + const HelpEngineWrapper &helpEngine = HelpEngineWrapper::instance(); + if (helpEngine.usesAppFont()) + setFont(helpEngine.appFont()); } BookmarkDialog::~BookmarkDialog() diff --git a/tools/assistant/tools/assistant/centralwidget.cpp b/tools/assistant/tools/assistant/centralwidget.cpp index 03af06c..dd91326 100644 --- a/tools/assistant/tools/assistant/centralwidget.cpp +++ b/tools/assistant/tools/assistant/centralwidget.cpp @@ -43,7 +43,8 @@ #include "centralwidget.h" #include "findwidget.h" #include "helpenginewrapper.h" -#include "helpviewer.h" +#include "helpviewer_qtb.h" +#include "helpviewer_qwv.h" #include "searchwidget.h" #include "mainwindow.h" #include "../shared/collectionconfiguration.h" @@ -57,6 +58,7 @@ #include <QtGui/QPrinter> #include <QtGui/QTabBar> #include <QtGui/QTabWidget> +#include <QtGui/QTextBrowser> #include <QtGui/QToolButton> #include <QtGui/QPageSetupDialog> #include <QtGui/QPrintDialog> @@ -70,6 +72,7 @@ namespace { HelpViewer* helpViewerFromTabPosition(const QTabWidget *widget, const QPoint &point) { + TRACE_OBJ QTabBar *tabBar = qFindChild<QTabBar*>(widget); for (int i = 0; i < tabBar->count(); ++i) { if (tabBar->tabRect(i).contains(point)) @@ -80,10 +83,8 @@ namespace { CentralWidget *staticCentralWidget = 0; } - // -- CentralWidget - CentralWidget::CentralWidget(MainWindow *parent) : QWidget(parent) , lastTabPage(0) @@ -174,7 +175,7 @@ CentralWidget::~CentralWidget() HelpViewer *viewer = qobject_cast<HelpViewer*>(tabWidget->widget(i)); if (viewer && viewer->source().isValid()) { currentPages << viewer->source().toString(); - zoomFactors << QString::number(viewer->zoom()); + zoomFactors << QString::number(viewer->scale()); } } @@ -208,7 +209,7 @@ void CentralWidget::zoomIn() TRACE_OBJ HelpViewer *viewer = currentHelpViewer(); if (viewer) - viewer->zoomIn(); + viewer->scaleUp(); if (tabWidget->currentWidget() == m_searchWidget) m_searchWidget->zoomIn(); @@ -219,7 +220,7 @@ void CentralWidget::zoomOut() TRACE_OBJ HelpViewer *viewer = currentHelpViewer(); if (viewer) - viewer->zoomOut(); + viewer->scaleDown(); if (tabWidget->currentWidget() == m_searchWidget) m_searchWidget->zoomOut(); @@ -237,9 +238,8 @@ void CentralWidget::nextPage() void CentralWidget::resetZoom() { TRACE_OBJ - HelpViewer *viewer = currentHelpViewer(); - if (viewer) - viewer->resetZoom(); + if (HelpViewer *viewer = currentHelpViewer()) + viewer->resetScale(); if (tabWidget->currentWidget() == m_searchWidget) m_searchWidget->resetZoom(); @@ -522,25 +522,12 @@ void CentralWidget::setSourceInNewTab(const QUrl &url, qreal zoom) return; #endif - viewer = new HelpViewer(this); + viewer = new HelpViewer(this, zoom); viewer->installEventFilter(this); viewer->setSource(url); viewer->setFocus(Qt::OtherFocusReason); tabWidget->setCurrentIndex(tabWidget->addTab(viewer, quoteTabTitle(viewer->documentTitle()))); - - QFont font; - getBrowserFontFor(viewer, &font); - -#if defined(QT_NO_WEBKIT) - font.setPointSize((int)(font.pointSize() + zoom)); - setBrowserFontFor(viewer, font); - viewer->setZoom((int)zoom); -#else - setBrowserFontFor(viewer, font); - viewer->setTextSizeMultiplier(zoom == 0.0 ? 1.0 : zoom); -#endif - connectSignals(); } @@ -579,7 +566,13 @@ void CentralWidget::connectSignals() } } -HelpViewer *CentralWidget::currentHelpViewer() const +HelpViewer* CentralWidget::viewerAt(int index) const +{ + TRACE_OBJ + return qobject_cast<HelpViewer*>(tabWidget->widget(index)); +} + +HelpViewer* CentralWidget::currentHelpViewer() const { TRACE_OBJ return qobject_cast<HelpViewer*>(tabWidget->currentWidget()); @@ -755,6 +748,7 @@ void CentralWidget::keyPressEvent(QKeyEvent *e) void CentralWidget::findNext() { + TRACE_OBJ find(findWidget->text(), true); } @@ -876,21 +870,24 @@ bool CentralWidget::findInTextBrowser(const QString &ttf, bool forward) void CentralWidget::updateBrowserFont() { TRACE_OBJ - QFont font; - bool searchAttached = searchWidgetAttached(); + const bool searchAttached = searchWidgetAttached(); if (searchAttached) { - getBrowserFontFor(m_searchWidget, &font); - setBrowserFontFor(m_searchWidget, font); + HelpEngineWrapper &helpEngine = HelpEngineWrapper::instance(); + m_searchWidget->setFont(helpEngine.usesBrowserFont() + ? helpEngine.browserFont() : qApp->font()); } - int i = searchAttached ? 1 : 0; - getBrowserFontFor(tabWidget->widget(i), &font); - for ( ; i < tabWidget->count(); ++i) - setBrowserFontFor(tabWidget->widget(i), font); + const int count = tabWidget->count(); + if (HelpViewer* viewer = viewerAt(count - 1)) { + const QFont &font = viewer->viewerFont(); + for (int i = searchAttached ? 1 : 0; i < count; ++i) + viewerAt(i)->setViewerFont(font); + } } bool CentralWidget::searchWidgetAttached() const { + TRACE_OBJ return m_searchWidget && m_searchWidget->isAttached(); } @@ -906,9 +903,9 @@ void CentralWidget::createSearchWidget(QHelpSearchEngine *searchEngine) connect(m_searchWidget, SIGNAL(requestShowLinkInNewTab(QUrl)), this, SLOT(setSourceFromSearchInNewTab(QUrl))); - QFont font; - getBrowserFontFor(m_searchWidget, &font); - setBrowserFontFor(m_searchWidget, font); + HelpEngineWrapper &helpEngine = HelpEngineWrapper::instance(); + m_searchWidget->setFont(!helpEngine.usesBrowserFont() ? qApp->font() + : helpEngine.browserFont()); } void CentralWidget::activateSearchWidget(bool updateLastTabPage) @@ -1103,41 +1100,4 @@ QMap<int, QString> CentralWidget::currentSourceFileList() const return sourceList; } -void CentralWidget::getBrowserFontFor(QWidget *viewer, QFont *font) -{ - TRACE_OBJ - HelpEngineWrapper &helpEngine = HelpEngineWrapper::instance(); - if (!helpEngine.usesBrowserFont()) { - *font = qApp->font(); // case for QTextBrowser and SearchWidget -#if !defined(QT_NO_WEBKIT) - QWebView *view = qobject_cast<QWebView*> (viewer); - if (view) { - QWebSettings *settings = QWebSettings::globalSettings(); - *font = QFont(settings->fontFamily(QWebSettings::StandardFont), - settings->fontSize(QWebSettings::DefaultFontSize)); - } -#endif - } else { - *font = helpEngine.browserFont(); - } -} - -void CentralWidget::setBrowserFontFor(QWidget *widget, const QFont &font) -{ - TRACE_OBJ -#if !defined(QT_NO_WEBKIT) - QWebView *view = qobject_cast<QWebView*> (widget); - if (view) { - QWebSettings *settings = view->settings(); - settings->setFontFamily(QWebSettings::StandardFont, font.family()); - settings->setFontSize(QWebSettings::DefaultFontSize, font.pointSize()); - } else if (widget && widget->font() != font) { - widget->setFont(font); - } -#else - if (widget && widget->font() != font) - widget->setFont(font); -#endif -} - QT_END_NAMESPACE diff --git a/tools/assistant/tools/assistant/centralwidget.h b/tools/assistant/tools/assistant/centralwidget.h index 6c3e93c..f286ff7 100644 --- a/tools/assistant/tools/assistant/centralwidget.h +++ b/tools/assistant/tools/assistant/centralwidget.h @@ -70,6 +70,8 @@ public: bool isBackwardAvailable() const; QList<QAction*> globalActions() const; void setGlobalActions(const QList<QAction*> &actions); + + HelpViewer *viewerAt(int index) const; HelpViewer *currentHelpViewer() const; bool searchWidgetAttached() const; @@ -143,9 +145,6 @@ private: QString quoteTabTitle(const QString &title) const; void setLastShownPages(); - void getBrowserFontFor(QWidget* viewer, QFont *font); - void setBrowserFontFor(QWidget *widget, const QFont &font); - private: int lastTabPage; QList<QAction*> globalActionList; diff --git a/tools/assistant/tools/assistant/contentwindow.cpp b/tools/assistant/tools/assistant/contentwindow.cpp index 976ed7a..e0347c8 100644 --- a/tools/assistant/tools/assistant/contentwindow.cpp +++ b/tools/assistant/tools/assistant/contentwindow.cpp @@ -144,7 +144,7 @@ bool ContentWindow::eventFilter(QObject *o, QEvent *e) qobject_cast<QHelpContentModel*>(m_contentWidget->model()); if (contentModel) { QHelpContentItem *itm = contentModel->contentItemAt(index); - if (itm && HelpViewer::canOpenPage(itm->url().path())) + if (itm && AbstractHelpViewer::canOpenPage(itm->url().path())) CentralWidget::instance()->setSourceInNewTab(itm->url()); } } else if (button == Qt::LeftButton) { @@ -170,7 +170,7 @@ void ContentWindow::showContextMenu(const QPoint &pos) QMenu menu; QAction *curTab = menu.addAction(tr("Open Link")); QAction *newTab = menu.addAction(tr("Open Link in New Tab")); - if (!HelpViewer::canOpenPage(itm->url().path())) + if (!AbstractHelpViewer::canOpenPage(itm->url().path())) newTab->setEnabled(false); menu.move(m_contentWidget->mapToGlobal(pos)); diff --git a/tools/assistant/tools/assistant/helpviewer.cpp b/tools/assistant/tools/assistant/helpviewer.cpp index 8e4d3ed..8597f6b 100644 --- a/tools/assistant/tools/assistant/helpviewer.cpp +++ b/tools/assistant/tools/assistant/helpviewer.cpp @@ -38,603 +38,31 @@ ** $QT_END_LICENSE$ ** ****************************************************************************/ -#include "tracer.h" - #include "helpviewer.h" -#include "centralwidget.h" -#include "helpenginewrapper.h" - -#include <QtCore/QDir> -#include <QtCore/QEvent> -#include <QtCore/QVariant> -#include <QtCore/QByteArray> -#include <QtCore/QStringBuilder> -#include <QtCore/QTemporaryFile> -#include <QtCore/QTimer> - -#include <QtGui/QMenu> -#include <QtGui/QKeyEvent> -#include <QtGui/QClipboard> -#include <QtGui/QApplication> -#include <QtGui/QMessageBox> -#include <QtGui/QDesktopServices> +#include "tracer.h" -#include <QNetworkAccessManager> -#include <QNetworkReply> -#include <QNetworkRequest> +#include <QtCore/QCoreApplication> +#include <QtCore/QUrl> QT_BEGIN_NAMESPACE -namespace { - const QString PageNotFoundMessage = - QCoreApplication::translate("HelpViewer", - "<title>Error 404...</title><div align=\"center\"><br><br>" - "<h1>The page could not be found</h1><br><h3>'%1'</h3></div>"); -} - -#if !defined(QT_NO_WEBKIT) - -class HelpNetworkReply : public QNetworkReply -{ -public: - HelpNetworkReply(const QNetworkRequest &request, const QByteArray &fileData, - const QString &mimeType); - - virtual void abort(); - - virtual qint64 bytesAvailable() const - { return data.length() + QNetworkReply::bytesAvailable(); } - -protected: - virtual qint64 readData(char *data, qint64 maxlen); - -private: - QByteArray data; - qint64 origLen; -}; - -HelpNetworkReply::HelpNetworkReply(const QNetworkRequest &request, - const QByteArray &fileData, const QString& mimeType) - : data(fileData), origLen(fileData.length()) -{ - TRACE_OBJ - setRequest(request); - setOpenMode(QIODevice::ReadOnly); - - setHeader(QNetworkRequest::ContentTypeHeader, mimeType); - setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(origLen)); - QTimer::singleShot(0, this, SIGNAL(metaDataChanged())); - QTimer::singleShot(0, this, SIGNAL(readyRead())); -} - -void HelpNetworkReply::abort() -{ - TRACE_OBJ - // nothing to do -} - -qint64 HelpNetworkReply::readData(char *buffer, qint64 maxlen) -{ - TRACE_OBJ - qint64 len = qMin(qint64(data.length()), maxlen); - if (len) { - qMemCopy(buffer, data.constData(), len); - data.remove(0, len); - } - if (!data.length()) - QTimer::singleShot(0, this, SIGNAL(finished())); - return len; -} - -class HelpNetworkAccessManager : public QNetworkAccessManager -{ -public: - HelpNetworkAccessManager(QObject *parent); - -protected: - virtual QNetworkReply *createRequest(Operation op, - const QNetworkRequest &request, QIODevice *outgoingData = 0); -}; - -HelpNetworkAccessManager::HelpNetworkAccessManager(QObject *parent) - : QNetworkAccessManager(parent) -{ - TRACE_OBJ -} - -QNetworkReply *HelpNetworkAccessManager::createRequest(Operation /*op*/, - const QNetworkRequest &request, QIODevice* /*outgoingData*/) -{ - TRACE_OBJ - const QUrl& url = request.url(); - QString mimeType = url.toString(); - if (mimeType.endsWith(QLatin1String(".svg")) - || mimeType.endsWith(QLatin1String(".svgz"))) { - mimeType = QLatin1String("image/svg+xml"); - } else if (mimeType.endsWith(QLatin1String(".css"))) { - mimeType = QLatin1String("text/css"); - } else if (mimeType.endsWith(QLatin1String(".js"))) { - mimeType = QLatin1String("text/javascript"); - } else if (mimeType.endsWith(QLatin1String(".txt"))) { - mimeType = QLatin1String("text/plain"); - } else { - mimeType = QLatin1String("text/html"); - } - - HelpEngineWrapper &helpEngine = HelpEngineWrapper::instance(); - const QByteArray &data = helpEngine.findFile(url).isValid() - ? helpEngine.fileData(url) - : PageNotFoundMessage.arg(url.toString()).toUtf8(); - return new HelpNetworkReply(request, data, mimeType); -} - -class HelpPage : public QWebPage -{ -public: - HelpPage(CentralWidget *central, QObject *parent); - -protected: - virtual QWebPage *createWindow(QWebPage::WebWindowType); - virtual void triggerAction(WebAction action, bool checked = false); - - virtual bool acceptNavigationRequest(QWebFrame *frame, - const QNetworkRequest &request, NavigationType type); - -private: - CentralWidget *centralWidget; - bool closeNewTabIfNeeded; - - friend class HelpViewer; - Qt::MouseButtons m_pressedButtons; - Qt::KeyboardModifiers m_keyboardModifiers; -}; - -HelpPage::HelpPage(CentralWidget *central, QObject *parent) - : QWebPage(parent) - , centralWidget(central) - , closeNewTabIfNeeded(false) - , m_pressedButtons(Qt::NoButton) - , m_keyboardModifiers(Qt::NoModifier) -{ - TRACE_OBJ -} - -QWebPage *HelpPage::createWindow(QWebPage::WebWindowType) -{ - TRACE_OBJ - HelpPage* newPage = static_cast<HelpPage*>(centralWidget->newEmptyTab()->page()); - if (newPage) - newPage->closeNewTabIfNeeded = closeNewTabIfNeeded; - closeNewTabIfNeeded = false; - return newPage; -} +QString AbstractHelpViewer::PageNotFoundMessage = + QCoreApplication::translate("HelpViewer", "<title>Error 404...</title><div " + "align=\"center\"><br><br><h1>The page could not be found</h1><br><h3>'%1'" + "</h3></div>"); -void HelpPage::triggerAction(WebAction action, bool checked) +AbstractHelpViewer::AbstractHelpViewer() { - TRACE_OBJ - switch (action) { - case OpenLinkInNewWindow: - closeNewTabIfNeeded = true; - default: // fall through - QWebPage::triggerAction(action, checked); - break; - } } -bool HelpPage::acceptNavigationRequest(QWebFrame *, - const QNetworkRequest &request, QWebPage::NavigationType type) +AbstractHelpViewer::~AbstractHelpViewer() { - TRACE_OBJ - const QUrl &url = request.url(); - const bool closeNewTab = closeNewTabIfNeeded; - closeNewTabIfNeeded = false; - - if (HelpViewer::isLocalUrl(url)) { - const QString& path = url.path(); - if (!HelpViewer::canOpenPage(path)) { - QTemporaryFile tmpTmpFile; - if (!tmpTmpFile.open()) - return false; - const QString extension = QFileInfo(path).completeSuffix(); - QFile actualTmpFile(tmpTmpFile.fileName() % QLatin1String(".") - % extension); - if (actualTmpFile.open(QIODevice::ReadWrite | QIODevice::Truncate)) { - actualTmpFile.write(HelpEngineWrapper::instance().fileData(url)); - actualTmpFile.close(); - QDesktopServices::openUrl(QUrl(actualTmpFile.fileName())); - } - - if (closeNewTab) - QMetaObject::invokeMethod(CentralWidget::instance(), "closeTab"); - return false; - } - - if (type == QWebPage::NavigationTypeLinkClicked - && (m_keyboardModifiers & Qt::ControlModifier - || m_pressedButtons == Qt::MidButton)) { - HelpViewer* viewer = centralWidget->newEmptyTab(); - if (viewer) - CentralWidget::instance()->setSource(url); - m_pressedButtons = Qt::NoButton; - m_keyboardModifiers = Qt::NoModifier; - return false; - } - return true; - } - - QDesktopServices::openUrl(url); - return false; } -HelpViewer::HelpViewer(CentralWidget *parent) - : QWebView(parent) - , parentWidget(parent) - , loadFinished(false) - , helpEngine(HelpEngineWrapper::instance()) +bool AbstractHelpViewer::isLocalUrl(const QUrl &url) { TRACE_OBJ - setAcceptDrops(false); - - setPage(new HelpPage(parent, this)); - - page()->setNetworkAccessManager(new HelpNetworkAccessManager(this)); - - QAction* action = pageAction(QWebPage::OpenLinkInNewWindow); - action->setText(tr("Open Link in New Tab")); - if (!parent) - action->setVisible(false); - - pageAction(QWebPage::DownloadLinkToDisk)->setVisible(false); - pageAction(QWebPage::DownloadImageToDisk)->setVisible(false); - pageAction(QWebPage::OpenImageInNewWindow)->setVisible(false); - - connect(pageAction(QWebPage::Copy), SIGNAL(changed()), this, - SLOT(actionChanged())); - connect(pageAction(QWebPage::Back), SIGNAL(changed()), this, - SLOT(actionChanged())); - connect(pageAction(QWebPage::Forward), SIGNAL(changed()), this, - SLOT(actionChanged())); - connect(page(), SIGNAL(linkHovered(QString,QString,QString)), this, - SIGNAL(highlighted(QString))); - connect(this, SIGNAL(urlChanged(QUrl)), this, SIGNAL(sourceChanged(QUrl))); - connect(this, SIGNAL(loadFinished(bool)), this, SLOT(setLoadFinished(bool))); -} - -void HelpViewer::setSource(const QUrl &url) -{ - TRACE_OBJ - loadFinished = false; - if (url.toString() == QLatin1String("help")) { - load(QUrl(QLatin1String("qthelp://com.trolltech.com." - "assistantinternal-1.0.0/assistant/assistant.html"))); - } else { - load(url); - } -} - -void HelpViewer::resetZoom() -{ - TRACE_OBJ - setTextSizeMultiplier(1.0); -} - -void HelpViewer::zoomIn(qreal range) -{ - TRACE_OBJ - setTextSizeMultiplier(textSizeMultiplier() + range / 10.0); -} - -void HelpViewer::zoomOut(qreal range) -{ - TRACE_OBJ - setTextSizeMultiplier(qMax(0.0, textSizeMultiplier() - range / 10.0)); -} - -void HelpViewer::wheelEvent(QWheelEvent *e) -{ - TRACE_OBJ - if (e->modifiers() & Qt::ControlModifier) { - const int delta = e->delta(); - if (delta > 0) - zoomIn(delta / 120); - else if (delta < 0) - zoomOut(-delta / 120); - e->accept(); - return; - } - QWebView::wheelEvent(e); -} - -void HelpViewer::mouseReleaseEvent(QMouseEvent *e) -{ - TRACE_OBJ - if (e->button() == Qt::XButton1) { - triggerPageAction(QWebPage::Back); - return; - } - - if (e->button() == Qt::XButton2) { - triggerPageAction(QWebPage::Forward); - return; - } - - QWebView::mouseReleaseEvent(e); -} - -void HelpViewer::actionChanged() -{ - TRACE_OBJ - QAction *a = qobject_cast<QAction *>(sender()); - if (a == pageAction(QWebPage::Copy)) - emit copyAvailable(a->isEnabled()); - else if (a == pageAction(QWebPage::Back)) - emit backwardAvailable(a->isEnabled()); - else if (a == pageAction(QWebPage::Forward)) - emit forwardAvailable(a->isEnabled()); -} - -void HelpViewer::mousePressEvent(QMouseEvent *event) -{ - TRACE_OBJ - HelpPage *currentPage = static_cast<HelpPage*>(page()); - if (currentPage) { - currentPage->m_pressedButtons = event->buttons(); - currentPage->m_keyboardModifiers = event->modifiers(); - } - QWebView::mousePressEvent(event); -} - -void HelpViewer::setLoadFinished(bool ok) -{ - TRACE_OBJ - loadFinished = ok; - emit sourceChanged(url()); -} - -#else // !defined(QT_NO_WEBKIT) - -HelpViewer::HelpViewer(CentralWidget *parent) - : QTextBrowser(parent) - , zoomCount(0) - , controlPressed(false) - , lastAnchor(QString()) - , parentWidget(parent) - , helpEngine(HelpEngineWrapper::instance()) -{ - TRACE_OBJ - document()->setDocumentMargin(8); -} - -void HelpViewer::setSource(const QUrl &url) -{ - TRACE_OBJ - bool help = url.toString() == QLatin1String("help"); - if (url.isValid() && !help) { - if (launchedWithExternalApp(url)) - return; - - QUrl u = helpEngine.findFile(url); - if (u.isValid()) { - QTextBrowser::setSource(u); - return; - } - } - - if (help) { - QTextBrowser::setSource(QUrl(QLatin1String("qthelp://com.trolltech.com." - "assistantinternal-1.0.0/assistant/assistant.html"))); - } else { - QTextBrowser::setSource(url); - setHtml(PageNotFoundMessage.arg(url.toString())); - emit sourceChanged(url); - } -} - -void HelpViewer::resetZoom() -{ - TRACE_OBJ - if (zoomCount == 0) - return; - - QTextBrowser::zoomOut(zoomCount); - zoomCount = 0; -} - -void HelpViewer::zoomIn(int range) -{ - TRACE_OBJ - if (zoomCount == 10) - return; - - QTextBrowser::zoomIn(range); - zoomCount++; -} - -void HelpViewer::zoomOut(int range) -{ - TRACE_OBJ - if (zoomCount == -5) - return; - - QTextBrowser::zoomOut(range); - zoomCount--; -} - -bool HelpViewer::launchedWithExternalApp(const QUrl &url) -{ - TRACE_OBJ - const bool canOpen = canOpenPage(url.path()); - if (!isLocalUrl(url) || !canOpen) { - bool launched = false; - if (!canOpen && url.scheme() == QLatin1String("qthelp")) { - const QString& path = url.path(); - const int lastDash = path.lastIndexOf(QChar('/')); - QString fileName = QDir::tempPath() + QDir::separator(); - if (lastDash < 0) - fileName += path; - else - fileName += path.mid(lastDash + 1, path.length()); - - QFile tmpFile(QDir::cleanPath(fileName)); - if (tmpFile.open(QIODevice::ReadWrite)) { - tmpFile.write(helpEngine.fileData(url)); - tmpFile.close(); - } - launched = QDesktopServices::openUrl(QUrl(tmpFile.fileName())); - } else { - launched = QDesktopServices::openUrl(url); - } - - if (!launched) { - QMessageBox::information(this, tr("Help"), - tr("Unable to launch external application.\n"), tr("OK")); - } - return true; - } - return false; -} - -QVariant HelpViewer::loadResource(int type, const QUrl &name) -{ - TRACE_OBJ - QByteArray ba; - if (type < 4) { - ba = helpEngine.fileData(name); - if (name.toString().endsWith(QLatin1String(".svg"), Qt::CaseInsensitive)) { - QImage image; - image.loadFromData(ba, "svg"); - if (!image.isNull()) - return image; - } - } - return ba; -} - -void HelpViewer::openLinkInNewTab() -{ - TRACE_OBJ - if(lastAnchor.isEmpty()) - return; - - parentWidget->setSourceInNewTab(QUrl(lastAnchor)); - lastAnchor.clear(); -} - -void HelpViewer::openLinkInNewTab(const QString &link) -{ - TRACE_OBJ - lastAnchor = link; - openLinkInNewTab(); -} - -bool HelpViewer::hasAnchorAt(const QPoint& pos) -{ - TRACE_OBJ - lastAnchor = anchorAt(pos); - if (lastAnchor.isEmpty()) - return false; - - lastAnchor = source().resolved(lastAnchor).toString(); - if (lastAnchor.at(0) == QLatin1Char('#')) { - QString src = source().toString(); - int hsh = src.indexOf(QLatin1Char('#')); - lastAnchor = (hsh>=0 ? src.left(hsh) : src) + lastAnchor; - } - - return true; -} - -void HelpViewer::contextMenuEvent(QContextMenuEvent *e) -{ - TRACE_OBJ - QMenu menu(QLatin1String(""), 0); - - QUrl link; - QAction *copyAnchorAction = 0; - if (hasAnchorAt(e->pos())) { - link = anchorAt(e->pos()); - if (link.isRelative()) - link = source().resolved(link); - copyAnchorAction = menu.addAction(tr("Copy &Link Location")); - copyAnchorAction->setEnabled(!link.isEmpty() && link.isValid()); - - menu.addAction(tr("Open Link in New Tab\tCtrl+LMB"), this, - SLOT(openLinkInNewTab())); - menu.addSeparator(); - } - menu.addActions(parentWidget->globalActions()); - QAction *action = menu.exec(e->globalPos()); - if (action == copyAnchorAction) - QApplication::clipboard()->setText(link.toString()); -} - -void HelpViewer::mouseReleaseEvent(QMouseEvent *e) -{ - TRACE_OBJ - if (e->button() == Qt::XButton1) { - QTextBrowser::backward(); - return; - } - - if (e->button() == Qt::XButton2) { - QTextBrowser::forward(); - return; - } - - controlPressed = e->modifiers() & Qt::ControlModifier; - if ((controlPressed && hasAnchorAt(e->pos())) || - (e->button() == Qt::MidButton && hasAnchorAt(e->pos()))) { - openLinkInNewTab(); - return; - } - - QTextBrowser::mouseReleaseEvent(e); -} - -void HelpViewer::keyPressEvent(QKeyEvent *e) -{ - TRACE_OBJ - if ((e->key() == Qt::Key_Home && e->modifiers() != Qt::NoModifier) - || (e->key() == Qt::Key_End && e->modifiers() != Qt::NoModifier)) { - QKeyEvent* event = new QKeyEvent(e->type(), e->key(), Qt::NoModifier, - e->text(), e->isAutoRepeat(), e->count()); - e = event; - } - QTextBrowser::keyPressEvent(e); -} - -void HelpViewer::wheelEvent(QWheelEvent *e) -{ - TRACE_OBJ - if (e->modifiers() == Qt::CTRL) { - e->accept(); - (e->delta() > 0) ? zoomIn() : zoomOut(); - } else { - e->ignore(); - QTextBrowser::wheelEvent(e); - } -} - -#endif // !defined(QT_NO_WEBKIT) - -void HelpViewer::home() -{ - TRACE_OBJ - setSource(helpEngine.homePage()); -} - -bool HelpViewer::canOpenPage(const QString &url) -{ - TRACE_OBJ - return url.endsWith(QLatin1String(".html"), Qt::CaseInsensitive) - || url.endsWith(QLatin1String(".htm"), Qt::CaseInsensitive) - || url == QLatin1String("blank"); -} - -bool HelpViewer::isLocalUrl(const QUrl &url) -{ - TRACE_OBJ - const QString scheme = url.scheme(); + const QString &scheme = url.scheme(); return scheme.isEmpty() || scheme == QLatin1String("file") || scheme == QLatin1String("qrc") @@ -643,5 +71,12 @@ bool HelpViewer::isLocalUrl(const QUrl &url) || scheme == QLatin1String("about"); } +bool AbstractHelpViewer::canOpenPage(const QString &url) +{ + TRACE_OBJ + return url.endsWith(QLatin1String(".html"), Qt::CaseInsensitive) + || url.endsWith(QLatin1String(".htm"), Qt::CaseInsensitive) + || url == QLatin1String("blank"); +} QT_END_NAMESPACE diff --git a/tools/assistant/tools/assistant/helpviewer.h b/tools/assistant/tools/assistant/helpviewer.h index 4dd8064..fe860fd 100644 --- a/tools/assistant/tools/assistant/helpviewer.h +++ b/tools/assistant/tools/assistant/helpviewer.h @@ -38,144 +38,37 @@ ** $QT_END_LICENSE$ ** ****************************************************************************/ - #ifndef HELPVIEWER_H #define HELPVIEWER_H -#include <QtCore/QUrl> -#include <QtCore/QVariant> -#include <QtGui/QTextBrowser> -#include <QtGui/QAction> +#include <QtCore/QString> -#if !defined(QT_NO_WEBKIT) -#include <QWebView> -#endif +#include <QtGui/QFont> QT_BEGIN_NAMESPACE -class CentralWidget; -class HelpEngineWrapper; - -class QPoint; -class QString; -class QKeyEvent; -class QMouseEvent; -class QContextMenuEvent; +class QUrl; -#if !defined(QT_NO_WEBKIT) - -class HelpViewer : public QWebView +class AbstractHelpViewer { - Q_OBJECT - public: - HelpViewer(CentralWidget *parent); - void setSource(const QUrl &url); - - inline QUrl source() const - { return url(); } - - inline QString documentTitle() const - { return title(); } - - inline bool hasSelection() const - { return !selectedText().isEmpty(); } // ### this is suboptimal - - void resetZoom(); - void zoomIn(qreal range = 1); - void zoomOut(qreal range = 1); + AbstractHelpViewer(); + ~AbstractHelpViewer(); - inline void copy() - { return triggerPageAction(QWebPage::Copy); } + virtual QFont viewerFont() const = 0; + virtual void setViewerFont(const QFont &font) = 0; - inline bool isForwardAvailable() const - { return pageAction(QWebPage::Forward)->isEnabled(); } - inline bool isBackwardAvailable() const - { return pageAction(QWebPage::Back)->isEnabled(); } - inline bool hasLoadFinished() const - { return loadFinished; } - inline qreal zoom() const - { return textSizeMultiplier(); } + virtual void scaleUp() = 0; + virtual void scaleDown() = 0; + + virtual void resetScale() = 0; + virtual qreal scale() const = 0; - static bool canOpenPage(const QString &url); + static QString PageNotFoundMessage; static bool isLocalUrl(const QUrl &url); - -public Q_SLOTS: - void home(); - void backward() { back(); } - -Q_SIGNALS: - void copyAvailable(bool enabled); - void forwardAvailable(bool enabled); - void backwardAvailable(bool enabled); - void highlighted(const QString &); - void sourceChanged(const QUrl &); - -protected: - virtual void wheelEvent(QWheelEvent *); - void mouseReleaseEvent(QMouseEvent *e); - void mousePressEvent(QMouseEvent *event); - -private Q_SLOTS: - void actionChanged(); - void setLoadFinished(bool ok); - -private: - CentralWidget* parentWidget; - bool loadFinished; - HelpEngineWrapper &helpEngine; -}; - -#else - -class HelpViewer : public QTextBrowser -{ - Q_OBJECT - -public: - HelpViewer(CentralWidget *parent); - void setSource(const QUrl &url); - - void resetZoom(); - void zoomIn(int range = 1); - void zoomOut(int range = 1); - int zoom() const { return zoomCount; } - void setZoom(int zoom) { zoomCount = zoom; } - - inline bool hasSelection() const - { return textCursor().hasSelection(); } - - bool launchedWithExternalApp(const QUrl &url); static bool canOpenPage(const QString &url); - static bool isLocalUrl(const QUrl &url); - -public Q_SLOTS: - void home(); - -protected: - void wheelEvent(QWheelEvent *e); - -private: - QVariant loadResource(int type, const QUrl &name); - void openLinkInNewTab(const QString &link); - bool hasAnchorAt(const QPoint& pos); - void contextMenuEvent(QContextMenuEvent *e); - void mouseReleaseEvent(QMouseEvent *e); - void keyPressEvent(QKeyEvent *e); - -private slots: - void openLinkInNewTab(); - -private: - int zoomCount; - bool controlPressed; - QString lastAnchor; - CentralWidget* parentWidget; - HelpEngineWrapper &helpEngine; }; -#endif - QT_END_NAMESPACE -#endif +#endif // HELPVIEWER_H diff --git a/tools/assistant/tools/assistant/helpviewer_qtb.cpp b/tools/assistant/tools/assistant/helpviewer_qtb.cpp new file mode 100644 index 0000000..3aafe67 --- /dev/null +++ b/tools/assistant/tools/assistant/helpviewer_qtb.cpp @@ -0,0 +1,331 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Assistant of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#if defined(QT_NO_WEBKIT) + +#include "helpviewer_qtb.h" +#include "helpviewer_qwv.h" + +#include "centralwidget.h" +#include "helpenginewrapper.h" +#include "tracer.h" + +#include <QtCore/QDir> +#include <QtCore/QStringBuilder> + +#include <QtGui/QContextMenuEvent> +#include <QtGui/QMenu> +#include <QtGui/QClipboard> +#include <QtGui/QApplication> +#include <QtGui/QMessageBox> +#include <QtGui/QDesktopServices> + +QT_BEGIN_NAMESPACE + +HelpViewer::HelpViewer(CentralWidget *parent, qreal zoom) + : QTextBrowser(parent) + , zoomCount(zoom) + , controlPressed(false) + , lastAnchor(QString()) + , parentWidget(parent) + , helpEngine(HelpEngineWrapper::instance()) + , forceFont(false) +{ + TRACE_OBJ + installEventFilter(this); + document()->setDocumentMargin(8); + + QFont font = viewerFont(); + font.setPointSize(int(font.pointSize() + zoom)); + setViewerFont(font); +} + +HelpViewer::~HelpViewer() +{ + TRACE_OBJ +} + +QFont HelpViewer::viewerFont() const +{ + TRACE_OBJ + if (HelpEngineWrapper::instance().usesBrowserFont()) + return helpEngine.browserFont(); + return qApp->font(); +} + +void HelpViewer::setViewerFont(const QFont &newFont) +{ + TRACE_OBJ + if (font() != newFont) { + forceFont = true; + setFont(newFont); + forceFont = false; + } +} + +void HelpViewer::scaleUp() +{ + TRACE_OBJ + if (zoomCount < 10) { + ++zoomCount; + forceFont = true; + zoomIn(); + forceFont = false; + } +} + +void HelpViewer::scaleDown() +{ + TRACE_OBJ + if (zoomCount > -5) { + --zoomCount; + forceFont = true; + zoomOut(); + forceFont = false; + } +} + +void HelpViewer::resetScale() +{ + TRACE_OBJ + if (zoomCount != 0) { + forceFont = true; + zoomOut(zoomCount); + forceFont = false; + } + zoomCount = 0; +} + +void HelpViewer::setSource(const QUrl &url) +{ + TRACE_OBJ + bool help = url.toString() == QLatin1String("help"); + if (url.isValid() && !help) { + if (launchedWithExternalApp(url)) + return; + + QUrl u = helpEngine.findFile(url); + if (u.isValid()) { + QTextBrowser::setSource(u); + return; + } + } + + if (help) { + QTextBrowser::setSource(QUrl(QLatin1String("qthelp://com.trolltech.com." + "assistantinternal-1.0.0/assistant/assistant.html"))); + } else { + QTextBrowser::setSource(url); + setHtml(PageNotFoundMessage.arg(url.toString())); + emit sourceChanged(url); + } +} + +bool HelpViewer::launchedWithExternalApp(const QUrl &url) +{ + TRACE_OBJ + const bool canOpen = canOpenPage(url.path()); + if (!isLocalUrl(url) || !canOpen) { + bool launched = false; + if (!canOpen && url.scheme() == QLatin1String("qthelp")) { + const QString& path = url.path(); + const int lastDash = path.lastIndexOf(QChar('/')); + QString fileName = QDir::tempPath() + QDir::separator(); + if (lastDash < 0) + fileName += path; + else + fileName += path.mid(lastDash + 1, path.length()); + + QFile tmpFile(QDir::cleanPath(fileName)); + if (tmpFile.open(QIODevice::ReadWrite)) { + tmpFile.write(helpEngine.fileData(url)); + tmpFile.close(); + } + launched = QDesktopServices::openUrl(QUrl(tmpFile.fileName())); + } else { + launched = QDesktopServices::openUrl(url); + } + + if (!launched) { + QMessageBox::information(this, tr("Help"), + tr("Unable to launch external application.\n"), tr("OK")); + } + return true; + } + return false; +} + +QVariant HelpViewer::loadResource(int type, const QUrl &name) +{ + TRACE_OBJ + QByteArray ba; + if (type < 4) { + ba = helpEngine.fileData(name); + if (name.toString().endsWith(QLatin1String(".svg"), Qt::CaseInsensitive)) { + QImage image; + image.loadFromData(ba, "svg"); + if (!image.isNull()) + return image; + } + } + return ba; +} + +void HelpViewer::openLinkInNewTab() +{ + TRACE_OBJ + if(lastAnchor.isEmpty()) + return; + + parentWidget->setSourceInNewTab(QUrl(lastAnchor)); + lastAnchor.clear(); +} + +void HelpViewer::openLinkInNewTab(const QString &link) +{ + TRACE_OBJ + lastAnchor = link; + openLinkInNewTab(); +} + +bool HelpViewer::hasAnchorAt(const QPoint& pos) +{ + TRACE_OBJ + lastAnchor = anchorAt(pos); + if (lastAnchor.isEmpty()) + return false; + + lastAnchor = source().resolved(lastAnchor).toString(); + if (lastAnchor.at(0) == QLatin1Char('#')) { + QString src = source().toString(); + int hsh = src.indexOf(QLatin1Char('#')); + lastAnchor = (hsh>=0 ? src.left(hsh) : src) + lastAnchor; + } + + return true; +} + +void HelpViewer::contextMenuEvent(QContextMenuEvent *e) +{ + TRACE_OBJ + QMenu menu(QLatin1String(""), 0); + + QUrl link; + QAction *copyAnchorAction = 0; + if (hasAnchorAt(e->pos())) { + link = anchorAt(e->pos()); + if (link.isRelative()) + link = source().resolved(link); + copyAnchorAction = menu.addAction(tr("Copy &Link Location")); + copyAnchorAction->setEnabled(!link.isEmpty() && link.isValid()); + + menu.addAction(tr("Open Link in New Tab\tCtrl+LMB"), this, + SLOT(openLinkInNewTab())); + menu.addSeparator(); + } + menu.addActions(parentWidget->globalActions()); + QAction *action = menu.exec(e->globalPos()); + if (action == copyAnchorAction) + QApplication::clipboard()->setText(link.toString()); +} + +void HelpViewer::mouseReleaseEvent(QMouseEvent *e) +{ + TRACE_OBJ + if (e->button() == Qt::XButton1) { + QTextBrowser::backward(); + return; + } + + if (e->button() == Qt::XButton2) { + QTextBrowser::forward(); + return; + } + + controlPressed = e->modifiers() & Qt::ControlModifier; + if ((controlPressed && hasAnchorAt(e->pos())) || + (e->button() == Qt::MidButton && hasAnchorAt(e->pos()))) { + openLinkInNewTab(); + return; + } + + QTextBrowser::mouseReleaseEvent(e); +} + +void HelpViewer::keyPressEvent(QKeyEvent *e) +{ + TRACE_OBJ + if ((e->key() == Qt::Key_Home && e->modifiers() != Qt::NoModifier) + || (e->key() == Qt::Key_End && e->modifiers() != Qt::NoModifier)) { + QKeyEvent* event = new QKeyEvent(e->type(), e->key(), Qt::NoModifier, + e->text(), e->isAutoRepeat(), e->count()); + e = event; + } + QTextBrowser::keyPressEvent(e); +} + +void HelpViewer::home() +{ + TRACE_OBJ + setSource(helpEngine.homePage()); +} + +void HelpViewer::wheelEvent(QWheelEvent *e) +{ + TRACE_OBJ + if (e->modifiers() == Qt::ControlModifier) { + e->accept(); + e->delta() > 0 ? scaleUp() : scaleDown(); + } else { + QTextBrowser::wheelEvent(e); + } +} + +bool HelpViewer::eventFilter(QObject *obj, QEvent *event) +{ + TRACE_OBJ + if (event->type() == QEvent::FontChange && !forceFont) + return true; + return QTextBrowser::eventFilter(obj, event); +} + +QT_END_NAMESPACE + +#endif // QT_NO_WEBKIT diff --git a/tools/assistant/tools/assistant/helpviewer_qtb.h b/tools/assistant/tools/assistant/helpviewer_qtb.h new file mode 100644 index 0000000..e927b34 --- /dev/null +++ b/tools/assistant/tools/assistant/helpviewer_qtb.h @@ -0,0 +1,116 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Assistant of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#if defined(QT_NO_WEBKIT) + +#ifndef HELPVIEWERQTB_H +#define HELPVIEWERQTB_H + +#include "helpviewer.h" + +#include <QtCore/QUrl> +#include <QtCore/QVariant> + +#include <QtGui/QTextBrowser> + +QT_BEGIN_NAMESPACE + +class CentralWidget; +class HelpEngineWrapper; +class QContextMenuEvent; +class QKeyEvent; +class QMouseEvent; + +class HelpViewer : public QTextBrowser, public AbstractHelpViewer +{ + Q_OBJECT + +public: + HelpViewer(CentralWidget *parent, qreal zoom = 0.0); + ~HelpViewer(); + + QFont viewerFont() const; + void setViewerFont(const QFont &font); + + void scaleUp(); + void scaleDown(); + void resetScale(); + qreal scale() const { return zoomCount; } + + void setSource(const QUrl &url); + + inline bool hasSelection() const + { return textCursor().hasSelection(); } + + bool launchedWithExternalApp(const QUrl &url); + +public Q_SLOTS: + void home(); + +protected: + void wheelEvent(QWheelEvent *e); + bool eventFilter(QObject *obj, QEvent *event); + +private: + QVariant loadResource(int type, const QUrl &name); + void openLinkInNewTab(const QString &link); + bool hasAnchorAt(const QPoint& pos); + void contextMenuEvent(QContextMenuEvent *e); + void mouseReleaseEvent(QMouseEvent *e); + void keyPressEvent(QKeyEvent *e); + +private slots: + void openLinkInNewTab(); + +private: + int zoomCount; + bool controlPressed; + QString lastAnchor; + CentralWidget* parentWidget; + HelpEngineWrapper &helpEngine; + + bool forceFont; +}; + +QT_END_NAMESPACE + +#endif // HELPVIEWERQTB_H + +#endif // QT_NO_WEBKIT diff --git a/tools/assistant/tools/assistant/helpviewer_qwv.cpp b/tools/assistant/tools/assistant/helpviewer_qwv.cpp new file mode 100644 index 0000000..4857e00 --- /dev/null +++ b/tools/assistant/tools/assistant/helpviewer_qwv.cpp @@ -0,0 +1,413 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Assistant of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#if !defined(QT_NO_WEBKIT) + +#include "helpviewer_qwv.h" + +#include "centralwidget.h" +#include "helpenginewrapper.h" +#include "tracer.h" + +#include <QtCore/QFileInfo> +#include <QtCore/QString> +#include <QtCore/QStringBuilder> +#include <QtCore/QTemporaryFile> +#include <QtCore/QTimer> + +#include <QtGui/QDesktopServices> +#include <QtGui/QWheelEvent> + +#include <QtNetwork/QNetworkAccessManager> +#include <QtNetwork/QNetworkReply> +#include <QtNetwork/QNetworkRequest> + +QT_BEGIN_NAMESPACE + +class HelpNetworkReply : public QNetworkReply +{ +public: + HelpNetworkReply(const QNetworkRequest &request, const QByteArray &fileData, + const QString &mimeType); + + virtual void abort(); + + virtual qint64 bytesAvailable() const + { return data.length() + QNetworkReply::bytesAvailable(); } + +protected: + virtual qint64 readData(char *data, qint64 maxlen); + +private: + QByteArray data; + qint64 origLen; +}; + +HelpNetworkReply::HelpNetworkReply(const QNetworkRequest &request, + const QByteArray &fileData, const QString& mimeType) + : data(fileData), origLen(fileData.length()) +{ + TRACE_OBJ + setRequest(request); + setOpenMode(QIODevice::ReadOnly); + + setHeader(QNetworkRequest::ContentTypeHeader, mimeType); + setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(origLen)); + QTimer::singleShot(0, this, SIGNAL(metaDataChanged())); + QTimer::singleShot(0, this, SIGNAL(readyRead())); +} + +void HelpNetworkReply::abort() +{ + TRACE_OBJ +} + +qint64 HelpNetworkReply::readData(char *buffer, qint64 maxlen) +{ + TRACE_OBJ + qint64 len = qMin(qint64(data.length()), maxlen); + if (len) { + qMemCopy(buffer, data.constData(), len); + data.remove(0, len); + } + if (!data.length()) + QTimer::singleShot(0, this, SIGNAL(finished())); + return len; +} + +class HelpNetworkAccessManager : public QNetworkAccessManager +{ +public: + HelpNetworkAccessManager(QObject *parent); + +protected: + virtual QNetworkReply *createRequest(Operation op, + const QNetworkRequest &request, QIODevice *outgoingData = 0); +}; + +HelpNetworkAccessManager::HelpNetworkAccessManager(QObject *parent) + : QNetworkAccessManager(parent) +{ + TRACE_OBJ +} + +QNetworkReply *HelpNetworkAccessManager::createRequest(Operation /*op*/, + const QNetworkRequest &request, QIODevice* /*outgoingData*/) +{ + TRACE_OBJ + const QUrl& url = request.url(); + QString mimeType = url.toString(); + if (mimeType.endsWith(QLatin1String(".svg")) + || mimeType.endsWith(QLatin1String(".svgz"))) { + mimeType = QLatin1String("image/svg+xml"); + } else if (mimeType.endsWith(QLatin1String(".css"))) { + mimeType = QLatin1String("text/css"); + } else if (mimeType.endsWith(QLatin1String(".js"))) { + mimeType = QLatin1String("text/javascript"); + } else if (mimeType.endsWith(QLatin1String(".txt"))) { + mimeType = QLatin1String("text/plain"); + } else { + mimeType = QLatin1String("text/html"); + } + + HelpEngineWrapper &helpEngine = HelpEngineWrapper::instance(); + const QByteArray &data = helpEngine.findFile(url).isValid() + ? helpEngine.fileData(url) + : AbstractHelpViewer::PageNotFoundMessage.arg(url.toString()).toUtf8(); + return new HelpNetworkReply(request, data, mimeType); +} + +class HelpPage : public QWebPage +{ +public: + HelpPage(CentralWidget *central, QObject *parent); + +protected: + virtual QWebPage *createWindow(QWebPage::WebWindowType); + virtual void triggerAction(WebAction action, bool checked = false); + + virtual bool acceptNavigationRequest(QWebFrame *frame, + const QNetworkRequest &request, NavigationType type); + +private: + CentralWidget *centralWidget; + bool closeNewTabIfNeeded; + + friend class HelpViewer; + Qt::MouseButtons m_pressedButtons; + Qt::KeyboardModifiers m_keyboardModifiers; +}; + +HelpPage::HelpPage(CentralWidget *central, QObject *parent) + : QWebPage(parent) + , centralWidget(central) + , closeNewTabIfNeeded(false) + , m_pressedButtons(Qt::NoButton) + , m_keyboardModifiers(Qt::NoModifier) +{ + TRACE_OBJ +} + +QWebPage *HelpPage::createWindow(QWebPage::WebWindowType) +{ + TRACE_OBJ + HelpPage* newPage = static_cast<HelpPage*>(centralWidget->newEmptyTab()->page()); + if (newPage) + newPage->closeNewTabIfNeeded = closeNewTabIfNeeded; + closeNewTabIfNeeded = false; + return newPage; +} + +void HelpPage::triggerAction(WebAction action, bool checked) +{ + TRACE_OBJ + switch (action) { + case OpenLinkInNewWindow: + closeNewTabIfNeeded = true; + default: // fall through + QWebPage::triggerAction(action, checked); + break; + } +} + +bool HelpPage::acceptNavigationRequest(QWebFrame *, + const QNetworkRequest &request, QWebPage::NavigationType type) +{ + TRACE_OBJ + const QUrl &url = request.url(); + const bool closeNewTab = closeNewTabIfNeeded; + closeNewTabIfNeeded = false; + + if (AbstractHelpViewer::isLocalUrl(url)) { + const QString& path = url.path(); + if (!AbstractHelpViewer::canOpenPage(path)) { + QTemporaryFile tmpTmpFile; + if (!tmpTmpFile.open()) + return false; + const QString &extension = QFileInfo(path).completeSuffix(); + QFile actualTmpFile(tmpTmpFile.fileName() % QLatin1String(".") + % extension); + if (actualTmpFile.open(QIODevice::ReadWrite | QIODevice::Truncate)) { + actualTmpFile.write(HelpEngineWrapper::instance().fileData(url)); + actualTmpFile.close(); + QDesktopServices::openUrl(QUrl(actualTmpFile.fileName())); + } + + if (closeNewTab) + QMetaObject::invokeMethod(CentralWidget::instance(), "closeTab"); + return false; + } + + if (type == QWebPage::NavigationTypeLinkClicked + && (m_keyboardModifiers & Qt::ControlModifier + || m_pressedButtons == Qt::MidButton)) { + HelpViewer* viewer = centralWidget->newEmptyTab(); + if (viewer) + CentralWidget::instance()->setSource(url); + m_pressedButtons = Qt::NoButton; + m_keyboardModifiers = Qt::NoModifier; + return false; + } + return true; + } + + QDesktopServices::openUrl(url); + return false; +} + +// -- HelpViewer + +HelpViewer::HelpViewer(CentralWidget *parent, qreal zoom) + : QWebView(parent) + , parentWidget(parent) + , loadFinished(false) + , helpEngine(HelpEngineWrapper::instance()) +{ + TRACE_OBJ + setAcceptDrops(false); + + setPage(new HelpPage(parent, this)); + + page()->setNetworkAccessManager(new HelpNetworkAccessManager(this)); + + QAction* action = pageAction(QWebPage::OpenLinkInNewWindow); + action->setText(tr("Open Link in New Tab")); + if (!parent) + action->setVisible(false); + + pageAction(QWebPage::DownloadLinkToDisk)->setVisible(false); + pageAction(QWebPage::DownloadImageToDisk)->setVisible(false); + pageAction(QWebPage::OpenImageInNewWindow)->setVisible(false); + + connect(pageAction(QWebPage::Copy), SIGNAL(changed()), this, + SLOT(actionChanged())); + connect(pageAction(QWebPage::Back), SIGNAL(changed()), this, + SLOT(actionChanged())); + connect(pageAction(QWebPage::Forward), SIGNAL(changed()), this, + SLOT(actionChanged())); + connect(page(), SIGNAL(linkHovered(QString,QString,QString)), this, + SIGNAL(highlighted(QString))); + connect(this, SIGNAL(urlChanged(QUrl)), this, SIGNAL(sourceChanged(QUrl))); + connect(this, SIGNAL(loadFinished(bool)), this, SLOT(setLoadFinished(bool))); + + setFont(viewerFont()); + setTextSizeMultiplier(zoom == 0.0 ? 1.0 : zoom); +} + +HelpViewer::~HelpViewer() +{ + TRACE_OBJ +} + +QFont HelpViewer::viewerFont() const +{ + TRACE_OBJ + if (helpEngine.usesBrowserFont()) + return helpEngine.browserFont(); + + QWebSettings *webSettings = QWebSettings::globalSettings(); + return QFont(webSettings->fontFamily(QWebSettings::StandardFont), + webSettings->fontSize(QWebSettings::DefaultFontSize)); +} + +void HelpViewer::setViewerFont(const QFont &font) +{ + TRACE_OBJ + QWebSettings *webSettings = settings(); + webSettings->setFontFamily(QWebSettings::StandardFont, font.family()); + webSettings->setFontSize(QWebSettings::DefaultFontSize, font.pointSize()); +} + +void HelpViewer::scaleUp() +{ + TRACE_OBJ + setTextSizeMultiplier(textSizeMultiplier() + 0.1); +} + +void HelpViewer::scaleDown() +{ + TRACE_OBJ + setTextSizeMultiplier(qMax(0.0, textSizeMultiplier() - 0.1)); +} + +void HelpViewer::resetScale() +{ + TRACE_OBJ + setTextSizeMultiplier(1.0); +} + +void HelpViewer::setSource(const QUrl &url) +{ + TRACE_OBJ + loadFinished = false; + if (url.toString() == QLatin1String("help")) { + load(QUrl(QLatin1String("qthelp://com.trolltech.com." + "assistantinternal-1.0.0/assistant/assistant.html"))); + } else { + load(url); + } +} + +void HelpViewer::home() +{ + TRACE_OBJ + setSource(helpEngine.homePage()); +} + +void HelpViewer::wheelEvent(QWheelEvent *e) +{ + TRACE_OBJ + if (e->modifiers()& Qt::ControlModifier) { + e->accept(); + e->delta() > 0 ? scaleUp() : scaleDown(); + } else { + QWebView::wheelEvent(e); + } +} + +void HelpViewer::mouseReleaseEvent(QMouseEvent *e) +{ + TRACE_OBJ + if (e->button() == Qt::XButton1) { + triggerPageAction(QWebPage::Back); + return; + } + + if (e->button() == Qt::XButton2) { + triggerPageAction(QWebPage::Forward); + return; + } + + QWebView::mouseReleaseEvent(e); +} + +void HelpViewer::actionChanged() +{ + TRACE_OBJ + QAction *a = qobject_cast<QAction *>(sender()); + if (a == pageAction(QWebPage::Copy)) + emit copyAvailable(a->isEnabled()); + else if (a == pageAction(QWebPage::Back)) + emit backwardAvailable(a->isEnabled()); + else if (a == pageAction(QWebPage::Forward)) + emit forwardAvailable(a->isEnabled()); +} + +void HelpViewer::mousePressEvent(QMouseEvent *event) +{ + TRACE_OBJ + HelpPage *currentPage = static_cast<HelpPage*>(page()); + if (currentPage) { + currentPage->m_pressedButtons = event->buttons(); + currentPage->m_keyboardModifiers = event->modifiers(); + } + QWebView::mousePressEvent(event); +} + +void HelpViewer::setLoadFinished(bool ok) +{ + TRACE_OBJ + loadFinished = ok; + emit sourceChanged(url()); +} + +QT_END_NAMESPACE + +#endif // !QT_NO_WEBKIT diff --git a/tools/assistant/tools/assistant/helpviewer_qwv.h b/tools/assistant/tools/assistant/helpviewer_qwv.h new file mode 100644 index 0000000..3f2e537 --- /dev/null +++ b/tools/assistant/tools/assistant/helpviewer_qwv.h @@ -0,0 +1,122 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Assistant of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#if !defined(QT_NO_WEBKIT) + +#ifndef HELPVIEWERQWV_H +#define HELPVIEWERQWV_H + +#include "helpviewer.h" + +#include <QtGui/QAction> +#include <QtWebKit/QWebView> + +QT_BEGIN_NAMESPACE + +class CentralWidget; +class HelpEngineWrapper; +class QMouseEvent; + +class HelpViewer : public QWebView, public AbstractHelpViewer +{ + Q_OBJECT + +public: + HelpViewer(CentralWidget *parent, qreal zoom = 0.0); + ~HelpViewer(); + + QFont viewerFont() const; + void setViewerFont(const QFont &font); + + void scaleUp(); + void scaleDown(); + void resetScale(); + qreal scale() const { return textSizeMultiplier(); } + + void setSource(const QUrl &url); + inline QUrl source() const { return url(); } + + inline QString documentTitle() const + { return title(); } + + inline bool hasSelection() const + { return !selectedText().isEmpty(); } // ### this is suboptimal + + inline void copy() + { return triggerPageAction(QWebPage::Copy); } + + inline bool isForwardAvailable() const + { return pageAction(QWebPage::Forward)->isEnabled(); } + inline bool isBackwardAvailable() const + { return pageAction(QWebPage::Back)->isEnabled(); } + inline bool hasLoadFinished() const + { return loadFinished; } + +public Q_SLOTS: + void home(); + void backward() { back(); } + +Q_SIGNALS: + void copyAvailable(bool enabled); + void forwardAvailable(bool enabled); + void backwardAvailable(bool enabled); + void highlighted(const QString &); + void sourceChanged(const QUrl &); + +protected: + virtual void wheelEvent(QWheelEvent *); + void mouseReleaseEvent(QMouseEvent *e); + void mousePressEvent(QMouseEvent *event); + +private Q_SLOTS: + void actionChanged(); + void setLoadFinished(bool ok); + +private: + CentralWidget* parentWidget; + bool loadFinished; + HelpEngineWrapper &helpEngine; +}; + +QT_END_NAMESPACE + +#endif // HELPVIEWERQWV_H + +#endif // !QT_NO_WEBKIT diff --git a/tools/assistant/tools/assistant/indexwindow.cpp b/tools/assistant/tools/assistant/indexwindow.cpp index 82242e5..63ddbe4 100644 --- a/tools/assistant/tools/assistant/indexwindow.cpp +++ b/tools/assistant/tools/assistant/indexwindow.cpp @@ -219,7 +219,7 @@ void IndexWindow::open(QHelpIndexWidget* indexWidget, const QModelIndex &index) return; } - if (!HelpViewer::canOpenPage(url.path())) + if (!AbstractHelpViewer::canOpenPage(url.path())) CentralWidget::instance()->setSource(url); else CentralWidget::instance()->setSourceInNewTab(url); diff --git a/tools/assistant/tools/assistant/mainwindow.cpp b/tools/assistant/tools/assistant/mainwindow.cpp index 2ff6b5e..4115d39 100644 --- a/tools/assistant/tools/assistant/mainwindow.cpp +++ b/tools/assistant/tools/assistant/mainwindow.cpp @@ -44,7 +44,6 @@ #include "bookmarkmanager.h" #include "centralwidget.h" -#include "helpviewer.h" #include "indexwindow.h" #include "topicchooser.h" #include "contentwindow.h" @@ -760,12 +759,10 @@ void MainWindow::showPreferences() { TRACE_OBJ PreferencesDialog dia(this); - connect(&dia, SIGNAL(updateApplicationFont()), this, SLOT(updateApplicationFont())); connect(&dia, SIGNAL(updateBrowserFont()), m_centralWidget, SLOT(updateBrowserFont())); - dia.showDialog(); } @@ -970,7 +967,9 @@ void MainWindow::updateApplicationFont() if (helpEngine.usesAppFont()) font = helpEngine.appFont(); - qApp->setFont(font, "QWidget"); + const QWidgetList &widgets = qApp->allWidgets(); + foreach (QWidget* widget, widgets) + widget->setFont(font); } void MainWindow::setupFilterCombo() diff --git a/tools/assistant/tools/assistant/preferencesdialog.cpp b/tools/assistant/tools/assistant/preferencesdialog.cpp index f0ef054..0e1d719 100644 --- a/tools/assistant/tools/assistant/preferencesdialog.cpp +++ b/tools/assistant/tools/assistant/preferencesdialog.cpp @@ -38,26 +38,24 @@ ** $QT_END_LICENSE$ ** ****************************************************************************/ -#include "tracer.h" - #include "preferencesdialog.h" + +#include "centralwidget.h" #include "filternamedialog.h" -#include "installdialog.h" #include "fontpanel.h" -#include "centralwidget.h" -#include "aboutdialog.h" #include "helpenginewrapper.h" +#include "installdialog.h" +#include "tracer.h" #include <QtCore/QtAlgorithms> #include <QtCore/QFileSystemWatcher> -#include <QtGui/QHeaderView> +#include <QtGui/QDesktopWidget> #include <QtGui/QFileDialog> -#include <QtGui/QMessageBox> -#include <QtGui/QMenu> #include <QtGui/QFontDatabase> -#include <QtGui/QApplication> -#include <QtGui/QDesktopWidget> +#include <QtGui/QHeaderView> +#include <QtGui/QMenu> +#include <QtGui/QMessageBox> #include <QtHelp/QHelpEngineCore> @@ -115,6 +113,9 @@ PreferencesDialog::PreferencesDialog(QWidget *parent) updateFontSettingsPage(); updateOptionsPage(); + + if (helpEngine.usesAppFont()) + setFont(helpEngine.appFont()); } PreferencesDialog::~PreferencesDialog() @@ -124,16 +125,13 @@ PreferencesDialog::~PreferencesDialog() helpEngine.setAppFont(m_appFontPanel->selectedFont()); helpEngine.setUseAppFont(m_appFontPanel->isChecked()); helpEngine.setAppWritingSystem(m_appFontPanel->writingSystem()); + emit updateApplicationFont(); } if (m_browserFontChanged) { helpEngine.setBrowserFont(m_browserFontPanel->selectedFont()); helpEngine.setUseBrowserFont(m_browserFontPanel->isChecked()); helpEngine.setBrowserWritingSystem(m_browserFontPanel->writingSystem()); - } - - if (m_appFontChanged || m_browserFontChanged) { - emit updateApplicationFont(); emit updateBrowserFont(); } diff --git a/tools/designer/src/lib/shared/actionrepository.cpp b/tools/designer/src/lib/shared/actionrepository.cpp index e3ff2c1..1076ff4 100644 --- a/tools/designer/src/lib/shared/actionrepository.cpp +++ b/tools/designer/src/lib/shared/actionrepository.cpp @@ -77,18 +77,12 @@ static inline QAction *actionOfItem(const QStandardItem* item) return qvariant_cast<QAction*>(item->data(qdesigner_internal::ActionModel::ActionRole)); } -static QIcon fixActionIcon(const QIcon &icon) -{ - if (icon.isNull()) - return qdesigner_internal::emptyIcon(); - return icon; -} - namespace qdesigner_internal { // ----------- ActionModel ActionModel::ActionModel(QWidget *parent ) : QStandardItemModel(parent), + m_emptyIcon(emptyIcon()), m_core(0) { QStringList headers; @@ -127,7 +121,7 @@ void ActionModel::update(int row) for (int i = 0; i < NumColumns; i++) list += item(row, i); - setItems(m_core, actionOfItem(list.front()), list); + setItems(m_core, actionOfItem(list.front()), m_emptyIcon, list); } void ActionModel::remove(int row) @@ -150,7 +144,7 @@ QModelIndex ActionModel::addAction(QAction *action) item->setFlags(flags); items.push_back(item); } - setItems(m_core, action, items); + setItems(m_core, action, m_emptyIcon, items); appendRow(items); return indexFromItem(items.front()); } @@ -185,7 +179,9 @@ PropertySheetKeySequenceValue ActionModel::actionShortCut(const QDesignerPropert return qvariant_cast<PropertySheetKeySequenceValue>(sheet->property(index)); } -void ActionModel::setItems(QDesignerFormEditorInterface *core, QAction *action, QStandardItemList &sl) +void ActionModel::setItems(QDesignerFormEditorInterface *core, QAction *action, + const QIcon &defaultIcon, + QStandardItemList &sl) { // Tooltip, mostly for icon view mode @@ -200,7 +196,10 @@ void ActionModel::setItems(QDesignerFormEditorInterface *core, QAction *action, QStandardItem *item = sl[NameColumn]; item->setText(action->objectName()); - item->setIcon(fixActionIcon(action->icon())); + QIcon icon = action->icon(); + if (icon.isNull()) + icon = defaultIcon; + item->setIcon(icon); item->setToolTip(firstTooltip); item->setWhatsThis(firstTooltip); // Used diff --git a/tools/designer/src/lib/shared/actionrepository_p.h b/tools/designer/src/lib/shared/actionrepository_p.h index 65adc5d..6e17e7b 100644 --- a/tools/designer/src/lib/shared/actionrepository_p.h +++ b/tools/designer/src/lib/shared/actionrepository_p.h @@ -59,6 +59,7 @@ #include <QtGui/QTreeView> #include <QtGui/QListView> #include <QtGui/QStackedWidget> +#include <QtGui/QIcon> QT_BEGIN_NAMESPACE @@ -110,10 +111,14 @@ signals: void resourceImageDropped(const QString &path, QAction *action); private: + typedef QList<QStandardItem *> QStandardItemList; + void initializeHeaders(); + static void setItems(QDesignerFormEditorInterface *core, QAction *a, + const QIcon &defaultIcon, + QStandardItemList &sl); - typedef QList<QStandardItem *> QStandardItemList; - static void setItems(QDesignerFormEditorInterface *core, QAction *a, QStandardItemList &sl); + const QIcon m_emptyIcon; QDesignerFormEditorInterface *m_core; }; diff --git a/tools/designer/src/lib/shared/iconloader.cpp b/tools/designer/src/lib/shared/iconloader.cpp index df0bb7e..ed312b8 100644 --- a/tools/designer/src/lib/shared/iconloader.cpp +++ b/tools/designer/src/lib/shared/iconloader.cpp @@ -70,8 +70,7 @@ QDESIGNER_SHARED_EXPORT QIcon createIconSet(const QString &name) QDESIGNER_SHARED_EXPORT QIcon emptyIcon() { - static const QIcon empty_icon(QLatin1String(":/trolltech/formeditor/images/emptyicon.png")); - return empty_icon; + return QIcon(QLatin1String(":/trolltech/formeditor/images/emptyicon.png")); } } // namespace qdesigner_internal diff --git a/tools/designer/src/lib/shared/qdesigner_menu.cpp b/tools/designer/src/lib/shared/qdesigner_menu.cpp index c83abad..ba512e4 100644 --- a/tools/designer/src/lib/shared/qdesigner_menu.cpp +++ b/tools/designer/src/lib/shared/qdesigner_menu.cpp @@ -88,6 +88,7 @@ static inline void extendClickableArea(QRect *subMenuRect, Qt::LayoutDirection d QDesignerMenu::QDesignerMenu(QWidget *parent) : QMenu(parent), + m_subMenuPixmap(QPixmap(QLatin1String(":/trolltech/formeditor/images/submenu.png"))), m_currentIndex(0), m_addItem(new SpecialMenuAction(this)), m_addSeparator(new SpecialMenuAction(this)), @@ -550,11 +551,10 @@ void QDesignerMenu::deleteAction(QAction *a) QRect QDesignerMenu::subMenuPixmapRect(QAction *action) const { - static const QPixmap pm(QLatin1String(":/trolltech/formeditor/images/submenu.png")); const QRect g = actionGeometry(action); - const int x = layoutDirection() == Qt::LeftToRight ? (g.right() - pm.width() - 2) : 2; - const int y = g.top() + (g.height() - pm.height())/2 + 1; - return QRect(x, y, pm.width(), pm.height()); + const int x = layoutDirection() == Qt::LeftToRight ? (g.right() - m_subMenuPixmap.width() - 2) : 2; + const int y = g.top() + (g.height() - m_subMenuPixmap.height())/2 + 1; + return QRect(x, y, m_subMenuPixmap.width(), m_subMenuPixmap.height()); } bool QDesignerMenu::hasSubMenuPixmap(QAction *action) const @@ -591,8 +591,7 @@ void QDesignerMenu::paintEvent(QPaintEvent *event) p.fillRect(g, lg); } else if (hasSubMenuPixmap(a)) { - static const QPixmap pm(QLatin1String(":/trolltech/formeditor/images/submenu.png")); - p.drawPixmap(subMenuPixmapRect(a).topLeft(), pm); + p.drawPixmap(subMenuPixmapRect(a).topLeft(), m_subMenuPixmap); } } diff --git a/tools/designer/src/lib/shared/qdesigner_menu_p.h b/tools/designer/src/lib/shared/qdesigner_menu_p.h index 9c9a311..ae1e0e7 100644 --- a/tools/designer/src/lib/shared/qdesigner_menu_p.h +++ b/tools/designer/src/lib/shared/qdesigner_menu_p.h @@ -57,6 +57,7 @@ #include <QtGui/QAction> #include <QtGui/QMenu> +#include <QtGui/QPixmap> #include <QtCore/QHash> QT_BEGIN_NAMESPACE @@ -183,6 +184,7 @@ protected: private: bool hideSubMenuOnCursorKey(); bool showSubMenuOnCursorKey(); + const QPixmap m_subMenuPixmap; QPoint m_startPosition; int m_currentIndex; diff --git a/tools/linguist/linguist/images/transbox.png b/tools/linguist/linguist/images/transbox.png Binary files differdeleted file mode 100644 index 2d7219b..0000000 --- a/tools/linguist/linguist/images/transbox.png +++ /dev/null diff --git a/tools/linguist/linguist/linguist.qrc b/tools/linguist/linguist/linguist.qrc index a43f0ce..b70b9cd 100644 --- a/tools/linguist/linguist/linguist.qrc +++ b/tools/linguist/linguist/linguist.qrc @@ -1,5 +1,5 @@ <RCC> - <qresource prefix="/" > + <qresource prefix="/"> <file>images/appicon.png</file> <file>images/mac/accelerator.png</file> <file>images/mac/book.png</file> @@ -28,7 +28,6 @@ <file>images/s_check_on.png</file> <file>images/s_check_warning.png</file> <file>images/splash.png</file> - <file>images/transbox.png</file> <file>images/up.png</file> <file>images/down.png</file> <file>images/editdelete.png</file> diff --git a/tools/linguist/linguist/messageeditor.cpp b/tools/linguist/linguist/messageeditor.cpp index b6c1688..3848723 100644 --- a/tools/linguist/linguist/messageeditor.cpp +++ b/tools/linguist/linguist/messageeditor.cpp @@ -98,14 +98,8 @@ MessageEditor::MessageEditor(MultiDataModel *dataModel, QMainWindow *parent) { setObjectName(QLatin1String("scroll area")); - // Use white explicitly as the background color for the editor page. QPalette p; - p.setColor(QPalette::Active, QPalette::Base, Qt::white); - p.setColor(QPalette::Inactive, QPalette::Base, Qt::white); - p.setColor(QPalette::Disabled, QPalette::Base, Qt::white); - p.setColor(QPalette::Active, QPalette::Window, Qt::white); - p.setColor(QPalette::Inactive, QPalette::Window, Qt::white); - p.setColor(QPalette::Disabled, QPalette::Window, Qt::white); + p.setBrush(QPalette::Window, p.brush(QPalette::Active, QPalette::Base)); setPalette(p); setupEditorPage(); diff --git a/tools/linguist/linguist/messagemodel.cpp b/tools/linguist/linguist/messagemodel.cpp index 6572059..4e2b473 100644 --- a/tools/linguist/linguist/messagemodel.cpp +++ b/tools/linguist/linguist/messagemodel.cpp @@ -584,12 +584,16 @@ void MultiContextItem::putMessageItem(int pos, MessageItem *m) m_messageLists.last()[pos] = m; } -void MultiContextItem::appendMessageItem(MessageItem *m) +void MultiContextItem::appendMessageItems(const QList<MessageItem *> &m) { + QList<MessageItem *> nullItems = m; // Basically, just a reservation + for (int i = 0; i < nullItems.count(); ++i) + nullItems[i] = 0; for (int i = 0; i < m_messageLists.count() - 1; ++i) - m_messageLists[i].append(0); - m_messageLists.last().append(m); - m_multiMessageList.append(MultiMessageItem(m)); + m_messageLists[i] += nullItems; + m_messageLists.last() += m; + foreach (MessageItem *mi, m) + m_multiMessageList.append(MultiMessageItem(mi)); } void MultiContextItem::removeMultiMessageItem(int pos) @@ -710,33 +714,43 @@ void MultiDataModel::append(DataModel *dm, bool readWrite) m_msgModel->endInsertColumns(); } m_msgModel->endInsertColumns(); + int appendedContexts = 0; for (int i = 0; i < dm->contextCount(); ++i) { ContextItem *c = dm->contextItem(i); int mcx = findContextIndex(c->context()); if (mcx >= 0) { MultiContextItem *mc = multiContextItem(mcx); mc->assignLastModel(c, readWrite); + QList<MessageItem *> appendItems; for (int j = 0; j < c->messageCount(); ++j) { MessageItem *m = c->messageItem(j); int msgIdx = mc->findMessage(m->text(), m->comment()); - if (msgIdx >= 0) { + if (msgIdx >= 0) mc->putMessageItem(msgIdx, m); - } else { - int msgCnt = mc->messageCount(); - m_msgModel->beginInsertRows(m_msgModel->createIndex(mcx, 0, 0), msgCnt, msgCnt); - mc->appendMessageItem(m); - m_msgModel->endInsertRows(); - ++m_numMessages; - } + else + appendItems << m; + } + if (!appendItems.isEmpty()) { + int msgCnt = mc->messageCount(); + m_msgModel->beginInsertRows(m_msgModel->createIndex(mcx, 0, 0), + msgCnt, msgCnt + appendItems.size() - 1); + mc->appendMessageItems(appendItems); + m_msgModel->endInsertRows(); + m_numMessages += appendItems.size(); } } else { - MultiContextItem item(modelCount() - 1, c, readWrite); - m_msgModel->beginInsertRows(QModelIndex(), contextCount(), contextCount()); - m_multiContextList.append(item); - m_msgModel->endInsertRows(); - m_numMessages += item.messageCount(); + m_multiContextList << MultiContextItem(modelCount() - 1, c, readWrite); + m_numMessages += c->messageCount(); + ++appendedContexts; } } + if (appendedContexts) { + // Do that en block to avoid itemview inefficiency. It doesn't hurt that we + // announce the availability of the data "long" after it was actually added. + m_msgModel->beginInsertRows(QModelIndex(), + contextCount() - appendedContexts, contextCount() - 1); + m_msgModel->endInsertRows(); + } dm->setWritable(readWrite); updateCountsOnAdd(modelCount() - 1, readWrite); connect(dm, SIGNAL(modifiedChanged()), SLOT(onModifiedChanged())); diff --git a/tools/linguist/linguist/messagemodel.h b/tools/linguist/linguist/messagemodel.h index 3e0107e..7d98873 100644 --- a/tools/linguist/linguist/messagemodel.h +++ b/tools/linguist/linguist/messagemodel.h @@ -332,7 +332,7 @@ private: void removeModel(int pos); void moveModel(int oldPos, int newPos); // newPos is *before* removing at oldPos void putMessageItem(int pos, MessageItem *m); - void appendMessageItem(MessageItem *m); + void appendMessageItems(const QList<MessageItem *> &m); void removeMultiMessageItem(int pos); void incrementFinishedCount() { ++m_finishedCount; } void decrementFinishedCount() { --m_finishedCount; } diff --git a/tools/runonphone/main.cpp b/tools/runonphone/main.cpp index a77e713..1a5cdee 100644 --- a/tools/runonphone/main.cpp +++ b/tools/runonphone/main.cpp @@ -174,11 +174,7 @@ int main(int argc, char *argv[]) } if(loglevel > 0) outstream << "Connecting to target via " << serialPortName << endl; -#ifdef Q_OS_WIN - launcher->setTrkServerName(QString("\\\\.\\") + serialPortName); -#else launcher->setTrkServerName(serialPortName); -#endif launcher->setFileName(QString("c:\\sys\\bin\\") + exeFile); launcher->setCommandLineArgs(cmdLine); diff --git a/tools/runonphone/runonphone.pro b/tools/runonphone/runonphone.pro index 2c1be98..7bed3e5 100644 --- a/tools/runonphone/runonphone.pro +++ b/tools/runonphone/runonphone.pro @@ -4,7 +4,7 @@ QT -= gui CONFIG += console CONFIG -= app_bundle -include(trk/trk.pri) +include(symbianutils/symbianutils.pri) SOURCES += main.cpp \ trksignalhandler.cpp @@ -12,6 +12,8 @@ SOURCES += main.cpp \ HEADERS += trksignalhandler.h \ serenum.h +DEFINES += SYMBIANUTILS_INCLUDE_PRI + windows { SOURCES += serenum_win.cpp LIBS += -lsetupapi \ diff --git a/tools/runonphone/trk/bluetoothlistener.cpp b/tools/runonphone/symbianutils/bluetoothlistener.cpp index 8d45fb5..df04288 100644 --- a/tools/runonphone/trk/bluetoothlistener.cpp +++ b/tools/runonphone/symbianutils/bluetoothlistener.cpp @@ -184,7 +184,7 @@ bool BluetoothListener::start(const QString &device, QString *errorMessage) return true; } -void BluetoothListener::slotStdOutput() +void BluetoothListener::slotStdOutput() { emitMessage(QString::fromLocal8Bit(d->process.readAllStandardOutput())); } diff --git a/tools/runonphone/trk/bluetoothlistener.h b/tools/runonphone/symbianutils/bluetoothlistener.h index 027f286..36894e7 100644 --- a/tools/runonphone/trk/bluetoothlistener.h +++ b/tools/runonphone/symbianutils/bluetoothlistener.h @@ -42,6 +42,8 @@ #ifndef BLUETOOTHLISTENER_H #define BLUETOOTHLISTENER_H +#include "symbianutils_global.h" + #include <QtCore/QObject> #include <QtCore/QProcess> @@ -53,7 +55,7 @@ struct BluetoothListenerPrivate; * The rfcomm command is used. It process can be started in the background * while connection attempts (TrkDevice::open()) are made in the foreground. */ -class BluetoothListener : public QObject +class SYMBIANUTILS_EXPORT BluetoothListener : public QObject { Q_OBJECT Q_DISABLE_COPY(BluetoothListener) diff --git a/tools/runonphone/trk/bluetoothlistener_gui.cpp b/tools/runonphone/symbianutils/bluetoothlistener_gui.cpp index 6ffdaef..5994eb5 100644 --- a/tools/runonphone/trk/bluetoothlistener_gui.cpp +++ b/tools/runonphone/symbianutils/bluetoothlistener_gui.cpp @@ -50,7 +50,7 @@ namespace trk { -PromptStartCommunicationResult +SYMBIANUTILS_EXPORT PromptStartCommunicationResult promptStartCommunication(BaseCommunicationStarter &starter, const QString &msgBoxTitle, const QString &msgBoxText, @@ -88,7 +88,7 @@ PromptStartCommunicationResult return PromptStartCommunicationConnected; } -PromptStartCommunicationResult +SYMBIANUTILS_EXPORT PromptStartCommunicationResult promptStartSerial(BaseCommunicationStarter &starter, QWidget *msgBoxParent, QString *errorMessage) @@ -98,7 +98,7 @@ PromptStartCommunicationResult return promptStartCommunication(starter, title, message, msgBoxParent, errorMessage); } -PromptStartCommunicationResult +SYMBIANUTILS_EXPORT PromptStartCommunicationResult promptStartBluetooth(BaseCommunicationStarter &starter, QWidget *msgBoxParent, QString *errorMessage) diff --git a/tools/runonphone/trk/bluetoothlistener_gui.h b/tools/runonphone/symbianutils/bluetoothlistener_gui.h index d673ffe..10e7145 100644 --- a/tools/runonphone/trk/bluetoothlistener_gui.h +++ b/tools/runonphone/symbianutils/bluetoothlistener_gui.h @@ -42,6 +42,8 @@ #ifndef BLUETOOTHLISTENER_GUI_H #define BLUETOOTHLISTENER_GUI_H +#include "symbianutils_global.h" + #include <QtCore/QtGlobal> QT_BEGIN_NAMESPACE @@ -62,7 +64,7 @@ enum PromptStartCommunicationResult { PromptStartCommunicationError }; -PromptStartCommunicationResult +SYMBIANUTILS_EXPORT PromptStartCommunicationResult promptStartCommunication(BaseCommunicationStarter &starter, const QString &msgBoxTitle, const QString &msgBoxText, @@ -71,14 +73,14 @@ PromptStartCommunicationResult // Convenience to start a serial connection (messages prompting // to launch Trk). -PromptStartCommunicationResult +SYMBIANUTILS_EXPORT PromptStartCommunicationResult promptStartSerial(BaseCommunicationStarter &starter, QWidget *msgBoxParent, QString *errorMessage); // Convenience to start blue tooth connection (messages // prompting to connect). -PromptStartCommunicationResult +SYMBIANUTILS_EXPORT PromptStartCommunicationResult promptStartBluetooth(BaseCommunicationStarter &starter, QWidget *msgBoxParent, QString *errorMessage); diff --git a/tools/runonphone/trk/callback.h b/tools/runonphone/symbianutils/callback.h index edc2c74..3996d73 100644 --- a/tools/runonphone/trk/callback.h +++ b/tools/runonphone/symbianutils/callback.h @@ -42,7 +42,7 @@ #ifndef DEBUGGER_CALLBACK_H #define DEBUGGER_CALLBACK_H -#include <QtCore/QtGlobal> +#include "symbianutils_global.h" namespace trk { namespace Internal { diff --git a/tools/runonphone/trk/communicationstarter.cpp b/tools/runonphone/symbianutils/communicationstarter.cpp index e5e556e..cdee49f 100644 --- a/tools/runonphone/trk/communicationstarter.cpp +++ b/tools/runonphone/symbianutils/communicationstarter.cpp @@ -58,7 +58,6 @@ struct BaseCommunicationStarterPrivate { int intervalMS; int attempts; int n; - QString device; QString errorString; BaseCommunicationStarter::State state; }; @@ -70,7 +69,6 @@ BaseCommunicationStarterPrivate::BaseCommunicationStarterPrivate(const BaseCommu intervalMS(1000), attempts(-1), n(0), - device(QLatin1String("/dev/rfcomm0")), state(BaseCommunicationStarter::TimedOut) { } @@ -108,7 +106,7 @@ BaseCommunicationStarter::StartResult BaseCommunicationStarter::start() // Before we instantiate timers, and such, try to open the device, // which should succeed if another listener is already running in // 'Watch' mode - if (d->trkDevice->open(d->device , &(d->errorString))) + if (d->trkDevice->open(&(d->errorString))) return ConnectionSucceeded; // Pull up resources for next attempt d->n = 0; @@ -155,12 +153,7 @@ void BaseCommunicationStarter::setAttempts(int a) QString BaseCommunicationStarter::device() const { - return d->device; -} - -void BaseCommunicationStarter::setDevice(const QString &dv) -{ - d->device = dv; + return d->trkDevice->port(); } QString BaseCommunicationStarter::errorString() const @@ -175,20 +168,20 @@ void BaseCommunicationStarter::slotTimer() if (d->attempts >= 0 && d->n >= d->attempts) { stopTimer(); d->errorString = tr("%1: timed out after %n attempts using an interval of %2ms.", 0, d->n) - .arg(d->device).arg(d->intervalMS); + .arg(d->trkDevice->port()).arg(d->intervalMS); d->state = TimedOut; emit timeout(); } else { // Attempt n to connect? - if (d->trkDevice->open(d->device , &(d->errorString))) { + if (d->trkDevice->open(&(d->errorString))) { stopTimer(); - const QString msg = tr("%1: Connection attempt %2 succeeded.").arg(d->device).arg(d->n); + const QString msg = tr("%1: Connection attempt %2 succeeded.").arg(d->trkDevice->port()).arg(d->n); emit message(msg); d->state = Connected; emit connected(); } else { const QString msg = tr("%1: Connection attempt %2 failed: %3 (retrying)...") - .arg(d->device).arg(d->n).arg(d->errorString); + .arg(d->trkDevice->port()).arg(d->n).arg(d->errorString); emit message(msg); } } @@ -228,13 +221,11 @@ BluetoothListener *ConsoleBluetoothStarter::createListener() bool ConsoleBluetoothStarter::startBluetooth(const TrkDevicePtr &trkDevice, QObject *listenerParent, - const QString &device, int attempts, QString *errorMessage) { // Set up a console starter to print to stdout. ConsoleBluetoothStarter starter(trkDevice, listenerParent); - starter.setDevice(device); starter.setAttempts(attempts); switch (starter.start()) { case Started: diff --git a/tools/runonphone/trk/communicationstarter.h b/tools/runonphone/symbianutils/communicationstarter.h index 34cf398..0a060ee 100644 --- a/tools/runonphone/trk/communicationstarter.h +++ b/tools/runonphone/symbianutils/communicationstarter.h @@ -42,6 +42,8 @@ #ifndef COMMUNICATIONSTARTER_H #define COMMUNICATIONSTARTER_H +#include "symbianutils_global.h" + #include <QtCore/QSharedPointer> #include <QtCore/QObject> @@ -60,7 +62,7 @@ struct BaseCommunicationStarterPrivate; * The base class can be used as is to prompt the user to launch App TRK for a * serial communication as this requires no further resource setup. */ -class BaseCommunicationStarter : public QObject { +class SYMBIANUTILS_EXPORT BaseCommunicationStarter : public QObject { Q_OBJECT Q_DISABLE_COPY(BaseCommunicationStarter) public: @@ -78,7 +80,6 @@ public: void setAttempts(int a); QString device() const; - void setDevice(const QString &); State state() const; QString errorString() const; @@ -117,7 +118,7 @@ private: * implement as a factory function that creates and sets up the * listener (mode, message connection, etc). */ -class AbstractBluetoothStarter : public BaseCommunicationStarter { +class SYMBIANUTILS_EXPORT AbstractBluetoothStarter : public BaseCommunicationStarter { Q_OBJECT Q_DISABLE_COPY(AbstractBluetoothStarter) public: @@ -134,13 +135,12 @@ protected: /* ConsoleBluetoothStarter: Convenience class for console processes. Creates a * listener in "Listen" mode with the messages redirected to standard output. */ -class ConsoleBluetoothStarter : public AbstractBluetoothStarter { +class SYMBIANUTILS_EXPORT ConsoleBluetoothStarter : public AbstractBluetoothStarter { Q_OBJECT Q_DISABLE_COPY(ConsoleBluetoothStarter) public: static bool startBluetooth(const TrkDevicePtr& trkDevice, QObject *listenerParent, - const QString &device, int attempts, QString *errorMessage); diff --git a/tools/runonphone/trk/launcher.cpp b/tools/runonphone/symbianutils/launcher.cpp index 1796fc5..408829b 100644 --- a/tools/runonphone/trk/launcher.cpp +++ b/tools/runonphone/symbianutils/launcher.cpp @@ -41,6 +41,7 @@ #include "launcher.h" #include "trkutils.h" +#include "trkutils_p.h" #include "trkdevice.h" #include "bluetoothlistener.h" @@ -66,7 +67,6 @@ struct LauncherPrivate { explicit LauncherPrivate(const TrkDevicePtr &d); TrkDevicePtr m_device; - QString m_trkServerName; QByteArray m_trkReadBuffer; Launcher::State m_state; @@ -130,12 +130,12 @@ void Launcher::addStartupActions(trk::Launcher::Actions startupActions) void Launcher::setTrkServerName(const QString &name) { - d->m_trkServerName = name; + d->m_device->setPort(name); } QString Launcher::trkServerName() const { - return d->m_trkServerName; + return d->m_device->port(); } TrkDevicePtr Launcher::trkDevice() const @@ -190,7 +190,7 @@ bool Launcher::startServer(QString *errorMessage) errorMessage->clear(); if (d->m_verbose) { const QString msg = QString::fromLatin1("Port=%1 Executable=%2 Arguments=%3 Package=%4 Remote Package=%5 Install file=%6") - .arg(d->m_trkServerName, d->m_fileName, + .arg(trkServerName(), d->m_fileName, d->m_commandLineArgs.join(QString(QLatin1Char(' '))), d->m_copyState.sourceFileName, d->m_copyState.destinationFileName, d->m_installFileName); logMessage(msg); @@ -212,7 +212,7 @@ bool Launcher::startServer(QString *errorMessage) qWarning("No remote executable given for running."); return false; } - if (!d->m_device->isOpen() && !d->m_device->open(d->m_trkServerName, errorMessage)) + if (!d->m_device->isOpen() && !d->m_device->open(errorMessage)) return false; if (d->m_closeDevice) { connect(this, SIGNAL(finished()), d->m_device.data(), SLOT(close())); @@ -595,17 +595,19 @@ void Launcher::handleSupportMask(const TrkResult &result) return; const char *data = result.data.data() + 1; - QByteArray str; + QString str = QLatin1String("SUPPORTED: "); for (int i = 0; i < 32; ++i) { //str.append(" [" + formatByte(data[i]) + "]: "); - for (int j = 0; j < 8; ++j) - if (data[i] & (1 << j)) - str.append(QByteArray::number(i * 8 + j, 16) + " "); + for (int j = 0; j < 8; ++j) { + if (data[i] & (1 << j)) { + str.append(QString::number(i * 8 + j, 16)); + str.append(QLatin1Char(' ')); + } + } } - logMessage("SUPPORTED: " + str); + logMessage(str); } - void Launcher::cleanUp() { // @@ -614,9 +616,7 @@ void Launcher::cleanUp() // Sub Cmd: Delete Process //ProcessID: 0x0000071F (1823) // [41 24 00 00 00 00 07 1F] - QByteArray ba; - appendByte(&ba, 0x00); - appendByte(&ba, 0x00); + QByteArray ba(2, char(0)); appendInt(&ba, d->m_session.pid); d->m_device->sendTrkMessage(TrkDeleteItem, TrkCallback(), ba, "Delete process"); @@ -669,7 +669,7 @@ void Launcher::copyFileToRemote() { emit copyingStarted(); QByteArray ba; - appendByte(&ba, 0x10); + ba.append(char(10)); appendString(&ba, d->m_copyState.destinationFileName.toLocal8Bit(), TargetByteOrder, false); d->m_device->sendTrkMessage(TrkOpenFile, TrkCallback(this, &Launcher::handleFileCreation), ba); } @@ -678,7 +678,7 @@ void Launcher::installRemotePackageSilently() { emit installingStarted(); QByteArray ba; - appendByte(&ba, 'C'); + ba.append('C'); appendString(&ba, d->m_installFileName.toLocal8Bit(), TargetByteOrder, false); d->m_device->sendTrkMessage(TrkInstallFile, TrkCallback(this, &Launcher::handleInstallPackageFinished), ba); } @@ -705,7 +705,7 @@ QByteArray Launcher::startProcessMessage(const QString &executable, // It's not started yet QByteArray ba; appendShort(&ba, 0, TargetByteOrder); // create new process - appendByte(&ba, 0); // options - currently unused + ba.append(char(0)); // options - currently unused if(arguments.isEmpty()) { appendString(&ba, executable.toLocal8Bit(), TargetByteOrder); return ba; diff --git a/tools/runonphone/trk/launcher.h b/tools/runonphone/symbianutils/launcher.h index 8dc6ebe..2b23fd8 100644 --- a/tools/runonphone/trk/launcher.h +++ b/tools/runonphone/symbianutils/launcher.h @@ -56,7 +56,7 @@ struct LauncherPrivate; typedef QSharedPointer<TrkDevice> TrkDevicePtr; -class Launcher : public QObject +class SYMBIANUTILS_EXPORT Launcher : public QObject { Q_OBJECT Q_DISABLE_COPY(Launcher) diff --git a/tools/runonphone/symbianutils/symbiandevicemanager.cpp b/tools/runonphone/symbianutils/symbiandevicemanager.cpp new file mode 100644 index 0000000..f663816 --- /dev/null +++ b/tools/runonphone/symbianutils/symbiandevicemanager.cpp @@ -0,0 +1,331 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the tools applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "symbiandevicemanager.h" + +#include <QtCore/QSettings> +#include <QtCore/QStringList> +#include <QtCore/QFileInfo> +#include <QtCore/QtDebug> +#include <QtCore/QTextStream> +#include <QtCore/QSharedData> +#include <QtCore/QScopedPointer> + +namespace SymbianUtils { + +enum { debug = 0 }; + +static const char REGKEY_CURRENT_CONTROL_SET[] = "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet"; +static const char USBSER[] = "Services/usbser/Enum"; + +const char *SymbianDeviceManager::linuxBlueToothDeviceRootC = "/dev/rfcomm"; + +// ------------- SymbianDevice +class SymbianDeviceData : public QSharedData { +public: + SymbianDeviceData() : type(SerialPortCommunication) {} + + QString portName; + QString friendlyName; + QString deviceDesc; + QString manufacturer; + DeviceCommunicationType type; +}; + +SymbianDevice::SymbianDevice(SymbianDeviceData *data) : + m_data(data) +{ + +} + +SymbianDevice::SymbianDevice() : + m_data(new SymbianDeviceData) +{ +} +SymbianDevice::SymbianDevice(const SymbianDevice &rhs) : + m_data(rhs.m_data) +{ +} + +SymbianDevice &SymbianDevice::operator=(const SymbianDevice &rhs) +{ + if (this != &rhs) + m_data = rhs.m_data; + return *this; +} + +SymbianDevice::~SymbianDevice() +{ +} + +QString SymbianDevice::portName() const +{ + return m_data->portName; +} + +QString SymbianDevice::friendlyName() const +{ + return m_data->friendlyName; +} + +QString SymbianDevice::deviceDesc() const +{ + return m_data->deviceDesc; +} + +QString SymbianDevice::manufacturer() const +{ + return m_data->manufacturer; +} + +DeviceCommunicationType SymbianDevice::type() const +{ + return m_data->type; +} + +bool SymbianDevice::isNull() const +{ + return !m_data->portName.isEmpty(); +} + +QString SymbianDevice::toString() const +{ + QString rc; + QTextStream str(&rc); + format(str); + return rc; +} + +void SymbianDevice::format(QTextStream &str) const +{ + str << (m_data->type == BlueToothCommunication ? "Bluetooth: " : "Serial: ") + << m_data->portName; + if (!m_data->friendlyName.isEmpty()) { + str << " (" << m_data->friendlyName; + if (!m_data->deviceDesc.isEmpty()) + str << " / " << m_data->deviceDesc; + str << ')'; + } + if (!m_data->manufacturer.isEmpty()) + str << " [" << m_data->manufacturer << ']'; +} + +// Compare by port and friendly name +int SymbianDevice::compare(const SymbianDevice &rhs) const +{ + if (const int prc = m_data->portName.compare(rhs.m_data->portName)) + return prc; + if (const int frc = m_data->friendlyName.compare(rhs.m_data->friendlyName)) + return frc; + return 0; +} + +QDebug operator<<(QDebug d, const SymbianDevice &cd) +{ + d.nospace() << cd.toString(); + return d; +} + +// ------------- SymbianDeviceManagerPrivate +struct SymbianDeviceManagerPrivate { + SymbianDeviceManagerPrivate() : m_initialized(false) {} + + bool m_initialized; + SymbianDeviceManager::SymbianDeviceList m_devices; +}; + +SymbianDeviceManager::SymbianDeviceManager(QObject *parent) : + QObject(parent), + d(new SymbianDeviceManagerPrivate) +{ +} + +SymbianDeviceManager::~SymbianDeviceManager() +{ + delete d; +} + +SymbianDeviceManager::SymbianDeviceList SymbianDeviceManager::devices() const +{ + if (!d->m_initialized) + const_cast<SymbianDeviceManager*>(this)->update(false); + return d->m_devices; +} + +QString SymbianDeviceManager::toString() const +{ + QString rc; + QTextStream str(&rc); + const int count = d->m_devices.size(); + for (int i = 0; i < count; i++) { + str << '#' << i << ' '; + d->m_devices.at(i).format(str); + str << '\n'; + } + return rc; +} + +QString SymbianDeviceManager::friendlyNameForPort(const QString &port) const +{ + foreach (const SymbianDevice &device, d->m_devices) { + if (device.portName() == port) + return device.friendlyName(); + } + return QString(); +} + +void SymbianDeviceManager::update() +{ + update(true); +} + +void SymbianDeviceManager::update(bool emitSignals) +{ + typedef SymbianDeviceList::iterator SymbianDeviceListIterator; + + if (debug) + qDebug(">SerialDeviceLister::update(%d)\n%s", int(emitSignals), + qPrintable(toString())); + + d->m_initialized = true; + // Get ordered new list + SymbianDeviceList newDevices = serialPorts() + blueToothDevices(); + if (newDevices.size() > 1) + qStableSort(newDevices.begin(), newDevices.end()); + if (d->m_devices == newDevices) // Happy, nothing changed. + return; + // Merge the lists and emit the respective added/removed signals, assuming + // no one can plug a different device on the same port at the speed of lightning + if (!d->m_devices.isEmpty()) { + // Find deleted devices + for (SymbianDeviceListIterator oldIt = d->m_devices.begin(); oldIt != d->m_devices.end(); ) { + if (newDevices.contains(*oldIt)) { + ++oldIt; + } else { + const SymbianDevice toBeDeleted = *oldIt; + oldIt = d->m_devices.erase(oldIt); + if (emitSignals) + emit deviceRemoved(toBeDeleted); + } + } + } + if (!newDevices.isEmpty()) { + // Find new devices and insert in order + foreach(const SymbianDevice &newDevice, newDevices) { + if (!d->m_devices.contains(newDevice)) { + d->m_devices.append(newDevice); + if (emitSignals) + emit deviceAdded(newDevice); + } + } + if (d->m_devices.size() > 1) + qStableSort(d->m_devices.begin(), d->m_devices.end()); + } + if (emitSignals) + emit updated(); + + if (debug) + qDebug("<SerialDeviceLister::update\n%s\n", qPrintable(toString())); +} + +SymbianDeviceManager::SymbianDeviceList SymbianDeviceManager::serialPorts() const +{ + SymbianDeviceList rc; +#ifdef Q_OS_WIN + const QSettings registry(REGKEY_CURRENT_CONTROL_SET, QSettings::NativeFormat); + const QString usbSerialRootKey = QLatin1String(USBSER) + QLatin1Char('/'); + const int count = registry.value(usbSerialRootKey + QLatin1String("Count")).toInt(); + for (int i = 0; i < count; ++i) { + QString driver = registry.value(usbSerialRootKey + QString::number(i)).toString(); + if (driver.contains(QLatin1String("JAVACOMM"))) { + driver.replace(QLatin1Char('\\'), QLatin1Char('/')); + const QString driverRootKey = QLatin1String("Enum/") + driver + QLatin1Char('/'); + if (debug > 1) + qDebug() << "SerialDeviceLister::serialPorts(): Checking " << i << count + << REGKEY_CURRENT_CONTROL_SET << usbSerialRootKey << driverRootKey; + QScopedPointer<SymbianDeviceData> device(new SymbianDeviceData); + device->type = SerialPortCommunication; + device->friendlyName = registry.value(driverRootKey + QLatin1String("FriendlyName")).toString(); + device->portName = registry.value(driverRootKey + QLatin1String("Device Parameters/PortName")).toString(); + device->deviceDesc = registry.value(driverRootKey + QLatin1String("DeviceDesc")).toString(); + device->manufacturer = registry.value(driverRootKey + QLatin1String("Mfg")).toString(); + rc.append(SymbianDevice(device.take())); + } + } +#endif + return rc; +} + +SymbianDeviceManager::SymbianDeviceList SymbianDeviceManager::blueToothDevices() const +{ + SymbianDeviceList rc; +#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) + // Bluetooth devices are created on connection. List the existing ones + // or at least the first one. + const QString prefix = QLatin1String(linuxBlueToothDeviceRootC); + const QString friendlyFormat = QLatin1String("Bluetooth device (%1)"); + for (int d = 0; d < 4; d++) { + QScopedPointer<SymbianDeviceData> device(new SymbianDeviceData); + device->type = BlueToothCommunication; + device->portName = prefix + QString::number(d); + if (d == 0 || QFileInfo(device->portName).exists()) { + device->friendlyName = friendlyFormat.arg(device->portName); + rc.push_back(SymbianDevice(device.take())); + } + } +#endif + return rc; +} + +Q_GLOBAL_STATIC(SymbianDeviceManager, symbianDeviceManager) + +SymbianDeviceManager *SymbianDeviceManager::instance() +{ + return symbianDeviceManager(); +} + +QDebug operator<<(QDebug d, const SymbianDeviceManager &sdm) +{ + d.nospace() << sdm.toString(); + return d; +} + +} // namespace SymbianUtilsInternal diff --git a/tools/runonphone/symbianutils/symbiandevicemanager.h b/tools/runonphone/symbianutils/symbiandevicemanager.h new file mode 100644 index 0000000..dcf131a --- /dev/null +++ b/tools/runonphone/symbianutils/symbiandevicemanager.h @@ -0,0 +1,145 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the tools applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SYMBIANDEVICEMANAGER_H +#define SYMBIANDEVICEMANAGER_H + +#include "symbianutils_global.h" + +#include <QtCore/QObject> +#include <QtCore/QExplicitlySharedDataPointer> + +QT_BEGIN_NAMESPACE +class QDebug; +class QTextStream; +QT_END_NAMESPACE + +namespace SymbianUtils { + +struct SymbianDeviceManagerPrivate; +class SymbianDeviceData; + +enum DeviceCommunicationType { + SerialPortCommunication = 0, + BlueToothCommunication = 1 +}; + +// SymbianDevice, explicitly shared. +class SYMBIANUTILS_EXPORT SymbianDevice { + explicit SymbianDevice(SymbianDeviceData *data); + friend class SymbianDeviceManager; +public: + SymbianDevice(); + SymbianDevice(const SymbianDevice &rhs); + SymbianDevice &operator=(const SymbianDevice &rhs); + ~SymbianDevice(); + int compare(const SymbianDevice &rhs) const; + + DeviceCommunicationType type() const; + bool isNull() const; + QString portName() const; + QString friendlyName() const; + + // Windows only. + QString deviceDesc() const; + QString manufacturer() const; + + void format(QTextStream &str) const; + QString toString() const; + +private: + QExplicitlySharedDataPointer<SymbianDeviceData> m_data; +}; + +QDebug operator<<(QDebug d, const SymbianDevice &); + +inline bool operator==(const SymbianDevice &d1, const SymbianDevice &d2) + { return d1.compare(d2) == 0; } +inline bool operator!=(const SymbianDevice &d1, const SymbianDevice &d2) + { return d1.compare(d2) != 0; } +inline bool operator<(const SymbianDevice &d1, const SymbianDevice &d2) + { return d1.compare(d2) < 0; } + +/* SymbianDeviceManager: Singleton that maintains a list of Symbian devices. + * and emits change signals. + * On Windows, the update slot must be connected to a signal + * emitted from an event handler listening for WM_DEVICECHANGE. */ +class SYMBIANUTILS_EXPORT SymbianDeviceManager : public QObject +{ + Q_OBJECT +public: + typedef QList<SymbianDevice> SymbianDeviceList; + + static const char *linuxBlueToothDeviceRootC; + + // Do not use this constructor, it is just public for Q_GLOBAL_STATIC + explicit SymbianDeviceManager(QObject *parent = 0); + virtual ~SymbianDeviceManager(); + + // Singleton access. + static SymbianDeviceManager *instance(); + + SymbianDeviceList devices() const; + QString toString() const; + + QString friendlyNameForPort(const QString &port) const; + +public slots: + void update(); + +signals: + void deviceRemoved(const SymbianDevice &d); + void deviceAdded(const SymbianDevice &d); + void updated(); + +private: + void update(bool emitSignals); + SymbianDeviceList serialPorts() const; + SymbianDeviceList blueToothDevices() const; + + SymbianDeviceManagerPrivate *d; +}; + +QDebug operator<<(QDebug d, const SymbianDeviceManager &); + +} // namespace SymbianUtils + +#endif // SYMBIANDEVICEMANAGER_H diff --git a/tools/runonphone/trk/trk.pri b/tools/runonphone/symbianutils/symbianutils.pri index 2ce17c0..6309517 100644 --- a/tools/runonphone/trk/trk.pri +++ b/tools/runonphone/symbianutils/symbianutils.pri @@ -1,18 +1,22 @@ INCLUDEPATH *= $$PWD # Input -HEADERS += $$PWD/callback.h \ +HEADERS += $$PWD/symbianutils_global.h \ + $$PWD/callback.h \ $$PWD/trkutils.h \ + $$PWD/trkutils_p.h \ $$PWD/trkdevice.h \ $$PWD/launcher.h \ $$PWD/bluetoothlistener.h \ - $$PWD/communicationstarter.h + $$PWD/communicationstarter.h \ + $$PWD/symbiandevicemanager.h SOURCES += $$PWD/trkutils.cpp \ $$PWD/trkdevice.cpp \ $$PWD/launcher.cpp \ $$PWD/bluetoothlistener.cpp \ - $$PWD/communicationstarter.cpp + $$PWD/communicationstarter.cpp \ + $$PWD/symbiandevicemanager.cpp # Tests/trklauncher is a console application contains(QT, gui) { diff --git a/tools/runonphone/symbianutils/symbianutils_global.h b/tools/runonphone/symbianutils/symbianutils_global.h new file mode 100644 index 0000000..a6ffbe7 --- /dev/null +++ b/tools/runonphone/symbianutils/symbianutils_global.h @@ -0,0 +1,55 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the tools applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SYMBIANUTILS_GLOBAL_H +#define SYMBIANUTILS_GLOBAL_H + +#include <QtCore/qglobal.h> + +#if defined(SYMBIANUTILS_BUILD_LIB) +# define SYMBIANUTILS_EXPORT Q_DECL_EXPORT +#elif defined(SYMBIANUTILS_BUILD_STATIC_LIB) || defined(SYMBIANUTILS_INCLUDE_PRI) +# define SYMBIANUTILS_EXPORT +#else +# define SYMBIANUTILS_EXPORT Q_DECL_IMPORT +#endif + +#endif // SYMBIANUTILS_GLOBAL_H diff --git a/tools/runonphone/trk/trkdevice.cpp b/tools/runonphone/symbianutils/trkdevice.cpp index fe3261b..b327ab3 100644 --- a/tools/runonphone/trk/trkdevice.cpp +++ b/tools/runonphone/symbianutils/trkdevice.cpp @@ -41,6 +41,7 @@ #include "trkdevice.h" #include "trkutils.h" +#include "trkutils_p.h" #include <QtCore/QString> #include <QtCore/QDebug> @@ -516,7 +517,7 @@ static inline bool overlappedSyncWrite(HANDLE file, bool WriterThread::write(const QByteArray &data, QString *errorMessage) { if (verboseTrk) - qDebug() << "Write raw data: " << data.toHex(); + qDebug() << "Write raw data: " << stringFromArray(data).toLatin1(); QMutexLocker locker(&m_context->mutex); #ifdef Q_OS_WIN DWORD charsWritten; @@ -856,8 +857,8 @@ void UnixReaderThread::terminate() { // Trigger select() by writing to the pipe char c = 0; - int written = write(m_terminatePipeFileDescriptors[1], &c, 1); - // FIXME: Use result. + const int written = write(m_terminatePipeFileDescriptors[1], &c, 1); + Q_UNUSED(written) wait(); } @@ -882,6 +883,7 @@ struct TrkDevicePrivate QByteArray trkReadBuffer; int verbose; QString errorString; + QString port; }; /////////////////////////////////////////////////////////////////////// @@ -913,13 +915,19 @@ TrkDevice::~TrkDevice() delete d; } -bool TrkDevice::open(const QString &port, QString *errorMessage) +bool TrkDevice::open(QString *errorMessage) { if (d->verbose) - qDebug() << "Opening" << port << "is open: " << isOpen() << " serialFrame=" << serialFrame(); + qDebug() << "Opening" << port() << "is open: " << isOpen() << " serialFrame=" << serialFrame(); + if (d->port.isEmpty()) { + *errorMessage = QLatin1String("Internal error: No port set on TrkDevice"); + return false; + } + close(); #ifdef Q_OS_WIN - d->deviceContext->device = CreateFile(port.toStdWString().c_str(), + const QString fullPort = QLatin1String("\\\\.\\") + d->port; + d->deviceContext->device = CreateFile(reinterpret_cast<const WCHAR*>(fullPort.utf16()), GENERIC_READ | GENERIC_WRITE, 0, NULL, @@ -928,7 +936,7 @@ bool TrkDevice::open(const QString &port, QString *errorMessage) NULL); if (INVALID_HANDLE_VALUE == d->deviceContext->device) { - *errorMessage = QString::fromLatin1("Could not open device '%1': %2").arg(port, winErrorMessage(GetLastError())); + *errorMessage = QString::fromLatin1("Could not open device '%1': %2").arg(port(), winErrorMessage(GetLastError())); return false; } memset(&d->deviceContext->readOverlapped, 0, sizeof(OVERLAPPED)); @@ -940,9 +948,9 @@ bool TrkDevice::open(const QString &port, QString *errorMessage) return false; } #else - d->deviceContext->file.setFileName(port); + d->deviceContext->file.setFileName(d->port); if (!d->deviceContext->file.open(QIODevice::ReadWrite|QIODevice::Unbuffered)) { - *errorMessage = QString::fromLatin1("Cannot open %1: %2").arg(port, d->deviceContext->file.errorString()); + *errorMessage = QString::fromLatin1("Cannot open %1: %2").arg(d->port, d->deviceContext->file.errorString()); return false; } @@ -981,7 +989,7 @@ bool TrkDevice::open(const QString &port, QString *errorMessage) d->writerThread->start(); if (d->verbose) - qDebug() << "Opened" << port; + qDebug() << "Opened" << d->port; return true; } @@ -1015,6 +1023,16 @@ bool TrkDevice::isOpen() const #endif } +QString TrkDevice::port() const +{ + return d->port; +} + +void TrkDevice::setPort(const QString &p) +{ + d->port = p; +} + QString TrkDevice::errorString() const { return d->errorString; @@ -1061,8 +1079,13 @@ void TrkDevice::sendTrkMessage(byte code, TrkCallback callback, const QByteArray &data, const QVariant &cookie) { if (!d->writerThread.isNull()) { - if (d->verbose > 1) - qDebug() << "Sending " << code << data.toHex(); + if (d->verbose > 1) { + QByteArray msg = "Sending: "; + msg += QByteArray::number(code, 16); + msg += ": "; + msg += stringFromArray(data).toLatin1(); + qDebug("%s", msg.data()); + } d->writerThread->queueTrkMessage(code, callback, data, cookie); } } diff --git a/tools/runonphone/trk/trkdevice.h b/tools/runonphone/symbianutils/trkdevice.h index e04f791..78012fd 100644 --- a/tools/runonphone/trk/trkdevice.h +++ b/tools/runonphone/symbianutils/trkdevice.h @@ -42,6 +42,7 @@ #ifndef TRKDEVICE_H #define TRKDEVICE_H +#include "symbianutils_global.h" #include "callback.h" #include <QtCore/QObject> @@ -74,18 +75,22 @@ enum { TRK_WRITE_QUEUE_NOOP_CODE = 0x7f }; typedef trk::Callback<const TrkResult &> TrkCallback; -class TrkDevice : public QObject +class SYMBIANUTILS_EXPORT TrkDevice : public QObject { Q_OBJECT Q_PROPERTY(bool serialFrame READ serialFrame WRITE setSerialFrame) Q_PROPERTY(bool verbose READ verbose WRITE setVerbose) + Q_PROPERTY(QString port READ port WRITE setPort) public: explicit TrkDevice(QObject *parent = 0); virtual ~TrkDevice(); - bool open(const QString &port, QString *errorMessage); + bool open(QString *errorMessage); bool isOpen() const; + QString port() const; + void setPort(const QString &p); + QString errorString() const; bool serialFrame() const; diff --git a/tools/runonphone/trk/trkutils.cpp b/tools/runonphone/symbianutils/trkutils.cpp index 3a96053..9b43c96 100644 --- a/tools/runonphone/trk/trkutils.cpp +++ b/tools/runonphone/symbianutils/trkutils.cpp @@ -86,7 +86,7 @@ void Session::reset() trkAppVersion.reset(); } -QString formatCpu(int major, int minor) +static QString formatCpu(int major, int minor) { //: CPU description of an S60 device //: %1 major verison, %2 minor version @@ -143,14 +143,46 @@ QString Session::deviceDescription(unsigned verbose) const return msg.arg(formatTrkVersion(trkAppVersion)); } +// -------------- + +QByteArray decode7d(const QByteArray &ba) +{ + QByteArray res; + res.reserve(ba.size()); + for (int i = 0; i < ba.size(); ++i) { + byte c = byte(ba.at(i)); + if (c == 0x7d) { + ++i; + c = 0x20 ^ byte(ba.at(i)); + } + res.append(c); + } + return res; +} + +QByteArray encode7d(const QByteArray &ba) +{ + QByteArray res; + res.reserve(ba.size() + 2); + for (int i = 0; i < ba.size(); ++i) { + byte c = byte(ba.at(i)); + if (c == 0x7e || c == 0x7d) { + res.append(0x7d); + res.append(0x20 ^ c); + } else { + res.append(c); + } + } + return res; +} // FIXME: Use the QByteArray based version below? -QString stringFromByte(byte c) +static inline QString stringFromByte(byte c) { - return QString("%1 ").arg(c, 2, 16, QChar('0')); + return QString::fromLatin1("%1").arg(c, 2, 16, QChar('0')); } -QString stringFromArray(const QByteArray &ba, int maxLen) +SYMBIANUTILS_EXPORT QString stringFromArray(const QByteArray &ba, int maxLen) { QString str; QString ascii; @@ -170,7 +202,7 @@ QString stringFromArray(const QByteArray &ba, int maxLen) return str + " " + ascii; } -QByteArray hexNumber(uint n, int digits) +SYMBIANUTILS_EXPORT QByteArray hexNumber(uint n, int digits) { QByteArray ba = QByteArray::number(n, 16); if (digits == 0 || ba.size() == digits) @@ -178,7 +210,7 @@ QByteArray hexNumber(uint n, int digits) return QByteArray(digits - ba.size(), '0') + ba; } -QByteArray hexxNumber(uint n, int digits) +SYMBIANUTILS_EXPORT QByteArray hexxNumber(uint n, int digits) { return "0x" + hexNumber(n, digits); } @@ -200,9 +232,13 @@ void TrkResult::clear() QString TrkResult::toString() const { - QString res = stringFromByte(code) + "[" + stringFromByte(token); - res.chop(1); - return res + "] " + stringFromArray(data); + QString res = stringFromByte(code); + res += QLatin1String(" ["); + res += stringFromByte(token); + res += QLatin1Char(']'); + res += QLatin1Char(' '); + res += stringFromArray(data); + return res; } QByteArray frameMessage(byte command, byte token, const QByteArray &data, bool serialFrame) @@ -303,12 +339,12 @@ bool extractResult(QByteArray *buffer, bool serialFrame, TrkResult *result, QByt return true; } -ushort extractShort(const char *data) +SYMBIANUTILS_EXPORT ushort extractShort(const char *data) { return byte(data[0]) * 256 + byte(data[1]); } -uint extractInt(const char *data) +SYMBIANUTILS_EXPORT uint extractInt(const char *data) { uint res = byte(data[0]); res *= 256; res += byte(data[1]); @@ -317,7 +353,7 @@ uint extractInt(const char *data) return res; } -QString quoteUnprintableLatin1(const QByteArray &ba) +SYMBIANUTILS_EXPORT QString quoteUnprintableLatin1(const QByteArray &ba) { QString res; char buf[10]; @@ -333,49 +369,7 @@ QString quoteUnprintableLatin1(const QByteArray &ba) return res; } -QByteArray decode7d(const QByteArray &ba) -{ - QByteArray res; - res.reserve(ba.size()); - for (int i = 0; i < ba.size(); ++i) { - byte c = byte(ba.at(i)); - if (c == 0x7d) { - ++i; - c = 0x20 ^ byte(ba.at(i)); - } - res.append(c); - } - //if (res != ba) - // logMessage("DECODED: " << stringFromArray(ba) - // << " -> " << stringFromArray(res)); - return res; -} - -QByteArray encode7d(const QByteArray &ba) -{ - QByteArray res; - res.reserve(ba.size() + 2); - for (int i = 0; i < ba.size(); ++i) { - byte c = byte(ba.at(i)); - if (c == 0x7e || c == 0x7d) { - res.append(0x7d); - res.append(0x20 ^ c); - } else { - res.append(c); - } - } - //if (res != ba) - // logMessage("ENCODED: " << stringFromArray(ba) - // << " -> " << stringFromArray(res)); - return res; -} - -void appendByte(QByteArray *ba, byte b) -{ - ba->append(b); -} - -void appendShort(QByteArray *ba, ushort s, Endianness endian) +SYMBIANUTILS_EXPORT void appendShort(QByteArray *ba, ushort s, Endianness endian) { if (endian == BigEndian) { ba->append(s / 256); @@ -386,7 +380,7 @@ void appendShort(QByteArray *ba, ushort s, Endianness endian) } } -void appendInt(QByteArray *ba, uint i, Endianness endian) +SYMBIANUTILS_EXPORT void appendInt(QByteArray *ba, uint i, Endianness endian) { const uchar b3 = i % 256; i /= 256; const uchar b2 = i % 256; i /= 256; diff --git a/tools/runonphone/trk/trkutils.h b/tools/runonphone/symbianutils/trkutils.h index 328dd2b..3a485c7 100644 --- a/tools/runonphone/trk/trkutils.h +++ b/tools/runonphone/symbianutils/trkutils.h @@ -42,19 +42,20 @@ #ifndef DEBUGGER_TRK_UTILS #define DEBUGGER_TRK_UTILS +#include "symbianutils_global.h" #include <QtCore/QByteArray> #include <QtCore/QHash> #include <QtCore/QStringList> #include <QtCore/QVariant> -typedef unsigned char byte; - QT_BEGIN_NAMESPACE class QDateTime; QT_END_NAMESPACE namespace trk { +typedef unsigned char byte; + enum Command { TrkPing = 0x00, TrkConnect = 0x01, @@ -85,17 +86,14 @@ enum Command { TrkNotifyProcessorReset = 0xa7 }; -QByteArray decode7d(const QByteArray &ba); -QByteArray encode7d(const QByteArray &ba); - inline byte extractByte(const char *data) { return *data; } -ushort extractShort(const char *data); -uint extractInt(const char *data); +SYMBIANUTILS_EXPORT ushort extractShort(const char *data); +SYMBIANUTILS_EXPORT uint extractInt(const char *data); -QString quoteUnprintableLatin1(const QByteArray &ba); +SYMBIANUTILS_EXPORT QString quoteUnprintableLatin1(const QByteArray &ba); // produces "xx xx xx " -QString stringFromArray(const QByteArray &ba, int maxLen = - 1); +SYMBIANUTILS_EXPORT QString stringFromArray(const QByteArray &ba, int maxLen = - 1); enum Endianness { @@ -104,13 +102,11 @@ enum Endianness TargetByteOrder = BigEndian, }; -void appendByte(QByteArray *ba, byte b); -void appendShort(QByteArray *ba, ushort s, Endianness = TargetByteOrder); -void appendInt(QByteArray *ba, uint i, Endianness = TargetByteOrder); -void appendString(QByteArray *ba, const QByteArray &str, Endianness = TargetByteOrder, bool appendNullTerminator = true); -void appendDateTime(QByteArray *ba, QDateTime dateTime, Endianness = TargetByteOrder); +SYMBIANUTILS_EXPORT void appendShort(QByteArray *ba, ushort s, Endianness = TargetByteOrder); +SYMBIANUTILS_EXPORT void appendInt(QByteArray *ba, uint i, Endianness = TargetByteOrder); +SYMBIANUTILS_EXPORT void appendString(QByteArray *ba, const QByteArray &str, Endianness = TargetByteOrder, bool appendNullTerminator = true); -struct Library +struct SYMBIANUTILS_EXPORT Library { Library() {} @@ -119,7 +115,7 @@ struct Library uint dataseg; }; -struct TrkAppVersion +struct SYMBIANUTILS_EXPORT TrkAppVersion { TrkAppVersion(); void reset(); @@ -130,7 +126,7 @@ struct TrkAppVersion int protocolMinor; }; -struct Session +struct SYMBIANUTILS_EXPORT Session { Session(); void reset(); @@ -163,7 +159,7 @@ struct Session QStringList modules; }; -struct TrkResult +struct SYMBIANUTILS_EXPORT TrkResult { TrkResult(); void clear(); @@ -179,15 +175,10 @@ struct TrkResult bool isDebugOutput; }; -// returns a QByteArray containing optionally -// the serial frame [0x01 0x90 <len>] and 0x7e encoded7d(ba) 0x7e -QByteArray frameMessage(byte command, byte token, const QByteArray &data, bool serialFrame); -ushort isValidTrkResult(const QByteArray &buffer, bool serialFrame); -bool extractResult(QByteArray *buffer, bool serialFrame, TrkResult *r, QByteArray *rawData = 0); -QByteArray errorMessage(byte code); -QByteArray hexNumber(uint n, int digits = 0); -QByteArray hexxNumber(uint n, int digits = 0); // prepends '0x', too -uint swapEndian(uint in); +SYMBIANUTILS_EXPORT QByteArray errorMessage(byte code); +SYMBIANUTILS_EXPORT QByteArray hexNumber(uint n, int digits = 0); +SYMBIANUTILS_EXPORT QByteArray hexxNumber(uint n, int digits = 0); // prepends '0x', too +SYMBIANUTILS_EXPORT uint swapEndian(uint in); } // namespace trk diff --git a/tools/runonphone/symbianutils/trkutils_p.h b/tools/runonphone/symbianutils/trkutils_p.h new file mode 100644 index 0000000..12b0109 --- /dev/null +++ b/tools/runonphone/symbianutils/trkutils_p.h @@ -0,0 +1,62 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the tools applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef DEBUGGER_TRK_PRIVATE_UTILS +#define DEBUGGER_TRK_PRIVATE_UTILS + +#include "trkutils.h" +#include "symbianutils_global.h" + +QT_BEGIN_NAMESPACE +class QDateTime; +QT_END_NAMESPACE + +namespace trk { + +void appendDateTime(QByteArray *ba, QDateTime dateTime, Endianness = TargetByteOrder); +// returns a QByteArray containing optionally +// the serial frame [0x01 0x90 <len>] and 0x7e encoded7d(ba) 0x7e +QByteArray frameMessage(byte command, byte token, const QByteArray &data, bool serialFrame); +bool extractResult(QByteArray *buffer, bool serialFrame, TrkResult *r, QByteArray *rawData = 0); + +} // namespace trk + +#endif // DEBUGGER_TRK_PRIVATE_UTILS diff --git a/tools/shared/qtpropertybrowser/qtpropertybrowserutils.cpp b/tools/shared/qtpropertybrowser/qtpropertybrowserutils.cpp index b84de11..0b14292 100644 --- a/tools/shared/qtpropertybrowser/qtpropertybrowserutils.cpp +++ b/tools/shared/qtpropertybrowser/qtpropertybrowserutils.cpp @@ -93,15 +93,23 @@ QtCursorDatabase::QtCursorDatabase() QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-busy.png"))); } +void QtCursorDatabase::clear() +{ + m_cursorNames.clear(); + m_cursorIcons.clear(); + m_valueToCursorShape.clear(); + m_cursorShapeToValue.clear(); +} + void QtCursorDatabase::appendCursor(Qt::CursorShape shape, const QString &name, const QIcon &icon) { if (m_cursorShapeToValue.contains(shape)) return; - int value = m_cursorNames.count(); + const int value = m_cursorNames.count(); m_cursorNames.append(name); - m_cursorIcons[value] = icon; - m_valueToCursorShape[value] = shape; - m_cursorShapeToValue[shape] = value; + m_cursorIcons.insert(value, icon); + m_valueToCursorShape.insert(value, shape); + m_cursorShapeToValue.insert(shape, value); } QStringList QtCursorDatabase::cursorShapeNames() const diff --git a/tools/shared/qtpropertybrowser/qtpropertybrowserutils_p.h b/tools/shared/qtpropertybrowser/qtpropertybrowserutils_p.h index b60fb94..baa7a4a 100644 --- a/tools/shared/qtpropertybrowser/qtpropertybrowserutils_p.h +++ b/tools/shared/qtpropertybrowser/qtpropertybrowserutils_p.h @@ -68,6 +68,7 @@ class QtCursorDatabase { public: QtCursorDatabase(); + void clear(); QStringList cursorShapeNames() const; QMap<int, QIcon> cursorShapeIcons() const; diff --git a/tools/shared/qtpropertybrowser/qtpropertymanager.cpp b/tools/shared/qtpropertybrowser/qtpropertymanager.cpp index 67ab2fb..d9ff10a 100644 --- a/tools/shared/qtpropertybrowser/qtpropertymanager.cpp +++ b/tools/shared/qtpropertybrowser/qtpropertymanager.cpp @@ -1391,16 +1391,54 @@ void QtStringPropertyManager::uninitializeProperty(QtProperty *property) } // QtBoolPropertyManager +// Return an icon containing a check box indicator +static QIcon drawCheckBox(bool value) +{ + QStyleOptionButton opt; + opt.state |= value ? QStyle::State_On : QStyle::State_Off; + opt.state |= QStyle::State_Enabled; + const QStyle *style = QApplication::style(); + // Figure out size of an indicator and make sure it is not scaled down in a list view item + // by making the pixmap as big as a list view icon and centering the indicator in it. + // (if it is smaller, it can't be helped) + const int indicatorWidth = style->pixelMetric(QStyle::PM_IndicatorWidth, &opt); + const int indicatorHeight = style->pixelMetric(QStyle::PM_IndicatorHeight, &opt); + const int listViewIconSize = indicatorWidth; + const int pixmapWidth = indicatorWidth; + const int pixmapHeight = qMax(indicatorHeight, listViewIconSize); + + opt.rect = QRect(0, 0, indicatorWidth, indicatorHeight); + QPixmap pixmap = QPixmap(pixmapWidth, pixmapHeight); + pixmap.fill(Qt::transparent); + { + // Center? + const int xoff = (pixmapWidth > indicatorWidth) ? (pixmapWidth - indicatorWidth) / 2 : 0; + const int yoff = (pixmapHeight > indicatorHeight) ? (pixmapHeight - indicatorHeight) / 2 : 0; + QPainter painter(&pixmap); + painter.translate(xoff, yoff); + style->drawPrimitive(QStyle::PE_IndicatorCheckBox, &opt, &painter); + } + return QIcon(pixmap); +} class QtBoolPropertyManagerPrivate { QtBoolPropertyManager *q_ptr; Q_DECLARE_PUBLIC(QtBoolPropertyManager) public: + QtBoolPropertyManagerPrivate(); QMap<const QtProperty *, bool> m_values; + const QIcon m_checkedIcon; + const QIcon m_uncheckedIcon; }; +QtBoolPropertyManagerPrivate::QtBoolPropertyManagerPrivate() : + m_checkedIcon(drawCheckBox(true)), + m_uncheckedIcon(drawCheckBox(false)) +{ +} + /*! \class QtBoolPropertyManager \internal @@ -1471,36 +1509,6 @@ QString QtBoolPropertyManager::valueText(const QtProperty *property) const return it.value() ? trueText : falseText; } -// Return an icon containing a check box indicator -static QIcon drawCheckBox(bool value) -{ - QStyleOptionButton opt; - opt.state |= value ? QStyle::State_On : QStyle::State_Off; - opt.state |= QStyle::State_Enabled; - const QStyle *style = QApplication::style(); - // Figure out size of an indicator and make sure it is not scaled down in a list view item - // by making the pixmap as big as a list view icon and centering the indicator in it. - // (if it is smaller, it can't be helped) - const int indicatorWidth = style->pixelMetric(QStyle::PM_IndicatorWidth, &opt); - const int indicatorHeight = style->pixelMetric(QStyle::PM_IndicatorHeight, &opt); - const int listViewIconSize = indicatorWidth; - const int pixmapWidth = indicatorWidth; - const int pixmapHeight = qMax(indicatorHeight, listViewIconSize); - - opt.rect = QRect(0, 0, indicatorWidth, indicatorHeight); - QPixmap pixmap = QPixmap(pixmapWidth, pixmapHeight); - pixmap.fill(Qt::transparent); - { - // Center? - const int xoff = (pixmapWidth > indicatorWidth) ? (pixmapWidth - indicatorWidth) / 2 : 0; - const int yoff = (pixmapHeight > indicatorHeight) ? (pixmapHeight - indicatorHeight) / 2 : 0; - QPainter painter(&pixmap); - painter.translate(xoff, yoff); - style->drawPrimitive(QStyle::PE_IndicatorCheckBox, &opt, &painter); - } - return QIcon(pixmap); -} - /*! \reimp */ @@ -1510,9 +1518,7 @@ QIcon QtBoolPropertyManager::valueIcon(const QtProperty *property) const if (it == d_ptr->m_values.constEnd()) return QIcon(); - static const QIcon checkedIcon = drawCheckBox(true); - static const QIcon uncheckedIcon = drawCheckBox(false); - return it.value() ? checkedIcon : uncheckedIcon; + return it.value() ? d_ptr->m_checkedIcon : d_ptr->m_uncheckedIcon; } /*! @@ -6287,7 +6293,15 @@ void QtColorPropertyManager::uninitializeProperty(QtProperty *property) // QtCursorPropertyManager -Q_GLOBAL_STATIC(QtCursorDatabase, cursorDatabase) +// Make sure icons are removed as soon as QApplication is destroyed, otherwise, +// handles are leaked on X11. +static void clearCursorDatabase(); +Q_GLOBAL_STATIC_WITH_INITIALIZER(QtCursorDatabase, cursorDatabase, qAddPostRoutine(clearCursorDatabase)) + +static void clearCursorDatabase() +{ + cursorDatabase()->clear(); +} class QtCursorPropertyManagerPrivate { |